forked from SolidOS/solid-logic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolid-logic.min.js
More file actions
22 lines (22 loc) · 61.5 KB
/
Copy pathsolid-logic.min.js
File metadata and controls
22 lines (22 loc) · 61.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("$rdf")):"function"==typeof define&&define.amd?define("SolidLogic",["$rdf"],t):"object"==typeof exports?exports.SolidLogic=t(require("$rdf")):e.SolidLogic=t(e.$rdf)}(this,e=>(()=>{var t={264(t){"use strict";t.exports=e},386(e){const t={acl:"http://www.w3.org/ns/auth/acl#",arg:"http://www.w3.org/ns/pim/arg#",as:"https://www.w3.org/ns/activitystreams#",bookmark:"http://www.w3.org/2002/01/bookmark#",cal:"http://www.w3.org/2002/12/cal/ical#",cco:"http://www.ontologyrepository.com/CommonCoreOntologies/",cert:"http://www.w3.org/ns/auth/cert#",contact:"http://www.w3.org/2000/10/swap/pim/contact#",dc:"http://purl.org/dc/elements/1.1/",dct:"http://purl.org/dc/terms/",doap:"http://usefulinc.com/ns/doap#",foaf:"http://xmlns.com/foaf/0.1/",geo:"http://www.w3.org/2003/01/geo/wgs84_pos#",gpx:"http://www.w3.org/ns/pim/gpx#",gr:"http://purl.org/goodrelations/v1#",http:"http://www.w3.org/2007/ont/http#",httph:"http://www.w3.org/2007/ont/httph#",icalTZ:"http://www.w3.org/2002/12/cal/icaltzd#",ldp:"http://www.w3.org/ns/ldp#",link:"http://www.w3.org/2007/ont/link#",log:"http://www.w3.org/2000/10/swap/log#",meeting:"http://www.w3.org/ns/pim/meeting#",mo:"http://purl.org/ontology/mo/",org:"http://www.w3.org/ns/org#",owl:"http://www.w3.org/2002/07/owl#",pad:"http://www.w3.org/ns/pim/pad#",patch:"http://www.w3.org/ns/pim/patch#",prov:"http://www.w3.org/ns/prov#",pto:"http://www.productontology.org/id/",qu:"http://www.w3.org/2000/10/swap/pim/qif#",trip:"http://www.w3.org/ns/pim/trip#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",rss:"http://purl.org/rss/1.0/",sched:"http://www.w3.org/ns/pim/schedule#",schema:"http://schema.org/",sioc:"http://rdfs.org/sioc/ns#",skos:"http://www.w3.org/2004/02/skos/core#",solid:"http://www.w3.org/ns/solid/terms#",space:"http://www.w3.org/ns/pim/space#",stat:"http://www.w3.org/ns/posix/stat#",tab:"http://www.w3.org/2007/ont/link#",tabont:"http://www.w3.org/2007/ont/link#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",wf:"http://www.w3.org/2005/01/wf/flow#",xsd:"http://www.w3.org/2001/XMLSchema#"};e.exports=function(e={namedNode:e=>e}){const r={};for(const n in t){const o=t[n];r[n]=function(t=""){return e.namedNode(o+t)}}return r}}},r={};function n(e){var o=r[e];if(void 0!==o)return o.exports;var s=r[e]={exports:{}};return t[e](s,s.exports,n),s.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};return(()=>{"use strict";function e(...e){console.log(...e)}function t(...e){console.warn(...e)}n.r(o),n.d(o,{ACL_LINK:()=>Ze,CrossOriginForbiddenError:()=>lt,FetchError:()=>ft,NotEditableError:()=>wt,NotFoundError:()=>ut,SameOriginForbiddenError:()=>ht,UnauthorizedError:()=>dt,WebOperationError:()=>pt,appContext:()=>et,authSession:()=>It,authn:()=>At,createTypeIndexLogic:()=>mt,getSuggestedIssuers:()=>kt,offlineTestID:()=>tt,solidLogicSingleton:()=>Et,store:()=>Pt});const r=crypto,s=e=>e instanceof CryptoKey;function a(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}const i=(e,...t)=>a("Key must be ",e,...t);function c(e,t,...r){return a(`Key for the ${e} algorithm must be `,t,...r)}const d=new TextEncoder,l=new TextDecoder;function h(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const u=e=>(e=>{let t=e;"string"==typeof t&&(t=d.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,"_"),w=e=>{let t=e;t instanceof Uint8Array&&(t=l.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.")}},p=e=>!!s(e)||"KeyObject"===e?.[Symbol.toStringTag],f=["CryptoKey"],y=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:u(e)};if(!s(e))throw new TypeError(i(e,...f,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:n,alg:o,use:a,...c}=await r.subtle.exportKey("jwk",e);return c};async function m(e){return y(e)}class g extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}g.code="ERR_JOSE_GENERIC";class b extends g{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}}b.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class _ extends g{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}}_.code="ERR_JWT_EXPIRED";class S extends g{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}S.code="ERR_JOSE_ALG_NOT_ALLOWED";class E extends g{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}E.code="ERR_JOSE_NOT_SUPPORTED";(class extends g{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends g{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class v extends g{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}v.code="ERR_JWS_INVALID";class k extends g{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}k.code="ERR_JWT_INVALID";class A extends g{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}A.code="ERR_JWK_INVALID";class I extends g{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}I.code="ERR_JWKS_INVALID";class P extends g{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}P.code="ERR_JWKS_NO_MATCHING_KEY";class T extends g{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,T.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class x extends g{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}x.code="ERR_JWKS_TIMEOUT";class C extends g{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function R(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 E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}C.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const $=(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 W(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 O(e){return parseInt(e.name.slice(4),10)}function D(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 L(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!U(e.algorithm,"HMAC"))throw W("HMAC");const r=parseInt(t.slice(2),10);if(O(e.algorithm.hash)!==r)throw W(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!U(e.algorithm,"RSASSA-PKCS1-v1_5"))throw W("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(O(e.algorithm.hash)!==r)throw W(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!U(e.algorithm,"RSA-PSS"))throw W("RSA-PSS");const r=parseInt(t.slice(2),10);if(O(e.algorithm.hash)!==r)throw W(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw W("Ed25519 or Ed448");break;case"Ed25519":if(!U(e.algorithm,"Ed25519"))throw W("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!U(e.algorithm,"ECDSA"))throw W("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 W(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}D(e,r)}function N(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function H(e){return N(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:n}=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 E('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 E('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 E('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new E('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),o=[t,e.ext??!1,e.key_ops??n],s={...e};return delete s.alg,delete s.use,r.subtle.importKey("jwk",s,...o)},K=e=>w(e);let j,M;const F=e=>"KeyObject"===e?.[Symbol.toStringTag],z=async(e,t,r,n,o=!1)=>{let s=e.get(t);if(s?.[n])return s[n];const a=await J({...r,alg:n});return o&&Object.freeze(t),s?s[n]=a:e.set(t,{[n]:a}),a},q=(e,t)=>{if(F(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):(M||(M=new WeakMap),z(M,e,r,t))}if(H(e)){if(e.k)return w(e.k);M||(M=new WeakMap);return z(M,e,e,t,!0)}return e},V=(e,t)=>{if(F(e)){let r=e.export({format:"jwk"});return r.k?K(r.k):(j||(j=new WeakMap),z(j,e,r,t))}if(H(e)){if(e.k)return w(e.k);j||(j=new WeakMap);return z(j,e,e,t,!0)}return e};async function B(e,t,n){if("sign"===n&&(t=await V(t,e)),"verify"===n&&(t=await q(t,e)),s(t))return L(t,e,n),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(i(t,...f));return r.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[n])}throw new TypeError(i(t,...f,"Uint8Array","JSON Web Key"))}const G=async(e,t,n)=>{const o=await B(e,t,"sign");$(e,o);const s=await r.subtle.sign(R(e,o.algorithm),o,n);return new Uint8Array(s)},X=(...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},Y=e=>e?.[Symbol.toStringTag],Z=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Q=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&H(t)){if(function(e){return H(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&Z(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!p(t))throw new TypeError(c(e,t,...f,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${Y(t)} instances for symmetric algorithms must be of type "secret"`)}};function ee(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Q(t,r,n,e):((e,t,r,n)=>{if(n&&H(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&Z(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&Z(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!p(t))throw new TypeError(c(e,t,...f,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${Y(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${Y(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${Y(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${Y(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${Y(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}ee.bind(void 0,!1);const te=ee.bind(void 0,!0);const re=function(e,t,r,n,o){if(void 0!==o.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let 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 E(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)};class ne{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 v("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!X(this._protectedHeader,this._unprotectedHeader))throw new v("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(re(v,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new v('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if("string"!=typeof o||!o)throw new v('JWS "alg" (Algorithm) Header Parameter missing or invalid');te(o,e,"sign");let s,a=this._payload;n&&(a=d.encode(u(a))),s=this._protectedHeader?d.encode(u(JSON.stringify(this._protectedHeader))):d.encode("");const i=h(s,d.encode("."),a),c=await G(o,e,i),w={signature:u(c),payload:""};return n&&(w.payload=l.decode(a)),this._unprotectedHeader&&(w.header=this._unprotectedHeader),this._protectedHeader&&(w.protected=l.decode(s)),w}}class oe{constructor(e){this._flattened=new ne(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}`}}const se=e=>Math.floor(e.getTime()/1e3),ae=86400,ie=/^(\+|\-)? ?(\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=ie.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*ae);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};function de(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class le{constructor(e={}){if(!N(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:de("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:de("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:de("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:de("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:de("setIssuedAt",se(e))}:this._payload="string"==typeof e?{...this._payload,iat:de("setIssuedAt",se(new Date)+ce(e))}:{...this._payload,iat:de("setIssuedAt",e)},this}}class he extends le{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new oe(d.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 k("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const ue=async(e,t,r)=>{let n,o,s=!1;"function"==typeof AbortController&&(n=new AbortController,o=setTimeout(()=>{s=!0,n.abort()},t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(s)throw new x;throw e});if(void 0!==o&&clearTimeout(o),200!==a.status)throw new g("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new g("Failed to parse the JSON Web Key Set HTTP response as JSON")}};async function we(e,t){if(!N(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 w(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new E('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return J({...e,alg:t});default:throw new E('Unsupported "kty" (Key Type) Parameter value')}}function pe(e){return N(e)}function fe(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class ye{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(pe)}(e))throw new I("JSON Web Key Set malformed");this._jwks=fe(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new E('Unsupported "alg" value for a JSON Web Key Set')}}(r),s=this._jwks.keys.filter(e=>{let t=o===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:a,length:i}=s;if(0===i)throw new P;if(1!==i){const e=new T,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of s)try{yield await me(t,e,r)}catch{}},e}return me(this._cached,a,r)}}async function me(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await we({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new I("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function ge(e){const t=new ye(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>fe(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}let be;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){be=`${"jose"}/${"v5.10.0"}`}const _e=Symbol();class Se{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?.[_e]&&(this._cache=t?.[_e],r=t?.[_e],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&N(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,N)&&(this._jwksTimestamp=this._cache.uat,this._local=ge(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof P&&!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);be&&!e.has("User-Agent")&&(e.set("User-Agent",be),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ue(this._url,this._timeoutDuration,this._options).then(e=>{this._local=ge(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}}const Ee=async(e,t,n,o)=>{const s=await B(e,t,"verify");$(e,s);const a=R(e,s.algorithm);try{return await r.subtle.verify(a,s,n,o)}catch{return!1}},ve=(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 ke(e,t,r){if(e instanceof Uint8Array&&(e=l.decode(e)),"string"!=typeof e)throw new v("Compact JWS must be a string or Uint8Array");const{0:n,1:o,2:s,length:a}=e.split(".");if(3!==a)throw new v("Invalid Compact JWS");const i=await async function(e,t,r){if(!N(e))throw new v("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new v('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new v("JWS Protected Header incorrect type");if(void 0===e.payload)throw new v("JWS Payload missing");if("string"!=typeof e.signature)throw new v("JWS Signature missing or incorrect type");if(void 0!==e.header&&!N(e.header))throw new v("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=w(e.protected);n=JSON.parse(l.decode(t))}catch{throw new v("JWS Protected Header is invalid")}if(!X(n,e.header))throw new v("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...n,...e.header};let s=!0;if(re(v,new Map([["b64",!0]]),r?.crit,n,o).has("b64")&&(s=n.b64,"boolean"!=typeof s))throw new v('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=o;if("string"!=typeof a||!a)throw new v('JWS "alg" (Algorithm) Header Parameter missing or invalid');const i=r&&ve("algorithms",r.algorithms);if(i&&!i.has(a))throw new S('"alg" (Algorithm) Header Parameter value not allowed');if(s){if("string"!=typeof e.payload)throw new v("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new v("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t?(t=await t(n,e),c=!0,te(a,t,"verify"),H(t)&&(t=await we(t,a))):te(a,t,"verify");const u=h(d.encode(e.protected??""),d.encode("."),"string"==typeof e.payload?d.encode(e.payload):e.payload);let p,f;try{p=w(e.signature)}catch{throw new v("Failed to base64url decode the signature")}if(!await Ee(a,t,p,u))throw new C;if(s)try{f=w(e.payload)}catch{throw new v("Failed to base64url decode the payload")}else f="string"==typeof e.payload?d.encode(e.payload):e.payload;const y={payload:f};return void 0!==e.protected&&(y.protectedHeader=n),void 0!==e.header&&(y.unprotectedHeader=e.header),c?{...y,key:t}:y}({payload:o,protected:n,signature:s},t,r),c={payload:i.payload,protectedHeader:i.protectedHeader};return"function"==typeof t?{...c,key:i.key}:c}const Ae=e=>e.toLowerCase().replace(/^application\//,""),Ie=(e,t,r={})=>{let n;try{n=JSON.parse(l.decode(t))}catch{}if(!N(n))throw new k("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&("string"!=typeof e.typ||Ae(e.typ)!==Ae(o)))throw new b('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:s=[],issuer:a,subject:i,audience:c,maxTokenAge:d}=r,h=[...s];void 0!==d&&h.push("iat"),void 0!==c&&h.push("aud"),void 0!==i&&h.push("sub"),void 0!==a&&h.push("iss");for(const e of new Set(h.reverse()))if(!(e in n))throw new b(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new b('unexpected "iss" claim value',n,"iss","check_failed");if(i&&n.sub!==i)throw new b('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(u=n.aud,w="string"==typeof c?[c]:c,!("string"==typeof u?w.includes(u):Array.isArray(u)&&w.some(Set.prototype.has.bind(new Set(u))))))throw new b('unexpected "aud" claim value',n,"aud","check_failed");var u,w;let p;switch(typeof r.clockTolerance){case"string":p=ce(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:f}=r,y=se(f||new Date);if((void 0!==n.iat||d)&&"number"!=typeof n.iat)throw new b('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new b('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>y+p)throw new b('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new b('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=y-p)throw new _('"exp" claim timestamp check failed',n,"exp","check_failed")}if(d){const e=y-n.iat;if(e-p>("number"==typeof d?d:ce(d)))throw new _('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-p)throw new b('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};const Pe=async(e,t)=>{const n=`SHA-${e.slice(-3)}`;return new Uint8Array(await r.subtle.digest(n,t))},Te=(e,t)=>{if("string"!=typeof e||!e)throw new A(`${t} missing or invalid`)};async function xe(e,t){if(!N(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),"sha256"!==t&&"sha384"!==t&&"sha512"!==t)throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":Te(e.crv,'"crv" (Curve) Parameter'),Te(e.x,'"x" (X Coordinate) Parameter'),Te(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":Te(e.crv,'"crv" (Subtype of Key Pair) Parameter'),Te(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":Te(e.e,'"e" (Exponent) Parameter'),Te(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":Te(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new E('"kty" (Key Type) Parameter missing or unsupported')}const n=d.encode(JSON.stringify(r));return u(await Pe(t,n))}function Ce(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new E("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function Re(e,t){return async function(e,t){let n,o;switch(e){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ce(t)},o=["sign","verify"];break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ce(t)},o=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ce(t)},o=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"},o=["sign","verify"];break;case"ES384":n={name:"ECDSA",namedCurve:"P-384"},o=["sign","verify"];break;case"ES512":n={name:"ECDSA",namedCurve:"P-521"},o=["sign","verify"];break;case"Ed25519":n={name:"Ed25519"},o=["sign","verify"];break;case"EdDSA":{o=["sign","verify"];const e=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":n={name:e};break;default:throw new E("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{o=["deriveKey","deriveBits"];const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":n={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":n={name:e};break;default:throw new E("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new E('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return r.subtle.generateKey(n,t?.extractable??!1,o)}(e,t)}const $e=w;
/**
* solid-oidc.js - Minimal Solid-OIDC client for browsers
*
* A zero-build, single-file Solid-OIDC authentication library.
*
* @license MIT
* @author JavaScriptSolidServer
* @see https://github.com/JavaScriptSolidServer/solid-oidc
*
* Based on solid-oidc-client-browser by uvdsl (Christoph Braun)
* @see https://github.com/uvdsl/solid-oidc-client-browser
*
* Implements:
* - RFC 6749 - OAuth 2.0
* - RFC 7636 - PKCE
* - RFC 9207 - OAuth 2.0 Authorization Server Issuer Identification
* - RFC 9449 - DPoP (Demonstration of Proof-of-Possession)
* - Solid-OIDC Specification
*/
const We="sessionStateChange",Ue="sessionExpirationWarning",Oe="sessionExpiration";class De{constructor(e="solid-oidc",t="session",r=1){this.dbName=e,this.storeName=t,this.dbVersion=r,this.db=null}async init(){return new Promise((e,t)=>{const r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=()=>t(new Error(`Database error: ${r.error}`)),r.onsuccess=()=>{this.db=r.result,e(this)},r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.storeName)||t.createObjectStore(this.storeName)}})}async setItem(e,t){return this.db||await this.init(),new Promise((r,n)=>{const o=this.db.transaction(this.storeName,"readwrite");o.oncomplete=()=>r(),o.onerror=()=>n(new Error(`Transaction error: ${o.error}`)),o.objectStore(this.storeName).put(t,e)})}async getItem(e){return this.db||await this.init(),new Promise((t,r)=>{const n=this.db.transaction(this.storeName,"readonly");n.onerror=()=>r(new Error(`Transaction error: ${n.error}`));const o=n.objectStore(this.storeName).get(e);o.onsuccess=()=>t(o.result||null)})}async deleteItem(e){return this.db||await this.init(),new Promise((t,r)=>{const n=this.db.transaction(this.storeName,"readwrite");n.oncomplete=()=>t(),n.onerror=()=>r(new Error(`Transaction error: ${n.error}`)),n.objectStore(this.storeName).delete(e)})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{const r=this.db.transaction(this.storeName,"readwrite");r.oncomplete=()=>e(),r.onerror=()=>t(new Error(`Transaction error: ${r.error}`)),r.objectStore(this.storeName).clear()})}close(){this.db&&(this.db.close(),this.db=null)}}async function Le(e,t,r,n=null){const o=await m(e.publicKey),s={htu:t,htm:r};return n&&(s.ath=n),new he(s).setIssuedAt().setJti(crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).sign(e.privateKey)}async function Ne(e,t,r){const n=await Le(r,e,"POST"),o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",DPoP:n},body:new URLSearchParams(t)});if(!o.ok)throw new Error(`Token request failed: ${o.status}`);return o.json()}async function He(e,t,r,n,o){const s=function(e,t){const r=new Se(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)),{payload:a}=await async function(e,t,r){const n=await ke(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new k("JWTs MUST NOT use unencoded payload");const o={payload:Ie(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...o,key:n.key}:o}(e,s,{issuer:r,audience:"solid"}),i=await xe(await m(o.publicKey));if(a.cnf?.jkt!==i)throw new Error("DPoP thumbprint mismatch");if(a.client_id!==n)throw new Error("client_id mismatch");return a}class Je extends EventTarget{constructor(e={}){super(),this.clientId=e.clientId||null,this.database=e.database||new De,this.onStateChange=e.onStateChange||null,this.onExpirationWarning=e.onExpirationWarning||null,this.onExpiration=e.onExpiration||null,this._isActive=!1,this._webId=null,this._exp=null,this._ath=null,this._tokens=null,this._idpDetails=null,this._refreshPromise=null,this.onStateChange&&this.addEventListener(We,this.onStateChange),this.onExpirationWarning&&this.addEventListener(Ue,this.onExpirationWarning),this.onExpiration&&this.addEventListener(Oe,this.onExpiration)}get isActive(){return this._isActive}get webId(){return this._webId}isExpired(){return!this._exp||Math.floor(Date.now()/1e3)>=this._exp}getExpiresIn(){return this._exp?this._exp-Math.floor(Date.now()/1e3):-1}async login(e,t){const r=new URL(t),n=r.origin+r.pathname+r.search,o=await async function(e){const t=new URL(e).origin,r=await fetch(`${t}/.well-known/openid-configuration`);if(!r.ok)throw new Error(`OIDC discovery failed: ${r.status}`);return r.json()}(e),s=o.issuer,a=e=>e.endsWith("/")?e.slice(0,-1):e;if(a(e)!==a(s))throw new Error(`Issuer mismatch: ${s} !== ${e}`);sessionStorage.setItem("solid_oidc_idp",s),sessionStorage.setItem("solid_oidc_token_endpoint",o.token_endpoint),sessionStorage.setItem("solid_oidc_jwks_uri",o.jwks_uri);let i=this.clientId;if(!i){i=(await async function(e,t){const r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({application_type:"web",redirect_uris:t,token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],scope:"openid offline_access webid"})});if(!r.ok)throw new Error(`Client registration failed: ${r.status}`);return r.json()}(o.registration_endpoint,[n])).client_id,sessionStorage.setItem("solid_oidc_client_id",i)}const c=await async function(){const e=crypto.randomUUID()+"-"+crypto.randomUUID(),t=new Uint8Array(await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)));return{verifier:e,challenge:btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}}();sessionStorage.setItem("solid_oidc_pkce_verifier",c.verifier);const d=crypto.randomUUID();sessionStorage.setItem("solid_oidc_csrf",d);const l=new URL(o.authorization_endpoint);l.searchParams.set("response_type","code"),l.searchParams.set("redirect_uri",n),l.searchParams.set("scope","openid offline_access webid"),l.searchParams.set("client_id",i),l.searchParams.set("code_challenge_method","S256"),l.searchParams.set("code_challenge",c.challenge),l.searchParams.set("state",d),l.searchParams.set("prompt","consent"),window.location.href=l.toString()}async handleRedirectFromLogin(){const e=new URL(window.location.href),t=e.searchParams.get("code");if(!t)return;const r=sessionStorage.getItem("solid_oidc_idp"),n=e.searchParams.get("iss");if(!r||n!==r)throw new Error(`Issuer mismatch: ${n} !== ${r}`);const o=sessionStorage.getItem("solid_oidc_csrf");if(e.searchParams.get("state")!==o)throw new Error("CSRF token mismatch");e.searchParams.delete("code"),e.searchParams.delete("iss"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString());const s=sessionStorage.getItem("solid_oidc_pkce_verifier"),a=sessionStorage.getItem("solid_oidc_token_endpoint"),i=sessionStorage.getItem("solid_oidc_jwks_uri"),c=this.clientId||sessionStorage.getItem("solid_oidc_client_id");if(!s||!a||!c)throw new Error("Missing session data");const d=await Re("ES256"),l=await Ne(a,{grant_type:"authorization_code",code:t,code_verifier:s,redirect_uri:e.origin+e.pathname,client_id:c},d);await He(l.access_token,i,r,c,d),this._idpDetails={idp:r,jwksUri:i,tokenEndpoint:a},await this.database.init(),await Promise.all([this.database.setItem("idp",r),this.database.setItem("jwks_uri",i),this.database.setItem("token_endpoint",a),this.database.setItem("client_id",c),this.database.setItem("dpop_keypair",d),this.database.setItem("refresh_token",l.refresh_token)]),this.database.close(),sessionStorage.removeItem("solid_oidc_idp"),sessionStorage.removeItem("solid_oidc_token_endpoint"),sessionStorage.removeItem("solid_oidc_jwks_uri"),sessionStorage.removeItem("solid_oidc_client_id"),sessionStorage.removeItem("solid_oidc_pkce_verifier"),sessionStorage.removeItem("solid_oidc_csrf"),await this._setTokens({...l,dpop_key_pair:d}),this._dispatchStateChange()}async restore(){return this._refreshPromise||(this._refreshPromise=(async()=>{try{const e=await async function(e){await e.init();const[t,r,n,o]=await Promise.all([e.getItem("refresh_token"),e.getItem("token_endpoint"),e.getItem("client_id"),e.getItem("dpop_keypair")]);if(!(t&&r&&n&&o))throw new Error("Missing refresh data");const s=await Ne(r,{grant_type:"refresh_token",refresh_token:t,client_id:n},o);return s.refresh_token&&await e.setItem("refresh_token",s.refresh_token),e.close(),{...s,dpop_key_pair:o}}(this.database);await this._setTokens(e),this._dispatchStateChange()}catch(e){throw this._isActive&&(this.isExpired()?this._dispatchExpiration():this._dispatchExpirationWarning()),e}finally{this._refreshPromise=null}})()),this._refreshPromise}async logout(){this._isActive=!1,this._webId=null,this._exp=null,this._ath=null,this._tokens=null,this._idpDetails=null,await this.database.init(),await this.database.clear(),this.database.close(),this._dispatchStateChange()}async authFetch(e,t={}){if(!this._isActive)return fetch(e,t);let r,n,o;this.isExpired()&&await this.restore(),e instanceof Request?(r=new URL(e.url),n=t.method||e.method||"GET",o=new Headers(e.headers)):(r=new URL(e.toString()),n=t.method||"GET",o=t.headers?new Headers(t.headers):new Headers);const s=await Le(this._tokens.dpop_key_pair,`${r.origin}${r.pathname}`,n.toUpperCase(),this._ath);return o.set("DPoP",s),o.set("Authorization",`DPoP ${this._tokens.access_token}`),e instanceof Request?fetch(new Request(e,{...t,headers:o})):fetch(r,{...t,headers:o})}async _setTokens(e){this._tokens=e;const t=function(e){if("string"!=typeof e)throw new k("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new k("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new k("Invalid JWT");if(!t)throw new k("JWTs must contain a payload");let n,o;try{n=$e(t)}catch{throw new k("Failed to base64url decode the payload")}try{o=JSON.parse(l.decode(n))}catch{throw new k("Failed to parse the decoded payload as JSON")}if(!N(o))throw new k("Invalid JWT Claims Set");return o}(e.access_token);if(!t.webid)throw new Error("Missing webid claim");if(!t.exp)throw new Error("Missing exp claim");this._ath=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=Array.from(new Uint8Array(r));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(e.access_token),this._webId=t.webid,this._exp=t.exp,this._isActive=!0}_dispatchStateChange(){this.dispatchEvent(new CustomEvent(We,{detail:{isActive:this._isActive,webId:this._webId}}))}_dispatchExpirationWarning(){this.dispatchEvent(new CustomEvent(Ue,{detail:{expires_in:this.getExpiresIn()}}))}_dispatchExpiration(){this.dispatchEvent(new CustomEvent(Oe))}}const Ke="sessionRestore",je="login",Me="logout",Fe="sessionExpired",ze="error";class qe{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var r;null===(r=this.listeners.get(e))||void 0===r||r.delete(t)}emit(e,...t){var r;null===(r=this.listeners.get(e))||void 0===r||r.forEach(e=>e(...t))}}class Ve{constructor(e){this._session=new Je({clientId:null==e?void 0:e.clientId,database:new De,onStateChange:e=>{const t=e.detail;(null==t?void 0:t.isActive)?(this._events.emit(je),this._events.emit(Ke,window.location.href)):this._events.emit(Me)},onExpiration:()=>{this._events.emit(Fe)}}),this._events=new qe,this._sessionId=crypto.randomUUID()}get events(){return this._events}get info(){var e;return{isLoggedIn:this._session.isActive,webId:null!==(e=this._session.webId)&&void 0!==e?e:void 0,sessionId:this._sessionId,expirationDate:this._session.isActive?Date.now()+1e3*this._session.getExpiresIn():void 0}}async handleIncomingRedirect(e){const t="string"==typeof e?{url:e}:null!=e?e:{};try{if(await this._session.handleRedirectFromLogin(),!this._session.isActive&&!1!==t.restorePreviousSession)try{await this._session.restore()}catch{}return this.info}catch(e){return void this._events.emit(ze,e)}}async login(e){const t=e.redirectUrl||window.location.href;await this._session.login(e.oidcIssuer,t)}async logout(){await this._session.logout()}async fetch(e,t){return this._session.authFetch(e,t)}}const Be=new Ve;var Ge=n(264),Xe=n(386);const Ye=n.n(Xe)()(Ge),Ze=(0,Ge.sym)("http://www.iana.org/assignments/link-relations/acl");function Qe(e){const t=Ye;function r(e,r,n,o={}){const s=o.public||[],a=(0,Ge.graph)(),i=(0,Ge.Namespace)("http://www.w3.org/ns/auth/acl#");let c=a.sym(`${n}#a1`);const d=a.sym(n),l=a.sym(e);if(a.add(c,t.rdf("type"),i("Authorization"),d),a.add(c,i("accessTo"),l,d),o.defaultForNew&&a.add(c,i("default"),l,d),a.add(c,i("agent"),r,d),a.add(c,i("mode"),i("Read"),d),a.add(c,i("mode"),i("Write"),d),a.add(c,i("mode"),i("Control"),d),s.length){c=a.sym(`${n}#a2`),a.add(c,t.rdf("type"),i("Authorization"),d),a.add(c,i("accessTo"),l,d),a.add(c,i("agentClass"),t.foaf("Agent"),d);for(let e=0;e<s.length;e++)a.add(c,i("mode"),i(s[e]),d)}return(0,Ge.serialize)(d,a,n)}return{findAclDocUrl:async function(t){await e.fetcher.load(t);const r=e.any(t,Ze);if(!r)throw new Error(`No ACL link discovered for ${t}`);return r.value},setACLUserPublic:function(t,n,o){const s=e.any(e.sym(t),Ze);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),Ze);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 a=r(t,n,s.uri,o);if(!e.fetcher)throw new Error("Cannot PUT this, store has no fetcher");return e.fetcher.webOperation("PUT",s.uri,{data:a,contentType:"text/turtle"}).then(e=>{if(!e.ok)throw new Error("Error writing ACL text: "+e.error);return s})})},genACLText:r}}const et=()=>{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 tt(){const{$SolidTestEnvironment:t}=window;if(void 0!==t&&t.username)return e("Assuming the user is "+t.username),(0,Ge.sym)(t.username);if("undefined"!=typeof document&&document.location&&"http://localhost"===(""+document.location).slice(0,16)){const t=document.getElementById("appTarget");if(!t)return null;const r=t.getAttribute("testID");return r?(e("Assuming user is "+r),(0,Ge.sym)(r)):null}return null}class rt{constructor(e){this.session=e}get authSession(){return this.session}currentUser(){const e=et();return e.viewingNoAuthPage?(0,Ge.sym)(e.webId):this&&this.session&&this.session.info&&this.session.info.webId&&this.session.info.isLoggedIn?(0,Ge.sym)(this.session.info.webId):tt()}async checkUser(t){const r=new URL(window.location.href).hash;r&&window.localStorage.setItem("preLoginRedirectHash",r),this.session.events.on(Ke,t=>{e(`Session restored to ${t}`),document.location.toString()!==t&&history.replaceState(null,"",t)});const n=new URL(window.location.href);n.hash="",await this.session.handleIncomingRedirect({restorePreviousSession:!0,url:n.href});const o=window.localStorage.getItem("preLoginRedirectHash");if(o){const e=new URL(window.location.href);e.hash!==o&&(history.pushState?history.pushState(null,document.title,o):location.hash=o,e.hash=o),window.localStorage.setItem("preLoginRedirectHash","")}let s=tt();if(s)return Promise.resolve(t?t(s):s);const a=this.webIdFromSession(this.session.info);return a&&(s=this.saveUser(a)),s&&e(`(Logged in as ${s} by authentication)`),Promise.resolve(t?t(s):s)}saveUser(e,t){let r;if(e){r="string"==typeof e?e:e.uri;const n=(0,Ge.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 nt(e){return(0,Ge.sym)(e.uri+"#id"+Date.now())}function ot(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const st="index.ttl#this";function at(e,t){const r=Ye;async function n(t,r,n){await e.fetcher.load(t);const o=e.any(t,new Ge.NamedNode("http://www.iana.org/assignments/link-relations/acl"));if(!o)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",o.value,{data:s,contentType:"text/turtle"})}async function o(t,n){const o=e.any(n,r.solid("privateTypeIndex"));if(!o)throw new Error("Private type index not found!");await e.fetcher.load(o);const s=nt(o),a=[(0,Ge.st)(s,r.rdf("type"),r.solid("TypeRegistration"),o.doc()),(0,Ge.st)(s,r.solid("forClass"),r.meeting("LongChat"),o.doc()),(0,Ge.st)(s,r.solid("instance"),t,o.doc())];await new Promise((t,r)=>{e.updater.update([],a,function(e,n,o){n?t(null):r(new Error(o))})})}async function s(r){const n=await t.loadMe(),o=function(e,t){const r=new URL(`IndividualChats/${new URL(e.value).host}/`,t.value).toString();return new Ge.NamedNode(r)}(r,await t.getPodRoot(n));let s=!0;try{await e.fetcher.load(new Ge.NamedNode(o.value+"index.ttl#this"))}catch(e){s=!1}return{me:n,chatContainer:o,exists:s}}async function a(e,t){return(await i({me:t,newBase:e.value})).newInstance}function i(t){const n=e,o=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+st),a=s.doc();return n.add(s,r.rdf("type"),r.meeting("LongChat"),a),n.add(s,r.dc("title"),"Chat channel",a),n.add(s,r.dc("created"),(0,Ge.term)(new Date(Date.now())),a),t.me&&n.add(s,r.dc("author"),t.me,a),new Promise(function(e,r){null==o||o.put(a,n.statementsMatching(void 0,void 0,void 0,a),"text/turtle",function(n,o,a){o?e({...t,newInstance:s}):r(new Error("FAILED to save new chat channel at: "+n+" : "+a))})})}async function c(t,n){var o;await e.fetcher.load(t.doc());const s=e.any(t,r.ldp("inbox"),void 0,t.doc());if(!s)throw new Error(`Invitee inbox not found! ${t.value}`);const a=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${r.rdf("seeAlso")} <${n.value}> .\n `,i=await(null===(o=e.fetcher)||void 0===o?void 0:o.webOperation("POST",s.value,{data:a,contentType:"text/turtle"}));if(!(null==i?void 0:i.headers.get("location")))throw new Error(`Invite sending returned a ${null==i?void 0:i.status}`)}return{setAcl:n,addToPrivateTypeIndex:o,findChat:s,createChatThing:a,getChat:async function(e,t=!0){const{me:r,chatContainer:i,exists:d}=await s(e);if(d)return new Ge.NamedNode(i.value+st);if(t){const t=await a(i,r);return await c(e,t),await n(i,r,e),await o(t,r),t}return null},sendInvite:c,mintNew:i}}function it(e,t,r,n,o){return{createInboxFor:async function(e,o){const s=await t.loadMe(),a=`${(await t.getPodRoot(s)).value}p2p-inboxes/${encodeURIComponent(o)}/`;return await n.createContainer(a),await r.setSinglePeerAccess({ownerWebId:s.value,peerWebId:e,accessToModes:"acl:Append",target:a}),a},getNewMessages:async function(e){e||(e=await t.loadMe());const r=await t.getMainInbox(e);return(await n.getContainerMembers(r)).filter(e=>!n.isContainer(e))},markAsRead:async function(t,r){const n=await e.fetcher._fetch(t);if(200!==n.status)throw new Error(`Not OK! ${t}`);const o=function(e,t){const r=t.getUTCFullYear(),n=("0"+(t.getUTCMonth()+1)).slice(-2),o=("0"+t.getUTCDate()).slice(-2),s=e.split("/"),a=s[s.length-1];return new URL(`./archive/${r}/${n}/${o}/${a}`,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(o,s)).status.toString()[0]&&await e.fetcher._fetch(t,{method:"DELETE"})}}}class ct extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class dt extends ct{}class lt extends ct{}class ht extends ct{}class ut extends ct{}class wt extends ct{}class pt extends ct{}class ft extends ct{constructor(e,t){super(t),this.status=e}}function yt(e,r,n){const o=Ye;async function s(r){await a(r);const s=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/Settings/Preferences.ttl";return(0,Ge.sym)(t)}(r);let i;try{i=await n.followOrCreateLink(r,o.space("preferencesFile"),s,r.doc())}catch(e){if(t(`User ${r} has no pointer in profile to preferences file.`),e instanceof wt)throw e;if(e instanceof pt)throw e;if(e instanceof dt)throw e;if(e instanceof lt)throw e;if(e instanceof ht)throw e;if(e instanceof ft)throw e;throw e}try{await e.fetcher.load(i)}catch(e){const n=`Unable to load preference of user ${r}: ${e}`;if(t(n),401===e.response.status)throw new dt;if(403===e.response.status){if(ot(i))throw new lt;throw new ht}throw new Error(n)}return i}async function a(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 i(t){return e.any(t,o.space("storage"),void 0,t.doc())}return{loadMe:async function(){const t=r.currentUser();if(null===t)throw new Error("Current user not found! Not logged in?");return await e.fetcher.load(t.doc()),t},getPodRoot:function(e){const t=i(e);if(!t)throw new Error("User pod root not found!");return t},getMainInbox:async function(t){await e.fetcher.load(t);const r=e.any(t,o.ldp("inbox"),void 0,t.doc());if(!r)throw new Error("User main inbox not found!");return r},findStorage:i,loadPreferences:s,loadProfile:a,silencedLoadPreferences:async function(e){try{return await s(e)}catch(e){return}}}}function mt(e,r,n,o){const s=Ye;async function a(r){if(!r)throw new Error("loadTypeIndexesFor: No user given");const a=await n.loadProfile(r),i=l(r);let c;try{c=await o.followOrCreateLink(r,s.solid("publicTypeIndex"),i,a)}catch(e){t(`User ${r} has no pointer in profile to publicTypeIndex file.`)}const d=c?[{label:"public",index:c,agent:r}]:[];let u,w;try{u=await n.silencedLoadPreferences(r)}catch(e){u=null}if(u){const n=h(u);let i;try{i=e.any(r,s.solid("privateTypeIndex"),void 0,a)||await o.followOrCreateLink(r,s.solid("privateTypeIndex"),n,u)}catch(e){t(`User ${r} has no pointer in preference file to privateTypeIndex file.`)}w=i?[{label:"private",index:i,agent:r}]:[]}else w=[];const p=d.concat(w);if(0===p.length)return p;const f=p.map(e=>e.index);try{await e.fetcher.load(f)}catch(e){t("Problems loading type index: ",e)}return p}async function i(r){let o;try{o=await n.silencedLoadPreferences(r)}catch(e){t(`User ${r} has no pointer in profile to preferences file.`)}if(o){const t=e.each(r,s.solid("community"),void 0,o).concat(e.each(r,s.solid("community"),void 0,r.doc()));let n=[];for(const e of t)n=n.concat(await a(e));return n}return[]}async function c(e){return(await a(e)).concat((await i(e)).flat())}async function d(e,t){const r=await c(t);let n=[];for(const t of r){const r=await u(t,e);n=n.concat(r)}return n}function l(e){var t;return(0,Ge.sym)((null===(t=e.doc().dir())||void 0===t?void 0:t.uri)+"publicTypeIndex.ttl")}function h(e){var t;return(0,Ge.sym)((null===(t=e.doc().dir())||void 0===t?void 0:t.uri)+"privateTypeIndex.ttl")}async function u(t,r){const n=t.index,o=[],a=e.statementsMatching(null,s.solid("instance"),null,n).concat(e.statementsMatching(null,s.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const i of a){const a=e.any(i,s.solid("forClass"),null,n);if(!r||a.sameTerm(r)){const r=e.each(i,s.solid("instance"),null,n);for(const e of r)o.push({instance:e,type:a,scope:t});const c=e.each(i,s.solid("instanceContainer"),null,n);for(const r of c)await e.fetcher.load(r),o.push({instance:(0,Ge.sym)(r.value),type:a,scope:t})}}return o}return{registerInTypeIndex:async function(t,r,n){const o=nt(r),a=[(0,Ge.st)(o,s.rdf("type"),s.solid("TypeRegistration"),r),(0,Ge.st)(o,s.solid("forClass"),n,r),(0,Ge.st)(o,s.solid("instance"),t,r)];try{await e.updater.update([],a)}catch(e){const n=`Unable to register ${t} in index ${r}: ${e}`;return console.warn(n),null}return o},getRegistrations:function(t,r){return e.each(void 0,s.solid("instance"),t).filter(t=>e.holds(t,s.solid("forClass"),r))},loadTypeIndexesFor:a,loadCommunityTypeIndexes:i,loadAllTypeIndexes:c,getScopedAppInstances:d,getAppInstances:async function(e){const t=r.currentUser();if(!t)throw new Error("getAppInstances: Must be logged in to find apps.");return(await d(e,t)).map(e=>e.instance)},suggestPublicTypeIndex:l,suggestPrivateTypeIndex:h,deleteTypeIndexRegistration:async function(t){const r=e.the(null,s.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:u}}function gt(r,n){e("SolidLogic: Unique instance created. There should only be one of these.");const o=Ge.graph();Ge.fetcher(o,{fetch:r.fetch}),o.updater=new Ge.UpdateManager(o),o.features=[];const s=new rt(n),a=Qe(o),i=function(e){function t(t){return e.statementsMatching(t,(0,Ge.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,Ge.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("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)}}}(o),c=function(r,n,o){async function s(e){let t;try{t=await r.fetcher.load(e)}catch(t){if(404!==t.response.status){if(401===t.response.status)throw new dt;if(403===t.response.status){if(ot(e))throw new lt;throw new ht}const r="createIfNotExists doc load error NOT 404: "+e+": "+t;throw new ft(t.status,t.message+r)}try{await r.fetcher.webOperation("PUT",e,{data:"",contentType:"text/turtle"})}catch(t){throw new pt("createIfNotExists: PUT FAILED: "+e+": "+t)}await r.fetcher.load(e)}return t}return{recursiveDelete:async function t(s){try{if(o.isContainer(s)){const e=await n.findAclDocUrl(s);await r.fetcher._fetch(e,{method:"DELETE"});const a=await o.getContainerMembers(s);await Promise.all(a.map(e=>t(e)))}const e=s.value;return r.fetcher._fetch(e,{method:"DELETE"})}catch(t){e(`Please manually remove ${s.value} from your system.`,t)}},setSinglePeerAccess:async function(e){let t=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","",`<#alice> a acl:Authorization;\n acl:agent <${e.ownerWebId}>;`,` acl:accessTo <${e.target}>;`,` acl:default <${e.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");e.accessToModes&&(t+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${e.peerWebId}>;`,` acl:accessTo <${e.target}>;`,` acl:mode ${e.accessToModes}.`,""].join("\n")),e.defaultModes&&(t+=["<#bobDefault> a acl:Authorization;",` acl:agent <${e.peerWebId}>;`,` acl:default <${e.target}>;`,` acl:mode ${e.defaultModes}.`,""].join("\n"));const o=await n.findAclDocUrl((0,Ge.sym)(e.target));return r.fetcher._fetch(o,{method:"PUT",body:t,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(e,t){await r.fetcher.webOperation("PUT",e.uri,{data:`# ${new Date} ${t}\n `,contentType:"text/turtle"})},followOrCreateLink:async function(e,n,o,a){await r.fetcher.load(a);const i=r.any(e,n,null,a);if(i)return i;if(!r.updater.editable(a)){const e=`followOrCreateLink: cannot edit ${a.value}`;throw t(e),new wt(e)}try{await r.updater.update([],[(0,Ge.st)(e,n,o,a)])}catch(e){throw t(`followOrCreateLink: Error making link in ${a} to ${o}: ${e}`),new pt(e)}try{await s(o)}catch(e){throw t(`followOrCreateLink: Error loading or saving new linked document: ${o}: ${e}`),e}return o},loadOrCreateIfNotExists:s}}(o,a,i),d=yt(o,s,c),l=at(o,d),h=it(o,d,c,i),u=mt(o,s,d,c);return e("SolidAuthnLogic initialized"),{store:o,authn:s,acl:a,inbox:h,chat:l,profile:d,typeIndex:u,load:function(e){return o.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((r,n)=>{o.updater.update(e,t,function(e,t,o){t?r():n(new Error(o))})})},clearStore:function(){o.statements.slice().forEach(o.remove.bind(o))}}}const bt=async(e,t)=>{const r=t&&t.credentials&&"omit"==t.credentials;return Be.info.webId&&!r?Be.fetch(e,t):window.fetch(e,t)},_t=Symbol.for("solid-logic-singleton"),St="undefined"!=typeof window?window:n.g;const Et=(St[_t]?e("SolidLogic: Using existing global singleton instance."):(e("SolidLogic: Creating new global singleton instance."),St[_t]=gt({fetch:bt},Be),e("Unique quadstore initialized.")),St[_t]),vt=[{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 kt(){const e=[...vt],{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 At=Et.authn,It=Et.authn.authSession,Pt=Et.store})(),o})());
//# sourceMappingURL=solid-logic.min.js.map