solid-logic 3.1.1-cfdb831 → 3.1.1-ecb4985

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.
@@ -37,5 +37,5 @@ t.read=function(e,t,r,n,i){var s,o,a=8*i-n-1,u=(1<<a)-1,c=u>>1,h=-7,l=r?i-1:0,d=
37
37
  * @author Feross Aboukhadijeh <https://feross.org>
38
38
  * @license MIT
39
39
  */
40
- const n=r(7526),i=r(251),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=u,t.IS=50;const o=2147483647;function a(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|g(e,t);let n=a(r);const i=n.write(e,t);i!==r&&(n=n.slice(0,i));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(X(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return d(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,ArrayBuffer)||e&&X(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(X(e,SharedArrayBuffer)||e&&X(e.buffer,SharedArrayBuffer)))return f(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const i=function(e){if(u.isBuffer(e)){const t=0|p(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||G(e.length)?a(0):d(e);if("Buffer"===e.type&&Array.isArray(e.data))return d(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function h(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return h(e),a(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),r=a(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function f(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(n,u.prototype),n}function p(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function g(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||X(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return J(e).length;default:if(i)return n?-1:W(e).length;t=(""+t).toLowerCase(),i=!0}}function y(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,r);case"utf8":case"utf-8":return F(this,t,r);case"ascii":return k(this,t,r);case"latin1":case"binary":return I(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function m(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),G(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:w(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):w(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,n,i){let s,o=1,a=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;o=2,a/=2,u/=2,r/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){let n=-1;for(s=r;s<a;s++)if(c(e,s)===c(t,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===u)return n*o}else-1!==n&&(s-=s-n),n=-1}else for(r+u>a&&(r=a-u),s=r;s>=0;s--){let r=!0;for(let n=0;n<u;n++)if(c(e,s+n)!==c(t,n)){r=!1;break}if(r)return s}return-1}function b(e,t,r,n){r=Number(r)||0;const i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;const s=t.length;let o;for(n>s/2&&(n=s/2),o=0;o<n;++o){const n=parseInt(t.substr(2*o,2),16);if(G(n))return o;e[r+o]=n}return o}function _(e,t,r,n){return z(W(t,e.length-r),e,r,n)}function S(e,t,r,n){return z(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function E(e,t,r,n){return z(J(t),e,r,n)}function x(e,t,r,n){return z(function(e,t){let r,n,i;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)r=e.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}(t,e.length-r),e,r,n)}function A(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function F(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i<r;){const t=e[i];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=r){let r,n,a,u;switch(o){case 1:t<128&&(s=t);break;case 2:r=e[i+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(s=u));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:r=e[i+1],n=e[i+2],a=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&a,u>65535&&u<1114112&&(s=u))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=T));return r}(n)}u.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),u.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}}),u.poolSize=8192,u.from=function(e,t,r){return c(e,t,r)},Object.setPrototypeOf(u.prototype,Uint8Array.prototype),Object.setPrototypeOf(u,Uint8Array),u.alloc=function(e,t,r){return function(e,t,r){return h(e),e<=0?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)}(e,t,r)},u.allocUnsafe=function(e){return l(e)},u.allocUnsafeSlow=function(e){return l(e)},u.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==u.prototype},u.compare=function(e,t){if(X(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),X(t,Uint8Array)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(e)||!u.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,s=Math.min(r,n);i<s;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},u.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=u.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(X(t,Uint8Array))i+t.length>n.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},u.byteLength=g,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)v(this,t,t+1);return this},u.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)v(this,t,t+3),v(this,t+1,t+2);return this},u.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)v(this,t,t+7),v(this,t+1,t+6),v(this,t+2,t+5),v(this,t+3,t+4);return this},u.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?F(this,0,e):y.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){let e="";const r=t.IS;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},s&&(u.prototype[s]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,i){if(X(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(t>>>=0);const a=Math.min(s,o),c=this.slice(n,i),h=e.slice(t,r);for(let e=0;e<a;++e)if(c[e]!==h[e]){s=c[e],o=h[e];break}return s<o?-1:o<s?1:0},u.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},u.prototype.indexOf=function(e,t,r){return m(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return m(this,e,t,r,!1)},u.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return b(this,e,t,r);case"utf8":case"utf-8":return _(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function k(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function I(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function C(e,t,r){const n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=t;n<r;++n)i+=Y[e[n]];return i}function R(e,t,r){const n=e.slice(t,r);let i="";for(let e=0;e<n.length-1;e+=2)i+=String.fromCharCode(n[e]+256*n[e+1]);return i}function P(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,r,n,i,s){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function U(e,t,r,n,i){q(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,r}function O(e,t,r,n,i){q(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r+7]=s,s>>=8,e[r+6]=s,s>>=8,e[r+5]=s,s>>=8,e[r+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=o,o>>=8,e[r+2]=o,o>>=8,e[r+1]=o,o>>=8,e[r]=o,r+8}function L(e,t,r,n,i,s){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function D(e,t,r,n,s){return t=+t,r>>>=0,s||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,s){return t=+t,r>>>=0,s||L(e,0,r,8),i.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,u.prototype),n},u.prototype.readUintLE=u.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return n},u.prototype.readUintBE=u.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=Q(function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),u.prototype.readBigUInt64BE=Q(function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=t,i=1,s=this[e+--n];for(;n>0&&(i*=256);)s+=this[e+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},u.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=Q(function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),u.prototype.readBigInt64BE=Q(function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)}),u.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){N(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=1,s=0;for(this[t]=255&e;++s<r&&(i*=256);)this[t+s]=e/i&255;return t+r},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){N(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=r-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=Q(function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,e,t,r,n-1,-n)}let i=0,s=1,o=0;for(this[t]=255&e;++i<r&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s|0)-o&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,e,t,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s|0)-o&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=Q(function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeFloatLE=function(e,t,r){return D(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return D(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);const i=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i},u.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{const s=u.isBuffer(e)?e:u.from(e,n),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=s[i%o]}return this};const M={};function B(e,t,r){M[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function H(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,i,s){if(e>r||e<t){const n="bigint"==typeof t?"n":"";let i;throw i=s>3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new M.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,i,s)}function K(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new M.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}B("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),B("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),B("ERR_OUT_OF_RANGE",function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n},RangeError);const $=/[^+/0-9A-Za-z-_]/g;function W(e,t){let r;t=t||1/0;const n=e.length;let i=null;const s=[];for(let o=0;o<n;++o){if(r=e.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function J(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace($,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(e,t,r,n){let i;for(i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function G(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},8392:t=>{"use strict";t.exports=e},8936:(e,t,r)=>{"use strict";r.d(t,{A:()=>i});var n=r(4705);class i{constructor(e){(0,n.A)(this,"termType",void 0),(0,n.A)(this,"classOrder",void 0),(0,n.A)(this,"value",void 0),this.value=e}substitute(e){return this}compareTerm(e){return this.classOrder<e.classOrder?-1:this.classOrder>e.classOrder?1:this.value<e.value?-1:this.value>e.value?1:0}equals(e){return!!e&&(this.termType===e.termType&&this.value===e.value)}hashString(){return this.toCanonical()}sameTerm(e){return this.equals(e)}toCanonical(){return this.toNT()}toNT(){return this.toString()}toNQ(){return this.toNT()}toString(){throw new Error("Node.toString() is abstract - see the subclasses instead")}}(0,n.A)(i,"fromValue",void 0),(0,n.A)(i,"toJS",void 0)},9403:(e,t,r)=>{"use strict";r.d(t,{$Q:()=>i,BR:()=>g,Fn:()=>b,H:()=>E,JG:()=>m,K9:()=>w,Kk:()=>n,MG:()=>p,P2:()=>o,QW:()=>s,S:()=>c,_0:()=>y,bD:()=>h,bM:()=>v,hu:()=>S,i2:()=>d,ic:()=>a,lc:()=>l,ny:()=>f,r0:()=>u,sT:()=>_});const n="NamedNode",i="BlankNode",s="Literal",o="Variable",a="DefaultGraph",u="Collection",c="Empty",h="Graph",l="text/html",d="application/ld+json",f="text/n3",p="application/n3",g="application/nquads",y="application/n-quads",v="application/n-triples",m="application/rdf+xml",w="application/sparql-update",b="application/sparql-update-single-match",_="text/turtle",S="application/x-turtle",E="application/xhtml+xml"}},o={};function a(e){var t=o[e];if(void 0!==t)return t.exports;var r=o[e]={id:e,loaded:!1,exports:{}};return s[e].call(r.exports,r,r.exports,a),r.loaded=!0,r.exports}a.m=s,a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,a.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var i=Object.create(null);a.r(i);var s={};t=t||[null,r({}),r([]),r(r)];for(var o=2&n&&e;("object"==typeof o||"function"==typeof o)&&!~t.indexOf(o);o=r(o))Object.getOwnPropertyNames(o).forEach(t=>s[t]=()=>e[t]);return s.default=()=>e,a.d(i,s),i},a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.f={},a.e=e=>Promise.all(Object.keys(a.f).reduce((t,r)=>(a.f[r](e,t),t),[])),a.u=e=>e+".solid-logic.min.js",a.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),a.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},i="SolidLogic:",a.l=(e,t,r,s)=>{if(n[e])n[e].push(t);else{var o,u;if(void 0!==r)for(var c=document.getElementsByTagName("script"),h=0;h<c.length;h++){var l=c[h];if(l.getAttribute("src")==e||l.getAttribute("data-webpack")==i+r){o=l;break}}o||(u=!0,(o=document.createElement("script")).charset="utf-8",o.timeout=120,a.nc&&o.setAttribute("nonce",a.nc),o.setAttribute("data-webpack",i+r),o.src=e),n[e]=[t];var d=(t,r)=>{o.onerror=o.onload=null,clearTimeout(f);var i=n[e];if(delete n[e],o.parentNode&&o.parentNode.removeChild(o),i&&i.forEach(e=>e(r)),t)return t(r)},f=setTimeout(d.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=d.bind(null,o.onerror),o.onload=d.bind(null,o.onload),u&&document.head.appendChild(o)}},a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;a.g.importScripts&&(e=a.g.location+"");var t=a.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var n=r.length-1;n>-1&&(!e||!/^http(s?):/.test(e));)e=r[n--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),a.p=e})(),(()=>{var e={792:0};a.f.j=(t,r)=>{var n=a.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var i=new Promise((r,i)=>n=e[t]=[r,i]);r.push(n[2]=i);var s=a.p+a.u(t),o=new Error;a.l(s,r=>{if(a.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var i=r&&("load"===r.type?"missing":r.type),s=r&&r.target&&r.target.src;o.message="Loading chunk "+t+" failed.\n("+i+": "+s+")",o.name="ChunkLoadError",o.type=i,o.request=s,n[1](o)}},"chunk-"+t,t)}};var t=(t,r)=>{var n,i,[s,o,u]=r,c=0;if(s.some(t=>0!==e[t])){for(n in o)a.o(o,n)&&(a.m[n]=o[n]);if(u)u(a)}for(t&&t(r);c<s.length;c++)i=s[c],a.o(e,i)&&e[i]&&e[i][0](),e[i]=0},r=this.webpackChunkSolidLogic=this.webpackChunkSolidLogic||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})();var u={};return(()=>{"use strict";a.r(u),a.d(u,{ACL_LINK:()=>rs,appContext:()=>is,authSession:()=>As,authn:()=>xs,createTypeIndexLogic:()=>bs,getSuggestedIssuers:()=>Es,offlineTestID:()=>ss,solidLogicSingleton:()=>_s,store:()=>Fs});var e={};function t(...e){console.log(...e)}function r(...e){console.warn(...e)}a.r(e),a.d(e,{BlankNode:()=>tr,Collection:()=>ar,ConnectedStore:()=>Zi,DataFactory:()=>Ui,Empty:()=>ur,Fetcher:()=>ki,Formula:()=>Ur,IndexedFormula:()=>Kr,Literal:()=>sr,LiveStore:()=>es,N3Parser:()=>fn,NamedNode:()=>rr.A,Namespace:()=>_r,NextId:()=>Qi,Node:()=>Or,Query:()=>Dr,RDFParser:()=>ui,RDFaProcessor:()=>oi,SPARQLToQuery:()=>Ri,Serializer:()=>Tr,Statement:()=>fr,Store:()=>Kr,UpdateManager:()=>Pi,UpdatesSocket:()=>Oi,UpdatesVia:()=>Li,Util:()=>Sr,Variable:()=>gr,blankNode:()=>Vi,defaultGraph:()=>$i,fetcher:()=>ji,fromNT:()=>Gi,graph:()=>Mi,isBlankNode:()=>nr.jt,isCollection:()=>nr.P3,isGraph:()=>nr.RN,isLiteral:()=>nr.c$,isNamedNode:()=>nr.Y2,isPredicate:()=>nr.YC,isQuad:()=>nr.aF,isRDFObject:()=>nr.GE,isRDFlibObject:()=>nr.DJ,isRDFlibPredicate:()=>nr.fY,isRDFlibSubject:()=>nr.CZ,isStatement:()=>nr.SH,isStore:()=>nr.ok,isSubject:()=>nr.hr,isTerm:()=>nr.D0,isVariable:()=>nr.DZ,jsonParser:()=>Ii,lit:()=>Bi,literal:()=>Wi,log:()=>br.A,namedNode:()=>qi,parse:()=>hi,quad:()=>Ji,queryToSPARQL:()=>Ci,serialize:()=>Ir,sparqlUpdateParser:()=>ci,st:()=>Hi,sym:()=>qi,term:()=>Yi,termValue:()=>fi.E,triple:()=>zi,uri:()=>pr,variable:()=>Ki});const n=new TextEncoder,i=new TextDecoder;function s(...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 o=e=>(e=>{let t=e;"string"==typeof t&&(t=n.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,"_"),c=e=>{let t=e;t instanceof Uint8Array&&(t=i.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 h extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}h.code="ERR_JOSE_GENERIC";class l extends h{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}l.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class d extends h{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}}d.code="ERR_JWT_EXPIRED";class f extends h{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}f.code="ERR_JOSE_ALG_NOT_ALLOWED";class p extends h{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}p.code="ERR_JOSE_NOT_SUPPORTED";(class extends h{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends h{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class g extends h{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}g.code="ERR_JWS_INVALID";class y extends h{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}y.code="ERR_JWT_INVALID";(class extends h{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";class v extends h{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}v.code="ERR_JWKS_INVALID";class m extends h{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}m.code="ERR_JWKS_NO_MATCHING_KEY";class w extends h{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,w.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class b extends h{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}b.code="ERR_JWKS_TIMEOUT";class _ extends h{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function S(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new p(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}_.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const E=crypto,x=e=>e instanceof CryptoKey,A=(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 F(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function T(e,t){return e.name===t}function k(e){return parseInt(e.name.slice(4),10)}function I(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 C(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!T(e.algorithm,"HMAC"))throw F("HMAC");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw F(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!T(e.algorithm,"RSASSA-PKCS1-v1_5"))throw F("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw F(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!T(e.algorithm,"RSA-PSS"))throw F("RSA-PSS");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw F(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw F("Ed25519 or Ed448");break;case"Ed25519":if(!T(e.algorithm,"Ed25519"))throw F("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!T(e.algorithm,"ECDSA"))throw F("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 F(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}I(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}const P=(e,...t)=>R("Key must be ",e,...t);function N(e,t,...r){return R(`Key for the ${e} algorithm must be `,t,...r)}const U=e=>!!x(e)||"KeyObject"===e?.[Symbol.toStringTag],O=["CryptoKey"];function L(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function D(e){return L(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 p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new p('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,E.subtle.importKey("jwk",i,...n)},M=e=>c(e);let B,H;const q=e=>"KeyObject"===e?.[Symbol.toStringTag],K=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},V=(e,t)=>{if(q(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?M(r.k):(H||(H=new WeakMap),K(H,e,r,t))}if(D(e)){if(e.k)return c(e.k);H||(H=new WeakMap);return K(H,e,e,t,!0)}return e},$=(e,t)=>{if(q(e)){let r=e.export({format:"jwk"});return r.k?M(r.k):(B||(B=new WeakMap),K(B,e,r,t))}if(D(e)){if(e.k)return c(e.k);B||(B=new WeakMap);return K(B,e,e,t,!0)}return e};async function W(e,t,r){if("sign"===r&&(t=await $(t,e)),"verify"===r&&(t=await V(t,e)),x(t))return C(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(P(t,...O));return E.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(P(t,...O,"Uint8Array","JSON Web Key"))}const J=async(e,t,r,n)=>{const i=await W(e,t,"verify");A(e,i);const s=S(e,i.algorithm);try{return await E.subtle.verify(s,i,r,n)}catch{return!1}},z=(...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},X=e=>e?.[Symbol.toStringTag],G=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Y=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&D(t)){if(function(e){return D(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&G(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!U(t))throw new TypeError(N(e,t,...O,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${X(t)} instances for symmetric algorithms must be of type "secret"`)}};function Q(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&&D(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!U(t))throw new TypeError(N(e,t,...O,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}Q.bind(void 0,!1);const Z=Q.bind(void 0,!0);const ee=function(e,t,r,n,i){if(void 0!==i.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!s.has(t))throw new p(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)},te=(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 re(e,t){if(!L(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return c(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new p('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return j({...e,alg:t});default:throw new p('Unsupported "kty" (Key Type) Parameter value')}}async function ne(e,t,r){if(e instanceof Uint8Array&&(e=i.decode(e)),"string"!=typeof e)throw new g("Compact JWS must be a string or Uint8Array");const{0:o,1:a,2:u,length:h}=e.split(".");if(3!==h)throw new g("Invalid Compact JWS");const l=await async function(e,t,r){if(!L(e))throw new g("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new g('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new g("JWS Protected Header incorrect type");if(void 0===e.payload)throw new g("JWS Payload missing");if("string"!=typeof e.signature)throw new g("JWS Signature missing or incorrect type");if(void 0!==e.header&&!L(e.header))throw new g("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=c(e.protected);o=JSON.parse(i.decode(t))}catch{throw new g("JWS Protected Header is invalid")}if(!z(o,e.header))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const a={...o,...e.header};let u=!0;if(ee(g,new Map([["b64",!0]]),r?.crit,o,a).has("b64")&&(u=o.b64,"boolean"!=typeof u))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:h}=a;if("string"!=typeof h||!h)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=r&&te("algorithms",r.algorithms);if(l&&!l.has(h))throw new f('"alg" (Algorithm) Header Parameter value not allowed');if(u){if("string"!=typeof e.payload)throw new g("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new g("JWS Payload must be a string or an Uint8Array instance");let d=!1;"function"==typeof t?(t=await t(o,e),d=!0,Z(h,t,"verify"),D(t)&&(t=await re(t,h))):Z(h,t,"verify");const p=s(n.encode(e.protected??""),n.encode("."),"string"==typeof e.payload?n.encode(e.payload):e.payload);let y,v;try{y=c(e.signature)}catch{throw new g("Failed to base64url decode the signature")}if(!await J(h,t,y,p))throw new _;if(u)try{v=c(e.payload)}catch{throw new g("Failed to base64url decode the payload")}else v="string"==typeof e.payload?n.encode(e.payload):e.payload;const m={payload:v};return void 0!==e.protected&&(m.protectedHeader=o),void 0!==e.header&&(m.unprotectedHeader=e.header),d?{...m,key:t}:m}({payload:a,protected:o,signature:u},t,r),d={payload:l.payload,protectedHeader:l.protectedHeader};return"function"==typeof t?{...d,key:l.key}:d}const ie=e=>Math.floor(e.getTime()/1e3),se=86400,oe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ae=e=>{const t=oe.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*se);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},ue=e=>e.toLowerCase().replace(/^application\//,""),ce=(e,t,r={})=>{let n;try{n=JSON.parse(i.decode(t))}catch{}if(!L(n))throw new y("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&("string"!=typeof e.typ||ue(e.typ)!==ue(s)))throw new l('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:o=[],issuer:a,subject:u,audience:c,maxTokenAge:h}=r,f=[...o];void 0!==h&&f.push("iat"),void 0!==c&&f.push("aud"),void 0!==u&&f.push("sub"),void 0!==a&&f.push("iss");for(const e of new Set(f.reverse()))if(!(e in n))throw new l(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new l('unexpected "iss" claim value',n,"iss","check_failed");if(u&&n.sub!==u)throw new l('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(p=n.aud,g="string"==typeof c?[c]:c,!("string"==typeof p?g.includes(p):Array.isArray(p)&&g.some(Set.prototype.has.bind(new Set(p))))))throw new l('unexpected "aud" claim value',n,"aud","check_failed");var p,g;let v;switch(typeof r.clockTolerance){case"string":v=ae(r.clockTolerance);break;case"number":v=r.clockTolerance;break;case"undefined":v=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,w=ie(m||new Date);if((void 0!==n.iat||h)&&"number"!=typeof n.iat)throw new l('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new l('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>w+v)throw new l('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new l('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=w-v)throw new d('"exp" claim timestamp check failed',n,"exp","check_failed")}if(h){const e=w-n.iat;if(e-v>("number"==typeof h?h:ae(h)))throw new d('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-v)throw new l('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};const he=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 b;throw e});if(void 0!==i&&clearTimeout(i),200!==o.status)throw new h("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new h("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function le(e){return L(e)}function de(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class fe{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(le)}(e))throw new v("JSON Web Key Set malformed");this._jwks=de(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},i=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new p('Unsupported "alg" value for a JSON Web Key Set')}}(r),s=this._jwks.keys.filter(e=>{let t=i===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:o,length:a}=s;if(0===a)throw new m;if(1!==a){const e=new w,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of s)try{yield await pe(t,e,r)}catch{}},e}return pe(this._cached,o,r)}}async function pe(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await re({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new v("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function ge(e){const t=new fe(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>de(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 ve=Symbol();class me{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?.[ve]&&(this._cache=t?.[ve],r=t?.[ve],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&L(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,L)&&(this._jwksTimestamp=this._cache.uat,this._local=ge(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof m&&!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=he(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 we=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:o(e)};if(!x(e))throw new TypeError(P(e,...O,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:i,...s}=await E.subtle.exportKey("jwk",e);return s};async function be(e){return we(e)}const _e=async(e,t,r)=>{const n=await W(e,t,"sign");A(e,n);const i=await E.subtle.sign(S(e,n.algorithm),n,r);return new Uint8Array(i)};class Se{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new g("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!z(this._protectedHeader,this._unprotectedHeader))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let a=!0;if(ee(g,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(a=this._protectedHeader.b64,"boolean"!=typeof a))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:u}=r;if("string"!=typeof u||!u)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');Z(u,e,"sign");let c,h=this._payload;a&&(h=n.encode(o(h))),c=this._protectedHeader?n.encode(o(JSON.stringify(this._protectedHeader))):n.encode("");const l=s(c,n.encode("."),h),d=await _e(u,e,l),f={signature:o(d),payload:""};return a&&(f.payload=i.decode(h)),this._unprotectedHeader&&(f.header=this._unprotectedHeader),this._protectedHeader&&(f.protected=i.decode(c)),f}}class Ee{constructor(e){this._flattened=new Se(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function xe(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Ae{constructor(e={}){if(!L(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:xe("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:xe("setNotBefore",ie(e))}:this._payload={...this._payload,nbf:ie(new Date)+ae(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:xe("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:xe("setExpirationTime",ie(e))}:this._payload={...this._payload,exp:ie(new Date)+ae(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:ie(new Date)}:e instanceof Date?this._payload={...this._payload,iat:xe("setIssuedAt",ie(e))}:this._payload="string"==typeof e?{...this._payload,iat:xe("setIssuedAt",ie(new Date)+ae(e))}:{...this._payload,iat:xe("setIssuedAt",e)},this}}class Fe extends Ae{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new Ee(n.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 Te(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new p("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function ke(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Te(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Te(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Te(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new p("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new p("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return E.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const Ie={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let Ce;const Re=new Uint8Array(16);const Pe=[];for(let e=0;e<256;++e)Pe.push((e+256).toString(16).slice(1));function Ne(e,t=0){return(Pe[e[t+0]]+Pe[e[t+1]]+Pe[e[t+2]]+Pe[e[t+3]]+"-"+Pe[e[t+4]]+Pe[e[t+5]]+"-"+Pe[e[t+6]]+Pe[e[t+7]]+"-"+Pe[e[t+8]]+Pe[e[t+9]]+"-"+Pe[e[t+10]]+Pe[e[t+11]]+Pe[e[t+12]]+Pe[e[t+13]]+Pe[e[t+14]]+Pe[e[t+15]]).toLowerCase()}const Ue=function(e,t,r){if(Ie.randomUUID&&!t&&!e)return Ie.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!Ce){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ce=crypto.getRandomValues.bind(crypto)}return Ce(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 Ne(n)},Oe="solidClientAuthn:",Le=["ES256","RS256"],De="error",je="login",Me="logout",Be="newRefreshToken",He="sessionExpired",qe="sessionExtended",Ke="sessionRestore",Ve="timeoutSet",$e=["openid","offline_access","webid"];class We{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 Je(e,t,r,n){let i,s;try{const{payload:s}=await async function(e,t,r){const n=await ne(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:ce(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}(e,function(e,t){const r=new me(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 ze(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 Xe(e){const t=new URL(e);return t.searchParams.delete("state"),t.searchParams.delete("code"),t.searchParams.delete("error"),t.searchParams.delete("error_description"),t.searchParams.delete("iss"),t}class Ge{storageUtility;redirector;constructor(e,t){this.storageUtility=e,this.redirector=t,this.storageUtility=e,this.redirector=t}parametersGuard=e=>void 0!==e.issuerConfiguration.grantTypesSupported&&e.issuerConfiguration.grantTypesSupported.indexOf("authorization_code")>-1&&void 0!==e.redirectUrl;async canHandle(e){return this.parametersGuard(e)}async setupRedirectHandler({oidcLoginOptions:e,state:t,codeVerifier:r,targetUrl:n}){if(!this.parametersGuard(e))throw new Error("The authorization code grant requires a redirectUrl.");var i,s;await Promise.all([this.storageUtility.setForUser(t,{sessionId:e.sessionId}),this.storageUtility.setForUser(e.sessionId,{codeVerifier:r,issuer:e.issuer.toString(),redirectUrl:e.redirectUrl,dpop:Boolean(e.dpop).toString(),keepAlive:(i=e.keepAlive,s=!0,"boolean"==typeof i?Boolean(i):Boolean(s)).toString()})]),this.redirector.redirect(n,{handleRedirect:e.handleRedirect})}}class Ye{sessionInfoManager;constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class Qe{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 Ze{handlers;constructor(e,t){this.handlers=[new Ye(e),new Qe(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 et(){return{isLoggedIn:!1,sessionId:Ue(),fetch:(...e)=>fetch(...e)}}async function tt(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}class rt{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 tt(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 nt({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 it(e){try{return new URL(e),!0}catch{return!1}}async function st(e,t,r,n){let i;if(function(e,t){return t.scopesSupported.includes("webid")&&void 0!==e.clientId&&it(e.clientId)}(e,t))i={clientId:e.clientId,clientName:e.clientName,clientType:"solid-oidc"};else{if(!function(e){return void 0!==e.clientId&&!it(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 ot=(e,t)=>fetch(e,t);class at{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=ot;logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===t?.logoutType?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=ot,delete this.boundLogout};getSessionInfo=async e=>this.sessionInfoManager.get(e);getAllSessionInfo=async()=>this.sessionInfoManager.getAll()}async function ut(e,t,r){try{const[n,i,s,o,a]=await Promise.all([t.getForUser(e,"issuer",{errorIfNull:!0}),t.getForUser(e,"codeVerifier"),t.getForUser(e,"redirectUrl"),t.getForUser(e,"dpop",{errorIfNull:!0}),t.getForUser(e,"keepAlive")]);await t.deleteForUser(e,"codeVerifier");return{codeVerifier:i,redirectUrl:s,issuerConfig:await r.fetchConfig(n),dpop:"true"===o,keepAlive:"string"!=typeof a||"true"===a}}catch(t){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${e}]: ${t}`)}}class ct{secureStorage;insecureStorage;constructor(e,t){this.secureStorage=e,this.insecureStorage=t,this.secureStorage=e,this.insecureStorage=t}getKey(e){return`solidClientAuthenticationUser:${e}`}async getUserData(e,t){const r=await(t?this.secureStorage:this.insecureStorage).get(this.getKey(e));if(void 0===r)return{};try{return JSON.parse(r)}catch(n){throw new Error(`Data for user [${e}] in [${t?"secure":"unsecure"}] storage is corrupted - expected valid JSON, but got: ${r}`)}}async setUserData(e,t,r){await(r?this.secureStorage:this.insecureStorage).set(this.getKey(e),JSON.stringify(t))}async get(e,t){const r=await(t?.secure?this.secureStorage:this.insecureStorage).get(e);if(void 0===r&&t?.errorIfNull)throw new Error(`[${e}] is not stored`);return r}async set(e,t,r){return(r?.secure?this.secureStorage:this.insecureStorage).set(e,t)}async delete(e,t){return(t?.secure?this.secureStorage:this.insecureStorage).delete(e)}async getForUser(e,t,r){const n=await this.getUserData(e,r?.secure);let i;if(n&&n[t]||(i=void 0),i=n[t],void 0===i&&r?.errorIfNull)throw new Error(`Field [${t}] for user [${e}] is not stored`);return i||void 0}async setForUser(e,t,r){let n;try{n=await this.getUserData(e,r?.secure)}catch{n={}}await this.setUserData(e,{...n,...t},r?.secure)}async deleteForUser(e,t,r){const n=await this.getUserData(e,r?.secure);delete n[t],await this.setUserData(e,n,r?.secure)}async deleteAllUserData(e,t){await(t?.secure?this.secureStorage:this.insecureStorage).delete(this.getKey(e))}}class ht{map={};async get(e){return this.map[e]||void 0}async set(e,t){this.map[e]=t}async delete(e){delete this.map[e]}}class lt extends Error{constructor(e){super(e)}}Error;class dt extends Error{missingFields;constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class ft extends Error{error;errorDescription;constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function pt(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function gt(e,t,r){return new Fe({htu:pt(e),htm:t.toUpperCase(),jti:Ue()}).setProtectedHeader({alg:Le[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 gt(e,n?.method??"get",r)),{...n,headers:i}}(e,t,r,n);const i=new Headers(n?.headers);return i.set("Authorization",`Bearer ${t}`),{...n,headers:i}}async function vt(e,t,r,n,i=fetch){return i(t,await yt(t.toString(),e,n,r))}const mt=e=>void 0!==e?e-5>0?e-5:e:600;function wt(e,t){let r,n=e;const i=t?.refreshOptions;if(void 0!==i){const e=async()=>{try{const{accessToken:s,refreshToken:o,expiresIn:a}=await async function(e,t,r){const n=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return r?.emit(qe,n.expiresIn??600),{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn}}(i,t.dpopKey,t.eventEmitter);n=s,void 0!==o&&(i.refreshToken=o),clearTimeout(r),r=setTimeout(e,1e3*mt(a)),t.eventEmitter?.emit(Ve,r)}catch(e){e instanceof ft&&(t?.eventEmitter?.emit(De,e.error,e.errorDescription),t?.eventEmitter?.emit(He)),e instanceof dt&&e.missingFields.includes("access_token")&&t?.eventEmitter?.emit(He)}};r=setTimeout(e,1e3*mt(t.expiresIn)),t.eventEmitter?.emit(Ve,r)}else if(void 0!==t&&void 0!==t.eventEmitter){const e=setTimeout(()=>{t.eventEmitter.emit(He)},1e3*mt(t.expiresIn));t.eventEmitter.emit(Ve,e)}return async(e,r)=>{let i=await vt(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 vt(n,i.url,r,t.dpopKey,t.fetch)),i}}var bt=a(7007),_t=a(6516);function St(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 Et(e,t){if(!t.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(t.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const r=(n=t.idTokenSigningAlgValuesSupported,Le.find(e=>n.includes(e))??null);var n;const i={client_name:e.clientName,application_type:"web",redirect_uris:[e.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:r,grant_types:["authorization_code","refresh_token"]},s=await fetch(t.registrationEndpoint.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(s.ok){const t=await s.json();return St(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 xt(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function At(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new ft(`Token endpoint returned error [${e.error}]${xt(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,xt(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 dt(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new dt(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new dt(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new dt(["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 Ft(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 ke(Le[0]),r={privateKey:e,publicKey:await be(t)};return[r.publicKey.alg]=Le,r}(),i.DPoP=await gt(e.tokenEndpoint,"POST",s)),t.clientSecret&&(i.Authorization=`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`);const o={grant_type:r.grantType,redirect_uri:r.redirectUrl,code:r.code,code_verifier:r.codeVerifier,client_id:t.clientId},a={method:"POST",headers:i,body:new URLSearchParams(o).toString()},u=await fetch(e.tokenEndpoint,a),c=At(await u.json(),n),{webId:h,clientId:l}=await Je(c.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:(d=c,void 0!==d.refresh_token&&"string"==typeof d.refresh_token?c.refresh_token:void 0),webId:h,clientId:l,dpopKey:s,expiresIn:c.expires_in};var d}async function Tt(e,t,r,n){if(void 0===r.clientId)throw new Error("No client ID available when trying to refresh the access token.");const i={grant_type:"refresh_token",refresh_token:e};let s={};void 0!==n&&(s={DPoP:await gt(t.tokenEndpoint,"POST",n)});let o={};void 0!==r.clientSecret?o={Authorization:`Basic ${btoa(`${r.clientId}:${r.clientSecret}`)}`}:(e=>{try{return new URL(e),!0}catch{return!1}})(r.clientId)&&(i.client_id=r.clientId);const a=await fetch(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(i).toString(),headers:{...s,...o,"Content-Type":"application/x-www-form-urlencoded"}});let u;try{u=await a.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const c=At(u,void 0!==n),{webId:h}=await Je(c.id_token,t.jwksUri,t.issuer,r.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:"string"==typeof c.refresh_token?c.refresh_token:void 0,webId:h,dpopKey:n,expiresIn:c.expires_in}}class kt extends ct{constructor(e,t){super(e,t)}}class It extends at{login=async(e,t)=>{"none"!==e.prompt&&await this.sessionInfoManager.clear(e.sessionId);const r=e.redirectUrl??function(e){const t=Xe(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}(window.location.href);if(!ze(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?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(De,"redirect",r)}};async cleanUrlAfterRedirect(e){const t=Xe(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(e=>{setTimeout(()=>e(),1)})}}function Ct(e){return"string"==typeof e.oidcIssuer}function Rt(e){return"string"==typeof e.redirectUrl}class Pt{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 Ct(e)&&Rt(e)}async handle(e){if(!Ct(e))throw new lt(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!Rt(e))throw new lt(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await st(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([...$e,...i.filter(e=>"string"==typeof e&&!e.includes(" "))])):$e)};var i;return this.oidcHandler.handle(n)}}class Nt extends Ge{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},r=new _t.OidcClient(t);try{const t=await r.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 Ut={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 Ot{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=>{Ut[r]&&(t[Ut[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await n.json())}catch(t){throw new lt(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(Ot.getLocalStorageKey(e),JSON.stringify(t)),t}}async function Lt(e,t){await tt(e,t),await async function(){const e=new _t.OidcClient({response_mode:"query"});await e.clearStaleState(new _t.WebStorageStateStore({}));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 Dt extends rt{async get(e){const[t,r,n,i,s,o,a,u]=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})]);if("string"!=typeof s||ze(s)){if(void 0!==u&&("string"!=typeof(c=u)||!["DPoP","Bearer"].includes(c)))throw new Error(`Tokens of type [${u}] are not supported.`);var c;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:u??"DPoP"}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return Lt(e,this.storageUtility)}}class jt{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 et()}}class Mt{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:u}=await ut(i,this.storageUtility,this.issuerConfigFetcher),c=r.searchParams.get("iss");if("string"==typeof c&&c!==s.issuer)throw new Error(`The value of the iss parameter (${c}) 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 h=await this.clientRegistrar.getClient({sessionId:i},s),l=Date.now(),d=await Ft(s,h,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:o,redirectUrl:a},u);let f;window.localStorage.removeItem(`oidc.${n}`),void 0!==d.refreshToken&&(f={sessionId:i,refreshToken:d.refreshToken,tokenRefresher:this.tokerRefresher});const p=wt(d.accessToken,{dpopKey:d.dpopKey,refreshOptions:f,eventEmitter:t,expiresIn:d.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 be(a.privateKey))},{secure:o})}(this.storageUtility,i,d.webId,d.clientId,"true",void 0,!0);const g=await this.sessionInfoManager.get(i);if(!g)throw new Error(`Could not retrieve session: [${i}].`);return Object.assign(g,{fetch:p,getLogoutUrl:nt({idTokenHint:d.idToken,endSessionEndpoint:s.endSessionEndpoint}),expirationDate:"number"==typeof d.expiresIn?l+1e3*d.expiresIn:void 0})}}class Bt extends We{constructor(e){super(e)}}class Ht{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 qt{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class Kt{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,u=void 0!==n&&0!==a&&Math.floor(Date.now()/1e3)>a;if(r&&("string"==typeof(c=o)&&["dynamic","static","solid-oidc"].includes(c))&&!u)return void 0!==n?{clientId:r,clientSecret:n,clientName:s,clientType:"dynamic",expiresAt:a}:{clientId:r,clientName:s,clientType:o};var c;try{const r=await Et(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 Vt{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(De,n,i)}return et()}}class $t{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 ut(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 Tt(t,i.issuerConfig,s,r);return void 0!==o.refreshToken&&n?.emit(Be,o.refreshToken),o}}function Wt(e){const t=new ht,r=e.secureStorage||t,n=e.insecureStorage||new Ht,i=new kt(r,n),s=new Ot(i),o=new Kt(i),a=new Dt(i),u=new $t(i,s,o),c=new qt,h=new Pt(i,new Nt(i,c),s,o),l=new Bt([new Vt,new Mt(i,a,s,o,u),new jt]);return new It(h,l,new Ze(a,c),a,s)}const Jt=`${Oe}currentSession`,zt=`${Oe}currentUrl`;class Xt{info;events;clientAuthentication;tokenRequestInProgress=!1;constructor(e={},t=void 0){this.events=new bt,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=Wt({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=Wt({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??Ue(),isLoggedIn:!1},this.events.on(je,()=>window.localStorage.setItem(Jt,this.info.sessionId)),this.events.on(He,()=>this.internalLogout(!1)),this.events.on(De,()=>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(Jt),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(Me)};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(zt);null===e?this.events.emit(je):(window.localStorage.removeItem(zt),this.events.emit(Ke,e))}else if(!0===t.restorePreviousSession){const e=window.localStorage.getItem(Jt);if(null!==e){if(await async function(e,t,r){const n=await t.validateCurrentSession(e);return null!==n&&(window.localStorage.setItem(zt,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(qe,e=>{this.info.expirationDate=Date.now()+1e3*e})}}const Gt=new Xt;var Yt=a(4705),Qt=a(1059),Zt=a(8936),er=a(9403);class tr extends Zt.A{static getId(e){if(e){if("string"!=typeof e)throw new Error("Bad id argument to new blank node: "+e);if(e.includes("#")){let t=e.split("#");return t[t.length-1]}return e}return"n"+tr.nextId++}constructor(e){super(tr.getId(e)),(0,Yt.A)(this,"termType",er.$Q),(0,Yt.A)(this,"classOrder",Qt.A.BlankNode),(0,Yt.A)(this,"isBlank",1),(0,Yt.A)(this,"isVar",1)}get id(){return this.value}set id(e){this.value=e}compareTerm(e){return this.classOrder<e.classOrder?-1:this.classOrder>e.classOrder?1:this.id<e.id?-1:this.id>e.id?1:0}copy(e){var t=new tr;return e.copyTo(this,t),t}toCanonical(){return tr.NTAnonymousNodePrefix+this.value}toString(){return tr.NTAnonymousNodePrefix+this.id}}(0,Yt.A)(tr,"nextId",0),(0,Yt.A)(tr,"NTAnonymousNodePrefix","_:");var rr=a(5108),nr=a(2915);const ir={boolean:new rr.A("http://www.w3.org/2001/XMLSchema#boolean"),dateTime:new rr.A("http://www.w3.org/2001/XMLSchema#dateTime"),decimal:new rr.A("http://www.w3.org/2001/XMLSchema#decimal"),double:new rr.A("http://www.w3.org/2001/XMLSchema#double"),integer:new rr.A("http://www.w3.org/2001/XMLSchema#integer"),langString:new rr.A("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),string:new rr.A("http://www.w3.org/2001/XMLSchema#string")};class sr extends Zt.A{constructor(e,t,r){super(e),(0,Yt.A)(this,"termType",er.QW),(0,Yt.A)(this,"classOrder",Qt.A.Literal),(0,Yt.A)(this,"datatype",ir.string),(0,Yt.A)(this,"isVar",0),(0,Yt.A)(this,"language",""),t?(this.language=t,this.datatype=ir.langString):this.datatype=r?rr.A.fromValue(r):ir.string}copy(){return new sr(this.value,this.lang,this.datatype)}equals(e){return!!e&&(this.termType===e.termType&&this.value===e.value&&this.language===e.language&&(!this.datatype&&!e.datatype||this.datatype&&this.datatype.equals(e.datatype)))}get lang(){return this.language}set lang(e){this.language=e||""}toNT(){return sr.toNT(this)}static toNT(e){if("number"==typeof e.value)return""+e.value;if("string"!=typeof e.value)throw new Error("Value of RDF literal is not string or number: "+e.value);var t=e.value;return t='"'+(t=(t=(t=(t=t.replace(/\\/g,"\\\\")).replace(/\"/g,'\\"')).replace(/\n/g,"\\n")).replace(/\r/g,"\\r"))+'"',e.language?t+="@"+e.language:e.datatype.equals(ir.string)||(t+="^^"+e.datatype.toCanonical()),t}toString(){return""+this.value}static fromBoolean(e){return new sr(e?"1":"0",null,ir.boolean)}static fromDate(e){if(!(e instanceof Date))throw new TypeError("Invalid argument to Literal.fromDate()");let t=function(e){return(""+(100+e)).slice(1,3)},r=e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"Z";return new sr(r,null,ir.dateTime)}static fromNumber(e){if("number"!=typeof e)throw new TypeError("Invalid argument to Literal.fromNumber()");let t;const r=e.toString();return t=r.indexOf("e")<0&&Math.abs(e)<=Number.MAX_SAFE_INTEGER?Number.isInteger(e)?ir.integer:ir.decimal:ir.double,new sr(r,null,t)}static fromValue(e){if((0,nr.c$)(e))return e;switch(typeof e){case"object":if(e instanceof Date)return sr.fromDate(e);case"boolean":return sr.fromBoolean(e);case"number":return sr.fromNumber(e);case"string":return new sr(e)}throw new Error("Can't make literal from "+e+" of type "+typeof e)}}function or(e){return null==e||(0,nr.D0)(e)?e:Array.isArray(e)?new ar(e):sr.fromValue(e)}class ar extends Zt.A{constructor(e){super((tr.nextId++).toString()),(0,Yt.A)(this,"termType",er.r0),(0,Yt.A)(this,"classOrder",Qt.A.Collection),(0,Yt.A)(this,"closed",!1),(0,Yt.A)(this,"compareTerm",tr.prototype.compareTerm),(0,Yt.A)(this,"elements",[]),(0,Yt.A)(this,"isVar",0),e&&e.length>0&&e.forEach(e=>{this.elements.push(or(e))})}get id(){return this.value}set id(e){this.value=e}append(e){return this.elements.push(e)}close(){return this.closed=!0,this.closed}shift(){return this.elements.shift()}substitute(e){const t=this.elements.map(t=>t.substitute(e));return new ar(t)}toNT(){return ar.toNT(this)}static toNT(e){return tr.NTAnonymousNodePrefix+e.id}toString(){return"("+this.elements.join(" ")+")"}unshift(e){return this.elements.unshift(e)}}(0,Yt.A)(ar,"termType",er.r0);class ur extends Zt.A{constructor(){super(""),(0,Yt.A)(this,"termType",er.S)}toString(){return"()"}}const cr="chrome:theSession";new rr.A(cr);class hr extends Zt.A{constructor(){super(""),(0,Yt.A)(this,"value",""),(0,Yt.A)(this,"termType",er.ic),(0,Yt.A)(this,"uri",cr)}toCanonical(){return this.value}toString(){return"DefaultGraph"}}function lr(e){return!!e&&e.termType===er.ic}const dr=new hr;class fr{constructor(e,t,r,n){(0,Yt.A)(this,"subject",void 0),(0,Yt.A)(this,"predicate",void 0),(0,Yt.A)(this,"object",void 0),(0,Yt.A)(this,"graph",void 0),this.subject=Zt.A.fromValue(e),this.predicate=Zt.A.fromValue(t),this.object=Zt.A.fromValue(r),this.graph=null==n?dr:Zt.A.fromValue(n)}get why(){return this.graph}set why(e){this.graph=e}equals(e){return e.subject.equals(this.subject)&&e.predicate.equals(this.predicate)&&e.object.equals(this.object)&&e.graph.equals(this.graph)}substitute(e){return new fr(this.subject.substitute(e),this.predicate.substitute(e),this.object.substitute(e),lr(this.graph)?this.graph:this.graph.substitute(e))}toCanonical(){let e=[this.subject.toCanonical(),this.predicate.toCanonical(),this.object.toCanonical()];return this.graph&&this.graph.termType!==er.ic&&e.push(this.graph.toCanonical()),e.join(" ")+" ."}toNT(){return[this.subject.toNT(),this.predicate.toNT(),this.object.toNT()].join(" ")+" ."}toNQ(){return[this.subject.toNT(),this.predicate.toNT(),this.object.toNT(),lr(this.graph)?"":this.graph.toNT()].join(" ")+" ."}toString(){return this.toNT()}}var pr=a(2727);class gr extends Zt.A{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";super(e),(0,Yt.A)(this,"termType",er.P2),(0,Yt.A)(this,"base","varid:"),(0,Yt.A)(this,"classOrder",Qt.A.Variable),(0,Yt.A)(this,"isVar",1),(0,Yt.A)(this,"uri",void 0),this.base="varid:",this.uri=pr.join(e,this.base)}equals(e){return!!e&&(this.termType===e.termType&&this.value===e.value)}hashString(){return this.toString()}substitute(e){var t;return null!=(t=e[this.toNT()])?t:this}toString(){return gr.toString(this)}static toString(e){return e.uri.slice(0,e.base.length)===e.base?`?${e.uri.slice(e.base.length)}`:`?${e.uri}`}}let yr=function(e){return e.collections="COLLECTIONS",e.defaultGraphType="DEFAULT_GRAPH_TYPE",e.equalsMethod="EQUALS_METHOD",e.id="ID",e.identity="IDENTITY",e.reversibleId="REVERSIBLE_ID",e.variableType="VARIABLE_TYPE",e}({});const vr=new hr,mr={supports:{[yr.collections]:!1,[yr.defaultGraphType]:!1,[yr.equalsMethod]:!0,[yr.identity]:!1,[yr.id]:!0,[yr.reversibleId]:!1,[yr.variableType]:!0},blankNode:e=>new tr(e),defaultGraph:()=>vr,equals(e,t){return e===t||!e||!t||((0,nr.aF)(e)||(0,nr.aF)(t)?!(!(0,nr.aF)(e)||!(0,nr.aF)(t))&&(this.equals(e.subject,t.subject)&&this.equals(e.predicate,t.predicate)&&this.equals(e.object,t.object)&&this.equals(e.graph,t.graph)):!(!(0,nr.D0)(e)||!(0,nr.D0)(t))&&this.id(e)===this.id(t))},id(e){if(!e)return"undefined";if((0,nr.aF)(e))return this.quadToNQ(e);switch(e.termType){case er.ic:return"defaultGraph";case er.P2:return gr.toString(e);default:const t=this.termToNQ(e);if(t)return t;throw new Error(`Can't id term with type '${e.termType}'`)}},isQuad:e=>e instanceof fr,literal(e,t){if("string"!=typeof e&&!t)return sr.fromValue(e);const r="string"==typeof e?e:""+e;return"string"==typeof t?-1===t.indexOf(":")?new sr(r,t):new sr(r,null,this.namedNode(t)):new sr(r,null,t)},namedNode:e=>new rr.A(e),quad:(e,t,r,n)=>new fr(e,t,r,n||vr),triple(e,t,r,n){return this.quad(e,t,r,n)},quadToNQ(e){return`${this.termToNQ(e.subject)} ${this.termToNQ(e.predicate)} ${this.termToNQ(e.object)} ${this.termToNQ(e.graph)} .`},termToNQ(e){switch(e.termType){case er.$Q:return"_:"+e.value;case er.ic:return"";case er.S:return"<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>";case er.QW:return sr.toNT(e);case er.bD:case er.Kk:return"<"+e.value+">";case er.r0:return"("+e.elements.map(e=>this.termToNQ(e)).join(" ")+")";default:throw new Error(`Can't serialize nonstandard term type (was '${e.termType}')`)}},toNQ(e){return this.isQuad(e)?this.quadToNQ(e):this.termToNQ(e)},variable:e=>new gr(e)},wr=mr;var br=a(4940);function _r(e,t){const r=t||{namedNode:e=>new rr.A(e)};return function(t){return r.namedNode(e+(t||""))}}var Sr=a(4011);function Er(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:wr;return{boolean:e.namedNode("http://www.w3.org/2001/XMLSchema#boolean"),dateTime:e.namedNode("http://www.w3.org/2001/XMLSchema#dateTime"),decimal:e.namedNode("http://www.w3.org/2001/XMLSchema#decimal"),double:e.namedNode("http://www.w3.org/2001/XMLSchema#double"),integer:e.namedNode("http://www.w3.org/2001/XMLSchema#integer"),langString:e.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),string:e.namedNode("http://www.w3.org/2001/XMLSchema#string")}}Er(wr);var xr=a(5386),Ar=a.n(xr),Fr=a(5306);function Tr(e){return new kr(e)}class kr{constructor(e){(0,Yt.A)(this,"_notQNameChars","\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~"),(0,Yt.A)(this,"_notNameChars",this._notQNameChars+":"),(0,Yt.A)(this,"validPrefix",new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/)),(0,Yt.A)(this,"forbidden1",new RegExp(/[\\"\b\f\r\v\t\n\u0080-\uffff]/gm)),(0,Yt.A)(this,"forbidden3",new RegExp(/[\\"\b\f\r\v\u0080-\uffff]/gm)),this.flags="",this.base=null,this.prefixes=[],this.namespaces=[];const t=Object.keys(Ar()());for(const e in t){const r=Ar()()[t[e]](""),n=t[e];this.prefixes[r]=n,this.namespaces[n]=r}this.suggestPrefix("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.suggestPrefix("xml","reserved:reservedForFutureUse"),this.namespacesUsed=[],this.keywords=["a"],this.prefixchars="abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",this.incoming=null,this.formulas=[],this.store=e,this.rdfFactory=e.rdfFactory||wr,this.xsd=Er(this.rdfFactory)}setBase(e){return this.base=e,this}setFlags(e){return this.flags=e||"",this}toStr(e){var t=e.toNT();return"Graph"===e.termType&&(this.formulas[t]=e),t}fromStr(e){if("{"===e[0]){var t=this.formulas[e];return t||console.log("No formula object for "+e),t}return this.store.fromNT(e)}setNamespaces(e){for(var t in e)this.setPrefix(t,e[t]);return this}setPrefix(e,t){if("default"!==e.slice(0,7)&&"ns"!==e.slice(0,2)&&e&&t){for(let t in this.prefixes)this.prefixes[t]==e&&delete this.prefixes[t];this.prefixes[t]=e,this.namespaces[e]=t}}suggestPrefix(e,t){"default"!==e.slice(0,7)&&"ns"!==e.slice(0,2)&&e&&t&&(e in this.namespaces||t in this.prefixes||(this.prefixes[t]=e,this.namespaces[e]=t))}suggestNamespaces(e){for(var t in e)this.suggestPrefix(t,e[t]);return this}checkIntegrity(){var e,t;for(e in this.namespaces)if(this.prefixes[this.namespaces[e]]!==e)throw new Error("Serializer integity error 1: "+e+", "+this.namespaces[e]+", "+this.prefixes[this.namespaces[e]]+"!");for(t in this.prefixes)if(this.namespaces[this.prefixes[t]]!==t)throw new Error("Serializer integity error 2: "+t+", "+this.prefixs[t]+", "+this.namespaces[this.prefixes[t]]+"!")}makeUpPrefix(e){var t=e;var r=function(t){return!!this.validPrefix.test(t)&&("ns"!==t&&(!(t in this.namespaces)&&(this.prefixes[e]=t,this.namespaces[t]=e,t)))}.bind(this);"#/".indexOf(t[t.length-1])>=0&&(t=t.slice(0,-1));var n=t.lastIndexOf("/");n>=0&&(t=t.slice(n+1));for(var i=0;i<t.length&&this.prefixchars.indexOf(t[i]);)i++;if((t=t.slice(0,i)).length<6&&r(t))return t;if(r(t.slice(0,3)))return t.slice(0,3);if(r(t.slice(0,2)))return t.slice(0,2);if(r(t.slice(0,4)))return t.slice(0,4);if(r(t.slice(0,1)))return t.slice(0,1);if(r(t.slice(0,5)))return t.slice(0,5);this.validPrefix.test(t)||(t="n");for(var s=0;;s++)if(r(t.slice(0,3)+s))return t.slice(0,3)+s}rootSubjects(e){for(var t={},r={},n={},i=0;i<e.length;i++){var s=e[i],o=function(e){t.hasOwnProperty(e)||(t[e]=[]),t[e].push(s.subject)};[s.subject,s.predicate,s.object].map(function(e){"BlankNode"===e.termType?n[e.toNT()]=!0:"Collection"===e.termType&&e.elements.forEach(function(e){o(e)})}),o(e[i].object);var a=r[this.toStr(s.subject)];a||(a=[]),a.push(s),r[this.toStr(s.subject)]=a}var u=[];for(var c in r)if(r.hasOwnProperty(c)){var h=this.fromStr(c);"BlankNode"===h.termType&&t[h]&&1===t[h].length||u.push(h)}this.incoming=t;for(var l={},d=0;d<u.length;d++)l[u[d].toNT()]=!0;return{roots:u,subjects:r,rootsHash:l,incoming:t}}toN3(e){return this.statementsToN3(e.statements)}explicitURI(e){var t;return this.flags.indexOf("r")<0&&this.base?e=pr.refTo(this.base,e):this.flags.indexOf("u")>=0?e=function(e){for(var t,r="",n=0;n<e.length;n++)r+=(t=e.charCodeAt(n))>65535?"\\U"+("00000000"+t.toString(16)).slice(-8):t>126?"\\u"+("0000"+t.toString(16)).slice(-4):e[n];return r}(e):(t=decodeURI(e),e=encodeURI(t)),"<"+e+">"}statementsToNTriples(e){var t=e.slice();t.sort();for(var r="",n="http://www.w3.org/1999/02/22-rdf-syntax-ns#",i=this,s=this.store,o=this.rdfFactory,a=function(e){if("Collection"!==e.termType)return i.atomicTermToN3(e);for(var t=e.elements,u=s.sym(n+"nill"),c=t.length-1;c>=0;c--){var h=o.blankNode();r+=a(h)+" "+a(s.sym(n+"first"))+" "+a(t[c])+".\n",r+=a(h)+" "+a(s.sym(n+"rest"))+" "+a(u)+".\n",u=h}return i.atomicTermToN3(u)},u=0;u<t.length;u++){var c=t[u],h="";h+=a(c.subject)+" ",h+=a(c.predicate)+" ",h+=a(c.object)+" ",this.flags.indexOf("q")>=0&&(h+=a(c.why)+" "),r+=h+=".\n"}return r}statementsToN3(e){var t=this.store,r={"http://www.w3.org/1999/02/22-rdf-syntax-ns#type":"aaa:00"};e.sort(function(e,n){return Sr.heavyCompareSPO(e,n,t,r)}),this.base&&!this.defaultNamespace&&(this.defaultNamespace=this.base+"#");var n={};this.flags.indexOf("s")<0&&(n["http://www.w3.org/2002/07/owl#sameAs"]="="),this.flags.indexOf("t")<0&&(n["http://www.w3.org/1999/02/22-rdf-syntax-ns#type"]="a"),this.flags.indexOf("i")<0&&(n["http://www.w3.org/2000/10/swap/log#implies"]="=>");var i=function(e){for(var t="",r=0;r<e;r++)t+=" ";return t},s=function(e){for(var t="",r=0;r<e.length;r++){var n=e[r],i="string"==typeof n?n:s(n);if(0!==r){var o=t.slice(-1)||" ";","===i||";"===i||("."!==i||"0123456789.:".includes(o))&&(t+=" ")}t+=i}return t},o=function(e,t){var r="",n=1e5;void 0===t&&(t=-1);for(var a=0;a<e.length;a++){var u=e[a];if("string"!=typeof u){var c=o(u,t+1);if(c.length<10*(80-4*t)&&c.indexOf('"""')<0){var h=s(u);h.length<80-4*t&&(u=h,c="")}c&&(n=1e4),r+=c}if("string"==typeof u){if(1===u.length&&"\n"===r.slice(-1)&&",.;".indexOf(u)>=0){r=r.slice(0,-1),"."==u&&"0123456789.:".includes(r.charAt(r.length-1))&&(r+=" ",n+=1),r+=u+"\n",n+=1;continue}if(n<4*t+4||n+u.length+1<80&&";.".indexOf(r[r.length-2])<0)r=r.slice(0,-1)+" "+u+"\n",n+=u.length+1;else{let e=i(4*t)+u;r+=e+"\n",n=e.length,t<0&&(r+="\n",n=1e5)}}}return r};var a=function(e){for(var t=this.rootSubjects(e),r=t.roots,n=[],i=0;i<r.length;i++){var s=r[i];n.push(u(s,t))}return n}.bind(this);function u(e,t){return"BlankNode"!==e.termType||t.incoming[e]?[l(e,t)].concat([c(e,t)]).concat(["."]):h(e,t,!0).concat(["."])}var c=function(e,t){var r=[],i=null,s=t.subjects[this.toStr(e)]||[];if(void 0===s)throw new Error("Cant find statements for "+e);for(var o=[],a=0;a<s.length;a++){var u=s[a];u.predicate.uri===i?o.push(","):(i&&(r=r.concat([o]).concat([";"]),o=[]),r.push(n[u.predicate.uri]?n[u.predicate.uri]:l(u.predicate,t))),i=u.predicate.uri,o.push(h(u.object,t))}return r=r.concat([o])}.bind(this);var h=function(e,t,r){return"BlankNode"!==e.termType||!r&&void 0!==t.rootsHash[e.toNT()]?l(e,t):t.subjects[this.toStr(e)]?["[",c(e,t),"]"]:"[]"}.bind(this);kr.prototype.termToN3=l;var l=function(e,t){var r,n;switch(e.termType){case"Graph":return(n=(n=["{"]).concat(a(e.statements))).concat(["}"]);case"Collection":for(n=["("],r=0;r<e.elements.length;r++)n.push([h(e.elements[r],t)]);return n.push(")"),n;default:return this.atomicTermToN3(e)}}.bind(this);var d=function(){var e="";for(var t in this.flags.indexOf("d")<0&&this.defaultNamespace&&(e+="@prefix : "+this.explicitURI(this.defaultNamespace)+".\n"),this.prefixes)this.prefixes.hasOwnProperty(t)&&this.namespacesUsed[t]&&(e+="@prefix "+this.prefixes[t]+": "+this.explicitURI(t)+".\n");return e+"\n"}.bind(this),f=a(e);return d()+o(f)}atomicTermToN3(e,t){switch(e.termType){case"BlankNode":case"Variable":return e.toNT();case"Literal":var r=e.value;if("string"!=typeof r)throw new TypeError("Value of RDF literal node must be a string");if(e.datatype&&this.flags.indexOf("x")<0)switch(e.datatype.uri){case"http://www.w3.org/2001/XMLSchema#integer":return r;case"http://www.w3.org/2001/XMLSchema#decimal":return r.indexOf(".")<0&&(r+=".0"),r;case"http://www.w3.org/2001/XMLSchema#double":{const e=r.toLowerCase().indexOf("e")>0;return r.indexOf(".")<0&&!e&&(r+=".0"),e||(r+="e0"),r}case"http://www.w3.org/2001/XMLSchema#boolean":return"1"===e.value?"true":"false"}var n=this.stringToN3(e.value,this.flags);return e.language?n+="@"+e.language:e.datatype.equals(this.xsd.string)||(n+="^^"+this.atomicTermToN3(e.datatype,t)),n;case"NamedNode":return this.symbolToN3(e);case"DefaultGraph":return"";default:throw new Error("Internal: atomicTermToN3 cannot handle "+e+" of termType: "+e.termType)}}stringToN3(e,t){t||(t="e");var r,n,i,s,o,a="";for(e.length>20&&'"'!==e.slice(-1)&&t.indexOf("n")<0&&(e.indexOf("\n")>0||e.indexOf('"')>0)?(s='"""',o=this.forbidden3):(s='"',o=this.forbidden1),r=0;r<e.length;){if(o.lastIndex=0,null==o.exec(e.slice(r)))break;n=r+o.lastIndex-1,a+=e.slice(r,n);var u=e[n];'"'===u&&'"""'===s&&'"""'!==e.slice(n,n+3)?a+=u:(i='\b\f\r\t\v\n\\"'.indexOf(u))>=0?a+="\\"+'bfrtvn\\"'[i]:t.indexOf("e")>=0?a+="\\u"+("000"+u.charCodeAt(0).toString(16).toLowerCase()).slice(-4):a+=u,r=n+1}return s+a+e.slice(r)+s}symbolToN3(e){var t=e.uri,r=t.indexOf("#");if(r<0&&this.flags.indexOf("/")<0&&(r=t.lastIndexOf("/")),r>=0&&this.flags.indexOf("p")<0&&(0===t.indexOf("http")||0===t.indexOf("ws")||0===t.indexOf("file"))){for(var n=!0,i=r+1;i<t.length;i++)if(this._notNameChars.indexOf(t[i])>=0){n=!1;break}if(n){var s=t.slice(r+1),o=t.slice(0,r+1);if(this.defaultNamespace&&this.defaultNamespace===o&&this.flags.indexOf("d")<0)return this.flags.indexOf("k")>=0&&this.keyords.indexOf(s)<0?s:":"+s;var a=this.prefixes[o];if(a||(a=this.makeUpPrefix(o)),a)return this.namespacesUsed[o]=!0,a+":"+s}}return this.explicitURI(t)}writeStore(e){var t=this.store,r=t.fetcher,n=r&&r.appNode,i=this.store.index[3];for(var s in i){var o=t.fromNT(s);n&&o.equals(n)||e("\n"+this.atomicTermToN3(o)+" "+this.atomicTermToN3(t.sym("http://www.w3.org/2000/10/swap/log#semantics"))+" { "+this.statementsToN3(t.statementsMatching(void 0,void 0,void 0,o))+" }.\n")}t.statementsMatching(void 0,t.sym("http://www.w3.org/2007/ont/link#requestedURI")).map(function(r){e("\n<"+r.object.value+"> log:metadata {\n");var n=t.statementsMatching(void 0,void 0,void 0,r.subject);e(this.statementsToN3(this.statementsToN3(n))),e("}.\n")});var a=[];n&&a.push(n);var u=[];a.map(function(e){u=u.concat(t.statementsMatching(void 0,void 0,void 0,e))}),e(this.statementsToN3(u))}statementsToXML(e){var t=[];t["http://www.w3.org/1999/02/22-rdf-syntax-ns#"]=!0;var r="http://www.w3.org/1999/02/22-rdf-syntax-ns#_",n=function(e){for(var t="",r=0;r<e;r++)t+=" ";return t},i=function(e){for(var t="",r=0;r<e.length;r++){var n=e[r];t+="string"==typeof n?n:i(n)}return t},s=function(e,t){var r,o="",a=1e5;t||(t=0);for(var u=0;u<e.length;u++){var c=e[u];if("string"!=typeof c){var h=s(c,t+1);h.length<10*(80-4*t)&&h.indexOf('"""')<0&&(r=i(c)).length<80-4*t&&(c=" "+r,h=""),h&&(a=1e4),o+=h}"string"==typeof c&&(a<4*t+4?(o=o.slice(0,-1)+" "+c+"\n",a+=c.length+1):(o+=(r=n(4*t)+c)+"\n",a=r.length))}return o};var o=function(e){this.suggestPrefix("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#");for(var t=this.rootSubjects(e),r=t.roots,n=[],i=0;i<r.length;i++){var s=r[i];n.push(c(s,t))}return n}.bind(this);function a(e){return void 0===e?"@@@undefined@@@@":e.replace(/[&<"]/g,function(e){switch(e[0]){case"&":return"&amp;";case"<":return"&lt;";case'"':return"&quot;"}})}var u=function(e){return a(this.base?pr.refTo(this.base,e.uri):e.uri)}.bind(this);var c=function(e,t){var n,i,s,o,f=[],p=t.subjects[this.toStr(e)];if(void 0===p)return l(e,t);p.sort(function(e,t){var n=e.predicate.uri,i=t.predicate.uri;if(n.substring(0,44)===r||i.substring(0,44)===r)return n.localeCompare(i);var s=n.substring(44),o=i.substring(44),a=parseInt(s,10),u=parseInt(o,10);return isNaN(a)||isNaN(u)||a!==s||u!==o?n.localeCompare(i):a-u});for(var g=0;g<p.length;g++)if("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"!==(s=p[g]).predicate.uri||n||"NamedNode"!==s.object.termType){if((o=s.predicate).uri.substr(0,44)===r){var y=o.uri.substr(44);y===parseInt(y,10).toString()&&(o=this.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#li"))}switch(i=d(o),s.object.termType){case"BlankNode":f=1===t.incoming[s.object].length?f.concat(["<"+i+' rdf:parseType="Resource">',c(s.object,t),"</"+i+">"]):f.concat(["<"+i+' rdf:nodeID="'+s.object.toNT().slice(2)+'"/>']);break;case"NamedNode":f=f.concat(["<"+i+' rdf:resource="'+u(s.object)+'"/>']);break;case"Literal":f=f.concat(["<"+i+(s.object.datatype.equals(this.xsd.string)?"":' rdf:datatype="'+a(s.object.datatype.uri)+'"')+(s.object.language?' xml:lang="'+s.object.language+'"':"")+">"+a(s.object.value)+"</"+i+">"]);break;case"Collection":f=f.concat(["<"+i+' rdf:parseType="Collection">',h(s.object,t),"</"+i+">"]);break;default:throw new Error("Can't serialize object of type "+s.object.termType+" into XML")}}else n=s.object;var v=n?d(n):"rdf:Description",m="";return"BlankNode"===e.termType?t.incoming[e]&&1===t.incoming[e].length||(m=' rdf:nodeID="'+e.toNT().slice(2)+'"'):m=' rdf:about="'+u(e)+'"',["<"+v+m+">"].concat([f]).concat(["</"+v+">"])}.bind(this);function h(e,t){for(var r=[],n=0;n<e.elements.length;n++)r.push(c(e.elements[n],t));return r}var l=function(e,t){var r=[],n=t.subjects[this.toStr(e)];if(!n)return r;n.sort();for(var i=0;i<n.length;i++){var s=n[i];switch(s.object.termType){case"BlankNode":r=t.rootsHash[s.object.toNT()]?r.concat(["<"+d(s.predicate)+' rdf:nodeID="'+s.object.toNT().slice(2)+'">',"</"+d(s.predicate)+">"]):r.concat(["<"+d(s.predicate)+' rdf:parseType="Resource">',l(s.object,t),"</"+d(s.predicate)+">"]);break;case"NamedNode":r=r.concat(["<"+d(s.predicate)+' rdf:resource="'+u(s.object)+'"/>']);break;case"Literal":r=r.concat(["<"+d(s.predicate)+(s.object.datatype.equals(this.xsd.string)?"":' rdf:datatype="'+a(s.object.datatype.value)+'"')+(s.object.language?' xml:lang="'+s.object.language+'"':"")+">"+a(s.object.value)+"</"+d(s.predicate)+">"]);break;case"Collection":r=r.concat(["<"+d(s.predicate)+' rdf:parseType="Collection">',h(s.object,t),"</"+d(s.predicate)+">"]);break;default:throw new Error("Can't serialize object of type "+s.object.termType+" into XML")}}return r}.bind(this);var d=function(e){var r=e.uri,n=r.indexOf("#");if(n<0&&this.flags.indexOf("/")<0&&(n=r.lastIndexOf("/")),n<0)throw new Error("Cannot make qname out of <"+r+">");for(var i=n+1;i<r.length;i++)if(this._notNameChars.indexOf(r[i])>=0)throw new Error('Invalid character "'+r[i]+'" cannot be in XML qname for URI: '+r);var s=r.slice(n+1),o=r.slice(0,n+1);if(this.defaultNamespace&&this.defaultNamespace===o&&this.flags.indexOf("d")<0)return s;var a=this.prefixes[o];return a||(a=this.makeUpPrefix(o)),t[o]=!0,a+":"+s}.bind(this),f=o(e),p="<rdf:RDF";for(var g in this.defaultNamespace&&(p+=' xmlns="'+a(this.defaultNamespace)+'"'),t)if(t.hasOwnProperty(g)){var y=this.base&&this.flags.includes("z")?pr.refTo(this.base,g):g;p+="\n xmlns:"+this.prefixes[g]+'="'+a(y)+'"'}return s([p+=">",f,"</rdf:RDF>"],-1)}statementsToJsonld(e){const t=this.statementsToN3(e),r=Fr.parse(t);return JSON.stringify(r,null,2)}}function Ir(e,t,r,n,i,s){r=r||e?.value;const o=s||{};n=n||er.sT;try{var a=Tr(t);o.flags&&a.setFlags(o.flags);var u=t.statementsMatching(void 0,void 0,void 0,e);switch("namespaces"in t&&a.suggestNamespaces(t.namespaces),o.namespaces&&a.setNamespaces(o.namespaces),a.setBase(r),n){case er.JG:return c(null,a.statementsToXML(u));case er.ny:case er.MG:return c(null,a.statementsToN3(u));case er.sT:case er.hu:return a.setFlags("si"),c(null,a.statementsToN3(u));case er.bM:return a.setFlags("deinprstux"),c(null,a.statementsToNTriples(u));case er.i2:return a.setFlags("si dr"),c(null,a.statementsToJsonld(u));case er._0:case er.BR:return a.setFlags("deinprstux q"),c(null,a.statementsToNTriples(u));default:throw new Error("Serialize: Content-type "+n+" not supported for data write.")}}catch(e){if(i)return i(e,void 0);throw e}function c(e,t){return i?void i(e,t):t}}const Cr=["blankNode","defaultGraph","literal","namedNode","quad","variable","supports"],Rr={first:"http://www.w3.org/1999/02/22-rdf-syntax-ns#first",rest:"http://www.w3.org/1999/02/22-rdf-syntax-ns#rest",nil:"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"};function Pr(e,t,r){const n=[];return r.reduce((t,r,i,s)=>{let o;return n.push(e.quad(t,e.namedNode(Rr.first),s[i])),i<s.length-1?(o=e.blankNode(),n.push(e.quad(t,e.namedNode(Rr.rest),o))):n.push(e.quad(t,e.namedNode(Rr.rest),e.namedNode(Rr.nil))),o},t),n}function Nr(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;var n=e.length;for(r<0&&(r=n+r);r<n;r++)if(e[r]===t)return r;return-1}class Ur extends Zt.A{constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};super(""),e=this,this.statements=t,this.constraints=r,this.initBindings=n,this.optional=i,(0,Yt.A)(this,"termType",er.bD),(0,Yt.A)(this,"classOrder",Qt.A.Graph),(0,Yt.A)(this,"fetcher",void 0),(0,Yt.A)(this,"isVar",0),(0,Yt.A)(this,"ns",_r),(0,Yt.A)(this,"rdfFactory",void 0),this.rdfFactory=s&&s.rdfFactory||wr;for(const t of Cr)this[t]=function(){return e.rdfFactory[t](...arguments)}}add(e,t,r,n){return 1===arguments.length&&e.forEach(e=>this.add(e.subject,e.predicate,e.object,e.graph)),this.statements.push(this.rdfFactory.quad(e,t,r,n))}addStatement(e){return this.add(e)}bnode(e){return this.rdfFactory.blankNode(e)}addAll(e){e.forEach(e=>{this.add(e.subject,e.predicate,e.object,e.graph)})}any(e,t,r,n){const i=this.anyStatementMatching(e,t,r,n);return null==i?null:null==e?i.subject:null==t?i.predicate:null==r?i.object:null}anyValue(e,t,r,n){const i=this.any(e,t,r,n);return i?i.value:void 0}anyJS(e,t,r,n){const i=this.any(e,t,r,n);return i?Zt.A.toJS(i):void 0}anyStatementMatching(e,t,r,n){let i=this.statementsMatching(e,t,r,n,!0);if(i&&0!==i.length)return i[0]}id(e){return this.rdfFactory.id(e)}statementsMatching(e,t,r,n,i){const s=this.statements.filter(i=>(!e||e.equals(i.subject))&&(!t||t.equals(i.predicate))&&(!r||r.equals(i.object))&&(!n||n.equals(i.graph)));return i?0===s.length?[]:[s[0]]:s}bottomTypeURIs(e){let t,r,n,i,s,o,a,u;t=[];for(let c in e)if(e.hasOwnProperty(c)){for(u=e[c],a=this.each(void 0,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),this.rdfFactory.namedNode(c)),r=!0,i=0,s=a.length;i<s;i++)if(n=a[i],o=n.uri,o in e){r=!1;break}r&&(t[c]=u)}return t}collection(){return new ar}each(e,t,r,n){const i=[];let s=this.statementsMatching(e,t,r,n,!1);if(null==e)for(let e=0,t=s.length;e<t;e++)i.push(s[e].subject);else if(null==t)for(let e=0,t=s.length;e<t;e++)i.push(s[e].predicate);else if(null==r)for(let e=0,t=s.length;e<t;e++)i.push(s[e].object);else if(null==n)for(let e=0,t=s.length;e<t;e++)i.push(new rr.A(s[e].graph.value));return i}equals(e){return!!e&&this.hashString()===e.hashString()}findMembersNT(e){let t,r,n,i,s,o,a,u,c,h,l,d,f,p;d={},d[e.toNT()]=!0,i={},o=this.transitiveClosure(d,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!0);for(let e in o)if(o.hasOwnProperty(e)){a=this.statementsMatching(void 0,this.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),this.fromNT(e));for(let e=0,t=a.length;e<t;e++)f=a[e],i[f.subject.toNT()]=f;u=this.each(void 0,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#domain"),this.fromNT(e));for(let e=0,r=u.length;e<r;e++)for(s=u[e],c=this.statementsMatching(void 0,s),n=0,t=c.length;n<t;n++)f=c[n],i[f.subject.toNT()]=f;h=this.each(void 0,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#range"),this.fromNT(e));for(let e=0,t=h.length;e<t;e++)for(s=h[e],l=this.statementsMatching(void 0,s),p=0,r=l.length;p<r;p++)f=l[p],i[f.object.toNT()]=f}return i}findMemberURIs(e){return this.NTtoURI(this.findMembersNT(e))}findSubClassesNT(e){let t={};return t[e.toNT()]=!0,this.transitiveClosure(t,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!0)}findSuperClassesNT(e){let t={};return t[e.toNT()]=!0,this.transitiveClosure(t,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!1)}findTypesNT(e){let t,r,n,i,s,o,a,u,c;n="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",c=[],i=this.statementsMatching(e,void 0,void 0);for(let e=0,t=i.length;e<t;e++)if(u=i[e],"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"===u.predicate.uri)c[u.object.toNT()]=u;else{s=this.each(u.predicate,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#domain"));for(let e=0,t=s.length;e<t;e++)r=s[e],c[r.toNT()]=u}o=this.statementsMatching(void 0,void 0,e);for(let e=0,r=o.length;e<r;e++){u=o[e],a=this.each(u.predicate,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#range"));for(let e=0,r=a.length;e<r;e++)t=a[e],c[t.toNT()]=u}return this.transitiveClosure(c,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!1)}findTypeURIs(e){return this.NTtoURI(this.findTypesNT(e))}connectedStatements(e,t,r){r=r||[];let n=[e],i={},s={},o=[],a=this,u=function(e){let u=function(e){"BlankNode"!==e.termType||i[e.value]||(i[e.value]=!0,n.push(e))},c=a.statementsMatching(null,null,e,t).concat(a.statementsMatching(e,null,null,t));c=c.filter(function(e){if(r[e.predicate.value])return!1;let t=e.toNT();return!s[t]&&(s[t]=!0,!0)}),c.forEach(function(e){u(e.subject),u(e.object)}),o=o.concat(c)};for(;n.length;)u(n.shift());return o}formula(e){return new Ur}fromNT(e){let t,r,n;switch(e[0]){case"<":return this.sym(e.slice(1,-1));case'"':if(n=void 0,t=void 0,r=e.lastIndexOf('"'),r<e.length-1)if("@"===e[r+1])n=e.slice(r+2);else{if("^^"!==e.slice(r+1,r+3))throw new Error("Can't convert string from NT: "+e);t=this.fromNT(e.slice(r+3))}return e=(e=(e=(e=e.slice(1,r)).replace(/\\"/g,'"')).replace(/\\n/g,"\n")).replace(/\\\\/g,"\\"),this.rdfFactory.literal(e,n||t);case"_":return this.rdfFactory.blankNode(e.slice(2));case"?":return new gr(e.slice(1))}throw new Error("Can't convert from NT: "+e)}holds(e,t,r,n){let i;if(1===arguments.length){if(!e)return!0;if(e instanceof Array){for(i=0;i<e.length;i++)if(!this.holds(e[i]))return!1;return!0}if((0,nr.SH)(e))return this.holds(e.subject,e.predicate,e.object,e.graph);if(e.statements)return this.holds(e.statements)}return null!=this.anyStatementMatching(e,t,r,n)}holdsStatement(e){return this.holds(e.subject,e.predicate,e.object,e.graph)}list(e,t){if(t.rdfFactory.supports.COLLECTIONS){const r=t.rdfFactory.collection();return e.forEach(function(e){r.append(e)}),r}{const r=t.rdfFactory.blankNode(),n=Pr(t.rdfFactory,r,e);return t.addAll(n),r}}NTtoURI(e){let t,r,n={};for(t in e)e.hasOwnProperty(t)&&(r=e[t],"<"===t[0]&&(n[t.slice(1,-1)]=r));return n}serialize(e,t,r,n){return Ir(r,this,e,t,void 0,n)}substitute(e){let t=this.statements.map(function(t){return t.substitute(e)});const r=new Ur;return r.addAll(t),r}sym(e,t){if(t)throw new Error("This feature (kb.sym with 2 args) is removed. Do not assume prefix mappings.");return this.rdfFactory.namedNode(e)}the(e,t,r,n){let i=this.any(e,t,r,n);return null==i&&br.A.error("No value found for the() {"+e+" "+t+" "+r+"}."),i}transitiveClosure(e,t,r){let n,i,s,o,a,u,c={};Object.assign(c,e);let h={};for(;;){if(u=function(){for(let e in c)if(c.hasOwnProperty(e))return e}(),null==u)return h;for(a=r?this.each(void 0,t,this.fromNT(u)):this.each(this.fromNT(u),t),i=0,s=a.length;i<s;i++)n=a[i],o=n.toNT(),o in h||o in c||(c[o]=c[u]);h[u]=c[u],delete c[u]}}topTypeURIs(e){let t,r,n,i,s,o,a,u;for(n in a=[],e)if(e.hasOwnProperty(n)){for(u=e[n],s=0,o=this.each(this.rdfFactory.namedNode(n),this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf")),t=0,i=o.length;t<i;t++)if(r=o[t],"http://www.w3.org/2000/01/rdf-schema#Resource"!==r.uri){s++;break}s||(a[n]=u)}return a["http://www.w3.org/2000/01/rdf-schema#Resource"]&&delete a["http://www.w3.org/2000/01/rdf-schema#Resource"],a["http://www.w3.org/2002/07/owl#Thing"]&&delete a["http://www.w3.org/2002/07/owl#Thing"],a}toString(){return"{"+this.statements.join("\n")+"}"}variable(e){return new gr(e)}whether(e,t,r,n){return this.statementsMatching(e,t,r,n,!1).length}}Zt.A.fromValue=or;const Or=Zt.A,Lr={xsd:_r("http://www.w3.org/2001/XMLSchema#")};Zt.A.toJS=function(e){return(0,nr.P3)(e)?e.elements.map(Zt.A.toJS):(0,nr.c$)(e)?e.datatype.equals(Lr.xsd("boolean"))?"1"===e.value||"true"===e.value:e.datatype.equals(Lr.xsd("dateTime"))||e.datatype.equals(Lr.xsd("date"))?new Date(e.value):e.datatype.equals(Lr.xsd("integer"))||e.datatype.equals(Lr.xsd("float"))||e.datatype.equals(Lr.xsd("decimal"))?Number(e.value):e.value:e};class Dr{constructor(e,t){this.pat=new Kr,this.vars=[],this.name=e,this.id=t}}function jr(e,t,r,n){function i(e){var t,r="";for(t in e)e.hasOwnProperty(t)&&(r+=" "+t+" -> "+e[t]);return r}function s(e){var t,r="Bindings: ",n=e.length;for(t=0;t<n;t++)r+=i(e[t][0])+";\n\t";return r}function o(e,t,r,n){var i;if(e.length!==t.length)return[];if(!e.length)return[[[],null]];var s=function(e,t,r,n){var i=r[e];if(void 0===i){if(e.isVar){var s=[];return s[e]=t,[[s,null]]}i=e}if(!i.complexType)return n.redirections[i]&&(i=n.redirections[i]),n.redirections[t]&&(t=n.redirections[t]),i.equals(t)||i.uri&&i.uri===cr?[[[],null]]:[];if(e instanceof Array)return t instanceof Array?o(e,t,r):[];throw new Error("query.js: oops - code not written yet")}(e[0],t[0],r,n);if(0===s.length)return s;var a,u,c,h,l,d,f,p=[],g=s.length;for(a=0;a<g;a++){for(l in f=[],u=s[a][0])u.hasOwnProperty(l)&&(f[l]=u[l]);for(l in r)r.hasOwnProperty(l)&&(f[l]=r[l]);for(h=(i=o(e.slice(1),t.slice(1),f,n)).length,c=0;c<h;c++){for(l in d=i[c][0],u)u.hasOwnProperty(l)&&(d[l]=u[l]);p.push([d,null])}}return p}function a(e,t){var r=t[e];return void 0===r?e:r}function u(e,t){var r,n={};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);for(r in t)t.hasOwnProperty(r)&&(n[r]=t[r]);return n}function c(e,t){return this.trunkBindings=t,this.originalCallback=e,this.branches=[],this}function h(e,t){return this.count=0,this.success=!1,this.done=!1,this.callback=e,this.onDone=t,this}c.prototype.checkAllDone=function(){var e;for(e=0;e<this.branches.length;e++)if(!this.branches[e].done)return;br.A.debug("OPTIONAL BIDNINGS ALL DONE:"),this.doCallBacks(this.branches.length-1,this.trunkBindings)},c.prototype.doCallBacks=function(e,t){var r;if(e<0)return this.originalCallback(t);for(r=0;r<this.branches[e].results.length;r++)this.doCallBacks(e-1,u(t,this.branches[e].results[r]))},h.prototype.reportMatch=function(e){this.callback(e),this.success=!0},h.prototype.reportDone=function(){this.done=!0,br.A.info("Mandatory query branch finished.***"),void 0!==this.onDone&&this.onDone()};var l=function(e){return this.count=0,this.done=!1,this.results=[],this.junction=e,e.branches.push(this),this};function d(e,t,r){var n,i,s,o;for(t.nvars=0,t.index=null,n=[t.subject,t.predicate,t.object,t.why],o=[e.subjectIndex,e.predicateIndex,e.objectIndex,e.whyIndex],s=0;s<4;s++){let u=n[s];if(u.uri&&u.uri===cr);else if(u.isVar&&void 0===r[u])t.nvars++;else{if(u=a(n[s],r),e.redirections[e.id(u)]&&(u=e.redirections[e.id(u)]),!(i=o[s][e.id(u)]))return t.index=[],!1;(null===t.index||t.index.length>i.length)&&(t.index=i)}}return null===t.index&&(t.index=e.statements),!0}function f(e,t){return e.nvars!==t.nvars?e.nvars-t.nvars:e.index.length-t.index.length}l.prototype.reportMatch=function(e){this.results.push(e)},l.prototype.reportDone=function(){br.A.debug("Optional branch finished - results.length = "+this.results.length),0===this.results.length&&(this.results.push({}),br.A.debug("Optional branch FAILED - that's OK.")),this.done=!0,this.junction.checkAllDone()};var p=function(e,r,n,s,o,a,u){br.A.debug("Match begins, Branch count now: "+u.count+" for "+u.pattern_debug);var h,d,f=r.statements;if(0===f.length){if(br.A.debug("FOUND MATCH WITH BINDINGS:"+i(n)),0===r.optional.length)u.reportMatch(n);else{br.A.debug("OPTIONAL: "+r.optional);var g,v=new c(t,n),m=[];for(g=0;g<r.optional.length;g++)m[g]=new l(v),m[g].pattern_debug=r.optional[g];for(g=0;g<r.optional.length;g++)m[g].count=m[g].count+1,p(e,r.optional[g],n,"",o,t,m[g])}return u.count--,void br.A.debug("Match ends -- success , Branch count now: "+u.count+" for "+u.pattern_debug)}var w=f.length;if(o){0;var b=function(t,i){var c=t.uri.split("#")[0];o.nowOrWhenFetched(c,void 0,function(i,c,h){i||console.log("Error following link to <"+t.uri+"> in query: "+c),p(e,r,n,s,o,a,u)})};for(d=0;d<w;d++){if(h=f[d],void 0!==n[h.subject]&&n[h.subject].uri&&o&&"unrequested"===o.getState((0,pr.docpart)(n[h.subject].uri)))return void b(n[h.subject]);if(void 0!==n[h.object]&&n[h.object].uri&&o&&"unrequested"===o.getState((0,pr.docpart)(n[h.object].uri)))return void b(n[h.object])}}y(e,r,n,s,o,a,u)},g=function(e,t){var r,n,i=!0;for(r in e)e.hasOwnProperty(r)&&t[r]&&(n=t[r].test)&&!n(e[r])&&(i=!1);return i},y=function(e,t,r,n,a,u,c){var h,l,y,v,m,w,b,_=t.statements,S=_.length;for(h=0;h<S;h++)d(e,b=_[h],r);_.sort(f),b=_[0];var E,x=e.formula();x.optional=t.optional,x.constraints=t.constraints,x.statements=_.slice(1),br.A.debug(n+"match2 searching "+b.index.length+" for "+b+"; bindings so far="+i(r));var A,F,T=b.index.length,k=0;for(E=0;E<T;E++)for(F=b.index[E],A=o([b.subject,b.predicate,b.object,b.why],[F.subject,F.predicate,F.object,F.why],r,e),br.A.info(n+" From first: "+A.length+": "+s(A)),y=A.length,l=0;l<y;l++)if(m=[],w=A[l][0],g(w,t.constraints)){for(v in w)w.hasOwnProperty(v)&&(m[v]=w[v]);for(v in r)r.hasOwnProperty(v)&&(m[v]=r[v]);c.count++,k++,p(e,x,m,n+" ",a,u,c)}else br.A.debug("Branch count CS: "+c.count);c.count--,0===k&&br.A.debug("Match2 fails completely on "+b),br.A.debug("Match2 ends, Branch count: "+c.count+" for "+c.pattern_debug),0===c.count&&(br.A.debug("Branch finished."),c.reportDone())},v=this;br.A.debug("Query on "+this.statements.length);var m=new h(t,n);m.count++,e.sync?p(v,e.pat,e.pat.initBindings,"",r,t,m):setTimeout(function(){p(v,e.pat,e.pat.initBindings,"",r,t,m)},0)}const Mr="http://www.w3.org/2002/07/owl#";function Br(e,t,r,n){var i=e.any(t,r,void 0);return!!i&&(e.equate(i,n),!0)}function Hr(e,t,r,n){var i=e.any(void 0,r,n);return!!i&&(e.equate(i,t),!0)}function qr(e,t,r,n,i){e.typeCallback&&e.typeCallback(e,n,i);var s=e.classActions[e.id(n)],o=!1;if(s)for(var a=0;a<s.length;a++)o=o||s[a](e,t,r,n,i);return o}class Kr extends Ur{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(void 0,void 0,void 0,void 0,t),(0,Yt.A)(this,"updater",void 0),(0,Yt.A)(this,"namespaces",void 0),(0,Yt.A)(this,"classActions",void 0),(0,Yt.A)(this,"propertyActions",void 0),(0,Yt.A)(this,"redirections",void 0),(0,Yt.A)(this,"aliases",void 0),(0,Yt.A)(this,"HTTPRedirects",void 0),(0,Yt.A)(this,"subjectIndex",void 0),(0,Yt.A)(this,"predicateIndex",void 0),(0,Yt.A)(this,"objectIndex",void 0),(0,Yt.A)(this,"whyIndex",void 0),(0,Yt.A)(this,"index",void 0),(0,Yt.A)(this,"features",void 0),(0,Yt.A)(this,"_universalVariables",void 0),(0,Yt.A)(this,"_existentialVariables",void 0),(0,Yt.A)(this,"rdfArrayRemove",void 0),(0,Yt.A)(this,"dataCallbacks",[]),(0,Yt.A)(this,"dataRemovalCallbacks",[]),this.propertyActions={},this.classActions={},this.redirections=[],this.aliases=[],this.HTTPRedirects=[],this.subjectIndex=[],this.predicateIndex=[],this.objectIndex=[],this.whyIndex=[],this.index=[this.subjectIndex,this.predicateIndex,this.objectIndex,this.whyIndex],this.namespaces={},this.features=e||[],this.rdfArrayRemove=t.rdfArrayRemove||Sr.RDFArrayRemove,t.dataCallback&&(this.dataCallbacks=[t.dataCallback]),t.dataRemovalCallback&&(this.dataRemovalCallbacks=[t.dataRemovalCallback]),this.initPropertyActions(this.features)}static get defaultGraphURI(){return cr}substitute(e){var t=this.statements.map(function(t){return t.substitute(e)}),r=new Kr;return r.add(t),r}addDataCallback(e){this.dataCallbacks.push(e)}addDataRemovalCallback(e){this.dataRemovalCallbacks.push(e)}applyPatch(e,t,r){var n,i=this,s=null;function o(o){if(e.delete){n=e.delete,s&&(n=n.substitute(s)),n=n.statements;var a=[],u=n.map(function(e){var r=i.statementsMatching(e.subject,e.predicate,e.object,t);return 0===r.length?(a.push(e),null):r[0]});if(a.length)return r("Could not find to delete: "+a.join("\n or "));u.map(function(e){i.remove(e)})}e.insert&&(n=e.insert,s&&(n=n.substitute(s)),(n=n.statements).map(function(e){e.graph=t,i.add(e.subject,e.predicate,e.object,e.graph)})),o()}if(e.where){var a=new Dr("patch");a.pat=e.where,a.pat.statements.map(function(e){e.graph=qi(t.value)}),a.sync=!0;var u=[];i.query(a,function(e){u.push(e)},i.fetcher,function(){return 0===u.length?r("No match found to be patched:"+e.where):u.length>1?r("Patch ambiguous. No patch done."):(s=u[0],void o(r))})}else o(r)}declareExistential(e){return this._existentialVariables||(this._existentialVariables=[]),this._existentialVariables.push(e),e}initPropertyActions(e){this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"))]=[qr],Nr(e,"sameAs")>=0&&(this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${Mr}sameAs`))]=[function(e,t,r,n,i){return e.equate(t,n),!0}]),Nr(e,"InverseFunctionalProperty")>=0&&(this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${Mr}InverseFunctionalProperty`))]=[function(e,t,r,n,i){return e.newPropertyAction(t,Hr)}]),Nr(e,"FunctionalProperty")>=0&&(this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${Mr}FunctionalProperty`))]=[function(e,t,r,n,i){return e.newPropertyAction(t,Br)}])}addStatement(e){return this.add(e.subject,e.predicate,e.object,e.graph),this.statements.length}add(e,t,r,n){var i,s,o;if(1===arguments.length){if(e instanceof Array)for(i=0;i<e.length;i++)this.add(e[i]);else(0,nr.aF)(e)?this.add(e.subject,e.predicate,e.object,e.graph):(0,nr.ok)(e)&&this.add(e.statements);return this}n||(n=this.fetcher?this.fetcher.appNode:this.rdfFactory.defaultGraph()),"string"==typeof e&&(e=this.rdfFactory.namedNode(e)),t=Or.fromValue(t);const a=Or.fromValue(r);if(n=Or.fromValue(n),!(0,nr.CZ)(e))throw new Error("Subject is not a subject type");if(!(0,nr.fY)(t))throw new Error(`Predicate ${t} is not a predicate type`);if(!(0,nr.DJ)(a))throw new Error(`Object ${a} is not an object type`);if(!(0,nr.RN)(n))throw new Error("Why is not a graph type");this.predicateCallback&&this.predicateCallback(this,t,n);var u=this.id(this.canon(t)),c=!1;if(s=this.propertyActions[u])for(i=0;i<s.length;i++)c=c||s[i](this,e,t,a,n);if(this.holds(e,t,a,n))return null;var h=[this.id(this.canon(e)),u,this.id(this.canon(a)),this.id(this.canon(n))];for(o=this.rdfFactory.quad(e,t,a,n),i=0;i<4;i++){var l=this.index[i],d=h[i];l[d]||(l[d]=[]),l[d].push(o)}this.statements.push(o);for(const e of this.dataCallbacks)e(o);return o}canon(e){if(!e)return e;const t=this.redirections[this.id(e)];if(t)return t;switch(e.termType){case er.$Q:return new tr(e.value);case er.r0:return e;case er.ic:return new hr;case er.S:case er.bD:return e;case er.QW:return new sr(e.value,e.language,e.datatype);case er.Kk:return new rr.A(e.value);case er.P2:return new gr(e.value);default:throw new Error(`Term Type not recognized for canonization: ${e.termType}`)}}check(){this.checkStatementList(this.statements);for(var e=0;e<4;e++){var t=this.index[e];for(var r in t)t.hasOwnProperty(r)&&this.checkStatementList(t[r],e)}}checkStatementList(e,t){void 0===t&&(t=0);for(var r,n=" found in "+["subject","predicate","object","why"][t]+" index.",i=0;i<e.length;i++){for(var s=[(r=e[i]).subject,r.predicate,r.object,r.graph],o=function(e,t){for(var r=0;r<e.length;r++)if(e[r].subject.equals(t.subject)&&e[r].predicate.equals(t.predicate)&&e[r].object.equals(t.object)&&e[r].why.equals(t.graph))return!0},a=0;a<4;a++){var u=this.canon(s[a]),c=this.id(u);this.index[a][c]&&o(this.index[a][c],r)}if(!o(this.statements,r))throw new Error("Statement list does not statement "+r+"@"+r.graph+n)}}close(){return this}compareTerms(e,t){return Object.prototype.hasOwnProperty.call(e,"compareTerm")?e.compareTerm(t):Qt.A[e.termType]<Qt.A[t.termType]?-1:Qt.A[e.termType]>Qt.A[t.termType]?1:e.value<t.value?-1:e.value>t.value?1:0}copyTo(e,t,r){r||(r=[]);var n=this.statementsMatching(e);-1!==Nr(r,"two-direction")&&n.concat(this.statementsMatching(void 0,void 0,e));for(var i=0;i<n.length;i++){var s=n[i];switch(s.object.termType){case"NamedNode":this.add(t,s.predicate,s.object);break;case"Literal":case"BlankNode":case"Collection":this.add(t,s.predicate,s.object.copy(this))}-1!==Nr(r,"delete")&&this.remove(s)}}equate(e,t){const r=this.canon(e),n=this.canon(t);var i=this.compareTerms(r,n);return!i||(i<0?this.replaceWith(n,r):this.replaceWith(r,n))}formula(e){return new Kr(e)}get length(){return this.statements.length}match(e,t,r,n){return this.statementsMatching(Or.fromValue(e),Or.fromValue(t),Or.fromValue(r),Or.fromValue(n))}mentionsURI(e){var t="<"+e+">";return!!this.subjectIndex[t]||!!this.objectIndex[t]||!!this.predicateIndex[t]}newExistential(e){if(!e)return this.bnode();var t=this.sym(e);return this.declareExistential(t)}newPropertyAction(e,t){var r=this.id(e);this.propertyActions[r]||(this.propertyActions[r]=[]),this.propertyActions[r].push(t);for(var n=this.statementsMatching(void 0,e,void 0),i=!1,s=0;s<n.length;s++)i=i||t(this,n[s].subject,e,n[s].object);return i}newUniversal(e){var t=this.sym(e);return this._universalVariables||(this._universalVariables=[]),this._universalVariables.push(t),t}variable(e){return new gr(e)}nextSymbol(e){for(var t=0;;t++){var r=e.value+"#n"+t;if(!this.mentionsURI(r))return this.sym(r)}}query(e,t,r,n){return jr.call(this,e,t,r,n)}querySync(e){var t=[];var r=!1;if(e.sync=!0,jr.call(this,e,function(e){t.push(e)},null,function(){r=!0}),!r)throw new Error("Sync query should have called done function");return t}remove(e){if(e instanceof Array){for(var t=0;t<e.length;t++)this.remove(e[t]);return this}if((0,nr.ok)(e))return this.remove(e.statements);var r=this.statementsMatching(e.subject,e.predicate,e.object,e.graph);if(!r.length)throw new Error("Statement to be removed is not on store: "+e);return this.removeStatement(r[0]),this}removeDocument(e){this.removeMetadata(e);for(var t=this.statementsMatching(void 0,void 0,void 0,e).slice(),r=0;r<t.length;r++)this.removeStatement(t[r]);return this.removeMatches(e,null,null),this}removeMetadata(e){const t=this.sym("chrome://TheCurrentSession"),r="http://www.w3.org/2007/ont/link#",n=this.statementsMatching(void 0,this.sym(`${r}requestedURI`),this.rdfFactory.literal(e.value),t).map(e=>e.subject);for(var i=0;i<n.length;i++){const e=n[i];if(null!=e){let n;const i=this.any(e,this.sym(`${r}status`),null,t);if(null!=i){n=this.statementsMatching(i,this.sym(`${r}status`),null,t).slice();for(var s=0;s<n.length;s++)this.removeStatement(n[s])}const o=this.any(e,this.sym(`${r}response`),null,t);if(null!=o){n=this.statementsMatching(o,null,null,t).slice();for(s=0;s<n.length;s++)this.removeStatement(n[s])}n=this.statementsMatching(e,null,null,t).slice();for(s=0;s<n.length;s++)this.removeStatement(n[s])}}return this.removeMatches(this.sym(e.value),null,null,t),this}removeMany(e,t,r,n,i){for(var s=this.statementsMatching(e,t,r,n,!1),o=[],a=0;a<s.length;a++)o.push(s[a]);for(i&&(o=o.slice(0,i)),a=0;a<o.length;a++)this.remove(o[a])}removeMatches(e,t,r,n){return this.removeMany(e,t,r,n),this}removeStatement(e){for(var t=[e.subject,e.predicate,e.object,e.graph],r=0;r<4;r++){var n=this.canon(t[r]),i=this.id(n);this.index[r][i]&&this.rdfArrayRemove(this.index[r][i],e)}this.rdfArrayRemove(this.statements,e);for(const t of this.dataRemovalCallbacks)t(e);return this}removeStatements(e){for(var t=0;t<e.length;t++)this.remove(e[t]);return this}replaceWith(e,t){for(var r=this.id(e),n=this.id(t),i=function(e){var t=e[r];if(t){var i=e[n];e[n]=i?t.concat(i):t,delete e[r]}},s=0;s<4;s++)i(this.index[s]);if(this.redirections[r]=t,e.value){if(this.aliases[n]||(this.aliases[n]=[]),this.aliases[n].push(e),this.aliases[r])for(s=0;s<this.aliases[r].length;s++)this.redirections[this.id(this.aliases[r][s])]=t,this.aliases[n].push(this.aliases[r][s]);this.add(t,this.sym("http://www.w3.org/2007/ont/link#uri"),e),this.fetcher&&this.fetcher.nowKnownAs(e,t)}return i(this.classActions),i(this.propertyActions),!0}allAliases(e){var t=this.aliases[this.id(this.canon(e))]||[];return t.push(this.canon(e)),t}sameThings(e,t){if(e.equals(t))return!0;var r=this.canon(e);if(!r)return!1;var n=this.canon(t);return!!n&&r.value===n.value}setPrefixForURI(e,t){if(("tab"!==e||!this.namespaces.tab)&&"ns"!==e.slice(0,2)&&"default"!==e.slice(0,7)){for(let e in this.namespaces)this.namespaces[e]==t&&delete this.namespaces[e];this.namespaces[e]=t}}statementsMatching(e,t,r,n,i){var s,o,a=[e,t,r,n],u=[],c=[],h=[],l=[];for(s=0;s<4;s++)u[s]=this.canon(Or.fromValue(a[s])),u[s]?(l.push(s),c[s]=this.id(u[s])):h.push(s);if(0===l.length)return this.statements;if(1===l.length)return s=l[0],(o=this.index[s][c[s]])&&i&&o.length>1&&(o=o.slice(0,1)),o=o||[];var d,f,p=1e10;for(f=0;f<l.length;f++){if(s=l[f],!(o=this.index[s][c[s]]))return[];o.length<p&&(p=o.length,d=f)}for(var g=l[d],y=this.index[g][c[g]],v=l.slice(0,d).concat(l.slice(d+1)),m=[],w=["subject","predicate","object","why"],b=0;b<y.length;b++){var _=y[b];for(f=0;f<v.length;f++)if(s=v[f],!this.canon(_[w[s]]).equals(u[s])){_=null;break}if(null!=_&&(m.push(_),i))break}return m}uris(e){var t=this.canon(e),r=this.aliases[this.id(t)];if(!t.value)return[];var n=[t.value];if(r)for(var i=0;i<r.length;i++)n.push(r[i].uri);return n}serialize(e,t,r,n){return Ir(r,this,e,t,void 0,n={...n||{},namespaces:n?.namespaces?{...this.namespaces,...n.namespaces}:{...this.namespaces}})}}(0,Yt.A)(Kr,"handleRDFType",void 0),Kr.handleRDFType=qr;const Vr=_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#");function $r(e,t){function r(n,i,s){const o=e.statementsMatching(n,Vr("rest"),null,t);if(1!==o.length)throw new Error(`Bad list structure: no rest at ${n}`);const a=e.statementsMatching(n,Vr("first"),null,t);if(1!==a.length)throw new Error(`Bad list structure: rest but ${a.length} firsts at ${n}`);const u=[a[0].object].concat(i),c=s.concat(o).concat(a),h=e.statementsMatching(null,Vr("rest"),n,t);if(0===h.length){const r=new ar(u);return e.remove(c),void function(e,t,r,n){for(const i of e.statementsMatching(r,null,null,n)){const r=new fr(t,i.predicate,i.object,n);e.remove(i),e.add(r)}for(const i of e.statementsMatching(null,r,null,n))e.remove(i),e.add(new fr(i.subject,t,i.object,n));for(const i of e.statementsMatching(null,null,r,n))e.remove(i),e.add(new fr(i.subject,i.predicate,t,n))}(e,r,n,t)}if(1!==h.length)throw new Error(`Bad list structure: ${h.length} pres at ${n}`);const l=h[0].subject;if("BlankNode"!==l.termType)throw new Error(`Bad list element node ${l} type: ${l.termType} `);r(l,u,c)}!function(e,t){const r=Vr("nil");for(const n of e.statementsMatching(r,null,null,t)){e.remove(n);const r=new ar;e.add(new fr(r,n.predicate,n.object,t))}for(const n of e.statementsMatching(null,null,r,t))if(!n.predicate.sameTerm(Vr("rest"))){e.remove(n);const r=new ar;e.add(new fr(n.subject,n.predicate,r,t))}}(e,t);e.statementsMatching(null,Vr("rest"),Vr("nil"),t).forEach(e=>{if("BlankNode"!==e.subject.termType)throw new Error(`Bad list element node ${e.subject} type: ${e.subject.termType} `);r(e.subject,[],[])})}var Wr=function(e){e=e.replace(/\r\n/g,"\n");for(var t="",r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t+=String.fromCharCode(n):n>127&&n<2048?(t+=String.fromCharCode(n>>6|192),t+=String.fromCharCode(63&n|128)):(t+=String.fromCharCode(n>>12|224),t+=String.fromCharCode(n>>6&63|128),t+=String.fromCharCode(63&n|128))}return t},Jr="http://www.w3.org/2000/10/swap/log#",zr=function(e){return e},Xr=function(e){return e},Gr=function(e){if(e.length>0)throw"missing.js: oops nnonempty dict not imp";return[]},Yr=function(e){return e.length},Qr=function(e,t,r){if(void 0===e.slice)throw"@@ mising.js: No .slice function for "+e+" of type "+typeof e;return void 0===r||null==r?e.slice(t):e.slice(t,r)},Zr=Error("dummy error stop iteration"),en=function(e){return this.last=0,this.li=e,this.next=function(){if(this.last==this.li.length)throw Zr;return this.li[this.last++]},this},tn=function(e,t){return e.indexOf(t)},rn=function(e,t){if(!e){if(t)throw"python Assertion failed: "+t;throw"(python) Assertion failed."}};String.prototype.encode=function(e){if("utf-8"!=e)throw"UTF8_converter: can only do utf-8";return Wr(this)},String.prototype.decode=function(e){if("utf-8"!=e)throw"UTF8_converter: can only do utf-8";return this};var nn=function(e,t){return pr.join(t,e)},sn="http://www.w3.org/1999/02/22-rdf-syntax-ns#nil",on="http://www.w3.org/2002/07/owl#sameAs";var an="\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~",un=an+":",cn=new RegExp("^([-+]?[0-9]+)(\\.[0-9]+)?([eE][-+]?[0-9]+)?","g"),hn=new RegExp("^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9](T[0-9][0-9]:[0-9][0-9](:[0-9][0-9](\\.[0-9]*)?)?)?Z?"),ln=new RegExp('[\\\\\\r\\n\\"]',"g"),dn=new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*","g");const fn=function(e,t,r,n,i,s,o,a){return new pn(e,t,r,n,i,s,o,a)};class pn{constructor(e,t,r,n,i,s,o,a){void 0===t&&(t=null),void 0===r&&(r=""),void 0===n&&(n=null),void 0===i&&(i=""),void 0===s&&(s=null),void 0===o&&(o=""),void 0===a&&(a=null),this._bindings=new Gr([]),this._flags=o,""!=r&&(rn(r.indexOf(":")>=0,"Document URI not absolute: "+r),this._bindings[""]=r+"#"),this._store=e,i&&e.setGenPrefix(i),this._thisDoc=r,this.source=e.sym(r),this.lines=0,this.statementCount=0,this.hasNil=!1,this.startOfLine=0,this.previousLine=0,this._genPrefix=i,this.keywords=new Xr(["a","this","bind","has","is","of","true","false"]),this.keywordsSet=0,this._anonymousNodes=new Gr([]),this._variables=new Gr([]),this._parentVariables=new Gr([]),this._reason=a,this._reason2=null,this._baseURI=n||(r||null),rn(!this._baseURI||this._baseURI.indexOf(":")>=0),this._genPrefix||(this._thisDoc?this._genPrefix=this._thisDoc+"#_g":this._genPrefix=RDFSink_uniqueURI()),null==t?this._thisDoc?this._formula=e.formula(r+"#_formula"):this._formula=e.formula():this._formula=t,this._context=this._formula,this._parentContext=null}here(e){return this._genPrefix+"_L"+this.lines+"C"+(e-this.startOfLine+1)}formula(){return this._formula}loadStream(e){return this.loadBuf(e.read())}loadBuf(e){return this.startDoc(),this.feed(e),this.endDoc()}feed(e){for(var t=e.decode("utf-8"),r=0;r>=0;){var n=this.skipSpace(t,r);if(n<0)return;if((r=this.directiveOrStatement(t,n))<0)throw yn(this._thisDoc,this.lines,t,n,"expected directive or statement")}}directiveOrStatement(e,t){var r,n=this.skipSpace(e,t);return n<0?n:(r=this.directive(e,n))>=0||(r=this.statement(e,n))>=0?this.checkDot(e,r):r}tok(e,t,r){if("@"==t.slice(r,r+1))r=r+1;else if(Nr(this.keywords,e)<0)return-1;var n=r+Yr(e);return t.slice(r,n)==e&&an.indexOf(t.charAt(n))>=0?n:-1}directive(e,t){if((s=this.skipSpace(e,t))<0)return s;var r=new Xr([]);if((s=this.tok("bind",e,t))>0)throw yn(this._thisDoc,this.lines,e,t,"keyword bind is obsolete: use @prefix");if((s=this.tok("keywords",e,t))>0){if((t=this.commaSeparatedList(e,s,r,!1))<0)throw yn(this._thisDoc,this.lines,e,t,"'@keywords' needs comma separated list of words");return this.setKeywords(Qr(r,null,null)),t}if((s=this.tok("forAll",e,t))>0){if((t=this.commaSeparatedList(e,s,r,!0))<0)throw yn(this._thisDoc,this.lines,e,t,"Bad variable list after @forAll");var n=new en(r);try{for(;;){var i=n.next();(Nr(this._variables,i)<0||Nr(this._parentVariables,i)>=0)&&(this._variables[i]=this._context.newUniversal(i))}}catch(e){if(e!=Zr)throw e}return t}if((s=this.tok("forSome",e,t))>0){if((t=this.commaSeparatedList(e,s,r,this.uri_ref2))<0)throw yn(this._thisDoc,this.lines,e,t,"Bad variable list after @forSome");n=new en(r);try{for(;;){i=n.next();this._context.declareExistential(i)}}catch(e){if(e!=Zr)throw e}return t}if((s=this.tok("prefix",e,t))>=0){var s,o=new Xr([]);if((t=this.qname(e,s,o))<0)throw yn(this._thisDoc,this.lines,e,s,"expected qname after @prefix");if((s=this.uri_ref2(e,t,o))<0)throw yn(this._thisDoc,this.lines,e,t,"expected <uriref> after @prefix _qname_");var a=o[1].uri;if(this._baseURI)a=nn(this._baseURI,a);else rn(a.indexOf(":")>=0,"With no base URI, cannot handle relative URI for NS");return rn(a.indexOf(":")>=0),this._bindings[o[0][0]]=a,this.bind(o[0][0],function(e){return encodeURI(e)}(a)),s}if((s=this.tok("base",e,t))>=0){o=new Xr([]);if((t=this.uri_ref2(e,s,o))<0)throw yn(this._thisDoc,this.lines,e,s,"expected <uri> after @base ");a=o[0].uri;if(!this._baseURI)throw yn(this._thisDoc,this.lines,e,s,"With no previous base URI, cannot use relative URI in @base <"+a+">");a=nn(this._baseURI,a);return rn(a.indexOf(":")>=0),this._baseURI=a,t}return-1}bind(e,t){""==e||this._store.setPrefixForURI(e,t)}setKeywords(e){null==e?this.keywordsSet=0:(this.keywords=e,this.keywordsSet=1)}startDoc(){}endDoc(){return this.hasNil&&this._store.rdfFactory.supports.COLLECTIONS&&$r(this._store,this.source),this._formula}makeStatement(e){e[0].add(e[2],e[1],e[3],this.source),(e[2].uri&&e[2].uri===sn||e[3].uri&&e[3].uri===sn)&&(this.hasNil=!0),this.statementCount+=1}statement(e,t){var r=new Xr([]);if((t=this.object(e,t,r))<0)return t;var n=this.property_list(e,t,r[0]);if(n<0)throw yn(this._thisDoc,this.lines,e,t,"expected propertylist");return n}subject(e,t,r){return this.item(e,t,r)}verb(e,t,r){if((i=this.skipSpace(e,t))<0)return i;var n=new Xr([]);if((i=this.tok("has",e,t))>=0){if((t=this.prop(e,i,n))<0)throw yn(this._thisDoc,this.lines,e,i,"expected property after 'has'");return r.push(new zr(["->",n[0]])),t}if((i=this.tok("is",e,t))>=0){if((t=this.prop(e,i,n))<0)throw yn(this._thisDoc,this.lines,e,i,"expected <property> after 'is'");if((i=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"End of file found, expected property after 'is'");var i;t=i;if((i=this.tok("of",e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"expected 'of' after 'is' <prop>");return r.push(new zr(["<-",n[0]])),i}if((i=this.tok("a",e,t))>=0)return r.push(new zr(["->",this._store.sym("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")])),i;if("<="==e.slice(t,t+2))return r.push(new zr(["<-",this._store.sym(Jr+"implies")])),t+2;if("="==e.slice(t,t+1))return">"==e.slice(t+1,t+2)?(r.push(new zr(["->",this._store.sym(Jr+"implies")])),t+2):(r.push(new zr(["->",this._store.sym(on)])),t+1);if(":="==e.slice(t,t+2))return r.push(new zr(["->",Jr+"becomes"])),t+2;if((i=this.prop(e,t,n))>=0)return r.push(new zr(["->",n[0]])),i;if(">-"==e.slice(t,t+2)||"<-"==e.slice(t,t+2))throw yn(this._thisDoc,this.lines,e,i,">- ... -> syntax is obsolete.");return-1}prop(e,t,r){return this.item(e,t,r)}item(e,t,r){return this.path(e,t,r)}blankNode(e){return this._context.bnode(e,this._reason2)}path(e,t,r){if((s=this.nodeOrLiteral(e,t,r))<0)return s;for(;"!^.".indexOf(e.slice(s,s+1))>=0;){var n=e.slice(s,s+1);if("."==n){var i=e.slice(s+1,s+2);if(!i||un.indexOf(i)>=0&&":?<[{(".indexOf(i)<0)break}var s,o=r.pop(),a=this.blankNode(this.here(s));if((s=this.node(e,s+1,r))<0)throw yn(this._thisDoc,this.lines,e,s,"EOF found in middle of path syntax");var u=r.pop();"^"==n?this.makeStatement(new zr([this._context,u,a,o])):this.makeStatement(new zr([this._context,u,o,a])),r.push(a)}return s}anonymousNode(e){if(t=this._anonymousNodes[e])return t;var t=this._store.bnode(e);return this._anonymousNodes[e]=t,t}node(e,t,r,n){void 0===n&&(n=null);var i=n;if((h=this.skipSpace(e,t))<0)return h;t=h;var s=e.slice(t,t+1);if("["==s){var o=this.here(t);if((h=this.skipSpace(e,t+1))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF after '['");if("="==e.slice(h,h+1)){var t=h+1,a=new Xr([]);if(!((h=this.objectList(e,t,a))>=0))throw yn(this._thisDoc,this.lines,e,t,"objectList expected after [= ");i=a[0];if(Yr(a)>1){var u=new en(a);try{for(;;){var c=u.next();this.makeStatement(new zr([this._context,this._store.sym(on),i,c]))}}catch(e){if(e!=Zr)throw e}}if((h=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF when objectList expected after [ = ");if(";"==e.slice(h,h+1))var h=h+1}if(null==i)i=this.blankNode(o);if((t=this.property_list(e,h,i))<0)throw yn(this._thisDoc,this.lines,e,h,"property_list expected");if((h=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF when ']' expected after [ <propertyList>");if("]"!=e.slice(h,h+1))throw yn(this._thisDoc,this.lines,e,h,"']' expected");return r.push(i),h+1}if("{"==s){if("$"==e.slice(t+1,t+2)){for(var h=(t+=1)+1,l=new Xr([]),d=!0;;){if((t=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"needed '$}', found end.");if("$}"==e.slice(t,t+2)){var h=t+2;break}if(d)d=!1;else{if(","!=e.slice(t,t+1))throw yn(this._thisDoc,this.lines,e,t,"expected: ','");t+=1}var f=new Xr([]);if((h=this.item(e,t,f))<0)throw yn(this._thisDoc,this.lines,e,t,"expected item in set or '$}'");l.push(f[0])}return r.push(this._store.newSet(l,this._context)),h}var h=t+1,p=this._parentContext;this._parentContext=this._context;var g=this._anonymousNodes,y=this._parentVariables;this._parentVariables=this._variables,this._anonymousNodes=new Gr([]),this._variables=this._variables.slice();var v=this._reason2;if(this._reason2=null,null==i)i=this._store.formula();for(this._context=i;;){if((t=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"needed '}', found end.");if("}"==e.slice(t,t+1)){var h=t+1;break}if((h=this.directiveOrStatement(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"expected statement or '}'")}return this._anonymousNodes=g,this._variables=this._parentVariables,this._parentVariables=y,this._context=this._parentContext,this._reason2=v,this._parentContext=p,r.push(i.close()),h}if("("==s){var m=this._store.list;if("$"==e.slice(t+1,t+2)){m=this._store.newSet;t+=1}for(h=t+1,l=new Xr([]);;){if((t=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"needed ')', found end.");if(")"==e.slice(t,t+1)){h=t+1;break}f=new Xr([]);if((h=this.item(e,t,f))<0)throw yn(this._thisDoc,this.lines,e,t,"expected item in list or ')'");l.push(f[0])}return r.push(m(l,this._context)),h}if((h=this.tok("this",e,t))>=0)throw yn(this._thisDoc,this.lines,e,t,"Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords.");if((h=this.tok("true",e,t))>=0)return r.push(!0),h;if((h=this.tok("false",e,t))>=0)return r.push(!1),h;if(null==i&&(h=this.uri_ref2(e,t,r))>=0)return h;return-1}property_list(e,t,r){for(;;){if((h=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF found when expected verb in property list");if(":-"!=e.slice(h,h+2)){t=h;var n=new Xr([]);if((h=this.verb(e,t,n))<=0)return t;var i=new Xr([]);if((t=this.objectList(e,h,i))<0)throw yn(this._thisDoc,this.lines,e,h,"objectList expected");var s=new en(i);try{for(;;){var o=s.next(),a=n[0],u=a[0],c=a[1];"->"==u?this.makeStatement(new zr([this._context,c,r,o])):this.makeStatement(new zr([this._context,c,o,r]))}}catch(e){if(e!=Zr)throw e}if((h=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,h,"EOF found in list of objects");if(";"!=e.slice(t,t+1))return t;t=t+1}else{var h,t=h+2,l=new Xr([]);if((h=this.node(e,t,l,r))<0)throw yn(this._thisDoc,this.lines,e,t,"bad {} or () or [] node after :- ");var t=h}}}commaSeparatedList(e,t,r,n){if((i=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,i,"EOF found expecting comma sep list");if("."==e.charAt(i))return t;if(n)var i=this.uri_ref2(e,i,r);else i=this.bareWord(e,i,r);if(i<0)return-1;for(;;){if((t=this.skipSpace(e,i))<0)return t;var s=e.slice(t,t+1);if(","!=s)return"."!=s?-1:t;if(n)i=this.uri_ref2(e,t+1,r);else i=this.bareWord(e,t+1,r);if(i<0)throw yn(this._thisDoc,this.lines,e,i,"bad list content")}}objectList(e,t,r){if((t=this.object(e,t,r))<0)return-1;for(;;){var n=this.skipSpace(e,t);if(n<0)throw yn(this._thisDoc,this.lines,e,n,"EOF found after object");if(","!=e.slice(n,n+1))return n;if((t=this.object(e,n+1,r))<0)return t}}checkDot(e,t){var r=this.skipSpace(e,t);if(r<0)return r;if("."==e.slice(r,r+1))return r+1;if("}"==e.slice(r,r+1))return r;if("]"==e.slice(r,r+1))return r;throw yn(this._thisDoc,this.lines,e,r,"expected '.' or '}' or ']' at end of statement")}uri_ref2(e,t,r){var n=new Xr([]);if((d=this.qname(e,t,n))>=0){var i=n[0],s=i[0],o=i[1];if(null==s){rn(0,"not used?");var a=this._baseURI+"#"}else{if(!(a=this._bindings[s])){if("_"==s)return r.push(this.anonymousNode(o)),d;throw yn(this._thisDoc,this.lines,e,t,"Prefix "+s+" not bound.")}}var u=this._store.sym(a+o);return Nr(this._variables,u)>=0?r.push(this._variables[u]):r.push(u),d}if((t=this.skipSpace(e,t))<0)return-1;if("?"==e.charAt(t)){var c=new Xr([]);return(d=this.variable(e,t,c))>0?(r.push(c[0]),d):-1}if("<"==e.charAt(t)){for(var h=t=t+1;t<Yr(e);){if(">"==e.charAt(t)){var l=e.slice(h,t);if(this._baseURI)l=nn(this._baseURI,l);else rn(l.indexOf(":")>=0,"With no base URI, cannot deal with relative URIs");if("#"==e.slice(t-1,t)&&"#"!=Qr(l,-1,null))l=l+"#";u=this._store.sym(l);return Nr(this._variables,u)>=0?r.push(this._variables[u]):r.push(u),t+1}t=t+1}throw yn(this._thisDoc,this.lines,e,d,"unterminated URI reference")}if(this.keywordsSet){var d;c=new Xr([]);if((d=this.bareWord(e,t,c))<0)return-1;if(Nr(this.keywords,c[0])>=0)throw yn(this._thisDoc,this.lines,e,t,'Keyword "'+c[0]+'" not allowed here.');return r.push(this._store.sym(this._bindings[""]+c[0])),d}return-1}skipSpace(e,t){for(var r=t||0;r<e.length;r++){var n=e.charAt(r);if(" \n\r\t\f\v            ​\u2028\u2029 ".indexOf(n)<0){if("#"!==e.charAt(r))return r;for(;;r++){if(r===e.length)return-1;if("\n"===e.charAt(r)){this.lines=this.lines+1;break}}}else"\n"===e.charAt(r)&&(this.lines=this.lines+1)}return-1}variable(e,t,r){if((n=this.skipSpace(e,t))<0)return-1;if("?"!=e.slice(n,n+1))return-1;var n;t=n+=1;if("0123456789-".indexOf(e.charAt(n))>=0)throw yn(this._thisDoc,this.lines,e,n,"Varible name can't start with '"+e.charAt(n)+"s'");for(;t<Yr(e)&&un.indexOf(e.charAt(t))<0;)t=t+1;if(null==this._parentContext)throw yn(this._thisDoc,this.lines,e,n,"Can't use ?xxx syntax for variable in outermost level: "+e.slice(n-1,t));return r.push(this._store.variable(e.slice(n,t))),t}bareWord(e,t,r){var n=this.skipSpace(e,t);if(n<0)return-1;var i=e.charAt(n);if("0123456789-".indexOf(i)>=0)return-1;if(un.indexOf(i)>=0)return-1;for(t=n;t<Yr(e)&&un.indexOf(e.charAt(t))<0;)t=t+1;return r.push(e.slice(n,t)),t}qname(e,t,r){if((t=this.skipSpace(e,t))<0)return-1;var n=e.charAt(t);if("0123456789-+".indexOf(n)>=0)return-1;if(un.indexOf(n)<0){var i=n;for(t=t+1;t<Yr(e);){n=e.charAt(t);if(!(un.indexOf(n)<0))break;i=i+n,t=t+1}}else i="";if(t<Yr(e)&&":"==e.charAt(t)){var s=i;for(t=t+1,i="";t<Yr(e);){n=e.charAt(t);if(!(un.indexOf(n)<0))break;i=i+n,t=t+1}return r.push(new zr([s,i])),t}return i&&this.keywordsSet&&Nr(this.keywords,i)<0?(r.push(new zr(["",i])),t):-1}object(e,t,r){if((s=this.subject(e,t,r))>=0)return s;{if((s=this.skipSpace(e,t))<0)return-1;t=s;var n=null;let a=e.charAt(t);if('"'==a||"'"==a){n=e.slice(t,t+3==a+a)?a+a+a:a;t=t+Yr(n);var i=this.strconst(e,t,n),s=i[0],o=i[1];return r.push(this._store.literal(o)),s}return-1}}nodeOrLiteral(e,t,r){if((u=this.node(e,t,r))>=0)return u;if((u=this.skipSpace(e,t))<0)return-1;t=u;var n=e.charAt(t);if("-+0987654321".indexOf(n)>=0){if(hn.lastIndex=0,null!=(l=hn.exec(e.slice(t)))){u=t+(i=l[0]).length,i.indexOf("T")>=0?r.push(this._store.literal(i,this._store.sym("http://www.w3.org/2001/XMLSchema#dateTime"))):r.push(this._store.literal(i,this._store.sym("http://www.w3.org/2001/XMLSchema#date")))}else{var i;if(cn.lastIndex=0,null==(l=cn.exec(e.slice(t))))throw yn(this._thisDoc,this.lines,e,t,"Bad number or date syntax");u=t+cn.lastIndex,(i=e.slice(t,u)).indexOf("e")>=0?r.push(this._store.literal(parseFloat(i),this._store.sym("http://www.w3.org/2001/XMLSchema#double"))):e.slice(t,u).indexOf(".")>=0?r.push(this._store.literal(parseFloat(i),this._store.sym("http://www.w3.org/2001/XMLSchema#decimal"))):r.push(this._store.literal(parseInt(i),this._store.sym("http://www.w3.org/2001/XMLSchema#integer")))}return u}if('"'==e.charAt(t)){if('"""'==e.slice(t,t+3))var s='"""';else s='"';t=t+Yr(s);var o=null,a=this.strconst(e,t,s),u=a[0],c=a[1],h=null;if("@"==e.slice(u,u+1)){var l;if(dn.lastIndex=0,null==(l=dn.exec(e.slice(u+1))))throw yn(this._thisDoc,startline,e,t,"Bad language code syntax on string literal, after @");t=dn.lastIndex+u+1,h=e.slice(u+1,t),u=t}if("^^"==e.slice(u,u+2)){var d=new Xr([]);u=this.uri_ref2(e,u+2,d),o=d[0]}return r.push(this._store.literal(c,h||o)),u}return-1}strconst(e,t,r){for(var n=t,i="",s=this.lines;n<Yr(e);){t=n+Yr(r);if(e.slice(n,t)==r)return new zr([t,i]);if('"'!=e.charAt(n)){if(ln.lastIndex=0,!ln.exec(e.slice(n)))throw yn(this._thisDoc,s,e,n,"Closing quote missing in string at ^ in "+e.slice(n-20,n)+"^"+e.slice(n,n+20));t=n+ln.lastIndex-1,i=i+e.slice(n,t);if('"'!=(u=e.charAt(t)))if("\r"!=u){if("\n"==u){if('"'==r)throw yn(this._thisDoc,s,e,t,"newline found in string literal");this.lines=this.lines+1;i=i+u,n=t+1;this.previousLine=this.startOfLine,this.startOfLine=n}else if("\\"==u){n=t+1;if(!(u=e.slice(n,n+1)))throw yn(this._thisDoc,s,e,t,"unterminated string literal (2)");var o=tn('abfrtvn\\"',u);if(o>=0)i=i+'a\b\f\r\t\v\n\\"'.charAt(o),n=n+1;else if("u"==u)n=(a=this.uEscape(e,n+1,s))[0],i=i+(u=a[1]);else{if("U"!=u)throw yn(this._thisDoc,this.lines,e,t,"bad escape");var a,u;n=(a=this.UEscape(e,n+1,s))[0],i=i+(u=a[1])}}}else var n=t+1;else var n=t}else var i=i+'"',n=n+1}throw yn(this._thisDoc,this.lines,e,t,"unterminated string literal")}uEscape(e,t,r){for(var n=t,i=0,s=0;i<4;){var o=e.slice(n,n+1).toLowerCase();n=n+1;if(""==o)throw yn(this._thisDoc,r,e,t,"unterminated string literal(3)");var a=tn("0123456789abcdef",o);if(a<0)throw yn(this._thisDoc,r,e,t,"bad string literal hex escape");s=16*s+a,i=i+1}var u=String.fromCharCode(s);return new zr([n,u])}UEscape(e,t,r){for(var n=t,i=0,s="\\U";i<8;){var o=e.slice(n,n+1).toLowerCase();n=n+1;if(""==o)throw yn(this._thisDoc,r,e,t,"unterminated string literal(3)");if(tn("0123456789abcdef",o)<0)throw yn(this._thisDoc,r,e,t,"bad string literal hex escape");s=s+o,i=i+1}var a,u=(a="0x"+Qr(s,2,10)-0,String.fromCharCode(a));return new zr([n,u])}}function gn(e,t,r,n,i){this._str=r.encode("utf-8"),this._str=r,this._i=n,this._why=i,this.lines=t,this._uri=e}function yn(e,t,r,n,i){let s=t+1,o="Line "+s+" of <"+e+">: Bad syntax: "+i+'\nat: "'+r.slice(n,n+30)+'"',a=new SyntaxError(o,e,s);return a.lineNo=s,a.characterInFile=n,a.syntaxProblem=i,a}gn.prototype.toString=function(){var e=this._str,t=this._i,r=0;if(t>60){var n="...";r=t-60}else n="";if(Yr(e)-t>60)var i="...";else i="";return'Line %i of <%s>: Bad syntax (%s) at ^ in:\n"%s%s^%s%s"'%new zr([this.lines+1,this._uri,this._why,n,e.slice(r,t),e.slice(t,t+60),i])};const vn={...wr,supports:{[yr.collections]:!0,[yr.defaultGraphType]:!1,[yr.equalsMethod]:!0,[yr.identity]:!1,[yr.id]:!0,[yr.reversibleId]:!1,[yr.variableType]:!0},collection:e=>new ar(e),id(e){return(0,nr.P3)(e)?`( ${e.elements.map(e=>this.id(e)).join(", ")} )`:(0,nr.DZ)(e)?gr.toString(e):wr.id(e)},termToNQ:e=>e.termType===er.r0?ar.toNT(e):wr.termToNQ(e)},mn=vn;function wn(e,t){return"string"==typeof t?e.rdfFactory.literal(t):Object.prototype.hasOwnProperty.call(t,"@list")?!0===e.rdfFactory.supports.COLLECTIONS?function(e,t){if(!Array.isArray(t))throw new TypeError("Object must be an array");return e.rdfFactory.collection(t.map(t=>wn(e,t)))}(e,t["@list"]):function(e,t){const r=t["@id"]?_n(e,t):e.rdfFactory.blankNode(),n=t["@list"].map(t=>wn(e,t)),i=Pr(e.rdfFactory,r,n);return e.addAll(i),r}(e,t):Object.prototype.hasOwnProperty.call(t,"@id")?_n(e,t):Object.prototype.hasOwnProperty.call(t,"@language")?e.rdfFactory.literal(t["@value"],t["@language"]):Object.prototype.hasOwnProperty.call(t,"@type")?e.rdfFactory.literal(t["@value"],e.rdfFactory.namedNode(t["@type"])):Object.prototype.hasOwnProperty.call(t,"@value")?e.rdfFactory.literal(t["@value"]):e.rdfFactory.literal(t)}async function bn(e,t,r){const n=r&&Object.prototype.hasOwnProperty.call(r,"termType")?r.value:r,i=await Promise.all([a.e(841),a.e(789)]).then(a.t.bind(a,4841,23));return(await i.default.flatten(JSON.parse(e),null,{base:n})).reduce((e,t)=>Sn(e,r,t),t)}function _n(e,t){return t["@id"].startsWith("_:")?e.rdfFactory.blankNode(t["@id"].substring(2)):e.rdfFactory.namedNode(t["@id"])}function Sn(e,t,r){const n=r["@id"]?_n(e,r):e.rdfFactory.blankNode();for(const i of Object.keys(r)){if("@id"===i)continue;if("@graph"==i){const t=n,s=r[i];for(let r=0;r<s.length;r++)e=Sn(e,t,s[r])}const s=r[i];if(Array.isArray(s))for(let r=0;r<s.length;r++)e.addStatement(En(e,n,i,s[r],t));else e.addStatement(En(e,n,i,s,t))}return e}function En(e,t,r,n,i){let s,o;return"@type"===r?(s=e.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),o=e.rdfFactory.namedNode(n)):(s=e.rdfFactory.namedNode(r),o=wn(e,n)),e.rdfFactory.quad(t,s,o,e.rdfFactory.namedNode(i))}var xn=a(8287);const An="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Fn="http://www.w3.org/2001/XMLSchema#",Tn="http://www.w3.org/2000/10/swap/",kn={xsd:{decimal:`${Fn}decimal`,boolean:`${Fn}boolean`,double:`${Fn}double`,integer:`${Fn}integer`,string:`${Fn}string`},rdf:{type:`${An}type`,nil:`${An}nil`,first:`${An}first`,rest:`${An}rest`,langString:`${An}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${Tn}reify#forSome`,forAll:`${Tn}reify#forAll`},log:{implies:`${Tn}log#implies`,isImpliedBy:`${Tn}log#isImpliedBy`}},{xsd:In}=kn,Cn=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,Rn={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},Pn=/[\x00-\x20<>\\"\{\}\|\^\`]/,Nn={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},Un=/$0^/;class On{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const e in this)!(e in Nn)&&this[e]instanceof RegExp&&(this[e]=Un)}else this._n3Mode=!1!==e.n3;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let r=this._input,n=r.length;for(;;){let e,o;for(;e=this._newline.exec(r);)this.comments&&(o=this._comment.exec(e[0]))&&i("comment",o[1],"",this._line,e[0].length),r=r.substr(e[0].length,r.length),n=r.length,this._line++;if(!e&&(e=this._whitespace.exec(r))&&(r=r.substr(e[0].length,r.length)),this._endOfFile.test(r))return t&&(this.comments&&(o=this._comment.exec(r))&&i("comment",o[1],"",this._line,r.length),r=null,i("eof","","",this._line,0)),this._input=r;const a=this._line,u=r[0];let c="",h="",l="",d=null,f=0,p=!1;switch(u){case"^":if(r.length<3)break;if("^"!==r[1]){this._n3Mode&&(f=1,c="^");break}if(this._previousMarker="^^",r=r.substr(2),"<"!==r[0]){p=!0;break}case"<":if(d=this._unescapedIri.exec(r))c="IRI",h=d[1];else if(d=this._iri.exec(r)){if(h=this._unescape(d[1]),null===h||Pn.test(h))return s(this);c="IRI"}else r.length>1&&"<"===r[1]?(c="<<",f=2):this._n3Mode&&r.length>1&&"="===r[1]&&(f=2,this._isImpliedBy?(c="abbreviation",h="<"):(c="inverse",h=">"));break;case">":r.length>1&&">"===r[1]&&(c=">>",f=2);break;case"_":((d=this._blank.exec(r))||t&&(d=this._blank.exec(`${r} `)))&&(c="blank",l="_",h=d[1]);break;case'"':if(d=this._simpleQuotedString.exec(r))h=d[1];else if(({value:h,matchLength:f}=this._parseLiteral(r)),null===h)return s(this);null===d&&0===f||(c="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(d=this._simpleApostropheString.exec(r))h=d[1];else if(({value:h,matchLength:f}=this._parseLiteral(r)),null===h)return s(this);null===d&&0===f||(c="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(d=this._variable.exec(r))&&(c="var",h=d[0]);break;case"@":"literal"===this._previousMarker&&(d=this._langcode.exec(r))?(c="langcode",h=d[1]):(d=this._keyword.exec(r))&&(c=d[0]);break;case".":if(1===r.length?t:r[1]<"0"||r[1]>"9"){c=".",f=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(d=this._number.exec(r)||t&&(d=this._number.exec(`${r} `)))&&(c="literal",h=d[0],l="string"==typeof d[1]?In.double:"string"==typeof d[2]?In.decimal:In.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(d=this._sparqlKeyword.exec(r))?c=d[0].toUpperCase():p=!0;break;case"f":case"t":(d=this._boolean.exec(r))?(c="literal",h=d[0],l=In.boolean):p=!0;break;case"a":(d=this._shortPredicates.exec(r))?(c="abbreviation",h="a"):p=!0;break;case"=":this._n3Mode&&r.length>1&&(c="abbreviation",">"!==r[1]?(f=1,h="="):(f=2,h=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(f=1,c=u);break;case"{":!this._lineMode&&r.length>=2&&("|"===r[1]?(c="{|",f=2):(c=u,f=1));break;case"|":r.length>=2&&"}"===r[1]&&(c="|}",f=2);break;default:p=!0}if(p&&("@prefix"!==this._previousMarker&&"PREFIX"!==this._previousMarker||!(d=this._prefix.exec(r))?((d=this._prefixed.exec(r))||t&&(d=this._prefixed.exec(`${r} `)))&&(c="prefixed",l=d[1]||"",h=this._unescape(d[2])):(c="prefix",h=d[1]||"")),"^^"===this._previousMarker)switch(c){case"prefixed":c="type";break;case"IRI":c="typeIRI";break;default:c=""}if(!c)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?s(this):this._input=r;const g=f||d[0].length,y=i(c,h,l,a,g);this.previousToken=y,this._previousMarker=c,r=r.substr(g,r.length)}function i(t,i,s,o,a){const u=r?n-r.length:n,c={type:t,value:i,prefix:s,line:o,start:u,end:u+a};return e(null,c),c}function s(t){e(t._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(Cn,(e,r,n,i)=>{if("string"==typeof r)return String.fromCharCode(Number.parseInt(r,16));if("string"==typeof n){let e=Number.parseInt(n,16);return e<=65535?String.fromCharCode(Number.parseInt(n,16)):String.fromCharCode(55296+((e-=65536)>>10),56320+(1023&e))}return i in Rn?Rn[i]:(t=!0,"")});return t?null:r}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],r=t.length;let n=Math.max(this._literalClosingPos,r);for(;(n=e.indexOf(t,n))>0;){let t=0;for(;"\\"===e[n-t-1];)t++;if(t%2==0){const t=e.substring(r,n),i=t.split(/\r\n|\r|\n/).length-1,s=n+r;if(1===r&&0!==i||3===r&&this._lineMode)break;return this._line+=i,{value:this._unescape(t),matchLength:s}}n++}this._literalClosingPos=e.length-r+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\ufeff")?e.substr(1):e}tokenize(e,t){if(this._line=1,"string"==typeof e){if(this._input=this._readStartingBom(e),"function"!=typeof t){const e=[];let t;if(this._tokenizeToEnd((r,n)=>r?t=r:e.push(n),!0),t)throw t;return e}queueMicrotask(()=>this._tokenizeToEnd(t,!0))}else this._pendingBuffer=null,"function"==typeof e.setEncoding&&e.setEncoding("utf8"),e.on("data",e=>{null!==this._input&&0!==e.length&&(this._pendingBuffer&&(e=xn.hp.concat([this._pendingBuffer,e]),this._pendingBuffer=null),128&e[e.length-1]?this._pendingBuffer=e:(void 0===this._input?this._input=this._readStartingBom("string"==typeof e?e:e.toString()):this._input+=e,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{"string"==typeof this._input&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf:Ln,xsd:Dn}=kn;let jn,Mn=0;const Bn={namedNode:zn,blankNode:Xn,variable:Yn,literal:Gn,defaultGraph:function(){return jn},quad:Qn,triple:Qn,fromTerm:Zn,fromQuad:ei},Hn=Bn;class qn{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof qn?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class Kn extends qn{get termType(){return"NamedNode"}}class Vn extends qn{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t<e.length&&"@"===e[t++]?e.substr(t).toLowerCase():""}get datatype(){return new Kn(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,r=t<e.length?e[t]:"";return"^"===r?e.substr(t+2):"@"!==r?Dn.string:Ln.langString}equals(e){return e instanceof Vn?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class $n extends qn{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Wn extends qn{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}jn=new class extends qn{constructor(){return super(""),jn||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};class Jn extends qn{constructor(e,t,r,n){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=n||jn}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}}function zn(e){return new Kn(e)}function Xn(e){return new $n(e||"n3-"+Mn++)}function Gn(e,t){if("string"==typeof t)return new Vn(`"${e}"@${t.toLowerCase()}`);let r=t?t.value:"";return""===r&&("boolean"==typeof e?r=Dn.boolean:"number"==typeof e&&(Number.isFinite(e)?r=Number.isInteger(e)?Dn.integer:Dn.double:(r=Dn.double,Number.isNaN(e)||(e=e>0?"INF":"-INF")))),""===r||r===Dn.string?new Vn(`"${e}"`):new Vn(`"${e}"^^${r}`)}function Yn(e){return new Wn(e)}function Qn(e,t,r,n){return new Jn(e,t,r,n)}function Zn(e){if(e instanceof qn)return e;switch(e.termType){case"NamedNode":return zn(e.value);case"BlankNode":return Xn(e.value);case"Variable":return Yn(e.value);case"DefaultGraph":return jn;case"Literal":return Gn(e.value,e.language||e.datatype);case"Quad":return ei(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function ei(e){if(e instanceof Jn)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return Qn(Zn(e.subject),Zn(e.predicate),Zn(e.object),Zn(e.graph))}let ti=0;class ri{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&ii(this,e.factory);const t="string"==typeof e.format?e.format.match(/\w*$/)[0].toLowerCase():"",r=/turtle/.test(t),n=/trig/.test(t),i=/triple/.test(t),s=/quad/.test(t),o=this._n3Mode=/n3/.test(t),a=i||s;(this._supportsNamedGraphs=!(r||o))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||n||i||o),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=""===t||/star|\*$/.test(t),a&&(this._resolveRelativeIRI=e=>null),this._blankNodePrefix="string"!=typeof e.blankNodePrefix?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new On({lineMode:a,n3:o,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){ti=0}_setBase(e){if(e){const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}else this._base="",this._basePath=""}_saveContext(e,t,r,n,i){const s=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:n,object:i,graph:t,inverse:!!s&&this._inversePredicate,blankPrefix:s?this._prefixes._:"",quantified:s?this._quantified:null}),s&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const r=this._contextStack.pop();if(!r||r.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=r.subject,this._predicate=r.predicate,this._object=r.object,this._graph=r.graph,this._n3Mode&&(this._inversePredicate=r.inverse,this._prefixes._=r.blankPrefix,this._quantified=r.quantified)}_readInTopContext(e){switch(e.type){case"eof":return null!==this._graph?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let r;switch(e.type){case"IRI":case"typeIRI":const t=this._resolveIRI(e.value);if(null===t)return this._error("Invalid IRI",e);r=this._factory.namedNode(t);break;case"type":case"prefixed":const n=this._prefixes[e.prefix];if(void 0===n)return this._error(`Undefined prefix "${e.prefix}:"`,e);r=this._factory.namedNode(n+e.value);break;case"blank":r=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":r=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&r.id in this._quantified&&(r=this._quantified[r.id]),r}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(0===e.prefix.length)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if(void 0===(this._subject=this._readEntity(e)))return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return null===this._predicate?this._error(`Unexpected ${t}`,e):(this._subject=null,"]"===t?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return null!==this._predicate?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if(void 0===(this._predicate=this._readEntity(e)))return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(0===e.prefix.length)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if(void 0===(this._object=this._readEntity(e)))return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return"{"===e.type?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return"{"!==e.type?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return"]"===e.type?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if("]"!==e.type)return this._readBlankNodePunctuation(e);null!==this._subject&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=null===this._predicate;return this._restoreContext("blank",e),null!==this._object?this._getContextEndReader():null!==this._predicate?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,r=null,n=this._readListItem;const i=this._subject,s=this._contextStack,o=s[s.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),n=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),0!==s.length&&"list"===s[s.length-1].type&&this._emit(this._subject,this._predicate,this._object,this._graph),null===this._predicate){if(n=this._readPredicate,this._subject===this.RDF_NIL)return n}else if(n=this._getContextEndReader(),this._object===this.RDF_NIL)return n;r=this.RDF_NIL;break;case"literal":0===e.prefix.length?(this._literalValue=e.value,n=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),n=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if(void 0===(t=this._readEntity(e)))return}if(null===r&&(this._subject=r=this._factory.blankNode()),null===i?null===o.predicate?o.subject=r:o.object=r:this._emit(i,this.RDF_REST,r,this._graph),null!==t){if(this._n3Mode&&("IRI"===e.type||"prefixed"===e.type))return this._saveContext("item",this._graph,r,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(r,this.RDF_FIRST,t,this._graph)}return n}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const r=this._readEntity(e);if(void 0===r)return;t=this._factory.literal(this._literalValue,r),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const r=this._completeLiteral(e);if(r)return this._object=r.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),null===r.token?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(r.token))}_readFormulaTail(e){return"}"!==e.type?this._readPunctuation(e):(null!==this._subject&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),null===this._object?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,r=this._graph;const n=this._subject,i=this._inversePredicate;switch(e.type){case"}":if(null===this._graph)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,i&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const s=this._predicate,o=this._object;this._subject=this._factory.quad(n,s,o,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if("Quad"!==this._subject.termType)return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&null===this._graph&&void 0!==(r=this._readEntity(e))){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(null!==n){const e=this._predicate,t=this._object;i?this._emit(t,e,n,r):this._emit(n,e,t,r)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return"."!==e.type?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return"prefix"!==e.type?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if("IRI"!==e.type)return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t="IRI"===e.type&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return"]"!==e.type?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):"."!==e.type?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if(void 0!==(t=this._readEntity(e,!0)))break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(null===this._subject?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return","===e.type?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,r=t.length&&t[t.length-1];if(r&&"item"===r.type){const t=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,t,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,r;const n=this._factory.blankNode();if(void 0!==(r=this._readEntity(e)))return null===this._predicate?(t=this._subject,this._subject=n):(t=this._object,this._object=n),this._emit(t,r,n,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let r,n;if(void 0!==(r=this._readEntity(e)))return null===this._predicate?(n=this._subject,this._subject=t):(n=this._object,this._object=t),this._emit(t,r,n,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return">>"!==e.type?this._supportsQuads&&null===this._graph&&void 0!==(this._graph=this._readEntity(e))?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(">>"!==e.type)return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),null===this._subject?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,r,n){this._callback(null,this._factory.quad(e,t,r,n||this.DEFAULTGRAPH))}_error(e,t){const r=new Error(`${e} on line ${t.line}.`);r.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(r),this._callback=ni}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return("/"===e[1]?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let r="",n=-1,i=-1,s=0,o="/";for(;n<t;){switch(o){case":":if(i<0&&"/"===e[++n]&&"/"===e[++n])for(;(i=n+1)<t&&"/"!==e[i];)n=i;break;case"?":case"#":n=t;break;case"/":if("."===e[n+1])switch(o=e[1+ ++n],o){case"/":r+=e.substring(s,n-1),s=n+1;break;case void 0:case"?":case"#":return r+e.substring(s,n)+e.substr(n+1);case".":if(o=e[1+ ++n],void 0===o||"/"===o||"?"===o||"#"===o){if(r+=e.substring(s,n-2),(s=r.lastIndexOf("/"))>=i&&(r=r.substr(0,s)),"/"!==o)return`${r}/${e.substr(n+1)}`;s=n+1}}}o=e[++n]}return r+e.substring(s)}parse(e,t,r){let n,i,s;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(n=t.onQuad,i=t.onPrefix,s=t.onComment):(n=t,i=r),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${ti++}_`,this._prefixCallback=i||ni,this._inversePredicate=!1,this._quantified=Object.create(null),!n){const t=[];let r;if(this._callback=(e,n)=>{e?r=e:n&&t.push(n)},this._lexer.tokenize(e).every(e=>this._readCallback=this._readCallback(e)),r)throw r;return t}let o=(e,t)=>{null!==e?(this._callback(e),this._callback=ni):this._readCallback&&(this._readCallback=this._readCallback(t))};s&&(this._lexer.comments=!0,o=(e,t)=>{null!==e?(this._callback(e),this._callback=ni):this._readCallback&&("comment"===t.type?s(t.value):this._readCallback=this._readCallback(t))}),this._callback=n,this._lexer.tokenize(e,o)}}function ni(){}function ii(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(kn.rdf.first),e.RDF_REST=t.namedNode(kn.rdf.rest),e.RDF_NIL=t.namedNode(kn.rdf.nil),e.N3_FORALL=t.namedNode(kn.r.forAll),e.N3_FORSOME=t.namedNode(kn.r.forSome),e.ABBREVIATIONS={a:t.namedNode(kn.rdf.type),"=":t.namedNode(kn.owl.sameAs),">":t.namedNode(kn.log.implies),"<":t.namedNode(kn.log.isImpliedBy)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}if(ii(ri.prototype,Hn),void 0===si)var si={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};class oi{constructor(e,t){this.options=t||{},this.kb=e,this.target=t.target||{graph:{subjects:{},prefixes:{},terms:{}}},this.blankNodes=[],this.htmlOptions={selfClosing:"br img input area base basefont col colgroup source wbr isindex link meta param hr"},this.theOne="_:"+(new Date).getTime(),this.language=null,this.vocabulary=null,this.blankCounter=0,this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"}],this.inXHTMLMode=!1,this.absURIRE=/[\w\_\-]+:\S+/,this.finishedHandlers=[],this.init()}addTriple(e,t,r,n){var i,s,o,a;i=void 0===t?wr.namedNode(this.options.base):this.toRDFNodeObject(t),o=this.toRDFNodeObject(r),s=this.toRDFNodeObject(n),a=wr.namedNode(this.options.base),this.kb.add(i,o,s,a)}ancestorPath(e){for(var t="";e&&e.nodeType!==si.DOCUMENT_NODE;)t="/"+e.localName+t,e=e.parentNode;return t}copyMappings(e){var t={};for(var r in e)t[r]=e[r];return t}copyProperties(){}deriveDateTimeType(e){for(var t=0;t<oi.dateTimeTypes.length;t++){var r=oi.dateTimeTypes[t].pattern.exec(e);if(r&&r[0].length===e.length)return oi.dateTimeTypes[t].type}return null}init(){}newBlankNode(){return this.blankCounter++,"_:"+this.blankCounter}newSubjectOrigin(e,t){}parseCURIE(e,t,r){var n,i=e.indexOf(":");if(i>=0){var s=e.substring(0,i);if(""===s)return(n=t[""])?n+e.substring(i+1):null;if("_"===s)return"_:"+e.substring(i+1);if(oi.NCNAME.test(s)&&(n=t[s]))return n+e.substring(i+1)}return null}parseCURIEOrURI(e,t,r){var n=this.parseCURIE(e,t,r);return n||this.resolveAndNormalize(r,e)}parsePredicate(e,t,r,n,i,s){if(""===e)return null;var o=this.parseTermOrCURIEOrAbsURI(e,t,s?null:r,n,i);return o&&0===o.indexOf("_:")?null:o}parsePrefixMappings(e,t){for(var r=this.tokenize(e),n=null,i=0;i<r.length;i++)":"===r[i][r[i].length-1]?n=r[i].substring(0,r[i].length-1):n&&(t[n]=this.options.base?pr.join(r[i],this.options.base):r[i],n=null)}static parseRDFaDOM(e,t,r){var n=new oi(t,{base:r});e.baseURI||(e.baseURI=r),n.process(e,{baseURI:r})}parseSafeCURIEOrCURIEOrURI(e,t,r){return"["===(e=this.trim(e)).charAt(0)&&"]"===e.charAt(e.length-1)?0===(e=(e=e.substring(1,e.length-1)).trim(e)).length?null:"_:"===e?this.theOne:this.parseCURIE(e,t,r):this.parseCURIEOrURI(e,t,r)}parseTermOrCURIEOrAbsURI(e,t,r,n,i){e=this.trim(e);var s=this.parseCURIE(e,n,i);if(s)return s;if(r){if(t&&!this.absURIRE.exec(e))return t+e;var o=r[e];if(o)return o;if(o=r[e.toLowerCase()])return o}return this.absURIRE.exec(e)?this.resolveAndNormalize(i,e):null}parseTermOrCURIEOrURI(e,t,r,n,i){e=this.trim(e);var s=this.parseCURIE(e,n,i);if(s)return s;var o=r[e];return o||((o=r[e.toLowerCase()])?o:t&&!this.absURIRE.exec(e)?t+e:this.resolveAndNormalize(i,e))}parseURI(e){return e}process(e,t){var r;t=t||{},e.nodeType===si.DOCUMENT_NODE?(e.baseURI&&!t.baseURI&&(t.baseURI=e.baseURI),r=e.baseURI,(e=e.documentElement).baseURI||(e.baseURI=r),this.setContext(e)):e.parentNode.nodeType===si.DOCUMENT_NODE&&this.setContext(e);var n=[],i=function(e){if(!e&&t&&t.baseURI)return t.baseURI;var r=e.indexOf("#");return r>=0&&(e=e.substring(0,r)),t&&t.baseURIMap&&(e=t.baseURIMap(e)),e};for(n.push({current:e,context:this.push(null,i(e.baseURI))});n.length>0;){var s=n.shift();if(s.parent){if(s.context.parent&&s.context.parent.listMapping===s.listMapping)continue;for(let e in s.listMapping){var o=s.listMapping[e];if(0!==o.length){var a=[];for(let e=0;e<o.length;e++)a.push(this.newBlankNode());for(let e=0;e<a.length;e++)this.addTriple(s.parent,a[e],"http://www.w3.org/1999/02/22-rdf-syntax-ns#first",o[e]),this.addTriple(s.parent,a[e],"http://www.w3.org/1999/02/22-rdf-syntax-ns#rest",{type:oi.objectURI,value:e+1<a.length?a[e+1]:"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"});this.addTriple(s.parent,s.subject,e,{type:oi.objectURI,value:a[0]})}else this.addTriple(s.parent,s.subject,e,{type:oi.objectURI,value:"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"})}}else{var u=s.current,c=s.context,h=!1,l=null,d=null,f=null,p=c.prefixes,g=!1,y=[],v=c.listMapping,m=!c.parent,w=c.language,b=c.vocabulary;r=this.parseURI(i(u.baseURI)),u.item=null;var _=u.getAttributeNode("vocab");if(_){let e=this.trim(_.value);if(e.length>0){b=e;var S=r.spec;this.addTriple(u,S,"http://www.w3.org/ns/rdfa#usesVocabulary",{type:oi.objectURI,value:b})}else b=this.vocabulary}for(var E=0;E<u.attributes.length;E++){var x=u.attributes[E];if("x"===x.nodeName.charAt(0)&&0===x.nodeName.indexOf("xmlns:")){g||(p=this.copyMappings(p),g=!0);var A=x.nodeName.substring(6),F=oi.trim(x.value);p[A]=this.options.base?pr.join(F,this.options.base):F}}var T=u.getAttributeNode("prefix");T&&(g||(p=this.copyMappings(p),g=!0),this.parsePrefixMappings(T.value,p));var k=null;for(let e=0;!k&&e<this.langAttributes.length;e++)k=u.getAttributeNodeNS(this.langAttributes[e].namespaceURI,this.langAttributes[e].localName);if(k){let e=oi.trim(k.value);w=e.length>0?e:null}var I,C,R=u.getAttributeNode("rel"),P=u.getAttributeNode("rev"),N=u.getAttributeNode("typeof"),U=u.getAttributeNode("property"),O=u.getAttributeNode("datatype"),L=this.inHTMLMode?u.getAttributeNode("datetime"):null,D=u.getAttributeNode("content"),j=u.getAttributeNode("about"),M=u.getAttributeNode("src"),B=u.getAttributeNode("resource"),H=u.getAttributeNode("href"),q=u.getAttributeNode("inlist"),K=[];if(R){C=this.tokenize(R.value);for(let e=0;e<C.length;e++)(I=this.parsePredicate(C[e],b,c.terms,p,r,this.inHTMLMode&&null!==U))&&K.push(I)}var V=[];if(P){C=this.tokenize(P.value);for(let e=0;e<C.length;e++)(I=this.parsePredicate(C[e],b,c.terms,p,r,this.inHTMLMode&&U))&&V.push(I)}if(this.inHTMLMode&&(R||P)&&U&&(0===K.length&&(R=null),0===V.length&&(P=null)),R||P?(j&&(l=this.parseSafeCURIEOrCURIEOrURI(j.value,p,r)),N&&(f=l),l||(u.parentNode.nodeType===si.DOCUMENT_NODE?l=i(u.baseURI):c.parentObject&&(l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject)),B&&(d=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),d||(H?d=this.resolveAndNormalize(r,encodeURI(H.value)):M?d=this.resolveAndNormalize(r,encodeURI(M.value)):!N||j||this.inXHTMLMode&&("head"===u.localName||"body"===u.localName)||(d=this.newBlankNode())),!N||j||!this.inXHTMLMode||"head"!==u.localName&&"body"!==u.localName?N&&!j&&(f=d):f=l):!U||D||O?(j&&(l=this.parseSafeCURIEOrCURIEOrURI(j.value,p,r)),!l&&B&&(l=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),!l&&H&&(l=this.resolveAndNormalize(r,encodeURI(H.value))),!l&&M&&(l=this.resolveAndNormalize(r,encodeURI(M.value))),l||(u.parentNode.nodeType===si.DOCUMENT_NODE?l=i(u.baseURI):!this.inXHTMLMode&&!this.inHTMLMode||"head"!==u.localName&&"body"!==u.localName?N?l=this.newBlankNode():c.parentObject&&(l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject,U||(h=!0)):l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject),N&&(f=l)):(j&&(l=this.parseSafeCURIEOrCURIEOrURI(j.value,p,r),N&&(f=l)),l||u.parentNode.nodeType!==si.DOCUMENT_NODE?!l&&c.parentObject&&(l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject):(l=i(u.baseURI),N&&(f=l)),N&&!f&&(B&&(f=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),!f&&H&&(f=this.resolveAndNormalize(r,encodeURI(H.value))),!f&&M&&(f=this.resolveAndNormalize(r,encodeURI(M.value))),f||!this.inXHTMLMode&&!this.inHTMLMode||"head"!==u.localName&&"body"!==u.localName||(f=l),f||(f=this.newBlankNode()),d=f)),l&&(j||B||f)){var $=l;N&&!j&&!B&&d&&($=d),this.newSubjectOrigin(u,$)}if(f){C=this.tokenize(N.value);for(let e=0;e<C.length;e++){var W=this.parseTermOrCURIEOrAbsURI(C[e],b,c.terms,p,r);W&&this.addTriple(u,f,oi.typeURI,{type:oi.objectURI,value:W})}}if(l&&l!==c.parentObject&&(v={},m=!0),d){if(R&&q)for(let e=0;e<K.length;e++){let t=v[K[e]];t||(t=[],v[K[e]]=t),t.push({type:oi.objectURI,value:d})}else if(R)for(let e=0;e<K.length;e++)this.addTriple(u,l,K[e],{type:oi.objectURI,value:d});if(P)for(let e=0;e<V.length;e++)this.addTriple(u,d,V[e],{type:oi.objectURI,value:l})}else{if(l&&!d&&(R||P)&&(d=this.newBlankNode()),R&&q)for(let e=0;e<K.length;e++){let t=v[K[e]];t||(t=[],v[I]=t),y.push({predicate:K[e],list:t})}else if(R)for(let e=0;e<K.length;e++)y.push({predicate:K[e],forward:!0});if(P)for(let e=0;e<V.length;e++)y.push({predicate:V[e],forward:!1})}if(U){var J=null,z=null;O?(J=""===O.value?oi.PlainLiteralURI:this.parseTermOrCURIEOrAbsURI(O.value,b,c.terms,p,r),z=L&&!D?L.value:J===oi.XMLLiteralURI||J===oi.HTMLLiteralURI?null:D?D.value:u.textContent):D?(J=oi.PlainLiteralURI,z=D.value):L?(z=L.value,(J=oi.deriveDateTimeType(z))||(J=oi.PlainLiteralURI)):R||P||(B&&(z=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),!z&&H?z=this.resolveAndNormalize(r,encodeURI(H.value)):!z&&M&&(z=this.resolveAndNormalize(r,encodeURI(M.value))),z&&(J=oi.objectURI)),J||(N&&!j?(J=oi.objectURI,z=f):(z=u.textContent,this.inHTMLMode&&"time"===u.localName&&(J=oi.deriveDateTimeType(z)),J||(J=oi.PlainLiteralURI))),C=this.tokenize(U.value);for(let e=0;e<C.length;e++){let t=this.parsePredicate(C[e],b,c.terms,p,r);if(t)if(q){let e=v[t];e||(e=[],v[t]=e),e.push(J===oi.XMLLiteralURI||J===oi.HTMLLiteralURI?{type:J,value:u.childNodes}:{type:J||oi.PlainLiteralURI,value:z,language:w})}else J===oi.XMLLiteralURI||J===oi.HTMLLiteralURI?this.addTriple(u,l,t,{type:J,value:u.childNodes}):this.addTriple(u,l,t,{type:J||oi.PlainLiteralURI,value:z,language:w})}}if(l&&!h)for(let e=0;e<c.incomplete.length;e++)c.incomplete[e].list?c.incomplete[e].list.push({type:oi.objectURI,value:l}):c.incomplete[e].forward?this.addTriple(u,c.subject,c.incomplete[e].predicate,{type:oi.objectURI,value:l}):this.addTriple(u,l,c.incomplete[e].predicate,{type:oi.objectURI,value:c.subject});var X=null,G=l;h?((X=this.push(c,c.subject)).parentObject=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject,X.incomplete=c.incomplete,X.language=w,X.prefixes=p,X.vocabulary=b):((X=this.push(c,l)).parentObject=d||l||c.subject,X.prefixes=p,X.incomplete=y,d&&(G=d,v={},m=!0),X.listMapping=v,X.language=w,X.vocabulary=b),m&&n.unshift({parent:u,context:c,subject:G,listMapping:v});for(var Y=u.lastChild;Y;Y=Y.previousSibling)Y.nodeType===si.ELEMENT_NODE&&n.unshift({current:Y,context:X})}}this.inHTMLMode&&this.copyProperties();for(let t=0;t<this.finishedHandlers.length;t++)this.finishedHandlers[t](e)}push(e,t){return{parent:e,subject:t||(e?e.subject:null),parentObject:null,incomplete:[],listMapping:e?e.listMapping:{},language:e?e.language:this.language,prefixes:e?e.prefixes:this.target.graph.prefixes,terms:e?e.terms:this.target.graph.terms,vocabulary:e?e.vocabulary:this.vocabulary}}resolveAndNormalize(e,t){return pr.join(t,e)}setContext(e){"html"===e.localName&&"XHTML+RDFa 1.1"===e.getAttribute("version")?this.setXHTMLContext():"html"===e.localName||"http://www.w3.org/1999/xhtml"===e.namespaceURI?"undefined"!=typeof document&&document.doctype?"-//W3C//DTD XHTML+RDFa 1.0//EN"===document.doctype.publicId&&"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"===document.doctype.systemId?(console.log("WARNING: RDF 1.0 is not supported. Defaulting to HTML5 mode."),this.setHTMLContext()):"-//W3C//DTD XHTML+RDFa 1.1//EN"===document.doctype.publicId&&"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd"===document.doctype.systemId?this.setXHTMLContext():this.setHTMLContext():this.setHTMLContext():this.setXMLContext()}setHTMLContext(){this.setInitialContext(),this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"},{namespaceURI:null,localName:"lang"}],this.inXHTMLMode=!1,this.inHTMLMode=!0}setInitialContext(){this.vocabulary=null,this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"}]}setXHTMLContext(){this.setInitialContext(),this.inXHTMLMode=!0,this.inHTMLMode=!1,this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"},{namespaceURI:null,localName:"lang"}],this.target.graph.terms.alternate="http://www.w3.org/1999/xhtml/vocab#alternate",this.target.graph.terms.appendix="http://www.w3.org/1999/xhtml/vocab#appendix",this.target.graph.terms.bookmark="http://www.w3.org/1999/xhtml/vocab#bookmark",this.target.graph.terms.cite="http://www.w3.org/1999/xhtml/vocab#cite",this.target.graph.terms.chapter="http://www.w3.org/1999/xhtml/vocab#chapter",this.target.graph.terms.contents="http://www.w3.org/1999/xhtml/vocab#contents",this.target.graph.terms.copyright="http://www.w3.org/1999/xhtml/vocab#copyright",this.target.graph.terms.first="http://www.w3.org/1999/xhtml/vocab#first",this.target.graph.terms.glossary="http://www.w3.org/1999/xhtml/vocab#glossary",this.target.graph.terms.help="http://www.w3.org/1999/xhtml/vocab#help",this.target.graph.terms.icon="http://www.w3.org/1999/xhtml/vocab#icon",this.target.graph.terms.index="http://www.w3.org/1999/xhtml/vocab#index",this.target.graph.terms.last="http://www.w3.org/1999/xhtml/vocab#last",this.target.graph.terms.license="http://www.w3.org/1999/xhtml/vocab#license",this.target.graph.terms.meta="http://www.w3.org/1999/xhtml/vocab#meta",this.target.graph.terms.next="http://www.w3.org/1999/xhtml/vocab#next",this.target.graph.terms.prev="http://www.w3.org/1999/xhtml/vocab#prev",this.target.graph.terms.previous="http://www.w3.org/1999/xhtml/vocab#previous",this.target.graph.terms.section="http://www.w3.org/1999/xhtml/vocab#section",this.target.graph.terms.stylesheet="http://www.w3.org/1999/xhtml/vocab#stylesheet",this.target.graph.terms.subsection="http://www.w3.org/1999/xhtml/vocab#subsection",this.target.graph.terms.start="http://www.w3.org/1999/xhtml/vocab#start",this.target.graph.terms.top="http://www.w3.org/1999/xhtml/vocab#top",this.target.graph.terms.up="http://www.w3.org/1999/xhtml/vocab#up",this.target.graph.terms.p3pv1="http://www.w3.org/1999/xhtml/vocab#p3pv1",this.target.graph.terms.related="http://www.w3.org/1999/xhtml/vocab#related",this.target.graph.terms.role="http://www.w3.org/1999/xhtml/vocab#role",this.target.graph.terms.transformation="http://www.w3.org/1999/xhtml/vocab#transformation"}setXMLContext(){this.setInitialContext(),this.inXHTMLMode=!1,this.inHTMLMode=!1}tokenize(e){return this.trim(e).split(/\s+/)}static tokenize(e){return this.trim(e).split(/\s+/)}toRDFNodeObject(e){if(void 0!==e){if("string"==typeof e)return"_:"===e.substring(0,2)?(void 0===this.blankNodes[e.substring(2)]&&(this.blankNodes[e.substring(2)]=new tr(e.substring(2))),this.blankNodes[e.substring(2)]):wr.namedNode(e);switch(e.type){case oi.objectURI:return"_:"===e.value.substring(0,2)?(void 0===this.blankNodes[e.value.substring(2)]&&(this.blankNodes[e.value.substring(2)]=new tr(e.value.substring(2))),this.blankNodes[e.value.substring(2)]):wr.namedNode(e.value);case oi.PlainLiteralURI:return new sr(e.value,e.language||"");case oi.XMLLiteralURI:case oi.HTMLLiteralURI:var t="";return Object.keys(e.value).forEach(r=>{t+=Sr.domToString(e.value[r],this.htmlOptions)}),new sr(t,"",new rr.A(e.type));default:return new sr(e.value,"",new rr.A(e.type))}}}trim(e){return e.replace(/^\s\s*/,"").replace(/\s\s*$/,"")}static trim(e){return e.replace(/^\s\s*/,"").replace(/\s\s*$/,"")}}oi.XMLLiteralURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral",oi.HTMLLiteralURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML",oi.PlainLiteralURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral",oi.objectURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#object",oi.typeURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",oi.nameChar="[-A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�က0-F.0-9·̀-ͯ‿-⁀]",oi.nameStartChar="[A-Za-zÀ-ÖØ-öø-ÿĀ-ıĴ-ľŁ-ňŊ-žƀ-ǃǍ-ǰǴ-ǵǺ-ȗɐ-ʨʻ-ˁΆΈ-ΊΌΎ-ΡΣ-ώϐ-ϖϚϜϞϠϢ-ϳЁ-ЌЎ-яё-ќў-ҁҐ-ӄӇ-ӈӋ-ӌӐ-ӫӮ-ӵӸ-ӹԱ-Ֆՙա-ֆא-תװ-ײء-غف-يٱ-ڷں-ھۀ-ێې-ۓەۥ-ۦअ-हऽक़-ॡঅ-ঌএ-ঐও-নপ-রলশ-হড়-ঢ়য়-ৡৰ-ৱਅ-ਊਏ-ਐਓ-ਨਪ-ਰਲ-ਲ਼ਵ-ਸ਼ਸ-ਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઋઍએ-ઑઓ-નપ-રલ-ળવ-હઽૠଅ-ଌଏ-ଐଓ-ନପ-ରଲ-ଳଶ-ହଽଡ଼-ଢ଼ୟ-ୡஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-வஷ-ஹఅ-ఌఎ-ఐఒ-నప-ళవ-హౠ-ౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹೞೠ-ೡഅ-ഌഎ-ഐഒ-നപ-ഹൠ-ൡก-ฮะา-ำเ-ๅກ-ຂຄງ-ຈຊຍດ-ທນ-ຟມ-ຣລວສ-ຫອ-ຮະາ-ຳຽເ-ໄཀ-ཇཉ-ཀྵႠ-Ⴥა-ჶᄀᄂ-ᄃᄅ-ᄇᄉᄋ-ᄌᄎ-ᄒᄼᄾᅀᅌᅎᅐᅔ-ᅕᅙᅟ-ᅡᅣᅥᅧᅩᅭ-ᅮᅲ-ᅳᅵᆞᆨᆫᆮ-ᆯᆷ-ᆸᆺᆼ-ᇂᇫᇰᇹḀ-ẛẠ-ỹἀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼΩK-Å℮ↀ-ↂぁ-ゔァ-ヺㄅ-ㄬ가-힣一-龥〇〡-〩_]",oi.NCNAME=new RegExp("^"+oi.nameStartChar+oi.nameChar+"*$"),oi.dateTimeTypes=[{pattern:/-?P(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+(?:\.[0-9]+)?S)?)?/,type:"http://www.w3.org/2001/XMLSchema#duration"},{pattern:/-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9]T(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/,type:"http://www.w3.org/2001/XMLSchema#dateTime"},{pattern:/-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9](?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/,type:"http://www.w3.org/2001/XMLSchema#date"},{pattern:/(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/,type:"http://www.w3.org/2001/XMLSchema#time"},{pattern:/-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]/,type:"http://www.w3.org/2001/XMLSchema#gYearMonth"},{pattern:/-?[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9]/,type:"http://www.w3.org/2001/XMLSchema#gYear"}];const ai=oi.parseRDFaDOM;class ui{constructor(e){this.store=e,this.bnodes={},this.why=null,this.reify=!1}frameFactory(e,t,r){return{NODE:1,ARC:2,parent:t,parser:e,store:e.store,element:r,lastChild:0,base:null,lang:null,node:null,nodeType:null,listIndex:1,rdfid:null,datatype:null,collection:!1,terminateFrame:function(){this.collection&&this.node.close()},addSymbol:function(e,t){t=pr.join(t,this.base),this.node=this.store.sym(t),this.nodeType=e},loadTriple:function(){if(this.parent.parent.collection?this.parent.parent.node.append(this.node):this.store.add(this.parent.parent.node,this.parent.node,this.node,this.parser.why),null!=this.parent.rdfid){var e=this.store.sym(pr.join("#"+this.parent.rdfid,this.base));this.store.add(e,this.store.sym(ui.ns.RDF+"type"),this.store.sym(ui.ns.RDF+"Statement"),this.parser.why),this.store.add(e,this.store.sym(ui.ns.RDF+"subject"),this.parent.parent.node,this.parser.why),this.store.add(e,this.store.sym(ui.ns.RDF+"predicate"),this.parent.node,this.parser.why),this.store.add(e,this.store.sym(ui.ns.RDF+"object"),this.node,this.parser.why)}},isTripleToLoad:function(){return null!=this.parent&&null!=this.parent.parent&&this.nodeType===this.NODE&&this.parent.nodeType===this.ARC&&this.parent.parent.nodeType===this.NODE},addNode:function(e){this.addSymbol(this.NODE,e),this.isTripleToLoad()&&this.loadTriple()},addCollection:function(){this.nodeType=this.NODE,this.node=this.store.collection(),this.collection=!0,this.isTripleToLoad()&&this.loadTriple()},addCollectionArc:function(){this.nodeType=this.ARC},addBNode:function(e){null!=e?null!=this.parser.bnodes[e]?this.node=this.parser.bnodes[e]:this.node=this.parser.bnodes[e]=this.store.bnode():this.node=this.store.bnode(),this.nodeType=this.NODE,this.isTripleToLoad()&&this.loadTriple()},addArc:function(e){e===ui.ns.RDF+"li"&&(e=ui.ns.RDF+"_"+this.parent.listIndex,this.parent.listIndex++),this.addSymbol(this.ARC,e)},addLiteral:function(e){this.parent.datatype&&this.parent.datatype!==ui.ns.RDF+"langString"?this.node=this.store.literal(e,this.store.sym(this.parent.datatype)):this.node=this.store.literal(e,this.lang),this.nodeType=this.NODE,this.isTripleToLoad()&&this.loadTriple()}}}getAttributeNodeNS(e,t,r){var n=null;if(e.getAttributeNodeNS)n=e.getAttributeNodeNS(t,r);else for(var i,s=e.attributes,o=0;o<s.length;++o)if((i=s[o]).namespaceURI===t&&(i.prefix?i.prefix+":"+r:r)===i.nodeName){n=i;break}return n}parse(e,t,r){var n,i=e.childNodes;if(this.cleanParser(),e.nodeType===ui.nodeType.DOCUMENT){for(var s=0;s<i.length;s++)if(i[s].nodeType===ui.nodeType.ELEMENT){n=i[s];break}}else{if(e.nodeType!==ui.nodeType.ELEMENT)throw new Error("RDFParser: can't find root in "+t+". Halting. ");n=e}this.why=r;var o=this.frameFactory(this);return this.base=t,o.base=t,o.lang=null,this.parseDOM(this.buildFrame(o,n)),!0}parseDOM(e){for(var t,r=function(e){var t="";if(null==e.namespaceURI)throw new Error("RDF/XML syntax error: No namespace for "+e.localName+" in "+this.base);return e.namespaceURI&&(t+=e.namespaceURI),e.localName?t+=e.localName:e.nodeName&&(e.nodeName.indexOf(":")>=0?t+=e.nodeName.split(":")[1]:t+=e.nodeName),t}.bind(this),n=!0;e.parent;){var i=e.element,s=i.attributes;if(i.nodeType===ui.nodeType.TEXT||i.nodeType===ui.nodeType.CDATA_SECTION)e.parent.nodeType===e.NODE&&(e.addArc(ui.ns.RDF+"value"),e=this.buildFrame(e)),e.addLiteral(i.nodeValue);else if(r(i)!==ui.ns.RDF+"RDF")if(e.parent&&e.parent.collection&&(e.addCollectionArc(),(e=this.buildFrame(e,e.element)).parent.element=null),e.parent&&e.parent.nodeType&&e.parent.nodeType!==e.ARC){e.addArc(r(i)),this.reify&&(t=this.getAttributeNodeNS(i,ui.ns.RDF,"ID"))&&(e.rdfid=t.nodeValue,i.removeAttributeNode(t));var o=this.getAttributeNodeNS(i,ui.ns.RDF,"parseType"),a=this.getAttributeNodeNS(i,ui.ns.RDF,"datatype");if(a&&(e.datatype=a.nodeValue,i.removeAttributeNode(a)),o){var u=o.nodeValue;"Literal"===u?(e.datatype=ui.ns.RDF+"XMLLiteral",(e=this.buildFrame(e)).addLiteral(i.innerHTML||i.childNodes),n=!1):"Resource"===u?((e=this.buildFrame(e,e.element)).parent.element=null,e.addBNode()):"Collection"===u&&((e=this.buildFrame(e,e.element)).parent.element=null,e.addCollection()),i.removeAttributeNode(o)}if(0!==s.length){var c=this.getAttributeNodeNS(i,ui.ns.RDF,"resource"),h=this.getAttributeNodeNS(i,ui.ns.RDF,"nodeID");e=this.buildFrame(e),c?(e.addNode(c.nodeValue),i.removeAttributeNode(c)):h?(e.addBNode(h.nodeValue),i.removeAttributeNode(h)):e.addBNode();for(var l=s.length-1;l>=0;l--){var d=this.buildFrame(e);d.addArc(r(s[l])),r(s[l])===ui.ns.RDF+"type"?this.buildFrame(d).addNode(s[l].nodeValue):this.buildFrame(d).addLiteral(s[l].nodeValue)}}else 0===i.childNodes.length&&this.buildFrame(e).addLiteral("")}else{var f=this.getAttributeNodeNS(i,ui.ns.RDF,"about");if(t=this.getAttributeNodeNS(i,ui.ns.RDF,"ID"),f&&t)throw new Error("RDFParser: "+i.nodeName+" has both rdf:id and rdf:about. Halting. Only one of these properties may be specified on a node.");if(!f&&t)e.addNode("#"+t.nodeValue),i.removeAttributeNode(t);else if(null==f&&null==t){var p=this.getAttributeNodeNS(i,ui.ns.RDF,"nodeID");p?(e.addBNode(p.nodeValue),i.removeAttributeNode(p)):e.addBNode()}else e.addNode(f.nodeValue),i.removeAttributeNode(f);var g=this.getAttributeNodeNS(i,ui.ns.RDF,"type");ui.ns.RDF+"Description"!==r(i)&&(g={nodeValue:r(i)}),null!=g&&(this.store.add(e.node,this.store.sym(ui.ns.RDF+"type"),this.store.sym(pr.join(g.nodeValue,e.base)),this.why),g.nodeName&&i.removeAttributeNode(g));for(var y=s.length-1;y>=0;y--)this.store.add(e.node,this.store.sym(r(s[y])),this.store.literal(s[y].nodeValue,e.lang),this.why)}for(i=e.element;e.parent;){for(var v=e;null==i;)i=(e=e.parent).element;var m=i.childNodes&&i.childNodes[e.lastChild];if(m&&n){if((m.nodeType===ui.nodeType.ELEMENT||m.nodeType===ui.nodeType.TEXT||m.nodeType===ui.nodeType.CDATA_SECTION)&&(m.nodeType!==ui.nodeType.TEXT&&m.nodeType!==ui.nodeType.CDATA_SECTION||1===i.childNodes.length)){e.lastChild++,e=this.buildFrame(v,i.childNodes[e.lastChild-1]);break}e.lastChild++}else{if(e.terminateFrame(),!(e=e.parent))break;i=e.element,n=!0}}}}cleanParser(){this.bnodes={},this.why=null}buildFrame(e,t){var r=this.frameFactory(this,e,t);if(e&&(r.base=e.base,r.lang=e.lang),!t||t.nodeType===ui.nodeType.TEXT||t.nodeType===ui.nodeType.CDATA_SECTION)return r;var n=t.attributes,i=t.getAttributeNode("xml:base");null!=i&&(r.base=i.nodeValue,t.removeAttribute("xml:base"));var s=t.getAttributeNode("xml:lang");null!=s&&(r.lang=s.nodeValue,t.removeAttribute("xml:lang"));for(var o=n.length-1;o>=0;o--)if("xml"===n[o].nodeName.substr(0,3)){if("xmlns:"===n[o].name.slice(0,6)){var a=n[o].nodeValue;this.base&&(a=pr.join(a,this.base)),this.store.setPrefixForURI(n[o].name.slice(6),a)}t.removeAttributeNode(n[o])}return r}}function ci(e,t,r){var n,i,s,o=["INSERT","DELETE","WHERE"],a=_r("http://www.w3.org/ns/pim/patch#"),u=fn(t,t,r,r,null,null,"",null),c={},h=function(e,t,r,n,i){return"Line "+(t+1)+" of <"+e+">: Bad syntax:\n "+i+'\n at: "'+r.slice(n,n+30)+'"'};n=0;var l=t.sym(r+"#query");for(c.query=l;;){if((i=u.skipSpace(e,n))<0)return c;if(";"===e[i]){if((n=u.skipSpace(e,i+1))<0)return c;i=n}var d=!1;for(s=0;s<o.length;s++){var f=o[s];if(e.slice(i,i+f.length)===f){if((n=u.skipSpace(e,i+f.length))<0)throw h(u._thisDoc,u.lines,e,i+f.length,"found EOF, needed {...} after "+f);if(("INSERT"===f||"DELETE"===f)&&"DATA"===e.slice(n,n+4)){if((i=u.skipSpace(e,n+4))<0)throw h(u._thisDoc,u.lines,e,n+4,"needed {...} after INSERT DATA "+f);n=i}var p=[];if((i=u.node(e,n,p))<0)throw h(u._thisDoc,u.lines,e,n,"bad syntax or EOF in {...} after "+f);c[f.toLowerCase()]=p[0],t.add(l,a(f.toLowerCase()),p[0]),d=!0,n=i}}if(!d&&"@prefix"===e.slice(i,i+7)){if((n=u.directive(e,i))<0)throw h(u._thisDoc,u.lines,e,n,"bad syntax or EOF after @prefix ");n=u.checkDot(e,n),d=!0}if(!d)throw h(u._thisDoc,u.lines,e,i,"Unknown syntax at start of statememt: '"+e.slice(i).slice(0,20)+"'")}}function hi(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"text/turtle",i=arguments.length>4?arguments[4]:void 0;n=n||er.sT,n=n.split(";")[0];try{if(n===er.ny||n===er.sT)fn(t,t,r,r,null,null,"",null).loadBuf(e),o();else if(n===er.JG){new ui(t).parse(Sr.parseXML(e),r,t.sym(r)),o()}else if(n===er.H)ai(Sr.parseXML(e,{contentType:er.H}),t,r),o();else if(n===er.lc)ai(Sr.parseXML(e,{contentType:er.lc}),t,r),o();else if(n===er.K9||n===er.Fn)ci(e,t,r),o();else if(n===er.i2)bn(e,t,r).then(o).catch(a);else{if(n!==er._0&&n!==er.BR)throw void 0===n?new Error("contentType is undefined"):new Error("Don't know how to parse "+n+" yet");var s=new ri({factory:mn});!function(e,r){e&&i(e,t);try{s.parse(r,u)}catch(e){i(e,t)}}(null,e)}}catch(e){a(e)}function o(){i&&i(null,t)}function a(e){if(n!==er.i2||n!==er._0||n!==er.BR){if(!i){let t=new Error(e+" while trying to parse <"+r+"> as "+n);throw t.cause=e,t}i(e,t)}}function u(e,r){r?t.add(r.subject,r.predicate,r.object,r.graph):i(e,t)}hi.handled={"text/n3":!0,"text/turtle":!0,"application/rdf+xml":!0,"application/xhtml+xml":!0,"text/html":!0,"application/sparql-update":!0,"application/sparql-update-single-match":!0,"application/ld+json":!0,"application/nquads":!0,"application/n-quads":!0}}(0,Yt.A)(ui,"ns",{RDF:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",RDFS:"http://www.w3.org/2000/01/rdf-schema#"}),(0,Yt.A)(ui,"nodeType",{ELEMENT:1,ATTRIBUTE:2,TEXT:3,CDATA_SECTION:4,ENTITY_REFERENCE:5,ENTITY:6,PROCESSING_INSTRUCTION:7,COMMENT:8,DOCUMENT:9,DOCUMENT_TYPE:10,DOCUMENT_FRAGMENT:11,NOTATION:12});var li=a(4945),di=a.n(li),fi=a(2931);const pi={"text/n3":!0,"text/turtle":!0,"application/rdf+xml":!0,"application/xhtml+xml":!0,"text/html":!0,"application/ld+json":!0},gi={rdf:er.JG,owl:er.JG,n3:"text/n3",ttl:"text/turtle",nt:"text/n3",acl:"text/n3",html:"text/html",xml:"text/xml"},yi=e=>({link:_r("http://www.w3.org/2007/ont/link#",e),http:_r("http://www.w3.org/2007/ont/http#",e),httph:_r("http://www.w3.org/2007/ont/httph#",e),rdf:_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#",e),rdfs:_r("http://www.w3.org/2000/01/rdf-schema#",e),dc:_r("http://purl.org/dc/elements/1.1/",e),ldp:_r("http://www.w3.org/ns/ldp#",e)}),vi=yi();class mi{constructor(e,t){(0,Yt.A)(this,"response",void 0),(0,Yt.A)(this,"dom",void 0),this.response=e,this.dom=t}}(0,Yt.A)(mi,"pattern",void 0);class wi extends mi{static toString(){return"RDFXMLHandler"}static register(e){e.mediatypes[er.JG]={q:.9}}parse(e,t,r){let n=e.store;if(this.dom||(this.dom=Sr.parseXML(t)),"parsererror"===this.dom.documentElement.nodeName)return e.failFetch(r,"Badly formed XML in "+r.resource.value,"parse_error");let i=new ui(n);try{i.parse(this.dom,r.original.value,r.original)}catch(t){return e.failFetch(r,"Syntax error parsing RDF/XML! "+t,"parse_error")}return r.noMeta||n.add(r.original,vi.rdf("type"),vi.link("RDFDocument"),e.appNode),e.doneFetch(r,this.response)}}wi.pattern=new RegExp("application/rdf\\+xml");class bi extends mi{static toString(){return"XHTMLHandler"}static register(e){e.mediatypes[er.H]={q:.8}}parse(e,t,r){let n,i;this.dom||(this.dom=Sr.parseXML(t));let s=e.store,o=this.dom.getElementsByTagName("title");o.length>0&&s.add(r.resource,vi.dc("title"),s.rdfFactory.literal(o[0].textContent),r.resource);let a=this.dom.getElementsByTagName("link");for(let t=a.length-1;t>=0;t--)n=a[t].getAttribute("rel"),i=!1,n||(n=a[t].getAttribute("rev"),i=!0),n&&e.linkData(r.original,n,a[t].getAttribute("href"),r.resource,i);let u=this.dom.getElementsByTagName("script");for(let e=0;e<u.length;e++){let t=u[e].getAttribute("type");pi[t]&&(hi(u[e].textContent,s,r.original.value,t),hi(u[e].textContent,s,r.original.value,t))}if(r.noMeta||s.add(r.resource,vi.rdf("type"),vi.link("WebPage"),e.appNode),!r.noRDFa&&ai)try{ai(this.dom,s,r.original.value)}catch(t){let n="Error trying to parse "+r.resource+" as RDFa:\n"+t+":\n"+t.stack;return e.failFetch(r,n,"parse_error")}return e.doneFetch(r,this.response)}}bi.pattern=new RegExp("application/xhtml");class _i extends mi{static toString(){return"XMLHandler"}static register(e){e.mediatypes["text/xml"]={q:.5},e.mediatypes["application/xml"]={q:.5}}static isElement(e){return e.nodeType===Node.ELEMENT_NODE}parse(e,t,r){let n=Sr.parseXML(t);for(let i=0;i<n.childNodes.length;i++){const s=n.childNodes[i];if(_i.isElement(s)){let i=s.namespaceURI;if(i&&i===i.rdf){return e.addStatus(r.req,"Has XML root element in the RDF namespace, so assume RDF/XML."),new wi(this.response,n).parse(e,t,r)}break}}if(n.doctype&&"html"===n.doctype.name&&n.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/)&&n.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)){return e.addStatus(r.req,"Has XHTML DOCTYPE. Switching to XHTML Handler.\n"),new bi(this.response,n).parse(e,t,r)}let i=n.getElementsByTagName("html")[0];if(i){let s=i.getAttribute("xmlns");if(s&&s.match(/^http:\/\/www.w3.org\/1999\/xhtml/)){return e.addStatus(r.req,"Has a default namespace for XHTML. Switching to XHTMLHandler.\n"),new bi(this.response,n).parse(e,t,r)}}return e.failFetch(r,"Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n"+t.slice(0,80),901)}}_i.pattern=new RegExp("(text|application)/(.*)xml");class Si extends mi{static toString(){return"HTMLHandler"}static register(e){e.mediatypes["text/html"]={q:.8}}parse(e,t,r){let n=e.store;if(Ti(t)){return e.addStatus(r.req,"Has an XML declaration. We'll assume it's XHTML as the content-type was text/html.\n"),new bi(this.response).parse(e,t,r)}if(function(e){const t=e.indexOf("<!DOCTYPE html"),r=e.indexOf(">");if(-1===t||-1===r||t>r)return!1;return-1!==e.substr(t,r-t).indexOf("XHTML")}(t)){return e.addStatus(r.req,"Has XHTML DOCTYPE. Switching to XHTMLHandler.\n"),new bi(this.response).parse(e,t,r)}if(function(e){const t=e.match(/[^(<html)]*<html\s+[^<]*xmlns=['"]http:\/\/www.w3.org\/1999\/xhtml["'][^<]*>/);return!!t}(t)){return e.addStatus(r.req,"Has default namespace for XHTML, so switching to XHTMLHandler.\n"),new bi(this.response).parse(e,t,r)}let i=new RegExp("<title>([\\s\\S]+?)</title>","im").exec(t);return i&&n.add(r.resource,vi.dc("title"),n.rdfFactory.literal(i[1]),r.resource),n.add(r.resource,vi.rdf("type"),vi.link("WebPage"),e.appNode),e.addStatus(r.req,"non-XML HTML document, not parsed for data."),e.doneFetch(r,this.response)}}Si.pattern=new RegExp("text/html");class Ei extends mi{static toString(){return"JsonLdHandler"}static register(e){e.mediatypes["application/ld+json"]={q:.9}}async parse(e,t,r,n){const i=e.store;try{return await bn(t,i,r.original.value),e.store.add(r.original,vi.rdf("type"),vi.link("RDFDocument"),e.appNode),e.doneFetch(r,n)}catch(t){const i="Error trying to parse "+r.resource+" as JSON-LD:\n"+t;return e.failFetch(r,i,"parse_error",n)}}}Ei.pattern=/application\/(ld\+json|activity\+json)/;class xi extends mi{static toString(){return"TextHandler"}static register(e){e.mediatypes["text/plain"]={q:.5}}parse(e,t,r){if(Ti(t)){return e.addStatus(r.req,"Warning: "+r.resource+" has an XML declaration. We'll assume it's XML but its content-type wasn't XML.\n"),new _i(this.response).parse(e,t,r)}if(t.slice(0,500).match(/xmlns:/)){return e.addStatus(r.req,"May have an XML namespace. We'll assume it's XML but its content-type wasn't XML.\n"),new _i(this.response).parse(e,t,r)}return e.addStatus(r.req,"Plain text document, no known RDF semantics."),e.doneFetch(r,this.response)}}xi.pattern=new RegExp("text/plain");class Ai extends mi{static toString(){return"N3Handler"}static register(e){e.mediatypes["text/n3"]={},e.mediatypes["text/turtle"]={}}parse(e,t,r,n){let i=e.store,s=fn(i,i,r.original.value,r.original.value,null,null,"",null);try{s.loadBuf(t)}catch(t){let i="Error trying to parse "+r.resource+" as Notation3:\n"+t;return e.failFetch(r,i,"parse_error",n)}return e.addStatus(r.req,"N3 parsed: "+s.statementCount+" triples in "+s.lines+" lines."),e.store.add(r.original,vi.rdf("type"),vi.link("RDFDocument"),e.appNode),e.doneFetch(r,this.response)}}Ai.pattern=new RegExp("(application|text)/(x-)?(rdf\\+)?(n3|turtle)");const Fi={RDFXMLHandler:wi,XHTMLHandler:bi,XMLHandler:_i,HTMLHandler:Si,TextHandler:xi,N3Handler:Ai,JsonLdHandler:Ei};function Ti(e){return!!e.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)}class ki{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((0,Yt.A)(this,"store",void 0),(0,Yt.A)(this,"timeout",void 0),(0,Yt.A)(this,"_fetch",void 0),(0,Yt.A)(this,"mediatypes",void 0),(0,Yt.A)(this,"appNode",void 0),(0,Yt.A)(this,"requested",void 0),(0,Yt.A)(this,"timeouts",void 0),(0,Yt.A)(this,"redirectedTo",void 0),(0,Yt.A)(this,"fetchQueue",void 0),(0,Yt.A)(this,"fetchCallbacks",void 0),(0,Yt.A)(this,"nonexistent",void 0),(0,Yt.A)(this,"lookedUp",void 0),(0,Yt.A)(this,"handlers",void 0),(0,Yt.A)(this,"ns",void 0),(0,Yt.A)(this,"fireCallbacks",void 0),this.store=e||new Kr,this.ns=yi(this.store.rdfFactory),this.timeout=t.timeout||3e4,this._fetch=t.fetch||void 0!==a.g&&(a.g.solidFetcher||a.g.solidFetch)||"undefined"!=typeof window&&(window.solidFetcher||window.solidFetch)||di(),!this._fetch)throw new Error("No _fetch function available for Fetcher");this.appNode=this.store.sym("chrome://TheCurrentSession"),this.store.fetcher=this,this.requested={},this.timeouts={},this.redirectedTo={},this.fetchQueue={},this.fetchCallbacks={},this.nonexistent={},this.lookedUp={},this.handlers=[],this.mediatypes={"image/*":{q:.9},"*/*":{q:.1}},Sr.callbackify(this,["request","fail","refresh","retract","done"]),Object.keys(t.handlers||Fi).map(e=>this.addHandler(Fi[e]))}static crossSiteProxy(e){return ki.crossSiteProxyTemplate?ki.crossSiteProxyTemplate.replace("{uri}",encodeURIComponent(e)):void 0}static offlineOverride(e){let t=e;var r;return"undefined"!=typeof window&&window.panes&&(r=window.panes.UI)&&r.preferences&&r.preferences.get("offlineModeUsingLocalhost")&&"http://"===t.slice(0,7)&&"localhost/"!==t.slice(7,17)&&(t="http://localhost/"+t.slice(7),br.A.warn("Localhost kludge for offline use: actually getting <"+t+">")),t}static proxyIfNecessary(e){var t;if("undefined"!=typeof window&&window.panes&&(t=window.panes.UI)&&t.isExtension)return e;if("undefined"!=typeof $SolidTestEnvironment&&$SolidTestEnvironment.localSiteMap){let t=e.split("/").slice(2);const r=(e,t)=>{let n=t[e.shift()];return n?"string"==typeof n?n+e.join("/"):e?r(e,n):null:null},n=r(t,$SolidTestEnvironment.localSiteMap);if(n)return n}return ki.crossSiteProxyTemplate&&"undefined"!=typeof document&&document.location&&"https:"===(""+document.location).slice(0,6)&&"http:"===e.slice(0,5)?ki.crossSiteProxyTemplate.replace("{uri}",encodeURIComponent(e)):e}static unsupportedProtocol(e){let t=pr.protocol(e);return"tel"===t||"mailto"===t||"urn"===t}static setCredentials(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};void 0===t.credentials&&(void 0!==t.withCredentials?t.credentials=t.withCredentials?"include":"omit":t.credentials="include")}load(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t=Object.assign({},t),e instanceof Array)return Promise.all(e.map(e=>this.load(e,Object.assign({},t))));const r=e;let n=(0,fi.E)(r);n=n.split("#")[0],t=this.initFetchOptions(n,t);const i=this.appNode,s=this.store,o=s.statementsMatching(void 0,this.ns.link("requestedURI"),s.sym(n),i).map(e=>e.subject);for(const e of o){const r=s.any(e,this.ns.link("response"),null,i);if(null!=r){const e=s.statementsMatching(r,this.ns.link("outOfDate"),!0,i);s.remove(e),t.force=!0,t.clearPreviousData=!0}}const a=this.initFetchOptions(n,t);return this.pendingFetchPromise(n,a.baseURI,a)}async pendingFetchPromise(e,t,r){let n;return!r.force&&await this.fetchQueue[t]?n=this.fetchQueue[t]:(n=Promise.race([this.setRequestTimeout(e,r),this.fetchUri(e,r)]),this.fetchQueue[t]=n,this.cleanupFetchRequest(t,void 0,this.timeout)),n.then(t=>(e in this.timeouts&&(this.timeouts[e].forEach(clearTimeout),delete this.timeouts[e]),t))}cleanupFetchRequest(e,t,r){void 0!==t&&console.warn("_options is deprecated"),this.timeouts[e]=(this.timeouts[e]||[]).concat(setTimeout(()=>{this.isPending(e)||delete this.fetchQueue[e]},r))}initFetchOptions(e,t){let r=this.store;!t.method||"GET"===t.method.toUpperCase()||(t.force=!0),t.resource=r.rdfFactory.namedNode(e),t.baseURI=t.baseURI||e,t.original=r.rdfFactory.namedNode(t.baseURI),t.req=r.bnode(),t.headers=t.headers||{},t.contentType&&(t.headers["content-type"]=t.contentType),t.force&&(t.cache="no-cache");let n=this.acceptString();t.headers.accept=n;let i=ki.offlineOverride(e);t.requestedURI=i,ki.setCredentials(i,t);let s=ki.proxyIfNecessary(i);return i!==s&&(t.proxyUsed=!0),t.actualProxyURI=s,t}fetchUri(e,t){if(!e)return Promise.reject(new Error("Cannot fetch an empty uri"));if(ki.unsupportedProtocol(e))return this.failFetch(t,"fetcher: Unsupported protocol","unsupported_protocol");let r=this.getState(e);if(t.force)delete this.nonexistent[e];else{if("fetched"===r)return Promise.resolve(this.doneFetch(t,{status:200,ok:!0,statusText:"Already loaded into quadstore."}));if("failed"===r&&404===this.requested[e]){let r="Previously failed: "+this.requested[e],n={url:e,status:this.requested[e],statusText:r,responseText:r,headers:new li.Headers,ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return this.failFetch(t,r,this.requested[e],n)}}this.fireCallbacks("request",[e]),this.requested[e]=!0,t.noMeta||this.saveRequestMetadata(e,t);let{actualProxyURI:n}=t;return this._fetch(n,t).then(r=>this.handleResponse(r,e,t),r=>{let i={url:n,status:999,statusText:(r.name||"network failure")+": "+(r.errno||r.code||r.type),responseText:r.message,headers:new li.Headers,ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return this.handleError(i,e,t)})}nowOrWhenFetched(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};const i=(0,fi.E)(e);"function"==typeof t?r=t:void 0===t||((0,nr.Y2)(t)?n.referringTerm=t:n=t),this.load(i,n).then(e=>{if(r)if(e)if(e.ok)r(!0,"OK",e);else{let t="HTTP error: Status "+e.status+" ("+e.statusText+")";e.responseText&&(t+=" "+e.responseText),r(!1,t,e)}else{r(!1,"@@ nowOrWhenFetched: no response object!")}},function(e){var t=e.message||e.statusText;t="Failed to load <"+i+"> "+t,e.response&&e.response.status&&(t+=" status: "+e.response.status),r(!1,t,e.response)})}addStatus(e,t){let r=new Date;t="["+r.getHours()+":"+r.getMinutes()+":"+r.getSeconds()+"."+r.getMilliseconds()+"] "+t;let n=this.store;const i=n.the(e,this.ns.link("status"));(0,nr.P3)(i)?i.append(n.rdfFactory.literal(t)):br.A.warn("web.js: No list to add to: "+i+","+t)}failFetch(e,t,r,n){this.addStatus(e.req,t),e.noMeta||this.store.add(e.original,this.ns.link("error"),this.store.rdfFactory.literal(t));let i=(e.method||"GET").toUpperCase();("GET"===i||"HEAD"===i)&&(e.resource.equals(e.original),this.requested[pr.docpart(e.original.value)]=r,this.fireCallbacks("fail",[e.original.value,t]));var s=new Error("Fetcher: "+t);return s.status=r,s.statusText=t,s.response=n,Promise.reject(s)}linkData(e,t,r,n,i){if(!r)return;let s,o=this.store,a=o.rdfFactory.namedNode(pr.join(r,e.value));if("alternate"===t||"seeAlso"===t||"meta"===t||"describedby"===t){if(a.value===e.value)return;s=this.ns.rdfs("seeAlso")}else s="type"===t?o.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"):o.rdfFactory.namedNode(pr.join(encodeURIComponent(t),"http://www.iana.org/assignments/link-relations/"));i?o.add(a,s,e,n):o.add(e,s,a,n)}parseLinkHeader(e,t,r){if(!e)return;const n=/[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g,i=e.match(/<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g);if(null!=i)for(let e=0;e<i.length;e++){let s=i[e].split(">"),o=s[0].substring(1),a=s[1].match(n);if(null==a)return;for(let e=0;e<a.length;e++){let n=a[e].split("=")[1].replace(/["']/g,"");this.linkData(t,n,o,r)}}}doneFetch(e,t){return this.addStatus(e.req,"Done."),this.requested[e.original.value]="done",this.fireCallbacks("done",[e.original.value]),t.req=e.req,t}nowKnownAs(e,t){this.lookedUp[e.value]?this.lookedUp[t.value]||this.lookUpThing(t,e):this.lookedUp[t.value]&&(this.lookedUp[e.value]||this.lookUpThing(e,t))}putBack(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=(0,fi.E)(e);let n=new rr.A(r).doc();return t.contentType=t["content-type"]||t["Content-Type"]||t.contentType||er.sT,"application/ld+json"===t.contentType?new Promise((r,i)=>{Ir(n,this.store,n.uri,t.contentType,(n,s)=>{n?i(n):(t.data=s,this.webOperation("PUT",e,t).then(e=>r(e)).catch(e=>i(e)))})}):(t.data=Ir(n,this.store,n.value,t.contentType),this.webOperation("PUT",r,t))}webCopy(e,t,r){return this.webOperation("GET",e).then(e=>this.webOperation("PUT",t,{data:e.responseText,contentType:r}))}delete(e,t){return this.webOperation("DELETE",e,t).then(t=>(this.requested[e]=404,this.nonexistent[e]=!0,this.unload(this.store.rdfFactory.namedNode(e)),t))}async createIfNotExists(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:er.sT,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";const n=this;try{var i=await n.load(e)}catch(s){if(404===s.response.status){try{i=await n.webOperation("PUT",e.value,{data:r,contentType:t})}catch(e){throw e}return delete n.requested[e.value],i}throw s}return i}createContainer(e,t,r){let n={"content-type":er.sT,link:this.ns.ldp("BasicContainer")+'; rel="type"'};t&&(n.slug=t);let i={headers:n};return r&&(i.body=r),this.webOperation("POST",e,i)}invalidateCache(e){const t=(0,fi.E)(e),r=this;r.fetchQueue&&r.fetchQueue[t]&&(r.fetchQueue[t].PromiseStatus,delete r.fetchQueue[t]);if(r.requested[t]&&"done"!==r.requested[t]&&"failed"!==r.requested[t]&&404!==r.requested[t]){let e=`Rdflib: fetcher: Destructive operation on <${r.requested[t]}> file being fetched! `+t;console.error(e)}else delete r.requested[t],delete r.nonexistent[t]}webOperation(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=(0,fi.E)(t);r.method=e,r.body=r.data||r.body,r.force=!0;const i=this;if(r.body&&!r.contentType)throw new Error("Web operation sending data must have a defined contentType.");return r.contentType&&(r.headers=r.headers||{},r.headers["content-type"]=r.contentType),ki.setCredentials(n,r),new Promise(function(t,s){i._fetch(n,r).then(r=>{if(r.ok)"PUT"!==e&&"PATCH"!==e&&"POST"!==e&&"DELETE"!==e||i.invalidateCache(n),r.text?r.text().then(e=>{r.responseText=e,t(r)}):t(r);else{let t="Web error: "+r.status;r.statusText&&(t+=" ("+r.statusText+")"),t+=" on "+e+" of <"+n+">",r.responseText&&(t+=": "+r.responseText);let i=new Error(t);i.response=r,s(i)}},t=>{s(new Error("Fetch error for "+e+" of <"+n+">:"+t))})})}lookUpThing(e,t){let r=this.store.uris(e);return r=r.map(e=>pr.docpart(e)),r.forEach(e=>{this.lookedUp[e]=!0}),this.load(r,{referringTerm:t})}getHeader(e,t){const r=this.store,n=e.value,i=r.each(void 0,this.ns.link("requestedURI"),r.rdfFactory.literal(n));for(let e=0;e<i.length;e++){let n=i[e];if(void 0!==n){let e=r.any(n,this.ns.link("response"));if(void 0!==e&&r.anyValue(e,this.ns.http("status"))&&r.anyValue(e,this.ns.http("status")).startsWith("2")){let n=r.each(e,this.ns.httph(t.toLowerCase()));return n.length?n.map(e=>e.value):[]}}}}saveRequestMetadata(e,t){let r=t.req,n=this.store,i=t.referringTerm;this.addStatus(t.req,"Accept: "+t.headers.accept),(0,nr.Y2)(i)&&n.add(n.rdfFactory.namedNode(e),this.ns.link("requestedBy"),i,this.appNode),t.original&&t.original.value!==e&&n.add(r,this.ns.link("orginalURI"),n.rdfFactory.literal(t.original.value),this.appNode);const s=new Date,o="["+s.getHours()+":"+s.getMinutes()+":"+s.getSeconds()+"] ";n.add(r,this.ns.rdfs("label"),n.rdfFactory.literal(o+" Request for "+e),this.appNode),n.add(r,this.ns.link("requestedURI"),n.rdfFactory.literal(e),this.appNode),n.add(r,this.ns.link("status"),n.collection(),this.appNode)}saveResponseMetadata(e,t){const r=this.store;let n=r.bnode();return r.add(t.req,this.ns.link("response"),n,this.appNode),r.add(n,this.ns.http("status"),r.rdfFactory.literal(e.status),this.appNode),r.add(n,this.ns.http("statusText"),r.rdfFactory.literal(e.statusText),this.appNode),e.headers.forEach((e,i)=>{r.add(n,this.ns.httph(i),this.store.rdfFactory.literal(e),this.appNode),"content-type"===i&&r.add(t.resource,this.ns.rdf("type"),r.rdfFactory.namedNode(Sr.mediaTypeClass(e).value),this.appNode)}),n}objectRefresh(e){let t=this.store.uris(e);if(void 0!==t)for(let e=0;e<t.length;e++)this.refresh(this.store.rdfFactory.namedNode(pr.docpart(t[e])))}refresh(e,t){this.fireCallbacks("refresh",arguments),this.nowOrWhenFetched(e,{force:!0,clearPreviousData:!0},t)}refreshIfExpired(e,t){let r=this.getHeader(e,"Expires");!r||new Date(r[0]).getTime()<=(new Date).getTime()?this.refresh(e,t):t(!0,"Not expired",{})}retract(e){this.store.removeMany(void 0,void 0,void 0,e),e.value&&delete this.requested[pr.docpart(e.value)],this.fireCallbacks("retract",arguments)}getState(e){return void 0===this.requested[e]?"unrequested":!0===this.requested[e]?"requested":"done"===this.requested[e]?"fetched":"redirected"===this.requested[e]?this.getState(this.redirectedTo[e]):"failed"}isPending(e){return!0===this.requested[e]}unload(e){this.store.removeDocument(e),delete this.requested[e.value]}addHandler(e){this.handlers.push(e),e.register(this)}retryNoCredentials(e,t){t.retriedWithNoCredentials=!0,delete this.requested[e],delete this.fetchQueue[e];let r=Object.assign({},t,{credentials:"omit"});return this.addStatus(t.req,"Abort: Will retry with credentials SUPPRESSED to see if that helps"),this.load(e,r)}isCrossSite(e){if("undefined"==typeof document||!document.location)return!1;const t=pr.hostpart,r=""+document.location;return(t(r)&&t(e)&&t(r))!==t(e)}handleError(e,t,r){if(this.isCrossSite(t)){if(r.credentials&&"include"===r.credentials&&!r.retriedWithNoCredentials)return this.retryNoCredentials(t,r);let e=ki.crossSiteProxy(t);if(e&&!r.proxyUsed)return this.redirectToProxy(e,r)}var n;return e instanceof Error?n="Fetch error: "+e.message:(n=e.statusText,e.responseText&&(n+=` ${e.responseText}`)),this.failFetch(r,n,e.status||998,e)}addType(e,t,r,n){let i=t;if(n){var s=r.any(i,this.ns.link("requestedURI"));s&&s.value!==n&&r.add(r.rdfFactory.namedNode(n),this.ns.rdf("type"),e,this.appNode)}for(;;){const t=r.any(i,this.ns.link("requestedURI"));if(t&&t.value&&r.add(r.rdfFactory.namedNode(t.value),this.ns.rdf("type"),e,this.appNode),i=r.any(void 0,r.rdfFactory.namedNode("http://www.w3.org/2007/ont/link#redirectedRequest"),i),!i)break;var o=r.any(i,r.rdfFactory.namedNode("http://www.w3.org/2007/ont/link#response"));if(!o)break;var a=r.any(o,r.rdfFactory.namedNode("http://www.w3.org/2007/ont/http#status"));if(!a)break;if("301"!==a&&"302"!==a)break}}handleResponse(e,t,r){const n=this.store,i=e.headers,s=r.req,o=this.saveResponseMetadata(e,r),a=this.normalizedContentType(r,i)||"";let u=i.get("content-location");if(0===e.status)return this.handleError(e,t,r);if(e.status>=400)return 404===e.status&&(this.nonexistent[r.original.value]=!0,this.nonexistent[t]=!0),this.saveErrorResponse(e,o).then(()=>{let t=r.resource+" "+e.statusText;return this.failFetch(r,t,e.status,e)});var c=null,h=null;if(u&&(h=pr.join(u,t))!==t&&(c=h),200===e.status){if(this.addType(this.ns.link("Document"),s,n,t),c&&this.addType(this.ns.link("Document"),s,n,c),r.clearPreviousData){const e=n.statementsMatching(void 0,void 0,void 0,r.resource).slice();for(let t=0;t<e.length;t++)n.removeStatement(e[t])}let e=a.includes("image/")||a.includes("application/pdf");a&&e&&(this.addType(n.rdfFactory.namedNode("http://purl.org/dc/terms/Image"),s,n,t),c&&this.addType(n.rdfFactory.namedNode("http://purl.org/dc/terms/Image"),s,n,c))}if(u){if(!r.force&&c&&"done"===this.requested[h])return this.doneFetch(r,e);this.requested[h]=!0}this.parseLinkHeader(i.get("link"),r.original,s);let l=this.handlerForContentType(a,e);return l?e.text().then(t=>(e.responseText=t,l.parse(this,t,r,e))):(this.addStatus(s,"Fetch over. No data handled."),this.doneFetch(r,e))}saveErrorResponse(e,t){let r=this.store;return e.text().then(e=>{e.length>10&&r.add(t,this.ns.http("content"),r.rdfFactory.literal(e),t)})}handlerForContentType(e,t){if(!e)return null;let r=this.handlers.find(t=>e.match(t.pattern));return r?new r(t):null}guessContentType(e){return gi[e.split(".").pop()]}normalizedContentType(e,t){if(e.forceContentType)return e.forceContentType;let r=t.get("content-type");if(!r||r.includes("application/octet-stream")){let t=this.guessContentType(e.resource.value);if(t)return t}let n=pr.protocol(e.resource.value);return!r&&["file","chrome"].includes(n)?"text/xml":r}redirectToProxy(e,t){this.addStatus(t.req,"BLOCKED -> Cross-site Proxy to <"+e+">"),t.proxyUsed=!0;const r=this.store,n=t.req;t.noMeta||(r.add(n,this.ns.link("redirectedTo"),r.rdfFactory.namedNode(e),n),this.addStatus(n,"redirected to new request")),this.requested[t.resource.value]="redirected",this.redirectedTo[t.resource.value]=e;let i=Object.assign({},t);return i.baseURI=t.resource.value,this.fetchUri(e,i).then(e=>(i.noMeta||r.add(n,this.ns.link("redirectedRequest"),i.req,this.appNode),e))}setRequestTimeout(e,t){return new Promise(r=>{this.timeouts[e]=(this.timeouts[e]||[]).concat(setTimeout(()=>{!this.isPending(e)||t.retriedWithNoCredentials||t.proxyUsed||r(this.failFetch(t,`Request to ${e} timed out`,"timeout"))},this.timeout))})}addFetchCallback(e,t){this.fetchCallbacks[e]?this.fetchCallbacks[e].push(t):this.fetchCallbacks[e]=[t]}acceptString(){let e="";for(let t in this.mediatypes){""!==e&&(e+=", "),e+=t;for(let r in this.mediatypes[t])e+=";"+r+"="+this.mediatypes[t][r]}return e}}(0,Yt.A)(ki,"HANDLERS",void 0),(0,Yt.A)(ki,"CONTENT_TYPE_BY_EXT",void 0),(0,Yt.A)(ki,"crossSiteProxyTemplate",void 0),ki.HANDLERS=Fi,ki.CONTENT_TYPE_BY_EXT=gi;const Ii={parseJSON:function(e,t,r){var n,i,s,o={},a=r.sym(t);for(var u in e){0===u.indexOf("_:")?o[u]?n=o[u]:(n=r.bnode(u),o[u]=n):n=r.sym(u);var c=e[u];for(var h in c){var l=c[h];for(var d in i=r.sym(h),l){var f=l[d];if("uri"===f.type)s=r.sym(f.value),r.add(n,i,s,a);else if("BlankNode"===f.type)o[f.value]?s=o[f.value]:(s=r.bnode(f.value),o[f.value]=s),r.add(n,i,s,a);else{if("Literal"!==f.type)throw new Error("error: unexpected termtype: "+d.type);s=f.datatype?r.literal(f.value,void 0,r.sym(f.datatype)):f.lang?r.literal(f.value,f.lang):r.literal(f.value),r.add(n,i,s,a)}}}}}};function Ci(e){var t=0;function r(e){var t="",r=e.statements;for(var n in r)br.A.debug("Found statement: "+r),t+=o()+r[n]+"\n";return t}function n(e){var t="";for(var r in e.constraints){var n=e.constraints[r];t+=o()+"FILTER ( "+n.describe(r)+" ) \n"}return t}function i(e){for(var s="",a=0;a<e.optional.length;a++)br.A.debug("Found optional query"),s+=o()+"OPTIONAL { \n",t++,s+=r(e.optional[a]),s+=n(e.optional[a]),s+=i(e.optional[a]),t--,s+=o()+"}\n";return s}function s(e){var s=o()+"WHERE \n{ \n";return t++,s+=r(e),s+=n(e),s+=i(e),t--,s+="}"}function o(){for(var e="",r=0;r<t;r++)e+=" ";return e}return function(e){return function(e){for(var t=o()+"SELECT ",r=0;r<e.vars.length;r++)t+=e.vars[r]+" ";return t+"\n"}(e)+s(e.pat)}(e)}function Ri(e,t,r){var n=[];function i(e){if(n[e])return n[e];var t=r.variable(e);return n[e]=t,t}function s(e){return"string"==typeof e&&e.match(/[^ \n\t]/)}function o(e){return"string"==typeof e&&e.match(/^[\?\$]/)}function a(e){return"string"==typeof e?e.replace(/^&lt;/,"<").replace(/&gt;$/,">"):e}function u(e){return"string"==typeof e&&e.match(/^<[^>]*>$/)}function c(e){return"string"==typeof e&&(e.match(/^_:/)||e.match(/^$/))}function h(e){return"string"==typeof e&&e.match(/:$/)}function l(e){return"string"==typeof e&&e.match(/^:|^[^_][^:]*:/)}function d(e){return e.split(":")[0]}function f(e){return e.split(":")[1]}function p(e){return u(e)?e.slice(1,e.length-1):e}function g(e){var t=-1===e.indexOf("'")?null:e.indexOf("'"),n=-1===e.indexOf('"')?null:e.indexOf('"');if(!t&&!n){var i=new Array(1);return i[0]=e,i}var s,o,a=new Array(2);if(!t||n&&n<t)s='"',o=n;else{if(n&&!(t&&t<n))return br.A.error("SQARQL QUERY OOPS!"),a;s="'",o=t}a[0]=e.slice(0,o);var u,c=e.slice(o+1).indexOf(s);return-1===c?(br.A.error("SPARQL parsing error: no matching parentheses in literal "+e),e):(e.slice(c+o+2).match(/^\^\^/)?(u=e.slice(c+o+2).indexOf(" "),a[1]=r.literal(e.slice(o+1,o+1+c),r.sym(p(e.slice(o+4+c,o+2+c+u)))),a=a.concat(g(e.slice(c+o+3+u)))):e.slice(c+o+2).match(/^@/)?(u=e.slice(c+o+2).indexOf(" "),a[1]=r.literal(e.slice(o+1,o+1+c),e.slice(o+3+c,o+2+c+u),null),a=a.concat(g(e.slice(c+o+2+u)))):(a[1]=r.literal(e.slice(o+1,o+1+c)),br.A.info("Literal found: "+a[1]),a=a.concat(g(e.slice(c+o+2)))),a)}function y(e){e=e.replace(/\(/g," ( ").replace(/\)/g," ) ").replace(/</g," <").replace(/>/g,"> ").replace(/{/g," { ").replace(/}/g," } ").replace(/[\t\n\r]/g," ").replace(/; /g," ; ").replace(/\. /g," . ").replace(/, /g," , "),br.A.info("New str into spaceDelimit: \n"+e);var t=[],r=e.split(" ");for(var n in r)s(r[n])&&(t=t.concat(r[n]));return t}function v(e,t){for(var r=0;r<t.length;r++)if("string"==typeof t[r]&&t[r].toLowerCase()===e.toLowerCase())return r;return null}function m(e,t){for(var r=[],n=0;n<t.length;n++)"string"==typeof t[n]&&t[n].toLowerCase()===e.toLowerCase()&&r.push(n);return r}function w(e,t,r){br.A.info("Looking for a close bracket of type "+r+" in "+e);for(var n=0,i=0;i<e.length;i++)if(e[i]===t&&n++,e[i]===r&&n--,n<0)return i;return br.A.error("Statement had no close parenthesis in SPARQL query"),0}function b(e){return this.describe=function(t){return t+" = "+e.toNT()},this.test=function(t){return e.equals(t)},this}function _(e){this.describe=function(t){return"REGEXP( '"+e+"' , "+t+" )"},this.test=function(t){var r=new RegExp(e);return!!t.value&&r.test(t.value)}}function S(e,t){3!==e.length||"Variable"!==e[0].termType||"NamedNode"!==e[2].termType&&"Literal"!==e[2].termType?6===e.length&&"string"==typeof e[0]&&"regexp"===e[0].toLowerCase()&&"("===e[1]&&")"===e[5]&&","===e[3]&&"Variable"===e[4].termType&&"Literal"===e[2].termType&&(br.A.debug("Constraint added: "+e),t.constraints[e[4]]=new _(e[2].value)):"="===e[1]||">"===e[1]||"<"===e[1]?(br.A.debug("Constraint added: "+e),t.constraints[e[0]]=new b(e[2])):br.A.warn("I don't know how to handle the constraint: "+e)}function E(e,t){br.A.debug("Optional query: "+e+" not yet implemented.");var n=r.formula();x(e,n),t.optional.push(n)}function x(e,t){var n,s,h=function(e){for(var t=[],n=0;n<e.length;n++)"string"==typeof e[n]?(e[n]=a(e[n]),o(e[n])?t[n]=i(e[n].slice(1)):c(e[n])?(br.A.info(e[n]+" was identified as a bnode."),t[n]=r.bnode()):u(e[n])?(br.A.info(e[n]+" was identified as a symbol."),t[n]=r.sym(p(e[n]))):l(e[n])?(br.A.info(e[n]+" was identified as a prefixed symbol"),T[d(e[n])]?t[n]=r.sym(e[n]=T[d(e[n])]+f(e[n])):(br.A.error("SPARQL error: "+e[n]+" with prefix "+d(e[n])+" does not have a correct prefix entry."),t[n]=e[n])):t[n]=e[n]):t[n]=e[n];return t}(e);for(br.A.debug("WHERE: "+h);v("OPTIONAL",h);)s=v("OPTIONAL",h),br.A.debug("OPT: "+s+" "+h[s]+" in "+h),"{"!==h[s+1]&&br.A.warn("Bad optional opening bracket in word "+s),-1===(n=w(h.slice(s+2),"{","}"))?br.A.error("No matching bracket in word "+s):(E(h.slice(s+2,s+2+n),t),s=v("OPTIONAL",h),n=w(h.slice(s+2),"{","}"),h.splice(s,n+3));for(br.A.debug("WHERE after optionals: "+h);v("FILTER",h);){var g=v("FILTER",h);"("!==h[g+1]&&br.A.warn("Bad filter opening bracket in word "+g),-1===(n=w(h.slice(g+2),"(",")"))?br.A.error("No matching bracket in word "+g):(S(h.slice(g+2,g+2+n),t),g=v("FILTER",h),n=w(h.slice(g+2),"(",")"),h.splice(g,n+3))}br.A.debug("WHERE after filters and optionals: "+h),function(e,t){var r=new Array(1);r[0]=-1;for(var n=r.concat(m(".",e)),i=[],s=0;s<n.length-1;s++)i[s]=e.slice(n[s]+1,n[s+1]);for(s in i){br.A.info("s+p+o "+s+" = "+i[s]);var o=i[s][0];i[s].splice(0,1);var a=r.concat(m(";",i[s]));a.push(i[s].length);for(var u=[],c=0;c<a.length-1;c++)u[c]=i[s].slice(a[c]+1,a[c+1]);for(s in u){br.A.info("p+o "+s+" = "+i[s]);var h=u[s][0];u[s].splice(0,1);var l=r.concat(m(",",u[s]));l.push(u[s].length);var d=[];for(c=0;c<l.length-1;c++)d[c]=u[s].slice(l[c]+1,l[c+1]);for(s in d){var f=d[s][0];br.A.info("Subj="+o+" Pred="+h+" Obj="+f),t.add(o,h,f)}}}}(h,t)}br.A.info("SPARQL input: \n"+e);var A=new Dr,F=function(e){var t=g(e),r=[];for(var n in t)r="string"==typeof t[n]?r.concat(y(t[n])):r.concat(t[n]);return r=function(e){for(var t=e,r=0;r<t.length;r++)if("a"===t[r]&&(t[r]="<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"),"is"===t[r]&&"of"===t[r+2]){t.splice(r,1),t.splice(r+1,1);var n=t[r-1];t[r-1]=t[r+1],t[r+1]=n}return t}(r),br.A.info("SPARQL Tokens: "+r),r}(e),T=function(e){var t=m("PREFIX",e),r=[];for(var n in t){var i=e[t[n]+1],s=e[t[n]+2];if(h(i))if(u(s)){br.A.info("Prefix found: "+i+" -> "+s);var o=d(i),a=p(s);r[o]=a}else br.A.error("Invalid SPARQL symbol: "+s);else br.A.error("Invalid SPARQL prefix: "+i)}return r}(F);T.rdf||(T.rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"),T.rdfs||(T.rdfs="http://www.w3.org/2000/01/rdf-schema#");var k=v("SELECT",F),I=v("WHERE",F);if(k<0||I<0||k>I)return br.A.error("Invalid or nonexistent SELECT and WHERE tags in SPARQL query"),!1;if(function(e,t){for(var r in br.A.info("SPARQL vars: "+e),e)if(o(e[r])){br.A.info("Added "+e[r]+" to query variables from SPARQL");var n=i(e[r].slice(1));t.vars.push(n),n.label=e[r].slice(1)}else br.A.warn("Incorrect SPARQL variable in SELECT: "+e[r])}(F.slice(k+1,I),A),x(F.slice(I+2,F.length-1),A.pat),t)return A;for(var C in A.pat.statements){var R=A.pat.statements[C];"NamedNode"===R.subject.termType&&r.fetcher&&r.fetcher.lookUpThing(R.subject,"sparql:"+R.subject),"NamedNode"===R.object.termType&&r.fetcher&&r.fetcher.lookUpThing(R.object,"sparql:"+R.object)}return A}class Pi{constructor(e){if((0,Yt.A)(this,"store",void 0),(0,Yt.A)(this,"ifps",void 0),(0,Yt.A)(this,"fps",void 0),(0,Yt.A)(this,"patchControl",void 0),(0,Yt.A)(this,"ns",void 0),(e=e||new Kr).updater)throw new Error("You can't have two UpdateManagers for the same store");e.fetcher||(e.fetcher=new ki(e)),this.store=e,e.updater=this,this.ifps={},this.fps={},this.ns={},this.ns.link=_r("http://www.w3.org/2007/ont/link#"),this.ns.http=_r("http://www.w3.org/2007/ont/http#"),this.ns.httph=_r("http://www.w3.org/2007/ont/httph#"),this.ns.ldp=_r("http://www.w3.org/ns/ldp#"),this.ns.rdf=_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.ns.rdfs=_r("http://www.w3.org/2000/01/rdf-schema#"),this.ns.rdf=_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.ns.owl=_r("http://www.w3.org/2002/07/owl#"),this.patchControl=[]}patchControlFor(e){return this.patchControl[e.value]||(this.patchControl[e.value]=[]),this.patchControl[e.value]}isHttpUri(e){return"http"===e.slice(0,4)}flagAuthorizationMetadata(e){e||(e=this.store);const t=e.fetcher?.appNode,r=e.statementsMatching(void 0,this.ns.link("requestedURI"),void 0,t).map(e=>e.subject);for(const n of r){const r=e.any(n,this.ns.link("response"),null,t);null!=r&&e.add(r,this.ns.link("outOfDate"),!0,t)}}async checkEditable(e,t){if(!e)return!1;t||(t=this.store);const r=this.editable(e,t);if(void 0!==r)return r;await(t.fetcher?.load(e));return this.editable(e,t)}editable(e,t){if(!e)return!1;if(t||(t=this.store),e=(0,fi.E)(e),!this.isHttpUri(e)&&t.holds(t.rdfFactory.namedNode(e),t.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),t.rdfFactory.namedNode("http://www.w3.org/2007/ont/link#MachineEditableDocument")))return"LOCALFILE";var r,n=!1;const i=t.fetcher?.appNode;for(var s,o=t.each(void 0,this.ns.link("requestedURI"),(0,pr.docpart)(e),i),a=0;a<o.length;a++)if(void 0!==(r=o[a])){const o=t.any(r,this.ns.link("response"),null,i);if(void 0!==o){if(t.anyJS(o,this.ns.link("outOfDate"),null,i))continue;var u=t.anyValue(o,this.ns.httph("wac-allow"));if(u)for(var c of u.split(",")){var h=c.split("=");if(h[0].includes("user")&&!h[1].includes("write")&&!h[1].includes("append"))return!1}var l=t.each(o,this.ns.httph("accept-patch"));if(l.length)for(let e=0;e<l.length;e++){if((s=l[e].value.trim()).indexOf("application/sparql-update")>=0)return"SPARQL";if(s.indexOf("application/sparql-update-single-match")>=0)return"SPARQL";if(s.indexOf("text/n3")>=0)return"N3PATCH"}var d=t.each(o,this.ns.httph("ms-author-via"));if(d.length)for(let e=0;e<d.length;e++){if((s=d[e].value.trim()).indexOf("SPARQL")>=0)return"SPARQL";if(s.indexOf("DAV")>=0)return"DAV"}if(!this.isHttpUri(e))return!!u&&"LOCALFILE";var f=t.each(o,this.ns.http("status"));if(f.length)for(let e=0;e<f.length;e++)200!==f[e]&&404!==f[e]||(n=!0)}}if(0===o.length);else if(n)return!1}anonymize(e){return"_:"===e.toNT().substr(0,2)&&this.mentioned(e)?"?"+e.toNT().substr(2):e.toNT()}anonymizeNT(e){return this.anonymize(e.subject)+" "+this.anonymize(e.predicate)+" "+this.anonymize(e.object)+" ."}nTriples(e){return`${e.subject.toNT()} ${e.predicate.toNT()} ${e.object.toNT()} .`}statementBnodes(e){return[e.subject,e.predicate,e.object].filter(function(e){return(0,nr.jt)(e)})}statementArrayBnodes(e){var t=[];for(let r=0;r<e.length;r++)t=t.concat(this.statementBnodes(e[r]));t.sort();var r=[];for(let e=0;e<t.length;e++)0!==e&&t[e].equals(t[e-1])||r.push(t[e]);return r}cacheIfps(){this.ifps={};var e=this.store.each(void 0,this.ns.rdf("type"),this.ns.owl("InverseFunctionalProperty"));for(let t=0;t<e.length;t++)this.ifps[e[t].value]=!0;this.fps={},e=this.store.each(void 0,this.ns.rdf("type"),this.ns.owl("FunctionalProperty"));for(let t=0;t<e.length;t++)this.fps[e[t].value]=!0}bnodeContext2(e,t,r){var n,i,s=this.store.statementsMatching(void 0,void 0,e,t);for(let e=0;e<s.length;e++)if(this.fps[s[e].predicate.value]){if(!(n=s[e].subject).isBlank)return[s[e]];if(r&&(i=this.bnodeContext2(n,t,r-1)))return i.concat([s[e]])}s=this.store.statementsMatching(e,void 0,void 0,t);for(let e=0;e<s.length;e++)if(this.ifps[s[e].predicate.value]){if(!(n=s[e].object).isBlank)return[s[e]];if(r&&(i=this.bnodeContext2(n,t,r-1)))return i.concat([s[e]])}return null}bnodeContext1(e,t){for(var r=0;r<3;r++){var n=this.bnodeContext2(e,t,r);if(null!==n)return n}return this.store.connectedStatements(e,t)}mentioned(e){return 0!==this.store.statementsMatching(e,null,null,null).length||0!==this.store.statementsMatching(null,e).length||0!==this.store.statementsMatching(null,null,e).length}bnodeContext(e,t){var r=[];if(e.length){this.cacheIfps();for(let i=0;i<e.length;i++){var n=e[i];this.mentioned(n)&&(r=r.concat(this.bnodeContext1(n,t)))}}return r}statementContext(e){var t=this.statementBnodes(e);return this.bnodeContext(t,e.graph)}contextWhere(e){var t=this;return e&&0!==e.length?"WHERE { "+e.map(function(e){return t.anonymizeNT(e)}).join("\n")+" }\n":""}fire(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return Promise.resolve().then(()=>{if(!e)throw new Error("No URI given for remote editing operation: "+t);return n.noMeta=!0,n.contentType=n.contentType||"application/sparql-update",n.body=t,this.store.fetcher.webOperation("PATCH",e,n)}).then(n=>{if(!n.ok){let r="UpdateManager: update failed for <"+e+"> status="+n.status+", "+n.statusText+"\n for query: "+t;throw new Error(r)}r(e,n.ok,n.responseText,n)}).catch(t=>{r(e,!1,t.message,t)})}update_statement(e){if(!e||e.graph){var t=this,r=this.statementContext(e);return{statement:e?[e.subject,e.predicate,e.object,e.graph]:void 0,statementNT:e?this.anonymizeNT(e):void 0,where:t.contextWhere(r),set_object:function(e,r){var n=this.where;n+="DELETE DATA { "+this.statementNT+" } ;\n",n+="INSERT DATA { "+this.anonymize(this.statement[0])+" "+this.anonymize(this.statement[1])+" "+this.anonymize(e)+" . }\n",t.fire(this.statement[3].value,n,r)}}}}insert_statement(e,t){var r=e instanceof Array?e[0]:e,n=this.contextWhere(this.statementContext(r));if(e instanceof Array){var i="";for(let t=0;t<e.length;t++)i+=e[t]+"\n";n+="INSERT DATA { "+i+" }\n"}else n+="INSERT DATA { "+this.anonymize(e.subject)+" "+this.anonymize(e.predicate)+" "+this.anonymize(e.object)+" . }\n";this.fire(r.graph.value,n,t)}delete_statement(e,t){var r=e instanceof Array?e[0]:e,n=this.contextWhere(this.statementContext(r));if(e instanceof Array){var i="";for(let t=0;t<e.length;t++)i+=e[t]+"\n";n+="DELETE DATA { "+i+" }\n"}else n+="DELETE DATA { "+this.anonymize(e.subject)+" "+this.anonymize(e.predicate)+" "+this.anonymize(e.object)+" . }\n";this.fire(r.graph.value,n,t)}requestDownstreamAction(e,t){var r=this.patchControlFor(e);if(r.pendingUpstream)if(r.downstreamAction){if(""+r.downstreamAction!=""+t)throw new Error("Can't wait for > 1 different downstream actions")}else r.downstreamAction=t;else t(e)}clearUpstreamCount(e){this.patchControlFor(e).upstreamCount=0}getUpdatesVia(e){var t=this.store.fetcher.getHeader(e,"updates-via");return t&&t.length?t[0].trim():null}addDownstreamChangeListener(e,t){var r=this.patchControlFor(e);r.downstreamChangeListeners||(r.downstreamChangeListeners=[]),r.downstreamChangeListeners.push(t),this.setRefreshHandler(e,e=>{this.reloadAndSync(e)})}reloadAndSync(e){var t=this.patchControlFor(e),r=this;if(t.reloading)t.outOfDate=!0;else{t.reloading=!0;var n=1e3,i=function(){r.reload(r.store,e,function(e,r,s){if(e){if(t.downstreamChangeListeners)for(let e=0;e<t.downstreamChangeListeners.length;e++)t.downstreamChangeListeners[e]();t.reloading=!1,t.outOfDate&&(t.outOfDate=!1,i())}else t.reloading=!1,s&&0===s.status&&(t.reloading=!0,n*=2,setTimeout(i,n))})};i()}}setRefreshHandler(e,t){let r=this.getUpdatesVia(e);var n=t,i=this,s=this,o=1500,a=0;if(!r)return!1;r=(0,pr.join)(r,e.value);const u=r.replace(/^http:/,"ws:").replace(/^https:/,"wss:");var c=function(){var t;if("undefined"!=typeof WebSocket)t=new WebSocket(u);else{if("undefined"==typeof window||!window.WebSocket)return;t=window.WebSocket(u)}t.onopen=function(){o=1500,this.send("sub "+e.value),a&&s.requestDownstreamAction(e,n)};var r=i.patchControlFor(e);r.upstreamCount=0,t.onerror=function(e){},t.onclose=function(e){o*=2,a+=1,setTimeout(function(){c()},o)},t.onmessage=function(t){if(t.data&&"pub"===t.data.slice(0,3)){if("upstreamCount"in r&&(r.upstreamCount-=1,r.upstreamCount>=0))return;r.upstreamCount=0,i.requestDownstreamAction(e,n)}}};return c(),!0}updateMany(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const r=e.concat(t).map(e=>e.why),n=this,i=[];r.forEach(e=>{i.find(t=>t.equals(e))||i.push(e)});const s=i.map(r=>n.update(e.filter(e=>e.why.equals(r)),t.filter(e=>e.why.equals(r))));return s.length,Promise.all(s)}constructSparqlUpdateQuery(e,t,r){var n=this.contextWhere(r),i="";if(n.length){if(e.length){i+="DELETE { ";for(let t=0;t<e.length;t++)i+=this.anonymizeNT(e[t])+"\n";i+=" }\n"}if(t.length){i+="INSERT { ";for(let e=0;e<t.length;e++)i+=this.anonymizeNT(t[e])+"\n";i+=" }\n"}i+=n}else{if(e.length){i+="DELETE DATA { ";for(let t=0;t<e.length;t++)i+=this.anonymizeNT(e[t])+"\n";i+=" } \n"}if(t.length){e.length&&(i+=" ; "),i+="INSERT DATA { ";for(let e=0;e<t.length;e++)i+=this.nTriples(t[e])+"\n";i+=" }\n"}}return i}constructN3PatchQuery(e,t,r){var n="\n@prefix solid: <http://www.w3.org/ns/solid/terms#>.\n@prefix ex: <http://www.example.org/terms#>.\n\n_:patch\n";return r&&r.length>0&&(n+=`\n solid:where {\n ${r.map(e=>this.anonymizeNT(e)).join("\n ")}\n };`),e.length>0&&(n+=`\n solid:deletes {\n ${e.map(e=>this.anonymizeNT(e)).join("\n ")}\n };`),t.length>0&&(n+=`\n solid:inserts {\n ${t.map(e=>this.anonymizeNT(e)).join("\n ")}\n };`),n+=" a solid:InsertDeletePatch .\n"}update(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!r){var s=this;return new Promise(function(r,o){s.update(e,t,function(e,t,n){t?r():o(new Error(n))},n,i)})}try{var o=this.store,a=e?(0,nr.ok)(e)?e.statements:e instanceof Array?e:[e]:[],u=t?(0,nr.ok)(t)?t.statements:t instanceof Array?t:[t]:[];if(!(a instanceof Array))throw new Error("Type Error "+typeof a+": "+a);if(!(u instanceof Array))throw new Error("Type Error "+typeof u+": "+u);if(0===a.length&&0===u.length)return r(null,!0);var c=a.length?a[0].graph:u[0].graph;if(!c){let e="Error patching: statement does not specify which document to patch:"+a[0]+", "+u[0];throw new Error(e)}if("NamedNode"!==c.termType){let e="Error patching: document not a NamedNode:"+a[0]+", "+u[0];throw new Error(e)}var h=this.patchControlFor(c),l=Date.now(),d=["subject","predicate","object","why"],f={delete:a,insert:u};["insert","delete"].map(function(e){f[e].map(function(e){if(!c.equals(e.graph))throw new Error("update: destination "+c+" inconsistent with delete quad "+e.graph);d.map(function(t){if(void 0===e[t])throw new Error("update: undefined "+t+" of statement.")})})});var p=this.editable(c.value,o);if(!1===p)throw new Error("Update: Can't make changes in uneditable "+c);if(void 0===p){if(n)throw new Error("Update: Loaded "+c+"but still can't figure out what editing protocol it supports.");return void this.store.fetcher.load(c).then(n=>{this.update(e,t,r,!0,i)},n=>{if(404!==n.response.status)throw new Error(`Update: Can't get updatability status ${c} before patching: ${n}`);this.update(e,t,r,!0,i)})}if(p.indexOf("SPARQL")>=0||p.indexOf("N3PATCH")>=0){var g=p.indexOf("SPARQL")>=0,y=[];a.length&&(y=this.statementArrayBnodes(a)),u.length&&(y=y.concat(this.statementArrayBnodes(u)));var v=this.bnodeContext(y,c),m=g?this.constructSparqlUpdateQuery(a,u,v):this.constructN3PatchQuery(a,u,v);i.contentType=g?"application/sparql-update":"text/n3",h.pendingUpstream=h.pendingUpstream?h.pendingUpstream+1:1,"upstreamCount"in h&&(h.upstreamCount+=1),this.fire(c.value,m,(e,t,n,i)=>{if(i.elapsedTimeMs=Date.now()-l,t){try{o.remove(a)}catch(e){t=!1,n="Remote Ok BUT error deleting "+a.length+" from store!!! "+e}for(let e=0;e<u.length;e++)o.add(u[e].subject,u[e].predicate,u[e].object,c)}if(r(e,t,n,i),h.pendingUpstream-=1,0===h.pendingUpstream&&h.downstreamAction){var s=h.downstreamAction;delete h.downstreamAction,s(c)}},i)}else if(p.indexOf("DAV")>=0)this.updateDav(c,a,u,r,i);else{if(!(p.indexOf("LOCALFILE")>=0))throw new Error("Unhandled edit method: '"+p+"' for "+c);try{this.updateLocalFile(c,a,u,r,i)}catch(e){r(c.value,!1,"Exception trying to write back file <"+c.value+">\n")}}}catch(e){r(void 0,!1,"Exception in update: "+e+"\n"+Sr.stackString(e))}}updateDav(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},s=this.store;var o=s.any(e,this.ns.link("request"));if(!o)throw new Error("No record of our HTTP GET request for document: "+e);var a=s.any(o,this.ns.link("response"));if(!a)return null;var u=s.the(a,this.ns.httph("content-type")).value;let c=s.statementsMatching(void 0,void 0,void 0,e).slice();for(let e=0;e<t.length;e++)Sr.RDFArrayRemove(c,t[e]);for(let e=0;e<r.length;e++)c.push(r[e]);const h=this.serialize(e.value,c,u);var l,d=s.the(a,this.ns.httph("content-location"));return d&&(l=(0,pr.join)(d.value,l)),i.contentType=u,i.noMeta=!0,i.body=h,s.fetcher.webOperation("PUT",l,i).then(i=>{if(!i.ok)throw new Error(i.error);for(let e=0;e<t.length;e++)s.remove(t[e]);for(let t=0;t<r.length;t++)s.add(r[t].subject,r[t].predicate,r[t].object,e);n(e.value,i.ok,i.responseText,i)}).catch(t=>{n(e.value,!1,t.message,t)})}updateLocalFile(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const s=this.store;let o=s.statementsMatching(void 0,void 0,void 0,e).slice();for(let e=0;e<t.length;e++)Sr.RDFArrayRemove(o,t[e]);for(let e=0;e<r.length;e++)o.push(r[e]);var a=e.value.lastIndexOf(".");if(a<1)throw new Error("Rewriting file: No filename extension: "+e.value);var u=e.value.slice(a+1);let c=ki.CONTENT_TYPE_BY_EXT[u];if(!c)throw new Error("File extension ."+u+" not supported for data write");i.body=this.serialize(e.value,o,c),i.contentType=c,s.fetcher.webOperation("PUT",e.value,i).then(i=>{if(!i.ok)return n(e.value,!1,i.error);for(let e=0;e<t.length;e++)s.remove(t[e]);for(let t=0;t<r.length;t++)s.add(r[t].subject,r[t].predicate,r[t].object,e);n(e.value,!0,"")})}serialize(e,t,r){const n=this.store;let i;if("string"==typeof t)return t;var s=Tr(n);switch(s.suggestNamespaces(n.namespaces),s.setBase(e),r){case"text/xml":case"application/rdf+xml":i=s.statementsToXML(t);break;case"text/n3":case"text/turtle":case"application/x-turtle":case"application/n3":i=s.statementsToN3(t);break;default:throw new Error("Content-type "+r+" not supported for data serialization")}return i}put(e,t,r,n){const i=this.store;let s;return Promise.resolve().then(()=>(s=this.serialize(e.value,t,r),i.fetcher.webOperation("PUT",e.value,{contentType:r,body:s}))).then(r=>{if(!r.ok)return n(e.value,r.ok,r.error,r);delete i.fetcher.nonexistent[e.value],delete i.fetcher.requested[e.value],"string"!=typeof t&&t.map(e=>{i.addStatement(e)}),n(e.value,r.ok,"",r)}).catch(t=>{n(e.value,!1,t.message)})}reload(e,t,r){var n=Date.now();e.fetcher.nowOrWhenFetched(t.value,{force:!0,noMeta:!0,clearPreviousData:!0},function(e,i,s){if(e)if(s.onErrorWasCalled||200!==s.status)r(!1,"Non-HTTP error reloading data: "+i,s);else{var o=Date.now()-n;t.reloadTimeTotal||(t.reloadTimeTotal=0),t.reloadTimeCount||(t.reloadTimeCount=0),t.reloadTimeTotal+=o,t.reloadTimeCount+=1,r(!0)}else r(!1,"Error reloading data: "+i,s)})}}const Ni={...mn,fetcher:(e,t)=>new ki(e,t),graph(){return new Kr(arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0)||{rdfFactory:mn})},lit(e,t,r){return this.literal(""+e,t||r)},st(e,t,r,n){return this.quad(e,t,r,n)}},Ui=Ni;class Oi{constructor(e,t){this.parent=e,this.via=t,this.connected=!1,this.pending={},this.subscribed={},this.socket={};try{this.socket=new WebSocket(t),this.socket.onopen=this.onOpen,this.socket.onclose=this.onClose,this.socket.onmessage=this.onMessage,this.socket.onerror=this.onError}catch(e){this.onError(e)}}_decode(e){var t,r,n,i,s,o,a;for(r in i={},s=function(){var r,n,i,s;for(s=[],r=0,n=(i=e.split("&")).length;r<n;r++)t=i[r],s.push(t.split("="));return s}())t=s[r],a=(o=[decodeURIComponent(t[0]),decodeURIComponent(t[1])])[1],null==i[n=o[0]]&&(i[n]=[]),i[n].push(a);return i}_send(e,t,r){var n,i;return i=[e,t,r].join(" "),"function"==typeof(n=this.socket).send?n.send(i):void 0}_subscribe(e){return this._send("sub",e,""),this.subscribed[e]=!0,this.subscribed[e]}onClose(e){var t;for(t in this.connected=!1,this.subscribed)this.pending[t]=!0;return this.subscribed={},this.subscribed}onError(e){throw new Error("onError"+e)}onMessage(e){var t,r;return"ping"===(r=e.data.split(" "))[0]?"function"==typeof(t=this.socket).send?t.send("pong "+r.slice(1).join(" ")):void 0:"pub"===r[0]?this.parent.onUpdate(r[1],this._decode(r[2])):void 0}onOpen(e){var t,r;for(r in this.connected=!0,t=[],this.pending)delete this.pending[r],t.push(this._subscribe(r));return t}subscribe(e){return this.connected?this._subscribe(e):(this.pending[e]=!0,this.pending[e])}}class Li{constructor(e){this.fetcher=e,this.graph={},this.via={},this.fetcher.addCallback("headers",this.onHeaders)}onHeaders(e){var t,r,n;return null==e.headers||"undefined"==typeof WebSocket||null===WebSocket||(t=e.headers.etag,n=e.headers["updates-via"],r=e.uri,t&&n&&(this.graph[r]={etag:t,via:n},this.register(n,r))),!0}onUpdate(e,t){return this.fetcher.refresh(Ui.namedNode(e))}register(e,t){return null==this.via[e]&&(this.via[e]=new Oi(this,e)),this.via[e].subscribe(t)}}const Di={};for(const e in Ui)"function"==typeof Ui[e]&&(Di[e]=Ui[e].bind(Ui));const{fetcher:ji,graph:Mi,lit:Bi,st:Hi,namedNode:qi,variable:Ki,blankNode:Vi,defaultGraph:$i,literal:Wi,quad:Ji,triple:zi}=Di,Xi=new Ur,Gi=e=>Xi.fromNT(e),Yi=Or.fromValue,Qi=tr.nextId;class Zi extends Kr{constructor(e){super(e),(0,Yt.A)(this,"fetcher",void 0),this.fetcher=new ki(this,{})}}class es extends Zi{constructor(e){super(e),(0,Yt.A)(this,"updater",void 0),this.updater=new Pi(this)}}const ts=Ar()(e),rs=qi("http://www.iana.org/assignments/link-relations/acl");function ns(e){const t=ts;function r(e,r,n,i={}){const s=i.public||[],o=Mi(),a=_r("http://www.w3.org/ns/auth/acl#");let u=o.sym(`${n}#a1`);const c=o.sym(n),h=o.sym(e);if(o.add(u,t.rdf("type"),a("Authorization"),c),o.add(u,a("accessTo"),h,c),i.defaultForNew&&o.add(u,a("default"),h,c),o.add(u,a("agent"),r,c),o.add(u,a("mode"),a("Read"),c),o.add(u,a("mode"),a("Write"),c),o.add(u,a("mode"),a("Control"),c),s.length){u=o.sym(`${n}#a2`),o.add(u,t.rdf("type"),a("Authorization"),c),o.add(u,a("accessTo"),h,c),o.add(u,a("agentClass"),t.foaf("Agent"),c);for(let e=0;e<s.length;e++)o.add(u,a("mode"),a(s[e]),c)}return Ir(c,o,n)}return{findAclDocUrl:async function(t){await e.fetcher.load(t);const r=e.any(t,rs);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),rs);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),rs);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 is=()=>{let{SolidAppContext:e}=window;if(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 ss(){const{$SolidTestEnvironment:e}=window;if(void 0!==e&&e.username)return t("Assuming the user is "+e.username),qi(e.username);if("undefined"!=typeof document&&document.location&&"http://localhost"===(""+document.location).slice(0,16)){const e=document.getElementById("appTarget");if(!e)return null;const r=e.getAttribute("testID");return r?(t("Assuming user is "+r),qi(r)):null}return null}class os{session;constructor(e){this.session=e}get authSession(){return this.session}currentUser(){const e=is();return e.viewingNoAuthPage?qi(e.webId):this&&this.session&&this.session.info&&this.session.info.webId&&this.session.info.isLoggedIn?qi(this.session.info.webId):ss()}async checkUser(e){const r=new URL(window.location.href).hash;r&&window.localStorage.setItem("preLoginRedirectHash",r),this.session.events.on(Ke,e=>{t(`Session restored to ${e}`),document.location.toString()!==e&&history.replaceState(null,"",e)});const n=new URL(window.location.href);n.hash="",await this.session.handleIncomingRedirect({restorePreviousSession:!0,url:n.href});const i=window.localStorage.getItem("preLoginRedirectHash");if(i){const e=new URL(window.location.href);e.hash!==i&&(history.pushState?history.pushState(null,document.title,i):location.hash=i,e.hash=i),window.localStorage.setItem("preLoginRedirectHash","")}let s=ss();if(s)return Promise.resolve(e?e(s):s);const o=this.webIdFromSession(this.session.info);return o&&(s=this.saveUser(o)),s&&t(`(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=qi(r);return t&&(t.me=n),n}return null}webIdFromSession(e){return e?.webId&&e.isLoggedIn?e.webId:null}}function as(e){return qi(e.uri+"#id"+Date.now())}function us(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const cs="index.ttl#this";function hs(e,t){const r=ts;async function n(t,r,n){await e.fetcher.load(t);const i=e.any(t,new rr.A("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=as(i),o=[Hi(s,r.rdf("type"),r.solid("TypeRegistration"),i.doc()),Hi(s,r.solid("forClass"),r.meeting("LongChat"),i.doc()),Hi(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 rr.A(r)}(r,await t.getPodRoot(n));let s=!0;try{await e.fetcher.load(new rr.A(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+cs),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"),Yi(new Date(Date.now())),o),t.me&&n.add(s,r.dc("author"),t.me,o),new Promise(function(e,r){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 u(t,n){await e.fetcher.load(t.doc());const i=e.any(t,r.ldp("inbox"),void 0,t.doc());if(!i)throw new Error(`Invitee inbox not found! ${t.value}`);const s=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${r.rdf("seeAlso")} <${n.value}> .\n `,o=await(e.fetcher?.webOperation("POST",i.value,{data:s,contentType:"text/turtle"})),a=o?.headers.get("location");if(!a)throw new Error(`Invite sending returned a ${o?.status}`)}return{setAcl:n,addToPrivateTypeIndex:i,findChat:s,createChatThing:o,getChat:async function(e,t=!0){const{me:r,chatContainer:a,exists:c}=await s(e);if(c)return new rr.A(a.value+cs);if(t){const t=await o(a,r);return await u(e,t),await n(a,r,e),await i(t,r),t}return null},sendInvite:u,mintNew:a}}function ls(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 ds extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class fs extends ds{}class ps extends ds{}class gs extends ds{}class ys extends ds{}class vs extends ds{}class ms extends ds{status;constructor(e,t){super(t),this.status=e}}function ws(e,t,n){const i=ts;async function s(t){await o(t);const s=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/Settings/";return qi(t+"Preferences.ttl")}(t);let a;try{a=await n.followOrCreateLink(t,i.space("preferencesFile"),s,t.doc())}catch(e){if(r(`User ${t} has no pointer in profile to preferences file.`),e instanceof ys)throw e;if(e instanceof vs)throw e;if(e instanceof fs)throw e;if(e instanceof ps)throw e;if(e instanceof gs)throw e;if(e instanceof ms)throw e;throw e}try{await e.fetcher.load(a)}catch(e){const n=`Unable to load preference of user ${t}: ${e}`;if(r(n),401===e.response.status)throw new fs;if(403===e.response.status){if(us(a))throw new ps;throw new gs}throw new Error(n)}return a}async function o(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 a(t){return e.any(t,i.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=a(e);if(!t)throw new Error("User pod root not found!");return t},getMainInbox:async function(t){await e.fetcher.load(t);const r=e.any(t,i.ldp("inbox"),void 0,t.doc());if(!r)throw new Error("User main inbox not found!");return r},findStorage:a,loadPreferences:s,loadProfile:o,silencedLoadPreferences:async function(e){try{return await s(e)}catch(e){return}}}}function bs(e,t,n,i){const s=ts;async function o(t){if(!t)throw new Error("loadTypeIndexesFor: No user given");const o=await n.loadProfile(t),a=h(t);let u;try{u=await i.followOrCreateLink(t,s.solid("publicTypeIndex"),a,o)}catch(e){r(`User ${t} has no pointer in profile to publicTypeIndex file.`)}const c=u?[{label:"public",index:u,agent:t}]:[];let d,f;try{d=await n.silencedLoadPreferences(t)}catch(e){d=null}if(d){const n=l(d);let a;try{a=e.any(t,s.solid("privateTypeIndex"),void 0,o)||await i.followOrCreateLink(t,s.solid("privateTypeIndex"),n,d)}catch(e){r(`User ${t} has no pointer in preference file to privateTypeIndex file.`)}f=a?[{label:"private",index:a,agent:t}]:[]}else f=[];const p=c.concat(f);if(0===p.length)return p;const g=p.map(e=>e.index);try{await e.fetcher.load(g)}catch(e){r("Problems loading type index: ",e)}return p}async function a(t){let i;try{i=await n.silencedLoadPreferences(t)}catch(e){r(`User ${t} has no pointer in profile to preferences file.`)}if(i){const r=e.each(t,s.solid("community"),void 0,i).concat(e.each(t,s.solid("community"),void 0,t.doc()));let n=[];for(const e of r)n=n.concat(await o(e));return n}return[]}async function u(e){return(await o(e)).concat((await a(e)).flat())}async function c(e,t){const r=await u(t);let n=[];for(const t of r){const r=await d(t,e);n=n.concat(r)}return n}function h(e){return qi(e.doc().dir()?.uri+"publicTypeIndex.ttl")}function l(e){return qi(e.doc().dir()?.uri+"privateTypeIndex.ttl")}async function d(t,r){const n=t.index,i=[],o=e.statementsMatching(null,s.solid("instance"),null,n).concat(e.statementsMatching(null,s.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const a of o){const o=e.any(a,s.solid("forClass"),null,n);if(!r||o.sameTerm(r)){const r=e.each(a,s.solid("instance"),null,n);for(const e of r)i.push({instance:e,type:o,scope:t});const u=e.each(a,s.solid("instanceContainer"),null,n);for(const r of u)await e.fetcher.load(r),i.push({instance:qi(r.value),type:o,scope:t})}}return i}return{registerInTypeIndex:async function(t,r,n){const i=as(r),o=[Hi(i,s.rdf("type"),s.solid("TypeRegistration"),r),Hi(i,s.solid("forClass"),n,r),Hi(i,s.solid("instance"),t,r)];try{await e.updater.update([],o)}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,s.solid("instance"),t).filter(t=>e.holds(t,s.solid("forClass"),r))},loadTypeIndexesFor:o,loadCommunityTypeIndexes:a,loadAllTypeIndexes:u,getScopedAppInstances:c,getAppInstances:async function(e){const r=t.currentUser();if(!r)throw new Error("getAppInstances: Must be logged in to find apps.");return(await c(e,r)).map(e=>e.instance)},suggestPublicTypeIndex:h,suggestPrivateTypeIndex:l,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:d}}const _s=function(e,n){t("SolidLogic: Unique instance created. There should only be one of these.");const i=Mi();ji(i,{fetch:e.fetch}),i.updater=new Pi(i),i.features=[];const s=new os(n),o=ns(i),a=function(e){function t(t){return e.statementsMatching(t,qi("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(qi(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)}}}(i),u=function(e,n,i){async function s(t){let r;try{r=await e.fetcher.load(t)}catch(r){if(404!==r.response.status){if(401===r.response.status)throw new fs;if(403===r.response.status){if(us(t))throw new ps;throw new gs}const e="createIfNotExists doc load error NOT 404: "+t+": "+r;throw new ms(r.status,r.message+e)}try{await e.fetcher.webOperation("PUT",t,{data:"",contentType:"text/turtle"})}catch(e){throw new vs("createIfNotExists: PUT FAILED: "+t+": "+e)}await e.fetcher.load(t)}return r}return{recursiveDelete:async function r(s){try{if(i.isContainer(s)){const t=await n.findAclDocUrl(s);await e.fetcher._fetch(t,{method:"DELETE"});const o=await i.getContainerMembers(s);await Promise.all(o.map(e=>r(e)))}const t=s.value;return e.fetcher._fetch(t,{method:"DELETE"})}catch(e){t(`Please manually remove ${s.value} from your system.`,e)}},setSinglePeerAccess:async function(t){let r=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","",`<#alice> a acl:Authorization;\n acl:agent <${t.ownerWebId}>;`,` acl:accessTo <${t.target}>;`,` acl:default <${t.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");t.accessToModes&&(r+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:accessTo <${t.target}>;`,` acl:mode ${t.accessToModes}.`,""].join("\n")),t.defaultModes&&(r+=["<#bobDefault> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:default <${t.target}>;`,` acl:mode ${t.defaultModes}.`,""].join("\n"));const i=await n.findAclDocUrl(qi(t.target));return e.fetcher._fetch(i,{method:"PUT",body:r,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(t,r){await e.fetcher.webOperation("PUT",t.uri,{data:`# ${new Date} ${r}\n `,contentType:"text/turtle"})},followOrCreateLink:async function(t,n,i,o){await e.fetcher.load(o);const a=e.any(t,n,null,o);if(a)return a;if(!e.updater.editable(o)){const e=`followOrCreateLink: cannot edit ${o.value}`;throw r(e),new ys(e)}try{await e.updater.update([],[Hi(t,n,i,o)])}catch(e){throw r(`followOrCreateLink: Error making link in ${o} to ${i}: ${e}`),new vs(e)}try{await s(i)}catch(e){throw r(`followOrCreateLink: Error loading or saving new linked document: ${i}: ${e}`),e}return i},loadOrCreateIfNotExists:s}}(i,o,a),c=ws(i,s,u),h=hs(i,c),l=ls(i,c,u,a),d=bs(i,s,c,u);return t("SolidAuthnLogic initialized"),{store:i,authn:s,acl:o,inbox:l,chat:h,profile:c,typeIndex:d,load:function(e){return i.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((r,n)=>{i.updater.update(e,t,function(e,t,i){t?r():n(new Error(i))})})},clearStore:function(){i.statements.slice().forEach(i.remove.bind(i))}}}({fetch:async(e,t)=>{const r=t&&t.credentials&&"omit"==t.credentials;return Gt.info.webId&&!r?Gt.fetch(e,t):window.fetch(e,t)}},Gt);t("Unique quadstore initialized.");const Ss=[{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 Es(){const e=[...Ss],{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 xs=_s.authn,As=_s.authn.authSession,Fs=_s.store})(),u})());
40
+ const n=r(7526),i=r(251),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=u,t.IS=50;const o=2147483647;function a(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|g(e,t);let n=a(r);const i=n.write(e,t);i!==r&&(n=n.slice(0,i));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(X(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return d(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,ArrayBuffer)||e&&X(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(X(e,SharedArrayBuffer)||e&&X(e.buffer,SharedArrayBuffer)))return f(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const i=function(e){if(u.isBuffer(e)){const t=0|p(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||G(e.length)?a(0):d(e);if("Buffer"===e.type&&Array.isArray(e.data))return d(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function h(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return h(e),a(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),r=a(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function f(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(n,u.prototype),n}function p(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function g(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||X(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return J(e).length;default:if(i)return n?-1:W(e).length;t=(""+t).toLowerCase(),i=!0}}function y(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,r);case"utf8":case"utf-8":return F(this,t,r);case"ascii":return k(this,t,r);case"latin1":case"binary":return I(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function m(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),G(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:w(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):w(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,n,i){let s,o=1,a=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;o=2,a/=2,u/=2,r/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){let n=-1;for(s=r;s<a;s++)if(c(e,s)===c(t,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===u)return n*o}else-1!==n&&(s-=s-n),n=-1}else for(r+u>a&&(r=a-u),s=r;s>=0;s--){let r=!0;for(let n=0;n<u;n++)if(c(e,s+n)!==c(t,n)){r=!1;break}if(r)return s}return-1}function b(e,t,r,n){r=Number(r)||0;const i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;const s=t.length;let o;for(n>s/2&&(n=s/2),o=0;o<n;++o){const n=parseInt(t.substr(2*o,2),16);if(G(n))return o;e[r+o]=n}return o}function _(e,t,r,n){return z(W(t,e.length-r),e,r,n)}function S(e,t,r,n){return z(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function E(e,t,r,n){return z(J(t),e,r,n)}function x(e,t,r,n){return z(function(e,t){let r,n,i;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)r=e.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}(t,e.length-r),e,r,n)}function A(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function F(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i<r;){const t=e[i];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=r){let r,n,a,u;switch(o){case 1:t<128&&(s=t);break;case 2:r=e[i+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(s=u));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:r=e[i+1],n=e[i+2],a=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&a,u>65535&&u<1114112&&(s=u))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=T));return r}(n)}u.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),u.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}}),u.poolSize=8192,u.from=function(e,t,r){return c(e,t,r)},Object.setPrototypeOf(u.prototype,Uint8Array.prototype),Object.setPrototypeOf(u,Uint8Array),u.alloc=function(e,t,r){return function(e,t,r){return h(e),e<=0?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)}(e,t,r)},u.allocUnsafe=function(e){return l(e)},u.allocUnsafeSlow=function(e){return l(e)},u.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==u.prototype},u.compare=function(e,t){if(X(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),X(t,Uint8Array)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(e)||!u.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,s=Math.min(r,n);i<s;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},u.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=u.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(X(t,Uint8Array))i+t.length>n.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},u.byteLength=g,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)v(this,t,t+1);return this},u.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)v(this,t,t+3),v(this,t+1,t+2);return this},u.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)v(this,t,t+7),v(this,t+1,t+6),v(this,t+2,t+5),v(this,t+3,t+4);return this},u.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?F(this,0,e):y.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){let e="";const r=t.IS;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},s&&(u.prototype[s]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,i){if(X(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(t>>>=0);const a=Math.min(s,o),c=this.slice(n,i),h=e.slice(t,r);for(let e=0;e<a;++e)if(c[e]!==h[e]){s=c[e],o=h[e];break}return s<o?-1:o<s?1:0},u.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},u.prototype.indexOf=function(e,t,r){return m(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return m(this,e,t,r,!1)},u.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let s=!1;for(;;)switch(n){case"hex":return b(this,e,t,r);case"utf8":case"utf-8":return _(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function k(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function I(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function C(e,t,r){const n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=t;n<r;++n)i+=Y[e[n]];return i}function R(e,t,r){const n=e.slice(t,r);let i="";for(let e=0;e<n.length-1;e+=2)i+=String.fromCharCode(n[e]+256*n[e+1]);return i}function P(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,r,n,i,s){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function U(e,t,r,n,i){q(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,r}function O(e,t,r,n,i){q(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r+7]=s,s>>=8,e[r+6]=s,s>>=8,e[r+5]=s,s>>=8,e[r+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=o,o>>=8,e[r+2]=o,o>>=8,e[r+1]=o,o>>=8,e[r]=o,r+8}function L(e,t,r,n,i,s){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function D(e,t,r,n,s){return t=+t,r>>>=0,s||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,s){return t=+t,r>>>=0,s||L(e,0,r,8),i.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,u.prototype),n},u.prototype.readUintLE=u.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return n},u.prototype.readUintBE=u.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=Q(function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),u.prototype.readBigUInt64BE=Q(function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let n=t,i=1,s=this[e+--n];for(;n>0&&(i*=256);)s+=this[e+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},u.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=Q(function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),u.prototype.readBigInt64BE=Q(function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)}),u.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){N(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=1,s=0;for(this[t]=255&e;++s<r&&(i*=256);)this[t+s]=e/i&255;return t+r},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){N(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=r-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=Q(function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=Q(function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,e,t,r,n-1,-n)}let i=0,s=1,o=0;for(this[t]=255&e;++i<r&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s|0)-o&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,e,t,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s|0)-o&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=Q(function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=Q(function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeFloatLE=function(e,t,r){return D(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return D(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);const i=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i},u.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{const s=u.isBuffer(e)?e:u.from(e,n),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=s[i%o]}return this};const M={};function B(e,t,r){M[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function H(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,i,s){if(e>r||e<t){const n="bigint"==typeof t?"n":"";let i;throw i=s>3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new M.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,i,s)}function K(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new M.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}B("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),B("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),B("ERR_OUT_OF_RANGE",function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n},RangeError);const $=/[^+/0-9A-Za-z-_]/g;function W(e,t){let r;t=t||1/0;const n=e.length;let i=null;const s=[];for(let o=0;o<n;++o){if(r=e.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function J(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace($,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(e,t,r,n){let i;for(i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function G(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function Q(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},8392:t=>{"use strict";t.exports=e},8936:(e,t,r)=>{"use strict";r.d(t,{A:()=>i});var n=r(4705);class i{constructor(e){(0,n.A)(this,"termType",void 0),(0,n.A)(this,"classOrder",void 0),(0,n.A)(this,"value",void 0),this.value=e}substitute(e){return this}compareTerm(e){return this.classOrder<e.classOrder?-1:this.classOrder>e.classOrder?1:this.value<e.value?-1:this.value>e.value?1:0}equals(e){return!!e&&(this.termType===e.termType&&this.value===e.value)}hashString(){return this.toCanonical()}sameTerm(e){return this.equals(e)}toCanonical(){return this.toNT()}toNT(){return this.toString()}toNQ(){return this.toNT()}toString(){throw new Error("Node.toString() is abstract - see the subclasses instead")}}(0,n.A)(i,"fromValue",void 0),(0,n.A)(i,"toJS",void 0)},9403:(e,t,r)=>{"use strict";r.d(t,{$Q:()=>i,BR:()=>g,Fn:()=>b,H:()=>E,JG:()=>m,K9:()=>w,Kk:()=>n,MG:()=>p,P2:()=>o,QW:()=>s,S:()=>c,_0:()=>y,bD:()=>h,bM:()=>v,hu:()=>S,i2:()=>d,ic:()=>a,lc:()=>l,ny:()=>f,r0:()=>u,sT:()=>_});const n="NamedNode",i="BlankNode",s="Literal",o="Variable",a="DefaultGraph",u="Collection",c="Empty",h="Graph",l="text/html",d="application/ld+json",f="text/n3",p="application/n3",g="application/nquads",y="application/n-quads",v="application/n-triples",m="application/rdf+xml",w="application/sparql-update",b="application/sparql-update-single-match",_="text/turtle",S="application/x-turtle",E="application/xhtml+xml"}},o={};function a(e){var t=o[e];if(void 0!==t)return t.exports;var r=o[e]={id:e,loaded:!1,exports:{}};return s[e].call(r.exports,r,r.exports,a),r.loaded=!0,r.exports}a.m=s,a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,a.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var i=Object.create(null);a.r(i);var s={};t=t||[null,r({}),r([]),r(r)];for(var o=2&n&&e;("object"==typeof o||"function"==typeof o)&&!~t.indexOf(o);o=r(o))Object.getOwnPropertyNames(o).forEach(t=>s[t]=()=>e[t]);return s.default=()=>e,a.d(i,s),i},a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.f={},a.e=e=>Promise.all(Object.keys(a.f).reduce((t,r)=>(a.f[r](e,t),t),[])),a.u=e=>e+".solid-logic.min.js",a.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),a.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},i="SolidLogic:",a.l=(e,t,r,s)=>{if(n[e])n[e].push(t);else{var o,u;if(void 0!==r)for(var c=document.getElementsByTagName("script"),h=0;h<c.length;h++){var l=c[h];if(l.getAttribute("src")==e||l.getAttribute("data-webpack")==i+r){o=l;break}}o||(u=!0,(o=document.createElement("script")).charset="utf-8",o.timeout=120,a.nc&&o.setAttribute("nonce",a.nc),o.setAttribute("data-webpack",i+r),o.src=e),n[e]=[t];var d=(t,r)=>{o.onerror=o.onload=null,clearTimeout(f);var i=n[e];if(delete n[e],o.parentNode&&o.parentNode.removeChild(o),i&&i.forEach(e=>e(r)),t)return t(r)},f=setTimeout(d.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=d.bind(null,o.onerror),o.onload=d.bind(null,o.onload),u&&document.head.appendChild(o)}},a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;a.g.importScripts&&(e=a.g.location+"");var t=a.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var n=r.length-1;n>-1&&(!e||!/^http(s?):/.test(e));)e=r[n--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),a.p=e})(),(()=>{var e={792:0};a.f.j=(t,r)=>{var n=a.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var i=new Promise((r,i)=>n=e[t]=[r,i]);r.push(n[2]=i);var s=a.p+a.u(t),o=new Error;a.l(s,r=>{if(a.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var i=r&&("load"===r.type?"missing":r.type),s=r&&r.target&&r.target.src;o.message="Loading chunk "+t+" failed.\n("+i+": "+s+")",o.name="ChunkLoadError",o.type=i,o.request=s,n[1](o)}},"chunk-"+t,t)}};var t=(t,r)=>{var n,i,[s,o,u]=r,c=0;if(s.some(t=>0!==e[t])){for(n in o)a.o(o,n)&&(a.m[n]=o[n]);if(u)u(a)}for(t&&t(r);c<s.length;c++)i=s[c],a.o(e,i)&&e[i]&&e[i][0](),e[i]=0},r=this.webpackChunkSolidLogic=this.webpackChunkSolidLogic||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})();var u={};return(()=>{"use strict";a.r(u),a.d(u,{ACL_LINK:()=>rs,CrossOriginForbiddenError:()=>ps,FetchError:()=>ws,NotEditableError:()=>vs,NotFoundError:()=>ys,SameOriginForbiddenError:()=>gs,UnauthorizedError:()=>fs,WebOperationError:()=>ms,appContext:()=>is,authSession:()=>Fs,authn:()=>As,createTypeIndexLogic:()=>_s,getSuggestedIssuers:()=>xs,offlineTestID:()=>ss,solidLogicSingleton:()=>Ss,store:()=>Ts});var e={};function t(...e){console.log(...e)}function r(...e){console.warn(...e)}a.r(e),a.d(e,{BlankNode:()=>tr,Collection:()=>ar,ConnectedStore:()=>Zi,DataFactory:()=>Ui,Empty:()=>ur,Fetcher:()=>ki,Formula:()=>Ur,IndexedFormula:()=>Kr,Literal:()=>sr,LiveStore:()=>es,N3Parser:()=>fn,NamedNode:()=>rr.A,Namespace:()=>_r,NextId:()=>Qi,Node:()=>Or,Query:()=>Dr,RDFParser:()=>ui,RDFaProcessor:()=>oi,SPARQLToQuery:()=>Ri,Serializer:()=>Tr,Statement:()=>fr,Store:()=>Kr,UpdateManager:()=>Pi,UpdatesSocket:()=>Oi,UpdatesVia:()=>Li,Util:()=>Sr,Variable:()=>gr,blankNode:()=>Vi,defaultGraph:()=>$i,fetcher:()=>ji,fromNT:()=>Gi,graph:()=>Mi,isBlankNode:()=>nr.jt,isCollection:()=>nr.P3,isGraph:()=>nr.RN,isLiteral:()=>nr.c$,isNamedNode:()=>nr.Y2,isPredicate:()=>nr.YC,isQuad:()=>nr.aF,isRDFObject:()=>nr.GE,isRDFlibObject:()=>nr.DJ,isRDFlibPredicate:()=>nr.fY,isRDFlibSubject:()=>nr.CZ,isStatement:()=>nr.SH,isStore:()=>nr.ok,isSubject:()=>nr.hr,isTerm:()=>nr.D0,isVariable:()=>nr.DZ,jsonParser:()=>Ii,lit:()=>Bi,literal:()=>Wi,log:()=>br.A,namedNode:()=>qi,parse:()=>hi,quad:()=>Ji,queryToSPARQL:()=>Ci,serialize:()=>Ir,sparqlUpdateParser:()=>ci,st:()=>Hi,sym:()=>qi,term:()=>Yi,termValue:()=>fi.E,triple:()=>zi,uri:()=>pr,variable:()=>Ki});const n=new TextEncoder,i=new TextDecoder;function s(...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 o=e=>(e=>{let t=e;"string"==typeof t&&(t=n.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,"_"),c=e=>{let t=e;t instanceof Uint8Array&&(t=i.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 h extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}h.code="ERR_JOSE_GENERIC";class l extends h{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}l.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class d extends h{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}}d.code="ERR_JWT_EXPIRED";class f extends h{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}f.code="ERR_JOSE_ALG_NOT_ALLOWED";class p extends h{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}p.code="ERR_JOSE_NOT_SUPPORTED";(class extends h{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends h{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class g extends h{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}g.code="ERR_JWS_INVALID";class y extends h{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}y.code="ERR_JWT_INVALID";(class extends h{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";class v extends h{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}v.code="ERR_JWKS_INVALID";class m extends h{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}m.code="ERR_JWKS_NO_MATCHING_KEY";class w extends h{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,w.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class b extends h{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}b.code="ERR_JWKS_TIMEOUT";class _ extends h{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function S(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new p(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}_.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const E=crypto,x=e=>e instanceof CryptoKey,A=(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 F(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function T(e,t){return e.name===t}function k(e){return parseInt(e.name.slice(4),10)}function I(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 C(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!T(e.algorithm,"HMAC"))throw F("HMAC");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw F(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!T(e.algorithm,"RSASSA-PKCS1-v1_5"))throw F("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw F(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!T(e.algorithm,"RSA-PSS"))throw F("RSA-PSS");const r=parseInt(t.slice(2),10);if(k(e.algorithm.hash)!==r)throw F(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw F("Ed25519 or Ed448");break;case"Ed25519":if(!T(e.algorithm,"Ed25519"))throw F("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!T(e.algorithm,"ECDSA"))throw F("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 F(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}I(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}const P=(e,...t)=>R("Key must be ",e,...t);function N(e,t,...r){return R(`Key for the ${e} algorithm must be `,t,...r)}const U=e=>!!x(e)||"KeyObject"===e?.[Symbol.toStringTag],O=["CryptoKey"];function L(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function D(e){return L(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 p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new p('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,E.subtle.importKey("jwk",i,...n)},M=e=>c(e);let B,H;const q=e=>"KeyObject"===e?.[Symbol.toStringTag],K=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},V=(e,t)=>{if(q(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?M(r.k):(H||(H=new WeakMap),K(H,e,r,t))}if(D(e)){if(e.k)return c(e.k);H||(H=new WeakMap);return K(H,e,e,t,!0)}return e},$=(e,t)=>{if(q(e)){let r=e.export({format:"jwk"});return r.k?M(r.k):(B||(B=new WeakMap),K(B,e,r,t))}if(D(e)){if(e.k)return c(e.k);B||(B=new WeakMap);return K(B,e,e,t,!0)}return e};async function W(e,t,r){if("sign"===r&&(t=await $(t,e)),"verify"===r&&(t=await V(t,e)),x(t))return C(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(P(t,...O));return E.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(P(t,...O,"Uint8Array","JSON Web Key"))}const J=async(e,t,r,n)=>{const i=await W(e,t,"verify");A(e,i);const s=S(e,i.algorithm);try{return await E.subtle.verify(s,i,r,n)}catch{return!1}},z=(...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},X=e=>e?.[Symbol.toStringTag],G=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Y=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&D(t)){if(function(e){return D(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&G(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!U(t))throw new TypeError(N(e,t,...O,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${X(t)} instances for symmetric algorithms must be of type "secret"`)}};function Q(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&&D(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!U(t))throw new TypeError(N(e,t,...O,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${X(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}Q.bind(void 0,!1);const Z=Q.bind(void 0,!0);const ee=function(e,t,r,n,i){if(void 0!==i.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!s.has(t))throw new p(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)},te=(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 re(e,t){if(!L(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return c(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new p('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return j({...e,alg:t});default:throw new p('Unsupported "kty" (Key Type) Parameter value')}}async function ne(e,t,r){if(e instanceof Uint8Array&&(e=i.decode(e)),"string"!=typeof e)throw new g("Compact JWS must be a string or Uint8Array");const{0:o,1:a,2:u,length:h}=e.split(".");if(3!==h)throw new g("Invalid Compact JWS");const l=await async function(e,t,r){if(!L(e))throw new g("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new g('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new g("JWS Protected Header incorrect type");if(void 0===e.payload)throw new g("JWS Payload missing");if("string"!=typeof e.signature)throw new g("JWS Signature missing or incorrect type");if(void 0!==e.header&&!L(e.header))throw new g("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=c(e.protected);o=JSON.parse(i.decode(t))}catch{throw new g("JWS Protected Header is invalid")}if(!z(o,e.header))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const a={...o,...e.header};let u=!0;if(ee(g,new Map([["b64",!0]]),r?.crit,o,a).has("b64")&&(u=o.b64,"boolean"!=typeof u))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:h}=a;if("string"!=typeof h||!h)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');const l=r&&te("algorithms",r.algorithms);if(l&&!l.has(h))throw new f('"alg" (Algorithm) Header Parameter value not allowed');if(u){if("string"!=typeof e.payload)throw new g("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new g("JWS Payload must be a string or an Uint8Array instance");let d=!1;"function"==typeof t?(t=await t(o,e),d=!0,Z(h,t,"verify"),D(t)&&(t=await re(t,h))):Z(h,t,"verify");const p=s(n.encode(e.protected??""),n.encode("."),"string"==typeof e.payload?n.encode(e.payload):e.payload);let y,v;try{y=c(e.signature)}catch{throw new g("Failed to base64url decode the signature")}if(!await J(h,t,y,p))throw new _;if(u)try{v=c(e.payload)}catch{throw new g("Failed to base64url decode the payload")}else v="string"==typeof e.payload?n.encode(e.payload):e.payload;const m={payload:v};return void 0!==e.protected&&(m.protectedHeader=o),void 0!==e.header&&(m.unprotectedHeader=e.header),d?{...m,key:t}:m}({payload:a,protected:o,signature:u},t,r),d={payload:l.payload,protectedHeader:l.protectedHeader};return"function"==typeof t?{...d,key:l.key}:d}const ie=e=>Math.floor(e.getTime()/1e3),se=86400,oe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ae=e=>{const t=oe.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*se);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},ue=e=>e.toLowerCase().replace(/^application\//,""),ce=(e,t,r={})=>{let n;try{n=JSON.parse(i.decode(t))}catch{}if(!L(n))throw new y("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&("string"!=typeof e.typ||ue(e.typ)!==ue(s)))throw new l('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:o=[],issuer:a,subject:u,audience:c,maxTokenAge:h}=r,f=[...o];void 0!==h&&f.push("iat"),void 0!==c&&f.push("aud"),void 0!==u&&f.push("sub"),void 0!==a&&f.push("iss");for(const e of new Set(f.reverse()))if(!(e in n))throw new l(`missing required "${e}" claim`,n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new l('unexpected "iss" claim value',n,"iss","check_failed");if(u&&n.sub!==u)throw new l('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(p=n.aud,g="string"==typeof c?[c]:c,!("string"==typeof p?g.includes(p):Array.isArray(p)&&g.some(Set.prototype.has.bind(new Set(p))))))throw new l('unexpected "aud" claim value',n,"aud","check_failed");var p,g;let v;switch(typeof r.clockTolerance){case"string":v=ae(r.clockTolerance);break;case"number":v=r.clockTolerance;break;case"undefined":v=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:m}=r,w=ie(m||new Date);if((void 0!==n.iat||h)&&"number"!=typeof n.iat)throw new l('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new l('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>w+v)throw new l('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new l('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=w-v)throw new d('"exp" claim timestamp check failed',n,"exp","check_failed")}if(h){const e=w-n.iat;if(e-v>("number"==typeof h?h:ae(h)))throw new d('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-v)throw new l('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};const he=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 b;throw e});if(void 0!==i&&clearTimeout(i),200!==o.status)throw new h("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new h("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function le(e){return L(e)}function de(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class fe{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(le)}(e))throw new v("JSON Web Key Set malformed");this._jwks=de(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},i=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new p('Unsupported "alg" value for a JSON Web Key Set')}}(r),s=this._jwks.keys.filter(e=>{let t=i===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:o,length:a}=s;if(0===a)throw new m;if(1!==a){const e=new w,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of s)try{yield await pe(t,e,r)}catch{}},e}return pe(this._cached,o,r)}}async function pe(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await re({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new v("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function ge(e){const t=new fe(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>de(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 ve=Symbol();class me{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?.[ve]&&(this._cache=t?.[ve],r=t?.[ve],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&L(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,L)&&(this._jwksTimestamp=this._cache.uat,this._local=ge(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof m&&!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=he(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 we=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:o(e)};if(!x(e))throw new TypeError(P(e,...O,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:i,...s}=await E.subtle.exportKey("jwk",e);return s};async function be(e){return we(e)}const _e=async(e,t,r)=>{const n=await W(e,t,"sign");A(e,n);const i=await E.subtle.sign(S(e,n.algorithm),n,r);return new Uint8Array(i)};class Se{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new g("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!z(this._protectedHeader,this._unprotectedHeader))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let a=!0;if(ee(g,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(a=this._protectedHeader.b64,"boolean"!=typeof a))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:u}=r;if("string"!=typeof u||!u)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');Z(u,e,"sign");let c,h=this._payload;a&&(h=n.encode(o(h))),c=this._protectedHeader?n.encode(o(JSON.stringify(this._protectedHeader))):n.encode("");const l=s(c,n.encode("."),h),d=await _e(u,e,l),f={signature:o(d),payload:""};return a&&(f.payload=i.decode(h)),this._unprotectedHeader&&(f.header=this._unprotectedHeader),this._protectedHeader&&(f.protected=i.decode(c)),f}}class Ee{constructor(e){this._flattened=new Se(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function xe(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Ae{constructor(e={}){if(!L(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:xe("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:xe("setNotBefore",ie(e))}:this._payload={...this._payload,nbf:ie(new Date)+ae(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:xe("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:xe("setExpirationTime",ie(e))}:this._payload={...this._payload,exp:ie(new Date)+ae(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:ie(new Date)}:e instanceof Date?this._payload={...this._payload,iat:xe("setIssuedAt",ie(e))}:this._payload="string"==typeof e?{...this._payload,iat:xe("setIssuedAt",ie(new Date)+ae(e))}:{...this._payload,iat:xe("setIssuedAt",e)},this}}class Fe extends Ae{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new Ee(n.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 Te(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new p("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function ke(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Te(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Te(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Te(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e=t?.crv??"Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new p("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new p("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new p('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return E.subtle.generateKey(r,t?.extractable??!1,n)}(e,t)}const Ie={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let Ce;const Re=new Uint8Array(16);const Pe=[];for(let e=0;e<256;++e)Pe.push((e+256).toString(16).slice(1));function Ne(e,t=0){return(Pe[e[t+0]]+Pe[e[t+1]]+Pe[e[t+2]]+Pe[e[t+3]]+"-"+Pe[e[t+4]]+Pe[e[t+5]]+"-"+Pe[e[t+6]]+Pe[e[t+7]]+"-"+Pe[e[t+8]]+Pe[e[t+9]]+"-"+Pe[e[t+10]]+Pe[e[t+11]]+Pe[e[t+12]]+Pe[e[t+13]]+Pe[e[t+14]]+Pe[e[t+15]]).toLowerCase()}const Ue=function(e,t,r){if(Ie.randomUUID&&!t&&!e)return Ie.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!Ce){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ce=crypto.getRandomValues.bind(crypto)}return Ce(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 Ne(n)},Oe="solidClientAuthn:",Le=["ES256","RS256"],De="error",je="login",Me="logout",Be="newRefreshToken",He="sessionExpired",qe="sessionExtended",Ke="sessionRestore",Ve="timeoutSet",$e=["openid","offline_access","webid"];class We{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 Je(e,t,r,n){let i,s;try{const{payload:s}=await async function(e,t,r){const n=await ne(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:ce(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}(e,function(e,t){const r=new me(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 ze(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 Xe(e){const t=new URL(e);return t.searchParams.delete("state"),t.searchParams.delete("code"),t.searchParams.delete("error"),t.searchParams.delete("error_description"),t.searchParams.delete("iss"),t}class Ge{storageUtility;redirector;constructor(e,t){this.storageUtility=e,this.redirector=t,this.storageUtility=e,this.redirector=t}parametersGuard=e=>void 0!==e.issuerConfiguration.grantTypesSupported&&e.issuerConfiguration.grantTypesSupported.indexOf("authorization_code")>-1&&void 0!==e.redirectUrl;async canHandle(e){return this.parametersGuard(e)}async setupRedirectHandler({oidcLoginOptions:e,state:t,codeVerifier:r,targetUrl:n}){if(!this.parametersGuard(e))throw new Error("The authorization code grant requires a redirectUrl.");var i,s;await Promise.all([this.storageUtility.setForUser(t,{sessionId:e.sessionId}),this.storageUtility.setForUser(e.sessionId,{codeVerifier:r,issuer:e.issuer.toString(),redirectUrl:e.redirectUrl,dpop:Boolean(e.dpop).toString(),keepAlive:(i=e.keepAlive,s=!0,"boolean"==typeof i?Boolean(i):Boolean(s)).toString()})]),this.redirector.redirect(n,{handleRedirect:e.handleRedirect})}}class Ye{sessionInfoManager;constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class Qe{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 Ze{handlers;constructor(e,t){this.handlers=[new Ye(e),new Qe(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 et(){return{isLoggedIn:!1,sessionId:Ue(),fetch:(...e)=>fetch(...e)}}async function tt(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}class rt{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 tt(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 nt({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 it(e){try{return new URL(e),!0}catch{return!1}}async function st(e,t,r,n){let i;if(function(e,t){return t.scopesSupported.includes("webid")&&void 0!==e.clientId&&it(e.clientId)}(e,t))i={clientId:e.clientId,clientName:e.clientName,clientType:"solid-oidc"};else{if(!function(e){return void 0!==e.clientId&&!it(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 ot=(e,t)=>fetch(e,t);class at{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=ot;logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===t?.logoutType?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=ot,delete this.boundLogout};getSessionInfo=async e=>this.sessionInfoManager.get(e);getAllSessionInfo=async()=>this.sessionInfoManager.getAll()}async function ut(e,t,r){try{const[n,i,s,o,a]=await Promise.all([t.getForUser(e,"issuer",{errorIfNull:!0}),t.getForUser(e,"codeVerifier"),t.getForUser(e,"redirectUrl"),t.getForUser(e,"dpop",{errorIfNull:!0}),t.getForUser(e,"keepAlive")]);await t.deleteForUser(e,"codeVerifier");return{codeVerifier:i,redirectUrl:s,issuerConfig:await r.fetchConfig(n),dpop:"true"===o,keepAlive:"string"!=typeof a||"true"===a}}catch(t){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${e}]: ${t}`)}}class ct{secureStorage;insecureStorage;constructor(e,t){this.secureStorage=e,this.insecureStorage=t,this.secureStorage=e,this.insecureStorage=t}getKey(e){return`solidClientAuthenticationUser:${e}`}async getUserData(e,t){const r=await(t?this.secureStorage:this.insecureStorage).get(this.getKey(e));if(void 0===r)return{};try{return JSON.parse(r)}catch(n){throw new Error(`Data for user [${e}] in [${t?"secure":"unsecure"}] storage is corrupted - expected valid JSON, but got: ${r}`)}}async setUserData(e,t,r){await(r?this.secureStorage:this.insecureStorage).set(this.getKey(e),JSON.stringify(t))}async get(e,t){const r=await(t?.secure?this.secureStorage:this.insecureStorage).get(e);if(void 0===r&&t?.errorIfNull)throw new Error(`[${e}] is not stored`);return r}async set(e,t,r){return(r?.secure?this.secureStorage:this.insecureStorage).set(e,t)}async delete(e,t){return(t?.secure?this.secureStorage:this.insecureStorage).delete(e)}async getForUser(e,t,r){const n=await this.getUserData(e,r?.secure);let i;if(n&&n[t]||(i=void 0),i=n[t],void 0===i&&r?.errorIfNull)throw new Error(`Field [${t}] for user [${e}] is not stored`);return i||void 0}async setForUser(e,t,r){let n;try{n=await this.getUserData(e,r?.secure)}catch{n={}}await this.setUserData(e,{...n,...t},r?.secure)}async deleteForUser(e,t,r){const n=await this.getUserData(e,r?.secure);delete n[t],await this.setUserData(e,n,r?.secure)}async deleteAllUserData(e,t){await(t?.secure?this.secureStorage:this.insecureStorage).delete(this.getKey(e))}}class ht{map={};async get(e){return this.map[e]||void 0}async set(e,t){this.map[e]=t}async delete(e){delete this.map[e]}}class lt extends Error{constructor(e){super(e)}}Error;class dt extends Error{missingFields;constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class ft extends Error{error;errorDescription;constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function pt(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function gt(e,t,r){return new Fe({htu:pt(e),htm:t.toUpperCase(),jti:Ue()}).setProtectedHeader({alg:Le[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 gt(e,n?.method??"get",r)),{...n,headers:i}}(e,t,r,n);const i=new Headers(n?.headers);return i.set("Authorization",`Bearer ${t}`),{...n,headers:i}}async function vt(e,t,r,n,i=fetch){return i(t,await yt(t.toString(),e,n,r))}const mt=e=>void 0!==e?e-5>0?e-5:e:600;function wt(e,t){let r,n=e;const i=t?.refreshOptions;if(void 0!==i){const e=async()=>{try{const{accessToken:s,refreshToken:o,expiresIn:a}=await async function(e,t,r){const n=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return r?.emit(qe,n.expiresIn??600),{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn}}(i,t.dpopKey,t.eventEmitter);n=s,void 0!==o&&(i.refreshToken=o),clearTimeout(r),r=setTimeout(e,1e3*mt(a)),t.eventEmitter?.emit(Ve,r)}catch(e){e instanceof ft&&(t?.eventEmitter?.emit(De,e.error,e.errorDescription),t?.eventEmitter?.emit(He)),e instanceof dt&&e.missingFields.includes("access_token")&&t?.eventEmitter?.emit(He)}};r=setTimeout(e,1e3*mt(t.expiresIn)),t.eventEmitter?.emit(Ve,r)}else if(void 0!==t&&void 0!==t.eventEmitter){const e=setTimeout(()=>{t.eventEmitter.emit(He)},1e3*mt(t.expiresIn));t.eventEmitter.emit(Ve,e)}return async(e,r)=>{let i=await vt(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 vt(n,i.url,r,t.dpopKey,t.fetch)),i}}var bt=a(7007),_t=a(6516);function St(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 Et(e,t){if(!t.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(t.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const r=(n=t.idTokenSigningAlgValuesSupported,Le.find(e=>n.includes(e))??null);var n;const i={client_name:e.clientName,application_type:"web",redirect_uris:[e.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:r,grant_types:["authorization_code","refresh_token"]},s=await fetch(t.registrationEndpoint.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(s.ok){const t=await s.json();return St(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 xt(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function At(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new ft(`Token endpoint returned error [${e.error}]${xt(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,xt(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 dt(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new dt(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new dt(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new dt(["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 Ft(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 ke(Le[0]),r={privateKey:e,publicKey:await be(t)};return[r.publicKey.alg]=Le,r}(),i.DPoP=await gt(e.tokenEndpoint,"POST",s)),t.clientSecret&&(i.Authorization=`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`);const o={grant_type:r.grantType,redirect_uri:r.redirectUrl,code:r.code,code_verifier:r.codeVerifier,client_id:t.clientId},a={method:"POST",headers:i,body:new URLSearchParams(o).toString()},u=await fetch(e.tokenEndpoint,a),c=At(await u.json(),n),{webId:h,clientId:l}=await Je(c.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:(d=c,void 0!==d.refresh_token&&"string"==typeof d.refresh_token?c.refresh_token:void 0),webId:h,clientId:l,dpopKey:s,expiresIn:c.expires_in};var d}async function Tt(e,t,r,n){if(void 0===r.clientId)throw new Error("No client ID available when trying to refresh the access token.");const i={grant_type:"refresh_token",refresh_token:e};let s={};void 0!==n&&(s={DPoP:await gt(t.tokenEndpoint,"POST",n)});let o={};void 0!==r.clientSecret?o={Authorization:`Basic ${btoa(`${r.clientId}:${r.clientSecret}`)}`}:(e=>{try{return new URL(e),!0}catch{return!1}})(r.clientId)&&(i.client_id=r.clientId);const a=await fetch(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(i).toString(),headers:{...s,...o,"Content-Type":"application/x-www-form-urlencoded"}});let u;try{u=await a.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const c=At(u,void 0!==n),{webId:h}=await Je(c.id_token,t.jwksUri,t.issuer,r.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:"string"==typeof c.refresh_token?c.refresh_token:void 0,webId:h,dpopKey:n,expiresIn:c.expires_in}}class kt extends ct{constructor(e,t){super(e,t)}}class It extends at{login=async(e,t)=>{"none"!==e.prompt&&await this.sessionInfoManager.clear(e.sessionId);const r=e.redirectUrl??function(e){const t=Xe(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}(window.location.href);if(!ze(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?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(De,"redirect",r)}};async cleanUrlAfterRedirect(e){const t=Xe(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(e=>{setTimeout(()=>e(),1)})}}function Ct(e){return"string"==typeof e.oidcIssuer}function Rt(e){return"string"==typeof e.redirectUrl}class Pt{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 Ct(e)&&Rt(e)}async handle(e){if(!Ct(e))throw new lt(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!Rt(e))throw new lt(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await st(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([...$e,...i.filter(e=>"string"==typeof e&&!e.includes(" "))])):$e)};var i;return this.oidcHandler.handle(n)}}class Nt extends Ge{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},r=new _t.OidcClient(t);try{const t=await r.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 Ut={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 Ot{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=>{Ut[r]&&(t[Ut[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await n.json())}catch(t){throw new lt(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(Ot.getLocalStorageKey(e),JSON.stringify(t)),t}}async function Lt(e,t){await tt(e,t),await async function(){const e=new _t.OidcClient({response_mode:"query"});await e.clearStaleState(new _t.WebStorageStateStore({}));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 Dt extends rt{async get(e){const[t,r,n,i,s,o,a,u]=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})]);if("string"!=typeof s||ze(s)){if(void 0!==u&&("string"!=typeof(c=u)||!["DPoP","Bearer"].includes(c)))throw new Error(`Tokens of type [${u}] are not supported.`);var c;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:u??"DPoP"}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return Lt(e,this.storageUtility)}}class jt{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 et()}}class Mt{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:u}=await ut(i,this.storageUtility,this.issuerConfigFetcher),c=r.searchParams.get("iss");if("string"==typeof c&&c!==s.issuer)throw new Error(`The value of the iss parameter (${c}) 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 h=await this.clientRegistrar.getClient({sessionId:i},s),l=Date.now(),d=await Ft(s,h,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:o,redirectUrl:a},u);let f;window.localStorage.removeItem(`oidc.${n}`),void 0!==d.refreshToken&&(f={sessionId:i,refreshToken:d.refreshToken,tokenRefresher:this.tokerRefresher});const p=wt(d.accessToken,{dpopKey:d.dpopKey,refreshOptions:f,eventEmitter:t,expiresIn:d.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 be(a.privateKey))},{secure:o})}(this.storageUtility,i,d.webId,d.clientId,"true",void 0,!0);const g=await this.sessionInfoManager.get(i);if(!g)throw new Error(`Could not retrieve session: [${i}].`);return Object.assign(g,{fetch:p,getLogoutUrl:nt({idTokenHint:d.idToken,endSessionEndpoint:s.endSessionEndpoint}),expirationDate:"number"==typeof d.expiresIn?l+1e3*d.expiresIn:void 0})}}class Bt extends We{constructor(e){super(e)}}class Ht{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 qt{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class Kt{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,u=void 0!==n&&0!==a&&Math.floor(Date.now()/1e3)>a;if(r&&("string"==typeof(c=o)&&["dynamic","static","solid-oidc"].includes(c))&&!u)return void 0!==n?{clientId:r,clientSecret:n,clientName:s,clientType:"dynamic",expiresAt:a}:{clientId:r,clientName:s,clientType:o};var c;try{const r=await Et(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 Vt{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(De,n,i)}return et()}}class $t{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 ut(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 Tt(t,i.issuerConfig,s,r);return void 0!==o.refreshToken&&n?.emit(Be,o.refreshToken),o}}function Wt(e){const t=new ht,r=e.secureStorage||t,n=e.insecureStorage||new Ht,i=new kt(r,n),s=new Ot(i),o=new Kt(i),a=new Dt(i),u=new $t(i,s,o),c=new qt,h=new Pt(i,new Nt(i,c),s,o),l=new Bt([new Vt,new Mt(i,a,s,o,u),new jt]);return new It(h,l,new Ze(a,c),a,s)}const Jt=`${Oe}currentSession`,zt=`${Oe}currentUrl`;class Xt{info;events;clientAuthentication;tokenRequestInProgress=!1;constructor(e={},t=void 0){this.events=new bt,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=Wt({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=Wt({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??Ue(),isLoggedIn:!1},this.events.on(je,()=>window.localStorage.setItem(Jt,this.info.sessionId)),this.events.on(He,()=>this.internalLogout(!1)),this.events.on(De,()=>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(Jt),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(Me)};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(zt);null===e?this.events.emit(je):(window.localStorage.removeItem(zt),this.events.emit(Ke,e))}else if(!0===t.restorePreviousSession){const e=window.localStorage.getItem(Jt);if(null!==e){if(await async function(e,t,r){const n=await t.validateCurrentSession(e);return null!==n&&(window.localStorage.setItem(zt,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(qe,e=>{this.info.expirationDate=Date.now()+1e3*e})}}const Gt=new Xt;var Yt=a(4705),Qt=a(1059),Zt=a(8936),er=a(9403);class tr extends Zt.A{static getId(e){if(e){if("string"!=typeof e)throw new Error("Bad id argument to new blank node: "+e);if(e.includes("#")){let t=e.split("#");return t[t.length-1]}return e}return"n"+tr.nextId++}constructor(e){super(tr.getId(e)),(0,Yt.A)(this,"termType",er.$Q),(0,Yt.A)(this,"classOrder",Qt.A.BlankNode),(0,Yt.A)(this,"isBlank",1),(0,Yt.A)(this,"isVar",1)}get id(){return this.value}set id(e){this.value=e}compareTerm(e){return this.classOrder<e.classOrder?-1:this.classOrder>e.classOrder?1:this.id<e.id?-1:this.id>e.id?1:0}copy(e){var t=new tr;return e.copyTo(this,t),t}toCanonical(){return tr.NTAnonymousNodePrefix+this.value}toString(){return tr.NTAnonymousNodePrefix+this.id}}(0,Yt.A)(tr,"nextId",0),(0,Yt.A)(tr,"NTAnonymousNodePrefix","_:");var rr=a(5108),nr=a(2915);const ir={boolean:new rr.A("http://www.w3.org/2001/XMLSchema#boolean"),dateTime:new rr.A("http://www.w3.org/2001/XMLSchema#dateTime"),decimal:new rr.A("http://www.w3.org/2001/XMLSchema#decimal"),double:new rr.A("http://www.w3.org/2001/XMLSchema#double"),integer:new rr.A("http://www.w3.org/2001/XMLSchema#integer"),langString:new rr.A("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),string:new rr.A("http://www.w3.org/2001/XMLSchema#string")};class sr extends Zt.A{constructor(e,t,r){super(e),(0,Yt.A)(this,"termType",er.QW),(0,Yt.A)(this,"classOrder",Qt.A.Literal),(0,Yt.A)(this,"datatype",ir.string),(0,Yt.A)(this,"isVar",0),(0,Yt.A)(this,"language",""),t?(this.language=t,this.datatype=ir.langString):this.datatype=r?rr.A.fromValue(r):ir.string}copy(){return new sr(this.value,this.lang,this.datatype)}equals(e){return!!e&&(this.termType===e.termType&&this.value===e.value&&this.language===e.language&&(!this.datatype&&!e.datatype||this.datatype&&this.datatype.equals(e.datatype)))}get lang(){return this.language}set lang(e){this.language=e||""}toNT(){return sr.toNT(this)}static toNT(e){if("number"==typeof e.value)return""+e.value;if("string"!=typeof e.value)throw new Error("Value of RDF literal is not string or number: "+e.value);var t=e.value;return t='"'+(t=(t=(t=(t=t.replace(/\\/g,"\\\\")).replace(/\"/g,'\\"')).replace(/\n/g,"\\n")).replace(/\r/g,"\\r"))+'"',e.language?t+="@"+e.language:e.datatype.equals(ir.string)||(t+="^^"+e.datatype.toCanonical()),t}toString(){return""+this.value}static fromBoolean(e){return new sr(e?"1":"0",null,ir.boolean)}static fromDate(e){if(!(e instanceof Date))throw new TypeError("Invalid argument to Literal.fromDate()");let t=function(e){return(""+(100+e)).slice(1,3)},r=e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"Z";return new sr(r,null,ir.dateTime)}static fromNumber(e){if("number"!=typeof e)throw new TypeError("Invalid argument to Literal.fromNumber()");let t;const r=e.toString();return t=r.indexOf("e")<0&&Math.abs(e)<=Number.MAX_SAFE_INTEGER?Number.isInteger(e)?ir.integer:ir.decimal:ir.double,new sr(r,null,t)}static fromValue(e){if((0,nr.c$)(e))return e;switch(typeof e){case"object":if(e instanceof Date)return sr.fromDate(e);case"boolean":return sr.fromBoolean(e);case"number":return sr.fromNumber(e);case"string":return new sr(e)}throw new Error("Can't make literal from "+e+" of type "+typeof e)}}function or(e){return null==e||(0,nr.D0)(e)?e:Array.isArray(e)?new ar(e):sr.fromValue(e)}class ar extends Zt.A{constructor(e){super((tr.nextId++).toString()),(0,Yt.A)(this,"termType",er.r0),(0,Yt.A)(this,"classOrder",Qt.A.Collection),(0,Yt.A)(this,"closed",!1),(0,Yt.A)(this,"compareTerm",tr.prototype.compareTerm),(0,Yt.A)(this,"elements",[]),(0,Yt.A)(this,"isVar",0),e&&e.length>0&&e.forEach(e=>{this.elements.push(or(e))})}get id(){return this.value}set id(e){this.value=e}append(e){return this.elements.push(e)}close(){return this.closed=!0,this.closed}shift(){return this.elements.shift()}substitute(e){const t=this.elements.map(t=>t.substitute(e));return new ar(t)}toNT(){return ar.toNT(this)}static toNT(e){return tr.NTAnonymousNodePrefix+e.id}toString(){return"("+this.elements.join(" ")+")"}unshift(e){return this.elements.unshift(e)}}(0,Yt.A)(ar,"termType",er.r0);class ur extends Zt.A{constructor(){super(""),(0,Yt.A)(this,"termType",er.S)}toString(){return"()"}}const cr="chrome:theSession";new rr.A(cr);class hr extends Zt.A{constructor(){super(""),(0,Yt.A)(this,"value",""),(0,Yt.A)(this,"termType",er.ic),(0,Yt.A)(this,"uri",cr)}toCanonical(){return this.value}toString(){return"DefaultGraph"}}function lr(e){return!!e&&e.termType===er.ic}const dr=new hr;class fr{constructor(e,t,r,n){(0,Yt.A)(this,"subject",void 0),(0,Yt.A)(this,"predicate",void 0),(0,Yt.A)(this,"object",void 0),(0,Yt.A)(this,"graph",void 0),this.subject=Zt.A.fromValue(e),this.predicate=Zt.A.fromValue(t),this.object=Zt.A.fromValue(r),this.graph=null==n?dr:Zt.A.fromValue(n)}get why(){return this.graph}set why(e){this.graph=e}equals(e){return e.subject.equals(this.subject)&&e.predicate.equals(this.predicate)&&e.object.equals(this.object)&&e.graph.equals(this.graph)}substitute(e){return new fr(this.subject.substitute(e),this.predicate.substitute(e),this.object.substitute(e),lr(this.graph)?this.graph:this.graph.substitute(e))}toCanonical(){let e=[this.subject.toCanonical(),this.predicate.toCanonical(),this.object.toCanonical()];return this.graph&&this.graph.termType!==er.ic&&e.push(this.graph.toCanonical()),e.join(" ")+" ."}toNT(){return[this.subject.toNT(),this.predicate.toNT(),this.object.toNT()].join(" ")+" ."}toNQ(){return[this.subject.toNT(),this.predicate.toNT(),this.object.toNT(),lr(this.graph)?"":this.graph.toNT()].join(" ")+" ."}toString(){return this.toNT()}}var pr=a(2727);class gr extends Zt.A{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";super(e),(0,Yt.A)(this,"termType",er.P2),(0,Yt.A)(this,"base","varid:"),(0,Yt.A)(this,"classOrder",Qt.A.Variable),(0,Yt.A)(this,"isVar",1),(0,Yt.A)(this,"uri",void 0),this.base="varid:",this.uri=pr.join(e,this.base)}equals(e){return!!e&&(this.termType===e.termType&&this.value===e.value)}hashString(){return this.toString()}substitute(e){var t;return null!=(t=e[this.toNT()])?t:this}toString(){return gr.toString(this)}static toString(e){return e.uri.slice(0,e.base.length)===e.base?`?${e.uri.slice(e.base.length)}`:`?${e.uri}`}}let yr=function(e){return e.collections="COLLECTIONS",e.defaultGraphType="DEFAULT_GRAPH_TYPE",e.equalsMethod="EQUALS_METHOD",e.id="ID",e.identity="IDENTITY",e.reversibleId="REVERSIBLE_ID",e.variableType="VARIABLE_TYPE",e}({});const vr=new hr,mr={supports:{[yr.collections]:!1,[yr.defaultGraphType]:!1,[yr.equalsMethod]:!0,[yr.identity]:!1,[yr.id]:!0,[yr.reversibleId]:!1,[yr.variableType]:!0},blankNode:e=>new tr(e),defaultGraph:()=>vr,equals(e,t){return e===t||!e||!t||((0,nr.aF)(e)||(0,nr.aF)(t)?!(!(0,nr.aF)(e)||!(0,nr.aF)(t))&&(this.equals(e.subject,t.subject)&&this.equals(e.predicate,t.predicate)&&this.equals(e.object,t.object)&&this.equals(e.graph,t.graph)):!(!(0,nr.D0)(e)||!(0,nr.D0)(t))&&this.id(e)===this.id(t))},id(e){if(!e)return"undefined";if((0,nr.aF)(e))return this.quadToNQ(e);switch(e.termType){case er.ic:return"defaultGraph";case er.P2:return gr.toString(e);default:const t=this.termToNQ(e);if(t)return t;throw new Error(`Can't id term with type '${e.termType}'`)}},isQuad:e=>e instanceof fr,literal(e,t){if("string"!=typeof e&&!t)return sr.fromValue(e);const r="string"==typeof e?e:""+e;return"string"==typeof t?-1===t.indexOf(":")?new sr(r,t):new sr(r,null,this.namedNode(t)):new sr(r,null,t)},namedNode:e=>new rr.A(e),quad:(e,t,r,n)=>new fr(e,t,r,n||vr),triple(e,t,r,n){return this.quad(e,t,r,n)},quadToNQ(e){return`${this.termToNQ(e.subject)} ${this.termToNQ(e.predicate)} ${this.termToNQ(e.object)} ${this.termToNQ(e.graph)} .`},termToNQ(e){switch(e.termType){case er.$Q:return"_:"+e.value;case er.ic:return"";case er.S:return"<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>";case er.QW:return sr.toNT(e);case er.bD:case er.Kk:return"<"+e.value+">";case er.r0:return"("+e.elements.map(e=>this.termToNQ(e)).join(" ")+")";default:throw new Error(`Can't serialize nonstandard term type (was '${e.termType}')`)}},toNQ(e){return this.isQuad(e)?this.quadToNQ(e):this.termToNQ(e)},variable:e=>new gr(e)},wr=mr;var br=a(4940);function _r(e,t){const r=t||{namedNode:e=>new rr.A(e)};return function(t){return r.namedNode(e+(t||""))}}var Sr=a(4011);function Er(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:wr;return{boolean:e.namedNode("http://www.w3.org/2001/XMLSchema#boolean"),dateTime:e.namedNode("http://www.w3.org/2001/XMLSchema#dateTime"),decimal:e.namedNode("http://www.w3.org/2001/XMLSchema#decimal"),double:e.namedNode("http://www.w3.org/2001/XMLSchema#double"),integer:e.namedNode("http://www.w3.org/2001/XMLSchema#integer"),langString:e.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),string:e.namedNode("http://www.w3.org/2001/XMLSchema#string")}}Er(wr);var xr=a(5386),Ar=a.n(xr),Fr=a(5306);function Tr(e){return new kr(e)}class kr{constructor(e){(0,Yt.A)(this,"_notQNameChars","\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~"),(0,Yt.A)(this,"_notNameChars",this._notQNameChars+":"),(0,Yt.A)(this,"validPrefix",new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/)),(0,Yt.A)(this,"forbidden1",new RegExp(/[\\"\b\f\r\v\t\n\u0080-\uffff]/gm)),(0,Yt.A)(this,"forbidden3",new RegExp(/[\\"\b\f\r\v\u0080-\uffff]/gm)),this.flags="",this.base=null,this.prefixes=[],this.namespaces=[];const t=Object.keys(Ar()());for(const e in t){const r=Ar()()[t[e]](""),n=t[e];this.prefixes[r]=n,this.namespaces[n]=r}this.suggestPrefix("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.suggestPrefix("xml","reserved:reservedForFutureUse"),this.namespacesUsed=[],this.keywords=["a"],this.prefixchars="abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",this.incoming=null,this.formulas=[],this.store=e,this.rdfFactory=e.rdfFactory||wr,this.xsd=Er(this.rdfFactory)}setBase(e){return this.base=e,this}setFlags(e){return this.flags=e||"",this}toStr(e){var t=e.toNT();return"Graph"===e.termType&&(this.formulas[t]=e),t}fromStr(e){if("{"===e[0]){var t=this.formulas[e];return t||console.log("No formula object for "+e),t}return this.store.fromNT(e)}setNamespaces(e){for(var t in e)this.setPrefix(t,e[t]);return this}setPrefix(e,t){if("default"!==e.slice(0,7)&&"ns"!==e.slice(0,2)&&e&&t){for(let t in this.prefixes)this.prefixes[t]==e&&delete this.prefixes[t];this.prefixes[t]=e,this.namespaces[e]=t}}suggestPrefix(e,t){"default"!==e.slice(0,7)&&"ns"!==e.slice(0,2)&&e&&t&&(e in this.namespaces||t in this.prefixes||(this.prefixes[t]=e,this.namespaces[e]=t))}suggestNamespaces(e){for(var t in e)this.suggestPrefix(t,e[t]);return this}checkIntegrity(){var e,t;for(e in this.namespaces)if(this.prefixes[this.namespaces[e]]!==e)throw new Error("Serializer integity error 1: "+e+", "+this.namespaces[e]+", "+this.prefixes[this.namespaces[e]]+"!");for(t in this.prefixes)if(this.namespaces[this.prefixes[t]]!==t)throw new Error("Serializer integity error 2: "+t+", "+this.prefixs[t]+", "+this.namespaces[this.prefixes[t]]+"!")}makeUpPrefix(e){var t=e;var r=function(t){return!!this.validPrefix.test(t)&&("ns"!==t&&(!(t in this.namespaces)&&(this.prefixes[e]=t,this.namespaces[t]=e,t)))}.bind(this);"#/".indexOf(t[t.length-1])>=0&&(t=t.slice(0,-1));var n=t.lastIndexOf("/");n>=0&&(t=t.slice(n+1));for(var i=0;i<t.length&&this.prefixchars.indexOf(t[i]);)i++;if((t=t.slice(0,i)).length<6&&r(t))return t;if(r(t.slice(0,3)))return t.slice(0,3);if(r(t.slice(0,2)))return t.slice(0,2);if(r(t.slice(0,4)))return t.slice(0,4);if(r(t.slice(0,1)))return t.slice(0,1);if(r(t.slice(0,5)))return t.slice(0,5);this.validPrefix.test(t)||(t="n");for(var s=0;;s++)if(r(t.slice(0,3)+s))return t.slice(0,3)+s}rootSubjects(e){for(var t={},r={},n={},i=0;i<e.length;i++){var s=e[i],o=function(e){t.hasOwnProperty(e)||(t[e]=[]),t[e].push(s.subject)};[s.subject,s.predicate,s.object].map(function(e){"BlankNode"===e.termType?n[e.toNT()]=!0:"Collection"===e.termType&&e.elements.forEach(function(e){o(e)})}),o(e[i].object);var a=r[this.toStr(s.subject)];a||(a=[]),a.push(s),r[this.toStr(s.subject)]=a}var u=[];for(var c in r)if(r.hasOwnProperty(c)){var h=this.fromStr(c);"BlankNode"===h.termType&&t[h]&&1===t[h].length||u.push(h)}this.incoming=t;for(var l={},d=0;d<u.length;d++)l[u[d].toNT()]=!0;return{roots:u,subjects:r,rootsHash:l,incoming:t}}toN3(e){return this.statementsToN3(e.statements)}explicitURI(e){var t;return this.flags.indexOf("r")<0&&this.base?e=pr.refTo(this.base,e):this.flags.indexOf("u")>=0?e=function(e){for(var t,r="",n=0;n<e.length;n++)r+=(t=e.charCodeAt(n))>65535?"\\U"+("00000000"+t.toString(16)).slice(-8):t>126?"\\u"+("0000"+t.toString(16)).slice(-4):e[n];return r}(e):(t=decodeURI(e),e=encodeURI(t)),"<"+e+">"}statementsToNTriples(e){var t=e.slice();t.sort();for(var r="",n="http://www.w3.org/1999/02/22-rdf-syntax-ns#",i=this,s=this.store,o=this.rdfFactory,a=function(e){if("Collection"!==e.termType)return i.atomicTermToN3(e);for(var t=e.elements,u=s.sym(n+"nill"),c=t.length-1;c>=0;c--){var h=o.blankNode();r+=a(h)+" "+a(s.sym(n+"first"))+" "+a(t[c])+".\n",r+=a(h)+" "+a(s.sym(n+"rest"))+" "+a(u)+".\n",u=h}return i.atomicTermToN3(u)},u=0;u<t.length;u++){var c=t[u],h="";h+=a(c.subject)+" ",h+=a(c.predicate)+" ",h+=a(c.object)+" ",this.flags.indexOf("q")>=0&&(h+=a(c.why)+" "),r+=h+=".\n"}return r}statementsToN3(e){var t=this.store,r={"http://www.w3.org/1999/02/22-rdf-syntax-ns#type":"aaa:00"};e.sort(function(e,n){return Sr.heavyCompareSPO(e,n,t,r)}),this.base&&!this.defaultNamespace&&(this.defaultNamespace=this.base+"#");var n={};this.flags.indexOf("s")<0&&(n["http://www.w3.org/2002/07/owl#sameAs"]="="),this.flags.indexOf("t")<0&&(n["http://www.w3.org/1999/02/22-rdf-syntax-ns#type"]="a"),this.flags.indexOf("i")<0&&(n["http://www.w3.org/2000/10/swap/log#implies"]="=>");var i=function(e){for(var t="",r=0;r<e;r++)t+=" ";return t},s=function(e){for(var t="",r=0;r<e.length;r++){var n=e[r],i="string"==typeof n?n:s(n);if(0!==r){var o=t.slice(-1)||" ";","===i||";"===i||("."!==i||"0123456789.:".includes(o))&&(t+=" ")}t+=i}return t},o=function(e,t){var r="",n=1e5;void 0===t&&(t=-1);for(var a=0;a<e.length;a++){var u=e[a];if("string"!=typeof u){var c=o(u,t+1);if(c.length<10*(80-4*t)&&c.indexOf('"""')<0){var h=s(u);h.length<80-4*t&&(u=h,c="")}c&&(n=1e4),r+=c}if("string"==typeof u){if(1===u.length&&"\n"===r.slice(-1)&&",.;".indexOf(u)>=0){r=r.slice(0,-1),"."==u&&"0123456789.:".includes(r.charAt(r.length-1))&&(r+=" ",n+=1),r+=u+"\n",n+=1;continue}if(n<4*t+4||n+u.length+1<80&&";.".indexOf(r[r.length-2])<0)r=r.slice(0,-1)+" "+u+"\n",n+=u.length+1;else{let e=i(4*t)+u;r+=e+"\n",n=e.length,t<0&&(r+="\n",n=1e5)}}}return r};var a=function(e){for(var t=this.rootSubjects(e),r=t.roots,n=[],i=0;i<r.length;i++){var s=r[i];n.push(u(s,t))}return n}.bind(this);function u(e,t){return"BlankNode"!==e.termType||t.incoming[e]?[l(e,t)].concat([c(e,t)]).concat(["."]):h(e,t,!0).concat(["."])}var c=function(e,t){var r=[],i=null,s=t.subjects[this.toStr(e)]||[];if(void 0===s)throw new Error("Cant find statements for "+e);for(var o=[],a=0;a<s.length;a++){var u=s[a];u.predicate.uri===i?o.push(","):(i&&(r=r.concat([o]).concat([";"]),o=[]),r.push(n[u.predicate.uri]?n[u.predicate.uri]:l(u.predicate,t))),i=u.predicate.uri,o.push(h(u.object,t))}return r=r.concat([o])}.bind(this);var h=function(e,t,r){return"BlankNode"!==e.termType||!r&&void 0!==t.rootsHash[e.toNT()]?l(e,t):t.subjects[this.toStr(e)]?["[",c(e,t),"]"]:"[]"}.bind(this);kr.prototype.termToN3=l;var l=function(e,t){var r,n;switch(e.termType){case"Graph":return(n=(n=["{"]).concat(a(e.statements))).concat(["}"]);case"Collection":for(n=["("],r=0;r<e.elements.length;r++)n.push([h(e.elements[r],t)]);return n.push(")"),n;default:return this.atomicTermToN3(e)}}.bind(this);var d=function(){var e="";for(var t in this.flags.indexOf("d")<0&&this.defaultNamespace&&(e+="@prefix : "+this.explicitURI(this.defaultNamespace)+".\n"),this.prefixes)this.prefixes.hasOwnProperty(t)&&this.namespacesUsed[t]&&(e+="@prefix "+this.prefixes[t]+": "+this.explicitURI(t)+".\n");return e+"\n"}.bind(this),f=a(e);return d()+o(f)}atomicTermToN3(e,t){switch(e.termType){case"BlankNode":case"Variable":return e.toNT();case"Literal":var r=e.value;if("string"!=typeof r)throw new TypeError("Value of RDF literal node must be a string");if(e.datatype&&this.flags.indexOf("x")<0)switch(e.datatype.uri){case"http://www.w3.org/2001/XMLSchema#integer":return r;case"http://www.w3.org/2001/XMLSchema#decimal":return r.indexOf(".")<0&&(r+=".0"),r;case"http://www.w3.org/2001/XMLSchema#double":{const e=r.toLowerCase().indexOf("e")>0;return r.indexOf(".")<0&&!e&&(r+=".0"),e||(r+="e0"),r}case"http://www.w3.org/2001/XMLSchema#boolean":return"1"===e.value?"true":"false"}var n=this.stringToN3(e.value,this.flags);return e.language?n+="@"+e.language:e.datatype.equals(this.xsd.string)||(n+="^^"+this.atomicTermToN3(e.datatype,t)),n;case"NamedNode":return this.symbolToN3(e);case"DefaultGraph":return"";default:throw new Error("Internal: atomicTermToN3 cannot handle "+e+" of termType: "+e.termType)}}stringToN3(e,t){t||(t="e");var r,n,i,s,o,a="";for(e.length>20&&'"'!==e.slice(-1)&&t.indexOf("n")<0&&(e.indexOf("\n")>0||e.indexOf('"')>0)?(s='"""',o=this.forbidden3):(s='"',o=this.forbidden1),r=0;r<e.length;){if(o.lastIndex=0,null==o.exec(e.slice(r)))break;n=r+o.lastIndex-1,a+=e.slice(r,n);var u=e[n];'"'===u&&'"""'===s&&'"""'!==e.slice(n,n+3)?a+=u:(i='\b\f\r\t\v\n\\"'.indexOf(u))>=0?a+="\\"+'bfrtvn\\"'[i]:t.indexOf("e")>=0?a+="\\u"+("000"+u.charCodeAt(0).toString(16).toLowerCase()).slice(-4):a+=u,r=n+1}return s+a+e.slice(r)+s}symbolToN3(e){var t=e.uri,r=t.indexOf("#");if(r<0&&this.flags.indexOf("/")<0&&(r=t.lastIndexOf("/")),r>=0&&this.flags.indexOf("p")<0&&(0===t.indexOf("http")||0===t.indexOf("ws")||0===t.indexOf("file"))){for(var n=!0,i=r+1;i<t.length;i++)if(this._notNameChars.indexOf(t[i])>=0){n=!1;break}if(n){var s=t.slice(r+1),o=t.slice(0,r+1);if(this.defaultNamespace&&this.defaultNamespace===o&&this.flags.indexOf("d")<0)return this.flags.indexOf("k")>=0&&this.keyords.indexOf(s)<0?s:":"+s;var a=this.prefixes[o];if(a||(a=this.makeUpPrefix(o)),a)return this.namespacesUsed[o]=!0,a+":"+s}}return this.explicitURI(t)}writeStore(e){var t=this.store,r=t.fetcher,n=r&&r.appNode,i=this.store.index[3];for(var s in i){var o=t.fromNT(s);n&&o.equals(n)||e("\n"+this.atomicTermToN3(o)+" "+this.atomicTermToN3(t.sym("http://www.w3.org/2000/10/swap/log#semantics"))+" { "+this.statementsToN3(t.statementsMatching(void 0,void 0,void 0,o))+" }.\n")}t.statementsMatching(void 0,t.sym("http://www.w3.org/2007/ont/link#requestedURI")).map(function(r){e("\n<"+r.object.value+"> log:metadata {\n");var n=t.statementsMatching(void 0,void 0,void 0,r.subject);e(this.statementsToN3(this.statementsToN3(n))),e("}.\n")});var a=[];n&&a.push(n);var u=[];a.map(function(e){u=u.concat(t.statementsMatching(void 0,void 0,void 0,e))}),e(this.statementsToN3(u))}statementsToXML(e){var t=[];t["http://www.w3.org/1999/02/22-rdf-syntax-ns#"]=!0;var r="http://www.w3.org/1999/02/22-rdf-syntax-ns#_",n=function(e){for(var t="",r=0;r<e;r++)t+=" ";return t},i=function(e){for(var t="",r=0;r<e.length;r++){var n=e[r];t+="string"==typeof n?n:i(n)}return t},s=function(e,t){var r,o="",a=1e5;t||(t=0);for(var u=0;u<e.length;u++){var c=e[u];if("string"!=typeof c){var h=s(c,t+1);h.length<10*(80-4*t)&&h.indexOf('"""')<0&&(r=i(c)).length<80-4*t&&(c=" "+r,h=""),h&&(a=1e4),o+=h}"string"==typeof c&&(a<4*t+4?(o=o.slice(0,-1)+" "+c+"\n",a+=c.length+1):(o+=(r=n(4*t)+c)+"\n",a=r.length))}return o};var o=function(e){this.suggestPrefix("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#");for(var t=this.rootSubjects(e),r=t.roots,n=[],i=0;i<r.length;i++){var s=r[i];n.push(c(s,t))}return n}.bind(this);function a(e){return void 0===e?"@@@undefined@@@@":e.replace(/[&<"]/g,function(e){switch(e[0]){case"&":return"&amp;";case"<":return"&lt;";case'"':return"&quot;"}})}var u=function(e){return a(this.base?pr.refTo(this.base,e.uri):e.uri)}.bind(this);var c=function(e,t){var n,i,s,o,f=[],p=t.subjects[this.toStr(e)];if(void 0===p)return l(e,t);p.sort(function(e,t){var n=e.predicate.uri,i=t.predicate.uri;if(n.substring(0,44)===r||i.substring(0,44)===r)return n.localeCompare(i);var s=n.substring(44),o=i.substring(44),a=parseInt(s,10),u=parseInt(o,10);return isNaN(a)||isNaN(u)||a!==s||u!==o?n.localeCompare(i):a-u});for(var g=0;g<p.length;g++)if("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"!==(s=p[g]).predicate.uri||n||"NamedNode"!==s.object.termType){if((o=s.predicate).uri.substr(0,44)===r){var y=o.uri.substr(44);y===parseInt(y,10).toString()&&(o=this.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#li"))}switch(i=d(o),s.object.termType){case"BlankNode":f=1===t.incoming[s.object].length?f.concat(["<"+i+' rdf:parseType="Resource">',c(s.object,t),"</"+i+">"]):f.concat(["<"+i+' rdf:nodeID="'+s.object.toNT().slice(2)+'"/>']);break;case"NamedNode":f=f.concat(["<"+i+' rdf:resource="'+u(s.object)+'"/>']);break;case"Literal":f=f.concat(["<"+i+(s.object.datatype.equals(this.xsd.string)?"":' rdf:datatype="'+a(s.object.datatype.uri)+'"')+(s.object.language?' xml:lang="'+s.object.language+'"':"")+">"+a(s.object.value)+"</"+i+">"]);break;case"Collection":f=f.concat(["<"+i+' rdf:parseType="Collection">',h(s.object,t),"</"+i+">"]);break;default:throw new Error("Can't serialize object of type "+s.object.termType+" into XML")}}else n=s.object;var v=n?d(n):"rdf:Description",m="";return"BlankNode"===e.termType?t.incoming[e]&&1===t.incoming[e].length||(m=' rdf:nodeID="'+e.toNT().slice(2)+'"'):m=' rdf:about="'+u(e)+'"',["<"+v+m+">"].concat([f]).concat(["</"+v+">"])}.bind(this);function h(e,t){for(var r=[],n=0;n<e.elements.length;n++)r.push(c(e.elements[n],t));return r}var l=function(e,t){var r=[],n=t.subjects[this.toStr(e)];if(!n)return r;n.sort();for(var i=0;i<n.length;i++){var s=n[i];switch(s.object.termType){case"BlankNode":r=t.rootsHash[s.object.toNT()]?r.concat(["<"+d(s.predicate)+' rdf:nodeID="'+s.object.toNT().slice(2)+'">',"</"+d(s.predicate)+">"]):r.concat(["<"+d(s.predicate)+' rdf:parseType="Resource">',l(s.object,t),"</"+d(s.predicate)+">"]);break;case"NamedNode":r=r.concat(["<"+d(s.predicate)+' rdf:resource="'+u(s.object)+'"/>']);break;case"Literal":r=r.concat(["<"+d(s.predicate)+(s.object.datatype.equals(this.xsd.string)?"":' rdf:datatype="'+a(s.object.datatype.value)+'"')+(s.object.language?' xml:lang="'+s.object.language+'"':"")+">"+a(s.object.value)+"</"+d(s.predicate)+">"]);break;case"Collection":r=r.concat(["<"+d(s.predicate)+' rdf:parseType="Collection">',h(s.object,t),"</"+d(s.predicate)+">"]);break;default:throw new Error("Can't serialize object of type "+s.object.termType+" into XML")}}return r}.bind(this);var d=function(e){var r=e.uri,n=r.indexOf("#");if(n<0&&this.flags.indexOf("/")<0&&(n=r.lastIndexOf("/")),n<0)throw new Error("Cannot make qname out of <"+r+">");for(var i=n+1;i<r.length;i++)if(this._notNameChars.indexOf(r[i])>=0)throw new Error('Invalid character "'+r[i]+'" cannot be in XML qname for URI: '+r);var s=r.slice(n+1),o=r.slice(0,n+1);if(this.defaultNamespace&&this.defaultNamespace===o&&this.flags.indexOf("d")<0)return s;var a=this.prefixes[o];return a||(a=this.makeUpPrefix(o)),t[o]=!0,a+":"+s}.bind(this),f=o(e),p="<rdf:RDF";for(var g in this.defaultNamespace&&(p+=' xmlns="'+a(this.defaultNamespace)+'"'),t)if(t.hasOwnProperty(g)){var y=this.base&&this.flags.includes("z")?pr.refTo(this.base,g):g;p+="\n xmlns:"+this.prefixes[g]+'="'+a(y)+'"'}return s([p+=">",f,"</rdf:RDF>"],-1)}statementsToJsonld(e){const t=this.statementsToN3(e),r=Fr.parse(t);return JSON.stringify(r,null,2)}}function Ir(e,t,r,n,i,s){r=r||e?.value;const o=s||{};n=n||er.sT;try{var a=Tr(t);o.flags&&a.setFlags(o.flags);var u=t.statementsMatching(void 0,void 0,void 0,e);switch("namespaces"in t&&a.suggestNamespaces(t.namespaces),o.namespaces&&a.setNamespaces(o.namespaces),a.setBase(r),n){case er.JG:return c(null,a.statementsToXML(u));case er.ny:case er.MG:return c(null,a.statementsToN3(u));case er.sT:case er.hu:return a.setFlags("si"),c(null,a.statementsToN3(u));case er.bM:return a.setFlags("deinprstux"),c(null,a.statementsToNTriples(u));case er.i2:return a.setFlags("si dr"),c(null,a.statementsToJsonld(u));case er._0:case er.BR:return a.setFlags("deinprstux q"),c(null,a.statementsToNTriples(u));default:throw new Error("Serialize: Content-type "+n+" not supported for data write.")}}catch(e){if(i)return i(e,void 0);throw e}function c(e,t){return i?void i(e,t):t}}const Cr=["blankNode","defaultGraph","literal","namedNode","quad","variable","supports"],Rr={first:"http://www.w3.org/1999/02/22-rdf-syntax-ns#first",rest:"http://www.w3.org/1999/02/22-rdf-syntax-ns#rest",nil:"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"};function Pr(e,t,r){const n=[];return r.reduce((t,r,i,s)=>{let o;return n.push(e.quad(t,e.namedNode(Rr.first),s[i])),i<s.length-1?(o=e.blankNode(),n.push(e.quad(t,e.namedNode(Rr.rest),o))):n.push(e.quad(t,e.namedNode(Rr.rest),e.namedNode(Rr.nil))),o},t),n}function Nr(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;var n=e.length;for(r<0&&(r=n+r);r<n;r++)if(e[r]===t)return r;return-1}class Ur extends Zt.A{constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};super(""),e=this,this.statements=t,this.constraints=r,this.initBindings=n,this.optional=i,(0,Yt.A)(this,"termType",er.bD),(0,Yt.A)(this,"classOrder",Qt.A.Graph),(0,Yt.A)(this,"fetcher",void 0),(0,Yt.A)(this,"isVar",0),(0,Yt.A)(this,"ns",_r),(0,Yt.A)(this,"rdfFactory",void 0),this.rdfFactory=s&&s.rdfFactory||wr;for(const t of Cr)this[t]=function(){return e.rdfFactory[t](...arguments)}}add(e,t,r,n){return 1===arguments.length&&e.forEach(e=>this.add(e.subject,e.predicate,e.object,e.graph)),this.statements.push(this.rdfFactory.quad(e,t,r,n))}addStatement(e){return this.add(e)}bnode(e){return this.rdfFactory.blankNode(e)}addAll(e){e.forEach(e=>{this.add(e.subject,e.predicate,e.object,e.graph)})}any(e,t,r,n){const i=this.anyStatementMatching(e,t,r,n);return null==i?null:null==e?i.subject:null==t?i.predicate:null==r?i.object:null}anyValue(e,t,r,n){const i=this.any(e,t,r,n);return i?i.value:void 0}anyJS(e,t,r,n){const i=this.any(e,t,r,n);return i?Zt.A.toJS(i):void 0}anyStatementMatching(e,t,r,n){let i=this.statementsMatching(e,t,r,n,!0);if(i&&0!==i.length)return i[0]}id(e){return this.rdfFactory.id(e)}statementsMatching(e,t,r,n,i){const s=this.statements.filter(i=>(!e||e.equals(i.subject))&&(!t||t.equals(i.predicate))&&(!r||r.equals(i.object))&&(!n||n.equals(i.graph)));return i?0===s.length?[]:[s[0]]:s}bottomTypeURIs(e){let t,r,n,i,s,o,a,u;t=[];for(let c in e)if(e.hasOwnProperty(c)){for(u=e[c],a=this.each(void 0,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),this.rdfFactory.namedNode(c)),r=!0,i=0,s=a.length;i<s;i++)if(n=a[i],o=n.uri,o in e){r=!1;break}r&&(t[c]=u)}return t}collection(){return new ar}each(e,t,r,n){const i=[];let s=this.statementsMatching(e,t,r,n,!1);if(null==e)for(let e=0,t=s.length;e<t;e++)i.push(s[e].subject);else if(null==t)for(let e=0,t=s.length;e<t;e++)i.push(s[e].predicate);else if(null==r)for(let e=0,t=s.length;e<t;e++)i.push(s[e].object);else if(null==n)for(let e=0,t=s.length;e<t;e++)i.push(new rr.A(s[e].graph.value));return i}equals(e){return!!e&&this.hashString()===e.hashString()}findMembersNT(e){let t,r,n,i,s,o,a,u,c,h,l,d,f,p;d={},d[e.toNT()]=!0,i={},o=this.transitiveClosure(d,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!0);for(let e in o)if(o.hasOwnProperty(e)){a=this.statementsMatching(void 0,this.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),this.fromNT(e));for(let e=0,t=a.length;e<t;e++)f=a[e],i[f.subject.toNT()]=f;u=this.each(void 0,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#domain"),this.fromNT(e));for(let e=0,r=u.length;e<r;e++)for(s=u[e],c=this.statementsMatching(void 0,s),n=0,t=c.length;n<t;n++)f=c[n],i[f.subject.toNT()]=f;h=this.each(void 0,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#range"),this.fromNT(e));for(let e=0,t=h.length;e<t;e++)for(s=h[e],l=this.statementsMatching(void 0,s),p=0,r=l.length;p<r;p++)f=l[p],i[f.object.toNT()]=f}return i}findMemberURIs(e){return this.NTtoURI(this.findMembersNT(e))}findSubClassesNT(e){let t={};return t[e.toNT()]=!0,this.transitiveClosure(t,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!0)}findSuperClassesNT(e){let t={};return t[e.toNT()]=!0,this.transitiveClosure(t,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!1)}findTypesNT(e){let t,r,n,i,s,o,a,u,c;n="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",c=[],i=this.statementsMatching(e,void 0,void 0);for(let e=0,t=i.length;e<t;e++)if(u=i[e],"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"===u.predicate.uri)c[u.object.toNT()]=u;else{s=this.each(u.predicate,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#domain"));for(let e=0,t=s.length;e<t;e++)r=s[e],c[r.toNT()]=u}o=this.statementsMatching(void 0,void 0,e);for(let e=0,r=o.length;e<r;e++){u=o[e],a=this.each(u.predicate,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#range"));for(let e=0,r=a.length;e<r;e++)t=a[e],c[t.toNT()]=u}return this.transitiveClosure(c,this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf"),!1)}findTypeURIs(e){return this.NTtoURI(this.findTypesNT(e))}connectedStatements(e,t,r){r=r||[];let n=[e],i={},s={},o=[],a=this,u=function(e){let u=function(e){"BlankNode"!==e.termType||i[e.value]||(i[e.value]=!0,n.push(e))},c=a.statementsMatching(null,null,e,t).concat(a.statementsMatching(e,null,null,t));c=c.filter(function(e){if(r[e.predicate.value])return!1;let t=e.toNT();return!s[t]&&(s[t]=!0,!0)}),c.forEach(function(e){u(e.subject),u(e.object)}),o=o.concat(c)};for(;n.length;)u(n.shift());return o}formula(e){return new Ur}fromNT(e){let t,r,n;switch(e[0]){case"<":return this.sym(e.slice(1,-1));case'"':if(n=void 0,t=void 0,r=e.lastIndexOf('"'),r<e.length-1)if("@"===e[r+1])n=e.slice(r+2);else{if("^^"!==e.slice(r+1,r+3))throw new Error("Can't convert string from NT: "+e);t=this.fromNT(e.slice(r+3))}return e=(e=(e=(e=e.slice(1,r)).replace(/\\"/g,'"')).replace(/\\n/g,"\n")).replace(/\\\\/g,"\\"),this.rdfFactory.literal(e,n||t);case"_":return this.rdfFactory.blankNode(e.slice(2));case"?":return new gr(e.slice(1))}throw new Error("Can't convert from NT: "+e)}holds(e,t,r,n){let i;if(1===arguments.length){if(!e)return!0;if(e instanceof Array){for(i=0;i<e.length;i++)if(!this.holds(e[i]))return!1;return!0}if((0,nr.SH)(e))return this.holds(e.subject,e.predicate,e.object,e.graph);if(e.statements)return this.holds(e.statements)}return null!=this.anyStatementMatching(e,t,r,n)}holdsStatement(e){return this.holds(e.subject,e.predicate,e.object,e.graph)}list(e,t){if(t.rdfFactory.supports.COLLECTIONS){const r=t.rdfFactory.collection();return e.forEach(function(e){r.append(e)}),r}{const r=t.rdfFactory.blankNode(),n=Pr(t.rdfFactory,r,e);return t.addAll(n),r}}NTtoURI(e){let t,r,n={};for(t in e)e.hasOwnProperty(t)&&(r=e[t],"<"===t[0]&&(n[t.slice(1,-1)]=r));return n}serialize(e,t,r,n){return Ir(r,this,e,t,void 0,n)}substitute(e){let t=this.statements.map(function(t){return t.substitute(e)});const r=new Ur;return r.addAll(t),r}sym(e,t){if(t)throw new Error("This feature (kb.sym with 2 args) is removed. Do not assume prefix mappings.");return this.rdfFactory.namedNode(e)}the(e,t,r,n){let i=this.any(e,t,r,n);return null==i&&br.A.error("No value found for the() {"+e+" "+t+" "+r+"}."),i}transitiveClosure(e,t,r){let n,i,s,o,a,u,c={};Object.assign(c,e);let h={};for(;;){if(u=function(){for(let e in c)if(c.hasOwnProperty(e))return e}(),null==u)return h;for(a=r?this.each(void 0,t,this.fromNT(u)):this.each(this.fromNT(u),t),i=0,s=a.length;i<s;i++)n=a[i],o=n.toNT(),o in h||o in c||(c[o]=c[u]);h[u]=c[u],delete c[u]}}topTypeURIs(e){let t,r,n,i,s,o,a,u;for(n in a=[],e)if(e.hasOwnProperty(n)){for(u=e[n],s=0,o=this.each(this.rdfFactory.namedNode(n),this.rdfFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#subClassOf")),t=0,i=o.length;t<i;t++)if(r=o[t],"http://www.w3.org/2000/01/rdf-schema#Resource"!==r.uri){s++;break}s||(a[n]=u)}return a["http://www.w3.org/2000/01/rdf-schema#Resource"]&&delete a["http://www.w3.org/2000/01/rdf-schema#Resource"],a["http://www.w3.org/2002/07/owl#Thing"]&&delete a["http://www.w3.org/2002/07/owl#Thing"],a}toString(){return"{"+this.statements.join("\n")+"}"}variable(e){return new gr(e)}whether(e,t,r,n){return this.statementsMatching(e,t,r,n,!1).length}}Zt.A.fromValue=or;const Or=Zt.A,Lr={xsd:_r("http://www.w3.org/2001/XMLSchema#")};Zt.A.toJS=function(e){return(0,nr.P3)(e)?e.elements.map(Zt.A.toJS):(0,nr.c$)(e)?e.datatype.equals(Lr.xsd("boolean"))?"1"===e.value||"true"===e.value:e.datatype.equals(Lr.xsd("dateTime"))||e.datatype.equals(Lr.xsd("date"))?new Date(e.value):e.datatype.equals(Lr.xsd("integer"))||e.datatype.equals(Lr.xsd("float"))||e.datatype.equals(Lr.xsd("decimal"))?Number(e.value):e.value:e};class Dr{constructor(e,t){this.pat=new Kr,this.vars=[],this.name=e,this.id=t}}function jr(e,t,r,n){function i(e){var t,r="";for(t in e)e.hasOwnProperty(t)&&(r+=" "+t+" -> "+e[t]);return r}function s(e){var t,r="Bindings: ",n=e.length;for(t=0;t<n;t++)r+=i(e[t][0])+";\n\t";return r}function o(e,t,r,n){var i;if(e.length!==t.length)return[];if(!e.length)return[[[],null]];var s=function(e,t,r,n){var i=r[e];if(void 0===i){if(e.isVar){var s=[];return s[e]=t,[[s,null]]}i=e}if(!i.complexType)return n.redirections[i]&&(i=n.redirections[i]),n.redirections[t]&&(t=n.redirections[t]),i.equals(t)||i.uri&&i.uri===cr?[[[],null]]:[];if(e instanceof Array)return t instanceof Array?o(e,t,r):[];throw new Error("query.js: oops - code not written yet")}(e[0],t[0],r,n);if(0===s.length)return s;var a,u,c,h,l,d,f,p=[],g=s.length;for(a=0;a<g;a++){for(l in f=[],u=s[a][0])u.hasOwnProperty(l)&&(f[l]=u[l]);for(l in r)r.hasOwnProperty(l)&&(f[l]=r[l]);for(h=(i=o(e.slice(1),t.slice(1),f,n)).length,c=0;c<h;c++){for(l in d=i[c][0],u)u.hasOwnProperty(l)&&(d[l]=u[l]);p.push([d,null])}}return p}function a(e,t){var r=t[e];return void 0===r?e:r}function u(e,t){var r,n={};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);for(r in t)t.hasOwnProperty(r)&&(n[r]=t[r]);return n}function c(e,t){return this.trunkBindings=t,this.originalCallback=e,this.branches=[],this}function h(e,t){return this.count=0,this.success=!1,this.done=!1,this.callback=e,this.onDone=t,this}c.prototype.checkAllDone=function(){var e;for(e=0;e<this.branches.length;e++)if(!this.branches[e].done)return;br.A.debug("OPTIONAL BIDNINGS ALL DONE:"),this.doCallBacks(this.branches.length-1,this.trunkBindings)},c.prototype.doCallBacks=function(e,t){var r;if(e<0)return this.originalCallback(t);for(r=0;r<this.branches[e].results.length;r++)this.doCallBacks(e-1,u(t,this.branches[e].results[r]))},h.prototype.reportMatch=function(e){this.callback(e),this.success=!0},h.prototype.reportDone=function(){this.done=!0,br.A.info("Mandatory query branch finished.***"),void 0!==this.onDone&&this.onDone()};var l=function(e){return this.count=0,this.done=!1,this.results=[],this.junction=e,e.branches.push(this),this};function d(e,t,r){var n,i,s,o;for(t.nvars=0,t.index=null,n=[t.subject,t.predicate,t.object,t.why],o=[e.subjectIndex,e.predicateIndex,e.objectIndex,e.whyIndex],s=0;s<4;s++){let u=n[s];if(u.uri&&u.uri===cr);else if(u.isVar&&void 0===r[u])t.nvars++;else{if(u=a(n[s],r),e.redirections[e.id(u)]&&(u=e.redirections[e.id(u)]),!(i=o[s][e.id(u)]))return t.index=[],!1;(null===t.index||t.index.length>i.length)&&(t.index=i)}}return null===t.index&&(t.index=e.statements),!0}function f(e,t){return e.nvars!==t.nvars?e.nvars-t.nvars:e.index.length-t.index.length}l.prototype.reportMatch=function(e){this.results.push(e)},l.prototype.reportDone=function(){br.A.debug("Optional branch finished - results.length = "+this.results.length),0===this.results.length&&(this.results.push({}),br.A.debug("Optional branch FAILED - that's OK.")),this.done=!0,this.junction.checkAllDone()};var p=function(e,r,n,s,o,a,u){br.A.debug("Match begins, Branch count now: "+u.count+" for "+u.pattern_debug);var h,d,f=r.statements;if(0===f.length){if(br.A.debug("FOUND MATCH WITH BINDINGS:"+i(n)),0===r.optional.length)u.reportMatch(n);else{br.A.debug("OPTIONAL: "+r.optional);var g,v=new c(t,n),m=[];for(g=0;g<r.optional.length;g++)m[g]=new l(v),m[g].pattern_debug=r.optional[g];for(g=0;g<r.optional.length;g++)m[g].count=m[g].count+1,p(e,r.optional[g],n,"",o,t,m[g])}return u.count--,void br.A.debug("Match ends -- success , Branch count now: "+u.count+" for "+u.pattern_debug)}var w=f.length;if(o){0;var b=function(t,i){var c=t.uri.split("#")[0];o.nowOrWhenFetched(c,void 0,function(i,c,h){i||console.log("Error following link to <"+t.uri+"> in query: "+c),p(e,r,n,s,o,a,u)})};for(d=0;d<w;d++){if(h=f[d],void 0!==n[h.subject]&&n[h.subject].uri&&o&&"unrequested"===o.getState((0,pr.docpart)(n[h.subject].uri)))return void b(n[h.subject]);if(void 0!==n[h.object]&&n[h.object].uri&&o&&"unrequested"===o.getState((0,pr.docpart)(n[h.object].uri)))return void b(n[h.object])}}y(e,r,n,s,o,a,u)},g=function(e,t){var r,n,i=!0;for(r in e)e.hasOwnProperty(r)&&t[r]&&(n=t[r].test)&&!n(e[r])&&(i=!1);return i},y=function(e,t,r,n,a,u,c){var h,l,y,v,m,w,b,_=t.statements,S=_.length;for(h=0;h<S;h++)d(e,b=_[h],r);_.sort(f),b=_[0];var E,x=e.formula();x.optional=t.optional,x.constraints=t.constraints,x.statements=_.slice(1),br.A.debug(n+"match2 searching "+b.index.length+" for "+b+"; bindings so far="+i(r));var A,F,T=b.index.length,k=0;for(E=0;E<T;E++)for(F=b.index[E],A=o([b.subject,b.predicate,b.object,b.why],[F.subject,F.predicate,F.object,F.why],r,e),br.A.info(n+" From first: "+A.length+": "+s(A)),y=A.length,l=0;l<y;l++)if(m=[],w=A[l][0],g(w,t.constraints)){for(v in w)w.hasOwnProperty(v)&&(m[v]=w[v]);for(v in r)r.hasOwnProperty(v)&&(m[v]=r[v]);c.count++,k++,p(e,x,m,n+" ",a,u,c)}else br.A.debug("Branch count CS: "+c.count);c.count--,0===k&&br.A.debug("Match2 fails completely on "+b),br.A.debug("Match2 ends, Branch count: "+c.count+" for "+c.pattern_debug),0===c.count&&(br.A.debug("Branch finished."),c.reportDone())},v=this;br.A.debug("Query on "+this.statements.length);var m=new h(t,n);m.count++,e.sync?p(v,e.pat,e.pat.initBindings,"",r,t,m):setTimeout(function(){p(v,e.pat,e.pat.initBindings,"",r,t,m)},0)}const Mr="http://www.w3.org/2002/07/owl#";function Br(e,t,r,n){var i=e.any(t,r,void 0);return!!i&&(e.equate(i,n),!0)}function Hr(e,t,r,n){var i=e.any(void 0,r,n);return!!i&&(e.equate(i,t),!0)}function qr(e,t,r,n,i){e.typeCallback&&e.typeCallback(e,n,i);var s=e.classActions[e.id(n)],o=!1;if(s)for(var a=0;a<s.length;a++)o=o||s[a](e,t,r,n,i);return o}class Kr extends Ur{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(void 0,void 0,void 0,void 0,t),(0,Yt.A)(this,"updater",void 0),(0,Yt.A)(this,"namespaces",void 0),(0,Yt.A)(this,"classActions",void 0),(0,Yt.A)(this,"propertyActions",void 0),(0,Yt.A)(this,"redirections",void 0),(0,Yt.A)(this,"aliases",void 0),(0,Yt.A)(this,"HTTPRedirects",void 0),(0,Yt.A)(this,"subjectIndex",void 0),(0,Yt.A)(this,"predicateIndex",void 0),(0,Yt.A)(this,"objectIndex",void 0),(0,Yt.A)(this,"whyIndex",void 0),(0,Yt.A)(this,"index",void 0),(0,Yt.A)(this,"features",void 0),(0,Yt.A)(this,"_universalVariables",void 0),(0,Yt.A)(this,"_existentialVariables",void 0),(0,Yt.A)(this,"rdfArrayRemove",void 0),(0,Yt.A)(this,"dataCallbacks",[]),(0,Yt.A)(this,"dataRemovalCallbacks",[]),this.propertyActions={},this.classActions={},this.redirections=[],this.aliases=[],this.HTTPRedirects=[],this.subjectIndex=[],this.predicateIndex=[],this.objectIndex=[],this.whyIndex=[],this.index=[this.subjectIndex,this.predicateIndex,this.objectIndex,this.whyIndex],this.namespaces={},this.features=e||[],this.rdfArrayRemove=t.rdfArrayRemove||Sr.RDFArrayRemove,t.dataCallback&&(this.dataCallbacks=[t.dataCallback]),t.dataRemovalCallback&&(this.dataRemovalCallbacks=[t.dataRemovalCallback]),this.initPropertyActions(this.features)}static get defaultGraphURI(){return cr}substitute(e){var t=this.statements.map(function(t){return t.substitute(e)}),r=new Kr;return r.add(t),r}addDataCallback(e){this.dataCallbacks.push(e)}addDataRemovalCallback(e){this.dataRemovalCallbacks.push(e)}applyPatch(e,t,r){var n,i=this,s=null;function o(o){if(e.delete){n=e.delete,s&&(n=n.substitute(s)),n=n.statements;var a=[],u=n.map(function(e){var r=i.statementsMatching(e.subject,e.predicate,e.object,t);return 0===r.length?(a.push(e),null):r[0]});if(a.length)return r("Could not find to delete: "+a.join("\n or "));u.map(function(e){i.remove(e)})}e.insert&&(n=e.insert,s&&(n=n.substitute(s)),(n=n.statements).map(function(e){e.graph=t,i.add(e.subject,e.predicate,e.object,e.graph)})),o()}if(e.where){var a=new Dr("patch");a.pat=e.where,a.pat.statements.map(function(e){e.graph=qi(t.value)}),a.sync=!0;var u=[];i.query(a,function(e){u.push(e)},i.fetcher,function(){return 0===u.length?r("No match found to be patched:"+e.where):u.length>1?r("Patch ambiguous. No patch done."):(s=u[0],void o(r))})}else o(r)}declareExistential(e){return this._existentialVariables||(this._existentialVariables=[]),this._existentialVariables.push(e),e}initPropertyActions(e){this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"))]=[qr],Nr(e,"sameAs")>=0&&(this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${Mr}sameAs`))]=[function(e,t,r,n,i){return e.equate(t,n),!0}]),Nr(e,"InverseFunctionalProperty")>=0&&(this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${Mr}InverseFunctionalProperty`))]=[function(e,t,r,n,i){return e.newPropertyAction(t,Hr)}]),Nr(e,"FunctionalProperty")>=0&&(this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${Mr}FunctionalProperty`))]=[function(e,t,r,n,i){return e.newPropertyAction(t,Br)}])}addStatement(e){return this.add(e.subject,e.predicate,e.object,e.graph),this.statements.length}add(e,t,r,n){var i,s,o;if(1===arguments.length){if(e instanceof Array)for(i=0;i<e.length;i++)this.add(e[i]);else(0,nr.aF)(e)?this.add(e.subject,e.predicate,e.object,e.graph):(0,nr.ok)(e)&&this.add(e.statements);return this}n||(n=this.fetcher?this.fetcher.appNode:this.rdfFactory.defaultGraph()),"string"==typeof e&&(e=this.rdfFactory.namedNode(e)),t=Or.fromValue(t);const a=Or.fromValue(r);if(n=Or.fromValue(n),!(0,nr.CZ)(e))throw new Error("Subject is not a subject type");if(!(0,nr.fY)(t))throw new Error(`Predicate ${t} is not a predicate type`);if(!(0,nr.DJ)(a))throw new Error(`Object ${a} is not an object type`);if(!(0,nr.RN)(n))throw new Error("Why is not a graph type");this.predicateCallback&&this.predicateCallback(this,t,n);var u=this.id(this.canon(t)),c=!1;if(s=this.propertyActions[u])for(i=0;i<s.length;i++)c=c||s[i](this,e,t,a,n);if(this.holds(e,t,a,n))return null;var h=[this.id(this.canon(e)),u,this.id(this.canon(a)),this.id(this.canon(n))];for(o=this.rdfFactory.quad(e,t,a,n),i=0;i<4;i++){var l=this.index[i],d=h[i];l[d]||(l[d]=[]),l[d].push(o)}this.statements.push(o);for(const e of this.dataCallbacks)e(o);return o}canon(e){if(!e)return e;const t=this.redirections[this.id(e)];if(t)return t;switch(e.termType){case er.$Q:return new tr(e.value);case er.r0:return e;case er.ic:return new hr;case er.S:case er.bD:return e;case er.QW:return new sr(e.value,e.language,e.datatype);case er.Kk:return new rr.A(e.value);case er.P2:return new gr(e.value);default:throw new Error(`Term Type not recognized for canonization: ${e.termType}`)}}check(){this.checkStatementList(this.statements);for(var e=0;e<4;e++){var t=this.index[e];for(var r in t)t.hasOwnProperty(r)&&this.checkStatementList(t[r],e)}}checkStatementList(e,t){void 0===t&&(t=0);for(var r,n=" found in "+["subject","predicate","object","why"][t]+" index.",i=0;i<e.length;i++){for(var s=[(r=e[i]).subject,r.predicate,r.object,r.graph],o=function(e,t){for(var r=0;r<e.length;r++)if(e[r].subject.equals(t.subject)&&e[r].predicate.equals(t.predicate)&&e[r].object.equals(t.object)&&e[r].why.equals(t.graph))return!0},a=0;a<4;a++){var u=this.canon(s[a]),c=this.id(u);this.index[a][c]&&o(this.index[a][c],r)}if(!o(this.statements,r))throw new Error("Statement list does not statement "+r+"@"+r.graph+n)}}close(){return this}compareTerms(e,t){return Object.prototype.hasOwnProperty.call(e,"compareTerm")?e.compareTerm(t):Qt.A[e.termType]<Qt.A[t.termType]?-1:Qt.A[e.termType]>Qt.A[t.termType]?1:e.value<t.value?-1:e.value>t.value?1:0}copyTo(e,t,r){r||(r=[]);var n=this.statementsMatching(e);-1!==Nr(r,"two-direction")&&n.concat(this.statementsMatching(void 0,void 0,e));for(var i=0;i<n.length;i++){var s=n[i];switch(s.object.termType){case"NamedNode":this.add(t,s.predicate,s.object);break;case"Literal":case"BlankNode":case"Collection":this.add(t,s.predicate,s.object.copy(this))}-1!==Nr(r,"delete")&&this.remove(s)}}equate(e,t){const r=this.canon(e),n=this.canon(t);var i=this.compareTerms(r,n);return!i||(i<0?this.replaceWith(n,r):this.replaceWith(r,n))}formula(e){return new Kr(e)}get length(){return this.statements.length}match(e,t,r,n){return this.statementsMatching(Or.fromValue(e),Or.fromValue(t),Or.fromValue(r),Or.fromValue(n))}mentionsURI(e){var t="<"+e+">";return!!this.subjectIndex[t]||!!this.objectIndex[t]||!!this.predicateIndex[t]}newExistential(e){if(!e)return this.bnode();var t=this.sym(e);return this.declareExistential(t)}newPropertyAction(e,t){var r=this.id(e);this.propertyActions[r]||(this.propertyActions[r]=[]),this.propertyActions[r].push(t);for(var n=this.statementsMatching(void 0,e,void 0),i=!1,s=0;s<n.length;s++)i=i||t(this,n[s].subject,e,n[s].object);return i}newUniversal(e){var t=this.sym(e);return this._universalVariables||(this._universalVariables=[]),this._universalVariables.push(t),t}variable(e){return new gr(e)}nextSymbol(e){for(var t=0;;t++){var r=e.value+"#n"+t;if(!this.mentionsURI(r))return this.sym(r)}}query(e,t,r,n){return jr.call(this,e,t,r,n)}querySync(e){var t=[];var r=!1;if(e.sync=!0,jr.call(this,e,function(e){t.push(e)},null,function(){r=!0}),!r)throw new Error("Sync query should have called done function");return t}remove(e){if(e instanceof Array){for(var t=0;t<e.length;t++)this.remove(e[t]);return this}if((0,nr.ok)(e))return this.remove(e.statements);var r=this.statementsMatching(e.subject,e.predicate,e.object,e.graph);if(!r.length)throw new Error("Statement to be removed is not on store: "+e);return this.removeStatement(r[0]),this}removeDocument(e){this.removeMetadata(e);for(var t=this.statementsMatching(void 0,void 0,void 0,e).slice(),r=0;r<t.length;r++)this.removeStatement(t[r]);return this.removeMatches(e,null,null),this}removeMetadata(e){const t=this.sym("chrome://TheCurrentSession"),r="http://www.w3.org/2007/ont/link#",n=this.statementsMatching(void 0,this.sym(`${r}requestedURI`),this.rdfFactory.literal(e.value),t).map(e=>e.subject);for(var i=0;i<n.length;i++){const e=n[i];if(null!=e){let n;const i=this.any(e,this.sym(`${r}status`),null,t);if(null!=i){n=this.statementsMatching(i,this.sym(`${r}status`),null,t).slice();for(var s=0;s<n.length;s++)this.removeStatement(n[s])}const o=this.any(e,this.sym(`${r}response`),null,t);if(null!=o){n=this.statementsMatching(o,null,null,t).slice();for(s=0;s<n.length;s++)this.removeStatement(n[s])}n=this.statementsMatching(e,null,null,t).slice();for(s=0;s<n.length;s++)this.removeStatement(n[s])}}return this.removeMatches(this.sym(e.value),null,null,t),this}removeMany(e,t,r,n,i){for(var s=this.statementsMatching(e,t,r,n,!1),o=[],a=0;a<s.length;a++)o.push(s[a]);for(i&&(o=o.slice(0,i)),a=0;a<o.length;a++)this.remove(o[a])}removeMatches(e,t,r,n){return this.removeMany(e,t,r,n),this}removeStatement(e){for(var t=[e.subject,e.predicate,e.object,e.graph],r=0;r<4;r++){var n=this.canon(t[r]),i=this.id(n);this.index[r][i]&&this.rdfArrayRemove(this.index[r][i],e)}this.rdfArrayRemove(this.statements,e);for(const t of this.dataRemovalCallbacks)t(e);return this}removeStatements(e){for(var t=0;t<e.length;t++)this.remove(e[t]);return this}replaceWith(e,t){for(var r=this.id(e),n=this.id(t),i=function(e){var t=e[r];if(t){var i=e[n];e[n]=i?t.concat(i):t,delete e[r]}},s=0;s<4;s++)i(this.index[s]);if(this.redirections[r]=t,e.value){if(this.aliases[n]||(this.aliases[n]=[]),this.aliases[n].push(e),this.aliases[r])for(s=0;s<this.aliases[r].length;s++)this.redirections[this.id(this.aliases[r][s])]=t,this.aliases[n].push(this.aliases[r][s]);this.add(t,this.sym("http://www.w3.org/2007/ont/link#uri"),e),this.fetcher&&this.fetcher.nowKnownAs(e,t)}return i(this.classActions),i(this.propertyActions),!0}allAliases(e){var t=this.aliases[this.id(this.canon(e))]||[];return t.push(this.canon(e)),t}sameThings(e,t){if(e.equals(t))return!0;var r=this.canon(e);if(!r)return!1;var n=this.canon(t);return!!n&&r.value===n.value}setPrefixForURI(e,t){if(("tab"!==e||!this.namespaces.tab)&&"ns"!==e.slice(0,2)&&"default"!==e.slice(0,7)){for(let e in this.namespaces)this.namespaces[e]==t&&delete this.namespaces[e];this.namespaces[e]=t}}statementsMatching(e,t,r,n,i){var s,o,a=[e,t,r,n],u=[],c=[],h=[],l=[];for(s=0;s<4;s++)u[s]=this.canon(Or.fromValue(a[s])),u[s]?(l.push(s),c[s]=this.id(u[s])):h.push(s);if(0===l.length)return this.statements;if(1===l.length)return s=l[0],(o=this.index[s][c[s]])&&i&&o.length>1&&(o=o.slice(0,1)),o=o||[];var d,f,p=1e10;for(f=0;f<l.length;f++){if(s=l[f],!(o=this.index[s][c[s]]))return[];o.length<p&&(p=o.length,d=f)}for(var g=l[d],y=this.index[g][c[g]],v=l.slice(0,d).concat(l.slice(d+1)),m=[],w=["subject","predicate","object","why"],b=0;b<y.length;b++){var _=y[b];for(f=0;f<v.length;f++)if(s=v[f],!this.canon(_[w[s]]).equals(u[s])){_=null;break}if(null!=_&&(m.push(_),i))break}return m}uris(e){var t=this.canon(e),r=this.aliases[this.id(t)];if(!t.value)return[];var n=[t.value];if(r)for(var i=0;i<r.length;i++)n.push(r[i].uri);return n}serialize(e,t,r,n){return Ir(r,this,e,t,void 0,n={...n||{},namespaces:n?.namespaces?{...this.namespaces,...n.namespaces}:{...this.namespaces}})}}(0,Yt.A)(Kr,"handleRDFType",void 0),Kr.handleRDFType=qr;const Vr=_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#");function $r(e,t){function r(n,i,s){const o=e.statementsMatching(n,Vr("rest"),null,t);if(1!==o.length)throw new Error(`Bad list structure: no rest at ${n}`);const a=e.statementsMatching(n,Vr("first"),null,t);if(1!==a.length)throw new Error(`Bad list structure: rest but ${a.length} firsts at ${n}`);const u=[a[0].object].concat(i),c=s.concat(o).concat(a),h=e.statementsMatching(null,Vr("rest"),n,t);if(0===h.length){const r=new ar(u);return e.remove(c),void function(e,t,r,n){for(const i of e.statementsMatching(r,null,null,n)){const r=new fr(t,i.predicate,i.object,n);e.remove(i),e.add(r)}for(const i of e.statementsMatching(null,r,null,n))e.remove(i),e.add(new fr(i.subject,t,i.object,n));for(const i of e.statementsMatching(null,null,r,n))e.remove(i),e.add(new fr(i.subject,i.predicate,t,n))}(e,r,n,t)}if(1!==h.length)throw new Error(`Bad list structure: ${h.length} pres at ${n}`);const l=h[0].subject;if("BlankNode"!==l.termType)throw new Error(`Bad list element node ${l} type: ${l.termType} `);r(l,u,c)}!function(e,t){const r=Vr("nil");for(const n of e.statementsMatching(r,null,null,t)){e.remove(n);const r=new ar;e.add(new fr(r,n.predicate,n.object,t))}for(const n of e.statementsMatching(null,null,r,t))if(!n.predicate.sameTerm(Vr("rest"))){e.remove(n);const r=new ar;e.add(new fr(n.subject,n.predicate,r,t))}}(e,t);e.statementsMatching(null,Vr("rest"),Vr("nil"),t).forEach(e=>{if("BlankNode"!==e.subject.termType)throw new Error(`Bad list element node ${e.subject} type: ${e.subject.termType} `);r(e.subject,[],[])})}var Wr=function(e){e=e.replace(/\r\n/g,"\n");for(var t="",r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t+=String.fromCharCode(n):n>127&&n<2048?(t+=String.fromCharCode(n>>6|192),t+=String.fromCharCode(63&n|128)):(t+=String.fromCharCode(n>>12|224),t+=String.fromCharCode(n>>6&63|128),t+=String.fromCharCode(63&n|128))}return t},Jr="http://www.w3.org/2000/10/swap/log#",zr=function(e){return e},Xr=function(e){return e},Gr=function(e){if(e.length>0)throw"missing.js: oops nnonempty dict not imp";return[]},Yr=function(e){return e.length},Qr=function(e,t,r){if(void 0===e.slice)throw"@@ mising.js: No .slice function for "+e+" of type "+typeof e;return void 0===r||null==r?e.slice(t):e.slice(t,r)},Zr=Error("dummy error stop iteration"),en=function(e){return this.last=0,this.li=e,this.next=function(){if(this.last==this.li.length)throw Zr;return this.li[this.last++]},this},tn=function(e,t){return e.indexOf(t)},rn=function(e,t){if(!e){if(t)throw"python Assertion failed: "+t;throw"(python) Assertion failed."}};String.prototype.encode=function(e){if("utf-8"!=e)throw"UTF8_converter: can only do utf-8";return Wr(this)},String.prototype.decode=function(e){if("utf-8"!=e)throw"UTF8_converter: can only do utf-8";return this};var nn=function(e,t){return pr.join(t,e)},sn="http://www.w3.org/1999/02/22-rdf-syntax-ns#nil",on="http://www.w3.org/2002/07/owl#sameAs";var an="\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~",un=an+":",cn=new RegExp("^([-+]?[0-9]+)(\\.[0-9]+)?([eE][-+]?[0-9]+)?","g"),hn=new RegExp("^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9](T[0-9][0-9]:[0-9][0-9](:[0-9][0-9](\\.[0-9]*)?)?)?Z?"),ln=new RegExp('[\\\\\\r\\n\\"]',"g"),dn=new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*","g");const fn=function(e,t,r,n,i,s,o,a){return new pn(e,t,r,n,i,s,o,a)};class pn{constructor(e,t,r,n,i,s,o,a){void 0===t&&(t=null),void 0===r&&(r=""),void 0===n&&(n=null),void 0===i&&(i=""),void 0===s&&(s=null),void 0===o&&(o=""),void 0===a&&(a=null),this._bindings=new Gr([]),this._flags=o,""!=r&&(rn(r.indexOf(":")>=0,"Document URI not absolute: "+r),this._bindings[""]=r+"#"),this._store=e,i&&e.setGenPrefix(i),this._thisDoc=r,this.source=e.sym(r),this.lines=0,this.statementCount=0,this.hasNil=!1,this.startOfLine=0,this.previousLine=0,this._genPrefix=i,this.keywords=new Xr(["a","this","bind","has","is","of","true","false"]),this.keywordsSet=0,this._anonymousNodes=new Gr([]),this._variables=new Gr([]),this._parentVariables=new Gr([]),this._reason=a,this._reason2=null,this._baseURI=n||(r||null),rn(!this._baseURI||this._baseURI.indexOf(":")>=0),this._genPrefix||(this._thisDoc?this._genPrefix=this._thisDoc+"#_g":this._genPrefix=RDFSink_uniqueURI()),null==t?this._thisDoc?this._formula=e.formula(r+"#_formula"):this._formula=e.formula():this._formula=t,this._context=this._formula,this._parentContext=null}here(e){return this._genPrefix+"_L"+this.lines+"C"+(e-this.startOfLine+1)}formula(){return this._formula}loadStream(e){return this.loadBuf(e.read())}loadBuf(e){return this.startDoc(),this.feed(e),this.endDoc()}feed(e){for(var t=e.decode("utf-8"),r=0;r>=0;){var n=this.skipSpace(t,r);if(n<0)return;if((r=this.directiveOrStatement(t,n))<0)throw yn(this._thisDoc,this.lines,t,n,"expected directive or statement")}}directiveOrStatement(e,t){var r,n=this.skipSpace(e,t);return n<0?n:(r=this.directive(e,n))>=0||(r=this.statement(e,n))>=0?this.checkDot(e,r):r}tok(e,t,r){if("@"==t.slice(r,r+1))r=r+1;else if(Nr(this.keywords,e)<0)return-1;var n=r+Yr(e);return t.slice(r,n)==e&&an.indexOf(t.charAt(n))>=0?n:-1}directive(e,t){if((s=this.skipSpace(e,t))<0)return s;var r=new Xr([]);if((s=this.tok("bind",e,t))>0)throw yn(this._thisDoc,this.lines,e,t,"keyword bind is obsolete: use @prefix");if((s=this.tok("keywords",e,t))>0){if((t=this.commaSeparatedList(e,s,r,!1))<0)throw yn(this._thisDoc,this.lines,e,t,"'@keywords' needs comma separated list of words");return this.setKeywords(Qr(r,null,null)),t}if((s=this.tok("forAll",e,t))>0){if((t=this.commaSeparatedList(e,s,r,!0))<0)throw yn(this._thisDoc,this.lines,e,t,"Bad variable list after @forAll");var n=new en(r);try{for(;;){var i=n.next();(Nr(this._variables,i)<0||Nr(this._parentVariables,i)>=0)&&(this._variables[i]=this._context.newUniversal(i))}}catch(e){if(e!=Zr)throw e}return t}if((s=this.tok("forSome",e,t))>0){if((t=this.commaSeparatedList(e,s,r,this.uri_ref2))<0)throw yn(this._thisDoc,this.lines,e,t,"Bad variable list after @forSome");n=new en(r);try{for(;;){i=n.next();this._context.declareExistential(i)}}catch(e){if(e!=Zr)throw e}return t}if((s=this.tok("prefix",e,t))>=0){var s,o=new Xr([]);if((t=this.qname(e,s,o))<0)throw yn(this._thisDoc,this.lines,e,s,"expected qname after @prefix");if((s=this.uri_ref2(e,t,o))<0)throw yn(this._thisDoc,this.lines,e,t,"expected <uriref> after @prefix _qname_");var a=o[1].uri;if(this._baseURI)a=nn(this._baseURI,a);else rn(a.indexOf(":")>=0,"With no base URI, cannot handle relative URI for NS");return rn(a.indexOf(":")>=0),this._bindings[o[0][0]]=a,this.bind(o[0][0],function(e){return encodeURI(e)}(a)),s}if((s=this.tok("base",e,t))>=0){o=new Xr([]);if((t=this.uri_ref2(e,s,o))<0)throw yn(this._thisDoc,this.lines,e,s,"expected <uri> after @base ");a=o[0].uri;if(!this._baseURI)throw yn(this._thisDoc,this.lines,e,s,"With no previous base URI, cannot use relative URI in @base <"+a+">");a=nn(this._baseURI,a);return rn(a.indexOf(":")>=0),this._baseURI=a,t}return-1}bind(e,t){""==e||this._store.setPrefixForURI(e,t)}setKeywords(e){null==e?this.keywordsSet=0:(this.keywords=e,this.keywordsSet=1)}startDoc(){}endDoc(){return this.hasNil&&this._store.rdfFactory.supports.COLLECTIONS&&$r(this._store,this.source),this._formula}makeStatement(e){e[0].add(e[2],e[1],e[3],this.source),(e[2].uri&&e[2].uri===sn||e[3].uri&&e[3].uri===sn)&&(this.hasNil=!0),this.statementCount+=1}statement(e,t){var r=new Xr([]);if((t=this.object(e,t,r))<0)return t;var n=this.property_list(e,t,r[0]);if(n<0)throw yn(this._thisDoc,this.lines,e,t,"expected propertylist");return n}subject(e,t,r){return this.item(e,t,r)}verb(e,t,r){if((i=this.skipSpace(e,t))<0)return i;var n=new Xr([]);if((i=this.tok("has",e,t))>=0){if((t=this.prop(e,i,n))<0)throw yn(this._thisDoc,this.lines,e,i,"expected property after 'has'");return r.push(new zr(["->",n[0]])),t}if((i=this.tok("is",e,t))>=0){if((t=this.prop(e,i,n))<0)throw yn(this._thisDoc,this.lines,e,i,"expected <property> after 'is'");if((i=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"End of file found, expected property after 'is'");var i;t=i;if((i=this.tok("of",e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"expected 'of' after 'is' <prop>");return r.push(new zr(["<-",n[0]])),i}if((i=this.tok("a",e,t))>=0)return r.push(new zr(["->",this._store.sym("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")])),i;if("<="==e.slice(t,t+2))return r.push(new zr(["<-",this._store.sym(Jr+"implies")])),t+2;if("="==e.slice(t,t+1))return">"==e.slice(t+1,t+2)?(r.push(new zr(["->",this._store.sym(Jr+"implies")])),t+2):(r.push(new zr(["->",this._store.sym(on)])),t+1);if(":="==e.slice(t,t+2))return r.push(new zr(["->",Jr+"becomes"])),t+2;if((i=this.prop(e,t,n))>=0)return r.push(new zr(["->",n[0]])),i;if(">-"==e.slice(t,t+2)||"<-"==e.slice(t,t+2))throw yn(this._thisDoc,this.lines,e,i,">- ... -> syntax is obsolete.");return-1}prop(e,t,r){return this.item(e,t,r)}item(e,t,r){return this.path(e,t,r)}blankNode(e){return this._context.bnode(e,this._reason2)}path(e,t,r){if((s=this.nodeOrLiteral(e,t,r))<0)return s;for(;"!^.".indexOf(e.slice(s,s+1))>=0;){var n=e.slice(s,s+1);if("."==n){var i=e.slice(s+1,s+2);if(!i||un.indexOf(i)>=0&&":?<[{(".indexOf(i)<0)break}var s,o=r.pop(),a=this.blankNode(this.here(s));if((s=this.node(e,s+1,r))<0)throw yn(this._thisDoc,this.lines,e,s,"EOF found in middle of path syntax");var u=r.pop();"^"==n?this.makeStatement(new zr([this._context,u,a,o])):this.makeStatement(new zr([this._context,u,o,a])),r.push(a)}return s}anonymousNode(e){if(t=this._anonymousNodes[e])return t;var t=this._store.bnode(e);return this._anonymousNodes[e]=t,t}node(e,t,r,n){void 0===n&&(n=null);var i=n;if((h=this.skipSpace(e,t))<0)return h;t=h;var s=e.slice(t,t+1);if("["==s){var o=this.here(t);if((h=this.skipSpace(e,t+1))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF after '['");if("="==e.slice(h,h+1)){var t=h+1,a=new Xr([]);if(!((h=this.objectList(e,t,a))>=0))throw yn(this._thisDoc,this.lines,e,t,"objectList expected after [= ");i=a[0];if(Yr(a)>1){var u=new en(a);try{for(;;){var c=u.next();this.makeStatement(new zr([this._context,this._store.sym(on),i,c]))}}catch(e){if(e!=Zr)throw e}}if((h=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF when objectList expected after [ = ");if(";"==e.slice(h,h+1))var h=h+1}if(null==i)i=this.blankNode(o);if((t=this.property_list(e,h,i))<0)throw yn(this._thisDoc,this.lines,e,h,"property_list expected");if((h=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF when ']' expected after [ <propertyList>");if("]"!=e.slice(h,h+1))throw yn(this._thisDoc,this.lines,e,h,"']' expected");return r.push(i),h+1}if("{"==s){if("$"==e.slice(t+1,t+2)){for(var h=(t+=1)+1,l=new Xr([]),d=!0;;){if((t=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"needed '$}', found end.");if("$}"==e.slice(t,t+2)){var h=t+2;break}if(d)d=!1;else{if(","!=e.slice(t,t+1))throw yn(this._thisDoc,this.lines,e,t,"expected: ','");t+=1}var f=new Xr([]);if((h=this.item(e,t,f))<0)throw yn(this._thisDoc,this.lines,e,t,"expected item in set or '$}'");l.push(f[0])}return r.push(this._store.newSet(l,this._context)),h}var h=t+1,p=this._parentContext;this._parentContext=this._context;var g=this._anonymousNodes,y=this._parentVariables;this._parentVariables=this._variables,this._anonymousNodes=new Gr([]),this._variables=this._variables.slice();var v=this._reason2;if(this._reason2=null,null==i)i=this._store.formula();for(this._context=i;;){if((t=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"needed '}', found end.");if("}"==e.slice(t,t+1)){var h=t+1;break}if((h=this.directiveOrStatement(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"expected statement or '}'")}return this._anonymousNodes=g,this._variables=this._parentVariables,this._parentVariables=y,this._context=this._parentContext,this._reason2=v,this._parentContext=p,r.push(i.close()),h}if("("==s){var m=this._store.list;if("$"==e.slice(t+1,t+2)){m=this._store.newSet;t+=1}for(h=t+1,l=new Xr([]);;){if((t=this.skipSpace(e,h))<0)throw yn(this._thisDoc,this.lines,e,t,"needed ')', found end.");if(")"==e.slice(t,t+1)){h=t+1;break}f=new Xr([]);if((h=this.item(e,t,f))<0)throw yn(this._thisDoc,this.lines,e,t,"expected item in list or ')'");l.push(f[0])}return r.push(m(l,this._context)),h}if((h=this.tok("this",e,t))>=0)throw yn(this._thisDoc,this.lines,e,t,"Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords.");if((h=this.tok("true",e,t))>=0)return r.push(!0),h;if((h=this.tok("false",e,t))>=0)return r.push(!1),h;if(null==i&&(h=this.uri_ref2(e,t,r))>=0)return h;return-1}property_list(e,t,r){for(;;){if((h=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,t,"EOF found when expected verb in property list");if(":-"!=e.slice(h,h+2)){t=h;var n=new Xr([]);if((h=this.verb(e,t,n))<=0)return t;var i=new Xr([]);if((t=this.objectList(e,h,i))<0)throw yn(this._thisDoc,this.lines,e,h,"objectList expected");var s=new en(i);try{for(;;){var o=s.next(),a=n[0],u=a[0],c=a[1];"->"==u?this.makeStatement(new zr([this._context,c,r,o])):this.makeStatement(new zr([this._context,c,o,r]))}}catch(e){if(e!=Zr)throw e}if((h=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,h,"EOF found in list of objects");if(";"!=e.slice(t,t+1))return t;t=t+1}else{var h,t=h+2,l=new Xr([]);if((h=this.node(e,t,l,r))<0)throw yn(this._thisDoc,this.lines,e,t,"bad {} or () or [] node after :- ");var t=h}}}commaSeparatedList(e,t,r,n){if((i=this.skipSpace(e,t))<0)throw yn(this._thisDoc,this.lines,e,i,"EOF found expecting comma sep list");if("."==e.charAt(i))return t;if(n)var i=this.uri_ref2(e,i,r);else i=this.bareWord(e,i,r);if(i<0)return-1;for(;;){if((t=this.skipSpace(e,i))<0)return t;var s=e.slice(t,t+1);if(","!=s)return"."!=s?-1:t;if(n)i=this.uri_ref2(e,t+1,r);else i=this.bareWord(e,t+1,r);if(i<0)throw yn(this._thisDoc,this.lines,e,i,"bad list content")}}objectList(e,t,r){if((t=this.object(e,t,r))<0)return-1;for(;;){var n=this.skipSpace(e,t);if(n<0)throw yn(this._thisDoc,this.lines,e,n,"EOF found after object");if(","!=e.slice(n,n+1))return n;if((t=this.object(e,n+1,r))<0)return t}}checkDot(e,t){var r=this.skipSpace(e,t);if(r<0)return r;if("."==e.slice(r,r+1))return r+1;if("}"==e.slice(r,r+1))return r;if("]"==e.slice(r,r+1))return r;throw yn(this._thisDoc,this.lines,e,r,"expected '.' or '}' or ']' at end of statement")}uri_ref2(e,t,r){var n=new Xr([]);if((d=this.qname(e,t,n))>=0){var i=n[0],s=i[0],o=i[1];if(null==s){rn(0,"not used?");var a=this._baseURI+"#"}else{if(!(a=this._bindings[s])){if("_"==s)return r.push(this.anonymousNode(o)),d;throw yn(this._thisDoc,this.lines,e,t,"Prefix "+s+" not bound.")}}var u=this._store.sym(a+o);return Nr(this._variables,u)>=0?r.push(this._variables[u]):r.push(u),d}if((t=this.skipSpace(e,t))<0)return-1;if("?"==e.charAt(t)){var c=new Xr([]);return(d=this.variable(e,t,c))>0?(r.push(c[0]),d):-1}if("<"==e.charAt(t)){for(var h=t=t+1;t<Yr(e);){if(">"==e.charAt(t)){var l=e.slice(h,t);if(this._baseURI)l=nn(this._baseURI,l);else rn(l.indexOf(":")>=0,"With no base URI, cannot deal with relative URIs");if("#"==e.slice(t-1,t)&&"#"!=Qr(l,-1,null))l=l+"#";u=this._store.sym(l);return Nr(this._variables,u)>=0?r.push(this._variables[u]):r.push(u),t+1}t=t+1}throw yn(this._thisDoc,this.lines,e,d,"unterminated URI reference")}if(this.keywordsSet){var d;c=new Xr([]);if((d=this.bareWord(e,t,c))<0)return-1;if(Nr(this.keywords,c[0])>=0)throw yn(this._thisDoc,this.lines,e,t,'Keyword "'+c[0]+'" not allowed here.');return r.push(this._store.sym(this._bindings[""]+c[0])),d}return-1}skipSpace(e,t){for(var r=t||0;r<e.length;r++){var n=e.charAt(r);if(" \n\r\t\f\v            ​\u2028\u2029 ".indexOf(n)<0){if("#"!==e.charAt(r))return r;for(;;r++){if(r===e.length)return-1;if("\n"===e.charAt(r)){this.lines=this.lines+1;break}}}else"\n"===e.charAt(r)&&(this.lines=this.lines+1)}return-1}variable(e,t,r){if((n=this.skipSpace(e,t))<0)return-1;if("?"!=e.slice(n,n+1))return-1;var n;t=n+=1;if("0123456789-".indexOf(e.charAt(n))>=0)throw yn(this._thisDoc,this.lines,e,n,"Varible name can't start with '"+e.charAt(n)+"s'");for(;t<Yr(e)&&un.indexOf(e.charAt(t))<0;)t=t+1;if(null==this._parentContext)throw yn(this._thisDoc,this.lines,e,n,"Can't use ?xxx syntax for variable in outermost level: "+e.slice(n-1,t));return r.push(this._store.variable(e.slice(n,t))),t}bareWord(e,t,r){var n=this.skipSpace(e,t);if(n<0)return-1;var i=e.charAt(n);if("0123456789-".indexOf(i)>=0)return-1;if(un.indexOf(i)>=0)return-1;for(t=n;t<Yr(e)&&un.indexOf(e.charAt(t))<0;)t=t+1;return r.push(e.slice(n,t)),t}qname(e,t,r){if((t=this.skipSpace(e,t))<0)return-1;var n=e.charAt(t);if("0123456789-+".indexOf(n)>=0)return-1;if(un.indexOf(n)<0){var i=n;for(t=t+1;t<Yr(e);){n=e.charAt(t);if(!(un.indexOf(n)<0))break;i=i+n,t=t+1}}else i="";if(t<Yr(e)&&":"==e.charAt(t)){var s=i;for(t=t+1,i="";t<Yr(e);){n=e.charAt(t);if(!(un.indexOf(n)<0))break;i=i+n,t=t+1}return r.push(new zr([s,i])),t}return i&&this.keywordsSet&&Nr(this.keywords,i)<0?(r.push(new zr(["",i])),t):-1}object(e,t,r){if((s=this.subject(e,t,r))>=0)return s;{if((s=this.skipSpace(e,t))<0)return-1;t=s;var n=null;let a=e.charAt(t);if('"'==a||"'"==a){n=e.slice(t,t+3==a+a)?a+a+a:a;t=t+Yr(n);var i=this.strconst(e,t,n),s=i[0],o=i[1];return r.push(this._store.literal(o)),s}return-1}}nodeOrLiteral(e,t,r){if((u=this.node(e,t,r))>=0)return u;if((u=this.skipSpace(e,t))<0)return-1;t=u;var n=e.charAt(t);if("-+0987654321".indexOf(n)>=0){if(hn.lastIndex=0,null!=(l=hn.exec(e.slice(t)))){u=t+(i=l[0]).length,i.indexOf("T")>=0?r.push(this._store.literal(i,this._store.sym("http://www.w3.org/2001/XMLSchema#dateTime"))):r.push(this._store.literal(i,this._store.sym("http://www.w3.org/2001/XMLSchema#date")))}else{var i;if(cn.lastIndex=0,null==(l=cn.exec(e.slice(t))))throw yn(this._thisDoc,this.lines,e,t,"Bad number or date syntax");u=t+cn.lastIndex,(i=e.slice(t,u)).indexOf("e")>=0?r.push(this._store.literal(parseFloat(i),this._store.sym("http://www.w3.org/2001/XMLSchema#double"))):e.slice(t,u).indexOf(".")>=0?r.push(this._store.literal(parseFloat(i),this._store.sym("http://www.w3.org/2001/XMLSchema#decimal"))):r.push(this._store.literal(parseInt(i),this._store.sym("http://www.w3.org/2001/XMLSchema#integer")))}return u}if('"'==e.charAt(t)){if('"""'==e.slice(t,t+3))var s='"""';else s='"';t=t+Yr(s);var o=null,a=this.strconst(e,t,s),u=a[0],c=a[1],h=null;if("@"==e.slice(u,u+1)){var l;if(dn.lastIndex=0,null==(l=dn.exec(e.slice(u+1))))throw yn(this._thisDoc,startline,e,t,"Bad language code syntax on string literal, after @");t=dn.lastIndex+u+1,h=e.slice(u+1,t),u=t}if("^^"==e.slice(u,u+2)){var d=new Xr([]);u=this.uri_ref2(e,u+2,d),o=d[0]}return r.push(this._store.literal(c,h||o)),u}return-1}strconst(e,t,r){for(var n=t,i="",s=this.lines;n<Yr(e);){t=n+Yr(r);if(e.slice(n,t)==r)return new zr([t,i]);if('"'!=e.charAt(n)){if(ln.lastIndex=0,!ln.exec(e.slice(n)))throw yn(this._thisDoc,s,e,n,"Closing quote missing in string at ^ in "+e.slice(n-20,n)+"^"+e.slice(n,n+20));t=n+ln.lastIndex-1,i=i+e.slice(n,t);if('"'!=(u=e.charAt(t)))if("\r"!=u){if("\n"==u){if('"'==r)throw yn(this._thisDoc,s,e,t,"newline found in string literal");this.lines=this.lines+1;i=i+u,n=t+1;this.previousLine=this.startOfLine,this.startOfLine=n}else if("\\"==u){n=t+1;if(!(u=e.slice(n,n+1)))throw yn(this._thisDoc,s,e,t,"unterminated string literal (2)");var o=tn('abfrtvn\\"',u);if(o>=0)i=i+'a\b\f\r\t\v\n\\"'.charAt(o),n=n+1;else if("u"==u)n=(a=this.uEscape(e,n+1,s))[0],i=i+(u=a[1]);else{if("U"!=u)throw yn(this._thisDoc,this.lines,e,t,"bad escape");var a,u;n=(a=this.UEscape(e,n+1,s))[0],i=i+(u=a[1])}}}else var n=t+1;else var n=t}else var i=i+'"',n=n+1}throw yn(this._thisDoc,this.lines,e,t,"unterminated string literal")}uEscape(e,t,r){for(var n=t,i=0,s=0;i<4;){var o=e.slice(n,n+1).toLowerCase();n=n+1;if(""==o)throw yn(this._thisDoc,r,e,t,"unterminated string literal(3)");var a=tn("0123456789abcdef",o);if(a<0)throw yn(this._thisDoc,r,e,t,"bad string literal hex escape");s=16*s+a,i=i+1}var u=String.fromCharCode(s);return new zr([n,u])}UEscape(e,t,r){for(var n=t,i=0,s="\\U";i<8;){var o=e.slice(n,n+1).toLowerCase();n=n+1;if(""==o)throw yn(this._thisDoc,r,e,t,"unterminated string literal(3)");if(tn("0123456789abcdef",o)<0)throw yn(this._thisDoc,r,e,t,"bad string literal hex escape");s=s+o,i=i+1}var a,u=(a="0x"+Qr(s,2,10)-0,String.fromCharCode(a));return new zr([n,u])}}function gn(e,t,r,n,i){this._str=r.encode("utf-8"),this._str=r,this._i=n,this._why=i,this.lines=t,this._uri=e}function yn(e,t,r,n,i){let s=t+1,o="Line "+s+" of <"+e+">: Bad syntax: "+i+'\nat: "'+r.slice(n,n+30)+'"',a=new SyntaxError(o,e,s);return a.lineNo=s,a.characterInFile=n,a.syntaxProblem=i,a}gn.prototype.toString=function(){var e=this._str,t=this._i,r=0;if(t>60){var n="...";r=t-60}else n="";if(Yr(e)-t>60)var i="...";else i="";return'Line %i of <%s>: Bad syntax (%s) at ^ in:\n"%s%s^%s%s"'%new zr([this.lines+1,this._uri,this._why,n,e.slice(r,t),e.slice(t,t+60),i])};const vn={...wr,supports:{[yr.collections]:!0,[yr.defaultGraphType]:!1,[yr.equalsMethod]:!0,[yr.identity]:!1,[yr.id]:!0,[yr.reversibleId]:!1,[yr.variableType]:!0},collection:e=>new ar(e),id(e){return(0,nr.P3)(e)?`( ${e.elements.map(e=>this.id(e)).join(", ")} )`:(0,nr.DZ)(e)?gr.toString(e):wr.id(e)},termToNQ:e=>e.termType===er.r0?ar.toNT(e):wr.termToNQ(e)},mn=vn;function wn(e,t){return"string"==typeof t?e.rdfFactory.literal(t):Object.prototype.hasOwnProperty.call(t,"@list")?!0===e.rdfFactory.supports.COLLECTIONS?function(e,t){if(!Array.isArray(t))throw new TypeError("Object must be an array");return e.rdfFactory.collection(t.map(t=>wn(e,t)))}(e,t["@list"]):function(e,t){const r=t["@id"]?_n(e,t):e.rdfFactory.blankNode(),n=t["@list"].map(t=>wn(e,t)),i=Pr(e.rdfFactory,r,n);return e.addAll(i),r}(e,t):Object.prototype.hasOwnProperty.call(t,"@id")?_n(e,t):Object.prototype.hasOwnProperty.call(t,"@language")?e.rdfFactory.literal(t["@value"],t["@language"]):Object.prototype.hasOwnProperty.call(t,"@type")?e.rdfFactory.literal(t["@value"],e.rdfFactory.namedNode(t["@type"])):Object.prototype.hasOwnProperty.call(t,"@value")?e.rdfFactory.literal(t["@value"]):e.rdfFactory.literal(t)}async function bn(e,t,r){const n=r&&Object.prototype.hasOwnProperty.call(r,"termType")?r.value:r,i=await Promise.all([a.e(841),a.e(789)]).then(a.t.bind(a,4841,23));return(await i.default.flatten(JSON.parse(e),null,{base:n})).reduce((e,t)=>Sn(e,r,t),t)}function _n(e,t){return t["@id"].startsWith("_:")?e.rdfFactory.blankNode(t["@id"].substring(2)):e.rdfFactory.namedNode(t["@id"])}function Sn(e,t,r){const n=r["@id"]?_n(e,r):e.rdfFactory.blankNode();for(const i of Object.keys(r)){if("@id"===i)continue;if("@graph"==i){const t=n,s=r[i];for(let r=0;r<s.length;r++)e=Sn(e,t,s[r])}const s=r[i];if(Array.isArray(s))for(let r=0;r<s.length;r++)e.addStatement(En(e,n,i,s[r],t));else e.addStatement(En(e,n,i,s,t))}return e}function En(e,t,r,n,i){let s,o;return"@type"===r?(s=e.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),o=e.rdfFactory.namedNode(n)):(s=e.rdfFactory.namedNode(r),o=wn(e,n)),e.rdfFactory.quad(t,s,o,e.rdfFactory.namedNode(i))}var xn=a(8287);const An="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Fn="http://www.w3.org/2001/XMLSchema#",Tn="http://www.w3.org/2000/10/swap/",kn={xsd:{decimal:`${Fn}decimal`,boolean:`${Fn}boolean`,double:`${Fn}double`,integer:`${Fn}integer`,string:`${Fn}string`},rdf:{type:`${An}type`,nil:`${An}nil`,first:`${An}first`,rest:`${An}rest`,langString:`${An}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${Tn}reify#forSome`,forAll:`${Tn}reify#forAll`},log:{implies:`${Tn}log#implies`,isImpliedBy:`${Tn}log#isImpliedBy`}},{xsd:In}=kn,Cn=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,Rn={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},Pn=/[\x00-\x20<>\\"\{\}\|\^\`]/,Nn={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},Un=/$0^/;class On{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const e in this)!(e in Nn)&&this[e]instanceof RegExp&&(this[e]=Un)}else this._n3Mode=!1!==e.n3;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let r=this._input,n=r.length;for(;;){let e,o;for(;e=this._newline.exec(r);)this.comments&&(o=this._comment.exec(e[0]))&&i("comment",o[1],"",this._line,e[0].length),r=r.substr(e[0].length,r.length),n=r.length,this._line++;if(!e&&(e=this._whitespace.exec(r))&&(r=r.substr(e[0].length,r.length)),this._endOfFile.test(r))return t&&(this.comments&&(o=this._comment.exec(r))&&i("comment",o[1],"",this._line,r.length),r=null,i("eof","","",this._line,0)),this._input=r;const a=this._line,u=r[0];let c="",h="",l="",d=null,f=0,p=!1;switch(u){case"^":if(r.length<3)break;if("^"!==r[1]){this._n3Mode&&(f=1,c="^");break}if(this._previousMarker="^^",r=r.substr(2),"<"!==r[0]){p=!0;break}case"<":if(d=this._unescapedIri.exec(r))c="IRI",h=d[1];else if(d=this._iri.exec(r)){if(h=this._unescape(d[1]),null===h||Pn.test(h))return s(this);c="IRI"}else r.length>1&&"<"===r[1]?(c="<<",f=2):this._n3Mode&&r.length>1&&"="===r[1]&&(f=2,this._isImpliedBy?(c="abbreviation",h="<"):(c="inverse",h=">"));break;case">":r.length>1&&">"===r[1]&&(c=">>",f=2);break;case"_":((d=this._blank.exec(r))||t&&(d=this._blank.exec(`${r} `)))&&(c="blank",l="_",h=d[1]);break;case'"':if(d=this._simpleQuotedString.exec(r))h=d[1];else if(({value:h,matchLength:f}=this._parseLiteral(r)),null===h)return s(this);null===d&&0===f||(c="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(d=this._simpleApostropheString.exec(r))h=d[1];else if(({value:h,matchLength:f}=this._parseLiteral(r)),null===h)return s(this);null===d&&0===f||(c="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(d=this._variable.exec(r))&&(c="var",h=d[0]);break;case"@":"literal"===this._previousMarker&&(d=this._langcode.exec(r))?(c="langcode",h=d[1]):(d=this._keyword.exec(r))&&(c=d[0]);break;case".":if(1===r.length?t:r[1]<"0"||r[1]>"9"){c=".",f=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(d=this._number.exec(r)||t&&(d=this._number.exec(`${r} `)))&&(c="literal",h=d[0],l="string"==typeof d[1]?In.double:"string"==typeof d[2]?In.decimal:In.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(d=this._sparqlKeyword.exec(r))?c=d[0].toUpperCase():p=!0;break;case"f":case"t":(d=this._boolean.exec(r))?(c="literal",h=d[0],l=In.boolean):p=!0;break;case"a":(d=this._shortPredicates.exec(r))?(c="abbreviation",h="a"):p=!0;break;case"=":this._n3Mode&&r.length>1&&(c="abbreviation",">"!==r[1]?(f=1,h="="):(f=2,h=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(f=1,c=u);break;case"{":!this._lineMode&&r.length>=2&&("|"===r[1]?(c="{|",f=2):(c=u,f=1));break;case"|":r.length>=2&&"}"===r[1]&&(c="|}",f=2);break;default:p=!0}if(p&&("@prefix"!==this._previousMarker&&"PREFIX"!==this._previousMarker||!(d=this._prefix.exec(r))?((d=this._prefixed.exec(r))||t&&(d=this._prefixed.exec(`${r} `)))&&(c="prefixed",l=d[1]||"",h=this._unescape(d[2])):(c="prefix",h=d[1]||"")),"^^"===this._previousMarker)switch(c){case"prefixed":c="type";break;case"IRI":c="typeIRI";break;default:c=""}if(!c)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?s(this):this._input=r;const g=f||d[0].length,y=i(c,h,l,a,g);this.previousToken=y,this._previousMarker=c,r=r.substr(g,r.length)}function i(t,i,s,o,a){const u=r?n-r.length:n,c={type:t,value:i,prefix:s,line:o,start:u,end:u+a};return e(null,c),c}function s(t){e(t._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(Cn,(e,r,n,i)=>{if("string"==typeof r)return String.fromCharCode(Number.parseInt(r,16));if("string"==typeof n){let e=Number.parseInt(n,16);return e<=65535?String.fromCharCode(Number.parseInt(n,16)):String.fromCharCode(55296+((e-=65536)>>10),56320+(1023&e))}return i in Rn?Rn[i]:(t=!0,"")});return t?null:r}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],r=t.length;let n=Math.max(this._literalClosingPos,r);for(;(n=e.indexOf(t,n))>0;){let t=0;for(;"\\"===e[n-t-1];)t++;if(t%2==0){const t=e.substring(r,n),i=t.split(/\r\n|\r|\n/).length-1,s=n+r;if(1===r&&0!==i||3===r&&this._lineMode)break;return this._line+=i,{value:this._unescape(t),matchLength:s}}n++}this._literalClosingPos=e.length-r+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\ufeff")?e.substr(1):e}tokenize(e,t){if(this._line=1,"string"==typeof e){if(this._input=this._readStartingBom(e),"function"!=typeof t){const e=[];let t;if(this._tokenizeToEnd((r,n)=>r?t=r:e.push(n),!0),t)throw t;return e}queueMicrotask(()=>this._tokenizeToEnd(t,!0))}else this._pendingBuffer=null,"function"==typeof e.setEncoding&&e.setEncoding("utf8"),e.on("data",e=>{null!==this._input&&0!==e.length&&(this._pendingBuffer&&(e=xn.hp.concat([this._pendingBuffer,e]),this._pendingBuffer=null),128&e[e.length-1]?this._pendingBuffer=e:(void 0===this._input?this._input=this._readStartingBom("string"==typeof e?e:e.toString()):this._input+=e,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{"string"==typeof this._input&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf:Ln,xsd:Dn}=kn;let jn,Mn=0;const Bn={namedNode:zn,blankNode:Xn,variable:Yn,literal:Gn,defaultGraph:function(){return jn},quad:Qn,triple:Qn,fromTerm:Zn,fromQuad:ei},Hn=Bn;class qn{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof qn?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class Kn extends qn{get termType(){return"NamedNode"}}class Vn extends qn{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t<e.length&&"@"===e[t++]?e.substr(t).toLowerCase():""}get datatype(){return new Kn(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,r=t<e.length?e[t]:"";return"^"===r?e.substr(t+2):"@"!==r?Dn.string:Ln.langString}equals(e){return e instanceof Vn?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class $n extends qn{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Wn extends qn{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}jn=new class extends qn{constructor(){return super(""),jn||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};class Jn extends qn{constructor(e,t,r,n){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=n||jn}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}}function zn(e){return new Kn(e)}function Xn(e){return new $n(e||"n3-"+Mn++)}function Gn(e,t){if("string"==typeof t)return new Vn(`"${e}"@${t.toLowerCase()}`);let r=t?t.value:"";return""===r&&("boolean"==typeof e?r=Dn.boolean:"number"==typeof e&&(Number.isFinite(e)?r=Number.isInteger(e)?Dn.integer:Dn.double:(r=Dn.double,Number.isNaN(e)||(e=e>0?"INF":"-INF")))),""===r||r===Dn.string?new Vn(`"${e}"`):new Vn(`"${e}"^^${r}`)}function Yn(e){return new Wn(e)}function Qn(e,t,r,n){return new Jn(e,t,r,n)}function Zn(e){if(e instanceof qn)return e;switch(e.termType){case"NamedNode":return zn(e.value);case"BlankNode":return Xn(e.value);case"Variable":return Yn(e.value);case"DefaultGraph":return jn;case"Literal":return Gn(e.value,e.language||e.datatype);case"Quad":return ei(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function ei(e){if(e instanceof Jn)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return Qn(Zn(e.subject),Zn(e.predicate),Zn(e.object),Zn(e.graph))}let ti=0;class ri{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&ii(this,e.factory);const t="string"==typeof e.format?e.format.match(/\w*$/)[0].toLowerCase():"",r=/turtle/.test(t),n=/trig/.test(t),i=/triple/.test(t),s=/quad/.test(t),o=this._n3Mode=/n3/.test(t),a=i||s;(this._supportsNamedGraphs=!(r||o))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||n||i||o),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=""===t||/star|\*$/.test(t),a&&(this._resolveRelativeIRI=e=>null),this._blankNodePrefix="string"!=typeof e.blankNodePrefix?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new On({lineMode:a,n3:o,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){ti=0}_setBase(e){if(e){const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}else this._base="",this._basePath=""}_saveContext(e,t,r,n,i){const s=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:n,object:i,graph:t,inverse:!!s&&this._inversePredicate,blankPrefix:s?this._prefixes._:"",quantified:s?this._quantified:null}),s&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const r=this._contextStack.pop();if(!r||r.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=r.subject,this._predicate=r.predicate,this._object=r.object,this._graph=r.graph,this._n3Mode&&(this._inversePredicate=r.inverse,this._prefixes._=r.blankPrefix,this._quantified=r.quantified)}_readInTopContext(e){switch(e.type){case"eof":return null!==this._graph?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let r;switch(e.type){case"IRI":case"typeIRI":const t=this._resolveIRI(e.value);if(null===t)return this._error("Invalid IRI",e);r=this._factory.namedNode(t);break;case"type":case"prefixed":const n=this._prefixes[e.prefix];if(void 0===n)return this._error(`Undefined prefix "${e.prefix}:"`,e);r=this._factory.namedNode(n+e.value);break;case"blank":r=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":r=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&r.id in this._quantified&&(r=this._quantified[r.id]),r}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(0===e.prefix.length)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if(void 0===(this._subject=this._readEntity(e)))return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return null===this._predicate?this._error(`Unexpected ${t}`,e):(this._subject=null,"]"===t?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return null!==this._predicate?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if(void 0===(this._predicate=this._readEntity(e)))return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(0===e.prefix.length)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if(void 0===(this._object=this._readEntity(e)))return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return"{"===e.type?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return"{"!==e.type?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return"]"===e.type?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if("]"!==e.type)return this._readBlankNodePunctuation(e);null!==this._subject&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=null===this._predicate;return this._restoreContext("blank",e),null!==this._object?this._getContextEndReader():null!==this._predicate?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,r=null,n=this._readListItem;const i=this._subject,s=this._contextStack,o=s[s.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),n=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),0!==s.length&&"list"===s[s.length-1].type&&this._emit(this._subject,this._predicate,this._object,this._graph),null===this._predicate){if(n=this._readPredicate,this._subject===this.RDF_NIL)return n}else if(n=this._getContextEndReader(),this._object===this.RDF_NIL)return n;r=this.RDF_NIL;break;case"literal":0===e.prefix.length?(this._literalValue=e.value,n=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),n=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if(void 0===(t=this._readEntity(e)))return}if(null===r&&(this._subject=r=this._factory.blankNode()),null===i?null===o.predicate?o.subject=r:o.object=r:this._emit(i,this.RDF_REST,r,this._graph),null!==t){if(this._n3Mode&&("IRI"===e.type||"prefixed"===e.type))return this._saveContext("item",this._graph,r,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(r,this.RDF_FIRST,t,this._graph)}return n}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const r=this._readEntity(e);if(void 0===r)return;t=this._factory.literal(this._literalValue,r),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const r=this._completeLiteral(e);if(r)return this._object=r.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),null===r.token?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(r.token))}_readFormulaTail(e){return"}"!==e.type?this._readPunctuation(e):(null!==this._subject&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),null===this._object?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,r=this._graph;const n=this._subject,i=this._inversePredicate;switch(e.type){case"}":if(null===this._graph)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,i&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const s=this._predicate,o=this._object;this._subject=this._factory.quad(n,s,o,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if("Quad"!==this._subject.termType)return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&null===this._graph&&void 0!==(r=this._readEntity(e))){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(null!==n){const e=this._predicate,t=this._object;i?this._emit(t,e,n,r):this._emit(n,e,t,r)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return"."!==e.type?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return"prefix"!==e.type?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if("IRI"!==e.type)return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t="IRI"===e.type&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return"]"!==e.type?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):"."!==e.type?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if(void 0!==(t=this._readEntity(e,!0)))break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(null===this._subject?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return","===e.type?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,r=t.length&&t[t.length-1];if(r&&"item"===r.type){const t=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,t,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,r;const n=this._factory.blankNode();if(void 0!==(r=this._readEntity(e)))return null===this._predicate?(t=this._subject,this._subject=n):(t=this._object,this._object=n),this._emit(t,r,n,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let r,n;if(void 0!==(r=this._readEntity(e)))return null===this._predicate?(n=this._subject,this._subject=t):(n=this._object,this._object=t),this._emit(t,r,n,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return">>"!==e.type?this._supportsQuads&&null===this._graph&&void 0!==(this._graph=this._readEntity(e))?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(">>"!==e.type)return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),null===this._subject?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,r,n){this._callback(null,this._factory.quad(e,t,r,n||this.DEFAULTGRAPH))}_error(e,t){const r=new Error(`${e} on line ${t.line}.`);r.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(r),this._callback=ni}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return("/"===e[1]?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let r="",n=-1,i=-1,s=0,o="/";for(;n<t;){switch(o){case":":if(i<0&&"/"===e[++n]&&"/"===e[++n])for(;(i=n+1)<t&&"/"!==e[i];)n=i;break;case"?":case"#":n=t;break;case"/":if("."===e[n+1])switch(o=e[1+ ++n],o){case"/":r+=e.substring(s,n-1),s=n+1;break;case void 0:case"?":case"#":return r+e.substring(s,n)+e.substr(n+1);case".":if(o=e[1+ ++n],void 0===o||"/"===o||"?"===o||"#"===o){if(r+=e.substring(s,n-2),(s=r.lastIndexOf("/"))>=i&&(r=r.substr(0,s)),"/"!==o)return`${r}/${e.substr(n+1)}`;s=n+1}}}o=e[++n]}return r+e.substring(s)}parse(e,t,r){let n,i,s;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(n=t.onQuad,i=t.onPrefix,s=t.onComment):(n=t,i=r),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${ti++}_`,this._prefixCallback=i||ni,this._inversePredicate=!1,this._quantified=Object.create(null),!n){const t=[];let r;if(this._callback=(e,n)=>{e?r=e:n&&t.push(n)},this._lexer.tokenize(e).every(e=>this._readCallback=this._readCallback(e)),r)throw r;return t}let o=(e,t)=>{null!==e?(this._callback(e),this._callback=ni):this._readCallback&&(this._readCallback=this._readCallback(t))};s&&(this._lexer.comments=!0,o=(e,t)=>{null!==e?(this._callback(e),this._callback=ni):this._readCallback&&("comment"===t.type?s(t.value):this._readCallback=this._readCallback(t))}),this._callback=n,this._lexer.tokenize(e,o)}}function ni(){}function ii(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(kn.rdf.first),e.RDF_REST=t.namedNode(kn.rdf.rest),e.RDF_NIL=t.namedNode(kn.rdf.nil),e.N3_FORALL=t.namedNode(kn.r.forAll),e.N3_FORSOME=t.namedNode(kn.r.forSome),e.ABBREVIATIONS={a:t.namedNode(kn.rdf.type),"=":t.namedNode(kn.owl.sameAs),">":t.namedNode(kn.log.implies),"<":t.namedNode(kn.log.isImpliedBy)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}if(ii(ri.prototype,Hn),void 0===si)var si={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};class oi{constructor(e,t){this.options=t||{},this.kb=e,this.target=t.target||{graph:{subjects:{},prefixes:{},terms:{}}},this.blankNodes=[],this.htmlOptions={selfClosing:"br img input area base basefont col colgroup source wbr isindex link meta param hr"},this.theOne="_:"+(new Date).getTime(),this.language=null,this.vocabulary=null,this.blankCounter=0,this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"}],this.inXHTMLMode=!1,this.absURIRE=/[\w\_\-]+:\S+/,this.finishedHandlers=[],this.init()}addTriple(e,t,r,n){var i,s,o,a;i=void 0===t?wr.namedNode(this.options.base):this.toRDFNodeObject(t),o=this.toRDFNodeObject(r),s=this.toRDFNodeObject(n),a=wr.namedNode(this.options.base),this.kb.add(i,o,s,a)}ancestorPath(e){for(var t="";e&&e.nodeType!==si.DOCUMENT_NODE;)t="/"+e.localName+t,e=e.parentNode;return t}copyMappings(e){var t={};for(var r in e)t[r]=e[r];return t}copyProperties(){}deriveDateTimeType(e){for(var t=0;t<oi.dateTimeTypes.length;t++){var r=oi.dateTimeTypes[t].pattern.exec(e);if(r&&r[0].length===e.length)return oi.dateTimeTypes[t].type}return null}init(){}newBlankNode(){return this.blankCounter++,"_:"+this.blankCounter}newSubjectOrigin(e,t){}parseCURIE(e,t,r){var n,i=e.indexOf(":");if(i>=0){var s=e.substring(0,i);if(""===s)return(n=t[""])?n+e.substring(i+1):null;if("_"===s)return"_:"+e.substring(i+1);if(oi.NCNAME.test(s)&&(n=t[s]))return n+e.substring(i+1)}return null}parseCURIEOrURI(e,t,r){var n=this.parseCURIE(e,t,r);return n||this.resolveAndNormalize(r,e)}parsePredicate(e,t,r,n,i,s){if(""===e)return null;var o=this.parseTermOrCURIEOrAbsURI(e,t,s?null:r,n,i);return o&&0===o.indexOf("_:")?null:o}parsePrefixMappings(e,t){for(var r=this.tokenize(e),n=null,i=0;i<r.length;i++)":"===r[i][r[i].length-1]?n=r[i].substring(0,r[i].length-1):n&&(t[n]=this.options.base?pr.join(r[i],this.options.base):r[i],n=null)}static parseRDFaDOM(e,t,r){var n=new oi(t,{base:r});e.baseURI||(e.baseURI=r),n.process(e,{baseURI:r})}parseSafeCURIEOrCURIEOrURI(e,t,r){return"["===(e=this.trim(e)).charAt(0)&&"]"===e.charAt(e.length-1)?0===(e=(e=e.substring(1,e.length-1)).trim(e)).length?null:"_:"===e?this.theOne:this.parseCURIE(e,t,r):this.parseCURIEOrURI(e,t,r)}parseTermOrCURIEOrAbsURI(e,t,r,n,i){e=this.trim(e);var s=this.parseCURIE(e,n,i);if(s)return s;if(r){if(t&&!this.absURIRE.exec(e))return t+e;var o=r[e];if(o)return o;if(o=r[e.toLowerCase()])return o}return this.absURIRE.exec(e)?this.resolveAndNormalize(i,e):null}parseTermOrCURIEOrURI(e,t,r,n,i){e=this.trim(e);var s=this.parseCURIE(e,n,i);if(s)return s;var o=r[e];return o||((o=r[e.toLowerCase()])?o:t&&!this.absURIRE.exec(e)?t+e:this.resolveAndNormalize(i,e))}parseURI(e){return e}process(e,t){var r;t=t||{},e.nodeType===si.DOCUMENT_NODE?(e.baseURI&&!t.baseURI&&(t.baseURI=e.baseURI),r=e.baseURI,(e=e.documentElement).baseURI||(e.baseURI=r),this.setContext(e)):e.parentNode.nodeType===si.DOCUMENT_NODE&&this.setContext(e);var n=[],i=function(e){if(!e&&t&&t.baseURI)return t.baseURI;var r=e.indexOf("#");return r>=0&&(e=e.substring(0,r)),t&&t.baseURIMap&&(e=t.baseURIMap(e)),e};for(n.push({current:e,context:this.push(null,i(e.baseURI))});n.length>0;){var s=n.shift();if(s.parent){if(s.context.parent&&s.context.parent.listMapping===s.listMapping)continue;for(let e in s.listMapping){var o=s.listMapping[e];if(0!==o.length){var a=[];for(let e=0;e<o.length;e++)a.push(this.newBlankNode());for(let e=0;e<a.length;e++)this.addTriple(s.parent,a[e],"http://www.w3.org/1999/02/22-rdf-syntax-ns#first",o[e]),this.addTriple(s.parent,a[e],"http://www.w3.org/1999/02/22-rdf-syntax-ns#rest",{type:oi.objectURI,value:e+1<a.length?a[e+1]:"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"});this.addTriple(s.parent,s.subject,e,{type:oi.objectURI,value:a[0]})}else this.addTriple(s.parent,s.subject,e,{type:oi.objectURI,value:"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"})}}else{var u=s.current,c=s.context,h=!1,l=null,d=null,f=null,p=c.prefixes,g=!1,y=[],v=c.listMapping,m=!c.parent,w=c.language,b=c.vocabulary;r=this.parseURI(i(u.baseURI)),u.item=null;var _=u.getAttributeNode("vocab");if(_){let e=this.trim(_.value);if(e.length>0){b=e;var S=r.spec;this.addTriple(u,S,"http://www.w3.org/ns/rdfa#usesVocabulary",{type:oi.objectURI,value:b})}else b=this.vocabulary}for(var E=0;E<u.attributes.length;E++){var x=u.attributes[E];if("x"===x.nodeName.charAt(0)&&0===x.nodeName.indexOf("xmlns:")){g||(p=this.copyMappings(p),g=!0);var A=x.nodeName.substring(6),F=oi.trim(x.value);p[A]=this.options.base?pr.join(F,this.options.base):F}}var T=u.getAttributeNode("prefix");T&&(g||(p=this.copyMappings(p),g=!0),this.parsePrefixMappings(T.value,p));var k=null;for(let e=0;!k&&e<this.langAttributes.length;e++)k=u.getAttributeNodeNS(this.langAttributes[e].namespaceURI,this.langAttributes[e].localName);if(k){let e=oi.trim(k.value);w=e.length>0?e:null}var I,C,R=u.getAttributeNode("rel"),P=u.getAttributeNode("rev"),N=u.getAttributeNode("typeof"),U=u.getAttributeNode("property"),O=u.getAttributeNode("datatype"),L=this.inHTMLMode?u.getAttributeNode("datetime"):null,D=u.getAttributeNode("content"),j=u.getAttributeNode("about"),M=u.getAttributeNode("src"),B=u.getAttributeNode("resource"),H=u.getAttributeNode("href"),q=u.getAttributeNode("inlist"),K=[];if(R){C=this.tokenize(R.value);for(let e=0;e<C.length;e++)(I=this.parsePredicate(C[e],b,c.terms,p,r,this.inHTMLMode&&null!==U))&&K.push(I)}var V=[];if(P){C=this.tokenize(P.value);for(let e=0;e<C.length;e++)(I=this.parsePredicate(C[e],b,c.terms,p,r,this.inHTMLMode&&U))&&V.push(I)}if(this.inHTMLMode&&(R||P)&&U&&(0===K.length&&(R=null),0===V.length&&(P=null)),R||P?(j&&(l=this.parseSafeCURIEOrCURIEOrURI(j.value,p,r)),N&&(f=l),l||(u.parentNode.nodeType===si.DOCUMENT_NODE?l=i(u.baseURI):c.parentObject&&(l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject)),B&&(d=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),d||(H?d=this.resolveAndNormalize(r,encodeURI(H.value)):M?d=this.resolveAndNormalize(r,encodeURI(M.value)):!N||j||this.inXHTMLMode&&("head"===u.localName||"body"===u.localName)||(d=this.newBlankNode())),!N||j||!this.inXHTMLMode||"head"!==u.localName&&"body"!==u.localName?N&&!j&&(f=d):f=l):!U||D||O?(j&&(l=this.parseSafeCURIEOrCURIEOrURI(j.value,p,r)),!l&&B&&(l=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),!l&&H&&(l=this.resolveAndNormalize(r,encodeURI(H.value))),!l&&M&&(l=this.resolveAndNormalize(r,encodeURI(M.value))),l||(u.parentNode.nodeType===si.DOCUMENT_NODE?l=i(u.baseURI):!this.inXHTMLMode&&!this.inHTMLMode||"head"!==u.localName&&"body"!==u.localName?N?l=this.newBlankNode():c.parentObject&&(l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject,U||(h=!0)):l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject),N&&(f=l)):(j&&(l=this.parseSafeCURIEOrCURIEOrURI(j.value,p,r),N&&(f=l)),l||u.parentNode.nodeType!==si.DOCUMENT_NODE?!l&&c.parentObject&&(l=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject):(l=i(u.baseURI),N&&(f=l)),N&&!f&&(B&&(f=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),!f&&H&&(f=this.resolveAndNormalize(r,encodeURI(H.value))),!f&&M&&(f=this.resolveAndNormalize(r,encodeURI(M.value))),f||!this.inXHTMLMode&&!this.inHTMLMode||"head"!==u.localName&&"body"!==u.localName||(f=l),f||(f=this.newBlankNode()),d=f)),l&&(j||B||f)){var $=l;N&&!j&&!B&&d&&($=d),this.newSubjectOrigin(u,$)}if(f){C=this.tokenize(N.value);for(let e=0;e<C.length;e++){var W=this.parseTermOrCURIEOrAbsURI(C[e],b,c.terms,p,r);W&&this.addTriple(u,f,oi.typeURI,{type:oi.objectURI,value:W})}}if(l&&l!==c.parentObject&&(v={},m=!0),d){if(R&&q)for(let e=0;e<K.length;e++){let t=v[K[e]];t||(t=[],v[K[e]]=t),t.push({type:oi.objectURI,value:d})}else if(R)for(let e=0;e<K.length;e++)this.addTriple(u,l,K[e],{type:oi.objectURI,value:d});if(P)for(let e=0;e<V.length;e++)this.addTriple(u,d,V[e],{type:oi.objectURI,value:l})}else{if(l&&!d&&(R||P)&&(d=this.newBlankNode()),R&&q)for(let e=0;e<K.length;e++){let t=v[K[e]];t||(t=[],v[I]=t),y.push({predicate:K[e],list:t})}else if(R)for(let e=0;e<K.length;e++)y.push({predicate:K[e],forward:!0});if(P)for(let e=0;e<V.length;e++)y.push({predicate:V[e],forward:!1})}if(U){var J=null,z=null;O?(J=""===O.value?oi.PlainLiteralURI:this.parseTermOrCURIEOrAbsURI(O.value,b,c.terms,p,r),z=L&&!D?L.value:J===oi.XMLLiteralURI||J===oi.HTMLLiteralURI?null:D?D.value:u.textContent):D?(J=oi.PlainLiteralURI,z=D.value):L?(z=L.value,(J=oi.deriveDateTimeType(z))||(J=oi.PlainLiteralURI)):R||P||(B&&(z=this.parseSafeCURIEOrCURIEOrURI(B.value,p,r)),!z&&H?z=this.resolveAndNormalize(r,encodeURI(H.value)):!z&&M&&(z=this.resolveAndNormalize(r,encodeURI(M.value))),z&&(J=oi.objectURI)),J||(N&&!j?(J=oi.objectURI,z=f):(z=u.textContent,this.inHTMLMode&&"time"===u.localName&&(J=oi.deriveDateTimeType(z)),J||(J=oi.PlainLiteralURI))),C=this.tokenize(U.value);for(let e=0;e<C.length;e++){let t=this.parsePredicate(C[e],b,c.terms,p,r);if(t)if(q){let e=v[t];e||(e=[],v[t]=e),e.push(J===oi.XMLLiteralURI||J===oi.HTMLLiteralURI?{type:J,value:u.childNodes}:{type:J||oi.PlainLiteralURI,value:z,language:w})}else J===oi.XMLLiteralURI||J===oi.HTMLLiteralURI?this.addTriple(u,l,t,{type:J,value:u.childNodes}):this.addTriple(u,l,t,{type:J||oi.PlainLiteralURI,value:z,language:w})}}if(l&&!h)for(let e=0;e<c.incomplete.length;e++)c.incomplete[e].list?c.incomplete[e].list.push({type:oi.objectURI,value:l}):c.incomplete[e].forward?this.addTriple(u,c.subject,c.incomplete[e].predicate,{type:oi.objectURI,value:l}):this.addTriple(u,l,c.incomplete[e].predicate,{type:oi.objectURI,value:c.subject});var X=null,G=l;h?((X=this.push(c,c.subject)).parentObject=i(u.parentNode.baseURI)===c.parentObject?i(u.baseURI):c.parentObject,X.incomplete=c.incomplete,X.language=w,X.prefixes=p,X.vocabulary=b):((X=this.push(c,l)).parentObject=d||l||c.subject,X.prefixes=p,X.incomplete=y,d&&(G=d,v={},m=!0),X.listMapping=v,X.language=w,X.vocabulary=b),m&&n.unshift({parent:u,context:c,subject:G,listMapping:v});for(var Y=u.lastChild;Y;Y=Y.previousSibling)Y.nodeType===si.ELEMENT_NODE&&n.unshift({current:Y,context:X})}}this.inHTMLMode&&this.copyProperties();for(let t=0;t<this.finishedHandlers.length;t++)this.finishedHandlers[t](e)}push(e,t){return{parent:e,subject:t||(e?e.subject:null),parentObject:null,incomplete:[],listMapping:e?e.listMapping:{},language:e?e.language:this.language,prefixes:e?e.prefixes:this.target.graph.prefixes,terms:e?e.terms:this.target.graph.terms,vocabulary:e?e.vocabulary:this.vocabulary}}resolveAndNormalize(e,t){return pr.join(t,e)}setContext(e){"html"===e.localName&&"XHTML+RDFa 1.1"===e.getAttribute("version")?this.setXHTMLContext():"html"===e.localName||"http://www.w3.org/1999/xhtml"===e.namespaceURI?"undefined"!=typeof document&&document.doctype?"-//W3C//DTD XHTML+RDFa 1.0//EN"===document.doctype.publicId&&"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"===document.doctype.systemId?(console.log("WARNING: RDF 1.0 is not supported. Defaulting to HTML5 mode."),this.setHTMLContext()):"-//W3C//DTD XHTML+RDFa 1.1//EN"===document.doctype.publicId&&"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd"===document.doctype.systemId?this.setXHTMLContext():this.setHTMLContext():this.setHTMLContext():this.setXMLContext()}setHTMLContext(){this.setInitialContext(),this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"},{namespaceURI:null,localName:"lang"}],this.inXHTMLMode=!1,this.inHTMLMode=!0}setInitialContext(){this.vocabulary=null,this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"}]}setXHTMLContext(){this.setInitialContext(),this.inXHTMLMode=!0,this.inHTMLMode=!1,this.langAttributes=[{namespaceURI:"http://www.w3.org/XML/1998/namespace",localName:"lang"},{namespaceURI:null,localName:"lang"}],this.target.graph.terms.alternate="http://www.w3.org/1999/xhtml/vocab#alternate",this.target.graph.terms.appendix="http://www.w3.org/1999/xhtml/vocab#appendix",this.target.graph.terms.bookmark="http://www.w3.org/1999/xhtml/vocab#bookmark",this.target.graph.terms.cite="http://www.w3.org/1999/xhtml/vocab#cite",this.target.graph.terms.chapter="http://www.w3.org/1999/xhtml/vocab#chapter",this.target.graph.terms.contents="http://www.w3.org/1999/xhtml/vocab#contents",this.target.graph.terms.copyright="http://www.w3.org/1999/xhtml/vocab#copyright",this.target.graph.terms.first="http://www.w3.org/1999/xhtml/vocab#first",this.target.graph.terms.glossary="http://www.w3.org/1999/xhtml/vocab#glossary",this.target.graph.terms.help="http://www.w3.org/1999/xhtml/vocab#help",this.target.graph.terms.icon="http://www.w3.org/1999/xhtml/vocab#icon",this.target.graph.terms.index="http://www.w3.org/1999/xhtml/vocab#index",this.target.graph.terms.last="http://www.w3.org/1999/xhtml/vocab#last",this.target.graph.terms.license="http://www.w3.org/1999/xhtml/vocab#license",this.target.graph.terms.meta="http://www.w3.org/1999/xhtml/vocab#meta",this.target.graph.terms.next="http://www.w3.org/1999/xhtml/vocab#next",this.target.graph.terms.prev="http://www.w3.org/1999/xhtml/vocab#prev",this.target.graph.terms.previous="http://www.w3.org/1999/xhtml/vocab#previous",this.target.graph.terms.section="http://www.w3.org/1999/xhtml/vocab#section",this.target.graph.terms.stylesheet="http://www.w3.org/1999/xhtml/vocab#stylesheet",this.target.graph.terms.subsection="http://www.w3.org/1999/xhtml/vocab#subsection",this.target.graph.terms.start="http://www.w3.org/1999/xhtml/vocab#start",this.target.graph.terms.top="http://www.w3.org/1999/xhtml/vocab#top",this.target.graph.terms.up="http://www.w3.org/1999/xhtml/vocab#up",this.target.graph.terms.p3pv1="http://www.w3.org/1999/xhtml/vocab#p3pv1",this.target.graph.terms.related="http://www.w3.org/1999/xhtml/vocab#related",this.target.graph.terms.role="http://www.w3.org/1999/xhtml/vocab#role",this.target.graph.terms.transformation="http://www.w3.org/1999/xhtml/vocab#transformation"}setXMLContext(){this.setInitialContext(),this.inXHTMLMode=!1,this.inHTMLMode=!1}tokenize(e){return this.trim(e).split(/\s+/)}static tokenize(e){return this.trim(e).split(/\s+/)}toRDFNodeObject(e){if(void 0!==e){if("string"==typeof e)return"_:"===e.substring(0,2)?(void 0===this.blankNodes[e.substring(2)]&&(this.blankNodes[e.substring(2)]=new tr(e.substring(2))),this.blankNodes[e.substring(2)]):wr.namedNode(e);switch(e.type){case oi.objectURI:return"_:"===e.value.substring(0,2)?(void 0===this.blankNodes[e.value.substring(2)]&&(this.blankNodes[e.value.substring(2)]=new tr(e.value.substring(2))),this.blankNodes[e.value.substring(2)]):wr.namedNode(e.value);case oi.PlainLiteralURI:return new sr(e.value,e.language||"");case oi.XMLLiteralURI:case oi.HTMLLiteralURI:var t="";return Object.keys(e.value).forEach(r=>{t+=Sr.domToString(e.value[r],this.htmlOptions)}),new sr(t,"",new rr.A(e.type));default:return new sr(e.value,"",new rr.A(e.type))}}}trim(e){return e.replace(/^\s\s*/,"").replace(/\s\s*$/,"")}static trim(e){return e.replace(/^\s\s*/,"").replace(/\s\s*$/,"")}}oi.XMLLiteralURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral",oi.HTMLLiteralURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML",oi.PlainLiteralURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral",oi.objectURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#object",oi.typeURI="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",oi.nameChar="[-A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�က0-F.0-9·̀-ͯ‿-⁀]",oi.nameStartChar="[A-Za-zÀ-ÖØ-öø-ÿĀ-ıĴ-ľŁ-ňŊ-žƀ-ǃǍ-ǰǴ-ǵǺ-ȗɐ-ʨʻ-ˁΆΈ-ΊΌΎ-ΡΣ-ώϐ-ϖϚϜϞϠϢ-ϳЁ-ЌЎ-яё-ќў-ҁҐ-ӄӇ-ӈӋ-ӌӐ-ӫӮ-ӵӸ-ӹԱ-Ֆՙա-ֆא-תװ-ײء-غف-يٱ-ڷں-ھۀ-ێې-ۓەۥ-ۦअ-हऽक़-ॡঅ-ঌএ-ঐও-নপ-রলশ-হড়-ঢ়য়-ৡৰ-ৱਅ-ਊਏ-ਐਓ-ਨਪ-ਰਲ-ਲ਼ਵ-ਸ਼ਸ-ਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઋઍએ-ઑઓ-નપ-રલ-ળવ-હઽૠଅ-ଌଏ-ଐଓ-ନପ-ରଲ-ଳଶ-ହଽଡ଼-ଢ଼ୟ-ୡஅ-ஊஎ-ஐஒ-கங-சஜஞ-டண-தந-பம-வஷ-ஹఅ-ఌఎ-ఐఒ-నప-ళవ-హౠ-ౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹೞೠ-ೡഅ-ഌഎ-ഐഒ-നപ-ഹൠ-ൡก-ฮะา-ำเ-ๅກ-ຂຄງ-ຈຊຍດ-ທນ-ຟມ-ຣລວສ-ຫອ-ຮະາ-ຳຽເ-ໄཀ-ཇཉ-ཀྵႠ-Ⴥა-ჶᄀᄂ-ᄃᄅ-ᄇᄉᄋ-ᄌᄎ-ᄒᄼᄾᅀᅌᅎᅐᅔ-ᅕᅙᅟ-ᅡᅣᅥᅧᅩᅭ-ᅮᅲ-ᅳᅵᆞᆨᆫᆮ-ᆯᆷ-ᆸᆺᆼ-ᇂᇫᇰᇹḀ-ẛẠ-ỹἀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼΩK-Å℮ↀ-ↂぁ-ゔァ-ヺㄅ-ㄬ가-힣一-龥〇〡-〩_]",oi.NCNAME=new RegExp("^"+oi.nameStartChar+oi.nameChar+"*$"),oi.dateTimeTypes=[{pattern:/-?P(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+(?:\.[0-9]+)?S)?)?/,type:"http://www.w3.org/2001/XMLSchema#duration"},{pattern:/-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9]T(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/,type:"http://www.w3.org/2001/XMLSchema#dateTime"},{pattern:/-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9](?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/,type:"http://www.w3.org/2001/XMLSchema#date"},{pattern:/(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/,type:"http://www.w3.org/2001/XMLSchema#time"},{pattern:/-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]/,type:"http://www.w3.org/2001/XMLSchema#gYearMonth"},{pattern:/-?[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9]/,type:"http://www.w3.org/2001/XMLSchema#gYear"}];const ai=oi.parseRDFaDOM;class ui{constructor(e){this.store=e,this.bnodes={},this.why=null,this.reify=!1}frameFactory(e,t,r){return{NODE:1,ARC:2,parent:t,parser:e,store:e.store,element:r,lastChild:0,base:null,lang:null,node:null,nodeType:null,listIndex:1,rdfid:null,datatype:null,collection:!1,terminateFrame:function(){this.collection&&this.node.close()},addSymbol:function(e,t){t=pr.join(t,this.base),this.node=this.store.sym(t),this.nodeType=e},loadTriple:function(){if(this.parent.parent.collection?this.parent.parent.node.append(this.node):this.store.add(this.parent.parent.node,this.parent.node,this.node,this.parser.why),null!=this.parent.rdfid){var e=this.store.sym(pr.join("#"+this.parent.rdfid,this.base));this.store.add(e,this.store.sym(ui.ns.RDF+"type"),this.store.sym(ui.ns.RDF+"Statement"),this.parser.why),this.store.add(e,this.store.sym(ui.ns.RDF+"subject"),this.parent.parent.node,this.parser.why),this.store.add(e,this.store.sym(ui.ns.RDF+"predicate"),this.parent.node,this.parser.why),this.store.add(e,this.store.sym(ui.ns.RDF+"object"),this.node,this.parser.why)}},isTripleToLoad:function(){return null!=this.parent&&null!=this.parent.parent&&this.nodeType===this.NODE&&this.parent.nodeType===this.ARC&&this.parent.parent.nodeType===this.NODE},addNode:function(e){this.addSymbol(this.NODE,e),this.isTripleToLoad()&&this.loadTriple()},addCollection:function(){this.nodeType=this.NODE,this.node=this.store.collection(),this.collection=!0,this.isTripleToLoad()&&this.loadTriple()},addCollectionArc:function(){this.nodeType=this.ARC},addBNode:function(e){null!=e?null!=this.parser.bnodes[e]?this.node=this.parser.bnodes[e]:this.node=this.parser.bnodes[e]=this.store.bnode():this.node=this.store.bnode(),this.nodeType=this.NODE,this.isTripleToLoad()&&this.loadTriple()},addArc:function(e){e===ui.ns.RDF+"li"&&(e=ui.ns.RDF+"_"+this.parent.listIndex,this.parent.listIndex++),this.addSymbol(this.ARC,e)},addLiteral:function(e){this.parent.datatype&&this.parent.datatype!==ui.ns.RDF+"langString"?this.node=this.store.literal(e,this.store.sym(this.parent.datatype)):this.node=this.store.literal(e,this.lang),this.nodeType=this.NODE,this.isTripleToLoad()&&this.loadTriple()}}}getAttributeNodeNS(e,t,r){var n=null;if(e.getAttributeNodeNS)n=e.getAttributeNodeNS(t,r);else for(var i,s=e.attributes,o=0;o<s.length;++o)if((i=s[o]).namespaceURI===t&&(i.prefix?i.prefix+":"+r:r)===i.nodeName){n=i;break}return n}parse(e,t,r){var n,i=e.childNodes;if(this.cleanParser(),e.nodeType===ui.nodeType.DOCUMENT){for(var s=0;s<i.length;s++)if(i[s].nodeType===ui.nodeType.ELEMENT){n=i[s];break}}else{if(e.nodeType!==ui.nodeType.ELEMENT)throw new Error("RDFParser: can't find root in "+t+". Halting. ");n=e}this.why=r;var o=this.frameFactory(this);return this.base=t,o.base=t,o.lang=null,this.parseDOM(this.buildFrame(o,n)),!0}parseDOM(e){for(var t,r=function(e){var t="";if(null==e.namespaceURI)throw new Error("RDF/XML syntax error: No namespace for "+e.localName+" in "+this.base);return e.namespaceURI&&(t+=e.namespaceURI),e.localName?t+=e.localName:e.nodeName&&(e.nodeName.indexOf(":")>=0?t+=e.nodeName.split(":")[1]:t+=e.nodeName),t}.bind(this),n=!0;e.parent;){var i=e.element,s=i.attributes;if(i.nodeType===ui.nodeType.TEXT||i.nodeType===ui.nodeType.CDATA_SECTION)e.parent.nodeType===e.NODE&&(e.addArc(ui.ns.RDF+"value"),e=this.buildFrame(e)),e.addLiteral(i.nodeValue);else if(r(i)!==ui.ns.RDF+"RDF")if(e.parent&&e.parent.collection&&(e.addCollectionArc(),(e=this.buildFrame(e,e.element)).parent.element=null),e.parent&&e.parent.nodeType&&e.parent.nodeType!==e.ARC){e.addArc(r(i)),this.reify&&(t=this.getAttributeNodeNS(i,ui.ns.RDF,"ID"))&&(e.rdfid=t.nodeValue,i.removeAttributeNode(t));var o=this.getAttributeNodeNS(i,ui.ns.RDF,"parseType"),a=this.getAttributeNodeNS(i,ui.ns.RDF,"datatype");if(a&&(e.datatype=a.nodeValue,i.removeAttributeNode(a)),o){var u=o.nodeValue;"Literal"===u?(e.datatype=ui.ns.RDF+"XMLLiteral",(e=this.buildFrame(e)).addLiteral(i.innerHTML||i.childNodes),n=!1):"Resource"===u?((e=this.buildFrame(e,e.element)).parent.element=null,e.addBNode()):"Collection"===u&&((e=this.buildFrame(e,e.element)).parent.element=null,e.addCollection()),i.removeAttributeNode(o)}if(0!==s.length){var c=this.getAttributeNodeNS(i,ui.ns.RDF,"resource"),h=this.getAttributeNodeNS(i,ui.ns.RDF,"nodeID");e=this.buildFrame(e),c?(e.addNode(c.nodeValue),i.removeAttributeNode(c)):h?(e.addBNode(h.nodeValue),i.removeAttributeNode(h)):e.addBNode();for(var l=s.length-1;l>=0;l--){var d=this.buildFrame(e);d.addArc(r(s[l])),r(s[l])===ui.ns.RDF+"type"?this.buildFrame(d).addNode(s[l].nodeValue):this.buildFrame(d).addLiteral(s[l].nodeValue)}}else 0===i.childNodes.length&&this.buildFrame(e).addLiteral("")}else{var f=this.getAttributeNodeNS(i,ui.ns.RDF,"about");if(t=this.getAttributeNodeNS(i,ui.ns.RDF,"ID"),f&&t)throw new Error("RDFParser: "+i.nodeName+" has both rdf:id and rdf:about. Halting. Only one of these properties may be specified on a node.");if(!f&&t)e.addNode("#"+t.nodeValue),i.removeAttributeNode(t);else if(null==f&&null==t){var p=this.getAttributeNodeNS(i,ui.ns.RDF,"nodeID");p?(e.addBNode(p.nodeValue),i.removeAttributeNode(p)):e.addBNode()}else e.addNode(f.nodeValue),i.removeAttributeNode(f);var g=this.getAttributeNodeNS(i,ui.ns.RDF,"type");ui.ns.RDF+"Description"!==r(i)&&(g={nodeValue:r(i)}),null!=g&&(this.store.add(e.node,this.store.sym(ui.ns.RDF+"type"),this.store.sym(pr.join(g.nodeValue,e.base)),this.why),g.nodeName&&i.removeAttributeNode(g));for(var y=s.length-1;y>=0;y--)this.store.add(e.node,this.store.sym(r(s[y])),this.store.literal(s[y].nodeValue,e.lang),this.why)}for(i=e.element;e.parent;){for(var v=e;null==i;)i=(e=e.parent).element;var m=i.childNodes&&i.childNodes[e.lastChild];if(m&&n){if((m.nodeType===ui.nodeType.ELEMENT||m.nodeType===ui.nodeType.TEXT||m.nodeType===ui.nodeType.CDATA_SECTION)&&(m.nodeType!==ui.nodeType.TEXT&&m.nodeType!==ui.nodeType.CDATA_SECTION||1===i.childNodes.length)){e.lastChild++,e=this.buildFrame(v,i.childNodes[e.lastChild-1]);break}e.lastChild++}else{if(e.terminateFrame(),!(e=e.parent))break;i=e.element,n=!0}}}}cleanParser(){this.bnodes={},this.why=null}buildFrame(e,t){var r=this.frameFactory(this,e,t);if(e&&(r.base=e.base,r.lang=e.lang),!t||t.nodeType===ui.nodeType.TEXT||t.nodeType===ui.nodeType.CDATA_SECTION)return r;var n=t.attributes,i=t.getAttributeNode("xml:base");null!=i&&(r.base=i.nodeValue,t.removeAttribute("xml:base"));var s=t.getAttributeNode("xml:lang");null!=s&&(r.lang=s.nodeValue,t.removeAttribute("xml:lang"));for(var o=n.length-1;o>=0;o--)if("xml"===n[o].nodeName.substr(0,3)){if("xmlns:"===n[o].name.slice(0,6)){var a=n[o].nodeValue;this.base&&(a=pr.join(a,this.base)),this.store.setPrefixForURI(n[o].name.slice(6),a)}t.removeAttributeNode(n[o])}return r}}function ci(e,t,r){var n,i,s,o=["INSERT","DELETE","WHERE"],a=_r("http://www.w3.org/ns/pim/patch#"),u=fn(t,t,r,r,null,null,"",null),c={},h=function(e,t,r,n,i){return"Line "+(t+1)+" of <"+e+">: Bad syntax:\n "+i+'\n at: "'+r.slice(n,n+30)+'"'};n=0;var l=t.sym(r+"#query");for(c.query=l;;){if((i=u.skipSpace(e,n))<0)return c;if(";"===e[i]){if((n=u.skipSpace(e,i+1))<0)return c;i=n}var d=!1;for(s=0;s<o.length;s++){var f=o[s];if(e.slice(i,i+f.length)===f){if((n=u.skipSpace(e,i+f.length))<0)throw h(u._thisDoc,u.lines,e,i+f.length,"found EOF, needed {...} after "+f);if(("INSERT"===f||"DELETE"===f)&&"DATA"===e.slice(n,n+4)){if((i=u.skipSpace(e,n+4))<0)throw h(u._thisDoc,u.lines,e,n+4,"needed {...} after INSERT DATA "+f);n=i}var p=[];if((i=u.node(e,n,p))<0)throw h(u._thisDoc,u.lines,e,n,"bad syntax or EOF in {...} after "+f);c[f.toLowerCase()]=p[0],t.add(l,a(f.toLowerCase()),p[0]),d=!0,n=i}}if(!d&&"@prefix"===e.slice(i,i+7)){if((n=u.directive(e,i))<0)throw h(u._thisDoc,u.lines,e,n,"bad syntax or EOF after @prefix ");n=u.checkDot(e,n),d=!0}if(!d)throw h(u._thisDoc,u.lines,e,i,"Unknown syntax at start of statememt: '"+e.slice(i).slice(0,20)+"'")}}function hi(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"text/turtle",i=arguments.length>4?arguments[4]:void 0;n=n||er.sT,n=n.split(";")[0];try{if(n===er.ny||n===er.sT)fn(t,t,r,r,null,null,"",null).loadBuf(e),o();else if(n===er.JG){new ui(t).parse(Sr.parseXML(e),r,t.sym(r)),o()}else if(n===er.H)ai(Sr.parseXML(e,{contentType:er.H}),t,r),o();else if(n===er.lc)ai(Sr.parseXML(e,{contentType:er.lc}),t,r),o();else if(n===er.K9||n===er.Fn)ci(e,t,r),o();else if(n===er.i2)bn(e,t,r).then(o).catch(a);else{if(n!==er._0&&n!==er.BR)throw void 0===n?new Error("contentType is undefined"):new Error("Don't know how to parse "+n+" yet");var s=new ri({factory:mn});!function(e,r){e&&i(e,t);try{s.parse(r,u)}catch(e){i(e,t)}}(null,e)}}catch(e){a(e)}function o(){i&&i(null,t)}function a(e){if(n!==er.i2||n!==er._0||n!==er.BR){if(!i){let t=new Error(e+" while trying to parse <"+r+"> as "+n);throw t.cause=e,t}i(e,t)}}function u(e,r){r?t.add(r.subject,r.predicate,r.object,r.graph):i(e,t)}hi.handled={"text/n3":!0,"text/turtle":!0,"application/rdf+xml":!0,"application/xhtml+xml":!0,"text/html":!0,"application/sparql-update":!0,"application/sparql-update-single-match":!0,"application/ld+json":!0,"application/nquads":!0,"application/n-quads":!0}}(0,Yt.A)(ui,"ns",{RDF:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",RDFS:"http://www.w3.org/2000/01/rdf-schema#"}),(0,Yt.A)(ui,"nodeType",{ELEMENT:1,ATTRIBUTE:2,TEXT:3,CDATA_SECTION:4,ENTITY_REFERENCE:5,ENTITY:6,PROCESSING_INSTRUCTION:7,COMMENT:8,DOCUMENT:9,DOCUMENT_TYPE:10,DOCUMENT_FRAGMENT:11,NOTATION:12});var li=a(4945),di=a.n(li),fi=a(2931);const pi={"text/n3":!0,"text/turtle":!0,"application/rdf+xml":!0,"application/xhtml+xml":!0,"text/html":!0,"application/ld+json":!0},gi={rdf:er.JG,owl:er.JG,n3:"text/n3",ttl:"text/turtle",nt:"text/n3",acl:"text/n3",html:"text/html",xml:"text/xml"},yi=e=>({link:_r("http://www.w3.org/2007/ont/link#",e),http:_r("http://www.w3.org/2007/ont/http#",e),httph:_r("http://www.w3.org/2007/ont/httph#",e),rdf:_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#",e),rdfs:_r("http://www.w3.org/2000/01/rdf-schema#",e),dc:_r("http://purl.org/dc/elements/1.1/",e),ldp:_r("http://www.w3.org/ns/ldp#",e)}),vi=yi();class mi{constructor(e,t){(0,Yt.A)(this,"response",void 0),(0,Yt.A)(this,"dom",void 0),this.response=e,this.dom=t}}(0,Yt.A)(mi,"pattern",void 0);class wi extends mi{static toString(){return"RDFXMLHandler"}static register(e){e.mediatypes[er.JG]={q:.9}}parse(e,t,r){let n=e.store;if(this.dom||(this.dom=Sr.parseXML(t)),"parsererror"===this.dom.documentElement.nodeName)return e.failFetch(r,"Badly formed XML in "+r.resource.value,"parse_error");let i=new ui(n);try{i.parse(this.dom,r.original.value,r.original)}catch(t){return e.failFetch(r,"Syntax error parsing RDF/XML! "+t,"parse_error")}return r.noMeta||n.add(r.original,vi.rdf("type"),vi.link("RDFDocument"),e.appNode),e.doneFetch(r,this.response)}}wi.pattern=new RegExp("application/rdf\\+xml");class bi extends mi{static toString(){return"XHTMLHandler"}static register(e){e.mediatypes[er.H]={q:.8}}parse(e,t,r){let n,i;this.dom||(this.dom=Sr.parseXML(t));let s=e.store,o=this.dom.getElementsByTagName("title");o.length>0&&s.add(r.resource,vi.dc("title"),s.rdfFactory.literal(o[0].textContent),r.resource);let a=this.dom.getElementsByTagName("link");for(let t=a.length-1;t>=0;t--)n=a[t].getAttribute("rel"),i=!1,n||(n=a[t].getAttribute("rev"),i=!0),n&&e.linkData(r.original,n,a[t].getAttribute("href"),r.resource,i);let u=this.dom.getElementsByTagName("script");for(let e=0;e<u.length;e++){let t=u[e].getAttribute("type");pi[t]&&(hi(u[e].textContent,s,r.original.value,t),hi(u[e].textContent,s,r.original.value,t))}if(r.noMeta||s.add(r.resource,vi.rdf("type"),vi.link("WebPage"),e.appNode),!r.noRDFa&&ai)try{ai(this.dom,s,r.original.value)}catch(t){let n="Error trying to parse "+r.resource+" as RDFa:\n"+t+":\n"+t.stack;return e.failFetch(r,n,"parse_error")}return e.doneFetch(r,this.response)}}bi.pattern=new RegExp("application/xhtml");class _i extends mi{static toString(){return"XMLHandler"}static register(e){e.mediatypes["text/xml"]={q:.5},e.mediatypes["application/xml"]={q:.5}}static isElement(e){return e.nodeType===Node.ELEMENT_NODE}parse(e,t,r){let n=Sr.parseXML(t);for(let i=0;i<n.childNodes.length;i++){const s=n.childNodes[i];if(_i.isElement(s)){let i=s.namespaceURI;if(i&&i===i.rdf){return e.addStatus(r.req,"Has XML root element in the RDF namespace, so assume RDF/XML."),new wi(this.response,n).parse(e,t,r)}break}}if(n.doctype&&"html"===n.doctype.name&&n.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/)&&n.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)){return e.addStatus(r.req,"Has XHTML DOCTYPE. Switching to XHTML Handler.\n"),new bi(this.response,n).parse(e,t,r)}let i=n.getElementsByTagName("html")[0];if(i){let s=i.getAttribute("xmlns");if(s&&s.match(/^http:\/\/www.w3.org\/1999\/xhtml/)){return e.addStatus(r.req,"Has a default namespace for XHTML. Switching to XHTMLHandler.\n"),new bi(this.response,n).parse(e,t,r)}}return e.failFetch(r,"Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n"+t.slice(0,80),901)}}_i.pattern=new RegExp("(text|application)/(.*)xml");class Si extends mi{static toString(){return"HTMLHandler"}static register(e){e.mediatypes["text/html"]={q:.8}}parse(e,t,r){let n=e.store;if(Ti(t)){return e.addStatus(r.req,"Has an XML declaration. We'll assume it's XHTML as the content-type was text/html.\n"),new bi(this.response).parse(e,t,r)}if(function(e){const t=e.indexOf("<!DOCTYPE html"),r=e.indexOf(">");if(-1===t||-1===r||t>r)return!1;return-1!==e.substr(t,r-t).indexOf("XHTML")}(t)){return e.addStatus(r.req,"Has XHTML DOCTYPE. Switching to XHTMLHandler.\n"),new bi(this.response).parse(e,t,r)}if(function(e){const t=e.match(/[^(<html)]*<html\s+[^<]*xmlns=['"]http:\/\/www.w3.org\/1999\/xhtml["'][^<]*>/);return!!t}(t)){return e.addStatus(r.req,"Has default namespace for XHTML, so switching to XHTMLHandler.\n"),new bi(this.response).parse(e,t,r)}let i=new RegExp("<title>([\\s\\S]+?)</title>","im").exec(t);return i&&n.add(r.resource,vi.dc("title"),n.rdfFactory.literal(i[1]),r.resource),n.add(r.resource,vi.rdf("type"),vi.link("WebPage"),e.appNode),e.addStatus(r.req,"non-XML HTML document, not parsed for data."),e.doneFetch(r,this.response)}}Si.pattern=new RegExp("text/html");class Ei extends mi{static toString(){return"JsonLdHandler"}static register(e){e.mediatypes["application/ld+json"]={q:.9}}async parse(e,t,r,n){const i=e.store;try{return await bn(t,i,r.original.value),e.store.add(r.original,vi.rdf("type"),vi.link("RDFDocument"),e.appNode),e.doneFetch(r,n)}catch(t){const i="Error trying to parse "+r.resource+" as JSON-LD:\n"+t;return e.failFetch(r,i,"parse_error",n)}}}Ei.pattern=/application\/(ld\+json|activity\+json)/;class xi extends mi{static toString(){return"TextHandler"}static register(e){e.mediatypes["text/plain"]={q:.5}}parse(e,t,r){if(Ti(t)){return e.addStatus(r.req,"Warning: "+r.resource+" has an XML declaration. We'll assume it's XML but its content-type wasn't XML.\n"),new _i(this.response).parse(e,t,r)}if(t.slice(0,500).match(/xmlns:/)){return e.addStatus(r.req,"May have an XML namespace. We'll assume it's XML but its content-type wasn't XML.\n"),new _i(this.response).parse(e,t,r)}return e.addStatus(r.req,"Plain text document, no known RDF semantics."),e.doneFetch(r,this.response)}}xi.pattern=new RegExp("text/plain");class Ai extends mi{static toString(){return"N3Handler"}static register(e){e.mediatypes["text/n3"]={},e.mediatypes["text/turtle"]={}}parse(e,t,r,n){let i=e.store,s=fn(i,i,r.original.value,r.original.value,null,null,"",null);try{s.loadBuf(t)}catch(t){let i="Error trying to parse "+r.resource+" as Notation3:\n"+t;return e.failFetch(r,i,"parse_error",n)}return e.addStatus(r.req,"N3 parsed: "+s.statementCount+" triples in "+s.lines+" lines."),e.store.add(r.original,vi.rdf("type"),vi.link("RDFDocument"),e.appNode),e.doneFetch(r,this.response)}}Ai.pattern=new RegExp("(application|text)/(x-)?(rdf\\+)?(n3|turtle)");const Fi={RDFXMLHandler:wi,XHTMLHandler:bi,XMLHandler:_i,HTMLHandler:Si,TextHandler:xi,N3Handler:Ai,JsonLdHandler:Ei};function Ti(e){return!!e.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)}class ki{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((0,Yt.A)(this,"store",void 0),(0,Yt.A)(this,"timeout",void 0),(0,Yt.A)(this,"_fetch",void 0),(0,Yt.A)(this,"mediatypes",void 0),(0,Yt.A)(this,"appNode",void 0),(0,Yt.A)(this,"requested",void 0),(0,Yt.A)(this,"timeouts",void 0),(0,Yt.A)(this,"redirectedTo",void 0),(0,Yt.A)(this,"fetchQueue",void 0),(0,Yt.A)(this,"fetchCallbacks",void 0),(0,Yt.A)(this,"nonexistent",void 0),(0,Yt.A)(this,"lookedUp",void 0),(0,Yt.A)(this,"handlers",void 0),(0,Yt.A)(this,"ns",void 0),(0,Yt.A)(this,"fireCallbacks",void 0),this.store=e||new Kr,this.ns=yi(this.store.rdfFactory),this.timeout=t.timeout||3e4,this._fetch=t.fetch||void 0!==a.g&&(a.g.solidFetcher||a.g.solidFetch)||"undefined"!=typeof window&&(window.solidFetcher||window.solidFetch)||di(),!this._fetch)throw new Error("No _fetch function available for Fetcher");this.appNode=this.store.sym("chrome://TheCurrentSession"),this.store.fetcher=this,this.requested={},this.timeouts={},this.redirectedTo={},this.fetchQueue={},this.fetchCallbacks={},this.nonexistent={},this.lookedUp={},this.handlers=[],this.mediatypes={"image/*":{q:.9},"*/*":{q:.1}},Sr.callbackify(this,["request","fail","refresh","retract","done"]),Object.keys(t.handlers||Fi).map(e=>this.addHandler(Fi[e]))}static crossSiteProxy(e){return ki.crossSiteProxyTemplate?ki.crossSiteProxyTemplate.replace("{uri}",encodeURIComponent(e)):void 0}static offlineOverride(e){let t=e;var r;return"undefined"!=typeof window&&window.panes&&(r=window.panes.UI)&&r.preferences&&r.preferences.get("offlineModeUsingLocalhost")&&"http://"===t.slice(0,7)&&"localhost/"!==t.slice(7,17)&&(t="http://localhost/"+t.slice(7),br.A.warn("Localhost kludge for offline use: actually getting <"+t+">")),t}static proxyIfNecessary(e){var t;if("undefined"!=typeof window&&window.panes&&(t=window.panes.UI)&&t.isExtension)return e;if("undefined"!=typeof $SolidTestEnvironment&&$SolidTestEnvironment.localSiteMap){let t=e.split("/").slice(2);const r=(e,t)=>{let n=t[e.shift()];return n?"string"==typeof n?n+e.join("/"):e?r(e,n):null:null},n=r(t,$SolidTestEnvironment.localSiteMap);if(n)return n}return ki.crossSiteProxyTemplate&&"undefined"!=typeof document&&document.location&&"https:"===(""+document.location).slice(0,6)&&"http:"===e.slice(0,5)?ki.crossSiteProxyTemplate.replace("{uri}",encodeURIComponent(e)):e}static unsupportedProtocol(e){let t=pr.protocol(e);return"tel"===t||"mailto"===t||"urn"===t}static setCredentials(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};void 0===t.credentials&&(void 0!==t.withCredentials?t.credentials=t.withCredentials?"include":"omit":t.credentials="include")}load(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t=Object.assign({},t),e instanceof Array)return Promise.all(e.map(e=>this.load(e,Object.assign({},t))));const r=e;let n=(0,fi.E)(r);n=n.split("#")[0],t=this.initFetchOptions(n,t);const i=this.appNode,s=this.store,o=s.statementsMatching(void 0,this.ns.link("requestedURI"),s.sym(n),i).map(e=>e.subject);for(const e of o){const r=s.any(e,this.ns.link("response"),null,i);if(null!=r){const e=s.statementsMatching(r,this.ns.link("outOfDate"),!0,i);s.remove(e),t.force=!0,t.clearPreviousData=!0}}const a=this.initFetchOptions(n,t);return this.pendingFetchPromise(n,a.baseURI,a)}async pendingFetchPromise(e,t,r){let n;return!r.force&&await this.fetchQueue[t]?n=this.fetchQueue[t]:(n=Promise.race([this.setRequestTimeout(e,r),this.fetchUri(e,r)]),this.fetchQueue[t]=n,this.cleanupFetchRequest(t,void 0,this.timeout)),n.then(t=>(e in this.timeouts&&(this.timeouts[e].forEach(clearTimeout),delete this.timeouts[e]),t))}cleanupFetchRequest(e,t,r){void 0!==t&&console.warn("_options is deprecated"),this.timeouts[e]=(this.timeouts[e]||[]).concat(setTimeout(()=>{this.isPending(e)||delete this.fetchQueue[e]},r))}initFetchOptions(e,t){let r=this.store;!t.method||"GET"===t.method.toUpperCase()||(t.force=!0),t.resource=r.rdfFactory.namedNode(e),t.baseURI=t.baseURI||e,t.original=r.rdfFactory.namedNode(t.baseURI),t.req=r.bnode(),t.headers=t.headers||{},t.contentType&&(t.headers["content-type"]=t.contentType),t.force&&(t.cache="no-cache");let n=this.acceptString();t.headers.accept=n;let i=ki.offlineOverride(e);t.requestedURI=i,ki.setCredentials(i,t);let s=ki.proxyIfNecessary(i);return i!==s&&(t.proxyUsed=!0),t.actualProxyURI=s,t}fetchUri(e,t){if(!e)return Promise.reject(new Error("Cannot fetch an empty uri"));if(ki.unsupportedProtocol(e))return this.failFetch(t,"fetcher: Unsupported protocol","unsupported_protocol");let r=this.getState(e);if(t.force)delete this.nonexistent[e];else{if("fetched"===r)return Promise.resolve(this.doneFetch(t,{status:200,ok:!0,statusText:"Already loaded into quadstore."}));if("failed"===r&&404===this.requested[e]){let r="Previously failed: "+this.requested[e],n={url:e,status:this.requested[e],statusText:r,responseText:r,headers:new li.Headers,ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return this.failFetch(t,r,this.requested[e],n)}}this.fireCallbacks("request",[e]),this.requested[e]=!0,t.noMeta||this.saveRequestMetadata(e,t);let{actualProxyURI:n}=t;return this._fetch(n,t).then(r=>this.handleResponse(r,e,t),r=>{let i={url:n,status:999,statusText:(r.name||"network failure")+": "+(r.errno||r.code||r.type),responseText:r.message,headers:new li.Headers,ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return this.handleError(i,e,t)})}nowOrWhenFetched(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};const i=(0,fi.E)(e);"function"==typeof t?r=t:void 0===t||((0,nr.Y2)(t)?n.referringTerm=t:n=t),this.load(i,n).then(e=>{if(r)if(e)if(e.ok)r(!0,"OK",e);else{let t="HTTP error: Status "+e.status+" ("+e.statusText+")";e.responseText&&(t+=" "+e.responseText),r(!1,t,e)}else{r(!1,"@@ nowOrWhenFetched: no response object!")}},function(e){var t=e.message||e.statusText;t="Failed to load <"+i+"> "+t,e.response&&e.response.status&&(t+=" status: "+e.response.status),r(!1,t,e.response)})}addStatus(e,t){let r=new Date;t="["+r.getHours()+":"+r.getMinutes()+":"+r.getSeconds()+"."+r.getMilliseconds()+"] "+t;let n=this.store;const i=n.the(e,this.ns.link("status"));(0,nr.P3)(i)?i.append(n.rdfFactory.literal(t)):br.A.warn("web.js: No list to add to: "+i+","+t)}failFetch(e,t,r,n){this.addStatus(e.req,t),e.noMeta||this.store.add(e.original,this.ns.link("error"),this.store.rdfFactory.literal(t));let i=(e.method||"GET").toUpperCase();("GET"===i||"HEAD"===i)&&(e.resource.equals(e.original),this.requested[pr.docpart(e.original.value)]=r,this.fireCallbacks("fail",[e.original.value,t]));var s=new Error("Fetcher: "+t);return s.status=r,s.statusText=t,s.response=n,Promise.reject(s)}linkData(e,t,r,n,i){if(!r)return;let s,o=this.store,a=o.rdfFactory.namedNode(pr.join(r,e.value));if("alternate"===t||"seeAlso"===t||"meta"===t||"describedby"===t){if(a.value===e.value)return;s=this.ns.rdfs("seeAlso")}else s="type"===t?o.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"):o.rdfFactory.namedNode(pr.join(encodeURIComponent(t),"http://www.iana.org/assignments/link-relations/"));i?o.add(a,s,e,n):o.add(e,s,a,n)}parseLinkHeader(e,t,r){if(!e)return;const n=/[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g,i=e.match(/<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g);if(null!=i)for(let e=0;e<i.length;e++){let s=i[e].split(">"),o=s[0].substring(1),a=s[1].match(n);if(null==a)return;for(let e=0;e<a.length;e++){let n=a[e].split("=")[1].replace(/["']/g,"");this.linkData(t,n,o,r)}}}doneFetch(e,t){return this.addStatus(e.req,"Done."),this.requested[e.original.value]="done",this.fireCallbacks("done",[e.original.value]),t.req=e.req,t}nowKnownAs(e,t){this.lookedUp[e.value]?this.lookedUp[t.value]||this.lookUpThing(t,e):this.lookedUp[t.value]&&(this.lookedUp[e.value]||this.lookUpThing(e,t))}putBack(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=(0,fi.E)(e);let n=new rr.A(r).doc();return t.contentType=t["content-type"]||t["Content-Type"]||t.contentType||er.sT,"application/ld+json"===t.contentType?new Promise((r,i)=>{Ir(n,this.store,n.uri,t.contentType,(n,s)=>{n?i(n):(t.data=s,this.webOperation("PUT",e,t).then(e=>r(e)).catch(e=>i(e)))})}):(t.data=Ir(n,this.store,n.value,t.contentType),this.webOperation("PUT",r,t))}webCopy(e,t,r){return this.webOperation("GET",e).then(e=>this.webOperation("PUT",t,{data:e.responseText,contentType:r}))}delete(e,t){return this.webOperation("DELETE",e,t).then(t=>(this.requested[e]=404,this.nonexistent[e]=!0,this.unload(this.store.rdfFactory.namedNode(e)),t))}async createIfNotExists(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:er.sT,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";const n=this;try{var i=await n.load(e)}catch(s){if(404===s.response.status){try{i=await n.webOperation("PUT",e.value,{data:r,contentType:t})}catch(e){throw e}return delete n.requested[e.value],i}throw s}return i}createContainer(e,t,r){let n={"content-type":er.sT,link:this.ns.ldp("BasicContainer")+'; rel="type"'};t&&(n.slug=t);let i={headers:n};return r&&(i.body=r),this.webOperation("POST",e,i)}invalidateCache(e){const t=(0,fi.E)(e),r=this;r.fetchQueue&&r.fetchQueue[t]&&(r.fetchQueue[t].PromiseStatus,delete r.fetchQueue[t]);if(r.requested[t]&&"done"!==r.requested[t]&&"failed"!==r.requested[t]&&404!==r.requested[t]){let e=`Rdflib: fetcher: Destructive operation on <${r.requested[t]}> file being fetched! `+t;console.error(e)}else delete r.requested[t],delete r.nonexistent[t]}webOperation(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=(0,fi.E)(t);r.method=e,r.body=r.data||r.body,r.force=!0;const i=this;if(r.body&&!r.contentType)throw new Error("Web operation sending data must have a defined contentType.");return r.contentType&&(r.headers=r.headers||{},r.headers["content-type"]=r.contentType),ki.setCredentials(n,r),new Promise(function(t,s){i._fetch(n,r).then(r=>{if(r.ok)"PUT"!==e&&"PATCH"!==e&&"POST"!==e&&"DELETE"!==e||i.invalidateCache(n),r.text?r.text().then(e=>{r.responseText=e,t(r)}):t(r);else{let t="Web error: "+r.status;r.statusText&&(t+=" ("+r.statusText+")"),t+=" on "+e+" of <"+n+">",r.responseText&&(t+=": "+r.responseText);let i=new Error(t);i.response=r,s(i)}},t=>{s(new Error("Fetch error for "+e+" of <"+n+">:"+t))})})}lookUpThing(e,t){let r=this.store.uris(e);return r=r.map(e=>pr.docpart(e)),r.forEach(e=>{this.lookedUp[e]=!0}),this.load(r,{referringTerm:t})}getHeader(e,t){const r=this.store,n=e.value,i=r.each(void 0,this.ns.link("requestedURI"),r.rdfFactory.literal(n));for(let e=0;e<i.length;e++){let n=i[e];if(void 0!==n){let e=r.any(n,this.ns.link("response"));if(void 0!==e&&r.anyValue(e,this.ns.http("status"))&&r.anyValue(e,this.ns.http("status")).startsWith("2")){let n=r.each(e,this.ns.httph(t.toLowerCase()));return n.length?n.map(e=>e.value):[]}}}}saveRequestMetadata(e,t){let r=t.req,n=this.store,i=t.referringTerm;this.addStatus(t.req,"Accept: "+t.headers.accept),(0,nr.Y2)(i)&&n.add(n.rdfFactory.namedNode(e),this.ns.link("requestedBy"),i,this.appNode),t.original&&t.original.value!==e&&n.add(r,this.ns.link("orginalURI"),n.rdfFactory.literal(t.original.value),this.appNode);const s=new Date,o="["+s.getHours()+":"+s.getMinutes()+":"+s.getSeconds()+"] ";n.add(r,this.ns.rdfs("label"),n.rdfFactory.literal(o+" Request for "+e),this.appNode),n.add(r,this.ns.link("requestedURI"),n.rdfFactory.literal(e),this.appNode),n.add(r,this.ns.link("status"),n.collection(),this.appNode)}saveResponseMetadata(e,t){const r=this.store;let n=r.bnode();return r.add(t.req,this.ns.link("response"),n,this.appNode),r.add(n,this.ns.http("status"),r.rdfFactory.literal(e.status),this.appNode),r.add(n,this.ns.http("statusText"),r.rdfFactory.literal(e.statusText),this.appNode),e.headers.forEach((e,i)=>{r.add(n,this.ns.httph(i),this.store.rdfFactory.literal(e),this.appNode),"content-type"===i&&r.add(t.resource,this.ns.rdf("type"),r.rdfFactory.namedNode(Sr.mediaTypeClass(e).value),this.appNode)}),n}objectRefresh(e){let t=this.store.uris(e);if(void 0!==t)for(let e=0;e<t.length;e++)this.refresh(this.store.rdfFactory.namedNode(pr.docpart(t[e])))}refresh(e,t){this.fireCallbacks("refresh",arguments),this.nowOrWhenFetched(e,{force:!0,clearPreviousData:!0},t)}refreshIfExpired(e,t){let r=this.getHeader(e,"Expires");!r||new Date(r[0]).getTime()<=(new Date).getTime()?this.refresh(e,t):t(!0,"Not expired",{})}retract(e){this.store.removeMany(void 0,void 0,void 0,e),e.value&&delete this.requested[pr.docpart(e.value)],this.fireCallbacks("retract",arguments)}getState(e){return void 0===this.requested[e]?"unrequested":!0===this.requested[e]?"requested":"done"===this.requested[e]?"fetched":"redirected"===this.requested[e]?this.getState(this.redirectedTo[e]):"failed"}isPending(e){return!0===this.requested[e]}unload(e){this.store.removeDocument(e),delete this.requested[e.value]}addHandler(e){this.handlers.push(e),e.register(this)}retryNoCredentials(e,t){t.retriedWithNoCredentials=!0,delete this.requested[e],delete this.fetchQueue[e];let r=Object.assign({},t,{credentials:"omit"});return this.addStatus(t.req,"Abort: Will retry with credentials SUPPRESSED to see if that helps"),this.load(e,r)}isCrossSite(e){if("undefined"==typeof document||!document.location)return!1;const t=pr.hostpart,r=""+document.location;return(t(r)&&t(e)&&t(r))!==t(e)}handleError(e,t,r){if(this.isCrossSite(t)){if(r.credentials&&"include"===r.credentials&&!r.retriedWithNoCredentials)return this.retryNoCredentials(t,r);let e=ki.crossSiteProxy(t);if(e&&!r.proxyUsed)return this.redirectToProxy(e,r)}var n;return e instanceof Error?n="Fetch error: "+e.message:(n=e.statusText,e.responseText&&(n+=` ${e.responseText}`)),this.failFetch(r,n,e.status||998,e)}addType(e,t,r,n){let i=t;if(n){var s=r.any(i,this.ns.link("requestedURI"));s&&s.value!==n&&r.add(r.rdfFactory.namedNode(n),this.ns.rdf("type"),e,this.appNode)}for(;;){const t=r.any(i,this.ns.link("requestedURI"));if(t&&t.value&&r.add(r.rdfFactory.namedNode(t.value),this.ns.rdf("type"),e,this.appNode),i=r.any(void 0,r.rdfFactory.namedNode("http://www.w3.org/2007/ont/link#redirectedRequest"),i),!i)break;var o=r.any(i,r.rdfFactory.namedNode("http://www.w3.org/2007/ont/link#response"));if(!o)break;var a=r.any(o,r.rdfFactory.namedNode("http://www.w3.org/2007/ont/http#status"));if(!a)break;if("301"!==a&&"302"!==a)break}}handleResponse(e,t,r){const n=this.store,i=e.headers,s=r.req,o=this.saveResponseMetadata(e,r),a=this.normalizedContentType(r,i)||"";let u=i.get("content-location");if(0===e.status)return this.handleError(e,t,r);if(e.status>=400)return 404===e.status&&(this.nonexistent[r.original.value]=!0,this.nonexistent[t]=!0),this.saveErrorResponse(e,o).then(()=>{let t=r.resource+" "+e.statusText;return this.failFetch(r,t,e.status,e)});var c=null,h=null;if(u&&(h=pr.join(u,t))!==t&&(c=h),200===e.status){if(this.addType(this.ns.link("Document"),s,n,t),c&&this.addType(this.ns.link("Document"),s,n,c),r.clearPreviousData){const e=n.statementsMatching(void 0,void 0,void 0,r.resource).slice();for(let t=0;t<e.length;t++)n.removeStatement(e[t])}let e=a.includes("image/")||a.includes("application/pdf");a&&e&&(this.addType(n.rdfFactory.namedNode("http://purl.org/dc/terms/Image"),s,n,t),c&&this.addType(n.rdfFactory.namedNode("http://purl.org/dc/terms/Image"),s,n,c))}if(u){if(!r.force&&c&&"done"===this.requested[h])return this.doneFetch(r,e);this.requested[h]=!0}this.parseLinkHeader(i.get("link"),r.original,s);let l=this.handlerForContentType(a,e);return l?e.text().then(t=>(e.responseText=t,l.parse(this,t,r,e))):(this.addStatus(s,"Fetch over. No data handled."),this.doneFetch(r,e))}saveErrorResponse(e,t){let r=this.store;return e.text().then(e=>{e.length>10&&r.add(t,this.ns.http("content"),r.rdfFactory.literal(e),t)})}handlerForContentType(e,t){if(!e)return null;let r=this.handlers.find(t=>e.match(t.pattern));return r?new r(t):null}guessContentType(e){return gi[e.split(".").pop()]}normalizedContentType(e,t){if(e.forceContentType)return e.forceContentType;let r=t.get("content-type");if(!r||r.includes("application/octet-stream")){let t=this.guessContentType(e.resource.value);if(t)return t}let n=pr.protocol(e.resource.value);return!r&&["file","chrome"].includes(n)?"text/xml":r}redirectToProxy(e,t){this.addStatus(t.req,"BLOCKED -> Cross-site Proxy to <"+e+">"),t.proxyUsed=!0;const r=this.store,n=t.req;t.noMeta||(r.add(n,this.ns.link("redirectedTo"),r.rdfFactory.namedNode(e),n),this.addStatus(n,"redirected to new request")),this.requested[t.resource.value]="redirected",this.redirectedTo[t.resource.value]=e;let i=Object.assign({},t);return i.baseURI=t.resource.value,this.fetchUri(e,i).then(e=>(i.noMeta||r.add(n,this.ns.link("redirectedRequest"),i.req,this.appNode),e))}setRequestTimeout(e,t){return new Promise(r=>{this.timeouts[e]=(this.timeouts[e]||[]).concat(setTimeout(()=>{!this.isPending(e)||t.retriedWithNoCredentials||t.proxyUsed||r(this.failFetch(t,`Request to ${e} timed out`,"timeout"))},this.timeout))})}addFetchCallback(e,t){this.fetchCallbacks[e]?this.fetchCallbacks[e].push(t):this.fetchCallbacks[e]=[t]}acceptString(){let e="";for(let t in this.mediatypes){""!==e&&(e+=", "),e+=t;for(let r in this.mediatypes[t])e+=";"+r+"="+this.mediatypes[t][r]}return e}}(0,Yt.A)(ki,"HANDLERS",void 0),(0,Yt.A)(ki,"CONTENT_TYPE_BY_EXT",void 0),(0,Yt.A)(ki,"crossSiteProxyTemplate",void 0),ki.HANDLERS=Fi,ki.CONTENT_TYPE_BY_EXT=gi;const Ii={parseJSON:function(e,t,r){var n,i,s,o={},a=r.sym(t);for(var u in e){0===u.indexOf("_:")?o[u]?n=o[u]:(n=r.bnode(u),o[u]=n):n=r.sym(u);var c=e[u];for(var h in c){var l=c[h];for(var d in i=r.sym(h),l){var f=l[d];if("uri"===f.type)s=r.sym(f.value),r.add(n,i,s,a);else if("BlankNode"===f.type)o[f.value]?s=o[f.value]:(s=r.bnode(f.value),o[f.value]=s),r.add(n,i,s,a);else{if("Literal"!==f.type)throw new Error("error: unexpected termtype: "+d.type);s=f.datatype?r.literal(f.value,void 0,r.sym(f.datatype)):f.lang?r.literal(f.value,f.lang):r.literal(f.value),r.add(n,i,s,a)}}}}}};function Ci(e){var t=0;function r(e){var t="",r=e.statements;for(var n in r)br.A.debug("Found statement: "+r),t+=o()+r[n]+"\n";return t}function n(e){var t="";for(var r in e.constraints){var n=e.constraints[r];t+=o()+"FILTER ( "+n.describe(r)+" ) \n"}return t}function i(e){for(var s="",a=0;a<e.optional.length;a++)br.A.debug("Found optional query"),s+=o()+"OPTIONAL { \n",t++,s+=r(e.optional[a]),s+=n(e.optional[a]),s+=i(e.optional[a]),t--,s+=o()+"}\n";return s}function s(e){var s=o()+"WHERE \n{ \n";return t++,s+=r(e),s+=n(e),s+=i(e),t--,s+="}"}function o(){for(var e="",r=0;r<t;r++)e+=" ";return e}return function(e){return function(e){for(var t=o()+"SELECT ",r=0;r<e.vars.length;r++)t+=e.vars[r]+" ";return t+"\n"}(e)+s(e.pat)}(e)}function Ri(e,t,r){var n=[];function i(e){if(n[e])return n[e];var t=r.variable(e);return n[e]=t,t}function s(e){return"string"==typeof e&&e.match(/[^ \n\t]/)}function o(e){return"string"==typeof e&&e.match(/^[\?\$]/)}function a(e){return"string"==typeof e?e.replace(/^&lt;/,"<").replace(/&gt;$/,">"):e}function u(e){return"string"==typeof e&&e.match(/^<[^>]*>$/)}function c(e){return"string"==typeof e&&(e.match(/^_:/)||e.match(/^$/))}function h(e){return"string"==typeof e&&e.match(/:$/)}function l(e){return"string"==typeof e&&e.match(/^:|^[^_][^:]*:/)}function d(e){return e.split(":")[0]}function f(e){return e.split(":")[1]}function p(e){return u(e)?e.slice(1,e.length-1):e}function g(e){var t=-1===e.indexOf("'")?null:e.indexOf("'"),n=-1===e.indexOf('"')?null:e.indexOf('"');if(!t&&!n){var i=new Array(1);return i[0]=e,i}var s,o,a=new Array(2);if(!t||n&&n<t)s='"',o=n;else{if(n&&!(t&&t<n))return br.A.error("SQARQL QUERY OOPS!"),a;s="'",o=t}a[0]=e.slice(0,o);var u,c=e.slice(o+1).indexOf(s);return-1===c?(br.A.error("SPARQL parsing error: no matching parentheses in literal "+e),e):(e.slice(c+o+2).match(/^\^\^/)?(u=e.slice(c+o+2).indexOf(" "),a[1]=r.literal(e.slice(o+1,o+1+c),r.sym(p(e.slice(o+4+c,o+2+c+u)))),a=a.concat(g(e.slice(c+o+3+u)))):e.slice(c+o+2).match(/^@/)?(u=e.slice(c+o+2).indexOf(" "),a[1]=r.literal(e.slice(o+1,o+1+c),e.slice(o+3+c,o+2+c+u),null),a=a.concat(g(e.slice(c+o+2+u)))):(a[1]=r.literal(e.slice(o+1,o+1+c)),br.A.info("Literal found: "+a[1]),a=a.concat(g(e.slice(c+o+2)))),a)}function y(e){e=e.replace(/\(/g," ( ").replace(/\)/g," ) ").replace(/</g," <").replace(/>/g,"> ").replace(/{/g," { ").replace(/}/g," } ").replace(/[\t\n\r]/g," ").replace(/; /g," ; ").replace(/\. /g," . ").replace(/, /g," , "),br.A.info("New str into spaceDelimit: \n"+e);var t=[],r=e.split(" ");for(var n in r)s(r[n])&&(t=t.concat(r[n]));return t}function v(e,t){for(var r=0;r<t.length;r++)if("string"==typeof t[r]&&t[r].toLowerCase()===e.toLowerCase())return r;return null}function m(e,t){for(var r=[],n=0;n<t.length;n++)"string"==typeof t[n]&&t[n].toLowerCase()===e.toLowerCase()&&r.push(n);return r}function w(e,t,r){br.A.info("Looking for a close bracket of type "+r+" in "+e);for(var n=0,i=0;i<e.length;i++)if(e[i]===t&&n++,e[i]===r&&n--,n<0)return i;return br.A.error("Statement had no close parenthesis in SPARQL query"),0}function b(e){return this.describe=function(t){return t+" = "+e.toNT()},this.test=function(t){return e.equals(t)},this}function _(e){this.describe=function(t){return"REGEXP( '"+e+"' , "+t+" )"},this.test=function(t){var r=new RegExp(e);return!!t.value&&r.test(t.value)}}function S(e,t){3!==e.length||"Variable"!==e[0].termType||"NamedNode"!==e[2].termType&&"Literal"!==e[2].termType?6===e.length&&"string"==typeof e[0]&&"regexp"===e[0].toLowerCase()&&"("===e[1]&&")"===e[5]&&","===e[3]&&"Variable"===e[4].termType&&"Literal"===e[2].termType&&(br.A.debug("Constraint added: "+e),t.constraints[e[4]]=new _(e[2].value)):"="===e[1]||">"===e[1]||"<"===e[1]?(br.A.debug("Constraint added: "+e),t.constraints[e[0]]=new b(e[2])):br.A.warn("I don't know how to handle the constraint: "+e)}function E(e,t){br.A.debug("Optional query: "+e+" not yet implemented.");var n=r.formula();x(e,n),t.optional.push(n)}function x(e,t){var n,s,h=function(e){for(var t=[],n=0;n<e.length;n++)"string"==typeof e[n]?(e[n]=a(e[n]),o(e[n])?t[n]=i(e[n].slice(1)):c(e[n])?(br.A.info(e[n]+" was identified as a bnode."),t[n]=r.bnode()):u(e[n])?(br.A.info(e[n]+" was identified as a symbol."),t[n]=r.sym(p(e[n]))):l(e[n])?(br.A.info(e[n]+" was identified as a prefixed symbol"),T[d(e[n])]?t[n]=r.sym(e[n]=T[d(e[n])]+f(e[n])):(br.A.error("SPARQL error: "+e[n]+" with prefix "+d(e[n])+" does not have a correct prefix entry."),t[n]=e[n])):t[n]=e[n]):t[n]=e[n];return t}(e);for(br.A.debug("WHERE: "+h);v("OPTIONAL",h);)s=v("OPTIONAL",h),br.A.debug("OPT: "+s+" "+h[s]+" in "+h),"{"!==h[s+1]&&br.A.warn("Bad optional opening bracket in word "+s),-1===(n=w(h.slice(s+2),"{","}"))?br.A.error("No matching bracket in word "+s):(E(h.slice(s+2,s+2+n),t),s=v("OPTIONAL",h),n=w(h.slice(s+2),"{","}"),h.splice(s,n+3));for(br.A.debug("WHERE after optionals: "+h);v("FILTER",h);){var g=v("FILTER",h);"("!==h[g+1]&&br.A.warn("Bad filter opening bracket in word "+g),-1===(n=w(h.slice(g+2),"(",")"))?br.A.error("No matching bracket in word "+g):(S(h.slice(g+2,g+2+n),t),g=v("FILTER",h),n=w(h.slice(g+2),"(",")"),h.splice(g,n+3))}br.A.debug("WHERE after filters and optionals: "+h),function(e,t){var r=new Array(1);r[0]=-1;for(var n=r.concat(m(".",e)),i=[],s=0;s<n.length-1;s++)i[s]=e.slice(n[s]+1,n[s+1]);for(s in i){br.A.info("s+p+o "+s+" = "+i[s]);var o=i[s][0];i[s].splice(0,1);var a=r.concat(m(";",i[s]));a.push(i[s].length);for(var u=[],c=0;c<a.length-1;c++)u[c]=i[s].slice(a[c]+1,a[c+1]);for(s in u){br.A.info("p+o "+s+" = "+i[s]);var h=u[s][0];u[s].splice(0,1);var l=r.concat(m(",",u[s]));l.push(u[s].length);var d=[];for(c=0;c<l.length-1;c++)d[c]=u[s].slice(l[c]+1,l[c+1]);for(s in d){var f=d[s][0];br.A.info("Subj="+o+" Pred="+h+" Obj="+f),t.add(o,h,f)}}}}(h,t)}br.A.info("SPARQL input: \n"+e);var A=new Dr,F=function(e){var t=g(e),r=[];for(var n in t)r="string"==typeof t[n]?r.concat(y(t[n])):r.concat(t[n]);return r=function(e){for(var t=e,r=0;r<t.length;r++)if("a"===t[r]&&(t[r]="<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"),"is"===t[r]&&"of"===t[r+2]){t.splice(r,1),t.splice(r+1,1);var n=t[r-1];t[r-1]=t[r+1],t[r+1]=n}return t}(r),br.A.info("SPARQL Tokens: "+r),r}(e),T=function(e){var t=m("PREFIX",e),r=[];for(var n in t){var i=e[t[n]+1],s=e[t[n]+2];if(h(i))if(u(s)){br.A.info("Prefix found: "+i+" -> "+s);var o=d(i),a=p(s);r[o]=a}else br.A.error("Invalid SPARQL symbol: "+s);else br.A.error("Invalid SPARQL prefix: "+i)}return r}(F);T.rdf||(T.rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"),T.rdfs||(T.rdfs="http://www.w3.org/2000/01/rdf-schema#");var k=v("SELECT",F),I=v("WHERE",F);if(k<0||I<0||k>I)return br.A.error("Invalid or nonexistent SELECT and WHERE tags in SPARQL query"),!1;if(function(e,t){for(var r in br.A.info("SPARQL vars: "+e),e)if(o(e[r])){br.A.info("Added "+e[r]+" to query variables from SPARQL");var n=i(e[r].slice(1));t.vars.push(n),n.label=e[r].slice(1)}else br.A.warn("Incorrect SPARQL variable in SELECT: "+e[r])}(F.slice(k+1,I),A),x(F.slice(I+2,F.length-1),A.pat),t)return A;for(var C in A.pat.statements){var R=A.pat.statements[C];"NamedNode"===R.subject.termType&&r.fetcher&&r.fetcher.lookUpThing(R.subject,"sparql:"+R.subject),"NamedNode"===R.object.termType&&r.fetcher&&r.fetcher.lookUpThing(R.object,"sparql:"+R.object)}return A}class Pi{constructor(e){if((0,Yt.A)(this,"store",void 0),(0,Yt.A)(this,"ifps",void 0),(0,Yt.A)(this,"fps",void 0),(0,Yt.A)(this,"patchControl",void 0),(0,Yt.A)(this,"ns",void 0),(e=e||new Kr).updater)throw new Error("You can't have two UpdateManagers for the same store");e.fetcher||(e.fetcher=new ki(e)),this.store=e,e.updater=this,this.ifps={},this.fps={},this.ns={},this.ns.link=_r("http://www.w3.org/2007/ont/link#"),this.ns.http=_r("http://www.w3.org/2007/ont/http#"),this.ns.httph=_r("http://www.w3.org/2007/ont/httph#"),this.ns.ldp=_r("http://www.w3.org/ns/ldp#"),this.ns.rdf=_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.ns.rdfs=_r("http://www.w3.org/2000/01/rdf-schema#"),this.ns.rdf=_r("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.ns.owl=_r("http://www.w3.org/2002/07/owl#"),this.patchControl=[]}patchControlFor(e){return this.patchControl[e.value]||(this.patchControl[e.value]=[]),this.patchControl[e.value]}isHttpUri(e){return"http"===e.slice(0,4)}flagAuthorizationMetadata(e){e||(e=this.store);const t=e.fetcher?.appNode,r=e.statementsMatching(void 0,this.ns.link("requestedURI"),void 0,t).map(e=>e.subject);for(const n of r){const r=e.any(n,this.ns.link("response"),null,t);null!=r&&e.add(r,this.ns.link("outOfDate"),!0,t)}}async checkEditable(e,t){if(!e)return!1;t||(t=this.store);const r=this.editable(e,t);if(void 0!==r)return r;await(t.fetcher?.load(e));return this.editable(e,t)}editable(e,t){if(!e)return!1;if(t||(t=this.store),e=(0,fi.E)(e),!this.isHttpUri(e)&&t.holds(t.rdfFactory.namedNode(e),t.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),t.rdfFactory.namedNode("http://www.w3.org/2007/ont/link#MachineEditableDocument")))return"LOCALFILE";var r,n=!1;const i=t.fetcher?.appNode;for(var s,o=t.each(void 0,this.ns.link("requestedURI"),(0,pr.docpart)(e),i),a=0;a<o.length;a++)if(void 0!==(r=o[a])){const o=t.any(r,this.ns.link("response"),null,i);if(void 0!==o){if(t.anyJS(o,this.ns.link("outOfDate"),null,i))continue;var u=t.anyValue(o,this.ns.httph("wac-allow"));if(u)for(var c of u.split(",")){var h=c.split("=");if(h[0].includes("user")&&!h[1].includes("write")&&!h[1].includes("append"))return!1}var l=t.each(o,this.ns.httph("accept-patch"));if(l.length)for(let e=0;e<l.length;e++){if((s=l[e].value.trim()).indexOf("application/sparql-update")>=0)return"SPARQL";if(s.indexOf("application/sparql-update-single-match")>=0)return"SPARQL";if(s.indexOf("text/n3")>=0)return"N3PATCH"}var d=t.each(o,this.ns.httph("ms-author-via"));if(d.length)for(let e=0;e<d.length;e++){if((s=d[e].value.trim()).indexOf("SPARQL")>=0)return"SPARQL";if(s.indexOf("DAV")>=0)return"DAV"}if(!this.isHttpUri(e))return!!u&&"LOCALFILE";var f=t.each(o,this.ns.http("status"));if(f.length)for(let e=0;e<f.length;e++)200!==f[e]&&404!==f[e]||(n=!0)}}if(0===o.length);else if(n)return!1}anonymize(e){return"_:"===e.toNT().substr(0,2)&&this.mentioned(e)?"?"+e.toNT().substr(2):e.toNT()}anonymizeNT(e){return this.anonymize(e.subject)+" "+this.anonymize(e.predicate)+" "+this.anonymize(e.object)+" ."}nTriples(e){return`${e.subject.toNT()} ${e.predicate.toNT()} ${e.object.toNT()} .`}statementBnodes(e){return[e.subject,e.predicate,e.object].filter(function(e){return(0,nr.jt)(e)})}statementArrayBnodes(e){var t=[];for(let r=0;r<e.length;r++)t=t.concat(this.statementBnodes(e[r]));t.sort();var r=[];for(let e=0;e<t.length;e++)0!==e&&t[e].equals(t[e-1])||r.push(t[e]);return r}cacheIfps(){this.ifps={};var e=this.store.each(void 0,this.ns.rdf("type"),this.ns.owl("InverseFunctionalProperty"));for(let t=0;t<e.length;t++)this.ifps[e[t].value]=!0;this.fps={},e=this.store.each(void 0,this.ns.rdf("type"),this.ns.owl("FunctionalProperty"));for(let t=0;t<e.length;t++)this.fps[e[t].value]=!0}bnodeContext2(e,t,r){var n,i,s=this.store.statementsMatching(void 0,void 0,e,t);for(let e=0;e<s.length;e++)if(this.fps[s[e].predicate.value]){if(!(n=s[e].subject).isBlank)return[s[e]];if(r&&(i=this.bnodeContext2(n,t,r-1)))return i.concat([s[e]])}s=this.store.statementsMatching(e,void 0,void 0,t);for(let e=0;e<s.length;e++)if(this.ifps[s[e].predicate.value]){if(!(n=s[e].object).isBlank)return[s[e]];if(r&&(i=this.bnodeContext2(n,t,r-1)))return i.concat([s[e]])}return null}bnodeContext1(e,t){for(var r=0;r<3;r++){var n=this.bnodeContext2(e,t,r);if(null!==n)return n}return this.store.connectedStatements(e,t)}mentioned(e){return 0!==this.store.statementsMatching(e,null,null,null).length||0!==this.store.statementsMatching(null,e).length||0!==this.store.statementsMatching(null,null,e).length}bnodeContext(e,t){var r=[];if(e.length){this.cacheIfps();for(let i=0;i<e.length;i++){var n=e[i];this.mentioned(n)&&(r=r.concat(this.bnodeContext1(n,t)))}}return r}statementContext(e){var t=this.statementBnodes(e);return this.bnodeContext(t,e.graph)}contextWhere(e){var t=this;return e&&0!==e.length?"WHERE { "+e.map(function(e){return t.anonymizeNT(e)}).join("\n")+" }\n":""}fire(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return Promise.resolve().then(()=>{if(!e)throw new Error("No URI given for remote editing operation: "+t);return n.noMeta=!0,n.contentType=n.contentType||"application/sparql-update",n.body=t,this.store.fetcher.webOperation("PATCH",e,n)}).then(n=>{if(!n.ok){let r="UpdateManager: update failed for <"+e+"> status="+n.status+", "+n.statusText+"\n for query: "+t;throw new Error(r)}r(e,n.ok,n.responseText,n)}).catch(t=>{r(e,!1,t.message,t)})}update_statement(e){if(!e||e.graph){var t=this,r=this.statementContext(e);return{statement:e?[e.subject,e.predicate,e.object,e.graph]:void 0,statementNT:e?this.anonymizeNT(e):void 0,where:t.contextWhere(r),set_object:function(e,r){var n=this.where;n+="DELETE DATA { "+this.statementNT+" } ;\n",n+="INSERT DATA { "+this.anonymize(this.statement[0])+" "+this.anonymize(this.statement[1])+" "+this.anonymize(e)+" . }\n",t.fire(this.statement[3].value,n,r)}}}}insert_statement(e,t){var r=e instanceof Array?e[0]:e,n=this.contextWhere(this.statementContext(r));if(e instanceof Array){var i="";for(let t=0;t<e.length;t++)i+=e[t]+"\n";n+="INSERT DATA { "+i+" }\n"}else n+="INSERT DATA { "+this.anonymize(e.subject)+" "+this.anonymize(e.predicate)+" "+this.anonymize(e.object)+" . }\n";this.fire(r.graph.value,n,t)}delete_statement(e,t){var r=e instanceof Array?e[0]:e,n=this.contextWhere(this.statementContext(r));if(e instanceof Array){var i="";for(let t=0;t<e.length;t++)i+=e[t]+"\n";n+="DELETE DATA { "+i+" }\n"}else n+="DELETE DATA { "+this.anonymize(e.subject)+" "+this.anonymize(e.predicate)+" "+this.anonymize(e.object)+" . }\n";this.fire(r.graph.value,n,t)}requestDownstreamAction(e,t){var r=this.patchControlFor(e);if(r.pendingUpstream)if(r.downstreamAction){if(""+r.downstreamAction!=""+t)throw new Error("Can't wait for > 1 different downstream actions")}else r.downstreamAction=t;else t(e)}clearUpstreamCount(e){this.patchControlFor(e).upstreamCount=0}getUpdatesVia(e){var t=this.store.fetcher.getHeader(e,"updates-via");return t&&t.length?t[0].trim():null}addDownstreamChangeListener(e,t){var r=this.patchControlFor(e);r.downstreamChangeListeners||(r.downstreamChangeListeners=[]),r.downstreamChangeListeners.push(t),this.setRefreshHandler(e,e=>{this.reloadAndSync(e)})}reloadAndSync(e){var t=this.patchControlFor(e),r=this;if(t.reloading)t.outOfDate=!0;else{t.reloading=!0;var n=1e3,i=function(){r.reload(r.store,e,function(e,r,s){if(e){if(t.downstreamChangeListeners)for(let e=0;e<t.downstreamChangeListeners.length;e++)t.downstreamChangeListeners[e]();t.reloading=!1,t.outOfDate&&(t.outOfDate=!1,i())}else t.reloading=!1,s&&0===s.status&&(t.reloading=!0,n*=2,setTimeout(i,n))})};i()}}setRefreshHandler(e,t){let r=this.getUpdatesVia(e);var n=t,i=this,s=this,o=1500,a=0;if(!r)return!1;r=(0,pr.join)(r,e.value);const u=r.replace(/^http:/,"ws:").replace(/^https:/,"wss:");var c=function(){var t;if("undefined"!=typeof WebSocket)t=new WebSocket(u);else{if("undefined"==typeof window||!window.WebSocket)return;t=window.WebSocket(u)}t.onopen=function(){o=1500,this.send("sub "+e.value),a&&s.requestDownstreamAction(e,n)};var r=i.patchControlFor(e);r.upstreamCount=0,t.onerror=function(e){},t.onclose=function(e){o*=2,a+=1,setTimeout(function(){c()},o)},t.onmessage=function(t){if(t.data&&"pub"===t.data.slice(0,3)){if("upstreamCount"in r&&(r.upstreamCount-=1,r.upstreamCount>=0))return;r.upstreamCount=0,i.requestDownstreamAction(e,n)}}};return c(),!0}updateMany(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const r=e.concat(t).map(e=>e.why),n=this,i=[];r.forEach(e=>{i.find(t=>t.equals(e))||i.push(e)});const s=i.map(r=>n.update(e.filter(e=>e.why.equals(r)),t.filter(e=>e.why.equals(r))));return s.length,Promise.all(s)}constructSparqlUpdateQuery(e,t,r){var n=this.contextWhere(r),i="";if(n.length){if(e.length){i+="DELETE { ";for(let t=0;t<e.length;t++)i+=this.anonymizeNT(e[t])+"\n";i+=" }\n"}if(t.length){i+="INSERT { ";for(let e=0;e<t.length;e++)i+=this.anonymizeNT(t[e])+"\n";i+=" }\n"}i+=n}else{if(e.length){i+="DELETE DATA { ";for(let t=0;t<e.length;t++)i+=this.anonymizeNT(e[t])+"\n";i+=" } \n"}if(t.length){e.length&&(i+=" ; "),i+="INSERT DATA { ";for(let e=0;e<t.length;e++)i+=this.nTriples(t[e])+"\n";i+=" }\n"}}return i}constructN3PatchQuery(e,t,r){var n="\n@prefix solid: <http://www.w3.org/ns/solid/terms#>.\n@prefix ex: <http://www.example.org/terms#>.\n\n_:patch\n";return r&&r.length>0&&(n+=`\n solid:where {\n ${r.map(e=>this.anonymizeNT(e)).join("\n ")}\n };`),e.length>0&&(n+=`\n solid:deletes {\n ${e.map(e=>this.anonymizeNT(e)).join("\n ")}\n };`),t.length>0&&(n+=`\n solid:inserts {\n ${t.map(e=>this.anonymizeNT(e)).join("\n ")}\n };`),n+=" a solid:InsertDeletePatch .\n"}update(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!r){var s=this;return new Promise(function(r,o){s.update(e,t,function(e,t,n){t?r():o(new Error(n))},n,i)})}try{var o=this.store,a=e?(0,nr.ok)(e)?e.statements:e instanceof Array?e:[e]:[],u=t?(0,nr.ok)(t)?t.statements:t instanceof Array?t:[t]:[];if(!(a instanceof Array))throw new Error("Type Error "+typeof a+": "+a);if(!(u instanceof Array))throw new Error("Type Error "+typeof u+": "+u);if(0===a.length&&0===u.length)return r(null,!0);var c=a.length?a[0].graph:u[0].graph;if(!c){let e="Error patching: statement does not specify which document to patch:"+a[0]+", "+u[0];throw new Error(e)}if("NamedNode"!==c.termType){let e="Error patching: document not a NamedNode:"+a[0]+", "+u[0];throw new Error(e)}var h=this.patchControlFor(c),l=Date.now(),d=["subject","predicate","object","why"],f={delete:a,insert:u};["insert","delete"].map(function(e){f[e].map(function(e){if(!c.equals(e.graph))throw new Error("update: destination "+c+" inconsistent with delete quad "+e.graph);d.map(function(t){if(void 0===e[t])throw new Error("update: undefined "+t+" of statement.")})})});var p=this.editable(c.value,o);if(!1===p)throw new Error("Update: Can't make changes in uneditable "+c);if(void 0===p){if(n)throw new Error("Update: Loaded "+c+"but still can't figure out what editing protocol it supports.");return void this.store.fetcher.load(c).then(n=>{this.update(e,t,r,!0,i)},n=>{if(404!==n.response.status)throw new Error(`Update: Can't get updatability status ${c} before patching: ${n}`);this.update(e,t,r,!0,i)})}if(p.indexOf("SPARQL")>=0||p.indexOf("N3PATCH")>=0){var g=p.indexOf("SPARQL")>=0,y=[];a.length&&(y=this.statementArrayBnodes(a)),u.length&&(y=y.concat(this.statementArrayBnodes(u)));var v=this.bnodeContext(y,c),m=g?this.constructSparqlUpdateQuery(a,u,v):this.constructN3PatchQuery(a,u,v);i.contentType=g?"application/sparql-update":"text/n3",h.pendingUpstream=h.pendingUpstream?h.pendingUpstream+1:1,"upstreamCount"in h&&(h.upstreamCount+=1),this.fire(c.value,m,(e,t,n,i)=>{if(i.elapsedTimeMs=Date.now()-l,t){try{o.remove(a)}catch(e){t=!1,n="Remote Ok BUT error deleting "+a.length+" from store!!! "+e}for(let e=0;e<u.length;e++)o.add(u[e].subject,u[e].predicate,u[e].object,c)}if(r(e,t,n,i),h.pendingUpstream-=1,0===h.pendingUpstream&&h.downstreamAction){var s=h.downstreamAction;delete h.downstreamAction,s(c)}},i)}else if(p.indexOf("DAV")>=0)this.updateDav(c,a,u,r,i);else{if(!(p.indexOf("LOCALFILE")>=0))throw new Error("Unhandled edit method: '"+p+"' for "+c);try{this.updateLocalFile(c,a,u,r,i)}catch(e){r(c.value,!1,"Exception trying to write back file <"+c.value+">\n")}}}catch(e){r(void 0,!1,"Exception in update: "+e+"\n"+Sr.stackString(e))}}updateDav(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},s=this.store;var o=s.any(e,this.ns.link("request"));if(!o)throw new Error("No record of our HTTP GET request for document: "+e);var a=s.any(o,this.ns.link("response"));if(!a)return null;var u=s.the(a,this.ns.httph("content-type")).value;let c=s.statementsMatching(void 0,void 0,void 0,e).slice();for(let e=0;e<t.length;e++)Sr.RDFArrayRemove(c,t[e]);for(let e=0;e<r.length;e++)c.push(r[e]);const h=this.serialize(e.value,c,u);var l,d=s.the(a,this.ns.httph("content-location"));return d&&(l=(0,pr.join)(d.value,l)),i.contentType=u,i.noMeta=!0,i.body=h,s.fetcher.webOperation("PUT",l,i).then(i=>{if(!i.ok)throw new Error(i.error);for(let e=0;e<t.length;e++)s.remove(t[e]);for(let t=0;t<r.length;t++)s.add(r[t].subject,r[t].predicate,r[t].object,e);n(e.value,i.ok,i.responseText,i)}).catch(t=>{n(e.value,!1,t.message,t)})}updateLocalFile(e,t,r,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const s=this.store;let o=s.statementsMatching(void 0,void 0,void 0,e).slice();for(let e=0;e<t.length;e++)Sr.RDFArrayRemove(o,t[e]);for(let e=0;e<r.length;e++)o.push(r[e]);var a=e.value.lastIndexOf(".");if(a<1)throw new Error("Rewriting file: No filename extension: "+e.value);var u=e.value.slice(a+1);let c=ki.CONTENT_TYPE_BY_EXT[u];if(!c)throw new Error("File extension ."+u+" not supported for data write");i.body=this.serialize(e.value,o,c),i.contentType=c,s.fetcher.webOperation("PUT",e.value,i).then(i=>{if(!i.ok)return n(e.value,!1,i.error);for(let e=0;e<t.length;e++)s.remove(t[e]);for(let t=0;t<r.length;t++)s.add(r[t].subject,r[t].predicate,r[t].object,e);n(e.value,!0,"")})}serialize(e,t,r){const n=this.store;let i;if("string"==typeof t)return t;var s=Tr(n);switch(s.suggestNamespaces(n.namespaces),s.setBase(e),r){case"text/xml":case"application/rdf+xml":i=s.statementsToXML(t);break;case"text/n3":case"text/turtle":case"application/x-turtle":case"application/n3":i=s.statementsToN3(t);break;default:throw new Error("Content-type "+r+" not supported for data serialization")}return i}put(e,t,r,n){const i=this.store;let s;return Promise.resolve().then(()=>(s=this.serialize(e.value,t,r),i.fetcher.webOperation("PUT",e.value,{contentType:r,body:s}))).then(r=>{if(!r.ok)return n(e.value,r.ok,r.error,r);delete i.fetcher.nonexistent[e.value],delete i.fetcher.requested[e.value],"string"!=typeof t&&t.map(e=>{i.addStatement(e)}),n(e.value,r.ok,"",r)}).catch(t=>{n(e.value,!1,t.message)})}reload(e,t,r){var n=Date.now();e.fetcher.nowOrWhenFetched(t.value,{force:!0,noMeta:!0,clearPreviousData:!0},function(e,i,s){if(e)if(s.onErrorWasCalled||200!==s.status)r(!1,"Non-HTTP error reloading data: "+i,s);else{var o=Date.now()-n;t.reloadTimeTotal||(t.reloadTimeTotal=0),t.reloadTimeCount||(t.reloadTimeCount=0),t.reloadTimeTotal+=o,t.reloadTimeCount+=1,r(!0)}else r(!1,"Error reloading data: "+i,s)})}}const Ni={...mn,fetcher:(e,t)=>new ki(e,t),graph(){return new Kr(arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0)||{rdfFactory:mn})},lit(e,t,r){return this.literal(""+e,t||r)},st(e,t,r,n){return this.quad(e,t,r,n)}},Ui=Ni;class Oi{constructor(e,t){this.parent=e,this.via=t,this.connected=!1,this.pending={},this.subscribed={},this.socket={};try{this.socket=new WebSocket(t),this.socket.onopen=this.onOpen,this.socket.onclose=this.onClose,this.socket.onmessage=this.onMessage,this.socket.onerror=this.onError}catch(e){this.onError(e)}}_decode(e){var t,r,n,i,s,o,a;for(r in i={},s=function(){var r,n,i,s;for(s=[],r=0,n=(i=e.split("&")).length;r<n;r++)t=i[r],s.push(t.split("="));return s}())t=s[r],a=(o=[decodeURIComponent(t[0]),decodeURIComponent(t[1])])[1],null==i[n=o[0]]&&(i[n]=[]),i[n].push(a);return i}_send(e,t,r){var n,i;return i=[e,t,r].join(" "),"function"==typeof(n=this.socket).send?n.send(i):void 0}_subscribe(e){return this._send("sub",e,""),this.subscribed[e]=!0,this.subscribed[e]}onClose(e){var t;for(t in this.connected=!1,this.subscribed)this.pending[t]=!0;return this.subscribed={},this.subscribed}onError(e){throw new Error("onError"+e)}onMessage(e){var t,r;return"ping"===(r=e.data.split(" "))[0]?"function"==typeof(t=this.socket).send?t.send("pong "+r.slice(1).join(" ")):void 0:"pub"===r[0]?this.parent.onUpdate(r[1],this._decode(r[2])):void 0}onOpen(e){var t,r;for(r in this.connected=!0,t=[],this.pending)delete this.pending[r],t.push(this._subscribe(r));return t}subscribe(e){return this.connected?this._subscribe(e):(this.pending[e]=!0,this.pending[e])}}class Li{constructor(e){this.fetcher=e,this.graph={},this.via={},this.fetcher.addCallback("headers",this.onHeaders)}onHeaders(e){var t,r,n;return null==e.headers||"undefined"==typeof WebSocket||null===WebSocket||(t=e.headers.etag,n=e.headers["updates-via"],r=e.uri,t&&n&&(this.graph[r]={etag:t,via:n},this.register(n,r))),!0}onUpdate(e,t){return this.fetcher.refresh(Ui.namedNode(e))}register(e,t){return null==this.via[e]&&(this.via[e]=new Oi(this,e)),this.via[e].subscribe(t)}}const Di={};for(const e in Ui)"function"==typeof Ui[e]&&(Di[e]=Ui[e].bind(Ui));const{fetcher:ji,graph:Mi,lit:Bi,st:Hi,namedNode:qi,variable:Ki,blankNode:Vi,defaultGraph:$i,literal:Wi,quad:Ji,triple:zi}=Di,Xi=new Ur,Gi=e=>Xi.fromNT(e),Yi=Or.fromValue,Qi=tr.nextId;class Zi extends Kr{constructor(e){super(e),(0,Yt.A)(this,"fetcher",void 0),this.fetcher=new ki(this,{})}}class es extends Zi{constructor(e){super(e),(0,Yt.A)(this,"updater",void 0),this.updater=new Pi(this)}}const ts=Ar()(e),rs=qi("http://www.iana.org/assignments/link-relations/acl");function ns(e){const t=ts;function r(e,r,n,i={}){const s=i.public||[],o=Mi(),a=_r("http://www.w3.org/ns/auth/acl#");let u=o.sym(`${n}#a1`);const c=o.sym(n),h=o.sym(e);if(o.add(u,t.rdf("type"),a("Authorization"),c),o.add(u,a("accessTo"),h,c),i.defaultForNew&&o.add(u,a("default"),h,c),o.add(u,a("agent"),r,c),o.add(u,a("mode"),a("Read"),c),o.add(u,a("mode"),a("Write"),c),o.add(u,a("mode"),a("Control"),c),s.length){u=o.sym(`${n}#a2`),o.add(u,t.rdf("type"),a("Authorization"),c),o.add(u,a("accessTo"),h,c),o.add(u,a("agentClass"),t.foaf("Agent"),c);for(let e=0;e<s.length;e++)o.add(u,a("mode"),a(s[e]),c)}return Ir(c,o,n)}return{findAclDocUrl:async function(t){await e.fetcher.load(t);const r=e.any(t,rs);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),rs);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),rs);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 is=()=>{let{SolidAppContext:e}=window;if(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 ss(){const{$SolidTestEnvironment:e}=window;if(void 0!==e&&e.username)return t("Assuming the user is "+e.username),qi(e.username);if("undefined"!=typeof document&&document.location&&"http://localhost"===(""+document.location).slice(0,16)){const e=document.getElementById("appTarget");if(!e)return null;const r=e.getAttribute("testID");return r?(t("Assuming user is "+r),qi(r)):null}return null}class os{session;constructor(e){this.session=e}get authSession(){return this.session}currentUser(){const e=is();return e.viewingNoAuthPage?qi(e.webId):this&&this.session&&this.session.info&&this.session.info.webId&&this.session.info.isLoggedIn?qi(this.session.info.webId):ss()}async checkUser(e){const r=new URL(window.location.href).hash;r&&window.localStorage.setItem("preLoginRedirectHash",r),this.session.events.on(Ke,e=>{t(`Session restored to ${e}`),document.location.toString()!==e&&history.replaceState(null,"",e)});const n=new URL(window.location.href);n.hash="",await this.session.handleIncomingRedirect({restorePreviousSession:!0,url:n.href});const i=window.localStorage.getItem("preLoginRedirectHash");if(i){const e=new URL(window.location.href);e.hash!==i&&(history.pushState?history.pushState(null,document.title,i):location.hash=i,e.hash=i),window.localStorage.setItem("preLoginRedirectHash","")}let s=ss();if(s)return Promise.resolve(e?e(s):s);const o=this.webIdFromSession(this.session.info);return o&&(s=this.saveUser(o)),s&&t(`(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=qi(r);return t&&(t.me=n),n}return null}webIdFromSession(e){return e?.webId&&e.isLoggedIn?e.webId:null}}function as(e){return qi(e.uri+"#id"+Date.now())}function us(e){return!e||`${window.location.origin}/`!==new URL(e.value).origin}const cs="index.ttl#this";function hs(e,t){const r=ts;async function n(t,r,n){await e.fetcher.load(t);const i=e.any(t,new rr.A("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=as(i),o=[Hi(s,r.rdf("type"),r.solid("TypeRegistration"),i.doc()),Hi(s,r.solid("forClass"),r.meeting("LongChat"),i.doc()),Hi(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 rr.A(r)}(r,await t.getPodRoot(n));let s=!0;try{await e.fetcher.load(new rr.A(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+cs),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"),Yi(new Date(Date.now())),o),t.me&&n.add(s,r.dc("author"),t.me,o),new Promise(function(e,r){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 u(t,n){await e.fetcher.load(t.doc());const i=e.any(t,r.ldp("inbox"),void 0,t.doc());if(!i)throw new Error(`Invitee inbox not found! ${t.value}`);const s=`\n <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;\n ${r.rdf("seeAlso")} <${n.value}> .\n `,o=await(e.fetcher?.webOperation("POST",i.value,{data:s,contentType:"text/turtle"})),a=o?.headers.get("location");if(!a)throw new Error(`Invite sending returned a ${o?.status}`)}return{setAcl:n,addToPrivateTypeIndex:i,findChat:s,createChatThing:o,getChat:async function(e,t=!0){const{me:r,chatContainer:a,exists:c}=await s(e);if(c)return new rr.A(a.value+cs);if(t){const t=await o(a,r);return await u(e,t),await n(a,r,e),await i(t,r),t}return null},sendInvite:u,mintNew:a}}function ls(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 ds extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}}class fs extends ds{}class ps extends ds{}class gs extends ds{}class ys extends ds{}class vs extends ds{}class ms extends ds{}class ws extends ds{status;constructor(e,t){super(t),this.status=e}}function bs(e,t,n){const i=ts;async function s(t){await o(t);const s=function(e){const t=e.uri.replace("/profile/","/").replace("/public/","/").split("/").slice(0,-1).join("/")+"/Settings/";return qi(t+"Preferences.ttl")}(t);let a;try{a=await n.followOrCreateLink(t,i.space("preferencesFile"),s,t.doc())}catch(e){if(r(`User ${t} has no pointer in profile to preferences file.`),e instanceof vs)throw e;if(e instanceof ms)throw e;if(e instanceof fs)throw e;if(e instanceof ps)throw e;if(e instanceof gs)throw e;if(e instanceof ws)throw e;throw e}try{await e.fetcher.load(a)}catch(e){const n=`Unable to load preference of user ${t}: ${e}`;if(r(n),401===e.response.status)throw new fs;if(403===e.response.status){if(us(a))throw new ps;throw new gs}throw new Error(n)}return a}async function o(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 a(t){return e.any(t,i.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=a(e);if(!t)throw new Error("User pod root not found!");return t},getMainInbox:async function(t){await e.fetcher.load(t);const r=e.any(t,i.ldp("inbox"),void 0,t.doc());if(!r)throw new Error("User main inbox not found!");return r},findStorage:a,loadPreferences:s,loadProfile:o,silencedLoadPreferences:async function(e){try{return await s(e)}catch(e){return}}}}function _s(e,t,n,i){const s=ts;async function o(t){if(!t)throw new Error("loadTypeIndexesFor: No user given");const o=await n.loadProfile(t),a=h(t);let u;try{u=await i.followOrCreateLink(t,s.solid("publicTypeIndex"),a,o)}catch(e){r(`User ${t} has no pointer in profile to publicTypeIndex file.`)}const c=u?[{label:"public",index:u,agent:t}]:[];let d,f;try{d=await n.silencedLoadPreferences(t)}catch(e){d=null}if(d){const n=l(d);let a;try{a=e.any(t,s.solid("privateTypeIndex"),void 0,o)||await i.followOrCreateLink(t,s.solid("privateTypeIndex"),n,d)}catch(e){r(`User ${t} has no pointer in preference file to privateTypeIndex file.`)}f=a?[{label:"private",index:a,agent:t}]:[]}else f=[];const p=c.concat(f);if(0===p.length)return p;const g=p.map(e=>e.index);try{await e.fetcher.load(g)}catch(e){r("Problems loading type index: ",e)}return p}async function a(t){let i;try{i=await n.silencedLoadPreferences(t)}catch(e){r(`User ${t} has no pointer in profile to preferences file.`)}if(i){const r=e.each(t,s.solid("community"),void 0,i).concat(e.each(t,s.solid("community"),void 0,t.doc()));let n=[];for(const e of r)n=n.concat(await o(e));return n}return[]}async function u(e){return(await o(e)).concat((await a(e)).flat())}async function c(e,t){const r=await u(t);let n=[];for(const t of r){const r=await d(t,e);n=n.concat(r)}return n}function h(e){return qi(e.doc().dir()?.uri+"publicTypeIndex.ttl")}function l(e){return qi(e.doc().dir()?.uri+"privateTypeIndex.ttl")}async function d(t,r){const n=t.index,i=[],o=e.statementsMatching(null,s.solid("instance"),null,n).concat(e.statementsMatching(null,s.solid("instanceContainer"),null,n)).map(e=>e.subject);for(const a of o){const o=e.any(a,s.solid("forClass"),null,n);if(!r||o.sameTerm(r)){const r=e.each(a,s.solid("instance"),null,n);for(const e of r)i.push({instance:e,type:o,scope:t});const u=e.each(a,s.solid("instanceContainer"),null,n);for(const r of u)await e.fetcher.load(r),i.push({instance:qi(r.value),type:o,scope:t})}}return i}return{registerInTypeIndex:async function(t,r,n){const i=as(r),o=[Hi(i,s.rdf("type"),s.solid("TypeRegistration"),r),Hi(i,s.solid("forClass"),n,r),Hi(i,s.solid("instance"),t,r)];try{await e.updater.update([],o)}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,s.solid("instance"),t).filter(t=>e.holds(t,s.solid("forClass"),r))},loadTypeIndexesFor:o,loadCommunityTypeIndexes:a,loadAllTypeIndexes:u,getScopedAppInstances:c,getAppInstances:async function(e){const r=t.currentUser();if(!r)throw new Error("getAppInstances: Must be logged in to find apps.");return(await c(e,r)).map(e=>e.instance)},suggestPublicTypeIndex:h,suggestPrivateTypeIndex:l,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:d}}const Ss=function(e,n){t("SolidLogic: Unique instance created. There should only be one of these.");const i=Mi();ji(i,{fetch:e.fetch}),i.updater=new Pi(i),i.features=[];const s=new os(n),o=ns(i),a=function(e){function t(t){return e.statementsMatching(t,qi("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(qi(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)}}}(i),u=function(e,n,i){async function s(t){let r;try{r=await e.fetcher.load(t)}catch(r){if(404!==r.response.status){if(401===r.response.status)throw new fs;if(403===r.response.status){if(us(t))throw new ps;throw new gs}const e="createIfNotExists doc load error NOT 404: "+t+": "+r;throw new ws(r.status,r.message+e)}try{await e.fetcher.webOperation("PUT",t,{data:"",contentType:"text/turtle"})}catch(e){throw new ms("createIfNotExists: PUT FAILED: "+t+": "+e)}await e.fetcher.load(t)}return r}return{recursiveDelete:async function r(s){try{if(i.isContainer(s)){const t=await n.findAclDocUrl(s);await e.fetcher._fetch(t,{method:"DELETE"});const o=await i.getContainerMembers(s);await Promise.all(o.map(e=>r(e)))}const t=s.value;return e.fetcher._fetch(t,{method:"DELETE"})}catch(e){t(`Please manually remove ${s.value} from your system.`,e)}},setSinglePeerAccess:async function(t){let r=["@prefix acl: <http://www.w3.org/ns/auth/acl#>.","",`<#alice> a acl:Authorization;\n acl:agent <${t.ownerWebId}>;`,` acl:accessTo <${t.target}>;`,` acl:default <${t.target}>;`," acl:mode acl:Read, acl:Write, acl:Control.",""].join("\n");t.accessToModes&&(r+=["<#bobAccessTo> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:accessTo <${t.target}>;`,` acl:mode ${t.accessToModes}.`,""].join("\n")),t.defaultModes&&(r+=["<#bobDefault> a acl:Authorization;",` acl:agent <${t.peerWebId}>;`,` acl:default <${t.target}>;`,` acl:mode ${t.defaultModes}.`,""].join("\n"));const i=await n.findAclDocUrl(qi(t.target));return e.fetcher._fetch(i,{method:"PUT",body:r,headers:[["Content-Type","text/turtle"]]})},createEmptyRdfDoc:async function(t,r){await e.fetcher.webOperation("PUT",t.uri,{data:`# ${new Date} ${r}\n `,contentType:"text/turtle"})},followOrCreateLink:async function(t,n,i,o){await e.fetcher.load(o);const a=e.any(t,n,null,o);if(a)return a;if(!e.updater.editable(o)){const e=`followOrCreateLink: cannot edit ${o.value}`;throw r(e),new vs(e)}try{await e.updater.update([],[Hi(t,n,i,o)])}catch(e){throw r(`followOrCreateLink: Error making link in ${o} to ${i}: ${e}`),new ms(e)}try{await s(i)}catch(e){throw r(`followOrCreateLink: Error loading or saving new linked document: ${i}: ${e}`),e}return i},loadOrCreateIfNotExists:s}}(i,o,a),c=bs(i,s,u),h=hs(i,c),l=ls(i,c,u,a),d=_s(i,s,c,u);return t("SolidAuthnLogic initialized"),{store:i,authn:s,acl:o,inbox:l,chat:h,profile:c,typeIndex:d,load:function(e){return i.fetcher.load(e)},updatePromise:function(e,t=[]){return new Promise((r,n)=>{i.updater.update(e,t,function(e,t,i){t?r():n(new Error(i))})})},clearStore:function(){i.statements.slice().forEach(i.remove.bind(i))}}}({fetch:async(e,t)=>{const r=t&&t.credentials&&"omit"==t.credentials;return Gt.info.webId&&!r?Gt.fetch(e,t):window.fetch(e,t)}},Gt);t("Unique quadstore initialized.");const Es=[{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 xs(){const e=[...Es],{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 As=Ss.authn,Fs=Ss.authn.authSession,Ts=Ss.store})(),u})());
41
41
  //# sourceMappingURL=solid-logic.min.js.map