solid-logic 4.0.7 → 4.0.8-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +3 -1
  2. package/dist/2729812e0bfc062ee77a.js +1 -0
  3. package/dist/a9c30b64ceaae48b72f0.js +2045 -0
  4. package/dist/authSession/authSession.d.ts +41 -2
  5. package/dist/authSession/authSession.d.ts.map +1 -1
  6. package/dist/authSession/events.d.ts +24 -0
  7. package/dist/authSession/events.d.ts.map +1 -0
  8. package/dist/authSession/issuer.d.ts +8 -0
  9. package/dist/authSession/issuer.d.ts.map +1 -0
  10. package/dist/authSession/session.d.ts +45 -0
  11. package/dist/authSession/session.d.ts.map +1 -0
  12. package/dist/authn/SolidAuthnLogic.d.ts +15 -6
  13. package/dist/authn/SolidAuthnLogic.d.ts.map +1 -1
  14. package/dist/authn/serverLogout.d.ts +6 -0
  15. package/dist/authn/serverLogout.d.ts.map +1 -0
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/logic/solidLogic.d.ts +3 -3
  19. package/dist/logic/solidLogic.d.ts.map +1 -1
  20. package/dist/logic/solidLogicSingleton.d.ts.map +1 -1
  21. package/dist/solid-logic.esm.js +492 -9622
  22. package/dist/solid-logic.esm.js.map +1 -1
  23. package/dist/solid-logic.esm.min.js +1 -1
  24. package/dist/solid-logic.esm.min.js.map +1 -1
  25. package/dist/solid-logic.js +4082 -8082
  26. package/dist/solid-logic.js.map +1 -1
  27. package/dist/solid-logic.min.js +1 -1
  28. package/dist/solid-logic.min.js.map +1 -1
  29. package/dist/types.d.ts +2 -2
  30. package/dist/types.d.ts.map +1 -1
  31. package/package.json +13 -10
  32. package/dist/acl/aclLogic.js +0 -117
  33. package/dist/acl/aclLogic.js.map +0 -1
  34. package/dist/authSession/authSession.js +0 -3
  35. package/dist/authSession/authSession.js.map +0 -1
  36. package/dist/authn/SolidAuthnLogic.js +0 -109
  37. package/dist/authn/SolidAuthnLogic.js.map +0 -1
  38. package/dist/authn/authUtil.js +0 -64
  39. package/dist/authn/authUtil.js.map +0 -1
  40. package/dist/chat/chatLogic.js +0 -157
  41. package/dist/chat/chatLogic.js.map +0 -1
  42. package/dist/inbox/inboxLogic.js +0 -51
  43. package/dist/inbox/inboxLogic.js.map +0 -1
  44. package/dist/index.js +0 -14
  45. package/dist/index.js.map +0 -1
  46. package/dist/issuer/issuerLogic.js +0 -37
  47. package/dist/issuer/issuerLogic.js.map +0 -1
  48. package/dist/logic/CustomError.js +0 -27
  49. package/dist/logic/CustomError.js.map +0 -1
  50. package/dist/logic/solidLogic.js +0 -64
  51. package/dist/logic/solidLogic.js.map +0 -1
  52. package/dist/logic/solidLogicSingleton.js +0 -31
  53. package/dist/logic/solidLogicSingleton.js.map +0 -1
  54. package/dist/profile/profileAclDocuments.js +0 -13
  55. package/dist/profile/profileAclDocuments.js.map +0 -1
  56. package/dist/profile/profileDocuments.js +0 -11
  57. package/dist/profile/profileDocuments.js.map +0 -1
  58. package/dist/profile/profileLogic.js +0 -344
  59. package/dist/profile/profileLogic.js.map +0 -1
  60. package/dist/typeIndex/typeIndexAclDocuments.js +0 -31
  61. package/dist/typeIndex/typeIndexAclDocuments.js.map +0 -1
  62. package/dist/typeIndex/typeIndexDocuments.js +0 -17
  63. package/dist/typeIndex/typeIndexDocuments.js.map +0 -1
  64. package/dist/typeIndex/typeIndexLogic.js +0 -248
  65. package/dist/typeIndex/typeIndexLogic.js.map +0 -1
  66. package/dist/types.js +0 -2
  67. package/dist/types.js.map +0 -1
  68. package/dist/util/containerLogic.js +0 -49
  69. package/dist/util/containerLogic.js.map +0 -1
  70. package/dist/util/debug.js +0 -13
  71. package/dist/util/debug.js.map +0 -1
  72. package/dist/util/ns.js +0 -5
  73. package/dist/util/ns.js.map +0 -1
  74. package/dist/util/utilityLogic.js +0 -201
  75. package/dist/util/utilityLogic.js.map +0 -1
  76. package/dist/util/utils.js +0 -39
  77. package/dist/util/utils.js.map +0 -1
  78. package/dist/versionInfo.js +0 -36
  79. package/dist/versionInfo.js.map +0 -1
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("$rdf")):"function"==typeof define&&define.amd?define("SolidLogic",["$rdf"],t):"object"==typeof exports?exports.SolidLogic=t(require("$rdf")):e.SolidLogic=t(e.$rdf)}(this,e=>(()=>{var t={7(e){"use strict";var t,r="object"==typeof Reflect?Reflect:null,n=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise(function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}f(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&f(e,"error",t,r)}(e,i,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function d(e,t,r,n){var i,s,o,d;if(a(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=c(e))>0&&o.length>i&&!o.warned){o.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=o.length,d=l,console&&console.warn&&console.warn(d)}return e}function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=l.bind(n);return i.listener=r,n.wrapFn=i,i}function h(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):g(i,i.length)}function p(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function g(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function f(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){n.once&&e.removeEventListener(t,i),r(s)})}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,s=this._events;if(void 0!==s)i=i&&void 0===s.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,l=g(c,d);for(r=0;r<d;++r)n(l[r],this,t)}return!0},s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)},s.prototype.once=function(e,t){return a(t),this.on(e,u(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,u(this,e,t)),this},s.prototype.removeListener=function(e,t){var r,n,i,s,o;if(a(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return h(this,e,!0)},s.prototype.rawListeners=function(e){return h(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},s.prototype.listenerCount=p,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},386(e){const t={acl:"http://www.w3.org/ns/auth/acl#",arg:"http://www.w3.org/ns/pim/arg#",as:"https://www.w3.org/ns/activitystreams#",bookmark:"http://www.w3.org/2002/01/bookmark#",cal:"http://www.w3.org/2002/12/cal/ical#",cco:"http://www.ontologyrepository.com/CommonCoreOntologies/",cert:"http://www.w3.org/ns/auth/cert#",contact:"http://www.w3.org/2000/10/swap/pim/contact#",dc:"http://purl.org/dc/elements/1.1/",dct:"http://purl.org/dc/terms/",doap:"http://usefulinc.com/ns/doap#",foaf:"http://xmlns.com/foaf/0.1/",geo:"http://www.w3.org/2003/01/geo/wgs84_pos#",gpx:"http://www.w3.org/ns/pim/gpx#",gr:"http://purl.org/goodrelations/v1#",http:"http://www.w3.org/2007/ont/http#",httph:"http://www.w3.org/2007/ont/httph#",icalTZ:"http://www.w3.org/2002/12/cal/icaltzd#",ldp:"http://www.w3.org/ns/ldp#",link:"http://www.w3.org/2007/ont/link#",log:"http://www.w3.org/2000/10/swap/log#",meeting:"http://www.w3.org/ns/pim/meeting#",mo:"http://purl.org/ontology/mo/",org:"http://www.w3.org/ns/org#",owl:"http://www.w3.org/2002/07/owl#",pad:"http://www.w3.org/ns/pim/pad#",patch:"http://www.w3.org/ns/pim/patch#",prov:"http://www.w3.org/ns/prov#",pto:"http://www.productontology.org/id/",qu:"http://www.w3.org/2000/10/swap/pim/qif#",trip:"http://www.w3.org/ns/pim/trip#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",rss:"http://purl.org/rss/1.0/",sched:"http://www.w3.org/ns/pim/schedule#",schema:"http://schema.org/",sioc:"http://rdfs.org/sioc/ns#",skos:"http://www.w3.org/2004/02/skos/core#",solid:"http://www.w3.org/ns/solid/terms#",space:"http://www.w3.org/ns/pim/space#",stat:"http://www.w3.org/ns/posix/stat#",tab:"http://www.w3.org/2007/ont/link#",tabont:"http://www.w3.org/2007/ont/link#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",wf:"http://www.w3.org/2005/01/wf/flow#",xsd:"http://www.w3.org/2001/XMLSchema#"};e.exports=function(e={namedNode:e=>e}){const r={};for(const n in t){const i=t[n];r[n]=function(t=""){return e.namedNode(i+t)}}return r}},264(t){"use strict";t.exports=e}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var s=r[e]={exports:{}};return t[e](s,s.exports,n),s.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return(()=>{"use strict";function e(...e){console.log(...e)}function t(...e){console.warn(...e)}n.r(i),n.d(i,{ACL_LINK:()=>Nr,CrossOriginForbiddenError:()=>Gr,FetchError:()=>en,NotEditableError:()=>Yr,NotFoundError:()=>Xr,SameOriginForbiddenError:()=>Qr,UnauthorizedError:()=>Br,WebOperationError:()=>Zr,appContext:()=>jr,authSession:()=>wn,authn:()=>fn,createTypeIndexLogic:()=>an,getSuggestedIssuers:()=>gn,offlineTestID:()=>Kr,solidLogicSingleton:()=>hn,store:()=>yn});const r=new TextEncoder,s=new TextDecoder;function o(...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 a=e=>(e=>{let t=e;"string"==typeof t&&(t=r.encode(t));const n=[];for(let e=0;e<t.length;e+=32768)n.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(n.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),c=e=>{let t=e;t instanceof Uint8Array&&(t=s.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 d extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}d.code="ERR_JOSE_GENERIC";class l extends d{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}}l.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class u extends d{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}}u.code="ERR_JWT_EXPIRED";class h extends d{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}h.code="ERR_JOSE_ALG_NOT_ALLOWED";class p extends d{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}p.code="ERR_JOSE_NOT_SUPPORTED";(class extends d{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends d{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class g extends d{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}g.code="ERR_JWS_INVALID";class f extends d{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}f.code="ERR_JWT_INVALID";(class extends d{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";class w extends d{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}w.code="ERR_JWKS_INVALID";class y extends d{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 m extends d{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Symbol.asyncIterator,m.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class _ extends d{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}_.code="ERR_JWKS_TIMEOUT";class v extends d{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function S(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 p(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}v.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const b=crypto,k=e=>e instanceof CryptoKey,E=(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 I(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function T(e,t){return e.name===t}function A(e){return parseInt(e.name.slice(4),10)}function U(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}function P(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!T(e.algorithm,"HMAC"))throw I("HMAC");const r=parseInt(t.slice(2),10);if(A(e.algorithm.hash)!==r)throw I(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!T(e.algorithm,"RSASSA-PKCS1-v1_5"))throw I("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(A(e.algorithm.hash)!==r)throw I(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!T(e.algorithm,"RSA-PSS"))throw I("RSA-PSS");const r=parseInt(t.slice(2),10);if(A(e.algorithm.hash)!==r)throw I(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw I("Ed25519 or Ed448");break;case"Ed25519":if(!T(e.algorithm,"Ed25519"))throw I("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!T(e.algorithm,"ECDSA"))throw I("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 I(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}U(e,r)}function x(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}(Object.getOwnPropertyDescriptor(E,"name")||{}).writable||Object.defineProperty(E,"name",{value:"default",configurable:!0});const C=(e,...t)=>x("Key must be ",e,...t);function R(e,t,...r){return x(`Key for the ${e} algorithm must be `,t,...r)}(Object.getOwnPropertyDescriptor(C,"name")||{}).writable||Object.defineProperty(C,"name",{value:"default",configurable:!0});const $=e=>!!k(e)||"KeyObject"===e?.[Symbol.toStringTag];(Object.getOwnPropertyDescriptor($,"name")||{}).writable||Object.defineProperty($,"name",{value:"default",configurable:!0});const O=["CryptoKey"];function L(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}function H(e){return L(e)&&"string"==typeof e.kty}const N=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 p('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 p('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 p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new p('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,b.subtle.importKey("jwk",i,...n)},D=e=>c(e);let j,K;const W=e=>"KeyObject"===e?.[Symbol.toStringTag],J=async(e,t,r,n,i=!1)=>{let s=e.get(t);if(s?.[n])return s[n];const o=await N({...r,alg:n});return i&&Object.freeze(t),s?s[n]=o:e.set(t,{[n]:o}),o},M=(e,t)=>{if(W(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?D(r.k):(K||(K=new WeakMap),J(K,e,r,t))}if(H(e)){if(e.k)return c(e.k);K||(K=new WeakMap);return J(K,e,e,t,!0)}return e},F=(e,t)=>{if(W(e)){let r=e.export({format:"jwk"});return r.k?D(r.k):(j||(j=new WeakMap),J(j,e,r,t))}if(H(e)){if(e.k)return c(e.k);j||(j=new WeakMap);return J(j,e,e,t,!0)}return e};async function q(e,t,r){if("sign"===r&&(t=await F(t,e)),"verify"===r&&(t=await M(t,e)),k(t))return P(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(C(t,...O));return b.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(C(t,...O,"Uint8Array","JSON Web Key"))}const z=async(e,t,r,n)=>{const i=await q(e,t,"verify");E(e,i);const s=S(e,i.algorithm);try{return await b.subtle.verify(s,i,r,n)}catch{return!1}},V=(...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},B=e=>e?.[Symbol.toStringTag],G=(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},Q=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&H(t)){if(function(e){return H(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&G(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(!$(t))throw new TypeError(R(e,t,...O,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${B(t)} instances for symmetric algorithms must be of type "secret"`)}};function X(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Q(t,r,n,e):((e,t,r,n)=>{if(n&&H(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&G(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)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!$(t))throw new TypeError(R(e,t,...O,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${B(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${B(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${B(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${B(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${B(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}X.bind(void 0,!1);const Y=X.bind(void 0,!0);const Z=function(e,t,r,n,i){if(void 0!==i.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 s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!s.has(t))throw new p(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)},ee=(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)};async function te(e,t){if(!L(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 c(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new p('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return N({...e,alg:t});default:throw new p('Unsupported "kty" (Key Type) Parameter value')}}async function re(e,t,n){if(e instanceof Uint8Array&&(e=s.decode(e)),"string"!=typeof e)throw new g("Compact JWS must be a string or Uint8Array");const{0:i,1:a,2:d,length:l}=e.split(".");if(3!==l)throw new g("Invalid Compact JWS");const u=await async function(e,t,n){if(!L(e))throw new g("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new g('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new g("JWS Protected Header incorrect type");if(void 0===e.payload)throw new g("JWS Payload missing");if("string"!=typeof e.signature)throw new g("JWS Signature missing or incorrect type");if(void 0!==e.header&&!L(e.header))throw new g("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{const t=c(e.protected);i=JSON.parse(s.decode(t))}catch{throw new g("JWS Protected Header is invalid")}if(!V(i,e.header))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const a={...i,...e.header};let d=!0;if(Z(g,new Map([["b64",!0]]),n?.crit,i,a).has("b64")&&(d=i.b64,"boolean"!=typeof d))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:l}=a;if("string"!=typeof l||!l)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');const u=n&&ee("algorithms",n.algorithms);if(u&&!u.has(l))throw new h('"alg" (Algorithm) Header Parameter value not allowed');if(d){if("string"!=typeof e.payload)throw new g("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new g("JWS Payload must be a string or an Uint8Array instance");let p=!1;"function"==typeof t?(t=await t(i,e),p=!0,Y(l,t,"verify"),H(t)&&(t=await te(t,l))):Y(l,t,"verify");const f=o(r.encode(e.protected??""),r.encode("."),"string"==typeof e.payload?r.encode(e.payload):e.payload);let w,y;try{w=c(e.signature)}catch{throw new g("Failed to base64url decode the signature")}if(!await z(l,t,w,f))throw new v;if(d)try{y=c(e.payload)}catch{throw new g("Failed to base64url decode the payload")}else y="string"==typeof e.payload?r.encode(e.payload):e.payload;const m={payload:y};return void 0!==e.protected&&(m.protectedHeader=i),void 0!==e.header&&(m.unprotectedHeader=e.header),p?{...m,key:t}:m}({payload:a,protected:i,signature:d},t,n),p={payload:u.payload,protectedHeader:u.protectedHeader};return"function"==typeof t?{...p,key:u.key}:p}const ne=e=>Math.floor(e.getTime()/1e3);(Object.getOwnPropertyDescriptor(ne,"name")||{}).writable||Object.defineProperty(ne,"name",{value:"default",configurable:!0});const ie=86400,se=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,oe=e=>{const t=se.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(r*ie);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};(Object.getOwnPropertyDescriptor(oe,"name")||{}).writable||Object.defineProperty(oe,"name",{value:"default",configurable:!0});const ae=e=>e.toLowerCase().replace(/^application\//,""),ce=(e,t,r={})=>{let n;try{n=JSON.parse(s.decode(t))}catch{}if(!L(n))throw new f("JWT Claims Set must be a top-level JSON object");const{typ:i}=r;if(i&&("string"!=typeof e.typ||ae(e.typ)!==ae(i)))throw new l('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:o=[],issuer:a,subject:c,audience:d,maxTokenAge:h}=r,p=[...o];void 0!==h&&p.push("iat"),void 0!==d&&p.push("aud"),void 0!==c&&p.push("sub"),void 0!==a&&p.push("iss");for(const e of new Set(p.reverse()))if(!(e in n))throw new l(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new l('unexpected "iss" claim value',n,"iss","check_failed");if(c&&n.sub!==c)throw new l('unexpected "sub" claim value',n,"sub","check_failed");if(d&&(g=n.aud,w="string"==typeof d?[d]:d,!("string"==typeof g?w.includes(g):Array.isArray(g)&&w.some(Set.prototype.has.bind(new Set(g))))))throw new l('unexpected "aud" claim value',n,"aud","check_failed");var g,w;let y;switch(typeof r.clockTolerance){case"string":y=oe(r.clockTolerance);break;case"number":y=r.clockTolerance;break;case"undefined":y=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,_=ne(m||new Date);if((void 0!==n.iat||h)&&"number"!=typeof n.iat)throw new l('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new l('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>_+y)throw new l('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new l('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=_-y)throw new u('"exp" claim timestamp check failed',n,"exp","check_failed")}if(h){const e=_-n.iat;if(e-y>("number"==typeof h?h:oe(h)))throw new u('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-y)throw new l('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};(Object.getOwnPropertyDescriptor(ce,"name")||{}).writable||Object.defineProperty(ce,"name",{value:"default",configurable:!0});const de=async(e,t,r)=>{let n,i,s=!1;"function"==typeof AbortController&&(n=new AbortController,i=setTimeout(()=>{s=!0,n.abort()},t));const o=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(s)throw new _;throw e});if(void 0!==i&&clearTimeout(i),200!==o.status)throw new d("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new d("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function le(e){return L(e)}function ue(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class he{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 w("JSON Web Key Set malformed");this._jwks=ue(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},i=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 p('Unsupported "alg" value for a JSON Web Key Set')}}(r),s=this._jwks.keys.filter(e=>{let t=i===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}=s;if(0===a)throw new y;if(1!==a){const e=new m,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of s)try{yield await pe(t,e,r)}catch{}},e}return pe(this._cached,o,r)}}async function pe(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await te({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new w("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function ge(e){const t=new he(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>ue(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}let fe;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){fe=`${"jose"}/${"v5.10.0"}`}const we=Symbol();class ye{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?.[we]&&(this._cache=t?.[we],r=t?.[we],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&L(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,L)&&(this._jwksTimestamp=this._cache.uat,this._local=ge(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);fe&&!e.has("User-Agent")&&(e.set("User-Agent",fe),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=de(this._url,this._timeoutDuration,this._options).then(e=>{this._local=ge(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}}const me=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:a(e)};if(!k(e))throw new TypeError(C(e,...O,"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:i,...s}=await b.subtle.exportKey("jwk",e);return s};async function _e(e){return me(e)}const ve=async(e,t,r)=>{const n=await q(e,t,"sign");E(e,n);const i=await b.subtle.sign(S(e,n.algorithm),n,r);return new Uint8Array(i)};class Se{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 g("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!V(this._protectedHeader,this._unprotectedHeader))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this._protectedHeader,...this._unprotectedHeader};let i=!0;if(Z(g,new Map([["b64",!0]]),t?.crit,this._protectedHeader,n).has("b64")&&(i=this._protectedHeader.b64,"boolean"!=typeof i))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:c}=n;if("string"!=typeof c||!c)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');Y(c,e,"sign");let d,l=this._payload;i&&(l=r.encode(a(l))),d=this._protectedHeader?r.encode(a(JSON.stringify(this._protectedHeader))):r.encode("");const u=o(d,r.encode("."),l),h=await ve(c,e,u),p={signature:a(h),payload:""};return i&&(p.payload=s.decode(l)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=s.decode(d)),p}}class be{constructor(e){this._flattened=new Se(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 ke(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Ee{constructor(e={}){if(!L(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:ke("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:ke("setNotBefore",ne(e))}:this._payload={...this._payload,nbf:ne(new Date)+oe(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:ke("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:ke("setExpirationTime",ne(e))}:this._payload={...this._payload,exp:ne(new Date)+oe(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:ne(new Date)}:e instanceof Date?this._payload={...this._payload,iat:ke("setIssuedAt",ne(e))}:this._payload="string"==typeof e?{...this._payload,iat:ke("setIssuedAt",ne(new Date)+oe(e))}:{...this._payload,iat:ke("setIssuedAt",e)},this}}class Ie extends Ee{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const n=new be(r.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new f("JWTs MUST NOT use unencoded payload");return n.sign(e,t)}}function Te(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new p("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function Ae(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:Te(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:Te(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:Te(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=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new p("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=t?.crv??"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 p("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return b.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const Ue={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let Pe;const xe=new Uint8Array(16);const Ce=[];for(let e=0;e<256;++e)Ce.push((e+256).toString(16).slice(1));function Re(e,t=0){return(Ce[e[t+0]]+Ce[e[t+1]]+Ce[e[t+2]]+Ce[e[t+3]]+"-"+Ce[e[t+4]]+Ce[e[t+5]]+"-"+Ce[e[t+6]]+Ce[e[t+7]]+"-"+Ce[e[t+8]]+Ce[e[t+9]]+"-"+Ce[e[t+10]]+Ce[e[t+11]]+Ce[e[t+12]]+Ce[e[t+13]]+Ce[e[t+14]]+Ce[e[t+15]]).toLowerCase()}const $e=function(e,t,r){if(Ue.randomUUID&&!t&&!e)return Ue.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!Pe){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Pe=crypto.getRandomValues.bind(crypto)}return Pe(xe)}();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=n[e];return t}return Re(n)},Oe="solidClientAuthn:",Le=["ES256","RS256"],He="error",Ne="login",De="logout",je="newRefreshToken",Ke="sessionExpired",We="sessionExtended",Je="sessionRestore",Me="timeoutSet",Fe=["openid","offline_access","webid"];class qe{handleables;constructor(e){this.handleables=e,this.handleables=e}async getProperHandler(e){const t=await Promise.all(this.handleables.map(t=>t.canHandle(...e)));for(let e=0;e<t.length;e+=1)if(t[e])return this.handleables[e];return null}async canHandle(...e){return null!==await this.getProperHandler(e)}async handle(...e){const t=await this.getProperHandler(e);if(t)return t.handle(...e);throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${e.map(e=>{try{return JSON.stringify(e)}catch(t){return e.toString()}}).join(", ")}`)}}async function ze(e,t,r,n){let i,s;try{const{payload:s}=await async function(e,t,r){const n=await re(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new f("JWTs MUST NOT use unencoded payload");const i={payload:ce(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}(e,function(e,t){const r=new ye(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}(new URL(t)),{issuer:r,audience:n});i=s}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof i.azp&&(s=i.azp),"string"==typeof i.webid)return{webId:i.webid,clientId:s};if("string"!=typeof i.sub)throw new Error(`The token ${JSON.stringify(i)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(i.sub),{webId:i.sub,clientId:s}}catch(e){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${i.sub}] is invalid as a URL - error [${e}].`)}}function Ve(e){try{const t=new URL(e),r=!t.searchParams.has("code")&&!t.searchParams.has("state"),n=""===t.hash;return r&&n}catch(e){return!1}}function Be(e){const t=new URL(e);return t.searchParams.delete("state"),t.searchParams.delete("code"),t.searchParams.delete("error"),t.searchParams.delete("error_description"),t.searchParams.delete("iss"),t}class Ge{storageUtility;redirector;constructor(e,t){this.storageUtility=e,this.redirector=t,this.storageUtility=e,this.redirector=t}parametersGuard=e=>void 0!==e.issuerConfiguration.grantTypesSupported&&e.issuerConfiguration.grantTypesSupported.indexOf("authorization_code")>-1&&void 0!==e.redirectUrl;async canHandle(e){return this.parametersGuard(e)}async setupRedirectHandler({oidcLoginOptions:e,state:t,codeVerifier:r,targetUrl:n}){if(!this.parametersGuard(e))throw new Error("The authorization code grant requires a redirectUrl.");var i,s;await Promise.all([this.storageUtility.setForUser(t,{sessionId:e.sessionId}),this.storageUtility.setForUser(e.sessionId,{codeVerifier:r,issuer:e.issuer.toString(),redirectUrl:e.redirectUrl,dpop:Boolean(e.dpop).toString(),keepAlive:(i=e.keepAlive,s=!0,"boolean"==typeof i?Boolean(i):Boolean(s)).toString()})]),this.redirector.redirect(n,{handleRedirect:e.handleRedirect})}}class Qe{sessionInfoManager;constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class Xe{redirector;constructor(e){this.redirector=e,this.redirector=e}async canHandle(e,t){return"idp"===t?.logoutType}async handle(e,t){if("idp"!==t?.logoutType)throw new Error("Attempting to call idp logout handler to perform app logout");if(void 0===t.toLogoutUrl)throw new Error("Cannot perform IDP logout. Did you log in using the OIDC authentication flow?");this.redirector.redirect(t.toLogoutUrl(t),{handleRedirect:t.handleRedirect})}}class Ye{handlers;constructor(e,t){this.handlers=[new Qe(e),new Xe(t)]}async canHandle(){return!0}async handle(e,t){for(const r of this.handlers)await r.canHandle(e,t)&&await r.handle(e,t)}}function Ze(){return{isLoggedIn:!1,sessionId:$e(),fetch:(...e)=>fetch(...e)}}async function et(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}class tt{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}update(e,t){throw new Error("Not Implemented")}set(e,t){throw new Error("Not Implemented")}get(e){throw new Error("Not implemented")}async getAll(){throw new Error("Not implemented")}async clear(e){return et(e,this.storageUtility)}async register(e){throw new Error("Not implemented")}async getRegisteredSessionIdAll(){throw new Error("Not implemented")}async clearAll(){throw new Error("Not implemented")}async setOidcContext(e,t){throw new Error("Not implemented")}}function rt({endSessionEndpoint:e,idTokenHint:t}){if(void 0!==e)return function({state:r,postLogoutUrl:n}){return function({endSessionEndpoint:e,idTokenHint:t,postLogoutRedirectUri:r,state:n}){const i=new URL(e);return void 0!==t&&i.searchParams.append("id_token_hint",t),void 0!==r&&(i.searchParams.append("post_logout_redirect_uri",r),void 0!==n&&i.searchParams.append("state",n)),i.toString()}({endSessionEndpoint:e,idTokenHint:t,state:r,postLogoutRedirectUri:n})}}function nt(e){try{return new URL(e),!0}catch{return!1}}async function it(e,t,r,n){let i;if(function(e,t){return t.scopesSupported.includes("webid")&&void 0!==e.clientId&&nt(e.clientId)}(e,t))i={clientId:e.clientId,clientName:e.clientName,clientType:"solid-oidc"};else{if(!function(e){return void 0!==e.clientId&&!nt(e.clientId)}(e))return n.getClient({sessionId:e.sessionId,clientName:e.clientName,redirectUrl:e.redirectUrl},t);i={clientId:e.clientId,clientSecret:e.clientSecret,clientName:e.clientName,clientType:"static"}}const s={clientId:i.clientId,clientType:i.clientType};return"static"===i.clientType&&(s.clientSecret=i.clientSecret),i.clientName&&(s.clientName=i.clientName),await r.setForUser(e.sessionId,s),i}const st=(e,t)=>fetch(e,t);class ot{loginHandler;redirectHandler;logoutHandler;sessionInfoManager;issuerConfigFetcher;boundLogout;constructor(e,t,r,n,i){this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i,this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i}fetch=st;logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===t?.logoutType?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=st,delete this.boundLogout};getSessionInfo=async e=>this.sessionInfoManager.get(e);getAllSessionInfo=async()=>this.sessionInfoManager.getAll()}async function at(e,t,r){try{const[n,i,s,o,a]=await Promise.all([t.getForUser(e,"issuer",{errorIfNull:!0}),t.getForUser(e,"codeVerifier"),t.getForUser(e,"redirectUrl"),t.getForUser(e,"dpop",{errorIfNull:!0}),t.getForUser(e,"keepAlive")]);await t.deleteForUser(e,"codeVerifier");return{codeVerifier:i,redirectUrl:s,issuerConfig:await r.fetchConfig(n),dpop:"true"===o,keepAlive:"string"!=typeof a||"true"===a}}catch(t){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${e}]: ${t}`)}}class ct{secureStorage;insecureStorage;constructor(e,t){this.secureStorage=e,this.insecureStorage=t,this.secureStorage=e,this.insecureStorage=t}getKey(e){return`solidClientAuthenticationUser:${e}`}async getUserData(e,t){const r=await(t?this.secureStorage:this.insecureStorage).get(this.getKey(e));if(void 0===r)return{};try{return JSON.parse(r)}catch(n){throw new Error(`Data for user [${e}] in [${t?"secure":"unsecure"}] storage is corrupted - expected valid JSON, but got: ${r}`)}}async setUserData(e,t,r){await(r?this.secureStorage:this.insecureStorage).set(this.getKey(e),JSON.stringify(t))}async get(e,t){const r=await(t?.secure?this.secureStorage:this.insecureStorage).get(e);if(void 0===r&&t?.errorIfNull)throw new Error(`[${e}] is not stored`);return r}async set(e,t,r){return(r?.secure?this.secureStorage:this.insecureStorage).set(e,t)}async delete(e,t){return(t?.secure?this.secureStorage:this.insecureStorage).delete(e)}async getForUser(e,t,r){const n=await this.getUserData(e,r?.secure);let i;if(n&&n[t]||(i=void 0),i=n[t],void 0===i&&r?.errorIfNull)throw new Error(`Field [${t}] for user [${e}] is not stored`);return i||void 0}async setForUser(e,t,r){let n;try{n=await this.getUserData(e,r?.secure)}catch{n={}}await this.setUserData(e,{...n,...t},r?.secure)}async deleteForUser(e,t,r){const n=await this.getUserData(e,r?.secure);delete n[t],await this.setUserData(e,n,r?.secure)}async deleteAllUserData(e,t){await(t?.secure?this.secureStorage:this.insecureStorage).delete(this.getKey(e))}}class dt{map={};async get(e){return this.map[e]||void 0}async set(e,t){this.map[e]=t}async delete(e){delete this.map[e]}}class lt extends Error{constructor(e){super(e)}}Error;class ut extends Error{missingFields;constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class ht extends Error{error;errorDescription;constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function pt(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function gt(e,t,r){return new Ie({htu:pt(e),htm:t.toUpperCase(),jti:$e()}).setProtectedHeader({alg:Le[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function ft(e,t,r,n){if(void 0!==r)return async function(e,t,r,n){const i=new Headers(n?.headers);return i.set("Authorization",`DPoP ${t}`),i.set("DPoP",await gt(e,n?.method??"get",r)),{...n,headers:i}}(e,t,r,n);const i=new Headers(n?.headers);return i.set("Authorization",`Bearer ${t}`),{...n,headers:i}}async function wt(e,t,r,n,i=fetch){return i(t,await ft(t.toString(),e,n,r))}const yt=e=>void 0!==e?e-5>0?e-5:e:600;function mt(e,t){let r,n=e;const i=t?.refreshOptions,s=t?.eventEmitter;if(void 0!==t&&void 0!==i){const e=async()=>{try{const{accessToken:o,refreshToken:a,expiresIn:c}=await async function(e,t,r){const n=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return r?.emit(We,n.expiresIn??600),{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn}}(i,t.dpopKey,s);n=o,void 0!==a&&(i.refreshToken=a),clearTimeout(r),r=setTimeout(e,1e3*yt(c)),t.eventEmitter?.emit(Me,r)}catch(e){e instanceof ht&&(s?.emit(He,e.error,e.errorDescription),s?.emit(Ke)),e instanceof ut&&e.missingFields.includes("access_token")&&s?.emit(Ke)}};r=setTimeout(e,1e3*yt(t.expiresIn)),s?.emit(Me,r)}else if(void 0!==s){const e=setTimeout(()=>{s.emit(Ke)},1e3*yt(t?.expiresIn));s.emit(Me,e)}return async(e,r)=>{let i=await wt(n,e,r,t?.dpopKey,t?.fetch);const s=!i.ok&&(o=i.status,![401,403].includes(o));var o;if(i.ok||s)return i;return i.url!==e&&void 0!==t?.dpopKey&&(i=await wt(n,i.url,r,t.dpopKey,t.fetch)),i}}var _t=n(7);class vt extends Error{}function St(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}(t)}catch(e){return atob(t)}}vt.prototype.name="InvalidTokenError";var bt,kt,Et,It={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},Tt=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(Tt||{});(Et=Tt||(Tt={})).reset=function(){bt=3,kt=It},Et.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");bt=e},Et.setLogger=function(e){kt=e};var At=class e{constructor(e){this._name=e}debug(...t){bt>=4&&kt.debug(e._format(this._name,this._method),...t)}info(...t){bt>=3&&kt.info(e._format(this._name,this._method),...t)}warn(...t){bt>=2&&kt.warn(e._format(this._name,this._method),...t)}error(...t){bt>=1&&kt.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,r){const n=new e(`${t}.${r}`);return n.debug("begin"),n}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(t,...r){bt>=4&&kt.debug(e._format(t),...r)}static info(t,...r){bt>=3&&kt.info(e._format(t),...r)}static warn(t,...r){bt>=2&&kt.warn(e._format(t),...r)}static error(t,...r){bt>=1&&kt.error(e._format(t),...r)}};Tt.reset();var Ut=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new vt("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new vt(`Invalid token specified: missing part #${r+1}`);let i;try{i=St(n)}catch(e){throw new vt(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new vt(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}(e)}catch(e){throw At.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,r){const n=`${Ct.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${Ct.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,(new TextEncoder).encode(n));return`${n}.${Ct.encodeBase64Url(new Uint8Array(i))}`}static async generateSignedJwtWithHmac(e,t,r){const n=`${Ct.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${Ct.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign("HMAC",r,(new TextEncoder).encode(n));return`${n}.${Ct.encodeBase64Url(new Uint8Array(i))}`}},Pt=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),xt=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Pt(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw At.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return Pt(r)}static async hash(e,t){const r=(new TextEncoder).encode(t),n=await crypto.subtle.digest(e,r);return new Uint8Array(n)}static async customCalculateJwkThumbprint(t){let r;switch(t.kty){case"RSA":r={e:t.e,kty:t.kty,n:t.n};break;case"EC":r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":r={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":r={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const n=await e.hash("SHA-256",JSON.stringify(r));return e.encodeBase64Url(n)}static async generateDPoPProof({url:t,accessToken:r,httpMethod:n,keyPair:i,nonce:s}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=n?n:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};r&&(o=await e.hash("SHA-256",r),a=e.encodeBase64Url(o),c.ath=a),s&&(c.nonce=s);try{const e=await crypto.subtle.exportKey("jwk",i.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await Ut.generateSignedJwt(t,c,i.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const r=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(r)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,r,n,i="HS256"){const s=Math.floor(Date.now()/1e3),o={alg:i,typ:"JWT"},a={iss:t,sub:t,aud:n,jti:e.generateUUIDv4(),exp:s+300,iat:s},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[i];if(!c)throw new Error(`Unsupported algorithm: ${i}. Supported algorithms are: HS256, HS384, HS512`);const d=new TextEncoder,l=await crypto.subtle.importKey("raw",d.encode(r),{name:"HMAC",hash:c},!1,["sign"]);return await Ut.generateSignedJwtWithHmac(o,a,l)}};xt.encodeBase64Url=e=>Pt(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var Ct=xt,Rt=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new At(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},$t=class e extends Rt{constructor(){super(...arguments),this._logger=new At(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const r=this._logger.create("init");t=Math.max(Math.floor(t),1);const n=e.getEpochTime()+t;if(this.expiration===n&&this._timerHandle)return void r.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),r.debug("using duration",t),this._expiration=n;const i=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*i)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},Ot=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const r=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(r.slice(1))}},Lt=";",Ht=class extends Error{constructor(e,t){var r,n,i;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw At.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(r=e.error_description)?r:null,this.error_uri=null!=(n=e.error_uri)?n:null,this.state=e.userState,this.session_state=null!=(i=e.session_state)?i:null,this.url_state=e.url_state}},Nt=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},Dt=class{constructor(){this._logger=new At("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},jt=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},Kt=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new At("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...n}=t;if(!r)return await fetch(e,n);const i=new AbortController,s=setTimeout(()=>i.abort(),1e3*r);try{return await fetch(e,{...t,signal:i.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new Nt("Network timed out");throw e}finally{clearTimeout(s)}}async getJson(e,{token:t,credentials:r,timeoutInSeconds:n}={}){const i=this._logger.create("getJson"),s={Accept:this._contentTypes.join(", ")};let o;t&&(i.debug("token passed, setting Authorization header"),s.Authorization="Bearer "+t),this._appendExtraHeaders(s);try{i.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:s,timeoutInSeconds:n,credentials:r})}catch(e){throw i.error("Network Error"),e}i.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(e=>a.startsWith(e))&&i.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(i.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(i.error("Error from server:",c),c.error)throw new Ht(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:n,initCredentials:i,extraHeaders:s}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...s};let c;void 0!==r&&(a.Authorization="Basic "+r),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:n,credentials:i})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(e=>d.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=d?d:"undefined"}, from URL: ${e}`);const l=await c.text();let u={};if(l)try{u=JSON.parse(l)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",u),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new jt(e,`${JSON.stringify(u)}`)}if(u.error)throw new Ht(u,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`)}return u}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),n=["accept","content-type"],i=["authorization"];0!==r.length&&r.forEach(r=>{if(n.includes(r.toLocaleLowerCase()))return void t.warn("Protected header could not be set",r,n);if(i.includes(r.toLocaleLowerCase())&&Object.keys(e).includes(r))return void t.warn("Header could not be overridden",r,i);const s="function"==typeof this._extraHeaders[r]?this._extraHeaders[r]():this._extraHeaders[r];s&&""!==s&&(e[r]=s)})}},Wt=class{constructor(e){this._settings=e,this._logger=new At("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new Kt(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const r=this._logger.create(`_getMetadataProperty('${e}')`),n=await this.getMetadata();if(r.debug("resolved"),void 0===n[e]){if(!0===t)return void r.warn("Metadata does not contain optional property");r.throw(new Error("Metadata does not contain property "+e))}return n[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const r=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}},Jt=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new At("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let r=0;r<e;r++){const e=await this._store.key(r);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},Mt=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:n,metadataSeed:i,client_id:s,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:d,post_logout_redirect_uri:l,client_authentication:u="client_secret_post",token_endpoint_auth_signing_alg:h="HS256",prompt:p,display:g,max_age:f,ui_locales:w,acr_values:y,resource:m,response_mode:_,filterProtocolClaims:v=!0,loadUserInfo:S=!1,requestTimeoutInSeconds:b,staleStateAgeInSeconds:k=900,mergeClaimsStrategy:E={array:"replace"},disablePKCE:I=!1,stateStore:T,revokeTokenAdditionalContentTypes:A,fetchRequestCredentials:U,refreshTokenAllowedScope:P,extraQueryParams:x={},extraTokenParams:C={},extraHeaders:R={},dpop:$,omitScopeWhenRequesting:O=!1}){var L;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=r,this.metadataSeed=i,this.signingKeys=n,this.client_id=s,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=d,this.post_logout_redirect_uri=l,this.client_authentication=u,this.token_endpoint_auth_signing_alg=h,this.prompt=p,this.display=g,this.max_age=f,this.ui_locales=w,this.acr_values=y,this.resource=m,this.response_mode=_,this.filterProtocolClaims=null==v||v,this.loadUserInfo=!!S,this.staleStateAgeInSeconds=k,this.mergeClaimsStrategy=E,this.omitScopeWhenRequesting=O,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=A,this.fetchRequestCredentials=U||"same-origin",this.requestTimeoutInSeconds=b,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new Dt;this.stateStore=new Jt({store:e})}if(this.refreshTokenAllowedScope=P,this.extraQueryParams=x,this.extraTokenParams=C,this.extraHeaders=R,this.dpop=$,this.dpop&&!(null==(L=this.dpop)?void 0:L.store))throw new Error("A DPoPStore is required when dpop is enabled")}},Ft=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new At("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=Ut.decode(e);return t.debug("JWT decoding successful"),r}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new Kt(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const n=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",n),n}},qt=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new At("TokenClient"),this._jsonService=new Kt(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:i,...s}){const o=this._logger.create("exchangeCode");r||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),s.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(s))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==n)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=Ct.generateBasicAuth(r,n);break;case"client_secret_post":a.append("client_id",r),n&&a.append("client_secret",n);break;case"client_secret_jwt":{const e=await Ct.generateClientAssertionJwt(r,n,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",r),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:n=this._settings.scope,...i}){const s=this._logger.create("exchangeCredentials");t||s.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",n);for(const[e,t]of Object.entries(i))null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw s.throw(new Error("A client_secret is required")),null;let a;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=Ct.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break;case"client_secret_jwt":{const e=await Ct.generateClientAssertionJwt(t,r,c,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}s.debug("got token endpoint");const d=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return s.debug("got response"),d}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:i,...s}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),s.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(s))Array.isArray(t)?t.forEach(t=>a.append(e,t)):null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=Ct.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r);break;case"client_secret_jwt":{const e=await Ct.generateClientAssertionJwt(t,r,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),l}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const i=new URLSearchParams;for(const[t,r]of Object.entries(e))null!=r&&i.set(t,r);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:i,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),r.debug("got response")}},zt=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new At("ResponseValidator"),this._userInfoService=new Ft(this._settings,this._metadataService),this._tokenClient=new qt(this._settings,this._metadataService)}async validateSigninResponse(e,t,r){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t,r),n.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e,"",t.nonce),n.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse"),n=e.isOpenId&&!!e.id_token;n&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,n),r.debug("claims processed")}async validateRefreshResponse(e,t){const r=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),r.debug("claims processed")}validateSignoutResponse(e,t){const r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new Ht(e)}_processSigninState(e,t){const r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new Ht(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const n=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void n.debug("not loading user info");n.debug("loading user info");const i=await this._userInfoService.getClaims(e.access_token);n.debug("user info claims received from user info endpoint"),r&&i.sub!==e.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(i)),n.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,r){const n=this._logger.create("_processCode");if(e.code){n.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:r,...t.extraTokenParams});Object.assign(e,i)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t,r){var n;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const s=Ut.decode(null!=(n=e.id_token)?n:"");if(s.sub||i.throw(new Error("ID Token is missing a subject claim")),r&&s.nonce!==r&&i.throw(new Error("nonce in id_token does not match nonce in client storage")),t){const e=Ut.decode(t);s.sub!==e.sub&&i.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&i.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},Vt=class e{constructor(e){this.id=e.id||Ct.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=$t.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new At("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return At.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,r){const n=At.createStatic("State","clearStaleState"),i=$t.getEpochTime()-r,s=await t.getAllKeys();n.debug("got keys",s);for(let r=0;r<s.length;r++){const o=s[r],a=await t.get(o);let c=!1;if(a)try{const t=await e.fromStorageString(a);n.debug("got item from key:",o,t.created),t.created<=i&&(c=!0)}catch(e){n.error("Error parsing state for key:",o,e),c=!0}else n.debug("no item in storage for key:",o),c=!0;c&&(n.debug("removed item for key:",o),t.remove(o))}}},Bt=class e extends Vt{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo,this.nonce=e.nonce}static async create(t){const r=!0===t.code_verifier?Ct.generateCodeVerifier():t.code_verifier||void 0,n=r?await Ct.generateCodeChallenge(r):void 0;return new e({...t,code_verifier:r,code_challenge:n})}toStorageString(){return new At("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo,nonce:this.nonce})}static fromStorageString(t){At.createStatic("SigninState","fromStorageString");const r=JSON.parse(t);return e.create(r)}},Gt=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:r,client_id:n,redirect_uri:i,response_type:s,scope:o,state_data:a,response_mode:c,request_type:d,client_secret:l,nonce:u,url_state:h,resource:p,skipUserInfo:g,extraQueryParams:f,extraTokenParams:w,disablePKCE:y,dpopJkt:m,omitScopeWhenRequesting:_,...v}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!n)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!s)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!r)throw this._logger.error("create: No authority passed"),new Error("authority");const S=await Bt.create({data:a,request_type:d,url_state:h,code_verifier:!y,client_id:n,authority:r,redirect_uri:i,response_mode:c,client_secret:l,scope:o,extraTokenParams:w,skipUserInfo:g,nonce:u}),b=new URL(t);b.searchParams.append("client_id",n),b.searchParams.append("redirect_uri",i),b.searchParams.append("response_type",s),_||b.searchParams.append("scope",o),u&&b.searchParams.append("nonce",u),m&&b.searchParams.append("dpop_jkt",m);let k=S.id;if(h&&(k=`${k}${Lt}${h}`),b.searchParams.append("state",k),S.code_challenge&&(b.searchParams.append("code_challenge",S.code_challenge),b.searchParams.append("code_challenge_method","S256")),p){(Array.isArray(p)?p:[p]).forEach(e=>b.searchParams.append("resource",e))}for(const[e,t]of Object.entries({response_mode:c,...v,...f}))null!=t&&b.searchParams.append(e,t.toString());return new e({url:b.href,state:S})}};Gt._logger=new At("SigninRequest");var Qt=Gt,Xt=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(Lt);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Lt))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-$t.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+$t.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},Yt=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:n,extraQueryParams:i,request_type:s,client_id:o,url_state:a}){if(this._logger=new At("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(r&&c.searchParams.append("id_token_hint",r),o&&c.searchParams.append("client_id",o),n&&(c.searchParams.append("post_logout_redirect_uri",n),t||a)){this.state=new Vt({data:t,request_type:s,url_state:a});let e=this.state.id;a&&(e=`${e}${Lt}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...i}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},Zt=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(Lt);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Lt))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},er=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],tr=["sub","iss","aud","exp","iat"],rr=class{constructor(e){this._settings=e,this._logger=new At("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:er;for(const r of e)tr.includes(r)||delete t[r]}return t}mergeClaims(e,t){const r={...e};for(const[e,n]of Object.entries(t))if(r[e]!==n)if(Array.isArray(r[e])||Array.isArray(n))if("replace"==this._settings.mergeClaimsStrategy.array)r[e]=n;else{const t=Array.isArray(r[e])?r[e]:[r[e]];for(const e of Array.isArray(n)?n:[n])t.includes(e)||t.push(e);r[e]=t}else"object"==typeof r[e]&&"object"==typeof n?r[e]=this.mergeClaims(r[e],n):r[e]=n;return r}},nr=class{constructor(e,t){this.keys=e,this.nonce=t}},ir=class{constructor(e,t){this._logger=new At("OidcClient"),this.settings=e instanceof Mt?e:new Mt(e),this.metadataService=null!=t?t:new Wt(this.settings),this._claimsService=new rr(this.settings),this._validator=new zt(this.settings,this.metadataService,this._claimsService),this._tokenClient=new qt(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:n,id_token_hint:i,login_hint:s,skipUserInfo:o,nonce:a,url_state:c,response_type:d=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:p=this.settings.display,max_age:g=this.settings.max_age,ui_locales:f=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:y=this.settings.resource,response_mode:m=this.settings.response_mode,extraQueryParams:_=this.settings.extraQueryParams,extraTokenParams:v=this.settings.extraTokenParams,dpopJkt:S,omitScopeWhenRequesting:b=this.settings.omitScopeWhenRequesting}){const k=this._logger.create("createSigninRequest");if("code"!==d)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const E=await this.metadataService.getAuthorizationEndpoint();k.debug("Received authorization endpoint",E);const I=await Qt.create({url:E,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:d,scope:l,state_data:e,url_state:c,prompt:h,display:p,max_age:g,ui_locales:f,id_token_hint:i,login_hint:s,acr_values:w,dpopJkt:S,resource:y,request:t,request_uri:r,extraQueryParams:_,extraTokenParams:v,request_type:n,response_mode:m,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:b});await this.clearStaleState();const T=I.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),I}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),n=new Xt(Ot.readParams(e,this.settings.response_mode));if(!n.state)throw r.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[t?"remove":"get"](n.state);if(!i)throw r.throw(new Error("No matching state found in storage")),null;return{state:await Bt.fromStorageString(i),response:n}}async processSigninResponse(e,t,r=!0){const n=this._logger.create("processSigninResponse"),{state:i,response:s}=await this.readSigninResponseState(e,r);if(n.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(s,i,t)}catch(e){if(!(e instanceof jt&&this.settings.dpop))throw e;{const r=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=r,await this._validator.validateSigninResponse(s,i,t)}}return s}async getDpopProof(e,t){let r,n;return(await e.getAllKeys()).includes(this.settings.client_id)?(n=await e.get(this.settings.client_id),n.nonce!==t&&t&&(n.nonce=t,await e.set(this.settings.client_id,n))):(r=await Ct.generateDPoPKeys(),n=new nr(r,t),await e.set(this.settings.client_id,n)),await Ct.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:n={}}){const i=await this._tokenClient.exchangeCredentials({username:e,password:t,...n}),s=new Xt(new URLSearchParams);return Object.assign(s,i),await this._validator.validateCredentialsResponse(s,r),s}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:i,extraTokenParams:s}){var o;const a=this._logger.create("useRefreshToken");let c,d;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:e}}try{d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:i,...s})}catch(o){if(!(o instanceof jt&&this.settings.dpop))throw o;i.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:i,...s})}const l=new Xt(new URLSearchParams);return Object.assign(l,d),a.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:n,url_state:i,post_logout_redirect_uri:s=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),r||!s||t||(r=this.settings.client_id);const d=new Yt({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:s,state_data:e,extraQueryParams:o,request_type:n,url_state:i});await this.clearStaleState();const l=d.state;return l&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),d}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),n=new Zt(Ot.readParams(e,this.settings.response_mode));if(!n.state){if(r.debug("No state in response"),n.error)throw r.warn("Response was error:",n.error),new Ht(n);return{state:void 0,response:n}}const i=await this.settings.stateStore[t?"remove":"get"](n.state);if(!i)throw r.throw(new Error("No matching state found in storage")),null;return{state:await Vt.fromStorageString(i),response:n}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:n}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,r)):t.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),Vt.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}};function sr(e,t){if("string"!=typeof e.client_id)throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(e)}`);if(t.redirectUrl&&function(e){return Array.isArray(e.redirect_uris)&&e.redirect_uris.every(e=>"string"==typeof e)}(e)&&e.redirect_uris[0]!==t.redirectUrl.toString())throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(e.redirect_uris)} don't match the provided ${JSON.stringify([t.redirectUrl.toString()])}`);return!0}async function or(e,t){if(!t.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(t.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const r=(n=t.idTokenSigningAlgValuesSupported,Le.find(e=>n.includes(e))??null);var n;const i={client_name:e.clientName,application_type:"web",redirect_uris:[e.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:r,grant_types:["authorization_code","refresh_token"]},s=await fetch(t.registrationEndpoint.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(s.ok){const t=await s.json();return sr(t,e),{clientId:t.client_id,clientSecret:t.client_secret,expiresAt:t.client_secret_expires_at,idTokenSignedResponseAlg:t.id_token_signed_response_alg,clientType:"dynamic"}}throw 400===s.status&&function(e,t){if("invalid_redirect_uri"===e.error)throw new Error(`Dynamic client registration failed: the provided redirect uri [${t.redirectUrl?.toString()}] is invalid - ${e.error_description??""}`);if("invalid_client_metadata"===e.error)throw new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(t)} is invalid - ${e.error_description??""}`);throw new Error(`Dynamic client registration failed: ${e.error} - ${e.error_description??""}`)}(await s.json(),e),new Error(`Dynamic client registration failed: the server returned ${s.status} ${s.statusText} - ${await s.text()}`)}function ar(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function cr(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new ht(`Token endpoint returned error [${e.error}]${ar(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,ar(e)?e.error_description:void 0);var r;if(!function(e){return void 0!==e.access_token&&"string"==typeof e.access_token}(e))throw new ut(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new ut(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new ut(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new ut(["expires_in"]);if(!t&&"bearer"!==e.token_type.toLowerCase())throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${e.token_type}].`);return e}async function dr(e,t,r,n){!function(e,t){if(t.grantType&&(!e.grantTypesSupported||!e.grantTypesSupported.includes(t.grantType)))throw new Error(`The issuer [${e.issuer}] does not support the [${t.grantType}] grant`);if(!e.tokenEndpoint)throw new Error(`This issuer [${e.issuer}] does not have a token endpoint`)}(e,r);const i={"content-type":"application/x-www-form-urlencoded"};let s;n&&(s=await async function(){const{privateKey:e,publicKey:t}=await Ae(Le[0],{extractable:!0}),r={privateKey:e,publicKey:await _e(t)};return[r.publicKey.alg]=Le,r}(),i.DPoP=await gt(e.tokenEndpoint,"POST",s)),t.clientSecret&&(i.Authorization=`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`);const o={grant_type:r.grantType,redirect_uri:r.redirectUrl,code:r.code,code_verifier:r.codeVerifier,client_id:t.clientId},a={method:"POST",headers:i,body:new URLSearchParams(o).toString()},c=await fetch(e.tokenEndpoint,a),d=cr(await c.json(),n),{webId:l,clientId:u}=await ze(d.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:d.access_token,idToken:d.id_token,refreshToken:(h=d,void 0!==h.refresh_token&&"string"==typeof h.refresh_token?d.refresh_token:void 0),webId:l,clientId:u,dpopKey:s,expiresIn:d.expires_in};var h}async function lr(e,t,r,n){if(void 0===r.clientId)throw new Error("No client ID available when trying to refresh the access token.");const i={grant_type:"refresh_token",refresh_token:e};let s={};void 0!==n&&(s={DPoP:await gt(t.tokenEndpoint,"POST",n)});let o={};void 0!==r.clientSecret?o={Authorization:`Basic ${btoa(`${r.clientId}:${r.clientSecret}`)}`}:(e=>{try{return new URL(e),!0}catch{return!1}})(r.clientId)&&(i.client_id=r.clientId);const a=await fetch(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(i).toString(),headers:{...s,...o,"Content-Type":"application/x-www-form-urlencoded"}});let c;try{c=await a.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const d=cr(c,void 0!==n),{webId:l}=await ze(d.id_token,t.jwksUri,t.issuer,r.clientId);return{accessToken:d.access_token,idToken:d.id_token,refreshToken:"string"==typeof d.refresh_token?d.refresh_token:void 0,webId:l,dpopKey:n,expiresIn:d.expires_in}}class ur extends ct{constructor(e,t){super(e,t)}}class hr extends ot{login=async(e,t)=>{"none"!==e.prompt&&await this.sessionInfoManager.clear(e.sessionId);const r=e.redirectUrl??function(e){const t=Be(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}(window.location.href);if(!Ve(r))throw new Error(`${r} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:r,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return void 0===t||void 0===t.clientAppId||void 0===t.issuer||function(e){return void 0!==e.clientExpiresAt&&0!==e.clientExpiresAt&&e.clientExpiresAt<Math.floor(Date.now()/1e3)}(t)?null:t};handleIncomingRedirect=async(e,t)=>{try{const r=await this.redirectHandler.handle(e,t,void 0);return this.fetch=r.fetch.bind(window),this.boundLogout=r.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:r.isLoggedIn,webId:r.webId,sessionId:r.sessionId,expirationDate:r.expirationDate,clientAppId:r.clientAppId}}catch(r){return await this.cleanUrlAfterRedirect(e),void t.emit(He,"redirect",r)}};async cleanUrlAfterRedirect(e){const t=Be(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(e=>{setTimeout(()=>e(),1)})}}function pr(e){return"string"==typeof e.oidcIssuer}function gr(e){return"string"==typeof e.redirectUrl}class fr{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;constructor(e,t,r,n){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=r,this.clientRegistrar=n}async canHandle(e){return pr(e)&&gr(e)}async handle(e){if(!pr(e))throw new lt(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!gr(e))throw new lt(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await it(e,t,this.storageUtility,this.clientRegistrar),n={issuer:t.issuer,dpop:"dpop"===e.tokenType.toLowerCase(),...e,issuerConfiguration:t,client:r,scopes:(i=e.customScopes,Array.isArray(i)?Array.from(new Set([...Fe,...i.filter(e=>"string"==typeof e&&!e.includes(" "))])):Fe)};var i;return this.oidcHandler.handle(n)}}class wr extends Ge{async handle(e){const t=e.redirectUrl??"",r={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:t,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,prompt:e.prompt??"consent"},n=new ir(r);try{const t=await n.createSigninRequest({});return await this.setupRedirectHandler({oidcLoginOptions:e,state:t.state.id,codeVerifier:t.state.code_verifier??"",targetUrl:t.url.toString()})}catch(e){console.error(e)}}}const yr={issuer:{toKey:"issuer",convertToUrl:!0},authorization_endpoint:{toKey:"authorizationEndpoint",convertToUrl:!0},token_endpoint:{toKey:"tokenEndpoint",convertToUrl:!0},userinfo_endpoint:{toKey:"userinfoEndpoint",convertToUrl:!0},jwks_uri:{toKey:"jwksUri",convertToUrl:!0},registration_endpoint:{toKey:"registrationEndpoint",convertToUrl:!0},end_session_endpoint:{toKey:"endSessionEndpoint",convertToUrl:!0},scopes_supported:{toKey:"scopesSupported"},response_types_supported:{toKey:"responseTypesSupported"},response_modes_supported:{toKey:"responseModesSupported"},grant_types_supported:{toKey:"grantTypesSupported"},acr_values_supported:{toKey:"acrValuesSupported"},subject_types_supported:{toKey:"subjectTypesSupported"},id_token_signing_alg_values_supported:{toKey:"idTokenSigningAlgValuesSupported"},id_token_encryption_alg_values_supported:{toKey:"idTokenEncryptionAlgValuesSupported"},id_token_encryption_enc_values_supported:{toKey:"idTokenEncryptionEncValuesSupported"},userinfo_signing_alg_values_supported:{toKey:"userinfoSigningAlgValuesSupported"},userinfo_encryption_alg_values_supported:{toKey:"userinfoEncryptionAlgValuesSupported"},userinfo_encryption_enc_values_supported:{toKey:"userinfoEncryptionEncValuesSupported"},request_object_signing_alg_values_supported:{toKey:"requestObjectSigningAlgValuesSupported"},request_object_encryption_alg_values_supported:{toKey:"requestObjectEncryptionAlgValuesSupported"},request_object_encryption_enc_values_supported:{toKey:"requestObjectEncryptionEncValuesSupported"},token_endpoint_auth_methods_supported:{toKey:"tokenEndpointAuthMethodsSupported"},token_endpoint_auth_signing_alg_values_supported:{toKey:"tokenEndpointAuthSigningAlgValuesSupported"},display_values_supported:{toKey:"displayValuesSupported"},claim_types_supported:{toKey:"claimTypesSupported"},claims_supported:{toKey:"claimsSupported"},service_documentation:{toKey:"serviceDocumentation"},claims_locales_supported:{toKey:"claimsLocalesSupported"},ui_locales_supported:{toKey:"uiLocalesSupported"},claims_parameter_supported:{toKey:"claimsParameterSupported"},request_parameter_supported:{toKey:"requestParameterSupported"},request_uri_parameter_supported:{toKey:"requestUriParameterSupported"},require_request_uri_registration:{toKey:"requireRequestUriRegistration"},op_policy_uri:{toKey:"opPolicyUri",convertToUrl:!0},op_tos_uri:{toKey:"opTosUri",convertToUrl:!0}};class mr{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}async fetchConfig(e){let t;const r=new URL(".well-known/openid-configuration",e.endsWith("/")?e:`${e}/`).href,n=await fetch(r);try{t=function(e){const t={};return Object.keys(e).forEach(r=>{yr[r]&&(t[yr[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await n.json())}catch(t){throw new lt(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(mr.getLocalStorageKey(e),JSON.stringify(t)),t}}async function _r(e,t){await et(e,t),await async function(){const e=new Jt({});await Vt.clearStaleState(e,900);const t=window.localStorage,r=[];for(let e=0;e<=t.length;e+=1){const n=t.key(e);n&&(n.match(/^oidc\..+$/)||n.match(/^solidClientAuthenticationUser:.+$/))&&r.push(n)}r.forEach(e=>t.removeItem(e))}()}class vr extends tt{async get(e){const[t,r,n,i,s,o,a,c,d]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1}),this.storageUtility.getForUser(e,"expiresAt",{secure:!1})]);if("string"!=typeof s||Ve(s)){if(void 0!==c&&("string"!=typeof(l=c)||!["DPoP","Bearer"].includes(l)))throw new Error(`Tokens of type [${c}] are not supported.`);var l;if(void 0!==n||void 0!==t||void 0!==r||void 0!==o)return{sessionId:e,webId:r,isLoggedIn:"true"===t,redirectUrl:s,refreshToken:o,issuer:a,clientAppId:n,clientAppSecret:i,tokenType:c??"DPoP",clientExpiresAt:void 0!==d?Number.parseInt(d,10):void 0}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return _r(e,this.storageUtility)}}class Sr{async canHandle(e){try{return new URL(e),!0}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e){return Ze()}}class br{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;constructor(e,t,r,n,i){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.tokerRefresher=i,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.tokerRefresher=i}async canHandle(e){try{const t=new URL(e);return null!==t.searchParams.get("code")&&null!==t.searchParams.get("state")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const r=new URL(e),n=r.searchParams.get("state"),i=await this.storageUtility.getForUser(n,"sessionId",{errorIfNull:!0}),{issuerConfig:s,codeVerifier:o,redirectUrl:a,dpop:c}=await at(i,this.storageUtility,this.issuerConfigFetcher),d=r.searchParams.get("iss");if("string"==typeof d&&d!==s.issuer)throw new Error(`The value of the iss parameter (${d}) does not match the issuer identifier of the authorization server (${s.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(void 0===o)throw new Error(`The code verifier for session ${i} is missing from storage.`);if(void 0===a)throw new Error(`The redirect URL for session ${i} is missing from storage.`);const l=await this.clientRegistrar.getClient({sessionId:i},s),u=Date.now(),h=await dr(s,l,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:o,redirectUrl:a},c);let p;window.localStorage.removeItem(`oidc.${n}`),void 0!==h.refreshToken&&(p={sessionId:i,refreshToken:h.refreshToken,tokenRefresher:this.tokerRefresher});const g=mt(h.accessToken,{dpopKey:h.dpopKey,refreshOptions:p,eventEmitter:t,expiresIn:h.expiresIn});await async function(e,t,r,n,i,s,o,a){void 0!==s&&await e.setForUser(t,{refreshToken:s},{secure:o}),void 0!==r&&await e.setForUser(t,{webId:r},{secure:o}),void 0!==n&&await e.setForUser(t,{clientId:n},{secure:o}),void 0!==i&&await e.setForUser(t,{isLoggedIn:i},{secure:o}),void 0!==a&&await e.setForUser(t,{publicKey:JSON.stringify(a.publicKey),privateKey:JSON.stringify(await _e(a.privateKey))},{secure:o})}(this.storageUtility,i,h.webId,h.clientId,"true",void 0,!0);const f=await this.sessionInfoManager.get(i);if(!f)throw new Error(`Could not retrieve session: [${i}].`);return Object.assign(f,{fetch:g,getLogoutUrl:rt({idTokenHint:h.idToken,endSessionEndpoint:s.endSessionEndpoint}),expirationDate:"number"==typeof h.expiresIn?u+1e3*h.expiresIn:void 0})}}class kr extends qe{constructor(e){super(e)}}class Er{get storage(){return window.localStorage}async get(e){return this.storage.getItem(e)||void 0}async set(e,t){this.storage.setItem(e,t)}async delete(e){this.storage.removeItem(e)}}class Ir{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class Tr{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[r,n,i,s,o]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),a=void 0!==i?Number.parseInt(i,10):-1,c=void 0!==n&&0!==a&&Math.floor(Date.now()/1e3)>a;if(r&&("string"==typeof(d=o)&&["dynamic","static","solid-oidc"].includes(d))&&!c)return void 0!==n?{clientId:r,clientSecret:n,clientName:s,clientType:"dynamic",expiresAt:a}:{clientId:r,clientName:s,clientType:o};var d;try{const r=await or(e,t),n={clientId:r.clientId,clientType:"dynamic"};return void 0!==r.clientSecret&&(n.clientSecret=r.clientSecret,n.expiresAt=String(r.expiresAt)),r.idTokenSignedResponseAlg&&(n.idTokenSignedResponseAlg=r.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,n,{secure:!1}),r}catch(e){throw new Error("Client registration failed.",{cause:e})}}}class Ar{async canHandle(e){try{return new URL(e).searchParams.has("error")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(void 0!==t){const r=new URL(e),n=r.searchParams.get("error"),i=r.searchParams.get("error_description");t.emit(He,n,i)}return Ze()}}class Ur{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,r){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=r,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=r}async refresh(e,t,r,n){const i=await at(e,this.storageUtility,this.issuerConfigFetcher),s=await this.clientRegistrar.getClient({sessionId:e},i.issuerConfig);if(void 0===t)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(i.dpop&&void 0===r)throw new Error(`For session [${e}], the key bound to the DPoP access token must be provided to refresh said access token.`);const o=await lr(t,i.issuerConfig,s,r);return void 0!==o.refreshToken&&n?.emit(je,o.refreshToken),o}}function Pr(e){const t=new dt,r=e.secureStorage||t,n=e.insecureStorage||new Er,i=new ur(r,n),s=new mr(i),o=new Tr(i),a=new vr(i),c=new Ur(i,s,o),d=new Ir,l=new fr(i,new wr(i,d),s,o),u=new kr([new Ar,new br(i,a,s,o,c),new Sr]);return new hr(l,u,new Ye(a,d),a,s)}const xr=`${Oe}currentSession`,Cr=`${Oe}currentUrl`;class Rr{info;events;clientAuthentication;tokenRequestInProgress=!1;constructor(e={},t=void 0){this.events=new _t,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=Pr({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=Pr({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??$e(),isLoggedIn:!1},this.events.on(Ne,()=>window.localStorage.setItem(xr,this.info.sessionId)),this.events.on(Ke,()=>this.internalLogout(!1)),this.events.on(He,()=>this.internalLogout(!1))}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(xr),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(De)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t="string"==typeof e?{url:e}:e,r=t.url??window.location.href;this.tokenRequestInProgress=!0;const n=await this.clientAuthentication.handleIncomingRedirect(r,this.events);if(function(e){return!!e?.isLoggedIn}(n)){this.setSessionInfo(n);const e=window.localStorage.getItem(Cr);null===e?this.events.emit(Ne):(window.localStorage.removeItem(Cr),this.events.emit(Je,e))}else if(!0===t.restorePreviousSession){const e=window.localStorage.getItem(xr);if(null!==e){if(await async function(e,t,r){const n=await t.validateCurrentSession(e);return null!==n&&(window.localStorage.setItem(Cr,window.location.href),await t.login({sessionId:e,prompt:"none",oidcIssuer:n.issuer,redirectUrl:n.redirectUrl,clientId:n.clientAppId,clientSecret:n.clientAppSecret,tokenType:n.tokenType??"DPoP"},r.events),!0)}(e,this.clientAuthentication,this))return new Promise(()=>{})}}return this.tokenRequestInProgress=!1,n};setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.clientAppId=e.clientAppId,this.info.expirationDate=e.expirationDate,this.events.on(We,e=>{this.info.expirationDate=Date.now()+1e3*e})}}const $r=new Rr;var Or=n(264),Lr=n(386);const Hr=n.n(Lr)()(Or),Nr=(0,Or.sym)("http://www.iana.org/assignments/link-relations/acl");function Dr(e){const t=Hr;function r(e,r,n,i={}){const s=i.public||[],o=(0,Or.graph)(),a=(0,Or.Namespace)("http://www.w3.org/ns/auth/acl#");let c=o.sym(`${n}#a1`);const d=o.sym(n),l=o.sym(e);if(o.add(c,t.rdf("type"),a("Authorization"),d),o.add(c,a("accessTo"),l,d),i.defaultForNew&&o.add(c,a("default"),l,d),o.add(c,a("agent"),r,d),o.add(c,a("mode"),a("Read"),d),o.add(c,a("mode"),a("Write"),d),o.add(c,a("mode"),a("Control"),d),s.length){c=o.sym(`${n}#a2`),o.add(c,t.rdf("type"),a("Authorization"),d),o.add(c,a("accessTo"),l,d),o.add(c,a("agentClass"),t.foaf("Agent"),d);for(let e=0;e<s.length;e++)o.add(c,a("mode"),a(s[e]),d)}return(0,Or.serialize)(d,o,n)}return{findAclDocUrl:async function(t){await e.fetcher.load(t);const r=e.any(t,Nr);if(!r)throw new Error(`No ACL link discovered for ${t}`);return r.value},setACLUserPublic:function(t,n,i){const s=e.any(e.sym(t),Nr);return Promise.resolve().then(()=>s||function(t){const r=e.fetcher;if(!r)throw new Error("Cannot fetch ACL rel, store has no fetcher");return r.load(t).then(r=>{if(!r.ok)throw new Error("fetchACLRel: While loading:"+r.error);const n=e.any(e.sym(t),Nr);if(!n)throw new Error("fetchACLRel: No Link rel=ACL header for "+t);return n})}(t).catch(e=>{throw new Error(`Error fetching rel=ACL header for ${t}: ${e}`)})).then(s=>{const o=r(t,n,s.uri,i);if(!e.fetcher)throw new Error("Cannot PUT this, store has no fetcher");return e.fetcher.webOperation("PUT",s.uri,{data:o,contentType:"text/turtle"}).then(e=>{if(!e.ok)throw new Error("Error writing ACL text: "+e.error);return s})})},genACLText:r}}const jr=()=>{let{SolidAppContext:e}=window;if(e||(e={}),e.viewingNoAuthPage=!1,e.noAuth&&window.document){if(window.document.location.href.startsWith(e.noAuth)){e.viewingNoAuthPage=!0;const t=new URLSearchParams(window.document.location.search);if(t){let r=e.viewedPage=t.get("uri")||null;if(r&&(r=decodeURI(r),!r.startsWith(e.noAuth))){const t=r.split(/\//);e.idp=t[0]+"//"+t[2],e.viewingNoAuthPage=!1}}}}return e};function Kr(){const{$SolidTestEnvironment:t}=window;if(void 0!==t&&t.username)return e("Assuming the user is "+t.username),(0,Or.sym)(t.username);if("undefined"!=typeof document&&document.location&&"http://localhost"===(""+document.location).slice(0,16)){const t=document.getElementById("appTarget");if(!t)return null;const r=t.getAttribute("testID");return r?(e("Assuming user is "+r),(0,Or.sym)(r)):null}return null}class Wr{constructor(e){this.session=e}get authSession(){return this.session}currentUser(){const e=jr();return e.viewingNoAuthPage?(0,Or.sym)(e.webId):this&&this.session&&this.session.info&&this.session.info.webId&&this.session.info.isLoggedIn?(0,Or.sym)(this.session.info.webId):Kr()}async checkUser(t){const r=new URL(window.location.href).hash;r&&window.localStorage.setItem("preLoginRedirectHash",r),this.session.events.on(Je,t=>{e(`Session restored to ${t}`),document.location.toString()!==t&&history.replaceState(null,"",t)});const n=new URL(window.location.href);n.hash="",await this.session.handleIncomingRedirect({restorePreviousSession:!0,url:n.href});const i=window.localStorage.getItem("preLoginRedirectHash");if(i){const e=new URL(window.location.href);e.hash!==i&&(history.pushState?history.pushState(null,document.title,i):location.hash=i,e.hash=i),window.localStorage.setItem("preLoginRedirectHash","")}let s=Kr();if(s)return Promise.resolve(t?t(s):s);const o=this.webIdFromSession(this.session.info);return o&&(s=this.saveUser(o)),s&&e(`(Logged in as ${s} by authentication)`),Promise.resolve(t?t(s):s)}saveUser(e,t){let r;if(e){r="string"==typeof e?e:e.uri;const n=(0,Or.namedNode)(r);return t&&(t.me=n),n}return null}webIdFromSession(e){return(null==e?void 0:e.webId)&&e.isLoggedIn?e.webId:null}}function Jr(e){return(0,Or.sym)(e.uri+"#id"+Date.now())}function Mr(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const Fr="index.ttl#this";function qr(e,t){const r=Hr;async function n(t,r,n){await e.fetcher.load(t);const i=e.any(t,new Or.NamedNode("http://www.iana.org/assignments/link-relations/acl"));if(!i)throw new Error("Chat ACL doc not found!");const s=`\n @prefix acl: <http://www.w3.org/ns/auth/acl#>.\n <#owner>\n a acl:Authorization;\n acl:agent <${r.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Write, acl:Control.\n <#invitee>\n a acl:Authorization;\n acl:agent <${n.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Append.\n `;await e.fetcher.webOperation("PUT",i.value,{data:s,contentType:"text/turtle"})}async function i(t,n){const i=e.any(n,r.solid("privateTypeIndex"));if(!i)throw new Error("Private type index not found!");await e.fetcher.load(i);const s=Jr(i),o=[(0,Or.st)(s,r.rdf("type"),r.solid("TypeRegistration"),i.doc()),(0,Or.st)(s,r.solid("forClass"),r.meeting("LongChat"),i.doc()),(0,Or.st)(s,r.solid("instance"),t,i.doc())];await new Promise((t,r)=>{e.updater.update([],o,function(e,n,i){n?t(null):r(new Error(i))})})}async function s(r){const n=await t.loadMe(),i=function(e,t){const r=new URL(`IndividualChats/${new URL(e.value).host}/`,t.value).toString();return new Or.NamedNode(r)}(r,await t.getPodRoot(n));let s=!0;try{await e.fetcher.load(new Or.NamedNode(i.value+"index.ttl#this"))}catch(e){s=!1}return{me:n,chatContainer:i,exists:s}}async function o(e,t){return(await a({me:t,newBase:e.value})).newInstance}function a(t){const n=e,i=n.updater;if(t.me&&!t.me.uri)throw new Error("chat mintNew: Invalid userid "+t.me);const s=t.newInstance=t.newInstance||n.sym(t.newBase+Fr),o=s.doc();return n.add(s,r.rdf("type"),r.meeting("LongChat"),o),n.add(s,r.dc("title"),"Chat channel",o),n.add(s,r.dc("created"),(0,Or.term)(new Date(Date.now())),o),t.me&&n.add(s,r.dc("author"),t.me,o),new Promise(function(e,r){null==i||i.put(o,n.statementsMatching(void 0,void 0,void 0,o),"text/turtle",function(n,i,o){i?e({...t,newInstance:s}):r(new Error("FAILED to save new chat channel at: "+n+" : "+o))})})}async function c(t,n){var i;await e.fetcher.load(t.doc());const s=e.any(t,r.ldp("inbox"),void 0,t.doc());if(!s)throw new Error(`Invitee inbox not found! ${t.value}`);const o=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${r.rdf("seeAlso")} <${n.value}> .\n `,a=await(null===(i=e.fetcher)||void 0===i?void 0:i.webOperation("POST",s.value,{data:o,contentType:"text/turtle"}));if(!(null==a?void 0:a.headers.get("location")))throw new Error(`Invite sending returned a ${null==a?void 0:a.status}`)}return{setAcl:n,addToPrivateTypeIndex:i,findChat:s,createChatThing:o,getChat:async function(e,t=!0){const{me:r,chatContainer:a,exists:d}=await s(e);if(d)return new Or.NamedNode(a.value+Fr);if(t){const t=await o(a,r);return await c(e,t),await n(a,r,e),await i(t,r),t}return null},sendInvite:c,mintNew:a}}function zr(e,t,r,n,i){return{createInboxFor:async function(e,i){const s=await t.loadMe(),o=`${(await t.getPodRoot(s)).value}p2p-inboxes/${encodeURIComponent(i)}/`;return await n.createContainer(o),await r.setSinglePeerAccess({ownerWebId:s.value,peerWebId:e,accessToModes:"acl:Append",target:o}),o},getNewMessages:async function(e){e||(e=await t.loadMe());const r=await t.getMainInbox(e);return(await n.getContainerMembers(r)).filter(e=>!n.isContainer(e))},markAsRead:async function(t,r){const n=await e.fetcher._fetch(t);if(200!==n.status)throw new Error(`Not OK! ${t}`);const i=function(e,t){const r=t.getUTCFullYear(),n=("0"+(t.getUTCMonth()+1)).slice(-2),i=("0"+t.getUTCDate()).slice(-2),s=e.split("/"),o=s[s.length-1];return new URL(`./archive/${r}/${n}/${i}/${o}`,e).toString()}(t,r),s={method:"PUT",body:await n.text(),headers:[["Content-Type",n.headers.get("Content-Type")||"application/octet-stream"]]};"2"===(await e.fetcher._fetch(i,s)).status.toString()[0]&&await e.fetcher._fetch(t,{method:"DELETE"})}}}class Vr extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class Br extends Vr{}class Gr extends Vr{}class Qr extends Vr{}class Xr extends Vr{}class Yr extends Vr{}class Zr extends Vr{}class en extends Vr{constructor(e,t){super(t),this.status=e}}function tn(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:ListedDocument."].join("\n")}function rn(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:UnlistedDocument."].join("\n")}function nn(e,t){const r=new URL(t).pathname.split("/").pop()||"publicTypeIndex.ttl";return["# ACL resource for the Public Type Index","","@prefix acl: <http://www.w3.org/ns/auth/acl#>.","@prefix foaf: <http://xmlns.com/foaf/0.1/>.","","<#owner>"," a acl:Authorization;",""," acl:agent",` <${e}>;`,"",` acl:accessTo <./${r}>;`,""," acl:mode"," acl:Read, acl:Write, acl:Control.","","# Public-readable","<#public>"," a acl:Authorization;",""," acl:agentClass foaf:Agent;","",` acl:accessTo <./${r}>;`,""," acl:mode acl:Read."].join("\n")}function sn(e){function t(t){return e.statementsMatching(t,(0,Or.sym)("http://www.w3.org/ns/ldp#contains"),void 0).map(e=>e.object)}function r(e){const t=e.value;return"/"===t.charAt(t.length-1)}return{isContainer:r,createContainer:async function(t){if(!r((0,Or.sym)(t)))throw new Error(`Not a container URL ${t}`);const n=await e.fetcher._fetch(t,{method:"PUT",headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:'<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'},body:" "});if(409!==n.status&&"2"!==n.status.toString()[0])throw new Error(`Not OK: got ${n.status} response while creating container at ${t}`)},getContainerElements:t,getContainerMembers:async function(r){return await e.fetcher.load(r),t(r)}}}function on(e,r,n){const i=Hr,s=sn(e),o=new Map,a=new Map;function c(e){return!!e&&(e.startsWith("https://")||e.startsWith("http://"))}function d(e){const t=e.doc(),r=t.dir();if((null==r?void 0:r.uri)&&c(r.uri))return r.uri;const n=t.uri;if(!n||!c(n))return null;const i=n.split("#")[0],s=i.lastIndexOf("/");return-1===s?null:i.slice(0,s+1)}function l(e,t){const r=d(e);if(!r)throw new Error(`Cannot derive directory for preferences file ${e.uri}`);return(0,Or.sym)(r+t)}function u(e){var t;if(404===(null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.status))return!0;const r=`${(null==e?void 0:e.message)||e||""}`;return r.includes("404")||r.includes("Not Found")}async function h(t,r){var n;const i=d(r);if(!i)throw new Error(`Cannot derive settings directory from ${r.uri}`);await async function(t){const r=(0,Or.sym)(t);try{return void await e.fetcher.load(r)}catch(e){if(!u(e))throw e}await s.createContainer(t)}(i);const o=(0,Or.sym)(i);let a;try{await e.fetcher.load(o),a=null===(n=e.any(o,Nr))||void 0===n?void 0:n.value}catch(e){if(!u(e))throw e}a||(a=`${i}.acl`);const c=(0,Or.sym)(a);try{return void await e.fetcher.load(c)}catch(e){if(!u(e))throw e}var l;await e.fetcher.webOperation("PUT",c.uri,{data:(l=t.uri,["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#owner>","a acl:Authorization;",`acl:agent <${l}>;`,"acl:accessTo <./>;","acl:default <./>;","acl:mode acl:Read, acl:Write, acl:Control."].join("\n")),contentType:"text/turtle"})}async function p(t,r){const s=r.doc(),o=t.doc();await e.fetcher.load(s);const a=e.any(t,i.solid("publicTypeIndex"),null,o),c=e.any(t,i.solid("publicTypeIndex"),null,s),d=a||c||l(r,"publicTypeIndex.ttl"),h=e.any(t,i.solid("privateTypeIndex"),null,s)||l(r,"privateTypeIndex.ttl"),p=!a;p&&await n.followOrCreateLinkWithContentOnCreate(t,i.solid("publicTypeIndex"),d,o,tn());const g=[];e.holds(s,i.rdf("type"),i.space("ConfigurationFile"),s)||g.push((0,Or.st)(s,i.rdf("type"),i.space("ConfigurationFile"),s)),e.holds(s,i.dct("title"),void 0,s)||g.push((0,Or.st)(s,i.dct("title"),(0,Or.literal)("Preferences file"),s)),e.holds(t,i.solid("publicTypeIndex"),d,s)||g.push((0,Or.st)(t,i.solid("publicTypeIndex"),d,s)),e.holds(t,i.solid("privateTypeIndex"),h,s)||g.push((0,Or.st)(t,i.solid("privateTypeIndex"),h,s)),g.length>0&&(await e.updater.update([],g),await e.fetcher.load(s)),await async function(t,r,i=!1){var s,o,a;if(!await n.loadOrCreateWithContentOnCreate(r,tn())&&!i)return;let c;try{await e.fetcher.load(r),c=null===(s=e.any(r,Nr))||void 0===s?void 0:s.value}catch(e){if(!u(e))throw e}c||(c=`${r.uri}.acl`);const d=(0,Or.sym)(c);try{await e.fetcher.webOperation("PUT",d.uri,{data:nn(t.uri,r.uri),contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(e){if(412!==(null!==(a=null===(o=null==e?void 0:e.response)||void 0===o?void 0:o.status)&&void 0!==a?a:null==e?void 0:e.status))throw e}}(t,d,p),await async function(e){await n.loadOrCreateWithContentOnCreate(e,rn())}(h)}async function g(e){var t,r;try{return!!await n.loadOrCreateWithContentOnCreate(e,["@prefix dct: <http://purl.org/dc/terms/>.","@prefix pim: <http://www.w3.org/ns/pim/space#>.","@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a pim:ConfigurationFile ;",' dct:title "Preferences file".'].join("\n"))}catch(n){if(401===(null===(t=n.response)||void 0===t?void 0:t.status))throw new Br;if(403===(null===(r=n.response)||void 0===r?void 0:r.status)){if(Mr(e))throw new Gr;throw new Qr}throw n}}async function f(r){const s=a.get(r.uri);if(s)return s;const c=o.get(r.uri);if(c)return c;const d=(async()=>{var s;await w(r);const o=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/settings/prefs.ttl";return(0,Or.sym)(t)}(r);let c;try{const t=e.any(r,i.space("preferencesFile"),null,r.doc());c=t||await n.followOrCreateLink(r,i.space("preferencesFile"),o,r.doc()),await h(r,c),await g(c),await p(r,c)}catch(e){if(t(`User ${r} has no pointer in profile to preferences file.`),e instanceof Yr)throw e;if(e instanceof Zr)throw e;if(e instanceof Br)throw e;if(e instanceof Gr)throw e;if(e instanceof Qr)throw e;if(e instanceof en)throw e;throw e}try{await e.fetcher.load(c)}catch(n){const i=`Unable to load preference of user ${r}: ${n}`;if(404===(null===(s=n.response)||void 0===s?void 0:s.status))return await h(r,c),await g(c),await p(r,c),await e.fetcher.load(c),c;if(t(i),401===n.response.status)throw new Br;if(403===n.response.status){if(Mr(c))throw new Gr;throw new Qr}throw new Error(i)}return a.set(r.uri,c),c})();o.set(r.uri,d);try{return await d}finally{o.get(r.uri)===d&&o.delete(r.uri)}}async function w(t){if(!t)throw new Error("loadProfile: no user given.");try{await e.fetcher.load(t.doc())}catch(e){throw new Error(`Unable to load profile of user ${t}: ${e}`)}return t.doc()}function y(t){return e.any(t,i.space("storage"),void 0,t.doc())}return{loadMe:async function(){const t=r.currentUser();if(null===t)throw new Error("Current user not found! Not logged in?");return await e.fetcher.load(t.doc()),t},getPodRoot:function(e){const t=y(e);if(!t)throw new Error("User pod root not found!");return t},getMainInbox:async function(t){await e.fetcher.load(t);const r=e.any(t,i.ldp("inbox"),void 0,t.doc());if(!r)throw new Error("User main inbox not found!");return r},findStorage:y,loadPreferences:f,loadProfile:w,silencedLoadPreferences:async function(e){try{return await f(e)}catch(e){return}}}}function an(r,n,i,s){const o=Hr;function a(e){return!!e&&(e.startsWith("https://")||e.startsWith("http://"))}async function c(e){if(!e)throw new Error("loadTypeIndexesFor: No user given");const n=await i.loadProfile(e);let a,c=null;try{c=p(e)}catch(r){t(`User ${e} has no usable profile document directory for publicTypeIndex.`)}try{const t=r.any(e,o.solid("publicTypeIndex"),void 0,n);a=t||(c?await s.followOrCreateLinkWithContentOnCreate(e,o.solid("publicTypeIndex"),c,n,tn()):null)}catch(r){t(`User ${e} has no pointer in profile to publicTypeIndex file: ${r}`)}const d=a?[{label:"public",index:a,agent:e}]:[];let l,u;try{l=await i.silencedLoadPreferences(e)}catch(e){l=null}if(l){let i,a=null;try{a=g(l)}catch(r){t(`User ${e} has no usable preferences document directory for privateTypeIndex.`)}try{const t=r.any(e,o.solid("privateTypeIndex"),void 0,n);i=t||(a?await s.followOrCreateLinkWithContentOnCreate(e,o.solid("privateTypeIndex"),a,l,rn()):null)}catch(r){t(`User ${e} has no pointer in preference file to privateTypeIndex file: ${r}`)}u=i?[{label:"private",index:i,agent:e}]:[]}else u=[];const h=d.concat(u);if(0===h.length)return h;const f=h.map(e=>e.index);try{await r.fetcher.load(f)}catch(e){t("Problems loading type index: ",e)}return h}async function d(e){let n;try{n=await i.silencedLoadPreferences(e)}catch(r){t(`User ${e} has no pointer in profile to preferences file.`)}if(n){const i=r.each(e,o.solid("community"),void 0,n).concat(r.each(e,o.solid("community"),void 0,e.doc()));let s=[];for(const r of i)if("NamedNode"===r.termType&&a(r.uri))try{s=s.concat(await c(r))}catch(e){t(`Skipping community type indexes for ${r.uri}: ${e}`)}else t(`Skipping malformed community node for ${e}: ${r}`);return s}return[]}async function l(e){return(await c(e)).concat(await d(e))}async function u(e,t){const r=await l(t);let n=[];for(const t of r){const r=await f(t,e);n=n.concat(r)}return n}function h(t){const r=t.doc(),n=r.dir();if((null==n?void 0:n.uri)&&a(n.uri))return n.uri;const i=r.uri;if(!i||!a(i))return e(`docDirUri: missing or non-http(s) doc uri for ${null==t?void 0:t.uri}`),null;const s=i.split("#")[0],o=s.lastIndexOf("/");return-1===o?(e(`docDirUri: no slash in doc uri ${i}`),null):s.slice(0,o+1)}function p(e){const t=h(e);if(!t)throw new Error(`suggestPublicTypeIndex: Cannot derive directory for ${e.uri}`);return(0,Or.sym)(t+"publicTypeIndex.ttl")}function g(e){const t=h(e);if(!t)throw new Error(`suggestPrivateTypeIndex: Cannot derive directory for ${e.uri}`);return(0,Or.sym)(t+"privateTypeIndex.ttl")}async function f(e,t){const n=e.index,i=[],s=r.statementsMatching(null,o.solid("instance"),null,n).concat(r.statementsMatching(null,o.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const a of s){const s=r.any(a,o.solid("forClass"),null,n);if(!t||s.sameTerm(t)){const t=r.each(a,o.solid("instance"),null,n);for(const r of t)i.push({instance:r,type:s,scope:e});const c=r.each(a,o.solid("instanceContainer"),null,n);for(const t of c)await r.fetcher.load(t),i.push({instance:(0,Or.sym)(t.value),type:s,scope:e})}}return i}return{registerInTypeIndex:async function(e,t,n){const i=Jr(t),s=[(0,Or.st)(i,o.rdf("type"),o.solid("TypeRegistration"),t),(0,Or.st)(i,o.solid("forClass"),n,t),(0,Or.st)(i,o.solid("instance"),e,t)];try{await r.updater.update([],s)}catch(r){const n=`Unable to register ${e} in index ${t}: ${r}`;return console.warn(n),null}return i},getRegistrations:function(e,t){return r.each(void 0,o.solid("instance"),e).filter(e=>r.holds(e,o.solid("forClass"),t))},loadTypeIndexesFor:c,loadCommunityTypeIndexes:d,loadAllTypeIndexes:l,getScopedAppInstances:u,getAppInstances:async function(e){const t=n.currentUser();if(!t)throw new Error("getAppInstances: Must be logged in to find apps.");return(await u(e,t)).map(e=>e.instance)},suggestPublicTypeIndex:p,suggestPrivateTypeIndex:g,deleteTypeIndexRegistration:async function(e){const t=r.the(null,o.solid("instance"),e.instance,e.scope.index);if(!t)throw new Error(`deleteTypeIndexRegistration: No registration found for ${e.instance}`);const n=r.statementsMatching(t,null,null,e.scope.index);await r.updater.update(n,[])},getScopedAppsFromIndex:f}}function cn(r,n){e("SolidLogic: Unique instance created. There should only be one of these.");const i=Or.graph();Or.fetcher(i,{fetch:r.fetch}),i.updater=new Or.UpdateManager(i),i.features=[];const s=new Wr(n),o=Dr(i),a=sn(i),c=function(r,n,i){async function s(e){var t,n,i,s,o;try{return await r.fetcher.load(e)}catch(a){if(404===(null===(t=null==a?void 0:a.response)||void 0===t?void 0:t.status)){try{await r.fetcher.webOperation("PUT",e.uri,{data:"",contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(t){if(412!==(null!==(i=null===(n=null==t?void 0:t.response)||void 0===n?void 0:n.status)&&void 0!==i?i:null==t?void 0:t.status))throw new Zr(`createIfNotExists: PUT FAILED: ${e}: ${t}`)}return await r.fetcher.load(e)}if(401===(null===(s=null==a?void 0:a.response)||void 0===s?void 0:s.status))throw new Br;if(403===(null===(o=null==a?void 0:a.response)||void 0===o?void 0:o.status)){if(Mr(e))throw new Gr;throw new Qr}const c=`createIfNotExists doc load error: ${e}: ${a}`;throw new en(null==a?void 0:a.status,`${(null==a?void 0:a.message)||""}${c}`)}}async function o(e,t){var n,i,s,o;try{return await r.fetcher.load(e),!1}catch(e){if(404!==(null!==(i=null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status)&&void 0!==i?i:null==e?void 0:e.status))throw e}try{return await r.fetcher.webOperation("PUT",e.uri,{data:t,contentType:"text/turtle",headers:{"If-None-Match":"*"}}),!0}catch(e){if(412===(null!==(o=null===(s=null==e?void 0:e.response)||void 0===s?void 0:s.status)&&void 0!==o?o:null==e?void 0:e.status))return!1;throw e}}return{recursiveDelete:async function t(s){try{if(i.isContainer(s)){const e=await n.findAclDocUrl(s);await r.fetcher._fetch(e,{method:"DELETE"});const o=await i.getContainerMembers(s);await Promise.all(o.map(e=>t(e)))}return r.fetcher._fetch(s.value,{method:"DELETE"})}catch(t){e(`Please manually remove ${s.value} from your system.`,t)}},setSinglePeerAccess:async function(e){let t=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#alice> a acl:Authorization;\n acl:agent <"+e.ownerWebId+">;",` acl:accessTo <${e.target}>;`,` acl:default <${e.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");e.accessToModes&&(t+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${e.peerWebId}>;`,` acl:accessTo <${e.target}>;`,` acl:mode ${e.accessToModes}.`,""].join("\n")),e.defaultModes&&(t+=["<#bobDefault> a acl:Authorization;",` acl:agent <${e.peerWebId}>;`,` acl:default <${e.target}>;`,` acl:mode ${e.defaultModes}.`,""].join("\n"));const i=await n.findAclDocUrl((0,Or.sym)(e.target));return r.fetcher._fetch(i,{method:"PUT",body:t,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(e,t){await r.fetcher.webOperation("PUT",e.uri,{data:`# ${new Date} ${t}\n`,contentType:"text/turtle"})},followOrCreateLink:async function(e,n,i,o){await r.fetcher.load(o);const a=r.any(e,n,null,o);if(a)return a;if(!r.updater.editable(o)){const e=`followOrCreateLink: cannot edit ${o.value}`;throw t(e),new Yr(e)}try{await r.updater.update([],[(0,Or.st)(e,n,i,o)])}catch(e){throw t(`followOrCreateLink: Error making link in ${o} to ${i}: ${e}`),new Zr(e)}try{await s(i)}catch(e){throw t(`followOrCreateLink: Error loading or saving new linked document: ${i}: ${e}`),e}return i},followOrCreateLinkWithContentOnCreate:async function(e,n,i,s,a){await r.fetcher.load(s);const c=r.any(e,n,null,s);if(c)return c;if(!r.updater.editable(s)){const e=`followOrCreateLinkWithContentOnCreate: cannot edit ${s.value}`;throw t(e),new Yr(e)}try{await r.updater.update([],[(0,Or.st)(e,n,i,s)])}catch(e){const r=`followOrCreateLinkWithContentOnCreate: Error making link in ${s} to ${i}: ${e}`;throw t(r),new Zr(r)}try{await o(i,a)}catch(e){throw t(`followOrCreateLinkWithContentOnCreate: Error loading or saving new linked document: ${i}: ${e}`),e}return i},loadOrCreateIfNotExists:s,loadOrCreateWithContentOnCreate:o}}(i,o,a),d=on(i,s,c),l=qr(i,d),u=zr(i,d,c,a),h=an(i,s,d,c);return e("SolidAuthnLogic initialized"),{store:i,authn:s,acl:o,inbox:u,chat:l,profile:d,typeIndex:h,load:function(e){return i.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((r,n)=>{i.updater.update(e,t,function(e,t,i){t?r():n(new Error(i))})})},clearStore:function(){i.statements.slice().forEach(i.remove.bind(i))}}}const dn=async(e,t)=>{const r=t&&t.credentials&&"omit"==t.credentials;return $r.info.webId&&!r?$r.fetch(e,t):window.fetch(e,t)},ln=Symbol.for("solid-logic-singleton"),un="undefined"!=typeof window?window:n.g;const hn=(un[ln]?e("SolidLogic: Using existing global singleton instance."):(e("SolidLogic: Creating new global singleton instance."),un[ln]=cn({fetch:dn},$r),e("Unique quadstore initialized.")),un[ln]),pn=[{name:"Solid Community",uri:"https://solidcommunity.net"},{name:"Solid Web",uri:"https://solidweb.org"},{name:"Solid Web ME",uri:"https://solidweb.me"},{name:"Inrupt.com",uri:"https://login.inrupt.com"}];function gn(){const e=[...pn],{host:t,origin:r}=new URL(location.href),n=e.map(({uri:e})=>new URL(e).host);return n.includes(t)||n.some(e=>function(e,t){const r=e.length-t.length-1;return r>0&&"."===e[r]&&e.endsWith(t)}(t,e))||e.unshift({name:t,uri:r}),e}const fn=hn.authn,wn=hn.authn.authSession,yn=hn.store})(),i})());
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("$rdf")):"function"==typeof define&&define.amd?define("SolidLogic",["$rdf"],t):"object"==typeof exports?exports.SolidLogic=t(require("$rdf")):e.SolidLogic=t(e.$rdf)}(this,e=>(()=>{var t={386(e){const t={acl:"http://www.w3.org/ns/auth/acl#",arg:"http://www.w3.org/ns/pim/arg#",as:"https://www.w3.org/ns/activitystreams#",bookmark:"http://www.w3.org/2002/01/bookmark#",cal:"http://www.w3.org/2002/12/cal/ical#",cco:"http://www.ontologyrepository.com/CommonCoreOntologies/",cert:"http://www.w3.org/ns/auth/cert#",contact:"http://www.w3.org/2000/10/swap/pim/contact#",dc:"http://purl.org/dc/elements/1.1/",dct:"http://purl.org/dc/terms/",doap:"http://usefulinc.com/ns/doap#",foaf:"http://xmlns.com/foaf/0.1/",geo:"http://www.w3.org/2003/01/geo/wgs84_pos#",gpx:"http://www.w3.org/ns/pim/gpx#",gr:"http://purl.org/goodrelations/v1#",http:"http://www.w3.org/2007/ont/http#",httph:"http://www.w3.org/2007/ont/httph#",icalTZ:"http://www.w3.org/2002/12/cal/icaltzd#",ldp:"http://www.w3.org/ns/ldp#",link:"http://www.w3.org/2007/ont/link#",log:"http://www.w3.org/2000/10/swap/log#",meeting:"http://www.w3.org/ns/pim/meeting#",mo:"http://purl.org/ontology/mo/",org:"http://www.w3.org/ns/org#",owl:"http://www.w3.org/2002/07/owl#",pad:"http://www.w3.org/ns/pim/pad#",patch:"http://www.w3.org/ns/pim/patch#",prov:"http://www.w3.org/ns/prov#",pto:"http://www.productontology.org/id/",qu:"http://www.w3.org/2000/10/swap/pim/qif#",trip:"http://www.w3.org/ns/pim/trip#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",rss:"http://purl.org/rss/1.0/",sched:"http://www.w3.org/ns/pim/schedule#",schema:"http://schema.org/",sioc:"http://rdfs.org/sioc/ns#",skos:"http://www.w3.org/2004/02/skos/core#",solid:"http://www.w3.org/ns/solid/terms#",space:"http://www.w3.org/ns/pim/space#",stat:"http://www.w3.org/ns/posix/stat#",tab:"http://www.w3.org/2007/ont/link#",tabont:"http://www.w3.org/2007/ont/link#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",wf:"http://www.w3.org/2005/01/wf/flow#",xsd:"http://www.w3.org/2001/XMLSchema#"};e.exports=function(e={namedNode:e=>e}){const r={};for(const n in t){const o=t[n];r[n]=function(t=""){return e.namedNode(o+t)}}return r}},552(e,t,r){"use strict";e.exports=r.p+"2729812e0bfc062ee77a.js"},264(t){"use strict";t.exports=e}},r={};function n(e){var o=r[e];if(void 0!==o)return o.exports;var i=r[e]={exports:{}};return t[e](i,i.exports,n),i.exports}n.m=t,n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.p="",n.b="undefined"!=typeof document&&document.baseURI||self.location.href;var o={};return(()=>{"use strict";n.r(o),n.d(o,{ACL_LINK:()=>Jr,CrossOriginForbiddenError:()=>Zr,FetchError:()=>nn,NotEditableError:()=>tn,NotFoundError:()=>en,SameOriginForbiddenError:()=>Qr,UnauthorizedError:()=>Yr,WebOperationError:()=>rn,appContext:()=>Kr,authSession:()=>bn,authn:()=>vn,createTypeIndexLogic:()=>ln,getSuggestedIssuers:()=>gn,offlineTestID:()=>Mr,performServerSideLogout:()=>yn,solidLogicSingleton:()=>fn,store:()=>En});var e={};function t(...e){console.log(...e)}function r(...e){console.warn(...e)}n.r(e),n.d(e,{SessionCore:()=>Ar,SessionEvents:()=>kr});var i=crypto;const a=e=>e instanceof CryptoKey;var s=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await i.subtle.digest(r,t))};const c=new TextEncoder,d=new TextDecoder;function l(...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 h=e=>(e=>{let t=e;"string"==typeof t&&(t=c.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,"_"),u=e=>{let t=e;t instanceof Uint8Array&&(t=d.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 p extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}p.code="ERR_JOSE_GENERIC";class w extends p{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}}w.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class f extends p{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}}f.code="ERR_JWT_EXPIRED";class y extends p{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}y.code="ERR_JOSE_ALG_NOT_ALLOWED";class m extends p{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}m.code="ERR_JOSE_NOT_SUPPORTED";(class extends p{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends p{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class g extends p{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}g.code="ERR_JWS_INVALID";class v extends p{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}v.code="ERR_JWT_INVALID";class b extends p{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}b.code="ERR_JWK_INVALID";class E extends p{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}E.code="ERR_JWKS_INVALID";class S extends p{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}S.code="ERR_JWKS_NO_MATCHING_KEY";class _ extends p{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}_.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class k extends p{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}k.code="ERR_JWKS_TIMEOUT";class A extends p{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function T(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function I(e,t){return e.name===t}function P(e){return parseInt(e.name.slice(4),10)}function R(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!I(e.algorithm,"HMAC"))throw T("HMAC");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw T(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!I(e.algorithm,"RSASSA-PKCS1-v1_5"))throw T("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw T(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!I(e.algorithm,"RSA-PSS"))throw T("RSA-PSS");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw T(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw T("Ed25519 or Ed448");break;case"Ed25519":if(!I(e.algorithm,"Ed25519"))throw T("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!I(e.algorithm,"ECDSA"))throw T("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 T(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 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function C(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}A.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var x=(e,...t)=>C("Key must be ",e,...t);function D(e,t,...r){return C(`Key for the ${e} algorithm must be `,t,...r)}var W=e=>!!a(e)||"KeyObject"===e?.[Symbol.toStringTag];const O=["CryptoKey"];var H=(...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 $(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 N=(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 U(e){return $(e)&&"string"==typeof e.kty}var j=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 m('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 m('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 m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new m('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,i.subtle.importKey("jwk",o,...n)};const J=e=>u(e);let L,K;const M=e=>"KeyObject"===e?.[Symbol.toStringTag],F=async(e,t,r,n,o=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const a=await j({...r,alg:n});return o&&Object.freeze(t),i?i[n]=a:e.set(t,{[n]:a}),a};var V=(e,t)=>{if(M(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?J(r.k):(K||(K=new WeakMap),F(K,e,r,t))}if(U(e)){if(e.k)return u(e.k);K||(K=new WeakMap);return F(K,e,e,t,!0)}return e},B=(e,t)=>{if(M(e)){let r=e.export({format:"jwk"});return r.k?J(r.k):(L||(L=new WeakMap),F(L,e,r,t))}if(U(e)){if(e.k)return u(e.k);L||(L=new WeakMap);return F(L,e,e,t,!0)}return e};async function G(e,t){if(!$(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 u(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new m('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return j({...e,alg:t});default:throw new m('Unsupported "kty" (Key Type) Parameter value')}}const q=e=>e?.[Symbol.toStringTag],z=(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},X=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&U(t)){if(function(e){return U(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&z(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(!W(t))throw new TypeError(D(e,t,...O,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${q(t)} instances for symmetric algorithms must be of type "secret"`)}};function Y(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?X(t,r,n,e):((e,t,r,n)=>{if(n&&U(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&z(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)&&z(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!W(t))throw new TypeError(D(e,t,...O,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${q(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}Y.bind(void 0,!1);const Z=Y.bind(void 0,!0);function Q(e,t,r,n,o){if(void 0!==o.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 m(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[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)}var ee=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};var te=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:h(e)};if(!a(e))throw new TypeError(x(e,...O,"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:o,...s}=await i.subtle.exportKey("jwk",e);return s};async function re(e){return te(e)}function ne(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 m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function oe(e,t,r){if("sign"===r&&(t=await B(t,e)),"verify"===r&&(t=await V(t,e)),a(t))return R(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(x(t,...O));return i.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(x(t,...O,"Uint8Array","JSON Web Key"))}var ie=async(e,t,r,n)=>{const o=await oe(e,t,"verify");N(e,o);const a=ne(e,o.algorithm);try{return await i.subtle.verify(a,o,r,n)}catch{return!1}};async function ae(e,t,r){if(e instanceof Uint8Array&&(e=d.decode(e)),"string"!=typeof e)throw new g("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:i,length:a}=e.split(".");if(3!==a)throw new g("Invalid Compact JWS");const s=await async function(e,t,r){if(!$(e))throw new g("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new g('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new g("JWS Protected Header incorrect type");if(void 0===e.payload)throw new g("JWS Payload missing");if("string"!=typeof e.signature)throw new g("JWS Signature missing or incorrect type");if(void 0!==e.header&&!$(e.header))throw new g("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=u(e.protected);n=JSON.parse(d.decode(t))}catch{throw new g("JWS Protected Header is invalid")}if(!H(n,e.header))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header};let i=!0;if(Q(g,new Map([["b64",!0]]),r?.crit,n,o).has("b64")&&(i=n.b64,"boolean"!=typeof i))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if("string"!=typeof a||!a)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');const s=r&&ee("algorithms",r.algorithms);if(s&&!s.has(a))throw new y('"alg" (Algorithm) Header Parameter value not allowed');if(i){if("string"!=typeof e.payload)throw new g("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new g("JWS Payload must be a string or an Uint8Array instance");let h=!1;"function"==typeof t?(t=await t(n,e),h=!0,Z(a,t,"verify"),U(t)&&(t=await G(t,a))):Z(a,t,"verify");const p=l(c.encode(e.protected??""),c.encode("."),"string"==typeof e.payload?c.encode(e.payload):e.payload);let w,f;try{w=u(e.signature)}catch{throw new g("Failed to base64url decode the signature")}if(!await ie(a,t,w,p))throw new A;if(i)try{f=u(e.payload)}catch{throw new g("Failed to base64url decode the payload")}else f="string"==typeof e.payload?c.encode(e.payload):e.payload;const m={payload:f};return void 0!==e.protected&&(m.protectedHeader=n),void 0!==e.header&&(m.unprotectedHeader=e.header),h?{...m,key:t}:m}({payload:o,protected:n,signature:i},t,r),h={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...h,key:s.key}:h}var se=e=>Math.floor(e.getTime()/1e3);const ce=86400,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 le=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(r*ce);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 he=e=>e.toLowerCase().replace(/^application\//,"");var ue=(e,t,r={})=>{let n;try{n=JSON.parse(d.decode(t))}catch{}if(!$(n))throw new v("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&("string"!=typeof e.typ||he(e.typ)!==he(o)))throw new w('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:l}=r,h=[...i];void 0!==l&&h.push("iat"),void 0!==c&&h.push("aud"),void 0!==s&&h.push("sub"),void 0!==a&&h.push("iss");for(const e of new Set(h.reverse()))if(!(e in n))throw new w(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new w('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new w('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(u=n.aud,p="string"==typeof c?[c]:c,!("string"==typeof u?p.includes(u):Array.isArray(u)&&p.some(Set.prototype.has.bind(new Set(u))))))throw new w('unexpected "aud" claim value',n,"aud","check_failed");var u,p;let y;switch(typeof r.clockTolerance){case"string":y=le(r.clockTolerance);break;case"number":y=r.clockTolerance;break;case"undefined":y=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,g=se(m||new Date);if((void 0!==n.iat||l)&&"number"!=typeof n.iat)throw new w('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new w('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>g+y)throw new w('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new w('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=g-y)throw new f('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){const e=g-n.iat;if(e-y>("number"==typeof l?l:le(l)))throw new f('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-y)throw new w('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function pe(e,t,r){const n=await ae(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new v("JWTs MUST NOT use unencoded payload");const o={payload:ue(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...o,key:n.key}:o}var we=async(e,t,r)=>{const n=await oe(e,t,"sign");N(e,n);const o=await i.subtle.sign(ne(e,n.algorithm),n,r);return new Uint8Array(o)};class fe{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 g("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!H(this._protectedHeader,this._unprotectedHeader))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(Q(g,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if("string"!=typeof o||!o)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');Z(o,e,"sign");let i,a=this._payload;n&&(a=c.encode(h(a))),i=this._protectedHeader?c.encode(h(JSON.stringify(this._protectedHeader))):c.encode("");const s=l(i,c.encode("."),a),u=await we(o,e,s),p={signature:h(u),payload:""};return n&&(p.payload=d.decode(a)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=d.decode(i)),p}}class ye{constructor(e){this._flattened=new fe(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 me(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ge{constructor(e={}){if(!$(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:me("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:me("setNotBefore",se(e))}:this._payload={...this._payload,nbf:se(new Date)+le(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:me("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:me("setExpirationTime",se(e))}:this._payload={...this._payload,exp:se(new Date)+le(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:se(new Date)}:e instanceof Date?this._payload={...this._payload,iat:me("setIssuedAt",se(e))}:this._payload="string"==typeof e?{...this._payload,iat:me("setIssuedAt",se(new Date)+le(e))}:{...this._payload,iat:me("setIssuedAt",e)},this}}class ve extends ge{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new ye(c.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 v("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const be=(e,t)=>{if("string"!=typeof e||!e)throw new b(`${t} missing or invalid`)};async function Ee(e,t){if(!$(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":be(e.crv,'"crv" (Curve) Parameter'),be(e.x,'"x" (X Coordinate) Parameter'),be(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":be(e.crv,'"crv" (Subtype of Key Pair) Parameter'),be(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":be(e.e,'"e" (Exponent) Parameter'),be(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":be(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new m('"kty" (Key Type) Parameter missing or unsupported')}const n=c.encode(JSON.stringify(r));return h(await s(t,n))}function Se(e){return $(e)}function _e(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class ke{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(Se)}(e))throw new E("JSON Web Key Set malformed");this._jwks=_e(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=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 m('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this._jwks.keys.filter(e=>{let t=o===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:a,length:s}=i;if(0===s)throw new S;if(1!==s){const e=new _,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of i)try{yield await Ae(t,e,r)}catch{}},e}return Ae(this._cached,a,r)}}async function Ae(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await G({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new E("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function Te(e){const t=new ke(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>_e(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var Ie=async(e,t,r)=>{let n,o,i=!1;"function"==typeof AbortController&&(n=new AbortController,o=setTimeout(()=>{i=!0,n.abort()},t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(i)throw new k;throw e});if(void 0!==o&&clearTimeout(o),200!==a.status)throw new p("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new p("Failed to parse the JSON Web Key Set HTTP response as JSON")}};let Pe;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){Pe=`${"jose"}/${"v5.10.0"}`}const Re=Symbol();class Ce{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?.[Re]&&(this._cache=t?.[Re],r=t?.[Re],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&$(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,$)&&(this._jwksTimestamp=this._cache.uat,this._local=Te(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 S&&!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);Pe&&!e.has("User-Agent")&&(e.set("User-Agent",Pe),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Ie(this._url,this._timeoutDuration,this._options).then(e=>{this._local=Te(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 Ce(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 De=u;function We(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new m("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function Oe(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:We(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:We(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:We(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=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new m("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=t?.crv??"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 m("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return i.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const He=async(e,t,r)=>{const n=new URL(t),o=n.origin+n.pathname+n.search,i=new URL(e).origin,a=await fetch(`${i}/.well-known/openid-configuration`).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),s=a.issuer,c=e=>e.endsWith("/")?e.slice(0,-1):e;if(c(e)!==c(s))throw new Error("RFC 9207 - iss !== idp - "+s+" !== "+e);sessionStorage.setItem("idp",s),sessionStorage.setItem("token_endpoint",a.token_endpoint),sessionStorage.setItem("jwks_uri",a.jwks_uri);let d=r?.client_id;if(!d){const e=a.registration_endpoint,t=await(async(e,t)=>{const r={...t,grant_types:["authorization_code","refresh_token"],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:[o]}).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()});d=t.client_id}try{new URL(d)}catch{sessionStorage.setItem("client_id",d)}const{pkce_code_verifier:l,pkce_code_challenge:h}=await $e();sessionStorage.setItem("pkce_code_verifier",l);const u=window.crypto.randomUUID();sessionStorage.setItem("csrf_token",u);const p=a.authorization_endpoint+"?response_type=code"+`&redirect_uri=${encodeURIComponent(o)}&scope=openid offline_access webid`+`&client_id=${encodeURIComponent(d)}&code_challenge_method=S256`+`&code_challenge=${h}`+`&state=${u}&prompt=consent`;window.location.href=p},$e=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(/=+$/,"")}},Ne=async(e,t,r,n,o,i)=>{const a=await re(i.publicKey);a.alg="ES256";const s=await new ve({htu:o,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:a}).sign(i.privateKey);return fetch(o,{method:"POST",headers:{dpop:s,"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})})},Ue=async(e,t,r,n)=>{const o=await re(n.publicKey);o.alg="ES256";const i=await new ve({htu:r,htm:"POST"}).setIssuedAt().setJti(self.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).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})})};var je;!function(e){e.STATE_CHANGE="sessionStateChange",e.EXPIRATION_WARNING="sessionExpirationWarning",e.EXPIRATION="sessionExpiration"}(je||(je={}));class Je extends EventTarget{isActive_=!1;exp_;webId_=void 0;currentAth_=void 0;information;database;refreshPromise;resolveRefresh;rejectRefresh;constructor(e,t){super(),this.authFetch=this.authFetch.bind(this),this.information={clientDetails:e},this.database=t?.database,t?.onSessionStateChange&&this.addEventListener(je.STATE_CHANGE,e=>t.onSessionStateChange?.(e)),t?.onSessionExpirationWarning&&this.addEventListener(je.EXPIRATION_WARNING,e=>t?.onSessionExpirationWarning?.(e)),t?.onSessionExpiration&&this.addEventListener(je.EXPIRATION,e=>t?.onSessionExpiration?.(e))}async login(e,t){await He(e,t,this.information.clientDetails)}async handleRedirectFromLogin(){const e=await(async(e,t)=>{const r=new URL(window.location.href),n=r.searchParams.get("code");if(null===n)return{clientDetails:e};const o=sessionStorage.getItem("idp");if(null===o||r.searchParams.get("iss")!==o)throw new Error("RFC 9207 - iss !== idp - "+r.searchParams.get("iss")+" !== "+o);if(r.searchParams.get("state")!==sessionStorage.getItem("csrf_token"))throw new Error("RFC 6749 - state !== csrf_token - "+r.searchParams.get("state")+" !== "+sessionStorage.getItem("csrf_token"));r.searchParams.delete("iss"),r.searchParams.delete("state"),r.searchParams.delete("code"),window.history.pushState({},document.title,r.toString());const i=sessionStorage.getItem("pkce_code_verifier");if(null===i)throw new Error("Access Token Request preparation - Could not find in sessionStorage: pkce_code_verifier");const a=e?.client_id||sessionStorage.getItem("client_id");if(!a)throw new Error("Access Token Request preparation - Could not find in sessionStorage: client_id (dynamic registration)");const s=sessionStorage.getItem("token_endpoint");if(null===s)throw new Error("Access Token Request preparation - Could not find in sessionStorage: token_endpoint");const c=await Oe("ES256"),d=await Ne(n,i,r.toString(),a,s,c).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),l=d.access_token,h=sessionStorage.getItem("jwks_uri");if(null===h)throw new Error("Access Token validation preparation - Could not find in sessionStorage: jwks_uri");const u=xe(new URL(h)),{payload:p}=await pe(l,u,{issuer:o,audience:"solid"}),w=await Ee(await re(c.publicKey));if(p.cnf.jkt!==w)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+p.cnf.jkt+" !== "+w);if(p.client_id!==a)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+p.client_id+" !== "+a);const f={...d,dpop_key_pair:c},y={idp:o,jwks_uri:h,token_endpoint:s};return e||(e={redirect_uris:[r.toString()]}),e.client_id=a,t&&(await t.init(),await Promise.all([t.setItem("idp",o),t.setItem("jwks_uri",h),t.setItem("token_endpoint",s),t.setItem("client_id",a),t.setItem("dpop_keypair",c),t.setItem("refresh_token",d.refresh_token)]),t.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:y,tokenDetails:f}})(this.information.clientDetails,this.database);e.tokenDetails&&(this.information.clientDetails=e.clientDetails,this.information.idpDetails=e.idpDetails,await this.setTokenDetails(e.tokenDetails),this.dispatchStateChangeEvent())}async restore(){if(!this.database)throw new Error("Could not refresh tokens: missing database. Provide database in sessionOption.");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=new Promise((e,t)=>{this.resolveRefresh=e,this.rejectRefresh=t});const e=this.isActive;return(async e=>{try{await e.init();const t=await e.getItem("client_id"),r=await e.getItem("token_endpoint"),n=await e.getItem("dpop_keypair"),o=await e.getItem("refresh_token");if(null===t||null===r||null===n||null===o)throw new Error("Could not refresh tokens: details missing from database.");const i=await Ue(o,t,r,n).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),a=i.access_token,s=await e.getItem("idp");if(null===s)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: idp");const c=await e.getItem("jwks_uri");if(null===c)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: jwks_uri");const d=xe(new URL(c)),{payload:l}=await pe(a,d,{issuer:s,audience:"solid"}),h=await Ee(await re(n.publicKey));if(l.cnf.jkt!==h)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+l.cnf.jkt+" !== "+h);if(l.client_id!==t)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+l.client_id+" !== "+t);return await e.setItem("refresh_token",i.refresh_token),{...i,dpop_key_pair:n}}finally{e.close()}})(this.database).then(e=>this.setTokenDetails(e)).then(()=>this.resolveRefresh()).catch(e=>{this.isActive?(this.rejectRefresh(new Error(e||"Token refresh failed")),this.isExpired()?this.dispatchExpirationEvent():this.dispatchExpirationWarningEvent()):this.rejectRefresh(new Error("No session to restore."))}).finally(()=>{this.clearRefreshPromise(),e!==this.isActive&&this.dispatchStateChangeEvent()}),this.refreshPromise}async logout(){this.isActive_=!1,this.exp_=void 0,this.webId_=void 0,this.currentAth_=void 0,this.information.idpDetails=void 0,this.information.tokenDetails=void 0,this.refreshPromise&&this.rejectRefresh&&(this.rejectRefresh(new Error("Logout during token refresh.")),this.clearRefreshPromise()),this.database&&(await this.database.init(),await this.database.clear(),this.database.close()),this.dispatchStateChangeEvent()}async authFetch(e,t,r){if(!this.isActive)return fetch(e,t);let n,o,i;e instanceof Request?(n=new URL(e.url),o=t?.method||e?.method||"GET",i=new Headers(e.headers)):(t=t||{},n=new URL(e.toString()),o=t.method||"GET",i=t.headers?new Headers(t.headers):new Headers),await this._renewTokensIfExpired(),r=r??{htu:`${n.origin}${n.pathname}`,htm:o.toUpperCase()};const a=await this._createSignedDPoPToken(r);return i.set("dpop",a),i.set("authorization",`DPoP ${this.information.tokenDetails.access_token}`),e instanceof Request?fetch(new Request(e,{...t,headers:i})):fetch(n,{...t,headers:i})}async setTokenDetails(e){this.information.tokenDetails=e,await this._updateSessionDetailsFromToken(e.access_token)}clearRefreshPromise(){this.refreshPromise=void 0,this.resolveRefresh=void 0,this.rejectRefresh=void 0}get isActive(){return this.isActive_}get webId(){return this.webId_}isExpired(){return!this.exp_||this._isTokenExpired(this.exp_)}getExpiresIn(){return this.exp_?this._getTokenTTL(this.exp_):-1}getTokenDetails(){return this.information.tokenDetails}async _renewTokensIfExpired(){this.isExpired()&&(this.refreshPromise?await this.refreshPromise:await this.restore())}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(/=+$/,"")}async _createSignedDPoPToken(e){if(!this.information.tokenDetails||!this.currentAth_)throw new Error("Session not established.");e.ath=this.currentAth_;const t=await re(this.information.tokenDetails.dpop_key_pair.publicKey);return new ve(e).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:t}).sign(this.information.tokenDetails.dpop_key_pair.privateKey)}async _updateSessionDetailsFromToken(e){if(e)try{const t=function(e){if("string"!=typeof e)throw new v("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new v("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new v("Invalid JWT");if(!t)throw new v("JWTs must contain a payload");let n,o;try{n=De(t)}catch{throw new v("Failed to base64url decode the payload")}try{o=JSON.parse(d.decode(n))}catch{throw new v("Failed to parse the decoded payload as JSON")}if(!$(o))throw new v("Invalid JWT Claims Set");return o}(e),r=t.webid;if(!r)throw new Error("Missing webid claim in access token");const n=t.exp;if(!n)throw new Error("Missing exp claim in access token");this.currentAth_=await this._computeAth(e),this.webId_=r,this.exp_=n,this.isActive_=!0}catch(e){await this.logout()}else await this.logout()}_isTokenExpired(e,t=0){return!("number"==typeof e&&!isNaN(e))||this._getTokenTTL(e,t)<0}_getTokenTTL(e,t=0){return e-(Math.floor(Date.now()/1e3)+t)}dispatchStateChangeEvent(){this.dispatchEvent(new CustomEvent(je.STATE_CHANGE,{detail:{isActive:this.isActive,webId:this.webId}}))}dispatchExpirationWarningEvent(){this.dispatchEvent(new CustomEvent(je.EXPIRATION_WARNING,{detail:{expires_in:this.getExpiresIn()}}))}dispatchExpirationEvent(){this.dispatchEvent(new CustomEvent(je.EXPIRATION))}}var Le;!function(e){e.SCHEDULE="SCHEDULE",e.REFRESH="REFRESH",e.STOP="STOP",e.DISCONNECT="DISCONNECT",e.TOKEN_DETAILS="TOKEN_DETAILS",e.ERROR_ON_REFRESH="ERROR_ON_REFRESH",e.EXPIRED="EXPIRED"}(Le||(Le={}));class Ke{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 o=this.db.transaction(this.storeName,"readwrite");o.oncomplete=()=>{r()},o.onerror=t=>{n(new Error(`Transaction error for setItem(${e},...): ${t.target.error}`))},o.onabort=t=>{n(new Error(`Transaction aborted for setItem(${e},...): ${t.target.error}`))};o.objectStore(this.storeName).put(t,e)})}async getItem(e){return this.db||await this.init(),new Promise((t,r)=>{const 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 o=n.objectStore(this.storeName).get(e);o.onsuccess=()=>{t(o.result||null)}})}async deleteItem(e){return this.db||await this.init(),new Promise((t,r)=>{const 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)}}class Me extends Je{worker;constructor(e,t){const r=new Ke;super(e,{...t,database:r});const o=t?.workerUrl??new URL(n(552),n.b);this.worker=new SharedWorker(o,{type:"module"}),this.worker.port.onmessage=e=>{this.handleWorkerMessage(e.data).catch(console.error)},window.addEventListener("beforeunload",()=>{this.worker.port.postMessage({type:Le.DISCONNECT})})}async handleWorkerMessage(e){const{type:t,payload:r,error:n}=e;switch(t){case Le.TOKEN_DETAILS:const e=this.isActive;await this.setTokenDetails(r.tokenDetails),e!==this.isActive&&this.dispatchStateChangeEvent(),this.refreshPromise&&this.resolveRefresh&&(this.resolveRefresh(),this.clearRefreshPromise());break;case Le.ERROR_ON_REFRESH:this.isActive&&this.dispatchExpirationWarningEvent(),this.refreshPromise&&this.rejectRefresh&&(this.isActive?this.rejectRefresh(new Error(n||"Token refresh failed")):this.rejectRefresh(new Error("No session to restore")),this.clearRefreshPromise());break;case Le.EXPIRED:this.isActive&&(this.dispatchExpirationEvent(),await this.logout()),this.refreshPromise&&this.rejectRefresh&&(this.rejectRefresh(new Error(n||"Token refresh failed")),this.clearRefreshPromise())}}async handleRedirectFromLogin(){await super.handleRedirectFromLogin(),this.isActive&&this.worker.port.postMessage({type:Le.SCHEDULE,payload:{...this.getTokenDetails(),expires_in:this.getExpiresIn()}})}async restore(){return this.refreshPromise||(this.refreshPromise=new Promise((e,t)=>{this.resolveRefresh=e,this.rejectRefresh=t}),this.worker.port.postMessage({type:Le.REFRESH})),this.refreshPromise}async logout(){this.worker.port.postMessage({type:Le.STOP}),await super.logout()}}var Fe=crypto;const Ve=e=>e instanceof CryptoKey;var Be=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await Fe.subtle.digest(r,t))};const Ge=new TextEncoder,qe=new TextDecoder;function ze(...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 Xe=e=>(e=>{let t=e;"string"==typeof t&&(t=Ge.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,"_"),Ye=e=>{let t=e;t instanceof Uint8Array&&(t=qe.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 Ze extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}Ze.code="ERR_JOSE_GENERIC";class Qe extends Ze{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}}Qe.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class et extends Ze{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}}et.code="ERR_JWT_EXPIRED";class tt extends Ze{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}tt.code="ERR_JOSE_ALG_NOT_ALLOWED";class rt extends Ze{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}rt.code="ERR_JOSE_NOT_SUPPORTED";(class extends Ze{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends Ze{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class nt extends Ze{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}nt.code="ERR_JWS_INVALID";class ot extends Ze{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ot.code="ERR_JWT_INVALID";class it extends Ze{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}it.code="ERR_JWK_INVALID";class at extends Ze{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}at.code="ERR_JWKS_INVALID";class st extends Ze{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}st.code="ERR_JWKS_NO_MATCHING_KEY";class ct extends Ze{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}ct.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class dt extends Ze{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}dt.code="ERR_JWKS_TIMEOUT";class lt extends Ze{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function ht(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ut(e,t){return e.name===t}function pt(e){return parseInt(e.name.slice(4),10)}function wt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ut(e.algorithm,"HMAC"))throw ht("HMAC");const r=parseInt(t.slice(2),10);if(pt(e.algorithm.hash)!==r)throw ht(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ut(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ht("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(pt(e.algorithm.hash)!==r)throw ht(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ut(e.algorithm,"RSA-PSS"))throw ht("RSA-PSS");const r=parseInt(t.slice(2),10);if(pt(e.algorithm.hash)!==r)throw ht(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ht("Ed25519 or Ed448");break;case"Ed25519":if(!ut(e.algorithm,"Ed25519"))throw ht("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!ut(e.algorithm,"ECDSA"))throw ht("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 ht(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 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function ft(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}lt.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var yt=(e,...t)=>ft("Key must be ",e,...t);function mt(e,t,...r){return ft(`Key for the ${e} algorithm must be `,t,...r)}var gt=e=>!!Ve(e)||"KeyObject"===e?.[Symbol.toStringTag];const vt=["CryptoKey"];var bt=(...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 Et(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 St=(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 _t(e){return Et(e)&&"string"==typeof e.kty}var kt=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 rt('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 rt('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 rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new rt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,Fe.subtle.importKey("jwk",o,...n)};const At=e=>Ye(e);let Tt,It;const Pt=e=>"KeyObject"===e?.[Symbol.toStringTag],Rt=async(e,t,r,n,o=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const a=await kt({...r,alg:n});return o&&Object.freeze(t),i?i[n]=a:e.set(t,{[n]:a}),a};var Ct=(e,t)=>{if(Pt(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?At(r.k):(It||(It=new WeakMap),Rt(It,e,r,t))}if(_t(e)){if(e.k)return Ye(e.k);It||(It=new WeakMap);return Rt(It,e,e,t,!0)}return e},xt=(e,t)=>{if(Pt(e)){let r=e.export({format:"jwk"});return r.k?At(r.k):(Tt||(Tt=new WeakMap),Rt(Tt,e,r,t))}if(_t(e)){if(e.k)return Ye(e.k);Tt||(Tt=new WeakMap);return Rt(Tt,e,e,t,!0)}return e};async function Dt(e,t){if(!Et(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 Ye(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new rt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return kt({...e,alg:t});default:throw new rt('Unsupported "kty" (Key Type) Parameter value')}}const Wt=e=>e?.[Symbol.toStringTag],Ot=(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},Ht=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&_t(t)){if(function(e){return _t(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&Ot(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(!gt(t))throw new TypeError(mt(e,t,...vt,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${Wt(t)} instances for symmetric algorithms must be of type "secret"`)}};function $t(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Ht(t,r,n,e):((e,t,r,n)=>{if(n&&_t(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&Ot(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)&&Ot(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!gt(t))throw new TypeError(mt(e,t,...vt,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${Wt(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}$t.bind(void 0,!1);const Nt=$t.bind(void 0,!0);function Ut(e,t,r,n,o){if(void 0!==o.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 rt(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[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)}var jt=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};var Jt=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:Xe(e)};if(!Ve(e))throw new TypeError(yt(e,...vt,"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:o,...i}=await Fe.subtle.exportKey("jwk",e);return i};async function Lt(e){return Jt(e)}function Kt(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 rt(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Mt(e,t,r){if("sign"===r&&(t=await xt(t,e)),"verify"===r&&(t=await Ct(t,e)),Ve(t))return wt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(yt(t,...vt));return Fe.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(yt(t,...vt,"Uint8Array","JSON Web Key"))}var Ft=async(e,t,r,n)=>{const o=await Mt(e,t,"verify");St(e,o);const i=Kt(e,o.algorithm);try{return await Fe.subtle.verify(i,o,r,n)}catch{return!1}};async function Vt(e,t,r){if(e instanceof Uint8Array&&(e=qe.decode(e)),"string"!=typeof e)throw new nt("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:i,length:a}=e.split(".");if(3!==a)throw new nt("Invalid Compact JWS");const s=await async function(e,t,r){if(!Et(e))throw new nt("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new nt('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new nt("JWS Protected Header incorrect type");if(void 0===e.payload)throw new nt("JWS Payload missing");if("string"!=typeof e.signature)throw new nt("JWS Signature missing or incorrect type");if(void 0!==e.header&&!Et(e.header))throw new nt("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=Ye(e.protected);n=JSON.parse(qe.decode(t))}catch{throw new nt("JWS Protected Header is invalid")}if(!bt(n,e.header))throw new nt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header};let i=!0;if(Ut(nt,new Map([["b64",!0]]),r?.crit,n,o).has("b64")&&(i=n.b64,"boolean"!=typeof i))throw new nt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if("string"!=typeof a||!a)throw new nt('JWS "alg" (Algorithm) Header Parameter missing or invalid');const s=r&&jt("algorithms",r.algorithms);if(s&&!s.has(a))throw new tt('"alg" (Algorithm) Header Parameter value not allowed');if(i){if("string"!=typeof e.payload)throw new nt("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new nt("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t?(t=await t(n,e),c=!0,Nt(a,t,"verify"),_t(t)&&(t=await Dt(t,a))):Nt(a,t,"verify");const d=ze(Ge.encode(e.protected??""),Ge.encode("."),"string"==typeof e.payload?Ge.encode(e.payload):e.payload);let l,h;try{l=Ye(e.signature)}catch{throw new nt("Failed to base64url decode the signature")}if(!await Ft(a,t,l,d))throw new lt;if(i)try{h=Ye(e.payload)}catch{throw new nt("Failed to base64url decode the payload")}else h="string"==typeof e.payload?Ge.encode(e.payload):e.payload;const u={payload:h};return void 0!==e.protected&&(u.protectedHeader=n),void 0!==e.header&&(u.unprotectedHeader=e.header),c?{...u,key:t}:u}({payload:o,protected:n,signature:i},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...c,key:s.key}:c}var Bt=e=>Math.floor(e.getTime()/1e3);const Gt=86400,qt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var zt=e=>{const t=qt.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(r*Gt);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 Xt=e=>e.toLowerCase().replace(/^application\//,"");var Yt=(e,t,r={})=>{let n;try{n=JSON.parse(qe.decode(t))}catch{}if(!Et(n))throw new ot("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&("string"!=typeof e.typ||Xt(e.typ)!==Xt(o)))throw new Qe('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:d}=r,l=[...i];void 0!==d&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==s&&l.push("sub"),void 0!==a&&l.push("iss");for(const e of new Set(l.reverse()))if(!(e in n))throw new Qe(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new Qe('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new Qe('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(h=n.aud,u="string"==typeof c?[c]:c,!("string"==typeof h?u.includes(h):Array.isArray(h)&&u.some(Set.prototype.has.bind(new Set(h))))))throw new Qe('unexpected "aud" claim value',n,"aud","check_failed");var h,u;let p;switch(typeof r.clockTolerance){case"string":p=zt(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:w}=r,f=Bt(w||new Date);if((void 0!==n.iat||d)&&"number"!=typeof n.iat)throw new Qe('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new Qe('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>f+p)throw new Qe('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new Qe('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=f-p)throw new et('"exp" claim timestamp check failed',n,"exp","check_failed")}if(d){const e=f-n.iat;if(e-p>("number"==typeof d?d:zt(d)))throw new et('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-p)throw new Qe('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Zt(e,t,r){const n=await Vt(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new ot("JWTs MUST NOT use unencoded payload");const o={payload:Yt(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...o,key:n.key}:o}var Qt=async(e,t,r)=>{const n=await Mt(e,t,"sign");St(e,n);const o=await Fe.subtle.sign(Kt(e,n.algorithm),n,r);return new Uint8Array(o)};class er{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 nt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!bt(this._protectedHeader,this._unprotectedHeader))throw new nt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(Ut(nt,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new nt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if("string"!=typeof o||!o)throw new nt('JWS "alg" (Algorithm) Header Parameter missing or invalid');Nt(o,e,"sign");let i,a=this._payload;n&&(a=Ge.encode(Xe(a))),i=this._protectedHeader?Ge.encode(Xe(JSON.stringify(this._protectedHeader))):Ge.encode("");const s=ze(i,Ge.encode("."),a),c=await Qt(o,e,s),d={signature:Xe(c),payload:""};return n&&(d.payload=qe.decode(a)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=qe.decode(i)),d}}class tr{constructor(e){this._flattened=new er(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 rr(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class nr{constructor(e={}){if(!Et(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:rr("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:rr("setNotBefore",Bt(e))}:this._payload={...this._payload,nbf:Bt(new Date)+zt(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:rr("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:rr("setExpirationTime",Bt(e))}:this._payload={...this._payload,exp:Bt(new Date)+zt(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:Bt(new Date)}:e instanceof Date?this._payload={...this._payload,iat:rr("setIssuedAt",Bt(e))}:this._payload="string"==typeof e?{...this._payload,iat:rr("setIssuedAt",Bt(new Date)+zt(e))}:{...this._payload,iat:rr("setIssuedAt",e)},this}}class or extends nr{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new tr(Ge.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 ot("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const ir=(e,t)=>{if("string"!=typeof e||!e)throw new it(`${t} missing or invalid`)};async function ar(e,t){if(!Et(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":ir(e.crv,'"crv" (Curve) Parameter'),ir(e.x,'"x" (X Coordinate) Parameter'),ir(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":ir(e.crv,'"crv" (Subtype of Key Pair) Parameter'),ir(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":ir(e.e,'"e" (Exponent) Parameter'),ir(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":ir(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new rt('"kty" (Key Type) Parameter missing or unsupported')}const n=Ge.encode(JSON.stringify(r));return Xe(await Be(t,n))}function sr(e){return Et(e)}function cr(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class dr{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(sr)}(e))throw new at("JSON Web Key Set malformed");this._jwks=cr(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=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 rt('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this._jwks.keys.filter(e=>{let t=o===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:a,length:s}=i;if(0===s)throw new st;if(1!==s){const e=new ct,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of i)try{yield await lr(t,e,r)}catch{}},e}return lr(this._cached,a,r)}}async function lr(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await Dt({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new at("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function hr(e){const t=new dr(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>cr(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var ur=async(e,t,r)=>{let n,o,i=!1;"function"==typeof AbortController&&(n=new AbortController,o=setTimeout(()=>{i=!0,n.abort()},t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(i)throw new dt;throw e});if(void 0!==o&&clearTimeout(o),200!==a.status)throw new Ze("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new Ze("Failed to parse the JSON Web Key Set HTTP response as JSON")}};let pr;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){pr=`${"jose"}/${"v5.10.0"}`}const wr=Symbol();class fr{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?.[wr]&&(this._cache=t?.[wr],r=t?.[wr],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&Et(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,Et)&&(this._jwksTimestamp=this._cache.uat,this._local=hr(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 st&&!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);pr&&!e.has("User-Agent")&&(e.set("User-Agent",pr),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ur(this._url,this._timeoutDuration,this._options).then(e=>{this._local=hr(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 yr(e,t){const r=new fr(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 mr=Ye;function gr(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new rt("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function vr(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:gr(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:gr(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:gr(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=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new rt("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=t?.crv??"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 rt("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new rt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return Fe.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const br=async(e,t,r)=>{const n=new URL(t),o=n.origin+n.pathname+n.search,i=new URL(e).origin,a=await fetch(`${i}/.well-known/openid-configuration`).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),s=a.issuer,c=e=>e.endsWith("/")?e.slice(0,-1):e;if(c(e)!==c(s))throw new Error("RFC 9207 - iss !== idp - "+s+" !== "+e);sessionStorage.setItem("idp",s),sessionStorage.setItem("token_endpoint",a.token_endpoint),sessionStorage.setItem("jwks_uri",a.jwks_uri);let d=r?.client_id;if(!d){const e=a.registration_endpoint,t=await(async(e,t)=>{const r={...t,grant_types:["authorization_code","refresh_token"],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:[o]}).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()});d=t.client_id}try{new URL(d)}catch{sessionStorage.setItem("client_id",d)}const{pkce_code_verifier:l,pkce_code_challenge:h}=await Er();sessionStorage.setItem("pkce_code_verifier",l);const u=window.crypto.randomUUID();sessionStorage.setItem("csrf_token",u);const p=a.authorization_endpoint+"?response_type=code"+`&redirect_uri=${encodeURIComponent(o)}&scope=openid offline_access webid`+`&client_id=${encodeURIComponent(d)}&code_challenge_method=S256`+`&code_challenge=${h}`+`&state=${u}&prompt=consent`;window.location.href=p},Er=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(/=+$/,"")}},Sr=async(e,t,r,n,o,i)=>{const a=await Lt(i.publicKey);a.alg="ES256";const s=await new or({htu:o,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:a}).sign(i.privateKey);return fetch(o,{method:"POST",headers:{dpop:s,"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=async(e,t,r,n)=>{const o=await Lt(n.publicKey);o.alg="ES256";const i=await new or({htu:r,htm:"POST"}).setIssuedAt().setJti(self.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).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})})};var kr;!function(e){e.STATE_CHANGE="sessionStateChange",e.EXPIRATION_WARNING="sessionExpirationWarning",e.EXPIRATION="sessionExpiration"}(kr||(kr={}));class Ar extends EventTarget{isActive_=!1;exp_;webId_=void 0;currentAth_=void 0;information;database;refreshPromise;resolveRefresh;rejectRefresh;constructor(e,t){super(),this.authFetch=this.authFetch.bind(this),this.information={clientDetails:e},this.database=t?.database,t?.onSessionStateChange&&this.addEventListener(kr.STATE_CHANGE,e=>t.onSessionStateChange?.(e)),t?.onSessionExpirationWarning&&this.addEventListener(kr.EXPIRATION_WARNING,e=>t?.onSessionExpirationWarning?.(e)),t?.onSessionExpiration&&this.addEventListener(kr.EXPIRATION,e=>t?.onSessionExpiration?.(e))}async login(e,t){await br(e,t,this.information.clientDetails)}async handleRedirectFromLogin(){const e=await(async(e,t)=>{const r=new URL(window.location.href),n=r.searchParams.get("code");if(null===n)return{clientDetails:e};const o=sessionStorage.getItem("idp");if(null===o||r.searchParams.get("iss")!==o)throw new Error("RFC 9207 - iss !== idp - "+r.searchParams.get("iss")+" !== "+o);if(r.searchParams.get("state")!==sessionStorage.getItem("csrf_token"))throw new Error("RFC 6749 - state !== csrf_token - "+r.searchParams.get("state")+" !== "+sessionStorage.getItem("csrf_token"));r.searchParams.delete("iss"),r.searchParams.delete("state"),r.searchParams.delete("code"),window.history.pushState({},document.title,r.toString());const i=sessionStorage.getItem("pkce_code_verifier");if(null===i)throw new Error("Access Token Request preparation - Could not find in sessionStorage: pkce_code_verifier");const a=e?.client_id||sessionStorage.getItem("client_id");if(!a)throw new Error("Access Token Request preparation - Could not find in sessionStorage: client_id (dynamic registration)");const s=sessionStorage.getItem("token_endpoint");if(null===s)throw new Error("Access Token Request preparation - Could not find in sessionStorage: token_endpoint");const c=await vr("ES256"),d=await Sr(n,i,r.toString(),a,s,c).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),l=d.access_token,h=sessionStorage.getItem("jwks_uri");if(null===h)throw new Error("Access Token validation preparation - Could not find in sessionStorage: jwks_uri");const u=yr(new URL(h)),{payload:p}=await Zt(l,u,{issuer:o,audience:"solid"}),w=await ar(await Lt(c.publicKey));if(p.cnf.jkt!==w)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+p.cnf.jkt+" !== "+w);if(p.client_id!==a)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+p.client_id+" !== "+a);const f={...d,dpop_key_pair:c},y={idp:o,jwks_uri:h,token_endpoint:s};return e||(e={redirect_uris:[r.toString()]}),e.client_id=a,t&&(await t.init(),await Promise.all([t.setItem("idp",o),t.setItem("jwks_uri",h),t.setItem("token_endpoint",s),t.setItem("client_id",a),t.setItem("dpop_keypair",c),t.setItem("refresh_token",d.refresh_token)]),t.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:y,tokenDetails:f}})(this.information.clientDetails,this.database);e.tokenDetails&&(this.information.clientDetails=e.clientDetails,this.information.idpDetails=e.idpDetails,await this.setTokenDetails(e.tokenDetails),this.dispatchStateChangeEvent())}async restore(){if(!this.database)throw new Error("Could not refresh tokens: missing database. Provide database in sessionOption.");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=new Promise((e,t)=>{this.resolveRefresh=e,this.rejectRefresh=t});const e=this.isActive;return(async e=>{try{await e.init();const t=await e.getItem("client_id"),r=await e.getItem("token_endpoint"),n=await e.getItem("dpop_keypair"),o=await e.getItem("refresh_token");if(null===t||null===r||null===n||null===o)throw new Error("Could not refresh tokens: details missing from database.");const i=await _r(o,t,r,n).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),a=i.access_token,s=await e.getItem("idp");if(null===s)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: idp");const c=await e.getItem("jwks_uri");if(null===c)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: jwks_uri");const d=yr(new URL(c)),{payload:l}=await Zt(a,d,{issuer:s,audience:"solid"}),h=await ar(await Lt(n.publicKey));if(l.cnf.jkt!==h)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+l.cnf.jkt+" !== "+h);if(l.client_id!==t)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+l.client_id+" !== "+t);return await e.setItem("refresh_token",i.refresh_token),{...i,dpop_key_pair:n}}finally{e.close()}})(this.database).then(e=>this.setTokenDetails(e)).then(()=>this.resolveRefresh()).catch(e=>{this.isActive?(this.rejectRefresh(new Error(e||"Token refresh failed")),this.isExpired()?this.dispatchExpirationEvent():this.dispatchExpirationWarningEvent()):this.rejectRefresh(new Error("No session to restore."))}).finally(()=>{this.clearRefreshPromise(),e!==this.isActive&&this.dispatchStateChangeEvent()}),this.refreshPromise}async logout(){this.isActive_=!1,this.exp_=void 0,this.webId_=void 0,this.currentAth_=void 0,this.information.idpDetails=void 0,this.information.tokenDetails=void 0,this.refreshPromise&&this.rejectRefresh&&(this.rejectRefresh(new Error("Logout during token refresh.")),this.clearRefreshPromise()),this.database&&(await this.database.init(),await this.database.clear(),this.database.close()),this.dispatchStateChangeEvent()}async authFetch(e,t,r){if(!this.isActive)return fetch(e,t);let n,o,i;e instanceof Request?(n=new URL(e.url),o=t?.method||e?.method||"GET",i=new Headers(e.headers)):(t=t||{},n=new URL(e.toString()),o=t.method||"GET",i=t.headers?new Headers(t.headers):new Headers),await this._renewTokensIfExpired(),r=r??{htu:`${n.origin}${n.pathname}`,htm:o.toUpperCase()};const a=await this._createSignedDPoPToken(r);return i.set("dpop",a),i.set("authorization",`DPoP ${this.information.tokenDetails.access_token}`),e instanceof Request?fetch(new Request(e,{...t,headers:i})):fetch(n,{...t,headers:i})}async setTokenDetails(e){this.information.tokenDetails=e,await this._updateSessionDetailsFromToken(e.access_token)}clearRefreshPromise(){this.refreshPromise=void 0,this.resolveRefresh=void 0,this.rejectRefresh=void 0}get isActive(){return this.isActive_}get webId(){return this.webId_}isExpired(){return!this.exp_||this._isTokenExpired(this.exp_)}getExpiresIn(){return this.exp_?this._getTokenTTL(this.exp_):-1}getTokenDetails(){return this.information.tokenDetails}async _renewTokensIfExpired(){this.isExpired()&&(this.refreshPromise?await this.refreshPromise:await this.restore())}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(/=+$/,"")}async _createSignedDPoPToken(e){if(!this.information.tokenDetails||!this.currentAth_)throw new Error("Session not established.");e.ath=this.currentAth_;const t=await Lt(this.information.tokenDetails.dpop_key_pair.publicKey);return new or(e).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:t}).sign(this.information.tokenDetails.dpop_key_pair.privateKey)}async _updateSessionDetailsFromToken(e){if(e)try{const t=function(e){if("string"!=typeof e)throw new ot("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new ot("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new ot("Invalid JWT");if(!t)throw new ot("JWTs must contain a payload");let n,o;try{n=mr(t)}catch{throw new ot("Failed to base64url decode the payload")}try{o=JSON.parse(qe.decode(n))}catch{throw new ot("Failed to parse the decoded payload as JSON")}if(!Et(o))throw new ot("Invalid JWT Claims Set");return o}(e),r=t.webid;if(!r)throw new Error("Missing webid claim in access token");const n=t.exp;if(!n)throw new Error("Missing exp claim in access token");this.currentAth_=await this._computeAth(e),this.webId_=r,this.exp_=n,this.isActive_=!0}catch(e){await this.logout()}else await this.logout()}_isTokenExpired(e,t=0){return!("number"==typeof e&&!isNaN(e))||this._getTokenTTL(e,t)<0}_getTokenTTL(e,t=0){return e-(Math.floor(Date.now()/1e3)+t)}dispatchStateChangeEvent(){this.dispatchEvent(new CustomEvent(kr.STATE_CHANGE,{detail:{isActive:this.isActive,webId:this.webId}}))}dispatchExpirationWarningEvent(){this.dispatchEvent(new CustomEvent(kr.EXPIRATION_WARNING,{detail:{expires_in:this.getExpiresIn()}}))}dispatchExpirationEvent(){this.dispatchEvent(new CustomEvent(kr.EXPIRATION))}}class Tr{constructor(){this.map=new Map}shouldPreserveExistingRefreshToken(e,t){return"refresh_token"===e&&(null==t||""===t)&&this.map.has(e)}async init(){return this}async setItem(e,t){this.shouldPreserveExistingRefreshToken(e,t)||this.map.set(e,t)}async getItem(e){return this.map.has(e)?this.map.get(e):null}async deleteItem(e){this.map.delete(e)}async clear(){this.map.clear()}close(){}}class Ir{constructor(){this.db=null,this.dbName="soidc",this.storeName="session",this.dbVersion=1}async shouldPreserveExistingRefreshToken(e,t){if("refresh_token"!==e||null!=t&&""!==t)return!1;const r=await this.getItem(e);return null!=r&&""!==r}async init(){if(this.db)return this;if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available in this environment");return await new Promise((e,t)=>{const r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=()=>t(r.error),r.onsuccess=()=>{this.db=r.result,e()},r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)}}),this}async setItem(e,t){await this.init(),await this.shouldPreserveExistingRefreshToken(e,t)||await this.withStore("readwrite",r=>r.put(t,e))}async getItem(e){return await this.init(),this.withStore("readonly",t=>t.get(e))}async deleteItem(e){await this.init(),await this.withStore("readwrite",t=>t.delete(e))}async clear(){await this.init(),await this.withStore("readwrite",e=>e.clear())}close(){this.db&&(this.db.close(),this.db=null)}withStore(e,t){return new Promise((r,n)=>{if(!this.db)return void n(new Error("Session database not initialized"));const o=this.db.transaction(this.storeName,e),i=o.objectStore(this.storeName),a=t(i);let s=null;o.onerror=()=>{var e;return n(null!==(e=o.error)&&void 0!==e?e:a.error)},o.onabort=()=>{var e,t;return n(null!==(t=null!==(e=o.error)&&void 0!==e?e:a.error)&&void 0!==t?t:new Error("IndexedDB transaction aborted"))},o.oncomplete=()=>r(s),a.onerror=()=>n(a.error),a.onsuccess=()=>{var e;s=null!==(e=a.result)&&void 0!==e?e:null}})}}const Pr=function(){var t,r,n;const o=e,i=null!==(n=null!==(t=o.SessionCore)&&void 0!==t?t:null===(r=o.default)||void 0===r?void 0:r.SessionCore)&&void 0!==n?n:o.default;return"function"!=typeof i?null:i}();const Rr=function(){if("undefined"!=typeof window&&(()=>{const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||e.endsWith(".localhost")})())return Pr?new Pr(void 0,{database:new Ir}):new Me;try{return new Me}catch(e){console.warn("solid-logic: falling back to non-worker auth session:",e);try{return Pr?new Pr(void 0,{database:new Ir}):new Me}catch(e){return console.warn("solid-logic: IndexedDB unavailable, using in-memory session database:",e),Pr?new Pr(void 0,{database:new Tr}):new Me}}}();async function Cr(e){const t=await async function(e){try{const t=new URL(e),r=new URL("/.well-known/openid-configuration",t.origin),n=await fetch(r.toString(),{credentials:"include"});if(!n.ok)return null;const o=await n.json();return"string"==typeof(null==o?void 0:o.issuer)&&o.issuer?o.issuer.replace(/\/$/,""):null}catch(e){return null}}(e);return t||e}var xr;const Dr=Rr,Wr="function"==typeof Dr.login?Dr.login.bind(Rr):void 0;if(Wr){const e=async(e,t)=>{var r,n,o,i;if(e&&"object"==typeof e&&!Array.isArray(e)){const t=null!==(n=null!==(r=e.oidcIssuer)&&void 0!==r?r:e.idp)&&void 0!==n?n:e.issuer,a=null!==(i=null!==(o=e.redirectUrl)&&void 0!==o?o:e.redirect_uri)&&void 0!==i?i:e.redirectUri;if("string"==typeof t&&"string"==typeof a)return Wr(await Cr(t),a)}return Wr("string"==typeof e?await Cr(e):e,t)};Dr.login=e}const Or=new class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var r;null===(r=this.listeners.get(e))||void 0===r||r.delete(t)}emit(e,...t){var r;null===(r=this.listeners.get(e))||void 0===r||r.forEach(e=>e(...t))}};let Hr=null!==(xr=Rr.isActive)&&void 0!==xr?xr:Boolean(Rr.webId);"function"==typeof Rr.addEventListener&&Rr.addEventListener("sessionStateChange",()=>{var e;const t=null!==(e=Rr.isActive)&&void 0!==e?e:Boolean(Rr.webId);Hr&&!t&&Or.emit("logout"),Hr=t});const $r=Object.assign(Rr,{events:Or});var Nr=n(264),Ur=n(386);const jr=n.n(Ur)()(Nr),Jr=(0,Nr.sym)("http://www.iana.org/assignments/link-relations/acl");function Lr(e){const t=jr;function r(e,r,n,o={}){const i=o.public||[],a=(0,Nr.graph)(),s=(0,Nr.Namespace)("http://www.w3.org/ns/auth/acl#");let c=a.sym(`${n}#a1`);const d=a.sym(n),l=a.sym(e);if(a.add(c,t.rdf("type"),s("Authorization"),d),a.add(c,s("accessTo"),l,d),o.defaultForNew&&a.add(c,s("default"),l,d),a.add(c,s("agent"),r,d),a.add(c,s("mode"),s("Read"),d),a.add(c,s("mode"),s("Write"),d),a.add(c,s("mode"),s("Control"),d),i.length){c=a.sym(`${n}#a2`),a.add(c,t.rdf("type"),s("Authorization"),d),a.add(c,s("accessTo"),l,d),a.add(c,s("agentClass"),t.foaf("Agent"),d);for(let e=0;e<i.length;e++)a.add(c,s("mode"),s(i[e]),d)}return(0,Nr.serialize)(d,a,n)}return{findAclDocUrl:async function(t){await e.fetcher.load(t);const r=e.any(t,Jr);if(!r)throw new Error(`No ACL link discovered for ${t}`);return r.value},setACLUserPublic:function(t,n,o){const i=e.any(e.sym(t),Jr);return Promise.resolve().then(()=>i||function(t){const r=e.fetcher;if(!r)throw new Error("Cannot fetch ACL rel, store has no fetcher");return r.load(t).then(r=>{if(!r.ok)throw new Error("fetchACLRel: While loading:"+r.error);const n=e.any(e.sym(t),Jr);if(!n)throw new Error("fetchACLRel: No Link rel=ACL header for "+t);return n})}(t).catch(e=>{throw new Error(`Error fetching rel=ACL header for ${t}: ${e}`)})).then(i=>{const a=r(t,n,i.uri,o);if(!e.fetcher)throw new Error("Cannot PUT this, store has no fetcher");return e.fetcher.webOperation("PUT",i.uri,{data:a,contentType:"text/turtle"}).then(e=>{if(!e.ok)throw new Error("Error writing ACL text: "+e.error);return i})})},genACLText:r}}const Kr=()=>{let{SolidAppContext:e}=window;if(e||(e={}),e.viewingNoAuthPage=!1,e.noAuth&&window.document){if(window.document.location.href.startsWith(e.noAuth)){e.viewingNoAuthPage=!0;const t=new URLSearchParams(window.document.location.search);if(t){let r=e.viewedPage=t.get("uri")||null;if(r&&(r=decodeURI(r),!r.startsWith(e.noAuth))){const t=r.split(/\//);e.idp=t[0]+"//"+t[2],e.viewingNoAuthPage=!1}}}}return e};function Mr(){const{$SolidTestEnvironment:e}=window;if(void 0!==e&&e.username)return t("Assuming the user is "+e.username),(0,Nr.sym)(e.username);if("undefined"!=typeof document&&document.location&&"http://localhost"===(""+document.location).slice(0,16)){const e=document.getElementById("appTarget");if(!e)return null;const r=e.getAttribute("testID");return r?(t("Assuming user is "+r),(0,Nr.sym)(r)):null}return null}class Fr{constructor(e){this.checkUserInFlight=null,this.sessionRestoreHookAttached=!1,this.fallbackWebId=null,this.session=e}get authSession(){return this.session}currentUser(){var e,t;const r=Kr();if(r.viewingNoAuthPage)return(0,Nr.sym)(r.webId);const n=this.session,o=null===(e=null==n?void 0:n.info)||void 0===e?void 0:e.webId,i=null==n?void 0:n.webId,a=o||i||this.fallbackWebId,s=null===(t=null==n?void 0:n.info)||void 0===t?void 0:t.isLoggedIn,c=null==n?void 0:n.isActive,d=!0===s||!0===c||null==s&&null==c&&Boolean(a)||Boolean(this.fallbackWebId);return this&&this.session&&a&&d?(0,Nr.sym)(a):Mr()}async checkUser(e){var r;const n=new URL(window.location.href).hash;n&&window.localStorage.setItem("preLoginRedirectHash",n);const o=this.session;this.sessionRestoreHookAttached||"function"!=typeof(null===(r=null==o?void 0:o.events)||void 0===r?void 0:r.on)||(o.events.on("sessionRestore",e=>{t(`Session restored to ${e}`),document.location.toString()!==e&&history.replaceState(null,"",e)}),this.sessionRestoreHookAttached=!0),this.checkUserInFlight||(this.checkUserInFlight=this.resolveCurrentUser());const i=this.checkUserInFlight;let a;try{a=await i}finally{this.checkUserInFlight===i&&(this.checkUserInFlight=null)}return Promise.resolve(e?e(a):a)}async resolveCurrentUser(){var e,r,n,o,i,a;const s=this.session,c=new URL(window.location.href);if(c.hash="","function"==typeof(null==s?void 0:s.handleIncomingRedirect))await s.handleIncomingRedirect({restorePreviousSession:!0,url:c.href});else{if("function"==typeof(null==s?void 0:s.restore)){const o=null!==(e=null==s?void 0:s.isActive)&&void 0!==e?e:Boolean(null==s?void 0:s.webId);try{await s.restore()}catch(e){const r=e instanceof Error?e.message:String(e);if(!/no session to restore/i.test(r))throw e;t("No previous session to restore")}const i=null!==(r=null==s?void 0:s.isActive)&&void 0!==r?r:Boolean(null==s?void 0:s.webId);!o&&i&&(null===(n=s.events)||void 0===n||n.emit("sessionRestore",window.location.href))}if("function"==typeof(null==s?void 0:s.handleRedirectFromLogin)){const e=null!==(o=null==s?void 0:s.isActive)&&void 0!==o?o:Boolean(null==s?void 0:s.webId);await s.handleRedirectFromLogin();const t=null!==(i=null==s?void 0:s.isActive)&&void 0!==i?i:Boolean(null==s?void 0:s.webId);!e&&t&&(null===(a=s.events)||void 0===a||a.emit("login"))}}const d=window.localStorage.getItem("preLoginRedirectHash");if(d){const e=new URL(window.location.href);e.hash!==d&&(history.pushState?history.pushState(null,document.title,d):location.hash=d,e.hash=d),window.localStorage.setItem("preLoginRedirectHash","")}let l=Mr();if(l)return l;let h=this.webIdFromSession(null==s?void 0:s.info,s);return h||(h=await this.probeNssCookieBackedWebId()),this.fallbackWebId=h||null,h&&(l=this.saveUser(h)),l&&t(`(Logged in as ${l} by authentication)`),l}async probeNssCookieBackedWebId(){if("undefined"==typeof window)return null;const{hostname:e,port:t,protocol:r}=window.location,n=".localhost";if(!e.endsWith(n))return null;const o=e.slice(0,-10);if(!o||"localhost"===o||o.includes("."))return null;try{if(403!==(await fetch("/account/password/change",{credentials:"include",redirect:"manual",cache:"no-store"})).status)return null;return`${`${r}//${e}${t?`:${t}`:""}`}/profile/card#me`}catch(e){return null}}saveUser(e,t){let r;if(e){r="string"==typeof e?e:e.uri;const n=(0,Nr.namedNode)(r);return t&&(t.me=n),n}return null}webIdFromSession(e,t){const r=(null==e?void 0:e.webId)||(null==t?void 0:t.webId);if(!r)return null;const n=null==e?void 0:e.isLoggedIn,o=null==t?void 0:t.isLoggedIn,i=null==t?void 0:t.isActive;return!0===n||!0===o||!0===i?r:!1===n&&!1===o&&!1===i?null:r}}function Vr(e){return(0,Nr.sym)(e.uri+"#id"+Date.now())}function Br(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const Gr="index.ttl#this";function qr(e,t){const r=jr;async function n(t,r,n){await e.fetcher.load(t);const o=e.any(t,new Nr.NamedNode("http://www.iana.org/assignments/link-relations/acl"));if(!o)throw new Error("Chat ACL doc not found!");const i=`\n @prefix acl: <http://www.w3.org/ns/auth/acl#>.\n <#owner>\n a acl:Authorization;\n acl:agent <${r.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Write, acl:Control.\n <#invitee>\n a acl:Authorization;\n acl:agent <${n.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Append.\n `;await e.fetcher.webOperation("PUT",o.value,{data:i,contentType:"text/turtle"})}async function o(t,n){const o=e.any(n,r.solid("privateTypeIndex"));if(!o)throw new Error("Private type index not found!");await e.fetcher.load(o);const i=Vr(o),a=[(0,Nr.st)(i,r.rdf("type"),r.solid("TypeRegistration"),o.doc()),(0,Nr.st)(i,r.solid("forClass"),r.meeting("LongChat"),o.doc()),(0,Nr.st)(i,r.solid("instance"),t,o.doc())];await new Promise((t,r)=>{e.updater.update([],a,function(e,n,o){n?t(null):r(new Error(o))})})}async function i(r){const n=await t.loadMe(),o=function(e,t){const r=new URL(`IndividualChats/${new URL(e.value).host}/`,t.value).toString();return new Nr.NamedNode(r)}(r,await t.getPodRoot(n));let i=!0;try{await e.fetcher.load(new Nr.NamedNode(o.value+"index.ttl#this"))}catch(e){i=!1}return{me:n,chatContainer:o,exists:i}}async function a(e,t){return(await s({me:t,newBase:e.value})).newInstance}function s(t){const n=e,o=n.updater;if(t.me&&!t.me.uri)throw new Error("chat mintNew: Invalid userid "+t.me);const i=t.newInstance=t.newInstance||n.sym(t.newBase+Gr),a=i.doc();return n.add(i,r.rdf("type"),r.meeting("LongChat"),a),n.add(i,r.dc("title"),"Chat channel",a),n.add(i,r.dc("created"),(0,Nr.term)(new Date(Date.now())),a),t.me&&n.add(i,r.dc("author"),t.me,a),new Promise(function(e,r){null==o||o.put(a,n.statementsMatching(void 0,void 0,void 0,a),"text/turtle",function(n,o,a){o?e({...t,newInstance:i}):r(new Error("FAILED to save new chat channel at: "+n+" : "+a))})})}async function c(t,n){var o;await e.fetcher.load(t.doc());const i=e.any(t,r.ldp("inbox"),void 0,t.doc());if(!i)throw new Error(`Invitee inbox not found! ${t.value}`);const a=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${r.rdf("seeAlso")} <${n.value}> .\n `,s=await(null===(o=e.fetcher)||void 0===o?void 0:o.webOperation("POST",i.value,{data:a,contentType:"text/turtle"}));if(!(null==s?void 0:s.headers.get("location")))throw new Error(`Invite sending returned a ${null==s?void 0:s.status}`)}return{setAcl:n,addToPrivateTypeIndex:o,findChat:i,createChatThing:a,getChat:async function(e,t=!0){const{me:r,chatContainer:s,exists:d}=await i(e);if(d)return new Nr.NamedNode(s.value+Gr);if(t){const t=await a(s,r);return await c(e,t),await n(s,r,e),await o(t,r),t}return null},sendInvite:c,mintNew:s}}function zr(e,t,r,n,o){return{createInboxFor:async function(e,o){const i=await t.loadMe(),a=`${(await t.getPodRoot(i)).value}p2p-inboxes/${encodeURIComponent(o)}/`;return await n.createContainer(a),await r.setSinglePeerAccess({ownerWebId:i.value,peerWebId:e,accessToModes:"acl:Append",target:a}),a},getNewMessages:async function(e){e||(e=await t.loadMe());const r=await t.getMainInbox(e);return(await n.getContainerMembers(r)).filter(e=>!n.isContainer(e))},markAsRead:async function(t,r){const n=await e.fetcher._fetch(t);if(200!==n.status)throw new Error(`Not OK! ${t}`);const o=function(e,t){const r=t.getUTCFullYear(),n=("0"+(t.getUTCMonth()+1)).slice(-2),o=("0"+t.getUTCDate()).slice(-2),i=e.split("/"),a=i[i.length-1];return new URL(`./archive/${r}/${n}/${o}/${a}`,e).toString()}(t,r),i={method:"PUT",body:await n.text(),headers:[["Content-Type",n.headers.get("Content-Type")||"application/octet-stream"]]};"2"===(await e.fetcher._fetch(o,i)).status.toString()[0]&&await e.fetcher._fetch(t,{method:"DELETE"})}}}class Xr extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class Yr extends Xr{}class Zr extends Xr{}class Qr extends Xr{}class en extends Xr{}class tn extends Xr{}class rn extends Xr{}class nn extends Xr{constructor(e,t){super(t),this.status=e}}function on(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:ListedDocument."].join("\n")}function an(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:UnlistedDocument."].join("\n")}function sn(e,t){const r=new URL(t).pathname.split("/").pop()||"publicTypeIndex.ttl";return["# ACL resource for the Public Type Index","","@prefix acl: <http://www.w3.org/ns/auth/acl#>.","@prefix foaf: <http://xmlns.com/foaf/0.1/>.","","<#owner>"," a acl:Authorization;",""," acl:agent",` <${e}>;`,"",` acl:accessTo <./${r}>;`,""," acl:mode"," acl:Read, acl:Write, acl:Control.","","# Public-readable","<#public>"," a acl:Authorization;",""," acl:agentClass foaf:Agent;","",` acl:accessTo <./${r}>;`,""," acl:mode acl:Read."].join("\n")}function cn(e){function t(t){return e.statementsMatching(t,(0,Nr.sym)("http://www.w3.org/ns/ldp#contains"),void 0).map(e=>e.object)}function r(e){const t=e.value;return"/"===t.charAt(t.length-1)}return{isContainer:r,createContainer:async function(t){if(!r((0,Nr.sym)(t)))throw new Error(`Not a container URL ${t}`);const n=await e.fetcher._fetch(t,{method:"PUT",headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:'<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'},body:" "});if(409!==n.status&&"2"!==n.status.toString()[0])throw new Error(`Not OK: got ${n.status} response while creating container at ${t}`)},getContainerElements:t,getContainerMembers:async function(r){return await e.fetcher.load(r),t(r)}}}function dn(e,t,n){const o=jr,i=cn(e),a=new Map,s=new Map;function c(e){return!!e&&(e.startsWith("https://")||e.startsWith("http://"))}function d(e){const t=e.doc(),r=t.dir();if((null==r?void 0:r.uri)&&c(r.uri))return r.uri;const n=t.uri;if(!n||!c(n))return null;const o=n.split("#")[0],i=o.lastIndexOf("/");return-1===i?null:o.slice(0,i+1)}function l(e,t){const r=d(e);if(!r)throw new Error(`Cannot derive directory for preferences file ${e.uri}`);return(0,Nr.sym)(r+t)}function h(e){var t;if(404===(null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.status))return!0;const r=`${(null==e?void 0:e.message)||e||""}`;return r.includes("404")||r.includes("Not Found")}async function u(t,r){var n;const o=d(r);if(!o)throw new Error(`Cannot derive settings directory from ${r.uri}`);await async function(t){const r=(0,Nr.sym)(t);try{return void await e.fetcher.load(r)}catch(e){if(!h(e))throw e}await i.createContainer(t)}(o);const a=(0,Nr.sym)(o);let s;try{await e.fetcher.load(a),s=null===(n=e.any(a,Jr))||void 0===n?void 0:n.value}catch(e){if(!h(e))throw e}s||(s=`${o}.acl`);const c=(0,Nr.sym)(s);try{return void await e.fetcher.load(c)}catch(e){if(!h(e))throw e}var l;await e.fetcher.webOperation("PUT",c.uri,{data:(l=t.uri,["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#owner>","a acl:Authorization;",`acl:agent <${l}>;`,"acl:accessTo <./>;","acl:default <./>;","acl:mode acl:Read, acl:Write, acl:Control."].join("\n")),contentType:"text/turtle"})}async function p(t,r){const i=r.doc(),a=t.doc();await e.fetcher.load(i);const s=e.any(t,o.solid("publicTypeIndex"),null,a),c=e.any(t,o.solid("publicTypeIndex"),null,i),d=s||c||l(r,"publicTypeIndex.ttl"),u=e.any(t,o.solid("privateTypeIndex"),null,i)||l(r,"privateTypeIndex.ttl"),p=!s;p&&await n.followOrCreateLinkWithContentOnCreate(t,o.solid("publicTypeIndex"),d,a,on());const w=[];e.holds(i,o.rdf("type"),o.space("ConfigurationFile"),i)||w.push((0,Nr.st)(i,o.rdf("type"),o.space("ConfigurationFile"),i)),e.holds(i,o.dct("title"),void 0,i)||w.push((0,Nr.st)(i,o.dct("title"),(0,Nr.literal)("Preferences file"),i)),e.holds(t,o.solid("publicTypeIndex"),d,i)||w.push((0,Nr.st)(t,o.solid("publicTypeIndex"),d,i)),e.holds(t,o.solid("privateTypeIndex"),u,i)||w.push((0,Nr.st)(t,o.solid("privateTypeIndex"),u,i)),w.length>0&&(await e.updater.update([],w),await e.fetcher.load(i)),await async function(t,r,o=!1){var i,a,s;if(!await n.loadOrCreateWithContentOnCreate(r,on())&&!o)return;let c;try{await e.fetcher.load(r),c=null===(i=e.any(r,Jr))||void 0===i?void 0:i.value}catch(e){if(!h(e))throw e}c||(c=`${r.uri}.acl`);const d=(0,Nr.sym)(c);try{await e.fetcher.webOperation("PUT",d.uri,{data:sn(t.uri,r.uri),contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(e){if(412!==(null!==(s=null===(a=null==e?void 0:e.response)||void 0===a?void 0:a.status)&&void 0!==s?s:null==e?void 0:e.status))throw e}}(t,d,p),await async function(e){await n.loadOrCreateWithContentOnCreate(e,an())}(u)}async function w(e){var t,r;try{return!!await n.loadOrCreateWithContentOnCreate(e,["@prefix dct: <http://purl.org/dc/terms/>.","@prefix pim: <http://www.w3.org/ns/pim/space#>.","@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a pim:ConfigurationFile ;",' dct:title "Preferences file".'].join("\n"))}catch(n){if(401===(null===(t=n.response)||void 0===t?void 0:t.status))throw new Yr;if(403===(null===(r=n.response)||void 0===r?void 0:r.status)){if(Br(e))throw new Zr;throw new Qr}throw n}}async function f(t){const i=s.get(t.uri);if(i)return i;const c=a.get(t.uri);if(c)return c;const d=(async()=>{var i;await y(t);const a=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/settings/prefs.ttl";return(0,Nr.sym)(t)}(t);let c;try{const r=e.any(t,o.space("preferencesFile"),null,t.doc());c=r||await n.followOrCreateLink(t,o.space("preferencesFile"),a,t.doc()),await u(t,c),await w(c),await p(t,c)}catch(e){if(r(`User ${t} has no pointer in profile to preferences file.`),e instanceof tn)throw e;if(e instanceof rn)throw e;if(e instanceof Yr)throw e;if(e instanceof Zr)throw e;if(e instanceof Qr)throw e;if(e instanceof nn)throw e;throw e}try{await e.fetcher.load(c)}catch(n){const o=`Unable to load preference of user ${t}: ${n}`;if(404===(null===(i=n.response)||void 0===i?void 0:i.status))return await u(t,c),await w(c),await p(t,c),await e.fetcher.load(c),c;if(r(o),401===n.response.status)throw new Yr;if(403===n.response.status){if(Br(c))throw new Zr;throw new Qr}throw new Error(o)}return s.set(t.uri,c),c})();a.set(t.uri,d);try{return await d}finally{a.get(t.uri)===d&&a.delete(t.uri)}}async function y(t){if(!t)throw new Error("loadProfile: no user given.");try{await e.fetcher.load(t.doc())}catch(e){throw new Error(`Unable to load profile of user ${t}: ${e}`)}return t.doc()}function m(t){return e.any(t,o.space("storage"),void 0,t.doc())}return{loadMe:async function(){const r=t.currentUser();if(null===r)throw new Error("Current user not found! Not logged in?");return await e.fetcher.load(r.doc()),r},getPodRoot:function(e){const t=m(e);if(!t)throw new Error("User pod root not found!");return t},getMainInbox:async function(t){await e.fetcher.load(t);const r=e.any(t,o.ldp("inbox"),void 0,t.doc());if(!r)throw new Error("User main inbox not found!");return r},findStorage:m,loadPreferences:f,loadProfile:y,silencedLoadPreferences:async function(e){try{return await f(e)}catch(e){return}}}}function ln(e,n,o,i){const a=jr;function s(e){return!!e&&(e.startsWith("https://")||e.startsWith("http://"))}async function c(t){if(!t)throw new Error("loadTypeIndexesFor: No user given");const n=await o.loadProfile(t);let s,c=null;try{c=p(t)}catch(e){r(`User ${t} has no usable profile document directory for publicTypeIndex.`)}try{const r=e.any(t,a.solid("publicTypeIndex"),void 0,n);s=r||(c?await i.followOrCreateLinkWithContentOnCreate(t,a.solid("publicTypeIndex"),c,n,on()):null)}catch(e){r(`User ${t} has no pointer in profile to publicTypeIndex file: ${e}`)}const d=s?[{label:"public",index:s,agent:t}]:[];let l,h;try{l=await o.silencedLoadPreferences(t)}catch(e){l=null}if(l){let o,s=null;try{s=w(l)}catch(e){r(`User ${t} has no usable preferences document directory for privateTypeIndex.`)}try{const r=e.any(t,a.solid("privateTypeIndex"),void 0,n);o=r||(s?await i.followOrCreateLinkWithContentOnCreate(t,a.solid("privateTypeIndex"),s,l,an()):null)}catch(e){r(`User ${t} has no pointer in preference file to privateTypeIndex file: ${e}`)}h=o?[{label:"private",index:o,agent:t}]:[]}else h=[];const u=d.concat(h);if(0===u.length)return u;const f=u.map(e=>e.index);try{await e.fetcher.load(f)}catch(e){r("Problems loading type index: ",e)}return u}async function d(t){let n;try{n=await o.silencedLoadPreferences(t)}catch(e){r(`User ${t} has no pointer in profile to preferences file.`)}if(n){const o=e.each(t,a.solid("community"),void 0,n).concat(e.each(t,a.solid("community"),void 0,t.doc()));let i=[];for(const e of o)if("NamedNode"===e.termType&&s(e.uri))try{i=i.concat(await c(e))}catch(t){r(`Skipping community type indexes for ${e.uri}: ${t}`)}else r(`Skipping malformed community node for ${t}: ${e}`);return i}return[]}async function l(e){return(await c(e)).concat(await d(e))}async function h(e,t){const r=await l(t);let n=[];for(const t of r){const r=await f(t,e);n=n.concat(r)}return n}function u(e){const r=e.doc(),n=r.dir();if((null==n?void 0:n.uri)&&s(n.uri))return n.uri;const o=r.uri;if(!o||!s(o))return t(`docDirUri: missing or non-http(s) doc uri for ${null==e?void 0:e.uri}`),null;const i=o.split("#")[0],a=i.lastIndexOf("/");return-1===a?(t(`docDirUri: no slash in doc uri ${o}`),null):i.slice(0,a+1)}function p(e){const t=u(e);if(!t)throw new Error(`suggestPublicTypeIndex: Cannot derive directory for ${e.uri}`);return(0,Nr.sym)(t+"publicTypeIndex.ttl")}function w(e){const t=u(e);if(!t)throw new Error(`suggestPrivateTypeIndex: Cannot derive directory for ${e.uri}`);return(0,Nr.sym)(t+"privateTypeIndex.ttl")}async function f(t,r){const n=t.index,o=[],i=e.statementsMatching(null,a.solid("instance"),null,n).concat(e.statementsMatching(null,a.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const s of i){const i=e.any(s,a.solid("forClass"),null,n);if(!r||i.sameTerm(r)){const r=e.each(s,a.solid("instance"),null,n);for(const e of r)o.push({instance:e,type:i,scope:t});const c=e.each(s,a.solid("instanceContainer"),null,n);for(const r of c)await e.fetcher.load(r),o.push({instance:(0,Nr.sym)(r.value),type:i,scope:t})}}return o}return{registerInTypeIndex:async function(t,r,n){const o=Vr(r),i=[(0,Nr.st)(o,a.rdf("type"),a.solid("TypeRegistration"),r),(0,Nr.st)(o,a.solid("forClass"),n,r),(0,Nr.st)(o,a.solid("instance"),t,r)];try{await e.updater.update([],i)}catch(e){const n=`Unable to register ${t} in index ${r}: ${e}`;return console.warn(n),null}return o},getRegistrations:function(t,r){return e.each(void 0,a.solid("instance"),t).filter(t=>e.holds(t,a.solid("forClass"),r))},loadTypeIndexesFor:c,loadCommunityTypeIndexes:d,loadAllTypeIndexes:l,getScopedAppInstances:h,getAppInstances:async function(e){const t=n.currentUser();if(!t)throw new Error("getAppInstances: Must be logged in to find apps.");return(await h(e,t)).map(e=>e.instance)},suggestPublicTypeIndex:p,suggestPrivateTypeIndex:w,deleteTypeIndexRegistration:async function(t){const r=e.the(null,a.solid("instance"),t.instance,t.scope.index);if(!r)throw new Error(`deleteTypeIndexRegistration: No registration found for ${t.instance}`);const n=e.statementsMatching(r,null,null,t.scope.index);await e.updater.update(n,[])},getScopedAppsFromIndex:f}}function hn(e,n){t("SolidLogic: Unique instance created. There should only be one of these.");const o=Nr.graph();Nr.fetcher(o,{fetch:e.fetch}),o.updater=new Nr.UpdateManager(o),o.features=[];const i=new Fr(n),a=Lr(o),s=cn(o),c=function(e,n,o){async function i(t){var r,n,o,i,a;try{return await e.fetcher.load(t)}catch(s){if(404===(null===(r=null==s?void 0:s.response)||void 0===r?void 0:r.status)){try{await e.fetcher.webOperation("PUT",t.uri,{data:"",contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(e){if(412!==(null!==(o=null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status)&&void 0!==o?o:null==e?void 0:e.status))throw new rn(`createIfNotExists: PUT FAILED: ${t}: ${e}`)}return await e.fetcher.load(t)}if(401===(null===(i=null==s?void 0:s.response)||void 0===i?void 0:i.status))throw new Yr;if(403===(null===(a=null==s?void 0:s.response)||void 0===a?void 0:a.status)){if(Br(t))throw new Zr;throw new Qr}const c=`createIfNotExists doc load error: ${t}: ${s}`;throw new nn(null==s?void 0:s.status,`${(null==s?void 0:s.message)||""}${c}`)}}async function a(t,r){var n,o,i,a;try{return await e.fetcher.load(t),!1}catch(e){if(404!==(null!==(o=null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status)&&void 0!==o?o:null==e?void 0:e.status))throw e}try{return await e.fetcher.webOperation("PUT",t.uri,{data:r,contentType:"text/turtle",headers:{"If-None-Match":"*"}}),!0}catch(e){if(412===(null!==(a=null===(i=null==e?void 0:e.response)||void 0===i?void 0:i.status)&&void 0!==a?a:null==e?void 0:e.status))return!1;throw e}}return{recursiveDelete:async function r(i){try{if(o.isContainer(i)){const t=await n.findAclDocUrl(i);await e.fetcher._fetch(t,{method:"DELETE"});const a=await o.getContainerMembers(i);await Promise.all(a.map(e=>r(e)))}return e.fetcher._fetch(i.value,{method:"DELETE"})}catch(e){t(`Please manually remove ${i.value} from your system.`,e)}},setSinglePeerAccess:async function(t){let r=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#alice> a acl:Authorization;\n acl:agent <"+t.ownerWebId+">;",` acl:accessTo <${t.target}>;`,` acl:default <${t.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");t.accessToModes&&(r+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:accessTo <${t.target}>;`,` acl:mode ${t.accessToModes}.`,""].join("\n")),t.defaultModes&&(r+=["<#bobDefault> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:default <${t.target}>;`,` acl:mode ${t.defaultModes}.`,""].join("\n"));const o=await n.findAclDocUrl((0,Nr.sym)(t.target));return e.fetcher._fetch(o,{method:"PUT",body:r,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(t,r){await e.fetcher.webOperation("PUT",t.uri,{data:`# ${new Date} ${r}\n`,contentType:"text/turtle"})},followOrCreateLink:async function(t,n,o,a){await e.fetcher.load(a);const s=e.any(t,n,null,a);if(s)return s;if(!e.updater.editable(a)){const e=`followOrCreateLink: cannot edit ${a.value}`;throw r(e),new tn(e)}try{await e.updater.update([],[(0,Nr.st)(t,n,o,a)])}catch(e){throw r(`followOrCreateLink: Error making link in ${a} to ${o}: ${e}`),new rn(e)}try{await i(o)}catch(e){throw r(`followOrCreateLink: Error loading or saving new linked document: ${o}: ${e}`),e}return o},followOrCreateLinkWithContentOnCreate:async function(t,n,o,i,s){await e.fetcher.load(i);const c=e.any(t,n,null,i);if(c)return c;if(!e.updater.editable(i)){const e=`followOrCreateLinkWithContentOnCreate: cannot edit ${i.value}`;throw r(e),new tn(e)}try{await e.updater.update([],[(0,Nr.st)(t,n,o,i)])}catch(e){const t=`followOrCreateLinkWithContentOnCreate: Error making link in ${i} to ${o}: ${e}`;throw r(t),new rn(t)}try{await a(o,s)}catch(e){throw r(`followOrCreateLinkWithContentOnCreate: Error loading or saving new linked document: ${o}: ${e}`),e}return o},loadOrCreateIfNotExists:i,loadOrCreateWithContentOnCreate:a}}(o,a,s),d=dn(o,i,c),l=qr(o,d),h=zr(o,d,c,s),u=ln(o,i,d,c);return t("SolidAuthnLogic initialized"),{store:o,authn:i,acl:a,inbox:h,chat:l,profile:d,typeIndex:u,load:function(e){return o.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((r,n)=>{o.updater.update(e,t,function(e,t,o){t?r():n(new Error(o))})})},clearStore:function(){o.statements.slice().forEach(o.remove.bind(o))}}}const un=async(e,t)=>{var r;const n=t&&t.credentials&&"omit"==t.credentials,o=$r;if(((null===(r=null==o?void 0:o.info)||void 0===r?void 0:r.webId)||(null==o?void 0:o.webId))&&!n){const r="function"==typeof o.fetch?o.fetch.bind(o):"function"==typeof o.authFetch?o.authFetch.bind(o):null;return r?r(e,t):window.fetch(e,t)}return window.fetch(e,t)},pn=Symbol.for("solid-logic-singleton"),wn="undefined"!=typeof window?window:n.g;const fn=(wn[pn]?t("SolidLogic: Using existing global singleton instance."):(t("SolidLogic: Creating new global singleton instance."),wn[pn]=hn({fetch:un},$r),t("Unique quadstore initialized.")),wn[pn]);async function yn(e={}){if("undefined"==typeof window)return!1;const t=e.issuer||"",r=e.postLogoutRedirectPath||"/";try{if(t){const e=new URL(t);e.pathname="/.well-known/openid-configuration";const r=await fetch(e.toString(),{credentials:"include"});if(200===r.status){const e=await r.json();e&&e.end_session_endpoint&&await fetch(e.end_session_endpoint,{credentials:"include"})}}}catch(e){}try{const e=await fetch("/.well-known/solid/logout",{credentials:"include"});if(e.ok||e.redirected)return window.location.assign(r),!0}catch(e){}return!1}const mn=[{name:"Solid Community",uri:"https://solidcommunity.net"},{name:"Solid Web",uri:"https://solidweb.org"},{name:"Solid Web ME",uri:"https://solidweb.me"},{name:"Inrupt.com",uri:"https://login.inrupt.com"}];function gn(){const e=[...mn],{host:t,origin:r}=new URL(location.href);return e.map(({uri:e})=>new URL(e).host).includes(t)||e.unshift({name:t,uri:r}),e}const vn=fn.authn,bn=fn.authn.authSession,En=fn.store})(),o})());
2
2
  //# sourceMappingURL=solid-logic.min.js.map