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.
- package/README.md +3 -1
- package/dist/2729812e0bfc062ee77a.js +1 -0
- package/dist/a9c30b64ceaae48b72f0.js +2045 -0
- package/dist/authSession/authSession.d.ts +41 -2
- package/dist/authSession/authSession.d.ts.map +1 -1
- package/dist/authSession/events.d.ts +24 -0
- package/dist/authSession/events.d.ts.map +1 -0
- package/dist/authSession/issuer.d.ts +8 -0
- package/dist/authSession/issuer.d.ts.map +1 -0
- package/dist/authSession/session.d.ts +45 -0
- package/dist/authSession/session.d.ts.map +1 -0
- package/dist/authn/SolidAuthnLogic.d.ts +15 -6
- package/dist/authn/SolidAuthnLogic.d.ts.map +1 -1
- package/dist/authn/serverLogout.d.ts +6 -0
- package/dist/authn/serverLogout.d.ts.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/logic/solidLogic.d.ts +3 -3
- package/dist/logic/solidLogic.d.ts.map +1 -1
- package/dist/logic/solidLogicSingleton.d.ts.map +1 -1
- package/dist/solid-logic.esm.js +492 -9622
- package/dist/solid-logic.esm.js.map +1 -1
- package/dist/solid-logic.esm.min.js +1 -1
- package/dist/solid-logic.esm.min.js.map +1 -1
- package/dist/solid-logic.js +4082 -8082
- package/dist/solid-logic.js.map +1 -1
- package/dist/solid-logic.min.js +1 -1
- package/dist/solid-logic.min.js.map +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +13 -10
- package/dist/acl/aclLogic.js +0 -117
- package/dist/acl/aclLogic.js.map +0 -1
- package/dist/authSession/authSession.js +0 -3
- package/dist/authSession/authSession.js.map +0 -1
- package/dist/authn/SolidAuthnLogic.js +0 -109
- package/dist/authn/SolidAuthnLogic.js.map +0 -1
- package/dist/authn/authUtil.js +0 -64
- package/dist/authn/authUtil.js.map +0 -1
- package/dist/chat/chatLogic.js +0 -157
- package/dist/chat/chatLogic.js.map +0 -1
- package/dist/inbox/inboxLogic.js +0 -51
- package/dist/inbox/inboxLogic.js.map +0 -1
- package/dist/index.js +0 -14
- package/dist/index.js.map +0 -1
- package/dist/issuer/issuerLogic.js +0 -37
- package/dist/issuer/issuerLogic.js.map +0 -1
- package/dist/logic/CustomError.js +0 -27
- package/dist/logic/CustomError.js.map +0 -1
- package/dist/logic/solidLogic.js +0 -64
- package/dist/logic/solidLogic.js.map +0 -1
- package/dist/logic/solidLogicSingleton.js +0 -31
- package/dist/logic/solidLogicSingleton.js.map +0 -1
- package/dist/profile/profileAclDocuments.js +0 -13
- package/dist/profile/profileAclDocuments.js.map +0 -1
- package/dist/profile/profileDocuments.js +0 -11
- package/dist/profile/profileDocuments.js.map +0 -1
- package/dist/profile/profileLogic.js +0 -344
- package/dist/profile/profileLogic.js.map +0 -1
- package/dist/typeIndex/typeIndexAclDocuments.js +0 -31
- package/dist/typeIndex/typeIndexAclDocuments.js.map +0 -1
- package/dist/typeIndex/typeIndexDocuments.js +0 -17
- package/dist/typeIndex/typeIndexDocuments.js.map +0 -1
- package/dist/typeIndex/typeIndexLogic.js +0 -248
- package/dist/typeIndex/typeIndexLogic.js.map +0 -1
- package/dist/types.js +0 -2
- package/dist/types.js.map +0 -1
- package/dist/util/containerLogic.js +0 -49
- package/dist/util/containerLogic.js.map +0 -1
- package/dist/util/debug.js +0 -13
- package/dist/util/debug.js.map +0 -1
- package/dist/util/ns.js +0 -5
- package/dist/util/ns.js.map +0 -1
- package/dist/util/utilityLogic.js +0 -201
- package/dist/util/utilityLogic.js.map +0 -1
- package/dist/util/utils.js +0 -39
- package/dist/util/utils.js.map +0 -1
- package/dist/versionInfo.js +0 -36
- package/dist/versionInfo.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as e from"rdflib";var t={7(e){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}}},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}function i(...e){console.log(...e)}function s(...e){console.warn(...e)}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);const o=new TextEncoder,a=new TextDecoder;function c(...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 d=e=>(e=>{let t=e;"string"==typeof t&&(t=o.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,"_"),l=e=>{let t=e;t instanceof Uint8Array&&(t=a.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 u extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}u.code="ERR_JOSE_GENERIC";class h extends u{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}}h.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class p extends u{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}}p.code="ERR_JWT_EXPIRED";class g extends u{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}g.code="ERR_JOSE_ALG_NOT_ALLOWED";class f extends u{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}f.code="ERR_JOSE_NOT_SUPPORTED";(class extends u{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends u{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class w extends u{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}w.code="ERR_JWS_INVALID";class y extends u{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}y.code="ERR_JWT_INVALID";(class extends u{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";class m extends u{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}m.code="ERR_JWKS_INVALID";class _ extends u{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}_.code="ERR_JWKS_NO_MATCHING_KEY";class v extends u{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,v.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class S extends u{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}S.code="ERR_JWKS_TIMEOUT";class b extends u{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function k(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 f(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}b.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const E=crypto,I=e=>e instanceof CryptoKey,T=(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 A(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function U(e,t){return e.name===t}function P(e){return parseInt(e.name.slice(4),10)}function C(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 x(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!U(e.algorithm,"HMAC"))throw A("HMAC");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw A(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!U(e.algorithm,"RSASSA-PKCS1-v1_5"))throw A("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw A(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!U(e.algorithm,"RSA-PSS"))throw A("RSA-PSS");const r=parseInt(t.slice(2),10);if(P(e.algorithm.hash)!==r)throw A(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw A("Ed25519 or Ed448");break;case"Ed25519":if(!U(e.algorithm,"Ed25519"))throw A("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!U(e.algorithm,"ECDSA"))throw A("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 A(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}C(e,r)}function R(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(T,"name")||{}).writable||Object.defineProperty(T,"name",{value:"default",configurable:!0});const $=(e,...t)=>R("Key must be ",e,...t);function O(e,t,...r){return R(`Key for the ${e} algorithm must be `,t,...r)}(Object.getOwnPropertyDescriptor($,"name")||{}).writable||Object.defineProperty($,"name",{value:"default",configurable:!0});const L=e=>!!I(e)||"KeyObject"===e?.[Symbol.toStringTag];(Object.getOwnPropertyDescriptor(L,"name")||{}).writable||Object.defineProperty(L,"name",{value:"default",configurable:!0});const H=["CryptoKey"];function D(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 N(e){return D(e)&&"string"==typeof e.kty}const 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 f('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 f('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 f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new f('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,E.subtle.importKey("jwk",i,...n)},K=e=>l(e);let W,J;const M=e=>"KeyObject"===e?.[Symbol.toStringTag],F=async(e,t,r,n,i=!1)=>{let s=e.get(t);if(s?.[n])return s[n];const o=await j({...r,alg:n});return i&&Object.freeze(t),s?s[n]=o:e.set(t,{[n]:o}),o},q=(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?K(r.k):(J||(J=new WeakMap),F(J,e,r,t))}if(N(e)){if(e.k)return l(e.k);J||(J=new WeakMap);return F(J,e,e,t,!0)}return e},z=(e,t)=>{if(M(e)){let r=e.export({format:"jwk"});return r.k?K(r.k):(W||(W=new WeakMap),F(W,e,r,t))}if(N(e)){if(e.k)return l(e.k);W||(W=new WeakMap);return F(W,e,e,t,!0)}return e};async function V(e,t,r){if("sign"===r&&(t=await z(t,e)),"verify"===r&&(t=await q(t,e)),I(t))return x(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError($(t,...H));return E.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError($(t,...H,"Uint8Array","JSON Web Key"))}const B=async(e,t,r,n)=>{const i=await V(e,t,"verify");T(e,i);const s=k(e,i.algorithm);try{return await E.subtle.verify(s,i,r,n)}catch{return!1}},G=(...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},Q=e=>e?.[Symbol.toStringTag],X=(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},Y=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&N(t)){if(function(e){return N(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&X(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(!L(t))throw new TypeError(O(e,t,...H,"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 Z(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Y(t,r,n,e):((e,t,r,n)=>{if(n&&N(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&X(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)&&X(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!L(t))throw new TypeError(O(e,t,...H,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)}Z.bind(void 0,!1);const ee=Z.bind(void 0,!0);const te=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 f(`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)},re=(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 ne(e,t){if(!D(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 l(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new f('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return j({...e,alg:t});default:throw new f('Unsupported "kty" (Key Type) Parameter value')}}async function ie(e,t,r){if(e instanceof Uint8Array&&(e=a.decode(e)),"string"!=typeof e)throw new w("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:s,length:d}=e.split(".");if(3!==d)throw new w("Invalid Compact JWS");const u=await async function(e,t,r){if(!D(e))throw new w("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new w('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new w("JWS Protected Header incorrect type");if(void 0===e.payload)throw new w("JWS Payload missing");if("string"!=typeof e.signature)throw new w("JWS Signature missing or incorrect type");if(void 0!==e.header&&!D(e.header))throw new w("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=l(e.protected);n=JSON.parse(a.decode(t))}catch{throw new w("JWS Protected Header is invalid")}if(!G(n,e.header))throw new w("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header};let s=!0;if(te(w,new Map([["b64",!0]]),r?.crit,n,i).has("b64")&&(s=n.b64,"boolean"!=typeof s))throw new w('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:d}=i;if("string"!=typeof d||!d)throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');const u=r&&re("algorithms",r.algorithms);if(u&&!u.has(d))throw new g('"alg" (Algorithm) Header Parameter value not allowed');if(s){if("string"!=typeof e.payload)throw new w("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new w("JWS Payload must be a string or an Uint8Array instance");let h=!1;"function"==typeof t?(t=await t(n,e),h=!0,ee(d,t,"verify"),N(t)&&(t=await ne(t,d))):ee(d,t,"verify");const p=c(o.encode(e.protected??""),o.encode("."),"string"==typeof e.payload?o.encode(e.payload):e.payload);let f,y;try{f=l(e.signature)}catch{throw new w("Failed to base64url decode the signature")}if(!await B(d,t,f,p))throw new b;if(s)try{y=l(e.payload)}catch{throw new w("Failed to base64url decode the payload")}else y="string"==typeof e.payload?o.encode(e.payload):e.payload;const m={payload:y};return void 0!==e.protected&&(m.protectedHeader=n),void 0!==e.header&&(m.unprotectedHeader=e.header),h?{...m,key:t}:m}({payload:i,protected:n,signature:s},t,r),h={payload:u.payload,protectedHeader:u.protectedHeader};return"function"==typeof t?{...h,key:u.key}:h}const se=e=>Math.floor(e.getTime()/1e3);(Object.getOwnPropertyDescriptor(se,"name")||{}).writable||Object.defineProperty(se,"name",{value:"default",configurable:!0});const oe=86400,ae=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ce=e=>{const t=ae.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*oe);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(ce,"name")||{}).writable||Object.defineProperty(ce,"name",{value:"default",configurable:!0});const de=e=>e.toLowerCase().replace(/^application\//,""),le=(e,t,r={})=>{let n;try{n=JSON.parse(a.decode(t))}catch{}if(!D(n))throw new y("JWT Claims Set must be a top-level JSON object");const{typ:i}=r;if(i&&("string"!=typeof e.typ||de(e.typ)!==de(i)))throw new h('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:s=[],issuer:o,subject:c,audience:d,maxTokenAge:l}=r,u=[...s];void 0!==l&&u.push("iat"),void 0!==d&&u.push("aud"),void 0!==c&&u.push("sub"),void 0!==o&&u.push("iss");for(const e of new Set(u.reverse()))if(!(e in n))throw new h(`missing required "${e}" claim`,n,e,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new h('unexpected "iss" claim value',n,"iss","check_failed");if(c&&n.sub!==c)throw new h('unexpected "sub" claim value',n,"sub","check_failed");if(d&&(g=n.aud,f="string"==typeof d?[d]:d,!("string"==typeof g?f.includes(g):Array.isArray(g)&&f.some(Set.prototype.has.bind(new Set(g))))))throw new h('unexpected "aud" claim value',n,"aud","check_failed");var g,f;let w;switch(typeof r.clockTolerance){case"string":w=ce(r.clockTolerance);break;case"number":w=r.clockTolerance;break;case"undefined":w=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,_=se(m||new Date);if((void 0!==n.iat||l)&&"number"!=typeof n.iat)throw new h('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new h('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>_+w)throw new h('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new h('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=_-w)throw new p('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){const e=_-n.iat;if(e-w>("number"==typeof l?l:ce(l)))throw new p('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-w)throw new h('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};(Object.getOwnPropertyDescriptor(le,"name")||{}).writable||Object.defineProperty(le,"name",{value:"default",configurable:!0});const ue=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 S;throw e});if(void 0!==i&&clearTimeout(i),200!==o.status)throw new u("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new u("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function he(e){return D(e)}function pe(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class ge{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(he)}(e))throw new m("JSON Web Key Set malformed");this._jwks=pe(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 f('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 _;if(1!==a){const e=new v,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of s)try{yield await fe(t,e,r)}catch{}},e}return fe(this._cached,o,r)}}async function fe(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await ne({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new m("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function we(e){const t=new ge(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>pe(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}let ye;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){ye=`${"jose"}/${"v5.10.0"}`}const me=Symbol();class _e{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?.[me]&&(this._cache=t?.[me],r=t?.[me],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&D(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,D)&&(this._jwksTimestamp=this._cache.uat,this._local=we(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 _&&!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);ye&&!e.has("User-Agent")&&(e.set("User-Agent",ye),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ue(this._url,this._timeoutDuration,this._options).then(e=>{this._local=we(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 ve=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:d(e)};if(!I(e))throw new TypeError($(e,...H,"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 E.subtle.exportKey("jwk",e);return s};async function Se(e){return ve(e)}const be=async(e,t,r)=>{const n=await V(e,t,"sign");T(e,n);const i=await E.subtle.sign(k(e,n.algorithm),n,r);return new Uint8Array(i)};class ke{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new w("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!G(this._protectedHeader,this._unprotectedHeader))throw new w("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(te(w,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new w('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');ee(i,e,"sign");let s,l=this._payload;n&&(l=o.encode(d(l))),s=this._protectedHeader?o.encode(d(JSON.stringify(this._protectedHeader))):o.encode("");const u=c(s,o.encode("."),l),h=await be(i,e,u),p={signature:d(h),payload:""};return n&&(p.payload=a.decode(l)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=a.decode(s)),p}}class Ee{constructor(e){this._flattened=new ke(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function Ie(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Te{constructor(e={}){if(!D(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:Ie("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:Ie("setNotBefore",se(e))}:this._payload={...this._payload,nbf:se(new Date)+ce(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:Ie("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:Ie("setExpirationTime",se(e))}:this._payload={...this._payload,exp:se(new Date)+ce(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:se(new Date)}:e instanceof Date?this._payload={...this._payload,iat:Ie("setIssuedAt",se(e))}:this._payload="string"==typeof e?{...this._payload,iat:Ie("setIssuedAt",se(new Date)+ce(e))}:{...this._payload,iat:Ie("setIssuedAt",e)},this}}class Ae extends Te{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new Ee(o.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 y("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}function Ue(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new f("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function Pe(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:Ue(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:Ue(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:Ue(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 f("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 f("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return E.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const Ce={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let xe;const Re=new Uint8Array(16);const $e=[];for(let e=0;e<256;++e)$e.push((e+256).toString(16).slice(1));function Oe(e,t=0){return($e[e[t+0]]+$e[e[t+1]]+$e[e[t+2]]+$e[e[t+3]]+"-"+$e[e[t+4]]+$e[e[t+5]]+"-"+$e[e[t+6]]+$e[e[t+7]]+"-"+$e[e[t+8]]+$e[e[t+9]]+"-"+$e[e[t+10]]+$e[e[t+11]]+$e[e[t+12]]+$e[e[t+13]]+$e[e[t+14]]+$e[e[t+15]]).toLowerCase()}const Le=function(e,t,r){if(Ce.randomUUID&&!t&&!e)return Ce.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!xe){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");xe=crypto.getRandomValues.bind(crypto)}return xe(Re)}();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 Oe(n)},He="solidClientAuthn:",De=["ES256","RS256"],Ne="error",je="login",Ke="logout",We="newRefreshToken",Je="sessionExpired",Me="sessionExtended",Fe="sessionRestore",qe="timeoutSet",ze=["openid","offline_access","webid"];class Ve{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 Be(e,t,r,n){let i,s;try{const{payload:s}=await async function(e,t,r){const n=await ie(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new y("JWTs MUST NOT use unencoded payload");const i={payload:le(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}(e,function(e,t){const r=new _e(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 Ge(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 Qe(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 Xe{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 Ye{sessionInfoManager;constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class Ze{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 et{handlers;constructor(e,t){this.handlers=[new Ye(e),new Ze(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 tt(){return{isLoggedIn:!1,sessionId:Le(),fetch:(...e)=>fetch(...e)}}async function rt(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}class nt{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 rt(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 it({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 st(e){try{return new URL(e),!0}catch{return!1}}async function ot(e,t,r,n){let i;if(function(e,t){return t.scopesSupported.includes("webid")&&void 0!==e.clientId&&st(e.clientId)}(e,t))i={clientId:e.clientId,clientName:e.clientName,clientType:"solid-oidc"};else{if(!function(e){return void 0!==e.clientId&&!st(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 at=(e,t)=>fetch(e,t);class ct{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=at;logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===t?.logoutType?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=at,delete this.boundLogout};getSessionInfo=async e=>this.sessionInfoManager.get(e);getAllSessionInfo=async()=>this.sessionInfoManager.getAll()}async function dt(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 lt{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 ut{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 ht extends Error{constructor(e){super(e)}}Error;class pt extends Error{missingFields;constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class gt extends Error{error;errorDescription;constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function ft(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function wt(e,t,r){return new Ae({htu:ft(e),htm:t.toUpperCase(),jti:Le()}).setProtectedHeader({alg:De[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function yt(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 wt(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 mt(e,t,r,n,i=fetch){return i(t,await yt(t.toString(),e,n,r))}const _t=e=>void 0!==e?e-5>0?e-5:e:600;function vt(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(Me,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*_t(c)),t.eventEmitter?.emit(qe,r)}catch(e){e instanceof gt&&(s?.emit(Ne,e.error,e.errorDescription),s?.emit(Je)),e instanceof pt&&e.missingFields.includes("access_token")&&s?.emit(Je)}};r=setTimeout(e,1e3*_t(t.expiresIn)),s?.emit(qe,r)}else if(void 0!==s){const e=setTimeout(()=>{s.emit(Je)},1e3*_t(t?.expiresIn));s.emit(qe,e)}return async(e,r)=>{let i=await mt(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 mt(n,i.url,r,t.dpopKey,t.fetch)),i}}var St=n(7);class bt extends Error{}function kt(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)}}bt.prototype.name="InvalidTokenError";var Et,It,Tt,At={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},Ut=(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))(Ut||{});(Tt=Ut||(Ut={})).reset=function(){Et=3,It=At},Tt.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");Et=e},Tt.setLogger=function(e){It=e};var Pt=class e{constructor(e){this._name=e}debug(...t){Et>=4&&It.debug(e._format(this._name,this._method),...t)}info(...t){Et>=3&&It.info(e._format(this._name,this._method),...t)}warn(...t){Et>=2&&It.warn(e._format(this._name,this._method),...t)}error(...t){Et>=1&&It.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){Et>=4&&It.debug(e._format(t),...r)}static info(t,...r){Et>=3&&It.info(e._format(t),...r)}static warn(t,...r){Et>=2&&It.warn(e._format(t),...r)}static error(t,...r){Et>=1&&It.error(e._format(t),...r)}};Ut.reset();var Ct=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new bt("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 bt(`Invalid token specified: missing part #${r+1}`);let i;try{i=kt(n)}catch(e){throw new bt(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new bt(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}(e)}catch(e){throw Pt.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,r){const n=`${$t.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${$t.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}.${$t.encodeBase64Url(new Uint8Array(i))}`}static async generateSignedJwtWithHmac(e,t,r){const n=`${$t.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${$t.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign("HMAC",r,(new TextEncoder).encode(n));return`${n}.${$t.encodeBase64Url(new Uint8Array(i))}`}},xt=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),Rt=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 xt(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw Pt.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return xt(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 Ct.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 Ct.generateSignedJwtWithHmac(o,a,l)}};Rt.encodeBase64Url=e=>xt(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var $t=Rt,Ot=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new Pt(`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)}},Lt=class e extends Ot{constructor(){super(...arguments),this._logger=new Pt(`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)}},Ht=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))}},Dt=";",Nt=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 Pt.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}},jt=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},Kt=class{constructor(){this._logger=new Pt("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]}},Wt=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},Jt=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new Pt("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 jt("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 Nt(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 Wt(e,`${JSON.stringify(u)}`)}if(u.error)throw new Nt(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)})}},Mt=class{constructor(e){this._settings=e,this._logger=new Pt("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new Jt(["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}},Ft=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new Pt("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}},qt=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:C={},extraTokenParams:x={},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 Kt;this.stateStore=new Ft({store:e})}if(this.refreshTokenAllowedScope=P,this.extraQueryParams=C,this.extraTokenParams=x,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")}},zt=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Pt("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=Ct.decode(e);return t.debug("JWT decoding successful"),r}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new Jt(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}},Vt=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Pt("TokenClient"),this._jsonService=new Jt(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=$t.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 $t.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=$t.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 $t.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=$t.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 $t.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")}},Bt=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new Pt("ResponseValidator"),this._userInfoService=new zt(this._settings,this._metadataService),this._tokenClient=new Vt(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 Nt(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 Nt(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=Ct.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=Ct.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}},Gt=class e{constructor(e){this.id=e.id||$t.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=Lt.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Pt("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 Pt.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,r){const n=Pt.createStatic("State","clearStaleState"),i=Lt.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))}}},Qt=class e extends Gt{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?$t.generateCodeVerifier():t.code_verifier||void 0,n=r?await $t.generateCodeChallenge(r):void 0;return new e({...t,code_verifier:r,code_challenge:n})}toStorageString(){return new Pt("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){Pt.createStatic("SigninState","fromStorageString");const r=JSON.parse(t);return e.create(r)}},Xt=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 Qt.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}${Dt}${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})}};Xt._logger=new Pt("SigninRequest");var Yt=Xt,Zt=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(Dt);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Dt))}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-Lt.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+Lt.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},er=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 Pt("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 Gt({data:t,request_type:s,url_state:a});let e=this.state.id;a&&(e=`${e}${Dt}${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}},tr=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(Dt);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Dt))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},rr=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],nr=["sub","iss","aud","exp","iat"],ir=class{constructor(e){this._settings=e,this._logger=new Pt("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:rr;for(const r of e)nr.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}},sr=class{constructor(e,t){this.keys=e,this.nonce=t}},or=class{constructor(e,t){this._logger=new Pt("OidcClient"),this.settings=e instanceof qt?e:new qt(e),this.metadataService=null!=t?t:new Mt(this.settings),this._claimsService=new ir(this.settings),this._validator=new Bt(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Vt(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 Yt.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 Zt(Ht.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 Qt.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 Wt&&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 $t.generateDPoPKeys(),n=new sr(r,t),await e.set(this.settings.client_id,n)),await $t.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 Zt(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 Wt&&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 Zt(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 er({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 tr(Ht.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 Nt(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 Gt.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"),Gt.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 ar(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 cr(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,De.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 ar(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 dr(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function lr(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new gt(`Token endpoint returned error [${e.error}]${dr(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,dr(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 pt(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new pt(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new pt(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new pt(["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 ur(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 Pe(De[0],{extractable:!0}),r={privateKey:e,publicKey:await Se(t)};return[r.publicKey.alg]=De,r}(),i.DPoP=await wt(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=lr(await c.json(),n),{webId:l,clientId:u}=await Be(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 hr(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 wt(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=lr(c,void 0!==n),{webId:l}=await Be(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 pr extends lt{constructor(e,t){super(e,t)}}class gr extends ct{login=async(e,t)=>{"none"!==e.prompt&&await this.sessionInfoManager.clear(e.sessionId);const r=e.redirectUrl??function(e){const t=Qe(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}(window.location.href);if(!Ge(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(Ne,"redirect",r)}};async cleanUrlAfterRedirect(e){const t=Qe(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(e=>{setTimeout(()=>e(),1)})}}function fr(e){return"string"==typeof e.oidcIssuer}function wr(e){return"string"==typeof e.redirectUrl}class yr{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 fr(e)&&wr(e)}async handle(e){if(!fr(e))throw new ht(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!wr(e))throw new ht(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await ot(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([...ze,...i.filter(e=>"string"==typeof e&&!e.includes(" "))])):ze)};var i;return this.oidcHandler.handle(n)}}class mr extends Xe{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 or(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 _r={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 vr{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=>{_r[r]&&(t[_r[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await n.json())}catch(t){throw new ht(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(vr.getLocalStorageKey(e),JSON.stringify(t)),t}}async function Sr(e,t){await rt(e,t),await async function(){const e=new Ft({});await Gt.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 br extends nt{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||Ge(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 Sr(e,this.storageUtility)}}class kr{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 tt()}}class Er{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 dt(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 ur(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=vt(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 Se(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:it({idTokenHint:h.idToken,endSessionEndpoint:s.endSessionEndpoint}),expirationDate:"number"==typeof h.expiresIn?u+1e3*h.expiresIn:void 0})}}class Ir extends Ve{constructor(e){super(e)}}class Tr{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 Ar{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class Ur{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 cr(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 Pr{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(Ne,n,i)}return tt()}}class Cr{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 dt(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 hr(t,i.issuerConfig,s,r);return void 0!==o.refreshToken&&n?.emit(We,o.refreshToken),o}}function xr(e){const t=new ut,r=e.secureStorage||t,n=e.insecureStorage||new Tr,i=new pr(r,n),s=new vr(i),o=new Ur(i),a=new br(i),c=new Cr(i,s,o),d=new Ar,l=new yr(i,new mr(i,d),s,o),u=new Ir([new Pr,new Er(i,a,s,o,c),new kr]);return new gr(l,u,new et(a,d),a,s)}const Rr=`${He}currentSession`,$r=`${He}currentUrl`;class Or{info;events;clientAuthentication;tokenRequestInProgress=!1;constructor(e={},t=void 0){this.events=new St,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=xr({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=xr({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??Le(),isLoggedIn:!1},this.events.on(je,()=>window.localStorage.setItem(Rr,this.info.sessionId)),this.events.on(Je,()=>this.internalLogout(!1)),this.events.on(Ne,()=>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(Rr),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(Ke)};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($r);null===e?this.events.emit(je):(window.localStorage.removeItem($r),this.events.emit(Fe,e))}else if(!0===t.restorePreviousSession){const e=window.localStorage.getItem(Rr);if(null!==e){if(await async function(e,t,r){const n=await t.validateCurrentSession(e);return null!==n&&(window.localStorage.setItem($r,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(Me,e=>{this.info.expirationDate=Date.now()+1e3*e})}}const Lr=new Or,Hr=e;var Dr=n(386);const Nr=n.n(Dr)()(Hr),jr=(0,Hr.sym)("http://www.iana.org/assignments/link-relations/acl");function Kr(e){const t=Nr;function r(e,r,n,i={}){const s=i.public||[],o=(0,Hr.graph)(),a=(0,Hr.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,Hr.serialize)(d,o,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,i){const s=e.any(e.sym(t),jr);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),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(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 Wr=()=>{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 Jr(){const{$SolidTestEnvironment:e}=window;if(void 0!==e&&e.username)return i("Assuming the user is "+e.username),(0,Hr.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 t=e.getAttribute("testID");return t?(i("Assuming user is "+t),(0,Hr.sym)(t)):null}return null}class Mr{constructor(e){this.session=e}get authSession(){return this.session}currentUser(){const e=Wr();return e.viewingNoAuthPage?(0,Hr.sym)(e.webId):this&&this.session&&this.session.info&&this.session.info.webId&&this.session.info.isLoggedIn?(0,Hr.sym)(this.session.info.webId):Jr()}async checkUser(e){const t=new URL(window.location.href).hash;t&&window.localStorage.setItem("preLoginRedirectHash",t),this.session.events.on(Fe,e=>{i(`Session restored to ${e}`),document.location.toString()!==e&&history.replaceState(null,"",e)});const r=new URL(window.location.href);r.hash="",await this.session.handleIncomingRedirect({restorePreviousSession:!0,url:r.href});const n=window.localStorage.getItem("preLoginRedirectHash");if(n){const e=new URL(window.location.href);e.hash!==n&&(history.pushState?history.pushState(null,document.title,n):location.hash=n,e.hash=n),window.localStorage.setItem("preLoginRedirectHash","")}let s=Jr();if(s)return Promise.resolve(e?e(s):s);const o=this.webIdFromSession(this.session.info);return o&&(s=this.saveUser(o)),s&&i(`(Logged in as ${s} by authentication)`),Promise.resolve(e?e(s):s)}saveUser(e,t){let r;if(e){r="string"==typeof e?e:e.uri;const n=(0,Hr.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 Fr(e){return(0,Hr.sym)(e.uri+"#id"+Date.now())}function qr(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const zr="index.ttl#this";function Vr(e,t){const r=Nr;async function n(t,r,n){await e.fetcher.load(t);const i=e.any(t,new Hr.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=Fr(i),o=[(0,Hr.st)(s,r.rdf("type"),r.solid("TypeRegistration"),i.doc()),(0,Hr.st)(s,r.solid("forClass"),r.meeting("LongChat"),i.doc()),(0,Hr.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 Hr.NamedNode(r)}(r,await t.getPodRoot(n));let s=!0;try{await e.fetcher.load(new Hr.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+zr),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,Hr.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 Hr.NamedNode(a.value+zr);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 Br(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 Gr extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class Qr extends Gr{}class Xr extends Gr{}class Yr extends Gr{}class Zr extends Gr{}class en extends Gr{}class tn extends Gr{}class rn extends Gr{constructor(e,t){super(t),this.status=e}}function nn(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:ListedDocument."].join("\n")}function sn(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:UnlistedDocument."].join("\n")}function on(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 an(e){function t(t){return e.statementsMatching(t,(0,Hr.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,Hr.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 cn(e,t,r){const n=Nr,i=an(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,Hr.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 s=d(r);if(!s)throw new Error(`Cannot derive settings directory from ${r.uri}`);await async function(t){const r=(0,Hr.sym)(t);try{return void await e.fetcher.load(r)}catch(e){if(!u(e))throw e}await i.createContainer(t)}(s);const o=(0,Hr.sym)(s);let a;try{await e.fetcher.load(o),a=null===(n=e.any(o,jr))||void 0===n?void 0:n.value}catch(e){if(!u(e))throw e}a||(a=`${s}.acl`);const c=(0,Hr.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,i){const s=i.doc(),o=t.doc();await e.fetcher.load(s);const a=e.any(t,n.solid("publicTypeIndex"),null,o),c=e.any(t,n.solid("publicTypeIndex"),null,s),d=a||c||l(i,"publicTypeIndex.ttl"),h=e.any(t,n.solid("privateTypeIndex"),null,s)||l(i,"privateTypeIndex.ttl"),p=!a;p&&await r.followOrCreateLinkWithContentOnCreate(t,n.solid("publicTypeIndex"),d,o,nn());const g=[];e.holds(s,n.rdf("type"),n.space("ConfigurationFile"),s)||g.push((0,Hr.st)(s,n.rdf("type"),n.space("ConfigurationFile"),s)),e.holds(s,n.dct("title"),void 0,s)||g.push((0,Hr.st)(s,n.dct("title"),(0,Hr.literal)("Preferences file"),s)),e.holds(t,n.solid("publicTypeIndex"),d,s)||g.push((0,Hr.st)(t,n.solid("publicTypeIndex"),d,s)),e.holds(t,n.solid("privateTypeIndex"),h,s)||g.push((0,Hr.st)(t,n.solid("privateTypeIndex"),h,s)),g.length>0&&(await e.updater.update([],g),await e.fetcher.load(s)),await async function(t,n,i=!1){var s,o,a;if(!await r.loadOrCreateWithContentOnCreate(n,nn())&&!i)return;let c;try{await e.fetcher.load(n),c=null===(s=e.any(n,jr))||void 0===s?void 0:s.value}catch(e){if(!u(e))throw e}c||(c=`${n.uri}.acl`);const d=(0,Hr.sym)(c);try{await e.fetcher.webOperation("PUT",d.uri,{data:on(t.uri,n.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 r.loadOrCreateWithContentOnCreate(e,sn())}(h)}async function g(e){var t,n;try{return!!await r.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(r){if(401===(null===(t=r.response)||void 0===t?void 0:t.status))throw new Qr;if(403===(null===(n=r.response)||void 0===n?void 0:n.status)){if(qr(e))throw new Xr;throw new Yr}throw r}}async function f(t){const i=a.get(t.uri);if(i)return i;const c=o.get(t.uri);if(c)return c;const d=(async()=>{var i;await w(t);const o=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/settings/prefs.ttl";return(0,Hr.sym)(t)}(t);let c;try{const i=e.any(t,n.space("preferencesFile"),null,t.doc());c=i||await r.followOrCreateLink(t,n.space("preferencesFile"),o,t.doc()),await h(t,c),await g(c),await p(t,c)}catch(e){if(s(`User ${t} has no pointer in profile to preferences file.`),e instanceof en)throw e;if(e instanceof tn)throw e;if(e instanceof Qr)throw e;if(e instanceof Xr)throw e;if(e instanceof Yr)throw e;if(e instanceof rn)throw e;throw e}try{await e.fetcher.load(c)}catch(r){const n=`Unable to load preference of user ${t}: ${r}`;if(404===(null===(i=r.response)||void 0===i?void 0:i.status))return await h(t,c),await g(c),await p(t,c),await e.fetcher.load(c),c;if(s(n),401===r.response.status)throw new Qr;if(403===r.response.status){if(qr(c))throw new Xr;throw new Yr}throw new Error(n)}return a.set(t.uri,c),c})();o.set(t.uri,d);try{return await d}finally{o.get(t.uri)===d&&o.delete(t.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,n.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=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,n.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 dn(e,t,r,n){const o=Nr;function a(e){return!!e&&(e.startsWith("https://")||e.startsWith("http://"))}async function c(t){if(!t)throw new Error("loadTypeIndexesFor: No user given");const i=await r.loadProfile(t);let a,c=null;try{c=p(t)}catch(e){s(`User ${t} has no usable profile document directory for publicTypeIndex.`)}try{const r=e.any(t,o.solid("publicTypeIndex"),void 0,i);a=r||(c?await n.followOrCreateLinkWithContentOnCreate(t,o.solid("publicTypeIndex"),c,i,nn()):null)}catch(e){s(`User ${t} has no pointer in profile to publicTypeIndex file: ${e}`)}const d=a?[{label:"public",index:a,agent:t}]:[];let l,u;try{l=await r.silencedLoadPreferences(t)}catch(e){l=null}if(l){let r,a=null;try{a=g(l)}catch(e){s(`User ${t} has no usable preferences document directory for privateTypeIndex.`)}try{const s=e.any(t,o.solid("privateTypeIndex"),void 0,i);r=s||(a?await n.followOrCreateLinkWithContentOnCreate(t,o.solid("privateTypeIndex"),a,l,sn()):null)}catch(e){s(`User ${t} has no pointer in preference file to privateTypeIndex file: ${e}`)}u=r?[{label:"private",index:r,agent:t}]:[]}else u=[];const h=d.concat(u);if(0===h.length)return h;const f=h.map(e=>e.index);try{await e.fetcher.load(f)}catch(e){s("Problems loading type index: ",e)}return h}async function d(t){let n;try{n=await r.silencedLoadPreferences(t)}catch(e){s(`User ${t} has no pointer in profile to preferences file.`)}if(n){const r=e.each(t,o.solid("community"),void 0,n).concat(e.each(t,o.solid("community"),void 0,t.doc()));let i=[];for(const e of r)if("NamedNode"===e.termType&&a(e.uri))try{i=i.concat(await c(e))}catch(t){s(`Skipping community type indexes for ${e.uri}: ${t}`)}else s(`Skipping malformed community node for ${t}: ${e}`);return i}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(e){const t=e.doc(),r=t.dir();if((null==r?void 0:r.uri)&&a(r.uri))return r.uri;const n=t.uri;if(!n||!a(n))return i(`docDirUri: missing or non-http(s) doc uri for ${null==e?void 0:e.uri}`),null;const s=n.split("#")[0],o=s.lastIndexOf("/");return-1===o?(i(`docDirUri: no slash in doc uri ${n}`),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,Hr.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,Hr.sym)(t+"privateTypeIndex.ttl")}async function f(t,r){const n=t.index,i=[],s=e.statementsMatching(null,o.solid("instance"),null,n).concat(e.statementsMatching(null,o.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const a of s){const s=e.any(a,o.solid("forClass"),null,n);if(!r||s.sameTerm(r)){const r=e.each(a,o.solid("instance"),null,n);for(const e of r)i.push({instance:e,type:s,scope:t});const c=e.each(a,o.solid("instanceContainer"),null,n);for(const r of c)await e.fetcher.load(r),i.push({instance:(0,Hr.sym)(r.value),type:s,scope:t})}}return i}return{registerInTypeIndex:async function(t,r,n){const i=Fr(r),s=[(0,Hr.st)(i,o.rdf("type"),o.solid("TypeRegistration"),r),(0,Hr.st)(i,o.solid("forClass"),n,r),(0,Hr.st)(i,o.solid("instance"),t,r)];try{await e.updater.update([],s)}catch(e){const n=`Unable to register ${t} in index ${r}: ${e}`;return console.warn(n),null}return i},getRegistrations:function(t,r){return e.each(void 0,o.solid("instance"),t).filter(t=>e.holds(t,o.solid("forClass"),r))},loadTypeIndexesFor:c,loadCommunityTypeIndexes:d,loadAllTypeIndexes:l,getScopedAppInstances:u,getAppInstances:async function(e){const r=t.currentUser();if(!r)throw new Error("getAppInstances: Must be logged in to find apps.");return(await u(e,r)).map(e=>e.instance)},suggestPublicTypeIndex:p,suggestPrivateTypeIndex:g,deleteTypeIndexRegistration:async function(t){const r=e.the(null,o.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 ln(e,t){i("SolidLogic: Unique instance created. There should only be one of these.");const r=Hr.graph();Hr.fetcher(r,{fetch:e.fetch}),r.updater=new Hr.UpdateManager(r),r.features=[];const n=new Mr(t),o=Kr(r),a=an(r),c=function(e,t,r){async function n(t){var r,n,i,s,o;try{return await e.fetcher.load(t)}catch(a){if(404===(null===(r=null==a?void 0:a.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!==(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 new tn(`createIfNotExists: PUT FAILED: ${t}: ${e}`)}return await e.fetcher.load(t)}if(401===(null===(s=null==a?void 0:a.response)||void 0===s?void 0:s.status))throw new Qr;if(403===(null===(o=null==a?void 0:a.response)||void 0===o?void 0:o.status)){if(qr(t))throw new Xr;throw new Yr}const c=`createIfNotExists doc load error: ${t}: ${a}`;throw new rn(null==a?void 0:a.status,`${(null==a?void 0:a.message)||""}${c}`)}}async function o(t,r){var n,i,s,o;try{return await e.fetcher.load(t),!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 e.fetcher.webOperation("PUT",t.uri,{data:r,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 n(s){try{if(r.isContainer(s)){const i=await t.findAclDocUrl(s);await e.fetcher._fetch(i,{method:"DELETE"});const o=await r.getContainerMembers(s);await Promise.all(o.map(e=>n(e)))}return e.fetcher._fetch(s.value,{method:"DELETE"})}catch(e){i(`Please manually remove ${s.value} from your system.`,e)}},setSinglePeerAccess:async function(r){let n=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#alice> a acl:Authorization;\n acl:agent <"+r.ownerWebId+">;",` acl:accessTo <${r.target}>;`,` acl:default <${r.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");r.accessToModes&&(n+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${r.peerWebId}>;`,` acl:accessTo <${r.target}>;`,` acl:mode ${r.accessToModes}.`,""].join("\n")),r.defaultModes&&(n+=["<#bobDefault> a acl:Authorization;",` acl:agent <${r.peerWebId}>;`,` acl:default <${r.target}>;`,` acl:mode ${r.defaultModes}.`,""].join("\n"));const i=await t.findAclDocUrl((0,Hr.sym)(r.target));return e.fetcher._fetch(i,{method:"PUT",body:n,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,r,i,o){await e.fetcher.load(o);const a=e.any(t,r,null,o);if(a)return a;if(!e.updater.editable(o)){const e=`followOrCreateLink: cannot edit ${o.value}`;throw s(e),new en(e)}try{await e.updater.update([],[(0,Hr.st)(t,r,i,o)])}catch(e){throw s(`followOrCreateLink: Error making link in ${o} to ${i}: ${e}`),new tn(e)}try{await n(i)}catch(e){throw s(`followOrCreateLink: Error loading or saving new linked document: ${i}: ${e}`),e}return i},followOrCreateLinkWithContentOnCreate:async function(t,r,n,i,a){await e.fetcher.load(i);const c=e.any(t,r,null,i);if(c)return c;if(!e.updater.editable(i)){const e=`followOrCreateLinkWithContentOnCreate: cannot edit ${i.value}`;throw s(e),new en(e)}try{await e.updater.update([],[(0,Hr.st)(t,r,n,i)])}catch(e){const t=`followOrCreateLinkWithContentOnCreate: Error making link in ${i} to ${n}: ${e}`;throw s(t),new tn(t)}try{await o(n,a)}catch(e){throw s(`followOrCreateLinkWithContentOnCreate: Error loading or saving new linked document: ${n}: ${e}`),e}return n},loadOrCreateIfNotExists:n,loadOrCreateWithContentOnCreate:o}}(r,o,a),d=cn(r,n,c),l=Vr(r,d),u=Br(r,d,c,a),h=dn(r,n,d,c);return i("SolidAuthnLogic initialized"),{store:r,authn:n,acl:o,inbox:u,chat:l,profile:d,typeIndex:h,load:function(e){return r.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((n,i)=>{r.updater.update(e,t,function(e,t,r){t?n():i(new Error(r))})})},clearStore:function(){r.statements.slice().forEach(r.remove.bind(r))}}}const un=async(e,t)=>{const r=t&&t.credentials&&"omit"==t.credentials;return Lr.info.webId&&!r?Lr.fetch(e,t):window.fetch(e,t)},hn=Symbol.for("solid-logic-singleton"),pn="undefined"!=typeof window?window:n.g;const gn=(pn[hn]?i("SolidLogic: Using existing global singleton instance."):(i("SolidLogic: Creating new global singleton instance."),pn[hn]=ln({fetch:un},Lr),i("Unique quadstore initialized.")),pn[hn]),fn=[{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 wn(){const e=[...fn],{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 yn=gn.authn,mn=gn.authn.authSession,_n=gn.store;export{jr as ACL_LINK,Xr as CrossOriginForbiddenError,rn as FetchError,en as NotEditableError,Zr as NotFoundError,Yr as SameOriginForbiddenError,Qr as UnauthorizedError,tn as WebOperationError,Wr as appContext,mn as authSession,yn as authn,dn as createTypeIndexLogic,wn as getSuggestedIssuers,Jr as offlineTestID,gn as solidLogicSingleton,_n as store};
|
|
1
|
+
import{Session as t}from"@uvdsl/solid-oidc-client-browser";import*as e from"@uvdsl/solid-oidc-client-browser/core";import*as n from"rdflib";var o={386(t){const e={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#"};t.exports=function(t={namedNode:t=>t}){const n={};for(const o in e){const r=e[o];n[o]=function(e=""){return t.namedNode(r+e)}}return n}}},r={};function i(t){var e=r[t];if(void 0!==e)return e.exports;var n=r[t]={exports:{}};return o[t](n,n.exports,i),n.exports}function a(...t){console.log(...t)}function s(...t){console.warn(...t)}i.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return i.d(e,{a:e}),e},i.d=(t,e)=>{for(var n in e)i.o(e,n)&&!i.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);const c=e;class l{constructor(){this.map=new Map}shouldPreserveExistingRefreshToken(t,e){return"refresh_token"===t&&(null==e||""===e)&&this.map.has(t)}async init(){return this}async setItem(t,e){this.shouldPreserveExistingRefreshToken(t,e)||this.map.set(t,e)}async getItem(t){return this.map.has(t)?this.map.get(t):null}async deleteItem(t){this.map.delete(t)}async clear(){this.map.clear()}close(){}}class d{constructor(){this.db=null,this.dbName="soidc",this.storeName="session",this.dbVersion=1}async shouldPreserveExistingRefreshToken(t,e){if("refresh_token"!==t||null!=e&&""!==e)return!1;const n=await this.getItem(t);return null!=n&&""!==n}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((t,e)=>{const n=indexedDB.open(this.dbName,this.dbVersion);n.onerror=()=>e(n.error),n.onsuccess=()=>{this.db=n.result,t()},n.onupgradeneeded=()=>{const t=n.result;t.objectStoreNames.contains(this.storeName)||t.createObjectStore(this.storeName)}}),this}async setItem(t,e){await this.init(),await this.shouldPreserveExistingRefreshToken(t,e)||await this.withStore("readwrite",n=>n.put(e,t))}async getItem(t){return await this.init(),this.withStore("readonly",e=>e.get(t))}async deleteItem(t){await this.init(),await this.withStore("readwrite",e=>e.delete(t))}async clear(){await this.init(),await this.withStore("readwrite",t=>t.clear())}close(){this.db&&(this.db.close(),this.db=null)}withStore(t,e){return new Promise((n,o)=>{if(!this.db)return void o(new Error("Session database not initialized"));const r=this.db.transaction(this.storeName,t),i=r.objectStore(this.storeName),a=e(i);let s=null;r.onerror=()=>{var t;return o(null!==(t=r.error)&&void 0!==t?t:a.error)},r.onabort=()=>{var t,e;return o(null!==(e=null!==(t=r.error)&&void 0!==t?t:a.error)&&void 0!==e?e:new Error("IndexedDB transaction aborted"))},r.oncomplete=()=>n(s),a.onerror=()=>o(a.error),a.onsuccess=()=>{var t;s=null!==(t=a.result)&&void 0!==t?t:null}})}}const u=function(){var t,e,n;const o=c,r=null!==(n=null!==(t=o.SessionCore)&&void 0!==t?t:null===(e=o.default)||void 0===e?void 0:e.SessionCore)&&void 0!==n?n:o.default;return"function"!=typeof r?null:r}();const w=function(){if("undefined"!=typeof window&&(()=>{const t=window.location.hostname;return"localhost"===t||"127.0.0.1"===t||t.endsWith(".localhost")})())return u?new u(void 0,{database:new d}):new t;try{return new t}catch(e){console.warn("solid-logic: falling back to non-worker auth session:",e);try{return u?new u(void 0,{database:new d}):new t}catch(e){return console.warn("solid-logic: IndexedDB unavailable, using in-memory session database:",e),u?new u(void 0,{database:new l}):new t}}}();async function h(t){const e=await async function(t){try{const e=new URL(t),n=new URL("/.well-known/openid-configuration",e.origin),o=await fetch(n.toString(),{credentials:"include"});if(!o.ok)return null;const r=await o.json();return"string"==typeof(null==r?void 0:r.issuer)&&r.issuer?r.issuer.replace(/\/$/,""):null}catch(t){return null}}(t);return e||t}var f;const p=w,g="function"==typeof p.login?p.login.bind(w):void 0;if(g){const t=async(t,e)=>{var n,o,r,i;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=null!==(o=null!==(n=t.oidcIssuer)&&void 0!==n?n:t.idp)&&void 0!==o?o:t.issuer,a=null!==(i=null!==(r=t.redirectUrl)&&void 0!==r?r:t.redirect_uri)&&void 0!==i?i:t.redirectUri;if("string"==typeof e&&"string"==typeof a)return g(await h(e),a)}return g("string"==typeof t?await h(t):t,e)};p.login=t}const y=new class{constructor(){this.listeners=new Map}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e)}off(t,e){var n;null===(n=this.listeners.get(t))||void 0===n||n.delete(e)}emit(t,...e){var n;null===(n=this.listeners.get(t))||void 0===n||n.forEach(t=>t(...e))}};let v=null!==(f=w.isActive)&&void 0!==f?f:Boolean(w.webId);"function"==typeof w.addEventListener&&w.addEventListener("sessionStateChange",()=>{var t;const e=null!==(t=w.isActive)&&void 0!==t?t:Boolean(w.webId);v&&!e&&y.emit("logout"),v=e});const m=Object.assign(w,{events:y}),b=n;var x=i(386);const I=i.n(x)()(b),C=(0,b.sym)("http://www.iana.org/assignments/link-relations/acl");function T(t){const e=I;function n(t,n,o,r={}){const i=r.public||[],a=(0,b.graph)(),s=(0,b.Namespace)("http://www.w3.org/ns/auth/acl#");let c=a.sym(`${o}#a1`);const l=a.sym(o),d=a.sym(t);if(a.add(c,e.rdf("type"),s("Authorization"),l),a.add(c,s("accessTo"),d,l),r.defaultForNew&&a.add(c,s("default"),d,l),a.add(c,s("agent"),n,l),a.add(c,s("mode"),s("Read"),l),a.add(c,s("mode"),s("Write"),l),a.add(c,s("mode"),s("Control"),l),i.length){c=a.sym(`${o}#a2`),a.add(c,e.rdf("type"),s("Authorization"),l),a.add(c,s("accessTo"),d,l),a.add(c,s("agentClass"),e.foaf("Agent"),l);for(let t=0;t<i.length;t++)a.add(c,s("mode"),s(i[t]),l)}return(0,b.serialize)(l,a,o)}return{findAclDocUrl:async function(e){await t.fetcher.load(e);const n=t.any(e,C);if(!n)throw new Error(`No ACL link discovered for ${e}`);return n.value},setACLUserPublic:function(e,o,r){const i=t.any(t.sym(e),C);return Promise.resolve().then(()=>i||function(e){const n=t.fetcher;if(!n)throw new Error("Cannot fetch ACL rel, store has no fetcher");return n.load(e).then(n=>{if(!n.ok)throw new Error("fetchACLRel: While loading:"+n.error);const o=t.any(t.sym(e),C);if(!o)throw new Error("fetchACLRel: No Link rel=ACL header for "+e);return o})}(e).catch(t=>{throw new Error(`Error fetching rel=ACL header for ${e}: ${t}`)})).then(i=>{const a=n(e,o,i.uri,r);if(!t.fetcher)throw new Error("Cannot PUT this, store has no fetcher");return t.fetcher.webOperation("PUT",i.uri,{data:a,contentType:"text/turtle"}).then(t=>{if(!t.ok)throw new Error("Error writing ACL text: "+t.error);return i})})},genACLText:n}}const $=()=>{let{SolidAppContext:t}=window;if(t||(t={}),t.viewingNoAuthPage=!1,t.noAuth&&window.document){if(window.document.location.href.startsWith(t.noAuth)){t.viewingNoAuthPage=!0;const e=new URLSearchParams(window.document.location.search);if(e){let n=t.viewedPage=e.get("uri")||null;if(n&&(n=decodeURI(n),!n.startsWith(t.noAuth))){const e=n.split(/\//);t.idp=e[0]+"//"+e[2],t.viewingNoAuthPage=!1}}}}return t};function U(){const{$SolidTestEnvironment:t}=window;if(void 0!==t&&t.username)return a("Assuming the user is "+t.username),(0,b.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 e=t.getAttribute("testID");return e?(a("Assuming user is "+e),(0,b.sym)(e)):null}return null}class k{constructor(t){this.checkUserInFlight=null,this.sessionRestoreHookAttached=!1,this.fallbackWebId=null,this.session=t}get authSession(){return this.session}currentUser(){var t,e;const n=$();if(n.viewingNoAuthPage)return(0,b.sym)(n.webId);const o=this.session,r=null===(t=null==o?void 0:o.info)||void 0===t?void 0:t.webId,i=null==o?void 0:o.webId,a=r||i||this.fallbackWebId,s=null===(e=null==o?void 0:o.info)||void 0===e?void 0:e.isLoggedIn,c=null==o?void 0:o.isActive,l=!0===s||!0===c||null==s&&null==c&&Boolean(a)||Boolean(this.fallbackWebId);return this&&this.session&&a&&l?(0,b.sym)(a):U()}async checkUser(t){var e;const n=new URL(window.location.href).hash;n&&window.localStorage.setItem("preLoginRedirectHash",n);const o=this.session;this.sessionRestoreHookAttached||"function"!=typeof(null===(e=null==o?void 0:o.events)||void 0===e?void 0:e.on)||(o.events.on("sessionRestore",t=>{a(`Session restored to ${t}`),document.location.toString()!==t&&history.replaceState(null,"",t)}),this.sessionRestoreHookAttached=!0),this.checkUserInFlight||(this.checkUserInFlight=this.resolveCurrentUser());const r=this.checkUserInFlight;let i;try{i=await r}finally{this.checkUserInFlight===r&&(this.checkUserInFlight=null)}return Promise.resolve(t?t(i):i)}async resolveCurrentUser(){var t,e,n,o,r,i;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!==(t=null==s?void 0:s.isActive)&&void 0!==t?t:Boolean(null==s?void 0:s.webId);try{await s.restore()}catch(t){const e=t instanceof Error?t.message:String(t);if(!/no session to restore/i.test(e))throw t;a("No previous session to restore")}const r=null!==(e=null==s?void 0:s.isActive)&&void 0!==e?e:Boolean(null==s?void 0:s.webId);!o&&r&&(null===(n=s.events)||void 0===n||n.emit("sessionRestore",window.location.href))}if("function"==typeof(null==s?void 0:s.handleRedirectFromLogin)){const t=null!==(o=null==s?void 0:s.isActive)&&void 0!==o?o:Boolean(null==s?void 0:s.webId);await s.handleRedirectFromLogin();const e=null!==(r=null==s?void 0:s.isActive)&&void 0!==r?r:Boolean(null==s?void 0:s.webId);!t&&e&&(null===(i=s.events)||void 0===i||i.emit("login"))}}const l=window.localStorage.getItem("preLoginRedirectHash");if(l){const t=new URL(window.location.href);t.hash!==l&&(history.pushState?history.pushState(null,document.title,l):location.hash=l,t.hash=l),window.localStorage.setItem("preLoginRedirectHash","")}let d=U();if(d)return d;let u=this.webIdFromSession(null==s?void 0:s.info,s);return u||(u=await this.probeNssCookieBackedWebId()),this.fallbackWebId=u||null,u&&(d=this.saveUser(u)),d&&a(`(Logged in as ${d} by authentication)`),d}async probeNssCookieBackedWebId(){if("undefined"==typeof window)return null;const{hostname:t,port:e,protocol:n}=window.location,o=".localhost";if(!t.endsWith(o))return null;const r=t.slice(0,-10);if(!r||"localhost"===r||r.includes("."))return null;try{if(403!==(await fetch("/account/password/change",{credentials:"include",redirect:"manual",cache:"no-store"})).status)return null;return`${`${n}//${t}${e?`:${e}`:""}`}/profile/card#me`}catch(t){return null}}saveUser(t,e){let n;if(t){n="string"==typeof t?t:t.uri;const o=(0,b.namedNode)(n);return e&&(e.me=o),o}return null}webIdFromSession(t,e){const n=(null==t?void 0:t.webId)||(null==e?void 0:e.webId);if(!n)return null;const o=null==t?void 0:t.isLoggedIn,r=null==e?void 0:e.isLoggedIn,i=null==e?void 0:e.isActive;return!0===o||!0===r||!0===i?n:!1===o&&!1===r&&!1===i?null:n}}function E(t){return(0,b.sym)(t.uri+"#id"+Date.now())}function L(t){return!t||`${window.location.origin}/`!==new URL(t.value).origin}const A="index.ttl#this";function P(t,e){const n=I;async function o(e,n,o){await t.fetcher.load(e);const r=t.any(e,new b.NamedNode("http://www.iana.org/assignments/link-relations/acl"));if(!r)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 <${n.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 <${o.value}>;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Append.\n `;await t.fetcher.webOperation("PUT",r.value,{data:i,contentType:"text/turtle"})}async function r(e,o){const r=t.any(o,n.solid("privateTypeIndex"));if(!r)throw new Error("Private type index not found!");await t.fetcher.load(r);const i=E(r),a=[(0,b.st)(i,n.rdf("type"),n.solid("TypeRegistration"),r.doc()),(0,b.st)(i,n.solid("forClass"),n.meeting("LongChat"),r.doc()),(0,b.st)(i,n.solid("instance"),e,r.doc())];await new Promise((e,n)=>{t.updater.update([],a,function(t,o,r){o?e(null):n(new Error(r))})})}async function i(n){const o=await e.loadMe(),r=function(t,e){const n=new URL(`IndividualChats/${new URL(t.value).host}/`,e.value).toString();return new b.NamedNode(n)}(n,await e.getPodRoot(o));let i=!0;try{await t.fetcher.load(new b.NamedNode(r.value+"index.ttl#this"))}catch(t){i=!1}return{me:o,chatContainer:r,exists:i}}async function a(t,e){return(await s({me:e,newBase:t.value})).newInstance}function s(e){const o=t,r=o.updater;if(e.me&&!e.me.uri)throw new Error("chat mintNew: Invalid userid "+e.me);const i=e.newInstance=e.newInstance||o.sym(e.newBase+A),a=i.doc();return o.add(i,n.rdf("type"),n.meeting("LongChat"),a),o.add(i,n.dc("title"),"Chat channel",a),o.add(i,n.dc("created"),(0,b.term)(new Date(Date.now())),a),e.me&&o.add(i,n.dc("author"),e.me,a),new Promise(function(t,n){null==r||r.put(a,o.statementsMatching(void 0,void 0,void 0,a),"text/turtle",function(o,r,a){r?t({...e,newInstance:i}):n(new Error("FAILED to save new chat channel at: "+o+" : "+a))})})}async function c(e,o){var r;await t.fetcher.load(e.doc());const i=t.any(e,n.ldp("inbox"),void 0,e.doc());if(!i)throw new Error(`Invitee inbox not found! ${e.value}`);const a=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${n.rdf("seeAlso")} <${o.value}> .\n `,s=await(null===(r=t.fetcher)||void 0===r?void 0:r.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:o,addToPrivateTypeIndex:r,findChat:i,createChatThing:a,getChat:async function(t,e=!0){const{me:n,chatContainer:s,exists:l}=await i(t);if(l)return new b.NamedNode(s.value+A);if(e){const e=await a(s,n);return await c(t,e),await o(s,n,t),await r(e,n),e}return null},sendInvite:c,mintNew:s}}function S(t,e,n,o,r){return{createInboxFor:async function(t,r){const i=await e.loadMe(),a=`${(await e.getPodRoot(i)).value}p2p-inboxes/${encodeURIComponent(r)}/`;return await o.createContainer(a),await n.setSinglePeerAccess({ownerWebId:i.value,peerWebId:t,accessToModes:"acl:Append",target:a}),a},getNewMessages:async function(t){t||(t=await e.loadMe());const n=await e.getMainInbox(t);return(await o.getContainerMembers(n)).filter(t=>!o.isContainer(t))},markAsRead:async function(e,n){const o=await t.fetcher._fetch(e);if(200!==o.status)throw new Error(`Not OK! ${e}`);const r=function(t,e){const n=e.getUTCFullYear(),o=("0"+(e.getUTCMonth()+1)).slice(-2),r=("0"+e.getUTCDate()).slice(-2),i=t.split("/"),a=i[i.length-1];return new URL(`./archive/${n}/${o}/${r}/${a}`,t).toString()}(e,n),i={method:"PUT",body:await o.text(),headers:[["Content-Type",o.headers.get("Content-Type")||"application/octet-stream"]]};"2"===(await t.fetcher._fetch(r,i)).status.toString()[0]&&await t.fetcher._fetch(e,{method:"DELETE"})}}}class R extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class N extends R{}class O extends R{}class W extends R{}class M extends R{}class F extends R{}class D extends R{}class j extends R{constructor(t,e){super(e),this.status=t}}function B(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:ListedDocument."].join("\n")}function _(){return["@prefix solid: <http://www.w3.org/ns/solid/terms#>.","<>"," a solid:TypeIndex ;"," a solid:UnlistedDocument."].join("\n")}function z(t,e){const n=new URL(e).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",` <${t}>;`,"",` acl:accessTo <./${n}>;`,""," acl:mode"," acl:Read, acl:Write, acl:Control.","","# Public-readable","<#public>"," a acl:Authorization;",""," acl:agentClass foaf:Agent;","",` acl:accessTo <./${n}>;`,""," acl:mode acl:Read."].join("\n")}function H(t){function e(e){return t.statementsMatching(e,(0,b.sym)("http://www.w3.org/ns/ldp#contains"),void 0).map(t=>t.object)}function n(t){const e=t.value;return"/"===e.charAt(e.length-1)}return{isContainer:n,createContainer:async function(e){if(!n((0,b.sym)(e)))throw new Error(`Not a container URL ${e}`);const o=await t.fetcher._fetch(e,{method:"PUT",headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:'<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'},body:" "});if(409!==o.status&&"2"!==o.status.toString()[0])throw new Error(`Not OK: got ${o.status} response while creating container at ${e}`)},getContainerElements:e,getContainerMembers:async function(n){return await t.fetcher.load(n),e(n)}}}function q(t,e,n){const o=I,r=H(t),i=new Map,a=new Map;function c(t){return!!t&&(t.startsWith("https://")||t.startsWith("http://"))}function l(t){const e=t.doc(),n=e.dir();if((null==n?void 0:n.uri)&&c(n.uri))return n.uri;const o=e.uri;if(!o||!c(o))return null;const r=o.split("#")[0],i=r.lastIndexOf("/");return-1===i?null:r.slice(0,i+1)}function d(t,e){const n=l(t);if(!n)throw new Error(`Cannot derive directory for preferences file ${t.uri}`);return(0,b.sym)(n+e)}function u(t){var e;if(404===(null===(e=null==t?void 0:t.response)||void 0===e?void 0:e.status))return!0;const n=`${(null==t?void 0:t.message)||t||""}`;return n.includes("404")||n.includes("Not Found")}async function w(e,n){var o;const i=l(n);if(!i)throw new Error(`Cannot derive settings directory from ${n.uri}`);await async function(e){const n=(0,b.sym)(e);try{return void await t.fetcher.load(n)}catch(t){if(!u(t))throw t}await r.createContainer(e)}(i);const a=(0,b.sym)(i);let s;try{await t.fetcher.load(a),s=null===(o=t.any(a,C))||void 0===o?void 0:o.value}catch(t){if(!u(t))throw t}s||(s=`${i}.acl`);const c=(0,b.sym)(s);try{return void await t.fetcher.load(c)}catch(t){if(!u(t))throw t}var d;await t.fetcher.webOperation("PUT",c.uri,{data:(d=e.uri,["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#owner>","a acl:Authorization;",`acl:agent <${d}>;`,"acl:accessTo <./>;","acl:default <./>;","acl:mode acl:Read, acl:Write, acl:Control."].join("\n")),contentType:"text/turtle"})}async function h(e,r){const i=r.doc(),a=e.doc();await t.fetcher.load(i);const s=t.any(e,o.solid("publicTypeIndex"),null,a),c=t.any(e,o.solid("publicTypeIndex"),null,i),l=s||c||d(r,"publicTypeIndex.ttl"),w=t.any(e,o.solid("privateTypeIndex"),null,i)||d(r,"privateTypeIndex.ttl"),h=!s;h&&await n.followOrCreateLinkWithContentOnCreate(e,o.solid("publicTypeIndex"),l,a,B());const f=[];t.holds(i,o.rdf("type"),o.space("ConfigurationFile"),i)||f.push((0,b.st)(i,o.rdf("type"),o.space("ConfigurationFile"),i)),t.holds(i,o.dct("title"),void 0,i)||f.push((0,b.st)(i,o.dct("title"),(0,b.literal)("Preferences file"),i)),t.holds(e,o.solid("publicTypeIndex"),l,i)||f.push((0,b.st)(e,o.solid("publicTypeIndex"),l,i)),t.holds(e,o.solid("privateTypeIndex"),w,i)||f.push((0,b.st)(e,o.solid("privateTypeIndex"),w,i)),f.length>0&&(await t.updater.update([],f),await t.fetcher.load(i)),await async function(e,o,r=!1){var i,a,s;if(!await n.loadOrCreateWithContentOnCreate(o,B())&&!r)return;let c;try{await t.fetcher.load(o),c=null===(i=t.any(o,C))||void 0===i?void 0:i.value}catch(t){if(!u(t))throw t}c||(c=`${o.uri}.acl`);const l=(0,b.sym)(c);try{await t.fetcher.webOperation("PUT",l.uri,{data:z(e.uri,o.uri),contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(t){if(412!==(null!==(s=null===(a=null==t?void 0:t.response)||void 0===a?void 0:a.status)&&void 0!==s?s:null==t?void 0:t.status))throw t}}(e,l,h),await async function(t){await n.loadOrCreateWithContentOnCreate(t,_())}(w)}async function f(t){var e,o;try{return!!await n.loadOrCreateWithContentOnCreate(t,["@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===(e=n.response)||void 0===e?void 0:e.status))throw new N;if(403===(null===(o=n.response)||void 0===o?void 0:o.status)){if(L(t))throw new O;throw new W}throw n}}async function p(e){const r=a.get(e.uri);if(r)return r;const c=i.get(e.uri);if(c)return c;const l=(async()=>{var r;await g(e);const i=function(t){const e=t.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/settings/prefs.ttl";return(0,b.sym)(e)}(e);let c;try{const r=t.any(e,o.space("preferencesFile"),null,e.doc());c=r||await n.followOrCreateLink(e,o.space("preferencesFile"),i,e.doc()),await w(e,c),await f(c),await h(e,c)}catch(t){if(s(`User ${e} has no pointer in profile to preferences file.`),t instanceof F)throw t;if(t instanceof D)throw t;if(t instanceof N)throw t;if(t instanceof O)throw t;if(t instanceof W)throw t;if(t instanceof j)throw t;throw t}try{await t.fetcher.load(c)}catch(n){const o=`Unable to load preference of user ${e}: ${n}`;if(404===(null===(r=n.response)||void 0===r?void 0:r.status))return await w(e,c),await f(c),await h(e,c),await t.fetcher.load(c),c;if(s(o),401===n.response.status)throw new N;if(403===n.response.status){if(L(c))throw new O;throw new W}throw new Error(o)}return a.set(e.uri,c),c})();i.set(e.uri,l);try{return await l}finally{i.get(e.uri)===l&&i.delete(e.uri)}}async function g(e){if(!e)throw new Error("loadProfile: no user given.");try{await t.fetcher.load(e.doc())}catch(t){throw new Error(`Unable to load profile of user ${e}: ${t}`)}return e.doc()}function y(e){return t.any(e,o.space("storage"),void 0,e.doc())}return{loadMe:async function(){const n=e.currentUser();if(null===n)throw new Error("Current user not found! Not logged in?");return await t.fetcher.load(n.doc()),n},getPodRoot:function(t){const e=y(t);if(!e)throw new Error("User pod root not found!");return e},getMainInbox:async function(e){await t.fetcher.load(e);const n=t.any(e,o.ldp("inbox"),void 0,e.doc());if(!n)throw new Error("User main inbox not found!");return n},findStorage:y,loadPreferences:p,loadProfile:g,silencedLoadPreferences:async function(t){try{return await p(t)}catch(t){return}}}}function K(t,e,n,o){const r=I;function i(t){return!!t&&(t.startsWith("https://")||t.startsWith("http://"))}async function c(e){if(!e)throw new Error("loadTypeIndexesFor: No user given");const i=await n.loadProfile(e);let a,c=null;try{c=h(e)}catch(t){s(`User ${e} has no usable profile document directory for publicTypeIndex.`)}try{const n=t.any(e,r.solid("publicTypeIndex"),void 0,i);a=n||(c?await o.followOrCreateLinkWithContentOnCreate(e,r.solid("publicTypeIndex"),c,i,B()):null)}catch(t){s(`User ${e} has no pointer in profile to publicTypeIndex file: ${t}`)}const l=a?[{label:"public",index:a,agent:e}]:[];let d,u;try{d=await n.silencedLoadPreferences(e)}catch(t){d=null}if(d){let n,a=null;try{a=f(d)}catch(t){s(`User ${e} has no usable preferences document directory for privateTypeIndex.`)}try{const s=t.any(e,r.solid("privateTypeIndex"),void 0,i);n=s||(a?await o.followOrCreateLinkWithContentOnCreate(e,r.solid("privateTypeIndex"),a,d,_()):null)}catch(t){s(`User ${e} has no pointer in preference file to privateTypeIndex file: ${t}`)}u=n?[{label:"private",index:n,agent:e}]:[]}else u=[];const w=l.concat(u);if(0===w.length)return w;const p=w.map(t=>t.index);try{await t.fetcher.load(p)}catch(t){s("Problems loading type index: ",t)}return w}async function l(e){let o;try{o=await n.silencedLoadPreferences(e)}catch(t){s(`User ${e} has no pointer in profile to preferences file.`)}if(o){const n=t.each(e,r.solid("community"),void 0,o).concat(t.each(e,r.solid("community"),void 0,e.doc()));let a=[];for(const t of n)if("NamedNode"===t.termType&&i(t.uri))try{a=a.concat(await c(t))}catch(e){s(`Skipping community type indexes for ${t.uri}: ${e}`)}else s(`Skipping malformed community node for ${e}: ${t}`);return a}return[]}async function d(t){return(await c(t)).concat(await l(t))}async function u(t,e){const n=await d(e);let o=[];for(const e of n){const n=await p(e,t);o=o.concat(n)}return o}function w(t){const e=t.doc(),n=e.dir();if((null==n?void 0:n.uri)&&i(n.uri))return n.uri;const o=e.uri;if(!o||!i(o))return a(`docDirUri: missing or non-http(s) doc uri for ${null==t?void 0:t.uri}`),null;const r=o.split("#")[0],s=r.lastIndexOf("/");return-1===s?(a(`docDirUri: no slash in doc uri ${o}`),null):r.slice(0,s+1)}function h(t){const e=w(t);if(!e)throw new Error(`suggestPublicTypeIndex: Cannot derive directory for ${t.uri}`);return(0,b.sym)(e+"publicTypeIndex.ttl")}function f(t){const e=w(t);if(!e)throw new Error(`suggestPrivateTypeIndex: Cannot derive directory for ${t.uri}`);return(0,b.sym)(e+"privateTypeIndex.ttl")}async function p(e,n){const o=e.index,i=[],a=t.statementsMatching(null,r.solid("instance"),null,o).concat(t.statementsMatching(null,r.solid("instanceContainer"),null,o)).map(t=>t.subject);for(const s of a){const a=t.any(s,r.solid("forClass"),null,o);if(!n||a.sameTerm(n)){const n=t.each(s,r.solid("instance"),null,o);for(const t of n)i.push({instance:t,type:a,scope:e});const c=t.each(s,r.solid("instanceContainer"),null,o);for(const n of c)await t.fetcher.load(n),i.push({instance:(0,b.sym)(n.value),type:a,scope:e})}}return i}return{registerInTypeIndex:async function(e,n,o){const i=E(n),a=[(0,b.st)(i,r.rdf("type"),r.solid("TypeRegistration"),n),(0,b.st)(i,r.solid("forClass"),o,n),(0,b.st)(i,r.solid("instance"),e,n)];try{await t.updater.update([],a)}catch(t){const o=`Unable to register ${e} in index ${n}: ${t}`;return console.warn(o),null}return i},getRegistrations:function(e,n){return t.each(void 0,r.solid("instance"),e).filter(e=>t.holds(e,r.solid("forClass"),n))},loadTypeIndexesFor:c,loadCommunityTypeIndexes:l,loadAllTypeIndexes:d,getScopedAppInstances:u,getAppInstances:async function(t){const n=e.currentUser();if(!n)throw new Error("getAppInstances: Must be logged in to find apps.");return(await u(t,n)).map(t=>t.instance)},suggestPublicTypeIndex:h,suggestPrivateTypeIndex:f,deleteTypeIndexRegistration:async function(e){const n=t.the(null,r.solid("instance"),e.instance,e.scope.index);if(!n)throw new Error(`deleteTypeIndexRegistration: No registration found for ${e.instance}`);const o=t.statementsMatching(n,null,null,e.scope.index);await t.updater.update(o,[])},getScopedAppsFromIndex:p}}function V(t,e){a("SolidLogic: Unique instance created. There should only be one of these.");const n=b.graph();b.fetcher(n,{fetch:t.fetch}),n.updater=new b.UpdateManager(n),n.features=[];const o=new k(e),r=T(n),i=H(n),c=function(t,e,n){async function o(e){var n,o,r,i,a;try{return await t.fetcher.load(e)}catch(s){if(404===(null===(n=null==s?void 0:s.response)||void 0===n?void 0:n.status)){try{await t.fetcher.webOperation("PUT",e.uri,{data:"",contentType:"text/turtle",headers:{"If-None-Match":"*"}})}catch(t){if(412!==(null!==(r=null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.status)&&void 0!==r?r:null==t?void 0:t.status))throw new D(`createIfNotExists: PUT FAILED: ${e}: ${t}`)}return await t.fetcher.load(e)}if(401===(null===(i=null==s?void 0:s.response)||void 0===i?void 0:i.status))throw new N;if(403===(null===(a=null==s?void 0:s.response)||void 0===a?void 0:a.status)){if(L(e))throw new O;throw new W}const c=`createIfNotExists doc load error: ${e}: ${s}`;throw new j(null==s?void 0:s.status,`${(null==s?void 0:s.message)||""}${c}`)}}async function r(e,n){var o,r,i,a;try{return await t.fetcher.load(e),!1}catch(t){if(404!==(null!==(r=null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.status)&&void 0!==r?r:null==t?void 0:t.status))throw t}try{return await t.fetcher.webOperation("PUT",e.uri,{data:n,contentType:"text/turtle",headers:{"If-None-Match":"*"}}),!0}catch(t){if(412===(null!==(a=null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.status)&&void 0!==a?a:null==t?void 0:t.status))return!1;throw t}}return{recursiveDelete:async function o(r){try{if(n.isContainer(r)){const i=await e.findAclDocUrl(r);await t.fetcher._fetch(i,{method:"DELETE"});const a=await n.getContainerMembers(r);await Promise.all(a.map(t=>o(t)))}return t.fetcher._fetch(r.value,{method:"DELETE"})}catch(t){a(`Please manually remove ${r.value} from your system.`,t)}},setSinglePeerAccess:async function(n){let o=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","","<#alice> a acl:Authorization;\n acl:agent <"+n.ownerWebId+">;",` acl:accessTo <${n.target}>;`,` acl:default <${n.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");n.accessToModes&&(o+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${n.peerWebId}>;`,` acl:accessTo <${n.target}>;`,` acl:mode ${n.accessToModes}.`,""].join("\n")),n.defaultModes&&(o+=["<#bobDefault> a acl:Authorization;",` acl:agent <${n.peerWebId}>;`,` acl:default <${n.target}>;`,` acl:mode ${n.defaultModes}.`,""].join("\n"));const r=await e.findAclDocUrl((0,b.sym)(n.target));return t.fetcher._fetch(r,{method:"PUT",body:o,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(e,n){await t.fetcher.webOperation("PUT",e.uri,{data:`# ${new Date} ${n}\n`,contentType:"text/turtle"})},followOrCreateLink:async function(e,n,r,i){await t.fetcher.load(i);const a=t.any(e,n,null,i);if(a)return a;if(!t.updater.editable(i)){const t=`followOrCreateLink: cannot edit ${i.value}`;throw s(t),new F(t)}try{await t.updater.update([],[(0,b.st)(e,n,r,i)])}catch(t){throw s(`followOrCreateLink: Error making link in ${i} to ${r}: ${t}`),new D(t)}try{await o(r)}catch(t){throw s(`followOrCreateLink: Error loading or saving new linked document: ${r}: ${t}`),t}return r},followOrCreateLinkWithContentOnCreate:async function(e,n,o,i,a){await t.fetcher.load(i);const c=t.any(e,n,null,i);if(c)return c;if(!t.updater.editable(i)){const t=`followOrCreateLinkWithContentOnCreate: cannot edit ${i.value}`;throw s(t),new F(t)}try{await t.updater.update([],[(0,b.st)(e,n,o,i)])}catch(t){const e=`followOrCreateLinkWithContentOnCreate: Error making link in ${i} to ${o}: ${t}`;throw s(e),new D(e)}try{await r(o,a)}catch(t){throw s(`followOrCreateLinkWithContentOnCreate: Error loading or saving new linked document: ${o}: ${t}`),t}return o},loadOrCreateIfNotExists:o,loadOrCreateWithContentOnCreate:r}}(n,r,i),l=q(n,o,c),d=P(n,l),u=S(n,l,c,i),w=K(n,o,l,c);return a("SolidAuthnLogic initialized"),{store:n,authn:o,acl:r,inbox:u,chat:d,profile:l,typeIndex:w,load:function(t){return n.fetcher.load(t)},updatePromise:function(t,e=[]){return new Promise((o,r)=>{n.updater.update(t,e,function(t,e,n){e?o():r(new Error(n))})})},clearStore:function(){n.statements.slice().forEach(n.remove.bind(n))}}}const X=async(t,e)=>{var n;const o=e&&e.credentials&&"omit"==e.credentials,r=m;if(((null===(n=null==r?void 0:r.info)||void 0===n?void 0:n.webId)||(null==r?void 0:r.webId))&&!o){const n="function"==typeof r.fetch?r.fetch.bind(r):"function"==typeof r.authFetch?r.authFetch.bind(r):null;return n?n(t,e):window.fetch(t,e)}return window.fetch(t,e)},Y=Symbol.for("solid-logic-singleton"),Z="undefined"!=typeof window?window:i.g;const G=(Z[Y]?a("SolidLogic: Using existing global singleton instance."):(a("SolidLogic: Creating new global singleton instance."),Z[Y]=V({fetch:X},m),a("Unique quadstore initialized.")),Z[Y]);async function J(t={}){if("undefined"==typeof window)return!1;const e=t.issuer||"",n=t.postLogoutRedirectPath||"/";try{if(e){const t=new URL(e);t.pathname="/.well-known/openid-configuration";const n=await fetch(t.toString(),{credentials:"include"});if(200===n.status){const t=await n.json();t&&t.end_session_endpoint&&await fetch(t.end_session_endpoint,{credentials:"include"})}}}catch(t){}try{const t=await fetch("/.well-known/solid/logout",{credentials:"include"});if(t.ok||t.redirected)return window.location.assign(n),!0}catch(t){}return!1}const Q=[{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 tt(){const t=[...Q],{host:e,origin:n}=new URL(location.href);return t.map(({uri:t})=>new URL(t).host).includes(e)||t.unshift({name:e,uri:n}),t}const et=G.authn,nt=G.authn.authSession,ot=G.store;export{C as ACL_LINK,O as CrossOriginForbiddenError,j as FetchError,F as NotEditableError,M as NotFoundError,W as SameOriginForbiddenError,N as UnauthorizedError,D as WebOperationError,$ as appContext,nt as authSession,et as authn,K as createTypeIndexLogic,tt as getSuggestedIssuers,U as offlineTestID,J as performServerSideLogout,G as solidLogicSingleton,ot as store};
|
|
2
2
|
//# sourceMappingURL=solid-logic.esm.min.js.map
|