@openhps/solid 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
1
  /*! For license information please see openhps-solid.min.js.LICENSE.txt */
2
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@openhps/core"),require("@openhps/rdf")):"function"==typeof define&&define.amd?define("OpenHPS",["core","rdf"],t):"object"==typeof exports?exports.OpenHPS=t(require("@openhps/core"),require("@openhps/rdf")):(e.OpenHPS=e.OpenHPS||{},e.OpenHPS.solid=t(e.OpenHPS.core,e.OpenHPS.rdf))}("undefined"!=typeof self?self:this,(e,t)=>(()=>{var r={358(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActorInitQuery=void 0;const n=r(638);"undefined"==typeof process&&(globalThis.process=r(606));class ActorInitQuery extends n.ActorInitQueryBase{}t.ActorInitQuery=ActorInitQuery},638(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActorInitQueryBase=void 0;const n=r(180),i=r(412);class ActorInitQueryBase extends n.ActorInit{async test(e){return(0,i.passTestVoid)()}async run(e){throw new Error("ActorInitSparql#run is not supported in the browser.")}}t.ActorInitQueryBase=ActorInitQueryBase},235(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.QueryEngineBase=void 0;const n=r(711),i=r(412);class QueryEngineBase{constructor(e){this.actorInitQuery=e}async queryBindings(e,t){return this.queryOfType(e,t,"bindings")}async queryQuads(e,t){return this.queryOfType(e,t,"quads")}async queryBoolean(e,t){return this.queryOfType(e,t,"boolean")}async queryVoid(e,t){return this.queryOfType(e,t,"void")}async queryOfType(e,t,r){const n=await this.query(e,t);if(n.resultType===r)return await n.execute();throw new Error(`Query result type '${r}' was expected, while '${n.resultType}' was found.`)}async query(e,t){const r=await this.queryOrExplain(e,t);if("explain"in r)throw new Error("Tried to explain a query when in query-only mode");return r}async explain(e,t,r){t.explain=r;return await this.queryOrExplain(e,t)}async queryOrExplain(e,t){const r=i.ActionContext.ensureActionContext(t);r.get(n.KeysInitQuery.invalidateCache)&&await this.invalidateHttpCache();const{result:s}=await this.actorInitQuery.mediatorQueryProcess.mediate({query:e,context:r});return"explain"in s?s:QueryEngineBase.internalToFinalResult(s)}async getResultMediaTypes(e){return e=i.ActionContext.ensureActionContext(e),(await this.actorInitQuery.mediatorQueryResultSerializeMediaTypeCombiner.mediate({context:e,mediaTypes:!0})).mediaTypes}async getResultMediaTypeFormats(e){return e=i.ActionContext.ensureActionContext(e),(await this.actorInitQuery.mediatorQueryResultSerializeMediaTypeFormatCombiner.mediate({context:e,mediaTypeFormats:!0})).mediaTypeFormats}async resultToString(e,t,r){if(r=i.ActionContext.ensureActionContext(r),!t)switch(e.resultType){case"bindings":t="application/json";break;case"quads":t="application/trig";break;default:t="simple"}const n={...await QueryEngineBase.finalToInternalResult(e),context:r};return(await this.actorInitQuery.mediatorQueryResultSerialize.mediate({context:r,handle:n,handleMediaType:t})).handle}invalidateHttpCache(e,t){return t=i.ActionContext.ensureActionContext(t),this.actorInitQuery.mediatorHttpInvalidate.mediate({url:e,context:t})}static internalToFinalResult(e){switch(e.type){case"bindings":return{resultType:"bindings",execute:async()=>e.bindingsStream,metadata:async()=>{const t=await e.metadata();return t.variables=t.variables.map(e=>e.variable),t},context:e.context};case"quads":return{resultType:"quads",execute:async()=>e.quadStream,metadata:async()=>await e.metadata(),context:e.context};case"boolean":return{resultType:"boolean",execute:async()=>e.execute(),context:e.context};case"void":return{resultType:"void",execute:async()=>e.execute(),context:e.context}}}static async finalToInternalResult(e){switch(e.resultType){case"bindings":return{type:"bindings",bindingsStream:await e.execute(),metadata:async()=>{const t=await e.metadata();return t.variables=t.variables.map(e=>({variable:e,canBeUndef:!1})),t}};case"quads":return{type:"quads",quadStream:await e.execute(),metadata:async()=>await e.metadata()};case"boolean":return{type:"boolean",execute:()=>e.execute()};case"void":return{type:"void",execute:()=>e.execute()}}}}t.QueryEngineBase=QueryEngineBase},632(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActorInit=void 0;const n=r(412);class ActorInit extends n.Actor{constructor(e){super(e)}}t.ActorInit=ActorInit},180(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(632),t)},39(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeysStatistics=t.KeysRdfJoin=t.KeysMergeBindingsContext=t.KeysRdfUpdateQuads=t.KeysQuerySourceIdentify=t.KeysRdfParseHtmlScript=t.KeysRdfParseJsonLd=t.KeysQueryOperation=t.KeysExpressionEvaluator=t.KeysInitQuery=t.KeysHttpProxy=t.KeysHttpMemento=t.KeysHttpWayback=t.KeysHttp=t.KeysCore=void 0;const n=r(412);t.KeysCore={log:n.CONTEXT_KEY_LOGGER},t.KeysHttp={includeCredentials:new n.ActionContextKey("@comunica/bus-http:include-credentials"),auth:new n.ActionContextKey("@comunica/bus-http:auth"),fetch:new n.ActionContextKey("@comunica/bus-http:fetch"),httpTimeout:new n.ActionContextKey("@comunica/bus-http:http-timeout"),httpBodyTimeout:new n.ActionContextKey("@comunica/bus-http:http-body-timeout"),httpRetryCount:new n.ActionContextKey("@comunica/bus-http:http-retry-count"),httpRetryDelayFallback:new n.ActionContextKey("@comunica/bus-http:http-retry-delay-fallback"),httpRetryDelayLimit:new n.ActionContextKey("@comunica/bus-http:http-retry-delay-limit"),httpRetryStatusCodes:new n.ActionContextKey("@comunica/bus-http:http-retry-status-codes")},t.KeysHttpWayback={recoverBrokenLinks:new n.ActionContextKey("@comunica/bus-http:recover-broken-links")},t.KeysHttpMemento={datetime:new n.ActionContextKey("@comunica/actor-http-memento:datetime")},t.KeysHttpProxy={httpProxyHandler:new n.ActionContextKey("@comunica/actor-http-proxy:httpProxyHandler")},t.KeysInitQuery={querySourcesUnidentified:new n.ActionContextKey("@comunica/actor-init-query:querySourcesUnidentified"),initialBindings:new n.ActionContextKey("@comunica/actor-init-query:initialBindings"),queryFormat:new n.ActionContextKey("@comunica/actor-init-query:queryFormat"),graphqlSingularizeVariables:new n.ActionContextKey("@comunica/actor-init-query:singularizeVariables"),lenient:new n.ActionContextKey("@comunica/actor-init-query:lenient"),queryString:new n.ActionContextKey("@comunica/actor-init-query:queryString"),query:new n.ActionContextKey("@comunica/actor-init-query:query"),baseIRI:new n.ActionContextKey("@comunica/actor-init-query:baseIRI"),fileBaseIRI:new n.ActionContextKey("@comunica/actor-init-query:fileBaseIRI"),functionArgumentsCache:new n.ActionContextKey("@comunica/actor-init-query:functionArgumentsCache"),queryTimestamp:new n.ActionContextKey("@comunica/actor-init-query:queryTimestamp"),queryTimestampHighResolution:new n.ActionContextKey("@comunica/actor-init-query:queryTimestampHighResolution"),extensionFunctionCreator:new n.ActionContextKey("@comunica/actor-init-query:extensionFunctionCreator"),extensionFunctions:new n.ActionContextKey("@comunica/actor-init-query:extensionFunctions"),extensionFunctionsAlwaysPushdown:new n.ActionContextKey("@comunica/actor-init-query:extensionFunctionsAlwaysPushdown"),cliArgsHandlers:new n.ActionContextKey("@comunica/actor-init-query:cliArgsHandlers"),explain:new n.ActionContextKey("@comunica/actor-init-query:explain"),physicalQueryPlanLogger:new n.ActionContextKey("@comunica/actor-init-query:physicalQueryPlanLogger"),physicalQueryPlanNode:new n.ActionContextKey("@comunica/actor-init-query:physicalQueryPlanNode"),jsonLdContext:new n.ActionContextKey("@context"),invalidateCache:new n.ActionContextKey("@comunica/actor-init-query:invalidateCache"),dataFactory:new n.ActionContextKey("@comunica/actor-init-query:dataFactory"),distinctConstruct:new n.ActionContextKey("@comunica/actor-init-query:distinctConstruct")},t.KeysExpressionEvaluator={extensionFunctionCreator:new n.ActionContextKey("@comunica/utils-expression-evaluator:extensionFunctionCreator"),superTypeProvider:new n.ActionContextKey("@comunica/utils-expression-evaluator:superTypeProvider"),defaultTimeZone:new n.ActionContextKey("@comunica/utils-expression-evaluator:defaultTimeZone"),actionContext:new n.ActionContextKey("@comunica/utils-expression-evaluator:actionContext")},t.KeysQueryOperation={operation:new n.ActionContextKey("@comunica/bus-query-operation:operation"),joinLeftMetadata:new n.ActionContextKey("@comunica/bus-query-operation:joinLeftMetadata"),joinRightMetadatas:new n.ActionContextKey("@comunica/bus-query-operation:joinRightMetadatas"),joinBindings:new n.ActionContextKey("@comunica/bus-query-operation:joinBindings"),readOnly:new n.ActionContextKey("@comunica/bus-query-operation:readOnly"),isPathArbitraryLengthDistinctKey:new n.ActionContextKey("@comunica/bus-query-operation:isPathArbitraryLengthDistinct"),limitIndicator:new n.ActionContextKey("@comunica/bus-query-operation:limitIndicator"),unionDefaultGraph:new n.ActionContextKey("@comunica/bus-query-operation:unionDefaultGraph"),querySources:new n.ActionContextKey("@comunica/bus-query-operation:querySources")},t.KeysRdfParseJsonLd={documentLoader:new n.ActionContextKey("@comunica/actor-rdf-parse-jsonld:documentLoader"),strictValues:new n.ActionContextKey("@comunica/actor-rdf-parse-jsonld:strictValues"),parserOptions:new n.ActionContextKey("@comunica/actor-rdf-parse-jsonld:parserOptions")},t.KeysRdfParseHtmlScript={processingHtmlScript:new n.ActionContextKey("@comunica/actor-rdf-parse-html-script:processingHtmlScript"),extractAllScripts:new n.ActionContextKey("extractAllScripts")},t.KeysQuerySourceIdentify={sourceIds:new n.ActionContextKey("@comunica/bus-query-source-identify:sourceIds"),hypermediaSourcesAggregatedStores:new n.ActionContextKey("@comunica/bus-query-source-identify:hypermediaSourcesAggregatedStores"),traverse:new n.ActionContextKey("@comunica/bus-query-source-identify:traverse")},t.KeysRdfUpdateQuads={destination:new n.ActionContextKey("@comunica/bus-rdf-update-quads:destination")},t.KeysMergeBindingsContext={sourcesBinding:new n.ActionContextKey("@comunica/bus-merge-bindings-context:sourcesBinding")},t.KeysRdfJoin={lastPhysicalJoin:new n.ActionContextKey("@comunica/bus-rdf-join:lastPhysicalJoin")},t.KeysStatistics={discoveredLinks:new n.ActionContextKey("@comunica/statistic:discoveredLinks"),dereferencedLinks:new n.ActionContextKey("@comunica/statistic:dereferencedLinks"),intermediateResults:new n.ActionContextKey("@comunica/statistic:intermediateResults")}},711(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(39),t)},301(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActionContextKey=t.ActionContext=void 0;const n=r(187);class ActionContext{constructor(e={}){this.map=(0,n.Map)(e)}setDefault(e,t){return this.has(e)?this:this.set(e,t)}set(e,t){return this.setRaw(e.name,t)}setRaw(e,t){return new ActionContext(this.map.set(e,t))}delete(e){return new ActionContext(this.map.delete(e.name))}get(e){return this.getRaw(e.name)}getRaw(e){return this.map.get(e)}getSafe(e){if(!this.has(e))throw new Error(`Context entry ${e.name} is required but not available`);return this.get(e)}has(e){return this.hasRaw(e.name)}hasRaw(e){return this.map.has(e)}merge(...e){let t=this;for(const r of e)for(const e of r.keys())t=t.set(e,r.get(e));return t}keys(){return[...this.map.keys()].map(e=>new ActionContextKey(e))}toJS(){return this.map.toJS()}toString(){return`ActionContext(${JSON.stringify(this.map.toJS())})`}[Symbol.for("nodejs.util.inspect.custom")](){return`ActionContext(${JSON.stringify(this.map.toJS(),null," ")})`}static ensureActionContext(e){return e instanceof ActionContext?e:new ActionContext((0,n.Map)(e??{}))}}t.ActionContext=ActionContext;class ActionContextKey{constructor(e){this.name=e}}t.ActionContextKey=ActionContextKey},782(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActionObserver=void 0;t.ActionObserver=class ActionObserver{constructor(e){Object.assign(this,e)}}},681(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Actor=void 0;const n=r(983);class Actor{constructor(e){this.beforeActors=[],Object.assign(this,e),this.bus.subscribe(this),this.beforeActors.length>0&&this.bus.addDependencies(this,this.beforeActors),e.busFailMessage&&(this.bus.failMessage=e.busFailMessage)}static getContextLogger(e){return e.get(n.CONTEXT_KEY_LOGGER)}runObservable(e,t){const r=this.run(e,t);return this.bus.onRun(this,e,r),r}getDefaultLogData(e,t){const r=t?t():{};return r.actor=this.name,r}logTrace(e,t,r){const n=Actor.getContextLogger(e);n&&n.trace(t,this.getDefaultLogData(e,r))}logDebug(e,t,r){const n=Actor.getContextLogger(e);n&&n.debug(t,this.getDefaultLogData(e,r))}logInfo(e,t,r){const n=Actor.getContextLogger(e);n&&n.info(t,this.getDefaultLogData(e,r))}logWarn(e,t,r){const n=Actor.getContextLogger(e);n&&n.warn(t,this.getDefaultLogData(e,r))}logError(e,t,r){const n=Actor.getContextLogger(e);n&&n.error(t,this.getDefaultLogData(e,r))}logFatal(e,t,r){const n=Actor.getContextLogger(e);n&&n.fatal(t,this.getDefaultLogData(e,r))}}t.Actor=Actor},126(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Bus=void 0;t.Bus=class Bus{constructor(e){this.actors=[],this.observers=[],this.dependencyLinks=new Map,Object.assign(this,e),this.failMessage=`All actors over bus ${this.name} failed to handle an action`}subscribe(e){this.actors.push(e),this.reorderForDependencies()}subscribeObserver(e){this.observers.push(e)}unsubscribe(e){const t=this.actors.indexOf(e);return t>=0&&(this.actors.splice(t,1),!0)}unsubscribeObserver(e){const t=this.observers.indexOf(e);return t>=0&&(this.observers.splice(t,1),!0)}publish(e){return this.actors.map(t=>({actor:t,reply:t.test(e)}))}onRun(e,t,r){for(const n of this.observers)n.onRun(e,t,r)}addDependencies(e,t){for(const r of t){let t=this.dependencyLinks.get(r);t||(t=[],this.dependencyLinks.set(r,t)),t.push(e)}this.reorderForDependencies()}reorderForDependencies(){if(this.dependencyLinks.size>0){const e=[];for(const t of this.dependencyLinks.keys()){const r=this.actors.indexOf(t);r>=0&&(this.actors.splice(r,1),e.push(t))}for(;e.length>0;){let t=-1;for(let r=0;r<e.length;r++){let n=!0;for(const t of this.dependencyLinks.get(e[r]))if(!this.actors.includes(t)&&e.includes(t)){n=!1;break}if(n){t=r;break}}if(t<0)throw new Error(`Cyclic dependency links detected in bus ${this.name}`);const r=e.splice(t,1)[0];this.actors.push(r)}}}}},437(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BusIndexed=void 0;const n=r(126);class BusIndexed extends n.Bus{constructor(e){super(e),this.actorsIndex={}}subscribe(e){const t=this.getActorIdentifiers(e)??["_undefined_"];for(const r of t){let t=this.actorsIndex[r];t||(t=this.actorsIndex[r]=[]),t.push(e),super.subscribe(e)}}unsubscribe(e){const t=this.getActorIdentifiers(e)??["_undefined_"];let r=!1;for(const n of t){const t=this.actorsIndex[n];if(t){const r=t.indexOf(e);r>=0&&t.splice(r,1),0===t.length&&delete this.actorsIndex[n]}r=r||super.unsubscribe(e)}return r}publish(e){const t=this.getActionIdentifier(e);if(t){return[...this.actorsIndex[t]||[],...this.actorsIndex._undefined_||[]].map(t=>({actor:t,reply:t.test(e)}))}return super.publish(e)}getActorIdentifiers(e){const t=this.actorIdentifierFields.reduce((e,t)=>e[t],e);if(t)return Array.isArray(t)?t:[t]}getActionIdentifier(e){return this.actionIdentifierFields.reduce((e,t)=>e[t],e)}}t.BusIndexed=BusIndexed},983(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CONTEXT_KEY_LOGGER=void 0;const n=r(301);t.CONTEXT_KEY_LOGGER=new n.ActionContextKey("@comunica/core:log")},991(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Mediator=void 0;class Mediator{constructor(e){Object.assign(this,e)}publish(e){const t=this.bus.publish(e);if(0===t.length)throw new Error(`No actors are able to reply to a message in the bus ${this.bus.name}`);return t}async mediateActor(e){return await this.mediateWith(e,this.publish(e))}async mediateTestable(e){return(await this.mediateActor(e)).mapAsync((t,r)=>t.runObservable(e,r))}async mediate(e){return(await this.mediateTestable(e)).getOrThrow()}constructFailureMessage(e,t){const r="\n ";return`${this.bus.failMessage.replaceAll(/\$\{(.*?)\}/gu,(t,r)=>Mediator.getObjectValue({action:e},r.split("."))||t)}\n Error messages of failing actors:${r}${t.join(r)}`}static getObjectValue(e,t){return 0===t.length?e:e?Mediator.getObjectValue(e[t[0]],t.slice(1)):void 0}}t.Mediator=Mediator},612(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestResultFailed=t.TestResultPassed=t.failTest=t.passTestVoidWithSideData=t.passTestWithSideData=t.passTestVoid=t.passTest=void 0,t.passTest=function(e){return new TestResultPassed(e,void 0)},t.passTestVoid=function(){return new TestResultPassed(!0,void 0)},t.passTestWithSideData=function(e,t){return new TestResultPassed(e,t)},t.passTestVoidWithSideData=function(e){return new TestResultPassed(!0,e)},t.failTest=function(e){return new TestResultFailed(e)};class TestResultPassed{constructor(e,t){this.value=e,this.sideData=t}isPassed(){return!0}isFailed(){return!1}get(){return this.value}getOrThrow(){return this.value}getSideData(){return this.sideData}getFailMessage(){}map(e){return new TestResultPassed(e(this.value,this.sideData),this.sideData)}async mapAsync(e){return new TestResultPassed(await e(this.value,this.sideData),this.sideData)}}t.TestResultPassed=TestResultPassed;class TestResultFailed{constructor(e){this.failMessage=e}isPassed(){return!1}isFailed(){return!0}get(){}getOrThrow(){throw new Error(this.getFailMessage())}getSideData(){throw new Error(this.getFailMessage())}getFailMessage(){return this.failMessage}map(){return this}async mapAsync(){return this}}t.TestResultFailed=TestResultFailed},412(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(301),t),i(r(126),t),i(r(437),t),i(r(983),t),i(r(782),t),i(r(681),t),i(r(991),t),i(r(612),t)},568(e){"use strict";const{AbortController:t,AbortSignal:r}="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t},526(e,t){"use strict";t.toByteArray=function(e){var t,r,s=a(e),o=s[0],c=s[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,o,c)),l=0,h=c>0?o-4:o;for(r=0;r<h;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,s=[],o=16383,a=0,c=n-i;a<c;a+=o)s.push(u(e,a,a+o>c?c:a+o));1===i?(t=e[n-1],s.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],s.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return s.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)r[o]=s[o],n[s.charCodeAt(o)]=o;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function c(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function u(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(c(n));return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287(e,t,r){"use strict";const n=r(526),i=r(251),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=c,t.SlowBuffer=function(e){+e!=e&&(e=0);return c.alloc(+e)},t.INSPECT_MAX_BYTES=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,c.prototype),t}function c(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 h(e)}return u(e,t,r)}function u(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|_(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(G(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(G(e,ArrayBuffer)||e&&G(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(G(e,SharedArrayBuffer)||e&&G(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 c.from(n,t,r);const i=function(e){if(c.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||V(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 c.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 l(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 h(e){return l(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,c.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 _(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||G(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 H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Q(e).length;default:if(i)return n?-1:H(e).length;t=(""+t).toLowerCase(),i=!0}}function g(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 j(this,t,r);case"utf8":case"utf-8":return T(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return k(this,t,r);case"base64":return E(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function w(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),V(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=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:b(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):b(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){let s,o=1,a=e.length,c=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,c/=2,r/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){let n=-1;for(s=r;s<a;s++)if(u(e,s)===u(t,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===c)return n*o}else-1!==n&&(s-=s-n),n=-1}else for(r+c>a&&(r=a-c),s=r;s>=0;s--){let r=!0;for(let n=0;n<c;n++)if(u(e,s+n)!==u(t,n)){r=!1;break}if(r)return s}return-1}function m(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(V(n))return o;e[r+o]=n}return o}function v(e,t,r,n){return J(H(t,e.length-r),e,r,n)}function S(e,t,r,n){return J(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 I(e,t,r,n){return J(Q(t),e,r,n)}function x(e,t,r,n){return J(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 E(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function T(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,c;switch(o){case 1:t<128&&(s=t);break;case 2:r=e[i+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(s=c));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(c=(15&t)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:r=e[i+1],n=e[i+2],a=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&a,c>65535&&c<1114112&&(s=c))}}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<=R)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=R));return r}(n)}t.kMaxLength=o,c.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}}(),c.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(c.prototype,"parent",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.buffer}}),Object.defineProperty(c.prototype,"offset",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.byteOffset}}),c.poolSize=8192,c.from=function(e,t,r){return u(e,t,r)},Object.setPrototypeOf(c.prototype,Uint8Array.prototype),Object.setPrototypeOf(c,Uint8Array),c.alloc=function(e,t,r){return function(e,t,r){return l(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)},c.allocUnsafe=function(e){return h(e)},c.allocUnsafeSlow=function(e){return h(e)},c.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==c.prototype},c.compare=function(e,t){if(G(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),G(t,Uint8Array)&&(t=c.from(t,t.offset,t.byteLength)),!c.isBuffer(e)||!c.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},c.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}},c.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return c.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=c.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(G(t,Uint8Array))i+t.length>n.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},c.byteLength=_,c.prototype._isBuffer=!0,c.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)y(this,t,t+1);return this},c.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)y(this,t,t+3),y(this,t+1,t+2);return this},c.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)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},c.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},c.prototype.toLocaleString=c.prototype.toString,c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},s&&(c.prototype[s]=c.prototype.inspect),c.prototype.compare=function(e,t,r,n,i){if(G(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.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),u=this.slice(n,i),l=e.slice(t,r);for(let e=0;e<a;++e)if(u[e]!==l[e]){s=u[e],o=l[e];break}return s<o?-1:o<s?1:0},c.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},c.prototype.indexOf=function(e,t,r){return w(this,e,t,r,!0)},c.prototype.lastIndexOf=function(e,t,r){return w(this,e,t,r,!1)},c.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 m(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return I(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}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const R=4096;function A(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 k(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 j(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+=X[e[n]];return i}function N(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 O(e,t,r,n,i,s){if(!c.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 C(e,t,r,n,i){z(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 D(e,t,r,n,i){z(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 $(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 U(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}c.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,c.prototype),n},c.prototype.readUintLE=c.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},c.prototype.readUintBE=c.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},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.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]},c.prototype.readUint32BE=c.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])},c.prototype.readBigUInt64LE=Y(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||K(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))}),c.prototype.readBigUInt64BE=Y(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||K(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)}),c.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},c.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},c.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.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},c.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},c.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},c.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]},c.prototype.readBigInt64LE=Y(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||K(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)}),c.prototype.readBigInt64BE=Y(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||K(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)}),c.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){O(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},c.prototype.writeUintBE=c.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){O(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},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||O(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},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||O(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},c.prototype.writeBigUInt64LE=Y(function(e,t=0){return C(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeBigUInt64BE=Y(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);O(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},c.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);O(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},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||O(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},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||O(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},c.prototype.writeBigInt64LE=Y(function(e,t=0){return C(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeBigInt64BE=Y(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeFloatLE=function(e,t,r){return $(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return $(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return U(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return U(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(!c.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},c.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&&!c.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=c.isBuffer(e)?e:c.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 F(e,t,r){M[e]=class NodeError 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 B(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 z(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){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||K(t,e.length-(r+1))}(n,i,s)}function q(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,r){if(Math.floor(e)!==e)throw q(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)}F("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),F("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),F("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=B(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=B(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function H(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 Q(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(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 G(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=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 Y(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},945(e,t,r){var n="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==r.g&&r.g,i=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var n=void 0!==e&&e||"undefined"!=typeof self&&self||void 0!==r.g&&r.g||{},i="URLSearchParams"in n,s="Symbol"in n&&"iterator"in Symbol,o="FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(e){return!1}}(),a="FormData"in n,c="ArrayBuffer"in n;if(c)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],l=ArrayBuffer.isView||function(e){return e&&u.indexOf(Object.prototype.toString.call(e))>-1};function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function d(e){return"string"!=typeof e&&(e=String(e)),e}function f(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return s&&(t[Symbol.iterator]=function(){return t}),t}function p(e){this.map={},e instanceof p?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function _(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function g(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function y(e){var t=new FileReader,r=g(t);return t.readAsArrayBuffer(e),r}function w(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:o&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:a&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:i&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():c&&o&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=w(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c&&(ArrayBuffer.prototype.isPrototypeOf(e)||l(e))?this._bodyArrayBuffer=w(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):i&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var e=_(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var e=_(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}if(o)return this.blob().then(y);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,r,n,i,s=_(this);if(s)return s;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=g(t),n=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=n?n[1]:"utf-8",t.readAsText(e,i),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n<t.length;n++)r[n]=String.fromCharCode(t[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a&&(this.formData=function(){return this.text().then(S)}),this.json=function(){return this.text().then(JSON.parse)},this}p.prototype.append=function(e,t){e=h(e),t=d(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},p.prototype.delete=function(e){delete this.map[h(e)]},p.prototype.get=function(e){return e=h(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(h(e))},p.prototype.set=function(e,t){this.map[h(e)]=d(t)},p.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},p.prototype.keys=function(){var e=[];return this.forEach(function(t,r){e.push(r)}),f(e)},p.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),f(e)},p.prototype.entries=function(){var e=[];return this.forEach(function(t,r){e.push([r,t])}),f(e)},s&&(p.prototype[Symbol.iterator]=p.prototype.entries);var m=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function v(e,t){if(!(this instanceof v))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r,i,s=(t=t||{}).body;if(e instanceof v){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new p(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,s||null==e._bodyInit||(s=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new p(t.headers)),this.method=(r=t.method||this.method||"GET",i=r.toUpperCase(),m.indexOf(i)>-1?i:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in n)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&s)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(s),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var o=/([?&])_=[^&]*/;if(o.test(this.url))this.url=this.url.replace(o,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function S(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}}),t}function I(e,t){if(!(this instanceof I))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},b.call(v.prototype),b.call(I.prototype),I.prototype.clone=function(){return new I(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},I.error=function(){var e=new I(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var x=[301,302,303,307,308];I.redirect=function(e,t){if(-1===x.indexOf(t))throw new RangeError("Invalid status code");return new I(null,{status:t,headers:{location:e}})},t.DOMException=n.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function E(e,r){return new Promise(function(i,s){var a=new v(e,r);if(a.signal&&a.signal.aborted)return s(new t.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function l(){u.abort()}if(u.onload=function(){var e,t,r={statusText:u.statusText,headers:(e=u.getAllResponseHeaders()||"",t=new p,e.replace(/\r?\n[\t ]+/g," ").split("\r").map(function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e}).forEach(function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();try{t.append(n,i)}catch(e){console.warn("Response "+e.message)}}}),t)};0===a.url.indexOf("file://")&&(u.status<200||u.status>599)?r.status=200:r.status=u.status,r.url="responseURL"in u?u.responseURL:r.headers.get("X-Request-URL");var n="response"in u?u.response:u.responseText;setTimeout(function(){i(new I(n,r))},0)},u.onerror=function(){setTimeout(function(){s(new TypeError("Network request failed"))},0)},u.ontimeout=function(){setTimeout(function(){s(new TypeError("Network request timed out"))},0)},u.onabort=function(){setTimeout(function(){s(new t.DOMException("Aborted","AbortError"))},0)},u.open(a.method,function(e){try{return""===e&&n.location.href?n.location.href:e}catch(t){return e}}(a.url),!0),"include"===a.credentials?u.withCredentials=!0:"omit"===a.credentials&&(u.withCredentials=!1),"responseType"in u&&(o?u.responseType="blob":c&&(u.responseType="arraybuffer")),r&&"object"==typeof r.headers&&!(r.headers instanceof p||n.Headers&&r.headers instanceof n.Headers)){var f=[];Object.getOwnPropertyNames(r.headers).forEach(function(e){f.push(h(e)),u.setRequestHeader(e,d(r.headers[e]))}),a.headers.forEach(function(e,t){-1===f.indexOf(t)&&u.setRequestHeader(t,e)})}else a.headers.forEach(function(e,t){u.setRequestHeader(t,e)});a.signal&&(a.signal.addEventListener("abort",l),u.onreadystatechange=function(){4===u.readyState&&a.signal.removeEventListener("abort",l)}),u.send(void 0===a._bodyInit?null:a._bodyInit)})}E.polyfill=!0,n.fetch||(n.fetch=E,n.Headers=p,n.Request=v,n.Response=I),t.Headers=p,t.Request=v,t.Response=I,t.fetch=E}({})}(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=n.fetch?n:i;(t=s.fetch).default=s.fetch,t.fetch=s.fetch,t.Headers=s.Headers,t.Request=s.Request,t.Response=s.Response,e.exports=t},7(e){"use strict";var t,r="object"==typeof Reflect?Reflect:null,n=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise(function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}_(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&_(e,"error",t,r)}(e,i,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function u(e,t,r,n){var i,s,o,u;if(a(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=c(e))>0&&o.length>i&&!o.warned){o.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=o.length,u=l,console&&console.warn&&console.warn(u)}return e}function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=l.bind(n);return i.listener=r,n.wrapFn=i,i}function d(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):p(i,i.length)}function f(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function p(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function _(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){n.once&&e.removeEventListener(t,i),r(s)})}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,s=this._events;if(void 0!==s)i=i&&void 0===s.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var u=c.length,l=p(c,u);for(r=0;r<u;++r)n(l[r],this,t)}return!0},s.prototype.addListener=function(e,t){return u(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return u(this,e,t,!0)},s.prototype.once=function(e,t){return a(t),this.on(e,h(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,h(this,e,t)),this},s.prototype.removeListener=function(e,t){var r,n,i,s,o;if(a(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return d(this,e,!0)},s.prototype.rawListeners=function(e){return d(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},251(e,t){t.read=function(e,t,r,n,i){var s,o,a=8*i-n-1,c=(1<<a)-1,u=c>>1,l=-7,h=r?i-1:0,d=r?-1:1,f=e[t+h];for(h+=d,s=f&(1<<-l)-1,f>>=-l,l+=a;l>0;s=256*s+e[t+h],h+=d,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=n;l>0;o=256*o+e[t+h],h+=d,l-=8);if(0===s)s=1-u;else{if(s===c)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),s-=u}return(f?-1:1)*o*Math.pow(2,s-n)},t.write=function(e,t,r,n,i,s){var o,a,c,u=8*s-i-1,l=(1<<u)-1,h=l>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,p=n?1:-1,_=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(o++,c/=2),o+h>=l?(a=0,o=l):o+h>=1?(a=(t*c-1)*Math.pow(2,i),o+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;e[r+f]=255&o,f+=p,o/=256,u-=8);e[r+f-p]|=128*_}},187(e,t,r){"use strict";r.d(t,{Map:()=>St});var n="@@__IMMUTABLE_INDEXED__@@";function i(e){return Boolean(e&&e[n])}var s="@@__IMMUTABLE_KEYED__@@";function o(e){return Boolean(e&&e[s])}function a(e){return o(e)||i(e)}var c="@@__IMMUTABLE_ITERABLE__@@";function u(e){return Boolean(e&&e[c])}var l=function(e){return u(e)?e:Q(e)},h=function(e){function t(e){return o(e)?e:J(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(l),d=function(e){function t(e){return i(e)?e:G(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(l),f=function(e){function t(e){return u(e)&&!a(e)?e:V(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(l);l.Keyed=h,l.Indexed=d,l.Set=f;var p="function"==typeof Symbol&&Symbol.iterator,_="@@iterator",g=p||_,y=function(e){this.next=e};function w(e,t,r,n){var i=0===e?t:1===e?r:[t,r];return n?n.value=i:n={value:i,done:!1},n}function b(){return{value:void 0,done:!0}}function m(e){return!!Array.isArray(e)||!!I(e)}function v(e){return!(!e||"function"!=typeof e.next)}function S(e){var t=I(e);return t&&t.call(e)}function I(e){var t=e&&(p&&e[p]||e[_]);if("function"==typeof t)return t}y.prototype.toString=function(){return"[Iterator]"},y.KEYS=0,y.VALUES=1,y.ENTRIES=2,y.prototype.inspect=y.prototype.toSource=function(){return this.toString()},y.prototype[g]=function(){return this};var x="delete",E=32,T=31,R={};function A(e){e&&(e.value=!0)}function k(){}function j(e){return void 0===e.size&&(e.size=e.__iterate(P)),e.size}function N(e,t){if("number"!=typeof t){var r=t>>>0;if(""+r!==t||4294967295===r)return NaN;t=r}return t<0?j(e)+t:t}function P(){return!0}function O(e,t,r){return(0===e&&!$(e)||void 0!==r&&e<=-r)&&(void 0===t||void 0!==r&&t>=r)}function C(e,t){return L(e,t,0)}function D(e,t){return L(e,t,t)}function L(e,t,r){return void 0===e?r:$(e)?t===1/0?t:0|Math.max(0,t+e):void 0===t||t===e?e:0|Math.min(t,e)}function $(e){return e<0||0===e&&1/e==-1/0}var U="@@__IMMUTABLE_RECORD__@@";function M(e){return Boolean(e&&e[U])}function F(e){return u(e)||M(e)}var B="@@__IMMUTABLE_ORDERED__@@";function z(e){return Boolean(e&&e[B])}var q="@@__IMMUTABLE_SEQ__@@";function K(e){return Boolean(e&&e[q])}var W=Object.prototype.hasOwnProperty;function H(e){return!(!Array.isArray(e)&&"string"!=typeof e)||e&&"object"==typeof e&&Number.isInteger(e.length)&&e.length>=0&&(0===e.length?1===Object.keys(e).length:e.hasOwnProperty(e.length-1))}var Q=function(e){function t(e){return null==e?te():F(e)?e.toSeq():function(e){var t=ie(e);if(t)return(n=I(r=e))&&n===r.entries?t.fromEntrySeq():function(e){var t=I(e);return t&&t===e.keys}(e)?t.toSetSeq():t;var r,n;if("object"==typeof e)return new Y(e);throw new TypeError("Expected Array or collection object of values, or keyed object: "+e)}(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.toSeq=function(){return this},t.prototype.toString=function(){return this.__toString("Seq {","}")},t.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},t.prototype.__iterate=function(e,t){var r=this._cache;if(r){for(var n=r.length,i=0;i!==n;){var s=r[t?n-++i:i++];if(!1===e(s[1],s[0],this))break}return i}return this.__iterateUncached(e,t)},t.prototype.__iterator=function(e,t){var r=this._cache;if(r){var n=r.length,i=0;return new y(function(){if(i===n)return{value:void 0,done:!0};var s=r[t?n-++i:i++];return w(e,s[0],s[1])})}return this.__iteratorUncached(e,t)},t}(l),J=function(e){function t(e){return null==e?te().toKeyedSeq():u(e)?o(e)?e.toSeq():e.fromEntrySeq():M(e)?e.toSeq():re(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.toKeyedSeq=function(){return this},t}(Q),G=function(e){function t(e){return null==e?te():u(e)?o(e)?e.entrySeq():e.toIndexedSeq():M(e)?e.toSeq().entrySeq():ne(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return t(arguments)},t.prototype.toIndexedSeq=function(){return this},t.prototype.toString=function(){return this.__toString("Seq [","]")},t}(Q),V=function(e){function t(e){return(u(e)&&!a(e)?e:G(e)).toSetSeq()}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return t(arguments)},t.prototype.toSetSeq=function(){return this},t}(Q);Q.isSeq=K,Q.Keyed=J,Q.Set=V,Q.Indexed=G,Q.prototype[q]=!0;var X=function(e){function t(e){this._array=e,this.size=e.length}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.get=function(e,t){return this.has(e)?this._array[N(this,e)]:t},t.prototype.__iterate=function(e,t){for(var r=this._array,n=r.length,i=0;i!==n;){var s=t?n-++i:i++;if(!1===e(r[s],s,this))break}return i},t.prototype.__iterator=function(e,t){var r=this._array,n=r.length,i=0;return new y(function(){if(i===n)return{value:void 0,done:!0};var s=t?n-++i:i++;return w(e,s,r[s])})},t}(G),Y=function(e){function t(e){var t=Object.keys(e).concat(Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e):[]);this._object=e,this._keys=t,this.size=t.length}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.get=function(e,t){return void 0===t||this.has(e)?this._object[e]:t},t.prototype.has=function(e){return W.call(this._object,e)},t.prototype.__iterate=function(e,t){for(var r=this._object,n=this._keys,i=n.length,s=0;s!==i;){var o=n[t?i-++s:s++];if(!1===e(r[o],o,this))break}return s},t.prototype.__iterator=function(e,t){var r=this._object,n=this._keys,i=n.length,s=0;return new y(function(){if(s===i)return{value:void 0,done:!0};var o=n[t?i-++s:s++];return w(e,o,r[o])})},t}(J);Y.prototype[B]=!0;var Z,ee=function(e){function t(e){this._collection=e,this.size=e.length||e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);var r=S(this._collection),n=0;if(v(r))for(var i;!(i=r.next()).done&&!1!==e(i.value,n++,this););return n},t.prototype.__iteratorUncached=function(e,t){if(t)return this.cacheResult().__iterator(e,t);var r=S(this._collection);if(!v(r))return new y(b);var n=0;return new y(function(){var t=r.next();return t.done?t:w(e,n++,t.value)})},t}(G);function te(){return Z||(Z=new X([]))}function re(e){var t=ie(e);if(t)return t.fromEntrySeq();if("object"==typeof e)return new Y(e);throw new TypeError("Expected Array or collection object of [k, v] entries, or keyed object: "+e)}function ne(e){var t=ie(e);if(t)return t;throw new TypeError("Expected Array or collection object of values: "+e)}function ie(e){return H(e)?new X(e):m(e)?new ee(e):void 0}function se(){return this.__ensureOwner()}function oe(){return this.__ownerID?this:this.__ensureOwner(new k)}var ae="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function(e,t){var r=65535&(e|=0),n=65535&(t|=0);return r*n+((e>>>16)*n+r*(t>>>16)<<16>>>0)|0};function ce(e){return e>>>1&1073741824|3221225471&e}var ue=Object.prototype.valueOf;function le(e){if(null==e)return he(e);if("function"==typeof e.hashCode)return ce(e.hashCode(e));var t,r=(t=e).valueOf!==ue&&"function"==typeof t.valueOf?t.valueOf(t):t;if(null==r)return he(r);switch(typeof r){case"boolean":return r?1108378657:1108378656;case"number":return function(e){if(e!=e||e===1/0)return 0;var t=0|e;t!==e&&(t^=4294967295*e);for(;e>4294967295;)t^=e/=4294967295;return ce(t)}(r);case"string":return r.length>Ie?function(e){var t=Te[e];void 0===t&&(t=de(e),Ee===xe&&(Ee=0,Te={}),Ee++,Te[e]=t);return t}(r):de(r);case"object":case"function":return function(e){var t;if(be&&void 0!==(t=we.get(e)))return t;if(t=e[Se],void 0!==t)return t;if(!ge){if(void 0!==(t=e.propertyIsEnumerable&&e.propertyIsEnumerable[Se]))return t;if(void 0!==(t=function(e){if(e&&e.nodeType>0)switch(e.nodeType){case 1:return e.uniqueID;case 9:return e.documentElement&&e.documentElement.uniqueID}}(e)))return t}if(t=ye(),be)we.set(e,t);else{if(void 0!==_e&&!1===_e(e))throw new Error("Non-extensible objects are not allowed as keys.");if(ge)Object.defineProperty(e,Se,{enumerable:!1,configurable:!1,writable:!1,value:t});else if(void 0!==e.propertyIsEnumerable&&e.propertyIsEnumerable===e.constructor.prototype.propertyIsEnumerable)e.propertyIsEnumerable=function(){return this.constructor.prototype.propertyIsEnumerable.apply(this,arguments)},e.propertyIsEnumerable[Se]=t;else{if(void 0===e.nodeType)throw new Error("Unable to set a non-enumerable property on object.");e[Se]=t}}return t}(r);case"symbol":return function(e){var t=me[e];if(void 0!==t)return t;return t=ye(),me[e]=t,t}(r);default:if("function"==typeof r.toString)return de(r.toString());throw new Error("Value type "+typeof r+" cannot be hashed.")}}function he(e){return null===e?1108378658:1108378659}function de(e){for(var t=0,r=0;r<e.length;r++)t=31*t+e.charCodeAt(r)|0;return ce(t)}var fe=(1048576*Math.random()|1)%1048576||40503;function pe(e){if("string"!=typeof e)return le(e);for(var t=0,r=0;r<e.length;r++)t=fe*t+e.charCodeAt(r)|0;return t}var _e=Object.isExtensible,ge=function(){try{return Object.defineProperty({},"@",{}),!0}catch(e){return!1}}();function ye(){var e=++ve;return 1073741824&ve&&(ve=0),e}var we,be="function"==typeof WeakMap;be&&(we=new WeakMap);var me=Object.create(null),ve=0,Se="__immutablehash__";"function"==typeof Symbol&&(Se=Symbol(Se));var Ie=16,xe=255,Ee=0,Te={},Re=function(e){function t(e,t){this._iter=e,this._useKeys=t,this.size=e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.get=function(e,t){return this._iter.get(e,t)},t.prototype.has=function(e){return this._iter.has(e)},t.prototype.valueSeq=function(){return this._iter.valueSeq()},t.prototype.reverse=function(){var e=this,t=Oe(this,!0);return this._useKeys||(t.valueSeq=function(){return e._iter.toSeq().reverse()}),t},t.prototype.map=function(e,t){var r=this,n=Pe(this,e,t);return this._useKeys||(n.valueSeq=function(){return r._iter.toSeq().map(e,t)}),n},t.prototype.__iterate=function(e,t){var r=this;return this._iter.__iterate(function(t,n){return e(t,n,r)},t)},t.prototype.__iterator=function(e,t){return this._iter.__iterator(e,t)},t}(J);Re.prototype[B]=!0;var Ae=function(e){function t(e){this._iter=e,this.size=e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.includes=function(e){return this._iter.includes(e)},t.prototype.__iterate=function(e,t){var r=this,n=0;return t&&j(this),this._iter.__iterate(function(i){return e(i,t?r.size-++n:n++,r)},t)},t.prototype.__iterator=function(e,t){var r=this,n=this._iter.__iterator(1,t),i=0;return t&&j(this),new y(function(){var s=n.next();return s.done?s:w(e,t?r.size-++i:i++,s.value,s)})},t}(G),ke=function(e){function t(e){this._iter=e,this.size=e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.has=function(e){return this._iter.includes(e)},t.prototype.__iterate=function(e,t){var r=this;return this._iter.__iterate(function(t){return e(t,t,r)},t)},t.prototype.__iterator=function(e,t){var r=this._iter.__iterator(1,t);return new y(function(){var t=r.next();return t.done?t:w(e,t.value,t.value,t)})},t}(V),je=function(e){function t(e){this._iter=e,this.size=e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.entrySeq=function(){return this._iter.toSeq()},t.prototype.__iterate=function(e,t){var r=this;return this._iter.__iterate(function(t){if(t){Ke(t);var n=u(t);return e(n?t.get(1):t[1],n?t.get(0):t[0],r)}},t)},t.prototype.__iterator=function(e,t){var r=this._iter.__iterator(1,t);return new y(function(){for(;;){var t=r.next();if(t.done)return t;var n=t.value;if(n){Ke(n);var i=u(n);return w(e,i?n.get(0):n[0],i?n.get(1):n[1],t)}}})},t}(J);function Ne(e){var t=He(e);return t._iter=e,t.size=e.size,t.flip=function(){return e},t.reverse=function(){var t=e.reverse.apply(this);return t.flip=function(){return e.reverse()},t},t.has=function(t){return e.includes(t)},t.includes=function(t){return e.has(t)},t.cacheResult=Qe,t.__iterateUncached=function(t,r){var n=this;return e.__iterate(function(e,r){return!1!==t(r,e,n)},r)},t.__iteratorUncached=function(t,r){if(2===t){var n=e.__iterator(t,r);return new y(function(){var e=n.next();if(!e.done){var t=e.value[0];e.value[0]=e.value[1],e.value[1]=t}return e})}return e.__iterator(1===t?0:1,r)},t}function Pe(e,t,r){var n=He(e);return n.size=e.size,n.has=function(t){return e.has(t)},n.get=function(n,i){var s=e.get(n,R);return s===R?i:t.call(r,s,n,e)},n.__iterateUncached=function(n,i){var s=this;return e.__iterate(function(e,i,o){return!1!==n(t.call(r,e,i,o),i,s)},i)},n.__iteratorUncached=function(n,i){var s=e.__iterator(2,i);return new y(function(){var i=s.next();if(i.done)return i;var o=i.value,a=o[0];return w(n,a,t.call(r,o[1],a,e),i)})},n}function Oe(e,t){var r=He(e);return r._iter=e,r.size=e.size,r.reverse=function(){return e},e.flip&&(r.flip=function(){var t=Ne(e);return t.reverse=function(){return e.flip()},t}),r.get=function(r,n){return e.get(t?r:-1-r,n)},r.has=function(r){return e.has(t?r:-1-r)},r.includes=function(t){return e.includes(t)},r.cacheResult=Qe,r.__iterate=function(r,n){var i=this,s=0;return n&&j(e),e.__iterate(function(e,o){return r(e,t?o:n?i.size-++s:s++,i)},!n)},r.__iterator=function(n,i){var s=0;i&&j(e);var o=e.__iterator(2,!i);return new y(function(){var e=o.next();if(e.done)return e;var a=e.value;return w(n,t?a[0]:i?r.size-++s:s++,a[1],e)})},r}function Ce(e,t,r,n){var i=He(e);return n&&(i.has=function(n){var i=e.get(n,R);return i!==R&&!!t.call(r,i,n,e)},i.get=function(n,i){var s=e.get(n,R);return s!==R&&t.call(r,s,n,e)?s:i}),i.__iterateUncached=function(i,s){var o=this,a=0;return e.__iterate(function(e,s,c){if(t.call(r,e,s,c))return a++,i(e,n?s:a-1,o)},s),a},i.__iteratorUncached=function(i,s){var o=e.__iterator(2,s),a=0;return new y(function(){for(;;){var s=o.next();if(s.done)return s;var c=s.value,u=c[0],l=c[1];if(t.call(r,l,u,e))return w(i,n?u:a++,l,s)}})},i}function De(e,t,r,n){var i=e.size;if(O(t,r,i))return e;if(void 0===i&&(t<0||r<0))return De(e.toSeq().cacheResult(),t,r,n);var s,o=C(t,i),a=D(r,i)-o;a==a&&(s=a<0?0:a);var c=He(e);return c.size=0===s?s:e.size&&s||void 0,!n&&K(e)&&s>=0&&(c.get=function(t,r){return(t=N(this,t))>=0&&t<s?e.get(t+o,r):r}),c.__iterateUncached=function(t,r){var i=this;if(0===s)return 0;if(r)return this.cacheResult().__iterate(t,r);var a=0,c=!0,u=0;return e.__iterate(function(e,r){if(!c||!(c=a++<o))return u++,!1!==t(e,n?r:u-1,i)&&u!==s}),u},c.__iteratorUncached=function(t,r){if(0!==s&&r)return this.cacheResult().__iterator(t,r);if(0===s)return new y(b);var i=e.__iterator(t,r),a=0,c=0;return new y(function(){for(;a++<o;)i.next();if(++c>s)return{value:void 0,done:!0};var e=i.next();return n||1===t||e.done?e:w(t,c-1,0===t?void 0:e.value[1],e)})},c}function Le(e,t,r,n){var i=He(e);return i.__iterateUncached=function(i,s){var o=this;if(s)return this.cacheResult().__iterate(i,s);var a=!0,c=0;return e.__iterate(function(e,s,u){if(!a||!(a=t.call(r,e,s,u)))return c++,i(e,n?s:c-1,o)}),c},i.__iteratorUncached=function(i,s){var o=this;if(s)return this.cacheResult().__iterator(i,s);var a=e.__iterator(2,s),c=!0,u=0;return new y(function(){var e,s,l;do{if((e=a.next()).done)return n||1===i?e:w(i,u++,0===i?void 0:e.value[1],e);var h=e.value;s=h[0],l=h[1],c&&(c=t.call(r,l,s,o))}while(c);return 2===i?e:w(i,s,l,e)})},i}Ae.prototype.cacheResult=Re.prototype.cacheResult=ke.prototype.cacheResult=je.prototype.cacheResult=Qe;var $e=function(e){function t(e){this._wrappedIterables=e.flatMap(function(e){return e._wrappedIterables?e._wrappedIterables:[e]}),this.size=this._wrappedIterables.reduce(function(e,t){if(void 0!==e){var r=t.size;if(void 0!==r)return e+r}},0),this[s]=this._wrappedIterables[0][s],this[n]=this._wrappedIterables[0][n],this[B]=this._wrappedIterables[0][B]}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.__iterateUncached=function(e,t){if(0!==this._wrappedIterables.length){if(t)return this.cacheResult().__iterate(e,t);for(var r=0,n=o(this),i=n?2:1,s=this._wrappedIterables[r].__iterator(i,t),a=!0,c=0;a;){for(var u=s.next();u.done;){if(++r===this._wrappedIterables.length)return c;u=(s=this._wrappedIterables[r].__iterator(i,t)).next()}a=!1!==(n?e(u.value[1],u.value[0],this):e(u.value,c,this)),c++}return c}},t.prototype.__iteratorUncached=function(e,t){var r=this;if(0===this._wrappedIterables.length)return new y(b);if(t)return this.cacheResult().__iterator(e,t);var n=0,i=this._wrappedIterables[n].__iterator(e,t);return new y(function(){for(var s=i.next();s.done;){if(++n===r._wrappedIterables.length)return s;s=(i=r._wrappedIterables[n].__iterator(e,t)).next()}return s})},t}(Q);function Ue(e,t,r){var n=He(e);return n.__iterateUncached=function(i,s){if(s)return this.cacheResult().__iterate(i,s);var o=0,a=!1;return function e(c,l){c.__iterate(function(s,c){return(!t||l<t)&&u(s)?e(s,l+1):(o++,!1===i(s,r?c:o-1,n)&&(a=!0)),!a},s)}(e,0),o},n.__iteratorUncached=function(n,i){if(i)return this.cacheResult().__iterator(n,i);var s=e.__iterator(n,i),o=[],a=0;return new y(function(){for(;s;){var e=s.next();if(!1===e.done){var c=e.value;if(2===n&&(c=c[1]),t&&!(o.length<t)||!u(c))return r?e:w(n,a++,c,e);o.push(s),s=c.__iterator(n,i)}else s=o.pop()}return{value:void 0,done:!0}})},n}function Me(e,t,r){t||(t=Je);var n=o(e),s=0,a=e.toSeq().map(function(t,n){return[n,t,s++,r?r(t,n,e):t]}).valueSeq().toArray();return a.sort(function(e,r){return t(e[3],r[3])||e[2]-r[2]}).forEach(n?function(e,t){a[t].length=2}:function(e,t){a[t]=e[1]}),n?J(a):i(e)?G(a):V(a)}function Fe(e,t,r){if(t||(t=Je),r){var n=e.toSeq().map(function(t,n){return[t,r(t,n,e)]}).reduce(function(e,r){return Be(t,e[1],r[1])?r:e});return n&&n[0]}return e.reduce(function(e,r){return Be(t,e,r)?r:e})}function Be(e,t,r){var n=e(r,t);return 0===n&&r!==t&&(null==r||r!=r)||n>0}function ze(e,t,r,n){var i=He(e),s=new X(r).map(function(e){return e.size});return i.size=n?s.max():s.min(),i.__iterate=function(e,t){for(var r,n=this.__iterator(1,t),i=0;!(r=n.next()).done&&!1!==e(r.value,i++,this););return i},i.__iteratorUncached=function(e,i){var s=r.map(function(e){return e=l(e),S(i?e.reverse():e)}),o=0,a=!1;return new y(function(){var r;return a||(r=s.map(function(e){return e.next()}),a=n?r.every(function(e){return e.done}):r.some(function(e){return e.done})),a?{value:void 0,done:!0}:w(e,o++,t.apply(null,r.map(function(e){return e.value})))})},i}function qe(e,t){return e===t?e:K(e)?t:e.constructor(t)}function Ke(e){if(e!==Object(e))throw new TypeError("Expected [K, V] tuple: "+e)}function We(e){return o(e)?h:i(e)?d:f}function He(e){return Object.create((o(e)?J:i(e)?G:V).prototype)}function Qe(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Q.prototype.cacheResult.call(this)}function Je(e,t){return void 0===e&&void 0===t?0:void 0===e?1:void 0===t?-1:e>t?1:e<t?-1:0}function Ge(e){return Boolean(e&&"function"==typeof e.equals&&"function"==typeof e.hashCode)}function Ve(e,t){if(e===t||e!=e&&t!=t)return!0;if(!e||!t)return!1;if("function"==typeof e.valueOf&&"function"==typeof t.valueOf){if((e=e.valueOf())===(t=t.valueOf())||e!=e&&t!=t)return!0;if(!e||!t)return!1}return!!(Ge(e)&&Ge(t)&&e.equals(t))}function Xe(e,t,r,n){return Jt(e,[t],r,n)}function Ye(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return et(this,e)}function Ze(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];if("function"!=typeof e)throw new TypeError("Invalid merger function: "+e);return et(this,t,e)}function et(e,t,r){for(var n=[],i=0;i<t.length;i++){var s=h(t[i]);0!==s.size&&n.push(s)}return 0===n.length?e:0!==e.toSeq().size||e.__ownerID||1!==n.length?e.withMutations(function(e){for(var t=r?function(t,n){Xe(e,n,R,function(e){return e===R?t:r(e,t,n)})}:function(t,r){e.set(r,t)},i=0;i<n.length;i++)n[i].forEach(t)}):M(e)?e:e.constructor(n[0])}var tt=Object.prototype.toString;function rt(e){if(!e||"object"!=typeof e||"[object Object]"!==tt.call(e))return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;for(var r=t,n=Object.getPrototypeOf(t);null!==n;)r=n,n=Object.getPrototypeOf(r);return r===t}function nt(e){return"object"==typeof e&&(F(e)||Array.isArray(e)||rt(e))}function it(e){return"string"==typeof e&&("__proto__"===e||"constructor"===e)}function st(e,t){t=t||0;for(var r=Math.max(0,e.length-t),n=new Array(r),i=0;i<r;i++)n[i]=e[i+t];return n}function ot(e){if(Array.isArray(e))return st(e);var t={};for(var r in e)it(r)||W.call(e,r)&&(t[r]=e[r]);return t}function at(e,t,r){return ct(e,t,function(e){function t(r,n,s){return nt(r)&&nt(n)&&(a=n,c=Q(r),u=Q(a),i(c)===i(u)&&o(c)===o(u))?ct(r,[n],t):e?e(r,n,s):n;var a,c,u}return t}(r))}function ct(e,t,r){if(!nt(e))throw new TypeError("Cannot merge into non-data-structure value: "+e);if(F(e))return"function"==typeof r&&e.mergeWith?e.mergeWith.apply(e,[r].concat(t)):e.merge?e.merge.apply(e,t):e.concat.apply(e,t);for(var n=Array.isArray(e),i=e,s=n?d:h,o=n?function(t){i===e&&(i=ot(i)),i.push(t)}:function(t,n){if(!it(n)){var s=W.call(i,n),o=s&&r?r(i[n],t,n):t;s&&o===i[n]||(i===e&&(i=ot(i)),i[n]=o)}},a=0;a<t.length;a++)s(t[a]).forEach(o);return i}function ut(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return at(this,e)}function lt(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return at(this,t,e)}function ht(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return Jt(this,e,Ct(),function(e){return at(e,t)})}function dt(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return Jt(this,e,Ct(),function(e){return ct(e,t)})}function ft(e,t){return function(e,t,r){return Jt(e,t,R,function(){return r})}(this,e,t)}function pt(e,t,r){return 1===arguments.length?e(this):Xe(this,e,t,r)}function _t(e,t,r){return Jt(this,e,t,r)}function gt(){return this.__altered}function yt(e){var t=this.asMutable();return e(t),t.wasAltered()?t.__ensureOwner(this.__ownerID):this}var wt="@@__IMMUTABLE_MAP__@@";function bt(e){return Boolean(e&&e[wt])}function mt(e,t){if(!e)throw new Error(t)}function vt(e){mt(e!==1/0,"Cannot perform this action with an infinite size.")}var St=function(e){function t(t){return null==t?Ct():bt(t)&&!z(t)?t:Ct().withMutations(function(r){var n=e(t);vt(n.size),n.forEach(function(e,t){return r.set(t,e)})})}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.toString=function(){return this.__toString("Map {","}")},t.prototype.get=function(e,t){return this._root?this._root.get(0,void 0,e,t):t},t.prototype.set=function(e,t){return Dt(this,e,t)},t.prototype.remove=function(e){return Dt(this,e,R)},t.prototype.deleteAll=function(e){var t=l(e);return 0===t.size?this:this.withMutations(function(e){t.forEach(function(t){return e.remove(t)})})},t.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):Ct()},t.prototype.sort=function(e){return _r(Me(this,e))},t.prototype.sortBy=function(e,t){return _r(Me(this,t,e))},t.prototype.map=function(e,t){var r=this;return this.withMutations(function(n){n.forEach(function(i,s){n.set(s,e.call(t,i,s,r))})})},t.prototype.__iterator=function(e,t){return new jt(this,e,t)},t.prototype.__iterate=function(e,t){var r=this,n=0;return this._root&&this._root.iterate(function(t){return n++,e(t[1],t[0],r)},t),n},t.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?Ot(this.size,this._root,e,this.__hash):0===this.size?Ct():(this.__ownerID=e,this.__altered=!1,this)},t}(h);St.isMap=bt;var It=St.prototype;It[wt]=!0,It[x]=It.remove,It.removeAll=It.deleteAll,It.setIn=ft,It.removeIn=It.deleteIn=Vt,It.update=pt,It.updateIn=_t,It.merge=It.concat=Ye,It.mergeWith=Ze,It.mergeDeep=ut,It.mergeDeepWith=lt,It.mergeIn=dt,It.mergeDeepIn=ht,It.withMutations=yt,It.wasAltered=gt,It.asImmutable=se,It["@@transducer/init"]=It.asMutable=oe,It["@@transducer/step"]=function(e,t){return e.set(t[0],t[1])},It["@@transducer/result"]=function(e){return e.asImmutable()};var xt=function(e,t){this.ownerID=e,this.entries=t};xt.prototype.get=function(e,t,r,n){for(var i=this.entries,s=0,o=i.length;s<o;s++)if(Ve(r,i[s][0]))return i[s][1];return n},xt.prototype.update=function(e,t,r,n,i,s,o){for(var a=i===R,c=this.entries,u=0,l=c.length;u<l&&!Ve(n,c[u][0]);u++);var h=u<l;if(h?c[u][1]===i:a)return this;if(A(o),(a||!h)&&A(s),!a||1!==c.length){if(!h&&!a&&c.length>=Bt)return function(e,t,r,n){e||(e=new k);for(var i=new At(e,le(r),[r,n]),s=0;s<t.length;s++){var o=t[s];i=i.update(e,0,void 0,o[0],o[1])}return i}(e,c,n,i);var d=e&&e===this.ownerID,f=d?c:st(c);return h?a?u===l-1?f.pop():f[u]=f.pop():f[u]=[n,i]:f.push([n,i]),d?(this.entries=f,this):new xt(e,f)}};var Et=function(e,t,r){this.ownerID=e,this.bitmap=t,this.nodes=r};Et.prototype.get=function(e,t,r,n){void 0===t&&(t=le(r));var i=1<<((0===e?t:t>>>e)&T),s=this.bitmap;return 0===(s&i)?n:this.nodes[Mt(s&i-1)].get(e+5,t,r,n)},Et.prototype.update=function(e,t,r,n,i,s,o){void 0===r&&(r=le(n));var a=(0===t?r:r>>>t)&T,c=1<<a,u=this.bitmap,l=0!==(u&c);if(!l&&i===R)return this;var h=Mt(u&c-1),d=this.nodes,f=l?d[h]:void 0,p=Lt(f,e,t+5,r,n,i,s,o);if(p===f)return this;if(!l&&p&&d.length>=zt)return function(e,t,r,n,i){for(var s=0,o=new Array(E),a=0;0!==r;a++,r>>>=1)o[a]=1&r?t[s++]:void 0;return o[n]=i,new Tt(e,s+1,o)}(e,d,u,a,p);if(l&&!p&&2===d.length&&$t(d[1^h]))return d[1^h];if(l&&p&&1===d.length&&$t(p))return p;var _=e&&e===this.ownerID,g=l?p?u:u^c:u|c,y=l?p?Ft(d,h,p,_):function(e,t,r){var n=e.length-1;if(r&&t===n)return e.pop(),e;for(var i=new Array(n),s=0,o=0;o<n;o++)o===t&&(s=1),i[o]=e[o+s];return i}(d,h,_):function(e,t,r,n){var i=e.length+1;if(n&&t+1===i)return e[t]=r,e;for(var s=new Array(i),o=0,a=0;a<i;a++)a===t?(s[a]=r,o=-1):s[a]=e[a+o];return s}(d,h,p,_);return _?(this.bitmap=g,this.nodes=y,this):new Et(e,g,y)};var Tt=function(e,t,r){this.ownerID=e,this.count=t,this.nodes=r};Tt.prototype.get=function(e,t,r,n){void 0===t&&(t=le(r));var i=(0===e?t:t>>>e)&T,s=this.nodes[i];return s?s.get(e+5,t,r,n):n},Tt.prototype.update=function(e,t,r,n,i,s,o){void 0===r&&(r=le(n));var a=(0===t?r:r>>>t)&T,c=i===R,u=this.nodes,l=u[a];if(c&&!l)return this;var h=Lt(l,e,t+5,r,n,i,s,o);if(h===l)return this;var d=this.count;if(l){if(!h&&--d<qt)return function(e,t,r,n){for(var i=0,s=0,o=new Array(r),a=0,c=1,u=t.length;a<u;a++,c<<=1){var l=t[a];void 0!==l&&a!==n&&(i|=c,o[s++]=l)}return new Et(e,i,o)}(e,u,d,a)}else d++;var f=e&&e===this.ownerID,p=Ft(u,a,h,f);return f?(this.count=d,this.nodes=p,this):new Tt(e,d,p)};var Rt=function(e,t,r){this.ownerID=e,this.keyHash=t,this.entries=r,this._index=void 0};Rt.prototype._positionOf=function(e,t){var r=this.entries,n=this._index;if(void 0===n&&t&&r.length>=Kt&&(n=this._buildIndex()),void 0!==n){var i=n[pe(e)];if(void 0!==i)for(var s=0;s<i.length;s++){var o=i[s];if(Ve(e,r[o][0]))return o}return-1}for(var a=0,c=r.length;a<c;a++)if(Ve(e,r[a][0]))return a;return-1},Rt.prototype._buildIndex=function(){for(var e=Object.create(null),t=this.entries,r=0,n=t.length;r<n;r++){var i=pe(t[r][0]),s=e[i];void 0!==s?s.push(r):e[i]=[r]}return this._index=e,e},Rt.prototype.get=function(e,t,r,n){var i=this._positionOf(r,!0);return-1===i?n:this.entries[i][1]},Rt.prototype.update=function(e,t,r,n,i,s,o){void 0===r&&(r=le(n));var a=i===R;if(r!==this.keyHash)return a?this:(A(o),A(s),Ut(this,e,t,r,[n,i]));var c=this.entries,u=c.length,l=e&&e===this.ownerID,h=this._positionOf(n,l),d=-1===h?u:h,f=-1!==h;if(f?c[d][1]===i:a)return this;if(A(o),(a||!f)&&A(s),a&&2===u)return new At(e,this.keyHash,c[1^d]);var p=l?c:st(c);if(f)a?(d===u-1?p.pop():p[d]=p.pop(),l&&(this._index=void 0)):p[d]=[n,i];else if(p.push([n,i]),l&&void 0!==this._index){var _=pe(n),g=this._index[_];void 0!==g?g.push(u):this._index[_]=[u]}return l?(this.entries=p,this):new Rt(e,this.keyHash,p)};var At=function(e,t,r){this.ownerID=e,this.keyHash=t,this.entry=r};At.prototype.get=function(e,t,r,n){return Ve(r,this.entry[0])?this.entry[1]:n},At.prototype.update=function(e,t,r,n,i,s,o){var a=i===R,c=Ve(n,this.entry[0]);return(c?i===this.entry[1]:a)?this:(A(o),a?void A(s):c?e&&e===this.ownerID?(this.entry[1]=i,this):new At(e,this.keyHash,[n,i]):(A(s),Ut(this,e,t,le(n),[n,i])))},xt.prototype.iterate=Rt.prototype.iterate=function(e,t){for(var r=this.entries,n=0,i=r.length-1;n<=i;n++)if(!1===e(r[t?i-n:n]))return!1},Et.prototype.iterate=Tt.prototype.iterate=function(e,t){for(var r=this.nodes,n=0,i=r.length-1;n<=i;n++){var s=r[t?i-n:n];if(s&&!1===s.iterate(e,t))return!1}},At.prototype.iterate=function(e,t){return e(this.entry)};var kt,jt=function(e){function t(e,t,r){this._type=t,this._reverse=r,this._stack=e._root&&Pt(e._root)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.next=function(){for(var e=this._type,t=this._stack;t;){var r=t.node,n=t.index++,i=void 0;if(r.entry){if(0===n)return Nt(e,r.entry)}else if(r.entries){if(n<=(i=r.entries.length-1))return Nt(e,r.entries[this._reverse?i-n:n])}else if(n<=(i=r.nodes.length-1)){var s=r.nodes[this._reverse?i-n:n];if(s){if(s.entry)return Nt(e,s.entry);t=this._stack=Pt(s,t)}continue}t=this._stack=this._stack.__prev}return{value:void 0,done:!0}},t}(y);function Nt(e,t){return w(e,t[0],t[1])}function Pt(e,t){return{node:e,index:0,__prev:t}}function Ot(e,t,r,n){var i=Object.create(It);return i.size=e,i._root=t,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function Ct(){return kt||(kt=Ot(0))}function Dt(e,t,r){var n,i;if(e._root){var s={value:!1},o={value:!1};if(n=Lt(e._root,e.__ownerID,0,void 0,t,r,s,o),!o.value)return e;i=e.size+(s.value?r===R?-1:1:0)}else{if(r===R)return e;i=1,n=new xt(e.__ownerID,[[t,r]])}return e.__ownerID?(e.size=i,e._root=n,e.__hash=void 0,e.__altered=!0,e):n?Ot(i,n):Ct()}function Lt(e,t,r,n,i,s,o,a){return e?e.update(t,r,n,i,s,o,a):s===R?e:(A(a),A(o),new At(t,n,[i,s]))}function $t(e){return e.constructor===At||e.constructor===Rt}function Ut(e,t,r,n,i){if(e.keyHash===n)return new Rt(t,n,[e.entry,i]);var s,o=(0===r?e.keyHash:e.keyHash>>>r)&T,a=(0===r?n:n>>>r)&T,c=o===a?[Ut(e,t,r+5,n,i)]:(s=new At(t,n,i),o<a?[e,s]:[s,e]);return new Et(t,1<<o|1<<a,c)}function Mt(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,e+=e>>8,127&(e+=e>>16)}function Ft(e,t,r,n){var i=n?e:st(e);return i[t]=r,i}var Bt=8,zt=16,qt=8,Kt=16;function Wt(e){if(H(e)&&"string"!=typeof e)return e;if(z(e))return e.toArray();throw new TypeError("Invalid keyPath: expected Ordered Collection or Array: "+e)}function Ht(e){try{return"string"==typeof e?JSON.stringify(e):String(e)}catch(t){return JSON.stringify(e)}}function Qt(e,t,r){return F(e)?e.get(t,r):function(e,t){return F(e)?e.has(t):nt(e)&&W.call(e,t)}(e,t)?"function"==typeof e.get?e.get(t):e[t]:r}function Jt(e,t,r,n){n||(n=r,r=void 0);var i=Gt(F(e),e,Wt(t),0,r,n);return i===R?r:i}function Gt(e,t,r,n,i,s){var o=t===R;if(n===r.length){var a=o?i:t,c=s(a);return c===a?t:c}if(!o&&!nt(t))throw new TypeError("Cannot update within non-data-structure value in path ["+Array.from(r).slice(0,n).map(Ht)+"]: "+t);var u=r[n],l=o?R:Qt(t,u,R),h=Gt(l===R?e:F(l),l,r,n+1,i,s);return h===l?t:h===R?function(e,t){if(!nt(e))throw new TypeError("Cannot update non-data-structure value: "+e);if(F(e)){if(!e.remove)throw new TypeError("Cannot update immutable value without .remove() method: "+e);return e.remove(t)}if(!W.call(e,t))return e;var r=ot(e);return Array.isArray(r)?r.splice(t,1):delete r[t],r}(t,u):function(e,t,r){if(it(t))return e;if(!nt(e))throw new TypeError("Cannot update non-data-structure value: "+e);if(F(e)){if(!e.set)throw new TypeError("Cannot update immutable value without .set() method: "+e);return e.set(t,r)}if(W.call(e,t)&&r===e[t])return e;var n=ot(e);return n[t]=r,n}(o?e?Ct():{}:t,u,h)}function Vt(e){return function(e,t){return Jt(e,t,function(){return R})}(this,e)}var Xt="@@__IMMUTABLE_LIST__@@";function Yt(e){return Boolean(e&&e[Xt])}var Zt=function(e){function t(t){var r=sr();if(null==t)return r;if(Yt(t))return t;var n=e(t),i=n.size;return 0===i?r:(vt(i),i>0&&i<E?ir(0,i,5,void 0,new tr(n.toArray())):r.withMutations(function(e){e.setSize(i),n.forEach(function(t,r){return e.set(r,t)})}))}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.prototype.toString=function(){return this.__toString("List [","]")},t.prototype.get=function(e,t){if((e=N(this,e))>=0&&e<this.size){var r=cr(this,e+=this._origin);return r&&r.array[e&T]}return t},t.prototype.set=function(e,t){return function(e,t,r){if(t=N(e,t),t!=t)return e;if(t>=e.size||t<0)return e.withMutations(function(e){t<0?ur(e,t).set(0,r):ur(e,0,t+1).set(t,r)});t+=e._origin;var n=e._tail,i=e._root,s={value:!1};t>=lr(e._capacity)?n=or(n,e.__ownerID,0,t,r,s):i=or(i,e.__ownerID,e._level,t,r,s);if(!s.value)return e;if(e.__ownerID)return e._root=i,e._tail=n,e.__hash=void 0,e.__altered=!0,e;return ir(e._origin,e._capacity,e._level,i,n)}(this,e,t)},t.prototype.remove=function(e){return this.has(e)?0===e?this.shift():e===this.size-1?this.pop():this.splice(e,1):this},t.prototype.insert=function(e,t){return this.splice(e,0,t)},t.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=5,this._root=this._tail=this.__hash=void 0,this.__altered=!0,this):sr()},t.prototype.push=function(){var e=arguments,t=this.size;return this.withMutations(function(r){ur(r,0,t+e.length);for(var n=0;n<e.length;n++)r.set(t+n,e[n])})},t.prototype.pop=function(){return ur(this,0,-1)},t.prototype.unshift=function(){var e=arguments;return this.withMutations(function(t){ur(t,-e.length);for(var r=0;r<e.length;r++)t.set(r,e[r])})},t.prototype.shift=function(){return ur(this,1)},t.prototype.shuffle=function(e){return void 0===e&&(e=Math.random),this.withMutations(function(t){for(var r,n,i=t.size;i;)r=Math.floor(e()*i--),n=t.get(r),t.set(r,t.get(i)),t.set(i,n)})},t.prototype.concat=function(){for(var t=arguments,r=[],n=0;n<arguments.length;n++){var i=t[n],s=e("string"!=typeof i&&m(i)?i:[i]);0!==s.size&&r.push(s)}return 0===r.length?this:0!==this.size||this.__ownerID||1!==r.length?this.withMutations(function(e){r.forEach(function(t){return t.forEach(function(t){return e.push(t)})})}):this.constructor(r[0])},t.prototype.setSize=function(e){return ur(this,0,e)},t.prototype.map=function(e,t){var r=this;return this.withMutations(function(n){for(var i=0;i<r.size;i++)n.set(i,e.call(t,n.get(i),i,r))})},t.prototype.slice=function(e,t){var r=this.size;return O(e,t,r)?this:ur(this,C(e,r),D(t,r))},t.prototype.__iterator=function(e,t){var r=t?this.size:0,n=nr(this,t);return new y(function(){var i=n();return i===rr?{value:void 0,done:!0}:w(e,t?--r:r++,i)})},t.prototype.__iterate=function(e,t){for(var r,n=t?this.size:0,i=nr(this,t);(r=i())!==rr&&!1!==e(r,t?--n:n++,this););return n},t.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?ir(this._origin,this._capacity,this._level,this._root,this._tail,e,this.__hash):0===this.size?sr():(this.__ownerID=e,this.__altered=!1,this)},t}(d);Zt.isList=Yt;var er=Zt.prototype;er[Xt]=!0,er[x]=er.remove,er.merge=er.concat,er.setIn=ft,er.deleteIn=er.removeIn=Vt,er.update=pt,er.updateIn=_t,er.mergeIn=dt,er.mergeDeepIn=ht,er.withMutations=yt,er.wasAltered=gt,er.asImmutable=se,er["@@transducer/init"]=er.asMutable=oe,er["@@transducer/step"]=function(e,t){return e.push(t)},er["@@transducer/result"]=function(e){return e.asImmutable()};var tr=function(e,t){this.array=e,this.ownerID=t};tr.prototype.removeBefore=function(e,t,r){if(!(r&(1<<t+5)-1)||0===this.array.length)return this;var n=r>>>t&T;if(n>=this.array.length)return new tr([],e);var i,s=0===n;if(t>0){var o=this.array[n];if((i=o&&o.removeBefore(e,t-5,r))===o&&s)return this}if(s&&!i)return this;var a=ar(this,e);if(!s)for(var c=0;c<n;c++)a.array[c]=void 0;return i&&(a.array[n]=i),a},tr.prototype.removeAfter=function(e,t,r){if(r===(t?1<<t+5:E)||0===this.array.length)return this;var n,i=r-1>>>t&T;if(i>=this.array.length)return this;if(t>0){var s=this.array[i];if((n=s&&s.removeAfter(e,t-5,r))===s&&i===this.array.length-1)return this}var o=ar(this,e);return o.array.splice(i+1),n&&(o.array[i]=n),o};var rr={};function nr(e,t){var r=e._origin,n=e._capacity,i=lr(n),s=e._tail;return o(e._root,e._level,0);function o(e,a,c){return 0===a?function(e,o){var a=o===i?s&&s.array:e&&e.array,c=o>r?0:r-o,u=n-o;u>E&&(u=E);return function(){if(c===u)return rr;var e=t?--u:c++;return a&&a[e]}}(e,c):function(e,i,s){var a,c=e&&e.array,u=s>r?0:r-s>>i,l=1+(n-s>>i);l>E&&(l=E);return function(){for(;;){if(a){var e=a();if(e!==rr)return e;a=null}if(u===l)return rr;var r=t?--l:u++;a=o(c&&c[r],i-5,s+(r<<i))}}}(e,a,c)}}function ir(e,t,r,n,i,s,o){var a=Object.create(er);return a.size=t-e,a._origin=e,a._capacity=t,a._level=r,a._root=n,a._tail=i,a.__ownerID=s,a.__hash=o,a.__altered=!1,a}function sr(){return ir(0,0,5)}function or(e,t,r,n,i,s){var o,a=n>>>r&T,c=e&&a<e.array.length;if(!c&&void 0===i)return e;if(r>0){var u=e&&e.array[a],l=or(u,t,r-5,n,i,s);return l===u?e:((o=ar(e,t)).array[a]=l,o)}return c&&e.array[a]===i?e:(s&&A(s),o=ar(e,t),void 0===i&&a===o.array.length-1?o.array.pop():o.array[a]=i,o)}function ar(e,t){return t&&e&&t===e.ownerID?e:new tr(e?e.array.slice():[],t)}function cr(e,t){if(t>=lr(e._capacity))return e._tail;if(t<1<<e._level+5){for(var r=e._root,n=e._level;r&&n>0;)r=r.array[t>>>n&T],n-=5;return r}}function ur(e,t,r){!function(e,t,r){var n=e._origin+(void 0===t?0:t),i=void 0===r?e._capacity:r<0?e._capacity+r:e._origin+r;if(Number.isFinite(i)&&i>hr||Number.isFinite(n)&&n<-hr||Number.isFinite(i)&&Number.isFinite(n)&&i-n>hr)throw new RangeError("Invalid List size: a List cannot hold more than "+hr+" (2 ** 30) values.")}(e,t,r),void 0!==t&&(t|=0),void 0!==r&&(r|=0);var n=e.__ownerID||new k,i=e._origin,s=e._capacity,o=i+t,a=void 0===r?s:r<0?s+r:i+r;if(o===i&&a===s)return e;if(o>=a)return e.clear();for(var c=e._level,u=e._root,l=0;o+l<0;)u=new tr(u&&u.array.length?[void 0,u]:[],n),l+=dr(c+=5);l&&(o+=l,i+=l,a+=l,s+=l);for(var h=lr(s),d=lr(a);d>=dr(c+5);)u=new tr(u&&u.array.length?[u]:[],n),c+=5;var f=e._tail,p=d<h?cr(e,a-1):d>h?new tr([],n):f;if(f&&d>h&&o<s&&f.array.length){for(var _=u=ar(u,n),g=c;g>5;g-=5){var y=h>>>g&T;_=_.array[y]=ar(_.array[y],n)}_.array[h>>>5&T]=f}if(a<s&&(p=p&&p.removeAfter(n,0,a)),o>=d)o-=d,a-=d,c=5,u=void 0,p=p&&p.removeBefore(n,0,o);else if(o>i||d<h){for(l=0;u;){var w=o>>>c&T;if(w!==d>>>c&T)break;w&&(l+=(1<<c)*w),c-=5,u=u.array[w]}u&&o>i&&(u=u.removeBefore(n,c,o-l)),u&&d<h&&(u=u.removeAfter(n,c,d-l)),l&&(o-=l,a-=l)}return e.__ownerID?(e.size=a-o,e._origin=o,e._capacity=a,e._level=c,e._root=u,e._tail=p,e.__hash=void 0,e.__altered=!0,e):ir(o,a,c,u,p)}function lr(e){return e<E?0:e-1>>>5<<5}var hr=Math.pow(2,30);function dr(e){return e<31?1<<e:Math.pow(2,e)}function fr(e){return bt(e)&&z(e)}var pr,_r=function(e){function t(e){return null==e?yr():fr(e)?e:yr().withMutations(function(t){var r=h(e);vt(r.size),r.forEach(function(e,r){return t.set(r,e)})})}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.prototype.toString=function(){return this.__toString("OrderedMap {","}")},t.prototype.get=function(e,t){var r=this._map.get(e);return void 0!==r?this._list.get(r)[1]:t},t.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this.__altered=!0,this):yr()},t.prototype.set=function(e,t){return wr(this,e,t)},t.prototype.remove=function(e){return wr(this,e,R)},t.prototype.__iterate=function(e,t){var r=this;return this._list.__iterate(function(t){return t&&e(t[1],t[0],r)},t)},t.prototype.__iterator=function(e,t){return this._list.fromEntrySeq().__iterator(e,t)},t.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map.__ensureOwner(e),r=this._list.__ensureOwner(e);return e?gr(t,r,e,this.__hash):0===this.size?yr():(this.__ownerID=e,this.__altered=!1,this._map=t,this._list=r,this)},t}(St);function gr(e,t,r,n){var i=Object.create(_r.prototype);return i.size=e?e.size:0,i._map=e,i._list=t,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function yr(){return pr||(pr=gr(Ct(),sr()))}function wr(e,t,r){var n,i,s=e._map,o=e._list,a=s.get(t),c=void 0!==a;if(r===R){if(!c)return e;o.size>=E&&o.size>=2*s.size?(n=(i=o.filter(function(e,t){return void 0!==e&&a!==t})).toKeyedSeq().map(function(e){return e[0]}).flip().toMap(),e.__ownerID&&(n.__ownerID=i.__ownerID=e.__ownerID)):(n=s.remove(t),i=a===o.size-1?o.pop():o.set(a,void 0))}else if(c){if(r===o.get(a)[1])return e;n=s,i=o.set(a,[t,r])}else n=s.set(t,o.size),i=o.set(o.size,[t,r]);return e.__ownerID?(e.size=n.size,e._map=n,e._list=i,e.__hash=void 0,e.__altered=!0,e):gr(n,i)}_r.isOrderedMap=fr,_r.prototype[B]=!0,_r.prototype[x]=_r.prototype.remove;var br="@@__IMMUTABLE_STACK__@@";function mr(e){return Boolean(e&&e[br])}var vr=function(e){function t(e){return null==e?Er():mr(e)?e:Er().pushAll(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.prototype.toString=function(){return this.__toString("Stack [","]")},t.prototype.get=function(e,t){var r=this._head;for(e=N(this,e);r&&e--;)r=r.next;return r?r.value:t},t.prototype.peek=function(){return this._head&&this._head.value},t.prototype.push=function(){var e=arguments;if(0===arguments.length)return this;for(var t=this.size+arguments.length,r=this._head,n=arguments.length-1;n>=0;n--)r={value:e[n],next:r};return this.__ownerID?(this.size=t,this._head=r,this.__hash=void 0,this.__altered=!0,this):xr(t,r)},t.prototype.pushAll=function(t){if(0===(t=e(t)).size)return this;if(0===this.size&&mr(t))return t;vt(t.size);var r=this.size,n=this._head;return t.__iterate(function(e){r++,n={value:e,next:n}},!0),this.__ownerID?(this.size=r,this._head=n,this.__hash=void 0,this.__altered=!0,this):xr(r,n)},t.prototype.pop=function(){return this.slice(1)},t.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Er()},t.prototype.slice=function(t,r){if(O(t,r,this.size))return this;var n=C(t,this.size);if(D(r,this.size)!==this.size)return e.prototype.slice.call(this,t,r);for(var i=this.size-n,s=this._head;n--;)s=s.next;return this.__ownerID?(this.size=i,this._head=s,this.__hash=void 0,this.__altered=!0,this):xr(i,s)},t.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?xr(this.size,this._head,e,this.__hash):0===this.size?Er():(this.__ownerID=e,this.__altered=!1,this)},t.prototype.__iterate=function(e,t){var r=this;if(t)return new X(this.toArray()).__iterate(function(t,n){return e(t,n,r)},t);for(var n=0,i=this._head;i&&!1!==e(i.value,n++,this);)i=i.next;return n},t.prototype.__iterator=function(e,t){if(t)return new X(this.toArray()).__iterator(e,t);var r=0,n=this._head;return new y(function(){if(n){var t=n.value;return n=n.next,w(e,r++,t)}return{value:void 0,done:!0}})},t}(d);vr.isStack=mr;var Sr,Ir=vr.prototype;function xr(e,t,r,n){var i=Object.create(Ir);return i.size=e,i._head=t,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function Er(){return Sr||(Sr=xr(0))}function Tr(e,t,r,n,i,s){return vt(e.size),e.__iterate(function(e,s,o){i?(i=!1,r=e):r=t.call(n,r,e,s,o)},s),r}function Rr(e,t){return t}function Ar(e,t){return[t,e]}function kr(e){return function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return!e.apply(this,t)}}function jr(e){return function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return-e.apply(this,t)}}function Nr(e,t){return e<t?1:e>t?-1:0}function Pr(e,t){if(e===t)return!0;if(!u(t)||void 0!==e.size&&void 0!==t.size&&e.size!==t.size||void 0!==e.__hash&&void 0!==t.__hash&&e.__hash!==t.__hash||o(e)!==o(t)||i(e)!==i(t)||z(e)!==z(t))return!1;if(0===e.size&&0===t.size)return!0;var r=!a(e);if(z(e)){var n=e.entries();return t.every(function(e,t){var i=n.next().value;return i&&Ve(i[1],e)&&(r||Ve(i[0],t))})&&n.next().done}var s=!1;if(void 0===e.size)if(void 0===t.size)"function"==typeof e.cacheResult&&e.cacheResult();else{s=!0;var c=e;e=t,t=c}var l=!0,h=t.__iterate(function(t,n){if(r?!e.has(t):s?!Ve(t,e.get(n,R)):!Ve(e.get(n,R),t))return l=!1,!1});return l&&e.size===h}Ir[br]=!0,Ir.shift=Ir.pop,Ir.unshift=Ir.push,Ir.unshiftAll=Ir.pushAll,Ir.withMutations=yt,Ir.wasAltered=gt,Ir.asImmutable=se,Ir["@@transducer/init"]=Ir.asMutable=oe,Ir["@@transducer/step"]=function(e,t){return e.unshift(t)},Ir["@@transducer/result"]=function(e){return e.asImmutable()};var Or,Cr=function(e){function t(e,r,n){if(void 0===n&&(n=1),!(this instanceof t))return new t(e,r,n);if(mt(0!==n,"Cannot step a Range by 0"),mt(void 0!==e,"You must define a start value when using Range"),mt(void 0!==r,"You must define an end value when using Range"),n=Math.abs(n),r<e&&(n=-n),this._start=e,this._end=r,this._step=n,this.size=Math.max(0,Math.ceil((r-e)/n-1)+1),0===this.size){if(Or)return Or;Or=this}}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.toString=function(){return 0===this.size?"Range []":"Range [ "+this._start+"..."+this._end+(1!==this._step?" by "+this._step:"")+" ]"},t.prototype.get=function(e,t){return this.has(e)?this._start+N(this,e)*this._step:t},t.prototype.includes=function(e){var t=(e-this._start)/this._step;return t>=0&&t<this.size&&t===Math.floor(t)},t.prototype.slice=function(e,r){return O(e,r,this.size)?this:(e=C(e,this.size),(r=D(r,this.size))<=e?new t(0,0):new t(this.get(e,this._end),this.get(r,this._end),this._step))},t.prototype.indexOf=function(e){var t=e-this._start;if(t%this._step===0){var r=t/this._step;if(r>=0&&r<this.size)return r}return-1},t.prototype.lastIndexOf=function(e){return this.indexOf(e)},t.prototype.__iterate=function(e,t){for(var r=this.size,n=this._step,i=t?this._start+(r-1)*n:this._start,s=0;s!==r&&!1!==e(i,t?r-++s:s++,this);)i+=t?-n:n;return s},t.prototype.__iterator=function(e,t){var r=this.size,n=this._step,i=t?this._start+(r-1)*n:this._start,s=0;return new y(function(){if(s===r)return{value:void 0,done:!0};var o=i;return i+=t?-n:n,w(e,t?r-++s:s++,o)})},t.prototype.equals=function(e){return e instanceof t?this._start===e._start&&this._end===e._end&&this._step===e._step:Pr(this,e)},t}(G),Dr="@@__IMMUTABLE_SET__@@";function Lr(e){return Boolean(e&&e[Dr])}var $r=function(e){function t(t){return null==t?zr():Lr(t)&&!z(t)?t:zr().withMutations(function(r){var n=e(t);vt(n.size),n.forEach(function(e){return r.add(e)})})}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.fromKeys=function(e){return this(h(e).keySeq())},t.intersect=function(e){return(e=l(e).toArray()).length?Mr.intersect.apply(t(e.pop()),e):zr()},t.union=function(e){return(e=l(e).toArray()).length?Mr.union.apply(t(e.pop()),e):zr()},t.prototype.toString=function(){return this.__toString("Set {","}")},t.prototype.has=function(e){return this._map.has(e)},t.prototype.add=function(e){return Fr(this,this._map.set(e,e))},t.prototype.remove=function(e){return Fr(this,this._map.remove(e))},t.prototype.clear=function(){return Fr(this,this._map.clear())},t.prototype.map=function(e,t){var r=this,n=!1,i=Fr(this,this._map.mapEntries(function(i){var s=i[1],o=e.call(t,s,s,r);return o!==s&&(n=!0),[o,o]},t));return n?i:this},t.prototype.union=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return 0===(t=t.filter(function(e){return 0!==e.size})).length?this:0!==this.size||this.__ownerID||1!==t.length?this.withMutations(function(r){for(var n=0;n<t.length;n++)"string"==typeof t[n]?r.add(t[n]):e(t[n]).forEach(function(e){return r.add(e)})}):this.constructor(t[0])},t.prototype.intersect=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];if(0===t.length)return this;t=t.map(function(t){return e(t)});var n=[];return this.forEach(function(e){t.every(function(t){return t.includes(e)})||n.push(e)}),this.withMutations(function(e){n.forEach(function(t){e.remove(t)})})},t.prototype.subtract=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];if(0===t.length)return this;t=t.map(function(t){return e(t)});var n=[];return this.forEach(function(e){t.some(function(t){return t.includes(e)})&&n.push(e)}),this.withMutations(function(e){n.forEach(function(t){e.remove(t)})})},t.prototype.sort=function(e){return rn(Me(this,e))},t.prototype.sortBy=function(e,t){return rn(Me(this,t,e))},t.prototype.wasAltered=function(){return this._map.wasAltered()},t.prototype.__iterate=function(e,t){var r=this;return this._map.__iterate(function(t){return e(t,t,r)},t)},t.prototype.__iterator=function(e,t){return this._map.__iterator(e,t)},t.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map.__ensureOwner(e);return e?this.__make(t,e):0===this.size?this.__empty():(this.__ownerID=e,this._map=t,this)},t}(f);$r.isSet=Lr;var Ur,Mr=$r.prototype;function Fr(e,t){return e.__ownerID?(e.size=t.size,e._map=t,e):t===e._map?e:0===t.size?e.__empty():e.__make(t)}function Br(e,t){var r=Object.create(Mr);return r.size=e?e.size:0,r._map=e,r.__ownerID=t,r}function zr(){return Ur||(Ur=Br(Ct()))}function qr(e,t,r){for(var n=Wt(t),i=0;i!==n.length;)if((e=Qt(e,n[i++],R))===R)return r;return e}function Kr(e,t){return qr(this,e,t)}function Wr(){vt(this.size);var e={};return this.__iterate(function(t,r){it(r)||(e[r]=t)}),e}function Hr(e){if(!e||"object"!=typeof e)return e;if(!u(e)){if(!nt(e))return e;e=Q(e)}if(o(e)){var t={};return e.__iterate(function(e,r){it(r)||(t[r]=Hr(e))}),t}var r=[];return e.__iterate(function(e){r.push(Hr(e))}),r}function Qr(e){if(e.size===1/0)return 0;var t=z(e),r=o(e),n=t?1:0;return e.__iterate(r?t?function(e,t){n=31*n+Jr(le(e),le(t))|0}:function(e,t){n=n+Jr(le(e),le(t))|0}:t?function(e){n=31*n+le(e)|0}:function(e){n=n+le(e)|0}),function(e,t){return t=ae(t,3432918353),t=ae(t<<15|t>>>-15,461845907),t=ae(t<<13|t>>>-13,5),t=(t+3864292196|0)^e,t=ae(t^t>>>16,2246822507),t=ae(t^t>>>13,3266489909),t=ce(t^t>>>16),t}(e.size,n)}function Jr(e,t){return e^t+2654435769+(e<<6)+(e>>2)|0}function Gr(e,t){var r=function(r){e.prototype[r]=t[r]};return Object.keys(t).forEach(r),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(t).forEach(r),e}Mr[Dr]=!0,Mr[x]=Mr.remove,Mr.merge=Mr.concat=Mr.union,Mr.withMutations=yt,Mr.asImmutable=se,Mr["@@transducer/init"]=Mr.asMutable=oe,Mr["@@transducer/step"]=function(e,t){return e.add(t)},Mr["@@transducer/result"]=function(e){return e.asImmutable()},Mr.__empty=zr,Mr.__make=Br,l.Iterator=y,Gr(l,{toArray:function(){vt(this.size);var e=new Array(this.size||0),t=o(this),r=0;return this.__iterate(function(n,i){e[r++]=t?[i,n]:n}),e},toIndexedSeq:function(){return new Ae(this)},toJS:function(){return Hr(this)},toKeyedSeq:function(){return new Re(this,!0)},toMap:function(){return St(this.toKeyedSeq())},toObject:Wr,toOrderedMap:function(){return _r(this.toKeyedSeq())},toOrderedSet:function(){return rn(o(this)?this.valueSeq():this)},toSet:function(){return $r(o(this)?this.valueSeq():this)},toSetSeq:function(){return new ke(this)},toSeq:function(){return i(this)?this.toIndexedSeq():o(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return vr(o(this)?this.valueSeq():this)},toList:function(){return Zt(o(this)?this.valueSeq():this)},toString:function(){return"[Collection]"},__toString:function(e,t){return 0===this.size?e+t:e+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+t},concat:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return qe(this,function(e,t){var r=o(e),n=[e].concat(t).map(function(e){return u(e)?r&&(e=h(e)):e=r?re(e):ne(Array.isArray(e)?e:[e]),e}).filter(function(e){return 0!==e.size});if(0===n.length)return e;if(1===n.length){var s=n[0];if(s===e||r&&o(s)||i(e)&&i(s))return s}return new $e(n)}(this,e))},includes:function(e){return this.some(function(t){return Ve(t,e)})},entries:function(){return this.__iterator(2)},every:function(e,t){vt(this.size);var r=!0;return this.__iterate(function(n,i,s){if(!e.call(t,n,i,s))return r=!1,!1}),r},filter:function(e,t){return qe(this,Ce(this,e,t,!0))},partition:function(e,t){return function(e,t,r){var n=o(e),i=[[],[]];e.__iterate(function(s,o){i[t.call(r,s,o,e)?1:0].push(n?[o,s]:s)});var s=We(e);return i.map(function(t){return qe(e,s(t))})}(this,e,t)},find:function(e,t,r){var n=this.findEntry(e,t);return n?n[1]:r},forEach:function(e,t){return vt(this.size),this.__iterate(t?e.bind(t):e)},join:function(e){vt(this.size),e=void 0!==e?""+e:",";var t="",r=!0;return this.__iterate(function(n){r?r=!1:t+=e,t+=null!=n?n.toString():""}),t},keys:function(){return this.__iterator(0)},map:function(e,t){return qe(this,Pe(this,e,t))},reduce:function(e,t,r){return Tr(this,e,t,r,arguments.length<2,!1)},reduceRight:function(e,t,r){return Tr(this,e,t,r,arguments.length<2,!0)},reverse:function(){return qe(this,Oe(this,!0))},slice:function(e,t){return qe(this,De(this,e,t,!0))},some:function(e,t){vt(this.size);var r=!1;return this.__iterate(function(n,i,s){if(e.call(t,n,i,s))return r=!0,!1}),r},sort:function(e){return qe(this,Me(this,e))},values:function(){return this.__iterator(1)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some(function(){return!0})},count:function(e,t){return j(e?this.toSeq().filter(e,t):this)},countBy:function(e,t){return function(e,t,r){var n=St().asMutable();return e.__iterate(function(i,s){n.update(t.call(r,i,s,e),0,function(e){return e+1})}),n.asImmutable()}(this,e,t)},equals:function(e){return Pr(this,e)},entrySeq:function(){var e=this;if(e._cache)return new X(e._cache);var t=e.toSeq().map(Ar).toIndexedSeq();return t.fromEntrySeq=function(){return e.toSeq()},t},filterNot:function(e,t){return this.filter(kr(e),t)},findEntry:function(e,t,r){var n=r;return this.__iterate(function(r,i,s){if(e.call(t,r,i,s))return n=[i,r],!1}),n},findKey:function(e,t){var r=this.findEntry(e,t);return r&&r[0]},findLast:function(e,t,r){return this.toKeyedSeq().reverse().find(e,t,r)},findLastEntry:function(e,t,r){return this.toKeyedSeq().reverse().findEntry(e,t,r)},findLastKey:function(e,t){return this.toKeyedSeq().reverse().findKey(e,t)},first:function(e){return this.find(P,null,e)},flatMap:function(e,t){return qe(this,function(e,t,r){var n=We(e);return e.toSeq().map(function(i,s){return n(t.call(r,i,s,e))}).flatten(!0)}(this,e,t))},flatten:function(e){return qe(this,Ue(this,e,!0))},fromEntrySeq:function(){return new je(this)},get:function(e,t){return this.find(function(t,r){return Ve(r,e)},void 0,t)},getIn:Kr,groupBy:function(e,t){return function(e,t,r){var n=o(e),i=(z(e)?_r():St()).asMutable();e.__iterate(function(s,o){i.update(t.call(r,s,o,e),function(e){return(e=e||[]).push(n?[o,s]:s),e})});var s=We(e);return i.map(function(t){return qe(e,s(t))}).asImmutable()}(this,e,t)},has:function(e){return this.get(e,R)!==R},hasIn:function(e){return qr(this,e,R)!==R},isSubset:function(e){return e="function"==typeof e.includes?e:l(e),this.every(function(t){return e.includes(t)})},isSuperset:function(e){return(e="function"==typeof e.isSubset?e:l(e)).isSubset(this)},keyOf:function(e){return this.findKey(function(t){return Ve(t,e)})},keySeq:function(){return this.toSeq().map(Rr).toIndexedSeq()},last:function(e){return this.toSeq().reverse().first(e)},lastKeyOf:function(e){return this.toKeyedSeq().reverse().keyOf(e)},max:function(e){return Fe(this,e)},maxBy:function(e,t){return Fe(this,t,e)},min:function(e){return Fe(this,e?jr(e):Nr)},minBy:function(e,t){return Fe(this,t?jr(t):Nr,e)},rest:function(){return this.slice(1)},skip:function(e){return 0===e?this:this.slice(Math.max(0,e))},skipLast:function(e){return 0===e?this:this.slice(0,-Math.max(0,e))},skipWhile:function(e,t){return qe(this,Le(this,e,t,!0))},skipUntil:function(e,t){return this.skipWhile(kr(e),t)},sortBy:function(e,t){return qe(this,Me(this,t,e))},take:function(e){return this.slice(0,Math.max(0,e))},takeLast:function(e){return this.slice(-Math.max(0,e))},takeWhile:function(e,t){return qe(this,function(e,t,r){var n=He(e);return n.__iterateUncached=function(n,i){var s=this;if(i)return this.cacheResult().__iterate(n,i);var o=0;return e.__iterate(function(e,i,a){return t.call(r,e,i,a)&&++o&&n(e,i,s)}),o},n.__iteratorUncached=function(n,i){var s=this;if(i)return this.cacheResult().__iterator(n,i);var o=e.__iterator(2,i),a=!0;return new y(function(){if(!a)return{value:void 0,done:!0};var e=o.next();if(e.done)return e;var i=e.value,c=i[0],u=i[1];return t.call(r,u,c,s)?2===n?e:w(n,c,u,e):(a=!1,{value:void 0,done:!0})})},n}(this,e,t))},takeUntil:function(e,t){return this.takeWhile(kr(e),t)},update:function(e){return e(this)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=Qr(this))}});var Vr=l.prototype;Vr[c]=!0,Vr[g]=Vr.values,Vr.toJSON=Vr.toArray,Vr.__toStringMapper=Ht,Vr.inspect=Vr.toSource=function(){return this.toString()},Vr.chain=Vr.flatMap,Vr.contains=Vr.includes,Gr(h,{flip:function(){return qe(this,Ne(this))},mapEntries:function(e,t){var r=this,n=0;return qe(this,this.toSeq().map(function(i,s){return e.call(t,[s,i],n++,r)}).fromEntrySeq())},mapKeys:function(e,t){var r=this;return qe(this,this.toSeq().flip().map(function(n,i){return e.call(t,n,i,r)}).flip())}});var Xr=h.prototype;Xr[s]=!0,Xr[g]=Vr.entries,Xr.toJSON=Wr,Xr.__toStringMapper=function(e,t){return Ht(t)+": "+Ht(e)},Gr(d,{toKeyedSeq:function(){return new Re(this,!1)},filter:function(e,t){return qe(this,Ce(this,e,t,!1))},findIndex:function(e,t){var r=this.findEntry(e,t);return r?r[0]:-1},indexOf:function(e){var t=this.keyOf(e);return void 0===t?-1:t},lastIndexOf:function(e){var t=this.lastKeyOf(e);return void 0===t?-1:t},reverse:function(){return qe(this,Oe(this,!1))},slice:function(e,t){return qe(this,De(this,e,t,!1))},splice:function(e,t){var r=arguments.length;if(t=Math.max(t||0,0),0===r||2===r&&!t)return this;e=C(e,e<0?this.count():this.size);var n=this.slice(0,e);return qe(this,1===r?n:n.concat(st(arguments,2),this.slice(e+t)))},findLastIndex:function(e,t){var r=this.findLastEntry(e,t);return r?r[0]:-1},first:function(e){return this.get(0,e)},flatten:function(e){return qe(this,Ue(this,e,!1))},get:function(e,t){return(e=N(this,e))<0||this.size===1/0||void 0!==this.size&&e>this.size?t:this.find(function(t,r){return r===e},void 0,t)},has:function(e){return(e=N(this,e))>=0&&(void 0!==this.size?this.size===1/0||e<this.size:this.find(function(t,r){return r===e},void 0,R)!==R)},interpose:function(e){return qe(this,function(e,t){var r=He(e);return r.size=e.size&&2*e.size-1,r.__iterateUncached=function(r,n){var i=this,s=0;return e.__iterate(function(e){return(!s||!1!==r(t,s++,i))&&!1!==r(e,s++,i)},n),s},r.__iteratorUncached=function(r,n){var i,s=e.__iterator(1,n),o=0;return new y(function(){return(!i||o%2)&&(i=s.next()).done?i:o%2?w(r,o++,t):w(r,o++,i.value,i)})},r}(this,e))},interleave:function(){var e=[this].concat(st(arguments)),t=ze(this.toSeq(),G.of,e),r=t.flatten(!0);return t.size&&(r.size=t.size*e.length),qe(this,r)},keySeq:function(){return Cr(0,this.size)},last:function(e){return this.get(-1,e)},skipWhile:function(e,t){return qe(this,Le(this,e,t,!1))},zip:function(){return qe(this,ze(this,en,[this].concat(st(arguments))))},zipAll:function(){return qe(this,ze(this,en,[this].concat(st(arguments)),!0))},zipWith:function(e){var t=st(arguments);return t[0]=this,qe(this,ze(this,e,t))}});var Yr=d.prototype;Yr[n]=!0,Yr[B]=!0,Gr(f,{get:function(e,t){return this.has(e)?e:t},includes:function(e){return this.has(e)},keySeq:function(){return this.valueSeq()}});var Zr=f.prototype;function en(){return st(arguments)}function tn(e){return Lr(e)&&z(e)}Zr.has=Vr.includes,Zr.contains=Zr.includes,Zr.keys=Zr.values,Gr(J,Xr),Gr(G,Yr),Gr(V,Zr);var rn=function(e){function t(e){return null==e?an():tn(e)?e:an().withMutations(function(t){var r=f(e);vt(r.size),r.forEach(function(e){return t.add(e)})})}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.fromKeys=function(e){return this(h(e).keySeq())},t.prototype.toString=function(){return this.__toString("OrderedSet {","}")},t}($r);rn.isOrderedSet=tn;var nn,sn=rn.prototype;function on(e,t){var r=Object.create(sn);return r.size=e?e.size:0,r._map=e,r.__ownerID=t,r}function an(){return nn||(nn=on(yr()))}sn[B]=!0,sn.zip=Yr.zip,sn.zipWith=Yr.zipWith,sn.zipAll=Yr.zipAll,sn.__empty=an,sn.__make=on;var cn=function(e,t){var r;!function(e){if(M(e))throw new Error("Can not call `Record` with an immutable Record as default values. Use a plain javascript object instead.");if(F(e))throw new Error("Can not call `Record` with an immutable Collection as default values. Use a plain javascript object instead.");if(null===e||"object"!=typeof e)throw new Error("Can not call `Record` with a non-object as default values. Use a plain javascript object instead.")}(e);var n=function(s){var o=this;if(s instanceof n)return s;if(!(this instanceof n))return new n(s);if(!r){r=!0;var a=Object.keys(e),c=i._indices={};i._name=t,i._keys=a,i._defaultValues=e;for(var u=0;u<a.length;u++){var l=a[u];c[l]=u,i[l]?"object"==typeof console&&console.warn&&console.warn("Cannot define "+hn(this)+' with property "'+l+'" since that property name is part of the Record API.'):fn(i,l)}}return this.__ownerID=void 0,this._values=Zt().withMutations(function(e){e.setSize(o._keys.length),h(s).forEach(function(t,r){e.set(o._indices[r],t===o._defaultValues[r]?void 0:t)})}),this},i=n.prototype=Object.create(un);return i.constructor=n,t&&(n.displayName=t),n};cn.prototype.toString=function(){for(var e,t=hn(this)+" { ",r=this._keys,n=0,i=r.length;n!==i;n++)t+=(n?", ":"")+(e=r[n])+": "+Ht(this.get(e));return t+" }"},cn.prototype.equals=function(e){return this===e||M(e)&&dn(this).equals(dn(e))},cn.prototype.hashCode=function(){return dn(this).hashCode()},cn.prototype.has=function(e){return this._indices.hasOwnProperty(e)},cn.prototype.get=function(e,t){if(!this.has(e))return t;var r=this._indices[e],n=this._values.get(r);return void 0===n?this._defaultValues[e]:n},cn.prototype.set=function(e,t){if(this.has(e)){var r=this._values.set(this._indices[e],t===this._defaultValues[e]?void 0:t);if(r!==this._values&&!this.__ownerID)return ln(this,r)}return this},cn.prototype.remove=function(e){return this.set(e)},cn.prototype.clear=function(){var e=this._values.clear().setSize(this._keys.length);return this.__ownerID?this:ln(this,e)},cn.prototype.wasAltered=function(){return this._values.wasAltered()},cn.prototype.toSeq=function(){return dn(this)},cn.prototype.toJS=function(){return Hr(this)},cn.prototype.entries=function(){return this.__iterator(2)},cn.prototype.__iterator=function(e,t){return dn(this).__iterator(e,t)},cn.prototype.__iterate=function(e,t){return dn(this).__iterate(e,t)},cn.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._values.__ensureOwner(e);return e?ln(this,t,e):(this.__ownerID=e,this._values=t,this)},cn.isRecord=M,cn.getDescriptiveName=hn;var un=cn.prototype;function ln(e,t,r){var n=Object.create(Object.getPrototypeOf(e));return n._values=t,n.__ownerID=r,n}function hn(e){return e.constructor.displayName||e.constructor.name||"Record"}function dn(e){return re(e._keys.map(function(t){return[t,e.get(t)]}))}function fn(e,t){try{Object.defineProperty(e,t,{get:function(){return this.get(t)},set:function(e){mt(this.__ownerID,"Cannot set on an immutable record."),this.set(t,e)}})}catch(e){}}un[U]=!0,un[x]=un.remove,un.deleteIn=un.removeIn=Vt,un.getIn=Kr,un.hasIn=Vr.hasIn,un.merge=Ye,un.mergeWith=Ze,un.mergeIn=dt,un.mergeDeep=ut,un.mergeDeepWith=lt,un.mergeDeepIn=ht,un.setIn=ft,un.update=pt,un.updateIn=_t,un.withMutations=yt,un.asMutable=oe,un.asImmutable=se,un[g]=un.entries,un.toJSON=un.toObject=Vr.toObject,un.inspect=un.toSource=function(){return this.toString()}},606(e){var t,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function o(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"==typeof clearTimeout?clearTimeout:s}catch(e){r=s}}();var a,c=[],u=!1,l=-1;function h(){u&&a&&(u=!1,a.length?c=a.concat(c):l=-1,c.length&&d())}function d(){if(!u){var e=o(h);u=!0;for(var t=c.length;t;){for(a=c,c=[];++l<t;)a&&a[l].run();l=-1,t=c.length}a=null,u=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===s||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function p(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];c.push(new f(e,t)),1!==c.length||u||o(d)},f.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=p,n.addListener=p,n.once=p,n.off=p,n.removeListener=p,n.removeAllListeners=p,n.emit=p,n.prependListener=p,n.prependOnceListener=p,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},147(e,t,r){"use strict";const{SymbolDispose:n}=r(134),{AbortError:i,codes:s}=r(371),{isNodeStream:o,isWebStream:a,kControllerErrorFunction:c}=r(115),u=r(238),{ERR_INVALID_ARG_TYPE:l}=s;let h;e.exports.addAbortSignal=function(t,r){if(((e,t)=>{if("object"!=typeof e||!("aborted"in e))throw new l(t,"AbortSignal",e)})(t,"signal"),!o(r)&&!a(r))throw new l("stream",["ReadableStream","WritableStream","Stream"],r);return e.exports.addAbortSignalNoValidate(t,r)},e.exports.addAbortSignalNoValidate=function(e,t){if("object"!=typeof e||!("aborted"in e))return t;const s=o(t)?()=>{t.destroy(new i(void 0,{cause:e.reason}))}:()=>{t[c](new i(void 0,{cause:e.reason}))};if(e.aborted)s();else{h=h||r(760).addAbortListener;const i=h(e,s);u(t,i[n])}return t}},345(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:s,Uint8Array:o}=r(134),{Buffer:a}=r(287),{inspect:c}=r(760);e.exports=class BufferList{constructor(){this.head=null,this.tail=null,this.length=0}push(e){const t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}unshift(e){const t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}shift(){if(0===this.length)return;const e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(0===this.length)return"";let t=this.head,r=""+t.data;for(;null!==(t=t.next);)r+=e+t.data;return r}concat(e){if(0===this.length)return a.alloc(0);const t=a.allocUnsafe(e>>>0);let r=this.head,n=0;for(;r;)s(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(e<r.length){const t=r.slice(0,e);return this.head.data=r.slice(e),t}return e===r.length?this.shift():t?this._getString(e):this._getBuffer(e)}first(){return this.head.data}*[i](){for(let e=this.head;e;e=e.next)yield e.data}_getString(e){let t="",r=this.head,i=0;do{const s=r.data;if(!(e>s.length)){e===s.length?(t+=s,++i,r.next?this.head=r.next:this.head=this.tail=null):(t+=n(s,0,e),this.head=r,r.data=n(s,e));break}t+=s,e-=s.length,++i}while(null!==(r=r.next));return this.length-=i,t}_getBuffer(e){const t=a.allocUnsafe(e),r=e;let n=this.head,i=0;do{const a=n.data;if(!(e>a.length)){e===a.length?(s(t,a,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(s(t,new o(a.buffer,a.byteOffset,e),r-e),this.head=n,n.data=a.slice(e));break}s(t,a,r-e),e-=a.length,++i}while(null!==(n=n.next));return this.length-=i,t}[Symbol.for("nodejs.util.inspect.custom")](e,t){return c(this,{...t,depth:0,customInspect:!1})}}},896(e,t,r){"use strict";const n=r(606),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:s},AbortError:o}=r(371),{Symbol:a}=r(134),{kIsDestroyed:c,isDestroyed:u,isFinished:l,isServerRequest:h}=r(115),d=a("kDestroy"),f=a("kConstruct");function p(e,t,r){e&&(e.stack,t&&!t.errored&&(t.errored=e),r&&!r.errored&&(r.errored=e))}function _(e,t,r){let i=!1;function s(t){if(i)return;i=!0;const s=e._readableState,o=e._writableState;p(t,o,s),o&&(o.closed=!0),s&&(s.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(g,e,t):n.nextTick(y,e)}try{e._destroy(t||null,s)}catch(t){s(t)}}function g(e,t){w(e,t),y(e)}function y(e){const t=e._readableState,r=e._writableState;r&&(r.closeEmitted=!0),t&&(t.closeEmitted=!0),(null!=r&&r.emitClose||null!=t&&t.emitClose)&&e.emit("close")}function w(e,t){const r=e._readableState,n=e._writableState;null!=n&&n.errorEmitted||null!=r&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),e.emit("error",t))}function b(e,t,r){const i=e._readableState,s=e._writableState;if(null!=s&&s.destroyed||null!=i&&i.destroyed)return this;null!=i&&i.autoDestroy||null!=s&&s.autoDestroy?e.destroy(t):t&&(t.stack,s&&!s.errored&&(s.errored=t),i&&!i.errored&&(i.errored=t),r?n.nextTick(w,e,t):w(e,t))}function m(e){let t=!1;function r(r){if(t)return void b(e,null!=r?r:new s);t=!0;const i=e._readableState,o=e._writableState,a=o||i;i&&(i.constructed=!0),o&&(o.constructed=!0),a.destroyed?e.emit(d,r):r?b(e,r,!0):n.nextTick(v,e)}try{e._construct(e=>{n.nextTick(r,e)})}catch(e){n.nextTick(r,e)}}function v(e){e.emit(f)}function S(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function I(e){e.emit("close")}function x(e,t){e.emit("error",t),n.nextTick(I,e)}e.exports={construct:function(e,t){if("function"!=typeof e._construct)return;const r=e._readableState,i=e._writableState;r&&(r.constructed=!1),i&&(i.constructed=!1),e.once(f,t),e.listenerCount(f)>1||n.nextTick(m,e)},destroyer:function(e,t){e&&!u(e)&&(t||l(e)||(t=new o),h(e)?(e.socket=null,e.destroy(t)):S(e)?e.abort():S(e.req)?e.req.abort():"function"==typeof e.destroy?e.destroy(t):"function"==typeof e.close?e.close():t?n.nextTick(x,e,t):n.nextTick(I,e),e.destroyed||(e[c]=!0))},destroy:function(e,t){const r=this._readableState,n=this._writableState,s=n||r;return null!=n&&n.destroyed||null!=r&&r.destroyed?("function"==typeof t&&t(),this):(p(e,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),s.constructed?_(this,e,t):this.once(d,function(r){_(this,i(r,e),t)}),this)},undestroy:function(){const e=this._readableState,t=this._writableState;e&&(e.constructed=!0,e.closed=!1,e.closeEmitted=!1,e.destroyed=!1,e.errored=null,e.errorEmitted=!1,e.reading=!1,e.ended=!1===e.readable,e.endEmitted=!1===e.readable),t&&(t.constructed=!0,t.destroyed=!1,t.closed=!1,t.closeEmitted=!1,t.errored=null,t.errorEmitted=!1,t.finalCalled=!1,t.prefinished=!1,t.ended=!1===t.writable,t.ending=!1===t.writable,t.finished=!1===t.writable)},errorOrDestroy:b}},370(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:s,ObjectSetPrototypeOf:o}=r(134);e.exports=u;const a=r(576),c=r(584);o(u.prototype,a.prototype),o(u,a);{const e=s(c.prototype);for(let t=0;t<e.length;t++){const r=e[t];u.prototype[r]||(u.prototype[r]=c.prototype[r])}}function u(e){if(!(this instanceof u))return new u(e);a.call(this,e),c.call(this,e),e?(this.allowHalfOpen=!1!==e.allowHalfOpen,!1===e.readable&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),!1===e.writable&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}let l,h;function d(){return void 0===l&&(l={}),l}n(u.prototype,{writable:{__proto__:null,...i(c.prototype,"writable")},writableHighWaterMark:{__proto__:null,...i(c.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...i(c.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...i(c.prototype,"writableBuffer")},writableLength:{__proto__:null,...i(c.prototype,"writableLength")},writableFinished:{__proto__:null,...i(c.prototype,"writableFinished")},writableCorked:{__proto__:null,...i(c.prototype,"writableCorked")},writableEnded:{__proto__:null,...i(c.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...i(c.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set(e){this._readableState&&this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}}),u.fromWeb=function(e,t){return d().newStreamDuplexFromReadableWritablePair(e,t)},u.toWeb=function(e){return d().newReadableWritablePairFromDuplex(e)},u.from=function(e){return h||(h=r(706)),h(e,"body")}},706(e,t,r){const n=r(606),i=r(287),{isReadable:s,isWritable:o,isIterable:a,isNodeStream:c,isReadableNodeStream:u,isWritableNodeStream:l,isDuplexNodeStream:h,isReadableStream:d,isWritableStream:f}=r(115),p=r(238),{AbortError:_,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:y}}=r(371),{destroyer:w}=r(896),b=r(370),m=r(576),v=r(584),{createDeferredPromise:S}=r(760),I=r(532),x=globalThis.Blob||i.Blob,E=void 0!==x?function(e){return e instanceof x}:function(e){return!1},T=globalThis.AbortController||r(568).AbortController,{FunctionPrototypeCall:R}=r(134);class Duplexify extends b{constructor(e){super(e),!1===(null==e?void 0:e.readable)&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),!1===(null==e?void 0:e.writable)&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}}function A(e){const t=e.readable&&"function"!=typeof e.readable.read?m.wrap(e.readable):e.readable,r=e.writable;let n,i,a,c,u,l=!!s(t),h=!!o(r);function d(e){const t=c;c=null,t?t(e):e&&u.destroy(e)}return u=new Duplexify({readableObjectMode:!(null==t||!t.readableObjectMode),writableObjectMode:!(null==r||!r.writableObjectMode),readable:l,writable:h}),h&&(p(r,e=>{h=!1,e&&w(t,e),d(e)}),u._write=function(e,t,i){r.write(e,t)?i():n=i},u._final=function(e){r.end(),i=e},r.on("drain",function(){if(n){const e=n;n=null,e()}}),r.on("finish",function(){if(i){const e=i;i=null,e()}})),l&&(p(t,e=>{l=!1,e&&w(t,e),d(e)}),t.on("readable",function(){if(a){const e=a;a=null,e()}}),t.on("end",function(){u.push(null)}),u._read=function(){for(;;){const e=t.read();if(null===e)return void(a=u._read);if(!u.push(e))return}}),u._destroy=function(e,s){e||null===c||(e=new _),a=null,n=null,i=null,null===c?s(e):(c=s,w(r,e),w(t,e))},u}e.exports=function e(t,r){if(h(t))return t;if(u(t))return A({readable:t});if(l(t))return A({writable:t});if(c(t))return A({writable:!1,readable:!1});if(d(t))return A({readable:m.fromWeb(t)});if(f(t))return A({writable:v.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:s,destroy:o}=function(e){let{promise:t,resolve:r}=S();const i=new T,s=i.signal,o=e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:o,cb:a}=await e;if(n.nextTick(a),o)return;if(s.aborted)throw new _(void 0,{cause:s.reason});({promise:t,resolve:r}=S()),yield i}}(),{signal:s});return{value:o,write(e,t,n){const i=r;r=null,i({chunk:e,done:!1,cb:n})},final(e){const t=r;r=null,t({done:!0,cb:e})},destroy(e,t){i.abort(),t(e)}}}(t);if(a(e))return I(Duplexify,e,{objectMode:!0,write:i,final:s,destroy:o});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=R(c,e,e=>{if(null!=e)throw new y("nully","body",e)},e=>{w(t,e)});return t=new Duplexify({objectMode:!0,readable:!1,write:i,final(e){s(async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}})},destroy:o})}throw new y("Iterable, AsyncIterable or AsyncFunction",r,e)}if(E(t))return e(t.arrayBuffer());if(a(t))return I(Duplexify,t,{objectMode:!0,writable:!1});if(d(null==t?void 0:t.readable)&&f(null==t?void 0:t.writable))return Duplexify.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable)){return A({readable:null!=t&&t.readable?u(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?l(null==t?void 0:t.writable)?null==t?void 0:t.writable:e(t.writable):void 0})}const i=null==t?void 0:t.then;if("function"==typeof i){let e;return R(i,t,t=>{null!=t&&e.push(t),e.push(null)},t=>{w(e,t)}),e=new Duplexify({objectMode:!0,writable:!1,read(){}})}throw new g(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},238(e,t,r){"use strict";const n=r(606),{AbortError:i,codes:s}=r(371),{ERR_INVALID_ARG_TYPE:o,ERR_STREAM_PREMATURE_CLOSE:a}=s,{kEmptyObject:c,once:u}=r(760),{validateAbortSignal:l,validateFunction:h,validateObject:d,validateBoolean:f}=r(277),{Promise:p,PromisePrototypeThen:_,SymbolDispose:g}=r(134),{isClosed:y,isReadable:w,isReadableNodeStream:b,isReadableStream:m,isReadableFinished:v,isReadableErrored:S,isWritable:I,isWritableNodeStream:x,isWritableStream:E,isWritableFinished:T,isWritableErrored:R,isNodeStream:A,willEmitClose:k,kIsClosedPromise:j}=r(115);let N;const P=()=>{};function O(e,t,s){var f,p;if(2===arguments.length?(s=t,t=c):null==t?t=c:d(t,"options"),h(s,"callback"),l(t.signal,"options.signal"),s=u(s),m(e)||E(e))return function(e,t,s){let o=!1,a=P;if(t.signal)if(a=()=>{o=!0,s.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(a);else{N=N||r(760).addAbortListener;const n=N(t.signal,a),i=s;s=u((...t)=>{n[g](),i.apply(e,t)})}const c=(...t)=>{o||n.nextTick(()=>s.apply(e,t))};return _(e[j].promise,c,c),P}(e,t,s);if(!A(e))throw new o("stream",["ReadableStream","WritableStream","Stream"],e);const O=null!==(f=t.readable)&&void 0!==f?f:b(e),C=null!==(p=t.writable)&&void 0!==p?p:x(e),D=e._writableState,L=e._readableState,$=()=>{e.writable||F()};let U=k(e)&&b(e)===O&&x(e)===C,M=T(e,!1);const F=()=>{M=!0,e.destroyed&&(U=!1),(!U||e.readable&&!O)&&(O&&!B||s.call(e))};let B=v(e,!1);const z=()=>{B=!0,e.destroyed&&(U=!1),(!U||e.writable&&!C)&&(C&&!M||s.call(e))},q=t=>{s.call(e,t)};let K=y(e);const W=()=>{K=!0;const t=R(e)||S(e);return t&&"boolean"!=typeof t?s.call(e,t):O&&!B&&b(e,!0)&&!v(e,!1)?s.call(e,new a):!C||M||T(e,!1)?void s.call(e):s.call(e,new a)},H=()=>{K=!0;const t=R(e)||S(e);if(t&&"boolean"!=typeof t)return s.call(e,t);s.call(e)},Q=()=>{e.req.on("finish",F)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?C&&!D&&(e.on("end",$),e.on("close",$)):(e.on("complete",F),U||e.on("abort",W),e.req?Q():e.on("request",Q)),U||"boolean"!=typeof e.aborted||e.on("aborted",W),e.on("end",z),e.on("finish",F),!1!==t.error&&e.on("error",q),e.on("close",W),K?n.nextTick(W):null!=D&&D.errorEmitted||null!=L&&L.errorEmitted?U||n.nextTick(H):(O||U&&!w(e)||!M&&!1!==I(e))&&(C||U&&!I(e)||!B&&!1!==w(e))?L&&e.req&&e.aborted&&n.nextTick(H):n.nextTick(H);const J=()=>{s=P,e.removeListener("aborted",W),e.removeListener("complete",F),e.removeListener("abort",W),e.removeListener("request",Q),e.req&&e.req.removeListener("finish",F),e.removeListener("end",$),e.removeListener("close",$),e.removeListener("finish",F),e.removeListener("end",z),e.removeListener("error",q),e.removeListener("close",W)};if(t.signal&&!K){const o=()=>{const r=s;J(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(o);else{N=N||r(760).addAbortListener;const n=N(t.signal,o),i=s;s=u((...t)=>{n[g](),i.apply(e,t)})}}return J}e.exports=O,e.exports.finished=function(e,t){var r;let n=!1;return null===t&&(t=c),null!==(r=t)&&void 0!==r&&r.cleanup&&(f(t.cleanup,"cleanup"),n=t.cleanup),new p((r,i)=>{const s=O(e,t,e=>{n&&s(),e?i(e):r()})})}},532(e,t,r){"use strict";const n=r(606),{PromisePrototypeThen:i,SymbolAsyncIterator:s,SymbolIterator:o}=r(134),{Buffer:a}=r(287),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:u}=r(371).codes;e.exports=function(e,t,r){let l,h;if("string"==typeof t||t instanceof a)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[s])h=!0,l=t[s]();else{if(!t||!t[o])throw new c("iterable",["Iterable"],t);h=!1,l=t[o]()}const d=new e({objectMode:!0,highWaterMark:1,...r});let f=!1;return d._read=function(){f||(f=!0,async function(){for(;;){try{const{value:e,done:t}=h?await l.next():l.next();if(t)d.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw f=!1,new u;if(d.push(t))continue;f=!1}}catch(e){d.destroy(e)}break}}())},d._destroy=function(e,t){i(async function(e){const t=null!=e,r="function"==typeof l.throw;if(t&&r){const{value:t,done:r}=await l.throw(e);if(await t,r)return}if("function"==typeof l.return){const{value:e}=await l.return();await e}}(e),()=>n.nextTick(t,e),r=>n.nextTick(t,r||e))},d}},259(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(134),{EventEmitter:s}=r(7);function o(e){s.call(this,e)}function a(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?n(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}i(o.prototype,s.prototype),i(o,s),o.prototype.pipe=function(e,t){const r=this;function n(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),e.on("drain",i),e._isStdio||t&&!1===t.end||(r.on("end",c),r.on("close",u));let o=!1;function c(){o||(o=!0,e.end())}function u(){o||(o=!0,"function"==typeof e.destroy&&e.destroy())}function l(e){h(),0===s.listenerCount(this,"error")&&this.emit("error",e)}function h(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",c),r.removeListener("close",u),r.removeListener("error",l),e.removeListener("error",l),r.removeListener("end",h),r.removeListener("close",h),e.removeListener("close",h)}return a(r,"error",l),a(e,"error",l),r.on("end",h),r.on("close",h),e.on("close",h),e.emit("pipe",r),e},e.exports={Stream:o,prependListener:a}},524(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(134);e.exports=s;const i=r(382);function s(e){if(!(this instanceof s))return new s(e);i.call(this,e)}n(s.prototype,i.prototype),n(s,i),s.prototype._transform=function(e,t,r){r(null,e)}},758(e,t,r){const n=r(606),{ArrayIsArray:i,Promise:s,SymbolAsyncIterator:o,SymbolDispose:a}=r(134),c=r(238),{once:u}=r(760),l=r(896),h=r(370),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:p,ERR_MISSING_ARGS:_,ERR_STREAM_DESTROYED:g,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=r(371),{validateFunction:b,validateAbortSignal:m}=r(277),{isIterable:v,isReadable:S,isReadableNodeStream:I,isNodeStream:x,isTransformStream:E,isWebStream:T,isReadableStream:R,isReadableFinished:A}=r(115),k=globalThis.AbortController||r(568).AbortController;let j,N,P;function O(e,t,r){let n=!1;e.on("close",()=>{n=!0});return{destroy:t=>{n||(n=!0,l.destroyer(e,t||new g("pipe")))},cleanup:c(e,{readable:t,writable:r},e=>{n=!e})}}function C(e){if(v(e))return e;if(I(e))return async function*(e){N||(N=r(576));yield*N.prototype[o].call(e)}(e);throw new f("val",["Readable","Iterable","AsyncIterable"],e)}async function D(e,t,r,{end:n}){let i,o=null;const a=e=>{if(e&&(i=e),o){const e=o;o=null,e()}},u=()=>new s((e,t)=>{i?t(i):o=()=>{i?t(i):e()}});t.on("drain",a);const l=c(t,{readable:!1},a);try{t.writableNeedDrain&&await u();for await(const r of e)t.write(r)||await u();n&&(t.end(),await u()),r()}catch(e){r(i!==e?d(i,e):e)}finally{l(),t.off("drain",a)}}async function L(e,t,r,{end:n}){E(t)&&(t=t.writable);const i=t.getWriter();try{for await(const t of e)await i.ready,i.write(t).catch(()=>{});await i.ready,n&&await i.close(),r()}catch(e){try{await i.abort(e),r(e)}catch(e){r(e)}}}function $(e,t,s){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new _("streams");const o=new k,c=o.signal,u=null==s?void 0:s.signal,l=[];function d(){F(new w)}let g,y,b;m(u,"options.signal"),P=P||r(760).addAbortListener,u&&(g=P(u,d));const A=[];let N,$=0;function M(e){F(e,0===--$)}function F(e,r){var i;if(!e||y&&"ERR_STREAM_PREMATURE_CLOSE"!==y.code||(y=e),y||r){for(;A.length;)A.shift()(y);null===(i=g)||void 0===i||i[a](),o.abort(),r&&(y||l.forEach(e=>e()),n.nextTick(t,y,b))}}for(let K=0;K<e.length;K++){const W=e[K],H=K<e.length-1,Q=K>0,J=H||!1!==(null==s?void 0:s.end),G=K===e.length-1;if(x(W)){if(J){const{destroy:V,cleanup:X}=O(W,H,Q);A.push(V),S(W)&&G&&l.push(X)}function B(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&M(e)}W.on("error",B),S(W)&&G&&l.push(()=>{W.removeListener("error",B)})}if(0===K)if("function"==typeof W){if(N=W({signal:c}),!v(N))throw new p("Iterable, AsyncIterable or Stream","source",N)}else N=v(W)||I(W)||E(W)?W:h.from(W);else if("function"==typeof W){var z;if(E(N))N=C(null===(z=N)||void 0===z?void 0:z.readable);else N=C(N);if(N=W(N,{signal:c}),H){if(!v(N,!0))throw new p("AsyncIterable",`transform[${K-1}]`,N)}else{var q;j||(j=r(524));const Y=new j({objectMode:!0}),Z=null===(q=N)||void 0===q?void 0:q.then;if("function"==typeof Z)$++,Z.call(N,e=>{b=e,null!=e&&Y.write(e),J&&Y.end(),n.nextTick(M)},e=>{Y.destroy(e),n.nextTick(M,e)});else if(v(N,!0))$++,D(N,Y,M,{end:J});else{if(!R(N)&&!E(N))throw new p("AsyncIterable or Promise","destination",N);{const re=N.readable||N;$++,D(re,Y,M,{end:J})}}N=Y;const{destroy:ee,cleanup:te}=O(N,!1,!0);A.push(ee),G&&l.push(te)}}else if(x(W)){if(I(N)){$+=2;const ne=U(N,W,M,{end:J});S(W)&&G&&l.push(ne)}else if(E(N)||R(N)){const ie=N.readable||N;$++,D(ie,W,M,{end:J})}else{if(!v(N))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);$++,D(N,W,M,{end:J})}N=W}else if(T(W)){if(I(N))$++,L(C(N),W,M,{end:J});else if(R(N)||v(N))$++,L(N,W,M,{end:J});else{if(!E(N))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);$++,L(N.readable,W,M,{end:J})}N=W}else N=h.from(W)}return(null!=c&&c.aborted||null!=u&&u.aborted)&&n.nextTick(d),N}function U(e,t,r,{end:i}){let s=!1;if(t.on("close",()=>{s||r(new y)}),e.pipe(t,{end:!1}),i){function o(){s=!0,t.end()}A(e)?n.nextTick(o):e.once("end",o)}else r();return c(e,{readable:!0,writable:!1},t=>{const n=e._readableState;t&&"ERR_STREAM_PREMATURE_CLOSE"===t.code&&n&&n.ended&&!n.errored&&!n.errorEmitted?e.once("end",r).once("error",r):r(t)}),c(t,{readable:!1,writable:!0},r)}e.exports={pipelineImpl:$,pipeline:function(...e){return $(e,u(function(e){return b(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},576(e,t,r){"use strict";const n=r(606),{ArrayPrototypeIndexOf:i,NumberIsInteger:s,NumberIsNaN:o,NumberParseInt:a,ObjectDefineProperties:c,ObjectKeys:u,ObjectSetPrototypeOf:l,Promise:h,SafeSet:d,SymbolAsyncDispose:f,SymbolAsyncIterator:p,Symbol:_}=r(134);e.exports=K,K.ReadableState=q;const{EventEmitter:g}=r(7),{Stream:y,prependListener:w}=r(259),{Buffer:b}=r(287),{addAbortSignal:m}=r(147),v=r(238);let S=r(760).debuglog("stream",e=>{S=e});const I=r(345),x=r(896),{getHighWaterMark:E,getDefaultHighWaterMark:T}=r(291),{aggregateTwoErrors:R,codes:{ERR_INVALID_ARG_TYPE:A,ERR_METHOD_NOT_IMPLEMENTED:k,ERR_OUT_OF_RANGE:j,ERR_STREAM_PUSH_AFTER_EOF:N,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:P},AbortError:O}=r(371),{validateObject:C}=r(277),D=_("kPaused"),{StringDecoder:L}=r(141),$=r(532);l(K.prototype,y.prototype),l(K,y);const U=()=>{},{errorOrDestroy:M}=x,F=2048,B=4096;function z(e){return{enumerable:!1,get(){return 0!==(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function q(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(370)),this.state=6192,e&&e.objectMode&&(this.state|=1),n&&e&&e.readableObjectMode&&(this.state|=1),this.highWaterMark=e?E(this,e,"readableHighWaterMark",n):T(!1),this.buffer=new I,this.length=0,this.pipes=[],this.flowing=null,this[D]=null,e&&!1===e.emitClose&&(this.state&=-2049),e&&!1===e.autoDestroy&&(this.state&=-4097),this.errored=null,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,e&&e.encoding&&(this.decoder=new L(e.encoding),this.encoding=e.encoding)}function K(e){if(!(this instanceof K))return new K(e);const t=this instanceof r(370);this._readableState=new q(e,this,t),e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&!t&&m(e.signal,this)),y.call(this,e),x.construct(this,()=>{this._readableState.needReadable&&V(this,this._readableState)})}function W(e,t,r,n){S("readableAddChunk",t);const i=e._readableState;let s;if(1&i.state||("string"==typeof t?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?t=b.from(t,r).toString(i.encoding):(t=b.from(t,r),r=""))):t instanceof b?r="":y._isUint8Array(t)?(t=y._uint8ArrayToBuffer(t),r=""):null!=t&&(s=new A("chunk",["string","Buffer","Uint8Array"],t))),s)M(e,s);else if(null===t)i.state&=-9,function(e,t){if(S("onEofChunk"),t.ended)return;if(t.decoder){const e=t.decoder.end();e&&e.length&&(t.buffer.push(e),t.length+=t.objectMode?1:e.length)}t.ended=!0,t.sync?J(e):(t.needReadable=!1,t.emittedReadable=!0,G(e))}(e,i);else if(1&i.state||t&&t.length>0)if(n)if(4&i.state)M(e,new P);else{if(i.destroyed||i.errored)return!1;H(e,i,t,!0)}else if(i.ended)M(e,new N);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?H(e,i,t,!1):V(e,i)):H(e,i,t,!1)}else n||(i.state&=-9,V(e,i));return!i.ended&&(i.length<i.highWaterMark||0===i.length)}function H(e,t,r,n){t.flowing&&0===t.length&&!t.sync&&e.listenerCount("data")>0?(65536&t.state?t.awaitDrainWriters.clear():t.awaitDrainWriters=null,t.dataEmitted=!0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),64&t.state&&J(e)),V(e,t)}c(q.prototype,{objectMode:z(1),ended:z(2),endEmitted:z(4),reading:z(8),constructed:z(16),sync:z(32),needReadable:z(64),emittedReadable:z(128),readableListening:z(256),resumeScheduled:z(512),errorEmitted:z(1024),emitClose:z(F),autoDestroy:z(B),destroyed:z(8192),closed:z(16384),closeEmitted:z(32768),multiAwaitDrain:z(65536),readingMore:z(1<<17),dataEmitted:z(1<<18)}),K.prototype.destroy=x.destroy,K.prototype._undestroy=x.undestroy,K.prototype._destroy=function(e,t){t(e)},K.prototype[g.captureRejectionSymbol]=function(e){this.destroy(e)},K.prototype[f]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new O,this.destroy(e)),new h((t,r)=>v(this,n=>n&&n!==e?r(n):t(null)))},K.prototype.push=function(e,t){return W(this,e,t,!1)},K.prototype.unshift=function(e,t){return W(this,e,t,!0)},K.prototype.isPaused=function(){const e=this._readableState;return!0===e[D]||!1===e.flowing},K.prototype.setEncoding=function(e){const t=new L(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;const r=this._readableState.buffer;let n="";for(const e of r)n+=t.write(e);return r.clear(),""!==n&&r.push(n),this._readableState.length=n.length,this};function Q(e,t){return e<=0||0===t.length&&t.ended?0:1&t.state?1:o(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function J(e){const t=e._readableState;S("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(S("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(G,e))}function G(e){const t=e._readableState;S("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||t.errored||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,te(e)}function V(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(X,e,t))}function X(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){const r=t.length;if(S("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}function Y(e){const t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!1===t[D]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function Z(e){S("readable nexttick read 0"),e.read(0)}function ee(e,t){S("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),te(e),t.flowing&&!t.reading&&e.read(0)}function te(e){const t=e._readableState;for(S("flow",t.flowing);t.flowing&&null!==e.read(););}function re(e,t){"function"!=typeof e.read&&(e=K.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=U;function i(t){this===e?(n(),n=U):n=t}e.on("readable",i);const s=v(e,{writable:!1},e=>{r=e?R(r,e):null,n(),n=U});try{for(;;){const t=e.destroyed?null:e.read();if(null!==t)yield t;else{if(r)throw r;if(null===r)return;await new h(i)}}}catch(e){throw r=R(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),s()):x.destroyer(e,null)}}(e,t);return r.stream=e,r}function ne(e,t){if(0===t.length)return null;let r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function ie(e){const t=e._readableState;S("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(se,t,e))}function se(e,t){if(S("endReadableNT",e.endEmitted,e.length),!e.errored&&!e.closeEmitted&&!e.endEmitted&&0===e.length)if(e.endEmitted=!0,t.emit("end"),t.writable&&!1===t.allowHalfOpen)n.nextTick(oe,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function oe(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let ae;function ce(){return void 0===ae&&(ae={}),ae}K.prototype.read=function(e){S("read",e),void 0===e?e=NaN:s(e)||(e=a(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new j("size","<= 1GiB",e);return e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,++e}(e)),0!==e&&(t.state&=-129),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return S("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ie(this):J(this),null;if(0===(e=Q(e,t))&&t.ended)return 0===t.length&&ie(this),null;let n,i=!!(64&t.state);if(S("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&(i=!0,S("length less than watermark",i)),t.ended||t.reading||t.destroyed||t.errored||!t.constructed)i=!1,S("reading, ended or constructing",i);else if(i){S("do read"),t.state|=40,0===t.length&&(t.state|=64);try{this._read(t.highWaterMark)}catch(e){M(this,e)}t.state&=-33,t.reading||(e=Q(r,t))}return n=e>0?ne(e,t):null,null===n?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.multiAwaitDrain?t.awaitDrainWriters.clear():t.awaitDrainWriters=null),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ie(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},K.prototype._read=function(e){throw new k("_read()")},K.prototype.pipe=function(e,t){const r=this,i=this._readableState;1===i.pipes.length&&(i.multiAwaitDrain||(i.multiAwaitDrain=!0,i.awaitDrainWriters=new d(i.awaitDrainWriters?[i.awaitDrainWriters]:[]))),i.pipes.push(e),S("pipe count=%d opts=%j",i.pipes.length,t);const s=(!t||!1!==t.end)&&e!==n.stdout&&e!==n.stderr?a:g;function o(t,n){S("onunpipe"),t===r&&n&&!1===n.hasUnpiped&&(n.hasUnpiped=!0,function(){S("cleanup"),e.removeListener("close",p),e.removeListener("finish",_),c&&e.removeListener("drain",c);e.removeListener("error",f),e.removeListener("unpipe",o),r.removeListener("end",a),r.removeListener("end",g),r.removeListener("data",h),u=!0,c&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&c()}())}function a(){S("onend"),e.end()}let c;i.endEmitted?n.nextTick(s):r.once("end",s),e.on("unpipe",o);let u=!1;function l(){u||(1===i.pipes.length&&i.pipes[0]===e?(S("false write response, pause",0),i.awaitDrainWriters=e,i.multiAwaitDrain=!1):i.pipes.length>1&&i.pipes.includes(e)&&(S("false write response, pause",i.awaitDrainWriters.size),i.awaitDrainWriters.add(e)),r.pause()),c||(c=function(e,t){return function(){const r=e._readableState;r.awaitDrainWriters===t?(S("pipeOnDrain",1),r.awaitDrainWriters=null):r.multiAwaitDrain&&(S("pipeOnDrain",r.awaitDrainWriters.size),r.awaitDrainWriters.delete(t)),r.awaitDrainWriters&&0!==r.awaitDrainWriters.size||!e.listenerCount("data")||e.resume()}}(r,e),e.on("drain",c))}function h(t){S("ondata");const r=e.write(t);S("dest.write",r),!1===r&&l()}function f(t){if(S("onerror",t),g(),e.removeListener("error",f),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?M(e,t):e.emit("error",t)}}function p(){e.removeListener("finish",_),g()}function _(){S("onfinish"),e.removeListener("close",p),g()}function g(){S("unpipe"),r.unpipe(e)}return r.on("data",h),w(e,"error",f),e.once("close",p),e.once("finish",_),e.emit("pipe",r),!0===e.writableNeedDrain?l():i.flowing||(S("pipe resume"),r.resume()),e},K.prototype.unpipe=function(e){const t=this._readableState;if(0===t.pipes.length)return this;if(!e){const e=t.pipes;t.pipes=[],this.pause();for(let t=0;t<e.length;t++)e[t].emit("unpipe",this,{hasUnpiped:!1});return this}const r=i(t.pipes,e);return-1===r||(t.pipes.splice(r,1),0===t.pipes.length&&this.pause(),e.emit("unpipe",this,{hasUnpiped:!1})),this},K.prototype.on=function(e,t){const r=y.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=this.listenerCount("readable")>0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,S("on readable",i.length,i.reading),i.length?J(this):i.reading||n.nextTick(Z,this))),r},K.prototype.addListener=K.prototype.on,K.prototype.removeListener=function(e,t){const r=y.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(Y,this),r},K.prototype.off=K.prototype.removeListener,K.prototype.removeAllListeners=function(e){const t=y.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(Y,this),t},K.prototype.resume=function(){const e=this._readableState;return e.flowing||(S("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(ee,e,t))}(this,e)),e[D]=!1,this},K.prototype.pause=function(){return S("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(S("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[D]=!0,this},K.prototype.wrap=function(e){let t=!1;e.on("data",r=>{!this.push(r)&&e.pause&&(t=!0,e.pause())}),e.on("end",()=>{this.push(null)}),e.on("error",e=>{M(this,e)}),e.on("close",()=>{this.destroy()}),e.on("destroy",()=>{this.destroy()}),this._read=()=>{t&&e.resume&&(t=!1,e.resume())};const r=u(e);for(let t=1;t<r.length;t++){const n=r[t];void 0===this[n]&&"function"==typeof e[n]&&(this[n]=e[n].bind(e))}return this},K.prototype[p]=function(){return re(this)},K.prototype.iterator=function(e){return void 0!==e&&C(e,"options"),re(this,e)},c(K.prototype,{readable:{__proto__:null,get(){const e=this._readableState;return!(!e||!1===e.readable||e.destroyed||e.errorEmitted||e.endEmitted)},set(e){this._readableState&&(this._readableState.readable=!!e)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!(!1===this._readableState.readable||!this._readableState.destroyed&&!this._readableState.errored||this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.objectMode}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return!!this._readableState&&this._readableState.closed}},destroyed:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.destroyed},set(e){this._readableState&&(this._readableState.destroyed=e)}},readableEnded:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.endEmitted}}}),c(q.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return!1!==this[D]},set(e){this[D]=!!e}}}),K._fromList=ne,K.from=function(e,t){return $(K,e,t)},K.fromWeb=function(e,t){return ce().newStreamReadableFromReadableStream(e,t)},K.toWeb=function(e,t){return ce().newReadableStreamFromStreamReadable(e,t)},K.wrap=function(e,t){var r,n;return new K({objectMode:null===(r=null!==(n=e.readableObjectMode)&&void 0!==n?n:e.objectMode)||void 0===r||r,...t,destroy(t,r){x.destroyer(e,t),r(t)}}).wrap(e)}},291(e,t,r){"use strict";const{MathFloor:n,NumberIsInteger:i}=r(134),{validateInteger:s}=r(277),{ERR_INVALID_ARG_VALUE:o}=r(371).codes;let a=16384,c=16;function u(e){return e?c:a}e.exports={getHighWaterMark:function(e,t,r,s){const a=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,s,r);if(null!=a){if(!i(a)||a<0){throw new o(s?`options.${r}`:"options.highWaterMark",a)}return n(a)}return u(e.objectMode)},getDefaultHighWaterMark:u,setDefaultHighWaterMark:function(e,t){s(t,"value",0),e?c=t:a=t}}},382(e,t,r){"use strict";const{ObjectSetPrototypeOf:n,Symbol:i}=r(134);e.exports=u;const{ERR_METHOD_NOT_IMPLEMENTED:s}=r(371).codes,o=r(370),{getHighWaterMark:a}=r(291);n(u.prototype,o.prototype),n(u,o);const c=i("kCallback");function u(e){if(!(this instanceof u))return new u(e);const t=e?a(this,e,"readableHighWaterMark",!0):null;0===t&&(e={...e,highWaterMark:null,readableHighWaterMark:t,writableHighWaterMark:e.writableHighWaterMark||0}),o.call(this,e),this._readableState.sync=!1,this[c]=null,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",h)}function l(e){"function"!=typeof this._flush||this.destroyed?(this.push(null),e&&e()):this._flush((t,r)=>{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())})}function h(){this._final!==l&&l.call(this)}u.prototype._final=l,u.prototype._transform=function(e,t,r){throw new s("_transform()")},u.prototype._write=function(e,t,r){const n=this._readableState,i=this._writableState,s=n.length;this._transform(e,t,(e,t)=>{e?r(e):(null!=t&&this.push(t),i.ended||s===n.length||n.length<n.highWaterMark?r():this[c]=r)})},u.prototype._read=function(){if(this[c]){const e=this[c];this[c]=null,e()}}},115(e,t,r){"use strict";const{SymbolAsyncIterator:n,SymbolIterator:i,SymbolFor:s}=r(134),o=s("nodejs.stream.destroyed"),a=s("nodejs.stream.errored"),c=s("nodejs.stream.readable"),u=s("nodejs.stream.writable"),l=s("nodejs.stream.disturbed"),h=s("nodejs.webstream.isClosedPromise"),d=s("nodejs.webstream.controllerErrorFunction");function f(e,t=!1){var r;return!(!e||"function"!=typeof e.pipe||"function"!=typeof e.on||t&&("function"!=typeof e.pause||"function"!=typeof e.resume)||e._writableState&&!1===(null===(r=e._readableState)||void 0===r?void 0:r.readable)||e._writableState&&!e._readableState)}function p(e){var t;return!(!e||"function"!=typeof e.write||"function"!=typeof e.on||e._readableState&&!1===(null===(t=e._writableState)||void 0===t?void 0:t.writable))}function _(e){return e&&(e._readableState||e._writableState||"function"==typeof e.write&&"function"==typeof e.on||"function"==typeof e.pipe&&"function"==typeof e.on)}function g(e){return!(!e||_(e)||"function"!=typeof e.pipeThrough||"function"!=typeof e.getReader||"function"!=typeof e.cancel)}function y(e){return!(!e||_(e)||"function"!=typeof e.getWriter||"function"!=typeof e.abort)}function w(e){return!(!e||_(e)||"object"!=typeof e.readable||"object"!=typeof e.writable)}function b(e){if(!_(e))return null;const t=e._writableState,r=e._readableState,n=t||r;return!!(e.destroyed||e[o]||null!=n&&n.destroyed)}function m(e){if(!p(e))return null;if(!0===e.writableEnded)return!0;const t=e._writableState;return(null==t||!t.errored)&&("boolean"!=typeof(null==t?void 0:t.ended)?null:t.ended)}function v(e,t){if(!f(e))return null;const r=e._readableState;return(null==r||!r.errored)&&("boolean"!=typeof(null==r?void 0:r.endEmitted)?null:!!(r.endEmitted||!1===t&&!0===r.ended&&0===r.length))}function S(e){return e&&null!=e[c]?e[c]:"boolean"!=typeof(null==e?void 0:e.readable)?null:!b(e)&&(f(e)&&e.readable&&!v(e))}function I(e){return e&&null!=e[u]?e[u]:"boolean"!=typeof(null==e?void 0:e.writable)?null:!b(e)&&(p(e)&&e.writable&&!m(e))}function x(e){return"boolean"==typeof e._closed&&"boolean"==typeof e._defaultKeepAlive&&"boolean"==typeof e._removedConnection&&"boolean"==typeof e._removedContLen}function E(e){return"boolean"==typeof e._sent100&&x(e)}e.exports={isDestroyed:b,kIsDestroyed:o,isDisturbed:function(e){var t;return!(!e||!(null!==(t=e[l])&&void 0!==t?t:e.readableDidRead||e.readableAborted))},isErrored:function(e){var t,r,n,i,s,o,c,u,l,h;return!(!e||!(null!==(t=null!==(r=null!==(n=null!==(i=null!==(s=null!==(o=e[a])&&void 0!==o?o:e.readableErrored)&&void 0!==s?s:e.writableErrored)&&void 0!==i?i:null===(c=e._readableState)||void 0===c?void 0:c.errorEmitted)&&void 0!==n?n:null===(u=e._writableState)||void 0===u?void 0:u.errorEmitted)&&void 0!==r?r:null===(l=e._readableState)||void 0===l?void 0:l.errored)&&void 0!==t?t:null===(h=e._writableState)||void 0===h?void 0:h.errored))},isReadable:S,kIsClosedPromise:h,kControllerErrorFunction:d,isClosed:function(e){if(!_(e))return null;if("boolean"==typeof e.closed)return e.closed;const t=e._writableState,r=e._readableState;return"boolean"==typeof(null==t?void 0:t.closed)||"boolean"==typeof(null==r?void 0:r.closed)?(null==t?void 0:t.closed)||(null==r?void 0:r.closed):"boolean"==typeof e._closed&&x(e)?e._closed:null},isDuplexNodeStream:function(e){return!(!e||"function"!=typeof e.pipe||!e._readableState||"function"!=typeof e.on||"function"!=typeof e.write)},isFinished:function(e,t){return _(e)?!!b(e)||(!1===(null==t?void 0:t.readable)||!S(e))&&(!1===(null==t?void 0:t.writable)||!I(e)):null},isIterable:function(e,t){return null!=e&&(!0===t?"function"==typeof e[n]:!1===t?"function"==typeof e[i]:"function"==typeof e[n]||"function"==typeof e[i])},isReadableNodeStream:f,isReadableStream:g,isReadableFinished:v,isReadableErrored:function(e){var t,r;return _(e)?e.readableErrored?e.readableErrored:null!==(t=null===(r=e._readableState)||void 0===r?void 0:r.errored)&&void 0!==t?t:null:null},isNodeStream:_,isWebStream:function(e){return g(e)||y(e)||w(e)},isWritable:I,isWritableNodeStream:p,isWritableStream:y,isWritableFinished:function(e,t){if(!p(e))return null;if(!0===e.writableFinished)return!0;const r=e._writableState;return(null==r||!r.errored)&&("boolean"!=typeof(null==r?void 0:r.finished)?null:!!(r.finished||!1===t&&!0===r.ended&&0===r.length))},isWritableErrored:function(e){var t,r;return _(e)?e.writableErrored?e.writableErrored:null!==(t=null===(r=e._writableState)||void 0===r?void 0:r.errored)&&void 0!==t?t:null:null},isServerRequest:function(e){var t;return"boolean"==typeof e._consuming&&"boolean"==typeof e._dumped&&void 0===(null===(t=e.req)||void 0===t?void 0:t.upgradeOrConnect)},willEmitClose:function(e){if(!_(e))return null;const t=e._writableState,r=e._readableState,n=t||r;return!n&&E(e)||!!(n&&n.autoDestroy&&n.emitClose&&!1===n.closed)},isTransformStream:w}},584(e,t,r){"use strict";const n=r(606),{ArrayPrototypeSlice:i,Error:s,FunctionPrototypeSymbolHasInstance:o,ObjectDefineProperty:a,ObjectDefineProperties:c,ObjectSetPrototypeOf:u,StringPrototypeToLowerCase:l,Symbol:h,SymbolHasInstance:d}=r(134);e.exports=C,C.WritableState=P;const{EventEmitter:f}=r(7),p=r(259).Stream,{Buffer:_}=r(287),g=r(896),{addAbortSignal:y}=r(147),{getHighWaterMark:w,getDefaultHighWaterMark:b}=r(291),{ERR_INVALID_ARG_TYPE:m,ERR_METHOD_NOT_IMPLEMENTED:v,ERR_MULTIPLE_CALLBACK:S,ERR_STREAM_CANNOT_PIPE:I,ERR_STREAM_DESTROYED:x,ERR_STREAM_ALREADY_FINISHED:E,ERR_STREAM_NULL_VALUES:T,ERR_STREAM_WRITE_AFTER_END:R,ERR_UNKNOWN_ENCODING:A}=r(371).codes,{errorOrDestroy:k}=g;function j(){}u(C.prototype,p.prototype),u(C,p);const N=h("kOnFinished");function P(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(370)),this.objectMode=!(!e||!e.objectMode),n&&(this.objectMode=this.objectMode||!(!e||!e.writableObjectMode)),this.highWaterMark=e?w(this,e,"writableHighWaterMark",n):b(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const i=!(!e||!1!==e.decodeStrings);this.decodeStrings=!i,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=U.bind(void 0,t),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,O(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!e||!1!==e.emitClose,this.autoDestroy=!e||!1!==e.autoDestroy,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[N]=[]}function O(e){e.buffered=[],e.bufferedIndex=0,e.allBuffers=!0,e.allNoop=!0}function C(e){const t=this instanceof r(370);if(!t&&!o(C,this))return new C(e);this._writableState=new P(e,this,t),e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&y(e.signal,this)),p.call(this,e),g.construct(this,()=>{const e=this._writableState;e.writing||z(this,e),W(this,e)})}function D(e,t,r,i){const s=e._writableState;if("function"==typeof r)i=r,r=s.defaultEncoding;else{if(r){if("buffer"!==r&&!_.isEncoding(r))throw new A(r)}else r=s.defaultEncoding;"function"!=typeof i&&(i=j)}if(null===t)throw new T;if(!s.objectMode)if("string"==typeof t)!1!==s.decodeStrings&&(t=_.from(t,r),r="buffer");else if(t instanceof _)r="buffer";else{if(!p._isUint8Array(t))throw new m("chunk",["string","Buffer","Uint8Array"],t);t=p._uint8ArrayToBuffer(t),r="buffer"}let o;return s.ending?o=new R:s.destroyed&&(o=new x("write")),o?(n.nextTick(i,o),k(e,o,!0),o):(s.pendingcb++,function(e,t,r,n,i){const s=t.objectMode?1:r.length;t.length+=s;const o=t.length<t.highWaterMark;o||(t.needDrain=!0);t.writing||t.corked||t.errored||!t.constructed?(t.buffered.push({chunk:r,encoding:n,callback:i}),t.allBuffers&&"buffer"!==n&&(t.allBuffers=!1),t.allNoop&&i!==j&&(t.allNoop=!1)):(t.writelen=s,t.writecb=i,t.writing=!0,t.sync=!0,e._write(r,n,t.onwrite),t.sync=!1);return o&&!t.errored&&!t.destroyed}(e,s,t,r,i))}function L(e,t,r,n,i,s,o){t.writelen=n,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new x("write")):r?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=!1}function $(e,t,r,n){--t.pendingcb,n(r),B(t),k(e,r)}function U(e,t){const r=e._writableState,i=r.sync,s=r.writecb;"function"==typeof s?(r.writing=!1,r.writecb=null,r.length-=r.writelen,r.writelen=0,t?(t.stack,r.errored||(r.errored=t),e._readableState&&!e._readableState.errored&&(e._readableState.errored=t),i?n.nextTick($,e,r,t,s):$(e,r,t,s)):(r.buffered.length>r.bufferedIndex&&z(e,r),i?null!==r.afterWriteTickInfo&&r.afterWriteTickInfo.cb===s?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:s,stream:e,state:r},n.nextTick(M,r.afterWriteTickInfo)):F(e,r,1,s))):k(e,new S)}function M({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,F(e,t,r,n)}function F(e,t,r,n){for(!t.ending&&!e.destroyed&&0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"));r-- >0;)t.pendingcb--,n();t.destroyed&&B(t),W(e,t)}function B(e){if(e.writing)return;for(let r=e.bufferedIndex;r<e.buffered.length;++r){var t;const{chunk:n,callback:i}=e.buffered[r],s=e.objectMode?1:n.length;e.length-=s,i(null!==(t=e.errored)&&void 0!==t?t:new x("write"))}const r=e[N].splice(0);for(let t=0;t<r.length;t++){var n;r[t](null!==(n=e.errored)&&void 0!==n?n:new x("end"))}O(e)}function z(e,t){if(t.corked||t.bufferProcessing||t.destroyed||!t.constructed)return;const{buffered:r,bufferedIndex:n,objectMode:s}=t,o=r.length-n;if(!o)return;let a=n;if(t.bufferProcessing=!0,o>1&&e._writev){t.pendingcb-=o-1;const n=t.allNoop?j:e=>{for(let t=a;t<r.length;++t)r[t].callback(e)},s=t.allNoop&&0===a?r:i(r,a);s.allBuffers=t.allBuffers,L(e,t,!0,t.length,s,"",n),O(t)}else{do{const{chunk:n,encoding:i,callback:o}=r[a];r[a++]=null;L(e,t,!1,s?1:n.length,n,i,o)}while(a<r.length&&!t.writing);a===r.length?O(t):a>256?(r.splice(0,a),t.bufferedIndex=0):t.bufferedIndex=a}t.bufferProcessing=!1}function q(e){return e.ending&&!e.destroyed&&e.constructed&&0===e.length&&!e.errored&&0===e.buffered.length&&!e.finished&&!e.writing&&!e.errorEmitted&&!e.closeEmitted}function K(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.finalCalled=!0,function(e,t){let r=!1;function i(i){if(r)k(e,null!=i?i:S());else if(r=!0,t.pendingcb--,i){const r=t[N].splice(0);for(let e=0;e<r.length;e++)r[e](i);k(e,i,t.sync)}else q(t)&&(t.prefinished=!0,e.emit("prefinish"),t.pendingcb++,n.nextTick(H,e,t))}t.sync=!0,t.pendingcb++;try{e._final(i)}catch(e){i(e)}t.sync=!1}(e,t)))}function W(e,t,r){q(t)&&(K(e,t),0===t.pendingcb&&(r?(t.pendingcb++,n.nextTick((e,t)=>{q(t)?H(e,t):t.pendingcb--},e,t)):q(t)&&(t.pendingcb++,H(e,t))))}function H(e,t){t.pendingcb--,t.finished=!0;const r=t[N].splice(0);for(let e=0;e<r.length;e++)r[e]();if(e.emit("finish"),t.autoDestroy){const t=e._readableState;(!t||t.autoDestroy&&(t.endEmitted||!1===t.readable))&&e.destroy()}}P.prototype.getBuffer=function(){return i(this.buffered,this.bufferedIndex)},a(P.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}}),a(C,d,{__proto__:null,value:function(e){return!!o(this,e)||this===C&&(e&&e._writableState instanceof P)}}),C.prototype.pipe=function(){k(this,new I)},C.prototype.write=function(e,t,r){return!0===D(this,e,t,r)},C.prototype.cork=function(){this._writableState.corked++},C.prototype.uncork=function(){const e=this._writableState;e.corked&&(e.corked--,e.writing||z(this,e))},C.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=l(e)),!_.isEncoding(e))throw new A(e);return this._writableState.defaultEncoding=e,this},C.prototype._write=function(e,t,r){if(!this._writev)throw new v("_write()");this._writev([{chunk:e,encoding:t}],r)},C.prototype._writev=null,C.prototype.end=function(e,t,r){const i=this._writableState;let o;if("function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e){const r=D(this,e,t);r instanceof s&&(o=r)}return i.corked&&(i.corked=1,this.uncork()),o||(i.errored||i.ending?i.finished?o=new E("end"):i.destroyed&&(o=new x("end")):(i.ending=!0,W(this,i,!0),i.ended=!0)),"function"==typeof r&&(o||i.finished?n.nextTick(r,o):i[N].push(r)),this},c(C.prototype,{closed:{__proto__:null,get(){return!!this._writableState&&this._writableState.closed}},destroyed:{__proto__:null,get(){return!!this._writableState&&this._writableState.destroyed},set(e){this._writableState&&(this._writableState.destroyed=e)}},writable:{__proto__:null,get(){const e=this._writableState;return!(!e||!1===e.writable||e.destroyed||e.errored||e.ending||e.ended)},set(e){this._writableState&&(this._writableState.writable=!!e)}},writableFinished:{__proto__:null,get(){return!!this._writableState&&this._writableState.finished}},writableObjectMode:{__proto__:null,get(){return!!this._writableState&&this._writableState.objectMode}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return!!this._writableState&&this._writableState.ending}},writableNeedDrain:{__proto__:null,get(){const e=this._writableState;return!!e&&(!e.destroyed&&!e.ending&&e.needDrain)}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!(!1===this._writableState.writable||!this._writableState.destroyed&&!this._writableState.errored||this._writableState.finished)}}});const Q=g.destroy;let J;function G(){return void 0===J&&(J={}),J}C.prototype.destroy=function(e,t){const r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[N].length)&&n.nextTick(B,r),Q.call(this,e,t),this},C.prototype._undestroy=g.undestroy,C.prototype._destroy=function(e,t){t(e)},C.prototype[f.captureRejectionSymbol]=function(e){this.destroy(e)},C.fromWeb=function(e,t){return G().newStreamWritableFromWritableStream(e,t)},C.toWeb=function(e){return G().newWritableStreamFromStreamWritable(e)}},277(e,t,r){"use strict";const{ArrayIsArray:n,ArrayPrototypeIncludes:i,ArrayPrototypeJoin:s,ArrayPrototypeMap:o,NumberIsInteger:a,NumberIsNaN:c,NumberMAX_SAFE_INTEGER:u,NumberMIN_SAFE_INTEGER:l,NumberParseInt:h,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:f,String:p,StringPrototypeToUpperCase:_,StringPrototypeTrim:g}=r(134),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:b,ERR_INVALID_ARG_VALUE:m,ERR_OUT_OF_RANGE:v,ERR_UNKNOWN_SIGNAL:S}}=r(371),{normalizeEncoding:I}=r(760),{isAsyncFunction:x,isArrayBufferView:E}=r(760).types;const T=y((e,t,r=l,n=u)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new v(t,"an integer",e);if(e<r||e>n)throw new v(t,`>= ${r} && <= ${n}`,e)});y((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new v(t,"an integer",e);if(e<r||e>n)throw new v(t,`>= ${r} && <= ${n}`,e)}),y((e,t,r=!1)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new v(t,"an integer",e);const n=r?1:0,i=4294967295;if(e<n||e>i)throw new v(t,`>= ${n} && <= ${i}`,e)});y((e,t,r)=>{if(!i(r,e)){const n=s(o(r,e=>"string"==typeof e?`'${e}'`:p(e)),", ");throw new m(t,e,"must be one of: "+n)}});function R(e,t){if("boolean"!=typeof e)throw new b(t,"boolean",e)}function A(e,t,r){return null!=e&&d(e,t)?e[t]:r}const k=y((e,t,r=null)=>{const i=A(r,"allowArray",!1),s=A(r,"allowFunction",!1);if(!A(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!s||"function"!=typeof e))throw new b(t,"Object",e)});y((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new b(t,"a dictionary",e)}),y((e,t,r=0)=>{if(!n(e))throw new b(t,"Array",e);if(e.length<r){throw new m(t,e,`must be longer than ${r}`)}});y((e,t="buffer")=>{if(!E(e))throw new b(t,["Buffer","TypedArray","DataView"],e)});const j=y((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new b(t,"AbortSignal",e)}),N=y((e,t)=>{if("function"!=typeof e)throw new b(t,"Function",e)});y((e,t)=>{if("function"!=typeof e||x(e))throw new b(t,"Function",e)}),y((e,t)=>{if(void 0!==e)throw new b(t,"undefined",e)});e.exports={validateBoolean:R,validateFunction:N,validateInteger:T,validateObject:k,validateAbortSignal:j}},371(e,t,r){"use strict";const{format:n,inspect:i}=r(231),{AggregateError:s}=r(134),o=globalThis.AggregateError||s,a=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],u=/^([A-Z][a-z0-9]*)+$/,l={};function h(e,t){if(!e)throw new l.ERR_INTERNAL_ASSERTION(t)}function d(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 f(e,t,r){r||(r=Error);class NodeError extends r{constructor(...r){super(function(e,t,r){if("function"==typeof t)return h(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);const i=(t.match(/%[dfijoOs]/g)||[]).length;return h(i===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${i}).`),0===r.length?t:n(t,...r)}(e,t,r))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(NodeError.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),NodeError.prototype.code=e,NodeError.prototype[a]=!0,l[e]=NodeError}function p(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class AbortError extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new l.ERR_INVALID_ARG_TYPE("options","Object",t);super(e,t),this.code="ABORT_ERR",this.name="AbortError"}}f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(e,t,r)=>{h("string"==typeof e,"'name' must be a string"),Array.isArray(t)||(t=[t]);let n="The ";e.endsWith(" argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="must be ";const s=[],o=[],a=[];for(const e of t)h("string"==typeof e,"All expected entries have to be of type string"),c.includes(e)?s.push(e.toLowerCase()):u.test(e)?o.push(e):(h("object"!==e,'The value "object" should be written as "Object"'),a.push(e));if(o.length>0){const e=s.indexOf("object");-1!==e&&(s.splice(s,e,1),o.push("Object"))}if(s.length>0){switch(s.length){case 1:n+=`of type ${s[0]}`;break;case 2:n+=`one of type ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`one of type ${s.join(", ")}, or ${e}`}}(o.length>0||a.length>0)&&(n+=" or ")}if(o.length>0){switch(o.length){case 1:n+=`an instance of ${o[0]}`;break;case 2:n+=`an instance of ${o[0]} or ${o[1]}`;break;default:{const e=o.pop();n+=`an instance of ${o.join(", ")}, or ${e}`}}a.length>0&&(n+=" or ")}switch(a.length){case 0:break;case 1:a[0].toLowerCase()!==a[0]&&(n+="an "),n+=`${a[0]}`;break;case 2:n+=`one of ${a[0]} or ${a[1]}`;break;default:{const e=a.pop();n+=`one of ${a.join(", ")}, or ${e}`}}if(null==r)n+=`. Received ${r}`;else if("function"==typeof r&&r.name)n+=`. Received function ${r.name}`;else if("object"==typeof r){var l;if(null!==(l=r.constructor)&&void 0!==l&&l.name)n+=`. Received an instance of ${r.constructor.name}`;else{n+=`. Received ${i(r,{depth:-1})}`}}else{let e=i(r,{colors:!1});e.length>25&&(e=`${e.slice(0,25)}...`),n+=`. Received type ${typeof r} (${e})`}return n},TypeError),f("ERR_INVALID_ARG_VALUE",(e,t,r="is invalid")=>{let n=i(t);n.length>128&&(n=n.slice(0,128)+"...");return`The ${e.includes(".")?"property":"argument"} '${e}' ${r}. Received ${n}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(e,t,r)=>{var n;return`Expected ${e} to be returned from the "${t}" function but got ${null!=r&&null!==(n=r.constructor)&&void 0!==n&&n.name?`instance of ${r.constructor.name}`:"type "+typeof r}.`},TypeError),f("ERR_MISSING_ARGS",(...e)=>{let t;h(e.length>0,"At least one arg needs to be specified");const r=e.length;switch(e=(Array.isArray(e)?e:[e]).map(e=>`"${e}"`).join(" or "),r){case 1:t+=`The ${e[0]} argument`;break;case 2:t+=`The ${e[0]} and ${e[1]} arguments`;break;default:{const r=e.pop();t+=`The ${e.join(", ")}, and ${r} arguments`}}return`${t} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(e,t,r)=>{let n;if(h(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32)n=d(String(r));else if("bigint"==typeof r){n=String(r);const e=BigInt(2)**BigInt(32);(r>e||r<-e)&&(n=d(n)),n+="n"}else n=i(r);return`The value of "${e}" is out of range. It must be ${t}. Received ${n}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError,aggregateTwoErrors:p(function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new o([t,e],t.message);return r.code=t.code,r}return e||t}),hideStackFrames:p,codes:l}},134(e){"use strict";class AggregateError extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError("Expected input to be an Array, got "+typeof e);let t="";for(let r=0;r<e.length;r++)t+=` ${e[r].stack}\n`;super(t),this.name="AggregateError",this.errors=e}}e.exports={AggregateError,ArrayIsArray:e=>Array.isArray(e),ArrayPrototypeIncludes:(e,t)=>e.includes(t),ArrayPrototypeIndexOf:(e,t)=>e.indexOf(t),ArrayPrototypeJoin:(e,t)=>e.join(t),ArrayPrototypeMap:(e,t)=>e.map(t),ArrayPrototypePop:(e,t)=>e.pop(t),ArrayPrototypePush:(e,t)=>e.push(t),ArrayPrototypeSlice:(e,t,r)=>e.slice(t,r),Error,FunctionPrototypeCall:(e,t,...r)=>e.call(t,...r),FunctionPrototypeSymbolHasInstance:(e,t)=>Function.prototype[Symbol.hasInstance].call(e,t),MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties:(e,t)=>Object.defineProperties(e,t),ObjectDefineProperty:(e,t,r)=>Object.defineProperty(e,t,r),ObjectGetOwnPropertyDescriptor:(e,t)=>Object.getOwnPropertyDescriptor(e,t),ObjectKeys:e=>Object.keys(e),ObjectSetPrototypeOf:(e,t)=>Object.setPrototypeOf(e,t),Promise,PromisePrototypeCatch:(e,t)=>e.catch(t),PromisePrototypeThen:(e,t,r)=>e.then(t,r),PromiseReject:e=>Promise.reject(e),PromiseResolve:e=>Promise.resolve(e),ReflectApply:Reflect.apply,RegExpPrototypeTest:(e,t)=>e.test(t),SafeSet:Set,String,StringPrototypeSlice:(e,t,r)=>e.slice(t,r),StringPrototypeToLowerCase:e=>e.toLowerCase(),StringPrototypeToUpperCase:e=>e.toUpperCase(),StringPrototypeTrim:e=>e.trim(),Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet:(e,t,r)=>e.set(t,r),Boolean,Uint8Array}},760(e,t,r){"use strict";const n=r(287),{format:i,inspect:s}=r(231),{codes:{ERR_INVALID_ARG_TYPE:o}}=r(371),{kResistStopPropagation:a,AggregateError:c,SymbolDispose:u}=r(134),l=globalThis.AbortSignal||r(568).AbortSignal,h=globalThis.AbortController||r(568).AbortController,d=Object.getPrototypeOf(async function(){}).constructor,f=globalThis.Blob||n.Blob,p=void 0!==f?function(e){return e instanceof f}:function(e){return!1},_=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new o(t,"AbortSignal",e)};e.exports={AggregateError:c,kEmptyObject:Object.freeze({}),once(e){let t=!1;return function(...r){t||(t=!0,e.apply(this,r))}},createDeferredPromise:function(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}},promisify:e=>new Promise((t,r)=>{e((e,...n)=>e?r(e):t(...n))}),debuglog:()=>function(){},format:i,inspect:s,types:{isAsyncFunction:e=>e instanceof d,isArrayBufferView:e=>ArrayBuffer.isView(e)},isBlob:p,deprecate:(e,t)=>e,addAbortListener:r(7).addAbortListener||function(e,t){if(void 0===e)throw new o("signal","AbortSignal",e);let r;return _(e,"signal"),((e,t)=>{if("function"!=typeof e)throw new o(t,"Function",e)})(t,"listener"),e.aborted?queueMicrotask(()=>t()):(e.addEventListener("abort",t,{__proto__:null,once:!0,[a]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[u](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:l.any||function(e){if(1===e.length)return e[0];const t=new h,r=()=>t.abort();return e.forEach(e=>{_(e,"signals"),e.addEventListener("abort",r,{once:!0})}),t.signal.addEventListener("abort",()=>{e.forEach(e=>e.removeEventListener("abort",r))},{once:!0}),t.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},231(e){"use strict";e.exports={format:(e,...t)=>e.replace(/%([sdifj])/g,function(...[e,r]){const n=t.shift();if("f"===r)return n.toFixed(6);if("j"===r)return JSON.stringify(n);if("s"===r&&"object"==typeof n){return`${n.constructor!==Object?n.constructor.name:""} {}`.trim()}return n.toString()}),inspect(e){switch(typeof e){case"string":if(e.includes("'")){if(!e.includes('"'))return`"${e}"`;if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}}}},861(e,t,r){var n=r(287),i=n.Buffer;function s(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(s(n,t),t.Buffer=o),o.prototype=Object.create(i.prototype),s(i,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},141(e,t,r){"use strict";var n=r(861).Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=h,t=3;break;default:return this.write=d,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function u(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function l(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function h(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=s,s.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""},s.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},s.prototype.text=function(e,t){var r=function(e,t,r){var n=t.length-1;if(n<r)return 0;var i=o(t[n]);if(i>=0)return i>0&&(e.lastNeed=i-1),i;if(--n<r||-2===i)return 0;if(i=o(t[n]),i>=0)return i>0&&(e.lastNeed=i-2),i;if(--n<r||-2===i)return 0;if(i=o(t[n]),i>=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},s.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},955(t){"use strict";t.exports=e},981(e){"use strict";e.exports=t}};const n={};function i(e){const t=n[e];if(void 0!==t)return t.exports;const s=n[e]={exports:{}};return r[e].call(s.exports,s,s.exports,i),s.exports}i.cw=e=>{var t;return()=>{if(e){var r=e;e=0,t={exports:{}},r.call(t.exports,t,t.exports)}return t.exports}},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let s={};return(()=>{"use strict";i.r(s),i.d(s,{Activity:()=>rd,ActivityAdd:()=>nd,ActivityRemove:()=>id,Collection:()=>Yh,Container:()=>td,DatasetSubscription:()=>DatasetSubscription,DefaultEngine:()=>ld,EventStream:()=>ed,GreaterThanOrEqualToRelation:()=>Jh,GreaterThanRelation:()=>Gh,LessThanOrEqualToRelation:()=>Vh,LessThanRelation:()=>Xh,Node:()=>Zh,PropertyType:()=>ud,Relation:()=>Qh,SolidClientService:()=>SolidClientService,SolidDataDriver:()=>SolidDataDriver,SolidProfileObject:()=>sd,SolidPropertyService:()=>SolidPropertyService,SolidPropertySink:()=>SolidPropertySink,SolidPropertySource:()=>SolidPropertySource,SolidService:()=>SolidService,defaultThingDeserializer:()=>ad,defaultThingSerializer:()=>od});var e=i.cw(function(e,t){var r=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),n=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.QueryEngineBase=void 0,n(i(638),t),n(i(358),t);var s=i(235);Object.defineProperty(t,"QueryEngineBase",{enumerable:!0,get:function(){return s.QueryEngineBase}})}),t=()=>i(287),r=i.cw(e=>{var t=/^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i,r=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,n=/\s|\uFEFF|\xA0/,i=/\r?\n[\x20\x09]+/g,s=/[;,"]/,o=/[;,"]|\s/,a=/^[!#$%&'*+\-\.^_`|~\da-zA-Z]+$/,c=1,u=2,l=4;function h(e){return e.replace(r,"")}function d(e){return n.test(e)}function f(e,t){for(;d(e[t]);)t++;return t}function p(e){return o.test(e)||!a.test(e)}class Link{constructor(e){this.refs=[],e&&this.parse(e)}rel(e){for(var t=[],r=e.toLowerCase(),n=0;n<this.refs.length;n++)"string"==typeof this.refs[n].rel&&this.refs[n].rel.toLowerCase()===r&&t.push(this.refs[n]);return t}get(e,t){e=e.toLowerCase(),t=t.toLowerCase();for(var r=[],n=0;n<this.refs.length;n++)"string"==typeof this.refs[n][e]&&this.refs[n][e].toLowerCase()===t&&r.push(this.refs[n]);return r}set(e){return this.refs.push(e),this}setUnique(e){return this.refs.some(t=>{return r=t,n=e,Object.keys(r).length===Object.keys(n).length&&Object.keys(r).every(e=>e in n&&r[e]===n[e]);var r,n})||this.refs.push(e),this}has(e,t){e=e.toLowerCase(),t=t.toLowerCase();for(var r=0;r<this.refs.length;r++)if("string"==typeof this.refs[r][e]&&this.refs[r][e].toLowerCase()===t)return!0;return!1}parse(e,t){e=h(e=(t=t||0)?e.slice(t):e).replace(i,"");for(var r=c,n=e.length,o=(t=0,null);t<n;)if(r===c){if(d(e[t])){t++;continue}if("<"!==e[t])throw new Error('Unexpected character "'+e[t]+'" at offset '+t);if(null!=o&&(null!=o.rel?this.refs.push(...Link.expandRelations(o)):this.refs.push(o)),-1===(_=e.indexOf(">",t)))throw new Error("Expected end of URI delimiter at offset "+t);o={uri:e.slice(t+1,_)},t=_,r=u,t++}else if(r===u){if(d(e[t])){t++;continue}if(";"===e[t])r=l,t++;else{if(","!==e[t])throw new Error('Unexpected character "'+e[t]+'" at offset '+t);r=c,t++}}else{if(r!==l)throw new Error('Unknown parser state "'+r+'"');if(";"===e[t]||d(e[t])){t++;continue}-1===(_=e.indexOf("=",t))&&(_=e.indexOf(";",t)),-1===_&&(_=e.length);var a=h(e.slice(t,_)).toLowerCase(),p="";if('"'===e[t=f(e,t=_+1)])for(t++;t<n;){if('"'===e[t]){t++;break}"\\"===e[t]&&t++,p+=e[t],t++}else{for(var _=t+1;!s.test(e[_])&&_<n;)_++;p=e.slice(t,_),t=_}switch(o[a]&&Link.isSingleOccurenceAttr(a)||("*"===a[a.length-1]?o[a]=Link.parseExtendedValue(p):(p="type"===a?p.toLowerCase():p,null!=o[a]?Array.isArray(o[a])?o[a].push(p):o[a]=[o[a],p]:o[a]=p)),e[t]){case",":r=c;break;case";":r=l}t++}return null!=o&&(null!=o.rel?this.refs.push(...Link.expandRelations(o)):this.refs.push(o)),o=null,this}toString(){for(var e=[],t="",r=null,n=0;n<this.refs.length;n++)r=this.refs[n],t=Object.keys(this.refs[n]).reduce(function(e,t){return"uri"===t?e:e+"; "+Link.formatAttribute(t,r[t])},"<"+r.uri+">"),e.push(t);return e.join(", ")}}Link.isCompatibleEncoding=function(e){return t.test(e)},Link.parse=function(e,t){return(new Link).parse(e,t)},Link.isSingleOccurenceAttr=function(e){return"rel"===e||"type"===e||"media"===e||"title"===e||"title*"===e},Link.isTokenAttr=function(e){return"rel"===e||"type"===e||"anchor"===e},Link.escapeQuotes=function(e){return e.replace(/"/g,'\\"')},Link.expandRelations=function(e){return e.rel.split(" ").map(function(t){var r=Object.assign({},e);return r.rel=t,r})},Link.parseExtendedValue=function(e){var t=/([^']+)?(?:'([^']*)')?(.+)/.exec(e);return{language:t[2].toLowerCase(),encoding:Link.isCompatibleEncoding(t[1])?null:t[1].toLowerCase(),value:Link.isCompatibleEncoding(t[1])?decodeURIComponent(t[3]):t[3]}},Link.formatExtendedAttribute=function(e,t){var r=(t.encoding||"utf-8").toUpperCase();return e+"="+r+"'"+(t.language||"en")+"'"+("undefined"!=typeof Buffer&&Buffer.isBuffer(t.value)&&Link.isCompatibleEncoding(r)?t.value.toString(r):"undefined"!=typeof Buffer&&Buffer.isBuffer(t.value)?t.value.toString("hex").replace(/[0-9a-f]{2}/gi,"%$1"):encodeURIComponent(t.value))},Link.formatAttribute=function(e,t){return Array.isArray(t)?t.map(t=>Link.formatAttribute(e,t)).join("; "):"*"===e[e.length-1]||"string"!=typeof t?Link.formatExtendedAttribute(e,t):(Link.isTokenAttr(e)?t=p(t)?'"'+Link.escapeQuotes(t)+'"':Link.escapeQuotes(t):p(t)&&(t='"'+(t=(t=encodeURIComponent(t)).replace(/%20/g," ").replace(/%2C/g,",").replace(/%3B/g,";"))+'"'),e+"="+t)},e.exports=Link}),n=()=>i(147),o=i.cw(e=>{const{pipeline:t}=h(),r=c(),{destroyer:n}=a(),{isNodeStream:i,isReadable:s,isWritable:o,isWebStream:l,isTransformStream:f,isWritableStream:p,isReadableStream:g}=d(),{AbortError:y,codes:{ERR_INVALID_ARG_VALUE:w,ERR_MISSING_ARGS:b}}=_(),m=u();e.exports=function(...e){if(0===e.length)throw new b("streams");if(1===e.length)return r.from(e[0]);const a=[...e];if("function"==typeof e[0]&&(e[0]=r.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=r.from(e[t])}for(let t=0;t<e.length;++t)if(i(e[t])||l(e[t])){if(t<e.length-1&&!(s(e[t])||g(e[t])||f(e[t])))throw new w(`streams[${t}]`,a[t],"must be readable");if(t>0&&!(o(e[t])||p(e[t])||f(e[t])))throw new w(`streams[${t}]`,a[t],"must be writable")}let c,u,h,d,_;const v=e[0],S=t(e,function(e){const t=d;d=null,t?t(e):e?_.destroy(e):x||I||_.destroy()}),I=!!(o(v)||p(v)||f(v)),x=!!(s(S)||g(S)||f(S));if(_=new r({writableObjectMode:!(null==v||!v.writableObjectMode),readableObjectMode:!(null==S||!S.readableObjectMode),writable:I,readable:x}),I){if(i(v))_._write=function(e,t,r){v.write(e,t)?r():c=r},_._final=function(e){v.end(),u=e},v.on("drain",function(){if(c){const e=c;c=null,e()}});else if(l(v)){const e=(f(v)?v.writable:v).getWriter();_._write=async function(t,r,n){try{await e.ready,e.write(t).catch(()=>{}),n()}catch(e){n(e)}},_._final=async function(t){try{await e.ready,e.close().catch(()=>{}),u=t}catch(e){t(e)}}}const e=f(S)?S.readable:S;m(e,()=>{if(u){const e=u;u=null,e()}})}if(x)if(i(S))S.on("readable",function(){if(h){const e=h;h=null,e()}}),S.on("end",function(){_.push(null)}),_._read=function(){for(;;){const e=S.read();if(null===e)return void(h=_._read);if(!_.push(e))return}};else if(l(S)){const e=(f(S)?S.readable:S).getReader();_._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!_.push(t))return;if(r)return void _.push(null)}catch{return}}}return _._destroy=function(e,t){e||null===d||(e=new y),h=null,c=null,u=null,null===d?t(e):(d=t,i(S)&&n(S,e))},_}}),a=()=>i(896),c=()=>i(370),u=()=>i(238),l=i.cw(e=>{const t=globalThis.AbortController||i(568).AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:s,ERR_MISSING_ARGS:a,ERR_OUT_OF_RANGE:c},AbortError:l}=_(),{validateAbortSignal:h,validateInteger:p,validateObject:w}=f(),b=g().Symbol("kWeak"),m=g().Symbol("kResistStopPropagation"),{finished:v}=u(),S=o(),{addAbortSignalNoValidate:I}=n(),{isWritable:x,isNodeStream:E}=d(),{deprecate:T}=y(),{ArrayPrototypePush:R,Boolean:A,MathFloor:k,Number:j,NumberIsNaN:N,Promise:P,PromiseReject:O,PromiseResolve:C,PromisePrototypeThen:D,Symbol:L}=g(),$=L("kEmpty"),U=L("kEof");function M(e,t){if("function"!=typeof e)throw new s("fn",["Function","AsyncFunction"],e);null!=t&&w(t,"options"),null!=(null==t?void 0:t.signal)&&h(t.signal,"options.signal");let r=1;null!=(null==t?void 0:t.concurrency)&&(r=k(t.concurrency));let n=r-1;return null!=(null==t?void 0:t.highWaterMark)&&(n=k(t.highWaterMark)),p(r,"options.concurrency",1),p(n,"options.highWaterMark",0),n+=r,async function*(){const i=y().AbortSignalAny([null==t?void 0:t.signal].filter(A)),s=this,o=[],a={signal:i};let c,u,h=!1,d=0;function f(){h=!0,p()}function p(){d-=1,_()}function _(){u&&!h&&d<r&&o.length<n&&(u(),u=null)}!async function(){try{for await(let t of s){if(h)return;if(i.aborted)throw new l;try{if(t=e(t,a),t===$)continue;t=C(t)}catch(e){t=O(e)}d+=1,D(t,p,f),o.push(t),c&&(c(),c=null),!h&&(o.length>=n||d>=r)&&await new P(e=>{u=e})}o.push(U)}catch(e){const t=O(e);D(t,p,f),o.push(t)}finally{h=!0,c&&(c(),c=null)}}();try{for(;;){for(;o.length>0;){const e=await o[0];if(e===U)return;if(i.aborted)throw new l;e!==$&&(yield e),o.shift(),_()}await new P(e=>{c=e})}}finally{h=!0,u&&(u(),u=null)}}.call(this)}async function F(e,t=void 0){for await(const r of B.call(this,e,t))return!0;return!1}function B(e,t){if("function"!=typeof e)throw new s("fn",["Function","AsyncFunction"],e);return M.call(this,async function(t,r){return await e(t,r)?t:$},t)}class ReduceAwareErrMissingArgs extends a{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function z(e){if(e=j(e),N(e))return 0;if(e<0)throw new c("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:T(function(e=void 0){return null!=e&&w(e,"options"),null!=(null==e?void 0:e.signal)&&h(e.signal,"options.signal"),async function*(){let t=0;for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new l({cause:e.signal.reason});yield[t++,n]}}.call(this)},"readable.asIndexedPairs will be removed in a future version."),drop:function(e,t=void 0){return null!=t&&w(t,"options"),null!=(null==t?void 0:t.signal)&&h(t.signal,"options.signal"),e=z(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new l;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new l;e--<=0&&(yield r)}}.call(this)},filter:B,flatMap:function(e,t){const r=M.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:M,take:function(e,t=void 0){return null!=t&&w(t,"options"),null!=(null==t?void 0:t.signal)&&h(t.signal,"options.signal"),e=z(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new l;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new l;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&w(t,"options"),null!=(null==t?void 0:t.signal)&&h(t.signal,"options.signal"),E(e)&&!x(e))throw new r("stream",e,"must be writable");const n=S(this,e);return null!=t&&t.signal&&I(t.signal,n),n}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new s("fn",["Function","AsyncFunction"],e);return!await F.call(this,async(...t)=>!await e(...t),t)},forEach:async function(e,t){if("function"!=typeof e)throw new s("fn",["Function","AsyncFunction"],e);for await(const r of M.call(this,async function(t,r){return await e(t,r),$},t));},reduce:async function(e,r,n){var i;if("function"!=typeof e)throw new s("reducer",["Function","AsyncFunction"],e);null!=n&&w(n,"options"),null!=(null==n?void 0:n.signal)&&h(n.signal,"options.signal");let o=arguments.length>1;if(null!=n&&null!==(i=n.signal)&&void 0!==i&&i.aborted){const e=new l(void 0,{cause:n.signal.reason});throw this.once("error",()=>{}),await v(this.destroy(e)),e}const a=new t,c=a.signal;if(null!=n&&n.signal){const e={once:!0,[b]:this,[m]:!0};n.signal.addEventListener("abort",()=>a.abort(),e)}let u=!1;try{for await(const t of this){var d;if(u=!0,null!=n&&null!==(d=n.signal)&&void 0!==d&&d.aborted)throw new l;o?r=await e(r,t,{signal:c}):(r=t,o=!0)}if(!u&&!o)throw new ReduceAwareErrMissingArgs}finally{a.abort()}return r},toArray:async function(e){null!=e&&w(e,"options"),null!=(null==e?void 0:e.signal)&&h(e.signal,"options.signal");const t=[];for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new l(void 0,{cause:e.signal.reason});R(t,n)}return t},some:F,find:async function(e,t){for await(const r of B.call(this,e,t))return r}}}),h=()=>i(758),d=()=>i(115),f=()=>i(277),p=i.cw(e=>{const t=w(),r=b(),n=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=n,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get:()=>r}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),_=()=>i(371),g=()=>i(134),y=()=>i(760),w=i.cw(e=>{const{Buffer:r}=t(),{ObjectDefineProperty:s,ObjectKeys:f,ReflectApply:p}=g(),{promisify:{custom:w}}=y(),{streamReturningOperators:m,promiseReturningOperators:v}=l(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:S}}=_(),I=o(),{setDefaultHighWaterMark:x,getDefaultHighWaterMark:E}=i(291),{pipeline:T}=h(),{destroyer:R}=a(),A=u(),k=b(),j=d(),N=e.exports=i(259).Stream;N.isDestroyed=j.isDestroyed,N.isDisturbed=j.isDisturbed,N.isErrored=j.isErrored,N.isReadable=j.isReadable,N.isWritable=j.isWritable,N.Readable=i(576);for(const O of f(m)){const C=m[O];function D(...e){if(new.target)throw S();return N.Readable.from(p(C,this,e))}s(D,"name",{__proto__:null,value:C.name}),s(D,"length",{__proto__:null,value:C.length}),s(N.Readable.prototype,O,{__proto__:null,value:D,enumerable:!1,configurable:!0,writable:!0})}for(const L of f(v)){const $=v[L];function U(...e){if(new.target)throw S();return p($,this,e)}s(U,"name",{__proto__:null,value:$.name}),s(U,"length",{__proto__:null,value:$.length}),s(N.Readable.prototype,L,{__proto__:null,value:U,enumerable:!1,configurable:!0,writable:!0})}N.Writable=i(584),N.Duplex=c(),N.Transform=i(382),N.PassThrough=i(524),N.pipeline=T;const{addAbortSignal:P}=n();N.addAbortSignal=P,N.finished=A,N.destroy=R,N.compose=I,N.setDefaultHighWaterMark=x,N.getDefaultHighWaterMark=E,s(N,"promises",{__proto__:null,configurable:!0,enumerable:!0,get:()=>k}),s(T,w,{__proto__:null,enumerable:!0,get:()=>k.pipeline}),s(A,w,{__proto__:null,enumerable:!0,get:()=>k.finished}),N.Stream=N,N._isUint8Array=function(e){return e instanceof Uint8Array},N._uint8ArrayToBuffer=function(e){return r.from(e.buffer,e.byteOffset,e.byteLength)}}),b=i.cw(e=>{const{ArrayPrototypePop:t,Promise:r}=g(),{isIterable:n,isNodeStream:i,isWebStream:s}=d(),{pipelineImpl:o}=h(),{finished:a}=u();w(),e.exports={finished:a,pipeline:function(...e){return new r((r,a)=>{let c,u;const l=e[e.length-1];if(l&&"object"==typeof l&&!i(l)&&!n(l)&&!s(l)){const r=t(e);c=r.signal,u=r.end}o(e,(e,t)=>{e?a(e):r(t)},{signal:c,end:u})})}}}),m={};i.r(m),i.d(m,{EventSource:()=>oc,EventStream:()=>sc,RetentionPolicy:()=>ac,Vocabulary:()=>cc,_BASE:()=>uc,_PREFIX:()=>lc,amount:()=>Ya,pointInTime:()=>Za,retentionPolicy:()=>Xa,timestampPath:()=>rc,versionKey:()=>ec,versionMaterializationOf:()=>nc,versionMaterializationUntil:()=>ic,versionOfPath:()=>tc});var v={};i.r(v),i.d(v,{Ascending:()=>Uc,BasicContainer:()=>Ac,Container:()=>Rc,Descending:()=>Mc,DirectContainer:()=>kc,IndirectContainer:()=>jc,MemberSubject:()=>Oc,NonRDFSource:()=>Tc,Page:()=>Nc,PageSortCriterion:()=>Pc,PreferContainment:()=>Cc,PreferEmptyContainer:()=>Lc,PreferMembership:()=>Dc,PreferMinimalContainer:()=>$c,RDFSource:()=>Ec,Resource:()=>xc,_BASE:()=>Fc,_PREFIX:()=>Bc,constrainedBy:()=>yc,contains:()=>gc,hasMemberRelation:()=>hc,inbox:()=>Ic,insertedContentRelation:()=>pc,isMemberOfRelation:()=>dc,member:()=>_c,membershipResource:()=>fc,pageSequence:()=>Sc,pageSortCollation:()=>vc,pageSortCriteria:()=>wc,pageSortOrder:()=>mc,pageSortPredicate:()=>bc});var S={};i.r(S),i.d(S,{Collection:()=>su,ConditionalImport:()=>lu,EqualToRelation:()=>wu,GeospatiallyContainsRelation:()=>mu,GreaterThanOrEqualToRelation:()=>_u,GreaterThanRelation:()=>pu,InBetweenRelation:()=>vu,LessThanOrEqualToRelation:()=>yu,LessThanRelation:()=>gu,Node:()=>au,NotEqualToRelation:()=>bu,Ontology:()=>Su,PrefixRelation:()=>hu,Relation:()=>uu,RootNode:()=>cu,SearchTree:()=>ou,SubstringRelation:()=>du,SuffixRelation:()=>fu,_BASE:()=>Iu,_PREFIX:()=>xu,conditionalImport:()=>eu,import__workaround:()=>Zc,latitudeTile:()=>nu,longitudeTile:()=>ru,member:()=>Vc,node:()=>Wc,path:()=>Jc,relation:()=>qc,remainingItems:()=>Kc,rootNode:()=>Hc,search:()=>Xc,shape:()=>Yc,timeQuery:()=>iu,value:()=>Qc,view:()=>Gc,viewDescription:()=>zc,zoom:()=>tu});var I={};i.r(I),i.d(I,{Accept:()=>Mu,Activity:()=>Tu,Add:()=>qu,Announce:()=>Ku,Application:()=>Wu,Arrive:()=>Hu,Article:()=>Qu,Audio:()=>Ju,Block:()=>Fu,Collection:()=>ku,CollectionPage:()=>ju,Create:()=>Xu,Delete:()=>Yu,Dislike:()=>Zu,Document:()=>Gu,Event:()=>el,Flag:()=>tl,Follow:()=>rl,Group:()=>nl,Ignore:()=>Bu,Image:()=>Nu,IntransitiveActivity:()=>zu,Invite:()=>il,Join:()=>ol,Leave:()=>al,Like:()=>cl,Link:()=>Au,Listen:()=>ll,Mention:()=>pl,Move:()=>dl,Note:()=>_l,Object__workaround:()=>Ru,Offer:()=>sl,OrderedCollection:()=>Vu,OrderedCollectionPage:()=>Uu,OrderedItems:()=>Pu,Organization:()=>wl,Page:()=>gl,Person:()=>yl,Place:()=>$u,Profile:()=>Du,Question:()=>Cu,Read:()=>hl,Reject:()=>bl,Relationship:()=>Ou,Remove:()=>ml,Service:()=>vl,TentativeAccept:()=>Sl,TentativeReject:()=>Il,Tombstone:()=>Lu,Travel:()=>fl,Undo:()=>xl,Update:()=>El,Video:()=>Tl,View:()=>ul,_BASE:()=>Bh,_PREFIX:()=>zh,accuracy:()=>dh,actor:()=>Rl,altitude:()=>fh,anyOf:()=>Jl,attachment:()=>kl,attachments:()=>jl,attributedTo:()=>Al,audience:()=>eh,author:()=>Nl,bcc:()=>Pl,bto:()=>Ol,cc:()=>Cl,content:()=>ph,context:()=>Dl,current:()=>Ll,deleted:()=>Fh,describes:()=>lh,downstreamDuplicates:()=>gh,duration:()=>yh,endTime:()=>wh,first:()=>$l,formerType:()=>hh,generator:()=>Ul,height:()=>bh,href:()=>mh,hreflang:()=>vh,icon:()=>Ml,id:()=>Sh,image:()=>Fl,inReplyTo:()=>Bl,instrument:()=>oh,items:()=>zl,last:()=>ql,latitude:()=>Ih,location:()=>Kl,longitude:()=>xh,mediaType:()=>Eh,name:()=>_h,next:()=>Wl,object:()=>Hl,objectType:()=>Th,oneOf:()=>Ql,origin:()=>sh,partOf:()=>th,prev:()=>Gl,preview:()=>Vl,provider:()=>Xl,published:()=>Rh,radius:()=>Ah,rating:()=>kh,rel:()=>jh,relationship:()=>Eu,replies:()=>Yl,result:()=>Zl,startIndex:()=>Nh,startTime:()=>Ph,subject:()=>uh,summary:()=>Oh,tag:()=>rh,tags:()=>nh,target:()=>ih,to:()=>ah,totalItems:()=>Ch,units:()=>Dh,updated:()=>Lh,upstreamDuplicates:()=>$h,url:()=>ch,verb:()=>Uh,width:()=>Mh});var x=i(981);function E(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}function T(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function R(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})}Object.create;Object.create;var A=i(955);class InruptClientError extends Error{}const k=new URL("about:blank");function j(e,t){if(void 0!==e)try{return new URL(e,t)}catch{}}class ClientHttpError extends InruptClientError{constructor(e,t,r,n){if(super(r,n),e.status>=200&&e.status<400)throw new InruptClientError(`A ClientHttpError cannot be built from a success response, got ${e.status} ${e.statusText}`);this.errorResponse=Object.freeze({status:e.status,statusText:e.statusText,headers:e.headers,url:e.url,body:t,ok:!1}),this.details=function(e){let t,r,n,i,s;if("application/problem+json"===e.headers.get("Content-Type"))try{const o=JSON.parse(e.body),a=j(o.type,e.url);void 0!==a&&(t=a),"string"==typeof o.title&&(r=o.title),"number"==typeof o.status&&(n=o.status),"string"==typeof o.detail&&(i=o.detail);const c=j(o.instance,e.url);void 0!==c&&(s=c)}catch{}return Object.freeze({type:t??k,title:r??e.statusText,status:n??e.status,detail:i,instance:s})}(this.errorResponse)}get response(){return this.errorResponse}get problemDetails(){return this.details}}function N(e){return"object"==typeof e&&"object"==typeof e.internal_resourceInfo}function P(e){const t=e;return"object"==typeof t&&"object"==typeof t.internal_resourceInfo&&"object"==typeof t.internal_resourceInfo.linkedResources}function O(e){const t=e;return"object"==typeof t.internal_changeLog&&Array.isArray(t.internal_changeLog.additions)&&Array.isArray(t.internal_changeLog.deletions)}class SolidClientError extends Error{}function C(e){return"string"==typeof e?e:e.value}function D(e,t={}){const r=new URL(e);return r.pathname=r.pathname.replace(/\/\/+/g,"/"),!1===t.trailingSlash&&"/"===r.pathname.slice(-1)&&(r.pathname=r.pathname.slice(0,r.pathname.length-1)),!0===t.trailingSlash&&"/"!==r.pathname.slice(-1)&&(r.pathname=`${r.pathname}/`),r.href}function L(e){var t,n,i,s,o;const a=null!==(n=null===(t=e.headers.get("Content-Type"))||void 0===t?void 0:t.split(";"))&&void 0!==n?n:[],c=a.length>0&&["text/turtle","application/ld+json"].includes(a[0]),u={sourceIri:e.url,isRawData:!c,contentLocation:null!==(i=e.headers.get("Content-Location"))&&void 0!==i?i:void 0,contentType:null!==(s=e.headers.get("Content-Type"))&&void 0!==s?s:void 0,linkedResources:{},location:null!==(o=e.headers.get("Location"))&&void 0!==o?o:void 0},l=e.headers.get("Link");if(l){const e=r().parse(l),t=e.get("rel","acl");1===t.length&&(u.aclUrl=new URL(t[0].uri,u.sourceIri).href),u.linkedResources=e.refs.reduce((e,t)=>{var r,n;return null!==(r=e[n=t.rel])&&void 0!==r||(e[n]=[]),e[t.rel].push(new URL(t.uri,u.sourceIri).href),e},u.linkedResources)}const h=e.headers.get("WAC-Allow");return h&&(u.permissions=function(e){function t(e){const t=e.split(" ");return t.includes("write")?{read:t.includes("read"),append:!0,write:!0,control:t.includes("control")}:{read:t.includes("read"),append:t.includes("append"),write:!1,control:t.includes("control")}}function r(e,t){const r=e.split(",").map(e=>e.split("=")).filter(e=>2===e.length&&e[0].trim()===t);if(1!==r.length)return"";const n=r[0][1].trim();return'"'!==n.charAt(0)||'"'!==n.charAt(n.length-1)?"":n.substring(1,n.length-1)}return{user:t(r(e,"user")),public:t(r(e,"public"))}}(h)),u}function $(e){return!e.ok}async function U(e,t){var r,n;return M(await(null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch)(D(e),{method:"HEAD"}),{ignoreAuthenticationErrors:null!==(n=null==t?void 0:t.ignoreAuthenticationErrors)&&void 0!==n&&n})}function M(e,t={ignoreAuthenticationErrors:!1}){if($(e)&&(!function(e){return 401===e.status||403===e.status}(e)||!t.ignoreAuthenticationErrors))throw new FetchError(`Fetching the metadata of the Resource at [${e.url}] failed: [${e.status}] [${e.statusText}].`,e);return{internal_resourceInfo:L(e)}}function F(e){return(N(e)?B(e):C(e)).endsWith("/")}function B(e){return N(e)?e.internal_resourceInfo.sourceIri:null}r();const z=B;function q(e){return e.internal_resourceInfo.linkedResources}class FetchError extends SolidClientError{constructor(e,t,r){super(e),this.response=t,this.httpError=new ClientHttpError(t,"string"==typeof r?r:"",e)}get statusCode(){return this.response.status}get statusText(){return this.response.statusText}get problemDetails(){return this.httpError.problemDetails}}t(),p();const K="http://www.w3.org/1999/02/22-rdf-syntax-ns#",W="http://www.w3.org/2001/XMLSchema#",H="http://www.w3.org/2000/10/swap/",Q={xsd:{decimal:`${W}decimal`,boolean:`${W}boolean`,dateTime:`${W}dateTime`,double:`${W}double`,integer:`${W}integer`,string:`${W}string`},rdf:{type:`${K}type`,nil:`${K}nil`,first:`${K}first`,rest:`${K}rest`,langString:`${K}langString`,dirLangString:`${K}dirLangString`,reifies:`${K}reifies`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${H}reify#forSome`,forAll:`${H}reify#forAll`},log:{implies:`${H}log#implies`,isImpliedBy:`${H}log#isImpliedBy`}},{rdf:J,xsd:G}=Q;let V,X=0;const Y="<>",Z={namedNode:ne,blankNode:ie,variable:oe,literal:se,defaultGraph:function(){return V},quad:ae,triple:ae,fromTerm:ce,fromQuad:ue},ee=Z;class Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof Term?this.id===e.id&&this.termType===e.termType:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class NamedNode extends Term{constructor(e){""!==e?super(e):(super(Y),Object.defineProperty(this,"value",{value:""}))}get termType(){return"NamedNode"}}class Literal extends Term{constructor(e){super(e)}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;const r=e.lastIndexOf("--");return t<e.length&&"@"===e[t++]?(r>t?e.substr(0,r):e).substr(t).toLowerCase():""}get direction(){const e=this.id,t=e.lastIndexOf('"'),r="@"===e[t+1]?e.lastIndexOf("--"):-1;return r>t&&r+2<e.length?e.substr(r+2).toLowerCase():""}get datatype(){return new NamedNode(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?G.string:e.indexOf("--",t)>0?J.dirLangString:J.langString}equals(e){return e instanceof Literal?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&(this.direction===e.direction||""===this.direction&&!e.direction)&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,direction:this.direction,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class BlankNode extends Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Variable extends Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}function te(e,t,r){if(t=t||Z,!e)return t.defaultGraph();switch(e[0]){case"?":return t.variable(e.substr(1));case"_":return t.blankNode(e.substr(2));case'"':if(t===Z)return new Literal(e);if('"'===e[e.length-1])return t.literal(e.substr(1,e.length-2));const n=e.lastIndexOf('"',e.length-1);let i;if("@"===e[n+1]){i=e.substr(n+2);const t=i.lastIndexOf("--");t>0&&t<i.length&&(i={language:i.substr(0,t),direction:i.substr(t+2)})}else i=t.namedNode(e.substr(n+3));return t.literal(e.substr(1,n-1),i);case"[":e=JSON.parse(e);break;case"<":if(e===Y)return t.namedNode("");default:if(!r||!Array.isArray(e))return t.namedNode(e)}return t.quad(te(e[0],t,!0),te(e[1],t,!0),te(e[2],t,!0),e[3]&&te(e[3],t,!0))}function re(e,t){if("string"==typeof e)return e;if(e instanceof Term&&"Quad"!==e.termType)return e.id;if(!e)return V.id;switch(e.termType){case"NamedNode":{const t=e.value;return""!==t?t:Y}case"BlankNode":return`_:${e.value}`;case"Variable":return`?${e.value}`;case"DefaultGraph":return"";case"Literal":return`"${e.value}"${e.language?`@${e.language}${e.direction?`--${e.direction}`:""}`:e.datatype&&e.datatype.value!==G.string?`^^${e.datatype.value}`:""}`;case"Quad":const r=[re(e.subject,!0),re(e.predicate,!0),re(e.object,!0)];return e.graph&&"DefaultGraph"!==e.graph.termType&&r.push(re(e.graph,!0)),t?r:JSON.stringify(r);default:throw new Error(`Unexpected termType: ${e.termType}`)}}V=new class DefaultGraph extends Term{constructor(){return super(""),V||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};class Quad extends Term{constructor(e,t,r,n){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=n||V}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 ne(e){return new NamedNode(e)}function ie(e){return new BlankNode(e||"n3-"+X++)}function se(e,t){if("string"==typeof t)return new Literal(`"${e}"@${t.toLowerCase()}`);if(void 0!==t&&!("termType"in t))return new Literal(`"${e}"@${t.language.toLowerCase()}${t.direction?`--${t.direction.toLowerCase()}`:""}`);let r=t?t.value:"";return""===r&&("boolean"==typeof e?r=G.boolean:"number"==typeof e?Number.isFinite(e)?r=Number.isInteger(e)&&Math.abs(e)<1e21?G.integer:G.double:(r=G.double,Number.isNaN(e)||(e=e>0?"INF":"-INF")):"bigint"==typeof e?r=G.integer:e instanceof Date&&!Number.isNaN(e.getTime())&&(r=G.dateTime,e=e.toISOString())),""===r||r===G.string?new Literal(`"${e}"`):new Literal(`"${e}"^^${r}`)}function oe(e){return new Variable(e)}function ae(e,t,r,n){return new Quad(e,t,r,n)}function ce(e){if(e instanceof Term)return e;switch(e.termType){case"NamedNode":return ne(e.value);case"BlankNode":return ie(e.value);case"Variable":return oe(e.value);case"DefaultGraph":return V;case"Literal":return se(e.value,e.language?e.direction?{language:e.language,direction:e.direction}:e.language:e.datatype);case"Quad":return ue(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function ue(e){if(e instanceof Quad)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return ae(ce(e.subject),ce(e.predicate),ce(e.object),ce(e.graph))}function le(e){return!!e&&"DefaultGraph"===e.termType}function he(e){return e.replace(/[.*+?^${}()|[\]\\/-]/g,"\\$&")}const de=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,fe=/^(?:(?!\.\.?(?:[/?#]|$))[^/?#]+(?:\/[^/?#]{3,})*\/?)?(?:[?#]|$)/;class BaseIRI{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!de.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!BaseIRI.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",he(e)],r=[],n=[],i=/[^/?#]*([/?#])/y;let s,o=0,a=0,c=i.lastIndex=e.length;for(;!o&&!a&&(s=i.exec(this.base));)"#"===s[1]?a=i.lastIndex-1:(t.push(he(s[0]),"(?:"),r.push(")?"),"?"!==s[1]?n.push(c=i.lastIndex):(o=c=i.lastIndex,a=this.base.indexOf("#",o),this._pathReplacements[o]="?"));for(let e=0;e<n.length;e++)this._pathReplacements[n[e]]="../".repeat(n.length-e-1);return this._pathReplacements[n[n.length-1]]="./",this._baseLength=a>0?a:this.base.length,t.push(he(this.base.substring(c,this._baseLength)),o?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...r].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const r=t[0].length;if(r===this._baseLength&&r===e.length)return"";const n=this._pathReplacements[r];if(n){const t=e.substring(r);return"?"===n||fe.test(t)?"./"===n&&/^[^?#]/.test(t)&&(t.indexOf(":")<0||!/^[^/?#]*:/.test(t))?t:n+t:e}return e.substring(r-1)}}const pe=ee.defaultGraph(),{rdf:_e,xsd:ge}=Q,{hasOwnProperty:ye}=Object.prototype,we=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,be=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,me=/[^ !#-\[\]-~\u0080-\uFFFD]/,ve=/[^ !#-\[\]-~\u0080-\uFFFD]/g,Se={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"},Ie=/["\\\u0000-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(?:^|[^\ud800-\udbff])[\udc00-\udfff]/,xe="A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD_:0-9",Ee=`${xe}\\-\\u00B7\\u0300-\\u036F\\u203F\\u2040`,Te="%[0-9A-Fa-f]{2}",Re=new RegExp(`^(?:(?:[${xe}]|${Te})(?:(?:[${Ee}.]|${Te})*(?:[${Ee}]|${Te}))?)?$`);class SerializedTerm extends Term{equals(e){return e===this}}class N3Writer{constructor(e,t){if(this._prefixRegex=/$0^/,this._hasPrefixes=!1,e&&"function"!=typeof e.write&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=void 0===t.end||!!t.end;else{let e="";this._outputStream={write(t,r,n){e+=t,n&&n()},end:t=>{t&&t(null,e)}},this._endStream=!0}if(t.version&&Ie.test(t.version))throw new Error(`Invalid version label: ${JSON.stringify(t.version)}`);this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine,this._escape=me,this._escapeAll=ve,this._characterReplacer=ke,t.version&&this._write(`VERSION "${t.version}"\n`)):(this._lineMode=!1,this._escape=we,this._escapeAll=be,this._characterReplacer=Ae,this._graph=pe,t.version&&this._write(`@version "${t.version}".\n`),this._prefixIRIs=Object.create(null),this._prefixPatterns=Object.create(null),t.baseIRI&&(this._baseIri=new BaseIRI(t.baseIRI),t.writeBase&&this._write(`@base <${t.baseIRI}>.\n`)),t.prefixes&&this.addPrefixes(t.prefixes))}get _inDefaultGraph(){return pe.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_endStatement(){null!==this._subject&&(this._write(this._inDefaultGraph?".\n":"\n}\n"),this._subject=null,this._graph=pe)}_writeQuad(e,t,r,n,i){try{n===this._graph||n.equals(this._graph)&&n.termType===this._graph.termType||(this._write((null===this._subject?"":this._inDefaultGraph?".\n":"\n}\n")+(pe.equals(n)?"":`${this._encodeIriOrBlank(n)} {\n`)),this._graph=n,this._subject=null),e===this._subject||e.equals(this._subject)?t===this._predicate||t.equals(this._predicate)?this._write(`, ${this._encodeObject(r)}`,i):this._write(`;\n ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i):this._write(`${(null===this._subject?"":".\n")+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i)}catch(e){i&&i(e)}}_writeQuadLine(e,t,r,n,i){delete this._prefixMatch,this._write(this.quadToString(e,t,r,n),i)}quadToString(e,t,r,n){return`${this._encodeSubject(e)} ${"Literal"===t.termType?this._encodeLiteral(t):this._encodeIriOrBlank(t)} ${this._encodeObject(r)}${n&&!le(n)?` ${this._encodeIriOrBlank(n)} .\n`:" .\n"}`}quadsToString(e){let t="";for(const r of e)t+=this.quadToString(r.subject,r.predicate,r.object,r.graph);return t}_encodeSubject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeIriOrBlank(e){if("NamedNode"!==e.termType)return this._lists&&ye.call(this._lists,e.value)&&(e=this.list(this._lists[e.value])),e instanceof Term?e.id:"Variable"===e.termType?`?${e.value}`:`_:${e.value}`;let t=e.value;this._baseIri&&(t=this._baseIri.toRelative(t)),this._escape.test(t)&&(t=t.replace(this._escapeAll,this._characterReplacer));const r=this._hasPrefixes?(this._prefixRegex||this._createPrefixRegex()).exec(t):null;return r?r[1]?this._prefixIRIs[r[1]]+r[2]:Re.test(t.slice(r[0].length))?t:`<${t}>`:`<${t}>`}_encodeLiteral(e){let t=e.value;this._escape.test(t)&&(t=t.replace(this._escapeAll,this._characterReplacer));const r=e.language;if(r){const n=e.direction;return`"${t}"@${r}${n?`--${n}`:""}`}if(this._lineMode){if(e.datatype.value===ge.string)return`"${t}"`}else switch(e.datatype.value){case ge.string:return`"${t}"`;case ge.boolean:if("true"===t||"false"===t)return t;break;case ge.integer:if(/^[+-]?\d+$/.test(t))return t;break;case ge.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case ge.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){switch(e.termType){case"NamedNode":return e.value===_e.type?"a":this._encodeIriOrBlank(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:r,graph:n}){const i=this._lineMode?" ":"";return`<<(${i}${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(r)}${le(n)?"":` ${this._encodeIriOrBlank(n)}`}${i})>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,r,n,i){void 0===r?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):"function"==typeof n?this._writeQuad(e,t,r,pe,n):this._writeQuad(e,t,r,n||pe,i)}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}addPrefix(e,t,r){const n={};n[e]=t,this.addPrefixes(n,r)}addPrefixes(e,t){if(!this._prefixIRIs)return t&&t();let r=!1;for(let t in e){let n=e[t];"string"!=typeof n&&(n=n.value),r=!0,this._endStatement(),this._prefixIRIs[n]=t+=":",this._prefixPatterns[n]=[he(n),he(t)],this._write(`@prefix ${t} <${n}>.\n`)}r&&(this._hasPrefixes=!0,this._prefixRegex=null),this._write(r?"\n":"",t)}_createPrefixRegex(){let e="",t="";for(const r in this._prefixPatterns){const[n,i]=this._prefixPatterns[r];e+=e?`|${n}`:n,t+=t?`|${i}`:i}return this._prefixRegex=new RegExp(`^(${e})([_a-zA-Z0-9](?:\\.?[\\-_a-zA-Z0-9])*)$|^(?:${t})`)}blank(e,t){let r,n,i=e;switch(void 0===e?i=[]:e.termType?i=[{predicate:e,object:t}]:"length"in e||(i=[e]),n=i.length){case 0:return new SerializedTerm("[]");case 1:if(r=i[0],!(r.object instanceof SerializedTerm))return new SerializedTerm(`[ ${this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)} ]`);default:let t="[";for(let s=0;s<n;s++)r=i[s],r.predicate.equals(e)?t+=`, ${this._encodeObject(r.object)}`:(t+=`${(s?";\n ":"\n ")+this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)}`,e=r.predicate);return new SerializedTerm(`${t}\n]`)}}list(e){const t=e&&e.length||0,r=new Array(t);for(let n=0;n<t;n++)r[n]=this._encodeObject(e[n]);return new SerializedTerm(`(${r.join(" ")})`)}end(e){this._endStatement(),this._write=this._blockedWrite;let t=e&&((r,n)=>{t=null,e(r,n)});if(this._endStream)try{return this._outputStream.end(t)}catch(e){}t&&t()}}function Ae(e){let t=Se[e];return void 0===t&&(1===e.length?(t=e.charCodeAt(0).toString(16),t="\\u0000".substr(0,6-t.length)+t):(t=(1024*(e.charCodeAt(0)-55296)+e.charCodeAt(1)+9216).toString(16),t="\\U00000000".substr(0,10-t.length)+t)),t}function ke(e){let t=Se[e];return void 0===t&&(t=e.charCodeAt(0).toString(16).toUpperCase(),t="\\u0000".substr(0,6-t.length)+t),t}const je=Symbol("iter"),Ne=Symbol("size");let Pe;function Oe({store:e,observer:t}){const r=e.deref();r&&r._removeObserver(t)}function Ce(e,t,r,n){const i=e&&e[t],s=i&&i[r];return!!s&&n in s}const De=/^[?_"[.<]/;function Le(e){if("string"==typeof e){const t=e.charCodeAt(0);return 60!==t&&46!==t||"<>"===e?e:`<${e}>`}const t=re(e);return t.charCodeAt(0)>=97||!e?t:"Quad"===e.termType?JSON.stringify($e(e)):"NamedNode"===e.termType&&De.test(e.value)?`<${e.value}>`:t}function $e(e){const t=[Ue(e.subject),Ue(e.predicate),Ue(e.object)];return e.graph&&!le(e.graph)&&t.push(Ue(e.graph)),t}function Ue(e){return"Quad"===e.termType?$e(e):Le(e)}class N3EntityIndex{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||ee}_termFromId(e){if("<"===e[0])return this._factory.namedNode(e.substring(1,e.length-1));if("."===e[0]){const t=this._entities,r=e.split(".");return this._factory.quad(this._termFromId(t[r[1]]),this._termFromId(t[r[2]]),this._termFromId(t[r[3]]),r[4]&&this._termFromId(t[r[4]]))}return te(e,this._factory)}_termToNumericId(e){if("Quad"===e.termType){const t=this._termToNumericId(e.subject),r=this._termToNumericId(e.predicate),n=this._termToNumericId(e.object);let i;return t&&r&&n&&(le(e.graph)||(i=this._termToNumericId(e.graph)))&&this._ids[i?`.${t}.${r}.${n}.${i}`:`.${t}.${r}.${n}`]}return"string"==typeof e?this._stringToNumericId(e):this._ids[Le(e)]}_stringToNumericId(e){const t=this._ids[e],r=t?this._entities[t].charCodeAt(0):e.charCodeAt(0);return 60!==r&&46!==r||"<>"===e?t:this._ids[`<${e}>`]}_termToNewNumericId(e){if("string"==typeof e)return this._stringToNumericId(e)||this._addEntity(Le(e));const t=e&&"Quad"===e.termType?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${le(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:Le(e);return this._ids[t]||this._addEntity(t)}_addEntity(e){return this._ids[this._entities[++this._id]=e]=this._id}createBlankNode(e){let t,r;if(e)for(t=e=`_:${e}`,r=1;this._ids[t];)t=e+r++;else do{t="_:b"+this._blankNodeIndex++}while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}function Me(e){return e instanceof N3Store?e._size:null}class N3Store{constructor(e,t){this._size=0,this._graphs=Object.create(null),this._graphCount=0,this._observers=null,t||!e||e[0]||"function"==typeof e.match||(t=e,e=null),t=t||{},this._factory=t.factory||ee,this._matchSemantics=ze(t.matchSemantics),this._entityIndex=t.entityIndex||new N3EntityIndex({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addAll(e)}get size(){return null===this._size&&(this._size=this.countQuads()),this._size}_addToIndex(e,t,r,n){let i=e[t];i||(e[t]=i={[Ne]:0},e[Ne]++);let s=i[r];s||(i[r]=s={[Ne]:0},i[Ne]++);const o=n in s;return o||(s[n]=null,s[Ne]++),!o}_removeFromIndex(e,t,r,n){const i=e[t],s=i[r];delete s[n],0===--s[Ne]&&(delete i[r],0===--i[Ne]&&(delete e[t],e[Ne]--))}*_findInIndex(e,t,r,n,i,s,o,a){const c=this._entities,u=this._termFromId(c[a]),l={subject:null,predicate:null,object:null};if(n){const a=e[t],h=a&&a[r];if(!h||!(n in h))return;return l[i]=this._termFromId(c[t]),l[s]=this._termFromId(c[r]),l[o]=this._termFromId(c[n]),void(yield this._factory.quad(l.subject,l.predicate,l.object,u))}if(t&&!(t in e))return;const h=t?null:Object.keys(e);for(let n=0,a=t||h[0];a;a=h&&h[++n]){const t=e[a];if(!t)continue;if(l[i]=this._termFromId(c[a]),r&&!(r in t))return;const n=r?null:Object.keys(t);for(let e=0,i=r||n[0];i;i=n&&n[++e]){const e=t[i];if(!e)continue;l[s]=this._termFromId(c[i]);const r=Object.keys(e);for(let e=0;e<r.length;e++)l[o]=this._termFromId(c[r[e]]),yield this._factory.quad(l.subject,l.predicate,l.object,u)}}}_loop(e,t){for(const r in e)t(r)}_loopByKey0(e,t,r){let n,i;if(n=e[t])for(i in n)r(i)}_loopByKey1(e,t,r){let n,i;for(n in e)i=e[n],i[t]&&r(n)}_loopBy2Keys(e,t,r,n){let i,s,o;if((i=e[t])&&(s=i[r]))for(o in s)n(o)}_loopByKey0Deep(e,t,r){let n,i,s,o;if(n=e[t])for(s in n)for(o in i=n[s],i)r(o)}_countInIndex(e,t,r,n){let i,s,o=0;if(t){if(!(i=e[t]))return 0;if(r)return(s=i[r])?n?n in s?1:0:s[Ne]:0;const a=Object.keys(i);for(let e=0;e<a.length;e++)o+=i[a[e]][Ne];return o}const a=Object.keys(e);for(let t=0;t<a.length;t++){i=e[a[t]];const r=Object.keys(i);for(let e=0;e<r.length;e++)o+=i[r[e]][Ne]}return o}_getGraphs(e){return"number"!=typeof(e=""===e?1:e&&(this._termToNumericId(e)||-1))?this._graphs:{[e]:this._graphs[e]}}_addObserver(e){const t=new WeakRef(e);return(Pe||(Pe=new FinalizationRegistry(Oe))).register(e,{store:new WeakRef(this),observer:t},t),(this._observers||(this._observers=new Set)).add(t),t}_removeObserver(e){Pe.unregister(e),this._observers&&(this._observers.delete(e),0===this._observers.size&&(this._observers=null))}_notifyObservers(e,t,r,n,i){for(const s of this._observers){const o=s.deref();o?o._onParentMutation(e,t,r,n,i):this._removeObserver(s)}}_uniqueEntities(e){const t=Object.create(null);return r=>{r in t||(t[r]=!0,e(this._termFromId(this._entities[r],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,r,n){return t||(n=e.graph,r=e.object,t=e.predicate,e=e.subject),n=n?this._termToNewNumericId(n):1,e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),r=this._termToNewNumericId(r),this._addQuad(e,t,r,n)}_addQuad(e,t,r,n){let i=this._graphs[n];if(i||(i=this._graphs[n]={subjects:{[Ne]:0},predicates:{[Ne]:0},objects:{[Ne]:0}},Object.freeze(i),this._graphCount++),null!==this._observers){if(Ce(i.subjects,e,t,r))return!1;this._notifyObservers(e,t,r,n,!0)}return!!this._addToIndex(i.subjects,e,t,r)&&(this._addToIndex(i.predicates,t,r,e),this._addToIndex(i.objects,r,e,t),null!==this._size&&this._size++,!0)}_addFromIndex(e,t=null){for(const r in e){const n=e[r].subjects,i=t&&t[r],s=i?i.subjects:null;for(const e in n){const t=Number(e),i=n[e],o=s&&s[e];for(const e in i){const n=Number(e),s=i[e],a=o&&o[e];for(const e in s)a&&e in a||this._addQuad(t,n,Number(e),Number(r))}}}}_addIntersectionFromIndex(e,t){for(const r in e){const n=t[r];if(n){let t=e[r].subjects,i=n.subjects;i[Ne]<t[Ne]&&([t,i]=[i,t]);for(const e in t){let n=t[e],s=i[e];if(s){s[Ne]<n[Ne]&&([n,s]=[s,n]);for(const t in n){let i=n[t],o=s[t];if(o){o[Ne]<i[Ne]&&([i,o]=[o,i]);for(const n in i)n in o&&this._addQuad(Number(e),Number(t),Number(n),Number(r))}}}}}}}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}delete(e){return this.removeQuad(e),this}has(e,t,r,n){if(e&&e.subject&&null==t&&null==r&&null==n&&({subject:e,predicate:t,object:r,graph:n}=e),e&&t&&r&&null!=n){const i=this._termToNumericId(e),s=this._termToNumericId(t),o=this._termToNumericId(r),a=""===n||le(n)?1:this._termToNumericId(n),c=a&&this._graphs[a];return!!i&&!!s&&!!o&&!!c&&Ce(c.subjects,i,s,o)}return!this.readQuads(e,t,r,n).next().done}import(e){return e.on("data",e=>{this.addQuad(e)}),e}removeQuad(e,t,r,n){return t||({subject:e,predicate:t,object:r,graph:n}=e),n=n?this._termToNumericId(n):1,!!((e=e&&this._termToNumericId(e))&&(t=t&&this._termToNumericId(t))&&(r=r&&this._termToNumericId(r)))&&this._removeQuad(e,t,r,n)}_removeQuad(e,t,r,n){const i=this._graphs,s=i[n];return!(!s||!Ce(s.subjects,e,t,r))&&(null!==this._observers&&this._notifyObservers(e,t,r,n,!1),this._removeFromIndex(s.subjects,e,t,r),this._removeFromIndex(s.predicates,t,r,e),this._removeFromIndex(s.objects,r,e,t),null!==this._size&&this._size--,0===s.subjects[Ne]&&(delete i[n],this._graphCount--),!0)}removeQuads(e){for(let t=0;t<e.length;t++)this.removeQuad(e[t])}remove(e){return e.on("data",e=>{this.removeQuad(e)}),e}removeMatches(e,t,r,n){const i=new(p().Readable)({objectMode:!0}),s=this.readQuads(e,t,r,n);return i._read=e=>{for(;--e>=0;){const{done:e,value:t}=s.next();if(e)return void i.push(null);i.push(t)}},this.remove(i)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,r,n){return[...this.readQuads(e,t,r,n)]}*readQuads(e,t,r,n){const i=this._getGraphs(n);let s,o,a,c;if(!(e&&!(o=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(const e in i)(s=i[e])&&(o?c?yield*this._findInIndex(s.objects,c,o,a,"object","subject","predicate",e):yield*this._findInIndex(s.subjects,o,a,null,"subject","predicate","object",e):a?yield*this._findInIndex(s.predicates,a,c,null,"predicate","object","subject",e):c?yield*this._findInIndex(s.objects,c,null,null,"object","subject","predicate",e):yield*this._findInIndex(s.subjects,null,null,null,"subject","predicate","object",e))}match(e,t,r,n,i=null){return new DatasetCoreAndReadableStream(this,e,t,r,n,{entityIndex:this._entityIndex,matchSemantics:i&&void 0!==i.matchSemantics?i.matchSemantics:this._matchSemantics})}countQuads(e,t,r,n){const i=this._getGraphs(n);let s,o,a,c,u=0;if(e&&!(o=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r)))return 0;for(const n in i)(s=i[n])&&(u+=e?r?this._countInIndex(s.objects,c,o,a):this._countInIndex(s.subjects,o,a,c):t?this._countInIndex(s.predicates,a,c,o):r?this._countInIndex(s.objects,c,o,a):this._countInIndex(s.subjects));return u}forEach(e,t,r,n,i){this.some(t=>(e(t,this),!1),t,r,n,i)}every(e,t,r,n,i){return!this.some(t=>!e(t,this),t,r,n,i)}some(e,t,r,n,i){for(const s of this.readQuads(t,r,n,i))if(e(s,this))return!0;return!1}getSubjects(e,t,r){const n=[];return this.forSubjects(e=>{n.push(e)},e,t,r),n}forSubjects(e,t,r,n){const i=this._getGraphs(n);let s,o,a;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(s=i[n])&&(o?a?this._loopBy2Keys(s.predicates,o,a,e):this._loopByKey1(s.subjects,o,e):a?this._loopByKey0(s.objects,a,e):this._loop(s.subjects,e))}getPredicates(e,t,r){const n=[];return this.forPredicates(e=>{n.push(e)},e,t,r),n}forPredicates(e,t,r,n){const i=this._getGraphs(n);let s,o,a;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(s=i[n])&&(o?a?this._loopBy2Keys(s.objects,a,o,e):this._loopByKey0(s.subjects,o,e):a?this._loopByKey1(s.predicates,a,e):this._loop(s.predicates,e))}getObjects(e,t,r){const n=[];return this.forObjects(e=>{n.push(e)},e,t,r),n}forObjects(e,t,r,n){const i=this._getGraphs(n);let s,o,a;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(s=i[n])&&(o?a?this._loopBy2Keys(s.subjects,o,a,e):this._loopByKey0Deep(s.subjects,o,e):a?this._loopByKey0(s.predicates,a,e):this._loop(s.objects,e))}getGraphs(e,t,r){const n=[];return this.forGraphs(e=>{n.push(e)},e,t,r),n}forGraphs(e,t,r,n){for(const i in this._graphs)this.some(t=>(e(t.graph),!0),t,r,n,this._termFromId(this._entities[i]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1,allowExtraArcs:r=!1}={}){const n=Object.create(null),i=t?()=>!0:(e,t)=>{throw new Error(`${e.value} ${t}`)},s=this.getQuads(null,Q.rdf.rest,Q.rdf.nil,null),o=[];return s.forEach(t=>{const s=[];let a,c,u=!1,l=!1;const h=t.graph,d=[];let f=t.subject;for(;f&&!u;){const t=this.getQuads(null,null,f,null),n=this.getQuads(f,null,null,null);let o,p=null,_=null,g=null;for(let s=0;s<n.length&&!u;s++)o=n[s],o.graph.equals(h)?a?u=i(f,"has non-list arcs out"):o.predicate.value===Q.rdf.first?(p?u=i(f,"has multiple rdf:first arcs"):p=o,e&&p===o&&d.push(o)):o.predicate.value===Q.rdf.rest?(_?u=i(f,"has multiple rdf:rest arcs"):_=o,e&&_===o&&d.push(o)):t.length?r?l=!0:u=i(f,`has non-list arc ${o.predicate.value}`):(a=o,c="subject"):u=i(f,"not confined to single graph");for(let e=0;e<t.length&&!u;++e)o=t[e],a?u=i(f,"can't have coreferences"):o.predicate.value===Q.rdf.rest?g?u=i(f,"has incoming rdf:rest arcs"):g=o:(a=o,c="object");p?s.push(p.object):u=i(f,"has no list head"),f=g&&g.subject}if(u)e=!1;else if(s.reverse(),a&&(n[a[c].value]=s),e&&!l)for(let e=0;e<d.length;e++)o.push(d[e])}),e&&this.removeQuads(o),n}addAll(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),Array.isArray(e))this.addQuads(e);else if(e instanceof N3Store&&e._entityIndex===this._entityIndex)this._addFromIndex(e._graphs);else for(const t of e)this.add(t);return this}contains(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return!0;if(!(e instanceof N3Store)||this._entityIndex!==e._entityIndex){const t=Me(e),r=this._size;return!(null!==t&&null!==r&&t>r)&&e.every(e=>this.has(e))}const t=this._graphs,r=e._graphs;let n,i,s,o,a,c;for(const e in r){if(!(n=t[e]))return!1;if(n=n.subjects,(i=r[e].subjects)[Ne]>n[Ne])return!1;for(const e in i){if(!(s=n[e])||(o=i[e])[Ne]>s[Ne])return!1;for(const e in o){if(!(a=s[e])||(c=o[e])[Ne]>a[Ne])return!1;for(const e in c)if(!(e in a))return!1}}}return!0}deleteMatches(e,t,r,n){for(const i of this.match(e,t,r,n,{matchSemantics:"lazy"}))this.removeQuad(i);return this}difference(e){if(e&&e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return new N3Store({entityIndex:this._entityIndex});if(e instanceof N3Store&&e._entityIndex===this._entityIndex){const t=new N3Store({entityIndex:this._entityIndex});return t._addFromIndex(this._graphs,e._graphs),t}return this.filter(t=>!e.has(t))}equals(e){return e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new N3Store({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this){const e=new N3Store({entityIndex:this._entityIndex});return e._addFromIndex(this._graphs),e}if(e instanceof N3Store&&this._entityIndex===e._entityIndex){const t=new N3Store({entityIndex:this._entityIndex});return 0!==this._size&&0!==e._size&&(e._graphCount<this._graphCount?t._addIntersectionFromIndex(e._graphs,this._graphs):t._addIntersectionFromIndex(this._graphs,e._graphs)),t}const t=Me(e),r=this._size;if(null!==t&&null!==r&&t<r&&"function"==typeof e[Symbol.iterator]&&e._factory===ee&&e._entityIndex._factory===ee){const t=new N3Store({entityIndex:this._entityIndex});for(const r of e)this.has(r)&&t.add(r);return t}return this.filter(t=>e.has(t))}map(e){const t=new N3Store({entityIndex:this._entityIndex});for(const r of this)t.add(e(r,this));return t}reduce(e,t){const r=this.readQuads();let n=void 0===t?r.next().value:t;for(const t of r)n=e(n,t,this);return n}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match(null,null,null,null,{matchSemantics:"lazy"})}toString(){return(new N3Writer).quadsToString(this)}union(e){const t=new N3Store({entityIndex:this._entityIndex});return t._addFromIndex(this._graphs),t.addAll(e),t}[Symbol.iterator](){return this.readQuads()}}function Fe(e,t,r=0){const n=t[r];if(n&&!(n in e))return!1;let i=!1,s=0;for(const o in n?{[n]:e[n]}:e){const n=2===r?null:Fe(e[o],t,r+1);!1!==n&&(i=i||Object.create(null),i[o]=n,s++)}return i&&(i[Ne]=s),i}function Be(e,t,r,n,i){const s={store:e,ids:[]},o=t&&e._termToNumericId(t),a=r&&e._termToNumericId(r),c=n&&e._termToNumericId(n);let u,l,h,d,f;!c||!o&&a?!o&&a?(u="predicates",[l,h,d]=[a,c,o],f=[1,2,0]):(u="subjects",[l,h,d]=[o,a,c],f=[0,1,2]):(u="objects",[l,h,d]=[c,o,a],f=[2,0,1]);const p=e._getGraphs(i),_=[];for(const e in p){const t=p[e][u],r=Number(e);for(const e in l?{[l]:t[l]}:t){const n=t[e];if(n){_[f[0]]=Number(e);for(const e in h?{[h]:n[h]}:n){const t=n[e];if(t){_[f[1]]=Number(e);for(const e in d?d in t?{[d]:null}:{}:t)_[f[2]]=Number(e),s.ids.push(_[0],_[1],_[2],r)}}}}}return s}function ze(e="lazy"){if("lazy"!==e&&"snapshot"!==e&&"forwarded"!==e)throw new Error(`Unknown matchSemantics: ${e}`);if("lazy"!==e&&("function"!=typeof WeakRef||"function"!=typeof FinalizationRegistry))throw new Error("Non-lazy matchSemantics requires WeakRef and FinalizationRegistry support");return e}function qe(e,t){const r=new Array(4);for(let n=0;n<4;n++){const i=e[n],s=t[n];if(null==i)r[n]=s;else{if(null!=s&&Le(i)!==Le(s))return!1;r[n]=i}}return r}class DatasetCoreAndReadableStream extends p().Readable{constructor(e,t,r,n,i,s){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:r,object:n,graph:i,options:s});const o=this._semantics=ze(s.matchSemantics);s.matchesNothing&&(this._matchesNothing=!0,this._filtered=new N3Store({factory:e._factory,entityIndex:s.entityIndex})),"lazy"!==o&&(this._readers=null,this._subjectId=this._predicateId=this._objectId=this._graphId=void 0,this._matchesNothing||(this._observer=e._addObserver(this)))}_matchesPattern(e,t,r,n){const{subject:i,predicate:s,object:o,graph:a,n3Store:c}=this;return(!i||e===(this._subjectId||(this._subjectId=c._termToNumericId(i))))&&((!s||t===(this._predicateId||(this._predicateId=c._termToNumericId(s))))&&((!o||r===(this._objectId||(this._objectId=c._termToNumericId(o))))&&(null==a||n===(this._graphId||(this._graphId=""===a||le(a)?1:c._termToNumericId(a))))))}_matchesQuad(e){const{subject:t,predicate:r,object:n,graph:i}=this;return!(this._matchesNothing||null!=t&&Le(t)!==Le(e.subject)||null!=r&&Le(r)!==Le(e.predicate)||null!=n&&Le(n)!==Le(e.object)||null!=i&&Le(i)!==Le(e.graph))}_assertMatchesPattern(e){if(!this._matchesQuad(e))throw new Error("Quad does not match the forwarded view pattern")}_sourceIterator(){return this._filtered?this._filtered[Symbol.iterator]():this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}_freezeCurrentIterators(){this._readers&&(this._readers.snapshot=this._filtered?Be(this._filtered):Be(this.n3Store,this.subject,this.predicate,this.object,this.graph),this._readers=null)}_onParentMutation(e,t,r,n,i){this._matchesPattern(e,t,r,n)&&(this._freezeCurrentIterators(),"forwarded"!==this._semantics?this._filtered=this.filtered:this._filtered&&(i?this._filtered._addQuad(e,t,r,n):this._filtered._removeQuad(e,t,r,n)))}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:r,predicate:n,subject:i}=this;"lazy"!==this._semantics&&this._freezeCurrentIterators();const s=this._filtered=new N3Store({factory:e._factory,entityIndex:this.options.entityIndex});let o,a,c;if("snapshot"===this._semantics&&this._detachObserver(),i&&!(o=s._termToNumericId(i))||n&&!(a=s._termToNumericId(n))||r&&!(c=s._termToNumericId(r)))return s;const u=e._getGraphs(t);for(const e in u){let t,r,n,i;(i=u[e])&&(!o&&a?(r=Fe(i.predicates,[a,c,o]))&&(t=Fe(i.subjects,[o,a,c]),n=Fe(i.objects,[c,o,a])):c?(n=Fe(i.objects,[c,o,a]))&&(t=Fe(i.subjects,[o,a,c]),r=Fe(i.predicates,[a,c,o])):(t=Fe(i.subjects,[o,a,c]))&&(r=Fe(i.predicates,[a,c,o]),n=Fe(i.objects,[c,o,a])),t&&(s._graphs[e]={subjects:t,predicates:r,objects:n},s._graphCount++))}s._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[je]&&(this[je]=this[Symbol.iterator]());const t=this[je];for(;--e>=0;){const{done:e,value:r}=t.next();if(e)return void this.push(null);this.push(r)}}_destroy(e,t){this[je]&&(this[je].return(),this[je]=null),t(e)}_detachObserver(){this._observer&&(this.n3Store._removeObserver(this._observer),this._observer=null)}_detach(){return this._filtered=this.filtered,this._detachObserver(),"lazy"===this._semantics&&(this._readers=null),this._semantics="snapshot",this}addAll(e){if("forwarded"===this._semantics){for(const t of e)this._assertMatchesPattern(t),this.n3Store.addQuad(t);return this}return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,r,n){if("forwarded"===this._semantics){if(this._matchesNothing)throw new Error("Cannot delete from a conflicting forwarded view pattern");const i=qe([this.subject,this.predicate,this.object,this.graph],[e,t,r,n]);if(!i)throw new Error("Deletion pattern does not match the forwarded view pattern");return this.n3Store.deleteMatches(...i),this}return this.filtered.deleteMatches(e,t,r,n)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,r,n,i){return this.filtered.every("forwarded"===this._semantics?t=>e(t,this):e,t,r,n,i)}filter(e){return this.filtered.filter("forwarded"===this._semantics?t=>e(t,this):e)}forEach(e,t,r,n,i){return this.filtered.forEach("forwarded"===this._semantics?t=>e(t,this):e,t,r,n,i)}import(e){if("forwarded"!==this._semantics)return this.filtered.import(e);const t=this;return e.on("data",function r(n){try{t._assertMatchesPattern(n),t.n3Store.addQuad(n)}catch(t){e.removeListener("data",r),"function"==typeof e.destroy?e.destroy(t):e.emit("error",t)}}),e}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map("forwarded"===this._semantics?t=>e(t,this):e)}some(e,t,r,n,i){return this.filtered.some("forwarded"===this._semantics?t=>e(t,this):e,t,r,n,i)}toCanonical(){return this.filtered.toCanonical()}toStream(){return"lazy"!==this._semantics?p().Readable.from(this[Symbol.iterator]()):this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph,{matchSemantics:"lazy"})}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph,{matchSemantics:"lazy"}).addAll(e)}toArray(){return"lazy"!==this._semantics?[...this]:this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce("forwarded"===this._semantics?(t,r)=>e(t,r,this):e,t)}toString(){return(new N3Writer).quadsToString(this)}add(e){return"forwarded"===this._semantics?(this._assertMatchesPattern(e),this.n3Store.addQuad(e),this):this.filtered.add(e)}delete(e){return"forwarded"===this._semantics?(this._assertMatchesPattern(e),this.n3Store.removeQuad(e),this):this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,r,n,i=null){const s=i&&i.matchSemantics;if(i&&void 0!==s&&(ze(s),s!==this._semantics))throw new Error(`Cannot override matchSemantics on a view: inherited "${this._semantics}", received "${s}"`);if("forwarded"!==this._semantics)return new DatasetCoreAndReadableStream(this.filtered,e,t,r,n,{entityIndex:this.options.entityIndex,matchSemantics:this._semantics});const o=!this._matchesNothing&&qe([this.subject,this.predicate,this.object,this.graph],[e,t,r,n]),[a,c,u,l]=o||[null,null,null,null];return new DatasetCoreAndReadableStream(this.n3Store,a,c,u,l,{entityIndex:this.options.entityIndex,matchSemantics:"forwarded",matchesNothing:!o})}[Symbol.iterator](){return"lazy"===this._semantics?this._sourceIterator():this._iterateStable()}*_iterateStable(){const e=this._readers||(this._readers={count:0,snapshot:null}),t=this._sourceIterator();let r=0;e.count++;try{for(;!e.snapshot;){const{value:n,done:i}=t.next();if(e.snapshot||i)break;r++,yield n}e.snapshot&&(yield*function*({store:e,ids:t},r){const n=e._entities;let i,s,o,a,c,u,l,h;for(let d=4*r;d<t.length;d+=4)c!==t[d]&&(i=e._termFromId(n[c=t[d]])),u!==t[d+1]&&(s=e._termFromId(n[u=t[d+1]])),l!==t[d+2]&&(o=e._termFromId(n[l=t[d+2]])),h!==t[d+3]&&(a=e._termFromId(n[h=t[d+3]])),yield e._factory.quad(i,s,o,a)}(e.snapshot,r))}finally{t.return(),0===--e.count&&(e.snapshot=null,this._readers===e&&(this._readers=null))}}}const Ke="https://inrupt.com/.well-known/sdk-local-node/",{freeze:We}=Object;function He(e){return e.substring(0,46)===Ke}function Qe(e){return e.substring(46)}function Je(e){return"string"==typeof e&&"_:"===e.substring(0,2)}function Ge(e){return e.substring(2)}function Ve(e){return`_:${e.value}`}const Xe="http://www.w3.org/2001/XMLSchema#boolean",Ye="http://www.w3.org/2001/XMLSchema#dateTime",Ze="http://www.w3.org/2001/XMLSchema#decimal",et="http://www.w3.org/2001/XMLSchema#integer",tt="http://www.w3.org/2001/XMLSchema#string",rt="http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";function nt(e){if(e.endsWith("Z"))return[e.substring(0,e.length-1),"Z"];const t=e.split("+"),r=e.split("-");return 1===t.length&&1===r.length?[t[0],void 0]:t.length>r.length?[t[0],`+${t[1]}`]:[r[0],`-${r[1]}`]}function it(e){if("Z"===e)return[0,0];const t="+"===e.charAt(0)?1:-1,[r,n]=e.substring(1).split(":");return[Number.parseInt(r,10)*t,Number.parseInt(n,10)*t]}function st(e){return ot(e)&&"NamedNode"===e.termType}function ot(e){return null!==e&&"object"==typeof e&&"string"==typeof e.termType&&"string"==typeof e.value&&"function"==typeof e.equals}function at(e){return st(e)&&He(e.value)}function ct(e){const t=C(e);if("function"!=typeof URL)return!0;try{return new URL(t),!0}catch(e){return!1}}function ut(e,t){return ee.namedNode(lt(Qe(e.value),t))}function lt(e,t){if("function"!=typeof URL)throw new Error("The URL interface is not available, so an IRI cannot be determined.");const r=new URL(t);return r.hash=e,r.href}function ht(e,t){var r;if(!["NamedNode","BlankNode"].includes(t.subject.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.subject.termType}] as their Subject node.`);const n="BlankNode"===t.subject.termType?`_:${t.subject.value}`:t.subject.value,i=null!==(r=e[n])&&void 0!==r?r:{type:"Subject",url:n,predicates:{}};return We({...e,[n]:dt(i,t)})}function dt(e,t){return We({...e,predicates:ft(e.predicates,t)})}function ft(e,t){var r;if(!["NamedNode"].includes(t.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.predicate.termType}] as their Predicate node.`);const n=t.predicate.value,i=null!==(r=e[n])&&void 0!==r?r:{};return We({...e,[n]:pt(i,t)})}function pt(e,t){var r,n,i,s,o,a,c,u;if("NamedNode"===t.object.termType){const n=We([...null!==(r=e.namedNodes)&&void 0!==r?r:[],t.object.value]);return We({...e,namedNodes:n})}if("Literal"===t.object.termType){if(t.object.datatype.value===rt){const r=t.object.language.toLowerCase(),o=We([...null!==(i=null===(n=e.langStrings)||void 0===n?void 0:n[r])&&void 0!==i?i:[],t.object.value]),a=We({...null!==(s=e.langStrings)&&void 0!==s?s:{},[r]:o});return We({...e,langStrings:a})}const r=We([...null!==(a=null===(o=e.literals)||void 0===o?void 0:o[t.object.datatype.value])&&void 0!==a?a:[],t.object.value]),u=We({...null!==(c=e.literals)&&void 0!==c?c:{},[t.object.datatype.value]:r});return We({...e,literals:u})}if("BlankNode"===t.object.termType){const r=We([...null!==(u=e.blankNodes)&&void 0!==u?u:[],Ve(t.object)]);return We({...e,blankNodes:r})}throw new Error(`Objects of type [${t.object.termType}] are not supported.`)}function _t(e,t={}){var r;const n=[],i=null!==(r=t.dataFactory)&&void 0!==r?r:ee;return Object.keys(e.graphs).forEach(r=>{const s=e.graphs[r],o="default"===r?i.defaultGraph():i.namedNode(r);Object.keys(s).forEach(e=>{const{predicates:r}=s[e],a=Je(e)?i.blankNode(Ge(e)):i.namedNode(e);n.push(...gt(r,a,o,t))})}),n}function gt(e,t,r,n={}){var i;const s=[],o=null!==(i=n.dataFactory)&&void 0!==i?i:ee;return Object.keys(e).forEach(n=>{var i,a,c,u;const l=o.namedNode(n),h=null!==(i=e[n].langStrings)&&void 0!==i?i:{},d=null!==(a=e[n].namedNodes)&&void 0!==a?a:[],f=null!==(c=e[n].literals)&&void 0!==c?c:{},p=null!==(u=e[n].blankNodes)&&void 0!==u?u:[];Object.keys(f).forEach(e=>{const n=o.namedNode(e);f[e].forEach(e=>{const i=o.literal(e,n);s.push(o.quad(t,l,i,r))})});Object.keys(h).forEach(e=>{h[e].forEach(n=>{const i=o.literal(n,e);s.push(o.quad(t,l,i,r))})}),d.forEach(e=>{const n=o.namedNode(e);s.push(o.quad(t,l,n,r))}),p.forEach(e=>{if(Je(e)){const n=o.blankNode(Ge(e));s.push(o.quad(t,l,n,r))}else{const n=o.blankNode(),i=o.quad(t,l,n,r),a=gt(e,n,r);s.push(i),s.push(...a)}})}),s}const yt="http://www.w3.org/ns/auth/acl#Authorization",wt="http://www.w3.org/ns/auth/acl#accessTo",bt="http://www.w3.org/ns/auth/acl#agent",mt="http://www.w3.org/ns/auth/acl#agentGroup",vt="http://www.w3.org/ns/auth/acl#agentClass",St="http://www.w3.org/ns/auth/acl#default",It="http://www.w3.org/ns/auth/acl#defaultForNew",xt="http://www.w3.org/ns/auth/acl#mode",Et="http://www.w3.org/ns/auth/acl#origin",Tt="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",Rt="http://www.w3.org/2000/01/rdf-schema#seeAlso",At="http://www.w3.org/ns/ldp#BasicContainer",kt="http://www.w3.org/ns/ldp#Resource",jt="http://www.w3.org/ns/ldp#contains",Nt="http://xmlns.com/foaf/0.1/Agent",Pt="http://xmlns.com/foaf/0.1/primaryTopic",Ot="http://xmlns.com/foaf/0.1/isPrimaryTopicOf",Ct="http://www.w3.org/ns/solid/acp#AccessControlResource",Dt="http://www.w3.org/ns/pim/space#storage",{xsd:Lt}=Q,$t=32,Ut=13;function Mt(e){return e===$t||e>=9&&e<=Ut||e>=160&&(160===e||5760===e||e>=8192&&e<=8202||8232===e||8233===e||8239===e||8287===e||12288===e||65279===e)}const Ft=new Uint8Array(128);for(const e of",;!^#()[]{}\"'<> \t\n\v\f\r")Ft[e.charCodeAt(0)]=1;function Bt(e,t,r){let n=e.charCodeAt(t);return 46===n&&(n=e.charCodeAt(++t)),t>=e.length?r:function(e){return e<128?1===Ft[e]:Mt(e)}(n)}const zt={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b"},qt={_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","'":"'","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},Kt=/[\x00-\x20<>\\"\{\}\|\^\`]/,Wt=new Uint8Array(128);for(let e=0;e<128;e++){const t=String.fromCharCode(e),r=t>="A"&&t<="Z"||t>="a"&&t<="z",n=r||"_"===t||"-"===t||t>="0"&&t<="9";Wt[e]=(r?1:0)|(n&&"-"!==t||":"===t?2:0)|(n?4:0)|(n||":"===t?8:0)|(t in qt?16:0)}function Ht(e,t,r){const n=e.charCodeAt(t);if(n<128)return 0!==(Wt[n]&r)?1:0;if(n>=55296&&n<=56191){const r=e.charCodeAt(t+1);return r>=56320&&r<=57343?2:0}return r>=4&&(183===n||n>=768&&n<=879||8255===n||8256===n)||n>=192&&n<=8191&&215!==n&&247!==n&&(n<768||n>=880&&894!==n)||n>=8204&&n<=8205||n>=8304&&n<=8591||n>=11264&&n<=12271||n>=12289&&n<=55295||n>=63744&&n<=64975||n>=65008&&n<=65533?1:0}function Qt(e){return e<128&&!!(16&Wt[e])}function Jt(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Gt(e,t){let r=Ht(e,t,1);for(;0!==r;){t+=r;const n=46===e.charCodeAt(t)?t+1:t,i=e.charCodeAt(n);r=i<128?4&Wt[i]?1:0:Ht(e,n,4),0!==r&&(t=n)}return t}function Vt(e,t,r){const n=Gt(e,t);if(58!==e.charCodeAt(n))return-1;const i=function(e,t){let r=t,n=2;for(;;){const i=e.charCodeAt(t);let s=i<128?0!==(Wt[i]&n)?1:0:Ht(e,t,n);if(0===s&&37===i&&Jt(e.charCodeAt(t+1))&&Jt(e.charCodeAt(t+2))?s=3:0===s&&92===i&&Qt(e.charCodeAt(t+1))&&(s=2),0!==s)r=t+=s,n=8;else{if(46!==i||8!==n)return r;t++}}}(e,n+1);return Bt(e,i,r)?i:-1}function Xt(e){return e<=1114111&&(e<55296||e>57343)}const Yt={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_commentLine:!0,_whitespace:!0},Zt=/$0^/,er=/\S*/y;function tr(e,t,r){return e.lastIndex=r,e.exec(t)}function rr(e,t,r){return e.lastIndex=r,e.test(t)}function nr(e,t,r){return e.lastIndex=0,e.exec(`${t.slice(r)} `)}function ir(e){return e===$t||9===e||10===e||e===Ut||35===e}const sr=/^(?:prefix|base|version|graph|forsome|forall|iri|a|true|false|has|is|of|id)$/i;class N3Lexer{constructor(e){if(this._iri=/<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/y,this._unescapedIri=/<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/y,this._simpleQuotedString=/"([^"\\\r\n]*)"(?=[^"])/y,this._simpleApostropheString=/'([^'\\\r\n]*)'(?=[^'])/y,this._langcode=/@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9])/iy,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-9: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#()\[\]\{\}"'<>])/y,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#()\[\]\{\}"'<>]))/y,this._number=/[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?\d+|(?=\.?\d)\d*(?:(\.)\d+)?)(?=\.?[,;:!\^\s#()\[\]\{\}"'<>])/y,this._boolean=/(?:true|false)(?=[.,;!\^\s#()\[\]\{\}"'<>])/y,this._atKeyword=/@[a-z]+(?=[\s#<:"'.])/iy,this._keyword=/(?:PREFIX|BASE|VERSION|GRAPH)(?=[\s#<"'])/iy,this._n3Verb=/(?:has|is|of)(?=[\s#()\[\]\{\}"'<>?_+\-0-9])/y,this._n3Id=/id(?=[\s#<])/y,this._shortPredicates=/a(?=[\s#()\[\]\{\}"'<>])/y,this._commentLine=/[ \t]*#([^\n\r]*)(?:\r\n|\n|\r)([ \t]*)/y,this._whitespace=/[ \t]+/y,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const e in this)!(e in Yt)&&this[e]instanceof RegExp&&(this[e]=Zt);this._keyword=/VERSION(?=[\s#<"])/y}else this._n3Mode=!1!==e.n3;if(this._directive=null,e.directives&&0!==e.directives.length){for(const t of e.directives)if(!/^[a-z]+$/i.test(t)||sr.test(t))throw new Error(`Invalid directive name: "${t}"`);this._directive=new RegExp(`(?:${e.directives.join("|")})(?=[\\s#<])`,"iy"),this._directiveMaxLength=Math.max(...e.directives.map(e=>e.length)),this._directiveStarts=e.directives.map(e=>e[0].toLowerCase()+e[0].toUpperCase()).join("")}this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){const r=this._input;let n=0,i=this._linePosition+r.length;for(;;){for(;;){let e=r.charCodeAt(n),o=0;if(e===$t||9===e){const t=r.charCodeAt(n+1);o=t===$t||9===t?tr(this._whitespace,r,n)[0].length:1,e=r.charCodeAt(n+o)}if(35===e){const e=tr(this._commentLine,r,n);if(!e){if(n+=o,!t)return this._suspend(r,n,i);this.comments&&s(r.slice(n+1),this._line,i-(r.length-n)),n=r.length;break}{const a=e[0].length;if(!t&&n+a===r.length&&r.charCodeAt(r.length-1)===Ut)return this._suspend(r,n,i);this.comments&&s(e[1],this._line,i-(r.length-n)+o),n+=a,i=r.length-n+e[2].length,this._line++}}else{if(10!==e&&e!==Ut){n+=o;break}{if(!t&&e===Ut&&n+o+1===r.length)return this._suspend(r,n,i);o+=e===Ut&&10===r.charCodeAt(n+o+1)?2:1;let s=0;const a=r.charCodeAt(n+o);if(a===$t||9===a){const e=r.charCodeAt(n+o+1);s=e===$t||9===e?tr(this._whitespace,r,n+o)[0].length:1}n+=o+s,i=r.length-n+s,this._line++}}}if(n>=r.length)return t&&"^^"===this._previousMarker?a(this,r,n):(this._linePosition=i,t?(o("eof","","",this._line,i,0),this._input=null):this._input="");const c=this._line,u=r[n];let l="",h="",d="",f=null,p=0,_=0,g=0,y=!1,w=!1;switch(u){case"^":if("^^"===this._previousMarker)return a(this,r,n);if(r.length-n<3)break;if("^"!==r[n+1]){this._n3Mode&&(p=1,l="^");break}if(this._previousMarker="^^",n+=2,"<"!==r[n]){if(ir(r.charCodeAt(n)))continue;y=!0;break}case"<":if(f=tr(this._unescapedIri,r,n))l="IRI",h=f[1],_=f[1].length+2;else if(f=tr(this._iri,r,n)){if(h=this._unescape(f[1],zt),null===h||Kt.test(h))return a(this,r,n);l="IRI",_=f[1].length+2}else r.length-n>2&&"<"===r[n+1]&&"("===r[n+2]?(l="<<(",p=3):!this._lineMode&&r.length-n>(t?1:2)&&"<"===r[n+1]?(l="<<",p=2):this._n3Mode&&r.length-n>1&&"="===r[n+1]?(p=2,this._isImpliedBy?(l="abbreviation",h="<"):(l="inverse",h=">")):this._n3Mode&&r.length-n>1&&"-"===r[n+1]&&(l="inversePredicate",p=2);break;case">":r.length-n>1&&">"===r[n+1]&&(l=">>",p=2);break;case"_":((f=tr(this._blank,r,n))||t&&(f=nr(this._blank,r,n)))&&(l="blank",d="_",h=f[1],_=f[1].length+2);break;case'"':if(f=tr(this._simpleQuotedString,r,n))h=f[1];else if(({value:h,matchLength:p,finalLineLength:g,tripleQuoted:w}=this._parseLiteral(r,n)),null===h)return a(this,r,n);null===f&&0===p||(l="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(f=tr(this._simpleApostropheString,r,n))h=f[1];else if(({value:h,matchLength:p,finalLineLength:g,tripleQuoted:w}=this._parseLiteral(r,n)),null===h)return a(this,r,n);null===f&&0===p||(l="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(f=tr(this._variable,r,n))&&(l="var",h=f[0]);break;case"@":if("literal"===this._previousMarker&&(f=tr(this._langcode,r,n))&&"version"!==f[1]){const e=n+f[0].length;t||"-"!==r[e]||"-"===r[e+1]?(l="langcode",h=f[1]):f=null}else(f=tr(this._atKeyword,r,n))&&(l=f[0]);break;case".":if(r.length-n===1?t:r[n+1]<"0"||r[n+1]>"9"){l=".",p=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":if("-"===r[n+1]){"langcode"===this._previousMarker&&(r.startsWith("--ltr",n)?(l="dircode",h="ltr",p=5):r.startsWith("--rtl",n)&&(l="dircode",h="rtl",p=5));break}(f=tr(this._number,r,n)||t&&(f=nr(this._number,r,n)))&&(l="literal",h=f[0],d="string"==typeof f[1]?Lt.double:"string"==typeof f[2]?Lt.decimal:Lt.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":case"V":case"v":(f=tr(this._keyword,r,n))?l=f[0].toUpperCase():y=!0;break;case"f":case"t":rr(this._boolean,r,n)?(l="literal",h="t"===u?"true":"false",d=Lt.boolean,p=h.length):y=!0;break;case"a":rr(this._shortPredicates,r,n)?(l="abbreviation",h="a",p=1):y=!0;break;case"h":case"o":this._n3Mode&&(f=this._matchN3Verb(r,n,t))?l=f[0]:y=!0;break;case"i":this._n3Mode&&rr(this._n3Id,r,n)?(l="id",p=2):this._n3Mode&&(f=this._matchN3Verb(r,n,t))?l=f[0]:y=!0;break;case"=":this._n3Mode&&r.length-n>1&&(l="abbreviation",">"!==r[n+1]?(p=1,h="="):(p=2,h=">"));break;case"!":if(!this._n3Mode)break;case")":if(!t&&(r.length-n===1||r.length-n===2&&">"===r[n+1]))break;if(r.length-n>2&&">"===r[n+1]&&">"===r[n+2]){l=")>>",p=3;break}case",":case";":case"[":case"]":case"(":case"}":case"~":this._lineMode||(p=1,l=u);break;case"{":!this._lineMode&&r.length-n>=2&&("|"===r[n+1]?(l="{|",p=2):(l=u,p=1));break;case"|":r.length-n>=2&&"}"===r[n+1]&&(l="|}",p=2);break;default:y=!0}if(y){let e;if(("@prefix"===this._previousMarker||"PREFIX"===this._previousMarker)&&58===r.charCodeAt(e=Gt(r,n))&&e+1<r.length&&("#"===r[e+1]||"<"===r[e+1]||Mt(r.charCodeAt(e+1))))l="prefix",h=r.slice(n,e),p=e+1-n;else if(null!==this._directive&&this._directiveStarts.includes(u)&&((f=tr(this._directive,r,n))||t&&r.length-n<=this._directiveMaxLength&&(f=nr(this._directive,r,n))))l=f[0].toUpperCase();else if(!this._lineMode&&(e=Vt(r,n,t))>=0){const t=r.indexOf(":",n);l="prefixed",d=r.slice(n,t),h=this._unescape(r.slice(t+1,e),qt),p=e-n}}if("^^"===this._previousMarker)switch(l){case"prefixed":l="type";break;case"IRI":l="typeIRI";break;default:l=""}if(!l)return t||!r.startsWith("'''",n)&&!r.startsWith('"""',n)&&/\n|\r/.test(r.slice(n))?a(this,r,n):this._suspend(r,n,i);const b=p||f[0].length,m=i-(r.length-n);let v;g?(v={type:l,value:h,prefix:d,line:c,start:m,end:g,endLine:this._line,tripleQuoted:w},e(null,v)):w?(v={type:l,value:h,prefix:d,line:c,start:m,end:m+b,tripleQuoted:w},e(null,v)):v=o(l,h,d,c,m,_||b),this.previousToken=v,this._previousMarker="literal"!==l||"VERSION"!==this._previousMarker&&"@version"!==this._previousMarker?l:"version",n=Math.min(n+b,r.length),g&&(i=r.length-n+g)}function s(t,r,n){e(null,{type:"comment",value:t,prefix:"",line:r,start:n,end:n+t.length+1})}function o(t,r,n,i,s,o){const a={type:t,value:r,prefix:n,line:i,start:s,end:s+o};return e(null,a),a}function a(t,r,n){e(t._syntaxError(tr(er,r,n)[0]))}}_suspend(e,t,r){return this._linePosition=r-(e.length-t),this._input=e.slice(t)}_matchN3Verb(e,t,r){const n=tr(this._n3Verb,e,t);if(!n)return null;const i=e[t+n[0].length];return"-"!==i&&"_"!==i&&(i<"0"||i>"9")&&" "!==i&&"\ufeff"!==i?n:Vt(e,t,!0)>=0?null:r||Gt(e,t)!==e.length?n:null}_unescape(e,t){let r=e.indexOf("\\");if(r<0)return e;let n="",i=0;for(;r>=0&&r+1<e.length;){const s=e[r+1];let o,a=r+2;if("u"===s||"U"===s){if(a+="u"===s?4:8,a>e.length)return null;let t=0;for(let n=r+2;n<a;n++){let r=e.charCodeAt(n);if(r>=48&&r<=57)r-=48;else if(r>=65&&r<=70)r-=55;else{if(!(r>=97&&r<=102))return null;r-=87}t=16*t+r}if(!Xt(t))return null;o=String.fromCodePoint(t)}else{if(!(s in t))return null;o=t[s]}n+=e.slice(i,r)+o,i=a,r=e.indexOf("\\",i)}return n+e.slice(i)}_parseLiteral(e,t){if(e.length-t>=3){const r=e[t],n=e[t+1]===r&&e[t+2]===r?3:1;let i=r;3===n&&(i='"'===r?'"""':"'''");let s=t+Math.max(this._literalClosingPos,n);for(;(s=e.indexOf(i,s))>t;){let r=0;for(;"\\"===e[s-r-1];)r++;if(r%2==0){const r=e.substring(t+n,s),i=r.split(/\r\n|\r|\n/),o=i.length-1,a=s-t+n;if(1===n&&0!==o||3===n&&this._lineMode)break;this._line+=o;const c=0===o?0:i[i.length-1].length+n;return{value:this._unescape(r,zt),matchLength:a,finalLineLength:c,tripleQuoted:3===n}}s++}this._literalClosingPos=e.length-t-n+1}return{value:"",matchLength:0,finalLineLength:0,tripleQuoted:!1}}_tryTokenizeToEnd(e,t){let r;try{this._tokenizeToEnd((t,n)=>{try{return e(t,n)}catch(e){throw r=e}},t)}catch(t){if(t===r||!(t instanceof RangeError))throw t;e(this._syntaxError(null,`Token too long on line ${this._line}.`))}}_syntaxError(e,t=`Unexpected "${e}" on line ${this._line}.`){this._input=null;const r=new Error(t);return r.context={token:void 0,line:this._line,previousToken:this.previousToken},r}_startTokenization(){return this._line=1,this._linePosition=0,this._previousMarker=void 0,this.previousToken=void 0,this._literalClosingPos=0,this._input=void 0,this._tokenization={}}_tokenizeString(e,t){this._startTokenization(),this._input=this._readStartingBom(e),this._tryTokenizeToEnd(t,!0)}_readStartingBom(e){return e.startsWith("\ufeff")?(this._linePosition=1,e.slice(1)):e}tokenize(e,t){const r=this._startTokenization();if("string"==typeof e){if(this._input=this._readStartingBom(e),"function"!=typeof t){const e=[];let t;if(this._tryTokenizeToEnd((r,n)=>r?t=r:e.push(n),!0),t)throw t;return e}queueMicrotask(()=>{this._tokenization===r&&this._tryTokenizeToEnd(t,!0)})}else{let n,i=0;"function"==typeof e.setEncoding&&e.setEncoding("utf8"),e.on("data",e=>{if(this._tokenization===r&&null!==this._input&&0!==e.length){if("string"!=typeof e&&(n=n||new TextDecoder("utf-8",{ignoreBOM:!0}),!(e=n.decode(e,{stream:!0}))))return;void 0===this._input?this._input=this._readStartingBom(e):this._input+=e,this._input.length>=i&&(this._tryTokenizeToEnd(t,!1),i=null!==this._input&&this._input.length>1024?2*this._input.length:0)}}),e.on("end",()=>{if(this._tokenization===r&&null!==this._input){const e=n?n.decode():"";e&&(this._input="string"==typeof this._input?this._input+e:e),"string"==typeof this._input&&this._tryTokenizeToEnd(t,!0)}}),e.on("error",e=>{this._tokenization===r&&t(e)})}}}let or=0;const ar=/(^|\/)\.\.?($|[/#?])/,cr=/^[^?#]*(?:^|\/)\.\.?(?:$|[/#?])/;class N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&hr(this,e.factory);const t="string"==typeof e.format?e.format.match(/(?:^|\W)(\w*)$/)[1].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;if(this._emitCurrent=this._emit,o&&(this._createQuad=this._createQuadInDirection,this._emit=this._emitInDirection,this._emitCurrent=this._emitCurrentInDirection),(this._supportsNamedGraphs=!(r||o))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||n||i||o),this._isImpliedBy=e.isImpliedBy,this._implicitEmptyPrefix=!!e.implicitEmptyPrefix,this._emptyFormulaAsTrue=!!e.emptyFormulaAsTrue,a&&(this._resolveRelativeIRI=e=>null),this._blankNodePrefix="string"!=typeof e.blankNodePrefix?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._directives=null,e.directives){this._directives=Object.create(null);for(const t of e.directives)this._directives[`@${t.toLowerCase()}`]=this._directives[t.toUpperCase()]=t}this._lexer=e.lexer||new N3Lexer({lineMode:a,n3:o,isImpliedBy:this._isImpliedBy,directives:e.directives}),this._explicitQuantifiers=!!e.explicitQuantifiers,this._formulaScopedBlankNodes=!!e.formulaScopedBlankNodes,this._parseUnsupportedVersions=!!e.parseUnsupportedVersions,this._version=e.version;const c=e.maxTripleTermDepth;this._maxTripleTermDepth=c===1/0||Number.isInteger(c)&&c>=0?c:1024}static _resetBlankNodePrefix(){or=0}_setBase(e){if(e){const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e;const r=e.indexOf("?"),n=r<0?e:e.substr(0,r);this._basePath=e.indexOf("/")<0?e:n.substr(0,n.lastIndexOf("/")+1);const i=e;e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(\/\/[^\/?#]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1],void 0===e[2]||i.length!==this._baseRoot.length&&"?"!==i[this._baseRoot.length]||(this._basePath=`${this._baseRoot}/`),this._basePathHasDotSegments=ar.test(this._basePath)}else this._base="",this._basePath="",this._basePathHasDotSegments=!1}_enterTripleTerm(e,t,r,n){return this._tripleTermDepth>=this._maxTripleTermDepth?(this._error(`Triple terms nested deeper than ${this._maxTripleTermDepth} level${1===this._maxTripleTermDepth?"":"s"}`,n),!1):(this._tripleTermDepth++,this._saveContext(e,this._graph,t,r,null),this._graph=null,!0)}_saveContext(e,t,r,n,i){if(!this._n3Mode)return void this._contextStack.push({type:e,subject:r,predicate:n,object:i,graph:t});const s={type:e,subject:r,predicate:n,object:i,graph:t,inverse:this._inversePredicate,expectOf:this._expectOf,blankPrefix:this._prefixes._,prefixChanges:this._prefixChanges,quantifiedChanges:this._quantifiedChanges,emptyFormula:this._emptyFormula};"formula"===e&&(s.base=[this._base,this._basePath,this._baseRoot,this._baseScheme,this._basePathHasDotSegments],this._prefixChanges=[]),this._contextStack.push(s),this._inversePredicate=!1,this._expectOf=!1,this._formulaScopedBlankNodes&&"formula"!==e||(this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantifiedChanges=[]),"formula"===e&&(this._subject=null,this._emptyFormula=!0)}_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._expectOf=r.expectOf,"formula"===e&&([this._base,this._basePath,this._baseRoot,this._baseScheme,this._basePathHasDotSegments]=r.base),this._prefixChanges!==r.prefixChanges&&(ur(this._prefixes,this._prefixChanges),this._prefixChanges=r.prefixChanges),this._prefixes._=r.blankPrefix,this._quantifiedChanges!==r.quantifiedChanges&&(ur(this._quantified,this._quantifiedChanges),this._quantifiedChanges=r.quantifiedChanges),this._emptyFormula=r.emptyFormula)}_readBeforeTopContext(e){return this._version&&!this._isValidVersion(this._version)?this._error(`Detected unsupported version as media type parameter: "${this._version}"`,e):this._readInTopContext(e)}_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"VERSION":this._sparqlStyle=!0;case"@version":return this._readVersion;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return null!==this._directives&&e.type in this._directives&&null===this._graph?(this._sparqlStyle="@"!==e.type[0],this._directiveCallback(this._directives[e.type]),this._readDeclarationPunctuation):this._readSubject(e)}}_readInFormulaContext(e){switch(e.type){case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;default:return this._readSubject(e)}}_getStatementReader(){const e=this._contextStack[this._contextStack.length-1];return e&&"formula"===e.type?this._readInFormulaContext:this._readInTopContext}_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}_readList(e,t,r,n){const i=this._contextStack;return"<<"===(i.length&&i[i.length-1]).type?this._error("Unexpected list in reified triple",e):(this._saveContext("list",this._graph,t,r,n),this._subject=null,this._readListItem)}_readSubject(e){switch(this._predicate=null,"}"!==e.type&&(this._emptyFormula=!1),e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._readList(e,this.RDF_NIL,null,null);case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readInFormulaContext):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":return this._n3Mode?0===e.prefix.length?(this._literalValue=e.value,this._completeSubjectLiteral):(this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),this._getPathReader(this._readPredicateOrNamedGraph)):this._error("Unexpected literal",e);case"<<(":return this._n3Mode?this._enterTripleTerm("<<(",null,null,e)&&this._readSubject:this._error("Disallowed triple term as subject",e);case"<<":return this._enterTripleTerm("<<",null,null,e)&&this._readSubject;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;let r=!1;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case"has":return this._readPredicateAfterVerb;case"is":return this._inversePredicate=!0,this._expectOf=!0,this._readPredicateAfterVerb;case"inversePredicate":return this._inversePredicate=!0,this._readPredicateAfterVerb;case"|}":return this._subject=null,this._readAnnotationBlockPunctuation(e);case".":case"]":case"}":return null!==this._predicate||this._n3Mode?(this._subject=null,"]"===t?this._readBlankNodeTail(e):this._readPunctuation(e)):this._error(`Unexpected ${t}`,e);case";":return null!==this._predicate?this._readPredicate:this._error("Expected predicate but got ;",e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(0===e.prefix.length)return this._literalValue=e.value,this._completePredicateLiteral;this._predicate=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),r=!0;break;case"(":return this._n3Mode?this._readList(e,this._subject,this.RDF_NIL,null):this._error(`Expected entity but got ${t}`,e);case"[":return this._n3Mode?(this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead):this._error("Disallowed blank node as predicate",e);case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._graph=this._factory.blankNode(),null),this._readSubject):this._readEntity(e);case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if(void 0===(this._predicate=this._readEntity(e)))return;r=this._n3Mode}return this._validAnnotation=!0,r?this._getPathReader(this._readObject,"predicate"):this._readObject}_readPredicateAfterVerb(e){return"has"===e.type||"is"===e.type||"of"===e.type||"inversePredicate"===e.type?this._error(`Expected expression but got ${e.type}`,e):this._readPredicate(e)}_readObject(e){if(this._expectOf)return"of"!==e.type?this._error(`Expected of but got ${e.type}`,e):(this._expectOf=!1,this._readObject);switch(e.type){case"literal":if(0===e.prefix.length)return this._literalValue=e.value,this._readDataTypeOrLang;if(this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),this._n3Mode)return this._getPathReader(this._getContextEndReader());break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._readList(e,this._subject,this._predicate,this.RDF_NIL);case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readInFormulaContext):this._error("Unexpected graph",e);case"<<(":return this._enterTripleTerm("<<(",this._subject,this._predicate,e)&&this._readSubject;case"<<":return this._enterTripleTerm("<<",this._subject,this._predicate,e)&&this._readSubject;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){if("]"===e.type)return this._subject=null,this._readBlankNodeTail(e);{const t=this._contextStack;return"<<"===(t.length>1&&t[t.length-2]).type?this._error("Unexpected compound blank node expression in reified triple",e):"id"===e.type?this._readIriPropertyListId:(this._predicate=null,this._readPredicate(e))}}_readIriPropertyListId(e){const t=this._readEntity(e);if(void 0===t)return;if("NamedNode"!==t.termType)return this._error(`Expected IRI after id but got ${e.type}`,e);const r=this._subject;this._subject=t;const n=this._contextStack[this._contextStack.length-1];return n.subject===r&&(n.subject=t),n.predicate===r&&(n.predicate=t),n.object===r&&(n.object=t),this._predicate=null,this._readIriPropertyListPredicate}_readIriPropertyListPredicate(e){return";"===e.type||"]"===e.type||"."===e.type||"}"===e.type?this._error(`Expected predicate but got ${e.type}`,e):this._readPredicate(e)}_readBlankNodeTail(e){if("]"!==e.type)return this._readBlankNodePunctuation(e);null!==this._subject&&this._emitCurrent(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._getPathReader(this._readObject,"predicate"):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){if(this._n3Mode)return null!==i&&this._emit(i,this.RDF_REST,this.RDF_NIL,this._graph),this._saveContext("item",this._graph,this._subject,this._predicate,this._object),this._subject=this._object,this._predicate=null,this._getPathReader(this._readListItem);this._emit(this._subject,this._predicate,this._object,this._graph)}if(null===this._predicate){if(n=this._n3Mode?this._getPathReader(this._readPredicate):this._readPredicate,this._subject===this.RDF_NIL)return n}else if(null===this._object){if(n=this._getPathReader(this._readObject,"predicate"),this._predicate===this.RDF_NIL)return n}else if(n=this._getContextEndReader(),this._n3Mode&&(n=this._getPathReader(n)),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?(r=this._factory.blankNode(),t=this._factory.blankNode(),null===i?null===o.predicate?o.subject=r:o.object=r:this._emit(i,this.RDF_REST,r,this._graph),this._emit(r,this.RDF_FIRST,t,this._graph),this._saveContext("formula",this._graph,r,this.RDF_FIRST,this._graph=t),this._subject=null,this._readInFormulaContext):this._error("Unexpected graph",e);case"<<(":case"<<":if(!this._enterTripleTerm(e.type,null,null,e))return;n=this._readSubject;break;default:if(void 0===(t=this._readEntity(e)))return}if(null===r&&(this._subject=r=this._factory.blankNode()),"<<"!==e.type&&"<<("!==e.type||(s[s.length-1].subject=this._subject),null===i?null===o.predicate?o.subject=r:null===o.object?o.predicate=r:o.object=r:this._emit(i,this.RDF_REST,r,this._graph),null!==t){if(this._n3Mode&&("IRI"===e.type||"prefixed"===e.type||"var"===e.type||"blank"===e.type||"literal"===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,t){let r,n=!1;switch(e.type){case"type":case"typeIRI":const i=this._readEntity(e);if(void 0===i)return;if(i.value===Q.rdf.langString||i.value===Q.rdf.dirLangString)return this._error("Detected illegal (directional) languaged-tagged string with explicit datatype",e);r=this._factory.literal(this._literalValue,i),e=null;break;case"langcode":if(e.value.split("-").some(e=>e.length>8))return this._error("Detected language tag with subtag longer than 8 characters",e);r=this._factory.literal(this._literalValue,e.value),this._literalLanguage=e.value,e=null,this._literalComponent=t,n=!0;break;default:r=this._factory.literal(this._literalValue)}return{token:e,literal:r,readCb:n}}_readDirCode(e){const t=this._literalComponent,r=this._literalListItem;if("dircode"===e.type){const r=this._factory.literal(this._literalValue,{language:this._literalLanguage,direction:e.value});"subject"===t?this._subject=r:"predicate"===t?this._predicate=r:this._object=r,this._literalLanguage=void 0,e=null}if("subject"===t||"predicate"===t){const r="subject"===t?this._readPredicateOrNamedGraph:this._readObject;return this._getPathEndReader(e,r,t)||r.call(this,e)}return this._completeObjectLiteralPost(e,r)}_completeTermLiteral(e,t){const r=this._completeLiteral(e,t);if(!r)return;let n;if("subject"===t?(this._subject=r.literal,n=this._readPredicateOrNamedGraph):(this._predicate=r.literal,this._validAnnotation=!0,n=this._readObject),r.readCb)return this._literalListItem=!1,this._readDirCode;const i=this._getPathEndReader(r.token,n,t);return i||n.call(this,r.token)}_completeSubjectLiteral(e){return this._completeTermLiteral(e,"subject")}_completePredicateLiteral(e){return this._completeTermLiteral(e,"predicate")}_completeObjectLiteral(e,t){const r=this._completeLiteral(e,"object");if(r)return this._object=r.literal,r.readCb?(this._literalListItem=t,this._readDirCode):this._completeObjectLiteralPost(r.token,t)}_completeObjectLiteralPost(e,t){return!this._n3Mode||null!==e&&"!"!==e.type&&"^"!==e.type?(t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),null===e?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(e))):t?(this._saveContext("item",this._graph,this._subject,this.RDF_FIRST,this._object),this._subject=this._object,this._predicate=null,this._getPathEndReader(e,this._readListItem)):this._getPathEndReader(e,this._getContextEndReader())}_readFormulaTail(e){if("}"!==e.type)return this._readPunctuation(e);null!==this._subject&&this._emitCurrent(this._subject,this._predicate,this._object,this._graph);const t=this._graph,r=this._emptyFormula;return this._restoreContext("formula",e),r&&this._emptyFormulaAsTrue&&(this._subject===t?this._subject=this.N3_TRUE:this._predicate===t?this._predicate=this.N3_TRUE:this._object=this.N3_TRUE),null!==this._object?this._getPathReader(this._getContextEndReader(),"object"):null!==this._predicate?this._getPathReader(this._readObject,"predicate"):this._getPathReader(this._readPredicate,"subject")}_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,this._tripleTerm=null,t=this._getStatementReader(),i&&(this._inversePredicate=!1);break;case";":i&&(this._inversePredicate=!1),t=this._readPredicate;break;case",":t=this._readObject;break;case"~":case"{|":return this._readAnnotationStart(e);case"|}":return this._error("Unexpected annotation syntax closing",e);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;this._emit(n,e,t,r,i)}return t}_readBlankNodePunctuation(e){let t,r=!1;switch(e.type){case";":r=this._inversePredicate,t=this._readPredicate;break;case",":t=this._readObject;break;case"~":case"{|":return this._readAnnotationStart(e);case"|}":return this._error("Unexpected annotation syntax closing",e);default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emitCurrent(this._subject,this._predicate,this._object,this._graph),r&&(this._inversePredicate=!1),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 null!==this._prefixChanges&&this._prefixChanges.push(this._prefix,this._prefixes[this._prefix]),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)}_isValidVersion(e){return this._parseUnsupportedVersions||N3Parser.SUPPORTED_VERSIONS.includes(e)}_readVersion(e){return"literal"!==e.type?this._error("Expected literal to follow version declaration",e):""!==e.prefix||e.tripleQuoted?this._error("Version declarations must use single quotes",e):(this._versionCallback(e.value),this._isValidVersion(e.value)?this._readDeclarationPunctuation:this._error(`Detected unsupported version: "${e.value}"`,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._getStatementReader().call(this,e)):"."!==e.type?this._error("Expected declaration to end with a dot",e):this._getStatementReader()}_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)):(null!==this._quantifiedChanges&&this._quantifiedChanges.push(t.id,this._quantified[t.id]),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,t){return this._afterPath=e,this._pathPosition=t||(null===this._predicate?"subject":"object"),this._readPath}_getPathEndReader(e,t,r){if(null!==e&&"!"!==e.type&&"^"!==e.type)return null;const n=this._getPathReader(t,r);return null===e?n:n.call(this,e)}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._afterPath,r=this._contextStack,n=r.length&&r[r.length-1];if(n&&"item"===n.type){const t=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,t,this._graph)}return this._afterPath=null,this._pathPosition=null,t.call(this,e)}}_readForwardPath(e){let t,r;const n=this._factory.blankNode();if(void 0!==(r=this._readEntity(e)))return"subject"===this._pathPosition?(t=this._subject,this._subject=n):"predicate"===this._pathPosition?(t=this._predicate,this._predicate=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"subject"===this._pathPosition?(n=this._subject,this._subject=t):"predicate"===this._pathPosition?(n=this._predicate,this._predicate=t):(n=this._object,this._object=t),this._emit(t,r,n,this._graph),this._readPath}_readTripleTermTail(e){if(")>>"!==e.type)return this._error(`Expected )>> but got ${e.type}`,e);const t=this._createQuad(this._subject,this._predicate,this._object,this._graph,this._inversePredicate);this._restoreContext("<<(",e),this._tripleTermDepth--;const r=this._contextStack,n=r.length&&r[r.length-1];return n&&"list"===n.type?(this._emit(this._subject,this.RDF_FIRST,t,this._graph),this._getContextEndReader()):null===this._subject?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_readReifiedTripleTailOrReifier(e){return"~"===e.type?this._readReifier:this._readReifiedTripleTail(e)}_readReifiedTripleTail(e){if(">>"!==e.type)return this._error(`Expected >> but got ${e.type}`,e);this._tripleTerm=null;const t=this._readTripleTerm();this._restoreContext("<<",e),this._tripleTermDepth--;const r=this._contextStack,n=r.length&&r[r.length-1];return n&&"list"===n.type?(this._emit(this._subject,this.RDF_FIRST,t,this._graph),this._getContextEndReader()):null===this._subject?(this._subject=t,this._readPredicateOrReifierTripleEnd):(this._object=t,this._getContextEndReader())}_readPredicateOrReifierTripleEnd(e){return"."===e.type?(this._subject=null,this._readPunctuation(e)):this._readPredicate(e)}_readReifier(e){return">>"===e.type?this._readReifiedTripleTail(e):(this._reifier=this._readEntity(e),this._readReifiedTripleTail)}_readAnnotationStart(e){return this._emitCurrent(this._subject,this._predicate,this._object,this._graph),this._tripleTerm=null,this._readAnnotation(e)}_readAnnotation(e){switch(e.type){case"~":return this._readReifierInAnnotation;case"{|":return this._readAnnotationBlockHead(e)}switch(this._tripleTerm=null,e.type){case";":return this._inversePredicate=!1,this._readPredicate;case",":return this._readObject;default:return this._subject=null,this._getContextEndReader().call(this,e)}}_readReifierInAnnotation(e){switch(e.type){case"IRI":case"typeIRI":case"type":case"prefixed":case"blank":case"var":return this._reifier=this._readEntity(e),this._readAnnotationBlockOrReifier}return this._reifier=this._factory.blankNode(),this._readAnnotationBlockOrReifier(e)}_readAnnotationBlockOrReifier(e){return"{|"===e.type?this._readAnnotationBlockHead(e):(this._readTripleTerm(),this._readAnnotation(e))}_readAnnotationBlockHead(e){const t=this._readTripleTerm();return this._saveContext("annotation",this._graph,this._subject,this._predicate,this._object),this._contextStack[this._contextStack.length-1].tripleTerm=this._tripleTerm,this._subject=t,this._predicate=this._object=this._tripleTerm=null,this._inversePredicate=!1,this._validAnnotation=!1,this._readPredicate}_readAnnotationBlockPunctuation(e){const t=this._contextStack;if("|}"===e.type){if(!t.length||"annotation"!==t[t.length-1].type)return this._error("Unexpected annotation syntax closing",e);if(!this._validAnnotation)return this._error("Annotation block can not be empty",e);null!==this._subject&&this._emitCurrent(this._subject,this._predicate,this._object,this._graph);const{tripleTerm:r}=t[t.length-1];return this._restoreContext("annotation",e),this._tripleTerm=r,this._readAnnotation}return this._readBlankNodePunctuation(e)}_readTripleTerm(){const e=this._contextStack,t=e.length&&e[e.length-1],r=t?t.graph:void 0,n=this._reifier||this._factory.blankNode();return this._reifier=null,this._tripleTerm=this._tripleTerm||this._createQuad(this._subject,this._predicate,this._object,null,this._inversePredicate),this._emit(n,this.RDF_REIFIES,this._tripleTerm,r||this._graph||this.DEFAULTGRAPH),n}_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._readTripleTermTail;case"<<":return this._readReifiedTripleTailOrReifier;case"annotation":return this._readAnnotationBlockPunctuation}}_createQuad(e,t,r,n){return this._factory.quad(e,t,r,n||this.DEFAULTGRAPH)}_createQuadInDirection(e,t,r,n,i){return i?this._factory.quad(r,t,e,n||this.DEFAULTGRAPH):this._factory.quad(e,t,r,n||this.DEFAULTGRAPH)}_emitInDirection(e,t,r,n,i){this._callback(null,this._createQuad(e,t,r,n,i))}_emitCurrentInDirection(e,t,r,n){this._callback(null,this._createQuad(e,t,r,n,this._inversePredicate))}_emit(e,t,r,n){this._callback(null,this._factory.quad(e,t,r,n||this.DEFAULTGRAPH))}_error(e,t){const r=` on line ${t.line}.`;e.length+r.length>200&&(e=`${e.slice(0,199-r.length)}…`);const n=new Error(`${e}${r}`);n.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(n),this._callback=lr}_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"?":{const t=this._base.indexOf("?");return(t<0?this._base:this._base.substr(0,t))+e}case"/":return"/"!==e[1]?this._baseRoot+this._removeDotSegments(e):this._baseScheme?this._removeDotSegments(this._baseScheme+e):this._removeDotSegments(`:${e}`).substr(1);default:return/^[^/:]*:/.test(e)?null:this._basePathHasDotSegments||cr.test(e)?this._removeDotSegments(this._basePath+e):this._basePath+e}}_removeDotSegments(e){if(!ar.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]&&"?"!==e[i]&&"#"!==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,n){let i,s,o,a,c,u,l;t&&(t.onQuad||t.onPrefix||t.onComment||t.onVersion||t.onDirective||t.onToken||t.onTokenEnd)?(i=t.onQuad,s=t.onPrefix,o=t.onComment,a=t.onVersion,c=t.onDirective,u=t.onToken,l=t.onTokenEnd):(i=t,s=r,a=n),this._readCallback=this._readBeforeTopContext,this._contextStack=[],this._graph=this._subject=this._predicate=this._object=null,this._tripleTerm=this._reifier=null,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${or++}_`,this._n3Mode&&this._implicitEmptyPrefix&&this._base&&(this._prefixes[""]=this._resolveIRI("#")),this._prefixCallback=s||lr,this._versionCallback=a||lr,this._directiveCallback=c||lr,this._inversePredicate=!1,this._expectOf=!1,this._quantified=Object.create(null),this._prefixChanges=null,this._quantifiedChanges=null,this._emptyFormula=!1,this._tripleTermDepth=0;const h=e=>this._readCallback=this._readCallback(e);let d=h;if((o||this._lexer.comments)&&(this._lexer.comments=!0,d=e=>"comment"!==e.type?h(e):(o&&o(e.value),this._readCallback)),u||l){const e=d;d=t=>{try{try{return u&&u(t),e(t)}finally{l&&l(t)}}catch(e){throw this._readCallback=null,e}}}if(!i){const t=[];let r;this._callback=(e,n)=>{e?r=e:n&&t.push(n)};const n=this._lexer;if(s||a||c||o||u||l||n.tokenize!==N3Lexer.prototype.tokenize||"function"!=typeof n._tokenizeString)n.tokenize(e).every(d);else{const t=[this._base,this._basePath,this._baseRoot,this._baseScheme];n._tokenizeString(e,(e,r)=>{e?([this._base,this._basePath,this._baseRoot,this._baseScheme]=t,this._callback(e),this._callback=lr):this._readCallback&&d(r)})}if(r)throw r;return t}this._callback=i,this._lexer.tokenize(e,(e,t)=>{null!==e?(this._callback(e),this._callback=lr):this._readCallback&&d(t)})}}function ur(e,t){for(let r=t.length-2;r>=0;r-=2)void 0===t[r+1]?delete e[t[r]]:e[t[r]]=t[r+1]}function lr(){}function hr(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(Q.rdf.first),e.RDF_REST=t.namedNode(Q.rdf.rest),e.RDF_NIL=t.namedNode(Q.rdf.nil),e.RDF_REIFIES=t.namedNode(Q.rdf.reifies),e.N3_FORALL=t.namedNode(Q.r.forAll),e.N3_FORSOME=t.namedNode(Q.r.forSome),e.N3_TRUE=t.literal("true",t.namedNode(Q.xsd.boolean)),e.ABBREVIATIONS={a:t.namedNode(Q.rdf.type),"=":t.namedNode(Q.owl.sameAs),">":t.namedNode(Q.log.implies),"<":t.namedNode(Q.log.isImpliedBy)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}N3Parser.SUPPORTED_VERSIONS=["1.2","1.2-basic","1.1"],hr(N3Parser.prototype,ee);const dr=()=>{const e=[],t=[],r=[];return{onQuad:t=>{e.push(t)},onError:e=>{r.push(e)},onComplete:e=>{t.push(e)},parse:(n,i)=>{var s;(s=B(i),new N3Parser({format:"text/turtle",baseIRI:s})).parse(n,(n,i)=>{n?r.forEach(e=>e(n)):i?e.forEach(e=>e(i)):t.forEach(e=>e())})}}};async function fr(e,t){const r=new N3Writer({format:"text/turtle",prefixes:null==t?void 0:t.prefixes}),n=e.map(e=>ee.quad(e.subject,e.predicate,e.object,void 0));r.addQuads(n);const i=new Promise((e,t)=>{r.end((r,n)=>{r?t(r):e(n)})});return await i}const pr=new Uint8Array(16);const _r=[];for(let e=0;e<256;++e)_r.push((e+256).toString(16).slice(1));function gr(e,t=0){return(_r[e[t+0]]+_r[e[t+1]]+_r[e[t+2]]+_r[e[t+3]]+"-"+_r[e[t+4]]+_r[e[t+5]]+"-"+_r[e[t+6]]+_r[e[t+7]]+"-"+_r[e[t+8]]+_r[e[t+9]]+"-"+_r[e[t+10]]+_r[e[t+11]]+_r[e[t+12]]+_r[e[t+13]]+_r[e[t+14]]+_r[e[t+15]]).toLowerCase()}const yr=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){e=e||{};const n=e.random??e.rng?.()??crypto.getRandomValues(pr);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 gr(n)}(e,t,r):crypto.randomUUID()};function wr(e){var t,r,n,i,s,o,a,c;if(st(e))return`<${e.value}> (URL)`;if(function(e){return ot(e)&&"Literal"===e.termType}(e)){if(!st(e.datatype))return`[${e.value}] (RDF/JS Literal of unknown type)`;let u;switch(e.datatype.value){case Xe:return u=null!==(r=null===(t=function(e){return"true"===e||"1"===e||"false"!==e&&"0"!==e&&null}(e.value))||void 0===t?void 0:t.valueOf())&&void 0!==r?r:`Invalid data: \`${e.value}\``,`${u} (boolean)`;case Ye:return u=null!==(i=null===(n=function(e){if(!/-?\d{4,}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const[t,r]=e.split("T"),[n,i]="-"===t.charAt(0)?[-1,t.substring(1)]:[1,t],[s,o,a]=i.split("-"),c=Number.parseInt(s,10)*n,u=Number.parseInt(o,10)-1,l=Number.parseInt(a,10),[h,d]=nt(r),[f,p]="string"==typeof d?it(d):[0,0],[_,g,y]=h.split(":"),w=Number.parseInt(_,10)+f,b=Number.parseInt(g,10)+p,[m,v]=y.split("."),S=Number.parseInt(m,10),I=v?Number.parseInt(v,10):0,x=new Date(Date.UTC(c,u,l,w,b,S,I));return c>=0&&c<100&&x.setUTCFullYear(x.getUTCFullYear()-1900),x}(e.value))||void 0===n?void 0:n.toUTCString())&&void 0!==i?i:`Invalid data: \`${e.value}\``,`${u} (datetime)`;case Ze:return u=null!==(o=null===(s=function(e){const t=Number.parseFloat(e);return Number.isNaN(t)?null:t}(e.value))||void 0===s?void 0:s.toString())&&void 0!==o?o:`Invalid data: \`${e.value}\``,`${u} (decimal)`;case et:return u=null!==(c=null===(a=function(e){const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}(e.value))||void 0===a?void 0:a.toString())&&void 0!==c?c:`Invalid data: \`${e.value}\``,`${u} (integer)`;case rt:return`"${e.value}" (${e.language} string)`;case tt:return`"${e.value}" (string)`;default:return`[${e.value}] (RDF/JS Literal of type: \`${e.datatype.value}\`)`}}return"BlankNode"===e.termType?`[${e.value}] (RDF/JS BlankNode)`:"Quad"===e.termType?"??? (nested RDF* Quad)":"Variable"===e.termType?`?${e.value} (RDF/JS Variable)`:e}function br(e){if(!Nr(e))throw new ThingExpectedError(e)}function mr(e,t){const r=O(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.filter(e=>!function(e){return"BlankNode"===e.subject.termType||"BlankNode"===e.object.termType}(e)).reduce(([e,t],r)=>void 0!==e.find(e=>e.equals(r))?[e.filter(e=>!e.equals(r)),t]:[e,t.concat(r)],[r.additions,r.deletions]);return We({...e,internal_changeLog:{additions:n,deletions:i}})}const vr=function(e,t){var r,n,i;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const s=C(t),o=null!==(i=null===(n=null===(r=e.predicates[s])||void 0===r?void 0:r.namedNodes)||void 0===n?void 0:n[0])&&void 0!==i?i:null;return null===o?null:He(o)?`#${Qe(o)}`:o};function Sr(e,t){var r,n,i;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const s=C(t);return null!==(i=null===(n=null===(r=e.predicates[s])||void 0===r?void 0:r.namedNodes)||void 0===n?void 0:n.map(e=>He(e)?`#${Qe(e)}`:e))&&void 0!==i?i:[]}const Ir=Sr;function xr(e,t){var r,n;br(e);const i=function(e,t){return Ir(e,t).map(e=>ee.namedNode(e))}(e,t),s=function(e,t){var r,n,i,s;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const o=C(t);let a=[];const c=null!==(n=null===(r=e.predicates[o])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{},u=Object.keys(c);for(const e of u){const t=c[e].map(t=>ee.literal(t,e));a=a.concat(t)}const l=null!==(s=null===(i=e.predicates[o])||void 0===i?void 0:i.literals)&&void 0!==s?s:{},h=Object.keys(l);for(const e of h){const t=l[e],r=ee.namedNode(e),n=t.map(e=>ee.literal(e,r));a=a.concat(n)}return a}(e,t),o=C(t),a=(null!==(n=null===(r=e.predicates[o])||void 0===r?void 0:r.blankNodes)&&void 0!==n?n:[]).map(e=>{const t=Je(e)?Ge(e):void 0;return ee.blankNode(t)});return i.concat(s).concat(a)}function Er(e,t,r){var n,i,s,o;if(!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const a=C(t);return null!==(o=null===(s=null===(i=null===(n=e.predicates[a])||void 0===n?void 0:n.literals)||void 0===i?void 0:i[r])||void 0===s?void 0:s[0])&&void 0!==o?o:null}function Tr(e,t,r={}){var n;if(!ct(t)&&!t.match(/^_:/))throw new ValidThingUrlExpectedError(t);const i=void 0!==r.scope?C(r.scope):"default",s=null!==(n=e.graphs[i])&&void 0!==n?n:{},o=C(t),a=s[He(o)&&P(e)?lt(Qe(o),B(e)):o];return void 0===a?null:a}function Rr(e,t={acceptBlankNodes:!1}){var r;const n=void 0!==t.scope?C(t.scope):"default",i=null!==(r=e.graphs[n])&&void 0!==r?r:{};return Object.values(i).filter(e=>!Je(e.url)||t.acceptBlankNodes)}function Ar(e,t){var r;const n=Or(t)&&P(e)?lt(Qe(t.url),B(e)):t.url,i=e.graphs.default,s=We({...i,[n]:We({...t,url:n})}),o=We({...e.graphs,default:s}),a=ee.namedNode(n),c=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,u=void 0!==c?gt(c,a,ee.defaultGraph()):[],l=gt(t.predicates,a,ee.defaultGraph());return function(e,t){const r=O(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.reduce(([e,t],r)=>void 0!==t.find(e=>e.equals(r))?[e,t.filter(e=>!e.equals(r))]:[e.concat(r),t],[r.additions,r.deletions]);return We({...e,internal_changeLog:{additions:n,deletions:i}})}(mr(We({...e,graphs:o}),u),l)}function kr(e,t){var r;let n;n=st(t)?t.value:"string"==typeof t?He(t)&&P(e)?lt(Qe(t),B(e)):t:Or(t)?t.url:Pr(t);const i={...e.graphs.default};delete i[n];const s=We({...e.graphs,default:We(i)}),o=ee.namedNode(n),a=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,c=void 0!==a?gt(a,o,ee.defaultGraph()):[];return mr(We({...e,graphs:s}),c)}function jr(e={}){var t;if(void 0!==e.url){const{url:t}=e;if(!ct(t))throw new ValidThingUrlExpectedError(t);return We({type:"Subject",predicates:We({}),url:t})}const r=null!==(t=e.name)&&void 0!==t?t:Cr(),n=`${Ke}${r}`;return We({type:"Subject",predicates:We({}),url:n})}function Nr(e){return"object"==typeof e&&null!==e&&"string"==typeof e.type&&"Subject"===e.type}const Pr=function(e,t){if(Or(e)){if(void 0===t)throw new Error("The URL of a Thing that has not been persisted cannot be determined without a base URL.");return lt(Qe(e.url),t)}return e.url};function Or(e){return He(e.url)}class ThingExpectedError extends SolidClientError{constructor(e){super(`Expected a Thing, but received: [${e}].`),this.receivedValue=e}}class thing_ValidPropertyUrlExpectedError extends SolidClientError{constructor(e){const t=st(e)?e.value:e;super(`Expected a valid URL to identify a property, but received: [${t}].`),this.receivedProperty=t}}class ValidValueUrlExpectedError extends SolidClientError{constructor(e){const t=st(e)?e.value:e;super(`Expected a valid URL value, but received: [${t}].`),this.receivedValue=t}}class ValidThingUrlExpectedError extends SolidClientError{constructor(e){const t=st(e)?e.value:e;super(`Expected a valid URL to identify a Thing, but received: [${t}].`),this.receivedValue=t}}const Cr=()=>yr();function Dr(e){const t=new URL(e);return t.hash="",t.href}function Lr(e){return Array.from(e).reduce((e,t)=>function(e,t){var r;if(!["NamedNode","DefaultGraph"].includes(t.graph.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.graph.termType}] as their Graph node.`);const n="DefaultGraph"===t.graph.termType?"default":t.graph.value,i=null!==(r=e.graphs[n])&&void 0!==r?r:{};return We({...e,graphs:We({...e.graphs,[n]:ht(i,t)})})}(e,t),{graphs:{default:{}},type:"Dataset"})}function $r(){return We({type:"Dataset",graphs:{default:{}}})}async function Ur(e,t){var r,n;const i=D(C(e)),s=Object.keys(null!==(r=null==t?void 0:t.parsers)&&void 0!==r?r:{}),o=s.length>0?s.join(", "):"text/turtle",a=await(null!==(n=null==t?void 0:t.fetch)&&void 0!==n?n:fetch)(i,{headers:{Accept:o}});if($(a)){const e=await a.clone().text();throw new FetchError(`Fetching the Resource at [${i}] failed: [${a.status}] [${a.statusText}] ${e}.`,a,e)}const c=await async function(e,t={}){if($(e)){const t=await e.clone().text();throw new FetchError(`Fetching the SolidDataset at [${e.url}] failed: [${e.status}] [${e.statusText}] ${t}.`,e,t)}const r=M(e),n={"text/turtle":dr(),...t.parsers},i=null!==(s=r.internal_resourceInfo.contentType)&&void 0!==s?s:null;var s;if(null===i)throw new Error(`Could not determine the content type of the Resource at [${B(r)}].`);const o=i.split(";")[0],a=n[o];if(void 0===a)throw new Error(`The Resource at [${B(r)}] has a MIME type of [${o}], but the only parsers available are for the following MIME types: [${Object.keys(n).join(", ")}].`);const c=await e.text(),u=await new Promise((e,t)=>{const n=new N3Store;a.onError(e=>{t(new Error(`Encountered an error parsing the Resource at [${B(r)}] with content type [${i}]: ${e}`))}),a.onQuad(e=>{n.add(e)}),a.onComplete(()=>{e(n)}),a.parse(c,r)}),l=We(Lr(u));return We({...l,...r})}(a,t);return c}async function Mr(e,t,r){var n;const i=D(C(e)),s=function(e){return O(e)?e:We({...e,internal_changeLog:{additions:[],deletions:[]}})}(t),o=Br(s,i)?await async function(e){return{method:"PATCH",body:`${e.internal_changeLog.deletions.length>0?`DELETE DATA {${(await fr(e.internal_changeLog.deletions.map(Kr))).trim()}};`:""} ${e.internal_changeLog.additions.length>0?`INSERT DATA {${(await fr(e.internal_changeLog.additions.map(Kr))).trim()}};`:""}`,headers:{"Content-Type":"application/sparql-update"}}}(s):await async function(e,t){return{method:"PUT",body:await fr(_t(e).map(Kr),t),headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:`<${kt}>; rel="type"`}}}(s,r),a=await(null!==(n=null==r?void 0:r.fetch)&&void 0!==n?n:fetch)(i,o);if($(a)){const e=Br(s,i)?`The changes that were sent to the Pod are listed below.\n\n${function(e){if(!N(e))return"This is a newly initialized SolidDataset, so there is no source to compare it to.";if(!O(e)||0===e.internal_changeLog.additions.length&&0===e.internal_changeLog.deletions.length)return`## Changes compared to ${B(e)}\n\nThis SolidDataset has not been modified since it was fetched from ${B(e)}.\n`;let t=`## Changes compared to ${B(e)}\n`;const r=function(e){const t=Object.create(null);return e.internal_changeLog.deletions.forEach(r=>{var n,i,s;const o=at(r.subject)?ut(r.subject,B(e)):r.subject;if(!st(o)||!st(r.predicate))return;const a=C(o),c=C(r.predicate);null!==(n=t[a])&&void 0!==n||(t[a]=Object.create(null)),null!==(i=(s=t[a])[c])&&void 0!==i||(s[c]={added:[],deleted:[]}),t[a][c].deleted.push(r.object)}),e.internal_changeLog.additions.forEach(r=>{var n,i,s;const o=at(r.subject)?ut(r.subject,B(e)):r.subject;if(!st(o)||!st(r.predicate))return;const a=C(o),c=C(r.predicate);null!==(n=t[a])&&void 0!==n||(t[a]=Object.create(null)),null!==(i=(s=t[a])[c])&&void 0!==i||(s[c]={added:[],deleted:[]}),t[a][c].added.push(r.object)}),t}(e);return Object.keys(r).forEach(e=>{t+=`\n### Thing: ${e}\n`;const n=r[e];Object.keys(n).forEach(e=>{t+=`\nProperty: ${e}\n`;const{deleted:r}=n[e],{added:i}=n[e];r.length>0&&(t+="- Removed:\n",t+=r.reduce((e,t)=>`${e} - ${wr(t)}\n`,"")),i.length>0&&(t+="- Added:\n",t+=i.reduce((e,t)=>`${e} - ${wr(t)}\n`,""))})}),t}(s)}`:`The SolidDataset that was sent to the Pod is listed below.\n\n${qr(s)}`,t=await a.clone().text();throw new FetchError(`Storing the Resource at [${i}] failed: [${a.status}] [${a.statusText}] ${t}.\n\n${e}`,a,t)}const c={...L(a),isRawData:!1};return Hr(We({...t,internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:c}))}async function Fr(e,t){var r;const n=N(e)?C(B(e)):D(C(e)),i=await(null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch)(n,{method:"DELETE"});if($(i)){const e=await i.clone().text();throw new FetchError(`Deleting the SolidDataset at [${n}] failed: [${i.status}] [${i.statusText}] ${e}.`,i,e)}}function Br(e,t){return O(e)&&N(e)&&"string"==typeof e.internal_resourceInfo.sourceIri&&(r=t,Dr(e.internal_resourceInfo.sourceIri)===Dr(r));var r}function zr(e,t){const r=new URL(t),n=new URL(e),i=n.href.startsWith(r.href),s=n.pathname.substring(r.pathname.length,n.pathname.length).replace(/(^\/)|(\/$)/g,"");return i&&s.length>=1&&!s.includes("/")}function qr(e){let t="";N(e)?t+=`# SolidDataset: ${B(e)}\n`:t+="# SolidDataset (no URL yet)\n";const r=Rr(e);return 0===r.length?t+="\n<empty>\n":r.forEach(r=>{t+=`\n${function(e){let t="";Or(e)?t+=`## Thing (no URL yet — identifier: \`#${Qe(e.url)}\`)\n`:t+=`## Thing: ${e.url}\n`;const r=Object.keys(e.predicates);if(0===r.length)t+="\n<empty>\n";else for(const n of r)t+=`\nProperty: ${n}\n`,t+=xr(e,n).reduce((e,t)=>`${e}- ${wr(t)}\n`,"");return t}(r)}`,O(e)&&(t+=`\n${function(e,t){const r=ee.namedNode(t.url),n=e.internal_changeLog.additions.reduce((e,t)=>t.subject.equals(r)?e+1:e,0),i=e.internal_changeLog.deletions.reduce((e,t)=>t.subject.equals(r)?e+1:e,0);return`(${1===n?"1 new value added":`${n} new values added`} / ${1===i?"1 value removed":`${i} values removed`})`}(e,r)}\n`)}),t}function Kr(e){const t=st(e.subject)?Wr(e.subject):e.subject,r=st(e.object)?Wr(e.object):e.object;return ee.quad(t,e.predicate,r,e.graph)}function Wr(e){return He(e.value)?ee.namedNode(`#${Qe(e.value)}`):e}function Hr(e){const t=B(e),r=e.graphs.default,n=Object.keys(r).reduce((e,r)=>{const n=function(e,t){const r=Object.keys(e.predicates).reduce((e,r)=>{var n;const i=null!==(n=e[r].namedNodes)&&void 0!==n?n:[];if(i.every(e=>!He(e)))return e;const s=We(i.map(e=>He(e)?`${t}#${Qe(e)}`:e)),o=We({...e[r],namedNodes:s});return We({...e,[r]:o})},e.predicates);return We({...e,predicates:r,url:He(e.url)?`${t}#${Qe(e.url)}`:e.url})}(e[r],t),i=He(r)?`${t}#${Qe(r)}`:r,s={...e};return delete s[r],s[i]=n,We(s)},r),i=We({...e.graphs,default:n});return We({...e,graphs:i})}async function Qr(e,t){var r,n;const i=null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch,s=null!==(n=null==t?void 0:t.webIdProfile)&&void 0!==n?n:await Ur(e),o=(await Promise.allSettled(function(e,t){const r=Tr(t,e),n=Rr(t).filter(e=>Ir(e,Pt).length>0).map(Pr).concat(r?Ir(r,Rt):[]).concat(r?Ir(r,Ot):[]).filter(e=>e!==z(t));return Array.from(new Set(n))}(e,s).map(e=>Ur(e,{fetch:i})))).filter(e=>"fulfilled"===e.status).map(e=>e.value);return{webIdProfile:s,altProfileAll:o}}async function Jr(e,t){return function(e,t){const r=new Set;return[e.webIdProfile,...e.altProfileAll].forEach(e=>{const n=Tr(e,t);null!==n&&Ir(n,Dt).forEach(e=>r.add(e))}),Array.from(r)}(await Qr(e,t),e)}function Gr(e,t){if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const r=C(t),n={...e.predicates};return delete n[r],We({...e,predicates:We(n)})}const Vr=(e,t,r)=>{var n,i,s;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const o=C(t);if(!Nr(r)&&!ct(r))throw new ValidValueUrlExpectedError(r);const a=Nr(r)?Pr(r):C(r),c=We(null!==(s=null===(i=null===(n=e.predicates[o])||void 0===n?void 0:n.namedNodes)||void 0===i?void 0:i.filter(e=>e.toLowerCase()!==a.toLowerCase()))&&void 0!==s?s:[]),u=We({...e.predicates[o],namedNodes:c}),l=We({...e.predicates,[o]:u});return We({...e,predicates:l})},Xr=Vr;const Yr=(e,t,r)=>{var n,i;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);if(!Nr(r)&&!ct(r))throw new ValidValueUrlExpectedError(r);const s=C(t),o=null!==(n=e.predicates[s])&&void 0!==n?n:{},a=null!==(i=o.namedNodes)&&void 0!==i?i:[];let c;c=st(r)?r.value:"string"==typeof r?r:Or(r)?r.url:Pr(r);const u=We(a.concat(C(c))),l=We({...o,namedNodes:u}),h=We({...e.predicates,[s]:l});return We({...e,predicates:h})},Zr=Yr;function en(e,t,r,n){var i,s,o;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const a=C(t),c=null!==(i=e.predicates[a])&&void 0!==i?i:{},u=null!==(s=c.literals)&&void 0!==s?s:{},l=null!==(o=u[n])&&void 0!==o?o:[],h=We(l.concat(r)),d=We({...u,[n]:h}),f=We({...c,literals:d}),p=We({...e.predicates,[a]:f});return We({...e,predicates:p})}const tn=(e,t,r)=>{if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);if(!Nr(r)&&!ct(r))throw new ValidValueUrlExpectedError(r);return Yr(Gr(e,t),t,r)};const rn=(e,t,r)=>(br(e),((e,t,r)=>(br(e),en(e,t,r,tt)))(Gr(e,t),t,r));async function nn(e,t){if(!In(e))return{resourceAcl:null,fallbackAcl:null};try{const r=await sn(e,t);return null===r?{resourceAcl:null,fallbackAcl:await on(e,t)}:{resourceAcl:r,fallbackAcl:null}}catch(e){if(e instanceof AclIsAcrError)return{resourceAcl:null,fallbackAcl:null};throw e}}async function sn(e,t){if(!In(e))return null;try{const r=await Ur(e.internal_resourceInfo.aclUrl,t);if(function(e){const t=q(e).type;return Array.isArray(t)&&t.includes(Ct)}(r))throw new AclIsAcrError(e,r);return We({...r,internal_accessTo:B(e)})}catch(e){if(e instanceof AclIsAcrError)throw e;return null}}async function on(e,t){const r=new URL(B(e)),n=r.pathname;if("/"===n)return null;const i=function(e){const t="/"===e.substring(e.length-1)?e.substring(0,e.length-1):e,r=`${e.substring(0,t.lastIndexOf("/"))}/`;return r}(n),s=new URL(i,r.origin).href,o=await U(s,t);if(!In(o))return null;const a=await sn(o,t);return null===a?on(o,t):a}function an(e){return Rr(e).filter(cn)}function cn(e){return Ir(e,Tt).includes(yt)}function un(e,t){return e.filter(e=>function(e,t){return Ir(e,wt).includes(t)}(e,t))}function ln(e,t){return e.filter(e=>function(e,t){return Ir(e,St).includes(t)||Ir(e,It).includes(t)}(e,t))}function hn(e){const t=Ir(e,xt);return t.includes(pn.write)?{read:t.includes(pn.read),append:!0,write:!0,control:t.includes(pn.control)}:{read:t.includes(pn.read),append:t.includes(pn.append),write:!1,control:t.includes(pn.control)}}function dn(e){return e.reduce((e,t)=>e.write||t.write?{read:e.read||t.read,append:!0,write:!0,control:e.control||t.control}:{read:e.read||t.read,append:e.append||t.append,write:!1,control:e.control||t.control},{read:!1,append:!1,write:!1,control:!1})}function fn(e){return!gt(e.predicates,ee.namedNode(e.url),ee.defaultGraph()).some(e=>!function(e){const{predicate:t}=e,{object:r}=e;if(t.equals(ee.namedNode(Tt))&&r.equals(ee.namedNode(yt)))return!0;if(t.equals(ee.namedNode(wt))||t.equals(ee.namedNode(St))||t.equals(ee.namedNode(It)))return!0;if(t.equals(ee.namedNode(xt))&&Object.values(pn).some(e=>r.equals(ee.namedNode(e))))return!0;if(t.equals(ee.namedNode(bt))||t.equals(ee.namedNode(mt))||t.equals(ee.namedNode(vt)))return!0;if(t.equals(ee.namedNode(Et)))return!0;return!1}(e))&&(null===vr(e,wt)&&null===vr(e,St)&&null===vr(e,It)||(null===vr(e,xt)||null===vr(e,bt)&&null===vr(e,mt)&&null===vr(e,vt)))}const pn={read:"http://www.w3.org/ns/auth/acl#Read",append:"http://www.w3.org/ns/auth/acl#Append",write:"http://www.w3.org/ns/auth/acl#Write",control:"http://www.w3.org/ns/auth/acl#Control"};function _n(e){let t=jr();return t=tn(t,Tt,yt),e.read&&(t=Zr(t,xt,pn.read)),e.append&&!e.write&&(t=Zr(t,xt,pn.append)),e.write&&(t=Zr(t,xt,pn.write)),e.control&&(t=Zr(t,xt,pn.control)),t}function gn(e,t){return Object.assign(function(e){let t;return t="function"==typeof e.slice?Object.assign(e.slice(),{...e}):{...e},t}(e),{internal_acl:t})}const yn=[bt,vt,mt,Et];function wn(e,t,r,n,i){if(!Ir(e,r).includes(t)){return[e,_n({read:!1,append:!1,write:!1,control:!1})]}const s=Xr(e,r,t);let o=function(e){let t=jr();function r(e,t,r){return Ir(e,r).reduce((e,t)=>Zr(e,r,t),t)}return t=tn(t,Tt,yt),t=r(e,t,wt),t=r(e,t,St),t=r(e,t,It),t=r(e,t,bt),t=r(e,t,mt),t=r(e,t,vt),t=r(e,t,Et),t=r(e,t,xt),t}(e);return o=Xr(o,"resource"===i?wt:St,n),"default"===i&&(o=Xr(o,It,n)),o=tn(o,r,t),yn.filter(e=>e!==r).forEach(e=>{o=Gr(o,e)}),[s,o]}function bn(e,t,r,n,i){let s=e;Rr(e).forEach(t=>{const[o,a]=wn(t,i,r,e.internal_accessTo,n);s=Ar(s,o),s=Ar(s,a)});let o=_n(t);o=tn(o,"resource"===n?wt:St,e.internal_accessTo),o=tn(o,r,i);return function(e){return an(e).filter(fn).reduce(kr,e)}(Ar(s,o))}class AclIsAcrError extends Error{constructor(e,t){super(`[${z(e)}] is governed by Access Control Policies in [${z(t)}] rather than by Web Access Control.`)}}function mn(e){return null!==e.internal_acl.resourceAcl&&B(e)===e.internal_acl.resourceAcl.internal_accessTo&&e.internal_resourceInfo.aclUrl===B(e.internal_acl.resourceAcl)}function vn(e){return null!==e.internal_acl.fallbackAcl}function Sn(e){return We({...$r(),internal_accessTo:B(e),internal_resourceInfo:{sourceIri:e.internal_resourceInfo.aclUrl,isRawData:!1,linkedResources:{}}})}function In(e){return"string"==typeof e.internal_resourceInfo.aclUrl}function xn(e,t){return mn(e)?function(e,t){const r=an(e),n=Rn(un(r,e.internal_accessTo),t);return dn(n.map(hn))}(e.internal_acl.resourceAcl,t):vn(e)?function(e,t){const r=an(e),n=Rn(ln(r,e.internal_accessTo),t);return dn(n.map(hn))}(e.internal_acl.fallbackAcl,t):null}function En(e,t,r){return bn(e,r,bt,"resource",t)}function Tn(e,t,r){return bn(e,r,bt,"default",t)}function Rn(e,t){return function(e,t,r){return e.filter(e=>Ir(e,r).includes(t))}(e,t,bt)}function An(e,t,r){return bn(e,r,mt,"resource",t)}function kn(e,t,r){return bn(e,r,mt,"default",t)}function jn(e,t){return bn(e,t,vt,"resource",Nt)}function Nn(e,t){return bn(e,t,vt,"default",Nt)}const Pn="http://www.w3.org/ns/solid/acp#",On={AccessControlResource:Pn.concat("AccessControlResource"),Matcher:Pn.concat("Matcher"),Policy:Pn.concat("Policy"),PublicAgent:Pn.concat("PublicAgent"),access:Pn.concat("access"),accessControl:Pn.concat("accessControl"),agent:Pn.concat("agent"),allOf:Pn.concat("allOf"),allow:Pn.concat("allow"),anyOf:Pn.concat("anyOf"),apply:Pn.concat("apply"),deny:Pn.concat("deny"),memberAccessControl:Pn.concat("memberAccessControl"),noneOf:Pn.concat("noneOf"),vc:Pn.concat("vc")},Cn="http://www.w3.org/ns/auth/acl#",Dn={Append:Cn.concat("Append"),Read:Cn.concat("Read"),Write:Cn.concat("Write")};function Ln(e){return"object"==typeof e.internal_acp&&null!==e.internal_acp&&"object"==typeof e.internal_acp.acr&&null!==e.internal_acp.acr}function $n(e){if(!Ln(e))throw new Error(`An Access Control Resource for [${B(e)}] is not available. This could be because the current user is not allowed to see it, or because their Pod Server does not support Access Control Resources.`);return e.internal_acp.acr}function Un(e){const t=function(e){const t=$n(e);return Tr(t,B(t))}(e);return null===t?[]:Ir(t,On.accessControl)}function Mn(e,t,r){const n=$n(e);return Array.from(new Set(t.map(e=>{const t=Tr(n,e);return null!==t?Ir(t,r):[]}).reduce((e,t)=>e.concat(t),[])))}function Fn(e,t){const r=Ir(e,t);return{read:r.includes(Dn.Read),append:r.includes(Dn.Append),write:r.includes(Dn.Write),controlRead:!1,controlWrite:!1}}function Bn(e,t,r){const n=Sr(t,On.allOf).map(t=>Tr($n(e),t)).filter(e=>null!==e),i=n.every(e=>Sr(e,On.agent).includes(r)),s=Sr(t,On.anyOf).map(t=>Tr($n(e),t)).filter(e=>null!==e),o=s.some(e=>Sr(e,On.agent).includes(r)),a=Sr(t,On.noneOf).map(t=>Tr($n(e),t)).filter(e=>null!==e),c=a.some(e=>Sr(e,On.agent).includes(r));return n.length+s.length>0&&(0===n.length||i)&&(0===s.length||o)&&(0===a.length||!c)}function zn(e,t,r){const n=function(e){return Fn(e,On.allow)}(e),i=function(e){return Fn(e,On.deny)}(e);return"control"===r?{read:t.read,append:t.append,write:t.write,controlRead:(t.controlRead||n.read)&&!i.read,controlWrite:(t.controlWrite||n.write)&&!i.write}:{read:(t.read||n.read)&&!i.read,append:(t.append||n.append)&&!i.append,write:(t.write||n.write)&&!i.write,controlRead:t.controlRead,controlWrite:t.controlWrite}}async function qn(e,t){let r={read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1};const n=function(e){return Mn(e,Un(e),On.apply)}(e).map(t=>Tr($n(e),t)).filter(e=>null!==e);n.forEach(n=>{Bn(e,n,t)&&(r=zn(n,r,"resource"))});const i=function(e){return Mn(e,Un(e),On.access)}(e).map(t=>Tr($n(e),t)).filter(e=>null!==e);return i.forEach(n=>{Bn(e,n,t)&&(r=zn(n,r,"control"))}),r}function Kn(e){return{read:e.read,write:e.write,append:e.append,controlRead:e.control,controlWrite:e.control}}function Wn(e,t,r){return async function(e,t,r,n){const i=r(gn(e,await nn(e,n)),t);return null===i?null:Kn(i)}(e,t,xn,r)}async function Hn(e,t){const r=await async function(e,t){if("string"!=typeof e.internal_resourceInfo.aclUrl)return null;try{return await U(e.internal_resourceInfo.aclUrl,t)}catch(e){return null}}(e,t);if(null===r)return null;const n=q(r).type;return Array.isArray(n)&&n.includes(On.AccessControlResource)?B(r):null}async function Qn(e,t,r){const n=await U(e,r),i=await async function(e,t){const r=await Hn(e,t);if(null===r)return null;let n;try{n=await Ur(r,t)}catch(e){return null}return{...e,internal_acp:{acr:{...n,accessTo:B(e)}}}}(n,r);return null===i?Wn(n,t,r):qn(i,t)}var Jn=i(945);class JOSEError extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class JWTClaimValidationFailed extends JOSEError{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class JWTExpired extends JOSEError{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class JOSEAlgNotAllowed extends JOSEError{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class JOSENotSupported extends JOSEError{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class JWSInvalid extends JOSEError{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class JWTInvalid extends JOSEError{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class JWKSInvalid extends JOSEError{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class JWKSNoMatchingKey extends JOSEError{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t)}}class JWKSMultipleMatchingKeys extends JOSEError{[Symbol.asyncIterator]=async function*(){};static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class JWKSTimeout extends JOSEError{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}}class JWSSignatureVerificationFailed extends JOSEError{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function Gn(e){const t={__proto__:null};for(const r in e)t[r]={...e[r],alg:r};return t}const Vn=[["verify"],["sign"]];function Xn(e){const t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Vn}}function Yn(e,t){const r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Vn,minRsaBits:2048}}function Zn(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Vn}}function ei(){const e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Vn}}function ti(e){const t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Vn}}const ri=Gn({HS256:Xn(256),HS384:Xn(384),HS512:Xn(512),RS256:Yn(256),RS384:Yn(384),RS512:Yn(512),PS256:Yn(256,32),PS384:Yn(384,48),PS512:Yn(512,64),ES256:Zn("P-256",256),ES384:Zn("P-384",384),ES512:Zn("P-521",512),EdDSA:ei(),Ed25519:ei(),"ML-DSA-44":ti(44),"ML-DSA-65":ti(65),"ML-DSA-87":ti(87)});function ni(e){const t="string"==typeof e?ri[e]:void 0;if(!t)throw new JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const ii=new TextEncoder,si=new TextDecoder,oi=new TextDecoder("utf-8",{fatal:!0});function ai(...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 ci=/[^\x00-\x7f]/;function ui(e){if("string"==typeof e&&e.length>=128){if(ci.test(e))throw new TypeError("non-ASCII string encountered in encode()");return ii.encode(e)}const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function li(e){try{return function(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}const r=atob(e),n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}("string"==typeof e?e:si.decode(e),!0)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.",{cause:e})}}function hi(e){return function(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});const r=[];for(let t=0;t<e.length;t+=32768)r.push(String.fromCharCode.apply(null,e.subarray(t,t+32768)));const n=btoa(r.join(""));return t?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}("string"==typeof e?ii.encode(e):e,!0)}function di(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function fi(e){return di(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(di)}function pi(...e){const t=new Set;for(const r of e)if(r)for(const e of Object.keys(r)){if(t.has(e))return!1;t.add(e)}return!0}function _i(e,t,r){try{return li(e)}catch(e){throw new r(`Failed to base64url decode the ${t}`,{cause:e})}}const gi={__proto__:null,b64:!0};function yi(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`);return void 0===t?void 0:new Set(t)}function wi(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[];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');const s=void 0===r?t:{__proto__:null,...r,...t};for(const t of n.crit){if(!(t in s))throw new JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s[t]&&(!Object.hasOwn(n,t)||void 0===n[t]))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return n.crit}function bi(e,t){if(t.includes("b64")){const t=e.b64;if("boolean"!=typeof t)throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return t}return!0}function mi(e,t){let r,n;try{r=JSON.stringify(t),n=JSON.parse(r)}catch(t){throw new e("JOSE Header is not valid JSON",{cause:t})}if(!di(n))throw new e("JOSE Header is not a JSON object");return[n,r]}async function vi(e,t,r){const{alg:n,secret:i}=e,s="decrypt"===r||"sign"===r;if(i&&t instanceof Uint8Array)return t;let o,a;if(di(t)){if(o=function(e){const t=Pi(e);if(void 0!==t.ext&&"boolean"!=typeof t.ext)throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(void 0!==t.key_ops){const e=t.key_ops,r=Array.isArray(e)?[...e]:void 0;if(!r||r.some(e=>"string"!=typeof e)||new Set(r).size!==r.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=r}return t}(t),"string"!=typeof o.kty)throw Ai(n,t,i);if(!(i?"oct"===o.kty&&"string"==typeof o.k:"oct"!==o.kty&&(s?"AKP"===o.kty&&"string"==typeof o.priv||"string"==typeof o.d:void 0===o.d&&void 0===o.priv)))throw new TypeError(i?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${s?"private":"public"} JWK`);if(((e,t,r)=>{const{alg:n}=e;if(void 0!==t.use){const e="sign"===r||"verify"===r?"sig":"enc";if(t.use!==e)throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){const n="encrypt"===r||"decrypt"===r?e.ops?.["encrypt"===r?0:1]:r;if(n&&!t.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}})(e,o,r),"oct"===o.kty)return li(o.k);if(!Object.isFrozen(t)){const{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Ti(t))throw Ai(n,t,i);const e=i?"secret":s?"private":"public";if(t.type!==e&&(i||["secret","public","private"].includes(t.type)))throw new TypeError(`${(e=>e[Symbol.toStringTag])(t)} instances must be of type "${e}" for the ${n} algorithm`);if(xi(t))return t;if(a=t,"secret"===a.type)return a.export()}Si||=new WeakMap;const c=t;let u=Si.get(c);if(u?.[n])return u[n];if(u||Si.set(c,u={}),a&&"function"==typeof a.toCryptoKey){const t="public"===a.type,r=Ii[a.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:r,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return u[n]=a.toCryptoKey(i,t,e.usages[t?0:1])}return o??=a.export({format:"jwk"}),o.alg=n,u[n]=await Oi(e,o)}let Si;const Ii={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};const xi=e=>{if("CryptoKey"===e?.[Symbol.toStringTag])return!0;try{return e instanceof CryptoKey}catch{return!1}},Ei=e=>"KeyObject"===e?.[Symbol.toStringTag],Ti=e=>xi(e)||Ei(e);function Ri(e,t,...r){if(r.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}function Ai(e,t,r){const n=["CryptoKey","KeyObject","JSON Web Key"];return r&&n.push("Uint8Array"),new TypeError(Ri(`Key for the ${e} algorithm must be `,t,...n))}const ki=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function ji(e,t){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 Ni(e,t,r){const n=e.algorithm;if(n.name!==t.name)throw ki(t.name);if(t.hash&&n.hash?.name!==t.hash)throw ki(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw ki(t.namedCurve,"algorithm.namedCurve");if(void 0!==t.length&&n.length!==t.length)throw ki(t.length,"algorithm.length");!function(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}(e,r)}function Pi(e){return{__proto__:null,...e}}async function Oi(e,t,r){if(!e.kty.includes(t.kty))throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');const n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!(!t.d&&!t.priv),s={...t,ext:r??t.ext};return"AKP"!==s.kty&&delete s.alg,delete s.use,crypto.subtle.importKey("jwk",s,n,s.ext??!i,t.key_ops??e.usages[i?1:0])}async function Ci(e,t,r,n=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,n,[r])),Ni(e,t,r),e}function Di(e){return void 0===e?{}:function(e,t,r){let n;try{n=JSON.parse(oi.decode(li(e)))}catch(e){throw new t(r,{cause:e})}if(!di(n))throw new t(r);return n}(e,JWSInvalid,"JWS Protected Header is invalid")}function Li(e){try{return ui(e)}catch(e){throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters",{cause:e})}}async function $i(e,t,r,n,i){const{protected:s,header:o,payload:a}=e,c=i??Di(s);if(!pi(c,o))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const u={...c,...o},l=bi(c,wi(JWSInvalid,gi,t[1],c,u)),{alg:h}=u;if("string"!=typeof h||!h)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(h))throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(l){if("string"!=typeof a)throw new JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof a&&!(a instanceof Uint8Array))throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");const d=l||"string"!=typeof a?a:n(a);let f=!1;"function"==typeof r&&(r=await r(c,e),f=!0);const p=ni(h),_=ai(void 0!==s?ui(s):new Uint8Array,ui("."),"string"==typeof d?t[2]??=function(e,t,r){try{return ui(e)}catch(e){throw new r(`The ${t} is not a valid base64url string`,{cause:e})}}(d,"payload",JWSInvalid):d),g=_i(e.signature,"signature",JWSInvalid),y=await vi(p,r,"verify"),w=await Ci(y,p.subtle,"verify");p.minRsaBits&&ji(p.alg,w);let b=!1;try{b=await crypto.subtle.verify(p.signing,w,g,_)}catch(e){throw new JWSSignatureVerificationFailed(void 0,{cause:e})}if(!b)throw new JWSSignatureVerificationFailed;const m={payload:"string"==typeof d?_i(d,"payload",JWSInvalid):d};return void 0!==s&&(m.protectedHeader=c),void 0!==o&&(m.unprotectedHeader=o),f?[{...m,key:y},l]:[m,l]}const Ui=e=>Math.floor(e.getTime()/1e3),Mi={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Fi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Bi="check_failed";function zi(){throw new TypeError("Invalid time period format")}function qi(e){"string"!=typeof e&&zi();const t=Fi.exec(e);(!t||t[4]&&t[1])&&zi();const r=parseFloat(t[2]),n=Math.round(r*Mi[t[3][0].toLowerCase()]);return Number.isFinite(n)||zi(),"-"===t[1]||"ago"===t[4]?-n:n}function Ki(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function Wi(e,t){if("string"!=typeof t)throw new TypeError(`"${e}" claim must be a string`)}function Hi(e,t){return"number"==typeof e?Ki(t,e):e instanceof Date?Ki(t,Ui(e)):Ui(new Date)+qi(e)}const Qi=e=>{const t=e.toLowerCase();return e.includes("/")?t:`application/${t}`};function Ji(e,t,r=!1){const n=e[t];if(void 0!==n||r){if("number"!=typeof n)throw new JWTClaimValidationFailed(`"${t}" claim must be a number`,e,t,"invalid");return n}}function Gi(e,t){throw new JWTClaimValidationFailed(`unexpected "${t}" claim value`,e,t,Bi)}function Vi(e,t,r={}){let n;try{n=JSON.parse(oi.decode(t))}catch(e){throw new JWTInvalid("JWT Claims Set must be a top-level JSON object",{cause:e})}if(!di(n))throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");const{typ:i}=r;if(void 0!==i&&("string"!=typeof e.typ||Qi(e.typ)!==Qi(i)))throw new JWTClaimValidationFailed('unexpected "typ" JWT header value',n,"typ",Bi);const{requiredClaims:s=[],issuer:o,subject:a,audience:c,maxTokenAge:u}=r,l=[...s];void 0!==u&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==a&&l.push("sub"),void 0!==o&&l.push("iss");for(const e of new Set(l.reverse()))if(!Object.hasOwn(n,e))throw new JWTClaimValidationFailed(`missing required "${e}" claim`,n,e,"missing");var h,d;void 0!==o&&!(Array.isArray(o)?o:[o]).includes(n.iss)&&Gi(n,"iss"),void 0!==a&&n.sub!==a&&Gi(n,"sub"),void 0!==c&&(h=n.aud,d="string"==typeof c?[c]:c,!("string"==typeof h?d.includes(h):Array.isArray(h)&&d.some(e=>h.includes(e))))&&Gi(n,"aud");const{clockTolerance:f}=r;let p=0;if("string"==typeof f)p=qi(f);else if(void 0!==f){if("number"!=typeof f)throw new TypeError("Invalid clockTolerance option type");p=f}if(Ki("clockTolerance option",p),p<0)throw new TypeError("Invalid clockTolerance option input");const{currentDate:_}=r,g=Ki("currentDate option",Ui(void 0===_?new Date:_)),y=Ji(n,"iat",void 0!==u),w=Ji(n,"nbf");if(void 0!==w&&w>g+p)throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed',n,"nbf",Bi);const b=Ji(n,"exp");if(void 0!==b&&b<=g-p)throw new JWTExpired('"exp" claim timestamp check failed',n,"exp",Bi);if(void 0!==u){const e=g-y,t=Ki("maxTokenAge option","number"==typeof u?u:qi(u));if(t<0)throw new TypeError("Invalid maxTokenAge option input");if(e-p>t)throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)',n,"iat",Bi);if(e<-p)throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',n,"iat",Bi)}return n}let Xi,Yi;function Zi(e){return Xi.get(e)}async function es(e,t,r){const[n,i]=await async function(e,t,r){if(e instanceof Uint8Array&&(e=si.decode(e)),"string"!=typeof e)throw new JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:s,length:o}=e.split(".");if(3!==o)throw new JWSInvalid("Invalid Compact JWS");return $i({payload:i,protected:n,signature:s},t,r,Li)}(e,function(e){return[e&&yi("algorithms",e.algorithms),e?.crit]}(r),t);if(!i)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");const s=Vi(n.protectedHeader,n.payload,r);return{...n,payload:s}}async function ts(e,t,r){const n=e.get(t)||e.set(t,{}).get(t),{alg:i}=r;if(void 0===n[i]){const e=Oi(r,t,!0).then(e=>{if("public"!==e.type)throw new JWKSInvalid("JSON Web Key Set members must be public keys");return n[i]=e,e}).catch(t=>{throw n[i]===e&&delete n[i],t});n[i]=e}return n[i]}function rs(e){let t;try{t=structuredClone(e)}catch(e){throw new JWKSInvalid("JSON Web Key Set malformed",{cause:e})}if(!fi(t))throw new JWKSInvalid("JSON Web Key Set malformed");const r=t.keys.map(e=>{const t=Pi(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),n=new WeakMap;return Object.defineProperty(async(e,i)=>{const{alg:s,kid:o}={...e,...i?.header},a="string"==typeof s?ri[s]:void 0;if(!a||a.secret)throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');const c=t.keys.filter((e,t)=>function(e,t,r,n){const{kty:i,key_ops:s,ext:o,kid:a,alg:c,use:u,crv:l}=e;return(void 0===o||"boolean"==typeof o)&&(void 0===s||Array.isArray(s)&&s.every((e,t)=>"string"==typeof e&&s.indexOf(e)===t)&&s.includes("verify"))&&t.kty.includes(i)&&(void 0===n||"string"==typeof n&&n===a)&&(void 0===c?"AKP"!==i:r===c)&&(void 0===u||"sig"===u)&&(!t.crv||l===t.crv)}(r[t],a,s,o)),{0:u,length:l}=c;if(!l)throw new JWKSNoMatchingKey;if(1!==l){const e=new JWKSMultipleMatchingKeys;throw e[Symbol.asyncIterator]=async function*(){for(const e of c)try{yield await ts(n,e,a)}catch{}},e}return ts(n,u,a)},"jwks",{value:()=>structuredClone(t)})}(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Yi="jose/v6.2.17");const ns=Symbol();const is=Symbol();function ss(e,t){return Number.isFinite(e)&&Date.now()<e+t}function os(e,t,r){if(Number.isNaN(e))throw new TypeError(`"${r}" option must not be NaN`);if("number"==typeof e&&e<0)throw new TypeError(`"${r}" option must not be negative`);return"number"==typeof e?e:t}function as(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");const r=new URL(e.href).href,n=t??{},i=n.timeoutDuration;if("number"==typeof i&&(!Number.isInteger(i)||i<0))throw new TypeError('"timeoutDuration" option must be a non-negative integer');const s="number"==typeof i?i:5e3,o=os(n.cooldownDuration,3e4,"cooldownDuration"),a=os(n.cacheMaxAge,6e5,"cacheMaxAge"),c=new Headers(n.headers);Yi&&!c.has("User-Agent")&&c.set("User-Agent",Yi),c.has("accept")||c.set("accept","application/json, application/jwk-set+json");const u=n[ns],l=n[is];let h,d,f,p=0,_=0;if(l&&"object"==typeof l){const{uat:e,jwks:t}=l;ss(e,a)&&fi(t)&&(h=e,f=rs(t))}const g=async()=>{if(d&&(typeof WebSocketPair<"u"||typeof navigator<"u"&&"Cloudflare-Workers"===navigator.userAgent||typeof EdgeRuntime<"u"&&"vercel"===EdgeRuntime)&&(d=void 0),!d){const e=++p,t=d=async function(e,t,r,n=fetch){const i=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(e=>{throw"TimeoutError"===e.name?new JWKSTimeout(void 0,{cause:e}):e});if(200!==i.status)throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch(e){throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON",{cause:e})}}(r,c,AbortSignal.timeout(s),u).then(t=>{const r=rs(t);if(e<=_)return;f=r;const n=Date.now();l&&(l.uat=n,l.jwks=t),h=n,_=e}).finally(()=>{d===t&&(d=void 0)})}await d};return Object.defineProperties(async(e,t)=>{(!f||!ss(h,a))&&await g();try{return await f(e,t)}catch(r){if(r instanceof JWKSNoMatchingKey&&!ss(h,o))return await g(),f(e,t);throw r}},{coolingDown:{get:()=>ss(h,o),enumerable:!0},fresh:{get:()=>ss(h,a),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!d,enumerable:!0},jwks:{value:()=>f?.jwks(),enumerable:!0}})}async function cs(e){if(Ei(e)){if("secret"!==e.type)return e.export({format:"jwk"});e=e.export()}if(e instanceof Uint8Array)return{kty:"oct",k:hi(e)};if(!xi(e))throw new TypeError(((e,...t)=>Ri("Key must be ",e,...t))(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const t=await crypto.subtle.exportKey("jwk",e);delete t.ext,delete t.key_ops,delete t.use,"AKP"!==t.kty&&delete t.alg;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return t}async function us(e,t,r){let[n,i,s,o]=e,a="";if(void 0!==i){const e=mi(JWSInvalid,i);i=e[0],a=hi(e[1])}if(void 0!==s&&(s=mi(JWSInvalid,s)[0]),!i&&!s)throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!pi(i,s))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const c={...i,...s};!function(e,t){const{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}(JWSInvalid,i);const u=bi(i,wi(JWSInvalid,gi,o,i,c));u||r?.();const{alg:l}=c;if("string"!=typeof l||!l)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');const h=ni(l);let d,f="",p=n;if(u){const t=e[4];t?(f=t[0]??=hi(n),p=t[1]??=ui(f)):(f=hi(n),d=ii.encode(`${a}.${f}`))}d??=ai(ui(a),ui("."),p);const _=await Ci(await vi(h,t,"sign"),h.subtle,"sign");h.minRsaBits&&ji(h.alg,_);const g={signature:hi(new Uint8Array(await crypto.subtle.sign(h.signing,_,d))),payload:f};return i&&(g.protected=a),s&&(g.header=s),[g,u]}const ls=class JWTClaimsBuilder{constructor(e={}){if(!di(e))throw new TypeError("JWT Claims Set MUST be an object");(Xi||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Wi("iss",e),Zi(this).iss=e,this}setSubject(e){return Wi("sub",e),Zi(this).sub=e,this}setAudience(e){return function(e){if("string"!=typeof e&&(!Array.isArray(e)||Array.from(e).some(e=>"string"!=typeof e)))throw new TypeError('"aud" claim must be a string or an array of strings')}(e),Zi(this).aud=e,this}setJti(e){return Wi("jti",e),Zi(this).jti=e,this}setNotBefore(e){return Zi(this).nbf=Hi(e,"setNotBefore"),this}setExpirationTime(e){return Zi(this).exp=Hi(e,"setExpirationTime"),this}setIssuedAt(e){const t=Zi(this);return t.iat=void 0===e?Ui(new Date):"string"==typeof e?Ki("setIssuedAt",Ui(new Date)+qi(e)):Hi(e,"setIssuedAt"),this}};class SignJWT extends ls{#e;setProtectedHeader(e){return function(e,t){if(void 0!==e)throw new TypeError(`${t} can only be called once`)}(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return async function(e,t,r,n,i){const[s]=await us([e,t,void 0,r],n,i);return`${s.protected}.${s.payload}.${s.signature}`}(function(e){const t=Zi(e);for(const e of["iat","nbf","exp"]){const r=t[e];if("number"==typeof r&&!Number.isFinite(r))throw new TypeError(`"${e}" claim must be a finite number`)}return ii.encode(JSON.stringify(t))}(this),this.#e,t?.crit,e,()=>{throw new JWTInvalid("JWTs MUST NOT use unencoded payload")})}}const hs=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],ds=[[],["deriveBits"]],fs=[[],[]];function ps(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:hs,ops:["wrapKey","unwrapKey"]}}function _s(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:r})=>{if("X25519"===t||"x25519"===r)return{name:"X25519"};if("OKP"===e)throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:ds,ops:[void 0,"deriveBits"]}}function gs(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:fs,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function ys(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:fs,ops:["deriveBits","deriveBits"]}}const ws=Gn({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:fs,ops:["encrypt","decrypt"]},"RSA-OAEP":ps(1),"RSA-OAEP-256":ps(256),"RSA-OAEP-384":ps(384),"RSA-OAEP-512":ps(512),"ECDH-ES":_s("direct-key-agreement"),"ECDH-ES+A128KW":_s("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":_s("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":_s("key-agreement-with-key-wrapping"),A128KW:gs(128),A192KW:gs(192),A256KW:gs(256),A128GCMKW:gs(128,!0),A192GCMKW:gs(192,!0),A256GCMKW:gs(256,!0),"PBES2-HS256+A128KW":ys(),"PBES2-HS384+A192KW":ys(),"PBES2-HS512+A256KW":ys()}),bs=["encrypt","decrypt"];function ms(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:fs,ops:bs,cekBits:e,ivBits:t?128:96,cbc:t}}Gn({A128GCM:ms(128),A192GCM:ms(192),A256GCM:ms(256),"A128CBC-HS256":ms(256,!0),"A192CBC-HS384":ms(384,!0),"A256CBC-HS512":ms(512,!0)});const vs='"alg" (Algorithm)';function Ss(e='JWK "alg" (Algorithm) Parameter'){throw new JOSENotSupported(`Invalid or unsupported ${e} value`)}function Is(e){const t=e?.modulusLength??2048;if("number"!=typeof t||!Number.isInteger(t)||t<2048)throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function xs(e,t){const r=function(e){if(void 0!==e&&"boolean"!=typeof e)throw new TypeError('"extractable" option must be a boolean');return e}(t?.extractable),n=function(e,t){return("string"==typeof e?ri[e]??ws[e]:void 0)??Ss(t)}(e,vs);let i;if(n.secret&&Ss(vs),n.resolve){const e=t?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(e))throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");i=n.resolve({crv:e})}else{if(void 0!==n.crv&&void 0!==t?.crv&&t.crv!==n.crv)throw new JOSENotSupported(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${n.crv}`);i="RSA"===n.kty[0]?{...n.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:Is(t)}:n.subtle}return crypto.subtle.generateKey(i,r??!1,[...n.usages[1],...n.usages[0]])}const Es=new Uint8Array(16);const Ts=[];for(let e=0;e<256;++e)Ts.push((e+256).toString(16).slice(1));function Rs(e,t=0){return(Ts[e[t+0]]+Ts[e[t+1]]+Ts[e[t+2]]+Ts[e[t+3]]+"-"+Ts[e[t+4]]+Ts[e[t+5]]+"-"+Ts[e[t+6]]+Ts[e[t+7]]+"-"+Ts[e[t+8]]+Ts[e[t+9]]+"-"+Ts[e[t+10]]+Ts[e[t+11]]+Ts[e[t+12]]+Ts[e[t+13]]+Ts[e[t+14]]+Ts[e[t+15]]).toLowerCase()}const As=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){e=e||{};const n=e.random??e.rng?.()??crypto.getRandomValues(Es);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 Rs(n)}(e,t,r):crypto.randomUUID()},ks="solidClientAuthn:",js=["ES256","RS256"],Ns="error",Ps="login",Os="logout",Cs="newRefreshToken",Ds="sessionExpired",Ls="sessionExtended",$s="sessionRestore",Us="timeoutSet",Ms=["openid","offline_access","webid"];class AggregateHandler{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 Fs(e,t,r,n){let i,s;try{const{payload:s}=await es(e,as(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 Bs(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 zs(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 AuthorizationCodeWithPkceOidcHandlerBase{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 GeneralLogoutHandler{sessionInfoManager;constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class IRpLogoutHandler{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 IWaterfallLogoutHandler{handlers;constructor(e,t){this.handlers=[new GeneralLogoutHandler(e),new IRpLogoutHandler(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 qs(){return{isLoggedIn:!1,sessionId:As(),fetch:(...e)=>fetch(...e)}}async function Ks(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}class SessionInfoManagerBase{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 Ks(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 Ws({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 Hs(e){try{return new URL(e),!0}catch{return!1}}async function Qs(e,t,r,n){let i;if(function(e,t){return t.scopesSupported.includes("webid")&&void 0!==e.clientId&&Hs(e.clientId)}(e,t))i={clientId:e.clientId,clientName:e.clientName,clientType:"solid-oidc"};else{if(!function(e){return void 0!==e.clientId&&!Hs(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 Js=(e,t)=>fetch(e,t);class dist_ClientAuthentication{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=Js;logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===t?.logoutType?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=Js,delete this.boundLogout};getSessionInfo=async e=>this.sessionInfoManager.get(e);getAllSessionInfo=async()=>this.sessionInfoManager.getAll()}async function Gs(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 StorageUtility{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 InMemoryStorage{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 ConfigurationError extends Error{constructor(e){super(e)}}Error;class InvalidResponseError extends Error{missingFields;constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class OidcProviderError extends Error{error;errorDescription;constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function Vs(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function Xs(e,t,r){return new SignJWT({htu:Vs(e),htm:t.toUpperCase(),jti:As()}).setProtectedHeader({alg:js[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function Ys(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 Xs(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 Zs(e,t,r,n,i=fetch){return i(t,await Ys(t.toString(),e,n,r))}const eo=e=>void 0!==e?e-5>0?e-5:e:600;function to(e,t){let r,n=e;const i=t?.refreshOptions,s=t?.eventEmitter;if(void 0!==t&&void 0!==i){const e=async()=>{try{const{accessToken:o,refreshToken:a,expiresIn:c}=await async function(e,t,r){const n=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return r?.emit(Ls,n.expiresIn??600),{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn}}(i,t.dpopKey,s);n=o,void 0!==a&&(i.refreshToken=a),clearTimeout(r),r=setTimeout(e,1e3*eo(c)),t.eventEmitter?.emit(Us,r)}catch(e){e instanceof OidcProviderError&&(s?.emit(Ns,e.error,e.errorDescription),s?.emit(Ds)),e instanceof InvalidResponseError&&e.missingFields.includes("access_token")&&s?.emit(Ds)}};r=setTimeout(e,1e3*eo(t.expiresIn)),s?.emit(Us,r)}else if(void 0!==s){const e=setTimeout(()=>{s.emit(Ds)},1e3*eo(t?.expiresIn));s.emit(Us,e)}return async(e,r)=>{let i=await Zs(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 Zs(n,i.url,r,t.dpopKey,t.fetch)),i}}class InvalidTokenError extends Error{}function ro(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}(t)}catch(e){return atob(t)}}InvalidTokenError.prototype.name="InvalidTokenError";var no,io,so,oo={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},ao=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(ao||{});(so=ao||(ao={})).reset=function(){no=3,io=oo},so.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");no=e},so.setLogger=function(e){io=e};var co=class _Logger{constructor(e){this._name=e}debug(...e){no>=4&&io.debug(_Logger._format(this._name,this._method),...e)}info(...e){no>=3&&io.info(_Logger._format(this._name,this._method),...e)}warn(...e){no>=2&&io.warn(_Logger._format(this._name,this._method),...e)}error(...e){no>=1&&io.error(_Logger._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const r=new _Logger(`${e}.${t}`);return r.debug("begin"),r}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(e,...t){no>=4&&io.debug(_Logger._format(e),...t)}static info(e,...t){no>=3&&io.info(_Logger._format(e),...t)}static warn(e,...t){no>=2&&io.warn(_Logger._format(e),...t)}static error(e,...t){no>=1&&io.error(_Logger._format(e),...t)}};ao.reset();var uo=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${r+1}`);let i;try{i=ro(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}(e)}catch(e){throw co.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,r){const n=`${fo.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${fo.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,(new TextEncoder).encode(n));return`${n}.${fo.encodeBase64Url(new Uint8Array(i))}`}static async generateSignedJwtWithHmac(e,t,r){const n=`${fo.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${fo.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign("HMAC",r,(new TextEncoder).encode(n));return`${n}.${fo.encodeBase64Url(new Uint8Array(i))}`}},lo=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),ho=class _CryptoUtils{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^_CryptoUtils._randomWord()&15>>+e/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return _CryptoUtils.generateUUIDv4()+_CryptoUtils.generateUUIDv4()+_CryptoUtils.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return lo(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw co.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return lo(r)}static async hash(e,t){const r=(new TextEncoder).encode(t),n=await crypto.subtle.digest(e,r);return new Uint8Array(n)}static async customCalculateJwkThumbprint(e){let t;switch(e.kty){case"RSA":t={e:e.e,kty:e.kty,n:e.n};break;case"EC":t={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":t={crv:e.crv,kty:e.kty,x:e.x};break;case"oct":t={crv:e.k,kty:e.kty};break;default:throw new Error("Unknown jwk type")}const r=await _CryptoUtils.hash("SHA-256",JSON.stringify(t));return _CryptoUtils.encodeBase64Url(r)}static async generateDPoPProof({url:e,accessToken:t,httpMethod:r,keyPair:n,nonce:i}){let s,o;const a={jti:window.crypto.randomUUID(),htm:null!=r?r:"GET",htu:e,iat:Math.floor(Date.now()/1e3)};t&&(s=await _CryptoUtils.hash("SHA-256",t),o=_CryptoUtils.encodeBase64Url(s),a.ath=o),i&&(a.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",n.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await uo.generateSignedJwt(t,a,n.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(e){try{const t=await crypto.subtle.exportKey("jwk",e.publicKey);return await _CryptoUtils.customCalculateJwkThumbprint(t)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(e,t,r,n="HS256"){const i=Math.floor(Date.now()/1e3),s={alg:n,typ:"JWT"},o={iss:e,sub:e,aud:r,jti:_CryptoUtils.generateUUIDv4(),exp:i+300,iat:i},a={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[n];if(!a)throw new Error(`Unsupported algorithm: ${n}. Supported algorithms are: HS256, HS384, HS512`);const c=new TextEncoder,u=await crypto.subtle.importKey("raw",c.encode(t),{name:"HMAC",hash:a},!1,["sign"]);return await uo.generateSignedJwtWithHmac(s,o,u)}};ho.encodeBase64Url=e=>lo(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var fo=ho,po=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new co(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},_o=class _Timer extends po{constructor(){super(...arguments),this._logger=new co(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-_Timer.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=_Timer.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const r=_Timer.getEpochTime()+e;if(this.expiration===r&&this._timerHandle)return void t.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),t.debug("using duration",e),this._expiration=r;const n=Math.min(e,5);this._timerHandle=setInterval(this._callback,1e3*n)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},go=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const r=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(r.slice(1))}},yo=";",wo=class extends Error{constructor(e,t){var r,n,i;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw co.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(r=e.error_description)?r:null,this.error_uri=null!=(n=e.error_uri)?n:null,this.state=e.userState,this.session_state=null!=(i=e.session_state)?i:null,this.url_state=e.url_state}},bo=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},mo=class{constructor(){this._logger=new co("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},vo=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},So=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new co("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...n}=t;if(!r)return await fetch(e,n);const i=new AbortController,s=setTimeout(()=>i.abort(),1e3*r);try{return await fetch(e,{...t,signal:i.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new bo("Network timed out");throw e}finally{clearTimeout(s)}}async getJson(e,{token:t,credentials:r,timeoutInSeconds:n}={}){const i=this._logger.create("getJson"),s={Accept:this._contentTypes.join(", ")};let o;t&&(i.debug("token passed, setting Authorization header"),s.Authorization="Bearer "+t),this._appendExtraHeaders(s);try{i.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:s,timeoutInSeconds:n,credentials:r})}catch(e){throw i.error("Network Error"),e}i.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(e=>a.startsWith(e))&&i.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(i.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(i.error("Error from server:",c),c.error)throw new wo(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:n,initCredentials:i,extraHeaders:s}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...s};let c;void 0!==r&&(a.Authorization="Basic "+r),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:n,credentials:i})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const u=c.headers.get("Content-Type");if(u&&!this._contentTypes.find(e=>u.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=u?u:"undefined"}, from URL: ${e}`);const l=await c.text();let h={};if(l)try{h=JSON.parse(l)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",h),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new vo(e,`${JSON.stringify(h)}`)}if(h.error)throw new wo(h,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(h)}`)}return h}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),n=["accept","content-type"],i=["authorization"];0!==r.length&&r.forEach(r=>{if(n.includes(r.toLocaleLowerCase()))return void t.warn("Protected header could not be set",r,n);if(i.includes(r.toLocaleLowerCase())&&Object.keys(e).includes(r))return void t.warn("Header could not be overridden",r,i);const s="function"==typeof this._extraHeaders[r]?this._extraHeaders[r]():this._extraHeaders[r];s&&""!==s&&(e[r]=s)})}},Io=class{constructor(e){this._settings=e,this._logger=new co("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new So(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const r=this._logger.create(`_getMetadataProperty('${e}')`),n=await this.getMetadata();if(r.debug("resolved"),void 0===n[e]){if(!0===t)return void r.warn("Metadata does not contain optional property");r.throw(new Error("Metadata does not contain property "+e))}return n[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const r=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}},xo=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new co("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let r=0;r<e;r++){const e=await this._store.key(r);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},Eo=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:n,metadataSeed:i,client_id:s,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:u,post_logout_redirect_uri:l,client_authentication:h="client_secret_post",token_endpoint_auth_signing_alg:d="HS256",prompt:f,display:p,max_age:_,ui_locales:g,acr_values:y,resource:w,response_mode:b,filterProtocolClaims:m=!0,loadUserInfo:v=!1,requestTimeoutInSeconds:S,staleStateAgeInSeconds:I=900,mergeClaimsStrategy:x={array:"replace"},disablePKCE:E=!1,stateStore:T,revokeTokenAdditionalContentTypes:R,fetchRequestCredentials:A,refreshTokenAllowedScope:k,extraQueryParams:j={},extraTokenParams:N={},extraHeaders:P={},dpop:O,omitScopeWhenRequesting:C=!1}){var D;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=r,this.metadataSeed=i,this.signingKeys=n,this.client_id=s,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=u,this.post_logout_redirect_uri=l,this.client_authentication=h,this.token_endpoint_auth_signing_alg=d,this.prompt=f,this.display=p,this.max_age=_,this.ui_locales=g,this.acr_values=y,this.resource=w,this.response_mode=b,this.filterProtocolClaims=null==m||m,this.loadUserInfo=!!v,this.staleStateAgeInSeconds=I,this.mergeClaimsStrategy=x,this.omitScopeWhenRequesting=C,this.disablePKCE=!!E,this.revokeTokenAdditionalContentTypes=R,this.fetchRequestCredentials=A||"same-origin",this.requestTimeoutInSeconds=S,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new mo;this.stateStore=new xo({store:e})}if(this.refreshTokenAllowedScope=k,this.extraQueryParams=j,this.extraTokenParams=N,this.extraHeaders=P,this.dpop=O,this.dpop&&!(null==(D=this.dpop)?void 0:D.store))throw new Error("A DPoPStore is required when dpop is enabled")}},To=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new co("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=uo.decode(e);return t.debug("JWT decoding successful"),r}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new So(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const n=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",n),n}},Ro=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new co("TokenClient"),this._jsonService=new So(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:i,...s}){const o=this._logger.create("exchangeCode");r||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),s.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(s))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==n)throw o.throw(new Error("A client_secret is required")),null;let c;const u=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=fo.generateBasicAuth(r,n);break;case"client_secret_post":a.append("client_id",r),n&&a.append("client_secret",n);break;case"client_secret_jwt":{const e=await fo.generateClientAssertionJwt(r,n,u,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",r),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(u,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:n=this._settings.scope,...i}){const s=this._logger.create("exchangeCredentials");t||s.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",n);for(const[e,t]of Object.entries(i))null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw s.throw(new Error("A client_secret is required")),null;let a;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=fo.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break;case"client_secret_jwt":{const e=await fo.generateClientAssertionJwt(t,r,c,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}s.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return s.debug("got response"),u}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:i,...s}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),s.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(s))Array.isArray(t)?t.forEach(t=>a.append(e,t)):null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw o.throw(new Error("A client_secret is required")),null;let c;const u=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=fo.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r);break;case"client_secret_jwt":{const e=await fo.generateClientAssertionJwt(t,r,u,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(u,{body:a,basicAuth:c,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),l}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const i=new URLSearchParams;for(const[t,r]of Object.entries(e))null!=r&&i.set(t,r);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:i,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),r.debug("got response")}},Ao=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new co("ResponseValidator"),this._userInfoService=new To(this._settings,this._metadataService),this._tokenClient=new Ro(this._settings,this._metadataService)}async validateSigninResponse(e,t,r){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t,r),n.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e,"",t.nonce),n.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse"),n=e.isOpenId&&!!e.id_token;n&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,n),r.debug("claims processed")}async validateRefreshResponse(e,t){const r=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),r.debug("claims processed")}validateSignoutResponse(e,t){const r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new wo(e)}_processSigninState(e,t){const r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new wo(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const n=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void n.debug("not loading user info");n.debug("loading user info");const i=await this._userInfoService.getClaims(e.access_token);n.debug("user info claims received from user info endpoint"),r&&i.sub!==e.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(i)),n.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,r){const n=this._logger.create("_processCode");if(e.code){n.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:r,...t.extraTokenParams});Object.assign(e,i)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t,r){var n;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const s=uo.decode(null!=(n=e.id_token)?n:"");if(s.sub||i.throw(new Error("ID Token is missing a subject claim")),r&&s.nonce!==r&&i.throw(new Error("nonce in id_token does not match nonce in client storage")),t){const e=uo.decode(t);s.sub!==e.sub&&i.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&i.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},ko=class _State{constructor(e){this.id=e.id||fo.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=_o.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new co("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(e){return co.createStatic("State","fromStorageString"),Promise.resolve(new _State(JSON.parse(e)))}static async clearStaleState(e,t){const r=co.createStatic("State","clearStaleState"),n=_o.getEpochTime()-t,i=await e.getAllKeys();r.debug("got keys",i);for(let t=0;t<i.length;t++){const s=i[t],o=await e.get(s);let a=!1;if(o)try{const e=await _State.fromStorageString(o);r.debug("got item from key:",s,e.created),e.created<=n&&(a=!0)}catch(e){r.error("Error parsing state for key:",s,e),a=!0}else r.debug("no item in storage for key:",s),a=!0;a&&(r.debug("removed item for key:",s),e.remove(s))}}},jo=class _SigninState extends ko{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo,this.nonce=e.nonce}static async create(e){const t=!0===e.code_verifier?fo.generateCodeVerifier():e.code_verifier||void 0,r=t?await fo.generateCodeChallenge(t):void 0;return new _SigninState({...e,code_verifier:t,code_challenge:r})}toStorageString(){return new co("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo,nonce:this.nonce})}static fromStorageString(e){co.createStatic("SigninState","fromStorageString");const t=JSON.parse(e);return _SigninState.create(t)}},No=class _SigninRequest{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:t,client_id:r,redirect_uri:n,response_type:i,scope:s,state_data:o,response_mode:a,request_type:c,client_secret:u,nonce:l,url_state:h,resource:d,skipUserInfo:f,extraQueryParams:p,extraTokenParams:_,disablePKCE:g,dpopJkt:y,omitScopeWhenRequesting:w,...b}){if(!e)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!n)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!s)throw this._logger.error("create: No scope passed"),new Error("scope");if(!t)throw this._logger.error("create: No authority passed"),new Error("authority");const m=await jo.create({data:o,request_type:c,url_state:h,code_verifier:!g,client_id:r,authority:t,redirect_uri:n,response_mode:a,client_secret:u,scope:s,extraTokenParams:_,skipUserInfo:f,nonce:l}),v=new URL(e);v.searchParams.append("client_id",r),v.searchParams.append("redirect_uri",n),v.searchParams.append("response_type",i),w||v.searchParams.append("scope",s),l&&v.searchParams.append("nonce",l),y&&v.searchParams.append("dpop_jkt",y);let S=m.id;if(h&&(S=`${S}${yo}${h}`),v.searchParams.append("state",S),m.code_challenge&&(v.searchParams.append("code_challenge",m.code_challenge),v.searchParams.append("code_challenge_method","S256")),d){(Array.isArray(d)?d:[d]).forEach(e=>v.searchParams.append("resource",e))}for(const[e,t]of Object.entries({response_mode:a,...b,...p}))null!=t&&v.searchParams.append(e,t.toString());return new _SigninRequest({url:v.href,state:m})}};No._logger=new co("SigninRequest");var Po=No,Oo=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(yo);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(yo))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-_o.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+_o.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},Co=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:n,extraQueryParams:i,request_type:s,client_id:o,url_state:a}){if(this._logger=new co("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(r&&c.searchParams.append("id_token_hint",r),o&&c.searchParams.append("client_id",o),n&&(c.searchParams.append("post_logout_redirect_uri",n),t||a)){this.state=new ko({data:t,request_type:s,url_state:a});let e=this.state.id;a&&(e=`${e}${yo}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...i}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},Do=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(yo);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(yo))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},Lo=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],$o=["sub","iss","aud","exp","iat"],Uo=class{constructor(e){this._settings=e,this._logger=new co("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:Lo;for(const r of e)$o.includes(r)||delete t[r]}return t}mergeClaims(e,t){const r={...e};for(const[e,n]of Object.entries(t))if(r[e]!==n)if(Array.isArray(r[e])||Array.isArray(n))if("replace"==this._settings.mergeClaimsStrategy.array)r[e]=n;else{const t=Array.isArray(r[e])?r[e]:[r[e]];for(const e of Array.isArray(n)?n:[n])t.includes(e)||t.push(e);r[e]=t}else"object"==typeof r[e]&&"object"==typeof n?r[e]=this.mergeClaims(r[e],n):r[e]=n;return r}},Mo=class{constructor(e,t){this.keys=e,this.nonce=t}},Fo=class{constructor(e,t){this._logger=new co("OidcClient"),this.settings=e instanceof Eo?e:new Eo(e),this.metadataService=null!=t?t:new Io(this.settings),this._claimsService=new Uo(this.settings),this._validator=new Ao(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Ro(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:n,id_token_hint:i,login_hint:s,skipUserInfo:o,nonce:a,url_state:c,response_type:u=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:h=this.settings.redirect_uri,prompt:d=this.settings.prompt,display:f=this.settings.display,max_age:p=this.settings.max_age,ui_locales:_=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:y=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:b=this.settings.extraQueryParams,extraTokenParams:m=this.settings.extraTokenParams,dpopJkt:v,omitScopeWhenRequesting:S=this.settings.omitScopeWhenRequesting}){const I=this._logger.create("createSigninRequest");if("code"!==u)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const x=await this.metadataService.getAuthorizationEndpoint();I.debug("Received authorization endpoint",x);const E=await Po.create({url:x,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:h,response_type:u,scope:l,state_data:e,url_state:c,prompt:d,display:f,max_age:p,ui_locales:_,id_token_hint:i,login_hint:s,acr_values:g,dpopJkt:v,resource:y,request:t,request_uri:r,extraQueryParams:b,extraTokenParams:m,request_type:n,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:S});await this.clearStaleState();const T=E.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),E}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),n=new Oo(go.readParams(e,this.settings.response_mode));if(!n.state)throw r.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[t?"remove":"get"](n.state);if(!i)throw r.throw(new Error("No matching state found in storage")),null;return{state:await jo.fromStorageString(i),response:n}}async processSigninResponse(e,t,r=!0){const n=this._logger.create("processSigninResponse"),{state:i,response:s}=await this.readSigninResponseState(e,r);if(n.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(s,i,t)}catch(e){if(!(e instanceof vo&&this.settings.dpop))throw e;{const r=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=r,await this._validator.validateSigninResponse(s,i,t)}}return s}async getDpopProof(e,t){let r,n;return(await e.getAllKeys()).includes(this.settings.client_id)?(n=await e.get(this.settings.client_id),n.nonce!==t&&t&&(n.nonce=t,await e.set(this.settings.client_id,n))):(r=await fo.generateDPoPKeys(),n=new Mo(r,t),await e.set(this.settings.client_id,n)),await fo.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:n={}}){const i=await this._tokenClient.exchangeCredentials({username:e,password:t,...n}),s=new Oo(new URLSearchParams);return Object.assign(s,i),await this._validator.validateCredentialsResponse(s,r),s}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:i,extraTokenParams:s}){var o;const a=this._logger.create("useRefreshToken");let c,u;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:e}}try{u=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:i,...s})}catch(o){if(!(o instanceof vo&&this.settings.dpop))throw o;i.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),u=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:i,...s})}const l=new Oo(new URLSearchParams);return Object.assign(l,u),a.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:n,url_state:i,post_logout_redirect_uri:s=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),r||!s||t||(r=this.settings.client_id);const u=new Co({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:s,state_data:e,extraQueryParams:o,request_type:n,url_state:i});await this.clearStaleState();const l=u.state;return l&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),u}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),n=new Do(go.readParams(e,this.settings.response_mode));if(!n.state){if(r.debug("No state in response"),n.error)throw r.warn("Response was error:",n.error),new wo(n);return{state:void 0,response:n}}const i=await this.settings.stateStore[t?"remove":"get"](n.state);if(!i)throw r.throw(new Error("No matching state found in storage")),null;return{state:await ko.fromStorageString(i),response:n}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:n}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,r)):t.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),ko.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}};function Bo(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 zo(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,js.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 Bo(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 qo(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function Ko(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new OidcProviderError(`Token endpoint returned error [${e.error}]${qo(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,qo(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 InvalidResponseError(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new InvalidResponseError(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new InvalidResponseError(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new InvalidResponseError(["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 Wo(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(e=!1){const{privateKey:t,publicKey:r}=await xs(js[0],{extractable:e}),n={privateKey:t,publicKey:await cs(r)};return[n.publicKey.alg]=js,n}(!1),i.DPoP=await Xs(e.tokenEndpoint,"POST",s)),t.clientSecret&&(i.Authorization=`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`);const o={grant_type:r.grantType,redirect_uri:r.redirectUrl,code:r.code,code_verifier:r.codeVerifier,client_id:t.clientId},a={method:"POST",headers:i,body:new URLSearchParams(o).toString()},c=await fetch(e.tokenEndpoint,a),u=Ko(await c.json(),n),{webId:l,clientId:h}=await Fs(u.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:(d=u,void 0!==d.refresh_token&&"string"==typeof d.refresh_token?u.refresh_token:void 0),webId:l,clientId:h,dpopKey:s,expiresIn:u.expires_in};var d}async function Ho(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 Xs(t.tokenEndpoint,"POST",n)});let o={};void 0!==r.clientSecret?o={Authorization:`Basic ${btoa(`${r.clientId}:${r.clientSecret}`)}`}:(e=>{try{return new URL(e),!0}catch{return!1}})(r.clientId)&&(i.client_id=r.clientId);const a=await fetch(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(i).toString(),headers:{...s,...o,"Content-Type":"application/x-www-form-urlencoded"}});let c;try{c=await a.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const u=Ko(c,void 0!==n),{webId:l}=await Fs(u.id_token,t.jwksUri,t.issuer,r.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:"string"==typeof u.refresh_token?u.refresh_token:void 0,webId:l,dpopKey:n,expiresIn:u.expires_in}}class ClientRegistrar{constructor(e){this.storageUtility=e}getClient(e,t){return R(this,void 0,void 0,function*(){const[r,n,i,s]=yield Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]);if(r)return{clientId:r,clientSecret:n,clientName:i,clientType:s};try{const r=yield zo(e,t),n={clientId:r.clientId,clientType:"dynamic"};return r.clientSecret&&(n.clientSecret=r.clientSecret),r.idTokenSignedResponseAlg&&(n.idTokenSignedResponseAlg=r.idTokenSignedResponseAlg),yield this.storageUtility.setForUser(e.sessionId,n,{secure:!1}),r}catch(e){throw new Error(`Client registration failed: [${e}]`,{cause:e})}})}}const Qo="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Jo="http://www.w3.org/2001/XMLSchema#",Go="http://www.w3.org/2000/10/swap/",Vo={xsd:{decimal:`${Jo}decimal`,boolean:`${Jo}boolean`,double:`${Jo}double`,integer:`${Jo}integer`,string:`${Jo}string`},rdf:{type:`${Qo}type`,nil:`${Qo}nil`,first:`${Qo}first`,rest:`${Qo}rest`,langString:`${Qo}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${Go}reify#forSome`,forAll:`${Go}reify#forAll`},log:{implies:`${Go}log#implies`,isImpliedBy:`${Go}log#isImpliedBy`}},{rdf:Xo,xsd:Yo}=Vo;let Zo,ea=0;const ta={namedNode:sa,blankNode:oa,variable:ca,literal:aa,defaultGraph:function(){return Zo},quad:ua,triple:ua,fromTerm:la,fromQuad:ha},ra=ta;class N3DataFactory_Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof N3DataFactory_Term?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 N3DataFactory_NamedNode extends N3DataFactory_Term{get termType(){return"NamedNode"}}class N3DataFactory_Literal extends N3DataFactory_Term{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 N3DataFactory_NamedNode(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?Yo.string:Xo.langString}equals(e){return e instanceof N3DataFactory_Literal?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 N3DataFactory_BlankNode extends N3DataFactory_Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class N3DataFactory_Variable extends N3DataFactory_Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}function na(e,t,r){if(t=t||ta,!e)return t.defaultGraph();switch(e[0]){case"?":return t.variable(e.substr(1));case"_":return t.blankNode(e.substr(2));case'"':if(t===ta)return new N3DataFactory_Literal(e);if('"'===e[e.length-1])return t.literal(e.substr(1,e.length-2));const n=e.lastIndexOf('"',e.length-1);return t.literal(e.substr(1,n-1),"@"===e[n+1]?e.substr(n+2):t.namedNode(e.substr(n+3)));case"[":e=JSON.parse(e);break;default:if(!r||!Array.isArray(e))return t.namedNode(e)}return t.quad(na(e[0],t,!0),na(e[1],t,!0),na(e[2],t,!0),e[3]&&na(e[3],t,!0))}function ia(e,t){if("string"==typeof e)return e;if(e instanceof N3DataFactory_Term&&"Quad"!==e.termType)return e.id;if(!e)return Zo.id;switch(e.termType){case"NamedNode":return e.value;case"BlankNode":return`_:${e.value}`;case"Variable":return`?${e.value}`;case"DefaultGraph":return"";case"Literal":return`"${e.value}"${e.language?`@${e.language}`:e.datatype&&e.datatype.value!==Yo.string?`^^${e.datatype.value}`:""}`;case"Quad":const r=[ia(e.subject,!0),ia(e.predicate,!0),ia(e.object,!0)];return e.graph&&"DefaultGraph"!==e.graph.termType&&r.push(ia(e.graph,!0)),t?r:JSON.stringify(r);default:throw new Error(`Unexpected termType: ${e.termType}`)}}Zo=new class N3DataFactory_DefaultGraph extends N3DataFactory_Term{constructor(){return super(""),Zo||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};class N3DataFactory_Quad extends N3DataFactory_Term{constructor(e,t,r,n){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=n||Zo}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 sa(e){return new N3DataFactory_NamedNode(e)}function oa(e){return new N3DataFactory_BlankNode(e||"n3-"+ea++)}function aa(e,t){if("string"==typeof t)return new N3DataFactory_Literal(`"${e}"@${t.toLowerCase()}`);let r=t?t.value:"";return""===r&&("boolean"==typeof e?r=Yo.boolean:"number"==typeof e&&(Number.isFinite(e)?r=Number.isInteger(e)?Yo.integer:Yo.double:(r=Yo.double,Number.isNaN(e)||(e=e>0?"INF":"-INF")))),""===r||r===Yo.string?new N3DataFactory_Literal(`"${e}"`):new N3DataFactory_Literal(`"${e}"^^${r}`)}function ca(e){return new N3DataFactory_Variable(e)}function ua(e,t,r,n){return new N3DataFactory_Quad(e,t,r,n)}function la(e){if(e instanceof N3DataFactory_Term)return e;switch(e.termType){case"NamedNode":return sa(e.value);case"BlankNode":return oa(e.value);case"Variable":return ca(e.value);case"DefaultGraph":return Zo;case"Literal":return aa(e.value,e.language||e.datatype);case"Quad":return ha(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function ha(e){if(e instanceof N3DataFactory_Quad)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return ua(la(e.subject),la(e.predicate),la(e.object),la(e.graph))}function da(e){return!!e&&"DefaultGraph"===e.termType}function fa(e){return e.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}const pa=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,_a=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/;class BaseIRI_BaseIRI{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!pa.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!BaseIRI_BaseIRI.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",fa(e)],r=[],n=[],i=/[^/?#]*([/?#])/y;let s,o=0,a=0,c=i.lastIndex=e.length;for(;!o&&!a&&(s=i.exec(this.base));)"#"===s[1]?a=i.lastIndex-1:(t.push(fa(s[0]),"(?:"),r.push(")?"),"?"!==s[1]?n.push(c=i.lastIndex):(o=c=i.lastIndex,a=this.base.indexOf("#",o),this._pathReplacements[o]="?"));for(let e=0;e<n.length;e++)this._pathReplacements[n[e]]="../".repeat(n.length-e-1);return this._pathReplacements[n[n.length-1]]="./",this._baseLength=a>0?a:this.base.length,t.push(fa(this.base.substring(c,this._baseLength)),o?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...r].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const r=t[0].length;if(r===this._baseLength&&r===e.length)return"";const n=this._pathReplacements[r];if(n){const t=e.substring(r);return"?"===n||_a.test(t)?"./"===n&&/^[^?#]/.test(t)?t:n+t:e}return e.substring(r-1)}}const ga=ra.defaultGraph(),{rdf:ya,xsd:wa}=Vo,ba=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,ma=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,va={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class N3Writer_SerializedTerm extends N3DataFactory_Term{equals(e){return e===this}}class N3Writer_N3Writer{constructor(e,t){if(this._prefixRegex=/$0^/,e&&"function"!=typeof e.write&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=void 0===t.end||!!t.end;else{let e="";this._outputStream={write(t,r,n){e+=t,n&&n()},end:t=>{t&&t(null,e)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=ga,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseIri=new BaseIRI_BaseIRI(t.baseIRI)))}get _inDefaultGraph(){return ga.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,r,n,i){try{n.equals(this._graph)||(this._write((null===this._subject?"":this._inDefaultGraph?".\n":"\n}\n")+(ga.equals(n)?"":`${this._encodeIriOrBlank(n)} {\n`)),this._graph=n,this._subject=null),e.equals(this._subject)?t.equals(this._predicate)?this._write(`, ${this._encodeObject(r)}`,i):this._write(`;\n ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i):this._write(`${(null===this._subject?"":".\n")+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i)}catch(e){i&&i(e)}}_writeQuadLine(e,t,r,n,i){delete this._prefixMatch,this._write(this.quadToString(e,t,r,n),i)}quadToString(e,t,r,n){return`${this._encodeSubject(e)} ${this._encodeIriOrBlank(t)} ${this._encodeObject(r)}${n&&n.value?` ${this._encodeIriOrBlank(n)} .\n`:" .\n"}`}quadsToString(e){let t="";for(const r of e)t+=this.quadToString(r.subject,r.predicate,r.object,r.graph);return t}_encodeSubject(e){return"Quad"===e.termType?this._encodeQuad(e):this._encodeIriOrBlank(e)}_encodeIriOrBlank(e){if("NamedNode"!==e.termType)return this._lists&&e.value in this._lists&&(e=this.list(this._lists[e.value])),"id"in e?e.id:`_:${e.value}`;let t=e.value;this._baseIri&&(t=this._baseIri.toRelative(t)),ba.test(t)&&(t=t.replace(ma,Sa));const r=this._prefixRegex.exec(t);return r?r[1]?this._prefixIRIs[r[1]]+r[2]:t:`<${t}>`}_encodeLiteral(e){let t=e.value;if(ba.test(t)&&(t=t.replace(ma,Sa)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===wa.string)return`"${t}"`}else switch(e.datatype.value){case wa.string:return`"${t}"`;case wa.boolean:if("true"===t||"false"===t)return t;break;case wa.integer:if(/^[+-]?\d+$/.test(t))return t;break;case wa.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case wa.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===ya.type?"a":this._encodeIriOrBlank(e)}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:r,graph:n}){return`<<${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(r)}${da(n)?"":` ${this._encodeIriOrBlank(n)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,r,n,i){void 0===r?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):"function"==typeof n?this._writeQuad(e,t,r,ga,n):this._writeQuad(e,t,r,n||ga,i)}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}addPrefix(e,t,r){const n={};n[e]=t,this.addPrefixes(n,r)}addPrefixes(e,t){if(!this._prefixIRIs)return t&&t();let r=!1;for(let t in e){let n=e[t];"string"!=typeof n&&(n=n.value),r=!0,null!==this._subject&&(this._write(this._inDefaultGraph?".\n":"\n}\n"),this._subject=null,this._graph=""),this._prefixIRIs[n]=t+=":",this._write(`@prefix ${t} <${n}>.\n`)}if(r){let e="",t="";for(const r in this._prefixIRIs)e+=e?`|${r}`:r,t+=(t?"|":"")+this._prefixIRIs[r];e=fa(e),this._prefixRegex=new RegExp(`^(?:${t})[^/]*$|^(${e})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(r?"\n":"",t)}blank(e,t){let r,n,i=e;switch(void 0===e?i=[]:e.termType?i=[{predicate:e,object:t}]:"length"in e||(i=[e]),n=i.length){case 0:return new N3Writer_SerializedTerm("[]");case 1:if(r=i[0],!(r.object instanceof N3Writer_SerializedTerm))return new N3Writer_SerializedTerm(`[ ${this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)} ]`);default:let t="[";for(let s=0;s<n;s++)r=i[s],r.predicate.equals(e)?t+=`, ${this._encodeObject(r.object)}`:(t+=`${(s?";\n ":"\n ")+this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)}`,e=r.predicate);return new N3Writer_SerializedTerm(`${t}\n]`)}}list(e){const t=e&&e.length||0,r=new Array(t);for(let n=0;n<t;n++)r[n]=this._encodeObject(e[n]);return new N3Writer_SerializedTerm(`(${r.join(" ")})`)}end(e){null!==this._subject&&(this._write(this._inDefaultGraph?".\n":"\n}\n"),this._subject=null),this._write=this._blockedWrite;let t=e&&((r,n)=>{t=null,e(r,n)});if(this._endStream)try{return this._outputStream.end(t)}catch(e){}t&&t()}}function Sa(e){let t=va[e];return void 0===t&&(1===e.length?(t=e.charCodeAt(0).toString(16),t="\\u0000".substr(0,6-t.length)+t):(t=(1024*(e.charCodeAt(0)-55296)+e.charCodeAt(1)+9216).toString(16),t="\\U00000000".substr(0,10-t.length)+t)),t}const Ia=Symbol("iter");function xa(e,t,r=4){if(0===r)return Object.assign(e,t);for(const n in t)e[n]=xa(e[n]||Object.create(null),t[n],r-1);return e}function Ea(e,t,r=4){let n=!1;for(const i in e)if(i in t){const s=0===r?null:Ea(e[i],t[i],r-1);if(!1!==s)n=n||Object.create(null),n[i]=s;else if(3===r)return!1}return n}function Ta(e,t,r=4){let n=!1;for(const i in e)if(i in t){if(0!==r){const s=Ta(e[i],t[i],r-1);if(!1!==s)n=n||Object.create(null),n[i]=s;else if(3===r)return!1}}else n=n||Object.create(null),n[i]=0===r?null:xa({},e[i],r-1);return n}class N3Store_N3EntityIndex{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||ra}_termFromId(e){if("."===e[0]){const t=this._entities,r=e.split(".");return this._factory.quad(this._termFromId(t[r[1]]),this._termFromId(t[r[2]]),this._termFromId(t[r[3]]),r[4]&&this._termFromId(t[r[4]]))}return na(e,this._factory)}_termToNumericId(e){if("Quad"===e.termType){const t=this._termToNumericId(e.subject),r=this._termToNumericId(e.predicate),n=this._termToNumericId(e.object);let i;return t&&r&&n&&(da(e.graph)||(i=this._termToNumericId(e.graph)))&&this._ids[i?`.${t}.${r}.${n}.${i}`:`.${t}.${r}.${n}`]}return this._ids[ia(e)]}_termToNewNumericId(e){const t=e&&"Quad"===e.termType?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${da(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:ia(e);return this._ids[t]||(this._ids[this._entities[++this._id]=t]=this._id)}createBlankNode(e){let t,r;if(e)for(t=e=`_:${e}`,r=1;this._ids[t];)t=e+r++;else do{t="_:b"+this._blankNodeIndex++}while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}class N3Store_N3Store{constructor(e,t){this._size=0,this._graphs=Object.create(null),t||!e||e[0]||"function"==typeof e.match||(t=e,e=null),t=t||{},this._factory=t.factory||ra,this._entityIndex=t.entityIndex||new N3Store_N3EntityIndex({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addAll(e)}get size(){let e=this._size;if(null!==e)return e;e=0;const t=this._graphs;let r,n;for(const i in t)for(const s in r=t[i].subjects)for(const t in n=r[s])e+=Object.keys(n[t]).length;return this._size=e}_addToIndex(e,t,r,n){const i=e[t]||(e[t]={}),s=i[r]||(i[r]={}),o=n in s;return o||(s[n]=null),!o}_removeFromIndex(e,t,r,n){const i=e[t],s=i[r];delete s[n];for(const e in s)return;delete i[r];for(const e in i)return;delete e[t]}*_findInIndex(e,t,r,n,i,s,o,a){let c,u,l;const h=this._entities,d=this._termFromId(h[a]),f={subject:null,predicate:null,object:null};t&&((c=e,e={})[t]=c[t]);for(const t in e)if(u=e[t]){f[i]=this._termFromId(h[t]),r&&((c=u,u={})[r]=c[r]);for(const e in u)if(l=u[e]){f[s]=this._termFromId(h[e]);const t=n?n in l?[n]:[]:Object.keys(l);for(let e=0;e<t.length;e++)f[o]=this._termFromId(h[t[e]]),yield this._factory.quad(f.subject,f.predicate,f.object,d)}}}_loop(e,t){for(const r in e)t(r)}_loopByKey0(e,t,r){let n,i;if(n=e[t])for(i in n)r(i)}_loopByKey1(e,t,r){let n,i;for(n in e)i=e[n],i[t]&&r(n)}_loopBy2Keys(e,t,r,n){let i,s,o;if((i=e[t])&&(s=i[r]))for(o in s)n(o)}_countInIndex(e,t,r,n){let i,s,o,a=0;t&&((i=e,e={})[t]=i[t]);for(const t in e)if(s=e[t]){r&&((i=s,s={})[r]=i[r]);for(const e in s)(o=s[e])&&(n?n in o&&a++:a+=Object.keys(o).length)}return a}_getGraphs(e){return"number"!=typeof(e=""===e?1:e&&(this._termToNumericId(e)||-1))?this._graphs:{[e]:this._graphs[e]}}_uniqueEntities(e){const t=Object.create(null);return r=>{r in t||(t[r]=!0,e(this._termFromId(this._entities[r],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,r,n){t||(n=e.graph,r=e.object,t=e.predicate,e=e.subject),n=n?this._termToNewNumericId(n):1;let i=this._graphs[n];return i||(i=this._graphs[n]={subjects:{},predicates:{},objects:{}},Object.freeze(i)),e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),r=this._termToNewNumericId(r),!!this._addToIndex(i.subjects,e,t,r)&&(this._addToIndex(i.predicates,t,r,e),this._addToIndex(i.objects,r,e,t),this._size=null,!0)}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}delete(e){return this.removeQuad(e),this}has(e,t,r,n){return e&&e.subject&&({subject:e,predicate:t,object:r,graph:n}=e),!this.readQuads(e,t,r,n).next().done}import(e){return e.on("data",e=>{this.addQuad(e)}),e}removeQuad(e,t,r,n){t||({subject:e,predicate:t,object:r,graph:n}=e),n=n?this._termToNumericId(n):1;const i=this._graphs;let s,o,a;if(!((e=e&&this._termToNumericId(e))&&(t=t&&this._termToNumericId(t))&&(r=r&&this._termToNumericId(r))&&(s=i[n])&&(o=s.subjects[e])&&(a=o[t])&&r in a))return!1;for(e in this._removeFromIndex(s.subjects,e,t,r),this._removeFromIndex(s.predicates,t,r,e),this._removeFromIndex(s.objects,r,e,t),null!==this._size&&this._size--,s.subjects)return!0;return delete i[n],!0}removeQuads(e){for(let t=0;t<e.length;t++)this.removeQuad(e[t])}remove(e){return e.on("data",e=>{this.removeQuad(e)}),e}removeMatches(e,t,r,n){const i=new(p().Readable)({objectMode:!0}),s=this.readQuads(e,t,r,n);return i._read=e=>{for(;--e>=0;){const{done:e,value:t}=s.next();if(e)return void i.push(null);i.push(t)}},this.remove(i)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,r,n){return[...this.readQuads(e,t,r,n)]}*readQuads(e,t,r,n){const i=this._getGraphs(n);let s,o,a,c;if(!(e&&!(o=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(const e in i)(s=i[e])&&(o?c?yield*this._findInIndex(s.objects,c,o,a,"object","subject","predicate",e):yield*this._findInIndex(s.subjects,o,a,null,"subject","predicate","object",e):a?yield*this._findInIndex(s.predicates,a,c,null,"predicate","object","subject",e):c?yield*this._findInIndex(s.objects,c,null,null,"object","subject","predicate",e):yield*this._findInIndex(s.subjects,null,null,null,"subject","predicate","object",e))}match(e,t,r,n){return new N3Store_DatasetCoreAndReadableStream(this,e,t,r,n,{entityIndex:this._entityIndex})}countQuads(e,t,r,n){const i=this._getGraphs(n);let s,o,a,c,u=0;if(e&&!(o=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r)))return 0;for(const n in i)(s=i[n])&&(u+=e?r?this._countInIndex(s.objects,c,o,a):this._countInIndex(s.subjects,o,a,c):t?this._countInIndex(s.predicates,a,c,o):this._countInIndex(s.objects,c,o,a));return u}forEach(e,t,r,n,i){this.some(t=>(e(t,this),!1),t,r,n,i)}every(e,t,r,n,i){return!this.some(t=>!e(t,this),t,r,n,i)}some(e,t,r,n,i){for(const s of this.readQuads(t,r,n,i))if(e(s,this))return!0;return!1}getSubjects(e,t,r){const n=[];return this.forSubjects(e=>{n.push(e)},e,t,r),n}forSubjects(e,t,r,n){const i=this._getGraphs(n);let s,o,a;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(s=i[n])&&(o?a?this._loopBy2Keys(s.predicates,o,a,e):this._loopByKey1(s.subjects,o,e):a?this._loopByKey0(s.objects,a,e):this._loop(s.subjects,e))}getPredicates(e,t,r){const n=[];return this.forPredicates(e=>{n.push(e)},e,t,r),n}forPredicates(e,t,r,n){const i=this._getGraphs(n);let s,o,a;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(s=i[n])&&(o?a?this._loopBy2Keys(s.objects,a,o,e):this._loopByKey0(s.subjects,o,e):a?this._loopByKey1(s.predicates,a,e):this._loop(s.predicates,e))}getObjects(e,t,r){const n=[];return this.forObjects(e=>{n.push(e)},e,t,r),n}forObjects(e,t,r,n){const i=this._getGraphs(n);let s,o,a;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(s=i[n])&&(o?a?this._loopBy2Keys(s.subjects,o,a,e):this._loopByKey1(s.objects,o,e):a?this._loopByKey0(s.predicates,a,e):this._loop(s.objects,e))}getGraphs(e,t,r){const n=[];return this.forGraphs(e=>{n.push(e)},e,t,r),n}forGraphs(e,t,r,n){for(const i in this._graphs)this.some(t=>(e(t.graph),!0),t,r,n,this._termFromId(this._entities[i]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1}={}){const r={},n=t?()=>!0:(e,t)=>{throw new Error(`${e.value} ${t}`)},i=this.getQuads(null,Vo.rdf.rest,Vo.rdf.nil,null),s=e?[...i]:[];return i.forEach(t=>{const i=[];let o,a,c=!1;const u=t.graph;let l=t.subject;for(;l&&!c;){const e=this.getQuads(null,null,l,null),t=this.getQuads(l,null,null,null);let r,h=null,d=null,f=null;for(let i=0;i<t.length&&!c;i++)r=t[i],r.graph.equals(u)?o?c=n(l,"has non-list arcs out"):r.predicate.value===Vo.rdf.first?h?c=n(l,"has multiple rdf:first arcs"):s.push(h=r):r.predicate.value===Vo.rdf.rest?d?c=n(l,"has multiple rdf:rest arcs"):s.push(d=r):e.length?c=n(l,"can't be subject and object"):(o=r,a="subject"):c=n(l,"not confined to single graph");for(let t=0;t<e.length&&!c;++t)r=e[t],o?c=n(l,"can't have coreferences"):r.predicate.value===Vo.rdf.rest?f?c=n(l,"has incoming rdf:rest arcs"):f=r:(o=r,a="object");h?i.unshift(h.object):c=n(l,"has no list head"),l=f&&f.subject}c?e=!1:o&&(r[o[a].value]=i)}),e&&this.removeQuads(s),r}addAll(e){if(e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),Array.isArray(e))this.addQuads(e);else if(e instanceof N3Store_N3Store&&e._entityIndex===this._entityIndex)0!==e._size&&(this._graphs=xa(this._graphs,e._graphs),this._size=null);else for(const t of e)this.add(t);return this}contains(e){if(e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return!0;if(!(e instanceof N3Store_N3Store)||this._entityIndex!==e._entityIndex)return e.every(e=>this.has(e));const t=this._graphs,r=e._graphs;let n,i,s,o,a;for(const e in r){if(!(n=t[e]))return!1;n=n.subjects;for(const t in i=r[e].subjects){if(!(s=n[t]))return!1;for(const e in o=i[t]){if(!(a=s[e]))return!1;for(const t in o[e])if(!(t in a))return!1}}}return!0}deleteMatches(e,t,r,n){for(const i of this.match(e,t,r,n))this.removeQuad(i);return this}difference(e){if(e&&e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return new N3Store_N3Store({entityIndex:this._entityIndex});if(e instanceof N3Store_N3Store&&e._entityIndex===this._entityIndex){const t=new N3Store_N3Store({entityIndex:this._entityIndex}),r=Ta(this._graphs,e._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>!e.has(t))}equals(e){return e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new N3Store_N3Store({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),e===this){const e=new N3Store_N3Store({entityIndex:this._entityIndex});return e._graphs=xa(Object.create(null),this._graphs),e._size=this._size,e}if(e instanceof N3Store_N3Store&&this._entityIndex===e._entityIndex){const t=new N3Store_N3Store({entityIndex:this._entityIndex}),r=Ea(e._graphs,this._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>e.has(t))}map(e){const t=new N3Store_N3Store({entityIndex:this._entityIndex});for(const r of this)t.add(e(r,this));return t}reduce(e,t){const r=this.readQuads();let n=void 0===t?r.next().value:t;for(const t of r)n=e(n,t,this);return n}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return(new N3Writer_N3Writer).quadsToString(this)}union(e){const t=new N3Store_N3Store({entityIndex:this._entityIndex});return t._graphs=xa(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}}function Ra(e,t,r=0){const n=t[r];if(n&&!(n in e))return!1;let i=!1;for(const s in n?{[n]:e[n]}:e){const n=2===r?null:Ra(e[s],t,r+1);!1!==n&&(i=i||Object.create(null),i[s]=n)}return i}class N3Store_DatasetCoreAndReadableStream extends p().Readable{constructor(e,t,r,n,i,s){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:r,object:n,graph:i,options:s})}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:r,predicate:n,subject:i}=this,s=this._filtered=new N3Store_N3Store({factory:e._factory,entityIndex:this.options.entityIndex});let o,a,c;if(i&&!(o=s._termToNumericId(i))||n&&!(a=s._termToNumericId(n))||r&&!(c=s._termToNumericId(r)))return s;const u=e._getGraphs(t);for(const e in u){let t,r,n,i;(i=u[e])&&(!o&&a?(r=Ra(i.predicates,[a,c,o]))&&(t=Ra(i.subjects,[o,a,c]),n=Ra(i.objects,[c,o,a])):c?(n=Ra(i.objects,[c,o,a]))&&(t=Ra(i.subjects,[o,a,c]),r=Ra(i.predicates,[a,c,o])):(t=Ra(i.subjects,[o,a,c]))&&(r=Ra(i.predicates,[a,c,o]),n=Ra(i.objects,[c,o,a])),t&&(s._graphs[e]={subjects:t,predicates:r,objects:n}))}s._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[Ia]&&(this[Ia]=this[Symbol.iterator]());const t=this[Ia];for(;--e>=0;){const{done:e,value:r}=t.next();if(e)return void this.push(null);this.push(r)}}addAll(e){return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,r,n){return this.filtered.deleteMatches(e,t,r,n)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,r,n,i){return this.filtered.every(e,t,r,n,i)}filter(e){return this.filtered.filter(e)}forEach(e,t,r,n,i){return this.filtered.forEach(e,t,r,n,i)}import(e){return this.filtered.import(e)}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map(e)}some(e,t,r,n,i){return this.filtered.some(e,t,r,n,i)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(e)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce(e,t)}toString(){return(new N3Writer_N3Writer).quadsToString(this)}add(e){return this.filtered.add(e)}delete(e){return this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,r,n){return new N3Store_DatasetCoreAndReadableStream(this.filtered,e,t,r,n,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}const{xsd:Aa}=Vo,ka=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,ja={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},Na=/[\x00-\x20<>\\"\{\}\|\^\`]/,Pa={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},Oa=/$0^/;class N3Lexer_N3Lexer{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 Pa)&&this[e]instanceof RegExp&&(this[e]=Oa)}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,c=r[0];let u="",l="",h="",d=null,f=0,p=!1;switch(c){case"^":if(r.length<3)break;if("^"!==r[1]){this._n3Mode&&(f=1,u="^");break}if(this._previousMarker="^^",r=r.substr(2),"<"!==r[0]){p=!0;break}case"<":if(d=this._unescapedIri.exec(r))u="IRI",l=d[1];else if(d=this._iri.exec(r)){if(l=this._unescape(d[1]),null===l||Na.test(l))return s(this);u="IRI"}else r.length>1&&"<"===r[1]?(u="<<",f=2):this._n3Mode&&r.length>1&&"="===r[1]&&(f=2,this._isImpliedBy?(u="abbreviation",l="<"):(u="inverse",l=">"));break;case">":r.length>1&&">"===r[1]&&(u=">>",f=2);break;case"_":((d=this._blank.exec(r))||t&&(d=this._blank.exec(`${r} `)))&&(u="blank",h="_",l=d[1]);break;case'"':if(d=this._simpleQuotedString.exec(r))l=d[1];else if(({value:l,matchLength:f}=this._parseLiteral(r)),null===l)return s(this);null===d&&0===f||(u="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(d=this._simpleApostropheString.exec(r))l=d[1];else if(({value:l,matchLength:f}=this._parseLiteral(r)),null===l)return s(this);null===d&&0===f||(u="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(d=this._variable.exec(r))&&(u="var",l=d[0]);break;case"@":"literal"===this._previousMarker&&(d=this._langcode.exec(r))?(u="langcode",l=d[1]):(d=this._keyword.exec(r))&&(u=d[0]);break;case".":if(1===r.length?t:r[1]<"0"||r[1]>"9"){u=".",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} `)))&&(u="literal",l=d[0],h="string"==typeof d[1]?Aa.double:"string"==typeof d[2]?Aa.decimal:Aa.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(d=this._sparqlKeyword.exec(r))?u=d[0].toUpperCase():p=!0;break;case"f":case"t":(d=this._boolean.exec(r))?(u="literal",l=d[0],h=Aa.boolean):p=!0;break;case"a":(d=this._shortPredicates.exec(r))?(u="abbreviation",l="a"):p=!0;break;case"=":this._n3Mode&&r.length>1&&(u="abbreviation",">"!==r[1]?(f=1,l="="):(f=2,l=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(f=1,u=c);break;case"{":!this._lineMode&&r.length>=2&&("|"===r[1]?(u="{|",f=2):(u=c,f=1));break;case"|":r.length>=2&&"}"===r[1]&&(u="|}",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} `)))&&(u="prefixed",h=d[1]||"",l=this._unescape(d[2])):(u="prefix",l=d[1]||"")),"^^"===this._previousMarker)switch(u){case"prefixed":u="type";break;case"IRI":u="typeIRI";break;default:u=""}if(!u)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?s(this):this._input=r;const _=f||d[0].length,g=i(u,l,h,a,_);this.previousToken=g,this._previousMarker=u,r=r.substr(_,r.length)}function i(t,i,s,o,a){const c=r?n-r.length:n,u={type:t,value:i,prefix:s,line:o,start:c,end:c+a};return e(null,u),u}function s(t){e(t._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(ka,(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 ja?ja[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,r){if(this._line=1,"string"==typeof e){if(this._input=this._readStartingBom(e),"function"!=typeof r){const e=[];let t;if(this._tokenizeToEnd((r,n)=>r?t=r:e.push(n),!0),t)throw t;return e}queueMicrotask(()=>this._tokenizeToEnd(r,!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=t().Buffer.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(r,!1)))}),e.on("end",()=>{"string"==typeof this._input&&this._tokenizeToEnd(r,!0)}),e.on("error",r)}}let Ca=0;class N3Parser_N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&La(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 N3Lexer_N3Lexer({lineMode:a,n3:o,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){Ca=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=Da}_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${Ca++}_`,this._prefixCallback=i||Da,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=Da):this._readCallback&&(this._readCallback=this._readCallback(t))};s&&(this._lexer.comments=!0,o=(e,t)=>{null!==e?(this._callback(e),this._callback=Da):this._readCallback&&("comment"===t.type?s(t.value):this._readCallback=this._readCallback(t))}),this._callback=n,this._lexer.tokenize(e,o)}}function Da(){}function La(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(Vo.rdf.first),e.RDF_REST=t.namedNode(Vo.rdf.rest),e.RDF_NIL=t.namedNode(Vo.rdf.nil),e.N3_FORALL=t.namedNode(Vo.r.forAll),e.N3_FORSOME=t.namedNode(Vo.r.forSome),e.ABBREVIATIONS={a:t.namedNode(Vo.rdf.type),"=":t.namedNode(Vo.owl.sameAs),">":t.namedNode(Vo.log.implies),"<":t.namedNode(Vo.log.isImpliedBy)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}La(N3Parser_N3Parser.prototype,ra);const $a="http://www.w3.org/ns/solid/notifications#",Ua={subscription:ra.namedNode(`${$a}subscription`),channelType:ra.namedNode(`${$a}channelType`),feature:ra.namedNode(`${$a}feature`),WebhookChannel2023:ra.namedNode(`${$a}WebhookChannel2023`),WebSocketChannel2023:ra.namedNode(`${$a}WebSocketChannel2023`)};async function Ma(e,t=""){const r=new N3Store_N3Store,n=new N3Parser_N3Parser(t?{baseIRI:t}:{});for(const t of n.parse(e))r.add(ra.quad(t.subject,t.predicate,t.object,ra.defaultGraph()));return r}function Fa(e,t){if(e)for(const r of e.split(/,\s*(?=<)/)){const e=r.match(/^\s*<([^>]*)>(.*)$/);if(!e)continue;const n=e[2].match(/;\s*rel\s*=\s*(?:"([^"]*)"|([^;\s,]+))/i);if(!n)continue;if((n[1]??n[2]).split(/\s+/).includes(t))return e[1]}}class DiscoveryClient{constructor(e){this.authnFetch=e,this.rdf={contentType:"text/turtle",parse:Ma}}async findService(e,t){const r=await this.fetchStorageDescription(e),n=(i=r,s=null,o=Ua.channelType,a=ra.namedNode(t),[...i.match(s,o,a,c)].shift())?.subject;var i,s,o,a,c;if(!n)return null;const u=function(e,t,r,n,i){return[...e.match(t,r,n,i)]}(r,n,Ua.feature).map(e=>e.object.value);return{id:n.value,channelType:t,feature:u}}async fetchResource(e){const t=await this.authnFetch(e,{headers:{Accept:this.rdf.contentType}});if(t.status<200||t.status>300)throw Error(`Failed fetching resource: ${e}`);return this.rdf.parse(await t.text(),t.url)}async discoverStorageDescription(e){const t=await this.authnFetch(e,{method:"head"});if(t.status<200||t.status>300)throw Error(`Failed fetching resource: ${e}`);return Fa(t.headers.get("Link"),"http://www.w3.org/ns/solid/terms#storageDescription")}async fetchStorageDescription(e){const t=await this.discoverStorageDescription(e);return this.fetchResource(t)}async discoverDescriptionResource(e){return Fa((await this.authnFetch(e,{method:"head"})).headers.get("Link"),"describedby")}async fetchDescriptionResource(e){const t=await this.discoverDescriptionResource(e);return this.fetchResource(t)}}const Ba="http://www.w3.org/ns/solid/notifications#",za={topic:ra.namedNode(`${Ba}topic`),sendTo:ra.namedNode(`${Ba}sendTo`),receiveFrom:ra.namedNode(`${Ba}receiveFrom`),WebhookChannel2023:ra.namedNode(`${Ba}WebhookChannel2023`),WebSocketChannel2023:ra.namedNode(`${Ba}WebSocketChannel2023`),LDNChannel2023:ra.namedNode(`${Ba}LDNChannel2023`)},qa={type:ra.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")};async function Ka(e,t=""){const r=new N3Store_N3Store,n=new N3Parser_N3Parser(t?{baseIRI:t}:{});for(const t of n.parse(e))r.add(ra.quad(t.subject,t.predicate,t.object,ra.defaultGraph()));return r}async function Wa(e){const t=new N3Writer_N3Writer({format:"text/turtle"});for(const r of e)t.addQuad(r);return new Promise((e,r)=>{t.end((t,n)=>{t?r(t):e(n)})})}function Ha(e,t,r,n,i){return[...e.match(t,r,n,i)].shift()}class SubscriptionClient{constructor(e){this.authnFetch=e,this.discovery=new DiscoveryClient(this.authnFetch),this.rdf={contentType:"text/turtle",parse:Ka,serialize:Wa}}async subscribe(e,t,r){const n=await this.discovery.findService(e,t);if(!n)throw Error(`Discovery did not succeed: channel type ${t} is not supported by the Solid Server.`);const i=function(e,t,r){const n=new N3Store_N3Store,i=ra.blankNode();return n.add(ra.quad(i,qa.type,ra.namedNode(t))),n.add(ra.quad(i,za.topic,ra.namedNode(e))),r&&n.add(ra.quad(i,za.sendTo,ra.namedNode(r))),n}(e,t,r),s=await this.authnFetch(n.id,{method:"POST",body:await this.rdf.serialize(i),headers:{Accept:this.rdf.contentType,"Content-Type":this.rdf.contentType}});if(!s.headers.get("Content-Type").startsWith(this.rdf.contentType))throw new Error("unexpected Content Type");return function(e){const t=Ha(e,null,qa.type).subject,r={id:t.value,type:Ha(e,t,qa.type).object.value,topic:Ha(e,t,za.topic).object.value},n=Ha(e,t,za.receiveFrom)?.object.value;n&&(r.receiveFrom=n);const i=Ha(e,t,za.sendTo)?.object.value;return i&&(r.sendTo=i),r}(await this.rdf.parse(await s.text(),s.url))}}var Qa;!function(e){e.WebhookChannel2023="http://www.w3.org/ns/solid/notifications#WebhookChannel2023",e.WebSocketChannel2023="http://www.w3.org/ns/solid/notifications#WebSocketChannel2023"}(Qa||(Qa={}));var Ja=i(7),Ga=null;"undefined"!=typeof WebSocket?Ga=WebSocket:"undefined"!=typeof MozWebSocket?Ga=MozWebSocket:void 0!==i.g?Ga=i.g.WebSocket||i.g.MozWebSocket:"undefined"!=typeof window?Ga=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(Ga=self.WebSocket||self.MozWebSocket);const Va=Ga,Xa="https://w3id.org/ldes#retentionPolicy",Ya="https://w3id.org/ldes#amount",Za="https://w3id.org/ldes#pointInTime",ec="https://w3id.org/ldes#versionKey",tc="https://w3id.org/ldes#versionOfPath",rc="https://w3id.org/ldes#timestampPath",nc="https://w3id.org/ldes#versionMaterializationOf",ic="https://w3id.org/ldes#versionMaterializationUntil",sc="https://w3id.org/ldes#EventStream",oc="https://w3id.org/ldes#EventSource",ac="https://w3id.org/ldes#RetentionPolicy",cc="https://w3id.org/ldes#Vocabulary",uc="https://w3id.org/ldes#",lc="ldes",hc="http://www.w3.org/ns/ldp#hasMemberRelation",dc="http://www.w3.org/ns/ldp#isMemberOfRelation",fc="http://www.w3.org/ns/ldp#membershipResource",pc="http://www.w3.org/ns/ldp#insertedContentRelation",_c="http://www.w3.org/ns/ldp#member",gc="http://www.w3.org/ns/ldp#contains",yc="http://www.w3.org/ns/ldp#constrainedBy",wc="http://www.w3.org/ns/ldp#pageSortCriteria",bc="http://www.w3.org/ns/ldp#pageSortPredicate",mc="http://www.w3.org/ns/ldp#pageSortOrder",vc="http://www.w3.org/ns/ldp#pageSortCollation",Sc="http://www.w3.org/ns/ldp#pageSequence",Ic="http://www.w3.org/ns/ldp#inbox",xc="http://www.w3.org/ns/ldp#Resource",Ec="http://www.w3.org/ns/ldp#RDFSource",Tc="http://www.w3.org/ns/ldp#NonRDFSource",Rc="http://www.w3.org/ns/ldp#Container",Ac="http://www.w3.org/ns/ldp#BasicContainer",kc="http://www.w3.org/ns/ldp#DirectContainer",jc="http://www.w3.org/ns/ldp#IndirectContainer",Nc="http://www.w3.org/ns/ldp#Page",Pc="http://www.w3.org/ns/ldp#PageSortCriterion",Oc="http://www.w3.org/ns/ldp#MemberSubject",Cc="http://www.w3.org/ns/ldp#PreferContainment",Dc="http://www.w3.org/ns/ldp#PreferMembership",Lc="http://www.w3.org/ns/ldp#PreferEmptyContainer",$c="http://www.w3.org/ns/ldp#PreferMinimalContainer",Uc="http://www.w3.org/ns/ldp#Ascending",Mc="http://www.w3.org/ns/ldp#Descending",Fc="http://www.w3.org/ns/ldp#",Bc="ldp",zc="https://w3id.org/tree#viewDescription",qc="https://w3id.org/tree#relation",Kc="https://w3id.org/tree#remainingItems",Wc="https://w3id.org/tree#node",Hc="https://w3id.org/tree#rootNode",Qc="https://w3id.org/tree#value",Jc="https://w3id.org/tree#path",Gc="https://w3id.org/tree#view",Vc="https://w3id.org/tree#member",Xc="https://w3id.org/tree#search",Yc="https://w3id.org/tree#shape",Zc="https://w3id.org/tree#import",eu="https://w3id.org/tree#conditionalImport",tu="https://w3id.org/tree#zoom",ru="https://w3id.org/tree#longitudeTile",nu="https://w3id.org/tree#latitudeTile",iu="https://w3id.org/tree#timeQuery",su="https://w3id.org/tree#Collection",ou="https://w3id.org/tree#SearchTree",au="https://w3id.org/tree#Node",cu="https://w3id.org/tree#RootNode",uu="https://w3id.org/tree#Relation",lu="https://w3id.org/tree#ConditionalImport",hu="https://w3id.org/tree#PrefixRelation",du="https://w3id.org/tree#SubstringRelation",fu="https://w3id.org/tree#SuffixRelation",pu="https://w3id.org/tree#GreaterThanRelation",_u="https://w3id.org/tree#GreaterThanOrEqualToRelation",gu="https://w3id.org/tree#LessThanRelation",yu="https://w3id.org/tree#LessThanOrEqualToRelation",wu="https://w3id.org/tree#EqualToRelation",bu="https://w3id.org/tree#NotEqualToRelation",mu="https://w3id.org/tree#GeospatiallyContainsRelation",vu="https://w3id.org/tree#InBetweenRelation",Su="https://w3id.org/tree#Ontology",Iu="https://w3id.org/tree#",xu="tree",Eu="https://www.w3.org/ns/activitystreams#relationship",Tu="https://www.w3.org/ns/activitystreams#Activity",Ru="https://www.w3.org/ns/activitystreams#Object",Au="https://www.w3.org/ns/activitystreams#Link",ku="https://www.w3.org/ns/activitystreams#Collection",ju="https://www.w3.org/ns/activitystreams#CollectionPage",Nu="https://www.w3.org/ns/activitystreams#Image",Pu="https://www.w3.org/ns/activitystreams#OrderedItems",Ou="https://www.w3.org/ns/activitystreams#Relationship",Cu="https://www.w3.org/ns/activitystreams#Question",Du="https://www.w3.org/ns/activitystreams#Profile",Lu="https://www.w3.org/ns/activitystreams#Tombstone",$u="https://www.w3.org/ns/activitystreams#Place",Uu="https://www.w3.org/ns/activitystreams#OrderedCollectionPage",Mu="https://www.w3.org/ns/activitystreams#Accept",Fu="https://www.w3.org/ns/activitystreams#Block",Bu="https://www.w3.org/ns/activitystreams#Ignore",zu="https://www.w3.org/ns/activitystreams#IntransitiveActivity",qu="https://www.w3.org/ns/activitystreams#Add",Ku="https://www.w3.org/ns/activitystreams#Announce",Wu="https://www.w3.org/ns/activitystreams#Application",Hu="https://www.w3.org/ns/activitystreams#Arrive",Qu="https://www.w3.org/ns/activitystreams#Article",Ju="https://www.w3.org/ns/activitystreams#Audio",Gu="https://www.w3.org/ns/activitystreams#Document",Vu="https://www.w3.org/ns/activitystreams#OrderedCollection",Xu="https://www.w3.org/ns/activitystreams#Create",Yu="https://www.w3.org/ns/activitystreams#Delete",Zu="https://www.w3.org/ns/activitystreams#Dislike",el="https://www.w3.org/ns/activitystreams#Event",tl="https://www.w3.org/ns/activitystreams#Flag",rl="https://www.w3.org/ns/activitystreams#Follow",nl="https://www.w3.org/ns/activitystreams#Group",il="https://www.w3.org/ns/activitystreams#Invite",sl="https://www.w3.org/ns/activitystreams#Offer",ol="https://www.w3.org/ns/activitystreams#Join",al="https://www.w3.org/ns/activitystreams#Leave",cl="https://www.w3.org/ns/activitystreams#Like",ul="https://www.w3.org/ns/activitystreams#View",ll="https://www.w3.org/ns/activitystreams#Listen",hl="https://www.w3.org/ns/activitystreams#Read",dl="https://www.w3.org/ns/activitystreams#Move",fl="https://www.w3.org/ns/activitystreams#Travel",pl="https://www.w3.org/ns/activitystreams#Mention",_l="https://www.w3.org/ns/activitystreams#Note",gl="https://www.w3.org/ns/activitystreams#Page",yl="https://www.w3.org/ns/activitystreams#Person",wl="https://www.w3.org/ns/activitystreams#Organization",bl="https://www.w3.org/ns/activitystreams#Reject",ml="https://www.w3.org/ns/activitystreams#Remove",vl="https://www.w3.org/ns/activitystreams#Service",Sl="https://www.w3.org/ns/activitystreams#TentativeAccept",Il="https://www.w3.org/ns/activitystreams#TentativeReject",xl="https://www.w3.org/ns/activitystreams#Undo",El="https://www.w3.org/ns/activitystreams#Update",Tl="https://www.w3.org/ns/activitystreams#Video",Rl="https://www.w3.org/ns/activitystreams#actor",Al="https://www.w3.org/ns/activitystreams#attributedTo",kl="https://www.w3.org/ns/activitystreams#attachment",jl="https://www.w3.org/ns/activitystreams#attachments",Nl="https://www.w3.org/ns/activitystreams#author",Pl="https://www.w3.org/ns/activitystreams#bcc",Ol="https://www.w3.org/ns/activitystreams#bto",Cl="https://www.w3.org/ns/activitystreams#cc",Dl="https://www.w3.org/ns/activitystreams#context",Ll="https://www.w3.org/ns/activitystreams#current",$l="https://www.w3.org/ns/activitystreams#first",Ul="https://www.w3.org/ns/activitystreams#generator",Ml="https://www.w3.org/ns/activitystreams#icon",Fl="https://www.w3.org/ns/activitystreams#image",Bl="https://www.w3.org/ns/activitystreams#inReplyTo",zl="https://www.w3.org/ns/activitystreams#items",ql="https://www.w3.org/ns/activitystreams#last",Kl="https://www.w3.org/ns/activitystreams#location",Wl="https://www.w3.org/ns/activitystreams#next",Hl="https://www.w3.org/ns/activitystreams#object",Ql="https://www.w3.org/ns/activitystreams#oneOf",Jl="https://www.w3.org/ns/activitystreams#anyOf",Gl="https://www.w3.org/ns/activitystreams#prev",Vl="https://www.w3.org/ns/activitystreams#preview",Xl="https://www.w3.org/ns/activitystreams#provider",Yl="https://www.w3.org/ns/activitystreams#replies",Zl="https://www.w3.org/ns/activitystreams#result",eh="https://www.w3.org/ns/activitystreams#audience",th="https://www.w3.org/ns/activitystreams#partOf",rh="https://www.w3.org/ns/activitystreams#tag",nh="https://www.w3.org/ns/activitystreams#tags",ih="https://www.w3.org/ns/activitystreams#target",sh="https://www.w3.org/ns/activitystreams#origin",oh="https://www.w3.org/ns/activitystreams#instrument",ah="https://www.w3.org/ns/activitystreams#to",ch="https://www.w3.org/ns/activitystreams#url",uh="https://www.w3.org/ns/activitystreams#subject",lh="https://www.w3.org/ns/activitystreams#describes",hh="https://www.w3.org/ns/activitystreams#formerType",dh="https://www.w3.org/ns/activitystreams#accuracy",fh="https://www.w3.org/ns/activitystreams#altitude",ph="https://www.w3.org/ns/activitystreams#content",_h="https://www.w3.org/ns/activitystreams#name",gh="https://www.w3.org/ns/activitystreams#downstreamDuplicates",yh="https://www.w3.org/ns/activitystreams#duration",wh="https://www.w3.org/ns/activitystreams#endTime",bh="https://www.w3.org/ns/activitystreams#height",mh="https://www.w3.org/ns/activitystreams#href",vh="https://www.w3.org/ns/activitystreams#hreflang",Sh="https://www.w3.org/ns/activitystreams#id",Ih="https://www.w3.org/ns/activitystreams#latitude",xh="https://www.w3.org/ns/activitystreams#longitude",Eh="https://www.w3.org/ns/activitystreams#mediaType",Th="https://www.w3.org/ns/activitystreams#objectType",Rh="https://www.w3.org/ns/activitystreams#published",Ah="https://www.w3.org/ns/activitystreams#radius",kh="https://www.w3.org/ns/activitystreams#rating",jh="https://www.w3.org/ns/activitystreams#rel",Nh="https://www.w3.org/ns/activitystreams#startIndex",Ph="https://www.w3.org/ns/activitystreams#startTime",Oh="https://www.w3.org/ns/activitystreams#summary",Ch="https://www.w3.org/ns/activitystreams#totalItems",Dh="https://www.w3.org/ns/activitystreams#units",Lh="https://www.w3.org/ns/activitystreams#updated",$h="https://www.w3.org/ns/activitystreams#upstreamDuplicates",Uh="https://www.w3.org/ns/activitystreams#verb",Mh="https://www.w3.org/ns/activitystreams#width",Fh="https://www.w3.org/ns/activitystreams#deleted",Bh="https://www.w3.org/ns/activitystreams#",zh="activitystreams",qh=m,Kh=v,Wh=S,Hh=I;let Qh=class Relation{constructor(e,t){this.value=e,this.node=t}setPath(e){return this.path=new x.SerializableNamedNode(e),this}};E([(0,A.SerializableMember)({rdf:{predicate:Wh.node,serializer:!1,deserializer:e=>new x.SerializableThing(e.value)}}),T("design:type",x.SerializableThing)],Qh.prototype,"node",void 0),E([(0,A.SerializableMember)({rdf:{predicate:Wh.path}}),T("design:type",x.SerializableNamedNode)],Qh.prototype,"path",void 0),E([(0,A.SerializableMember)({constructor:Object,rdf:{predicate:Wh.value,serializer:e=>x.RDFSerializer.serialize(e),deserializer:e=>x.RDFSerializer.deserialize(e)}}),T("design:type",Object)],Qh.prototype,"value",void 0),Qh=E([(0,A.SerializableObject)({rdf:{type:Wh.Relation,serializer:(e,t)=>e.value?e.value.constructor===Date?{termType:"NamedNode",value:t+e.value.getTime().toString()}:{termType:"NamedNode",value:t+encodeURIComponent(e.value.toString())}:{}}}),T("design:paramtypes",[Object,Function])],Qh);let Jh=class GreaterThanOrEqualToRelation extends Qh{test(e){return e>=this.value}};Jh=E([(0,A.SerializableObject)({rdf:{type:Wh.GreaterThanOrEqualToRelation}})],Jh);let Gh=class GreaterThanRelation extends Qh{test(e){return e>this.value}};Gh=E([(0,A.SerializableObject)({rdf:{type:Wh.GreaterThanRelation}})],Gh);let Vh=class LessThanOrEqualToRelation extends Qh{test(e){return e<=this.value}};Vh=E([(0,A.SerializableObject)({rdf:{type:Wh.LessThanOrEqualToRelation}})],Vh);let Xh=class LessThanRelation extends Qh{test(e){return e<this.value}};Xh=E([(0,A.SerializableObject)({rdf:{type:Wh.LessThanRelation}})],Xh);let Yh=class Collection extends x.SerializableThing{constructor(){super(...arguments),this.members=[]}};E([(0,A.SerializableArrayMember)(x.SerializableThing,{rdf:{predicate:Wh.member,serializer:!1}}),T("design:type",Array)],Yh.prototype,"members",void 0),Yh=E([(0,A.SerializableObject)({rdf:{type:Wh.Collection}})],Yh);let Zh=class Node extends x.SerializableThing{constructor(e){super(e),this.relations=[]}getChildNodes(){return this.relations.map(e=>e.node)}getChildNode(e){const t=this.relations.filter(t=>!!t&&(t.value&&t.test(e)));if(0===t.length)return null;const r=t.sort((e,t)=>"number"==typeof e.value&&"number"==typeof t.value?e.value-t.value:e.value instanceof Date&&t.value instanceof Date?e.value.getTime()-t.value.getTime():e.value.toString().localeCompare(t.value.toString())).map(e=>e.node);return r[r.length-1]}};E([(0,A.SerializableArrayMember)(Qh,{rdf:{predicate:Wh.relation}}),T("design:type",Array)],Zh.prototype,"relations",void 0),E([(0,A.SerializableMember)({rdf:{}}),T("design:type",Yh)],Zh.prototype,"collection",void 0),Zh=E([(0,A.SerializableObject)({rdf:{type:Wh.Node}}),T("design:paramtypes",[String])],Zh);let ed=class EventStream extends x.SerializableThing{constructor(){super(...arguments),this.timestampPath=new x.SerializableNamedNode(x.dcterms.created),this.versionOfPath=new x.SerializableNamedNode(x.dcterms.isVersionOf)}setTimestampPath(e){this.timestampPath=new x.SerializableNamedNode(e)}setVersionOfPath(e){this.versionOfPath=new x.SerializableNamedNode(e)}};E([(0,A.SerializableMember)({rdf:{predicate:qh.timestampPath}}),T("design:type",x.SerializableNamedNode)],ed.prototype,"timestampPath",void 0),E([(0,A.SerializableMember)({rdf:{predicate:qh.versionOfPath}}),T("design:type",x.SerializableNamedNode)],ed.prototype,"versionOfPath",void 0),E([(0,A.SerializableMember)({rdf:{predicate:Wh.view,serializer:!1}}),T("design:type",Zh)],ed.prototype,"view",void 0),ed=E([(0,A.SerializableObject)({rdf:{type:qh.EventStream}})],ed);let td=class Container extends x.SerializableThing{};td=E([(0,A.SerializableObject)({rdf:{type:Kh.Container}})],td);let rd=class Activity{};E([(0,A.SerializableMember)({rdf:{predicate:Hh.object,serializer:!1}}),T("design:type",String)],rd.prototype,"object",void 0),E([(0,A.SerializableMember)({rdf:{predicate:Hh.actor,serializer:!1}}),T("design:type",String)],rd.prototype,"actor",void 0),E([(0,A.SerializableMember)({rdf:{predicate:Hh.target,serializer:!1}}),T("design:type",String)],rd.prototype,"target",void 0),E([(0,A.SerializableMember)({rdf:{predicate:Hh.published}}),T("design:type",Date)],rd.prototype,"published",void 0),rd=E([(0,A.SerializableObject)({rdf:{type:Hh.Activity}})],rd);let nd=class ActivityAdd extends rd{};nd=E([(0,A.SerializableObject)({rdf:{type:Hh.Add}})],nd);let id=class ActivityRemove extends rd{};id=E([(0,A.SerializableObject)({rdf:{type:Hh.Remove}})],id);class DatasetSubscription extends Ja.EventEmitter{constructor(){super()}static create(e,t){return new Promise((r,n)=>{const i=new DatasetSubscription;let s=!1;i._ws=new Va(e,["solid-0.1"]),i._ws.onopen=()=>{s=!0,r(i)},i._ws.onmessage=t?e=>{i.emit("message",e.data);try{x.RDFSerializer.deserializeFromJSONLD(void 0,JSON.parse(e.data)).then(e=>{e?i.emit("activity",e):i.emit("error",new Error("Failed to deserialize activity stream"))}).catch(e=>{i.emit("error",e)})}catch(e){i.emit("error",e)}}:e=>{if(e.data&&"pub"===e.data.slice(0,3)){const t=new nd;t.object=e.data.substring(3),i.emit("activity",t)}},i._ws.onerror=e=>{s?i.emit("error",e):n(e)}})}subscribe(e){this._ws.send(`sub ${e}`)}close(){this._ws&&this._ws.close()}on(e,t){return super.on(e,t)}}class StorageUtilityWrapper extends StorageUtility{constructor(e,t){super(e,t)}}class SolidStorage{constructor(e){this.driver=e}get(e){return new Promise(t=>{this.driver.findByUID(e).then(e=>{t(e)}).catch(()=>{t(void 0)})})}set(e,t){return new Promise((r,n)=>{this.driver.insert(e,t).then(()=>{r()}).catch(n)})}delete(e){return new Promise(t=>{this.driver.delete(e).then(t).catch(()=>t(void 0))})}}class SolidService extends A.RemoteService{constructor(e){super(),this.options=e||{},this.driver=this.options.dataServiceDriver||new A.MemoryDataService(String),this.storage=new SolidStorage(this.driver),this.storageUtility=new StorageUtilityWrapper(this.storage,this.storage),this.clientRegistrar=new ClientRegistrar(this.storageUtility),this.uid=this.constructor.name,this.options.defaultOidcIssuer=this.options.defaultOidcIssuer||"https://login.inrupt.com/",this.once("build",()=>this.driver.emitAsync("build"))}get session(){return this._session}set session(e){this._session=e}get clientAuthentication(){if(this._clientAuthentication)return this._clientAuthentication;const e=this.createSession({sessionInfo:{isLoggedIn:!1,sessionId:"dummy"},storage:this.storage,insecureStorage:this.storage,secureStorage:this.storage});return this._clientAuthentication=e.clientAuthentication,this._clientAuthentication}getDocumentURL(e,t){return R(this,void 0,void 0,function*(){const r=new URL(yield this.getPodUrl(e)),n=new URL(e.info.webId);n.pathname="",n.hash="";const i=new URL(r.href);if(t){const e=t.replace(r.href,"").replace(n.href,""),s=new URL((r.pathname.length>1?r.pathname:"")+e.replace(/^\//,""),r.href);i.pathname=s.pathname,i.hash=s.hash}return i})}getPodUrl(e){return new Promise((t,r)=>{Jr(e.info.webId,{fetch:e.fetch}).then(r=>{if(void 0===r[0]){const r=new URL(e.info.webId);return r.hash="",r.pathname=r.pathname.replace(/\/profile\/card$/,"/"),void t(r.href)}t(r[0])}).catch(r)})}getDatasetStore(e,t){return new Promise((r,n)=>{this.getDataset(e,t).then(e=>{e||(e=$r());const t=Object.keys(e.graphs).map(t=>{const r=e.graphs[t];return x.RDFSerializer.subjectsToQuads(Object.values(r))}).reduce((e,t)=>e.concat(t),[]),n=(0,x.createChangeLog)(new x.Store(t)),i=Object.assign(n,e);r(i)}).catch(n)})}createDataset(){return $r()}getDataset(e,t){return R(this,void 0,void 0,function*(){var r;const n=t.startsWith("http")?new URL(t):yield this.getDocumentURL(e,t);n.hash="";try{return yield Ur(n.href,e?{fetch:e.fetch}:this.session)}catch(e){if(404===(null===(r=null==e?void 0:e.response)||void 0===r?void 0:r.status))return;throw e}})}getDatasetSubscription(e,t){const r=e?e.fetch:Jn.fetch;function n(){return new Promise((e,n)=>{const i=new DiscoveryClient(r);Promise.all([i.findService(t,Qa.WebSocketChannel2023)]).then(([e])=>{if(!e)return void n(new Error("No WebSocket service found"));return new SubscriptionClient(r).subscribe(t,e.channelType)}).then(t=>{e(t.receiveFrom)}).catch(n)})}function i(e,t){return new Promise((r,n)=>{DatasetSubscription.create(e,t).then(t=>{t.subscribe(e),r(t)}).catch(n)})}return new Promise((e,s)=>{new Promise((e,n)=>{r(t,{method:"HEAD"}).then(t=>{const r=t.headers.get("updates-via");if(!r)return e(void 0);e(r)}).catch(n)}).then(t=>{t?i(t,void 0).then(e).catch(s):n().then(e=>i(e,Qa.WebSocketChannel2023)).then(e).catch(s)}).catch(s)})}createContainer(e,t){return new Promise((r,n)=>{t.endsWith("/")||(t+="/"),this.getDataset(e,t).then(i=>{if(i&&F(i))r(i);else{if(!i||F(i))return async function(e,t={}){var r,n;const i=D(C(e),{trailingSlash:!0}),s=await(null!==(r=t.fetch)&&void 0!==r?r:fetch)(i,{method:"PUT",body:t.initialContent?await fr(_t(t.initialContent).map(Kr)):void 0,headers:{Accept:"text/turtle","Content-Type":"text/turtle","If-None-Match":"*",Link:`<${At}>; rel="type"`}});if($(s)){const r=void 0===t.initialContent?"empty":"non-empty",n=await s.clone().text();throw new FetchError(`Creating the ${r} Container at [${e}] failed: [${s.status}] [${s.statusText}] ${n}.`,s,n)}const o=L(s);return We({...null!==(n=t.initialContent)&&void 0!==n?n:$r(),internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:o})}(t,e?{fetch:e.fetch}:void 0);n(new Error("Resource already exists and is not a container"))}}).then(r).catch(n)})}deleteContainer(e,t){return new Promise((r,n)=>{(async function(e,t){var r;const n=N(e)?C(B(e)):D(C(e));if(!F(e))throw new Error(`You're trying to delete the Container at [${n}], but Container URLs should end in a \`/\`. Are you sure this is a Container?`);const i=await(null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch)(n,{method:"DELETE"});if($(i)){const e=await i.clone().text();throw new FetchError(`Deleting the Container at [${n}] failed: [${i.status}] [${i.statusText}] ${e}.`,i,e)}})(t,e?{fetch:e.fetch}:void 0).then(()=>{r()}).catch(n)})}deleteRecursively(e,t){return R(this,void 0,void 0,function*(){if("string"==typeof t){const r=yield this.getDataset(e,t);return r?yield this.deleteRecursively(e,r):Promise.resolve()}if(!t)return Promise.resolve();const r=function(e){const t=B(e),r=Tr(e,t);return null===r?[]:Ir(r,jt).filter(e=>zr(e,t))}(t),n=yield Promise.all(r.map(t=>R(this,void 0,void 0,function*(){try{return yield Ur(t,e?{fetch:e.fetch}:this.session)}catch(r){return yield async function(e,t){var r;const n=N(e)?C(z(e)):D(C(e),{trailingSlash:!1}),i=await(null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch)(n,{...null==t?void 0:t.init,method:"DELETE"});if($(i)){const e=await i.clone().text();throw new FetchError(`Deleting the file at [${n}] failed: [${i.status}] [${i.statusText}] ${e}.`,i,e)}}(t,e?{fetch:e.fetch}:this.session),null}})));return yield Promise.all(n.map(t=>R(this,void 0,void 0,function*(){if(null!==t)return yield this.deleteRecursively(e,t)}))),yield Fr(t,e?{fetch:e.fetch}:this.session)})}deleteDataset(e,t){return new Promise((r,n)=>{Fr(t,e?{fetch:e.fetch}:this.session).then(()=>{r()}).catch(n)})}saveDataset(e,t,r,n){return new Promise((i,s)=>{var o,a;const c=e?{fetch:e.fetch}:this.session,u=new URL(t);u.hash="";const l=new URL(u.href);if(l.pathname=l.pathname.replace(/\/[^/]+$/,"/"),r instanceof x.Store){let e,t=[];if(r.additions&&r.deletions?(e=null!==(o=r.additions)&&void 0!==o?o:[],t=null!==(a=r.deletions)&&void 0!==a?a:[]):e=(r=(0,x.createChangeLog)(r)).getQuads(null,null,null,null),0===e.length&&0===t.length)return void i(null);const n="Dataset"===r.type?r:$r(),s=Object.assign(Object.assign({},this.storeToDataset(r)),{internal_changeLog:{additions:e,deletions:t},internal_resourceInfo:n.internal_resourceInfo});r=s}else r=r||$r();if(n){const e=Object.assign({sourceIri:u.href},r.internal_resourceInfo);r=Object.assign(Object.assign({},r),{internal_resourceInfo:e}),async function(e,t,r){var n;const i=D(C(e),{trailingSlash:!0}),s=await fr(_t(t).map(Kr)),o={"Content-Type":"text/turtle",Link:`<${kt}>; rel="type"`};(null==r?void 0:r.slugSuggestion)&&(o.slug=r.slugSuggestion);const a=await(null!==(n=null==r?void 0:r.fetch)&&void 0!==n?n:fetch)(i,{method:"POST",body:s,headers:o});if($(a)){const e=await a.clone().text();throw new FetchError(`Storing the Resource in the Container at [${i}] failed: [${a.status}] [${a.statusText}] ${e}.\n\nThe SolidDataset that was sent to the Pod is listed below.\n\n${qr(t)}`,a,e)}const c=L(a);if(!c.location)throw new Error("Could not determine the location of the newly saved SolidDataset.");let u;try{u=new URL(c.location).href}catch(e){u=new URL(c.location,a.url).href}const l={internal_resourceInfo:{isRawData:!1,sourceIri:u}};return Hr(We({...t,...l}))}(l.href,r,c).then(i).catch(s)}else Mr(u.href,r,c).then(i).catch(s)})}getThing(e,t){return new Promise((r,n)=>{this.getDataset(e,t).then(e=>{if(!e)return void r(void 0);const n=Tr(e,t);r(n)}).catch(n)})}setAccess(e,t,r=x.foaf.Agent,n){return new Promise((i,s)=>{n=null!=n?n:this.session,async function(e,t){const r=await Ur(e,t);return gn(r,await nn(r,t))}(e,n?{fetch:n.fetch}:void 0).then(e=>{let i;var s;!function(e){return"object"==typeof e.internal_acl}(e)?(i=Sn(e),i=Tn(i,n.info.webId,{read:!0,append:!0,write:!0,control:!0}),i=En(i,n.info.webId,{read:!0,append:!0,write:!0,control:!0})):i=mn(s=e)?s.internal_acl.resourceAcl:null;const o=t.group||r===x.foaf.Agent||"public"===r;return i=o?An(i,r,{read:t.read,append:t.append,write:t.write,control:t.controlWrite}):En(i,r,{read:t.read,append:t.append,write:t.write,control:t.controlWrite}),t.public&&(i=jn(i,{read:t.read,append:t.append,write:t.write,control:t.controlWrite})),t.public&&t.default&&(i=Nn(i,{read:t.read,append:t.append,write:t.write,control:t.controlWrite})),o&&t.default?i=kn(i,r,{read:t.read,append:t.append,write:t.write,control:t.controlWrite}):t.default&&(i=Tn(i,r,{read:t.read,append:t.append,write:t.write,control:t.controlWrite})),async function(e,t,r){if(!In(e))throw new Error(`Could not determine the location of the ACL for the Resource at [${B(e)}]; possibly the current user does not have Control access to that Resource. Try calling \`hasAccessibleAcl()\` before calling \`saveAclFor()\`.`);return{...await Mr(e.internal_resourceInfo.aclUrl,t,r),internal_accessTo:B(e)}}(e,i,n?{fetch:n.fetch}:this.session)}).then(()=>{i()}).catch(s)})}getAccess(e,t=x.foaf.Agent,r){return new Promise((n,i)=>{Qn(e,t,r?{fetch:r.fetch}:void 0).then(e=>{n(e)}).catch(i)})}logout(e){return new Promise((t,r)=>{e.logout().then(()=>(this.session=void 0,this.storage.delete("currentSession"))).then(()=>{t()}).catch(r)})}setThing(e,t){return this.createThing(e,t)}createThing(e,t,r){return new Promise((n,i)=>{const s=new URL(t.url);function o(r,o=!0){var a;const c=null!==(a=Tr(r,t.url))&&void 0!==a?a:{},u=this._mergeDeep(c,t);r=Ar(r,u),o?this.saveDataset(e,r,s.href).then(()=>{n(r)}).catch(i):n(r)}s.hash="",r?o.bind(this)(r,!1):this.getDataset(e,s.href).then(e=>{e||(e=$r()),o.bind(this)(e)}).catch(i)})}_isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}_mergeDeep(e,t){const r=Object.assign({},e);return this._isObject(e)&&this._isObject(t)&&Object.keys(t).forEach(n=>{var i;Array.isArray(t[n])?r[n]=[...t[n],...null!==(i=e[n])&&void 0!==i?i:[]]:this._isObject(t[n])?n in e?r[n]=this._mergeDeep(e[n],t[n]):Object.assign(r,{[n]:t[n]}):Object.assign(r,{[n]:t[n]})}),r}remotePush(e,t,r){return new Promise((e,t)=>{e(void 0)})}remotePull(e,t){return new Promise((e,t)=>{e(void 0)})}remoteEvent(e,t,...r){return new Promise((e,t)=>{e(void 0)})}remoteServiceCall(e,t,...r){return new Promise((e,t)=>{e(void 0)})}fetchProfile(e){return new Promise((t,r)=>{this.findSessionByWebId(e.webId).then(t=>Ur(e.profileDocumentUrl.href,t?{fetch:t.fetch}:void 0)).then(r=>{const n=Tr(r,e.webId);var i,s;e.displayName=(i=n,s=x.vcard.fn,br(i),Er(i,s,tt)),t(e)}).catch(r)})}storeProfile(e){return new Promise((t,r)=>{const n=`${SolidService.PREFIX}:webId:${e.webId}`;let i;this.storage.set(n,e.sessionId).then(()=>this.findSessionByWebId(e.webId)).then(r=>{i=r;const n=e.profileDocumentUrl;if(n)return Ur(n.href,i?{fetch:i.fetch}:void 0);t(void 0)}).then(t=>{const r=Tr(t,e.webId),n=rn(r,x.vcard.fn,e.displayName),s=Ar(t,n);return this.saveDataset(i,n.url,s)}).then(()=>{t(e)}).catch(r)})}findSessionInfoById(e){return new Promise((t,r)=>{this.clientAuthentication.getSessionInfo(e).then(e=>{t(e)}).catch(r)})}findSessionById(e){return new Promise((t,r)=>{let n;this.findSessionInfoById(e).then(e=>{if(void 0!==e)return n=this.createSession({sessionInfo:e,storage:this.storage,insecureStorage:this.storage,secureStorage:this.storage}),!e.isLoggedIn&&e.issuer?n.login({oidcIssuer:e.issuer,clientId:e.clientAppId,clientSecret:e.clientAppSecret,handleRedirect:()=>{}}):void 0;t(void 0)}).then(()=>{t(n)}).catch(r)})}findSessionByWebId(e){return new Promise((t,r)=>{const n=`${SolidService.PREFIX}:webId:${e}`;this.storage.get(n).then(e=>{if(e)return this.findSessionById(e);t(void 0)}).then(e=>{t(e)}).catch(r)})}findSessionByObjectUID(e,t){return new Promise((r,n)=>{const i=`${`${SolidService.PREFIX}:${e.name}`}:${t}`;this.storage.get(i).then(e=>this.findSessionById(e)).then(r).catch(n)})}linkSession(e,t,r){return new Promise((n,i)=>{const s=null!=r?r:e.constructor,o=`${`${SolidService.PREFIX}:${s.name}`}:${e.uid}`;this.storage.set(o,t).then(n).catch(i)})}unlinkSession(e,t){return new Promise((r,n)=>{const i=null!=t?t:e.constructor,s=`${`${SolidService.PREFIX}:${i.name}`}:${e instanceof A.DataObject||e instanceof A.DataFrame?e.uid:e}`;this.storage.delete(s).then(r).catch(n)})}storeToDataset(e){const t={graphs:{default:{}},type:"Dataset"};return e.getSubjects(void 0,void 0,void 0).filter(e=>"BlankNode"!==e.termType).forEach(r=>{const n=x.RDFSerializer.quadsToThing(r,e);x.RDFSerializer.thingToSubjects(n).forEach(e=>{t.graphs.default[e.url]=e})}),t}}SolidService.PREFIX="OpenHPS:solid",x.RDFSerializer.getDocumentLoader().addContext("https://www.w3.org/ns/solid/notification/v1",{});let sd=class SolidProfileObject extends A.DataObject{constructor(e,t){super(e,t)}get webId(){return this.uid}set webId(e){this.uid=e}get name(){var e;return null!==(e=this._formattedName)&&void 0!==e?e:`${this.firstName} ${this.lastName}`}set name(e){this._formattedName=e}get profileDocumentUrl(){try{const e=new URL(this.webId);return e.hash="",e}catch(e){return}}};E([(0,A.SerializableMember)({rdf:{predicates:[x.vcard.given_name,x.foaf.givenname]}}),T("design:type",String)],sd.prototype,"firstName",void 0),E([(0,A.SerializableMember)({rdf:{predicates:[x.vcard.family_name,x.foaf.surname]}}),T("design:type",String)],sd.prototype,"lastName",void 0),E([(0,A.SerializableMember)({rdf:{predicates:[x.vcard.fn,x.foaf.name]}}),T("design:type",String)],sd.prototype,"_formattedName",void 0),E([(0,A.SerializableMember)({rdf:{predicates:[x.foaf.nick]}}),T("design:type",String)],sd.prototype,"nickname",void 0),E([(0,A.SerializableMember)({rdf:{predicate:[x.vcard.hasPhoto]}}),T("design:type",String)],sd.prototype,"picture",void 0),E([(0,A.SerializableMember)(),T("design:type",String)],sd.prototype,"oidcIssuer",void 0),E([(0,A.SerializableMember)(),T("design:type",String)],sd.prototype,"sessionId",void 0),sd=E([(0,A.SerializableObject)({rdf:{type:x.foaf.Person}}),T("design:paramtypes",[String,String])],sd),A.DataObject.prototype.webId=void 0,(0,A.SerializableMember)(String)(A.DataObject.prototype,"webId"),A.DataFrame.prototype.webId=void 0,(0,A.SerializableMember)(String)(A.DataFrame.prototype,"webId");class QueryEngine extends e().QueryEngineBase{constructor(e){super(e)}}class SolidDataDriver extends x.SPARQLDataDriver{constructor(e,t){var r,n,i;super(e,t),this.options.engine=null!==(r=this.options.engine)&&void 0!==r?r:require("./engine-default")(),this.options.engine&&(this.engine=new QueryEngine(this.options.engine)),this.options.lenient=!0,this.options.uriPrefix=this.options.uriPrefix||"/openhps",this.options.serialize=null!==(n=this.options.serialize)&&void 0!==n?n:od,this.options.deserialize=null!==(i=this.options.deserialize)&&void 0!==i?i:ad,this.once("build",this._initService.bind(this))}_initService(){return R(this,void 0,void 0,function*(){return new Promise((e,t)=>this.model?(this.service=this.model.findService(SolidService),this.service?void e():t(new Error("Unable to find SolidDataService!"))):e())})}queryQuads(e,t,r){return r?super.queryQuads(e,Object.assign({"@comunica/actor-http-inrupt-solid-client-authn:session":r,sources:[r.info.webId],lenient:!0},t)):super.queryQuads(e,t)}queryBindings(e,t,r){return t?super.queryBindings(e,Object.assign({"@comunica/actor-http-inrupt-solid-client-authn:session":t,sources:[t.info.webId],lenient:!0},r)):super.queryBindings(e,r)}findByUID(e){return new Promise((t,r)=>{this.service.findSessionByObjectUID(this.dataType,e).then(t=>this.service.getThing(t,`/${this.options.uriPrefix}/${e}`)).then(e=>{const r=this.options.deserialize(e);t(r)}).catch(r)})}getQueryStore(e){return this.service.findSessionByWebId(e.webId).then(t=>this.service.getDataset(t,e.uri)).then(e=>{if(!e)return;const t=Object.values(e.graphs.default),r=x.RDFSerializer.subjectsToQuads(t);return new x.Store(r)})}findOne(e,t={}){return this.getQueryStore(e).then(r=>{if(r)return super.findOne(e.query,t,{sources:[r],lenient:!0})})}findAll(e,t={}){return this.getQueryStore(e).then(r=>r?super.findAll(e.query,Object.assign({},t),{sources:[r],lenient:!0}):[])}count(e){return this.getQueryStore(e).then(t=>t?super.count(e.query,{sources:[t],lenient:!0}):0)}insert(e,t){return new Promise((e,r)=>{if(!t.webId){if(!this.service.session)return r(new Error("Unable to store data object or frame without WebID!"));t.webId=this.service.session.info.webId}this.service.findSessionByWebId(t.webId).then(n=>R(this,void 0,void 0,function*(){if(!n)return void r(new Error(`Unable to find solid session for ${t.webId}!`));if(!n.info.isLoggedIn)return void r(new Error("Solid session is not logged in!"));yield this.service.linkSession(t,n.info.sessionId,this.dataType);const i=yield this.service.getPodUrl(n),s=this.options.serialize(t,i);if(0===s.length)return void r(new Error("Unable to serialize object to RDF!"));const o=new URL(s[0].url);o.hash="",yield this.linkObjectToSession(t.uid,o.href,n,this.dataType),this.service.getDataset(n,o.href).then(e=>{e||(e=this.service.createDataset());let t=Promise.resolve(e);for(let e=0;e<s.length;e++)t=t.then(t=>new Promise((r,i)=>{this.service.createThing(n,s[e],t).then(e=>{r(e)}).catch(i)}));return t}).then(e=>this.service.saveDataset(n,o.href,e)).then(()=>{e(t)}).catch(r)})).catch(r)})}delete(e){return new Promise((t,r)=>{let n,i;this.service.findSessionByObjectUID(this.dataType,e).then(t=>R(this,void 0,void 0,function*(){if(t)return i=t,n=yield this.findObjectURI(e,t,this.dataType),yield this.service.unlinkSession(e,this.dataType),yield this.unlinkObjectFromSession(e,t,this.dataType),Ur(n,{fetch:t.fetch});r(new Error(`Unable to find solid session for ${this.dataType.name} with id '${e}'!`))})).then(e=>Object.values(e.graphs.default)[0].url===n?Fr(n,{fetch:i.fetch}):(e=kr(e,n),Mr(n,e,{fetch:i.fetch}))).then(()=>t()).catch(r)})}deleteAll(){throw new Error("Not supported with SolidDataDriver!")}findObjectURI(e,t,r){return new Promise((n,i)=>{const s=`${`${SolidService.PREFIX}:${r.name}`}:${t.info.sessionId}:${e}`;this.service.storage.get(s).then(e=>n(e)).catch(i)})}linkObjectToSession(e,t,r,n){return new Promise((i,s)=>{const o=`${`${SolidService.PREFIX}:${n.name}`}:${r.info.sessionId}:${e}`;this.service.storage.set(o,t).then(i).catch(s)})}unlinkObjectFromSession(e,t,r){return new Promise((n,i)=>{const s=`${`${SolidService.PREFIX}:${r.name}`}:${t.info.sessionId}:${e}`;this.service.storage.delete(s).then(n).catch(i)})}}function od(e,t){return x.RDFSerializer.serializeToSubjects(e,t)}function ad(e){return x.RDFSerializer.deserializeFromSubjects(e.url,[e])}function cd(e){return!e.collection||e.collection.members.length<50}class SolidPropertyService extends A.DataService{constructor(e){super(new SolidDataDriver(void 0,{sources:[void 0],lenient:!0})),this.filter=null!=e?e:cd}get session(){return this.service.session}set service(e){this.driver.service=e}get service(){return this.driver.service}fetchProperties(e,t){return new Promise((r,n)=>{const i=`SELECT DISTINCT ?property ?name WHERE {\n ?me <${x.ssn.hasProperty}> ?property .\n OPTIONAL {\n ?property <${x.rdfs.label}> ?name .\n }\n FILTER(?me = <${t.webId}>)\n }`;this.driver.queryBindings(i,e,{sources:[t.webId],lenient:!0}).then(e=>{const t=[];e.forEach(e=>{const r=e.get("property").value,n=e.has("name")?e.get("name").value:void 0,i=new x.Property;i.id=r,i.label=n,t.push(i)}),r(t)}).catch(n)})}createProperty(e,t){return new Promise((r,n)=>{const i=this.getPropertyContainer(t);t.id.endsWith("/property.ttl")||(t.id=`${t.id.replace(/\/$/,"")}/property.ttl`),this.service.getDatasetStore(e,e.info.webId).then(r=>{const n=x.RDFSerializer.quadsToThing(x.DataFactory.namedNode(e.info.webId),r),i=x.RDFBuilder.fromSerialized(n);i.add(x.ssn.hasProperty,t.id);const s=i.build(!0);let o=!1;return s.additions.length>0&&(o=!0,r.addQuads(s.additions)),s.deletions.length>0&&(o=!0,r.removeQuads(s.deletions)),o?this.service.saveDataset(e,e.info.webId,r):Promise.resolve()}).then(()=>this.service.getDataset(e,i.href)).then(n=>{if(!n)return this.service.createContainer(e,i.href);r(t.id)}).then(()=>Promise.all([this.service.getDatasetStore(e,`${i.href}property.ttl`),this.service.getDatasetStore(e,`${i.href}.meta`)])).then(([r,n])=>{r.addQuads(x.RDFSerializer.serializeToQuads(t));const s=new URL(`${i.href}property.ttl`);s.hash="EventStream";const o=new URL(`${i.href}property.ttl`);o.hash="root";const a=new ed(s.href);return a.setTimestampPath(x.sosa.resultTime),a.view=new Zh(o.href),n.addQuads(x.RDFSerializer.serializeToQuads(a)),r.addQuads(x.RDFSerializer.serializeToQuads(a.view)),this.service.saveDataset(e,`${i.href}property.ttl`,r).then(()=>this.service.saveDataset(e,`${i.href}.meta`,n))}).then(()=>{r(t.id)}).catch(n)})}createTreeNode(e,t,r){return new Promise((n,i)=>{const s=new URL(t.id);s.hash="";const o=`${s.href}${F(s.href)?(s.href.endsWith("/")?"":"/")+".meta":""}`;this.service.getDatasetStore(e,o).then(n=>(n.addQuads(x.RDFSerializer.serializeToQuads(t,`${s.href}#`)),r&&n.addQuads(x.RDFSerializer.serializeToQuads(r,`${s.href}#`)),this.service.saveDataset(e,o,n))).then(()=>n(t)).catch(i)})}fetchTreeNode(e,t,r){return new Promise((n,i)=>{const s=new URL(t.id);s.hash="";const o=`${s.href}${F(s.href)?(s.href.endsWith("/")?"":"/")+".meta":""}`;this.service.getDatasetStore(e,o).then(e=>{if(x.RDFSerializer.quadsToThing(x.DataFactory.namedNode(t.id),e)){const s=x.RDFSerializer.deserializeFromStore(t.id,e,Zh),o=r?x.RDFSerializer.deserializeFromStore(r,e,Yh):void 0;s?(s.collection=o,n(s)):i(new Error("Node could not be deserialized"))}else i(new Error("Node not found"))}).catch(i)})}findRootNode(e,t){return new Promise((r,n)=>{this.getPropertyContainer(t);Promise.all([this.service.getDatasetStore(e,`${t.id}`)]).then(e=>R(this,[e],void 0,function*([e]){const t=yield this.driver.queryBindings(`SELECT DISTINCT ?node WHERE {\n ?node a <${Wh.Node}> . \n }`,void 0,{sources:[e]});if(0===t.length)return void r(void 0);const n=x.RDFSerializer.deserializeFromStore(x.DataFactory.namedNode(t[0].get("node").value),e);r(n||void 0)})).catch(n)})}getPropertyContainer(e){const t=new URL(e.id);return t.hash="",e.id.endsWith("/property.ttl")&&(t.pathname=t.pathname.replace(/\/property\.ttl$/,"")),t.href.endsWith("/")||(t.pathname+="/"),t}addObservation(e,t,r){return new Promise((n,i)=>{const s=this.getPropertyContainer(t);this.findRootNode(e,t).then(n=>R(this,void 0,void 0,function*(){if(!(n||(yield this.createProperty(e,t),n=yield this.findRootNode(e,t))))throw new Error("Root node could not be created");for(const e of n.relations){if(!e.node)throw console.error(e),new Error("Relation node not found");if(!e.value)throw console.error(e),new Error("Relation value not found")}let i=n.getChildNode(r.resultTime);i&&(i=yield this.fetchTreeNode(e,i,s.href),i=this.filter(i)?i:void 0),i||(i=new Zh,i.id=`${s.href}${r.resultTime.getTime()}/`,yield this.service.createContainer(e,i.id),n.relations.push(new Jh(r.resultTime,i).setPath(x.sosa.resultTime)),yield this.createTreeNode(e,n)),r.id=`${i.id}${this.generateUUID()}.ttl`;const o=new Yh(s.href);return o.members.push(r),yield this.createTreeNode(e,i,o),this.service.saveDataset(e,`${r.id}`,x.RDFSerializer.serializeToStore(r),!0)})).then(()=>{n()}).catch(i)})}fetchObservations(e,t,r={}){return new Promise((n,i)=>{this.findAll({query:Object.assign({},r.after?{resultTime:{$gte:r.after}}:{}),limit:r.limit,uri:t.id,webId:e.info.webId},{dataType:x.Observation}).then(e=>{n(e)}).catch(i)})}}class SolidPropertySink extends A.SinkNode{constructor(e){super(e),this.once("ready",this.onBuild.bind(this))}onBuild(){return new Promise((e,t)=>{this.service=this.model.findService(SolidPropertyService),this.service||t(new Error("No Solid session found")),e()})}onPush(e,t){return new Promise((t,r)=>{Array.isArray(e)?Promise.all(e.map(e=>this.writeFrame(e))).then(()=>t()).catch(r):this.writeFrame(e).then(()=>t()).catch(r)})}prepareProperty(e,t){return new Promise((r,n)=>{this.service.service.getDocumentURL(t,"/properties/").then(i=>{let s;if(e===ud.POSITION){const e=new x.Property(i.href+"position/");e.label="Position",s=this.service.createProperty(t,e)}s.then(r).catch(n)}).catch(n)})}writeFrame(e){return new Promise((t,r)=>{let n=[];for(const e of this.options.properties)e===ud.POSITION&&n.push(this.prepareProperty(e,this.service.session));Promise.all(n).then(t=>{n=[];for(const r of e.getObjects())for(const[i,s]of this.options.properties.entries()){const o=new x.ObservableProperty(t[i]),a=new x.Observation(`_:${e.createdTimestamp}`);a.resultTime=new Date(e.createdTimestamp),a.observedProperties=[o],r.webId&&(a.featuresOfInterest=[new x.FeatureOfInterest(r.webId)]),s===ud.POSITION&&(a.results=[r.position]),n.push(this.service.addObservation(this.service.session,o,a))}return Promise.all(n)}).then(()=>t()).catch(r)})}}var ud;!function(e){e[e.POSITION=0]="POSITION"}(ud||(ud={}));class SolidPropertySource extends A.SourceNode{constructor(e){super(e),this.once("ready",this.onBuild.bind(this))}onBuild(){return new Promise((e,t)=>{this.service=this.model.findService(SolidPropertyService),this.service||t(new Error("No Solid session found")),e()})}onPull(e){throw new Error("Method not implemented.")}}const ld=require("./engine-default")(),hd=new Uint8Array(16);const dd=[];for(let e=0;e<256;++e)dd.push((e+256).toString(16).slice(1));function fd(e,t=0){return(dd[e[t+0]]+dd[e[t+1]]+dd[e[t+2]]+dd[e[t+3]]+"-"+dd[e[t+4]]+dd[e[t+5]]+"-"+dd[e[t+6]]+dd[e[t+7]]+"-"+dd[e[t+8]]+dd[e[t+9]]+"-"+dd[e[t+10]]+dd[e[t+11]]+dd[e[t+12]]+dd[e[t+13]]+dd[e[t+14]]+dd[e[t+15]]).toLowerCase()}const pd=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){e=e||{};const n=e.random??e.rng?.()??crypto.getRandomValues(hd);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 fd(n)}(e,t,r):crypto.randomUUID()};class StorageUtilityBrowser extends StorageUtility{constructor(e,t){super(e,t)}}class ClientAuthentication extends dist_ClientAuthentication{login=async(e,t)=>{"none"!==e.prompt&&await this.sessionInfoManager.clear(e.sessionId);const r=e.redirectUrl??function(e){const t=zs(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}(window.location.href);if(!Bs(r))throw new Error(`${r} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:r,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return void 0===t||void 0===t.clientAppId||void 0===t.issuer||function(e){return void 0!==e.clientExpiresAt&&0!==e.clientExpiresAt&&e.clientExpiresAt<Math.floor(Date.now()/1e3)}(t)?null:t};handleIncomingRedirect=async(e,t)=>{try{const r=await this.redirectHandler.handle(e,t,void 0);return this.fetch=r.fetch.bind(window),this.boundLogout=r.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:r.isLoggedIn,webId:r.webId,sessionId:r.sessionId,expirationDate:r.expirationDate,clientAppId:r.clientAppId}}catch(r){return await this.cleanUrlAfterRedirect(e),void t.emit(Ns,"redirect",r)}};async cleanUrlAfterRedirect(e){const t=zs(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(e=>{setTimeout(()=>e(),1)})}}function _d(e){return"string"==typeof e.oidcIssuer}function gd(e){return"string"==typeof e.redirectUrl}class OidcLoginHandler{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 _d(e)&&gd(e)}async handle(e){if(!_d(e))throw new ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!gd(e))throw new ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await Qs(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([...Ms,...i.filter(e=>"string"==typeof e&&!e.includes(" "))])):Ms)};var i;return this.oidcHandler.handle(n)}}class AuthorizationCodeWithPkceOidcHandler extends AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){const t=e.redirectUrl??"",r={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:t,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,prompt:e.prompt??"consent"},n=new Fo(r);try{const t=await n.createSigninRequest({});return await this.setupRedirectHandler({oidcLoginOptions:e,state:t.state.id,codeVerifier:t.state.code_verifier??"",targetUrl:t.url.toString()})}catch(e){console.error(e)}}}const yd={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 IssuerConfigFetcher{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=>{yd[r]&&(t[yd[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await n.json())}catch(t){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function wd(e,t){await Ks(e,t),await async function(){const e=new xo({});await ko.clearStaleState(e,900);const t=window.localStorage,r=[];for(let e=0;e<=t.length;e+=1){const n=t.key(e);n&&(n.match(/^oidc\..+$/)||n.match(/^solidClientAuthenticationUser:.+$/))&&r.push(n)}r.forEach(e=>t.removeItem(e))}()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,r,n,i,s,o,a,c,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}),this.storageUtility.getForUser(e,"expiresAt",{secure:!1})]);if("string"!=typeof s||Bs(s)){if(void 0!==c&&("string"!=typeof(l=c)||!["DPoP","Bearer"].includes(l)))throw new Error(`Tokens of type [${c}] are not supported.`);var l;if(void 0!==n||void 0!==t||void 0!==r||void 0!==o)return{sessionId:e,webId:r,isLoggedIn:"true"===t,redirectUrl:s,refreshToken:o,issuer:a,clientAppId:n,clientAppSecret:i,tokenType:c??"DPoP",clientExpiresAt:void 0!==u?Number.parseInt(u,10):void 0}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return wd(e,this.storageUtility)}}class FallbackRedirectHandler{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 qs()}}class AuthCodeRedirectHandler{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;constructor(e,t,r,n,i){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.tokerRefresher=i,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=r,this.clientRegistrar=n,this.tokerRefresher=i}async canHandle(e){try{const t=new URL(e);return null!==t.searchParams.get("code")&&null!==t.searchParams.get("state")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const r=new URL(e),n=r.searchParams.get("state"),i=await this.storageUtility.getForUser(n,"sessionId",{errorIfNull:!0}),{issuerConfig:s,codeVerifier:o,redirectUrl:a,dpop:c}=await Gs(i,this.storageUtility,this.issuerConfigFetcher),u=r.searchParams.get("iss");if("string"==typeof u&&u!==s.issuer)throw new Error(`The value of the iss parameter (${u}) does not match the issuer identifier of the authorization server (${s.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(void 0===o)throw new Error(`The code verifier for session ${i} is missing from storage.`);if(void 0===a)throw new Error(`The redirect URL for session ${i} is missing from storage.`);const l=await this.clientRegistrar.getClient({sessionId:i},s),h=Date.now(),d=await Wo(s,l,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:o,redirectUrl:a},c);let f;window.localStorage.removeItem(`oidc.${n}`),void 0!==d.refreshToken&&(f={sessionId:i,refreshToken:d.refreshToken,tokenRefresher:this.tokerRefresher});const p=to(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 cs(a.privateKey))},{secure:o})}(this.storageUtility,i,d.webId,d.clientId,"true",void 0,!0);const _=await this.sessionInfoManager.get(i);if(!_)throw new Error(`Could not retrieve session: [${i}].`);return Object.assign(_,{fetch:p,getLogoutUrl:Ws({idTokenHint:d.idToken,endSessionEndpoint:s.endSessionEndpoint}),expirationDate:"number"==typeof d.expiresIn?h+1e3*d.expiresIn:void 0})}}class AggregateRedirectHandler extends AggregateHandler{constructor(e){super(e)}}class BrowserStorage{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 Redirector{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class dist_ClientRegistrar{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[r,n,i,s,o]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),a=void 0!==i?Number.parseInt(i,10):-1,c=void 0!==n&&0!==a&&Math.floor(Date.now()/1e3)>a;if(r&&("string"==typeof(u=o)&&["dynamic","static","solid-oidc"].includes(u))&&!c)return void 0!==n?{clientId:r,clientSecret:n,clientName:s,clientType:"dynamic",expiresAt:a}:{clientId:r,clientName:s,clientType:o};var u;try{const r=await zo(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 ErrorOidcHandler{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(Ns,n,i)}return qs()}}class TokenRefresher{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 Gs(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 Ho(t,i.issuerConfig,s,r);return void 0!==o.refreshToken&&n?.emit(Cs,o.refreshToken),o}}function bd(e){const t=new InMemoryStorage,r=e.secureStorage||t,n=e.insecureStorage||new BrowserStorage,i=new StorageUtilityBrowser(r,n),s=new IssuerConfigFetcher(i),o=new dist_ClientRegistrar(i),a=new SessionInfoManager(i),c=new TokenRefresher(i,s,o),u=new Redirector,l=new OidcLoginHandler(i,new AuthorizationCodeWithPkceOidcHandler(i,u),s,o),h=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(i,a,s,o,c),new FallbackRedirectHandler]);return new ClientAuthentication(l,h,new IWaterfallLogoutHandler(a,u),a,s)}const md=`${ks}currentSession`,vd=`${ks}currentUrl`;class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;constructor(e={},t=void 0){this.events=new Ja,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=bd({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=bd({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??pd(),isLoggedIn:!1},this.events.on(Ps,()=>window.localStorage.setItem(md,this.info.sessionId)),this.events.on(Ds,()=>this.internalLogout(!1)),this.events.on(Ns,()=>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(md),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(Os)};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(vd);null===e?this.events.emit(Ps):(window.localStorage.removeItem(vd),this.events.emit($s,e))}else if(!0===t.restorePreviousSession){const e=window.localStorage.getItem(md);if(null!==e){if(await async function(e,t,r){const n=await t.validateCurrentSession(e);return null!==n&&(window.localStorage.setItem(vd,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(Ls,e=>{this.info.expirationDate=Date.now()+1e3*e})}}const Sd={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 IssuerConfigFetcher_IssuerConfigFetcher{constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}fetchConfig(e){return R(this,void 0,void 0,function*(){let t;const r=new URL(".well-known/openid-configuration",e.endsWith("/")?e:`${e}/`).href;try{const e=yield fetch(r);t=function(e){const t={};return Object.keys(e).forEach(r=>{Sd[r]&&(t[Sd[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(yield e.json())}catch(t){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return yield this.storageUtility.set(IssuerConfigFetcher_IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t})}}class SolidClientService extends SolidService{constructor(e){var t;super(e),this.options.autoLogin=null!==(t=this.options.autoLogin)&&void 0!==t&&t,this.once("build",this._initialize.bind(this))}get session(){return this._session}set session(e){this._session=e}_initialize(){return new Promise(e=>{this.issuerConfigFetcher=new IssuerConfigFetcher_IssuerConfigFetcher(this.storageUtility),this.handleLogin().then(()=>{e()}).catch(t=>{this.emit("error",t),e()}).finally(()=>{this.emitAsync("ready")})})}login(e=this.options.defaultOidcIssuer,t=!1){return new Promise((t,r)=>{const n=this.createSession({insecureStorage:this.storage,secureStorage:this.storage});this.storage.set("currentSession",n.info.sessionId).then(()=>{const i=this.options.handleRedirect?e=>this.options.handleRedirect(e,e=>{if(e){if(!n.info.isLoggedIn)return void r(e);this.emit("error",e)}t()}):void 0;return n.login({oidcIssuer:e,clientName:this.options.clientName,clientId:this.options.clientId,clientSecret:this.options.clientSecret,redirectUrl:this.options.redirectUrl?this.options.redirectUrl:window.location.href,handleRedirect:i})}).then(()=>{t()}).catch(r)})}handleLogin(){return new Promise((e,t)=>{let r,n,i;this.storage.get("currentSession").then(t=>{if(t){const e="solidClientAuthn:currentSession",r=window.localStorage.getItem(e);r&&t!==r&&window.localStorage.setItem(e,t)}if(t)return i=t,this.findSessionInfoById(t);e(void 0)}).then(e=>R(this,void 0,void 0,function*(){return r=e,n=this.createSession({sessionInfo:Object.assign({sessionId:i},r),insecureStorage:this.storage,secureStorage:this.storage}),this.handleRedirect(n)})).then(e=>R(this,void 0,void 0,function*(){if(e&&e.isLoggedIn){this.session=n,yield this.storage.set("currentSession",e.sessionId);const t=new sd(e.webId);return t.sessionId=e.sessionId,this.storeProfile(t)}throw yield this.storage.delete("currentSession"),new Error("Unable to log in to Solid Pod!")})).then(()=>{this.emit("login",this.session),e(this.session)}).catch(t)})}handleRedirect(e){return R(this,void 0,void 0,function*(){try{const t=new URL(window.location.href);if(null===t.searchParams.get("code")&&null===t.searchParams.get("state")){if(!e)return;const r=yield this.storage.get(`solidClientAuthenticationUser:${e.info.sessionId}:tokens`);if(r){const t=JSON.parse(r),n=yield to(t.accessToken,{fetch,dpopKey:t.dpopKey,refreshOptions:void 0,eventEmitter:void 0,expiresIn:t.expiresIn}),i=yield this.findSessionInfoById(e.info.sessionId);if(!i)throw new Error(`Could not retrieve session: [${e.info.sessionId}].`);const{issuerConfig:s}=yield Gs(e.info.sessionId,this.storageUtility,this.issuerConfigFetcher);return Object.assign(i,{fetch:n,getLogoutUrl:Ws({idTokenHint:t.idToken,endSessionEndpoint:s.endSessionEndpoint}),expirationDate:t.expirationDate}),Object.assign(e.info,i)}return e.handleIncomingRedirect(t.href)}const r=t.searchParams.get("state"),n=yield this.storageUtility.getForUser(r,"sessionId",{errorIfNull:!0}),{issuerConfig:i,codeVerifier:s,redirectUrl:o,dpop:a}=yield Gs(n,this.storageUtility,this.issuerConfigFetcher),c=t.searchParams.get("iss");if("string"==typeof c&&c!==i.issuer)throw new Error(`The value of the iss parameter (${c}) does not match the issuer identifier of the authorization server (${i.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(void 0===s)throw new Error(`The code verifier for session ${n} is missing from storage.`);if(void 0===o)throw new Error(`The redirect URL for session ${n} is missing from storage.`);const u=yield this.clientRegistrar.getClient({sessionId:n},i),l=Date.now(),h=yield Wo(i,u,{grantType:"authorization_code",code:t.searchParams.get("code"),codeVerifier:s,redirectUrl:o},a),d="number"==typeof h.expiresIn?l+1e3*h.expiresIn:void 0;yield this.storage.set(`solidClientAuthenticationUser:${n}:tokens`,JSON.stringify(Object.assign(Object.assign({},h),{expirationDate:d})));const f=yield to(h.accessToken,{fetch,dpopKey:h.dpopKey,refreshOptions:void 0,eventEmitter:void 0,expiresIn:h.expiresIn});yield this.storageUtility.setForUser(n,{webId:h.webId,isLoggedIn:"true"},{secure:!0});const p=yield this.findSessionInfoById(n);if(!p)throw new Error(`Could not retrieve session: [${n}].`);return window.history.replaceState({},document.title,o),Object.assign(p,{fetch:f,getLogoutUrl:Ws({idTokenHint:h.idToken,endSessionEndpoint:i.endSessionEndpoint}),expirationDate:d}),Object.assign(e.info,p)}catch(e){return void this.emit("error",e)}})}createSession(e){return new Session(e)}}})(),s})());
2
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@openhps/core"),require("@openhps/rdf")):"function"==typeof define&&define.amd?define("OpenHPS",["core","rdf"],t):"object"==typeof exports?exports.OpenHPS=t(require("@openhps/core"),require("@openhps/rdf")):(e.OpenHPS=e.OpenHPS||{},e.OpenHPS.solid=t(e.OpenHPS.core,e.OpenHPS.rdf))}("undefined"!=typeof self?self:this,(e,t)=>(()=>{var r={358(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActorInitQuery=void 0;const n=r(638);"undefined"==typeof process&&(globalThis.process=r(606));class ActorInitQuery extends n.ActorInitQueryBase{}t.ActorInitQuery=ActorInitQuery},638(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActorInitQueryBase=void 0;const n=r(180),i=r(412);class ActorInitQueryBase extends n.ActorInit{async test(e){return(0,i.passTestVoid)()}async run(e){throw new Error("ActorInitSparql#run is not supported in the browser.")}}t.ActorInitQueryBase=ActorInitQueryBase},235(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.QueryEngineBase=void 0;const n=r(711),i=r(412);class QueryEngineBase{constructor(e){this.actorInitQuery=e}async queryBindings(e,t){return this.queryOfType(e,t,"bindings")}async queryQuads(e,t){return this.queryOfType(e,t,"quads")}async queryBoolean(e,t){return this.queryOfType(e,t,"boolean")}async queryVoid(e,t){return this.queryOfType(e,t,"void")}async queryOfType(e,t,r){const n=await this.query(e,t);if(n.resultType===r)return await n.execute();throw new Error(`Query result type '${r}' was expected, while '${n.resultType}' was found.`)}async query(e,t){const r=await this.queryOrExplain(e,t);if("explain"in r)throw new Error("Tried to explain a query when in query-only mode");return r}async explain(e,t,r){t.explain=r;return await this.queryOrExplain(e,t)}async queryOrExplain(e,t){const r=i.ActionContext.ensureActionContext(t);r.get(n.KeysInitQuery.invalidateCache)&&await this.invalidateHttpCache();const{result:o}=await this.actorInitQuery.mediatorQueryProcess.mediate({query:e,context:r});return"explain"in o?o:QueryEngineBase.internalToFinalResult(o)}async getResultMediaTypes(e){return e=i.ActionContext.ensureActionContext(e),(await this.actorInitQuery.mediatorQueryResultSerializeMediaTypeCombiner.mediate({context:e,mediaTypes:!0})).mediaTypes}async getResultMediaTypeFormats(e){return e=i.ActionContext.ensureActionContext(e),(await this.actorInitQuery.mediatorQueryResultSerializeMediaTypeFormatCombiner.mediate({context:e,mediaTypeFormats:!0})).mediaTypeFormats}async resultToString(e,t,r){if(r=i.ActionContext.ensureActionContext(r),!t)switch(e.resultType){case"bindings":t="application/json";break;case"quads":t="application/trig";break;default:t="simple"}const n={...await QueryEngineBase.finalToInternalResult(e),context:r};return(await this.actorInitQuery.mediatorQueryResultSerialize.mediate({context:r,handle:n,handleMediaType:t})).handle}invalidateHttpCache(e,t){return t=i.ActionContext.ensureActionContext(t),this.actorInitQuery.mediatorHttpInvalidate.mediate({url:e,context:t})}static internalToFinalResult(e){switch(e.type){case"bindings":return{resultType:"bindings",execute:async()=>e.bindingsStream,metadata:async()=>{const t=await e.metadata();return t.variables=t.variables.map(e=>e.variable),t},context:e.context};case"quads":return{resultType:"quads",execute:async()=>e.quadStream,metadata:async()=>await e.metadata(),context:e.context};case"boolean":return{resultType:"boolean",execute:async()=>e.execute(),context:e.context};case"void":return{resultType:"void",execute:async()=>e.execute(),context:e.context}}}static async finalToInternalResult(e){switch(e.resultType){case"bindings":return{type:"bindings",bindingsStream:await e.execute(),metadata:async()=>{const t=await e.metadata();return t.variables=t.variables.map(e=>({variable:e,canBeUndef:!1})),t}};case"quads":return{type:"quads",quadStream:await e.execute(),metadata:async()=>await e.metadata()};case"boolean":return{type:"boolean",execute:()=>e.execute()};case"void":return{type:"void",execute:()=>e.execute()}}}}t.QueryEngineBase=QueryEngineBase},632(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActorInit=void 0;const n=r(412);class ActorInit extends n.Actor{constructor(e){super(e)}}t.ActorInit=ActorInit},180(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(632),t)},39(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeysStatistics=t.KeysRdfJoin=t.KeysMergeBindingsContext=t.KeysRdfUpdateQuads=t.KeysQuerySourceIdentify=t.KeysRdfParseHtmlScript=t.KeysRdfParseJsonLd=t.KeysQueryOperation=t.KeysExpressionEvaluator=t.KeysInitQuery=t.KeysHttpProxy=t.KeysHttpMemento=t.KeysHttpWayback=t.KeysHttp=t.KeysCore=void 0;const n=r(412);t.KeysCore={log:n.CONTEXT_KEY_LOGGER},t.KeysHttp={includeCredentials:new n.ActionContextKey("@comunica/bus-http:include-credentials"),auth:new n.ActionContextKey("@comunica/bus-http:auth"),fetch:new n.ActionContextKey("@comunica/bus-http:fetch"),httpTimeout:new n.ActionContextKey("@comunica/bus-http:http-timeout"),httpBodyTimeout:new n.ActionContextKey("@comunica/bus-http:http-body-timeout"),httpRetryCount:new n.ActionContextKey("@comunica/bus-http:http-retry-count"),httpRetryDelayFallback:new n.ActionContextKey("@comunica/bus-http:http-retry-delay-fallback"),httpRetryDelayLimit:new n.ActionContextKey("@comunica/bus-http:http-retry-delay-limit"),httpRetryStatusCodes:new n.ActionContextKey("@comunica/bus-http:http-retry-status-codes")},t.KeysHttpWayback={recoverBrokenLinks:new n.ActionContextKey("@comunica/bus-http:recover-broken-links")},t.KeysHttpMemento={datetime:new n.ActionContextKey("@comunica/actor-http-memento:datetime")},t.KeysHttpProxy={httpProxyHandler:new n.ActionContextKey("@comunica/actor-http-proxy:httpProxyHandler")},t.KeysInitQuery={querySourcesUnidentified:new n.ActionContextKey("@comunica/actor-init-query:querySourcesUnidentified"),initialBindings:new n.ActionContextKey("@comunica/actor-init-query:initialBindings"),queryFormat:new n.ActionContextKey("@comunica/actor-init-query:queryFormat"),graphqlSingularizeVariables:new n.ActionContextKey("@comunica/actor-init-query:singularizeVariables"),lenient:new n.ActionContextKey("@comunica/actor-init-query:lenient"),queryString:new n.ActionContextKey("@comunica/actor-init-query:queryString"),query:new n.ActionContextKey("@comunica/actor-init-query:query"),baseIRI:new n.ActionContextKey("@comunica/actor-init-query:baseIRI"),fileBaseIRI:new n.ActionContextKey("@comunica/actor-init-query:fileBaseIRI"),functionArgumentsCache:new n.ActionContextKey("@comunica/actor-init-query:functionArgumentsCache"),queryTimestamp:new n.ActionContextKey("@comunica/actor-init-query:queryTimestamp"),queryTimestampHighResolution:new n.ActionContextKey("@comunica/actor-init-query:queryTimestampHighResolution"),extensionFunctionCreator:new n.ActionContextKey("@comunica/actor-init-query:extensionFunctionCreator"),extensionFunctions:new n.ActionContextKey("@comunica/actor-init-query:extensionFunctions"),extensionFunctionsAlwaysPushdown:new n.ActionContextKey("@comunica/actor-init-query:extensionFunctionsAlwaysPushdown"),cliArgsHandlers:new n.ActionContextKey("@comunica/actor-init-query:cliArgsHandlers"),explain:new n.ActionContextKey("@comunica/actor-init-query:explain"),physicalQueryPlanLogger:new n.ActionContextKey("@comunica/actor-init-query:physicalQueryPlanLogger"),physicalQueryPlanNode:new n.ActionContextKey("@comunica/actor-init-query:physicalQueryPlanNode"),jsonLdContext:new n.ActionContextKey("@context"),invalidateCache:new n.ActionContextKey("@comunica/actor-init-query:invalidateCache"),dataFactory:new n.ActionContextKey("@comunica/actor-init-query:dataFactory"),distinctConstruct:new n.ActionContextKey("@comunica/actor-init-query:distinctConstruct")},t.KeysExpressionEvaluator={extensionFunctionCreator:new n.ActionContextKey("@comunica/utils-expression-evaluator:extensionFunctionCreator"),superTypeProvider:new n.ActionContextKey("@comunica/utils-expression-evaluator:superTypeProvider"),defaultTimeZone:new n.ActionContextKey("@comunica/utils-expression-evaluator:defaultTimeZone"),actionContext:new n.ActionContextKey("@comunica/utils-expression-evaluator:actionContext")},t.KeysQueryOperation={operation:new n.ActionContextKey("@comunica/bus-query-operation:operation"),joinLeftMetadata:new n.ActionContextKey("@comunica/bus-query-operation:joinLeftMetadata"),joinRightMetadatas:new n.ActionContextKey("@comunica/bus-query-operation:joinRightMetadatas"),joinBindings:new n.ActionContextKey("@comunica/bus-query-operation:joinBindings"),readOnly:new n.ActionContextKey("@comunica/bus-query-operation:readOnly"),isPathArbitraryLengthDistinctKey:new n.ActionContextKey("@comunica/bus-query-operation:isPathArbitraryLengthDistinct"),limitIndicator:new n.ActionContextKey("@comunica/bus-query-operation:limitIndicator"),unionDefaultGraph:new n.ActionContextKey("@comunica/bus-query-operation:unionDefaultGraph"),querySources:new n.ActionContextKey("@comunica/bus-query-operation:querySources")},t.KeysRdfParseJsonLd={documentLoader:new n.ActionContextKey("@comunica/actor-rdf-parse-jsonld:documentLoader"),strictValues:new n.ActionContextKey("@comunica/actor-rdf-parse-jsonld:strictValues"),parserOptions:new n.ActionContextKey("@comunica/actor-rdf-parse-jsonld:parserOptions")},t.KeysRdfParseHtmlScript={processingHtmlScript:new n.ActionContextKey("@comunica/actor-rdf-parse-html-script:processingHtmlScript"),extractAllScripts:new n.ActionContextKey("extractAllScripts")},t.KeysQuerySourceIdentify={sourceIds:new n.ActionContextKey("@comunica/bus-query-source-identify:sourceIds"),hypermediaSourcesAggregatedStores:new n.ActionContextKey("@comunica/bus-query-source-identify:hypermediaSourcesAggregatedStores"),traverse:new n.ActionContextKey("@comunica/bus-query-source-identify:traverse")},t.KeysRdfUpdateQuads={destination:new n.ActionContextKey("@comunica/bus-rdf-update-quads:destination")},t.KeysMergeBindingsContext={sourcesBinding:new n.ActionContextKey("@comunica/bus-merge-bindings-context:sourcesBinding")},t.KeysRdfJoin={lastPhysicalJoin:new n.ActionContextKey("@comunica/bus-rdf-join:lastPhysicalJoin")},t.KeysStatistics={discoveredLinks:new n.ActionContextKey("@comunica/statistic:discoveredLinks"),dereferencedLinks:new n.ActionContextKey("@comunica/statistic:dereferencedLinks"),intermediateResults:new n.ActionContextKey("@comunica/statistic:intermediateResults")}},711(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(39),t)},301(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActionContextKey=t.ActionContext=void 0;const n=r(187);class ActionContext{constructor(e={}){this.map=(0,n.Map)(e)}setDefault(e,t){return this.has(e)?this:this.set(e,t)}set(e,t){return this.setRaw(e.name,t)}setRaw(e,t){return new ActionContext(this.map.set(e,t))}delete(e){return new ActionContext(this.map.delete(e.name))}get(e){return this.getRaw(e.name)}getRaw(e){return this.map.get(e)}getSafe(e){if(!this.has(e))throw new Error(`Context entry ${e.name} is required but not available`);return this.get(e)}has(e){return this.hasRaw(e.name)}hasRaw(e){return this.map.has(e)}merge(...e){let t=this;for(const r of e)for(const e of r.keys())t=t.set(e,r.get(e));return t}keys(){return[...this.map.keys()].map(e=>new ActionContextKey(e))}toJS(){return this.map.toJS()}toString(){return`ActionContext(${JSON.stringify(this.map.toJS())})`}[Symbol.for("nodejs.util.inspect.custom")](){return`ActionContext(${JSON.stringify(this.map.toJS(),null," ")})`}static ensureActionContext(e){return e instanceof ActionContext?e:new ActionContext((0,n.Map)(e??{}))}}t.ActionContext=ActionContext;class ActionContextKey{constructor(e){this.name=e}}t.ActionContextKey=ActionContextKey},782(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActionObserver=void 0;t.ActionObserver=class ActionObserver{constructor(e){Object.assign(this,e)}}},681(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Actor=void 0;const n=r(983);class Actor{constructor(e){this.beforeActors=[],Object.assign(this,e),this.bus.subscribe(this),this.beforeActors.length>0&&this.bus.addDependencies(this,this.beforeActors),e.busFailMessage&&(this.bus.failMessage=e.busFailMessage)}static getContextLogger(e){return e.get(n.CONTEXT_KEY_LOGGER)}runObservable(e,t){const r=this.run(e,t);return this.bus.onRun(this,e,r),r}getDefaultLogData(e,t){const r=t?t():{};return r.actor=this.name,r}logTrace(e,t,r){const n=Actor.getContextLogger(e);n&&n.trace(t,this.getDefaultLogData(e,r))}logDebug(e,t,r){const n=Actor.getContextLogger(e);n&&n.debug(t,this.getDefaultLogData(e,r))}logInfo(e,t,r){const n=Actor.getContextLogger(e);n&&n.info(t,this.getDefaultLogData(e,r))}logWarn(e,t,r){const n=Actor.getContextLogger(e);n&&n.warn(t,this.getDefaultLogData(e,r))}logError(e,t,r){const n=Actor.getContextLogger(e);n&&n.error(t,this.getDefaultLogData(e,r))}logFatal(e,t,r){const n=Actor.getContextLogger(e);n&&n.fatal(t,this.getDefaultLogData(e,r))}}t.Actor=Actor},126(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Bus=void 0;t.Bus=class Bus{constructor(e){this.actors=[],this.observers=[],this.dependencyLinks=new Map,Object.assign(this,e),this.failMessage=`All actors over bus ${this.name} failed to handle an action`}subscribe(e){this.actors.push(e),this.reorderForDependencies()}subscribeObserver(e){this.observers.push(e)}unsubscribe(e){const t=this.actors.indexOf(e);return t>=0&&(this.actors.splice(t,1),!0)}unsubscribeObserver(e){const t=this.observers.indexOf(e);return t>=0&&(this.observers.splice(t,1),!0)}publish(e){return this.actors.map(t=>({actor:t,reply:t.test(e)}))}onRun(e,t,r){for(const n of this.observers)n.onRun(e,t,r)}addDependencies(e,t){for(const r of t){let t=this.dependencyLinks.get(r);t||(t=[],this.dependencyLinks.set(r,t)),t.push(e)}this.reorderForDependencies()}reorderForDependencies(){if(this.dependencyLinks.size>0){const e=[];for(const t of this.dependencyLinks.keys()){const r=this.actors.indexOf(t);r>=0&&(this.actors.splice(r,1),e.push(t))}for(;e.length>0;){let t=-1;for(let r=0;r<e.length;r++){let n=!0;for(const t of this.dependencyLinks.get(e[r]))if(!this.actors.includes(t)&&e.includes(t)){n=!1;break}if(n){t=r;break}}if(t<0)throw new Error(`Cyclic dependency links detected in bus ${this.name}`);const r=e.splice(t,1)[0];this.actors.push(r)}}}}},437(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BusIndexed=void 0;const n=r(126);class BusIndexed extends n.Bus{constructor(e){super(e),this.actorsIndex={}}subscribe(e){const t=this.getActorIdentifiers(e)??["_undefined_"];for(const r of t){let t=this.actorsIndex[r];t||(t=this.actorsIndex[r]=[]),t.push(e),super.subscribe(e)}}unsubscribe(e){const t=this.getActorIdentifiers(e)??["_undefined_"];let r=!1;for(const n of t){const t=this.actorsIndex[n];if(t){const r=t.indexOf(e);r>=0&&t.splice(r,1),0===t.length&&delete this.actorsIndex[n]}r=r||super.unsubscribe(e)}return r}publish(e){const t=this.getActionIdentifier(e);if(t){return[...this.actorsIndex[t]||[],...this.actorsIndex._undefined_||[]].map(t=>({actor:t,reply:t.test(e)}))}return super.publish(e)}getActorIdentifiers(e){const t=this.actorIdentifierFields.reduce((e,t)=>e[t],e);if(t)return Array.isArray(t)?t:[t]}getActionIdentifier(e){return this.actionIdentifierFields.reduce((e,t)=>e[t],e)}}t.BusIndexed=BusIndexed},983(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CONTEXT_KEY_LOGGER=void 0;const n=r(301);t.CONTEXT_KEY_LOGGER=new n.ActionContextKey("@comunica/core:log")},991(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Mediator=void 0;class Mediator{constructor(e){Object.assign(this,e)}publish(e){const t=this.bus.publish(e);if(0===t.length)throw new Error(`No actors are able to reply to a message in the bus ${this.bus.name}`);return t}async mediateActor(e){return await this.mediateWith(e,this.publish(e))}async mediateTestable(e){return(await this.mediateActor(e)).mapAsync((t,r)=>t.runObservable(e,r))}async mediate(e){return(await this.mediateTestable(e)).getOrThrow()}constructFailureMessage(e,t){const r="\n ";return`${this.bus.failMessage.replaceAll(/\$\{(.*?)\}/gu,(t,r)=>Mediator.getObjectValue({action:e},r.split("."))||t)}\n Error messages of failing actors:${r}${t.join(r)}`}static getObjectValue(e,t){return 0===t.length?e:e?Mediator.getObjectValue(e[t[0]],t.slice(1)):void 0}}t.Mediator=Mediator},612(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestResultFailed=t.TestResultPassed=t.failTest=t.passTestVoidWithSideData=t.passTestWithSideData=t.passTestVoid=t.passTest=void 0,t.passTest=function(e){return new TestResultPassed(e,void 0)},t.passTestVoid=function(){return new TestResultPassed(!0,void 0)},t.passTestWithSideData=function(e,t){return new TestResultPassed(e,t)},t.passTestVoidWithSideData=function(e){return new TestResultPassed(!0,e)},t.failTest=function(e){return new TestResultFailed(e)};class TestResultPassed{constructor(e,t){this.value=e,this.sideData=t}isPassed(){return!0}isFailed(){return!1}get(){return this.value}getOrThrow(){return this.value}getSideData(){return this.sideData}getFailMessage(){}map(e){return new TestResultPassed(e(this.value,this.sideData),this.sideData)}async mapAsync(e){return new TestResultPassed(await e(this.value,this.sideData),this.sideData)}}t.TestResultPassed=TestResultPassed;class TestResultFailed{constructor(e){this.failMessage=e}isPassed(){return!1}isFailed(){return!0}get(){}getOrThrow(){throw new Error(this.getFailMessage())}getSideData(){throw new Error(this.getFailMessage())}getFailMessage(){return this.failMessage}map(){return this}async mapAsync(){return this}}t.TestResultFailed=TestResultFailed},412(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(301),t),i(r(126),t),i(r(437),t),i(r(983),t),i(r(782),t),i(r(681),t),i(r(991),t),i(r(612),t)},568(e){"use strict";const{AbortController:t,AbortSignal:r}="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t},526(e,t){"use strict";t.toByteArray=function(e){var t,r,o=s(e),a=o[0],c=o[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,a,c)),l=0,d=c>0?a-4:a;for(r=0;r<d;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,o=[],a=16383,s=0,c=n-i;s<c;s+=a)o.push(u(e,s,s+a>c?c:s+a));1===i?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=o[a],n[o.charCodeAt(a)]=a;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function c(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function u(e,t,r){for(var n,i=[],o=t;o<r;o+=3)n=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),i.push(c(n));return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287(e,t,r){"use strict";const n=r(526),i=r(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=c,t.SlowBuffer=function(e){+e!=e&&(e=0);return c.alloc(+e)},t.INSPECT_MAX_BYTES=50;const a=2147483647;function s(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(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 d(e)}return u(e,t,r)}function u(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=s(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(G(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return h(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(G(e,ArrayBuffer)||e&&G(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(G(e,SharedArrayBuffer)||e&&G(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 c.from(n,t,r);const i=function(e){if(c.isBuffer(e)){const t=0|p(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?s(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.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 l(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 d(e){return l(e),s(e<0?0:0|p(e))}function h(e){const t=e.length<0?0:0|p(e.length),r=s(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,c.prototype),n}function p(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function m(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||G(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 K(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return W(e).length;default:if(i)return n?-1:K(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 j(this,t,r);case"utf8":case"utf-8":return T(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return k(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function g(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function _(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),V(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=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:b(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):b(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){let o,a=1,s=e.length,c=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;a=2,s/=2,c/=2,r/=2}function u(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){let n=-1;for(o=r;o<s;o++)if(u(e,o)===u(t,-1===n?0:o-n)){if(-1===n&&(n=o),o-n+1===c)return n*a}else-1!==n&&(o-=o-n),n=-1}else for(r+c>s&&(r=s-c),o=r;o>=0;o--){let r=!0;for(let n=0;n<c;n++)if(u(e,o+n)!==u(t,n)){r=!1;break}if(r)return o}return-1}function w(e,t,r,n){r=Number(r)||0;const i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;const o=t.length;let a;for(n>o/2&&(n=o/2),a=0;a<n;++a){const n=parseInt(t.substr(2*a,2),16);if(V(n))return a;e[r+a]=n}return a}function v(e,t,r,n){return J(K(t,e.length-r),e,r,n)}function S(e,t,r,n){return J(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 x(e,t,r,n){return J(W(t),e,r,n)}function I(e,t,r,n){return J(function(e,t){let r,n,i;const o=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)r=e.charCodeAt(a),n=r>>8,i=r%256,o.push(i),o.push(n);return o}(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 T(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i<r;){const t=e[i];let o=null,a=t>239?4:t>223?3:t>191?2:1;if(i+a<=r){let r,n,s,c;switch(a){case 1:t<128&&(o=t);break;case 2:r=e[i+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(o=c));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(c=(15&t)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:r=e[i+1],n=e[i+2],s=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(c=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=a}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=E));return r}(n)}t.kMaxLength=a,c.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}}(),c.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(c.prototype,"parent",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.buffer}}),Object.defineProperty(c.prototype,"offset",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.byteOffset}}),c.poolSize=8192,c.from=function(e,t,r){return u(e,t,r)},Object.setPrototypeOf(c.prototype,Uint8Array.prototype),Object.setPrototypeOf(c,Uint8Array),c.alloc=function(e,t,r){return function(e,t,r){return l(e),e<=0?s(e):void 0!==t?"string"==typeof r?s(e).fill(t,r):s(e).fill(t):s(e)}(e,t,r)},c.allocUnsafe=function(e){return d(e)},c.allocUnsafeSlow=function(e){return d(e)},c.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==c.prototype},c.compare=function(e,t){if(G(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),G(t,Uint8Array)&&(t=c.from(t,t.offset,t.byteLength)),!c.isBuffer(e)||!c.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,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},c.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}},c.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return c.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=c.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(G(t,Uint8Array))i+t.length>n.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},c.byteLength=m,c.prototype._isBuffer=!0,c.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)g(this,t,t+1);return this},c.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)g(this,t,t+3),g(this,t+1,t+2);return this},c.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)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},c.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):y.apply(this,arguments)},c.prototype.toLocaleString=c.prototype.toString,c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},o&&(c.prototype[o]=c.prototype.inspect),c.prototype.compare=function(e,t,r,n,i){if(G(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.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 o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(o,a),u=this.slice(n,i),l=e.slice(t,r);for(let e=0;e<s;++e)if(u[e]!==l[e]){o=u[e],a=l[e];break}return o<a?-1:a<o?1:0},c.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},c.prototype.indexOf=function(e,t,r){return _(this,e,t,r,!0)},c.prototype.lastIndexOf=function(e,t,r){return _(this,e,t,r,!1)},c.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 o=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return x(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=4096;function R(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 k(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 j(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+=X[e[n]];return i}function N(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 C(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 P(e,t,r,n,i,o){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function O(e,t,r,n,i){z(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function F(e,t,r,n,i){z(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function q(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function M(e,t,r,n,o){return t=+t,r>>>=0,o||q(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function $(e,t,r,n,o){return t=+t,r>>>=0,o||q(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.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,c.prototype),n},c.prototype.readUintLE=c.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return n},c.prototype.readUintBE=c.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=Y(function(e){B(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||Q(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))}),c.prototype.readBigUInt64BE=Y(function(e){B(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||Q(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)}),c.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},c.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=Y(function(e){B(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||Q(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)}),c.prototype.readBigInt64BE=Y(function(e){B(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||Q(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)}),c.prototype.readFloatLE=function(e,t){return e>>>=0,t||C(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){P(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[t]=255&e;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r},c.prototype.writeUintBE=c.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){P(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(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},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(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},c.prototype.writeBigUInt64LE=Y(function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeBigUInt64BE=Y(function(e,t=0){return F(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let i=0,o=1,a=0;for(this[t]=255&e;++i<r&&(o*=256);)e<0&&0===a&&0!==this[t+i-1]&&(a=1),this[t+i]=(e/o|0)-a&255;return t+r},c.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let i=r-1,o=1,a=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/o|0)-a&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(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},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(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},c.prototype.writeBigInt64LE=Y(function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeBigInt64BE=Y(function(e,t=0){return F(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeFloatLE=function(e,t,r){return M(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return M(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return $(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return $(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(!c.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},c.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&&!c.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 o=c.isBuffer(e)?e:c.from(e,n),a=o.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%a]}return this};const D={};function L(e,t,r){D[e]=class NodeError 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 U(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 z(e,t,r,n,i,o){if(e>r||e<t){const n="bigint"==typeof t?"n":"";let i;throw i=o>3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new D.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){B(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||Q(t,e.length-(r+1))}(n,i,o)}function B(e,t){if("number"!=typeof e)throw new D.ERR_INVALID_ARG_TYPE(t,"number",e)}function Q(e,t,r){if(Math.floor(e)!==e)throw B(e,r),new D.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new D.ERR_BUFFER_OUT_OF_BOUNDS;throw new D.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}L("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),L("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=U(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=U(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function K(e,t){let r;t=t||1/0;const n=e.length;let i=null;const o=[];for(let a=0;a<n;++a){if(r=e.charCodeAt(a),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.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;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function W(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(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 G(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=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 Y(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},945(e,t,r){var n="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==r.g&&r.g,i=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var n=void 0!==e&&e||"undefined"!=typeof self&&self||void 0!==r.g&&r.g||{},i="URLSearchParams"in n,o="Symbol"in n&&"iterator"in Symbol,a="FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(e){return!1}}(),s="FormData"in n,c="ArrayBuffer"in n;if(c)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],l=ArrayBuffer.isView||function(e){return e&&u.indexOf(Object.prototype.toString.call(e))>-1};function d(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function h(e){return"string"!=typeof e&&(e=String(e)),e}function f(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return o&&(t[Symbol.iterator]=function(){return t}),t}function p(e){this.map={},e instanceof p?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function m(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function y(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function g(e){var t=new FileReader,r=y(t);return t.readAsArrayBuffer(e),r}function _(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:a&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:s&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:i&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():c&&a&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=_(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c&&(ArrayBuffer.prototype.isPrototypeOf(e)||l(e))?this._bodyArrayBuffer=_(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):i&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a&&(this.blob=function(){var e=m(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var e=m(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}if(a)return this.blob().then(g);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,r,n,i,o=m(this);if(o)return o;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=y(t),n=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=n?n[1]:"utf-8",t.readAsText(e,i),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n<t.length;n++)r[n]=String.fromCharCode(t[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s&&(this.formData=function(){return this.text().then(S)}),this.json=function(){return this.text().then(JSON.parse)},this}p.prototype.append=function(e,t){e=d(e),t=h(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},p.prototype.delete=function(e){delete this.map[d(e)]},p.prototype.get=function(e){return e=d(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(d(e))},p.prototype.set=function(e,t){this.map[d(e)]=h(t)},p.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},p.prototype.keys=function(){var e=[];return this.forEach(function(t,r){e.push(r)}),f(e)},p.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),f(e)},p.prototype.entries=function(){var e=[];return this.forEach(function(t,r){e.push([r,t])}),f(e)},o&&(p.prototype[Symbol.iterator]=p.prototype.entries);var w=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function v(e,t){if(!(this instanceof v))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r,i,o=(t=t||{}).body;if(e instanceof v){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new p(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,o||null==e._bodyInit||(o=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new p(t.headers)),this.method=(r=t.method||this.method||"GET",i=r.toUpperCase(),w.indexOf(i)>-1?i:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in n)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(o),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var a=/([?&])_=[^&]*/;if(a.test(this.url))this.url=this.url.replace(a,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function S(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}}),t}function x(e,t){if(!(this instanceof x))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},b.call(v.prototype),b.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},x.error=function(){var e=new x(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var I=[301,302,303,307,308];x.redirect=function(e,t){if(-1===I.indexOf(t))throw new RangeError("Invalid status code");return new x(null,{status:t,headers:{location:e}})},t.DOMException=n.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function A(e,r){return new Promise(function(i,o){var s=new v(e,r);if(s.signal&&s.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function l(){u.abort()}if(u.onload=function(){var e,t,r={statusText:u.statusText,headers:(e=u.getAllResponseHeaders()||"",t=new p,e.replace(/\r?\n[\t ]+/g," ").split("\r").map(function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e}).forEach(function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();try{t.append(n,i)}catch(e){console.warn("Response "+e.message)}}}),t)};0===s.url.indexOf("file://")&&(u.status<200||u.status>599)?r.status=200:r.status=u.status,r.url="responseURL"in u?u.responseURL:r.headers.get("X-Request-URL");var n="response"in u?u.response:u.responseText;setTimeout(function(){i(new x(n,r))},0)},u.onerror=function(){setTimeout(function(){o(new TypeError("Network request failed"))},0)},u.ontimeout=function(){setTimeout(function(){o(new TypeError("Network request timed out"))},0)},u.onabort=function(){setTimeout(function(){o(new t.DOMException("Aborted","AbortError"))},0)},u.open(s.method,function(e){try{return""===e&&n.location.href?n.location.href:e}catch(t){return e}}(s.url),!0),"include"===s.credentials?u.withCredentials=!0:"omit"===s.credentials&&(u.withCredentials=!1),"responseType"in u&&(a?u.responseType="blob":c&&(u.responseType="arraybuffer")),r&&"object"==typeof r.headers&&!(r.headers instanceof p||n.Headers&&r.headers instanceof n.Headers)){var f=[];Object.getOwnPropertyNames(r.headers).forEach(function(e){f.push(d(e)),u.setRequestHeader(e,h(r.headers[e]))}),s.headers.forEach(function(e,t){-1===f.indexOf(t)&&u.setRequestHeader(t,e)})}else s.headers.forEach(function(e,t){u.setRequestHeader(t,e)});s.signal&&(s.signal.addEventListener("abort",l),u.onreadystatechange=function(){4===u.readyState&&s.signal.removeEventListener("abort",l)}),u.send(void 0===s._bodyInit?null:s._bodyInit)})}A.polyfill=!0,n.fetch||(n.fetch=A,n.Headers=p,n.Request=v,n.Response=x),t.Headers=p,t.Request=v,t.Response=x,t.fetch=A}({})}(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var o=n.fetch?n:i;(t=o.fetch).default=o.fetch,t.fetch=o.fetch,t.Headers=o.Headers,t.Request=o.Request,t.Response=o.Response,e.exports=t},7(e){"use strict";var t,r="object"==typeof Reflect?Reflect:null,n=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise(function(r,n){function i(r){e.removeListener(t,o),n(r)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&m(e,"error",t,r)}(e,i,{once:!0})})},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var a=10;function s(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,r,n){var i,o,a,u;if(s(r),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),a=o[t]),void 0===a)a=o[t]=r,++e._eventsCount;else if("function"==typeof a?a=o[t]=n?[r,a]:[a,r]:n?a.unshift(r):a.push(r),(i=c(e))>0&&a.length>i&&!a.warned){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=a.length,u=l,console&&console.warn&&console.warn(u)}return e}function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=l.bind(n);return i.listener=r,n.wrapFn=i,i}function h(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):p(i,i.length)}function f(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function p(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function m(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(o){n.once&&e.removeEventListener(t,i),r(o)})}}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return c(this)},o.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var u=c.length,l=p(c,u);for(r=0;r<u;++r)n(l[r],this,t)}return!0},o.prototype.addListener=function(e,t){return u(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return u(this,e,t,!0)},o.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},o.prototype.removeListener=function(e,t){var r,n,i,o,a;if(s(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,o=Object.keys(r);for(n=0;n<o.length;++n)"removeListener"!==(i=o[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},o.prototype.listeners=function(e){return h(this,e,!0)},o.prototype.rawListeners=function(e){return h(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},o.prototype.listenerCount=f,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},251(e,t){t.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,c=(1<<s)-1,u=c>>1,l=-7,d=r?i-1:0,h=r?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-l)-1,f>>=-l,l+=s;l>0;o=256*o+e[t+d],d+=h,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+d],d+=h,l-=8);if(0===o)o=1-u;else{if(o===c)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),o-=u}return(f?-1:1)*a*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var a,s,c,u=8*o-i-1,l=(1<<u)-1,d=l>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(a++,c/=2),a+d>=l?(s=0,a=l):a+d>=1?(s=(t*c-1)*Math.pow(2,i),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;e[r+f]=255&s,f+=p,s/=256,i-=8);for(a=a<<i|s,u+=i;u>0;e[r+f]=255&a,f+=p,a/=256,u-=8);e[r+f-p]|=128*m}},187(e,t,r){"use strict";r.d(t,{Map:()=>St});var n="@@__IMMUTABLE_INDEXED__@@";function i(e){return Boolean(e&&e[n])}var o="@@__IMMUTABLE_KEYED__@@";function a(e){return Boolean(e&&e[o])}function s(e){return a(e)||i(e)}var c="@@__IMMUTABLE_ITERABLE__@@";function u(e){return Boolean(e&&e[c])}var l=function(e){return u(e)?e:W(e)},d=function(e){function t(e){return a(e)?e:J(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(l),h=function(e){function t(e){return i(e)?e:G(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(l),f=function(e){function t(e){return u(e)&&!s(e)?e:V(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(l);l.Keyed=d,l.Indexed=h,l.Set=f;var p="function"==typeof Symbol&&Symbol.iterator,m="@@iterator",y=p||m,g=function(e){this.next=e};function _(e,t,r,n){var i=0===e?t:1===e?r:[t,r];return n?n.value=i:n={value:i,done:!1},n}function b(){return{value:void 0,done:!0}}function w(e){return!!Array.isArray(e)||!!x(e)}function v(e){return!(!e||"function"!=typeof e.next)}function S(e){var t=x(e);return t&&t.call(e)}function x(e){var t=e&&(p&&e[p]||e[m]);if("function"==typeof t)return t}g.prototype.toString=function(){return"[Iterator]"},g.KEYS=0,g.VALUES=1,g.ENTRIES=2,g.prototype.inspect=g.prototype.toSource=function(){return this.toString()},g.prototype[y]=function(){return this};var I="delete",A=32,T=31,E={};function R(e){e&&(e.value=!0)}function k(){}function j(e){return void 0===e.size&&(e.size=e.__iterate(C)),e.size}function N(e,t){if("number"!=typeof t){var r=t>>>0;if(""+r!==t||4294967295===r)return NaN;t=r}return t<0?j(e)+t:t}function C(){return!0}function P(e,t,r){return(0===e&&!M(e)||void 0!==r&&e<=-r)&&(void 0===t||void 0!==r&&t>=r)}function O(e,t){return q(e,t,0)}function F(e,t){return q(e,t,t)}function q(e,t,r){return void 0===e?r:M(e)?t===1/0?t:0|Math.max(0,t+e):void 0===t||t===e?e:0|Math.min(t,e)}function M(e){return e<0||0===e&&1/e==-1/0}var $="@@__IMMUTABLE_RECORD__@@";function D(e){return Boolean(e&&e[$])}function L(e){return u(e)||D(e)}var U="@@__IMMUTABLE_ORDERED__@@";function z(e){return Boolean(e&&e[U])}var B="@@__IMMUTABLE_SEQ__@@";function Q(e){return Boolean(e&&e[B])}var H=Object.prototype.hasOwnProperty;function K(e){return!(!Array.isArray(e)&&"string"!=typeof e)||e&&"object"==typeof e&&Number.isInteger(e.length)&&e.length>=0&&(0===e.length?1===Object.keys(e).length:e.hasOwnProperty(e.length-1))}var W=function(e){function t(e){return null==e?te():L(e)?e.toSeq():function(e){var t=ie(e);if(t)return(n=x(r=e))&&n===r.entries?t.fromEntrySeq():function(e){var t=x(e);return t&&t===e.keys}(e)?t.toSetSeq():t;var r,n;if("object"==typeof e)return new Y(e);throw new TypeError("Expected Array or collection object of values, or keyed object: "+e)}(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.toSeq=function(){return this},t.prototype.toString=function(){return this.__toString("Seq {","}")},t.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},t.prototype.__iterate=function(e,t){var r=this._cache;if(r){for(var n=r.length,i=0;i!==n;){var o=r[t?n-++i:i++];if(!1===e(o[1],o[0],this))break}return i}return this.__iterateUncached(e,t)},t.prototype.__iterator=function(e,t){var r=this._cache;if(r){var n=r.length,i=0;return new g(function(){if(i===n)return{value:void 0,done:!0};var o=r[t?n-++i:i++];return _(e,o[0],o[1])})}return this.__iteratorUncached(e,t)},t}(l),J=function(e){function t(e){return null==e?te().toKeyedSeq():u(e)?a(e)?e.toSeq():e.fromEntrySeq():D(e)?e.toSeq():re(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.toKeyedSeq=function(){return this},t}(W),G=function(e){function t(e){return null==e?te():u(e)?a(e)?e.entrySeq():e.toIndexedSeq():D(e)?e.toSeq().entrySeq():ne(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return t(arguments)},t.prototype.toIndexedSeq=function(){return this},t.prototype.toString=function(){return this.__toString("Seq [","]")},t}(W),V=function(e){function t(e){return(u(e)&&!s(e)?e:G(e)).toSetSeq()}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return t(arguments)},t.prototype.toSetSeq=function(){return this},t}(W);W.isSeq=Q,W.Keyed=J,W.Set=V,W.Indexed=G,W.prototype[B]=!0;var X=function(e){function t(e){this._array=e,this.size=e.length}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.get=function(e,t){return this.has(e)?this._array[N(this,e)]:t},t.prototype.__iterate=function(e,t){for(var r=this._array,n=r.length,i=0;i!==n;){var o=t?n-++i:i++;if(!1===e(r[o],o,this))break}return i},t.prototype.__iterator=function(e,t){var r=this._array,n=r.length,i=0;return new g(function(){if(i===n)return{value:void 0,done:!0};var o=t?n-++i:i++;return _(e,o,r[o])})},t}(G),Y=function(e){function t(e){var t=Object.keys(e).concat(Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e):[]);this._object=e,this._keys=t,this.size=t.length}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.get=function(e,t){return void 0===t||this.has(e)?this._object[e]:t},t.prototype.has=function(e){return H.call(this._object,e)},t.prototype.__iterate=function(e,t){for(var r=this._object,n=this._keys,i=n.length,o=0;o!==i;){var a=n[t?i-++o:o++];if(!1===e(r[a],a,this))break}return o},t.prototype.__iterator=function(e,t){var r=this._object,n=this._keys,i=n.length,o=0;return new g(function(){if(o===i)return{value:void 0,done:!0};var a=n[t?i-++o:o++];return _(e,a,r[a])})},t}(J);Y.prototype[U]=!0;var Z,ee=function(e){function t(e){this._collection=e,this.size=e.length||e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);var r=S(this._collection),n=0;if(v(r))for(var i;!(i=r.next()).done&&!1!==e(i.value,n++,this););return n},t.prototype.__iteratorUncached=function(e,t){if(t)return this.cacheResult().__iterator(e,t);var r=S(this._collection);if(!v(r))return new g(b);var n=0;return new g(function(){var t=r.next();return t.done?t:_(e,n++,t.value)})},t}(G);function te(){return Z||(Z=new X([]))}function re(e){var t=ie(e);if(t)return t.fromEntrySeq();if("object"==typeof e)return new Y(e);throw new TypeError("Expected Array or collection object of [k, v] entries, or keyed object: "+e)}function ne(e){var t=ie(e);if(t)return t;throw new TypeError("Expected Array or collection object of values: "+e)}function ie(e){return K(e)?new X(e):w(e)?new ee(e):void 0}function oe(){return this.__ensureOwner()}function ae(){return this.__ownerID?this:this.__ensureOwner(new k)}var se="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function(e,t){var r=65535&(e|=0),n=65535&(t|=0);return r*n+((e>>>16)*n+r*(t>>>16)<<16>>>0)|0};function ce(e){return e>>>1&1073741824|3221225471&e}var ue=Object.prototype.valueOf;function le(e){if(null==e)return de(e);if("function"==typeof e.hashCode)return ce(e.hashCode(e));var t,r=(t=e).valueOf!==ue&&"function"==typeof t.valueOf?t.valueOf(t):t;if(null==r)return de(r);switch(typeof r){case"boolean":return r?1108378657:1108378656;case"number":return function(e){if(e!=e||e===1/0)return 0;var t=0|e;t!==e&&(t^=4294967295*e);for(;e>4294967295;)t^=e/=4294967295;return ce(t)}(r);case"string":return r.length>xe?function(e){var t=Te[e];void 0===t&&(t=he(e),Ae===Ie&&(Ae=0,Te={}),Ae++,Te[e]=t);return t}(r):he(r);case"object":case"function":return function(e){var t;if(be&&void 0!==(t=_e.get(e)))return t;if(t=e[Se],void 0!==t)return t;if(!ye){if(void 0!==(t=e.propertyIsEnumerable&&e.propertyIsEnumerable[Se]))return t;if(void 0!==(t=function(e){if(e&&e.nodeType>0)switch(e.nodeType){case 1:return e.uniqueID;case 9:return e.documentElement&&e.documentElement.uniqueID}}(e)))return t}if(t=ge(),be)_e.set(e,t);else{if(void 0!==me&&!1===me(e))throw new Error("Non-extensible objects are not allowed as keys.");if(ye)Object.defineProperty(e,Se,{enumerable:!1,configurable:!1,writable:!1,value:t});else if(void 0!==e.propertyIsEnumerable&&e.propertyIsEnumerable===e.constructor.prototype.propertyIsEnumerable)e.propertyIsEnumerable=function(){return this.constructor.prototype.propertyIsEnumerable.apply(this,arguments)},e.propertyIsEnumerable[Se]=t;else{if(void 0===e.nodeType)throw new Error("Unable to set a non-enumerable property on object.");e[Se]=t}}return t}(r);case"symbol":return function(e){var t=we[e];if(void 0!==t)return t;return t=ge(),we[e]=t,t}(r);default:if("function"==typeof r.toString)return he(r.toString());throw new Error("Value type "+typeof r+" cannot be hashed.")}}function de(e){return null===e?1108378658:1108378659}function he(e){for(var t=0,r=0;r<e.length;r++)t=31*t+e.charCodeAt(r)|0;return ce(t)}var fe=(1048576*Math.random()|1)%1048576||40503;function pe(e){if("string"!=typeof e)return le(e);for(var t=0,r=0;r<e.length;r++)t=fe*t+e.charCodeAt(r)|0;return t}var me=Object.isExtensible,ye=function(){try{return Object.defineProperty({},"@",{}),!0}catch(e){return!1}}();function ge(){var e=++ve;return 1073741824&ve&&(ve=0),e}var _e,be="function"==typeof WeakMap;be&&(_e=new WeakMap);var we=Object.create(null),ve=0,Se="__immutablehash__";"function"==typeof Symbol&&(Se=Symbol(Se));var xe=16,Ie=255,Ae=0,Te={},Ee=function(e){function t(e,t){this._iter=e,this._useKeys=t,this.size=e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.get=function(e,t){return this._iter.get(e,t)},t.prototype.has=function(e){return this._iter.has(e)},t.prototype.valueSeq=function(){return this._iter.valueSeq()},t.prototype.reverse=function(){var e=this,t=Pe(this,!0);return this._useKeys||(t.valueSeq=function(){return e._iter.toSeq().reverse()}),t},t.prototype.map=function(e,t){var r=this,n=Ce(this,e,t);return this._useKeys||(n.valueSeq=function(){return r._iter.toSeq().map(e,t)}),n},t.prototype.__iterate=function(e,t){var r=this;return this._iter.__iterate(function(t,n){return e(t,n,r)},t)},t.prototype.__iterator=function(e,t){return this._iter.__iterator(e,t)},t}(J);Ee.prototype[U]=!0;var Re=function(e){function t(e){this._iter=e,this.size=e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.includes=function(e){return this._iter.includes(e)},t.prototype.__iterate=function(e,t){var r=this,n=0;return t&&j(this),this._iter.__iterate(function(i){return e(i,t?r.size-++n:n++,r)},t)},t.prototype.__iterator=function(e,t){var r=this,n=this._iter.__iterator(1,t),i=0;return t&&j(this),new g(function(){var o=n.next();return o.done?o:_(e,t?r.size-++i:i++,o.value,o)})},t}(G),ke=function(e){function t(e){this._iter=e,this.size=e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.has=function(e){return this._iter.includes(e)},t.prototype.__iterate=function(e,t){var r=this;return this._iter.__iterate(function(t){return e(t,t,r)},t)},t.prototype.__iterator=function(e,t){var r=this._iter.__iterator(1,t);return new g(function(){var t=r.next();return t.done?t:_(e,t.value,t.value,t)})},t}(V),je=function(e){function t(e){this._iter=e,this.size=e.size}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.entrySeq=function(){return this._iter.toSeq()},t.prototype.__iterate=function(e,t){var r=this;return this._iter.__iterate(function(t){if(t){Qe(t);var n=u(t);return e(n?t.get(1):t[1],n?t.get(0):t[0],r)}},t)},t.prototype.__iterator=function(e,t){var r=this._iter.__iterator(1,t);return new g(function(){for(;;){var t=r.next();if(t.done)return t;var n=t.value;if(n){Qe(n);var i=u(n);return _(e,i?n.get(0):n[0],i?n.get(1):n[1],t)}}})},t}(J);function Ne(e){var t=Ke(e);return t._iter=e,t.size=e.size,t.flip=function(){return e},t.reverse=function(){var t=e.reverse.apply(this);return t.flip=function(){return e.reverse()},t},t.has=function(t){return e.includes(t)},t.includes=function(t){return e.has(t)},t.cacheResult=We,t.__iterateUncached=function(t,r){var n=this;return e.__iterate(function(e,r){return!1!==t(r,e,n)},r)},t.__iteratorUncached=function(t,r){if(2===t){var n=e.__iterator(t,r);return new g(function(){var e=n.next();if(!e.done){var t=e.value[0];e.value[0]=e.value[1],e.value[1]=t}return e})}return e.__iterator(1===t?0:1,r)},t}function Ce(e,t,r){var n=Ke(e);return n.size=e.size,n.has=function(t){return e.has(t)},n.get=function(n,i){var o=e.get(n,E);return o===E?i:t.call(r,o,n,e)},n.__iterateUncached=function(n,i){var o=this;return e.__iterate(function(e,i,a){return!1!==n(t.call(r,e,i,a),i,o)},i)},n.__iteratorUncached=function(n,i){var o=e.__iterator(2,i);return new g(function(){var i=o.next();if(i.done)return i;var a=i.value,s=a[0];return _(n,s,t.call(r,a[1],s,e),i)})},n}function Pe(e,t){var r=Ke(e);return r._iter=e,r.size=e.size,r.reverse=function(){return e},e.flip&&(r.flip=function(){var t=Ne(e);return t.reverse=function(){return e.flip()},t}),r.get=function(r,n){return e.get(t?r:-1-r,n)},r.has=function(r){return e.has(t?r:-1-r)},r.includes=function(t){return e.includes(t)},r.cacheResult=We,r.__iterate=function(r,n){var i=this,o=0;return n&&j(e),e.__iterate(function(e,a){return r(e,t?a:n?i.size-++o:o++,i)},!n)},r.__iterator=function(n,i){var o=0;i&&j(e);var a=e.__iterator(2,!i);return new g(function(){var e=a.next();if(e.done)return e;var s=e.value;return _(n,t?s[0]:i?r.size-++o:o++,s[1],e)})},r}function Oe(e,t,r,n){var i=Ke(e);return n&&(i.has=function(n){var i=e.get(n,E);return i!==E&&!!t.call(r,i,n,e)},i.get=function(n,i){var o=e.get(n,E);return o!==E&&t.call(r,o,n,e)?o:i}),i.__iterateUncached=function(i,o){var a=this,s=0;return e.__iterate(function(e,o,c){if(t.call(r,e,o,c))return s++,i(e,n?o:s-1,a)},o),s},i.__iteratorUncached=function(i,o){var a=e.__iterator(2,o),s=0;return new g(function(){for(;;){var o=a.next();if(o.done)return o;var c=o.value,u=c[0],l=c[1];if(t.call(r,l,u,e))return _(i,n?u:s++,l,o)}})},i}function Fe(e,t,r,n){var i=e.size;if(P(t,r,i))return e;if(void 0===i&&(t<0||r<0))return Fe(e.toSeq().cacheResult(),t,r,n);var o,a=O(t,i),s=F(r,i)-a;s==s&&(o=s<0?0:s);var c=Ke(e);return c.size=0===o?o:e.size&&o||void 0,!n&&Q(e)&&o>=0&&(c.get=function(t,r){return(t=N(this,t))>=0&&t<o?e.get(t+a,r):r}),c.__iterateUncached=function(t,r){var i=this;if(0===o)return 0;if(r)return this.cacheResult().__iterate(t,r);var s=0,c=!0,u=0;return e.__iterate(function(e,r){if(!c||!(c=s++<a))return u++,!1!==t(e,n?r:u-1,i)&&u!==o}),u},c.__iteratorUncached=function(t,r){if(0!==o&&r)return this.cacheResult().__iterator(t,r);if(0===o)return new g(b);var i=e.__iterator(t,r),s=0,c=0;return new g(function(){for(;s++<a;)i.next();if(++c>o)return{value:void 0,done:!0};var e=i.next();return n||1===t||e.done?e:_(t,c-1,0===t?void 0:e.value[1],e)})},c}function qe(e,t,r,n){var i=Ke(e);return i.__iterateUncached=function(i,o){var a=this;if(o)return this.cacheResult().__iterate(i,o);var s=!0,c=0;return e.__iterate(function(e,o,u){if(!s||!(s=t.call(r,e,o,u)))return c++,i(e,n?o:c-1,a)}),c},i.__iteratorUncached=function(i,o){var a=this;if(o)return this.cacheResult().__iterator(i,o);var s=e.__iterator(2,o),c=!0,u=0;return new g(function(){var e,o,l;do{if((e=s.next()).done)return n||1===i?e:_(i,u++,0===i?void 0:e.value[1],e);var d=e.value;o=d[0],l=d[1],c&&(c=t.call(r,l,o,a))}while(c);return 2===i?e:_(i,o,l,e)})},i}Re.prototype.cacheResult=Ee.prototype.cacheResult=ke.prototype.cacheResult=je.prototype.cacheResult=We;var Me=function(e){function t(e){this._wrappedIterables=e.flatMap(function(e){return e._wrappedIterables?e._wrappedIterables:[e]}),this.size=this._wrappedIterables.reduce(function(e,t){if(void 0!==e){var r=t.size;if(void 0!==r)return e+r}},0),this[o]=this._wrappedIterables[0][o],this[n]=this._wrappedIterables[0][n],this[U]=this._wrappedIterables[0][U]}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.__iterateUncached=function(e,t){if(0!==this._wrappedIterables.length){if(t)return this.cacheResult().__iterate(e,t);for(var r=0,n=a(this),i=n?2:1,o=this._wrappedIterables[r].__iterator(i,t),s=!0,c=0;s;){for(var u=o.next();u.done;){if(++r===this._wrappedIterables.length)return c;u=(o=this._wrappedIterables[r].__iterator(i,t)).next()}s=!1!==(n?e(u.value[1],u.value[0],this):e(u.value,c,this)),c++}return c}},t.prototype.__iteratorUncached=function(e,t){var r=this;if(0===this._wrappedIterables.length)return new g(b);if(t)return this.cacheResult().__iterator(e,t);var n=0,i=this._wrappedIterables[n].__iterator(e,t);return new g(function(){for(var o=i.next();o.done;){if(++n===r._wrappedIterables.length)return o;o=(i=r._wrappedIterables[n].__iterator(e,t)).next()}return o})},t}(W);function $e(e,t,r){var n=Ke(e);return n.__iterateUncached=function(i,o){if(o)return this.cacheResult().__iterate(i,o);var a=0,s=!1;return function e(c,l){c.__iterate(function(o,c){return(!t||l<t)&&u(o)?e(o,l+1):(a++,!1===i(o,r?c:a-1,n)&&(s=!0)),!s},o)}(e,0),a},n.__iteratorUncached=function(n,i){if(i)return this.cacheResult().__iterator(n,i);var o=e.__iterator(n,i),a=[],s=0;return new g(function(){for(;o;){var e=o.next();if(!1===e.done){var c=e.value;if(2===n&&(c=c[1]),t&&!(a.length<t)||!u(c))return r?e:_(n,s++,c,e);a.push(o),o=c.__iterator(n,i)}else o=a.pop()}return{value:void 0,done:!0}})},n}function De(e,t,r){t||(t=Je);var n=a(e),o=0,s=e.toSeq().map(function(t,n){return[n,t,o++,r?r(t,n,e):t]}).valueSeq().toArray();return s.sort(function(e,r){return t(e[3],r[3])||e[2]-r[2]}).forEach(n?function(e,t){s[t].length=2}:function(e,t){s[t]=e[1]}),n?J(s):i(e)?G(s):V(s)}function Le(e,t,r){if(t||(t=Je),r){var n=e.toSeq().map(function(t,n){return[t,r(t,n,e)]}).reduce(function(e,r){return Ue(t,e[1],r[1])?r:e});return n&&n[0]}return e.reduce(function(e,r){return Ue(t,e,r)?r:e})}function Ue(e,t,r){var n=e(r,t);return 0===n&&r!==t&&(null==r||r!=r)||n>0}function ze(e,t,r,n){var i=Ke(e),o=new X(r).map(function(e){return e.size});return i.size=n?o.max():o.min(),i.__iterate=function(e,t){for(var r,n=this.__iterator(1,t),i=0;!(r=n.next()).done&&!1!==e(r.value,i++,this););return i},i.__iteratorUncached=function(e,i){var o=r.map(function(e){return e=l(e),S(i?e.reverse():e)}),a=0,s=!1;return new g(function(){var r;return s||(r=o.map(function(e){return e.next()}),s=n?r.every(function(e){return e.done}):r.some(function(e){return e.done})),s?{value:void 0,done:!0}:_(e,a++,t.apply(null,r.map(function(e){return e.value})))})},i}function Be(e,t){return e===t?e:Q(e)?t:e.constructor(t)}function Qe(e){if(e!==Object(e))throw new TypeError("Expected [K, V] tuple: "+e)}function He(e){return a(e)?d:i(e)?h:f}function Ke(e){return Object.create((a(e)?J:i(e)?G:V).prototype)}function We(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):W.prototype.cacheResult.call(this)}function Je(e,t){return void 0===e&&void 0===t?0:void 0===e?1:void 0===t?-1:e>t?1:e<t?-1:0}function Ge(e){return Boolean(e&&"function"==typeof e.equals&&"function"==typeof e.hashCode)}function Ve(e,t){if(e===t||e!=e&&t!=t)return!0;if(!e||!t)return!1;if("function"==typeof e.valueOf&&"function"==typeof t.valueOf){if((e=e.valueOf())===(t=t.valueOf())||e!=e&&t!=t)return!0;if(!e||!t)return!1}return!!(Ge(e)&&Ge(t)&&e.equals(t))}function Xe(e,t,r,n){return Jt(e,[t],r,n)}function Ye(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return et(this,e)}function Ze(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];if("function"!=typeof e)throw new TypeError("Invalid merger function: "+e);return et(this,t,e)}function et(e,t,r){for(var n=[],i=0;i<t.length;i++){var o=d(t[i]);0!==o.size&&n.push(o)}return 0===n.length?e:0!==e.toSeq().size||e.__ownerID||1!==n.length?e.withMutations(function(e){for(var t=r?function(t,n){Xe(e,n,E,function(e){return e===E?t:r(e,t,n)})}:function(t,r){e.set(r,t)},i=0;i<n.length;i++)n[i].forEach(t)}):D(e)?e:e.constructor(n[0])}var tt=Object.prototype.toString;function rt(e){if(!e||"object"!=typeof e||"[object Object]"!==tt.call(e))return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;for(var r=t,n=Object.getPrototypeOf(t);null!==n;)r=n,n=Object.getPrototypeOf(r);return r===t}function nt(e){return"object"==typeof e&&(L(e)||Array.isArray(e)||rt(e))}function it(e){return"string"==typeof e&&("__proto__"===e||"constructor"===e)}function ot(e,t){t=t||0;for(var r=Math.max(0,e.length-t),n=new Array(r),i=0;i<r;i++)n[i]=e[i+t];return n}function at(e){if(Array.isArray(e))return ot(e);var t={};for(var r in e)it(r)||H.call(e,r)&&(t[r]=e[r]);return t}function st(e,t,r){return ct(e,t,function(e){function t(r,n,o){return nt(r)&&nt(n)&&(s=n,c=W(r),u=W(s),i(c)===i(u)&&a(c)===a(u))?ct(r,[n],t):e?e(r,n,o):n;var s,c,u}return t}(r))}function ct(e,t,r){if(!nt(e))throw new TypeError("Cannot merge into non-data-structure value: "+e);if(L(e))return"function"==typeof r&&e.mergeWith?e.mergeWith.apply(e,[r].concat(t)):e.merge?e.merge.apply(e,t):e.concat.apply(e,t);for(var n=Array.isArray(e),i=e,o=n?h:d,a=n?function(t){i===e&&(i=at(i)),i.push(t)}:function(t,n){if(!it(n)){var o=H.call(i,n),a=o&&r?r(i[n],t,n):t;o&&a===i[n]||(i===e&&(i=at(i)),i[n]=a)}},s=0;s<t.length;s++)o(t[s]).forEach(a);return i}function ut(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return st(this,e)}function lt(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return st(this,t,e)}function dt(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return Jt(this,e,Ot(),function(e){return st(e,t)})}function ht(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return Jt(this,e,Ot(),function(e){return ct(e,t)})}function ft(e,t){return function(e,t,r){return Jt(e,t,E,function(){return r})}(this,e,t)}function pt(e,t,r){return 1===arguments.length?e(this):Xe(this,e,t,r)}function mt(e,t,r){return Jt(this,e,t,r)}function yt(){return this.__altered}function gt(e){var t=this.asMutable();return e(t),t.wasAltered()?t.__ensureOwner(this.__ownerID):this}var _t="@@__IMMUTABLE_MAP__@@";function bt(e){return Boolean(e&&e[_t])}function wt(e,t){if(!e)throw new Error(t)}function vt(e){wt(e!==1/0,"Cannot perform this action with an infinite size.")}var St=function(e){function t(t){return null==t?Ot():bt(t)&&!z(t)?t:Ot().withMutations(function(r){var n=e(t);vt(n.size),n.forEach(function(e,t){return r.set(t,e)})})}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.toString=function(){return this.__toString("Map {","}")},t.prototype.get=function(e,t){return this._root?this._root.get(0,void 0,e,t):t},t.prototype.set=function(e,t){return Ft(this,e,t)},t.prototype.remove=function(e){return Ft(this,e,E)},t.prototype.deleteAll=function(e){var t=l(e);return 0===t.size?this:this.withMutations(function(e){t.forEach(function(t){return e.remove(t)})})},t.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):Ot()},t.prototype.sort=function(e){return mr(De(this,e))},t.prototype.sortBy=function(e,t){return mr(De(this,t,e))},t.prototype.map=function(e,t){var r=this;return this.withMutations(function(n){n.forEach(function(i,o){n.set(o,e.call(t,i,o,r))})})},t.prototype.__iterator=function(e,t){return new jt(this,e,t)},t.prototype.__iterate=function(e,t){var r=this,n=0;return this._root&&this._root.iterate(function(t){return n++,e(t[1],t[0],r)},t),n},t.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?Pt(this.size,this._root,e,this.__hash):0===this.size?Ot():(this.__ownerID=e,this.__altered=!1,this)},t}(d);St.isMap=bt;var xt=St.prototype;xt[_t]=!0,xt[I]=xt.remove,xt.removeAll=xt.deleteAll,xt.setIn=ft,xt.removeIn=xt.deleteIn=Vt,xt.update=pt,xt.updateIn=mt,xt.merge=xt.concat=Ye,xt.mergeWith=Ze,xt.mergeDeep=ut,xt.mergeDeepWith=lt,xt.mergeIn=ht,xt.mergeDeepIn=dt,xt.withMutations=gt,xt.wasAltered=yt,xt.asImmutable=oe,xt["@@transducer/init"]=xt.asMutable=ae,xt["@@transducer/step"]=function(e,t){return e.set(t[0],t[1])},xt["@@transducer/result"]=function(e){return e.asImmutable()};var It=function(e,t){this.ownerID=e,this.entries=t};It.prototype.get=function(e,t,r,n){for(var i=this.entries,o=0,a=i.length;o<a;o++)if(Ve(r,i[o][0]))return i[o][1];return n},It.prototype.update=function(e,t,r,n,i,o,a){for(var s=i===E,c=this.entries,u=0,l=c.length;u<l&&!Ve(n,c[u][0]);u++);var d=u<l;if(d?c[u][1]===i:s)return this;if(R(a),(s||!d)&&R(o),!s||1!==c.length){if(!d&&!s&&c.length>=Ut)return function(e,t,r,n){e||(e=new k);for(var i=new Rt(e,le(r),[r,n]),o=0;o<t.length;o++){var a=t[o];i=i.update(e,0,void 0,a[0],a[1])}return i}(e,c,n,i);var h=e&&e===this.ownerID,f=h?c:ot(c);return d?s?u===l-1?f.pop():f[u]=f.pop():f[u]=[n,i]:f.push([n,i]),h?(this.entries=f,this):new It(e,f)}};var At=function(e,t,r){this.ownerID=e,this.bitmap=t,this.nodes=r};At.prototype.get=function(e,t,r,n){void 0===t&&(t=le(r));var i=1<<((0===e?t:t>>>e)&T),o=this.bitmap;return 0===(o&i)?n:this.nodes[Dt(o&i-1)].get(e+5,t,r,n)},At.prototype.update=function(e,t,r,n,i,o,a){void 0===r&&(r=le(n));var s=(0===t?r:r>>>t)&T,c=1<<s,u=this.bitmap,l=0!==(u&c);if(!l&&i===E)return this;var d=Dt(u&c-1),h=this.nodes,f=l?h[d]:void 0,p=qt(f,e,t+5,r,n,i,o,a);if(p===f)return this;if(!l&&p&&h.length>=zt)return function(e,t,r,n,i){for(var o=0,a=new Array(A),s=0;0!==r;s++,r>>>=1)a[s]=1&r?t[o++]:void 0;return a[n]=i,new Tt(e,o+1,a)}(e,h,u,s,p);if(l&&!p&&2===h.length&&Mt(h[1^d]))return h[1^d];if(l&&p&&1===h.length&&Mt(p))return p;var m=e&&e===this.ownerID,y=l?p?u:u^c:u|c,g=l?p?Lt(h,d,p,m):function(e,t,r){var n=e.length-1;if(r&&t===n)return e.pop(),e;for(var i=new Array(n),o=0,a=0;a<n;a++)a===t&&(o=1),i[a]=e[a+o];return i}(h,d,m):function(e,t,r,n){var i=e.length+1;if(n&&t+1===i)return e[t]=r,e;for(var o=new Array(i),a=0,s=0;s<i;s++)s===t?(o[s]=r,a=-1):o[s]=e[s+a];return o}(h,d,p,m);return m?(this.bitmap=y,this.nodes=g,this):new At(e,y,g)};var Tt=function(e,t,r){this.ownerID=e,this.count=t,this.nodes=r};Tt.prototype.get=function(e,t,r,n){void 0===t&&(t=le(r));var i=(0===e?t:t>>>e)&T,o=this.nodes[i];return o?o.get(e+5,t,r,n):n},Tt.prototype.update=function(e,t,r,n,i,o,a){void 0===r&&(r=le(n));var s=(0===t?r:r>>>t)&T,c=i===E,u=this.nodes,l=u[s];if(c&&!l)return this;var d=qt(l,e,t+5,r,n,i,o,a);if(d===l)return this;var h=this.count;if(l){if(!d&&--h<Bt)return function(e,t,r,n){for(var i=0,o=0,a=new Array(r),s=0,c=1,u=t.length;s<u;s++,c<<=1){var l=t[s];void 0!==l&&s!==n&&(i|=c,a[o++]=l)}return new At(e,i,a)}(e,u,h,s)}else h++;var f=e&&e===this.ownerID,p=Lt(u,s,d,f);return f?(this.count=h,this.nodes=p,this):new Tt(e,h,p)};var Et=function(e,t,r){this.ownerID=e,this.keyHash=t,this.entries=r,this._index=void 0};Et.prototype._positionOf=function(e,t){var r=this.entries,n=this._index;if(void 0===n&&t&&r.length>=Qt&&(n=this._buildIndex()),void 0!==n){var i=n[pe(e)];if(void 0!==i)for(var o=0;o<i.length;o++){var a=i[o];if(Ve(e,r[a][0]))return a}return-1}for(var s=0,c=r.length;s<c;s++)if(Ve(e,r[s][0]))return s;return-1},Et.prototype._buildIndex=function(){for(var e=Object.create(null),t=this.entries,r=0,n=t.length;r<n;r++){var i=pe(t[r][0]),o=e[i];void 0!==o?o.push(r):e[i]=[r]}return this._index=e,e},Et.prototype.get=function(e,t,r,n){var i=this._positionOf(r,!0);return-1===i?n:this.entries[i][1]},Et.prototype.update=function(e,t,r,n,i,o,a){void 0===r&&(r=le(n));var s=i===E;if(r!==this.keyHash)return s?this:(R(a),R(o),$t(this,e,t,r,[n,i]));var c=this.entries,u=c.length,l=e&&e===this.ownerID,d=this._positionOf(n,l),h=-1===d?u:d,f=-1!==d;if(f?c[h][1]===i:s)return this;if(R(a),(s||!f)&&R(o),s&&2===u)return new Rt(e,this.keyHash,c[1^h]);var p=l?c:ot(c);if(f)s?(h===u-1?p.pop():p[h]=p.pop(),l&&(this._index=void 0)):p[h]=[n,i];else if(p.push([n,i]),l&&void 0!==this._index){var m=pe(n),y=this._index[m];void 0!==y?y.push(u):this._index[m]=[u]}return l?(this.entries=p,this):new Et(e,this.keyHash,p)};var Rt=function(e,t,r){this.ownerID=e,this.keyHash=t,this.entry=r};Rt.prototype.get=function(e,t,r,n){return Ve(r,this.entry[0])?this.entry[1]:n},Rt.prototype.update=function(e,t,r,n,i,o,a){var s=i===E,c=Ve(n,this.entry[0]);return(c?i===this.entry[1]:s)?this:(R(a),s?void R(o):c?e&&e===this.ownerID?(this.entry[1]=i,this):new Rt(e,this.keyHash,[n,i]):(R(o),$t(this,e,t,le(n),[n,i])))},It.prototype.iterate=Et.prototype.iterate=function(e,t){for(var r=this.entries,n=0,i=r.length-1;n<=i;n++)if(!1===e(r[t?i-n:n]))return!1},At.prototype.iterate=Tt.prototype.iterate=function(e,t){for(var r=this.nodes,n=0,i=r.length-1;n<=i;n++){var o=r[t?i-n:n];if(o&&!1===o.iterate(e,t))return!1}},Rt.prototype.iterate=function(e,t){return e(this.entry)};var kt,jt=function(e){function t(e,t,r){this._type=t,this._reverse=r,this._stack=e._root&&Ct(e._root)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.next=function(){for(var e=this._type,t=this._stack;t;){var r=t.node,n=t.index++,i=void 0;if(r.entry){if(0===n)return Nt(e,r.entry)}else if(r.entries){if(n<=(i=r.entries.length-1))return Nt(e,r.entries[this._reverse?i-n:n])}else if(n<=(i=r.nodes.length-1)){var o=r.nodes[this._reverse?i-n:n];if(o){if(o.entry)return Nt(e,o.entry);t=this._stack=Ct(o,t)}continue}t=this._stack=this._stack.__prev}return{value:void 0,done:!0}},t}(g);function Nt(e,t){return _(e,t[0],t[1])}function Ct(e,t){return{node:e,index:0,__prev:t}}function Pt(e,t,r,n){var i=Object.create(xt);return i.size=e,i._root=t,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function Ot(){return kt||(kt=Pt(0))}function Ft(e,t,r){var n,i;if(e._root){var o={value:!1},a={value:!1};if(n=qt(e._root,e.__ownerID,0,void 0,t,r,o,a),!a.value)return e;i=e.size+(o.value?r===E?-1:1:0)}else{if(r===E)return e;i=1,n=new It(e.__ownerID,[[t,r]])}return e.__ownerID?(e.size=i,e._root=n,e.__hash=void 0,e.__altered=!0,e):n?Pt(i,n):Ot()}function qt(e,t,r,n,i,o,a,s){return e?e.update(t,r,n,i,o,a,s):o===E?e:(R(s),R(a),new Rt(t,n,[i,o]))}function Mt(e){return e.constructor===Rt||e.constructor===Et}function $t(e,t,r,n,i){if(e.keyHash===n)return new Et(t,n,[e.entry,i]);var o,a=(0===r?e.keyHash:e.keyHash>>>r)&T,s=(0===r?n:n>>>r)&T,c=a===s?[$t(e,t,r+5,n,i)]:(o=new Rt(t,n,i),a<s?[e,o]:[o,e]);return new At(t,1<<a|1<<s,c)}function Dt(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,e+=e>>8,127&(e+=e>>16)}function Lt(e,t,r,n){var i=n?e:ot(e);return i[t]=r,i}var Ut=8,zt=16,Bt=8,Qt=16;function Ht(e){if(K(e)&&"string"!=typeof e)return e;if(z(e))return e.toArray();throw new TypeError("Invalid keyPath: expected Ordered Collection or Array: "+e)}function Kt(e){try{return"string"==typeof e?JSON.stringify(e):String(e)}catch(t){return JSON.stringify(e)}}function Wt(e,t,r){return L(e)?e.get(t,r):function(e,t){return L(e)?e.has(t):nt(e)&&H.call(e,t)}(e,t)?"function"==typeof e.get?e.get(t):e[t]:r}function Jt(e,t,r,n){n||(n=r,r=void 0);var i=Gt(L(e),e,Ht(t),0,r,n);return i===E?r:i}function Gt(e,t,r,n,i,o){var a=t===E;if(n===r.length){var s=a?i:t,c=o(s);return c===s?t:c}if(!a&&!nt(t))throw new TypeError("Cannot update within non-data-structure value in path ["+Array.from(r).slice(0,n).map(Kt)+"]: "+t);var u=r[n],l=a?E:Wt(t,u,E),d=Gt(l===E?e:L(l),l,r,n+1,i,o);return d===l?t:d===E?function(e,t){if(!nt(e))throw new TypeError("Cannot update non-data-structure value: "+e);if(L(e)){if(!e.remove)throw new TypeError("Cannot update immutable value without .remove() method: "+e);return e.remove(t)}if(!H.call(e,t))return e;var r=at(e);return Array.isArray(r)?r.splice(t,1):delete r[t],r}(t,u):function(e,t,r){if(it(t))return e;if(!nt(e))throw new TypeError("Cannot update non-data-structure value: "+e);if(L(e)){if(!e.set)throw new TypeError("Cannot update immutable value without .set() method: "+e);return e.set(t,r)}if(H.call(e,t)&&r===e[t])return e;var n=at(e);return n[t]=r,n}(a?e?Ot():{}:t,u,d)}function Vt(e){return function(e,t){return Jt(e,t,function(){return E})}(this,e)}var Xt="@@__IMMUTABLE_LIST__@@";function Yt(e){return Boolean(e&&e[Xt])}var Zt=function(e){function t(t){var r=or();if(null==t)return r;if(Yt(t))return t;var n=e(t),i=n.size;return 0===i?r:(vt(i),i>0&&i<A?ir(0,i,5,void 0,new tr(n.toArray())):r.withMutations(function(e){e.setSize(i),n.forEach(function(t,r){return e.set(r,t)})}))}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.prototype.toString=function(){return this.__toString("List [","]")},t.prototype.get=function(e,t){if((e=N(this,e))>=0&&e<this.size){var r=cr(this,e+=this._origin);return r&&r.array[e&T]}return t},t.prototype.set=function(e,t){return function(e,t,r){if(t=N(e,t),t!=t)return e;if(t>=e.size||t<0)return e.withMutations(function(e){t<0?ur(e,t).set(0,r):ur(e,0,t+1).set(t,r)});t+=e._origin;var n=e._tail,i=e._root,o={value:!1};t>=lr(e._capacity)?n=ar(n,e.__ownerID,0,t,r,o):i=ar(i,e.__ownerID,e._level,t,r,o);if(!o.value)return e;if(e.__ownerID)return e._root=i,e._tail=n,e.__hash=void 0,e.__altered=!0,e;return ir(e._origin,e._capacity,e._level,i,n)}(this,e,t)},t.prototype.remove=function(e){return this.has(e)?0===e?this.shift():e===this.size-1?this.pop():this.splice(e,1):this},t.prototype.insert=function(e,t){return this.splice(e,0,t)},t.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=5,this._root=this._tail=this.__hash=void 0,this.__altered=!0,this):or()},t.prototype.push=function(){var e=arguments,t=this.size;return this.withMutations(function(r){ur(r,0,t+e.length);for(var n=0;n<e.length;n++)r.set(t+n,e[n])})},t.prototype.pop=function(){return ur(this,0,-1)},t.prototype.unshift=function(){var e=arguments;return this.withMutations(function(t){ur(t,-e.length);for(var r=0;r<e.length;r++)t.set(r,e[r])})},t.prototype.shift=function(){return ur(this,1)},t.prototype.shuffle=function(e){return void 0===e&&(e=Math.random),this.withMutations(function(t){for(var r,n,i=t.size;i;)r=Math.floor(e()*i--),n=t.get(r),t.set(r,t.get(i)),t.set(i,n)})},t.prototype.concat=function(){for(var t=arguments,r=[],n=0;n<arguments.length;n++){var i=t[n],o=e("string"!=typeof i&&w(i)?i:[i]);0!==o.size&&r.push(o)}return 0===r.length?this:0!==this.size||this.__ownerID||1!==r.length?this.withMutations(function(e){r.forEach(function(t){return t.forEach(function(t){return e.push(t)})})}):this.constructor(r[0])},t.prototype.setSize=function(e){return ur(this,0,e)},t.prototype.map=function(e,t){var r=this;return this.withMutations(function(n){for(var i=0;i<r.size;i++)n.set(i,e.call(t,n.get(i),i,r))})},t.prototype.slice=function(e,t){var r=this.size;return P(e,t,r)?this:ur(this,O(e,r),F(t,r))},t.prototype.__iterator=function(e,t){var r=t?this.size:0,n=nr(this,t);return new g(function(){var i=n();return i===rr?{value:void 0,done:!0}:_(e,t?--r:r++,i)})},t.prototype.__iterate=function(e,t){for(var r,n=t?this.size:0,i=nr(this,t);(r=i())!==rr&&!1!==e(r,t?--n:n++,this););return n},t.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?ir(this._origin,this._capacity,this._level,this._root,this._tail,e,this.__hash):0===this.size?or():(this.__ownerID=e,this.__altered=!1,this)},t}(h);Zt.isList=Yt;var er=Zt.prototype;er[Xt]=!0,er[I]=er.remove,er.merge=er.concat,er.setIn=ft,er.deleteIn=er.removeIn=Vt,er.update=pt,er.updateIn=mt,er.mergeIn=ht,er.mergeDeepIn=dt,er.withMutations=gt,er.wasAltered=yt,er.asImmutable=oe,er["@@transducer/init"]=er.asMutable=ae,er["@@transducer/step"]=function(e,t){return e.push(t)},er["@@transducer/result"]=function(e){return e.asImmutable()};var tr=function(e,t){this.array=e,this.ownerID=t};tr.prototype.removeBefore=function(e,t,r){if(!(r&(1<<t+5)-1)||0===this.array.length)return this;var n=r>>>t&T;if(n>=this.array.length)return new tr([],e);var i,o=0===n;if(t>0){var a=this.array[n];if((i=a&&a.removeBefore(e,t-5,r))===a&&o)return this}if(o&&!i)return this;var s=sr(this,e);if(!o)for(var c=0;c<n;c++)s.array[c]=void 0;return i&&(s.array[n]=i),s},tr.prototype.removeAfter=function(e,t,r){if(r===(t?1<<t+5:A)||0===this.array.length)return this;var n,i=r-1>>>t&T;if(i>=this.array.length)return this;if(t>0){var o=this.array[i];if((n=o&&o.removeAfter(e,t-5,r))===o&&i===this.array.length-1)return this}var a=sr(this,e);return a.array.splice(i+1),n&&(a.array[i]=n),a};var rr={};function nr(e,t){var r=e._origin,n=e._capacity,i=lr(n),o=e._tail;return a(e._root,e._level,0);function a(e,s,c){return 0===s?function(e,a){var s=a===i?o&&o.array:e&&e.array,c=a>r?0:r-a,u=n-a;u>A&&(u=A);return function(){if(c===u)return rr;var e=t?--u:c++;return s&&s[e]}}(e,c):function(e,i,o){var s,c=e&&e.array,u=o>r?0:r-o>>i,l=1+(n-o>>i);l>A&&(l=A);return function(){for(;;){if(s){var e=s();if(e!==rr)return e;s=null}if(u===l)return rr;var r=t?--l:u++;s=a(c&&c[r],i-5,o+(r<<i))}}}(e,s,c)}}function ir(e,t,r,n,i,o,a){var s=Object.create(er);return s.size=t-e,s._origin=e,s._capacity=t,s._level=r,s._root=n,s._tail=i,s.__ownerID=o,s.__hash=a,s.__altered=!1,s}function or(){return ir(0,0,5)}function ar(e,t,r,n,i,o){var a,s=n>>>r&T,c=e&&s<e.array.length;if(!c&&void 0===i)return e;if(r>0){var u=e&&e.array[s],l=ar(u,t,r-5,n,i,o);return l===u?e:((a=sr(e,t)).array[s]=l,a)}return c&&e.array[s]===i?e:(o&&R(o),a=sr(e,t),void 0===i&&s===a.array.length-1?a.array.pop():a.array[s]=i,a)}function sr(e,t){return t&&e&&t===e.ownerID?e:new tr(e?e.array.slice():[],t)}function cr(e,t){if(t>=lr(e._capacity))return e._tail;if(t<1<<e._level+5){for(var r=e._root,n=e._level;r&&n>0;)r=r.array[t>>>n&T],n-=5;return r}}function ur(e,t,r){!function(e,t,r){var n=e._origin+(void 0===t?0:t),i=void 0===r?e._capacity:r<0?e._capacity+r:e._origin+r;if(Number.isFinite(i)&&i>dr||Number.isFinite(n)&&n<-dr||Number.isFinite(i)&&Number.isFinite(n)&&i-n>dr)throw new RangeError("Invalid List size: a List cannot hold more than "+dr+" (2 ** 30) values.")}(e,t,r),void 0!==t&&(t|=0),void 0!==r&&(r|=0);var n=e.__ownerID||new k,i=e._origin,o=e._capacity,a=i+t,s=void 0===r?o:r<0?o+r:i+r;if(a===i&&s===o)return e;if(a>=s)return e.clear();for(var c=e._level,u=e._root,l=0;a+l<0;)u=new tr(u&&u.array.length?[void 0,u]:[],n),l+=hr(c+=5);l&&(a+=l,i+=l,s+=l,o+=l);for(var d=lr(o),h=lr(s);h>=hr(c+5);)u=new tr(u&&u.array.length?[u]:[],n),c+=5;var f=e._tail,p=h<d?cr(e,s-1):h>d?new tr([],n):f;if(f&&h>d&&a<o&&f.array.length){for(var m=u=sr(u,n),y=c;y>5;y-=5){var g=d>>>y&T;m=m.array[g]=sr(m.array[g],n)}m.array[d>>>5&T]=f}if(s<o&&(p=p&&p.removeAfter(n,0,s)),a>=h)a-=h,s-=h,c=5,u=void 0,p=p&&p.removeBefore(n,0,a);else if(a>i||h<d){for(l=0;u;){var _=a>>>c&T;if(_!==h>>>c&T)break;_&&(l+=(1<<c)*_),c-=5,u=u.array[_]}u&&a>i&&(u=u.removeBefore(n,c,a-l)),u&&h<d&&(u=u.removeAfter(n,c,h-l)),l&&(a-=l,s-=l)}return e.__ownerID?(e.size=s-a,e._origin=a,e._capacity=s,e._level=c,e._root=u,e._tail=p,e.__hash=void 0,e.__altered=!0,e):ir(a,s,c,u,p)}function lr(e){return e<A?0:e-1>>>5<<5}var dr=Math.pow(2,30);function hr(e){return e<31?1<<e:Math.pow(2,e)}function fr(e){return bt(e)&&z(e)}var pr,mr=function(e){function t(e){return null==e?gr():fr(e)?e:gr().withMutations(function(t){var r=d(e);vt(r.size),r.forEach(function(e,r){return t.set(r,e)})})}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.prototype.toString=function(){return this.__toString("OrderedMap {","}")},t.prototype.get=function(e,t){var r=this._map.get(e);return void 0!==r?this._list.get(r)[1]:t},t.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this.__altered=!0,this):gr()},t.prototype.set=function(e,t){return _r(this,e,t)},t.prototype.remove=function(e){return _r(this,e,E)},t.prototype.__iterate=function(e,t){var r=this;return this._list.__iterate(function(t){return t&&e(t[1],t[0],r)},t)},t.prototype.__iterator=function(e,t){return this._list.fromEntrySeq().__iterator(e,t)},t.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map.__ensureOwner(e),r=this._list.__ensureOwner(e);return e?yr(t,r,e,this.__hash):0===this.size?gr():(this.__ownerID=e,this.__altered=!1,this._map=t,this._list=r,this)},t}(St);function yr(e,t,r,n){var i=Object.create(mr.prototype);return i.size=e?e.size:0,i._map=e,i._list=t,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function gr(){return pr||(pr=yr(Ot(),or()))}function _r(e,t,r){var n,i,o=e._map,a=e._list,s=o.get(t),c=void 0!==s;if(r===E){if(!c)return e;a.size>=A&&a.size>=2*o.size?(n=(i=a.filter(function(e,t){return void 0!==e&&s!==t})).toKeyedSeq().map(function(e){return e[0]}).flip().toMap(),e.__ownerID&&(n.__ownerID=i.__ownerID=e.__ownerID)):(n=o.remove(t),i=s===a.size-1?a.pop():a.set(s,void 0))}else if(c){if(r===a.get(s)[1])return e;n=o,i=a.set(s,[t,r])}else n=o.set(t,a.size),i=a.set(a.size,[t,r]);return e.__ownerID?(e.size=n.size,e._map=n,e._list=i,e.__hash=void 0,e.__altered=!0,e):yr(n,i)}mr.isOrderedMap=fr,mr.prototype[U]=!0,mr.prototype[I]=mr.prototype.remove;var br="@@__IMMUTABLE_STACK__@@";function wr(e){return Boolean(e&&e[br])}var vr=function(e){function t(e){return null==e?Ar():wr(e)?e:Ar().pushAll(e)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.prototype.toString=function(){return this.__toString("Stack [","]")},t.prototype.get=function(e,t){var r=this._head;for(e=N(this,e);r&&e--;)r=r.next;return r?r.value:t},t.prototype.peek=function(){return this._head&&this._head.value},t.prototype.push=function(){var e=arguments;if(0===arguments.length)return this;for(var t=this.size+arguments.length,r=this._head,n=arguments.length-1;n>=0;n--)r={value:e[n],next:r};return this.__ownerID?(this.size=t,this._head=r,this.__hash=void 0,this.__altered=!0,this):Ir(t,r)},t.prototype.pushAll=function(t){if(0===(t=e(t)).size)return this;if(0===this.size&&wr(t))return t;vt(t.size);var r=this.size,n=this._head;return t.__iterate(function(e){r++,n={value:e,next:n}},!0),this.__ownerID?(this.size=r,this._head=n,this.__hash=void 0,this.__altered=!0,this):Ir(r,n)},t.prototype.pop=function(){return this.slice(1)},t.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Ar()},t.prototype.slice=function(t,r){if(P(t,r,this.size))return this;var n=O(t,this.size);if(F(r,this.size)!==this.size)return e.prototype.slice.call(this,t,r);for(var i=this.size-n,o=this._head;n--;)o=o.next;return this.__ownerID?(this.size=i,this._head=o,this.__hash=void 0,this.__altered=!0,this):Ir(i,o)},t.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?Ir(this.size,this._head,e,this.__hash):0===this.size?Ar():(this.__ownerID=e,this.__altered=!1,this)},t.prototype.__iterate=function(e,t){var r=this;if(t)return new X(this.toArray()).__iterate(function(t,n){return e(t,n,r)},t);for(var n=0,i=this._head;i&&!1!==e(i.value,n++,this);)i=i.next;return n},t.prototype.__iterator=function(e,t){if(t)return new X(this.toArray()).__iterator(e,t);var r=0,n=this._head;return new g(function(){if(n){var t=n.value;return n=n.next,_(e,r++,t)}return{value:void 0,done:!0}})},t}(h);vr.isStack=wr;var Sr,xr=vr.prototype;function Ir(e,t,r,n){var i=Object.create(xr);return i.size=e,i._head=t,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function Ar(){return Sr||(Sr=Ir(0))}function Tr(e,t,r,n,i,o){return vt(e.size),e.__iterate(function(e,o,a){i?(i=!1,r=e):r=t.call(n,r,e,o,a)},o),r}function Er(e,t){return t}function Rr(e,t){return[t,e]}function kr(e){return function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return!e.apply(this,t)}}function jr(e){return function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return-e.apply(this,t)}}function Nr(e,t){return e<t?1:e>t?-1:0}function Cr(e,t){if(e===t)return!0;if(!u(t)||void 0!==e.size&&void 0!==t.size&&e.size!==t.size||void 0!==e.__hash&&void 0!==t.__hash&&e.__hash!==t.__hash||a(e)!==a(t)||i(e)!==i(t)||z(e)!==z(t))return!1;if(0===e.size&&0===t.size)return!0;var r=!s(e);if(z(e)){var n=e.entries();return t.every(function(e,t){var i=n.next().value;return i&&Ve(i[1],e)&&(r||Ve(i[0],t))})&&n.next().done}var o=!1;if(void 0===e.size)if(void 0===t.size)"function"==typeof e.cacheResult&&e.cacheResult();else{o=!0;var c=e;e=t,t=c}var l=!0,d=t.__iterate(function(t,n){if(r?!e.has(t):o?!Ve(t,e.get(n,E)):!Ve(e.get(n,E),t))return l=!1,!1});return l&&e.size===d}xr[br]=!0,xr.shift=xr.pop,xr.unshift=xr.push,xr.unshiftAll=xr.pushAll,xr.withMutations=gt,xr.wasAltered=yt,xr.asImmutable=oe,xr["@@transducer/init"]=xr.asMutable=ae,xr["@@transducer/step"]=function(e,t){return e.unshift(t)},xr["@@transducer/result"]=function(e){return e.asImmutable()};var Pr,Or=function(e){function t(e,r,n){if(void 0===n&&(n=1),!(this instanceof t))return new t(e,r,n);if(wt(0!==n,"Cannot step a Range by 0"),wt(void 0!==e,"You must define a start value when using Range"),wt(void 0!==r,"You must define an end value when using Range"),n=Math.abs(n),r<e&&(n=-n),this._start=e,this._end=r,this._step=n,this.size=Math.max(0,Math.ceil((r-e)/n-1)+1),0===this.size){if(Pr)return Pr;Pr=this}}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.toString=function(){return 0===this.size?"Range []":"Range [ "+this._start+"..."+this._end+(1!==this._step?" by "+this._step:"")+" ]"},t.prototype.get=function(e,t){return this.has(e)?this._start+N(this,e)*this._step:t},t.prototype.includes=function(e){var t=(e-this._start)/this._step;return t>=0&&t<this.size&&t===Math.floor(t)},t.prototype.slice=function(e,r){return P(e,r,this.size)?this:(e=O(e,this.size),(r=F(r,this.size))<=e?new t(0,0):new t(this.get(e,this._end),this.get(r,this._end),this._step))},t.prototype.indexOf=function(e){var t=e-this._start;if(t%this._step===0){var r=t/this._step;if(r>=0&&r<this.size)return r}return-1},t.prototype.lastIndexOf=function(e){return this.indexOf(e)},t.prototype.__iterate=function(e,t){for(var r=this.size,n=this._step,i=t?this._start+(r-1)*n:this._start,o=0;o!==r&&!1!==e(i,t?r-++o:o++,this);)i+=t?-n:n;return o},t.prototype.__iterator=function(e,t){var r=this.size,n=this._step,i=t?this._start+(r-1)*n:this._start,o=0;return new g(function(){if(o===r)return{value:void 0,done:!0};var a=i;return i+=t?-n:n,_(e,t?r-++o:o++,a)})},t.prototype.equals=function(e){return e instanceof t?this._start===e._start&&this._end===e._end&&this._step===e._step:Cr(this,e)},t}(G),Fr="@@__IMMUTABLE_SET__@@";function qr(e){return Boolean(e&&e[Fr])}var Mr=function(e){function t(t){return null==t?zr():qr(t)&&!z(t)?t:zr().withMutations(function(r){var n=e(t);vt(n.size),n.forEach(function(e){return r.add(e)})})}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.fromKeys=function(e){return this(d(e).keySeq())},t.intersect=function(e){return(e=l(e).toArray()).length?Dr.intersect.apply(t(e.pop()),e):zr()},t.union=function(e){return(e=l(e).toArray()).length?Dr.union.apply(t(e.pop()),e):zr()},t.prototype.toString=function(){return this.__toString("Set {","}")},t.prototype.has=function(e){return this._map.has(e)},t.prototype.add=function(e){return Lr(this,this._map.set(e,e))},t.prototype.remove=function(e){return Lr(this,this._map.remove(e))},t.prototype.clear=function(){return Lr(this,this._map.clear())},t.prototype.map=function(e,t){var r=this,n=!1,i=Lr(this,this._map.mapEntries(function(i){var o=i[1],a=e.call(t,o,o,r);return a!==o&&(n=!0),[a,a]},t));return n?i:this},t.prototype.union=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return 0===(t=t.filter(function(e){return 0!==e.size})).length?this:0!==this.size||this.__ownerID||1!==t.length?this.withMutations(function(r){for(var n=0;n<t.length;n++)"string"==typeof t[n]?r.add(t[n]):e(t[n]).forEach(function(e){return r.add(e)})}):this.constructor(t[0])},t.prototype.intersect=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];if(0===t.length)return this;t=t.map(function(t){return e(t)});var n=[];return this.forEach(function(e){t.every(function(t){return t.includes(e)})||n.push(e)}),this.withMutations(function(e){n.forEach(function(t){e.remove(t)})})},t.prototype.subtract=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];if(0===t.length)return this;t=t.map(function(t){return e(t)});var n=[];return this.forEach(function(e){t.some(function(t){return t.includes(e)})&&n.push(e)}),this.withMutations(function(e){n.forEach(function(t){e.remove(t)})})},t.prototype.sort=function(e){return rn(De(this,e))},t.prototype.sortBy=function(e,t){return rn(De(this,t,e))},t.prototype.wasAltered=function(){return this._map.wasAltered()},t.prototype.__iterate=function(e,t){var r=this;return this._map.__iterate(function(t){return e(t,t,r)},t)},t.prototype.__iterator=function(e,t){return this._map.__iterator(e,t)},t.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map.__ensureOwner(e);return e?this.__make(t,e):0===this.size?this.__empty():(this.__ownerID=e,this._map=t,this)},t}(f);Mr.isSet=qr;var $r,Dr=Mr.prototype;function Lr(e,t){return e.__ownerID?(e.size=t.size,e._map=t,e):t===e._map?e:0===t.size?e.__empty():e.__make(t)}function Ur(e,t){var r=Object.create(Dr);return r.size=e?e.size:0,r._map=e,r.__ownerID=t,r}function zr(){return $r||($r=Ur(Ot()))}function Br(e,t,r){for(var n=Ht(t),i=0;i!==n.length;)if((e=Wt(e,n[i++],E))===E)return r;return e}function Qr(e,t){return Br(this,e,t)}function Hr(){vt(this.size);var e={};return this.__iterate(function(t,r){it(r)||(e[r]=t)}),e}function Kr(e){if(!e||"object"!=typeof e)return e;if(!u(e)){if(!nt(e))return e;e=W(e)}if(a(e)){var t={};return e.__iterate(function(e,r){it(r)||(t[r]=Kr(e))}),t}var r=[];return e.__iterate(function(e){r.push(Kr(e))}),r}function Wr(e){if(e.size===1/0)return 0;var t=z(e),r=a(e),n=t?1:0;return e.__iterate(r?t?function(e,t){n=31*n+Jr(le(e),le(t))|0}:function(e,t){n=n+Jr(le(e),le(t))|0}:t?function(e){n=31*n+le(e)|0}:function(e){n=n+le(e)|0}),function(e,t){return t=se(t,3432918353),t=se(t<<15|t>>>-15,461845907),t=se(t<<13|t>>>-13,5),t=(t+3864292196|0)^e,t=se(t^t>>>16,2246822507),t=se(t^t>>>13,3266489909),t=ce(t^t>>>16),t}(e.size,n)}function Jr(e,t){return e^t+2654435769+(e<<6)+(e>>2)|0}function Gr(e,t){var r=function(r){e.prototype[r]=t[r]};return Object.keys(t).forEach(r),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(t).forEach(r),e}Dr[Fr]=!0,Dr[I]=Dr.remove,Dr.merge=Dr.concat=Dr.union,Dr.withMutations=gt,Dr.asImmutable=oe,Dr["@@transducer/init"]=Dr.asMutable=ae,Dr["@@transducer/step"]=function(e,t){return e.add(t)},Dr["@@transducer/result"]=function(e){return e.asImmutable()},Dr.__empty=zr,Dr.__make=Ur,l.Iterator=g,Gr(l,{toArray:function(){vt(this.size);var e=new Array(this.size||0),t=a(this),r=0;return this.__iterate(function(n,i){e[r++]=t?[i,n]:n}),e},toIndexedSeq:function(){return new Re(this)},toJS:function(){return Kr(this)},toKeyedSeq:function(){return new Ee(this,!0)},toMap:function(){return St(this.toKeyedSeq())},toObject:Hr,toOrderedMap:function(){return mr(this.toKeyedSeq())},toOrderedSet:function(){return rn(a(this)?this.valueSeq():this)},toSet:function(){return Mr(a(this)?this.valueSeq():this)},toSetSeq:function(){return new ke(this)},toSeq:function(){return i(this)?this.toIndexedSeq():a(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return vr(a(this)?this.valueSeq():this)},toList:function(){return Zt(a(this)?this.valueSeq():this)},toString:function(){return"[Collection]"},__toString:function(e,t){return 0===this.size?e+t:e+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+t},concat:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return Be(this,function(e,t){var r=a(e),n=[e].concat(t).map(function(e){return u(e)?r&&(e=d(e)):e=r?re(e):ne(Array.isArray(e)?e:[e]),e}).filter(function(e){return 0!==e.size});if(0===n.length)return e;if(1===n.length){var o=n[0];if(o===e||r&&a(o)||i(e)&&i(o))return o}return new Me(n)}(this,e))},includes:function(e){return this.some(function(t){return Ve(t,e)})},entries:function(){return this.__iterator(2)},every:function(e,t){vt(this.size);var r=!0;return this.__iterate(function(n,i,o){if(!e.call(t,n,i,o))return r=!1,!1}),r},filter:function(e,t){return Be(this,Oe(this,e,t,!0))},partition:function(e,t){return function(e,t,r){var n=a(e),i=[[],[]];e.__iterate(function(o,a){i[t.call(r,o,a,e)?1:0].push(n?[a,o]:o)});var o=He(e);return i.map(function(t){return Be(e,o(t))})}(this,e,t)},find:function(e,t,r){var n=this.findEntry(e,t);return n?n[1]:r},forEach:function(e,t){return vt(this.size),this.__iterate(t?e.bind(t):e)},join:function(e){vt(this.size),e=void 0!==e?""+e:",";var t="",r=!0;return this.__iterate(function(n){r?r=!1:t+=e,t+=null!=n?n.toString():""}),t},keys:function(){return this.__iterator(0)},map:function(e,t){return Be(this,Ce(this,e,t))},reduce:function(e,t,r){return Tr(this,e,t,r,arguments.length<2,!1)},reduceRight:function(e,t,r){return Tr(this,e,t,r,arguments.length<2,!0)},reverse:function(){return Be(this,Pe(this,!0))},slice:function(e,t){return Be(this,Fe(this,e,t,!0))},some:function(e,t){vt(this.size);var r=!1;return this.__iterate(function(n,i,o){if(e.call(t,n,i,o))return r=!0,!1}),r},sort:function(e){return Be(this,De(this,e))},values:function(){return this.__iterator(1)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some(function(){return!0})},count:function(e,t){return j(e?this.toSeq().filter(e,t):this)},countBy:function(e,t){return function(e,t,r){var n=St().asMutable();return e.__iterate(function(i,o){n.update(t.call(r,i,o,e),0,function(e){return e+1})}),n.asImmutable()}(this,e,t)},equals:function(e){return Cr(this,e)},entrySeq:function(){var e=this;if(e._cache)return new X(e._cache);var t=e.toSeq().map(Rr).toIndexedSeq();return t.fromEntrySeq=function(){return e.toSeq()},t},filterNot:function(e,t){return this.filter(kr(e),t)},findEntry:function(e,t,r){var n=r;return this.__iterate(function(r,i,o){if(e.call(t,r,i,o))return n=[i,r],!1}),n},findKey:function(e,t){var r=this.findEntry(e,t);return r&&r[0]},findLast:function(e,t,r){return this.toKeyedSeq().reverse().find(e,t,r)},findLastEntry:function(e,t,r){return this.toKeyedSeq().reverse().findEntry(e,t,r)},findLastKey:function(e,t){return this.toKeyedSeq().reverse().findKey(e,t)},first:function(e){return this.find(C,null,e)},flatMap:function(e,t){return Be(this,function(e,t,r){var n=He(e);return e.toSeq().map(function(i,o){return n(t.call(r,i,o,e))}).flatten(!0)}(this,e,t))},flatten:function(e){return Be(this,$e(this,e,!0))},fromEntrySeq:function(){return new je(this)},get:function(e,t){return this.find(function(t,r){return Ve(r,e)},void 0,t)},getIn:Qr,groupBy:function(e,t){return function(e,t,r){var n=a(e),i=(z(e)?mr():St()).asMutable();e.__iterate(function(o,a){i.update(t.call(r,o,a,e),function(e){return(e=e||[]).push(n?[a,o]:o),e})});var o=He(e);return i.map(function(t){return Be(e,o(t))}).asImmutable()}(this,e,t)},has:function(e){return this.get(e,E)!==E},hasIn:function(e){return Br(this,e,E)!==E},isSubset:function(e){return e="function"==typeof e.includes?e:l(e),this.every(function(t){return e.includes(t)})},isSuperset:function(e){return(e="function"==typeof e.isSubset?e:l(e)).isSubset(this)},keyOf:function(e){return this.findKey(function(t){return Ve(t,e)})},keySeq:function(){return this.toSeq().map(Er).toIndexedSeq()},last:function(e){return this.toSeq().reverse().first(e)},lastKeyOf:function(e){return this.toKeyedSeq().reverse().keyOf(e)},max:function(e){return Le(this,e)},maxBy:function(e,t){return Le(this,t,e)},min:function(e){return Le(this,e?jr(e):Nr)},minBy:function(e,t){return Le(this,t?jr(t):Nr,e)},rest:function(){return this.slice(1)},skip:function(e){return 0===e?this:this.slice(Math.max(0,e))},skipLast:function(e){return 0===e?this:this.slice(0,-Math.max(0,e))},skipWhile:function(e,t){return Be(this,qe(this,e,t,!0))},skipUntil:function(e,t){return this.skipWhile(kr(e),t)},sortBy:function(e,t){return Be(this,De(this,t,e))},take:function(e){return this.slice(0,Math.max(0,e))},takeLast:function(e){return this.slice(-Math.max(0,e))},takeWhile:function(e,t){return Be(this,function(e,t,r){var n=Ke(e);return n.__iterateUncached=function(n,i){var o=this;if(i)return this.cacheResult().__iterate(n,i);var a=0;return e.__iterate(function(e,i,s){return t.call(r,e,i,s)&&++a&&n(e,i,o)}),a},n.__iteratorUncached=function(n,i){var o=this;if(i)return this.cacheResult().__iterator(n,i);var a=e.__iterator(2,i),s=!0;return new g(function(){if(!s)return{value:void 0,done:!0};var e=a.next();if(e.done)return e;var i=e.value,c=i[0],u=i[1];return t.call(r,u,c,o)?2===n?e:_(n,c,u,e):(s=!1,{value:void 0,done:!0})})},n}(this,e,t))},takeUntil:function(e,t){return this.takeWhile(kr(e),t)},update:function(e){return e(this)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=Wr(this))}});var Vr=l.prototype;Vr[c]=!0,Vr[y]=Vr.values,Vr.toJSON=Vr.toArray,Vr.__toStringMapper=Kt,Vr.inspect=Vr.toSource=function(){return this.toString()},Vr.chain=Vr.flatMap,Vr.contains=Vr.includes,Gr(d,{flip:function(){return Be(this,Ne(this))},mapEntries:function(e,t){var r=this,n=0;return Be(this,this.toSeq().map(function(i,o){return e.call(t,[o,i],n++,r)}).fromEntrySeq())},mapKeys:function(e,t){var r=this;return Be(this,this.toSeq().flip().map(function(n,i){return e.call(t,n,i,r)}).flip())}});var Xr=d.prototype;Xr[o]=!0,Xr[y]=Vr.entries,Xr.toJSON=Hr,Xr.__toStringMapper=function(e,t){return Kt(t)+": "+Kt(e)},Gr(h,{toKeyedSeq:function(){return new Ee(this,!1)},filter:function(e,t){return Be(this,Oe(this,e,t,!1))},findIndex:function(e,t){var r=this.findEntry(e,t);return r?r[0]:-1},indexOf:function(e){var t=this.keyOf(e);return void 0===t?-1:t},lastIndexOf:function(e){var t=this.lastKeyOf(e);return void 0===t?-1:t},reverse:function(){return Be(this,Pe(this,!1))},slice:function(e,t){return Be(this,Fe(this,e,t,!1))},splice:function(e,t){var r=arguments.length;if(t=Math.max(t||0,0),0===r||2===r&&!t)return this;e=O(e,e<0?this.count():this.size);var n=this.slice(0,e);return Be(this,1===r?n:n.concat(ot(arguments,2),this.slice(e+t)))},findLastIndex:function(e,t){var r=this.findLastEntry(e,t);return r?r[0]:-1},first:function(e){return this.get(0,e)},flatten:function(e){return Be(this,$e(this,e,!1))},get:function(e,t){return(e=N(this,e))<0||this.size===1/0||void 0!==this.size&&e>this.size?t:this.find(function(t,r){return r===e},void 0,t)},has:function(e){return(e=N(this,e))>=0&&(void 0!==this.size?this.size===1/0||e<this.size:this.find(function(t,r){return r===e},void 0,E)!==E)},interpose:function(e){return Be(this,function(e,t){var r=Ke(e);return r.size=e.size&&2*e.size-1,r.__iterateUncached=function(r,n){var i=this,o=0;return e.__iterate(function(e){return(!o||!1!==r(t,o++,i))&&!1!==r(e,o++,i)},n),o},r.__iteratorUncached=function(r,n){var i,o=e.__iterator(1,n),a=0;return new g(function(){return(!i||a%2)&&(i=o.next()).done?i:a%2?_(r,a++,t):_(r,a++,i.value,i)})},r}(this,e))},interleave:function(){var e=[this].concat(ot(arguments)),t=ze(this.toSeq(),G.of,e),r=t.flatten(!0);return t.size&&(r.size=t.size*e.length),Be(this,r)},keySeq:function(){return Or(0,this.size)},last:function(e){return this.get(-1,e)},skipWhile:function(e,t){return Be(this,qe(this,e,t,!1))},zip:function(){return Be(this,ze(this,en,[this].concat(ot(arguments))))},zipAll:function(){return Be(this,ze(this,en,[this].concat(ot(arguments)),!0))},zipWith:function(e){var t=ot(arguments);return t[0]=this,Be(this,ze(this,e,t))}});var Yr=h.prototype;Yr[n]=!0,Yr[U]=!0,Gr(f,{get:function(e,t){return this.has(e)?e:t},includes:function(e){return this.has(e)},keySeq:function(){return this.valueSeq()}});var Zr=f.prototype;function en(){return ot(arguments)}function tn(e){return qr(e)&&z(e)}Zr.has=Vr.includes,Zr.contains=Zr.includes,Zr.keys=Zr.values,Gr(J,Xr),Gr(G,Yr),Gr(V,Zr);var rn=function(e){function t(e){return null==e?sn():tn(e)?e:sn().withMutations(function(t){var r=f(e);vt(r.size),r.forEach(function(e){return t.add(e)})})}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.of=function(){return this(arguments)},t.fromKeys=function(e){return this(d(e).keySeq())},t.prototype.toString=function(){return this.__toString("OrderedSet {","}")},t}(Mr);rn.isOrderedSet=tn;var nn,on=rn.prototype;function an(e,t){var r=Object.create(on);return r.size=e?e.size:0,r._map=e,r.__ownerID=t,r}function sn(){return nn||(nn=an(gr()))}on[U]=!0,on.zip=Yr.zip,on.zipWith=Yr.zipWith,on.zipAll=Yr.zipAll,on.__empty=sn,on.__make=an;var cn=function(e,t){var r;!function(e){if(D(e))throw new Error("Can not call `Record` with an immutable Record as default values. Use a plain javascript object instead.");if(L(e))throw new Error("Can not call `Record` with an immutable Collection as default values. Use a plain javascript object instead.");if(null===e||"object"!=typeof e)throw new Error("Can not call `Record` with a non-object as default values. Use a plain javascript object instead.")}(e);var n=function(o){var a=this;if(o instanceof n)return o;if(!(this instanceof n))return new n(o);if(!r){r=!0;var s=Object.keys(e),c=i._indices={};i._name=t,i._keys=s,i._defaultValues=e;for(var u=0;u<s.length;u++){var l=s[u];c[l]=u,i[l]?"object"==typeof console&&console.warn&&console.warn("Cannot define "+dn(this)+' with property "'+l+'" since that property name is part of the Record API.'):fn(i,l)}}return this.__ownerID=void 0,this._values=Zt().withMutations(function(e){e.setSize(a._keys.length),d(o).forEach(function(t,r){e.set(a._indices[r],t===a._defaultValues[r]?void 0:t)})}),this},i=n.prototype=Object.create(un);return i.constructor=n,t&&(n.displayName=t),n};cn.prototype.toString=function(){for(var e,t=dn(this)+" { ",r=this._keys,n=0,i=r.length;n!==i;n++)t+=(n?", ":"")+(e=r[n])+": "+Kt(this.get(e));return t+" }"},cn.prototype.equals=function(e){return this===e||D(e)&&hn(this).equals(hn(e))},cn.prototype.hashCode=function(){return hn(this).hashCode()},cn.prototype.has=function(e){return this._indices.hasOwnProperty(e)},cn.prototype.get=function(e,t){if(!this.has(e))return t;var r=this._indices[e],n=this._values.get(r);return void 0===n?this._defaultValues[e]:n},cn.prototype.set=function(e,t){if(this.has(e)){var r=this._values.set(this._indices[e],t===this._defaultValues[e]?void 0:t);if(r!==this._values&&!this.__ownerID)return ln(this,r)}return this},cn.prototype.remove=function(e){return this.set(e)},cn.prototype.clear=function(){var e=this._values.clear().setSize(this._keys.length);return this.__ownerID?this:ln(this,e)},cn.prototype.wasAltered=function(){return this._values.wasAltered()},cn.prototype.toSeq=function(){return hn(this)},cn.prototype.toJS=function(){return Kr(this)},cn.prototype.entries=function(){return this.__iterator(2)},cn.prototype.__iterator=function(e,t){return hn(this).__iterator(e,t)},cn.prototype.__iterate=function(e,t){return hn(this).__iterate(e,t)},cn.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._values.__ensureOwner(e);return e?ln(this,t,e):(this.__ownerID=e,this._values=t,this)},cn.isRecord=D,cn.getDescriptiveName=dn;var un=cn.prototype;function ln(e,t,r){var n=Object.create(Object.getPrototypeOf(e));return n._values=t,n.__ownerID=r,n}function dn(e){return e.constructor.displayName||e.constructor.name||"Record"}function hn(e){return re(e._keys.map(function(t){return[t,e.get(t)]}))}function fn(e,t){try{Object.defineProperty(e,t,{get:function(){return this.get(t)},set:function(e){wt(this.__ownerID,"Cannot set on an immutable record."),this.set(t,e)}})}catch(e){}}un[$]=!0,un[I]=un.remove,un.deleteIn=un.removeIn=Vt,un.getIn=Qr,un.hasIn=Vr.hasIn,un.merge=Ye,un.mergeWith=Ze,un.mergeIn=ht,un.mergeDeep=ut,un.mergeDeepWith=lt,un.mergeDeepIn=dt,un.setIn=ft,un.update=pt,un.updateIn=mt,un.withMutations=gt,un.asMutable=ae,un.asImmutable=oe,un[y]=un.entries,un.toJSON=un.toObject=Vr.toObject,un.inspect=un.toSource=function(){return this.toString()}},606(e){var t,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function a(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var s,c=[],u=!1,l=-1;function d(){u&&s&&(u=!1,s.length?c=s.concat(c):l=-1,c.length&&h())}function h(){if(!u){var e=a(d);u=!0;for(var t=c.length;t;){for(s=c,c=[];++l<t;)s&&s[l].run();l=-1,t=c.length}s=null,u=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===o||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function p(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];c.push(new f(e,t)),1!==c.length||u||a(h)},f.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=p,n.addListener=p,n.once=p,n.off=p,n.removeListener=p,n.removeAllListeners=p,n.emit=p,n.prependListener=p,n.prependOnceListener=p,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},147(e,t,r){"use strict";const{SymbolDispose:n}=r(134),{AbortError:i,codes:o}=r(371),{isNodeStream:a,isWebStream:s,kControllerErrorFunction:c}=r(115),u=r(238),{ERR_INVALID_ARG_TYPE:l}=o;let d;e.exports.addAbortSignal=function(t,r){if(((e,t)=>{if("object"!=typeof e||!("aborted"in e))throw new l(t,"AbortSignal",e)})(t,"signal"),!a(r)&&!s(r))throw new l("stream",["ReadableStream","WritableStream","Stream"],r);return e.exports.addAbortSignalNoValidate(t,r)},e.exports.addAbortSignalNoValidate=function(e,t){if("object"!=typeof e||!("aborted"in e))return t;const o=a(t)?()=>{t.destroy(new i(void 0,{cause:e.reason}))}:()=>{t[c](new i(void 0,{cause:e.reason}))};if(e.aborted)o();else{d=d||r(760).addAbortListener;const i=d(e,o);u(t,i[n])}return t}},345(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:o,Uint8Array:a}=r(134),{Buffer:s}=r(287),{inspect:c}=r(760);e.exports=class BufferList{constructor(){this.head=null,this.tail=null,this.length=0}push(e){const t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}unshift(e){const t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}shift(){if(0===this.length)return;const e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(0===this.length)return"";let t=this.head,r=""+t.data;for(;null!==(t=t.next);)r+=e+t.data;return r}concat(e){if(0===this.length)return s.alloc(0);const t=s.allocUnsafe(e>>>0);let r=this.head,n=0;for(;r;)o(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(e<r.length){const t=r.slice(0,e);return this.head.data=r.slice(e),t}return e===r.length?this.shift():t?this._getString(e):this._getBuffer(e)}first(){return this.head.data}*[i](){for(let e=this.head;e;e=e.next)yield e.data}_getString(e){let t="",r=this.head,i=0;do{const o=r.data;if(!(e>o.length)){e===o.length?(t+=o,++i,r.next?this.head=r.next:this.head=this.tail=null):(t+=n(o,0,e),this.head=r,r.data=n(o,e));break}t+=o,e-=o.length,++i}while(null!==(r=r.next));return this.length-=i,t}_getBuffer(e){const t=s.allocUnsafe(e),r=e;let n=this.head,i=0;do{const s=n.data;if(!(e>s.length)){e===s.length?(o(t,s,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(o(t,new a(s.buffer,s.byteOffset,e),r-e),this.head=n,n.data=s.slice(e));break}o(t,s,r-e),e-=s.length,++i}while(null!==(n=n.next));return this.length-=i,t}[Symbol.for("nodejs.util.inspect.custom")](e,t){return c(this,{...t,depth:0,customInspect:!1})}}},896(e,t,r){"use strict";const n=r(606),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:a}=r(371),{Symbol:s}=r(134),{kIsDestroyed:c,isDestroyed:u,isFinished:l,isServerRequest:d}=r(115),h=s("kDestroy"),f=s("kConstruct");function p(e,t,r){e&&(e.stack,t&&!t.errored&&(t.errored=e),r&&!r.errored&&(r.errored=e))}function m(e,t,r){let i=!1;function o(t){if(i)return;i=!0;const o=e._readableState,a=e._writableState;p(t,a,o),a&&(a.closed=!0),o&&(o.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(y,e,t):n.nextTick(g,e)}try{e._destroy(t||null,o)}catch(t){o(t)}}function y(e,t){_(e,t),g(e)}function g(e){const t=e._readableState,r=e._writableState;r&&(r.closeEmitted=!0),t&&(t.closeEmitted=!0),(null!=r&&r.emitClose||null!=t&&t.emitClose)&&e.emit("close")}function _(e,t){const r=e._readableState,n=e._writableState;null!=n&&n.errorEmitted||null!=r&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),e.emit("error",t))}function b(e,t,r){const i=e._readableState,o=e._writableState;if(null!=o&&o.destroyed||null!=i&&i.destroyed)return this;null!=i&&i.autoDestroy||null!=o&&o.autoDestroy?e.destroy(t):t&&(t.stack,o&&!o.errored&&(o.errored=t),i&&!i.errored&&(i.errored=t),r?n.nextTick(_,e,t):_(e,t))}function w(e){let t=!1;function r(r){if(t)return void b(e,null!=r?r:new o);t=!0;const i=e._readableState,a=e._writableState,s=a||i;i&&(i.constructed=!0),a&&(a.constructed=!0),s.destroyed?e.emit(h,r):r?b(e,r,!0):n.nextTick(v,e)}try{e._construct(e=>{n.nextTick(r,e)})}catch(e){n.nextTick(r,e)}}function v(e){e.emit(f)}function S(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function x(e){e.emit("close")}function I(e,t){e.emit("error",t),n.nextTick(x,e)}e.exports={construct:function(e,t){if("function"!=typeof e._construct)return;const r=e._readableState,i=e._writableState;r&&(r.constructed=!1),i&&(i.constructed=!1),e.once(f,t),e.listenerCount(f)>1||n.nextTick(w,e)},destroyer:function(e,t){e&&!u(e)&&(t||l(e)||(t=new a),d(e)?(e.socket=null,e.destroy(t)):S(e)?e.abort():S(e.req)?e.req.abort():"function"==typeof e.destroy?e.destroy(t):"function"==typeof e.close?e.close():t?n.nextTick(I,e,t):n.nextTick(x,e),e.destroyed||(e[c]=!0))},destroy:function(e,t){const r=this._readableState,n=this._writableState,o=n||r;return null!=n&&n.destroyed||null!=r&&r.destroyed?("function"==typeof t&&t(),this):(p(e,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),o.constructed?m(this,e,t):this.once(h,function(r){m(this,i(r,e),t)}),this)},undestroy:function(){const e=this._readableState,t=this._writableState;e&&(e.constructed=!0,e.closed=!1,e.closeEmitted=!1,e.destroyed=!1,e.errored=null,e.errorEmitted=!1,e.reading=!1,e.ended=!1===e.readable,e.endEmitted=!1===e.readable),t&&(t.constructed=!0,t.destroyed=!1,t.closed=!1,t.closeEmitted=!1,t.errored=null,t.errorEmitted=!1,t.finalCalled=!1,t.prefinished=!1,t.ended=!1===t.writable,t.ending=!1===t.writable,t.finished=!1===t.writable)},errorOrDestroy:b}},370(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:o,ObjectSetPrototypeOf:a}=r(134);e.exports=u;const s=r(576),c=r(584);a(u.prototype,s.prototype),a(u,s);{const e=o(c.prototype);for(let t=0;t<e.length;t++){const r=e[t];u.prototype[r]||(u.prototype[r]=c.prototype[r])}}function u(e){if(!(this instanceof u))return new u(e);s.call(this,e),c.call(this,e),e?(this.allowHalfOpen=!1!==e.allowHalfOpen,!1===e.readable&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),!1===e.writable&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}let l,d;function h(){return void 0===l&&(l={}),l}n(u.prototype,{writable:{__proto__:null,...i(c.prototype,"writable")},writableHighWaterMark:{__proto__:null,...i(c.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...i(c.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...i(c.prototype,"writableBuffer")},writableLength:{__proto__:null,...i(c.prototype,"writableLength")},writableFinished:{__proto__:null,...i(c.prototype,"writableFinished")},writableCorked:{__proto__:null,...i(c.prototype,"writableCorked")},writableEnded:{__proto__:null,...i(c.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...i(c.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set(e){this._readableState&&this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}}),u.fromWeb=function(e,t){return h().newStreamDuplexFromReadableWritablePair(e,t)},u.toWeb=function(e){return h().newReadableWritablePairFromDuplex(e)},u.from=function(e){return d||(d=r(706)),d(e,"body")}},706(e,t,r){const n=r(606),i=r(287),{isReadable:o,isWritable:a,isIterable:s,isNodeStream:c,isReadableNodeStream:u,isWritableNodeStream:l,isDuplexNodeStream:d,isReadableStream:h,isWritableStream:f}=r(115),p=r(238),{AbortError:m,codes:{ERR_INVALID_ARG_TYPE:y,ERR_INVALID_RETURN_VALUE:g}}=r(371),{destroyer:_}=r(896),b=r(370),w=r(576),v=r(584),{createDeferredPromise:S}=r(760),x=r(532),I=globalThis.Blob||i.Blob,A=void 0!==I?function(e){return e instanceof I}:function(e){return!1},T=globalThis.AbortController||r(568).AbortController,{FunctionPrototypeCall:E}=r(134);class Duplexify extends b{constructor(e){super(e),!1===(null==e?void 0:e.readable)&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),!1===(null==e?void 0:e.writable)&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}}function R(e){const t=e.readable&&"function"!=typeof e.readable.read?w.wrap(e.readable):e.readable,r=e.writable;let n,i,s,c,u,l=!!o(t),d=!!a(r);function h(e){const t=c;c=null,t?t(e):e&&u.destroy(e)}return u=new Duplexify({readableObjectMode:!(null==t||!t.readableObjectMode),writableObjectMode:!(null==r||!r.writableObjectMode),readable:l,writable:d}),d&&(p(r,e=>{d=!1,e&&_(t,e),h(e)}),u._write=function(e,t,i){r.write(e,t)?i():n=i},u._final=function(e){r.end(),i=e},r.on("drain",function(){if(n){const e=n;n=null,e()}}),r.on("finish",function(){if(i){const e=i;i=null,e()}})),l&&(p(t,e=>{l=!1,e&&_(t,e),h(e)}),t.on("readable",function(){if(s){const e=s;s=null,e()}}),t.on("end",function(){u.push(null)}),u._read=function(){for(;;){const e=t.read();if(null===e)return void(s=u._read);if(!u.push(e))return}}),u._destroy=function(e,o){e||null===c||(e=new m),s=null,n=null,i=null,null===c?o(e):(c=o,_(r,e),_(t,e))},u}e.exports=function e(t,r){if(d(t))return t;if(u(t))return R({readable:t});if(l(t))return R({writable:t});if(c(t))return R({writable:!1,readable:!1});if(h(t))return R({readable:w.fromWeb(t)});if(f(t))return R({writable:v.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:o,destroy:a}=function(e){let{promise:t,resolve:r}=S();const i=new T,o=i.signal,a=e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:a,cb:s}=await e;if(n.nextTick(s),a)return;if(o.aborted)throw new m(void 0,{cause:o.reason});({promise:t,resolve:r}=S()),yield i}}(),{signal:o});return{value:a,write(e,t,n){const i=r;r=null,i({chunk:e,done:!1,cb:n})},final(e){const t=r;r=null,t({done:!0,cb:e})},destroy(e,t){i.abort(),t(e)}}}(t);if(s(e))return x(Duplexify,e,{objectMode:!0,write:i,final:o,destroy:a});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=E(c,e,e=>{if(null!=e)throw new g("nully","body",e)},e=>{_(t,e)});return t=new Duplexify({objectMode:!0,readable:!1,write:i,final(e){o(async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}})},destroy:a})}throw new g("Iterable, AsyncIterable or AsyncFunction",r,e)}if(A(t))return e(t.arrayBuffer());if(s(t))return x(Duplexify,t,{objectMode:!0,writable:!1});if(h(null==t?void 0:t.readable)&&f(null==t?void 0:t.writable))return Duplexify.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable)){return R({readable:null!=t&&t.readable?u(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?l(null==t?void 0:t.writable)?null==t?void 0:t.writable:e(t.writable):void 0})}const i=null==t?void 0:t.then;if("function"==typeof i){let e;return E(i,t,t=>{null!=t&&e.push(t),e.push(null)},t=>{_(e,t)}),e=new Duplexify({objectMode:!0,writable:!1,read(){}})}throw new y(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},238(e,t,r){"use strict";const n=r(606),{AbortError:i,codes:o}=r(371),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_PREMATURE_CLOSE:s}=o,{kEmptyObject:c,once:u}=r(760),{validateAbortSignal:l,validateFunction:d,validateObject:h,validateBoolean:f}=r(277),{Promise:p,PromisePrototypeThen:m,SymbolDispose:y}=r(134),{isClosed:g,isReadable:_,isReadableNodeStream:b,isReadableStream:w,isReadableFinished:v,isReadableErrored:S,isWritable:x,isWritableNodeStream:I,isWritableStream:A,isWritableFinished:T,isWritableErrored:E,isNodeStream:R,willEmitClose:k,kIsClosedPromise:j}=r(115);let N;const C=()=>{};function P(e,t,o){var f,p;if(2===arguments.length?(o=t,t=c):null==t?t=c:h(t,"options"),d(o,"callback"),l(t.signal,"options.signal"),o=u(o),w(e)||A(e))return function(e,t,o){let a=!1,s=C;if(t.signal)if(s=()=>{a=!0,o.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(s);else{N=N||r(760).addAbortListener;const n=N(t.signal,s),i=o;o=u((...t)=>{n[y](),i.apply(e,t)})}const c=(...t)=>{a||n.nextTick(()=>o.apply(e,t))};return m(e[j].promise,c,c),C}(e,t,o);if(!R(e))throw new a("stream",["ReadableStream","WritableStream","Stream"],e);const P=null!==(f=t.readable)&&void 0!==f?f:b(e),O=null!==(p=t.writable)&&void 0!==p?p:I(e),F=e._writableState,q=e._readableState,M=()=>{e.writable||L()};let $=k(e)&&b(e)===P&&I(e)===O,D=T(e,!1);const L=()=>{D=!0,e.destroyed&&($=!1),(!$||e.readable&&!P)&&(P&&!U||o.call(e))};let U=v(e,!1);const z=()=>{U=!0,e.destroyed&&($=!1),(!$||e.writable&&!O)&&(O&&!D||o.call(e))},B=t=>{o.call(e,t)};let Q=g(e);const H=()=>{Q=!0;const t=E(e)||S(e);return t&&"boolean"!=typeof t?o.call(e,t):P&&!U&&b(e,!0)&&!v(e,!1)?o.call(e,new s):!O||D||T(e,!1)?void o.call(e):o.call(e,new s)},K=()=>{Q=!0;const t=E(e)||S(e);if(t&&"boolean"!=typeof t)return o.call(e,t);o.call(e)},W=()=>{e.req.on("finish",L)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?O&&!F&&(e.on("end",M),e.on("close",M)):(e.on("complete",L),$||e.on("abort",H),e.req?W():e.on("request",W)),$||"boolean"!=typeof e.aborted||e.on("aborted",H),e.on("end",z),e.on("finish",L),!1!==t.error&&e.on("error",B),e.on("close",H),Q?n.nextTick(H):null!=F&&F.errorEmitted||null!=q&&q.errorEmitted?$||n.nextTick(K):(P||$&&!_(e)||!D&&!1!==x(e))&&(O||$&&!x(e)||!U&&!1!==_(e))?q&&e.req&&e.aborted&&n.nextTick(K):n.nextTick(K);const J=()=>{o=C,e.removeListener("aborted",H),e.removeListener("complete",L),e.removeListener("abort",H),e.removeListener("request",W),e.req&&e.req.removeListener("finish",L),e.removeListener("end",M),e.removeListener("close",M),e.removeListener("finish",L),e.removeListener("end",z),e.removeListener("error",B),e.removeListener("close",H)};if(t.signal&&!Q){const a=()=>{const r=o;J(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(a);else{N=N||r(760).addAbortListener;const n=N(t.signal,a),i=o;o=u((...t)=>{n[y](),i.apply(e,t)})}}return J}e.exports=P,e.exports.finished=function(e,t){var r;let n=!1;return null===t&&(t=c),null!==(r=t)&&void 0!==r&&r.cleanup&&(f(t.cleanup,"cleanup"),n=t.cleanup),new p((r,i)=>{const o=P(e,t,e=>{n&&o(),e?i(e):r()})})}},532(e,t,r){"use strict";const n=r(606),{PromisePrototypeThen:i,SymbolAsyncIterator:o,SymbolIterator:a}=r(134),{Buffer:s}=r(287),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:u}=r(371).codes;e.exports=function(e,t,r){let l,d;if("string"==typeof t||t instanceof s)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[o])d=!0,l=t[o]();else{if(!t||!t[a])throw new c("iterable",["Iterable"],t);d=!1,l=t[a]()}const h=new e({objectMode:!0,highWaterMark:1,...r});let f=!1;return h._read=function(){f||(f=!0,async function(){for(;;){try{const{value:e,done:t}=d?await l.next():l.next();if(t)h.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw f=!1,new u;if(h.push(t))continue;f=!1}}catch(e){h.destroy(e)}break}}())},h._destroy=function(e,t){i(async function(e){const t=null!=e,r="function"==typeof l.throw;if(t&&r){const{value:t,done:r}=await l.throw(e);if(await t,r)return}if("function"==typeof l.return){const{value:e}=await l.return();await e}}(e),()=>n.nextTick(t,e),r=>n.nextTick(t,r||e))},h}},259(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(134),{EventEmitter:o}=r(7);function a(e){o.call(this,e)}function s(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?n(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}i(a.prototype,o.prototype),i(a,o),a.prototype.pipe=function(e,t){const r=this;function n(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),e.on("drain",i),e._isStdio||t&&!1===t.end||(r.on("end",c),r.on("close",u));let a=!1;function c(){a||(a=!0,e.end())}function u(){a||(a=!0,"function"==typeof e.destroy&&e.destroy())}function l(e){d(),0===o.listenerCount(this,"error")&&this.emit("error",e)}function d(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",c),r.removeListener("close",u),r.removeListener("error",l),e.removeListener("error",l),r.removeListener("end",d),r.removeListener("close",d),e.removeListener("close",d)}return s(r,"error",l),s(e,"error",l),r.on("end",d),r.on("close",d),e.on("close",d),e.emit("pipe",r),e},e.exports={Stream:a,prependListener:s}},524(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(134);e.exports=o;const i=r(382);function o(e){if(!(this instanceof o))return new o(e);i.call(this,e)}n(o.prototype,i.prototype),n(o,i),o.prototype._transform=function(e,t,r){r(null,e)}},758(e,t,r){const n=r(606),{ArrayIsArray:i,Promise:o,SymbolAsyncIterator:a,SymbolDispose:s}=r(134),c=r(238),{once:u}=r(760),l=r(896),d=r(370),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:p,ERR_MISSING_ARGS:m,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:g},AbortError:_}=r(371),{validateFunction:b,validateAbortSignal:w}=r(277),{isIterable:v,isReadable:S,isReadableNodeStream:x,isNodeStream:I,isTransformStream:A,isWebStream:T,isReadableStream:E,isReadableFinished:R}=r(115),k=globalThis.AbortController||r(568).AbortController;let j,N,C;function P(e,t,r){let n=!1;e.on("close",()=>{n=!0});return{destroy:t=>{n||(n=!0,l.destroyer(e,t||new y("pipe")))},cleanup:c(e,{readable:t,writable:r},e=>{n=!e})}}function O(e){if(v(e))return e;if(x(e))return async function*(e){N||(N=r(576));yield*N.prototype[a].call(e)}(e);throw new f("val",["Readable","Iterable","AsyncIterable"],e)}async function F(e,t,r,{end:n}){let i,a=null;const s=e=>{if(e&&(i=e),a){const e=a;a=null,e()}},u=()=>new o((e,t)=>{i?t(i):a=()=>{i?t(i):e()}});t.on("drain",s);const l=c(t,{readable:!1},s);try{t.writableNeedDrain&&await u();for await(const r of e)t.write(r)||await u();n&&(t.end(),await u()),r()}catch(e){r(i!==e?h(i,e):e)}finally{l(),t.off("drain",s)}}async function q(e,t,r,{end:n}){A(t)&&(t=t.writable);const i=t.getWriter();try{for await(const t of e)await i.ready,i.write(t).catch(()=>{});await i.ready,n&&await i.close(),r()}catch(e){try{await i.abort(e),r(e)}catch(e){r(e)}}}function M(e,t,o){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new m("streams");const a=new k,c=a.signal,u=null==o?void 0:o.signal,l=[];function h(){L(new _)}let y,g,b;w(u,"options.signal"),C=C||r(760).addAbortListener,u&&(y=C(u,h));const R=[];let N,M=0;function D(e){L(e,0===--M)}function L(e,r){var i;if(!e||g&&"ERR_STREAM_PREMATURE_CLOSE"!==g.code||(g=e),g||r){for(;R.length;)R.shift()(g);null===(i=y)||void 0===i||i[s](),a.abort(),r&&(g||l.forEach(e=>e()),n.nextTick(t,g,b))}}for(let Q=0;Q<e.length;Q++){const H=e[Q],K=Q<e.length-1,W=Q>0,J=K||!1!==(null==o?void 0:o.end),G=Q===e.length-1;if(I(H)){if(J){const{destroy:V,cleanup:X}=P(H,K,W);R.push(V),S(H)&&G&&l.push(X)}function U(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&D(e)}H.on("error",U),S(H)&&G&&l.push(()=>{H.removeListener("error",U)})}if(0===Q)if("function"==typeof H){if(N=H({signal:c}),!v(N))throw new p("Iterable, AsyncIterable or Stream","source",N)}else N=v(H)||x(H)||A(H)?H:d.from(H);else if("function"==typeof H){var z;if(A(N))N=O(null===(z=N)||void 0===z?void 0:z.readable);else N=O(N);if(N=H(N,{signal:c}),K){if(!v(N,!0))throw new p("AsyncIterable",`transform[${Q-1}]`,N)}else{var B;j||(j=r(524));const Y=new j({objectMode:!0}),Z=null===(B=N)||void 0===B?void 0:B.then;if("function"==typeof Z)M++,Z.call(N,e=>{b=e,null!=e&&Y.write(e),J&&Y.end(),n.nextTick(D)},e=>{Y.destroy(e),n.nextTick(D,e)});else if(v(N,!0))M++,F(N,Y,D,{end:J});else{if(!E(N)&&!A(N))throw new p("AsyncIterable or Promise","destination",N);{const re=N.readable||N;M++,F(re,Y,D,{end:J})}}N=Y;const{destroy:ee,cleanup:te}=P(N,!1,!0);R.push(ee),G&&l.push(te)}}else if(I(H)){if(x(N)){M+=2;const ne=$(N,H,D,{end:J});S(H)&&G&&l.push(ne)}else if(A(N)||E(N)){const ie=N.readable||N;M++,F(ie,H,D,{end:J})}else{if(!v(N))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);M++,F(N,H,D,{end:J})}N=H}else if(T(H)){if(x(N))M++,q(O(N),H,D,{end:J});else if(E(N)||v(N))M++,q(N,H,D,{end:J});else{if(!A(N))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],N);M++,q(N.readable,H,D,{end:J})}N=H}else N=d.from(H)}return(null!=c&&c.aborted||null!=u&&u.aborted)&&n.nextTick(h),N}function $(e,t,r,{end:i}){let o=!1;if(t.on("close",()=>{o||r(new g)}),e.pipe(t,{end:!1}),i){function a(){o=!0,t.end()}R(e)?n.nextTick(a):e.once("end",a)}else r();return c(e,{readable:!0,writable:!1},t=>{const n=e._readableState;t&&"ERR_STREAM_PREMATURE_CLOSE"===t.code&&n&&n.ended&&!n.errored&&!n.errorEmitted?e.once("end",r).once("error",r):r(t)}),c(t,{readable:!1,writable:!0},r)}e.exports={pipelineImpl:M,pipeline:function(...e){return M(e,u(function(e){return b(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},576(e,t,r){"use strict";const n=r(606),{ArrayPrototypeIndexOf:i,NumberIsInteger:o,NumberIsNaN:a,NumberParseInt:s,ObjectDefineProperties:c,ObjectKeys:u,ObjectSetPrototypeOf:l,Promise:d,SafeSet:h,SymbolAsyncDispose:f,SymbolAsyncIterator:p,Symbol:m}=r(134);e.exports=Q,Q.ReadableState=B;const{EventEmitter:y}=r(7),{Stream:g,prependListener:_}=r(259),{Buffer:b}=r(287),{addAbortSignal:w}=r(147),v=r(238);let S=r(760).debuglog("stream",e=>{S=e});const x=r(345),I=r(896),{getHighWaterMark:A,getDefaultHighWaterMark:T}=r(291),{aggregateTwoErrors:E,codes:{ERR_INVALID_ARG_TYPE:R,ERR_METHOD_NOT_IMPLEMENTED:k,ERR_OUT_OF_RANGE:j,ERR_STREAM_PUSH_AFTER_EOF:N,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:C},AbortError:P}=r(371),{validateObject:O}=r(277),F=m("kPaused"),{StringDecoder:q}=r(141),M=r(532);l(Q.prototype,g.prototype),l(Q,g);const $=()=>{},{errorOrDestroy:D}=I,L=2048,U=4096;function z(e){return{enumerable:!1,get(){return 0!==(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function B(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(370)),this.state=6192,e&&e.objectMode&&(this.state|=1),n&&e&&e.readableObjectMode&&(this.state|=1),this.highWaterMark=e?A(this,e,"readableHighWaterMark",n):T(!1),this.buffer=new x,this.length=0,this.pipes=[],this.flowing=null,this[F]=null,e&&!1===e.emitClose&&(this.state&=-2049),e&&!1===e.autoDestroy&&(this.state&=-4097),this.errored=null,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,e&&e.encoding&&(this.decoder=new q(e.encoding),this.encoding=e.encoding)}function Q(e){if(!(this instanceof Q))return new Q(e);const t=this instanceof r(370);this._readableState=new B(e,this,t),e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&!t&&w(e.signal,this)),g.call(this,e),I.construct(this,()=>{this._readableState.needReadable&&V(this,this._readableState)})}function H(e,t,r,n){S("readableAddChunk",t);const i=e._readableState;let o;if(1&i.state||("string"==typeof t?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?t=b.from(t,r).toString(i.encoding):(t=b.from(t,r),r=""))):t instanceof b?r="":g._isUint8Array(t)?(t=g._uint8ArrayToBuffer(t),r=""):null!=t&&(o=new R("chunk",["string","Buffer","Uint8Array"],t))),o)D(e,o);else if(null===t)i.state&=-9,function(e,t){if(S("onEofChunk"),t.ended)return;if(t.decoder){const e=t.decoder.end();e&&e.length&&(t.buffer.push(e),t.length+=t.objectMode?1:e.length)}t.ended=!0,t.sync?J(e):(t.needReadable=!1,t.emittedReadable=!0,G(e))}(e,i);else if(1&i.state||t&&t.length>0)if(n)if(4&i.state)D(e,new C);else{if(i.destroyed||i.errored)return!1;K(e,i,t,!0)}else if(i.ended)D(e,new N);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?K(e,i,t,!1):V(e,i)):K(e,i,t,!1)}else n||(i.state&=-9,V(e,i));return!i.ended&&(i.length<i.highWaterMark||0===i.length)}function K(e,t,r,n){t.flowing&&0===t.length&&!t.sync&&e.listenerCount("data")>0?(65536&t.state?t.awaitDrainWriters.clear():t.awaitDrainWriters=null,t.dataEmitted=!0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),64&t.state&&J(e)),V(e,t)}c(B.prototype,{objectMode:z(1),ended:z(2),endEmitted:z(4),reading:z(8),constructed:z(16),sync:z(32),needReadable:z(64),emittedReadable:z(128),readableListening:z(256),resumeScheduled:z(512),errorEmitted:z(1024),emitClose:z(L),autoDestroy:z(U),destroyed:z(8192),closed:z(16384),closeEmitted:z(32768),multiAwaitDrain:z(65536),readingMore:z(1<<17),dataEmitted:z(1<<18)}),Q.prototype.destroy=I.destroy,Q.prototype._undestroy=I.undestroy,Q.prototype._destroy=function(e,t){t(e)},Q.prototype[y.captureRejectionSymbol]=function(e){this.destroy(e)},Q.prototype[f]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new P,this.destroy(e)),new d((t,r)=>v(this,n=>n&&n!==e?r(n):t(null)))},Q.prototype.push=function(e,t){return H(this,e,t,!1)},Q.prototype.unshift=function(e,t){return H(this,e,t,!0)},Q.prototype.isPaused=function(){const e=this._readableState;return!0===e[F]||!1===e.flowing},Q.prototype.setEncoding=function(e){const t=new q(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;const r=this._readableState.buffer;let n="";for(const e of r)n+=t.write(e);return r.clear(),""!==n&&r.push(n),this._readableState.length=n.length,this};function W(e,t){return e<=0||0===t.length&&t.ended?0:1&t.state?1:a(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function J(e){const t=e._readableState;S("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(S("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(G,e))}function G(e){const t=e._readableState;S("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||t.errored||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,te(e)}function V(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(X,e,t))}function X(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){const r=t.length;if(S("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}function Y(e){const t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!1===t[F]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function Z(e){S("readable nexttick read 0"),e.read(0)}function ee(e,t){S("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),te(e),t.flowing&&!t.reading&&e.read(0)}function te(e){const t=e._readableState;for(S("flow",t.flowing);t.flowing&&null!==e.read(););}function re(e,t){"function"!=typeof e.read&&(e=Q.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=$;function i(t){this===e?(n(),n=$):n=t}e.on("readable",i);const o=v(e,{writable:!1},e=>{r=e?E(r,e):null,n(),n=$});try{for(;;){const t=e.destroyed?null:e.read();if(null!==t)yield t;else{if(r)throw r;if(null===r)return;await new d(i)}}}catch(e){throw r=E(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),o()):I.destroyer(e,null)}}(e,t);return r.stream=e,r}function ne(e,t){if(0===t.length)return null;let r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function ie(e){const t=e._readableState;S("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(oe,t,e))}function oe(e,t){if(S("endReadableNT",e.endEmitted,e.length),!e.errored&&!e.closeEmitted&&!e.endEmitted&&0===e.length)if(e.endEmitted=!0,t.emit("end"),t.writable&&!1===t.allowHalfOpen)n.nextTick(ae,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function ae(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let se;function ce(){return void 0===se&&(se={}),se}Q.prototype.read=function(e){S("read",e),void 0===e?e=NaN:o(e)||(e=s(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new j("size","<= 1GiB",e);return e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,++e}(e)),0!==e&&(t.state&=-129),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return S("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ie(this):J(this),null;if(0===(e=W(e,t))&&t.ended)return 0===t.length&&ie(this),null;let n,i=!!(64&t.state);if(S("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&(i=!0,S("length less than watermark",i)),t.ended||t.reading||t.destroyed||t.errored||!t.constructed)i=!1,S("reading, ended or constructing",i);else if(i){S("do read"),t.state|=40,0===t.length&&(t.state|=64);try{this._read(t.highWaterMark)}catch(e){D(this,e)}t.state&=-33,t.reading||(e=W(r,t))}return n=e>0?ne(e,t):null,null===n?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.multiAwaitDrain?t.awaitDrainWriters.clear():t.awaitDrainWriters=null),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ie(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},Q.prototype._read=function(e){throw new k("_read()")},Q.prototype.pipe=function(e,t){const r=this,i=this._readableState;1===i.pipes.length&&(i.multiAwaitDrain||(i.multiAwaitDrain=!0,i.awaitDrainWriters=new h(i.awaitDrainWriters?[i.awaitDrainWriters]:[]))),i.pipes.push(e),S("pipe count=%d opts=%j",i.pipes.length,t);const o=(!t||!1!==t.end)&&e!==n.stdout&&e!==n.stderr?s:y;function a(t,n){S("onunpipe"),t===r&&n&&!1===n.hasUnpiped&&(n.hasUnpiped=!0,function(){S("cleanup"),e.removeListener("close",p),e.removeListener("finish",m),c&&e.removeListener("drain",c);e.removeListener("error",f),e.removeListener("unpipe",a),r.removeListener("end",s),r.removeListener("end",y),r.removeListener("data",d),u=!0,c&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&c()}())}function s(){S("onend"),e.end()}let c;i.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",a);let u=!1;function l(){u||(1===i.pipes.length&&i.pipes[0]===e?(S("false write response, pause",0),i.awaitDrainWriters=e,i.multiAwaitDrain=!1):i.pipes.length>1&&i.pipes.includes(e)&&(S("false write response, pause",i.awaitDrainWriters.size),i.awaitDrainWriters.add(e)),r.pause()),c||(c=function(e,t){return function(){const r=e._readableState;r.awaitDrainWriters===t?(S("pipeOnDrain",1),r.awaitDrainWriters=null):r.multiAwaitDrain&&(S("pipeOnDrain",r.awaitDrainWriters.size),r.awaitDrainWriters.delete(t)),r.awaitDrainWriters&&0!==r.awaitDrainWriters.size||!e.listenerCount("data")||e.resume()}}(r,e),e.on("drain",c))}function d(t){S("ondata");const r=e.write(t);S("dest.write",r),!1===r&&l()}function f(t){if(S("onerror",t),y(),e.removeListener("error",f),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?D(e,t):e.emit("error",t)}}function p(){e.removeListener("finish",m),y()}function m(){S("onfinish"),e.removeListener("close",p),y()}function y(){S("unpipe"),r.unpipe(e)}return r.on("data",d),_(e,"error",f),e.once("close",p),e.once("finish",m),e.emit("pipe",r),!0===e.writableNeedDrain?l():i.flowing||(S("pipe resume"),r.resume()),e},Q.prototype.unpipe=function(e){const t=this._readableState;if(0===t.pipes.length)return this;if(!e){const e=t.pipes;t.pipes=[],this.pause();for(let t=0;t<e.length;t++)e[t].emit("unpipe",this,{hasUnpiped:!1});return this}const r=i(t.pipes,e);return-1===r||(t.pipes.splice(r,1),0===t.pipes.length&&this.pause(),e.emit("unpipe",this,{hasUnpiped:!1})),this},Q.prototype.on=function(e,t){const r=g.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=this.listenerCount("readable")>0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,S("on readable",i.length,i.reading),i.length?J(this):i.reading||n.nextTick(Z,this))),r},Q.prototype.addListener=Q.prototype.on,Q.prototype.removeListener=function(e,t){const r=g.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(Y,this),r},Q.prototype.off=Q.prototype.removeListener,Q.prototype.removeAllListeners=function(e){const t=g.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(Y,this),t},Q.prototype.resume=function(){const e=this._readableState;return e.flowing||(S("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(ee,e,t))}(this,e)),e[F]=!1,this},Q.prototype.pause=function(){return S("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(S("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[F]=!0,this},Q.prototype.wrap=function(e){let t=!1;e.on("data",r=>{!this.push(r)&&e.pause&&(t=!0,e.pause())}),e.on("end",()=>{this.push(null)}),e.on("error",e=>{D(this,e)}),e.on("close",()=>{this.destroy()}),e.on("destroy",()=>{this.destroy()}),this._read=()=>{t&&e.resume&&(t=!1,e.resume())};const r=u(e);for(let t=1;t<r.length;t++){const n=r[t];void 0===this[n]&&"function"==typeof e[n]&&(this[n]=e[n].bind(e))}return this},Q.prototype[p]=function(){return re(this)},Q.prototype.iterator=function(e){return void 0!==e&&O(e,"options"),re(this,e)},c(Q.prototype,{readable:{__proto__:null,get(){const e=this._readableState;return!(!e||!1===e.readable||e.destroyed||e.errorEmitted||e.endEmitted)},set(e){this._readableState&&(this._readableState.readable=!!e)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!(!1===this._readableState.readable||!this._readableState.destroyed&&!this._readableState.errored||this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.objectMode}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return!!this._readableState&&this._readableState.closed}},destroyed:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.destroyed},set(e){this._readableState&&(this._readableState.destroyed=e)}},readableEnded:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.endEmitted}}}),c(B.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return!1!==this[F]},set(e){this[F]=!!e}}}),Q._fromList=ne,Q.from=function(e,t){return M(Q,e,t)},Q.fromWeb=function(e,t){return ce().newStreamReadableFromReadableStream(e,t)},Q.toWeb=function(e,t){return ce().newReadableStreamFromStreamReadable(e,t)},Q.wrap=function(e,t){var r,n;return new Q({objectMode:null===(r=null!==(n=e.readableObjectMode)&&void 0!==n?n:e.objectMode)||void 0===r||r,...t,destroy(t,r){I.destroyer(e,t),r(t)}}).wrap(e)}},291(e,t,r){"use strict";const{MathFloor:n,NumberIsInteger:i}=r(134),{validateInteger:o}=r(277),{ERR_INVALID_ARG_VALUE:a}=r(371).codes;let s=16384,c=16;function u(e){return e?c:s}e.exports={getHighWaterMark:function(e,t,r,o){const s=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,o,r);if(null!=s){if(!i(s)||s<0){throw new a(o?`options.${r}`:"options.highWaterMark",s)}return n(s)}return u(e.objectMode)},getDefaultHighWaterMark:u,setDefaultHighWaterMark:function(e,t){o(t,"value",0),e?c=t:s=t}}},382(e,t,r){"use strict";const{ObjectSetPrototypeOf:n,Symbol:i}=r(134);e.exports=u;const{ERR_METHOD_NOT_IMPLEMENTED:o}=r(371).codes,a=r(370),{getHighWaterMark:s}=r(291);n(u.prototype,a.prototype),n(u,a);const c=i("kCallback");function u(e){if(!(this instanceof u))return new u(e);const t=e?s(this,e,"readableHighWaterMark",!0):null;0===t&&(e={...e,highWaterMark:null,readableHighWaterMark:t,writableHighWaterMark:e.writableHighWaterMark||0}),a.call(this,e),this._readableState.sync=!1,this[c]=null,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",d)}function l(e){"function"!=typeof this._flush||this.destroyed?(this.push(null),e&&e()):this._flush((t,r)=>{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())})}function d(){this._final!==l&&l.call(this)}u.prototype._final=l,u.prototype._transform=function(e,t,r){throw new o("_transform()")},u.prototype._write=function(e,t,r){const n=this._readableState,i=this._writableState,o=n.length;this._transform(e,t,(e,t)=>{e?r(e):(null!=t&&this.push(t),i.ended||o===n.length||n.length<n.highWaterMark?r():this[c]=r)})},u.prototype._read=function(){if(this[c]){const e=this[c];this[c]=null,e()}}},115(e,t,r){"use strict";const{SymbolAsyncIterator:n,SymbolIterator:i,SymbolFor:o}=r(134),a=o("nodejs.stream.destroyed"),s=o("nodejs.stream.errored"),c=o("nodejs.stream.readable"),u=o("nodejs.stream.writable"),l=o("nodejs.stream.disturbed"),d=o("nodejs.webstream.isClosedPromise"),h=o("nodejs.webstream.controllerErrorFunction");function f(e,t=!1){var r;return!(!e||"function"!=typeof e.pipe||"function"!=typeof e.on||t&&("function"!=typeof e.pause||"function"!=typeof e.resume)||e._writableState&&!1===(null===(r=e._readableState)||void 0===r?void 0:r.readable)||e._writableState&&!e._readableState)}function p(e){var t;return!(!e||"function"!=typeof e.write||"function"!=typeof e.on||e._readableState&&!1===(null===(t=e._writableState)||void 0===t?void 0:t.writable))}function m(e){return e&&(e._readableState||e._writableState||"function"==typeof e.write&&"function"==typeof e.on||"function"==typeof e.pipe&&"function"==typeof e.on)}function y(e){return!(!e||m(e)||"function"!=typeof e.pipeThrough||"function"!=typeof e.getReader||"function"!=typeof e.cancel)}function g(e){return!(!e||m(e)||"function"!=typeof e.getWriter||"function"!=typeof e.abort)}function _(e){return!(!e||m(e)||"object"!=typeof e.readable||"object"!=typeof e.writable)}function b(e){if(!m(e))return null;const t=e._writableState,r=e._readableState,n=t||r;return!!(e.destroyed||e[a]||null!=n&&n.destroyed)}function w(e){if(!p(e))return null;if(!0===e.writableEnded)return!0;const t=e._writableState;return(null==t||!t.errored)&&("boolean"!=typeof(null==t?void 0:t.ended)?null:t.ended)}function v(e,t){if(!f(e))return null;const r=e._readableState;return(null==r||!r.errored)&&("boolean"!=typeof(null==r?void 0:r.endEmitted)?null:!!(r.endEmitted||!1===t&&!0===r.ended&&0===r.length))}function S(e){return e&&null!=e[c]?e[c]:"boolean"!=typeof(null==e?void 0:e.readable)?null:!b(e)&&(f(e)&&e.readable&&!v(e))}function x(e){return e&&null!=e[u]?e[u]:"boolean"!=typeof(null==e?void 0:e.writable)?null:!b(e)&&(p(e)&&e.writable&&!w(e))}function I(e){return"boolean"==typeof e._closed&&"boolean"==typeof e._defaultKeepAlive&&"boolean"==typeof e._removedConnection&&"boolean"==typeof e._removedContLen}function A(e){return"boolean"==typeof e._sent100&&I(e)}e.exports={isDestroyed:b,kIsDestroyed:a,isDisturbed:function(e){var t;return!(!e||!(null!==(t=e[l])&&void 0!==t?t:e.readableDidRead||e.readableAborted))},isErrored:function(e){var t,r,n,i,o,a,c,u,l,d;return!(!e||!(null!==(t=null!==(r=null!==(n=null!==(i=null!==(o=null!==(a=e[s])&&void 0!==a?a:e.readableErrored)&&void 0!==o?o:e.writableErrored)&&void 0!==i?i:null===(c=e._readableState)||void 0===c?void 0:c.errorEmitted)&&void 0!==n?n:null===(u=e._writableState)||void 0===u?void 0:u.errorEmitted)&&void 0!==r?r:null===(l=e._readableState)||void 0===l?void 0:l.errored)&&void 0!==t?t:null===(d=e._writableState)||void 0===d?void 0:d.errored))},isReadable:S,kIsClosedPromise:d,kControllerErrorFunction:h,isClosed:function(e){if(!m(e))return null;if("boolean"==typeof e.closed)return e.closed;const t=e._writableState,r=e._readableState;return"boolean"==typeof(null==t?void 0:t.closed)||"boolean"==typeof(null==r?void 0:r.closed)?(null==t?void 0:t.closed)||(null==r?void 0:r.closed):"boolean"==typeof e._closed&&I(e)?e._closed:null},isDuplexNodeStream:function(e){return!(!e||"function"!=typeof e.pipe||!e._readableState||"function"!=typeof e.on||"function"!=typeof e.write)},isFinished:function(e,t){return m(e)?!!b(e)||(!1===(null==t?void 0:t.readable)||!S(e))&&(!1===(null==t?void 0:t.writable)||!x(e)):null},isIterable:function(e,t){return null!=e&&(!0===t?"function"==typeof e[n]:!1===t?"function"==typeof e[i]:"function"==typeof e[n]||"function"==typeof e[i])},isReadableNodeStream:f,isReadableStream:y,isReadableFinished:v,isReadableErrored:function(e){var t,r;return m(e)?e.readableErrored?e.readableErrored:null!==(t=null===(r=e._readableState)||void 0===r?void 0:r.errored)&&void 0!==t?t:null:null},isNodeStream:m,isWebStream:function(e){return y(e)||g(e)||_(e)},isWritable:x,isWritableNodeStream:p,isWritableStream:g,isWritableFinished:function(e,t){if(!p(e))return null;if(!0===e.writableFinished)return!0;const r=e._writableState;return(null==r||!r.errored)&&("boolean"!=typeof(null==r?void 0:r.finished)?null:!!(r.finished||!1===t&&!0===r.ended&&0===r.length))},isWritableErrored:function(e){var t,r;return m(e)?e.writableErrored?e.writableErrored:null!==(t=null===(r=e._writableState)||void 0===r?void 0:r.errored)&&void 0!==t?t:null:null},isServerRequest:function(e){var t;return"boolean"==typeof e._consuming&&"boolean"==typeof e._dumped&&void 0===(null===(t=e.req)||void 0===t?void 0:t.upgradeOrConnect)},willEmitClose:function(e){if(!m(e))return null;const t=e._writableState,r=e._readableState,n=t||r;return!n&&A(e)||!!(n&&n.autoDestroy&&n.emitClose&&!1===n.closed)},isTransformStream:_}},584(e,t,r){"use strict";const n=r(606),{ArrayPrototypeSlice:i,Error:o,FunctionPrototypeSymbolHasInstance:a,ObjectDefineProperty:s,ObjectDefineProperties:c,ObjectSetPrototypeOf:u,StringPrototypeToLowerCase:l,Symbol:d,SymbolHasInstance:h}=r(134);e.exports=O,O.WritableState=C;const{EventEmitter:f}=r(7),p=r(259).Stream,{Buffer:m}=r(287),y=r(896),{addAbortSignal:g}=r(147),{getHighWaterMark:_,getDefaultHighWaterMark:b}=r(291),{ERR_INVALID_ARG_TYPE:w,ERR_METHOD_NOT_IMPLEMENTED:v,ERR_MULTIPLE_CALLBACK:S,ERR_STREAM_CANNOT_PIPE:x,ERR_STREAM_DESTROYED:I,ERR_STREAM_ALREADY_FINISHED:A,ERR_STREAM_NULL_VALUES:T,ERR_STREAM_WRITE_AFTER_END:E,ERR_UNKNOWN_ENCODING:R}=r(371).codes,{errorOrDestroy:k}=y;function j(){}u(O.prototype,p.prototype),u(O,p);const N=d("kOnFinished");function C(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(370)),this.objectMode=!(!e||!e.objectMode),n&&(this.objectMode=this.objectMode||!(!e||!e.writableObjectMode)),this.highWaterMark=e?_(this,e,"writableHighWaterMark",n):b(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const i=!(!e||!1!==e.decodeStrings);this.decodeStrings=!i,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=$.bind(void 0,t),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,P(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!e||!1!==e.emitClose,this.autoDestroy=!e||!1!==e.autoDestroy,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[N]=[]}function P(e){e.buffered=[],e.bufferedIndex=0,e.allBuffers=!0,e.allNoop=!0}function O(e){const t=this instanceof r(370);if(!t&&!a(O,this))return new O(e);this._writableState=new C(e,this,t),e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&g(e.signal,this)),p.call(this,e),y.construct(this,()=>{const e=this._writableState;e.writing||z(this,e),H(this,e)})}function F(e,t,r,i){const o=e._writableState;if("function"==typeof r)i=r,r=o.defaultEncoding;else{if(r){if("buffer"!==r&&!m.isEncoding(r))throw new R(r)}else r=o.defaultEncoding;"function"!=typeof i&&(i=j)}if(null===t)throw new T;if(!o.objectMode)if("string"==typeof t)!1!==o.decodeStrings&&(t=m.from(t,r),r="buffer");else if(t instanceof m)r="buffer";else{if(!p._isUint8Array(t))throw new w("chunk",["string","Buffer","Uint8Array"],t);t=p._uint8ArrayToBuffer(t),r="buffer"}let a;return o.ending?a=new E:o.destroyed&&(a=new I("write")),a?(n.nextTick(i,a),k(e,a,!0),a):(o.pendingcb++,function(e,t,r,n,i){const o=t.objectMode?1:r.length;t.length+=o;const a=t.length<t.highWaterMark;a||(t.needDrain=!0);t.writing||t.corked||t.errored||!t.constructed?(t.buffered.push({chunk:r,encoding:n,callback:i}),t.allBuffers&&"buffer"!==n&&(t.allBuffers=!1),t.allNoop&&i!==j&&(t.allNoop=!1)):(t.writelen=o,t.writecb=i,t.writing=!0,t.sync=!0,e._write(r,n,t.onwrite),t.sync=!1);return a&&!t.errored&&!t.destroyed}(e,o,t,r,i))}function q(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new I("write")):r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function M(e,t,r,n){--t.pendingcb,n(r),U(t),k(e,r)}function $(e,t){const r=e._writableState,i=r.sync,o=r.writecb;"function"==typeof o?(r.writing=!1,r.writecb=null,r.length-=r.writelen,r.writelen=0,t?(t.stack,r.errored||(r.errored=t),e._readableState&&!e._readableState.errored&&(e._readableState.errored=t),i?n.nextTick(M,e,r,t,o):M(e,r,t,o)):(r.buffered.length>r.bufferedIndex&&z(e,r),i?null!==r.afterWriteTickInfo&&r.afterWriteTickInfo.cb===o?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:o,stream:e,state:r},n.nextTick(D,r.afterWriteTickInfo)):L(e,r,1,o))):k(e,new S)}function D({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,L(e,t,r,n)}function L(e,t,r,n){for(!t.ending&&!e.destroyed&&0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"));r-- >0;)t.pendingcb--,n();t.destroyed&&U(t),H(e,t)}function U(e){if(e.writing)return;for(let r=e.bufferedIndex;r<e.buffered.length;++r){var t;const{chunk:n,callback:i}=e.buffered[r],o=e.objectMode?1:n.length;e.length-=o,i(null!==(t=e.errored)&&void 0!==t?t:new I("write"))}const r=e[N].splice(0);for(let t=0;t<r.length;t++){var n;r[t](null!==(n=e.errored)&&void 0!==n?n:new I("end"))}P(e)}function z(e,t){if(t.corked||t.bufferProcessing||t.destroyed||!t.constructed)return;const{buffered:r,bufferedIndex:n,objectMode:o}=t,a=r.length-n;if(!a)return;let s=n;if(t.bufferProcessing=!0,a>1&&e._writev){t.pendingcb-=a-1;const n=t.allNoop?j:e=>{for(let t=s;t<r.length;++t)r[t].callback(e)},o=t.allNoop&&0===s?r:i(r,s);o.allBuffers=t.allBuffers,q(e,t,!0,t.length,o,"",n),P(t)}else{do{const{chunk:n,encoding:i,callback:a}=r[s];r[s++]=null;q(e,t,!1,o?1:n.length,n,i,a)}while(s<r.length&&!t.writing);s===r.length?P(t):s>256?(r.splice(0,s),t.bufferedIndex=0):t.bufferedIndex=s}t.bufferProcessing=!1}function B(e){return e.ending&&!e.destroyed&&e.constructed&&0===e.length&&!e.errored&&0===e.buffered.length&&!e.finished&&!e.writing&&!e.errorEmitted&&!e.closeEmitted}function Q(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.finalCalled=!0,function(e,t){let r=!1;function i(i){if(r)k(e,null!=i?i:S());else if(r=!0,t.pendingcb--,i){const r=t[N].splice(0);for(let e=0;e<r.length;e++)r[e](i);k(e,i,t.sync)}else B(t)&&(t.prefinished=!0,e.emit("prefinish"),t.pendingcb++,n.nextTick(K,e,t))}t.sync=!0,t.pendingcb++;try{e._final(i)}catch(e){i(e)}t.sync=!1}(e,t)))}function H(e,t,r){B(t)&&(Q(e,t),0===t.pendingcb&&(r?(t.pendingcb++,n.nextTick((e,t)=>{B(t)?K(e,t):t.pendingcb--},e,t)):B(t)&&(t.pendingcb++,K(e,t))))}function K(e,t){t.pendingcb--,t.finished=!0;const r=t[N].splice(0);for(let e=0;e<r.length;e++)r[e]();if(e.emit("finish"),t.autoDestroy){const t=e._readableState;(!t||t.autoDestroy&&(t.endEmitted||!1===t.readable))&&e.destroy()}}C.prototype.getBuffer=function(){return i(this.buffered,this.bufferedIndex)},s(C.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}}),s(O,h,{__proto__:null,value:function(e){return!!a(this,e)||this===O&&(e&&e._writableState instanceof C)}}),O.prototype.pipe=function(){k(this,new x)},O.prototype.write=function(e,t,r){return!0===F(this,e,t,r)},O.prototype.cork=function(){this._writableState.corked++},O.prototype.uncork=function(){const e=this._writableState;e.corked&&(e.corked--,e.writing||z(this,e))},O.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=l(e)),!m.isEncoding(e))throw new R(e);return this._writableState.defaultEncoding=e,this},O.prototype._write=function(e,t,r){if(!this._writev)throw new v("_write()");this._writev([{chunk:e,encoding:t}],r)},O.prototype._writev=null,O.prototype.end=function(e,t,r){const i=this._writableState;let a;if("function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e){const r=F(this,e,t);r instanceof o&&(a=r)}return i.corked&&(i.corked=1,this.uncork()),a||(i.errored||i.ending?i.finished?a=new A("end"):i.destroyed&&(a=new I("end")):(i.ending=!0,H(this,i,!0),i.ended=!0)),"function"==typeof r&&(a||i.finished?n.nextTick(r,a):i[N].push(r)),this},c(O.prototype,{closed:{__proto__:null,get(){return!!this._writableState&&this._writableState.closed}},destroyed:{__proto__:null,get(){return!!this._writableState&&this._writableState.destroyed},set(e){this._writableState&&(this._writableState.destroyed=e)}},writable:{__proto__:null,get(){const e=this._writableState;return!(!e||!1===e.writable||e.destroyed||e.errored||e.ending||e.ended)},set(e){this._writableState&&(this._writableState.writable=!!e)}},writableFinished:{__proto__:null,get(){return!!this._writableState&&this._writableState.finished}},writableObjectMode:{__proto__:null,get(){return!!this._writableState&&this._writableState.objectMode}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return!!this._writableState&&this._writableState.ending}},writableNeedDrain:{__proto__:null,get(){const e=this._writableState;return!!e&&(!e.destroyed&&!e.ending&&e.needDrain)}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!(!1===this._writableState.writable||!this._writableState.destroyed&&!this._writableState.errored||this._writableState.finished)}}});const W=y.destroy;let J;function G(){return void 0===J&&(J={}),J}O.prototype.destroy=function(e,t){const r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[N].length)&&n.nextTick(U,r),W.call(this,e,t),this},O.prototype._undestroy=y.undestroy,O.prototype._destroy=function(e,t){t(e)},O.prototype[f.captureRejectionSymbol]=function(e){this.destroy(e)},O.fromWeb=function(e,t){return G().newStreamWritableFromWritableStream(e,t)},O.toWeb=function(e){return G().newWritableStreamFromStreamWritable(e)}},277(e,t,r){"use strict";const{ArrayIsArray:n,ArrayPrototypeIncludes:i,ArrayPrototypeJoin:o,ArrayPrototypeMap:a,NumberIsInteger:s,NumberIsNaN:c,NumberMAX_SAFE_INTEGER:u,NumberMIN_SAFE_INTEGER:l,NumberParseInt:d,ObjectPrototypeHasOwnProperty:h,RegExpPrototypeExec:f,String:p,StringPrototypeToUpperCase:m,StringPrototypeTrim:y}=r(134),{hideStackFrames:g,codes:{ERR_SOCKET_BAD_PORT:_,ERR_INVALID_ARG_TYPE:b,ERR_INVALID_ARG_VALUE:w,ERR_OUT_OF_RANGE:v,ERR_UNKNOWN_SIGNAL:S}}=r(371),{normalizeEncoding:x}=r(760),{isAsyncFunction:I,isArrayBufferView:A}=r(760).types;const T=g((e,t,r=l,n=u)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!s(e))throw new v(t,"an integer",e);if(e<r||e>n)throw new v(t,`>= ${r} && <= ${n}`,e)});g((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!s(e))throw new v(t,"an integer",e);if(e<r||e>n)throw new v(t,`>= ${r} && <= ${n}`,e)}),g((e,t,r=!1)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!s(e))throw new v(t,"an integer",e);const n=r?1:0,i=4294967295;if(e<n||e>i)throw new v(t,`>= ${n} && <= ${i}`,e)});g((e,t,r)=>{if(!i(r,e)){const n=o(a(r,e=>"string"==typeof e?`'${e}'`:p(e)),", ");throw new w(t,e,"must be one of: "+n)}});function E(e,t){if("boolean"!=typeof e)throw new b(t,"boolean",e)}function R(e,t,r){return null!=e&&h(e,t)?e[t]:r}const k=g((e,t,r=null)=>{const i=R(r,"allowArray",!1),o=R(r,"allowFunction",!1);if(!R(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!o||"function"!=typeof e))throw new b(t,"Object",e)});g((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new b(t,"a dictionary",e)}),g((e,t,r=0)=>{if(!n(e))throw new b(t,"Array",e);if(e.length<r){throw new w(t,e,`must be longer than ${r}`)}});g((e,t="buffer")=>{if(!A(e))throw new b(t,["Buffer","TypedArray","DataView"],e)});const j=g((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new b(t,"AbortSignal",e)}),N=g((e,t)=>{if("function"!=typeof e)throw new b(t,"Function",e)});g((e,t)=>{if("function"!=typeof e||I(e))throw new b(t,"Function",e)}),g((e,t)=>{if(void 0!==e)throw new b(t,"undefined",e)});e.exports={validateBoolean:E,validateFunction:N,validateInteger:T,validateObject:k,validateAbortSignal:j}},371(e,t,r){"use strict";const{format:n,inspect:i}=r(231),{AggregateError:o}=r(134),a=globalThis.AggregateError||o,s=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],u=/^([A-Z][a-z0-9]*)+$/,l={};function d(e,t){if(!e)throw new l.ERR_INTERNAL_ASSERTION(t)}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 f(e,t,r){r||(r=Error);class NodeError extends r{constructor(...r){super(function(e,t,r){if("function"==typeof t)return d(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);const i=(t.match(/%[dfijoOs]/g)||[]).length;return d(i===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${i}).`),0===r.length?t:n(t,...r)}(e,t,r))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(NodeError.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),NodeError.prototype.code=e,NodeError.prototype[s]=!0,l[e]=NodeError}function p(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class AbortError extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new l.ERR_INVALID_ARG_TYPE("options","Object",t);super(e,t),this.code="ABORT_ERR",this.name="AbortError"}}f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(e,t,r)=>{d("string"==typeof e,"'name' must be a string"),Array.isArray(t)||(t=[t]);let n="The ";e.endsWith(" argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="must be ";const o=[],a=[],s=[];for(const e of t)d("string"==typeof e,"All expected entries have to be of type string"),c.includes(e)?o.push(e.toLowerCase()):u.test(e)?a.push(e):(d("object"!==e,'The value "object" should be written as "Object"'),s.push(e));if(a.length>0){const e=o.indexOf("object");-1!==e&&(o.splice(o,e,1),a.push("Object"))}if(o.length>0){switch(o.length){case 1:n+=`of type ${o[0]}`;break;case 2:n+=`one of type ${o[0]} or ${o[1]}`;break;default:{const e=o.pop();n+=`one of type ${o.join(", ")}, or ${e}`}}(a.length>0||s.length>0)&&(n+=" or ")}if(a.length>0){switch(a.length){case 1:n+=`an instance of ${a[0]}`;break;case 2:n+=`an instance of ${a[0]} or ${a[1]}`;break;default:{const e=a.pop();n+=`an instance of ${a.join(", ")}, or ${e}`}}s.length>0&&(n+=" or ")}switch(s.length){case 0:break;case 1:s[0].toLowerCase()!==s[0]&&(n+="an "),n+=`${s[0]}`;break;case 2:n+=`one of ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`one of ${s.join(", ")}, or ${e}`}}if(null==r)n+=`. Received ${r}`;else if("function"==typeof r&&r.name)n+=`. Received function ${r.name}`;else if("object"==typeof r){var l;if(null!==(l=r.constructor)&&void 0!==l&&l.name)n+=`. Received an instance of ${r.constructor.name}`;else{n+=`. Received ${i(r,{depth:-1})}`}}else{let e=i(r,{colors:!1});e.length>25&&(e=`${e.slice(0,25)}...`),n+=`. Received type ${typeof r} (${e})`}return n},TypeError),f("ERR_INVALID_ARG_VALUE",(e,t,r="is invalid")=>{let n=i(t);n.length>128&&(n=n.slice(0,128)+"...");return`The ${e.includes(".")?"property":"argument"} '${e}' ${r}. Received ${n}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(e,t,r)=>{var n;return`Expected ${e} to be returned from the "${t}" function but got ${null!=r&&null!==(n=r.constructor)&&void 0!==n&&n.name?`instance of ${r.constructor.name}`:"type "+typeof r}.`},TypeError),f("ERR_MISSING_ARGS",(...e)=>{let t;d(e.length>0,"At least one arg needs to be specified");const r=e.length;switch(e=(Array.isArray(e)?e:[e]).map(e=>`"${e}"`).join(" or "),r){case 1:t+=`The ${e[0]} argument`;break;case 2:t+=`The ${e[0]} and ${e[1]} arguments`;break;default:{const r=e.pop();t+=`The ${e.join(", ")}, and ${r} arguments`}}return`${t} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(e,t,r)=>{let n;if(d(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32)n=h(String(r));else if("bigint"==typeof r){n=String(r);const e=BigInt(2)**BigInt(32);(r>e||r<-e)&&(n=h(n)),n+="n"}else n=i(r);return`The value of "${e}" is out of range. It must be ${t}. Received ${n}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError,aggregateTwoErrors:p(function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new a([t,e],t.message);return r.code=t.code,r}return e||t}),hideStackFrames:p,codes:l}},134(e){"use strict";class AggregateError extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError("Expected input to be an Array, got "+typeof e);let t="";for(let r=0;r<e.length;r++)t+=` ${e[r].stack}\n`;super(t),this.name="AggregateError",this.errors=e}}e.exports={AggregateError,ArrayIsArray:e=>Array.isArray(e),ArrayPrototypeIncludes:(e,t)=>e.includes(t),ArrayPrototypeIndexOf:(e,t)=>e.indexOf(t),ArrayPrototypeJoin:(e,t)=>e.join(t),ArrayPrototypeMap:(e,t)=>e.map(t),ArrayPrototypePop:(e,t)=>e.pop(t),ArrayPrototypePush:(e,t)=>e.push(t),ArrayPrototypeSlice:(e,t,r)=>e.slice(t,r),Error,FunctionPrototypeCall:(e,t,...r)=>e.call(t,...r),FunctionPrototypeSymbolHasInstance:(e,t)=>Function.prototype[Symbol.hasInstance].call(e,t),MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties:(e,t)=>Object.defineProperties(e,t),ObjectDefineProperty:(e,t,r)=>Object.defineProperty(e,t,r),ObjectGetOwnPropertyDescriptor:(e,t)=>Object.getOwnPropertyDescriptor(e,t),ObjectKeys:e=>Object.keys(e),ObjectSetPrototypeOf:(e,t)=>Object.setPrototypeOf(e,t),Promise,PromisePrototypeCatch:(e,t)=>e.catch(t),PromisePrototypeThen:(e,t,r)=>e.then(t,r),PromiseReject:e=>Promise.reject(e),PromiseResolve:e=>Promise.resolve(e),ReflectApply:Reflect.apply,RegExpPrototypeTest:(e,t)=>e.test(t),SafeSet:Set,String,StringPrototypeSlice:(e,t,r)=>e.slice(t,r),StringPrototypeToLowerCase:e=>e.toLowerCase(),StringPrototypeToUpperCase:e=>e.toUpperCase(),StringPrototypeTrim:e=>e.trim(),Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet:(e,t,r)=>e.set(t,r),Boolean,Uint8Array}},760(e,t,r){"use strict";const n=r(287),{format:i,inspect:o}=r(231),{codes:{ERR_INVALID_ARG_TYPE:a}}=r(371),{kResistStopPropagation:s,AggregateError:c,SymbolDispose:u}=r(134),l=globalThis.AbortSignal||r(568).AbortSignal,d=globalThis.AbortController||r(568).AbortController,h=Object.getPrototypeOf(async function(){}).constructor,f=globalThis.Blob||n.Blob,p=void 0!==f?function(e){return e instanceof f}:function(e){return!1},m=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new a(t,"AbortSignal",e)};e.exports={AggregateError:c,kEmptyObject:Object.freeze({}),once(e){let t=!1;return function(...r){t||(t=!0,e.apply(this,r))}},createDeferredPromise:function(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}},promisify:e=>new Promise((t,r)=>{e((e,...n)=>e?r(e):t(...n))}),debuglog:()=>function(){},format:i,inspect:o,types:{isAsyncFunction:e=>e instanceof h,isArrayBufferView:e=>ArrayBuffer.isView(e)},isBlob:p,deprecate:(e,t)=>e,addAbortListener:r(7).addAbortListener||function(e,t){if(void 0===e)throw new a("signal","AbortSignal",e);let r;return m(e,"signal"),((e,t)=>{if("function"!=typeof e)throw new a(t,"Function",e)})(t,"listener"),e.aborted?queueMicrotask(()=>t()):(e.addEventListener("abort",t,{__proto__:null,once:!0,[s]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[u](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:l.any||function(e){if(1===e.length)return e[0];const t=new d,r=()=>t.abort();return e.forEach(e=>{m(e,"signals"),e.addEventListener("abort",r,{once:!0})}),t.signal.addEventListener("abort",()=>{e.forEach(e=>e.removeEventListener("abort",r))},{once:!0}),t.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},231(e){"use strict";e.exports={format:(e,...t)=>e.replace(/%([sdifj])/g,function(...[e,r]){const n=t.shift();if("f"===r)return n.toFixed(6);if("j"===r)return JSON.stringify(n);if("s"===r&&"object"==typeof n){return`${n.constructor!==Object?n.constructor.name:""} {}`.trim()}return n.toString()}),inspect(e){switch(typeof e){case"string":if(e.includes("'")){if(!e.includes('"'))return`"${e}"`;if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}}}},861(e,t,r){var n=r(287),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=a),a.prototype=Object.create(i.prototype),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},141(e,t,r){"use strict";var n=r(861).Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=l,this.end=d,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function u(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function l(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""},o.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},o.prototype.text=function(e,t){var r=function(e,t,r){var n=t.length-1;if(n<r)return 0;var i=a(t[n]);if(i>=0)return i>0&&(e.lastNeed=i-1),i;if(--n<r||-2===i)return 0;if(i=a(t[n]),i>=0)return i>0&&(e.lastNeed=i-2),i;if(--n<r||-2===i)return 0;if(i=a(t[n]),i>=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},955(t){"use strict";t.exports=e},981(e){"use strict";e.exports=t}};const n={};function i(e){const t=n[e];if(void 0!==t)return t.exports;const o=n[e]={exports:{}};return r[e].call(o.exports,o,o.exports,i),o.exports}i.cw=e=>{var t;return()=>{if(e){var r=e;e=0,t={exports:{}},r.call(t.exports,t,t.exports)}return t.exports}},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let o={};return(()=>{"use strict";i.r(o),i.d(o,{Activity:()=>rh,ActivityAdd:()=>nh,ActivityRemove:()=>ih,Collection:()=>Yd,Container:()=>th,DatasetSubscription:()=>DatasetSubscription,DefaultEngine:()=>lh,EventStream:()=>eh,GreaterThanOrEqualToRelation:()=>Jd,GreaterThanRelation:()=>Gd,LessThanOrEqualToRelation:()=>Vd,LessThanRelation:()=>Xd,Node:()=>Zd,PropertyType:()=>uh,Relation:()=>Wd,SolidClientService:()=>SolidClientService,SolidDataDriver:()=>SolidDataDriver,SolidProfileObject:()=>oh,SolidPropertyService:()=>SolidPropertyService,SolidPropertySink:()=>SolidPropertySink,SolidPropertySource:()=>SolidPropertySource,SolidService:()=>SolidService,defaultThingDeserializer:()=>sh,defaultThingSerializer:()=>ah});var e=i.cw(function(e,t){var r=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),n=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.QueryEngineBase=void 0,n(i(638),t),n(i(358),t);var o=i(235);Object.defineProperty(t,"QueryEngineBase",{enumerable:!0,get:function(){return o.QueryEngineBase}})}),t=()=>i(287),r=i.cw(e=>{var t=/^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i,r=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,n=/\s|\uFEFF|\xA0/,i=/\r?\n[\x20\x09]+/g,o=/[;,"]/,a=/[;,"]|\s/,s=/^[!#$%&'*+\-\.^_`|~\da-zA-Z]+$/,c=1,u=2,l=4;function d(e){return e.replace(r,"")}function h(e){return n.test(e)}function f(e,t){for(;h(e[t]);)t++;return t}function p(e){return a.test(e)||!s.test(e)}class Link{constructor(e){this.refs=[],e&&this.parse(e)}rel(e){for(var t=[],r=e.toLowerCase(),n=0;n<this.refs.length;n++)"string"==typeof this.refs[n].rel&&this.refs[n].rel.toLowerCase()===r&&t.push(this.refs[n]);return t}get(e,t){e=e.toLowerCase(),t=t.toLowerCase();for(var r=[],n=0;n<this.refs.length;n++)"string"==typeof this.refs[n][e]&&this.refs[n][e].toLowerCase()===t&&r.push(this.refs[n]);return r}set(e){return this.refs.push(e),this}setUnique(e){return this.refs.some(t=>{return r=t,n=e,Object.keys(r).length===Object.keys(n).length&&Object.keys(r).every(e=>e in n&&r[e]===n[e]);var r,n})||this.refs.push(e),this}has(e,t){e=e.toLowerCase(),t=t.toLowerCase();for(var r=0;r<this.refs.length;r++)if("string"==typeof this.refs[r][e]&&this.refs[r][e].toLowerCase()===t)return!0;return!1}parse(e,t){e=d(e=(t=t||0)?e.slice(t):e).replace(i,"");for(var r=c,n=e.length,a=(t=0,null);t<n;)if(r===c){if(h(e[t])){t++;continue}if("<"!==e[t])throw new Error('Unexpected character "'+e[t]+'" at offset '+t);if(null!=a&&(null!=a.rel?this.refs.push(...Link.expandRelations(a)):this.refs.push(a)),-1===(m=e.indexOf(">",t)))throw new Error("Expected end of URI delimiter at offset "+t);a={uri:e.slice(t+1,m)},t=m,r=u,t++}else if(r===u){if(h(e[t])){t++;continue}if(";"===e[t])r=l,t++;else{if(","!==e[t])throw new Error('Unexpected character "'+e[t]+'" at offset '+t);r=c,t++}}else{if(r!==l)throw new Error('Unknown parser state "'+r+'"');if(";"===e[t]||h(e[t])){t++;continue}-1===(m=e.indexOf("=",t))&&(m=e.indexOf(";",t)),-1===m&&(m=e.length);var s=d(e.slice(t,m)).toLowerCase(),p="";if('"'===e[t=f(e,t=m+1)])for(t++;t<n;){if('"'===e[t]){t++;break}"\\"===e[t]&&t++,p+=e[t],t++}else{for(var m=t+1;!o.test(e[m])&&m<n;)m++;p=e.slice(t,m),t=m}switch(a[s]&&Link.isSingleOccurenceAttr(s)||("*"===s[s.length-1]?a[s]=Link.parseExtendedValue(p):(p="type"===s?p.toLowerCase():p,null!=a[s]?Array.isArray(a[s])?a[s].push(p):a[s]=[a[s],p]:a[s]=p)),e[t]){case",":r=c;break;case";":r=l}t++}return null!=a&&(null!=a.rel?this.refs.push(...Link.expandRelations(a)):this.refs.push(a)),a=null,this}toString(){for(var e=[],t="",r=null,n=0;n<this.refs.length;n++)r=this.refs[n],t=Object.keys(this.refs[n]).reduce(function(e,t){return"uri"===t?e:e+"; "+Link.formatAttribute(t,r[t])},"<"+r.uri+">"),e.push(t);return e.join(", ")}}Link.isCompatibleEncoding=function(e){return t.test(e)},Link.parse=function(e,t){return(new Link).parse(e,t)},Link.isSingleOccurenceAttr=function(e){return"rel"===e||"type"===e||"media"===e||"title"===e||"title*"===e},Link.isTokenAttr=function(e){return"rel"===e||"type"===e||"anchor"===e},Link.escapeQuotes=function(e){return e.replace(/"/g,'\\"')},Link.expandRelations=function(e){return e.rel.split(" ").map(function(t){var r=Object.assign({},e);return r.rel=t,r})},Link.parseExtendedValue=function(e){var t=/([^']+)?(?:'([^']*)')?(.+)/.exec(e);return{language:t[2].toLowerCase(),encoding:Link.isCompatibleEncoding(t[1])?null:t[1].toLowerCase(),value:Link.isCompatibleEncoding(t[1])?decodeURIComponent(t[3]):t[3]}},Link.formatExtendedAttribute=function(e,t){var r=(t.encoding||"utf-8").toUpperCase();return e+"="+r+"'"+(t.language||"en")+"'"+("undefined"!=typeof Buffer&&Buffer.isBuffer(t.value)&&Link.isCompatibleEncoding(r)?t.value.toString(r):"undefined"!=typeof Buffer&&Buffer.isBuffer(t.value)?t.value.toString("hex").replace(/[0-9a-f]{2}/gi,"%$1"):encodeURIComponent(t.value))},Link.formatAttribute=function(e,t){return Array.isArray(t)?t.map(t=>Link.formatAttribute(e,t)).join("; "):"*"===e[e.length-1]||"string"!=typeof t?Link.formatExtendedAttribute(e,t):(Link.isTokenAttr(e)?t=p(t)?'"'+Link.escapeQuotes(t)+'"':Link.escapeQuotes(t):p(t)&&(t='"'+(t=(t=encodeURIComponent(t)).replace(/%20/g," ").replace(/%2C/g,",").replace(/%3B/g,";"))+'"'),e+"="+t)},e.exports=Link}),n=()=>i(147),a=i.cw(e=>{const{pipeline:t}=d(),r=c(),{destroyer:n}=s(),{isNodeStream:i,isReadable:o,isWritable:a,isWebStream:l,isTransformStream:f,isWritableStream:p,isReadableStream:y}=h(),{AbortError:g,codes:{ERR_INVALID_ARG_VALUE:_,ERR_MISSING_ARGS:b}}=m(),w=u();e.exports=function(...e){if(0===e.length)throw new b("streams");if(1===e.length)return r.from(e[0]);const s=[...e];if("function"==typeof e[0]&&(e[0]=r.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=r.from(e[t])}for(let t=0;t<e.length;++t)if(i(e[t])||l(e[t])){if(t<e.length-1&&!(o(e[t])||y(e[t])||f(e[t])))throw new _(`streams[${t}]`,s[t],"must be readable");if(t>0&&!(a(e[t])||p(e[t])||f(e[t])))throw new _(`streams[${t}]`,s[t],"must be writable")}let c,u,d,h,m;const v=e[0],S=t(e,function(e){const t=h;h=null,t?t(e):e?m.destroy(e):I||x||m.destroy()}),x=!!(a(v)||p(v)||f(v)),I=!!(o(S)||y(S)||f(S));if(m=new r({writableObjectMode:!(null==v||!v.writableObjectMode),readableObjectMode:!(null==S||!S.readableObjectMode),writable:x,readable:I}),x){if(i(v))m._write=function(e,t,r){v.write(e,t)?r():c=r},m._final=function(e){v.end(),u=e},v.on("drain",function(){if(c){const e=c;c=null,e()}});else if(l(v)){const e=(f(v)?v.writable:v).getWriter();m._write=async function(t,r,n){try{await e.ready,e.write(t).catch(()=>{}),n()}catch(e){n(e)}},m._final=async function(t){try{await e.ready,e.close().catch(()=>{}),u=t}catch(e){t(e)}}}const e=f(S)?S.readable:S;w(e,()=>{if(u){const e=u;u=null,e()}})}if(I)if(i(S))S.on("readable",function(){if(d){const e=d;d=null,e()}}),S.on("end",function(){m.push(null)}),m._read=function(){for(;;){const e=S.read();if(null===e)return void(d=m._read);if(!m.push(e))return}};else if(l(S)){const e=(f(S)?S.readable:S).getReader();m._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!m.push(t))return;if(r)return void m.push(null)}catch{return}}}return m._destroy=function(e,t){e||null===h||(e=new g),d=null,c=null,u=null,null===h?t(e):(h=t,i(S)&&n(S,e))},m}}),s=()=>i(896),c=()=>i(370),u=()=>i(238),l=i.cw(e=>{const t=globalThis.AbortController||i(568).AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:s,ERR_OUT_OF_RANGE:c},AbortError:l}=m(),{validateAbortSignal:d,validateInteger:p,validateObject:_}=f(),b=y().Symbol("kWeak"),w=y().Symbol("kResistStopPropagation"),{finished:v}=u(),S=a(),{addAbortSignalNoValidate:x}=n(),{isWritable:I,isNodeStream:A}=h(),{deprecate:T}=g(),{ArrayPrototypePush:E,Boolean:R,MathFloor:k,Number:j,NumberIsNaN:N,Promise:C,PromiseReject:P,PromiseResolve:O,PromisePrototypeThen:F,Symbol:q}=y(),M=q("kEmpty"),$=q("kEof");function D(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);null!=t&&_(t,"options"),null!=(null==t?void 0:t.signal)&&d(t.signal,"options.signal");let r=1;null!=(null==t?void 0:t.concurrency)&&(r=k(t.concurrency));let n=r-1;return null!=(null==t?void 0:t.highWaterMark)&&(n=k(t.highWaterMark)),p(r,"options.concurrency",1),p(n,"options.highWaterMark",0),n+=r,async function*(){const i=g().AbortSignalAny([null==t?void 0:t.signal].filter(R)),o=this,a=[],s={signal:i};let c,u,d=!1,h=0;function f(){d=!0,p()}function p(){h-=1,m()}function m(){u&&!d&&h<r&&a.length<n&&(u(),u=null)}!async function(){try{for await(let t of o){if(d)return;if(i.aborted)throw new l;try{if(t=e(t,s),t===M)continue;t=O(t)}catch(e){t=P(e)}h+=1,F(t,p,f),a.push(t),c&&(c(),c=null),!d&&(a.length>=n||h>=r)&&await new C(e=>{u=e})}a.push($)}catch(e){const t=P(e);F(t,p,f),a.push(t)}finally{d=!0,c&&(c(),c=null)}}();try{for(;;){for(;a.length>0;){const e=await a[0];if(e===$)return;if(i.aborted)throw new l;e!==M&&(yield e),a.shift(),m()}await new C(e=>{c=e})}}finally{d=!0,u&&(u(),u=null)}}.call(this)}async function L(e,t=void 0){for await(const r of U.call(this,e,t))return!0;return!1}function U(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return D.call(this,async function(t,r){return await e(t,r)?t:M},t)}class ReduceAwareErrMissingArgs extends s{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function z(e){if(e=j(e),N(e))return 0;if(e<0)throw new c("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:T(function(e=void 0){return null!=e&&_(e,"options"),null!=(null==e?void 0:e.signal)&&d(e.signal,"options.signal"),async function*(){let t=0;for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new l({cause:e.signal.reason});yield[t++,n]}}.call(this)},"readable.asIndexedPairs will be removed in a future version."),drop:function(e,t=void 0){return null!=t&&_(t,"options"),null!=(null==t?void 0:t.signal)&&d(t.signal,"options.signal"),e=z(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new l;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new l;e--<=0&&(yield r)}}.call(this)},filter:U,flatMap:function(e,t){const r=D.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:D,take:function(e,t=void 0){return null!=t&&_(t,"options"),null!=(null==t?void 0:t.signal)&&d(t.signal,"options.signal"),e=z(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new l;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new l;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&_(t,"options"),null!=(null==t?void 0:t.signal)&&d(t.signal,"options.signal"),A(e)&&!I(e))throw new r("stream",e,"must be writable");const n=S(this,e);return null!=t&&t.signal&&x(t.signal,n),n}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return!await L.call(this,async(...t)=>!await e(...t),t)},forEach:async function(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);for await(const r of D.call(this,async function(t,r){return await e(t,r),M},t));},reduce:async function(e,r,n){var i;if("function"!=typeof e)throw new o("reducer",["Function","AsyncFunction"],e);null!=n&&_(n,"options"),null!=(null==n?void 0:n.signal)&&d(n.signal,"options.signal");let a=arguments.length>1;if(null!=n&&null!==(i=n.signal)&&void 0!==i&&i.aborted){const e=new l(void 0,{cause:n.signal.reason});throw this.once("error",()=>{}),await v(this.destroy(e)),e}const s=new t,c=s.signal;if(null!=n&&n.signal){const e={once:!0,[b]:this,[w]:!0};n.signal.addEventListener("abort",()=>s.abort(),e)}let u=!1;try{for await(const t of this){var h;if(u=!0,null!=n&&null!==(h=n.signal)&&void 0!==h&&h.aborted)throw new l;a?r=await e(r,t,{signal:c}):(r=t,a=!0)}if(!u&&!a)throw new ReduceAwareErrMissingArgs}finally{s.abort()}return r},toArray:async function(e){null!=e&&_(e,"options"),null!=(null==e?void 0:e.signal)&&d(e.signal,"options.signal");const t=[];for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new l(void 0,{cause:e.signal.reason});E(t,n)}return t},some:L,find:async function(e,t){for await(const r of U.call(this,e,t))return r}}}),d=()=>i(758),h=()=>i(115),f=()=>i(277),p=i.cw(e=>{const t=_(),r=b(),n=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=n,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get:()=>r}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),m=()=>i(371),y=()=>i(134),g=()=>i(760),_=i.cw(e=>{const{Buffer:r}=t(),{ObjectDefineProperty:o,ObjectKeys:f,ReflectApply:p}=y(),{promisify:{custom:_}}=g(),{streamReturningOperators:w,promiseReturningOperators:v}=l(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:S}}=m(),x=a(),{setDefaultHighWaterMark:I,getDefaultHighWaterMark:A}=i(291),{pipeline:T}=d(),{destroyer:E}=s(),R=u(),k=b(),j=h(),N=e.exports=i(259).Stream;N.isDestroyed=j.isDestroyed,N.isDisturbed=j.isDisturbed,N.isErrored=j.isErrored,N.isReadable=j.isReadable,N.isWritable=j.isWritable,N.Readable=i(576);for(const P of f(w)){const O=w[P];function F(...e){if(new.target)throw S();return N.Readable.from(p(O,this,e))}o(F,"name",{__proto__:null,value:O.name}),o(F,"length",{__proto__:null,value:O.length}),o(N.Readable.prototype,P,{__proto__:null,value:F,enumerable:!1,configurable:!0,writable:!0})}for(const q of f(v)){const M=v[q];function $(...e){if(new.target)throw S();return p(M,this,e)}o($,"name",{__proto__:null,value:M.name}),o($,"length",{__proto__:null,value:M.length}),o(N.Readable.prototype,q,{__proto__:null,value:$,enumerable:!1,configurable:!0,writable:!0})}N.Writable=i(584),N.Duplex=c(),N.Transform=i(382),N.PassThrough=i(524),N.pipeline=T;const{addAbortSignal:C}=n();N.addAbortSignal=C,N.finished=R,N.destroy=E,N.compose=x,N.setDefaultHighWaterMark=I,N.getDefaultHighWaterMark=A,o(N,"promises",{__proto__:null,configurable:!0,enumerable:!0,get:()=>k}),o(T,_,{__proto__:null,enumerable:!0,get:()=>k.pipeline}),o(R,_,{__proto__:null,enumerable:!0,get:()=>k.finished}),N.Stream=N,N._isUint8Array=function(e){return e instanceof Uint8Array},N._uint8ArrayToBuffer=function(e){return r.from(e.buffer,e.byteOffset,e.byteLength)}}),b=i.cw(e=>{const{ArrayPrototypePop:t,Promise:r}=y(),{isIterable:n,isNodeStream:i,isWebStream:o}=h(),{pipelineImpl:a}=d(),{finished:s}=u();_(),e.exports={finished:s,pipeline:function(...e){return new r((r,s)=>{let c,u;const l=e[e.length-1];if(l&&"object"==typeof l&&!i(l)&&!n(l)&&!o(l)){const r=t(e);c=r.signal,u=r.end}a(e,(e,t)=>{e?s(e):r(t)},{signal:c,end:u})})}}}),w={};i.r(w),i.d(w,{EventSource:()=>ac,EventStream:()=>oc,RetentionPolicy:()=>sc,Vocabulary:()=>cc,_BASE:()=>uc,_PREFIX:()=>lc,amount:()=>Ys,pointInTime:()=>Zs,retentionPolicy:()=>Xs,timestampPath:()=>rc,versionKey:()=>ec,versionMaterializationOf:()=>nc,versionMaterializationUntil:()=>ic,versionOfPath:()=>tc});var v={};i.r(v),i.d(v,{Ascending:()=>$c,BasicContainer:()=>Rc,Container:()=>Ec,Descending:()=>Dc,DirectContainer:()=>kc,IndirectContainer:()=>jc,MemberSubject:()=>Pc,NonRDFSource:()=>Tc,Page:()=>Nc,PageSortCriterion:()=>Cc,PreferContainment:()=>Oc,PreferEmptyContainer:()=>qc,PreferMembership:()=>Fc,PreferMinimalContainer:()=>Mc,RDFSource:()=>Ac,Resource:()=>Ic,_BASE:()=>Lc,_PREFIX:()=>Uc,constrainedBy:()=>gc,contains:()=>yc,hasMemberRelation:()=>dc,inbox:()=>xc,insertedContentRelation:()=>pc,isMemberOfRelation:()=>hc,member:()=>mc,membershipResource:()=>fc,pageSequence:()=>Sc,pageSortCollation:()=>vc,pageSortCriteria:()=>_c,pageSortOrder:()=>wc,pageSortPredicate:()=>bc});var S={};i.r(S),i.d(S,{Collection:()=>ou,ConditionalImport:()=>lu,EqualToRelation:()=>_u,GeospatiallyContainsRelation:()=>wu,GreaterThanOrEqualToRelation:()=>mu,GreaterThanRelation:()=>pu,InBetweenRelation:()=>vu,LessThanOrEqualToRelation:()=>gu,LessThanRelation:()=>yu,Node:()=>su,NotEqualToRelation:()=>bu,Ontology:()=>Su,PrefixRelation:()=>du,Relation:()=>uu,RootNode:()=>cu,SearchTree:()=>au,SubstringRelation:()=>hu,SuffixRelation:()=>fu,_BASE:()=>xu,_PREFIX:()=>Iu,conditionalImport:()=>eu,import__workaround:()=>Zc,latitudeTile:()=>nu,longitudeTile:()=>ru,member:()=>Vc,node:()=>Hc,path:()=>Jc,relation:()=>Bc,remainingItems:()=>Qc,rootNode:()=>Kc,search:()=>Xc,shape:()=>Yc,timeQuery:()=>iu,value:()=>Wc,view:()=>Gc,viewDescription:()=>zc,zoom:()=>tu});var x={};i.r(x),i.d(x,{Accept:()=>Du,Activity:()=>Tu,Add:()=>Bu,Announce:()=>Qu,Application:()=>Hu,Arrive:()=>Ku,Article:()=>Wu,Audio:()=>Ju,Block:()=>Lu,Collection:()=>ku,CollectionPage:()=>ju,Create:()=>Xu,Delete:()=>Yu,Dislike:()=>Zu,Document:()=>Gu,Event:()=>el,Flag:()=>tl,Follow:()=>rl,Group:()=>nl,Ignore:()=>Uu,Image:()=>Nu,IntransitiveActivity:()=>zu,Invite:()=>il,Join:()=>al,Leave:()=>sl,Like:()=>cl,Link:()=>Ru,Listen:()=>ll,Mention:()=>pl,Move:()=>hl,Note:()=>ml,Object__workaround:()=>Eu,Offer:()=>ol,OrderedCollection:()=>Vu,OrderedCollectionPage:()=>$u,OrderedItems:()=>Cu,Organization:()=>_l,Page:()=>yl,Person:()=>gl,Place:()=>Mu,Profile:()=>Fu,Question:()=>Ou,Read:()=>dl,Reject:()=>bl,Relationship:()=>Pu,Remove:()=>wl,Service:()=>vl,TentativeAccept:()=>Sl,TentativeReject:()=>xl,Tombstone:()=>qu,Travel:()=>fl,Undo:()=>Il,Update:()=>Al,Video:()=>Tl,View:()=>ul,_BASE:()=>Ud,_PREFIX:()=>zd,accuracy:()=>hd,actor:()=>El,altitude:()=>fd,anyOf:()=>Jl,attachment:()=>kl,attachments:()=>jl,attributedTo:()=>Rl,audience:()=>ed,author:()=>Nl,bcc:()=>Cl,bto:()=>Pl,cc:()=>Ol,content:()=>pd,context:()=>Fl,current:()=>ql,deleted:()=>Ld,describes:()=>ld,downstreamDuplicates:()=>yd,duration:()=>gd,endTime:()=>_d,first:()=>Ml,formerType:()=>dd,generator:()=>$l,height:()=>bd,href:()=>wd,hreflang:()=>vd,icon:()=>Dl,id:()=>Sd,image:()=>Ll,inReplyTo:()=>Ul,instrument:()=>ad,items:()=>zl,last:()=>Bl,latitude:()=>xd,location:()=>Ql,longitude:()=>Id,mediaType:()=>Ad,name:()=>md,next:()=>Hl,object:()=>Kl,objectType:()=>Td,oneOf:()=>Wl,origin:()=>od,partOf:()=>td,prev:()=>Gl,preview:()=>Vl,provider:()=>Xl,published:()=>Ed,radius:()=>Rd,rating:()=>kd,rel:()=>jd,relationship:()=>Au,replies:()=>Yl,result:()=>Zl,startIndex:()=>Nd,startTime:()=>Cd,subject:()=>ud,summary:()=>Pd,tag:()=>rd,tags:()=>nd,target:()=>id,to:()=>sd,totalItems:()=>Od,units:()=>Fd,updated:()=>qd,upstreamDuplicates:()=>Md,url:()=>cd,verb:()=>$d,width:()=>Dd});var I=i(981);function A(e,t,r,n){var i,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,n);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(a=(o<3?i(a):o>3?i(t,r,a):i(t,r))||a);return o>3&&a&&Object.defineProperty(t,r,a),a}function T(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function E(e,t,r,n){return new(r||(r=Promise))(function(i,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,s)}c((n=n.apply(e,t||[])).next())})}Object.create;Object.create;var R=i(955);class InruptClientError extends Error{}const k=new URL("about:blank");function j(e,t){if(void 0!==e)try{return new URL(e,t)}catch{}}class ClientHttpError extends InruptClientError{constructor(e,t,r,n){if(super(r,n),e.status>=200&&e.status<400)throw new InruptClientError(`A ClientHttpError cannot be built from a success response, got ${e.status} ${e.statusText}`);this.errorResponse=Object.freeze({status:e.status,statusText:e.statusText,headers:e.headers,url:e.url,body:t,ok:!1}),this.details=function(e){let t,r,n,i,o;if("application/problem+json"===e.headers.get("Content-Type"))try{const a=JSON.parse(e.body),s=j(a.type,e.url);void 0!==s&&(t=s),"string"==typeof a.title&&(r=a.title),"number"==typeof a.status&&(n=a.status),"string"==typeof a.detail&&(i=a.detail);const c=j(a.instance,e.url);void 0!==c&&(o=c)}catch{}return Object.freeze({type:t??k,title:r??e.statusText,status:n??e.status,detail:i,instance:o})}(this.errorResponse)}get response(){return this.errorResponse}get problemDetails(){return this.details}}function N(e){return"object"==typeof e&&"object"==typeof e.internal_resourceInfo}function C(e){const t=e;return"object"==typeof t&&"object"==typeof t.internal_resourceInfo&&"object"==typeof t.internal_resourceInfo.linkedResources}function P(e){const t=e;return"object"==typeof t.internal_changeLog&&Array.isArray(t.internal_changeLog.additions)&&Array.isArray(t.internal_changeLog.deletions)}class SolidClientError extends Error{}function O(e){return"string"==typeof e?e:e.value}function F(e,t={}){const r=new URL(e);return r.pathname=r.pathname.replace(/\/\/+/g,"/"),!1===t.trailingSlash&&"/"===r.pathname.slice(-1)&&(r.pathname=r.pathname.slice(0,r.pathname.length-1)),!0===t.trailingSlash&&"/"!==r.pathname.slice(-1)&&(r.pathname=`${r.pathname}/`),r.href}function q(e){var t,n,i,o,a;const s=null!==(n=null===(t=e.headers.get("Content-Type"))||void 0===t?void 0:t.split(";"))&&void 0!==n?n:[],c=s.length>0&&["text/turtle","application/ld+json"].includes(s[0]),u={sourceIri:e.url,isRawData:!c,contentLocation:null!==(i=e.headers.get("Content-Location"))&&void 0!==i?i:void 0,contentType:null!==(o=e.headers.get("Content-Type"))&&void 0!==o?o:void 0,linkedResources:{},location:null!==(a=e.headers.get("Location"))&&void 0!==a?a:void 0},l=e.headers.get("Link");if(l){const e=r().parse(l),t=e.get("rel","acl");1===t.length&&(u.aclUrl=new URL(t[0].uri,u.sourceIri).href),u.linkedResources=e.refs.reduce((e,t)=>{var r,n;return null!==(r=e[n=t.rel])&&void 0!==r||(e[n]=[]),e[t.rel].push(new URL(t.uri,u.sourceIri).href),e},u.linkedResources)}const d=e.headers.get("WAC-Allow");return d&&(u.permissions=function(e){function t(e){const t=e.split(" ");return t.includes("write")?{read:t.includes("read"),append:!0,write:!0,control:t.includes("control")}:{read:t.includes("read"),append:t.includes("append"),write:!1,control:t.includes("control")}}function r(e,t){const r=e.split(",").map(e=>e.split("=")).filter(e=>2===e.length&&e[0].trim()===t);if(1!==r.length)return"";const n=r[0][1].trim();return'"'!==n.charAt(0)||'"'!==n.charAt(n.length-1)?"":n.substring(1,n.length-1)}return{user:t(r(e,"user")),public:t(r(e,"public"))}}(d)),u}function M(e){return!e.ok}async function $(e,t){var r,n;return D(await(null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch)(F(e),{method:"HEAD"}),{ignoreAuthenticationErrors:null!==(n=null==t?void 0:t.ignoreAuthenticationErrors)&&void 0!==n&&n})}function D(e,t={ignoreAuthenticationErrors:!1}){if(M(e)&&(!function(e){return 401===e.status||403===e.status}(e)||!t.ignoreAuthenticationErrors))throw new FetchError(`Fetching the metadata of the Resource at [${e.url}] failed: [${e.status}] [${e.statusText}].`,e);return{internal_resourceInfo:q(e)}}function L(e){return(N(e)?U(e):O(e)).endsWith("/")}function U(e){return N(e)?e.internal_resourceInfo.sourceIri:null}r();const z=U;function B(e){return e.internal_resourceInfo.linkedResources}class FetchError extends SolidClientError{constructor(e,t,r){super(e),this.response=t,this.httpError=new ClientHttpError(t,"string"==typeof r?r:"",e)}get statusCode(){return this.response.status}get statusText(){return this.response.statusText}get problemDetails(){return this.httpError.problemDetails}}t(),p();const Q="http://www.w3.org/1999/02/22-rdf-syntax-ns#",H="http://www.w3.org/2001/XMLSchema#",K="http://www.w3.org/2000/10/swap/",W={xsd:{decimal:`${H}decimal`,boolean:`${H}boolean`,dateTime:`${H}dateTime`,double:`${H}double`,integer:`${H}integer`,string:`${H}string`},rdf:{type:`${Q}type`,nil:`${Q}nil`,first:`${Q}first`,rest:`${Q}rest`,langString:`${Q}langString`,dirLangString:`${Q}dirLangString`,reifies:`${Q}reifies`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${K}reify#forSome`,forAll:`${K}reify#forAll`},log:{implies:`${K}log#implies`,isImpliedBy:`${K}log#isImpliedBy`}},{rdf:J,xsd:G}=W;let V,X=0;const Y="<>",Z={namedNode:ne,blankNode:ie,variable:ae,literal:oe,defaultGraph:function(){return V},quad:se,triple:se,fromTerm:ce,fromQuad:ue},ee=Z;class Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof Term?this.id===e.id&&this.termType===e.termType:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class NamedNode extends Term{constructor(e){""!==e?super(e):(super(Y),Object.defineProperty(this,"value",{value:""}))}get termType(){return"NamedNode"}}class Literal extends Term{constructor(e){super(e)}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;const r=e.lastIndexOf("--");return t<e.length&&"@"===e[t++]?(r>t?e.substr(0,r):e).substr(t).toLowerCase():""}get direction(){const e=this.id,t=e.lastIndexOf('"'),r="@"===e[t+1]?e.lastIndexOf("--"):-1;return r>t&&r+2<e.length?e.substr(r+2).toLowerCase():""}get datatype(){return new NamedNode(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?G.string:e.indexOf("--",t)>0?J.dirLangString:J.langString}equals(e){return e instanceof Literal?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&(this.direction===e.direction||""===this.direction&&!e.direction)&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,direction:this.direction,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class BlankNode extends Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Variable extends Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}function te(e,t,r){if(t=t||Z,!e)return t.defaultGraph();switch(e[0]){case"?":return t.variable(e.substr(1));case"_":return t.blankNode(e.substr(2));case'"':if(t===Z)return new Literal(e);if('"'===e[e.length-1])return t.literal(e.substr(1,e.length-2));const n=e.lastIndexOf('"',e.length-1);let i;if("@"===e[n+1]){i=e.substr(n+2);const t=i.lastIndexOf("--");t>0&&t<i.length&&(i={language:i.substr(0,t),direction:i.substr(t+2)})}else i=t.namedNode(e.substr(n+3));return t.literal(e.substr(1,n-1),i);case"[":e=JSON.parse(e);break;case"<":if(e===Y)return t.namedNode("");default:if(!r||!Array.isArray(e))return t.namedNode(e)}return t.quad(te(e[0],t,!0),te(e[1],t,!0),te(e[2],t,!0),e[3]&&te(e[3],t,!0))}function re(e,t){if("string"==typeof e)return e;if(e instanceof Term&&"Quad"!==e.termType)return e.id;if(!e)return V.id;switch(e.termType){case"NamedNode":{const t=e.value;return""!==t?t:Y}case"BlankNode":return`_:${e.value}`;case"Variable":return`?${e.value}`;case"DefaultGraph":return"";case"Literal":return`"${e.value}"${e.language?`@${e.language}${e.direction?`--${e.direction}`:""}`:e.datatype&&e.datatype.value!==G.string?`^^${e.datatype.value}`:""}`;case"Quad":const r=[re(e.subject,!0),re(e.predicate,!0),re(e.object,!0)];return e.graph&&"DefaultGraph"!==e.graph.termType&&r.push(re(e.graph,!0)),t?r:JSON.stringify(r);default:throw new Error(`Unexpected termType: ${e.termType}`)}}V=new class DefaultGraph extends Term{constructor(){return super(""),V||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};class Quad extends Term{constructor(e,t,r,n){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=n||V}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 ne(e){return new NamedNode(e)}function ie(e){return new BlankNode(e||"n3-"+X++)}function oe(e,t){if("string"==typeof t)return new Literal(`"${e}"@${t.toLowerCase()}`);if(void 0!==t&&!("termType"in t))return new Literal(`"${e}"@${t.language.toLowerCase()}${t.direction?`--${t.direction.toLowerCase()}`:""}`);let r=t?t.value:"";return""===r&&("boolean"==typeof e?r=G.boolean:"number"==typeof e?Number.isFinite(e)?r=Number.isInteger(e)&&Math.abs(e)<1e21?G.integer:G.double:(r=G.double,Number.isNaN(e)||(e=e>0?"INF":"-INF")):"bigint"==typeof e?r=G.integer:e instanceof Date&&!Number.isNaN(e.getTime())&&(r=G.dateTime,e=e.toISOString())),""===r||r===G.string?new Literal(`"${e}"`):new Literal(`"${e}"^^${r}`)}function ae(e){return new Variable(e)}function se(e,t,r,n){return new Quad(e,t,r,n)}function ce(e){if(e instanceof Term)return e;switch(e.termType){case"NamedNode":return ne(e.value);case"BlankNode":return ie(e.value);case"Variable":return ae(e.value);case"DefaultGraph":return V;case"Literal":return oe(e.value,e.language?e.direction?{language:e.language,direction:e.direction}:e.language:e.datatype);case"Quad":return ue(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function ue(e){if(e instanceof Quad)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return se(ce(e.subject),ce(e.predicate),ce(e.object),ce(e.graph))}function le(e){return!!e&&"DefaultGraph"===e.termType}function de(e){return e.replace(/[.*+?^${}()|[\]\\/-]/g,"\\$&")}const he=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,fe=/^(?:(?!\.\.?(?:[/?#]|$))[^/?#]+(?:\/[^/?#]{3,})*\/?)?(?:[?#]|$)/;class BaseIRI{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!he.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!BaseIRI.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",de(e)],r=[],n=[],i=/[^/?#]*([/?#])/y;let o,a=0,s=0,c=i.lastIndex=e.length;for(;!a&&!s&&(o=i.exec(this.base));)"#"===o[1]?s=i.lastIndex-1:(t.push(de(o[0]),"(?:"),r.push(")?"),"?"!==o[1]?n.push(c=i.lastIndex):(a=c=i.lastIndex,s=this.base.indexOf("#",a),this._pathReplacements[a]="?"));for(let e=0;e<n.length;e++)this._pathReplacements[n[e]]="../".repeat(n.length-e-1);return this._pathReplacements[n[n.length-1]]="./",this._baseLength=s>0?s:this.base.length,t.push(de(this.base.substring(c,this._baseLength)),a?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...r].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const r=t[0].length;if(r===this._baseLength&&r===e.length)return"";const n=this._pathReplacements[r];if(n){const t=e.substring(r);return"?"===n||fe.test(t)?"./"===n&&/^[^?#]/.test(t)&&(t.indexOf(":")<0||!/^[^/?#]*:/.test(t))?t:n+t:e}return e.substring(r-1)}}const pe=ee.defaultGraph(),{rdf:me,xsd:ye}=W,{hasOwnProperty:ge}=Object.prototype,_e=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,be=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,we=/[^ !#-\[\]-~\u0080-\uFFFD]/,ve=/[^ !#-\[\]-~\u0080-\uFFFD]/g,Se={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"},xe=/["\\\u0000-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(?:^|[^\ud800-\udbff])[\udc00-\udfff]/,Ie="A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD_:0-9",Ae=`${Ie}\\-\\u00B7\\u0300-\\u036F\\u203F\\u2040`,Te="%[0-9A-Fa-f]{2}",Ee=new RegExp(`^(?:(?:[${Ie}]|${Te})(?:(?:[${Ae}.]|${Te})*(?:[${Ae}]|${Te}))?)?$`);class SerializedTerm extends Term{equals(e){return e===this}}class N3Writer{constructor(e,t){if(this._prefixRegex=/$0^/,this._hasPrefixes=!1,e&&"function"!=typeof e.write&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=void 0===t.end||!!t.end;else{let e="";this._outputStream={write(t,r,n){e+=t,n&&n()},end:t=>{t&&t(null,e)}},this._endStream=!0}if(t.version&&xe.test(t.version))throw new Error(`Invalid version label: ${JSON.stringify(t.version)}`);this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine,this._escape=we,this._escapeAll=ve,this._characterReplacer=ke,t.version&&this._write(`VERSION "${t.version}"\n`)):(this._lineMode=!1,this._escape=_e,this._escapeAll=be,this._characterReplacer=Re,this._graph=pe,t.version&&this._write(`@version "${t.version}".\n`),this._prefixIRIs=Object.create(null),this._prefixPatterns=Object.create(null),t.baseIRI&&(this._baseIri=new BaseIRI(t.baseIRI),t.writeBase&&this._write(`@base <${t.baseIRI}>.\n`)),t.prefixes&&this.addPrefixes(t.prefixes))}get _inDefaultGraph(){return pe.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_endStatement(){null!==this._subject&&(this._write(this._inDefaultGraph?".\n":"\n}\n"),this._subject=null,this._graph=pe)}_writeQuad(e,t,r,n,i){try{n===this._graph||n.equals(this._graph)&&n.termType===this._graph.termType||(this._write((null===this._subject?"":this._inDefaultGraph?".\n":"\n}\n")+(pe.equals(n)?"":`${this._encodeIriOrBlank(n)} {\n`)),this._graph=n,this._subject=null),e===this._subject||e.equals(this._subject)?t===this._predicate||t.equals(this._predicate)?this._write(`, ${this._encodeObject(r)}`,i):this._write(`;\n ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i):this._write(`${(null===this._subject?"":".\n")+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i)}catch(e){i&&i(e)}}_writeQuadLine(e,t,r,n,i){delete this._prefixMatch,this._write(this.quadToString(e,t,r,n),i)}quadToString(e,t,r,n){return`${this._encodeSubject(e)} ${"Literal"===t.termType?this._encodeLiteral(t):this._encodeIriOrBlank(t)} ${this._encodeObject(r)}${n&&!le(n)?` ${this._encodeIriOrBlank(n)} .\n`:" .\n"}`}quadsToString(e){let t="";for(const r of e)t+=this.quadToString(r.subject,r.predicate,r.object,r.graph);return t}_encodeSubject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeIriOrBlank(e){if("NamedNode"!==e.termType)return this._lists&&ge.call(this._lists,e.value)&&(e=this.list(this._lists[e.value])),e instanceof Term?e.id:"Variable"===e.termType?`?${e.value}`:`_:${e.value}`;let t=e.value;this._baseIri&&(t=this._baseIri.toRelative(t)),this._escape.test(t)&&(t=t.replace(this._escapeAll,this._characterReplacer));const r=this._hasPrefixes?(this._prefixRegex||this._createPrefixRegex()).exec(t):null;return r?r[1]?this._prefixIRIs[r[1]]+r[2]:Ee.test(t.slice(r[0].length))?t:`<${t}>`:`<${t}>`}_encodeLiteral(e){let t=e.value;this._escape.test(t)&&(t=t.replace(this._escapeAll,this._characterReplacer));const r=e.language;if(r){const n=e.direction;return`"${t}"@${r}${n?`--${n}`:""}`}if(this._lineMode){if(e.datatype.value===ye.string)return`"${t}"`}else switch(e.datatype.value){case ye.string:return`"${t}"`;case ye.boolean:if("true"===t||"false"===t)return t;break;case ye.integer:if(/^[+-]?\d+$/.test(t))return t;break;case ye.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case ye.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){switch(e.termType){case"NamedNode":return e.value===me.type?"a":this._encodeIriOrBlank(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:r,graph:n}){const i=this._lineMode?" ":"";return`<<(${i}${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(r)}${le(n)?"":` ${this._encodeIriOrBlank(n)}`}${i})>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,r,n,i){void 0===r?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):"function"==typeof n?this._writeQuad(e,t,r,pe,n):this._writeQuad(e,t,r,n||pe,i)}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}addPrefix(e,t,r){const n={};n[e]=t,this.addPrefixes(n,r)}addPrefixes(e,t){if(!this._prefixIRIs)return t&&t();let r=!1;for(let t in e){let n=e[t];"string"!=typeof n&&(n=n.value),r=!0,this._endStatement(),this._prefixIRIs[n]=t+=":",this._prefixPatterns[n]=[de(n),de(t)],this._write(`@prefix ${t} <${n}>.\n`)}r&&(this._hasPrefixes=!0,this._prefixRegex=null),this._write(r?"\n":"",t)}_createPrefixRegex(){let e="",t="";for(const r in this._prefixPatterns){const[n,i]=this._prefixPatterns[r];e+=e?`|${n}`:n,t+=t?`|${i}`:i}return this._prefixRegex=new RegExp(`^(${e})([_a-zA-Z0-9](?:\\.?[\\-_a-zA-Z0-9])*)$|^(?:${t})`)}blank(e,t){let r,n,i=e;switch(void 0===e?i=[]:e.termType?i=[{predicate:e,object:t}]:"length"in e||(i=[e]),n=i.length){case 0:return new SerializedTerm("[]");case 1:if(r=i[0],!(r.object instanceof SerializedTerm))return new SerializedTerm(`[ ${this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)} ]`);default:let t="[";for(let o=0;o<n;o++)r=i[o],r.predicate.equals(e)?t+=`, ${this._encodeObject(r.object)}`:(t+=`${(o?";\n ":"\n ")+this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)}`,e=r.predicate);return new SerializedTerm(`${t}\n]`)}}list(e){const t=e&&e.length||0,r=new Array(t);for(let n=0;n<t;n++)r[n]=this._encodeObject(e[n]);return new SerializedTerm(`(${r.join(" ")})`)}end(e){this._endStatement(),this._write=this._blockedWrite;let t=e&&((r,n)=>{t=null,e(r,n)});if(this._endStream)try{return this._outputStream.end(t)}catch(e){}t&&t()}}function Re(e){let t=Se[e];return void 0===t&&(1===e.length?(t=e.charCodeAt(0).toString(16),t="\\u0000".substr(0,6-t.length)+t):(t=(1024*(e.charCodeAt(0)-55296)+e.charCodeAt(1)+9216).toString(16),t="\\U00000000".substr(0,10-t.length)+t)),t}function ke(e){let t=Se[e];return void 0===t&&(t=e.charCodeAt(0).toString(16).toUpperCase(),t="\\u0000".substr(0,6-t.length)+t),t}const je=Symbol("iter"),Ne=Symbol("size");let Ce;function Pe({store:e,observer:t}){const r=e.deref();r&&r._removeObserver(t)}function Oe(e,t,r,n){const i=e&&e[t],o=i&&i[r];return!!o&&n in o}const Fe=/^[?_"[.<]/;function qe(e){if("string"==typeof e){const t=e.charCodeAt(0);return 60!==t&&46!==t||"<>"===e?e:`<${e}>`}const t=re(e);return t.charCodeAt(0)>=97||!e?t:"Quad"===e.termType?JSON.stringify(Me(e)):"NamedNode"===e.termType&&Fe.test(e.value)?`<${e.value}>`:t}function Me(e){const t=[$e(e.subject),$e(e.predicate),$e(e.object)];return e.graph&&!le(e.graph)&&t.push($e(e.graph)),t}function $e(e){return"Quad"===e.termType?Me(e):qe(e)}class N3EntityIndex{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||ee}_termFromId(e){if("<"===e[0])return this._factory.namedNode(e.substring(1,e.length-1));if("."===e[0]){const t=this._entities,r=e.split(".");return this._factory.quad(this._termFromId(t[r[1]]),this._termFromId(t[r[2]]),this._termFromId(t[r[3]]),r[4]&&this._termFromId(t[r[4]]))}return te(e,this._factory)}_termToNumericId(e){if("Quad"===e.termType){const t=this._termToNumericId(e.subject),r=this._termToNumericId(e.predicate),n=this._termToNumericId(e.object);let i;return t&&r&&n&&(le(e.graph)||(i=this._termToNumericId(e.graph)))&&this._ids[i?`.${t}.${r}.${n}.${i}`:`.${t}.${r}.${n}`]}return"string"==typeof e?this._stringToNumericId(e):this._ids[qe(e)]}_stringToNumericId(e){const t=this._ids[e],r=t?this._entities[t].charCodeAt(0):e.charCodeAt(0);return 60!==r&&46!==r||"<>"===e?t:this._ids[`<${e}>`]}_termToNewNumericId(e){if("string"==typeof e)return this._stringToNumericId(e)||this._addEntity(qe(e));const t=e&&"Quad"===e.termType?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${le(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:qe(e);return this._ids[t]||this._addEntity(t)}_addEntity(e){return this._ids[this._entities[++this._id]=e]=this._id}createBlankNode(e){let t,r;if(e)for(t=e=`_:${e}`,r=1;this._ids[t];)t=e+r++;else do{t="_:b"+this._blankNodeIndex++}while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}function De(e){return e instanceof N3Store?e._size:null}class N3Store{constructor(e,t){this._size=0,this._graphs=Object.create(null),this._graphCount=0,this._observers=null,t||!e||e[0]||"function"==typeof e.match||(t=e,e=null),t=t||{},this._factory=t.factory||ee,this._matchSemantics=ze(t.matchSemantics),this._entityIndex=t.entityIndex||new N3EntityIndex({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addAll(e)}get size(){return null===this._size&&(this._size=this.countQuads()),this._size}_addToIndex(e,t,r,n){let i=e[t];i||(e[t]=i={[Ne]:0},e[Ne]++);let o=i[r];o||(i[r]=o={[Ne]:0},i[Ne]++);const a=n in o;return a||(o[n]=null,o[Ne]++),!a}_removeFromIndex(e,t,r,n){const i=e[t],o=i[r];delete o[n],0===--o[Ne]&&(delete i[r],0===--i[Ne]&&(delete e[t],e[Ne]--))}*_findInIndex(e,t,r,n,i,o,a,s){const c=this._entities,u=this._termFromId(c[s]),l={subject:null,predicate:null,object:null};if(n){const s=e[t],d=s&&s[r];if(!d||!(n in d))return;return l[i]=this._termFromId(c[t]),l[o]=this._termFromId(c[r]),l[a]=this._termFromId(c[n]),void(yield this._factory.quad(l.subject,l.predicate,l.object,u))}if(t&&!(t in e))return;const d=t?null:Object.keys(e);for(let n=0,s=t||d[0];s;s=d&&d[++n]){const t=e[s];if(!t)continue;if(l[i]=this._termFromId(c[s]),r&&!(r in t))return;const n=r?null:Object.keys(t);for(let e=0,i=r||n[0];i;i=n&&n[++e]){const e=t[i];if(!e)continue;l[o]=this._termFromId(c[i]);const r=Object.keys(e);for(let e=0;e<r.length;e++)l[a]=this._termFromId(c[r[e]]),yield this._factory.quad(l.subject,l.predicate,l.object,u)}}}_loop(e,t){for(const r in e)t(r)}_loopByKey0(e,t,r){let n,i;if(n=e[t])for(i in n)r(i)}_loopByKey1(e,t,r){let n,i;for(n in e)i=e[n],i[t]&&r(n)}_loopBy2Keys(e,t,r,n){let i,o,a;if((i=e[t])&&(o=i[r]))for(a in o)n(a)}_loopByKey0Deep(e,t,r){let n,i,o,a;if(n=e[t])for(o in n)for(a in i=n[o],i)r(a)}_countInIndex(e,t,r,n){let i,o,a=0;if(t){if(!(i=e[t]))return 0;if(r)return(o=i[r])?n?n in o?1:0:o[Ne]:0;const s=Object.keys(i);for(let e=0;e<s.length;e++)a+=i[s[e]][Ne];return a}const s=Object.keys(e);for(let t=0;t<s.length;t++){i=e[s[t]];const r=Object.keys(i);for(let e=0;e<r.length;e++)a+=i[r[e]][Ne]}return a}_getGraphs(e){return"number"!=typeof(e=""===e?1:e&&(this._termToNumericId(e)||-1))?this._graphs:{[e]:this._graphs[e]}}_addObserver(e){const t=new WeakRef(e);return(Ce||(Ce=new FinalizationRegistry(Pe))).register(e,{store:new WeakRef(this),observer:t},t),(this._observers||(this._observers=new Set)).add(t),t}_removeObserver(e){Ce.unregister(e),this._observers&&(this._observers.delete(e),0===this._observers.size&&(this._observers=null))}_notifyObservers(e,t,r,n,i){for(const o of this._observers){const a=o.deref();a?a._onParentMutation(e,t,r,n,i):this._removeObserver(o)}}_uniqueEntities(e){const t=Object.create(null);return r=>{r in t||(t[r]=!0,e(this._termFromId(this._entities[r],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,r,n){return t||(n=e.graph,r=e.object,t=e.predicate,e=e.subject),n=n?this._termToNewNumericId(n):1,e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),r=this._termToNewNumericId(r),this._addQuad(e,t,r,n)}_addQuad(e,t,r,n){let i=this._graphs[n];if(i||(i=this._graphs[n]={subjects:{[Ne]:0},predicates:{[Ne]:0},objects:{[Ne]:0}},Object.freeze(i),this._graphCount++),null!==this._observers){if(Oe(i.subjects,e,t,r))return!1;this._notifyObservers(e,t,r,n,!0)}return!!this._addToIndex(i.subjects,e,t,r)&&(this._addToIndex(i.predicates,t,r,e),this._addToIndex(i.objects,r,e,t),null!==this._size&&this._size++,!0)}_addFromIndex(e,t=null){for(const r in e){const n=e[r].subjects,i=t&&t[r],o=i?i.subjects:null;for(const e in n){const t=Number(e),i=n[e],a=o&&o[e];for(const e in i){const n=Number(e),o=i[e],s=a&&a[e];for(const e in o)s&&e in s||this._addQuad(t,n,Number(e),Number(r))}}}}_addIntersectionFromIndex(e,t){for(const r in e){const n=t[r];if(n){let t=e[r].subjects,i=n.subjects;i[Ne]<t[Ne]&&([t,i]=[i,t]);for(const e in t){let n=t[e],o=i[e];if(o){o[Ne]<n[Ne]&&([n,o]=[o,n]);for(const t in n){let i=n[t],a=o[t];if(a){a[Ne]<i[Ne]&&([i,a]=[a,i]);for(const n in i)n in a&&this._addQuad(Number(e),Number(t),Number(n),Number(r))}}}}}}}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}delete(e){return this.removeQuad(e),this}has(e,t,r,n){if(e&&e.subject&&null==t&&null==r&&null==n&&({subject:e,predicate:t,object:r,graph:n}=e),e&&t&&r&&null!=n){const i=this._termToNumericId(e),o=this._termToNumericId(t),a=this._termToNumericId(r),s=""===n||le(n)?1:this._termToNumericId(n),c=s&&this._graphs[s];return!!i&&!!o&&!!a&&!!c&&Oe(c.subjects,i,o,a)}return!this.readQuads(e,t,r,n).next().done}import(e){return e.on("data",e=>{this.addQuad(e)}),e}removeQuad(e,t,r,n){return t||({subject:e,predicate:t,object:r,graph:n}=e),n=n?this._termToNumericId(n):1,!!((e=e&&this._termToNumericId(e))&&(t=t&&this._termToNumericId(t))&&(r=r&&this._termToNumericId(r)))&&this._removeQuad(e,t,r,n)}_removeQuad(e,t,r,n){const i=this._graphs,o=i[n];return!(!o||!Oe(o.subjects,e,t,r))&&(null!==this._observers&&this._notifyObservers(e,t,r,n,!1),this._removeFromIndex(o.subjects,e,t,r),this._removeFromIndex(o.predicates,t,r,e),this._removeFromIndex(o.objects,r,e,t),null!==this._size&&this._size--,0===o.subjects[Ne]&&(delete i[n],this._graphCount--),!0)}removeQuads(e){for(let t=0;t<e.length;t++)this.removeQuad(e[t])}remove(e){return e.on("data",e=>{this.removeQuad(e)}),e}removeMatches(e,t,r,n){const i=new(p().Readable)({objectMode:!0}),o=this.readQuads(e,t,r,n);return i._read=e=>{for(;--e>=0;){const{done:e,value:t}=o.next();if(e)return void i.push(null);i.push(t)}},this.remove(i)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,r,n){return[...this.readQuads(e,t,r,n)]}*readQuads(e,t,r,n){const i=this._getGraphs(n);let o,a,s,c;if(!(e&&!(a=this._termToNumericId(e))||t&&!(s=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(const e in i)(o=i[e])&&(a?c?yield*this._findInIndex(o.objects,c,a,s,"object","subject","predicate",e):yield*this._findInIndex(o.subjects,a,s,null,"subject","predicate","object",e):s?yield*this._findInIndex(o.predicates,s,c,null,"predicate","object","subject",e):c?yield*this._findInIndex(o.objects,c,null,null,"object","subject","predicate",e):yield*this._findInIndex(o.subjects,null,null,null,"subject","predicate","object",e))}match(e,t,r,n,i=null){return new DatasetCoreAndReadableStream(this,e,t,r,n,{entityIndex:this._entityIndex,matchSemantics:i&&void 0!==i.matchSemantics?i.matchSemantics:this._matchSemantics})}countQuads(e,t,r,n){const i=this._getGraphs(n);let o,a,s,c,u=0;if(e&&!(a=this._termToNumericId(e))||t&&!(s=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r)))return 0;for(const n in i)(o=i[n])&&(u+=e?r?this._countInIndex(o.objects,c,a,s):this._countInIndex(o.subjects,a,s,c):t?this._countInIndex(o.predicates,s,c,a):r?this._countInIndex(o.objects,c,a,s):this._countInIndex(o.subjects));return u}forEach(e,t,r,n,i){this.some(t=>(e(t,this),!1),t,r,n,i)}every(e,t,r,n,i){return!this.some(t=>!e(t,this),t,r,n,i)}some(e,t,r,n,i){for(const o of this.readQuads(t,r,n,i))if(e(o,this))return!0;return!1}getSubjects(e,t,r){const n=[];return this.forSubjects(e=>{n.push(e)},e,t,r),n}forSubjects(e,t,r,n){const i=this._getGraphs(n);let o,a,s;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(s=this._termToNumericId(r))))for(n in i)(o=i[n])&&(a?s?this._loopBy2Keys(o.predicates,a,s,e):this._loopByKey1(o.subjects,a,e):s?this._loopByKey0(o.objects,s,e):this._loop(o.subjects,e))}getPredicates(e,t,r){const n=[];return this.forPredicates(e=>{n.push(e)},e,t,r),n}forPredicates(e,t,r,n){const i=this._getGraphs(n);let o,a,s;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(s=this._termToNumericId(r))))for(n in i)(o=i[n])&&(a?s?this._loopBy2Keys(o.objects,s,a,e):this._loopByKey0(o.subjects,a,e):s?this._loopByKey1(o.predicates,s,e):this._loop(o.predicates,e))}getObjects(e,t,r){const n=[];return this.forObjects(e=>{n.push(e)},e,t,r),n}forObjects(e,t,r,n){const i=this._getGraphs(n);let o,a,s;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(s=this._termToNumericId(r))))for(n in i)(o=i[n])&&(a?s?this._loopBy2Keys(o.subjects,a,s,e):this._loopByKey0Deep(o.subjects,a,e):s?this._loopByKey0(o.predicates,s,e):this._loop(o.objects,e))}getGraphs(e,t,r){const n=[];return this.forGraphs(e=>{n.push(e)},e,t,r),n}forGraphs(e,t,r,n){for(const i in this._graphs)this.some(t=>(e(t.graph),!0),t,r,n,this._termFromId(this._entities[i]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1,allowExtraArcs:r=!1}={}){const n=Object.create(null),i=t?()=>!0:(e,t)=>{throw new Error(`${e.value} ${t}`)},o=this.getQuads(null,W.rdf.rest,W.rdf.nil,null),a=[];return o.forEach(t=>{const o=[];let s,c,u=!1,l=!1;const d=t.graph,h=[];let f=t.subject;for(;f&&!u;){const t=this.getQuads(null,null,f,null),n=this.getQuads(f,null,null,null);let a,p=null,m=null,y=null;for(let o=0;o<n.length&&!u;o++)a=n[o],a.graph.equals(d)?s?u=i(f,"has non-list arcs out"):a.predicate.value===W.rdf.first?(p?u=i(f,"has multiple rdf:first arcs"):p=a,e&&p===a&&h.push(a)):a.predicate.value===W.rdf.rest?(m?u=i(f,"has multiple rdf:rest arcs"):m=a,e&&m===a&&h.push(a)):t.length?r?l=!0:u=i(f,`has non-list arc ${a.predicate.value}`):(s=a,c="subject"):u=i(f,"not confined to single graph");for(let e=0;e<t.length&&!u;++e)a=t[e],s?u=i(f,"can't have coreferences"):a.predicate.value===W.rdf.rest?y?u=i(f,"has incoming rdf:rest arcs"):y=a:(s=a,c="object");p?o.push(p.object):u=i(f,"has no list head"),f=y&&y.subject}if(u)e=!1;else if(o.reverse(),s&&(n[s[c].value]=o),e&&!l)for(let e=0;e<h.length;e++)a.push(h[e])}),e&&this.removeQuads(a),n}addAll(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),Array.isArray(e))this.addQuads(e);else if(e instanceof N3Store&&e._entityIndex===this._entityIndex)this._addFromIndex(e._graphs);else for(const t of e)this.add(t);return this}contains(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return!0;if(!(e instanceof N3Store)||this._entityIndex!==e._entityIndex){const t=De(e),r=this._size;return!(null!==t&&null!==r&&t>r)&&e.every(e=>this.has(e))}const t=this._graphs,r=e._graphs;let n,i,o,a,s,c;for(const e in r){if(!(n=t[e]))return!1;if(n=n.subjects,(i=r[e].subjects)[Ne]>n[Ne])return!1;for(const e in i){if(!(o=n[e])||(a=i[e])[Ne]>o[Ne])return!1;for(const e in a){if(!(s=o[e])||(c=a[e])[Ne]>s[Ne])return!1;for(const e in c)if(!(e in s))return!1}}}return!0}deleteMatches(e,t,r,n){for(const i of this.match(e,t,r,n,{matchSemantics:"lazy"}))this.removeQuad(i);return this}difference(e){if(e&&e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return new N3Store({entityIndex:this._entityIndex});if(e instanceof N3Store&&e._entityIndex===this._entityIndex){const t=new N3Store({entityIndex:this._entityIndex});return t._addFromIndex(this._graphs,e._graphs),t}return this.filter(t=>!e.has(t))}equals(e){return e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new N3Store({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this){const e=new N3Store({entityIndex:this._entityIndex});return e._addFromIndex(this._graphs),e}if(e instanceof N3Store&&this._entityIndex===e._entityIndex){const t=new N3Store({entityIndex:this._entityIndex});return 0!==this._size&&0!==e._size&&(e._graphCount<this._graphCount?t._addIntersectionFromIndex(e._graphs,this._graphs):t._addIntersectionFromIndex(this._graphs,e._graphs)),t}const t=De(e),r=this._size;if(null!==t&&null!==r&&t<r&&"function"==typeof e[Symbol.iterator]&&e._factory===ee&&e._entityIndex._factory===ee){const t=new N3Store({entityIndex:this._entityIndex});for(const r of e)this.has(r)&&t.add(r);return t}return this.filter(t=>e.has(t))}map(e){const t=new N3Store({entityIndex:this._entityIndex});for(const r of this)t.add(e(r,this));return t}reduce(e,t){const r=this.readQuads();let n=void 0===t?r.next().value:t;for(const t of r)n=e(n,t,this);return n}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match(null,null,null,null,{matchSemantics:"lazy"})}toString(){return(new N3Writer).quadsToString(this)}union(e){const t=new N3Store({entityIndex:this._entityIndex});return t._addFromIndex(this._graphs),t.addAll(e),t}[Symbol.iterator](){return this.readQuads()}}function Le(e,t,r=0){const n=t[r];if(n&&!(n in e))return!1;let i=!1,o=0;for(const a in n?{[n]:e[n]}:e){const n=2===r?null:Le(e[a],t,r+1);!1!==n&&(i=i||Object.create(null),i[a]=n,o++)}return i&&(i[Ne]=o),i}function Ue(e,t,r,n,i){const o={store:e,ids:[]},a=t&&e._termToNumericId(t),s=r&&e._termToNumericId(r),c=n&&e._termToNumericId(n);let u,l,d,h,f;!c||!a&&s?!a&&s?(u="predicates",[l,d,h]=[s,c,a],f=[1,2,0]):(u="subjects",[l,d,h]=[a,s,c],f=[0,1,2]):(u="objects",[l,d,h]=[c,a,s],f=[2,0,1]);const p=e._getGraphs(i),m=[];for(const e in p){const t=p[e][u],r=Number(e);for(const e in l?{[l]:t[l]}:t){const n=t[e];if(n){m[f[0]]=Number(e);for(const e in d?{[d]:n[d]}:n){const t=n[e];if(t){m[f[1]]=Number(e);for(const e in h?h in t?{[h]:null}:{}:t)m[f[2]]=Number(e),o.ids.push(m[0],m[1],m[2],r)}}}}}return o}function ze(e="lazy"){if("lazy"!==e&&"snapshot"!==e&&"forwarded"!==e)throw new Error(`Unknown matchSemantics: ${e}`);if("lazy"!==e&&("function"!=typeof WeakRef||"function"!=typeof FinalizationRegistry))throw new Error("Non-lazy matchSemantics requires WeakRef and FinalizationRegistry support");return e}function Be(e,t){const r=new Array(4);for(let n=0;n<4;n++){const i=e[n],o=t[n];if(null==i)r[n]=o;else{if(null!=o&&qe(i)!==qe(o))return!1;r[n]=i}}return r}class DatasetCoreAndReadableStream extends p().Readable{constructor(e,t,r,n,i,o){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:r,object:n,graph:i,options:o});const a=this._semantics=ze(o.matchSemantics);o.matchesNothing&&(this._matchesNothing=!0,this._filtered=new N3Store({factory:e._factory,entityIndex:o.entityIndex})),"lazy"!==a&&(this._readers=null,this._subjectId=this._predicateId=this._objectId=this._graphId=void 0,this._matchesNothing||(this._observer=e._addObserver(this)))}_matchesPattern(e,t,r,n){const{subject:i,predicate:o,object:a,graph:s,n3Store:c}=this;return(!i||e===(this._subjectId||(this._subjectId=c._termToNumericId(i))))&&((!o||t===(this._predicateId||(this._predicateId=c._termToNumericId(o))))&&((!a||r===(this._objectId||(this._objectId=c._termToNumericId(a))))&&(null==s||n===(this._graphId||(this._graphId=""===s||le(s)?1:c._termToNumericId(s))))))}_matchesQuad(e){const{subject:t,predicate:r,object:n,graph:i}=this;return!(this._matchesNothing||null!=t&&qe(t)!==qe(e.subject)||null!=r&&qe(r)!==qe(e.predicate)||null!=n&&qe(n)!==qe(e.object)||null!=i&&qe(i)!==qe(e.graph))}_assertMatchesPattern(e){if(!this._matchesQuad(e))throw new Error("Quad does not match the forwarded view pattern")}_sourceIterator(){return this._filtered?this._filtered[Symbol.iterator]():this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}_freezeCurrentIterators(){this._readers&&(this._readers.snapshot=this._filtered?Ue(this._filtered):Ue(this.n3Store,this.subject,this.predicate,this.object,this.graph),this._readers=null)}_onParentMutation(e,t,r,n,i){this._matchesPattern(e,t,r,n)&&(this._freezeCurrentIterators(),"forwarded"!==this._semantics?this._filtered=this.filtered:this._filtered&&(i?this._filtered._addQuad(e,t,r,n):this._filtered._removeQuad(e,t,r,n)))}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:r,predicate:n,subject:i}=this;"lazy"!==this._semantics&&this._freezeCurrentIterators();const o=this._filtered=new N3Store({factory:e._factory,entityIndex:this.options.entityIndex});let a,s,c;if("snapshot"===this._semantics&&this._detachObserver(),i&&!(a=o._termToNumericId(i))||n&&!(s=o._termToNumericId(n))||r&&!(c=o._termToNumericId(r)))return o;const u=e._getGraphs(t);for(const e in u){let t,r,n,i;(i=u[e])&&(!a&&s?(r=Le(i.predicates,[s,c,a]))&&(t=Le(i.subjects,[a,s,c]),n=Le(i.objects,[c,a,s])):c?(n=Le(i.objects,[c,a,s]))&&(t=Le(i.subjects,[a,s,c]),r=Le(i.predicates,[s,c,a])):(t=Le(i.subjects,[a,s,c]))&&(r=Le(i.predicates,[s,c,a]),n=Le(i.objects,[c,a,s])),t&&(o._graphs[e]={subjects:t,predicates:r,objects:n},o._graphCount++))}o._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[je]&&(this[je]=this[Symbol.iterator]());const t=this[je];for(;--e>=0;){const{done:e,value:r}=t.next();if(e)return void this.push(null);this.push(r)}}_destroy(e,t){this[je]&&(this[je].return(),this[je]=null),t(e)}_detachObserver(){this._observer&&(this.n3Store._removeObserver(this._observer),this._observer=null)}_detach(){return this._filtered=this.filtered,this._detachObserver(),"lazy"===this._semantics&&(this._readers=null),this._semantics="snapshot",this}addAll(e){if("forwarded"===this._semantics){for(const t of e)this._assertMatchesPattern(t),this.n3Store.addQuad(t);return this}return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,r,n){if("forwarded"===this._semantics){if(this._matchesNothing)throw new Error("Cannot delete from a conflicting forwarded view pattern");const i=Be([this.subject,this.predicate,this.object,this.graph],[e,t,r,n]);if(!i)throw new Error("Deletion pattern does not match the forwarded view pattern");return this.n3Store.deleteMatches(...i),this}return this.filtered.deleteMatches(e,t,r,n)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,r,n,i){return this.filtered.every("forwarded"===this._semantics?t=>e(t,this):e,t,r,n,i)}filter(e){return this.filtered.filter("forwarded"===this._semantics?t=>e(t,this):e)}forEach(e,t,r,n,i){return this.filtered.forEach("forwarded"===this._semantics?t=>e(t,this):e,t,r,n,i)}import(e){if("forwarded"!==this._semantics)return this.filtered.import(e);const t=this;return e.on("data",function r(n){try{t._assertMatchesPattern(n),t.n3Store.addQuad(n)}catch(t){e.removeListener("data",r),"function"==typeof e.destroy?e.destroy(t):e.emit("error",t)}}),e}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map("forwarded"===this._semantics?t=>e(t,this):e)}some(e,t,r,n,i){return this.filtered.some("forwarded"===this._semantics?t=>e(t,this):e,t,r,n,i)}toCanonical(){return this.filtered.toCanonical()}toStream(){return"lazy"!==this._semantics?p().Readable.from(this[Symbol.iterator]()):this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph,{matchSemantics:"lazy"})}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph,{matchSemantics:"lazy"}).addAll(e)}toArray(){return"lazy"!==this._semantics?[...this]:this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce("forwarded"===this._semantics?(t,r)=>e(t,r,this):e,t)}toString(){return(new N3Writer).quadsToString(this)}add(e){return"forwarded"===this._semantics?(this._assertMatchesPattern(e),this.n3Store.addQuad(e),this):this.filtered.add(e)}delete(e){return"forwarded"===this._semantics?(this._assertMatchesPattern(e),this.n3Store.removeQuad(e),this):this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,r,n,i=null){const o=i&&i.matchSemantics;if(i&&void 0!==o&&(ze(o),o!==this._semantics))throw new Error(`Cannot override matchSemantics on a view: inherited "${this._semantics}", received "${o}"`);if("forwarded"!==this._semantics)return new DatasetCoreAndReadableStream(this.filtered,e,t,r,n,{entityIndex:this.options.entityIndex,matchSemantics:this._semantics});const a=!this._matchesNothing&&Be([this.subject,this.predicate,this.object,this.graph],[e,t,r,n]),[s,c,u,l]=a||[null,null,null,null];return new DatasetCoreAndReadableStream(this.n3Store,s,c,u,l,{entityIndex:this.options.entityIndex,matchSemantics:"forwarded",matchesNothing:!a})}[Symbol.iterator](){return"lazy"===this._semantics?this._sourceIterator():this._iterateStable()}*_iterateStable(){const e=this._readers||(this._readers={count:0,snapshot:null}),t=this._sourceIterator();let r=0;e.count++;try{for(;!e.snapshot;){const{value:n,done:i}=t.next();if(e.snapshot||i)break;r++,yield n}e.snapshot&&(yield*function*({store:e,ids:t},r){const n=e._entities;let i,o,a,s,c,u,l,d;for(let h=4*r;h<t.length;h+=4)c!==t[h]&&(i=e._termFromId(n[c=t[h]])),u!==t[h+1]&&(o=e._termFromId(n[u=t[h+1]])),l!==t[h+2]&&(a=e._termFromId(n[l=t[h+2]])),d!==t[h+3]&&(s=e._termFromId(n[d=t[h+3]])),yield e._factory.quad(i,o,a,s)}(e.snapshot,r))}finally{t.return(),0===--e.count&&(e.snapshot=null,this._readers===e&&(this._readers=null))}}}const Qe="https://inrupt.com/.well-known/sdk-local-node/",{freeze:He}=Object;function Ke(e){return e.substring(0,46)===Qe}function We(e){return e.substring(46)}function Je(e){return"string"==typeof e&&"_:"===e.substring(0,2)}function Ge(e){return e.substring(2)}function Ve(e){return`_:${e.value}`}const Xe="http://www.w3.org/2001/XMLSchema#boolean",Ye="http://www.w3.org/2001/XMLSchema#dateTime",Ze="http://www.w3.org/2001/XMLSchema#decimal",et="http://www.w3.org/2001/XMLSchema#integer",tt="http://www.w3.org/2001/XMLSchema#string",rt="http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";function nt(e){if(e.endsWith("Z"))return[e.substring(0,e.length-1),"Z"];const t=e.split("+"),r=e.split("-");return 1===t.length&&1===r.length?[t[0],void 0]:t.length>r.length?[t[0],`+${t[1]}`]:[r[0],`-${r[1]}`]}function it(e){if("Z"===e)return[0,0];const t="+"===e.charAt(0)?1:-1,[r,n]=e.substring(1).split(":");return[Number.parseInt(r,10)*t,Number.parseInt(n,10)*t]}function ot(e){return at(e)&&"NamedNode"===e.termType}function at(e){return null!==e&&"object"==typeof e&&"string"==typeof e.termType&&"string"==typeof e.value&&"function"==typeof e.equals}function st(e){return ot(e)&&Ke(e.value)}function ct(e){const t=O(e);if("function"!=typeof URL)return!0;try{return new URL(t),!0}catch(e){return!1}}function ut(e,t){return ee.namedNode(lt(We(e.value),t))}function lt(e,t){if("function"!=typeof URL)throw new Error("The URL interface is not available, so an IRI cannot be determined.");const r=new URL(t);return r.hash=e,r.href}function dt(e,t){var r;if(!["NamedNode","BlankNode"].includes(t.subject.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.subject.termType}] as their Subject node.`);const n="BlankNode"===t.subject.termType?`_:${t.subject.value}`:t.subject.value,i=null!==(r=e[n])&&void 0!==r?r:{type:"Subject",url:n,predicates:{}};return He({...e,[n]:ht(i,t)})}function ht(e,t){return He({...e,predicates:ft(e.predicates,t)})}function ft(e,t){var r;if(!["NamedNode"].includes(t.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.predicate.termType}] as their Predicate node.`);const n=t.predicate.value,i=null!==(r=e[n])&&void 0!==r?r:{};return He({...e,[n]:pt(i,t)})}function pt(e,t){var r,n,i,o,a,s,c,u;if("NamedNode"===t.object.termType){const n=He([...null!==(r=e.namedNodes)&&void 0!==r?r:[],t.object.value]);return He({...e,namedNodes:n})}if("Literal"===t.object.termType){if(t.object.datatype.value===rt){const r=t.object.language.toLowerCase(),a=He([...null!==(i=null===(n=e.langStrings)||void 0===n?void 0:n[r])&&void 0!==i?i:[],t.object.value]),s=He({...null!==(o=e.langStrings)&&void 0!==o?o:{},[r]:a});return He({...e,langStrings:s})}const r=He([...null!==(s=null===(a=e.literals)||void 0===a?void 0:a[t.object.datatype.value])&&void 0!==s?s:[],t.object.value]),u=He({...null!==(c=e.literals)&&void 0!==c?c:{},[t.object.datatype.value]:r});return He({...e,literals:u})}if("BlankNode"===t.object.termType){const r=He([...null!==(u=e.blankNodes)&&void 0!==u?u:[],Ve(t.object)]);return He({...e,blankNodes:r})}throw new Error(`Objects of type [${t.object.termType}] are not supported.`)}function mt(e,t={}){var r;const n=[],i=null!==(r=t.dataFactory)&&void 0!==r?r:ee;return Object.keys(e.graphs).forEach(r=>{const o=e.graphs[r],a="default"===r?i.defaultGraph():i.namedNode(r);Object.keys(o).forEach(e=>{const{predicates:r}=o[e],s=Je(e)?i.blankNode(Ge(e)):i.namedNode(e);n.push(...yt(r,s,a,t))})}),n}function yt(e,t,r,n={}){var i;const o=[],a=null!==(i=n.dataFactory)&&void 0!==i?i:ee;return Object.keys(e).forEach(n=>{var i,s,c,u;const l=a.namedNode(n),d=null!==(i=e[n].langStrings)&&void 0!==i?i:{},h=null!==(s=e[n].namedNodes)&&void 0!==s?s:[],f=null!==(c=e[n].literals)&&void 0!==c?c:{},p=null!==(u=e[n].blankNodes)&&void 0!==u?u:[];Object.keys(f).forEach(e=>{const n=a.namedNode(e);f[e].forEach(e=>{const i=a.literal(e,n);o.push(a.quad(t,l,i,r))})});Object.keys(d).forEach(e=>{d[e].forEach(n=>{const i=a.literal(n,e);o.push(a.quad(t,l,i,r))})}),h.forEach(e=>{const n=a.namedNode(e);o.push(a.quad(t,l,n,r))}),p.forEach(e=>{if(Je(e)){const n=a.blankNode(Ge(e));o.push(a.quad(t,l,n,r))}else{const n=a.blankNode(),i=a.quad(t,l,n,r),s=yt(e,n,r);o.push(i),o.push(...s)}})}),o}const gt="http://www.w3.org/ns/auth/acl#Authorization",_t="http://www.w3.org/ns/auth/acl#accessTo",bt="http://www.w3.org/ns/auth/acl#agent",wt="http://www.w3.org/ns/auth/acl#agentGroup",vt="http://www.w3.org/ns/auth/acl#agentClass",St="http://www.w3.org/ns/auth/acl#default",xt="http://www.w3.org/ns/auth/acl#defaultForNew",It="http://www.w3.org/ns/auth/acl#mode",At="http://www.w3.org/ns/auth/acl#origin",Tt="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",Et="http://www.w3.org/2000/01/rdf-schema#seeAlso",Rt="http://www.w3.org/ns/ldp#BasicContainer",kt="http://www.w3.org/ns/ldp#Resource",jt="http://www.w3.org/ns/ldp#contains",Nt="http://xmlns.com/foaf/0.1/Agent",Ct="http://xmlns.com/foaf/0.1/primaryTopic",Pt="http://xmlns.com/foaf/0.1/isPrimaryTopicOf",Ot="http://www.w3.org/ns/solid/acp#AccessControlResource",Ft="http://www.w3.org/ns/pim/space#storage",{xsd:qt}=W,Mt=32,$t=13;function Dt(e){return e===Mt||e>=9&&e<=$t||e>=160&&(160===e||5760===e||e>=8192&&e<=8202||8232===e||8233===e||8239===e||8287===e||12288===e||65279===e)}const Lt=new Uint8Array(128);for(const e of",;!^#()[]{}\"'<> \t\n\v\f\r")Lt[e.charCodeAt(0)]=1;function Ut(e,t,r){let n=e.charCodeAt(t);return 46===n&&(n=e.charCodeAt(++t)),t>=e.length?r:function(e){return e<128?1===Lt[e]:Dt(e)}(n)}const zt={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b"},Bt={_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","'":"'","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},Qt=/[\x00-\x20<>\\"\{\}\|\^\`]/,Ht=new Uint8Array(128);for(let e=0;e<128;e++){const t=String.fromCharCode(e),r=t>="A"&&t<="Z"||t>="a"&&t<="z",n=r||"_"===t||"-"===t||t>="0"&&t<="9";Ht[e]=(r?1:0)|(n&&"-"!==t||":"===t?2:0)|(n?4:0)|(n||":"===t?8:0)|(t in Bt?16:0)}function Kt(e,t,r){const n=e.charCodeAt(t);if(n<128)return 0!==(Ht[n]&r)?1:0;if(n>=55296&&n<=56191){const r=e.charCodeAt(t+1);return r>=56320&&r<=57343?2:0}return r>=4&&(183===n||n>=768&&n<=879||8255===n||8256===n)||n>=192&&n<=8191&&215!==n&&247!==n&&(n<768||n>=880&&894!==n)||n>=8204&&n<=8205||n>=8304&&n<=8591||n>=11264&&n<=12271||n>=12289&&n<=55295||n>=63744&&n<=64975||n>=65008&&n<=65533?1:0}function Wt(e){return e<128&&!!(16&Ht[e])}function Jt(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Gt(e,t){let r=Kt(e,t,1);for(;0!==r;){t+=r;const n=46===e.charCodeAt(t)?t+1:t,i=e.charCodeAt(n);r=i<128?4&Ht[i]?1:0:Kt(e,n,4),0!==r&&(t=n)}return t}function Vt(e,t,r){const n=Gt(e,t);if(58!==e.charCodeAt(n))return-1;const i=function(e,t){let r=t,n=2;for(;;){const i=e.charCodeAt(t);let o=i<128?0!==(Ht[i]&n)?1:0:Kt(e,t,n);if(0===o&&37===i&&Jt(e.charCodeAt(t+1))&&Jt(e.charCodeAt(t+2))?o=3:0===o&&92===i&&Wt(e.charCodeAt(t+1))&&(o=2),0!==o)r=t+=o,n=8;else{if(46!==i||8!==n)return r;t++}}}(e,n+1);return Ut(e,i,r)?i:-1}function Xt(e){return e<=1114111&&(e<55296||e>57343)}const Yt={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_commentLine:!0,_whitespace:!0},Zt=/$0^/,er=/\S*/y;function tr(e,t,r){return e.lastIndex=r,e.exec(t)}function rr(e,t,r){return e.lastIndex=r,e.test(t)}function nr(e,t,r){return e.lastIndex=0,e.exec(`${t.slice(r)} `)}function ir(e){return e===Mt||9===e||10===e||e===$t||35===e}const or=/^(?:prefix|base|version|graph|forsome|forall|iri|a|true|false|has|is|of|id)$/i;class N3Lexer{constructor(e){if(this._iri=/<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/y,this._unescapedIri=/<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/y,this._simpleQuotedString=/"([^"\\\r\n]*)"(?=[^"])/y,this._simpleApostropheString=/'([^'\\\r\n]*)'(?=[^'])/y,this._langcode=/@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9])/iy,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-9: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#()\[\]\{\}"'<>])/y,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#()\[\]\{\}"'<>]))/y,this._number=/[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?\d+|(?=\.?\d)\d*(?:(\.)\d+)?)(?=\.?[,;:!\^\s#()\[\]\{\}"'<>])/y,this._boolean=/(?:true|false)(?=[.,;!\^\s#()\[\]\{\}"'<>])/y,this._atKeyword=/@[a-z]+(?=[\s#<:"'.])/iy,this._keyword=/(?:PREFIX|BASE|VERSION|GRAPH)(?=[\s#<"'])/iy,this._n3Verb=/(?:has|is|of)(?=[\s#()\[\]\{\}"'<>?_+\-0-9])/y,this._n3Id=/id(?=[\s#<])/y,this._shortPredicates=/a(?=[\s#()\[\]\{\}"'<>])/y,this._commentLine=/[ \t]*#([^\n\r]*)(?:\r\n|\n|\r)([ \t]*)/y,this._whitespace=/[ \t]+/y,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const e in this)!(e in Yt)&&this[e]instanceof RegExp&&(this[e]=Zt);this._keyword=/VERSION(?=[\s#<"])/y}else this._n3Mode=!1!==e.n3;if(this._directive=null,e.directives&&0!==e.directives.length){for(const t of e.directives)if(!/^[a-z]+$/i.test(t)||or.test(t))throw new Error(`Invalid directive name: "${t}"`);this._directive=new RegExp(`(?:${e.directives.join("|")})(?=[\\s#<])`,"iy"),this._directiveMaxLength=Math.max(...e.directives.map(e=>e.length)),this._directiveStarts=e.directives.map(e=>e[0].toLowerCase()+e[0].toUpperCase()).join("")}this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){const r=this._input;let n=0,i=this._linePosition+r.length;for(;;){for(;;){let e=r.charCodeAt(n),a=0;if(e===Mt||9===e){const t=r.charCodeAt(n+1);a=t===Mt||9===t?tr(this._whitespace,r,n)[0].length:1,e=r.charCodeAt(n+a)}if(35===e){const e=tr(this._commentLine,r,n);if(!e){if(n+=a,!t)return this._suspend(r,n,i);this.comments&&o(r.slice(n+1),this._line,i-(r.length-n)),n=r.length;break}{const s=e[0].length;if(!t&&n+s===r.length&&r.charCodeAt(r.length-1)===$t)return this._suspend(r,n,i);this.comments&&o(e[1],this._line,i-(r.length-n)+a),n+=s,i=r.length-n+e[2].length,this._line++}}else{if(10!==e&&e!==$t){n+=a;break}{if(!t&&e===$t&&n+a+1===r.length)return this._suspend(r,n,i);a+=e===$t&&10===r.charCodeAt(n+a+1)?2:1;let o=0;const s=r.charCodeAt(n+a);if(s===Mt||9===s){const e=r.charCodeAt(n+a+1);o=e===Mt||9===e?tr(this._whitespace,r,n+a)[0].length:1}n+=a+o,i=r.length-n+o,this._line++}}}if(n>=r.length)return t&&"^^"===this._previousMarker?s(this,r,n):(this._linePosition=i,t?(a("eof","","",this._line,i,0),this._input=null):this._input="");const c=this._line,u=r[n];let l="",d="",h="",f=null,p=0,m=0,y=0,g=!1,_=!1;switch(u){case"^":if("^^"===this._previousMarker)return s(this,r,n);if(r.length-n<3)break;if("^"!==r[n+1]){this._n3Mode&&(p=1,l="^");break}if(this._previousMarker="^^",n+=2,"<"!==r[n]){if(ir(r.charCodeAt(n)))continue;g=!0;break}case"<":if(f=tr(this._unescapedIri,r,n))l="IRI",d=f[1],m=f[1].length+2;else if(f=tr(this._iri,r,n)){if(d=this._unescape(f[1],zt),null===d||Qt.test(d))return s(this,r,n);l="IRI",m=f[1].length+2}else r.length-n>2&&"<"===r[n+1]&&"("===r[n+2]?(l="<<(",p=3):!this._lineMode&&r.length-n>(t?1:2)&&"<"===r[n+1]?(l="<<",p=2):this._n3Mode&&r.length-n>1&&"="===r[n+1]?(p=2,this._isImpliedBy?(l="abbreviation",d="<"):(l="inverse",d=">")):this._n3Mode&&r.length-n>1&&"-"===r[n+1]&&(l="inversePredicate",p=2);break;case">":r.length-n>1&&">"===r[n+1]&&(l=">>",p=2);break;case"_":((f=tr(this._blank,r,n))||t&&(f=nr(this._blank,r,n)))&&(l="blank",h="_",d=f[1],m=f[1].length+2);break;case'"':if(f=tr(this._simpleQuotedString,r,n))d=f[1];else if(({value:d,matchLength:p,finalLineLength:y,tripleQuoted:_}=this._parseLiteral(r,n)),null===d)return s(this,r,n);null===f&&0===p||(l="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(f=tr(this._simpleApostropheString,r,n))d=f[1];else if(({value:d,matchLength:p,finalLineLength:y,tripleQuoted:_}=this._parseLiteral(r,n)),null===d)return s(this,r,n);null===f&&0===p||(l="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(f=tr(this._variable,r,n))&&(l="var",d=f[0]);break;case"@":if("literal"===this._previousMarker&&(f=tr(this._langcode,r,n))&&"version"!==f[1]){const e=n+f[0].length;t||"-"!==r[e]||"-"===r[e+1]?(l="langcode",d=f[1]):f=null}else(f=tr(this._atKeyword,r,n))&&(l=f[0]);break;case".":if(r.length-n===1?t:r[n+1]<"0"||r[n+1]>"9"){l=".",p=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":if("-"===r[n+1]){"langcode"===this._previousMarker&&(r.startsWith("--ltr",n)?(l="dircode",d="ltr",p=5):r.startsWith("--rtl",n)&&(l="dircode",d="rtl",p=5));break}(f=tr(this._number,r,n)||t&&(f=nr(this._number,r,n)))&&(l="literal",d=f[0],h="string"==typeof f[1]?qt.double:"string"==typeof f[2]?qt.decimal:qt.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":case"V":case"v":(f=tr(this._keyword,r,n))?l=f[0].toUpperCase():g=!0;break;case"f":case"t":rr(this._boolean,r,n)?(l="literal",d="t"===u?"true":"false",h=qt.boolean,p=d.length):g=!0;break;case"a":rr(this._shortPredicates,r,n)?(l="abbreviation",d="a",p=1):g=!0;break;case"h":case"o":this._n3Mode&&(f=this._matchN3Verb(r,n,t))?l=f[0]:g=!0;break;case"i":this._n3Mode&&rr(this._n3Id,r,n)?(l="id",p=2):this._n3Mode&&(f=this._matchN3Verb(r,n,t))?l=f[0]:g=!0;break;case"=":this._n3Mode&&r.length-n>1&&(l="abbreviation",">"!==r[n+1]?(p=1,d="="):(p=2,d=">"));break;case"!":if(!this._n3Mode)break;case")":if(!t&&(r.length-n===1||r.length-n===2&&">"===r[n+1]))break;if(r.length-n>2&&">"===r[n+1]&&">"===r[n+2]){l=")>>",p=3;break}case",":case";":case"[":case"]":case"(":case"}":case"~":this._lineMode||(p=1,l=u);break;case"{":!this._lineMode&&r.length-n>=2&&("|"===r[n+1]?(l="{|",p=2):(l=u,p=1));break;case"|":r.length-n>=2&&"}"===r[n+1]&&(l="|}",p=2);break;default:g=!0}if(g){let e;if(("@prefix"===this._previousMarker||"PREFIX"===this._previousMarker)&&58===r.charCodeAt(e=Gt(r,n))&&e+1<r.length&&("#"===r[e+1]||"<"===r[e+1]||Dt(r.charCodeAt(e+1))))l="prefix",d=r.slice(n,e),p=e+1-n;else if(null!==this._directive&&this._directiveStarts.includes(u)&&((f=tr(this._directive,r,n))||t&&r.length-n<=this._directiveMaxLength&&(f=nr(this._directive,r,n))))l=f[0].toUpperCase();else if(!this._lineMode&&(e=Vt(r,n,t))>=0){const t=r.indexOf(":",n);l="prefixed",h=r.slice(n,t),d=this._unescape(r.slice(t+1,e),Bt),p=e-n}}if("^^"===this._previousMarker)switch(l){case"prefixed":l="type";break;case"IRI":l="typeIRI";break;default:l=""}if(!l)return t||!r.startsWith("'''",n)&&!r.startsWith('"""',n)&&/\n|\r/.test(r.slice(n))?s(this,r,n):this._suspend(r,n,i);const b=p||f[0].length,w=i-(r.length-n);let v;y?(v={type:l,value:d,prefix:h,line:c,start:w,end:y,endLine:this._line,tripleQuoted:_},e(null,v)):_?(v={type:l,value:d,prefix:h,line:c,start:w,end:w+b,tripleQuoted:_},e(null,v)):v=a(l,d,h,c,w,m||b),this.previousToken=v,this._previousMarker="literal"!==l||"VERSION"!==this._previousMarker&&"@version"!==this._previousMarker?l:"version",n=Math.min(n+b,r.length),y&&(i=r.length-n+y)}function o(t,r,n){e(null,{type:"comment",value:t,prefix:"",line:r,start:n,end:n+t.length+1})}function a(t,r,n,i,o,a){const s={type:t,value:r,prefix:n,line:i,start:o,end:o+a};return e(null,s),s}function s(t,r,n){e(t._syntaxError(tr(er,r,n)[0]))}}_suspend(e,t,r){return this._linePosition=r-(e.length-t),this._input=e.slice(t)}_matchN3Verb(e,t,r){const n=tr(this._n3Verb,e,t);if(!n)return null;const i=e[t+n[0].length];return"-"!==i&&"_"!==i&&(i<"0"||i>"9")&&" "!==i&&"\ufeff"!==i?n:Vt(e,t,!0)>=0?null:r||Gt(e,t)!==e.length?n:null}_unescape(e,t){let r=e.indexOf("\\");if(r<0)return e;let n="",i=0;for(;r>=0&&r+1<e.length;){const o=e[r+1];let a,s=r+2;if("u"===o||"U"===o){if(s+="u"===o?4:8,s>e.length)return null;let t=0;for(let n=r+2;n<s;n++){let r=e.charCodeAt(n);if(r>=48&&r<=57)r-=48;else if(r>=65&&r<=70)r-=55;else{if(!(r>=97&&r<=102))return null;r-=87}t=16*t+r}if(!Xt(t))return null;a=String.fromCodePoint(t)}else{if(!(o in t))return null;a=t[o]}n+=e.slice(i,r)+a,i=s,r=e.indexOf("\\",i)}return n+e.slice(i)}_parseLiteral(e,t){if(e.length-t>=3){const r=e[t],n=e[t+1]===r&&e[t+2]===r?3:1;let i=r;3===n&&(i='"'===r?'"""':"'''");let o=t+Math.max(this._literalClosingPos,n);for(;(o=e.indexOf(i,o))>t;){let r=0;for(;"\\"===e[o-r-1];)r++;if(r%2==0){const r=e.substring(t+n,o),i=r.split(/\r\n|\r|\n/),a=i.length-1,s=o-t+n;if(1===n&&0!==a||3===n&&this._lineMode)break;this._line+=a;const c=0===a?0:i[i.length-1].length+n;return{value:this._unescape(r,zt),matchLength:s,finalLineLength:c,tripleQuoted:3===n}}o++}this._literalClosingPos=e.length-t-n+1}return{value:"",matchLength:0,finalLineLength:0,tripleQuoted:!1}}_tryTokenizeToEnd(e,t){let r;try{this._tokenizeToEnd((t,n)=>{try{return e(t,n)}catch(e){throw r=e}},t)}catch(t){if(t===r||!(t instanceof RangeError))throw t;e(this._syntaxError(null,`Token too long on line ${this._line}.`))}}_syntaxError(e,t=`Unexpected "${e}" on line ${this._line}.`){this._input=null;const r=new Error(t);return r.context={token:void 0,line:this._line,previousToken:this.previousToken},r}_startTokenization(){return this._line=1,this._linePosition=0,this._previousMarker=void 0,this.previousToken=void 0,this._literalClosingPos=0,this._input=void 0,this._tokenization={}}_tokenizeString(e,t){this._startTokenization(),this._input=this._readStartingBom(e),this._tryTokenizeToEnd(t,!0)}_readStartingBom(e){return e.startsWith("\ufeff")?(this._linePosition=1,e.slice(1)):e}tokenize(e,t){const r=this._startTokenization();if("string"==typeof e){if(this._input=this._readStartingBom(e),"function"!=typeof t){const e=[];let t;if(this._tryTokenizeToEnd((r,n)=>r?t=r:e.push(n),!0),t)throw t;return e}queueMicrotask(()=>{this._tokenization===r&&this._tryTokenizeToEnd(t,!0)})}else{let n,i=0;"function"==typeof e.setEncoding&&e.setEncoding("utf8"),e.on("data",e=>{if(this._tokenization===r&&null!==this._input&&0!==e.length){if("string"!=typeof e&&(n=n||new TextDecoder("utf-8",{ignoreBOM:!0}),!(e=n.decode(e,{stream:!0}))))return;void 0===this._input?this._input=this._readStartingBom(e):this._input+=e,this._input.length>=i&&(this._tryTokenizeToEnd(t,!1),i=null!==this._input&&this._input.length>1024?2*this._input.length:0)}}),e.on("end",()=>{if(this._tokenization===r&&null!==this._input){const e=n?n.decode():"";e&&(this._input="string"==typeof this._input?this._input+e:e),"string"==typeof this._input&&this._tryTokenizeToEnd(t,!0)}}),e.on("error",e=>{this._tokenization===r&&t(e)})}}}let ar=0;const sr=/(^|\/)\.\.?($|[/#?])/,cr=/^[^?#]*(?:^|\/)\.\.?(?:$|[/#?])/;class N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&dr(this,e.factory);const t="string"==typeof e.format?e.format.match(/(?:^|\W)(\w*)$/)[1].toLowerCase():"",r=/turtle/.test(t),n=/trig/.test(t),i=/triple/.test(t),o=/quad/.test(t),a=this._n3Mode=/n3/.test(t),s=i||o;if(this._emitCurrent=this._emit,a&&(this._createQuad=this._createQuadInDirection,this._emit=this._emitInDirection,this._emitCurrent=this._emitCurrentInDirection),(this._supportsNamedGraphs=!(r||a))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||n||i||a),this._isImpliedBy=e.isImpliedBy,this._implicitEmptyPrefix=!!e.implicitEmptyPrefix,this._emptyFormulaAsTrue=!!e.emptyFormulaAsTrue,s&&(this._resolveRelativeIRI=e=>null),this._blankNodePrefix="string"!=typeof e.blankNodePrefix?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._directives=null,e.directives){this._directives=Object.create(null);for(const t of e.directives)this._directives[`@${t.toLowerCase()}`]=this._directives[t.toUpperCase()]=t}this._lexer=e.lexer||new N3Lexer({lineMode:s,n3:a,isImpliedBy:this._isImpliedBy,directives:e.directives}),this._explicitQuantifiers=!!e.explicitQuantifiers,this._formulaScopedBlankNodes=!!e.formulaScopedBlankNodes,this._parseUnsupportedVersions=!!e.parseUnsupportedVersions,this._version=e.version;const c=e.maxTripleTermDepth;this._maxTripleTermDepth=c===1/0||Number.isInteger(c)&&c>=0?c:1024}static _resetBlankNodePrefix(){ar=0}_setBase(e){if(e){const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e;const r=e.indexOf("?"),n=r<0?e:e.substr(0,r);this._basePath=e.indexOf("/")<0?e:n.substr(0,n.lastIndexOf("/")+1);const i=e;e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(\/\/[^\/?#]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1],void 0===e[2]||i.length!==this._baseRoot.length&&"?"!==i[this._baseRoot.length]||(this._basePath=`${this._baseRoot}/`),this._basePathHasDotSegments=sr.test(this._basePath)}else this._base="",this._basePath="",this._basePathHasDotSegments=!1}_enterTripleTerm(e,t,r,n){return this._tripleTermDepth>=this._maxTripleTermDepth?(this._error(`Triple terms nested deeper than ${this._maxTripleTermDepth} level${1===this._maxTripleTermDepth?"":"s"}`,n),!1):(this._tripleTermDepth++,this._saveContext(e,this._graph,t,r,null),this._graph=null,!0)}_saveContext(e,t,r,n,i){if(!this._n3Mode)return void this._contextStack.push({type:e,subject:r,predicate:n,object:i,graph:t});const o={type:e,subject:r,predicate:n,object:i,graph:t,inverse:this._inversePredicate,expectOf:this._expectOf,blankPrefix:this._prefixes._,prefixChanges:this._prefixChanges,quantifiedChanges:this._quantifiedChanges,emptyFormula:this._emptyFormula};"formula"===e&&(o.base=[this._base,this._basePath,this._baseRoot,this._baseScheme,this._basePathHasDotSegments],this._prefixChanges=[]),this._contextStack.push(o),this._inversePredicate=!1,this._expectOf=!1,this._formulaScopedBlankNodes&&"formula"!==e||(this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantifiedChanges=[]),"formula"===e&&(this._subject=null,this._emptyFormula=!0)}_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._expectOf=r.expectOf,"formula"===e&&([this._base,this._basePath,this._baseRoot,this._baseScheme,this._basePathHasDotSegments]=r.base),this._prefixChanges!==r.prefixChanges&&(ur(this._prefixes,this._prefixChanges),this._prefixChanges=r.prefixChanges),this._prefixes._=r.blankPrefix,this._quantifiedChanges!==r.quantifiedChanges&&(ur(this._quantified,this._quantifiedChanges),this._quantifiedChanges=r.quantifiedChanges),this._emptyFormula=r.emptyFormula)}_readBeforeTopContext(e){return this._version&&!this._isValidVersion(this._version)?this._error(`Detected unsupported version as media type parameter: "${this._version}"`,e):this._readInTopContext(e)}_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"VERSION":this._sparqlStyle=!0;case"@version":return this._readVersion;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return null!==this._directives&&e.type in this._directives&&null===this._graph?(this._sparqlStyle="@"!==e.type[0],this._directiveCallback(this._directives[e.type]),this._readDeclarationPunctuation):this._readSubject(e)}}_readInFormulaContext(e){switch(e.type){case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;default:return this._readSubject(e)}}_getStatementReader(){const e=this._contextStack[this._contextStack.length-1];return e&&"formula"===e.type?this._readInFormulaContext:this._readInTopContext}_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}_readList(e,t,r,n){const i=this._contextStack;return"<<"===(i.length&&i[i.length-1]).type?this._error("Unexpected list in reified triple",e):(this._saveContext("list",this._graph,t,r,n),this._subject=null,this._readListItem)}_readSubject(e){switch(this._predicate=null,"}"!==e.type&&(this._emptyFormula=!1),e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._readList(e,this.RDF_NIL,null,null);case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readInFormulaContext):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":return this._n3Mode?0===e.prefix.length?(this._literalValue=e.value,this._completeSubjectLiteral):(this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),this._getPathReader(this._readPredicateOrNamedGraph)):this._error("Unexpected literal",e);case"<<(":return this._n3Mode?this._enterTripleTerm("<<(",null,null,e)&&this._readSubject:this._error("Disallowed triple term as subject",e);case"<<":return this._enterTripleTerm("<<",null,null,e)&&this._readSubject;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;let r=!1;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case"has":return this._readPredicateAfterVerb;case"is":return this._inversePredicate=!0,this._expectOf=!0,this._readPredicateAfterVerb;case"inversePredicate":return this._inversePredicate=!0,this._readPredicateAfterVerb;case"|}":return this._subject=null,this._readAnnotationBlockPunctuation(e);case".":case"]":case"}":return null!==this._predicate||this._n3Mode?(this._subject=null,"]"===t?this._readBlankNodeTail(e):this._readPunctuation(e)):this._error(`Unexpected ${t}`,e);case";":return null!==this._predicate?this._readPredicate:this._error("Expected predicate but got ;",e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(0===e.prefix.length)return this._literalValue=e.value,this._completePredicateLiteral;this._predicate=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),r=!0;break;case"(":return this._n3Mode?this._readList(e,this._subject,this.RDF_NIL,null):this._error(`Expected entity but got ${t}`,e);case"[":return this._n3Mode?(this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead):this._error("Disallowed blank node as predicate",e);case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._graph=this._factory.blankNode(),null),this._readSubject):this._readEntity(e);case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if(void 0===(this._predicate=this._readEntity(e)))return;r=this._n3Mode}return this._validAnnotation=!0,r?this._getPathReader(this._readObject,"predicate"):this._readObject}_readPredicateAfterVerb(e){return"has"===e.type||"is"===e.type||"of"===e.type||"inversePredicate"===e.type?this._error(`Expected expression but got ${e.type}`,e):this._readPredicate(e)}_readObject(e){if(this._expectOf)return"of"!==e.type?this._error(`Expected of but got ${e.type}`,e):(this._expectOf=!1,this._readObject);switch(e.type){case"literal":if(0===e.prefix.length)return this._literalValue=e.value,this._readDataTypeOrLang;if(this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),this._n3Mode)return this._getPathReader(this._getContextEndReader());break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._readList(e,this._subject,this._predicate,this.RDF_NIL);case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readInFormulaContext):this._error("Unexpected graph",e);case"<<(":return this._enterTripleTerm("<<(",this._subject,this._predicate,e)&&this._readSubject;case"<<":return this._enterTripleTerm("<<",this._subject,this._predicate,e)&&this._readSubject;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){if("]"===e.type)return this._subject=null,this._readBlankNodeTail(e);{const t=this._contextStack;return"<<"===(t.length>1&&t[t.length-2]).type?this._error("Unexpected compound blank node expression in reified triple",e):"id"===e.type?this._readIriPropertyListId:(this._predicate=null,this._readPredicate(e))}}_readIriPropertyListId(e){const t=this._readEntity(e);if(void 0===t)return;if("NamedNode"!==t.termType)return this._error(`Expected IRI after id but got ${e.type}`,e);const r=this._subject;this._subject=t;const n=this._contextStack[this._contextStack.length-1];return n.subject===r&&(n.subject=t),n.predicate===r&&(n.predicate=t),n.object===r&&(n.object=t),this._predicate=null,this._readIriPropertyListPredicate}_readIriPropertyListPredicate(e){return";"===e.type||"]"===e.type||"."===e.type||"}"===e.type?this._error(`Expected predicate but got ${e.type}`,e):this._readPredicate(e)}_readBlankNodeTail(e){if("]"!==e.type)return this._readBlankNodePunctuation(e);null!==this._subject&&this._emitCurrent(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._getPathReader(this._readObject,"predicate"):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,o=this._contextStack,a=o[o.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!==o.length&&"list"===o[o.length-1].type){if(this._n3Mode)return null!==i&&this._emit(i,this.RDF_REST,this.RDF_NIL,this._graph),this._saveContext("item",this._graph,this._subject,this._predicate,this._object),this._subject=this._object,this._predicate=null,this._getPathReader(this._readListItem);this._emit(this._subject,this._predicate,this._object,this._graph)}if(null===this._predicate){if(n=this._n3Mode?this._getPathReader(this._readPredicate):this._readPredicate,this._subject===this.RDF_NIL)return n}else if(null===this._object){if(n=this._getPathReader(this._readObject,"predicate"),this._predicate===this.RDF_NIL)return n}else if(n=this._getContextEndReader(),this._n3Mode&&(n=this._getPathReader(n)),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?(r=this._factory.blankNode(),t=this._factory.blankNode(),null===i?null===a.predicate?a.subject=r:a.object=r:this._emit(i,this.RDF_REST,r,this._graph),this._emit(r,this.RDF_FIRST,t,this._graph),this._saveContext("formula",this._graph,r,this.RDF_FIRST,this._graph=t),this._subject=null,this._readInFormulaContext):this._error("Unexpected graph",e);case"<<(":case"<<":if(!this._enterTripleTerm(e.type,null,null,e))return;n=this._readSubject;break;default:if(void 0===(t=this._readEntity(e)))return}if(null===r&&(this._subject=r=this._factory.blankNode()),"<<"!==e.type&&"<<("!==e.type||(o[o.length-1].subject=this._subject),null===i?null===a.predicate?a.subject=r:null===a.object?a.predicate=r:a.object=r:this._emit(i,this.RDF_REST,r,this._graph),null!==t){if(this._n3Mode&&("IRI"===e.type||"prefixed"===e.type||"var"===e.type||"blank"===e.type||"literal"===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,t){let r,n=!1;switch(e.type){case"type":case"typeIRI":const i=this._readEntity(e);if(void 0===i)return;if(i.value===W.rdf.langString||i.value===W.rdf.dirLangString)return this._error("Detected illegal (directional) languaged-tagged string with explicit datatype",e);r=this._factory.literal(this._literalValue,i),e=null;break;case"langcode":if(e.value.split("-").some(e=>e.length>8))return this._error("Detected language tag with subtag longer than 8 characters",e);r=this._factory.literal(this._literalValue,e.value),this._literalLanguage=e.value,e=null,this._literalComponent=t,n=!0;break;default:r=this._factory.literal(this._literalValue)}return{token:e,literal:r,readCb:n}}_readDirCode(e){const t=this._literalComponent,r=this._literalListItem;if("dircode"===e.type){const r=this._factory.literal(this._literalValue,{language:this._literalLanguage,direction:e.value});"subject"===t?this._subject=r:"predicate"===t?this._predicate=r:this._object=r,this._literalLanguage=void 0,e=null}if("subject"===t||"predicate"===t){const r="subject"===t?this._readPredicateOrNamedGraph:this._readObject;return this._getPathEndReader(e,r,t)||r.call(this,e)}return this._completeObjectLiteralPost(e,r)}_completeTermLiteral(e,t){const r=this._completeLiteral(e,t);if(!r)return;let n;if("subject"===t?(this._subject=r.literal,n=this._readPredicateOrNamedGraph):(this._predicate=r.literal,this._validAnnotation=!0,n=this._readObject),r.readCb)return this._literalListItem=!1,this._readDirCode;const i=this._getPathEndReader(r.token,n,t);return i||n.call(this,r.token)}_completeSubjectLiteral(e){return this._completeTermLiteral(e,"subject")}_completePredicateLiteral(e){return this._completeTermLiteral(e,"predicate")}_completeObjectLiteral(e,t){const r=this._completeLiteral(e,"object");if(r)return this._object=r.literal,r.readCb?(this._literalListItem=t,this._readDirCode):this._completeObjectLiteralPost(r.token,t)}_completeObjectLiteralPost(e,t){return!this._n3Mode||null!==e&&"!"!==e.type&&"^"!==e.type?(t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),null===e?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(e))):t?(this._saveContext("item",this._graph,this._subject,this.RDF_FIRST,this._object),this._subject=this._object,this._predicate=null,this._getPathEndReader(e,this._readListItem)):this._getPathEndReader(e,this._getContextEndReader())}_readFormulaTail(e){if("}"!==e.type)return this._readPunctuation(e);null!==this._subject&&this._emitCurrent(this._subject,this._predicate,this._object,this._graph);const t=this._graph,r=this._emptyFormula;return this._restoreContext("formula",e),r&&this._emptyFormulaAsTrue&&(this._subject===t?this._subject=this.N3_TRUE:this._predicate===t?this._predicate=this.N3_TRUE:this._object=this.N3_TRUE),null!==this._object?this._getPathReader(this._getContextEndReader(),"object"):null!==this._predicate?this._getPathReader(this._readObject,"predicate"):this._getPathReader(this._readPredicate,"subject")}_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,this._tripleTerm=null,t=this._getStatementReader(),i&&(this._inversePredicate=!1);break;case";":i&&(this._inversePredicate=!1),t=this._readPredicate;break;case",":t=this._readObject;break;case"~":case"{|":return this._readAnnotationStart(e);case"|}":return this._error("Unexpected annotation syntax closing",e);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;this._emit(n,e,t,r,i)}return t}_readBlankNodePunctuation(e){let t,r=!1;switch(e.type){case";":r=this._inversePredicate,t=this._readPredicate;break;case",":t=this._readObject;break;case"~":case"{|":return this._readAnnotationStart(e);case"|}":return this._error("Unexpected annotation syntax closing",e);default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emitCurrent(this._subject,this._predicate,this._object,this._graph),r&&(this._inversePredicate=!1),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 null!==this._prefixChanges&&this._prefixChanges.push(this._prefix,this._prefixes[this._prefix]),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)}_isValidVersion(e){return this._parseUnsupportedVersions||N3Parser.SUPPORTED_VERSIONS.includes(e)}_readVersion(e){return"literal"!==e.type?this._error("Expected literal to follow version declaration",e):""!==e.prefix||e.tripleQuoted?this._error("Version declarations must use single quotes",e):(this._versionCallback(e.value),this._isValidVersion(e.value)?this._readDeclarationPunctuation:this._error(`Detected unsupported version: "${e.value}"`,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._getStatementReader().call(this,e)):"."!==e.type?this._error("Expected declaration to end with a dot",e):this._getStatementReader()}_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)):(null!==this._quantifiedChanges&&this._quantifiedChanges.push(t.id,this._quantified[t.id]),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,t){return this._afterPath=e,this._pathPosition=t||(null===this._predicate?"subject":"object"),this._readPath}_getPathEndReader(e,t,r){if(null!==e&&"!"!==e.type&&"^"!==e.type)return null;const n=this._getPathReader(t,r);return null===e?n:n.call(this,e)}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._afterPath,r=this._contextStack,n=r.length&&r[r.length-1];if(n&&"item"===n.type){const t=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,t,this._graph)}return this._afterPath=null,this._pathPosition=null,t.call(this,e)}}_readForwardPath(e){let t,r;const n=this._factory.blankNode();if(void 0!==(r=this._readEntity(e)))return"subject"===this._pathPosition?(t=this._subject,this._subject=n):"predicate"===this._pathPosition?(t=this._predicate,this._predicate=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"subject"===this._pathPosition?(n=this._subject,this._subject=t):"predicate"===this._pathPosition?(n=this._predicate,this._predicate=t):(n=this._object,this._object=t),this._emit(t,r,n,this._graph),this._readPath}_readTripleTermTail(e){if(")>>"!==e.type)return this._error(`Expected )>> but got ${e.type}`,e);const t=this._createQuad(this._subject,this._predicate,this._object,this._graph,this._inversePredicate);this._restoreContext("<<(",e),this._tripleTermDepth--;const r=this._contextStack,n=r.length&&r[r.length-1];return n&&"list"===n.type?(this._emit(this._subject,this.RDF_FIRST,t,this._graph),this._getContextEndReader()):null===this._subject?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_readReifiedTripleTailOrReifier(e){return"~"===e.type?this._readReifier:this._readReifiedTripleTail(e)}_readReifiedTripleTail(e){if(">>"!==e.type)return this._error(`Expected >> but got ${e.type}`,e);this._tripleTerm=null;const t=this._readTripleTerm();this._restoreContext("<<",e),this._tripleTermDepth--;const r=this._contextStack,n=r.length&&r[r.length-1];return n&&"list"===n.type?(this._emit(this._subject,this.RDF_FIRST,t,this._graph),this._getContextEndReader()):null===this._subject?(this._subject=t,this._readPredicateOrReifierTripleEnd):(this._object=t,this._getContextEndReader())}_readPredicateOrReifierTripleEnd(e){return"."===e.type?(this._subject=null,this._readPunctuation(e)):this._readPredicate(e)}_readReifier(e){return">>"===e.type?this._readReifiedTripleTail(e):(this._reifier=this._readEntity(e),this._readReifiedTripleTail)}_readAnnotationStart(e){return this._emitCurrent(this._subject,this._predicate,this._object,this._graph),this._tripleTerm=null,this._readAnnotation(e)}_readAnnotation(e){switch(e.type){case"~":return this._readReifierInAnnotation;case"{|":return this._readAnnotationBlockHead(e)}switch(this._tripleTerm=null,e.type){case";":return this._inversePredicate=!1,this._readPredicate;case",":return this._readObject;default:return this._subject=null,this._getContextEndReader().call(this,e)}}_readReifierInAnnotation(e){switch(e.type){case"IRI":case"typeIRI":case"type":case"prefixed":case"blank":case"var":return this._reifier=this._readEntity(e),this._readAnnotationBlockOrReifier}return this._reifier=this._factory.blankNode(),this._readAnnotationBlockOrReifier(e)}_readAnnotationBlockOrReifier(e){return"{|"===e.type?this._readAnnotationBlockHead(e):(this._readTripleTerm(),this._readAnnotation(e))}_readAnnotationBlockHead(e){const t=this._readTripleTerm();return this._saveContext("annotation",this._graph,this._subject,this._predicate,this._object),this._contextStack[this._contextStack.length-1].tripleTerm=this._tripleTerm,this._subject=t,this._predicate=this._object=this._tripleTerm=null,this._inversePredicate=!1,this._validAnnotation=!1,this._readPredicate}_readAnnotationBlockPunctuation(e){const t=this._contextStack;if("|}"===e.type){if(!t.length||"annotation"!==t[t.length-1].type)return this._error("Unexpected annotation syntax closing",e);if(!this._validAnnotation)return this._error("Annotation block can not be empty",e);null!==this._subject&&this._emitCurrent(this._subject,this._predicate,this._object,this._graph);const{tripleTerm:r}=t[t.length-1];return this._restoreContext("annotation",e),this._tripleTerm=r,this._readAnnotation}return this._readBlankNodePunctuation(e)}_readTripleTerm(){const e=this._contextStack,t=e.length&&e[e.length-1],r=t?t.graph:void 0,n=this._reifier||this._factory.blankNode();return this._reifier=null,this._tripleTerm=this._tripleTerm||this._createQuad(this._subject,this._predicate,this._object,null,this._inversePredicate),this._emit(n,this.RDF_REIFIES,this._tripleTerm,r||this._graph||this.DEFAULTGRAPH),n}_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._readTripleTermTail;case"<<":return this._readReifiedTripleTailOrReifier;case"annotation":return this._readAnnotationBlockPunctuation}}_createQuad(e,t,r,n){return this._factory.quad(e,t,r,n||this.DEFAULTGRAPH)}_createQuadInDirection(e,t,r,n,i){return i?this._factory.quad(r,t,e,n||this.DEFAULTGRAPH):this._factory.quad(e,t,r,n||this.DEFAULTGRAPH)}_emitInDirection(e,t,r,n,i){this._callback(null,this._createQuad(e,t,r,n,i))}_emitCurrentInDirection(e,t,r,n){this._callback(null,this._createQuad(e,t,r,n,this._inversePredicate))}_emit(e,t,r,n){this._callback(null,this._factory.quad(e,t,r,n||this.DEFAULTGRAPH))}_error(e,t){const r=` on line ${t.line}.`;e.length+r.length>200&&(e=`${e.slice(0,199-r.length)}…`);const n=new Error(`${e}${r}`);n.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(n),this._callback=lr}_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"?":{const t=this._base.indexOf("?");return(t<0?this._base:this._base.substr(0,t))+e}case"/":return"/"!==e[1]?this._baseRoot+this._removeDotSegments(e):this._baseScheme?this._removeDotSegments(this._baseScheme+e):this._removeDotSegments(`:${e}`).substr(1);default:return/^[^/:]*:/.test(e)?null:this._basePathHasDotSegments||cr.test(e)?this._removeDotSegments(this._basePath+e):this._basePath+e}}_removeDotSegments(e){if(!sr.test(e))return e;const t=e.length;let r="",n=-1,i=-1,o=0,a="/";for(;n<t;){switch(a){case":":if(i<0&&"/"===e[++n]&&"/"===e[++n])for(;(i=n+1)<t&&"/"!==e[i]&&"?"!==e[i]&&"#"!==e[i];)n=i;break;case"?":case"#":n=t;break;case"/":if("."===e[n+1])switch(a=e[1+ ++n],a){case"/":r+=e.substring(o,n-1),o=n+1;break;case void 0:case"?":case"#":return r+e.substring(o,n)+e.substr(n+1);case".":if(a=e[1+ ++n],void 0===a||"/"===a||"?"===a||"#"===a){if(r+=e.substring(o,n-2),(o=r.lastIndexOf("/"))>=i&&(r=r.substr(0,o)),"/"!==a)return`${r}/${e.substr(n+1)}`;o=n+1}}}a=e[++n]}return r+e.substring(o)}parse(e,t,r,n){let i,o,a,s,c,u,l;t&&(t.onQuad||t.onPrefix||t.onComment||t.onVersion||t.onDirective||t.onToken||t.onTokenEnd)?(i=t.onQuad,o=t.onPrefix,a=t.onComment,s=t.onVersion,c=t.onDirective,u=t.onToken,l=t.onTokenEnd):(i=t,o=r,s=n),this._readCallback=this._readBeforeTopContext,this._contextStack=[],this._graph=this._subject=this._predicate=this._object=null,this._tripleTerm=this._reifier=null,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${ar++}_`,this._n3Mode&&this._implicitEmptyPrefix&&this._base&&(this._prefixes[""]=this._resolveIRI("#")),this._prefixCallback=o||lr,this._versionCallback=s||lr,this._directiveCallback=c||lr,this._inversePredicate=!1,this._expectOf=!1,this._quantified=Object.create(null),this._prefixChanges=null,this._quantifiedChanges=null,this._emptyFormula=!1,this._tripleTermDepth=0;const d=e=>this._readCallback=this._readCallback(e);let h=d;if((a||this._lexer.comments)&&(this._lexer.comments=!0,h=e=>"comment"!==e.type?d(e):(a&&a(e.value),this._readCallback)),u||l){const e=h;h=t=>{try{try{return u&&u(t),e(t)}finally{l&&l(t)}}catch(e){throw this._readCallback=null,e}}}if(!i){const t=[];let r;this._callback=(e,n)=>{e?r=e:n&&t.push(n)};const n=this._lexer;if(o||s||c||a||u||l||n.tokenize!==N3Lexer.prototype.tokenize||"function"!=typeof n._tokenizeString)n.tokenize(e).every(h);else{const t=[this._base,this._basePath,this._baseRoot,this._baseScheme];n._tokenizeString(e,(e,r)=>{e?([this._base,this._basePath,this._baseRoot,this._baseScheme]=t,this._callback(e),this._callback=lr):this._readCallback&&h(r)})}if(r)throw r;return t}this._callback=i,this._lexer.tokenize(e,(e,t)=>{null!==e?(this._callback(e),this._callback=lr):this._readCallback&&h(t)})}}function ur(e,t){for(let r=t.length-2;r>=0;r-=2)void 0===t[r+1]?delete e[t[r]]:e[t[r]]=t[r+1]}function lr(){}function dr(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(W.rdf.first),e.RDF_REST=t.namedNode(W.rdf.rest),e.RDF_NIL=t.namedNode(W.rdf.nil),e.RDF_REIFIES=t.namedNode(W.rdf.reifies),e.N3_FORALL=t.namedNode(W.r.forAll),e.N3_FORSOME=t.namedNode(W.r.forSome),e.N3_TRUE=t.literal("true",t.namedNode(W.xsd.boolean)),e.ABBREVIATIONS={a:t.namedNode(W.rdf.type),"=":t.namedNode(W.owl.sameAs),">":t.namedNode(W.log.implies),"<":t.namedNode(W.log.isImpliedBy)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}N3Parser.SUPPORTED_VERSIONS=["1.2","1.2-basic","1.1"],dr(N3Parser.prototype,ee);const hr=()=>{const e=[],t=[],r=[];return{onQuad:t=>{e.push(t)},onError:e=>{r.push(e)},onComplete:e=>{t.push(e)},parse:(n,i)=>{var o;(o=U(i),new N3Parser({format:"text/turtle",baseIRI:o})).parse(n,(n,i)=>{n?r.forEach(e=>e(n)):i?e.forEach(e=>e(i)):t.forEach(e=>e())})}}};async function fr(e,t){const r=new N3Writer({format:"text/turtle",prefixes:null==t?void 0:t.prefixes}),n=e.map(e=>ee.quad(e.subject,e.predicate,e.object,void 0));r.addQuads(n);const i=new Promise((e,t)=>{r.end((r,n)=>{r?t(r):e(n)})});return await i}const pr=new Uint8Array(16);const mr=[];for(let e=0;e<256;++e)mr.push((e+256).toString(16).slice(1));function yr(e,t=0){return(mr[e[t+0]]+mr[e[t+1]]+mr[e[t+2]]+mr[e[t+3]]+"-"+mr[e[t+4]]+mr[e[t+5]]+"-"+mr[e[t+6]]+mr[e[t+7]]+"-"+mr[e[t+8]]+mr[e[t+9]]+"-"+mr[e[t+10]]+mr[e[t+11]]+mr[e[t+12]]+mr[e[t+13]]+mr[e[t+14]]+mr[e[t+15]]).toLowerCase()}const gr=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){e=e||{};const n=e.random??e.rng?.()??crypto.getRandomValues(pr);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 yr(n)}(e,t,r):crypto.randomUUID()};function _r(e){var t,r,n,i,o,a,s,c;if(ot(e))return`<${e.value}> (URL)`;if(function(e){return at(e)&&"Literal"===e.termType}(e)){if(!ot(e.datatype))return`[${e.value}] (RDF/JS Literal of unknown type)`;let u;switch(e.datatype.value){case Xe:return u=null!==(r=null===(t=function(e){return"true"===e||"1"===e||"false"!==e&&"0"!==e&&null}(e.value))||void 0===t?void 0:t.valueOf())&&void 0!==r?r:`Invalid data: \`${e.value}\``,`${u} (boolean)`;case Ye:return u=null!==(i=null===(n=function(e){if(!/-?\d{4,}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const[t,r]=e.split("T"),[n,i]="-"===t.charAt(0)?[-1,t.substring(1)]:[1,t],[o,a,s]=i.split("-"),c=Number.parseInt(o,10)*n,u=Number.parseInt(a,10)-1,l=Number.parseInt(s,10),[d,h]=nt(r),[f,p]="string"==typeof h?it(h):[0,0],[m,y,g]=d.split(":"),_=Number.parseInt(m,10)+f,b=Number.parseInt(y,10)+p,[w,v]=g.split("."),S=Number.parseInt(w,10),x=v?Number.parseInt(v,10):0,I=new Date(Date.UTC(c,u,l,_,b,S,x));return c>=0&&c<100&&I.setUTCFullYear(I.getUTCFullYear()-1900),I}(e.value))||void 0===n?void 0:n.toUTCString())&&void 0!==i?i:`Invalid data: \`${e.value}\``,`${u} (datetime)`;case Ze:return u=null!==(a=null===(o=function(e){const t=Number.parseFloat(e);return Number.isNaN(t)?null:t}(e.value))||void 0===o?void 0:o.toString())&&void 0!==a?a:`Invalid data: \`${e.value}\``,`${u} (decimal)`;case et:return u=null!==(c=null===(s=function(e){const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}(e.value))||void 0===s?void 0:s.toString())&&void 0!==c?c:`Invalid data: \`${e.value}\``,`${u} (integer)`;case rt:return`"${e.value}" (${e.language} string)`;case tt:return`"${e.value}" (string)`;default:return`[${e.value}] (RDF/JS Literal of type: \`${e.datatype.value}\`)`}}return"BlankNode"===e.termType?`[${e.value}] (RDF/JS BlankNode)`:"Quad"===e.termType?"??? (nested RDF* Quad)":"Variable"===e.termType?`?${e.value} (RDF/JS Variable)`:e}function br(e){if(!Nr(e))throw new ThingExpectedError(e)}function wr(e,t){const r=P(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.filter(e=>!function(e){return"BlankNode"===e.subject.termType||"BlankNode"===e.object.termType}(e)).reduce(([e,t],r)=>void 0!==e.find(e=>e.equals(r))?[e.filter(e=>!e.equals(r)),t]:[e,t.concat(r)],[r.additions,r.deletions]);return He({...e,internal_changeLog:{additions:n,deletions:i}})}const vr=function(e,t){var r,n,i;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const o=O(t),a=null!==(i=null===(n=null===(r=e.predicates[o])||void 0===r?void 0:r.namedNodes)||void 0===n?void 0:n[0])&&void 0!==i?i:null;return null===a?null:Ke(a)?`#${We(a)}`:a};function Sr(e,t){var r,n,i;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const o=O(t);return null!==(i=null===(n=null===(r=e.predicates[o])||void 0===r?void 0:r.namedNodes)||void 0===n?void 0:n.map(e=>Ke(e)?`#${We(e)}`:e))&&void 0!==i?i:[]}const xr=Sr;function Ir(e,t){var r,n;br(e);const i=function(e,t){return xr(e,t).map(e=>ee.namedNode(e))}(e,t),o=function(e,t){var r,n,i,o;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const a=O(t);let s=[];const c=null!==(n=null===(r=e.predicates[a])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{},u=Object.keys(c);for(const e of u){const t=c[e].map(t=>ee.literal(t,e));s=s.concat(t)}const l=null!==(o=null===(i=e.predicates[a])||void 0===i?void 0:i.literals)&&void 0!==o?o:{},d=Object.keys(l);for(const e of d){const t=l[e],r=ee.namedNode(e),n=t.map(e=>ee.literal(e,r));s=s.concat(n)}return s}(e,t),a=O(t),s=(null!==(n=null===(r=e.predicates[a])||void 0===r?void 0:r.blankNodes)&&void 0!==n?n:[]).map(e=>{const t=Je(e)?Ge(e):void 0;return ee.blankNode(t)});return i.concat(o).concat(s)}function Ar(e,t,r){var n,i,o,a;if(!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const s=O(t);return null!==(a=null===(o=null===(i=null===(n=e.predicates[s])||void 0===n?void 0:n.literals)||void 0===i?void 0:i[r])||void 0===o?void 0:o[0])&&void 0!==a?a:null}function Tr(e,t,r={}){var n;if(!ct(t)&&!t.match(/^_:/))throw new ValidThingUrlExpectedError(t);const i=void 0!==r.scope?O(r.scope):"default",o=null!==(n=e.graphs[i])&&void 0!==n?n:{},a=O(t),s=o[Ke(a)&&C(e)?lt(We(a),U(e)):a];return void 0===s?null:s}function Er(e,t={acceptBlankNodes:!1}){var r;const n=void 0!==t.scope?O(t.scope):"default",i=null!==(r=e.graphs[n])&&void 0!==r?r:{};return Object.values(i).filter(e=>!Je(e.url)||t.acceptBlankNodes)}function Rr(e,t){var r;const n=Pr(t)&&C(e)?lt(We(t.url),U(e)):t.url,i=e.graphs.default,o=He({...i,[n]:He({...t,url:n})}),a=He({...e.graphs,default:o}),s=ee.namedNode(n),c=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,u=void 0!==c?yt(c,s,ee.defaultGraph()):[],l=yt(t.predicates,s,ee.defaultGraph());return function(e,t){const r=P(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.reduce(([e,t],r)=>void 0!==t.find(e=>e.equals(r))?[e,t.filter(e=>!e.equals(r))]:[e.concat(r),t],[r.additions,r.deletions]);return He({...e,internal_changeLog:{additions:n,deletions:i}})}(wr(He({...e,graphs:a}),u),l)}function kr(e,t){var r;let n;n=ot(t)?t.value:"string"==typeof t?Ke(t)&&C(e)?lt(We(t),U(e)):t:Pr(t)?t.url:Cr(t);const i={...e.graphs.default};delete i[n];const o=He({...e.graphs,default:He(i)}),a=ee.namedNode(n),s=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,c=void 0!==s?yt(s,a,ee.defaultGraph()):[];return wr(He({...e,graphs:o}),c)}function jr(e={}){var t;if(void 0!==e.url){const{url:t}=e;if(!ct(t))throw new ValidThingUrlExpectedError(t);return He({type:"Subject",predicates:He({}),url:t})}const r=null!==(t=e.name)&&void 0!==t?t:Or(),n=`${Qe}${r}`;return He({type:"Subject",predicates:He({}),url:n})}function Nr(e){return"object"==typeof e&&null!==e&&"string"==typeof e.type&&"Subject"===e.type}const Cr=function(e,t){if(Pr(e)){if(void 0===t)throw new Error("The URL of a Thing that has not been persisted cannot be determined without a base URL.");return lt(We(e.url),t)}return e.url};function Pr(e){return Ke(e.url)}class ThingExpectedError extends SolidClientError{constructor(e){super(`Expected a Thing, but received: [${e}].`),this.receivedValue=e}}class thing_ValidPropertyUrlExpectedError extends SolidClientError{constructor(e){const t=ot(e)?e.value:e;super(`Expected a valid URL to identify a property, but received: [${t}].`),this.receivedProperty=t}}class ValidValueUrlExpectedError extends SolidClientError{constructor(e){const t=ot(e)?e.value:e;super(`Expected a valid URL value, but received: [${t}].`),this.receivedValue=t}}class ValidThingUrlExpectedError extends SolidClientError{constructor(e){const t=ot(e)?e.value:e;super(`Expected a valid URL to identify a Thing, but received: [${t}].`),this.receivedValue=t}}const Or=()=>gr();function Fr(e){const t=new URL(e);return t.hash="",t.href}function qr(e){return Array.from(e).reduce((e,t)=>function(e,t){var r;if(!["NamedNode","DefaultGraph"].includes(t.graph.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.graph.termType}] as their Graph node.`);const n="DefaultGraph"===t.graph.termType?"default":t.graph.value,i=null!==(r=e.graphs[n])&&void 0!==r?r:{};return He({...e,graphs:He({...e.graphs,[n]:dt(i,t)})})}(e,t),{graphs:{default:{}},type:"Dataset"})}function Mr(){return He({type:"Dataset",graphs:{default:{}}})}async function $r(e,t){var r,n;const i=F(O(e)),o=Object.keys(null!==(r=null==t?void 0:t.parsers)&&void 0!==r?r:{}),a=o.length>0?o.join(", "):"text/turtle",s=await(null!==(n=null==t?void 0:t.fetch)&&void 0!==n?n:fetch)(i,{headers:{Accept:a}});if(M(s)){const e=await s.clone().text();throw new FetchError(`Fetching the Resource at [${i}] failed: [${s.status}] [${s.statusText}] ${e}.`,s,e)}const c=await async function(e,t={}){if(M(e)){const t=await e.clone().text();throw new FetchError(`Fetching the SolidDataset at [${e.url}] failed: [${e.status}] [${e.statusText}] ${t}.`,e,t)}const r=D(e),n={"text/turtle":hr(),...t.parsers},i=null!==(o=r.internal_resourceInfo.contentType)&&void 0!==o?o:null;var o;if(null===i)throw new Error(`Could not determine the content type of the Resource at [${U(r)}].`);const a=i.split(";")[0],s=n[a];if(void 0===s)throw new Error(`The Resource at [${U(r)}] has a MIME type of [${a}], but the only parsers available are for the following MIME types: [${Object.keys(n).join(", ")}].`);const c=await e.text(),u=await new Promise((e,t)=>{const n=new N3Store;s.onError(e=>{t(new Error(`Encountered an error parsing the Resource at [${U(r)}] with content type [${i}]: ${e}`))}),s.onQuad(e=>{n.add(e)}),s.onComplete(()=>{e(n)}),s.parse(c,r)}),l=He(qr(u));return He({...l,...r})}(s,t);return c}async function Dr(e,t,r){var n;const i=F(O(e)),o=function(e){return P(e)?e:He({...e,internal_changeLog:{additions:[],deletions:[]}})}(t),a=Ur(o,i)?await async function(e){return{method:"PATCH",body:`${e.internal_changeLog.deletions.length>0?`DELETE DATA {${(await fr(e.internal_changeLog.deletions.map(Qr))).trim()}};`:""} ${e.internal_changeLog.additions.length>0?`INSERT DATA {${(await fr(e.internal_changeLog.additions.map(Qr))).trim()}};`:""}`,headers:{"Content-Type":"application/sparql-update"}}}(o):await async function(e,t){return{method:"PUT",body:await fr(mt(e).map(Qr),t),headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:`<${kt}>; rel="type"`}}}(o,r),s=await(null!==(n=null==r?void 0:r.fetch)&&void 0!==n?n:fetch)(i,a);if(M(s)){const e=Ur(o,i)?`The changes that were sent to the Pod are listed below.\n\n${function(e){if(!N(e))return"This is a newly initialized SolidDataset, so there is no source to compare it to.";if(!P(e)||0===e.internal_changeLog.additions.length&&0===e.internal_changeLog.deletions.length)return`## Changes compared to ${U(e)}\n\nThis SolidDataset has not been modified since it was fetched from ${U(e)}.\n`;let t=`## Changes compared to ${U(e)}\n`;const r=function(e){const t=Object.create(null);return e.internal_changeLog.deletions.forEach(r=>{var n,i,o;const a=st(r.subject)?ut(r.subject,U(e)):r.subject;if(!ot(a)||!ot(r.predicate))return;const s=O(a),c=O(r.predicate);null!==(n=t[s])&&void 0!==n||(t[s]=Object.create(null)),null!==(i=(o=t[s])[c])&&void 0!==i||(o[c]={added:[],deleted:[]}),t[s][c].deleted.push(r.object)}),e.internal_changeLog.additions.forEach(r=>{var n,i,o;const a=st(r.subject)?ut(r.subject,U(e)):r.subject;if(!ot(a)||!ot(r.predicate))return;const s=O(a),c=O(r.predicate);null!==(n=t[s])&&void 0!==n||(t[s]=Object.create(null)),null!==(i=(o=t[s])[c])&&void 0!==i||(o[c]={added:[],deleted:[]}),t[s][c].added.push(r.object)}),t}(e);return Object.keys(r).forEach(e=>{t+=`\n### Thing: ${e}\n`;const n=r[e];Object.keys(n).forEach(e=>{t+=`\nProperty: ${e}\n`;const{deleted:r}=n[e],{added:i}=n[e];r.length>0&&(t+="- Removed:\n",t+=r.reduce((e,t)=>`${e} - ${_r(t)}\n`,"")),i.length>0&&(t+="- Added:\n",t+=i.reduce((e,t)=>`${e} - ${_r(t)}\n`,""))})}),t}(o)}`:`The SolidDataset that was sent to the Pod is listed below.\n\n${Br(o)}`,t=await s.clone().text();throw new FetchError(`Storing the Resource at [${i}] failed: [${s.status}] [${s.statusText}] ${t}.\n\n${e}`,s,t)}const c={...q(s),isRawData:!1};return Kr(He({...t,internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:c}))}async function Lr(e,t){var r;const n=N(e)?O(U(e)):F(O(e)),i=await(null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch)(n,{method:"DELETE"});if(M(i)){const e=await i.clone().text();throw new FetchError(`Deleting the SolidDataset at [${n}] failed: [${i.status}] [${i.statusText}] ${e}.`,i,e)}}function Ur(e,t){return P(e)&&N(e)&&"string"==typeof e.internal_resourceInfo.sourceIri&&(r=t,Fr(e.internal_resourceInfo.sourceIri)===Fr(r));var r}function zr(e,t){const r=new URL(t),n=new URL(e),i=n.href.startsWith(r.href),o=n.pathname.substring(r.pathname.length,n.pathname.length).replace(/(^\/)|(\/$)/g,"");return i&&o.length>=1&&!o.includes("/")}function Br(e){let t="";N(e)?t+=`# SolidDataset: ${U(e)}\n`:t+="# SolidDataset (no URL yet)\n";const r=Er(e);return 0===r.length?t+="\n<empty>\n":r.forEach(r=>{t+=`\n${function(e){let t="";Pr(e)?t+=`## Thing (no URL yet — identifier: \`#${We(e.url)}\`)\n`:t+=`## Thing: ${e.url}\n`;const r=Object.keys(e.predicates);if(0===r.length)t+="\n<empty>\n";else for(const n of r)t+=`\nProperty: ${n}\n`,t+=Ir(e,n).reduce((e,t)=>`${e}- ${_r(t)}\n`,"");return t}(r)}`,P(e)&&(t+=`\n${function(e,t){const r=ee.namedNode(t.url),n=e.internal_changeLog.additions.reduce((e,t)=>t.subject.equals(r)?e+1:e,0),i=e.internal_changeLog.deletions.reduce((e,t)=>t.subject.equals(r)?e+1:e,0);return`(${1===n?"1 new value added":`${n} new values added`} / ${1===i?"1 value removed":`${i} values removed`})`}(e,r)}\n`)}),t}function Qr(e){const t=ot(e.subject)?Hr(e.subject):e.subject,r=ot(e.object)?Hr(e.object):e.object;return ee.quad(t,e.predicate,r,e.graph)}function Hr(e){return Ke(e.value)?ee.namedNode(`#${We(e.value)}`):e}function Kr(e){const t=U(e),r=e.graphs.default,n=Object.keys(r).reduce((e,r)=>{const n=function(e,t){const r=Object.keys(e.predicates).reduce((e,r)=>{var n;const i=null!==(n=e[r].namedNodes)&&void 0!==n?n:[];if(i.every(e=>!Ke(e)))return e;const o=He(i.map(e=>Ke(e)?`${t}#${We(e)}`:e)),a=He({...e[r],namedNodes:o});return He({...e,[r]:a})},e.predicates);return He({...e,predicates:r,url:Ke(e.url)?`${t}#${We(e.url)}`:e.url})}(e[r],t),i=Ke(r)?`${t}#${We(r)}`:r,o={...e};return delete o[r],o[i]=n,He(o)},r),i=He({...e.graphs,default:n});return He({...e,graphs:i})}async function Wr(e,t){var r,n;const i=null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch,o=null!==(n=null==t?void 0:t.webIdProfile)&&void 0!==n?n:await $r(e),a=(await Promise.allSettled(function(e,t){const r=Tr(t,e),n=Er(t).filter(e=>xr(e,Ct).length>0).map(Cr).concat(r?xr(r,Et):[]).concat(r?xr(r,Pt):[]).filter(e=>e!==z(t));return Array.from(new Set(n))}(e,o).map(e=>$r(e,{fetch:i})))).filter(e=>"fulfilled"===e.status).map(e=>e.value);return{webIdProfile:o,altProfileAll:a}}async function Jr(e,t){return function(e,t){const r=new Set;return[e.webIdProfile,...e.altProfileAll].forEach(e=>{const n=Tr(e,t);null!==n&&xr(n,Ft).forEach(e=>r.add(e))}),Array.from(r)}(await Wr(e,t),e)}function Gr(e,t){if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const r=O(t),n={...e.predicates};return delete n[r],He({...e,predicates:He(n)})}const Vr=(e,t,r)=>{var n,i,o;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const a=O(t);if(!Nr(r)&&!ct(r))throw new ValidValueUrlExpectedError(r);const s=Nr(r)?Cr(r):O(r),c=He(null!==(o=null===(i=null===(n=e.predicates[a])||void 0===n?void 0:n.namedNodes)||void 0===i?void 0:i.filter(e=>e.toLowerCase()!==s.toLowerCase()))&&void 0!==o?o:[]),u=He({...e.predicates[a],namedNodes:c}),l=He({...e.predicates,[a]:u});return He({...e,predicates:l})},Xr=Vr;const Yr=(e,t,r)=>{var n,i;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);if(!Nr(r)&&!ct(r))throw new ValidValueUrlExpectedError(r);const o=O(t),a=null!==(n=e.predicates[o])&&void 0!==n?n:{},s=null!==(i=a.namedNodes)&&void 0!==i?i:[];let c;c=ot(r)?r.value:"string"==typeof r?r:Pr(r)?r.url:Cr(r);const u=He(s.concat(O(c))),l=He({...a,namedNodes:u}),d=He({...e.predicates,[o]:l});return He({...e,predicates:d})},Zr=Yr;function en(e,t,r,n){var i,o,a;if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);const s=O(t),c=null!==(i=e.predicates[s])&&void 0!==i?i:{},u=null!==(o=c.literals)&&void 0!==o?o:{},l=null!==(a=u[n])&&void 0!==a?a:[],d=He(l.concat(r)),h=He({...u,[n]:d}),f=He({...c,literals:h}),p=He({...e.predicates,[s]:f});return He({...e,predicates:p})}const tn=(e,t,r)=>{if(br(e),!ct(t))throw new thing_ValidPropertyUrlExpectedError(t);if(!Nr(r)&&!ct(r))throw new ValidValueUrlExpectedError(r);return Yr(Gr(e,t),t,r)};const rn=(e,t,r)=>(br(e),((e,t,r)=>(br(e),en(e,t,r,tt)))(Gr(e,t),t,r));async function nn(e,t){if(!xn(e))return{resourceAcl:null,fallbackAcl:null};try{const r=await on(e,t);return null===r?{resourceAcl:null,fallbackAcl:await an(e,t)}:{resourceAcl:r,fallbackAcl:null}}catch(e){if(e instanceof AclIsAcrError)return{resourceAcl:null,fallbackAcl:null};throw e}}async function on(e,t){if(!xn(e))return null;try{const r=await $r(e.internal_resourceInfo.aclUrl,t);if(function(e){const t=B(e).type;return Array.isArray(t)&&t.includes(Ot)}(r))throw new AclIsAcrError(e,r);return He({...r,internal_accessTo:U(e)})}catch(e){if(e instanceof AclIsAcrError)throw e;return null}}async function an(e,t){const r=new URL(U(e)),n=r.pathname;if("/"===n)return null;const i=function(e){const t="/"===e.substring(e.length-1)?e.substring(0,e.length-1):e,r=`${e.substring(0,t.lastIndexOf("/"))}/`;return r}(n),o=new URL(i,r.origin).href,a=await $(o,t);if(!xn(a))return null;const s=await on(a,t);return null===s?an(a,t):s}function sn(e){return Er(e).filter(cn)}function cn(e){return xr(e,Tt).includes(gt)}function un(e,t){return e.filter(e=>function(e,t){return xr(e,_t).includes(t)}(e,t))}function ln(e,t){return e.filter(e=>function(e,t){return xr(e,St).includes(t)||xr(e,xt).includes(t)}(e,t))}function dn(e){const t=xr(e,It);return t.includes(pn.write)?{read:t.includes(pn.read),append:!0,write:!0,control:t.includes(pn.control)}:{read:t.includes(pn.read),append:t.includes(pn.append),write:!1,control:t.includes(pn.control)}}function hn(e){return e.reduce((e,t)=>e.write||t.write?{read:e.read||t.read,append:!0,write:!0,control:e.control||t.control}:{read:e.read||t.read,append:e.append||t.append,write:!1,control:e.control||t.control},{read:!1,append:!1,write:!1,control:!1})}function fn(e){return!yt(e.predicates,ee.namedNode(e.url),ee.defaultGraph()).some(e=>!function(e){const{predicate:t}=e,{object:r}=e;if(t.equals(ee.namedNode(Tt))&&r.equals(ee.namedNode(gt)))return!0;if(t.equals(ee.namedNode(_t))||t.equals(ee.namedNode(St))||t.equals(ee.namedNode(xt)))return!0;if(t.equals(ee.namedNode(It))&&Object.values(pn).some(e=>r.equals(ee.namedNode(e))))return!0;if(t.equals(ee.namedNode(bt))||t.equals(ee.namedNode(wt))||t.equals(ee.namedNode(vt)))return!0;if(t.equals(ee.namedNode(At)))return!0;return!1}(e))&&(null===vr(e,_t)&&null===vr(e,St)&&null===vr(e,xt)||(null===vr(e,It)||null===vr(e,bt)&&null===vr(e,wt)&&null===vr(e,vt)))}const pn={read:"http://www.w3.org/ns/auth/acl#Read",append:"http://www.w3.org/ns/auth/acl#Append",write:"http://www.w3.org/ns/auth/acl#Write",control:"http://www.w3.org/ns/auth/acl#Control"};function mn(e){let t=jr();return t=tn(t,Tt,gt),e.read&&(t=Zr(t,It,pn.read)),e.append&&!e.write&&(t=Zr(t,It,pn.append)),e.write&&(t=Zr(t,It,pn.write)),e.control&&(t=Zr(t,It,pn.control)),t}function yn(e,t){return Object.assign(function(e){let t;return t="function"==typeof e.slice?Object.assign(e.slice(),{...e}):{...e},t}(e),{internal_acl:t})}const gn=[bt,vt,wt,At];function _n(e,t,r,n,i){if(!xr(e,r).includes(t)){return[e,mn({read:!1,append:!1,write:!1,control:!1})]}const o=Xr(e,r,t);let a=function(e){let t=jr();function r(e,t,r){return xr(e,r).reduce((e,t)=>Zr(e,r,t),t)}return t=tn(t,Tt,gt),t=r(e,t,_t),t=r(e,t,St),t=r(e,t,xt),t=r(e,t,bt),t=r(e,t,wt),t=r(e,t,vt),t=r(e,t,At),t=r(e,t,It),t}(e);return a=Xr(a,"resource"===i?_t:St,n),"default"===i&&(a=Xr(a,xt,n)),a=tn(a,r,t),gn.filter(e=>e!==r).forEach(e=>{a=Gr(a,e)}),[o,a]}function bn(e,t,r,n,i){let o=e;Er(e).forEach(t=>{const[a,s]=_n(t,i,r,e.internal_accessTo,n);o=Rr(o,a),o=Rr(o,s)});let a=mn(t);a=tn(a,"resource"===n?_t:St,e.internal_accessTo),a=tn(a,r,i);return function(e){return sn(e).filter(fn).reduce(kr,e)}(Rr(o,a))}class AclIsAcrError extends Error{constructor(e,t){super(`[${z(e)}] is governed by Access Control Policies in [${z(t)}] rather than by Web Access Control.`)}}function wn(e){return null!==e.internal_acl.resourceAcl&&U(e)===e.internal_acl.resourceAcl.internal_accessTo&&e.internal_resourceInfo.aclUrl===U(e.internal_acl.resourceAcl)}function vn(e){return null!==e.internal_acl.fallbackAcl}function Sn(e){return He({...Mr(),internal_accessTo:U(e),internal_resourceInfo:{sourceIri:e.internal_resourceInfo.aclUrl,isRawData:!1,linkedResources:{}}})}function xn(e){return"string"==typeof e.internal_resourceInfo.aclUrl}function In(e,t){return wn(e)?function(e,t){const r=sn(e),n=En(un(r,e.internal_accessTo),t);return hn(n.map(dn))}(e.internal_acl.resourceAcl,t):vn(e)?function(e,t){const r=sn(e),n=En(ln(r,e.internal_accessTo),t);return hn(n.map(dn))}(e.internal_acl.fallbackAcl,t):null}function An(e,t,r){return bn(e,r,bt,"resource",t)}function Tn(e,t,r){return bn(e,r,bt,"default",t)}function En(e,t){return function(e,t,r){return e.filter(e=>xr(e,r).includes(t))}(e,t,bt)}function Rn(e,t,r){return bn(e,r,wt,"resource",t)}function kn(e,t,r){return bn(e,r,wt,"default",t)}function jn(e,t){return bn(e,t,vt,"resource",Nt)}function Nn(e,t){return bn(e,t,vt,"default",Nt)}const Cn="http://www.w3.org/ns/solid/acp#",Pn={AccessControlResource:Cn.concat("AccessControlResource"),Matcher:Cn.concat("Matcher"),Policy:Cn.concat("Policy"),PublicAgent:Cn.concat("PublicAgent"),access:Cn.concat("access"),accessControl:Cn.concat("accessControl"),agent:Cn.concat("agent"),allOf:Cn.concat("allOf"),allow:Cn.concat("allow"),anyOf:Cn.concat("anyOf"),apply:Cn.concat("apply"),deny:Cn.concat("deny"),memberAccessControl:Cn.concat("memberAccessControl"),noneOf:Cn.concat("noneOf"),vc:Cn.concat("vc")},On="http://www.w3.org/ns/auth/acl#",Fn={Append:On.concat("Append"),Read:On.concat("Read"),Write:On.concat("Write")};function qn(e){return"object"==typeof e.internal_acp&&null!==e.internal_acp&&"object"==typeof e.internal_acp.acr&&null!==e.internal_acp.acr}function Mn(e){if(!qn(e))throw new Error(`An Access Control Resource for [${U(e)}] is not available. This could be because the current user is not allowed to see it, or because their Pod Server does not support Access Control Resources.`);return e.internal_acp.acr}function $n(e){const t=function(e){const t=Mn(e);return Tr(t,U(t))}(e);return null===t?[]:xr(t,Pn.accessControl)}function Dn(e,t,r){const n=Mn(e);return Array.from(new Set(t.map(e=>{const t=Tr(n,e);return null!==t?xr(t,r):[]}).reduce((e,t)=>e.concat(t),[])))}function Ln(e,t){const r=xr(e,t);return{read:r.includes(Fn.Read),append:r.includes(Fn.Append),write:r.includes(Fn.Write),controlRead:!1,controlWrite:!1}}function Un(e,t,r){const n=Sr(t,Pn.allOf).map(t=>Tr(Mn(e),t)).filter(e=>null!==e),i=n.every(e=>Sr(e,Pn.agent).includes(r)),o=Sr(t,Pn.anyOf).map(t=>Tr(Mn(e),t)).filter(e=>null!==e),a=o.some(e=>Sr(e,Pn.agent).includes(r)),s=Sr(t,Pn.noneOf).map(t=>Tr(Mn(e),t)).filter(e=>null!==e),c=s.some(e=>Sr(e,Pn.agent).includes(r));return n.length+o.length>0&&(0===n.length||i)&&(0===o.length||a)&&(0===s.length||!c)}function zn(e,t,r){const n=function(e){return Ln(e,Pn.allow)}(e),i=function(e){return Ln(e,Pn.deny)}(e);return"control"===r?{read:t.read,append:t.append,write:t.write,controlRead:(t.controlRead||n.read)&&!i.read,controlWrite:(t.controlWrite||n.write)&&!i.write}:{read:(t.read||n.read)&&!i.read,append:(t.append||n.append)&&!i.append,write:(t.write||n.write)&&!i.write,controlRead:t.controlRead,controlWrite:t.controlWrite}}async function Bn(e,t){let r={read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1};const n=function(e){return Dn(e,$n(e),Pn.apply)}(e).map(t=>Tr(Mn(e),t)).filter(e=>null!==e);n.forEach(n=>{Un(e,n,t)&&(r=zn(n,r,"resource"))});const i=function(e){return Dn(e,$n(e),Pn.access)}(e).map(t=>Tr(Mn(e),t)).filter(e=>null!==e);return i.forEach(n=>{Un(e,n,t)&&(r=zn(n,r,"control"))}),r}function Qn(e){return{read:e.read,write:e.write,append:e.append,controlRead:e.control,controlWrite:e.control}}function Hn(e,t,r){return async function(e,t,r,n){const i=r(yn(e,await nn(e,n)),t);return null===i?null:Qn(i)}(e,t,In,r)}async function Kn(e,t){const r=await async function(e,t){if("string"!=typeof e.internal_resourceInfo.aclUrl)return null;try{return await $(e.internal_resourceInfo.aclUrl,t)}catch(e){return null}}(e,t);if(null===r)return null;const n=B(r).type;return Array.isArray(n)&&n.includes(Pn.AccessControlResource)?U(r):null}async function Wn(e,t,r){const n=await $(e,r),i=await async function(e,t){const r=await Kn(e,t);if(null===r)return null;let n;try{n=await $r(r,t)}catch(e){return null}return{...e,internal_acp:{acr:{...n,accessTo:U(e)}}}}(n,r);return null===i?Hn(n,t,r):Bn(i,t)}var Jn=i(945);class JOSEError extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class JWTClaimValidationFailed extends JOSEError{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class JWTExpired extends JOSEError{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class JOSEAlgNotAllowed extends JOSEError{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class JOSENotSupported extends JOSEError{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class JWSInvalid extends JOSEError{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class JWTInvalid extends JOSEError{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class JWKSInvalid extends JOSEError{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class JWKSNoMatchingKey extends JOSEError{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t)}}class JWKSMultipleMatchingKeys extends JOSEError{[Symbol.asyncIterator]=async function*(){};static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class JWKSTimeout extends JOSEError{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}}class JWSSignatureVerificationFailed extends JOSEError{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function Gn(e){const t={__proto__:null};for(const r in e)t[r]={...e[r],alg:r};return t}const Vn=[["verify"],["sign"]];function Xn(e){const t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Vn}}function Yn(e,t){const r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Vn,minRsaBits:2048}}function Zn(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Vn}}function ei(){const e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Vn}}function ti(e){const t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Vn}}const ri=Gn({HS256:Xn(256),HS384:Xn(384),HS512:Xn(512),RS256:Yn(256),RS384:Yn(384),RS512:Yn(512),PS256:Yn(256,32),PS384:Yn(384,48),PS512:Yn(512,64),ES256:Zn("P-256",256),ES384:Zn("P-384",384),ES512:Zn("P-521",512),EdDSA:ei(),Ed25519:ei(),"ML-DSA-44":ti(44),"ML-DSA-65":ti(65),"ML-DSA-87":ti(87)});function ni(e){const t="string"==typeof e?ri[e]:void 0;if(!t)throw new JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const ii=new TextEncoder,oi=new TextDecoder,ai=new TextDecoder("utf-8",{fatal:!0});function si(...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 ci=/[^\x00-\x7f]/;function ui(e){if("string"==typeof e&&e.length>=128){if(ci.test(e))throw new TypeError("non-ASCII string encountered in encode()");return ii.encode(e)}const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function li(e){try{return function(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}const r=atob(e),n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}("string"==typeof e?e:oi.decode(e),!0)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.",{cause:e})}}function di(e){return function(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});const r=[];for(let t=0;t<e.length;t+=32768)r.push(String.fromCharCode.apply(null,e.subarray(t,t+32768)));const n=btoa(r.join(""));return t?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}("string"==typeof e?ii.encode(e):e,!0)}function hi(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function fi(e){return hi(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(hi)}function pi(...e){const t=new Set;for(const r of e)if(r)for(const e of Object.keys(r)){if(t.has(e))return!1;t.add(e)}return!0}function mi(e,t,r){try{return li(e)}catch(e){throw new r(`Failed to base64url decode the ${t}`,{cause:e})}}const yi={__proto__:null,b64:!0};function gi(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`);return void 0===t?void 0:new Set(t)}function _i(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[];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');const o=void 0===r?t:{__proto__:null,...r,...t};for(const t of n.crit){if(!(t in o))throw new JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o[t]&&(!Object.hasOwn(n,t)||void 0===n[t]))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return n.crit}function bi(e,t){if(t.includes("b64")){const t=e.b64;if("boolean"!=typeof t)throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return t}return!0}function wi(e,t){let r,n;try{r=JSON.stringify(t),n=JSON.parse(r)}catch(t){throw new e("JOSE Header is not valid JSON",{cause:t})}if(!hi(n))throw new e("JOSE Header is not a JSON object");return[n,r]}async function vi(e,t,r){const{alg:n,secret:i}=e,o="decrypt"===r||"sign"===r;if(i&&t instanceof Uint8Array)return t;let a,s;if(hi(t)){if(a=function(e){const t=Ci(e);if(void 0!==t.ext&&"boolean"!=typeof t.ext)throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(void 0!==t.key_ops){const e=t.key_ops,r=Array.isArray(e)?[...e]:void 0;if(!r||r.some(e=>"string"!=typeof e)||new Set(r).size!==r.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=r}return t}(t),"string"!=typeof a.kty)throw Ri(n,t,i);if(!(i?"oct"===a.kty&&"string"==typeof a.k:"oct"!==a.kty&&(o?"AKP"===a.kty&&"string"==typeof a.priv||"string"==typeof a.d:void 0===a.d&&void 0===a.priv)))throw new TypeError(i?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${o?"private":"public"} JWK`);if(((e,t,r)=>{const{alg:n}=e;if(void 0!==t.use){const e="sign"===r||"verify"===r?"sig":"enc";if(t.use!==e)throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){const n="encrypt"===r||"decrypt"===r?e.ops?.["encrypt"===r?0:1]:r;if(n&&!t.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}})(e,a,r),"oct"===a.kty)return li(a.k);if(!Object.isFrozen(t)){const{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Ti(t))throw Ri(n,t,i);const e=i?"secret":o?"private":"public";if(t.type!==e&&(i||["secret","public","private"].includes(t.type)))throw new TypeError(`${(e=>e[Symbol.toStringTag])(t)} instances must be of type "${e}" for the ${n} algorithm`);if(Ii(t))return t;if(s=t,"secret"===s.type)return s.export()}Si||=new WeakMap;const c=t;let u=Si.get(c);if(u?.[n])return u[n];if(u||Si.set(c,u={}),s&&"function"==typeof s.toCryptoKey){const t="public"===s.type,r=xi[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:r,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return u[n]=s.toCryptoKey(i,t,e.usages[t?0:1])}return a??=s.export({format:"jwk"}),a.alg=n,u[n]=await Pi(e,a)}let Si;const xi={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};const Ii=e=>{if("CryptoKey"===e?.[Symbol.toStringTag])return!0;try{return e instanceof CryptoKey}catch{return!1}},Ai=e=>"KeyObject"===e?.[Symbol.toStringTag],Ti=e=>Ii(e)||Ai(e);function Ei(e,t,...r){if(r.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}function Ri(e,t,r){const n=["CryptoKey","KeyObject","JSON Web Key"];return r&&n.push("Uint8Array"),new TypeError(Ei(`Key for the ${e} algorithm must be `,t,...n))}const ki=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function ji(e,t){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 Ni(e,t,r){const n=e.algorithm;if(n.name!==t.name)throw ki(t.name);if(t.hash&&n.hash?.name!==t.hash)throw ki(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw ki(t.namedCurve,"algorithm.namedCurve");if(void 0!==t.length&&n.length!==t.length)throw ki(t.length,"algorithm.length");!function(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}(e,r)}function Ci(e){return{__proto__:null,...e}}async function Pi(e,t,r){if(!e.kty.includes(t.kty))throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');const n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!(!t.d&&!t.priv),o={...t,ext:r??t.ext};return"AKP"!==o.kty&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,n,o.ext??!i,t.key_ops??e.usages[i?1:0])}async function Oi(e,t,r,n=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,n,[r])),Ni(e,t,r),e}function Fi(e){return void 0===e?{}:function(e,t,r){let n;try{n=JSON.parse(ai.decode(li(e)))}catch(e){throw new t(r,{cause:e})}if(!hi(n))throw new t(r);return n}(e,JWSInvalid,"JWS Protected Header is invalid")}function qi(e){try{return ui(e)}catch(e){throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters",{cause:e})}}async function Mi(e,t,r,n,i){const{protected:o,header:a,payload:s}=e,c=i??Fi(o);if(!pi(c,a))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const u={...c,...a},l=bi(c,_i(JWSInvalid,yi,t[1],c,u)),{alg:d}=u;if("string"!=typeof d||!d)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(d))throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(l){if("string"!=typeof s)throw new JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof s&&!(s instanceof Uint8Array))throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");const h=l||"string"!=typeof s?s:n(s);let f=!1;"function"==typeof r&&(r=await r(c,e),f=!0);const p=ni(d),m=si(void 0!==o?ui(o):new Uint8Array,ui("."),"string"==typeof h?t[2]??=function(e,t,r){try{return ui(e)}catch(e){throw new r(`The ${t} is not a valid base64url string`,{cause:e})}}(h,"payload",JWSInvalid):h),y=mi(e.signature,"signature",JWSInvalid),g=await vi(p,r,"verify"),_=await Oi(g,p.subtle,"verify");p.minRsaBits&&ji(p.alg,_);let b=!1;try{b=await crypto.subtle.verify(p.signing,_,y,m)}catch(e){throw new JWSSignatureVerificationFailed(void 0,{cause:e})}if(!b)throw new JWSSignatureVerificationFailed;const w={payload:"string"==typeof h?mi(h,"payload",JWSInvalid):h};return void 0!==o&&(w.protectedHeader=c),void 0!==a&&(w.unprotectedHeader=a),f?[{...w,key:g},l]:[w,l]}const $i=e=>Math.floor(e.getTime()/1e3),Di={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Li=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ui="check_failed";function zi(){throw new TypeError("Invalid time period format")}function Bi(e){"string"!=typeof e&&zi();const t=Li.exec(e);(!t||t[4]&&t[1])&&zi();const r=parseFloat(t[2]),n=Math.round(r*Di[t[3][0].toLowerCase()]);return Number.isFinite(n)||zi(),"-"===t[1]||"ago"===t[4]?-n:n}function Qi(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function Hi(e,t){if("string"!=typeof t)throw new TypeError(`"${e}" claim must be a string`)}function Ki(e,t){return"number"==typeof e?Qi(t,e):e instanceof Date?Qi(t,$i(e)):$i(new Date)+Bi(e)}const Wi=e=>{const t=e.toLowerCase();return e.includes("/")?t:`application/${t}`};function Ji(e,t,r=!1){const n=e[t];if(void 0!==n||r){if("number"!=typeof n)throw new JWTClaimValidationFailed(`"${t}" claim must be a number`,e,t,"invalid");return n}}function Gi(e,t){throw new JWTClaimValidationFailed(`unexpected "${t}" claim value`,e,t,Ui)}function Vi(e,t,r={}){let n;try{n=JSON.parse(ai.decode(t))}catch(e){throw new JWTInvalid("JWT Claims Set must be a top-level JSON object",{cause:e})}if(!hi(n))throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");const{typ:i}=r;if(void 0!==i&&("string"!=typeof e.typ||Wi(e.typ)!==Wi(i)))throw new JWTClaimValidationFailed('unexpected "typ" JWT header value',n,"typ",Ui);const{requiredClaims:o=[],issuer:a,subject:s,audience:c,maxTokenAge:u}=r,l=[...o];void 0!==u&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==s&&l.push("sub"),void 0!==a&&l.push("iss");for(const e of new Set(l.reverse()))if(!Object.hasOwn(n,e))throw new JWTClaimValidationFailed(`missing required "${e}" claim`,n,e,"missing");var d,h;void 0!==a&&!(Array.isArray(a)?a:[a]).includes(n.iss)&&Gi(n,"iss"),void 0!==s&&n.sub!==s&&Gi(n,"sub"),void 0!==c&&(d=n.aud,h="string"==typeof c?[c]:c,!("string"==typeof d?h.includes(d):Array.isArray(d)&&h.some(e=>d.includes(e))))&&Gi(n,"aud");const{clockTolerance:f}=r;let p=0;if("string"==typeof f)p=Bi(f);else if(void 0!==f){if("number"!=typeof f)throw new TypeError("Invalid clockTolerance option type");p=f}if(Qi("clockTolerance option",p),p<0)throw new TypeError("Invalid clockTolerance option input");const{currentDate:m}=r,y=Qi("currentDate option",$i(void 0===m?new Date:m)),g=Ji(n,"iat",void 0!==u),_=Ji(n,"nbf");if(void 0!==_&&_>y+p)throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed',n,"nbf",Ui);const b=Ji(n,"exp");if(void 0!==b&&b<=y-p)throw new JWTExpired('"exp" claim timestamp check failed',n,"exp",Ui);if(void 0!==u){const e=y-g,t=Qi("maxTokenAge option","number"==typeof u?u:Bi(u));if(t<0)throw new TypeError("Invalid maxTokenAge option input");if(e-p>t)throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)',n,"iat",Ui);if(e<-p)throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',n,"iat",Ui)}return n}let Xi,Yi;function Zi(e){return Xi.get(e)}async function eo(e,t,r){const[n,i]=await async function(e,t,r){if(e instanceof Uint8Array&&(e=oi.decode(e)),"string"!=typeof e)throw new JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:a}=e.split(".");if(3!==a)throw new JWSInvalid("Invalid Compact JWS");return Mi({payload:i,protected:n,signature:o},t,r,qi)}(e,function(e){return[e&&gi("algorithms",e.algorithms),e?.crit]}(r),t);if(!i)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");const o=Vi(n.protectedHeader,n.payload,r);return{...n,payload:o}}async function to(e,t,r){const n=e.get(t)||e.set(t,{}).get(t),{alg:i}=r;if(void 0===n[i]){const e=Pi(r,t,!0).then(e=>{if("public"!==e.type)throw new JWKSInvalid("JSON Web Key Set members must be public keys");return n[i]=e,e}).catch(t=>{throw n[i]===e&&delete n[i],t});n[i]=e}return n[i]}function ro(e){let t;try{t=structuredClone(e)}catch(e){throw new JWKSInvalid("JSON Web Key Set malformed",{cause:e})}if(!fi(t))throw new JWKSInvalid("JSON Web Key Set malformed");const r=t.keys.map(e=>{const t=Ci(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),n=new WeakMap;return Object.defineProperty(async(e,i)=>{const{alg:o,kid:a}={...e,...i?.header},s="string"==typeof o?ri[o]:void 0;if(!s||s.secret)throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');const c=t.keys.filter((e,t)=>function(e,t,r,n){const{kty:i,key_ops:o,ext:a,kid:s,alg:c,use:u,crv:l}=e;return(void 0===a||"boolean"==typeof a)&&(void 0===o||Array.isArray(o)&&o.every((e,t)=>"string"==typeof e&&o.indexOf(e)===t)&&o.includes("verify"))&&t.kty.includes(i)&&(void 0===n||"string"==typeof n&&n===s)&&(void 0===c?"AKP"!==i:r===c)&&(void 0===u||"sig"===u)&&(!t.crv||l===t.crv)}(r[t],s,o,a)),{0:u,length:l}=c;if(!l)throw new JWKSNoMatchingKey;if(1!==l){const e=new JWKSMultipleMatchingKeys;throw e[Symbol.asyncIterator]=async function*(){for(const e of c)try{yield await to(n,e,s)}catch{}},e}return to(n,u,s)},"jwks",{value:()=>structuredClone(t)})}(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Yi="jose/v6.2.17");const no=Symbol();const io=Symbol();function oo(e,t){return Number.isFinite(e)&&Date.now()<e+t}function ao(e,t,r){if(Number.isNaN(e))throw new TypeError(`"${r}" option must not be NaN`);if("number"==typeof e&&e<0)throw new TypeError(`"${r}" option must not be negative`);return"number"==typeof e?e:t}function so(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");const r=new URL(e.href).href,n=t??{},i=n.timeoutDuration;if("number"==typeof i&&(!Number.isInteger(i)||i<0))throw new TypeError('"timeoutDuration" option must be a non-negative integer');const o="number"==typeof i?i:5e3,a=ao(n.cooldownDuration,3e4,"cooldownDuration"),s=ao(n.cacheMaxAge,6e5,"cacheMaxAge"),c=new Headers(n.headers);Yi&&!c.has("User-Agent")&&c.set("User-Agent",Yi),c.has("accept")||c.set("accept","application/json, application/jwk-set+json");const u=n[no],l=n[io];let d,h,f,p=0,m=0;if(l&&"object"==typeof l){const{uat:e,jwks:t}=l;oo(e,s)&&fi(t)&&(d=e,f=ro(t))}const y=async()=>{if(h&&(typeof WebSocketPair<"u"||typeof navigator<"u"&&"Cloudflare-Workers"===navigator.userAgent||typeof EdgeRuntime<"u"&&"vercel"===EdgeRuntime)&&(h=void 0),!h){const e=++p,t=h=async function(e,t,r,n=fetch){const i=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(e=>{throw"TimeoutError"===e.name?new JWKSTimeout(void 0,{cause:e}):e});if(200!==i.status)throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch(e){throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON",{cause:e})}}(r,c,AbortSignal.timeout(o),u).then(t=>{const r=ro(t);if(e<=m)return;f=r;const n=Date.now();l&&(l.uat=n,l.jwks=t),d=n,m=e}).finally(()=>{h===t&&(h=void 0)})}await h};return Object.defineProperties(async(e,t)=>{(!f||!oo(d,s))&&await y();try{return await f(e,t)}catch(r){if(r instanceof JWKSNoMatchingKey&&!oo(d,a))return await y(),f(e,t);throw r}},{coolingDown:{get:()=>oo(d,a),enumerable:!0},fresh:{get:()=>oo(d,s),enumerable:!0},reload:{value:y,enumerable:!0},reloading:{get:()=>!!h,enumerable:!0},jwks:{value:()=>f?.jwks(),enumerable:!0}})}async function co(e){if(Ai(e)){if("secret"!==e.type)return e.export({format:"jwk"});e=e.export()}if(e instanceof Uint8Array)return{kty:"oct",k:di(e)};if(!Ii(e))throw new TypeError(((e,...t)=>Ei("Key must be ",e,...t))(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const t=await crypto.subtle.exportKey("jwk",e);delete t.ext,delete t.key_ops,delete t.use,"AKP"!==t.kty&&delete t.alg;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return t}async function uo(e,t,r){let[n,i,o,a]=e,s="";if(void 0!==i){const e=wi(JWSInvalid,i);i=e[0],s=di(e[1])}if(void 0!==o&&(o=wi(JWSInvalid,o)[0]),!i&&!o)throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!pi(i,o))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const c={...i,...o};!function(e,t){const{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}(JWSInvalid,i);const u=bi(i,_i(JWSInvalid,yi,a,i,c));u||r?.();const{alg:l}=c;if("string"!=typeof l||!l)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');const d=ni(l);let h,f="",p=n;if(u){const t=e[4];t?(f=t[0]??=di(n),p=t[1]??=ui(f)):(f=di(n),h=ii.encode(`${s}.${f}`))}h??=si(ui(s),ui("."),p);const m=await Oi(await vi(d,t,"sign"),d.subtle,"sign");d.minRsaBits&&ji(d.alg,m);const y={signature:di(new Uint8Array(await crypto.subtle.sign(d.signing,m,h))),payload:f};return i&&(y.protected=s),o&&(y.header=o),[y,u]}const lo=class JWTClaimsBuilder{constructor(e={}){if(!hi(e))throw new TypeError("JWT Claims Set MUST be an object");(Xi||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Hi("iss",e),Zi(this).iss=e,this}setSubject(e){return Hi("sub",e),Zi(this).sub=e,this}setAudience(e){return function(e){if("string"!=typeof e&&(!Array.isArray(e)||Array.from(e).some(e=>"string"!=typeof e)))throw new TypeError('"aud" claim must be a string or an array of strings')}(e),Zi(this).aud=e,this}setJti(e){return Hi("jti",e),Zi(this).jti=e,this}setNotBefore(e){return Zi(this).nbf=Ki(e,"setNotBefore"),this}setExpirationTime(e){return Zi(this).exp=Ki(e,"setExpirationTime"),this}setIssuedAt(e){const t=Zi(this);return t.iat=void 0===e?$i(new Date):"string"==typeof e?Qi("setIssuedAt",$i(new Date)+Bi(e)):Ki(e,"setIssuedAt"),this}};class SignJWT extends lo{#e;setProtectedHeader(e){return function(e,t){if(void 0!==e)throw new TypeError(`${t} can only be called once`)}(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return async function(e,t,r,n,i){const[o]=await uo([e,t,void 0,r],n,i);return`${o.protected}.${o.payload}.${o.signature}`}(function(e){const t=Zi(e);for(const e of["iat","nbf","exp"]){const r=t[e];if("number"==typeof r&&!Number.isFinite(r))throw new TypeError(`"${e}" claim must be a finite number`)}return ii.encode(JSON.stringify(t))}(this),this.#e,t?.crit,e,()=>{throw new JWTInvalid("JWTs MUST NOT use unencoded payload")})}}const ho=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],fo=[[],["deriveBits"]],po=[[],[]];function mo(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:ho,ops:["wrapKey","unwrapKey"]}}function yo(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:r})=>{if("X25519"===t||"x25519"===r)return{name:"X25519"};if("OKP"===e)throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:fo,ops:[void 0,"deriveBits"]}}function go(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:po,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function _o(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:po,ops:["deriveBits","deriveBits"]}}const bo=Gn({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:po,ops:["encrypt","decrypt"]},"RSA-OAEP":mo(1),"RSA-OAEP-256":mo(256),"RSA-OAEP-384":mo(384),"RSA-OAEP-512":mo(512),"ECDH-ES":yo("direct-key-agreement"),"ECDH-ES+A128KW":yo("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":yo("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":yo("key-agreement-with-key-wrapping"),A128KW:go(128),A192KW:go(192),A256KW:go(256),A128GCMKW:go(128,!0),A192GCMKW:go(192,!0),A256GCMKW:go(256,!0),"PBES2-HS256+A128KW":_o(),"PBES2-HS384+A192KW":_o(),"PBES2-HS512+A256KW":_o()}),wo=["encrypt","decrypt"];function vo(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:po,ops:wo,cekBits:e,ivBits:t?128:96,cbc:t}}Gn({A128GCM:vo(128),A192GCM:vo(192),A256GCM:vo(256),"A128CBC-HS256":vo(256,!0),"A192CBC-HS384":vo(384,!0),"A256CBC-HS512":vo(512,!0)});const So='"alg" (Algorithm)';function xo(e='JWK "alg" (Algorithm) Parameter'){throw new JOSENotSupported(`Invalid or unsupported ${e} value`)}function Io(e){const t=e?.modulusLength??2048;if("number"!=typeof t||!Number.isInteger(t)||t<2048)throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function Ao(e,t){const r=function(e){if(void 0!==e&&"boolean"!=typeof e)throw new TypeError('"extractable" option must be a boolean');return e}(t?.extractable),n=function(e,t){return("string"==typeof e?ri[e]??bo[e]:void 0)??xo(t)}(e,So);let i;if(n.secret&&xo(So),n.resolve){const e=t?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(e))throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");i=n.resolve({crv:e})}else{if(void 0!==n.crv&&void 0!==t?.crv&&t.crv!==n.crv)throw new JOSENotSupported(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${n.crv}`);i="RSA"===n.kty[0]?{...n.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:Io(t)}:n.subtle}return crypto.subtle.generateKey(i,r??!1,[...n.usages[1],...n.usages[0]])}const To=new Uint8Array(16);const Eo=[];for(let e=0;e<256;++e)Eo.push((e+256).toString(16).slice(1));function Ro(e,t=0){return(Eo[e[t+0]]+Eo[e[t+1]]+Eo[e[t+2]]+Eo[e[t+3]]+"-"+Eo[e[t+4]]+Eo[e[t+5]]+"-"+Eo[e[t+6]]+Eo[e[t+7]]+"-"+Eo[e[t+8]]+Eo[e[t+9]]+"-"+Eo[e[t+10]]+Eo[e[t+11]]+Eo[e[t+12]]+Eo[e[t+13]]+Eo[e[t+14]]+Eo[e[t+15]]).toLowerCase()}const ko=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){e=e||{};const n=e.random??e.rng?.()??crypto.getRandomValues(To);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 Ro(n)}(e,t,r):crypto.randomUUID()},jo="solidClientAuthn:",No=["ES256","RS256"],Co="error",Po="login",Oo="logout",Fo="newRefreshToken",qo="sessionExpired",Mo="sessionExtended",$o="sessionRestore",Do="timeoutSet",Lo=["openid","offline_access","webid"];class AggregateHandler{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 Uo(e,t,r,n){let i,o;try{const{payload:o}=await eo(e,so(new URL(t)),{issuer:r,audience:n});i=o}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof i.azp&&(o=i.azp),"string"==typeof i.webid)return{webId:i.webid,clientId:o};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:o}}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 zo(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 Bo(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 AuthorizationCodeWithPkceOidcHandlerBase{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,o;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,o=!0,"boolean"==typeof i?Boolean(i):Boolean(o)).toString()})]),this.redirector.redirect(n,{handleRedirect:e.handleRedirect})}}class GeneralLogoutHandler{sessionInfoManager;constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class IRpLogoutHandler{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 IWaterfallLogoutHandler{handlers;constructor(e,t){this.handlers=[new GeneralLogoutHandler(e),new IRpLogoutHandler(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 Qo(){return{isLoggedIn:!1,sessionId:ko(),fetch:(...e)=>fetch(...e)}}async function Ho(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}class SessionInfoManagerBase{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 Ho(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 Ko({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 Wo(e){try{return new URL(e),!0}catch{return!1}}async function Jo(e,t,r,n){let i;if(function(e,t){return t.scopesSupported.includes("webid")&&void 0!==e.clientId&&Wo(e.clientId)}(e,t))i={clientId:e.clientId,clientName:e.clientName,clientType:"solid-oidc"};else{if(!function(e){return void 0!==e.clientId&&!Wo(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 o={clientId:i.clientId,clientType:i.clientType};return"static"===i.clientType&&(o.clientSecret=i.clientSecret),i.clientName&&(o.clientName=i.clientName),await r.setForUser(e.sessionId,o),i}const Go=(e,t)=>fetch(e,t);class dist_ClientAuthentication{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=Go;logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===t?.logoutType?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=Go,delete this.boundLogout};getSessionInfo=async e=>this.sessionInfoManager.get(e);getAllSessionInfo=async()=>this.sessionInfoManager.getAll()}async function Vo(e,t,r){try{const[n,i,o,a,s]=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:o,issuerConfig:await r.fetchConfig(n),dpop:"true"===a,keepAlive:"string"!=typeof s||"true"===s}}catch(t){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${e}]: ${t}`)}}class StorageUtility{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 InMemoryStorage{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 ConfigurationError extends Error{constructor(e){super(e)}}Error;class InvalidResponseError extends Error{missingFields;constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class OidcProviderError extends Error{error;errorDescription;constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function Xo(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function Yo(e,t,r){return new SignJWT({htu:Xo(e),htm:t.toUpperCase(),jti:ko()}).setProtectedHeader({alg:No[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function Zo(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 Yo(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 ea(e,t,r,n,i=fetch){return i(t,await Zo(t.toString(),e,n,r))}const ta=e=>void 0!==e?e-5>0?e-5:e:600;function ra(e,t){let r,n=e;const i=t?.refreshOptions,o=t?.eventEmitter;if(void 0!==t&&void 0!==i){const e=async()=>{try{const{accessToken:a,refreshToken:s,expiresIn:c}=await async function(e,t,r){const n=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return r?.emit(Mo,n.expiresIn??600),{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn}}(i,t.dpopKey,o);n=a,void 0!==s&&(i.refreshToken=s),clearTimeout(r),r=setTimeout(e,1e3*ta(c)),t.eventEmitter?.emit(Do,r)}catch(e){e instanceof OidcProviderError&&(o?.emit(Co,e.error,e.errorDescription),o?.emit(qo)),e instanceof InvalidResponseError&&e.missingFields.includes("access_token")&&o?.emit(qo)}};r=setTimeout(e,1e3*ta(t.expiresIn)),o?.emit(Do,r)}else if(void 0!==o){const e=setTimeout(()=>{o.emit(qo)},1e3*ta(t?.expiresIn));o.emit(Do,e)}return async(e,r)=>{let i=await ea(n,e,r,t?.dpopKey,t?.fetch);const o=!i.ok&&(a=i.status,![401,403].includes(a));var a;if(i.ok||o)return i;return i.url!==e&&void 0!==t?.dpopKey&&(i=await ea(n,i.url,r,t.dpopKey,t.fetch)),i}}class InvalidTokenError extends Error{}function na(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}(t)}catch(e){return atob(t)}}InvalidTokenError.prototype.name="InvalidTokenError";var ia,oa,aa,sa={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},ca=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(ca||{});(aa=ca||(ca={})).reset=function(){ia=3,oa=sa},aa.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");ia=e},aa.setLogger=function(e){oa=e};var ua=class _Logger{constructor(e){this._name=e}debug(...e){ia>=4&&oa.debug(_Logger._format(this._name,this._method),...e)}info(...e){ia>=3&&oa.info(_Logger._format(this._name,this._method),...e)}warn(...e){ia>=2&&oa.warn(_Logger._format(this._name,this._method),...e)}error(...e){ia>=1&&oa.error(_Logger._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const r=new _Logger(`${e}.${t}`);return r.debug("begin"),r}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(e,...t){ia>=4&&oa.debug(_Logger._format(e),...t)}static info(e,...t){ia>=3&&oa.info(_Logger._format(e),...t)}static warn(e,...t){ia>=2&&oa.warn(_Logger._format(e),...t)}static error(e,...t){ia>=1&&oa.error(_Logger._format(e),...t)}};ca.reset();var la=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${r+1}`);let i;try{i=na(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}(e)}catch(e){throw ua.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,r){const n=`${fa.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${fa.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,(new TextEncoder).encode(n));return`${n}.${fa.encodeBase64Url(new Uint8Array(i))}`}static async generateSignedJwtWithHmac(e,t,r){const n=`${fa.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${fa.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign("HMAC",r,(new TextEncoder).encode(n));return`${n}.${fa.encodeBase64Url(new Uint8Array(i))}`}},da=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),ha=class _CryptoUtils{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^_CryptoUtils._randomWord()&15>>+e/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return _CryptoUtils.generateUUIDv4()+_CryptoUtils.generateUUIDv4()+_CryptoUtils.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return da(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw ua.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return da(r)}static async hash(e,t){const r=(new TextEncoder).encode(t),n=await crypto.subtle.digest(e,r);return new Uint8Array(n)}static async customCalculateJwkThumbprint(e){let t;switch(e.kty){case"RSA":t={e:e.e,kty:e.kty,n:e.n};break;case"EC":t={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":t={crv:e.crv,kty:e.kty,x:e.x};break;case"oct":t={crv:e.k,kty:e.kty};break;default:throw new Error("Unknown jwk type")}const r=await _CryptoUtils.hash("SHA-256",JSON.stringify(t));return _CryptoUtils.encodeBase64Url(r)}static async generateDPoPProof({url:e,accessToken:t,httpMethod:r,keyPair:n,nonce:i}){let o,a;const s={jti:window.crypto.randomUUID(),htm:null!=r?r:"GET",htu:e,iat:Math.floor(Date.now()/1e3)};t&&(o=await _CryptoUtils.hash("SHA-256",t),a=_CryptoUtils.encodeBase64Url(o),s.ath=a),i&&(s.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",n.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await la.generateSignedJwt(t,s,n.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(e){try{const t=await crypto.subtle.exportKey("jwk",e.publicKey);return await _CryptoUtils.customCalculateJwkThumbprint(t)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(e,t,r,n="HS256"){const i=Math.floor(Date.now()/1e3),o={alg:n,typ:"JWT"},a={iss:e,sub:e,aud:r,jti:_CryptoUtils.generateUUIDv4(),exp:i+300,iat:i},s={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[n];if(!s)throw new Error(`Unsupported algorithm: ${n}. Supported algorithms are: HS256, HS384, HS512`);const c=new TextEncoder,u=await crypto.subtle.importKey("raw",c.encode(t),{name:"HMAC",hash:s},!1,["sign"]);return await la.generateSignedJwtWithHmac(o,a,u)}};ha.encodeBase64Url=e=>da(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var fa=ha,pa=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new ua(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},ma=class _Timer extends pa{constructor(){super(...arguments),this._logger=new ua(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-_Timer.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=_Timer.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const r=_Timer.getEpochTime()+e;if(this.expiration===r&&this._timerHandle)return void t.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),t.debug("using duration",e),this._expiration=r;const n=Math.min(e,5);this._timerHandle=setInterval(this._callback,1e3*n)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},ya=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const r=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(r.slice(1))}},ga=";",_a=class extends Error{constructor(e,t){var r,n,i;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw ua.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(r=e.error_description)?r:null,this.error_uri=null!=(n=e.error_uri)?n:null,this.state=e.userState,this.session_state=null!=(i=e.session_state)?i:null,this.url_state=e.url_state}},ba=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},wa=class{constructor(){this._logger=new ua("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},va=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},Sa=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new ua("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...n}=t;if(!r)return await fetch(e,n);const i=new AbortController,o=setTimeout(()=>i.abort(),1e3*r);try{return await fetch(e,{...t,signal:i.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new ba("Network timed out");throw e}finally{clearTimeout(o)}}async getJson(e,{token:t,credentials:r,timeoutInSeconds:n}={}){const i=this._logger.create("getJson"),o={Accept:this._contentTypes.join(", ")};let a;t&&(i.debug("token passed, setting Authorization header"),o.Authorization="Bearer "+t),this._appendExtraHeaders(o);try{i.debug("url:",e),a=await this.fetchWithTimeout(e,{method:"GET",headers:o,timeoutInSeconds:n,credentials:r})}catch(e){throw i.error("Network Error"),e}i.debug("HTTP response received, status",a.status);const s=a.headers.get("Content-Type");if(s&&!this._contentTypes.find(e=>s.startsWith(e))&&i.throw(new Error(`Invalid response Content-Type: ${null!=s?s:"undefined"}, from URL: ${e}`)),a.ok&&this._jwtHandler&&(null==s?void 0:s.startsWith("application/jwt")))return await this._jwtHandler(await a.text());let c;try{c=await a.json()}catch(e){if(i.error("Error parsing JSON response",e),a.ok)throw e;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(i.error("Error from server:",c),c.error)throw new _a(c);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:n,initCredentials:i,extraHeaders:o}){const a=this._logger.create("postForm"),s={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...o};let c;void 0!==r&&(s.Authorization="Basic "+r),this._appendExtraHeaders(s);try{a.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:s,body:t,timeoutInSeconds:n,credentials:i})}catch(e){throw a.error("Network error"),e}a.debug("HTTP response received, status",c.status);const u=c.headers.get("Content-Type");if(u&&!this._contentTypes.find(e=>u.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=u?u:"undefined"}, from URL: ${e}`);const l=await c.text();let d={};if(l)try{d=JSON.parse(l)}catch(e){if(a.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(a.error("Error from server:",d),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new va(e,`${JSON.stringify(d)}`)}if(d.error)throw new _a(d,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),n=["accept","content-type"],i=["authorization"];0!==r.length&&r.forEach(r=>{if(n.includes(r.toLocaleLowerCase()))return void t.warn("Protected header could not be set",r,n);if(i.includes(r.toLocaleLowerCase())&&Object.keys(e).includes(r))return void t.warn("Header could not be overridden",r,i);const o="function"==typeof this._extraHeaders[r]?this._extraHeaders[r]():this._extraHeaders[r];o&&""!==o&&(e[r]=o)})}},xa=class{constructor(e){this._settings=e,this._logger=new ua("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new Sa(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const r=this._logger.create(`_getMetadataProperty('${e}')`),n=await this.getMetadata();if(r.debug("resolved"),void 0===n[e]){if(!0===t)return void r.warn("Metadata does not contain optional property");r.throw(new Error("Metadata does not contain property "+e))}return n[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const r=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}},Ia=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new ua("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let r=0;r<e;r++){const e=await this._store.key(r);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},Aa=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:n,metadataSeed:i,client_id:o,client_secret:a,response_type:s="code",scope:c="openid",redirect_uri:u,post_logout_redirect_uri:l,client_authentication:d="client_secret_post",token_endpoint_auth_signing_alg:h="HS256",prompt:f,display:p,max_age:m,ui_locales:y,acr_values:g,resource:_,response_mode:b,filterProtocolClaims:w=!0,loadUserInfo:v=!1,requestTimeoutInSeconds:S,staleStateAgeInSeconds:x=900,mergeClaimsStrategy:I={array:"replace"},disablePKCE:A=!1,stateStore:T,revokeTokenAdditionalContentTypes:E,fetchRequestCredentials:R,refreshTokenAllowedScope:k,extraQueryParams:j={},extraTokenParams:N={},extraHeaders:C={},dpop:P,omitScopeWhenRequesting:O=!1}){var F;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=r,this.metadataSeed=i,this.signingKeys=n,this.client_id=o,this.client_secret=a,this.response_type=s,this.scope=c,this.redirect_uri=u,this.post_logout_redirect_uri=l,this.client_authentication=d,this.token_endpoint_auth_signing_alg=h,this.prompt=f,this.display=p,this.max_age=m,this.ui_locales=y,this.acr_values=g,this.resource=_,this.response_mode=b,this.filterProtocolClaims=null==w||w,this.loadUserInfo=!!v,this.staleStateAgeInSeconds=x,this.mergeClaimsStrategy=I,this.omitScopeWhenRequesting=O,this.disablePKCE=!!A,this.revokeTokenAdditionalContentTypes=E,this.fetchRequestCredentials=R||"same-origin",this.requestTimeoutInSeconds=S,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new wa;this.stateStore=new Ia({store:e})}if(this.refreshTokenAllowedScope=k,this.extraQueryParams=j,this.extraTokenParams=N,this.extraHeaders=C,this.dpop=P,this.dpop&&!(null==(F=this.dpop)?void 0:F.store))throw new Error("A DPoPStore is required when dpop is enabled")}},Ta=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new ua("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=la.decode(e);return t.debug("JWT decoding successful"),r}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new Sa(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const n=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",n),n}},Ea=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new ua("TokenClient"),this._jsonService=new Sa(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:i,...o}){const a=this._logger.create("exchangeCode");r||a.throw(new Error("A client_id is required")),t||a.throw(new Error("A redirect_uri is required")),o.code||a.throw(new Error("A code is required"));const s=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(o))null!=t&&s.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==n)throw a.throw(new Error("A client_secret is required")),null;let c;const u=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=fa.generateBasicAuth(r,n);break;case"client_secret_post":s.append("client_id",r),n&&s.append("client_secret",n);break;case"client_secret_jwt":{const e=await fa.generateClientAssertionJwt(r,n,u,this._settings.token_endpoint_auth_signing_alg);s.append("client_id",r),s.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),s.append("client_assertion",e);break}}a.debug("got token endpoint");const l=await this._jsonService.postForm(u,{body:s,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return a.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:n=this._settings.scope,...i}){const o=this._logger.create("exchangeCredentials");t||o.throw(new Error("A client_id is required"));const a=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||a.set("scope",n);for(const[e,t]of Object.entries(i))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw o.throw(new Error("A client_secret is required")),null;let s;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":s=fa.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r);break;case"client_secret_jwt":{const e=await fa.generateClientAssertionJwt(t,r,c,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:a,basicAuth:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return o.debug("got response"),u}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:i,...o}){const a=this._logger.create("exchangeRefreshToken");t||a.throw(new Error("A client_id is required")),o.refresh_token||a.throw(new Error("A refresh_token is required"));const s=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(o))Array.isArray(t)?t.forEach(t=>s.append(e,t)):null!=t&&s.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw a.throw(new Error("A client_secret is required")),null;let c;const u=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=fa.generateBasicAuth(t,r);break;case"client_secret_post":s.append("client_id",t),r&&s.append("client_secret",r);break;case"client_secret_jwt":{const e=await fa.generateClientAssertionJwt(t,r,u,this._settings.token_endpoint_auth_signing_alg);s.append("client_id",t),s.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),s.append("client_assertion",e);break}}a.debug("got token endpoint");const l=await this._jsonService.postForm(u,{body:s,basicAuth:c,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return a.debug("got response"),l}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const i=new URLSearchParams;for(const[t,r]of Object.entries(e))null!=r&&i.set(t,r);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:i,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),r.debug("got response")}},Ra=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new ua("ResponseValidator"),this._userInfoService=new Ta(this._settings,this._metadataService),this._tokenClient=new Ea(this._settings,this._metadataService)}async validateSigninResponse(e,t,r){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t,r),n.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e,"",t.nonce),n.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse"),n=e.isOpenId&&!!e.id_token;n&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,n),r.debug("claims processed")}async validateRefreshResponse(e,t){const r=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),r.debug("claims processed")}validateSignoutResponse(e,t){const r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new _a(e)}_processSigninState(e,t){const r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new _a(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const n=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void n.debug("not loading user info");n.debug("loading user info");const i=await this._userInfoService.getClaims(e.access_token);n.debug("user info claims received from user info endpoint"),r&&i.sub!==e.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(i)),n.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,r){const n=this._logger.create("_processCode");if(e.code){n.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:r,...t.extraTokenParams});Object.assign(e,i)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t,r){var n;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const o=la.decode(null!=(n=e.id_token)?n:"");if(o.sub||i.throw(new Error("ID Token is missing a subject claim")),r&&o.nonce!==r&&i.throw(new Error("nonce in id_token does not match nonce in client storage")),t){const e=la.decode(t);o.sub!==e.sub&&i.throw(new Error("sub in id_token does not match current sub")),o.auth_time&&o.auth_time!==e.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),o.azp&&o.azp!==e.azp&&i.throw(new Error("azp in id_token does not match original azp")),!o.azp&&e.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=o}},ka=class _State{constructor(e){this.id=e.id||fa.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=ma.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new ua("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(e){return ua.createStatic("State","fromStorageString"),Promise.resolve(new _State(JSON.parse(e)))}static async clearStaleState(e,t){const r=ua.createStatic("State","clearStaleState"),n=ma.getEpochTime()-t,i=await e.getAllKeys();r.debug("got keys",i);for(let t=0;t<i.length;t++){const o=i[t],a=await e.get(o);let s=!1;if(a)try{const e=await _State.fromStorageString(a);r.debug("got item from key:",o,e.created),e.created<=n&&(s=!0)}catch(e){r.error("Error parsing state for key:",o,e),s=!0}else r.debug("no item in storage for key:",o),s=!0;s&&(r.debug("removed item for key:",o),e.remove(o))}}},ja=class _SigninState extends ka{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo,this.nonce=e.nonce}static async create(e){const t=!0===e.code_verifier?fa.generateCodeVerifier():e.code_verifier||void 0,r=t?await fa.generateCodeChallenge(t):void 0;return new _SigninState({...e,code_verifier:t,code_challenge:r})}toStorageString(){return new ua("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo,nonce:this.nonce})}static fromStorageString(e){ua.createStatic("SigninState","fromStorageString");const t=JSON.parse(e);return _SigninState.create(t)}},Na=class _SigninRequest{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:t,client_id:r,redirect_uri:n,response_type:i,scope:o,state_data:a,response_mode:s,request_type:c,client_secret:u,nonce:l,url_state:d,resource:h,skipUserInfo:f,extraQueryParams:p,extraTokenParams:m,disablePKCE:y,dpopJkt:g,omitScopeWhenRequesting:_,...b}){if(!e)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!n)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!t)throw this._logger.error("create: No authority passed"),new Error("authority");const w=await ja.create({data:a,request_type:c,url_state:d,code_verifier:!y,client_id:r,authority:t,redirect_uri:n,response_mode:s,client_secret:u,scope:o,extraTokenParams:m,skipUserInfo:f,nonce:l}),v=new URL(e);v.searchParams.append("client_id",r),v.searchParams.append("redirect_uri",n),v.searchParams.append("response_type",i),_||v.searchParams.append("scope",o),l&&v.searchParams.append("nonce",l),g&&v.searchParams.append("dpop_jkt",g);let S=w.id;if(d&&(S=`${S}${ga}${d}`),v.searchParams.append("state",S),w.code_challenge&&(v.searchParams.append("code_challenge",w.code_challenge),v.searchParams.append("code_challenge_method","S256")),h){(Array.isArray(h)?h:[h]).forEach(e=>v.searchParams.append("resource",e))}for(const[e,t]of Object.entries({response_mode:s,...b,...p}))null!=t&&v.searchParams.append(e,t.toString());return new _SigninRequest({url:v.href,state:w})}};Na._logger=new ua("SigninRequest");var Ca=Na,Pa=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(ga);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(ga))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-ma.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+ma.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},Oa=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:n,extraQueryParams:i,request_type:o,client_id:a,url_state:s}){if(this._logger=new ua("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(r&&c.searchParams.append("id_token_hint",r),a&&c.searchParams.append("client_id",a),n&&(c.searchParams.append("post_logout_redirect_uri",n),t||s)){this.state=new ka({data:t,request_type:o,url_state:s});let e=this.state.id;s&&(e=`${e}${ga}${s}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...i}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},Fa=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(ga);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(ga))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},qa=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],Ma=["sub","iss","aud","exp","iat"],$a=class{constructor(e){this._settings=e,this._logger=new ua("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:qa;for(const r of e)Ma.includes(r)||delete t[r]}return t}mergeClaims(e,t){const r={...e};for(const[e,n]of Object.entries(t))if(r[e]!==n)if(Array.isArray(r[e])||Array.isArray(n))if("replace"==this._settings.mergeClaimsStrategy.array)r[e]=n;else{const t=Array.isArray(r[e])?r[e]:[r[e]];for(const e of Array.isArray(n)?n:[n])t.includes(e)||t.push(e);r[e]=t}else"object"==typeof r[e]&&"object"==typeof n?r[e]=this.mergeClaims(r[e],n):r[e]=n;return r}},Da=class{constructor(e,t){this.keys=e,this.nonce=t}},La=class{constructor(e,t){this._logger=new ua("OidcClient"),this.settings=e instanceof Aa?e:new Aa(e),this.metadataService=null!=t?t:new xa(this.settings),this._claimsService=new $a(this.settings),this._validator=new Ra(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Ea(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:n,id_token_hint:i,login_hint:o,skipUserInfo:a,nonce:s,url_state:c,response_type:u=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:f=this.settings.display,max_age:p=this.settings.max_age,ui_locales:m=this.settings.ui_locales,acr_values:y=this.settings.acr_values,resource:g=this.settings.resource,response_mode:_=this.settings.response_mode,extraQueryParams:b=this.settings.extraQueryParams,extraTokenParams:w=this.settings.extraTokenParams,dpopJkt:v,omitScopeWhenRequesting:S=this.settings.omitScopeWhenRequesting}){const x=this._logger.create("createSigninRequest");if("code"!==u)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const I=await this.metadataService.getAuthorizationEndpoint();x.debug("Received authorization endpoint",I);const A=await Ca.create({url:I,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:u,scope:l,state_data:e,url_state:c,prompt:h,display:f,max_age:p,ui_locales:m,id_token_hint:i,login_hint:o,acr_values:y,dpopJkt:v,resource:g,request:t,request_uri:r,extraQueryParams:b,extraTokenParams:w,request_type:n,response_mode:_,client_secret:this.settings.client_secret,skipUserInfo:a,nonce:s,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:S});await this.clearStaleState();const T=A.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),A}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),n=new Pa(ya.readParams(e,this.settings.response_mode));if(!n.state)throw r.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[t?"remove":"get"](n.state);if(!i)throw r.throw(new Error("No matching state found in storage")),null;return{state:await ja.fromStorageString(i),response:n}}async processSigninResponse(e,t,r=!0){const n=this._logger.create("processSigninResponse"),{state:i,response:o}=await this.readSigninResponseState(e,r);if(n.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(o,i,t)}catch(e){if(!(e instanceof va&&this.settings.dpop))throw e;{const r=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=r,await this._validator.validateSigninResponse(o,i,t)}}return o}async getDpopProof(e,t){let r,n;return(await e.getAllKeys()).includes(this.settings.client_id)?(n=await e.get(this.settings.client_id),n.nonce!==t&&t&&(n.nonce=t,await e.set(this.settings.client_id,n))):(r=await fa.generateDPoPKeys(),n=new Da(r,t),await e.set(this.settings.client_id,n)),await fa.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:n={}}){const i=await this._tokenClient.exchangeCredentials({username:e,password:t,...n}),o=new Pa(new URLSearchParams);return Object.assign(o,i),await this._validator.validateCredentialsResponse(o,r),o}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:i,extraTokenParams:o}){var a;const s=this._logger.create("useRefreshToken");let c,u;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(a=e.scope)?void 0:a.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:e}}try{u=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:i,...o})}catch(a){if(!(a instanceof va&&this.settings.dpop))throw a;i.DPoP=await this.getDpopProof(this.settings.dpop.store,a.nonce),u=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:i,...o})}const l=new Pa(new URLSearchParams);return Object.assign(l,u),s.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:n,url_state:i,post_logout_redirect_uri:o=this.settings.post_logout_redirect_uri,extraQueryParams:a=this.settings.extraQueryParams}={}){const s=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw s.throw(new Error("No end session endpoint")),null;s.debug("Received end session endpoint",c),r||!o||t||(r=this.settings.client_id);const u=new Oa({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:o,state_data:e,extraQueryParams:a,request_type:n,url_state:i});await this.clearStaleState();const l=u.state;return l&&(s.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),u}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),n=new Fa(ya.readParams(e,this.settings.response_mode));if(!n.state){if(r.debug("No state in response"),n.error)throw r.warn("Response was error:",n.error),new _a(n);return{state:void 0,response:n}}const i=await this.settings.stateStore[t?"remove":"get"](n.state);if(!i)throw r.throw(new Error("No matching state found in storage")),null;return{state:await ka.fromStorageString(i),response:n}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:n}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,r)):t.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),ka.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}};function Ua(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 za(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,No.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"]},o=await fetch(t.registrationEndpoint.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(o.ok){const t=await o.json();return Ua(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===o.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 o.json(),e),new Error(`Dynamic client registration failed: the server returned ${o.status} ${o.statusText} - ${await o.text()}`)}function Ba(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function Qa(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new OidcProviderError(`Token endpoint returned error [${e.error}]${Ba(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,Ba(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 InvalidResponseError(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new InvalidResponseError(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new InvalidResponseError(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new InvalidResponseError(["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 Ha(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 o;n&&(o=await async function(e=!1){const{privateKey:t,publicKey:r}=await Ao(No[0],{extractable:e}),n={privateKey:t,publicKey:await co(r)};return[n.publicKey.alg]=No,n}(!1),i.DPoP=await Yo(e.tokenEndpoint,"POST",o)),t.clientSecret&&(i.Authorization=`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`);const a={grant_type:r.grantType,redirect_uri:r.redirectUrl,code:r.code,code_verifier:r.codeVerifier,client_id:t.clientId},s={method:"POST",headers:i,body:new URLSearchParams(a).toString()},c=await fetch(e.tokenEndpoint,s),u=Qa(await c.json(),n),{webId:l,clientId:d}=await Uo(u.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:(h=u,void 0!==h.refresh_token&&"string"==typeof h.refresh_token?u.refresh_token:void 0),webId:l,clientId:d,dpopKey:o,expiresIn:u.expires_in};var h}async function Ka(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 o={};void 0!==n&&(o={DPoP:await Yo(t.tokenEndpoint,"POST",n)});let a={};void 0!==r.clientSecret?a={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 s=await fetch(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(i).toString(),headers:{...o,...a,"Content-Type":"application/x-www-form-urlencoded"}});let c;try{c=await s.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const u=Qa(c,void 0!==n),{webId:l}=await Uo(u.id_token,t.jwksUri,t.issuer,r.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:"string"==typeof u.refresh_token?u.refresh_token:void 0,webId:l,dpopKey:n,expiresIn:u.expires_in}}class ClientRegistrar{constructor(e){this.storageUtility=e}getClient(e,t){return E(this,void 0,void 0,function*(){const[r,n,i,o]=yield Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]);if(r)return{clientId:r,clientSecret:n,clientName:i,clientType:o};try{const r=yield za(e,t),n={clientId:r.clientId,clientType:"dynamic"};return r.clientSecret&&(n.clientSecret=r.clientSecret),r.idTokenSignedResponseAlg&&(n.idTokenSignedResponseAlg=r.idTokenSignedResponseAlg),yield this.storageUtility.setForUser(e.sessionId,n,{secure:!1}),r}catch(e){throw new Error(`Client registration failed: [${e}]`,{cause:e})}})}}const Wa="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Ja="http://www.w3.org/2001/XMLSchema#",Ga="http://www.w3.org/2000/10/swap/",Va={xsd:{decimal:`${Ja}decimal`,boolean:`${Ja}boolean`,double:`${Ja}double`,integer:`${Ja}integer`,string:`${Ja}string`},rdf:{type:`${Wa}type`,nil:`${Wa}nil`,first:`${Wa}first`,rest:`${Wa}rest`,langString:`${Wa}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${Ga}reify#forSome`,forAll:`${Ga}reify#forAll`},log:{implies:`${Ga}log#implies`,isImpliedBy:`${Ga}log#isImpliedBy`}},{rdf:Xa,xsd:Ya}=Va;let Za,es=0;const ts={namedNode:os,blankNode:as,variable:cs,literal:ss,defaultGraph:function(){return Za},quad:us,triple:us,fromTerm:ls,fromQuad:ds},rs=ts;class N3DataFactory_Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof N3DataFactory_Term?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 N3DataFactory_NamedNode extends N3DataFactory_Term{get termType(){return"NamedNode"}}class N3DataFactory_Literal extends N3DataFactory_Term{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 N3DataFactory_NamedNode(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?Ya.string:Xa.langString}equals(e){return e instanceof N3DataFactory_Literal?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 N3DataFactory_BlankNode extends N3DataFactory_Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class N3DataFactory_Variable extends N3DataFactory_Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}function ns(e,t,r){if(t=t||ts,!e)return t.defaultGraph();switch(e[0]){case"?":return t.variable(e.substr(1));case"_":return t.blankNode(e.substr(2));case'"':if(t===ts)return new N3DataFactory_Literal(e);if('"'===e[e.length-1])return t.literal(e.substr(1,e.length-2));const n=e.lastIndexOf('"',e.length-1);return t.literal(e.substr(1,n-1),"@"===e[n+1]?e.substr(n+2):t.namedNode(e.substr(n+3)));case"[":e=JSON.parse(e);break;default:if(!r||!Array.isArray(e))return t.namedNode(e)}return t.quad(ns(e[0],t,!0),ns(e[1],t,!0),ns(e[2],t,!0),e[3]&&ns(e[3],t,!0))}function is(e,t){if("string"==typeof e)return e;if(e instanceof N3DataFactory_Term&&"Quad"!==e.termType)return e.id;if(!e)return Za.id;switch(e.termType){case"NamedNode":return e.value;case"BlankNode":return`_:${e.value}`;case"Variable":return`?${e.value}`;case"DefaultGraph":return"";case"Literal":return`"${e.value}"${e.language?`@${e.language}`:e.datatype&&e.datatype.value!==Ya.string?`^^${e.datatype.value}`:""}`;case"Quad":const r=[is(e.subject,!0),is(e.predicate,!0),is(e.object,!0)];return e.graph&&"DefaultGraph"!==e.graph.termType&&r.push(is(e.graph,!0)),t?r:JSON.stringify(r);default:throw new Error(`Unexpected termType: ${e.termType}`)}}Za=new class N3DataFactory_DefaultGraph extends N3DataFactory_Term{constructor(){return super(""),Za||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};class N3DataFactory_Quad extends N3DataFactory_Term{constructor(e,t,r,n){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=n||Za}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 os(e){return new N3DataFactory_NamedNode(e)}function as(e){return new N3DataFactory_BlankNode(e||"n3-"+es++)}function ss(e,t){if("string"==typeof t)return new N3DataFactory_Literal(`"${e}"@${t.toLowerCase()}`);let r=t?t.value:"";return""===r&&("boolean"==typeof e?r=Ya.boolean:"number"==typeof e&&(Number.isFinite(e)?r=Number.isInteger(e)?Ya.integer:Ya.double:(r=Ya.double,Number.isNaN(e)||(e=e>0?"INF":"-INF")))),""===r||r===Ya.string?new N3DataFactory_Literal(`"${e}"`):new N3DataFactory_Literal(`"${e}"^^${r}`)}function cs(e){return new N3DataFactory_Variable(e)}function us(e,t,r,n){return new N3DataFactory_Quad(e,t,r,n)}function ls(e){if(e instanceof N3DataFactory_Term)return e;switch(e.termType){case"NamedNode":return os(e.value);case"BlankNode":return as(e.value);case"Variable":return cs(e.value);case"DefaultGraph":return Za;case"Literal":return ss(e.value,e.language||e.datatype);case"Quad":return ds(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function ds(e){if(e instanceof N3DataFactory_Quad)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return us(ls(e.subject),ls(e.predicate),ls(e.object),ls(e.graph))}function hs(e){return!!e&&"DefaultGraph"===e.termType}function fs(e){return e.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}const ps=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,ms=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/;class BaseIRI_BaseIRI{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!ps.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!BaseIRI_BaseIRI.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",fs(e)],r=[],n=[],i=/[^/?#]*([/?#])/y;let o,a=0,s=0,c=i.lastIndex=e.length;for(;!a&&!s&&(o=i.exec(this.base));)"#"===o[1]?s=i.lastIndex-1:(t.push(fs(o[0]),"(?:"),r.push(")?"),"?"!==o[1]?n.push(c=i.lastIndex):(a=c=i.lastIndex,s=this.base.indexOf("#",a),this._pathReplacements[a]="?"));for(let e=0;e<n.length;e++)this._pathReplacements[n[e]]="../".repeat(n.length-e-1);return this._pathReplacements[n[n.length-1]]="./",this._baseLength=s>0?s:this.base.length,t.push(fs(this.base.substring(c,this._baseLength)),a?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...r].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const r=t[0].length;if(r===this._baseLength&&r===e.length)return"";const n=this._pathReplacements[r];if(n){const t=e.substring(r);return"?"===n||ms.test(t)?"./"===n&&/^[^?#]/.test(t)?t:n+t:e}return e.substring(r-1)}}const ys=rs.defaultGraph(),{rdf:gs,xsd:_s}=Va,bs=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,ws=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,vs={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class N3Writer_SerializedTerm extends N3DataFactory_Term{equals(e){return e===this}}class N3Writer_N3Writer{constructor(e,t){if(this._prefixRegex=/$0^/,e&&"function"!=typeof e.write&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=void 0===t.end||!!t.end;else{let e="";this._outputStream={write(t,r,n){e+=t,n&&n()},end:t=>{t&&t(null,e)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=ys,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseIri=new BaseIRI_BaseIRI(t.baseIRI)))}get _inDefaultGraph(){return ys.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,r,n,i){try{n.equals(this._graph)||(this._write((null===this._subject?"":this._inDefaultGraph?".\n":"\n}\n")+(ys.equals(n)?"":`${this._encodeIriOrBlank(n)} {\n`)),this._graph=n,this._subject=null),e.equals(this._subject)?t.equals(this._predicate)?this._write(`, ${this._encodeObject(r)}`,i):this._write(`;\n ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i):this._write(`${(null===this._subject?"":".\n")+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,i)}catch(e){i&&i(e)}}_writeQuadLine(e,t,r,n,i){delete this._prefixMatch,this._write(this.quadToString(e,t,r,n),i)}quadToString(e,t,r,n){return`${this._encodeSubject(e)} ${this._encodeIriOrBlank(t)} ${this._encodeObject(r)}${n&&n.value?` ${this._encodeIriOrBlank(n)} .\n`:" .\n"}`}quadsToString(e){let t="";for(const r of e)t+=this.quadToString(r.subject,r.predicate,r.object,r.graph);return t}_encodeSubject(e){return"Quad"===e.termType?this._encodeQuad(e):this._encodeIriOrBlank(e)}_encodeIriOrBlank(e){if("NamedNode"!==e.termType)return this._lists&&e.value in this._lists&&(e=this.list(this._lists[e.value])),"id"in e?e.id:`_:${e.value}`;let t=e.value;this._baseIri&&(t=this._baseIri.toRelative(t)),bs.test(t)&&(t=t.replace(ws,Ss));const r=this._prefixRegex.exec(t);return r?r[1]?this._prefixIRIs[r[1]]+r[2]:t:`<${t}>`}_encodeLiteral(e){let t=e.value;if(bs.test(t)&&(t=t.replace(ws,Ss)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===_s.string)return`"${t}"`}else switch(e.datatype.value){case _s.string:return`"${t}"`;case _s.boolean:if("true"===t||"false"===t)return t;break;case _s.integer:if(/^[+-]?\d+$/.test(t))return t;break;case _s.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case _s.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===gs.type?"a":this._encodeIriOrBlank(e)}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:r,graph:n}){return`<<${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(r)}${hs(n)?"":` ${this._encodeIriOrBlank(n)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,r,n,i){void 0===r?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):"function"==typeof n?this._writeQuad(e,t,r,ys,n):this._writeQuad(e,t,r,n||ys,i)}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}addPrefix(e,t,r){const n={};n[e]=t,this.addPrefixes(n,r)}addPrefixes(e,t){if(!this._prefixIRIs)return t&&t();let r=!1;for(let t in e){let n=e[t];"string"!=typeof n&&(n=n.value),r=!0,null!==this._subject&&(this._write(this._inDefaultGraph?".\n":"\n}\n"),this._subject=null,this._graph=""),this._prefixIRIs[n]=t+=":",this._write(`@prefix ${t} <${n}>.\n`)}if(r){let e="",t="";for(const r in this._prefixIRIs)e+=e?`|${r}`:r,t+=(t?"|":"")+this._prefixIRIs[r];e=fs(e),this._prefixRegex=new RegExp(`^(?:${t})[^/]*$|^(${e})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(r?"\n":"",t)}blank(e,t){let r,n,i=e;switch(void 0===e?i=[]:e.termType?i=[{predicate:e,object:t}]:"length"in e||(i=[e]),n=i.length){case 0:return new N3Writer_SerializedTerm("[]");case 1:if(r=i[0],!(r.object instanceof N3Writer_SerializedTerm))return new N3Writer_SerializedTerm(`[ ${this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)} ]`);default:let t="[";for(let o=0;o<n;o++)r=i[o],r.predicate.equals(e)?t+=`, ${this._encodeObject(r.object)}`:(t+=`${(o?";\n ":"\n ")+this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)}`,e=r.predicate);return new N3Writer_SerializedTerm(`${t}\n]`)}}list(e){const t=e&&e.length||0,r=new Array(t);for(let n=0;n<t;n++)r[n]=this._encodeObject(e[n]);return new N3Writer_SerializedTerm(`(${r.join(" ")})`)}end(e){null!==this._subject&&(this._write(this._inDefaultGraph?".\n":"\n}\n"),this._subject=null),this._write=this._blockedWrite;let t=e&&((r,n)=>{t=null,e(r,n)});if(this._endStream)try{return this._outputStream.end(t)}catch(e){}t&&t()}}function Ss(e){let t=vs[e];return void 0===t&&(1===e.length?(t=e.charCodeAt(0).toString(16),t="\\u0000".substr(0,6-t.length)+t):(t=(1024*(e.charCodeAt(0)-55296)+e.charCodeAt(1)+9216).toString(16),t="\\U00000000".substr(0,10-t.length)+t)),t}const xs=Symbol("iter");function Is(e,t,r=4){if(0===r)return Object.assign(e,t);for(const n in t)e[n]=Is(e[n]||Object.create(null),t[n],r-1);return e}function As(e,t,r=4){let n=!1;for(const i in e)if(i in t){const o=0===r?null:As(e[i],t[i],r-1);if(!1!==o)n=n||Object.create(null),n[i]=o;else if(3===r)return!1}return n}function Ts(e,t,r=4){let n=!1;for(const i in e)if(i in t){if(0!==r){const o=Ts(e[i],t[i],r-1);if(!1!==o)n=n||Object.create(null),n[i]=o;else if(3===r)return!1}}else n=n||Object.create(null),n[i]=0===r?null:Is({},e[i],r-1);return n}class N3Store_N3EntityIndex{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||rs}_termFromId(e){if("."===e[0]){const t=this._entities,r=e.split(".");return this._factory.quad(this._termFromId(t[r[1]]),this._termFromId(t[r[2]]),this._termFromId(t[r[3]]),r[4]&&this._termFromId(t[r[4]]))}return ns(e,this._factory)}_termToNumericId(e){if("Quad"===e.termType){const t=this._termToNumericId(e.subject),r=this._termToNumericId(e.predicate),n=this._termToNumericId(e.object);let i;return t&&r&&n&&(hs(e.graph)||(i=this._termToNumericId(e.graph)))&&this._ids[i?`.${t}.${r}.${n}.${i}`:`.${t}.${r}.${n}`]}return this._ids[is(e)]}_termToNewNumericId(e){const t=e&&"Quad"===e.termType?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${hs(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:is(e);return this._ids[t]||(this._ids[this._entities[++this._id]=t]=this._id)}createBlankNode(e){let t,r;if(e)for(t=e=`_:${e}`,r=1;this._ids[t];)t=e+r++;else do{t="_:b"+this._blankNodeIndex++}while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}class N3Store_N3Store{constructor(e,t){this._size=0,this._graphs=Object.create(null),t||!e||e[0]||"function"==typeof e.match||(t=e,e=null),t=t||{},this._factory=t.factory||rs,this._entityIndex=t.entityIndex||new N3Store_N3EntityIndex({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addAll(e)}get size(){let e=this._size;if(null!==e)return e;e=0;const t=this._graphs;let r,n;for(const i in t)for(const o in r=t[i].subjects)for(const t in n=r[o])e+=Object.keys(n[t]).length;return this._size=e}_addToIndex(e,t,r,n){const i=e[t]||(e[t]={}),o=i[r]||(i[r]={}),a=n in o;return a||(o[n]=null),!a}_removeFromIndex(e,t,r,n){const i=e[t],o=i[r];delete o[n];for(const e in o)return;delete i[r];for(const e in i)return;delete e[t]}*_findInIndex(e,t,r,n,i,o,a,s){let c,u,l;const d=this._entities,h=this._termFromId(d[s]),f={subject:null,predicate:null,object:null};t&&((c=e,e={})[t]=c[t]);for(const t in e)if(u=e[t]){f[i]=this._termFromId(d[t]),r&&((c=u,u={})[r]=c[r]);for(const e in u)if(l=u[e]){f[o]=this._termFromId(d[e]);const t=n?n in l?[n]:[]:Object.keys(l);for(let e=0;e<t.length;e++)f[a]=this._termFromId(d[t[e]]),yield this._factory.quad(f.subject,f.predicate,f.object,h)}}}_loop(e,t){for(const r in e)t(r)}_loopByKey0(e,t,r){let n,i;if(n=e[t])for(i in n)r(i)}_loopByKey1(e,t,r){let n,i;for(n in e)i=e[n],i[t]&&r(n)}_loopBy2Keys(e,t,r,n){let i,o,a;if((i=e[t])&&(o=i[r]))for(a in o)n(a)}_countInIndex(e,t,r,n){let i,o,a,s=0;t&&((i=e,e={})[t]=i[t]);for(const t in e)if(o=e[t]){r&&((i=o,o={})[r]=i[r]);for(const e in o)(a=o[e])&&(n?n in a&&s++:s+=Object.keys(a).length)}return s}_getGraphs(e){return"number"!=typeof(e=""===e?1:e&&(this._termToNumericId(e)||-1))?this._graphs:{[e]:this._graphs[e]}}_uniqueEntities(e){const t=Object.create(null);return r=>{r in t||(t[r]=!0,e(this._termFromId(this._entities[r],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,r,n){t||(n=e.graph,r=e.object,t=e.predicate,e=e.subject),n=n?this._termToNewNumericId(n):1;let i=this._graphs[n];return i||(i=this._graphs[n]={subjects:{},predicates:{},objects:{}},Object.freeze(i)),e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),r=this._termToNewNumericId(r),!!this._addToIndex(i.subjects,e,t,r)&&(this._addToIndex(i.predicates,t,r,e),this._addToIndex(i.objects,r,e,t),this._size=null,!0)}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}delete(e){return this.removeQuad(e),this}has(e,t,r,n){return e&&e.subject&&({subject:e,predicate:t,object:r,graph:n}=e),!this.readQuads(e,t,r,n).next().done}import(e){return e.on("data",e=>{this.addQuad(e)}),e}removeQuad(e,t,r,n){t||({subject:e,predicate:t,object:r,graph:n}=e),n=n?this._termToNumericId(n):1;const i=this._graphs;let o,a,s;if(!((e=e&&this._termToNumericId(e))&&(t=t&&this._termToNumericId(t))&&(r=r&&this._termToNumericId(r))&&(o=i[n])&&(a=o.subjects[e])&&(s=a[t])&&r in s))return!1;for(e in this._removeFromIndex(o.subjects,e,t,r),this._removeFromIndex(o.predicates,t,r,e),this._removeFromIndex(o.objects,r,e,t),null!==this._size&&this._size--,o.subjects)return!0;return delete i[n],!0}removeQuads(e){for(let t=0;t<e.length;t++)this.removeQuad(e[t])}remove(e){return e.on("data",e=>{this.removeQuad(e)}),e}removeMatches(e,t,r,n){const i=new(p().Readable)({objectMode:!0}),o=this.readQuads(e,t,r,n);return i._read=e=>{for(;--e>=0;){const{done:e,value:t}=o.next();if(e)return void i.push(null);i.push(t)}},this.remove(i)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,r,n){return[...this.readQuads(e,t,r,n)]}*readQuads(e,t,r,n){const i=this._getGraphs(n);let o,a,s,c;if(!(e&&!(a=this._termToNumericId(e))||t&&!(s=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(const e in i)(o=i[e])&&(a?c?yield*this._findInIndex(o.objects,c,a,s,"object","subject","predicate",e):yield*this._findInIndex(o.subjects,a,s,null,"subject","predicate","object",e):s?yield*this._findInIndex(o.predicates,s,c,null,"predicate","object","subject",e):c?yield*this._findInIndex(o.objects,c,null,null,"object","subject","predicate",e):yield*this._findInIndex(o.subjects,null,null,null,"subject","predicate","object",e))}match(e,t,r,n){return new N3Store_DatasetCoreAndReadableStream(this,e,t,r,n,{entityIndex:this._entityIndex})}countQuads(e,t,r,n){const i=this._getGraphs(n);let o,a,s,c,u=0;if(e&&!(a=this._termToNumericId(e))||t&&!(s=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r)))return 0;for(const n in i)(o=i[n])&&(u+=e?r?this._countInIndex(o.objects,c,a,s):this._countInIndex(o.subjects,a,s,c):t?this._countInIndex(o.predicates,s,c,a):this._countInIndex(o.objects,c,a,s));return u}forEach(e,t,r,n,i){this.some(t=>(e(t,this),!1),t,r,n,i)}every(e,t,r,n,i){return!this.some(t=>!e(t,this),t,r,n,i)}some(e,t,r,n,i){for(const o of this.readQuads(t,r,n,i))if(e(o,this))return!0;return!1}getSubjects(e,t,r){const n=[];return this.forSubjects(e=>{n.push(e)},e,t,r),n}forSubjects(e,t,r,n){const i=this._getGraphs(n);let o,a,s;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(s=this._termToNumericId(r))))for(n in i)(o=i[n])&&(a?s?this._loopBy2Keys(o.predicates,a,s,e):this._loopByKey1(o.subjects,a,e):s?this._loopByKey0(o.objects,s,e):this._loop(o.subjects,e))}getPredicates(e,t,r){const n=[];return this.forPredicates(e=>{n.push(e)},e,t,r),n}forPredicates(e,t,r,n){const i=this._getGraphs(n);let o,a,s;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(s=this._termToNumericId(r))))for(n in i)(o=i[n])&&(a?s?this._loopBy2Keys(o.objects,s,a,e):this._loopByKey0(o.subjects,a,e):s?this._loopByKey1(o.predicates,s,e):this._loop(o.predicates,e))}getObjects(e,t,r){const n=[];return this.forObjects(e=>{n.push(e)},e,t,r),n}forObjects(e,t,r,n){const i=this._getGraphs(n);let o,a,s;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(s=this._termToNumericId(r))))for(n in i)(o=i[n])&&(a?s?this._loopBy2Keys(o.subjects,a,s,e):this._loopByKey1(o.objects,a,e):s?this._loopByKey0(o.predicates,s,e):this._loop(o.objects,e))}getGraphs(e,t,r){const n=[];return this.forGraphs(e=>{n.push(e)},e,t,r),n}forGraphs(e,t,r,n){for(const i in this._graphs)this.some(t=>(e(t.graph),!0),t,r,n,this._termFromId(this._entities[i]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1}={}){const r={},n=t?()=>!0:(e,t)=>{throw new Error(`${e.value} ${t}`)},i=this.getQuads(null,Va.rdf.rest,Va.rdf.nil,null),o=e?[...i]:[];return i.forEach(t=>{const i=[];let a,s,c=!1;const u=t.graph;let l=t.subject;for(;l&&!c;){const e=this.getQuads(null,null,l,null),t=this.getQuads(l,null,null,null);let r,d=null,h=null,f=null;for(let i=0;i<t.length&&!c;i++)r=t[i],r.graph.equals(u)?a?c=n(l,"has non-list arcs out"):r.predicate.value===Va.rdf.first?d?c=n(l,"has multiple rdf:first arcs"):o.push(d=r):r.predicate.value===Va.rdf.rest?h?c=n(l,"has multiple rdf:rest arcs"):o.push(h=r):e.length?c=n(l,"can't be subject and object"):(a=r,s="subject"):c=n(l,"not confined to single graph");for(let t=0;t<e.length&&!c;++t)r=e[t],a?c=n(l,"can't have coreferences"):r.predicate.value===Va.rdf.rest?f?c=n(l,"has incoming rdf:rest arcs"):f=r:(a=r,s="object");d?i.unshift(d.object):c=n(l,"has no list head"),l=f&&f.subject}c?e=!1:a&&(r[a[s].value]=i)}),e&&this.removeQuads(o),r}addAll(e){if(e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),Array.isArray(e))this.addQuads(e);else if(e instanceof N3Store_N3Store&&e._entityIndex===this._entityIndex)0!==e._size&&(this._graphs=Is(this._graphs,e._graphs),this._size=null);else for(const t of e)this.add(t);return this}contains(e){if(e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return!0;if(!(e instanceof N3Store_N3Store)||this._entityIndex!==e._entityIndex)return e.every(e=>this.has(e));const t=this._graphs,r=e._graphs;let n,i,o,a,s;for(const e in r){if(!(n=t[e]))return!1;n=n.subjects;for(const t in i=r[e].subjects){if(!(o=n[t]))return!1;for(const e in a=i[t]){if(!(s=o[e]))return!1;for(const t in a[e])if(!(t in s))return!1}}}return!0}deleteMatches(e,t,r,n){for(const i of this.match(e,t,r,n))this.removeQuad(i);return this}difference(e){if(e&&e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return new N3Store_N3Store({entityIndex:this._entityIndex});if(e instanceof N3Store_N3Store&&e._entityIndex===this._entityIndex){const t=new N3Store_N3Store({entityIndex:this._entityIndex}),r=Ts(this._graphs,e._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>!e.has(t))}equals(e){return e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new N3Store_N3Store({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof N3Store_DatasetCoreAndReadableStream&&(e=e.filtered),e===this){const e=new N3Store_N3Store({entityIndex:this._entityIndex});return e._graphs=Is(Object.create(null),this._graphs),e._size=this._size,e}if(e instanceof N3Store_N3Store&&this._entityIndex===e._entityIndex){const t=new N3Store_N3Store({entityIndex:this._entityIndex}),r=As(e._graphs,this._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>e.has(t))}map(e){const t=new N3Store_N3Store({entityIndex:this._entityIndex});for(const r of this)t.add(e(r,this));return t}reduce(e,t){const r=this.readQuads();let n=void 0===t?r.next().value:t;for(const t of r)n=e(n,t,this);return n}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return(new N3Writer_N3Writer).quadsToString(this)}union(e){const t=new N3Store_N3Store({entityIndex:this._entityIndex});return t._graphs=Is(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}}function Es(e,t,r=0){const n=t[r];if(n&&!(n in e))return!1;let i=!1;for(const o in n?{[n]:e[n]}:e){const n=2===r?null:Es(e[o],t,r+1);!1!==n&&(i=i||Object.create(null),i[o]=n)}return i}class N3Store_DatasetCoreAndReadableStream extends p().Readable{constructor(e,t,r,n,i,o){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:r,object:n,graph:i,options:o})}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:r,predicate:n,subject:i}=this,o=this._filtered=new N3Store_N3Store({factory:e._factory,entityIndex:this.options.entityIndex});let a,s,c;if(i&&!(a=o._termToNumericId(i))||n&&!(s=o._termToNumericId(n))||r&&!(c=o._termToNumericId(r)))return o;const u=e._getGraphs(t);for(const e in u){let t,r,n,i;(i=u[e])&&(!a&&s?(r=Es(i.predicates,[s,c,a]))&&(t=Es(i.subjects,[a,s,c]),n=Es(i.objects,[c,a,s])):c?(n=Es(i.objects,[c,a,s]))&&(t=Es(i.subjects,[a,s,c]),r=Es(i.predicates,[s,c,a])):(t=Es(i.subjects,[a,s,c]))&&(r=Es(i.predicates,[s,c,a]),n=Es(i.objects,[c,a,s])),t&&(o._graphs[e]={subjects:t,predicates:r,objects:n}))}o._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[xs]&&(this[xs]=this[Symbol.iterator]());const t=this[xs];for(;--e>=0;){const{done:e,value:r}=t.next();if(e)return void this.push(null);this.push(r)}}addAll(e){return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,r,n){return this.filtered.deleteMatches(e,t,r,n)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,r,n,i){return this.filtered.every(e,t,r,n,i)}filter(e){return this.filtered.filter(e)}forEach(e,t,r,n,i){return this.filtered.forEach(e,t,r,n,i)}import(e){return this.filtered.import(e)}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map(e)}some(e,t,r,n,i){return this.filtered.some(e,t,r,n,i)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(e)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce(e,t)}toString(){return(new N3Writer_N3Writer).quadsToString(this)}add(e){return this.filtered.add(e)}delete(e){return this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,r,n){return new N3Store_DatasetCoreAndReadableStream(this.filtered,e,t,r,n,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}const{xsd:Rs}=Va,ks=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,js={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},Ns=/[\x00-\x20<>\\"\{\}\|\^\`]/,Cs={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},Ps=/$0^/;class N3Lexer_N3Lexer{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 Cs)&&this[e]instanceof RegExp&&(this[e]=Ps)}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,a;for(;e=this._newline.exec(r);)this.comments&&(a=this._comment.exec(e[0]))&&i("comment",a[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&&(a=this._comment.exec(r))&&i("comment",a[1],"",this._line,r.length),r=null,i("eof","","",this._line,0)),this._input=r;const s=this._line,c=r[0];let u="",l="",d="",h=null,f=0,p=!1;switch(c){case"^":if(r.length<3)break;if("^"!==r[1]){this._n3Mode&&(f=1,u="^");break}if(this._previousMarker="^^",r=r.substr(2),"<"!==r[0]){p=!0;break}case"<":if(h=this._unescapedIri.exec(r))u="IRI",l=h[1];else if(h=this._iri.exec(r)){if(l=this._unescape(h[1]),null===l||Ns.test(l))return o(this);u="IRI"}else r.length>1&&"<"===r[1]?(u="<<",f=2):this._n3Mode&&r.length>1&&"="===r[1]&&(f=2,this._isImpliedBy?(u="abbreviation",l="<"):(u="inverse",l=">"));break;case">":r.length>1&&">"===r[1]&&(u=">>",f=2);break;case"_":((h=this._blank.exec(r))||t&&(h=this._blank.exec(`${r} `)))&&(u="blank",d="_",l=h[1]);break;case'"':if(h=this._simpleQuotedString.exec(r))l=h[1];else if(({value:l,matchLength:f}=this._parseLiteral(r)),null===l)return o(this);null===h&&0===f||(u="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(h=this._simpleApostropheString.exec(r))l=h[1];else if(({value:l,matchLength:f}=this._parseLiteral(r)),null===l)return o(this);null===h&&0===f||(u="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(h=this._variable.exec(r))&&(u="var",l=h[0]);break;case"@":"literal"===this._previousMarker&&(h=this._langcode.exec(r))?(u="langcode",l=h[1]):(h=this._keyword.exec(r))&&(u=h[0]);break;case".":if(1===r.length?t:r[1]<"0"||r[1]>"9"){u=".",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"-":(h=this._number.exec(r)||t&&(h=this._number.exec(`${r} `)))&&(u="literal",l=h[0],d="string"==typeof h[1]?Rs.double:"string"==typeof h[2]?Rs.decimal:Rs.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(h=this._sparqlKeyword.exec(r))?u=h[0].toUpperCase():p=!0;break;case"f":case"t":(h=this._boolean.exec(r))?(u="literal",l=h[0],d=Rs.boolean):p=!0;break;case"a":(h=this._shortPredicates.exec(r))?(u="abbreviation",l="a"):p=!0;break;case"=":this._n3Mode&&r.length>1&&(u="abbreviation",">"!==r[1]?(f=1,l="="):(f=2,l=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(f=1,u=c);break;case"{":!this._lineMode&&r.length>=2&&("|"===r[1]?(u="{|",f=2):(u=c,f=1));break;case"|":r.length>=2&&"}"===r[1]&&(u="|}",f=2);break;default:p=!0}if(p&&("@prefix"!==this._previousMarker&&"PREFIX"!==this._previousMarker||!(h=this._prefix.exec(r))?((h=this._prefixed.exec(r))||t&&(h=this._prefixed.exec(`${r} `)))&&(u="prefixed",d=h[1]||"",l=this._unescape(h[2])):(u="prefix",l=h[1]||"")),"^^"===this._previousMarker)switch(u){case"prefixed":u="type";break;case"IRI":u="typeIRI";break;default:u=""}if(!u)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?o(this):this._input=r;const m=f||h[0].length,y=i(u,l,d,s,m);this.previousToken=y,this._previousMarker=u,r=r.substr(m,r.length)}function i(t,i,o,a,s){const c=r?n-r.length:n,u={type:t,value:i,prefix:o,line:a,start:c,end:c+s};return e(null,u),u}function o(t){e(t._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(ks,(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 js?js[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,o=n+r;if(1===r&&0!==i||3===r&&this._lineMode)break;return this._line+=i,{value:this._unescape(t),matchLength:o}}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,r){if(this._line=1,"string"==typeof e){if(this._input=this._readStartingBom(e),"function"!=typeof r){const e=[];let t;if(this._tokenizeToEnd((r,n)=>r?t=r:e.push(n),!0),t)throw t;return e}queueMicrotask(()=>this._tokenizeToEnd(r,!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=t().Buffer.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(r,!1)))}),e.on("end",()=>{"string"==typeof this._input&&this._tokenizeToEnd(r,!0)}),e.on("error",r)}}let Os=0;class N3Parser_N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&qs(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),o=/quad/.test(t),a=this._n3Mode=/n3/.test(t),s=i||o;(this._supportsNamedGraphs=!(r||a))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||n||i||a),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=""===t||/star|\*$/.test(t),s&&(this._resolveRelativeIRI=e=>null),this._blankNodePrefix="string"!=typeof e.blankNodePrefix?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new N3Lexer_N3Lexer({lineMode:s,n3:a,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){Os=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 o=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:n,object:i,graph:t,inverse:!!o&&this._inversePredicate,blankPrefix:o?this._prefixes._:"",quantified:o?this._quantified:null}),o&&(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,o=this._contextStack,a=o[o.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!==o.length&&"list"===o[o.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===a.predicate?a.subject=r:a.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 o=this._predicate,a=this._object;this._subject=this._factory.quad(n,o,a,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=Fs}_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,o=0,a="/";for(;n<t;){switch(a){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(a=e[1+ ++n],a){case"/":r+=e.substring(o,n-1),o=n+1;break;case void 0:case"?":case"#":return r+e.substring(o,n)+e.substr(n+1);case".":if(a=e[1+ ++n],void 0===a||"/"===a||"?"===a||"#"===a){if(r+=e.substring(o,n-2),(o=r.lastIndexOf("/"))>=i&&(r=r.substr(0,o)),"/"!==a)return`${r}/${e.substr(n+1)}`;o=n+1}}}a=e[++n]}return r+e.substring(o)}parse(e,t,r){let n,i,o;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(n=t.onQuad,i=t.onPrefix,o=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${Os++}_`,this._prefixCallback=i||Fs,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 a=(e,t)=>{null!==e?(this._callback(e),this._callback=Fs):this._readCallback&&(this._readCallback=this._readCallback(t))};o&&(this._lexer.comments=!0,a=(e,t)=>{null!==e?(this._callback(e),this._callback=Fs):this._readCallback&&("comment"===t.type?o(t.value):this._readCallback=this._readCallback(t))}),this._callback=n,this._lexer.tokenize(e,a)}}function Fs(){}function qs(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(Va.rdf.first),e.RDF_REST=t.namedNode(Va.rdf.rest),e.RDF_NIL=t.namedNode(Va.rdf.nil),e.N3_FORALL=t.namedNode(Va.r.forAll),e.N3_FORSOME=t.namedNode(Va.r.forSome),e.ABBREVIATIONS={a:t.namedNode(Va.rdf.type),"=":t.namedNode(Va.owl.sameAs),">":t.namedNode(Va.log.implies),"<":t.namedNode(Va.log.isImpliedBy)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}qs(N3Parser_N3Parser.prototype,rs);const Ms="http://www.w3.org/ns/solid/notifications#",$s={subscription:rs.namedNode(`${Ms}subscription`),channelType:rs.namedNode(`${Ms}channelType`),feature:rs.namedNode(`${Ms}feature`),WebhookChannel2023:rs.namedNode(`${Ms}WebhookChannel2023`),WebSocketChannel2023:rs.namedNode(`${Ms}WebSocketChannel2023`)};async function Ds(e,t=""){const r=new N3Store_N3Store,n=new N3Parser_N3Parser(t?{baseIRI:t}:{});for(const t of n.parse(e))r.add(rs.quad(t.subject,t.predicate,t.object,rs.defaultGraph()));return r}function Ls(e,t){if(e)for(const r of e.split(/,\s*(?=<)/)){const e=r.match(/^\s*<([^>]*)>(.*)$/);if(!e)continue;const n=e[2].match(/;\s*rel\s*=\s*(?:"([^"]*)"|([^;\s,]+))/i);if(!n)continue;if((n[1]??n[2]).split(/\s+/).includes(t))return e[1]}}class DiscoveryClient{constructor(e){this.authnFetch=e,this.rdf={contentType:"text/turtle",parse:Ds}}async findService(e,t){const r=await this.fetchStorageDescription(e),n=(i=r,o=null,a=$s.channelType,s=rs.namedNode(t),[...i.match(o,a,s,c)].shift())?.subject;var i,o,a,s,c;if(!n)return null;const u=function(e,t,r,n,i){return[...e.match(t,r,n,i)]}(r,n,$s.feature).map(e=>e.object.value);return{id:n.value,channelType:t,feature:u}}async fetchResource(e){const t=await this.authnFetch(e,{headers:{Accept:this.rdf.contentType}});if(t.status<200||t.status>300)throw Error(`Failed fetching resource: ${e}`);return this.rdf.parse(await t.text(),t.url)}async discoverStorageDescription(e){const t=await this.authnFetch(e,{method:"head"});if(t.status<200||t.status>300)throw Error(`Failed fetching resource: ${e}`);return Ls(t.headers.get("Link"),"http://www.w3.org/ns/solid/terms#storageDescription")}async fetchStorageDescription(e){const t=await this.discoverStorageDescription(e);return this.fetchResource(t)}async discoverDescriptionResource(e){return Ls((await this.authnFetch(e,{method:"head"})).headers.get("Link"),"describedby")}async fetchDescriptionResource(e){const t=await this.discoverDescriptionResource(e);return this.fetchResource(t)}}const Us="http://www.w3.org/ns/solid/notifications#",zs={topic:rs.namedNode(`${Us}topic`),sendTo:rs.namedNode(`${Us}sendTo`),receiveFrom:rs.namedNode(`${Us}receiveFrom`),WebhookChannel2023:rs.namedNode(`${Us}WebhookChannel2023`),WebSocketChannel2023:rs.namedNode(`${Us}WebSocketChannel2023`),LDNChannel2023:rs.namedNode(`${Us}LDNChannel2023`)},Bs={type:rs.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")};async function Qs(e,t=""){const r=new N3Store_N3Store,n=new N3Parser_N3Parser(t?{baseIRI:t}:{});for(const t of n.parse(e))r.add(rs.quad(t.subject,t.predicate,t.object,rs.defaultGraph()));return r}async function Hs(e){const t=new N3Writer_N3Writer({format:"text/turtle"});for(const r of e)t.addQuad(r);return new Promise((e,r)=>{t.end((t,n)=>{t?r(t):e(n)})})}function Ks(e,t,r,n,i){return[...e.match(t,r,n,i)].shift()}class SubscriptionClient{constructor(e){this.authnFetch=e,this.discovery=new DiscoveryClient(this.authnFetch),this.rdf={contentType:"text/turtle",parse:Qs,serialize:Hs}}async subscribe(e,t,r){const n=await this.discovery.findService(e,t);if(!n)throw Error(`Discovery did not succeed: channel type ${t} is not supported by the Solid Server.`);const i=function(e,t,r){const n=new N3Store_N3Store,i=rs.blankNode();return n.add(rs.quad(i,Bs.type,rs.namedNode(t))),n.add(rs.quad(i,zs.topic,rs.namedNode(e))),r&&n.add(rs.quad(i,zs.sendTo,rs.namedNode(r))),n}(e,t,r),o=await this.authnFetch(n.id,{method:"POST",body:await this.rdf.serialize(i),headers:{Accept:this.rdf.contentType,"Content-Type":this.rdf.contentType}});if(!o.headers.get("Content-Type").startsWith(this.rdf.contentType))throw new Error("unexpected Content Type");return function(e){const t=Ks(e,null,Bs.type).subject,r={id:t.value,type:Ks(e,t,Bs.type).object.value,topic:Ks(e,t,zs.topic).object.value},n=Ks(e,t,zs.receiveFrom)?.object.value;n&&(r.receiveFrom=n);const i=Ks(e,t,zs.sendTo)?.object.value;return i&&(r.sendTo=i),r}(await this.rdf.parse(await o.text(),o.url))}}var Ws;!function(e){e.WebhookChannel2023="http://www.w3.org/ns/solid/notifications#WebhookChannel2023",e.WebSocketChannel2023="http://www.w3.org/ns/solid/notifications#WebSocketChannel2023"}(Ws||(Ws={}));var Js=i(7),Gs=null;"undefined"!=typeof WebSocket?Gs=WebSocket:"undefined"!=typeof MozWebSocket?Gs=MozWebSocket:void 0!==i.g?Gs=i.g.WebSocket||i.g.MozWebSocket:"undefined"!=typeof window?Gs=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(Gs=self.WebSocket||self.MozWebSocket);const Vs=Gs,Xs="https://w3id.org/ldes#retentionPolicy",Ys="https://w3id.org/ldes#amount",Zs="https://w3id.org/ldes#pointInTime",ec="https://w3id.org/ldes#versionKey",tc="https://w3id.org/ldes#versionOfPath",rc="https://w3id.org/ldes#timestampPath",nc="https://w3id.org/ldes#versionMaterializationOf",ic="https://w3id.org/ldes#versionMaterializationUntil",oc="https://w3id.org/ldes#EventStream",ac="https://w3id.org/ldes#EventSource",sc="https://w3id.org/ldes#RetentionPolicy",cc="https://w3id.org/ldes#Vocabulary",uc="https://w3id.org/ldes#",lc="ldes",dc="http://www.w3.org/ns/ldp#hasMemberRelation",hc="http://www.w3.org/ns/ldp#isMemberOfRelation",fc="http://www.w3.org/ns/ldp#membershipResource",pc="http://www.w3.org/ns/ldp#insertedContentRelation",mc="http://www.w3.org/ns/ldp#member",yc="http://www.w3.org/ns/ldp#contains",gc="http://www.w3.org/ns/ldp#constrainedBy",_c="http://www.w3.org/ns/ldp#pageSortCriteria",bc="http://www.w3.org/ns/ldp#pageSortPredicate",wc="http://www.w3.org/ns/ldp#pageSortOrder",vc="http://www.w3.org/ns/ldp#pageSortCollation",Sc="http://www.w3.org/ns/ldp#pageSequence",xc="http://www.w3.org/ns/ldp#inbox",Ic="http://www.w3.org/ns/ldp#Resource",Ac="http://www.w3.org/ns/ldp#RDFSource",Tc="http://www.w3.org/ns/ldp#NonRDFSource",Ec="http://www.w3.org/ns/ldp#Container",Rc="http://www.w3.org/ns/ldp#BasicContainer",kc="http://www.w3.org/ns/ldp#DirectContainer",jc="http://www.w3.org/ns/ldp#IndirectContainer",Nc="http://www.w3.org/ns/ldp#Page",Cc="http://www.w3.org/ns/ldp#PageSortCriterion",Pc="http://www.w3.org/ns/ldp#MemberSubject",Oc="http://www.w3.org/ns/ldp#PreferContainment",Fc="http://www.w3.org/ns/ldp#PreferMembership",qc="http://www.w3.org/ns/ldp#PreferEmptyContainer",Mc="http://www.w3.org/ns/ldp#PreferMinimalContainer",$c="http://www.w3.org/ns/ldp#Ascending",Dc="http://www.w3.org/ns/ldp#Descending",Lc="http://www.w3.org/ns/ldp#",Uc="ldp",zc="https://w3id.org/tree#viewDescription",Bc="https://w3id.org/tree#relation",Qc="https://w3id.org/tree#remainingItems",Hc="https://w3id.org/tree#node",Kc="https://w3id.org/tree#rootNode",Wc="https://w3id.org/tree#value",Jc="https://w3id.org/tree#path",Gc="https://w3id.org/tree#view",Vc="https://w3id.org/tree#member",Xc="https://w3id.org/tree#search",Yc="https://w3id.org/tree#shape",Zc="https://w3id.org/tree#import",eu="https://w3id.org/tree#conditionalImport",tu="https://w3id.org/tree#zoom",ru="https://w3id.org/tree#longitudeTile",nu="https://w3id.org/tree#latitudeTile",iu="https://w3id.org/tree#timeQuery",ou="https://w3id.org/tree#Collection",au="https://w3id.org/tree#SearchTree",su="https://w3id.org/tree#Node",cu="https://w3id.org/tree#RootNode",uu="https://w3id.org/tree#Relation",lu="https://w3id.org/tree#ConditionalImport",du="https://w3id.org/tree#PrefixRelation",hu="https://w3id.org/tree#SubstringRelation",fu="https://w3id.org/tree#SuffixRelation",pu="https://w3id.org/tree#GreaterThanRelation",mu="https://w3id.org/tree#GreaterThanOrEqualToRelation",yu="https://w3id.org/tree#LessThanRelation",gu="https://w3id.org/tree#LessThanOrEqualToRelation",_u="https://w3id.org/tree#EqualToRelation",bu="https://w3id.org/tree#NotEqualToRelation",wu="https://w3id.org/tree#GeospatiallyContainsRelation",vu="https://w3id.org/tree#InBetweenRelation",Su="https://w3id.org/tree#Ontology",xu="https://w3id.org/tree#",Iu="tree",Au="https://www.w3.org/ns/activitystreams#relationship",Tu="https://www.w3.org/ns/activitystreams#Activity",Eu="https://www.w3.org/ns/activitystreams#Object",Ru="https://www.w3.org/ns/activitystreams#Link",ku="https://www.w3.org/ns/activitystreams#Collection",ju="https://www.w3.org/ns/activitystreams#CollectionPage",Nu="https://www.w3.org/ns/activitystreams#Image",Cu="https://www.w3.org/ns/activitystreams#OrderedItems",Pu="https://www.w3.org/ns/activitystreams#Relationship",Ou="https://www.w3.org/ns/activitystreams#Question",Fu="https://www.w3.org/ns/activitystreams#Profile",qu="https://www.w3.org/ns/activitystreams#Tombstone",Mu="https://www.w3.org/ns/activitystreams#Place",$u="https://www.w3.org/ns/activitystreams#OrderedCollectionPage",Du="https://www.w3.org/ns/activitystreams#Accept",Lu="https://www.w3.org/ns/activitystreams#Block",Uu="https://www.w3.org/ns/activitystreams#Ignore",zu="https://www.w3.org/ns/activitystreams#IntransitiveActivity",Bu="https://www.w3.org/ns/activitystreams#Add",Qu="https://www.w3.org/ns/activitystreams#Announce",Hu="https://www.w3.org/ns/activitystreams#Application",Ku="https://www.w3.org/ns/activitystreams#Arrive",Wu="https://www.w3.org/ns/activitystreams#Article",Ju="https://www.w3.org/ns/activitystreams#Audio",Gu="https://www.w3.org/ns/activitystreams#Document",Vu="https://www.w3.org/ns/activitystreams#OrderedCollection",Xu="https://www.w3.org/ns/activitystreams#Create",Yu="https://www.w3.org/ns/activitystreams#Delete",Zu="https://www.w3.org/ns/activitystreams#Dislike",el="https://www.w3.org/ns/activitystreams#Event",tl="https://www.w3.org/ns/activitystreams#Flag",rl="https://www.w3.org/ns/activitystreams#Follow",nl="https://www.w3.org/ns/activitystreams#Group",il="https://www.w3.org/ns/activitystreams#Invite",ol="https://www.w3.org/ns/activitystreams#Offer",al="https://www.w3.org/ns/activitystreams#Join",sl="https://www.w3.org/ns/activitystreams#Leave",cl="https://www.w3.org/ns/activitystreams#Like",ul="https://www.w3.org/ns/activitystreams#View",ll="https://www.w3.org/ns/activitystreams#Listen",dl="https://www.w3.org/ns/activitystreams#Read",hl="https://www.w3.org/ns/activitystreams#Move",fl="https://www.w3.org/ns/activitystreams#Travel",pl="https://www.w3.org/ns/activitystreams#Mention",ml="https://www.w3.org/ns/activitystreams#Note",yl="https://www.w3.org/ns/activitystreams#Page",gl="https://www.w3.org/ns/activitystreams#Person",_l="https://www.w3.org/ns/activitystreams#Organization",bl="https://www.w3.org/ns/activitystreams#Reject",wl="https://www.w3.org/ns/activitystreams#Remove",vl="https://www.w3.org/ns/activitystreams#Service",Sl="https://www.w3.org/ns/activitystreams#TentativeAccept",xl="https://www.w3.org/ns/activitystreams#TentativeReject",Il="https://www.w3.org/ns/activitystreams#Undo",Al="https://www.w3.org/ns/activitystreams#Update",Tl="https://www.w3.org/ns/activitystreams#Video",El="https://www.w3.org/ns/activitystreams#actor",Rl="https://www.w3.org/ns/activitystreams#attributedTo",kl="https://www.w3.org/ns/activitystreams#attachment",jl="https://www.w3.org/ns/activitystreams#attachments",Nl="https://www.w3.org/ns/activitystreams#author",Cl="https://www.w3.org/ns/activitystreams#bcc",Pl="https://www.w3.org/ns/activitystreams#bto",Ol="https://www.w3.org/ns/activitystreams#cc",Fl="https://www.w3.org/ns/activitystreams#context",ql="https://www.w3.org/ns/activitystreams#current",Ml="https://www.w3.org/ns/activitystreams#first",$l="https://www.w3.org/ns/activitystreams#generator",Dl="https://www.w3.org/ns/activitystreams#icon",Ll="https://www.w3.org/ns/activitystreams#image",Ul="https://www.w3.org/ns/activitystreams#inReplyTo",zl="https://www.w3.org/ns/activitystreams#items",Bl="https://www.w3.org/ns/activitystreams#last",Ql="https://www.w3.org/ns/activitystreams#location",Hl="https://www.w3.org/ns/activitystreams#next",Kl="https://www.w3.org/ns/activitystreams#object",Wl="https://www.w3.org/ns/activitystreams#oneOf",Jl="https://www.w3.org/ns/activitystreams#anyOf",Gl="https://www.w3.org/ns/activitystreams#prev",Vl="https://www.w3.org/ns/activitystreams#preview",Xl="https://www.w3.org/ns/activitystreams#provider",Yl="https://www.w3.org/ns/activitystreams#replies",Zl="https://www.w3.org/ns/activitystreams#result",ed="https://www.w3.org/ns/activitystreams#audience",td="https://www.w3.org/ns/activitystreams#partOf",rd="https://www.w3.org/ns/activitystreams#tag",nd="https://www.w3.org/ns/activitystreams#tags",id="https://www.w3.org/ns/activitystreams#target",od="https://www.w3.org/ns/activitystreams#origin",ad="https://www.w3.org/ns/activitystreams#instrument",sd="https://www.w3.org/ns/activitystreams#to",cd="https://www.w3.org/ns/activitystreams#url",ud="https://www.w3.org/ns/activitystreams#subject",ld="https://www.w3.org/ns/activitystreams#describes",dd="https://www.w3.org/ns/activitystreams#formerType",hd="https://www.w3.org/ns/activitystreams#accuracy",fd="https://www.w3.org/ns/activitystreams#altitude",pd="https://www.w3.org/ns/activitystreams#content",md="https://www.w3.org/ns/activitystreams#name",yd="https://www.w3.org/ns/activitystreams#downstreamDuplicates",gd="https://www.w3.org/ns/activitystreams#duration",_d="https://www.w3.org/ns/activitystreams#endTime",bd="https://www.w3.org/ns/activitystreams#height",wd="https://www.w3.org/ns/activitystreams#href",vd="https://www.w3.org/ns/activitystreams#hreflang",Sd="https://www.w3.org/ns/activitystreams#id",xd="https://www.w3.org/ns/activitystreams#latitude",Id="https://www.w3.org/ns/activitystreams#longitude",Ad="https://www.w3.org/ns/activitystreams#mediaType",Td="https://www.w3.org/ns/activitystreams#objectType",Ed="https://www.w3.org/ns/activitystreams#published",Rd="https://www.w3.org/ns/activitystreams#radius",kd="https://www.w3.org/ns/activitystreams#rating",jd="https://www.w3.org/ns/activitystreams#rel",Nd="https://www.w3.org/ns/activitystreams#startIndex",Cd="https://www.w3.org/ns/activitystreams#startTime",Pd="https://www.w3.org/ns/activitystreams#summary",Od="https://www.w3.org/ns/activitystreams#totalItems",Fd="https://www.w3.org/ns/activitystreams#units",qd="https://www.w3.org/ns/activitystreams#updated",Md="https://www.w3.org/ns/activitystreams#upstreamDuplicates",$d="https://www.w3.org/ns/activitystreams#verb",Dd="https://www.w3.org/ns/activitystreams#width",Ld="https://www.w3.org/ns/activitystreams#deleted",Ud="https://www.w3.org/ns/activitystreams#",zd="activitystreams",Bd=w,Qd=v,Hd=S,Kd=x;let Wd=class Relation{constructor(e,t){this.value=e,this.node=t}setPath(e){return this.path=new I.SerializableNamedNode(e),this}};A([(0,R.SerializableMember)({rdf:{predicate:Hd.node,serializer:!1,deserializer:e=>new I.SerializableThing(e.value)}}),T("design:type",I.SerializableThing)],Wd.prototype,"node",void 0),A([(0,R.SerializableMember)({rdf:{predicate:Hd.path}}),T("design:type",I.SerializableNamedNode)],Wd.prototype,"path",void 0),A([(0,R.SerializableMember)({constructor:Object,rdf:{predicate:Hd.value,serializer:e=>I.RDFSerializer.serialize(e),deserializer:e=>I.RDFSerializer.deserialize(e)}}),T("design:type",Object)],Wd.prototype,"value",void 0),Wd=A([(0,R.SerializableObject)({rdf:{type:Hd.Relation,serializer:(e,t)=>e.value?e.value.constructor===Date?{termType:"NamedNode",value:t+e.value.getTime().toString()}:{termType:"NamedNode",value:t+encodeURIComponent(e.value.toString())}:{}}}),T("design:paramtypes",[Object,Function])],Wd);let Jd=class GreaterThanOrEqualToRelation extends Wd{test(e){return e>=this.value}};Jd=A([(0,R.SerializableObject)({rdf:{type:Hd.GreaterThanOrEqualToRelation}})],Jd);let Gd=class GreaterThanRelation extends Wd{test(e){return e>this.value}};Gd=A([(0,R.SerializableObject)({rdf:{type:Hd.GreaterThanRelation}})],Gd);let Vd=class LessThanOrEqualToRelation extends Wd{test(e){return e<=this.value}};Vd=A([(0,R.SerializableObject)({rdf:{type:Hd.LessThanOrEqualToRelation}})],Vd);let Xd=class LessThanRelation extends Wd{test(e){return e<this.value}};Xd=A([(0,R.SerializableObject)({rdf:{type:Hd.LessThanRelation}})],Xd);let Yd=class Collection extends I.SerializableThing{constructor(){super(...arguments),this.members=[]}};A([(0,R.SerializableArrayMember)(I.SerializableThing,{rdf:{predicate:Hd.member,serializer:!1}}),T("design:type",Array)],Yd.prototype,"members",void 0),Yd=A([(0,R.SerializableObject)({rdf:{type:Hd.Collection}})],Yd);let Zd=class Node extends I.SerializableThing{constructor(e){super(e),this.relations=[]}getChildNodes(){return this.relations.map(e=>e.node)}getChildNode(e){const t=this.relations.filter(t=>!!t&&(t.value&&t.test(e)));if(0===t.length)return null;const r=t.sort((e,t)=>"number"==typeof e.value&&"number"==typeof t.value?e.value-t.value:e.value instanceof Date&&t.value instanceof Date?e.value.getTime()-t.value.getTime():e.value.toString().localeCompare(t.value.toString())).map(e=>e.node);return r[r.length-1]}};A([(0,R.SerializableArrayMember)(Wd,{rdf:{predicate:Hd.relation}}),T("design:type",Array)],Zd.prototype,"relations",void 0),A([(0,R.SerializableMember)({rdf:{}}),T("design:type",Yd)],Zd.prototype,"collection",void 0),Zd=A([(0,R.SerializableObject)({rdf:{type:Hd.Node}}),T("design:paramtypes",[String])],Zd);let eh=class EventStream extends I.SerializableThing{constructor(){super(...arguments),this.timestampPath=new I.SerializableNamedNode(I.dcterms.created),this.versionOfPath=new I.SerializableNamedNode(I.dcterms.isVersionOf)}setTimestampPath(e){this.timestampPath=new I.SerializableNamedNode(e)}setVersionOfPath(e){this.versionOfPath=new I.SerializableNamedNode(e)}};A([(0,R.SerializableMember)({rdf:{predicate:Bd.timestampPath}}),T("design:type",I.SerializableNamedNode)],eh.prototype,"timestampPath",void 0),A([(0,R.SerializableMember)({rdf:{predicate:Bd.versionOfPath}}),T("design:type",I.SerializableNamedNode)],eh.prototype,"versionOfPath",void 0),A([(0,R.SerializableMember)({rdf:{predicate:Hd.view,serializer:!1}}),T("design:type",Zd)],eh.prototype,"view",void 0),eh=A([(0,R.SerializableObject)({rdf:{type:Bd.EventStream}})],eh);let th=class Container extends I.SerializableThing{};th=A([(0,R.SerializableObject)({rdf:{type:Qd.Container}})],th);let rh=class Activity{};A([(0,R.SerializableMember)({rdf:{predicate:Kd.object,serializer:!1}}),T("design:type",String)],rh.prototype,"object",void 0),A([(0,R.SerializableMember)({rdf:{predicate:Kd.actor,serializer:!1}}),T("design:type",String)],rh.prototype,"actor",void 0),A([(0,R.SerializableMember)({rdf:{predicate:Kd.target,serializer:!1}}),T("design:type",String)],rh.prototype,"target",void 0),A([(0,R.SerializableMember)({rdf:{predicate:Kd.published}}),T("design:type",Date)],rh.prototype,"published",void 0),rh=A([(0,R.SerializableObject)({rdf:{type:Kd.Activity}})],rh);let nh=class ActivityAdd extends rh{};nh=A([(0,R.SerializableObject)({rdf:{type:Kd.Add}})],nh);let ih=class ActivityRemove extends rh{};ih=A([(0,R.SerializableObject)({rdf:{type:Kd.Remove}})],ih);class DatasetSubscription extends Js.EventEmitter{constructor(){super()}static create(e,t){return new Promise((r,n)=>{const i=new DatasetSubscription;let o=!1;i._ws=new Vs(e,["solid-0.1"]),i._ws.onopen=()=>{o=!0,r(i)},i._ws.onmessage=t?e=>{i.emit("message",e.data);try{I.RDFSerializer.deserializeFromJSONLD(void 0,JSON.parse(e.data)).then(e=>{e?i.emit("activity",e):i.emit("error",new Error("Failed to deserialize activity stream"))}).catch(e=>{i.emit("error",e)})}catch(e){i.emit("error",e)}}:e=>{if(e.data&&"pub"===e.data.slice(0,3)){const t=new nh;t.object=e.data.substring(3),i.emit("activity",t)}},i._ws.onerror=e=>{o?i.emit("error",e):n(e)}})}subscribe(e){this._ws.send(`sub ${e}`)}close(){this._ws&&this._ws.close()}on(e,t){return super.on(e,t)}}class StorageUtilityWrapper extends StorageUtility{constructor(e,t){super(e,t)}}class SolidStorage{constructor(e){this.driver=e}get(e){return new Promise(t=>{this.driver.findByUID(e).then(e=>{t(e)}).catch(()=>{t(void 0)})})}set(e,t){return new Promise((r,n)=>{this.driver.insert(e,t).then(()=>{r()}).catch(n)})}delete(e){return new Promise(t=>{this.driver.delete(e).then(t).catch(()=>t(void 0))})}}class SolidService extends R.RemoteService{constructor(e){super(),this.options=e||{},this.driver=this.options.dataServiceDriver||new R.MemoryDataService(String),this.storage=new SolidStorage(this.driver),this.storageUtility=new StorageUtilityWrapper(this.storage,this.storage),this.clientRegistrar=new ClientRegistrar(this.storageUtility),this.uid=this.constructor.name,this.options.defaultOidcIssuer=this.options.defaultOidcIssuer||"https://login.inrupt.com/",this.once("build",()=>this.driver.emitAsync("build"))}get session(){return this._session}set session(e){this._session=e}get clientAuthentication(){if(this._clientAuthentication)return this._clientAuthentication;const e=this.createSession({sessionInfo:{isLoggedIn:!1,sessionId:"dummy"},storage:this.storage,insecureStorage:this.storage,secureStorage:this.storage});return this._clientAuthentication=e.clientAuthentication,this._clientAuthentication}getDocumentURL(e,t){return E(this,void 0,void 0,function*(){const r=new URL(yield this.getPodUrl(e)),n=new URL(e.info.webId);n.pathname="",n.hash="";const i=new URL(r.href);if(t){const e=t.replace(r.href,"").replace(n.href,""),o=new URL((r.pathname.length>1?r.pathname:"")+e.replace(/^\//,""),r.href);i.pathname=o.pathname,i.hash=o.hash}return i})}getPodUrl(e){return new Promise((t,r)=>{Jr(e.info.webId,{fetch:e.fetch}).then(r=>{if(void 0===r[0]){const r=new URL(e.info.webId);return r.hash="",r.pathname=r.pathname.replace(/\/profile\/card$/,"/"),void t(r.href)}t(r[0])}).catch(r)})}getDatasetStore(e,t){return new Promise((r,n)=>{this.getDataset(e,t).then(e=>{e||(e=Mr());const t=Object.keys(e.graphs).map(t=>{const r=e.graphs[t];return I.RDFSerializer.subjectsToQuads(Object.values(r))}).reduce((e,t)=>e.concat(t),[]),n=(0,I.createChangeLog)(new I.Store(t)),i=Object.assign(n,e);r(i)}).catch(n)})}createDataset(){return Mr()}getDataset(e,t){return E(this,void 0,void 0,function*(){var r;const n=t.startsWith("http")?new URL(t):yield this.getDocumentURL(e,t);n.hash="";try{return yield $r(n.href,e?{fetch:e.fetch}:this.session)}catch(e){if(404===(null===(r=null==e?void 0:e.response)||void 0===r?void 0:r.status))return;throw e}})}getDatasetSubscription(e,t){const r=e?e.fetch:Jn.fetch;function n(){return new Promise((e,n)=>{const i=new DiscoveryClient(r);Promise.all([i.findService(t,Ws.WebSocketChannel2023)]).then(([e])=>{if(!e)return void n(new Error("No WebSocket service found"));return new SubscriptionClient(r).subscribe(t,e.channelType)}).then(t=>{e(t.receiveFrom)}).catch(n)})}function i(e,t){return new Promise((r,n)=>{DatasetSubscription.create(e,t).then(t=>{t.subscribe(e),r(t)}).catch(n)})}return new Promise((e,o)=>{new Promise((e,n)=>{r(t,{method:"HEAD"}).then(t=>{const r=t.headers.get("updates-via");if(!r)return e(void 0);e(r)}).catch(n)}).then(t=>{t?i(t,void 0).then(e).catch(o):n().then(e=>i(e,Ws.WebSocketChannel2023)).then(e).catch(o)}).catch(o)})}createContainer(e,t){return new Promise((r,n)=>{t.endsWith("/")||(t+="/"),this.getDataset(e,t).then(i=>{if(i&&L(i))r(i);else{if(!i||L(i))return async function(e,t={}){var r,n;const i=F(O(e),{trailingSlash:!0}),o=await(null!==(r=t.fetch)&&void 0!==r?r:fetch)(i,{method:"PUT",body:t.initialContent?await fr(mt(t.initialContent).map(Qr)):void 0,headers:{Accept:"text/turtle","Content-Type":"text/turtle","If-None-Match":"*",Link:`<${Rt}>; rel="type"`}});if(M(o)){const r=void 0===t.initialContent?"empty":"non-empty",n=await o.clone().text();throw new FetchError(`Creating the ${r} Container at [${e}] failed: [${o.status}] [${o.statusText}] ${n}.`,o,n)}const a=q(o);return He({...null!==(n=t.initialContent)&&void 0!==n?n:Mr(),internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:a})}(t,e?{fetch:e.fetch}:void 0);n(new Error("Resource already exists and is not a container"))}}).then(r).catch(n)})}deleteContainer(e,t){return new Promise((r,n)=>{(async function(e,t){var r;const n=N(e)?O(U(e)):F(O(e));if(!L(e))throw new Error(`You're trying to delete the Container at [${n}], but Container URLs should end in a \`/\`. Are you sure this is a Container?`);const i=await(null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch)(n,{method:"DELETE"});if(M(i)){const e=await i.clone().text();throw new FetchError(`Deleting the Container at [${n}] failed: [${i.status}] [${i.statusText}] ${e}.`,i,e)}})(t,e?{fetch:e.fetch}:void 0).then(()=>{r()}).catch(n)})}deleteRecursively(e,t){return E(this,void 0,void 0,function*(){if("string"==typeof t){const r=yield this.getDataset(e,t);return r?yield this.deleteRecursively(e,r):Promise.resolve()}if(!t)return Promise.resolve();const r=function(e){const t=U(e),r=Tr(e,t);return null===r?[]:xr(r,jt).filter(e=>zr(e,t))}(t),n=yield Promise.all(r.map(t=>E(this,void 0,void 0,function*(){try{return yield $r(t,e?{fetch:e.fetch}:this.session)}catch(r){return yield async function(e,t){var r;const n=N(e)?O(z(e)):F(O(e),{trailingSlash:!1}),i=await(null!==(r=null==t?void 0:t.fetch)&&void 0!==r?r:fetch)(n,{...null==t?void 0:t.init,method:"DELETE"});if(M(i)){const e=await i.clone().text();throw new FetchError(`Deleting the file at [${n}] failed: [${i.status}] [${i.statusText}] ${e}.`,i,e)}}(t,e?{fetch:e.fetch}:this.session),null}})));return yield Promise.all(n.map(t=>E(this,void 0,void 0,function*(){if(null!==t)return yield this.deleteRecursively(e,t)}))),yield Lr(t,e?{fetch:e.fetch}:this.session)})}deleteDataset(e,t){return new Promise((r,n)=>{Lr(t,e?{fetch:e.fetch}:this.session).then(()=>{r()}).catch(n)})}saveDataset(e,t,r,n){return new Promise((i,o)=>{var a,s;const c=e?{fetch:e.fetch}:this.session,u=new URL(t);u.hash="";const l=new URL(u.href);if(l.pathname=l.pathname.replace(/\/[^/]+$/,"/"),r instanceof I.Store){let e,t=[];if(r.additions&&r.deletions?(e=null!==(a=r.additions)&&void 0!==a?a:[],t=null!==(s=r.deletions)&&void 0!==s?s:[]):e=(r=(0,I.createChangeLog)(r)).getQuads(null,null,null,null),0===e.length&&0===t.length)return void i(null);const n="Dataset"===r.type?r:Mr(),o=Object.assign(Object.assign({},this.storeToDataset(r)),{internal_changeLog:{additions:e,deletions:t},internal_resourceInfo:n.internal_resourceInfo});r=o}else r=r||Mr();if(n){const e=Object.assign({sourceIri:u.href},r.internal_resourceInfo);r=Object.assign(Object.assign({},r),{internal_resourceInfo:e}),async function(e,t,r){var n;const i=F(O(e),{trailingSlash:!0}),o=await fr(mt(t).map(Qr)),a={"Content-Type":"text/turtle",Link:`<${kt}>; rel="type"`};(null==r?void 0:r.slugSuggestion)&&(a.slug=r.slugSuggestion);const s=await(null!==(n=null==r?void 0:r.fetch)&&void 0!==n?n:fetch)(i,{method:"POST",body:o,headers:a});if(M(s)){const e=await s.clone().text();throw new FetchError(`Storing the Resource in the Container at [${i}] failed: [${s.status}] [${s.statusText}] ${e}.\n\nThe SolidDataset that was sent to the Pod is listed below.\n\n${Br(t)}`,s,e)}const c=q(s);if(!c.location)throw new Error("Could not determine the location of the newly saved SolidDataset.");let u;try{u=new URL(c.location).href}catch(e){u=new URL(c.location,s.url).href}const l={internal_resourceInfo:{isRawData:!1,sourceIri:u}};return Kr(He({...t,...l}))}(l.href,r,c).then(i).catch(o)}else Dr(u.href,r,c).then(i).catch(o)})}getThing(e,t){return new Promise((r,n)=>{this.getDataset(e,t).then(e=>{if(!e)return void r(void 0);const n=Tr(e,t);r(n)}).catch(n)})}setAccess(e,t,r=I.foaf.Agent,n){return new Promise((i,o)=>{n=null!=n?n:this.session,async function(e,t){const r=await $r(e,t);return yn(r,await nn(r,t))}(e,n?{fetch:n.fetch}:void 0).then(e=>{let i;var o;!function(e){return"object"==typeof e.internal_acl}(e)?(i=Sn(e),i=Tn(i,n.info.webId,{read:!0,append:!0,write:!0,control:!0}),i=An(i,n.info.webId,{read:!0,append:!0,write:!0,control:!0})):i=wn(o=e)?o.internal_acl.resourceAcl:null;const a=t.group||r===I.foaf.Agent||"public"===r;return i=a?Rn(i,r,{read:t.read,append:t.append,write:t.write,control:t.controlWrite}):An(i,r,{read:t.read,append:t.append,write:t.write,control:t.controlWrite}),t.public&&(i=jn(i,{read:t.read,append:t.append,write:t.write,control:t.controlWrite})),t.public&&t.default&&(i=Nn(i,{read:t.read,append:t.append,write:t.write,control:t.controlWrite})),a&&t.default?i=kn(i,r,{read:t.read,append:t.append,write:t.write,control:t.controlWrite}):t.default&&(i=Tn(i,r,{read:t.read,append:t.append,write:t.write,control:t.controlWrite})),async function(e,t,r){if(!xn(e))throw new Error(`Could not determine the location of the ACL for the Resource at [${U(e)}]; possibly the current user does not have Control access to that Resource. Try calling \`hasAccessibleAcl()\` before calling \`saveAclFor()\`.`);return{...await Dr(e.internal_resourceInfo.aclUrl,t,r),internal_accessTo:U(e)}}(e,i,n?{fetch:n.fetch}:this.session)}).then(()=>{i()}).catch(o)})}getAccess(e,t=I.foaf.Agent,r){return new Promise((n,i)=>{Wn(e,t,r?{fetch:r.fetch}:void 0).then(e=>{n(e)}).catch(i)})}logout(e){return new Promise((t,r)=>{e.logout().then(()=>(this.session=void 0,this.storage.delete("currentSession"))).then(()=>{t()}).catch(r)})}setThing(e,t){return this.createThing(e,t)}createThing(e,t,r){return new Promise((n,i)=>{const o=new URL(t.url);function a(r,a=!0){var s;const c=null!==(s=Tr(r,t.url))&&void 0!==s?s:{},u=this._mergeDeep(c,t);r=Rr(r,u),a?this.saveDataset(e,r,o.href).then(()=>{n(r)}).catch(i):n(r)}o.hash="",r?a.bind(this)(r,!1):this.getDataset(e,o.href).then(e=>{e||(e=Mr()),a.bind(this)(e)}).catch(i)})}_isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}_mergeDeep(e,t){const r=Object.assign({},e);return this._isObject(e)&&this._isObject(t)&&Object.keys(t).forEach(n=>{var i;Array.isArray(t[n])?r[n]=[...t[n],...null!==(i=e[n])&&void 0!==i?i:[]]:this._isObject(t[n])?n in e?r[n]=this._mergeDeep(e[n],t[n]):Object.assign(r,{[n]:t[n]}):Object.assign(r,{[n]:t[n]})}),r}remotePush(e,t,r){return new Promise((e,t)=>{e(void 0)})}remotePull(e,t){return new Promise((e,t)=>{e(void 0)})}remoteEvent(e,t,...r){return new Promise((e,t)=>{e(void 0)})}remoteServiceCall(e,t,...r){return new Promise((e,t)=>{e(void 0)})}fetchProfile(e){return new Promise((t,r)=>{this.findSessionByWebId(e.webId).then(t=>$r(e.profileDocumentUrl.href,t?{fetch:t.fetch}:void 0)).then(r=>{const n=Tr(r,e.webId);var i,o;e.displayName=(i=n,o=I.vcard.fn,br(i),Ar(i,o,tt)),t(e)}).catch(r)})}storeProfile(e){return new Promise((t,r)=>{const n=`${SolidService.PREFIX}:webId:${e.webId}`;let i;this.storage.set(n,e.sessionId).then(()=>this.findSessionByWebId(e.webId)).then(r=>{i=r;const n=e.profileDocumentUrl;if(n)return $r(n.href,i?{fetch:i.fetch}:void 0);t(void 0)}).then(t=>{const r=Tr(t,e.webId),n=rn(r,I.vcard.fn,e.displayName),o=Rr(t,n);return this.saveDataset(i,n.url,o)}).then(()=>{t(e)}).catch(r)})}findSessionInfoById(e){return new Promise((t,r)=>{this.clientAuthentication.getSessionInfo(e).then(e=>{t(e)}).catch(r)})}findSessionById(e){return new Promise((t,r)=>{let n;this.findSessionInfoById(e).then(e=>{if(void 0!==e)return n=this.createSession({sessionInfo:e,storage:this.storage,insecureStorage:this.storage,secureStorage:this.storage}),!e.isLoggedIn&&e.issuer?n.login({oidcIssuer:e.issuer,clientId:e.clientAppId,clientSecret:e.clientAppSecret,handleRedirect:()=>{}}):void 0;t(void 0)}).then(()=>{t(n)}).catch(r)})}findSessionByWebId(e){return new Promise((t,r)=>{const n=`${SolidService.PREFIX}:webId:${e}`;this.storage.get(n).then(e=>{if(e)return this.findSessionById(e);t(void 0)}).then(e=>{t(e)}).catch(r)})}findSessionByObjectUID(e,t){return new Promise((r,n)=>{const i=`${`${SolidService.PREFIX}:${e.name}`}:${t}`;this.storage.get(i).then(e=>this.findSessionById(e)).then(r).catch(n)})}linkSession(e,t,r){return new Promise((n,i)=>{const o=null!=r?r:e.constructor,a=`${`${SolidService.PREFIX}:${o.name}`}:${e.uid}`;this.storage.set(a,t).then(n).catch(i)})}unlinkSession(e,t){return new Promise((r,n)=>{const i=null!=t?t:e.constructor,o=`${`${SolidService.PREFIX}:${i.name}`}:${e instanceof R.DataObject||e instanceof R.DataFrame?e.uid:e}`;this.storage.delete(o).then(r).catch(n)})}storeToDataset(e){const t={graphs:{default:{}},type:"Dataset"};return e.getSubjects(void 0,void 0,void 0).filter(e=>"BlankNode"!==e.termType).forEach(r=>{const n=I.RDFSerializer.quadsToThing(r,e);I.RDFSerializer.thingToSubjects(n).forEach(e=>{t.graphs.default[e.url]=e})}),t}}SolidService.PREFIX="OpenHPS:solid",I.RDFSerializer.getDocumentLoader().addContext("https://www.w3.org/ns/solid/notification/v1",{});let oh=class SolidProfileObject extends R.DataObject{constructor(e,t){super(e,t)}get webId(){return this.uid}set webId(e){this.uid=e}get name(){var e;return null!==(e=this._formattedName)&&void 0!==e?e:`${this.firstName} ${this.lastName}`}set name(e){this._formattedName=e}get profileDocumentUrl(){try{const e=new URL(this.webId);return e.hash="",e}catch(e){return}}};A([(0,R.SerializableMember)({rdf:{predicates:[I.vcard.given_name,I.foaf.givenname]}}),T("design:type",String)],oh.prototype,"firstName",void 0),A([(0,R.SerializableMember)({rdf:{predicates:[I.vcard.family_name,I.foaf.surname]}}),T("design:type",String)],oh.prototype,"lastName",void 0),A([(0,R.SerializableMember)({rdf:{predicates:[I.vcard.fn,I.foaf.name]}}),T("design:type",String)],oh.prototype,"_formattedName",void 0),A([(0,R.SerializableMember)({rdf:{predicates:[I.foaf.nick]}}),T("design:type",String)],oh.prototype,"nickname",void 0),A([(0,R.SerializableMember)({rdf:{predicate:[I.vcard.hasPhoto]}}),T("design:type",String)],oh.prototype,"picture",void 0),A([(0,R.SerializableMember)(),T("design:type",String)],oh.prototype,"oidcIssuer",void 0),A([(0,R.SerializableMember)(),T("design:type",String)],oh.prototype,"sessionId",void 0),oh=A([(0,R.SerializableObject)({rdf:{type:I.foaf.Person}}),T("design:paramtypes",[String,String])],oh),R.DataObject.prototype.webId=void 0,(0,R.SerializableMember)(String)(R.DataObject.prototype,"webId"),R.DataFrame.prototype.webId=void 0,(0,R.SerializableMember)(String)(R.DataFrame.prototype,"webId");class QueryEngine extends e().QueryEngineBase{constructor(e){super(e)}}class SolidDataDriver extends I.SPARQLDataDriver{constructor(e,t){var r,n,i;super(e,t),this.options.engine=null!==(r=this.options.engine)&&void 0!==r?r:require("./engine-default")(),this.options.engine&&(this.engine=new QueryEngine(this.options.engine)),this.options.lenient=!0,this.options.uriPrefix=this.options.uriPrefix||"/openhps",this.options.serialize=null!==(n=this.options.serialize)&&void 0!==n?n:ah,this.options.deserialize=null!==(i=this.options.deserialize)&&void 0!==i?i:sh,this.once("build",this._initService.bind(this))}_initService(){return E(this,void 0,void 0,function*(){return new Promise((e,t)=>this.model?(this.service=this.model.findService(SolidService),this.service?void e():t(new Error("Unable to find SolidDataService!"))):e())})}queryQuads(e,t,r){return r?super.queryQuads(e,Object.assign({"@comunica/actor-http-inrupt-solid-client-authn:session":r,sources:[r.info.webId],lenient:!0},t)):super.queryQuads(e,t)}queryBindings(e,t,r){return t?super.queryBindings(e,Object.assign({"@comunica/actor-http-inrupt-solid-client-authn:session":t,sources:[t.info.webId],lenient:!0},r)):super.queryBindings(e,r)}findByUID(e){return new Promise((t,r)=>{this.service.findSessionByObjectUID(this.dataType,e).then(t=>this.service.getThing(t,`/${this.options.uriPrefix}/${e}`)).then(e=>{const r=this.options.deserialize(e);t(r)}).catch(r)})}getQueryStore(e){return this.service.findSessionByWebId(e.webId).then(t=>this.service.getDataset(t,e.uri)).then(e=>{if(!e)return;const t=Object.values(e.graphs.default),r=I.RDFSerializer.subjectsToQuads(t);return new I.Store(r)})}findOne(e,t={}){return this.getQueryStore(e).then(r=>{if(r)return super.findOne(e.query,t,{sources:[r],lenient:!0})})}findAll(e,t={}){return this.getQueryStore(e).then(r=>r?super.findAll(e.query,Object.assign({},t),{sources:[r],lenient:!0}):[])}count(e){return this.getQueryStore(e).then(t=>t?super.count(e.query,{sources:[t],lenient:!0}):0)}insert(e,t){return new Promise((e,r)=>{if(!t.webId){if(!this.service.session)return r(new Error("Unable to store data object or frame without WebID!"));t.webId=this.service.session.info.webId}this.service.findSessionByWebId(t.webId).then(n=>E(this,void 0,void 0,function*(){if(!n)return void r(new Error(`Unable to find solid session for ${t.webId}!`));if(!n.info.isLoggedIn)return void r(new Error("Solid session is not logged in!"));yield this.service.linkSession(t,n.info.sessionId,this.dataType);const i=yield this.service.getPodUrl(n),o=this.options.serialize(t,i);if(0===o.length)return void r(new Error("Unable to serialize object to RDF!"));const a=new URL(o[0].url);a.hash="",yield this.linkObjectToSession(t.uid,a.href,n,this.dataType),this.service.getDataset(n,a.href).then(e=>{e||(e=this.service.createDataset());let t=Promise.resolve(e);for(let e=0;e<o.length;e++)t=t.then(t=>new Promise((r,i)=>{this.service.createThing(n,o[e],t).then(e=>{r(e)}).catch(i)}));return t}).then(e=>this.service.saveDataset(n,a.href,e)).then(()=>{e(t)}).catch(r)})).catch(r)})}delete(e){return new Promise((t,r)=>{let n,i;this.service.findSessionByObjectUID(this.dataType,e).then(t=>E(this,void 0,void 0,function*(){if(t)return i=t,n=yield this.findObjectURI(e,t,this.dataType),yield this.service.unlinkSession(e,this.dataType),yield this.unlinkObjectFromSession(e,t,this.dataType),$r(n,{fetch:t.fetch});r(new Error(`Unable to find solid session for ${this.dataType.name} with id '${e}'!`))})).then(e=>Object.values(e.graphs.default)[0].url===n?Lr(n,{fetch:i.fetch}):(e=kr(e,n),Dr(n,e,{fetch:i.fetch}))).then(()=>t()).catch(r)})}deleteAll(){throw new Error("Not supported with SolidDataDriver!")}findObjectURI(e,t,r){return new Promise((n,i)=>{const o=`${`${SolidService.PREFIX}:${r.name}`}:${t.info.sessionId}:${e}`;this.service.storage.get(o).then(e=>n(e)).catch(i)})}linkObjectToSession(e,t,r,n){return new Promise((i,o)=>{const a=`${`${SolidService.PREFIX}:${n.name}`}:${r.info.sessionId}:${e}`;this.service.storage.set(a,t).then(i).catch(o)})}unlinkObjectFromSession(e,t,r){return new Promise((n,i)=>{const o=`${`${SolidService.PREFIX}:${r.name}`}:${t.info.sessionId}:${e}`;this.service.storage.delete(o).then(n).catch(i)})}}function ah(e,t){return I.RDFSerializer.serializeToSubjects(e,t)}function sh(e){return I.RDFSerializer.deserializeFromSubjects(e.url,[e])}function ch(e){return!e.collection||e.collection.members.length<50}class SolidPropertyService extends R.DataService{constructor(e){super(new SolidDataDriver(void 0,{sources:[void 0],lenient:!0})),this.filter=null!=e?e:ch}get session(){return this.service.session}set service(e){this.driver.service=e}get service(){return this.driver.service}fetchProperties(e,t){return new Promise((r,n)=>{const i=`SELECT DISTINCT ?property ?name WHERE {\n ?me <${I.ssn.hasProperty}> ?property .\n OPTIONAL {\n ?property <${I.rdfs.label}> ?name .\n }\n FILTER(?me = <${t.webId}>)\n }`;this.driver.queryBindings(i,e,{sources:[t.webId],lenient:!0}).then(e=>{const t=[];e.forEach(e=>{const r=e.get("property").value,n=e.has("name")?e.get("name").value:void 0,i=new I.Property;i.id=r,i.label=n,t.push(i)}),r(t)}).catch(n)})}createProperty(e,t){return new Promise((r,n)=>{const i=this.getPropertyContainer(t);t.id.endsWith("/property.ttl")||(t.id=`${t.id.replace(/\/$/,"")}/property.ttl`),this.service.getDatasetStore(e,e.info.webId).then(r=>{const n=I.RDFSerializer.quadsToThing(I.DataFactory.namedNode(e.info.webId),r),i=I.RDFBuilder.fromSerialized(n);i.add(I.ssn.hasProperty,t.id);const o=i.build(!0);let a=!1;return o.additions.length>0&&(a=!0,r.addQuads(o.additions)),o.deletions.length>0&&(a=!0,r.removeQuads(o.deletions)),a?this.service.saveDataset(e,e.info.webId,r):Promise.resolve()}).then(()=>this.service.getDataset(e,i.href)).then(n=>{if(!n)return this.service.createContainer(e,i.href);r(t.id)}).then(()=>Promise.all([this.service.getDatasetStore(e,`${i.href}property.ttl`),this.service.getDatasetStore(e,`${i.href}.meta`)])).then(([r,n])=>{r.addQuads(I.RDFSerializer.serializeToQuads(t));const o=new URL(`${i.href}property.ttl`);o.hash="EventStream";const a=new URL(`${i.href}property.ttl`);a.hash="root";const s=new eh(o.href);return s.setTimestampPath(I.sosa.resultTime),s.view=new Zd(a.href),n.addQuads(I.RDFSerializer.serializeToQuads(s)),r.addQuads(I.RDFSerializer.serializeToQuads(s.view)),this.service.saveDataset(e,`${i.href}property.ttl`,r).then(()=>this.service.saveDataset(e,`${i.href}.meta`,n))}).then(()=>{r(t.id)}).catch(n)})}createTreeNode(e,t,r){return new Promise((n,i)=>{const o=new URL(t.id);o.hash="";const a=`${o.href}${L(o.href)?(o.href.endsWith("/")?"":"/")+".meta":""}`;this.service.getDatasetStore(e,a).then(n=>(n.addQuads(I.RDFSerializer.serializeToQuads(t,`${o.href}#`)),r&&n.addQuads(I.RDFSerializer.serializeToQuads(r,`${o.href}#`)),this.service.saveDataset(e,a,n))).then(()=>n(t)).catch(i)})}fetchTreeNode(e,t,r){return new Promise((n,i)=>{const o=new URL(t.id);o.hash="";const a=`${o.href}${L(o.href)?(o.href.endsWith("/")?"":"/")+".meta":""}`;this.service.getDatasetStore(e,a).then(e=>{if(I.RDFSerializer.quadsToThing(I.DataFactory.namedNode(t.id),e)){const o=I.RDFSerializer.deserializeFromStore(t.id,e,Zd),a=r?I.RDFSerializer.deserializeFromStore(r,e,Yd):void 0;o?(o.collection=a,n(o)):i(new Error("Node could not be deserialized"))}else i(new Error("Node not found"))}).catch(i)})}findRootNode(e,t){return new Promise((r,n)=>{this.getPropertyContainer(t);Promise.all([this.service.getDatasetStore(e,`${t.id}`)]).then(e=>E(this,[e],void 0,function*([e]){const t=yield this.driver.queryBindings(`SELECT DISTINCT ?node WHERE {\n ?node a <${Hd.Node}> . \n }`,void 0,{sources:[e]});if(0===t.length)return void r(void 0);const n=I.RDFSerializer.deserializeFromStore(I.DataFactory.namedNode(t[0].get("node").value),e);r(n||void 0)})).catch(n)})}getPropertyContainer(e){const t=new URL(e.id);return t.hash="",e.id.endsWith("/property.ttl")&&(t.pathname=t.pathname.replace(/\/property\.ttl$/,"")),t.href.endsWith("/")||(t.pathname+="/"),t}addObservation(e,t,r){return new Promise((n,i)=>{const o=this.getPropertyContainer(t);this.findRootNode(e,t).then(n=>E(this,void 0,void 0,function*(){if(!(n||(yield this.createProperty(e,t),n=yield this.findRootNode(e,t))))throw new Error("Root node could not be created");for(const e of n.relations){if(!e.node)throw console.error(e),new Error("Relation node not found");if(!e.value)throw console.error(e),new Error("Relation value not found")}let i=n.getChildNode(r.resultTime);i&&(i=yield this.fetchTreeNode(e,i,o.href),i=this.filter(i)?i:void 0),i||(i=new Zd,i.id=`${o.href}${r.resultTime.getTime()}/`,yield this.service.createContainer(e,i.id),n.relations.push(new Jd(r.resultTime,i).setPath(I.sosa.resultTime)),yield this.createTreeNode(e,n)),r.id=`${i.id}${this.generateUUID()}.ttl`;const a=new Yd(o.href);return a.members.push(r),yield this.createTreeNode(e,i,a),this.service.saveDataset(e,`${r.id}`,I.RDFSerializer.serializeToStore(r),!0)})).then(()=>{n()}).catch(i)})}fetchObservations(e,t,r={}){return new Promise((n,i)=>{this.findAll({query:Object.assign({},r.after?{resultTime:{$gte:r.after}}:{}),limit:r.limit,uri:t.id,webId:e.info.webId},{dataType:I.Observation}).then(e=>{n(e)}).catch(i)})}}class SolidPropertySink extends R.SinkNode{constructor(e){super(e),this.once("ready",this.onBuild.bind(this))}onBuild(){return new Promise((e,t)=>{this.service=this.model.findService(SolidPropertyService),this.service||t(new Error("No Solid session found")),e()})}onPush(e,t){return new Promise((t,r)=>{Array.isArray(e)?Promise.all(e.map(e=>this.writeFrame(e))).then(()=>t()).catch(r):this.writeFrame(e).then(()=>t()).catch(r)})}prepareProperty(e,t){return new Promise((r,n)=>{this.service.service.getDocumentURL(t,"/properties/").then(i=>{let o;if(e===uh.POSITION){const e=new I.Property(i.href+"position/");e.label="Position",o=this.service.createProperty(t,e)}o.then(r).catch(n)}).catch(n)})}writeFrame(e){return new Promise((t,r)=>{let n=[];for(const e of this.options.properties)e===uh.POSITION&&n.push(this.prepareProperty(e,this.service.session));Promise.all(n).then(t=>{n=[];for(const r of e.getObjects())for(const[i,o]of this.options.properties.entries()){const a=new I.ObservableProperty(t[i]),s=new I.Observation(`_:${e.createdTimestamp}`);s.resultTime=new Date(e.createdTimestamp),s.observedProperties=[a],r.webId&&(s.featuresOfInterest=[new I.FeatureOfInterest(r.webId)]),o===uh.POSITION&&(s.results=[r.position]),n.push(this.service.addObservation(this.service.session,a,s))}return Promise.all(n)}).then(()=>t()).catch(r)})}}var uh;!function(e){e[e.POSITION=0]="POSITION"}(uh||(uh={}));class SolidPropertySource extends R.SourceNode{constructor(e){super(e),this.once("ready",this.onBuild.bind(this))}onBuild(){return new Promise((e,t)=>{this.service=this.model.findService(SolidPropertyService),this.service||t(new Error("No Solid session found")),e()})}onPull(e){throw new Error("Method not implemented.")}}const lh=function(){const e=new(require("@comunica/logger-void").LoggerVoid),t=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-init/^5.0.0/components/ActorInit.jsonld#ActorInit_default_bus"}),r=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-extract-links/^0.0.0/components/ActorExtractLinks.jsonld#ActorExtractLinks_default_bus"}),n=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-context-preprocess/^5.0.0/components/ActorContextPreprocess.jsonld#ActorContextPreprocess_default_bus"}),i=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-factory-aggregated-store/^0.0.0/components/ActorFactoryAggregatedStore.jsonld#ActorFactoryAggregatedStore_default_bus"}),o=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-hash-bindings/^5.0.0/components/ActorHashBindings.jsonld#ActorHashBindings_default_bus"}),a=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-hash-quads/^5.0.0/components/ActorHashQuads.jsonld#ActorHashQuads_default_bus"}),s=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-optimize-query-operation/^5.0.0/components/ActorOptimizeQueryOperation.jsonld#ActorOptimizeQueryOperation_default_bus"}),c=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-query-parse/^5.0.0/components/ActorQueryParse.jsonld#ActorQueryParse_default_bus"}),u=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-query-result-serialize/^5.0.0/components/ActorQueryResultSerialize.jsonld#ActorQueryResultSerialize_default_bus"}),l=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-query-serialize/^5.0.0/components/ActorQuerySerialize.jsonld#ActorQuerySerialize_default_bus"}),d=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-query-source-dereference-link/^5.0.0/components/ActorQuerySourceDereferenceLink.jsonld#ActorQuerySourceDereferenceLink_default_bus"}),h=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-query-source-identify-hypermedia/^5.0.0/components/ActorQuerySourceIdentifyHypermedia.jsonld#ActorQuerySourceIdentifyHypermedia_default_bus"}),f=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-dereference/^5.0.0/components/ActorDereference.jsonld#ActorDereference_default_bus"}),p=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-dereference-rdf/^5.0.0/components/ActorDereferenceRdf.jsonld#ActorDereferenceRdf_default_bus"}),m=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-join-entries-sort/^5.0.0/components/ActorRdfJoinEntriesSort.jsonld#ActorRdfJoinEntriesSort_default_bus"}),y=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-join-selectivity/^5.0.0/components/ActorRdfJoinSelectivity.jsonld#ActorRdfJoinSelectivity_default_bus"}),g=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-metadata/^5.0.0/components/ActorRdfMetadata.jsonld#ActorRdfMetadata_default_bus"}),_=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-metadata-accumulate/^5.0.0/components/ActorRdfMetadataAccumulate.jsonld#ActorRdfMetadataAccumulate_default_bus"}),b=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-metadata-extract/^5.0.0/components/ActorRdfMetadataExtract.jsonld#ActorRdfMetadataExtract_default_bus"}),w=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-parse/^5.0.0/components/ActorRdfParse.jsonld#ActorRdfParse_default_bus"}),v=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-parse-html/^5.0.0/components/ActorRdfParseHtml.jsonld#ActorRdfParseHtml_default_bus"}),S=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-resolve-hypermedia-links/^5.0.0/components/ActorRdfResolveHypermediaLinks.jsonld#ActorRdfResolveHypermediaLinks_default_bus"}),x=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-resolve-hypermedia-links-queue/^5.0.0/components/ActorRdfResolveHypermediaLinksQueue.jsonld#ActorRdfResolveHypermediaLinksQueue_default_bus"}),I=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-serialize/^5.0.0/components/ActorRdfSerialize.jsonld#ActorRdfSerialize_default_bus"}),A=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-update-hypermedia/^5.0.0/components/ActorRdfUpdateHypermedia.jsonld#ActorRdfUpdateHypermedia_default_bus"}),T=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-update-quads/^5.0.0/components/ActorRdfUpdateQuads.jsonld#ActorRdfUpdateQuads_default_bus"}),E=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-bindings-aggregator-factory/^5.0.0/components/ActorBindingsAggregatorFactory.jsonld#ActorBindingsAggregatorFactory_default_bus"}),R=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-expression-evaluator-factory/^5.0.0/components/ActorExpressionEvaluatorFactory.jsonld#ActorExpressionEvaluatorFactory_default_bus"}),k=new(require("@comunica/bus-function-factory").BusFunctionFactory)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-function-factory/^5.0.0/components/ActorFunctionFactory.jsonld#ActorFunctionFactory_default_bus"}),j=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-http/^5.0.0/components/ActorHttp.jsonld#ActorHttp_default_bus"}),N=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-http/^5.0.0/components/ActorHttp.jsonld#ActorHttp_fallback_bus"}),C=new(require("@comunica/bus-query-operation").BusQueryOperation)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-query-operation/^5.0.0/components/ActorQueryOperation.jsonld#ActorQueryOperation_default_bus"}),P=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-query-process/^5.0.0/components/ActorQueryProcess.jsonld#ActorQueryProcess_default_bus"}),O=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-query-source-identify/^5.0.0/components/ActorQuerySourceIdentify.jsonld#ActorQuerySourceIdentify_default_bus"}),F=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-rdf-join/^5.0.0/components/ActorRdfJoin.jsonld#ActorRdfJoin_default_bus"}),q=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-term-comparator-factory/^5.0.0/components/ActorTermComparatorFactory.jsonld#ActorTermComparatorFactory_default_bus"}),M=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-http-invalidate/^5.0.0/components/ActorHttpInvalidate.jsonld#ActorHttpInvalidate_default_bus"}),$=new(require("@comunica/core").Bus)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/bus-merge-bindings-context/^5.0.0/components/ActorMergeBindingsContext.jsonld#ActorMergeBindingsContext_default_bus"}),D=(new(require("@comunica/actor-extract-links-predicates").ActorExtractLinksPredicates)({checkSubject:!1,predicateRegexes:["http://www.w3.org/2000/01/rdf-schema#seeAlso","http://www.w3.org/2002/07/owl##sameAs","http://xmlns.com/foaf/0.1/isPrimaryTopicOf"],name:"urn:comunica:default:extract-links/actors#predicates-common",bus:r}),new(require("@comunica/actor-extract-links-predicates").ActorExtractLinksPredicates)({checkSubject:!0,predicateRegexes:["http://www.w3.org/ns/ldp#contains"],name:"urn:comunica:default:extract-links/actors#predicates-ldp",bus:r}),new(require("@comunica/actor-extract-links-headers").ActorExtractLinksHeaders)({headersRegexes:['rel="describedby"'],name:"urn:comunica:default:extract-links/actors#links-describedby",bus:r}),new(require("@comunica/actor-extract-links-predicates").ActorExtractLinksPredicates)({checkSubject:!0,predicateRegexes:["http://www.w3.org/ns/pim/space#storage"],name:"urn:comunica:default:extract-links/actors#predicates-solid",bus:r}),new(require("@comunica/actor-extract-links-quad-pattern-query").ActorExtractLinksQuadPatternQuery)({onlyVariables:!0,name:"urn:comunica:default:extract-links/actors#quad-pattern-query",bus:r}),new(require("@comunica/mediator-combine-array").MediatorCombineArray)({filterErrors:!0,fields:["links","linksConditional"],name:"urn:comunica:default:extract-links/mediators#main",bus:r})),L=(new(require("@comunica/actor-context-preprocess-convert-shortcuts").ActorContextPreprocessConvertShortcuts)({contextKeyShortcuts:{baseIRI:"@comunica/actor-init-query:baseIRI",dataFactory:"@comunica/actor-init-query:dataFactory",datetime:"@comunica/actor-http-memento:datetime",destination:"@comunica/bus-rdf-update-quads:destination",distinctConstruct:"@comunica/actor-init-query:distinctConstruct",explain:"@comunica/actor-init-query:explain",extensionFunctionCreator:"@comunica/actor-init-query:extensionFunctionCreator",extensionFunctions:"@comunica/actor-init-query:extensionFunctions",extensionFunctionsAlwaysPushdown:"@comunica/actor-init-query:extensionFunctionsAlwaysPushdown",fetch:"@comunica/bus-http:fetch",fileBaseIRI:"@comunica/actor-init-query:fileBaseIRI",fullTermComparison:"@comunica/utils-expression-evaluator:fullTermComparison",functionArgumentsCache:"@comunica/actor-init-query:functionArgumentsCache",httpAbortSignal:"@comunica/bus-http:http-abort-controller",httpAuth:"@comunica/bus-http:auth",httpBodyTimeout:"@comunica/bus-http:http-body-timeout",httpCache:"@comunica/bus-http:httpCache",httpIncludeCredentials:"@comunica/bus-http:include-credentials",httpProxyHandler:"@comunica/actor-http-proxy:httpProxyHandler",httpRetryBodyAllowUnsafe:"@comunica/bus-http:http-retry-body-allow-unsafe",httpRetryBodyCount:"@comunica/bus-http:http-retry-body-count",httpRetryBodyDelayFallback:"@comunica/bus-http:http-retry-body-delay-fallback",httpRetryBodyMaxBytes:"@comunica/bus-http:http-retry-body-max-bytes",httpRetryCount:"@comunica/bus-http:http-retry-count",httpRetryDelayFallback:"@comunica/bus-http:http-retry-delay-fallback",httpRetryDelayLimit:"@comunica/bus-http:http-retry-delay-limit",httpRetryStatusCodes:"@comunica/bus-http:http-retry-status-codes",httpTimeout:"@comunica/bus-http:http-timeout",initialBindings:"@comunica/actor-init-query:initialBindings",invalidateCache:"@comunica/actor-init-query:invalidateCache",lenient:"@comunica/actor-init-query:lenient",log:"@comunica/core:log",nonLexicalComparison:"@comunica/utils-expression-evaluator:nonLexicalComparison",parseUnsupportedVersions:"@comunica/actor-init-query:parseUnsupportedVersions",queryFormat:"@comunica/actor-init-query:queryFormat",queryTimestamp:"@comunica/actor-init-query:queryTimestamp",queryTimestampHighResolution:"@comunica/actor-init-query:queryTimestampHighResolution",rdfSerializationPrefixes:"@comunica/bus-rdf-serialize:rdfSerializationPrefixes",readOnly:"@comunica/bus-query-operation:readOnly",recoverBrokenLinks:"@comunica/bus-http-wayback:recover-broken-links",serviceAllowFileTargets:"@comunica/actor-init-query:serviceAllowFileTargets",serviceAllowVariableTargets:"@comunica/actor-init-query:serviceAllowVariableTargets",sources:"@comunica/actor-init-query:querySourcesUnidentified",traverse:"@comunica/bus-query-source-identify:traverse",unionDefaultGraph:"@comunica/bus-query-operation:unionDefaultGraph"},name:"urn:comunica:default:context-preprocess/actors#convert-shortcuts",bus:n,busFailMessage:"Context preprocessing failed"}),new(require("@comunica/actor-context-preprocess-set-defaults").ActorContextPreprocessSetDefaults)({logger:e,name:"urn:comunica:default:context-preprocess/actors#set-defaults",bus:n,busFailMessage:"Context preprocessing failed"}),new(require("@comunica/actor-context-preprocess-source-to-destination").ActorContextPreprocessSourceToDestination)({name:"urn:comunica:default:context-preprocess/actors#source-to-destination",bus:n,busFailMessage:"Context preprocessing failed"}),new(require("@comunica/actor-context-preprocess-set-defaults-link-traversal").ActorContextPreprocessSetDefaultsLinkTraversal)({name:"urn:comunica:default:context-preprocess/actors#set-defaults-link-traversal",bus:n,busFailMessage:"Context preprocessing failed"}),new(require("@comunica/mediator-combine-pipeline").MediatorCombinePipeline)({name:"urn:comunica:default:context-preprocess/mediators#main",bus:n})),U=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:factory-aggregated-store/mediators#main",bus:i}),z=(new(require("@comunica/actor-hash-bindings-murmur").ActorHashBindingsMurmur)({name:"urn:comunica:default:hash-bindings/actors#murmur",bus:o,busFailMessage:"Failed to obtaining hash functions for bindings"}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:hash-bindings/mediators#main",bus:o})),B=(new(require("@comunica/actor-hash-quads-murmur").ActorHashQuadsMurmur)({name:"urn:comunica:default:hash-quads/actors#murmur",bus:a,busFailMessage:"Failed to obtaining hash functions for quads"}),new(require("@comunica/actor-optimize-query-operation-rewrite-copy").ActorOptimizeQueryOperationRewriteCopy)({name:"urn:comunica:default:optimize-query-operation/actors#rewrite-copy",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize"}),new(require("@comunica/actor-optimize-query-operation-rewrite-move").ActorOptimizeQueryOperationRewriteMove)({name:"urn:comunica:default:optimize-query-operation/actors#rewrite-move",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize"}),new(require("@comunica/actor-optimize-query-operation-rewrite-add").ActorOptimizeQueryOperationRewriteAdd)({name:"urn:comunica:default:optimize-query-operation/actors#rewrite-add",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize"}),new(require("@comunica/actor-optimize-query-operation-group-sources").ActorOptimizeQueryOperationGroupSources)({name:"urn:comunica:default:optimize-query-operation/actors#group-sources",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize"})),Q=(new(require("@comunica/actor-optimize-query-operation-construct-distinct").ActorOptimizeQueryOperationConstructDistinct)({name:"urn:comunica:default:optimize-query-operation/actors#construct-distinct",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize"}),new(require("@comunica/mediator-combine-pipeline").MediatorCombinePipeline)({filterFailures:!0,name:"urn:comunica:default:optimize-query-operation/mediators#main",bus:s})),H=(new(require("@comunica/actor-query-parse-sparql").ActorQueryParseSparql)({prefixes:{dbpedia:"http://dbpedia.org/resource/","dbpedia-owl":"http://dbpedia.org/ontology/",dbpprop:"http://dbpedia.org/property/",dc:"http://purl.org/dc/terms/",dc11:"http://purl.org/dc/elements/1.1/",dcterms:"http://purl.org/dc/terms/",foaf:"http://xmlns.com/foaf/0.1/",geo:"http://www.w3.org/2003/01/geo/wgs84_pos#",owl:"http://www.w3.org/2002/07/owl#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",schema:"http://schema.org/",skos:"http://www.w3.org/2008/05/skos#",xsd:"http://www.w3.org/2001/XMLSchema#"},minimalErrorMessages:!1,name:"urn:comunica:default:query-parse/actors#sparql",bus:c,busFailMessage:'Query parsing failed: none of the configured parsers were able to the query "${action.query}"'}),new(require("@comunica/actor-query-parse-graphql").ActorQueryParseGraphql)({name:"urn:comunica:default:query-parse/actors#graphql",bus:c,busFailMessage:'Query parsing failed: none of the configured parsers were able to the query "${action.query}"'}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:query-parse/mediators#main",bus:c})),K=(new(require("@comunica/actor-query-result-serialize-json").ActorQueryResultSerializeJson)({mediaTypePriorities:{"application/json":1},mediaTypeFormats:{"application/json":"https://comunica.linkeddatafragments.org/#results_JSON"},name:"urn:comunica:default:query-result-serialize/actors#json",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/actor-query-result-serialize-simple").ActorQueryResultSerializeSimple)({mediaTypePriorities:{simple:.9},mediaTypeFormats:{simple:"https://comunica.linkeddatafragments.org/#results_simple"},name:"urn:comunica:default:query-result-serialize/actors#simple",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/actor-query-result-serialize-sparql-csv").ActorQueryResultSerializeSparqlCsv)({mediaTypePriorities:{"text/csv":.75},mediaTypeFormats:{"text/csv":"http://www.w3.org/ns/formats/SPARQL_Results_CSV"},name:"urn:comunica:default:query-result-serialize/actors#csv",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/actor-query-result-serialize-sparql-tsv").ActorQueryResultSerializeSparqlTsv)({mediaTypePriorities:{"text/tab-separated-values":.75},mediaTypeFormats:{"text/tab-separated-values":"http://www.w3.org/ns/formats/SPARQL_Results_TSV"},name:"urn:comunica:default:query-result-serialize/actors#sparql-tsv",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/actor-query-result-serialize-sparql-xml").ActorQueryResultSerializeSparqlXml)({mediaTypePriorities:{"application/sparql-results+xml":.8},mediaTypeFormats:{"application/sparql-results+xml":"http://www.w3.org/ns/formats/SPARQL_Results_XML"},name:"urn:comunica:default:query-result-serialize/actors#sparql-xml",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/actor-query-result-serialize-table").ActorQueryResultSerializeTable)({columnWidth:50,mediaTypePriorities:{table:.6},mediaTypeFormats:{table:"https://comunica.linkeddatafragments.org/#results_table"},name:"urn:comunica:default:query-result-serialize/actors#table",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/actor-query-result-serialize-tree").ActorQueryResultSerializeTree)({mediaTypePriorities:{tree:.5},mediaTypeFormats:{tree:"https://comunica.linkeddatafragments.org/#results_tree"},name:"urn:comunica:default:query-result-serialize/actors#tree",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:query-result-serialize/mediators#serialize",bus:u})),W=new(require("@comunica/mediator-combine-union").MediatorCombineUnion)({field:"mediaTypes",name:"urn:comunica:default:query-result-serialize/mediators#mediaType",bus:u}),J=new(require("@comunica/mediator-combine-union").MediatorCombineUnion)({field:"mediaTypeFormats",name:"urn:comunica:default:query-result-serialize/mediators#mediaTypeFormat",bus:u}),G=(new(require("@comunica/actor-query-serialize-sparql").ActorQuerySerializeSparql)({name:"urn:comunica:default:query-serialize/actors#sparql",bus:l,busFailMessage:'Query serializing failed: none of the configured parsers were able to serialize for the query language "${action.queryFormat.language}" at version "${action.queryFormat.version}"'}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:query-serialize/mediators#main",bus:l})),V=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:query-source-dereference-link/mediators#main",bus:d}),X=new(require("@comunica/mediator-number").MediatorNumber)({field:"filterFactor",type:"max",ignoreFailures:!0,name:"urn:comunica:default:query-source-identify-hypermedia/mediators#main",bus:h}),Y=new(require("@comunica/actor-dereference-fallback").ActorDereferenceFallback)({name:"urn:comunica:default:dereference/actors#fallback",bus:f,busFailMessage:"Dereferencing failed: none of the configured actors were able to handle ${action.url}"}),Z=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:dereference/mediators#main",bus:f}),ee=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:dereference-rdf/mediators#main",bus:p}),te=(new(require("@comunica/actor-rdf-join-entries-sort-traversal-zero-knowledge").ActorRdfJoinEntriesSortTraversalZeroKnowledge)({name:"urn:comunica:default:rdf-join-entries-sort/actors#traversal-zero-knowledge",bus:m,busFailMessage:"Sorting join entries failed: none of the configured actors were able to sort"}),new(require("@comunica/mediator-number").MediatorNumber)({field:"accuracy",type:"max",ignoreFailures:!0,name:"urn:comunica:default:rdf-join-entries-sort/mediators#main",bus:m})),re=(new(require("@comunica/actor-rdf-join-selectivity-variable-counting").ActorRdfJoinSelectivityVariableCounting)({name:"urn:comunica:default:rdf-join-selectivity/actors#variable-counting",bus:y,busFailMessage:"Determining join selectivity failed: none of the configured actors were able to calculate selectivities"}),new(require("@comunica/mediator-number").MediatorNumber)({field:"accuracy",type:"max",ignoreFailures:!0,name:"urn:comunica:default:rdf-join-selectivity/mediators#main",bus:y})),ne=(new(require("@comunica/actor-rdf-metadata-primary-topic").ActorRdfMetadataPrimaryTopic)({metadataToData:!1,dataToMetadataOnInvalidMetadataGraph:!0,name:"urn:comunica:default:rdf-metadata/actors#primary-topic",bus:g,busFailMessage:"Metadata splicing failed: none of the configured actors were able to splice metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-all").ActorRdfMetadataAll)({name:"urn:comunica:default:rdf-metadata/actors#all",bus:g,busFailMessage:"Metadata splicing failed: none of the configured actors were able to splice metadata from ${action.url}"}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:rdf-metadata/mediators#main",bus:g})),ie=(new(require("@comunica/actor-rdf-metadata-accumulate-cardinality").ActorRdfMetadataAccumulateCardinality)({name:"urn:comunica:default:rdf-metadata-accumulate/actors#cardinality",bus:_,busFailMessage:"Metadata accumulation failed: none of the configured actors were able to accumulate metadata in mode ${action.mode}"}),new(require("@comunica/actor-rdf-metadata-accumulate-pagesize").ActorRdfMetadataAccumulatePageSize)({name:"urn:comunica:default:rdf-metadata-accumulate/actors#pagesize",bus:_,busFailMessage:"Metadata accumulation failed: none of the configured actors were able to accumulate metadata in mode ${action.mode}"}),new(require("@comunica/actor-rdf-metadata-accumulate-requesttime").ActorRdfMetadataAccumulateRequestTime)({name:"urn:comunica:default:rdf-metadata-accumulate/actors#requesttime",bus:_,busFailMessage:"Metadata accumulation failed: none of the configured actors were able to accumulate metadata in mode ${action.mode}"}),new(require("@comunica/mediator-combine-union").MediatorCombineUnion)({field:"metadata",name:"urn:comunica:default:rdf-metadata-accumulate/mediators#main",bus:_})),oe=(new(require("@comunica/actor-rdf-metadata-extract-hydra-controls").ActorRdfMetadataExtractHydraControls)({name:"urn:comunica:default:rdf-metadata-extract/actors#hydra-controls",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-extract-hydra-count").ActorRdfMetadataExtractHydraCount)({predicates:["http://www.w3.org/ns/hydra/core#totalItems","http://rdfs.org/ns/void#triples"],name:"urn:comunica:default:rdf-metadata-extract/actors#hydra-count",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-extract-hydra-pagesize").ActorRdfMetadataExtractHydraPagesize)({predicates:["http://www.w3.org/ns/hydra/core#itemsPerPage"],name:"urn:comunica:default:rdf-metadata-extract/actors#hydra-pagesize",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-extract-request-time").ActorRdfMetadataExtractRequestTime)({name:"urn:comunica:default:rdf-metadata-extract/actors#request-time",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-extract-allow-http-methods").ActorRdfMetadataExtractAllowHttpMethods)({name:"urn:comunica:default:rdf-metadata-extract/actors#allow-http-methods",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-extract-post-accepted").ActorRdfMetadataExtractPostAccepted)({name:"urn:comunica:default:rdf-metadata-extract/actors#post-accepted",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-extract-put-accepted").ActorRdfMetadataExtractPutAccepted)({name:"urn:comunica:default:rdf-metadata-extract/actors#put-accepted",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-extract-patch-sparql-update").ActorRdfMetadataExtractPatchSparqlUpdate)({name:"urn:comunica:default:rdf-metadata-extract/actors#patch-sparql-update",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-extract-sparql-service").ActorRdfMetadataExtractSparqlService)({inferHttpsEndpoint:!0,name:"urn:comunica:default:rdf-metadata-extract/actors#sparql-service",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-metadata-extract-void").ActorRdfMetadataExtractVoid)({name:"urn:comunica:default:rdf-metadata-extract/actors#void",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/mediator-combine-union").MediatorCombineUnion)({filterFailures:!0,field:"metadata",name:"urn:comunica:default:rdf-metadata-extract/mediators#main",bus:b})),ae=(new(require("@comunica/actor-rdf-parse-n3").ActorRdfParseN3)({mediaTypePriorities:{"application/n-quads":1,"application/n-triples":.8,"application/trig":.95,"text/n3":.35,"text/turtle":.6},mediaTypeFormats:{"application/n-quads":"http://www.w3.org/ns/formats/N-Quads","application/n-triples":"http://www.w3.org/ns/formats/N-Triples","application/trig":"http://www.w3.org/ns/formats/TriG","text/n3":"http://www.w3.org/ns/formats/N3","text/turtle":"http://www.w3.org/ns/formats/Turtle"},priorityScale:1,name:"urn:comunica:default:rdf-parse/actors#n3",bus:w,busFailMessage:"RDF parsing failed: none of the configured parsers were able to handle the media type ${action.handle.mediaType} for ${action.handle.url}"}),new(require("@comunica/actor-rdf-parse-rdfxml").ActorRdfParseRdfXml)({mediaTypePriorities:{"application/rdf+xml":1},mediaTypeFormats:{"application/rdf+xml":"http://www.w3.org/ns/formats/RDF_XML"},priorityScale:.5,name:"urn:comunica:default:rdf-parse/actors#rdfxml",bus:w,busFailMessage:"RDF parsing failed: none of the configured parsers were able to handle the media type ${action.handle.mediaType} for ${action.handle.url}"}),new(require("@comunica/actor-rdf-parse-xml-rdfa").ActorRdfParseXmlRdfa)({mediaTypePriorities:{"application/xml":1,"image/svg+xml":1,"text/xml":1},mediaTypeFormats:{"application/xml":"http://www.w3.org/ns/formats/RDFa","image/svg+xml":"http://www.w3.org/ns/formats/RDFa","text/xml":"http://www.w3.org/ns/formats/RDFa"},priorityScale:.3,name:"urn:comunica:default:rdf-parse/actors#xmlrdfa",bus:w,busFailMessage:"RDF parsing failed: none of the configured parsers were able to handle the media type ${action.handle.mediaType} for ${action.handle.url}"}),new(require("@comunica/actor-rdf-parse-shaclc").ActorRdfParseShaclc)({mediaTypePriorities:{"text/shaclc":1,"text/shaclc-ext":.5},mediaTypeFormats:{"text/shaclc":"http://www.w3.org/ns/formats/Shaclc","text/shaclc-ext":"http://www.w3.org/ns/formats/ShaclcExtended"},priorityScale:.1,name:"urn:comunica:default:rdf-parse/actors#shaclc",bus:w,busFailMessage:"RDF parsing failed: none of the configured parsers were able to handle the media type ${action.handle.mediaType} for ${action.handle.url}"}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:rdf-parse/mediators#parse",bus:w})),se=new(require("@comunica/mediator-combine-union").MediatorCombineUnion)({field:"mediaTypes",name:"urn:comunica:default:rdf-parse/mediators#mediaType",bus:w}),ce=(new(require("@comunica/actor-rdf-parse-html").ActorRdfParseHtml)({busRdfParseHtml:v,mediaTypePriorities:{"application/xhtml+xml":.9,"text/html":1},mediaTypeFormats:{"application/xhtml+xml":"http://www.w3.org/ns/formats/HTML","text/html":"http://www.w3.org/ns/formats/HTML"},priorityScale:.2,name:"urn:comunica:default:rdf-parse/actors#html",bus:w,busFailMessage:"RDF parsing failed: none of the configured parsers were able to handle the media type ${action.handle.mediaType} for ${action.handle.url}"}),new(require("@comunica/actor-rdf-parse-html-microdata").ActorRdfParseHtmlMicrodata)({name:"urn:comunica:default:rdf-parse-html/actors#microdata",bus:v,busFailMessage:"RDF HTML parsing failed: none of the configured parsers were able to parse RDF in HTML"}),new(require("@comunica/actor-rdf-parse-html-rdfa").ActorRdfParseHtmlRdfa)({name:"urn:comunica:default:rdf-parse-html/actors#rdfa",bus:v,busFailMessage:"RDF HTML parsing failed: none of the configured parsers were able to parse RDF in HTML"}),new(require("@comunica/actor-rdf-resolve-hypermedia-links-next").ActorRdfResolveHypermediaLinksNext)({name:"urn:comunica:default:rdf-resolve-hypermedia-links/actors#next",bus:S,busFailMessage:"Hypermedia link resolution failed: none of the configured actors were able to resolve links from metadata"}),new(require("@comunica/actor-rdf-resolve-hypermedia-links-traverse").ActorRdfResolveHypermediaLinksTraverse)({name:"urn:comunica:default:rdf-resolve-hypermedia-links/actors#traverse",bus:S,busFailMessage:"Hypermedia link resolution failed: none of the configured actors were able to resolve links from metadata"}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:rdf-resolve-hypermedia-links/mediators#main",bus:S})),ue=(new(require("@comunica/actor-rdf-resolve-hypermedia-links-queue-fifo").ActorRdfResolveHypermediaLinksQueueFifo)({name:"urn:comunica:default:rdf-resolve-hypermedia-links-queue/actors#fifo",bus:x,busFailMessage:"Link queue creation failed: none of the configured actors were able to create a link queue"}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:rdf-resolve-hypermedia-links-queue/mediators#main",bus:x})),le=(new(require("@comunica/actor-rdf-serialize-n3").ActorRdfSerializeN3)({mediaTypePriorities:{"application/n-quads":1,"application/n-triples":.8,"application/trig":.95,"text/n3":.35,"text/turtle":.6},mediaTypeFormats:{"application/n-quads":"http://www.w3.org/ns/formats/N-Quads","application/n-triples":"http://www.w3.org/ns/formats/N-Triples","application/trig":"http://www.w3.org/ns/formats/TriG","text/n3":"http://www.w3.org/ns/formats/N3","text/turtle":"http://www.w3.org/ns/formats/Turtle"},name:"urn:comunica:default:rdf-serialize/actors#n3",bus:I,busFailMessage:"RDF serialization failed: none of the configured serializers were able to handle media type ${action.handleMediaType}"}),new(require("@comunica/actor-rdf-serialize-jsonld").ActorRdfSerializeJsonLd)({jsonStringifyIndentSpaces:2,mediaTypePriorities:{"application/ld+json":1},mediaTypeFormats:{"application/ld+json":"http://www.w3.org/ns/formats/JSON-LD"},priorityScale:.9,name:"urn:comunica:default:rdf-serialize/actors#jsonld",bus:I,busFailMessage:"RDF serialization failed: none of the configured serializers were able to handle media type ${action.handleMediaType}"}),new(require("@comunica/actor-rdf-serialize-shaclc").ActorRdfSerializeShaclc)({mediaTypePriorities:{"text/shaclc":1,"text/shaclc-ext":.5},mediaTypeFormats:{"text/shaclc":"http://www.w3.org/ns/formats/Shaclc","text/shaclc-ext":"http://www.w3.org/ns/formats/ShaclcExtended"},priorityScale:.1,name:"urn:comunica:default:rdf-serialize/actors#shaclc",bus:I,busFailMessage:"RDF serialization failed: none of the configured serializers were able to handle media type ${action.handleMediaType}"}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:rdf-serialize/mediators#serialize",bus:I})),de=new(require("@comunica/mediator-combine-union").MediatorCombineUnion)({field:"mediaTypes",name:"urn:comunica:default:rdf-serialize/mediators#mediaType",bus:I}),he=new(require("@comunica/mediator-combine-union").MediatorCombineUnion)({field:"mediaTypeFormats",name:"urn:comunica:default:rdf-serialize/mediators#mediaTypeFormat",bus:I}),fe=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:rdf-update-hypermedia/mediators#main",bus:A}),pe=(new(require("@comunica/actor-rdf-update-quads-rdfjs-store").ActorRdfUpdateQuadsRdfJsStore)({name:"urn:comunica:default:rdf-update-quads/actors#rdfjs-store",bus:T,busFailMessage:"RDF updating failed: none of the configured actors were able to handle an update"}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:rdf-update-quads/mediators#main",bus:T})),me=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:bindings-aggregator-factory/mediators#main",bus:E}),ye=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:expression-evaluator-factory/mediators#main",bus:R}),ge=(new(require("@comunica/actor-function-factory-expression-bnode").ActorFunctionFactoryExpressionBnode)({name:"urn:comunica:default:function-factory/actors#expression-function-bnode",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-expression-bound").ActorFunctionFactoryExpressionBound)({name:"urn:comunica:default:function-factory/actors#expression-function-bound",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-expression-coalesce").ActorFunctionFactoryExpressionCoalesce)({name:"urn:comunica:default:function-factory/actors#expression-function-coalesce",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-expression-extensions").ActorFunctionFactoryExpressionExtensions)({name:"urn:comunica:default:function-factory/actors#expression-function-extensions",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-expression-concat").ActorFunctionFactoryExpressionConcat)({name:"urn:comunica:default:function-factory/actors#expression-function-concat",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-expression-if").ActorFunctionFactoryExpressionIf)({name:"urn:comunica:default:function-factory/actors#expression-function-if",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-expression-logical-and").ActorFunctionFactoryExpressionLogicalAnd)({name:"urn:comunica:default:function-factory/actors#expression-function-logical-and",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-expression-logical-or").ActorFunctionFactoryExpressionLogicalOr)({name:"urn:comunica:default:function-factory/actors#expression-function-logical-or",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-expression-same-term").ActorFunctionFactoryExpressionSameTerm)({name:"urn:comunica:default:function-factory/actors#expression-function-same-term",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-abs").ActorFunctionFactoryTermAbs)({name:"urn:comunica:default:function-factory/actors#term-function-abs",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-addition").ActorFunctionFactoryTermAddition)({name:"urn:comunica:default:function-factory/actors#term-function-addition",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-ceil").ActorFunctionFactoryTermCeil)({name:"urn:comunica:default:function-factory/actors#term-function-ceil",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-contains").ActorFunctionFactoryTermContains)({name:"urn:comunica:default:function-factory/actors#term-function-contains",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-datatype").ActorFunctionFactoryTermDatatype)({name:"urn:comunica:default:function-factory/actors#term-function-datatype",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-day").ActorFunctionFactoryTermDay)({name:"urn:comunica:default:function-factory/actors#term-function-day",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-division").ActorFunctionFactoryTermDivision)({name:"urn:comunica:default:function-factory/actors#term-function-division",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-encode-for-uri").ActorFunctionFactoryTermEncodeForUri)({name:"urn:comunica:default:function-factory/actors#term-function-encode-for-uri",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-equality").ActorFunctionFactoryTermEquality)({name:"urn:comunica:default:function-factory/actors#term-function-equality",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-floor").ActorFunctionFactoryTermFloor)({name:"urn:comunica:default:function-factory/actors#term-function-floor",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-has-lang").ActorFunctionFactoryTermHasLang)({name:"urn:comunica:default:function-factory/actors#term-function-has-lang",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-has-langdir").ActorFunctionFactoryTermHasLangdir)({name:"urn:comunica:default:function-factory/actors#term-function-has-langdir",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-hours").ActorFunctionFactoryTermHours)({name:"urn:comunica:default:function-factory/actors#term-function-hours",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-iri").ActorFunctionFactoryTermIri)({name:"urn:comunica:default:function-factory/actors#term-function-iri",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-is-blank").ActorFunctionFactoryTermIsBlank)({name:"urn:comunica:default:function-factory/actors#term-function-is-blank",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-is-iri").ActorFunctionFactoryTermIsIri)({name:"urn:comunica:default:function-factory/actors#term-function-is-iri",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-is-literal").ActorFunctionFactoryTermIsLiteral)({name:"urn:comunica:default:function-factory/actors#term-function-is-literal",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-is-numeric").ActorFunctionFactoryTermIsNumeric)({name:"urn:comunica:default:function-factory/actors#term-function-is-numeric",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-is-triple").ActorFunctionFactoryTermIsTriple)({name:"urn:comunica:default:function-factory/actors#term-function-is-triple",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-lang").ActorFunctionFactoryTermLang)({name:"urn:comunica:default:function-factory/actors#term-function-lang",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-langdir").ActorFunctionFactoryTermLangdir)({name:"urn:comunica:default:function-factory/actors#term-function-langdir",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-langmatches").ActorFunctionFactoryTermLangmatches)({name:"urn:comunica:default:function-factory/actors#term-function-langmatches",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-lcase").ActorFunctionFactoryTermLcase)({name:"urn:comunica:default:function-factory/actors#term-function-lcase",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-md5").ActorFunctionFactoryTermMd5)({name:"urn:comunica:default:function-factory/actors#term-function-md5",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-minutes").ActorFunctionFactoryTermMinutes)({name:"urn:comunica:default:function-factory/actors#term-function-minutes",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-month").ActorFunctionFactoryTermMonth)({name:"urn:comunica:default:function-factory/actors#term-function-month",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-multiplication").ActorFunctionFactoryTermMultiplication)({name:"urn:comunica:default:function-factory/actors#term-function-multiplication",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-not").ActorFunctionFactoryTermNot)({name:"urn:comunica:default:function-factory/actors#term-function-not",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-now").ActorFunctionFactoryTermNow)({name:"urn:comunica:default:function-factory/actors#term-function-now",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-object").ActorFunctionFactoryTermObject)({name:"urn:comunica:default:function-factory/actors#term-function-object",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-predicate").ActorFunctionFactoryTermPredicate)({name:"urn:comunica:default:function-factory/actors#term-function-predicate",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-rand").ActorFunctionFactoryTermRand)({name:"urn:comunica:default:function-factory/actors#term-function-rand",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-regex").ActorFunctionFactoryTermRegex)({name:"urn:comunica:default:function-factory/actors#term-function-regex",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-replace").ActorFunctionFactoryTermReplace)({name:"urn:comunica:default:function-factory/actors#term-function-replace",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-round").ActorFunctionFactoryTermRound)({name:"urn:comunica:default:function-factory/actors#term-function-round",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-seconds").ActorFunctionFactoryTermSeconds)({name:"urn:comunica:default:function-factory/actors#term-function-seconds",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-sha1").ActorFunctionFactoryTermSha1)({name:"urn:comunica:default:function-factory/actors#term-function-sha1",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-sha256").ActorFunctionFactoryTermSha256)({name:"urn:comunica:default:function-factory/actors#term-function-sha256",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-sha384").ActorFunctionFactoryTermSha384)({name:"urn:comunica:default:function-factory/actors#term-function-sha384",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-sha512").ActorFunctionFactoryTermSha512)({name:"urn:comunica:default:function-factory/actors#term-function-sha512",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str-before").ActorFunctionFactoryTermStrBefore)({name:"urn:comunica:default:function-factory/actors#term-function-str-before",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str-after").ActorFunctionFactoryTermStrAfter)({name:"urn:comunica:default:function-factory/actors#term-function-str-after",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str-dt").ActorFunctionFactoryTermStrDt)({name:"urn:comunica:default:function-factory/actors#term-function-str-dt",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str-lang").ActorFunctionFactoryTermStrLang)({name:"urn:comunica:default:function-factory/actors#term-function-str-lang",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str-ends").ActorFunctionFactoryTermStrEnds)({name:"urn:comunica:default:function-factory/actors#term-function-str-ends",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str-langdir").ActorFunctionFactoryTermStrLangdir)({name:"urn:comunica:default:function-factory/actors#term-function-str-langdir",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str-len").ActorFunctionFactoryTermStrLen)({name:"urn:comunica:default:function-factory/actors#term-function-str-len",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str-starts").ActorFunctionFactoryTermStrStarts)({name:"urn:comunica:default:function-factory/actors#term-function-str-starts",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str-uuid").ActorFunctionFactoryTermStrUuid)({name:"urn:comunica:default:function-factory/actors#term-function-str-uuid",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-str").ActorFunctionFactoryTermStr)({name:"urn:comunica:default:function-factory/actors#term-function-str",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-sub-str").ActorFunctionFactoryTermSubStr)({name:"urn:comunica:default:function-factory/actors#term-function-sub-str",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-subject").ActorFunctionFactoryTermSubject)({name:"urn:comunica:default:function-factory/actors#term-function-subject",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-subtraction").ActorFunctionFactoryTermSubtraction)({name:"urn:comunica:default:function-factory/actors#term-function-subtraction",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-timezone").ActorFunctionFactoryTermTimezone)({name:"urn:comunica:default:function-factory/actors#term-function-timezone",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-triple").ActorFunctionFactoryTermTriple)({name:"urn:comunica:default:function-factory/actors#term-function-triple",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-tz").ActorFunctionFactoryTermTz)({name:"urn:comunica:default:function-factory/actors#term-function-tz",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-ucase").ActorFunctionFactoryTermUcase)({name:"urn:comunica:default:function-factory/actors#term-function-ucase",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-unary-minus").ActorFunctionFactoryTermUnaryMinus)({name:"urn:comunica:default:function-factory/actors#term-function-unary-minus",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-unary-plus").ActorFunctionFactoryTermUnaryPlus)({name:"urn:comunica:default:function-factory/actors#term-function-unary-plus",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-uuid").ActorFunctionFactoryTermUuid)({name:"urn:comunica:default:function-factory/actors#term-function-uuid",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-boolean").ActorFunctionFactoryTermXsdToBoolean)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-boolean",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-date").ActorFunctionFactoryTermXsdToDate)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-date",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-datetime").ActorFunctionFactoryTermXsdToDatetime)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-datetime",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-day-time-duration").ActorFunctionFactoryTermXsdToDayTimeDuration)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-day-time-duration",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-decimal").ActorFunctionFactoryTermXsdToDecimal)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-decimal",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-double").ActorFunctionFactoryTermXsdToDouble)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-double",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-duration").ActorFunctionFactoryTermXsdToDuration)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-duration",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-float").ActorFunctionFactoryTermXsdToFloat)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-float",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-integer").ActorFunctionFactoryTermXsdToInteger)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-integer",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-string").ActorFunctionFactoryTermXsdToString)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-string",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-time").ActorFunctionFactoryTermXsdToTime)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-time",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-xsd-to-year-month-duration").ActorFunctionFactoryTermXsdToYearMonthDuration)({name:"urn:comunica:default:function-factory/actors#term-function-xsd-to-year-month-duration",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-year").ActorFunctionFactoryTermYear)({name:"urn:comunica:default:function-factory/actors#term-function-year",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:function-factory/mediators#main",bus:k})),_e=new(require("@comunica/mediator-number").MediatorNumber)({field:"time",type:"min",ignoreFailures:!0,name:"urn:comunica:default:http/mediators#no-fallback",bus:j}),be=new(require("@comunica/mediator-number").MediatorNumber)({field:"time",type:"min",ignoreFailures:!0,name:"urn:comunica:default:http/mediators#main",bus:N}),we=(new(require("@comunica/actor-query-operation-source").ActorQueryOperationSource)({name:"urn:comunica:default:query-operation/actors#source",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/mediator-number").MediatorNumber)({field:"httpRequests",type:"min",ignoreFailures:!0,name:"urn:comunica:default:query-operation/mediators#main",bus:C})),ve=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:query-process/mediators#main",bus:P}),Se=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:query-source-identify/mediators#main",bus:O}),xe=new(require("@comunica/mediator-join-coefficients-fixed").MediatorJoinCoefficientsFixed)({cpuWeight:10,memoryWeight:1,timeWeight:2,ioWeight:10,name:"urn:comunica:default:rdf-join/mediators#main",bus:F}),Ie=new(require("@comunica/mediator-race").MediatorRace)({name:"urn:comunica:default:term-comparator-factory/mediators#main",bus:q}),Ae=new(require("@comunica/mediator-all").MediatorAll)({name:"urn:comunica:default:http-invalidate/mediators#main",bus:M}),Te=new(require("@comunica/bus-http-invalidate").ActorHttpInvalidateListenable)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-optimize-query-operation-query-source-identify/^5.0.0/components/ActorOptimizeQueryOperationQuerySourceIdentify.jsonld#IActorOptimizeQueryOperationQuerySourceIdentifyArgs_default_invalidator",bus:M,busFailMessage:"HTTP invalidation failed: none of the configured actors were able to invalidate ${action.url}"}),Ee=new(require("@comunica/bus-http-invalidate").ActorHttpInvalidateListenable)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-rdf-parse-jsonld/^5.0.0/components/ActorRdfParseJsonLd.jsonld#IActorRdfParseJsonLdArgs_default_invalidator",bus:M,busFailMessage:"HTTP invalidation failed: none of the configured actors were able to invalidate ${action.url}"}),Re=new(require("@comunica/bus-http-invalidate").ActorHttpInvalidateListenable)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-rdf-update-quads-hypermedia/^5.0.0/components/ActorRdfUpdateQuadsHypermedia.jsonld#IActorRdfUpdateQuadsHypermediaArgs_default_invalidator",bus:M,busFailMessage:"HTTP invalidation failed: none of the configured actors were able to invalidate ${action.url}"}),ke=new(require("@comunica/bus-http-invalidate").ActorHttpInvalidateListenable)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-http-limit-rate/^5.0.0/components/ActorHttpLimitRate.jsonld#IActorHttpLimitRateArgs_default_invalidator",bus:M,busFailMessage:"HTTP invalidation failed: none of the configured actors were able to invalidate ${action.url}"}),je=new(require("@comunica/bus-http-invalidate").ActorHttpInvalidateListenable)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-http-retry/^5.0.0/components/ActorHttpRetry.jsonld#IActorHttpQueueArgs_default_invalidator",bus:M,busFailMessage:"HTTP invalidation failed: none of the configured actors were able to invalidate ${action.url}"}),Ne=new(require("@comunica/bus-http-invalidate").ActorHttpInvalidateListenable)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-http-fetch/^5.0.0/components/ActorHttpFetch.jsonld#IActorHttpFetchArgs_default_invalidator",bus:M,busFailMessage:"HTTP invalidation failed: none of the configured actors were able to invalidate ${action.url}"}),Ce=new(require("@comunica/bus-http-invalidate").ActorHttpInvalidateListenable)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-query-result-serialize-sparql-json/^5.0.0/components/ActionObserverHttp.jsonld#IActionObserverHttpArgs_default_invalidator",bus:M,busFailMessage:"HTTP invalidation failed: none of the configured actors were able to invalidate ${action.url}"}),Pe=new(require("@comunica/bus-http-invalidate").ActorHttpInvalidateListenable)({name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-query-result-serialize-stats/^5.0.0/components/ActionObserverHttp.jsonld#IActionObserverHttpArgs_default_invalidator",bus:M,busFailMessage:"HTTP invalidation failed: none of the configured actors were able to invalidate ${action.url}"}),Oe=new(require("@comunica/mediator-combine-union").MediatorCombineUnion)({field:"mergeHandlers",name:"urn:comunica:default:merge-bindings-context/mediators#main",bus:$}),Fe=(new(require("@comunica/actor-rdf-metadata-extract-traverse").ActorRdfMetadataExtractTraverse)({mediatorExtractLinks:D,name:"urn:comunica:default:rdf-metadata-extract/actors#traverse",bus:b,busFailMessage:"Metadata extraction failed: none of the configured actors were able to extract metadata from ${action.url}"}),new(require("@comunica/actor-rdf-join-inner-single").ActorRdfJoinSingle)({mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#inner-single",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-rdf-join-inner-symmetrichash").ActorRdfJoinSymmetricHash)({mediatorHashBindings:z,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#inner-symmetric-hash",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"})),qe=new(require("@comunica/actor-rdf-join-inner-nestedloop").ActorRdfJoinNestedLoop)({mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#inner-nested-loop",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),Me=(new(require("@comunica/actor-rdf-join-minus-hash").ActorRdfJoinMinusHash)({canHandleUndefs:!1,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#minus-hash-def",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-rdf-join-minus-hash").ActorRdfJoinMinusHash)({canHandleUndefs:!0,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#minus-hash-undef",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-rdf-join-optional-hash").ActorRdfJoinOptionalHash)({canHandleUndefs:!1,blocking:!1,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#optional-hash-def-nonblocking",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-rdf-join-optional-hash").ActorRdfJoinOptionalHash)({canHandleUndefs:!1,blocking:!0,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#optional-hash-def-blocking",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-rdf-join-optional-hash").ActorRdfJoinOptionalHash)({canHandleUndefs:!0,blocking:!1,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#optional-hash-undef-nonblocking",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-rdf-join-optional-hash").ActorRdfJoinOptionalHash)({canHandleUndefs:!0,blocking:!0,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#optional-hash-undef-blocking",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-rdf-join-optional-nestedloop").ActorRdfJoinOptionalNestedLoop)({mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#optional-nested-loop",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-factory-aggregated-store-memory").ActorFactoryAggregatedStoreMemory)({emitPartialCardinalities:!1,mediatorMetadataAccumulate:ie,name:"urn:comunica:default:factory-aggregated-store/actors#memory",bus:i,busFailMessage:"Aggregated store creation failed: none of the configured actors were able to create an aggregated store"}),new(require("@comunica/actor-query-source-dereference-link-hypermedia").ActorQuerySourceDereferenceLinkHypermedia)({mediatorDereferenceRdf:ee,mediatorMetadata:ne,mediatorMetadataExtract:oe,mediatorMetadataAccumulate:ie,mediatorQuerySourceIdentifyHypermedia:X,sparqlServiceDescriptionTimeout:3e3,name:"urn:comunica:default:query-source-dereference-link/actors#dereference",bus:d,busFailMessage:"Query source dereference link failed: none of the configured actors were able to resolve ${action.link.url}"})),$e=(new(require("@comunica/actor-dereference-rdf-parse").ActorDereferenceRdfParse)({mediatorDereference:Z,mediatorParse:ae,mediatorParseMediatypes:se,mediaMappings:{htm:"text/html",html:"text/html",json:"application/json",jsonld:"application/ld+json",n3:"text/n3",nq:"application/n-quads",nquads:"application/n-quads",nt:"application/n-triples",ntriples:"application/n-triples",owl:"application/rdf+xml",rdf:"application/rdf+xml",rdfxml:"application/rdf+xml",shaclc:"text/shaclc",shaclce:"text/shaclc-ext",shc:"text/shaclc",shce:"text/shaclc-ext",svg:"image/svg+xml",svgz:"image/svg+xml",trig:"application/trig",ttl:"text/turtle",turtle:"text/turtle",xht:"application/xhtml+xml",xhtml:"application/xhtml+xml",xml:"application/xml"},name:"urn:comunica:default:dereference-rdf/actors#parse",bus:p,busFailMessage:"RDF dereferencing failed: none of the configured parsers were able to handle the media type ${action.handle.mediaType} for ${action.handle.url}"}),new(require("@comunica/actor-rdf-parse-html-script").ActorRdfParseHtmlScript)({mediatorRdfParseMediatypes:se,mediatorRdfParseHandle:ae,name:"urn:comunica:default:rdf-parse-html/actors#script",bus:v,busFailMessage:"RDF HTML parsing failed: none of the configured parsers were able to parse RDF in HTML"}),new(require("@comunica/actor-query-result-serialize-rdf").ActorQueryResultSerializeRdf)({mediatorRdfSerialize:le,mediatorMediaTypeCombiner:de,mediatorMediaTypeFormatCombiner:he,name:"urn:comunica:default:query-result-serialize/actors#rdf",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/actor-bindings-aggregator-factory-count").ActorBindingsAggregatorFactoryCount)({mediatorExpressionEvaluatorFactory:ye,name:"urn:comunica:default:bindings-aggregator-factory/actors#count",bus:E,busFailMessage:"Creation of Aggregator failed: none of the configured actors were able to handle ${action.expr.aggregator}"}),new(require("@comunica/actor-bindings-aggregator-factory-group-concat").ActorBindingsAggregatorFactoryGroupConcat)({mediatorExpressionEvaluatorFactory:ye,name:"urn:comunica:default:bindings-aggregator-factory/actors#group-concat",bus:E,busFailMessage:"Creation of Aggregator failed: none of the configured actors were able to handle ${action.expr.aggregator}"}),new(require("@comunica/actor-bindings-aggregator-factory-sample").ActorBindingsAggregatorFactorySample)({mediatorExpressionEvaluatorFactory:ye,name:"urn:comunica:default:bindings-aggregator-factory/actors#sample",bus:E,busFailMessage:"Creation of Aggregator failed: none of the configured actors were able to handle ${action.expr.aggregator}"}),new(require("@comunica/actor-bindings-aggregator-factory-wildcard-count").ActorBindingsAggregatorFactoryWildcardCount)({mediatorExpressionEvaluatorFactory:ye,name:"urn:comunica:default:bindings-aggregator-factory/actors#wildcard-count",bus:E,busFailMessage:"Creation of Aggregator failed: none of the configured actors were able to handle ${action.expr.aggregator}"}),new(require("@comunica/actor-bindings-aggregator-factory-average").ActorBindingsAggregatorFactoryAverage)({mediatorFunctionFactory:ge,mediatorExpressionEvaluatorFactory:ye,name:"urn:comunica:default:bindings-aggregator-factory/actors#average",bus:E,busFailMessage:"Creation of Aggregator failed: none of the configured actors were able to handle ${action.expr.aggregator}"}),new(require("@comunica/actor-bindings-aggregator-factory-sum").ActorBindingsAggregatorFactorySum)({mediatorFunctionFactory:ge,mediatorExpressionEvaluatorFactory:ye,name:"urn:comunica:default:bindings-aggregator-factory/actors#sum",bus:E,busFailMessage:"Creation of Aggregator failed: none of the configured actors were able to handle ${action.expr.aggregator}"}),new(require("@comunica/actor-function-factory-expression-in").ActorFunctionFactoryExpressionIn)({mediatorFunctionFactory:ge,name:"urn:comunica:default:function-factory/actors#expression-function-in",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-expression-not-in").ActorFunctionFactoryExpressionNotIn)({mediatorFunctionFactory:ge,name:"urn:comunica:default:function-factory/actors#expression-function-not-in",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-greater-than-equal").ActorFunctionFactoryTermGreaterThanEqual)({mediatorFunctionFactory:ge,name:"urn:comunica:default:function-factory/actors#term-function-greater-than-equal",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-greater-than").ActorFunctionFactoryTermGreaterThan)({mediatorFunctionFactory:ge,name:"urn:comunica:default:function-factory/actors#term-function-greater-than",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-inequality").ActorFunctionFactoryTermInequality)({mediatorFunctionFactory:ge,name:"urn:comunica:default:function-factory/actors#term-function-inequality",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-lesser-than").ActorFunctionFactoryTermLesserThan)({mediatorFunctionFactory:ge,name:"urn:comunica:default:function-factory/actors#term-function-lesser-than",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-function-factory-term-lesser-than-equal").ActorFunctionFactoryTermLesserThanEqual)({mediatorFunctionFactory:ge,name:"urn:comunica:default:function-factory/actors#term-function-lesser-than-equal",bus:k,busFailMessage:"Creation of function evaluator failed: no configured actor was able to evaluate function ${action.functionName}"}),new(require("@comunica/actor-http-wayback").ActorHttpWayback)({mediatorHttp:_e,name:"urn:comunica:default:http/actors#wayback",bus:N,busFailMessage:"HTTP request failed: none of the configured actors were able to handle ${action.input}"}),new(require("@comunica/actor-rdf-update-hypermedia-patch-sparql-update").ActorRdfUpdateHypermediaPatchSparqlUpdate)({mediatorHttp:be,name:"urn:comunica:default:rdf-update-hypermedia/actors#patch-sparql-update",bus:A,busFailMessage:"RDF hypermedia updating failed: none of the configured actors were able to handle an update for ${action.url}"}),new(require("@comunica/actor-rdf-update-hypermedia-put-ldp").ActorRdfUpdateHypermediaPutLdp)({mediatorHttp:be,mediatorRdfSerializeMediatypes:de,mediatorRdfSerialize:le,name:"urn:comunica:default:rdf-update-hypermedia/actors#put-ldp",bus:A,busFailMessage:"RDF hypermedia updating failed: none of the configured actors were able to handle an update for ${action.url}"}),new(require("@comunica/actor-rdf-update-hypermedia-sparql").ActorRdfUpdateHypermediaSparql)({mediatorHttp:be,checkUrlSuffixSparql:!0,checkUrlSuffixUpdate:!0,name:"urn:comunica:default:rdf-update-hypermedia/actors#sparql",bus:A,busFailMessage:"RDF hypermedia updating failed: none of the configured actors were able to handle an update for ${action.url}"}),new(require("@comunica/actor-query-operation-ask").ActorQueryOperationAsk)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#ask",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-construct").ActorQueryOperationConstruct)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#construct",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-bgp-join").ActorQueryOperationBgpJoin)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#bgp",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-distinct-identity").ActorQueryOperationDistinctIdentity)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#distinct",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-extend").ActorQueryOperationExtend)({mediatorExpressionEvaluatorFactory:ye,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#extend",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-filter").ActorQueryOperationFilter)({mediatorExpressionEvaluatorFactory:ye,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#filter",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-from-quad").ActorQueryOperationFromQuad)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#from",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-project").ActorQueryOperationProject)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#project",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-reduced-hash").ActorQueryOperationReducedHash)({mediatorHashBindings:z,cacheSize:100,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#reduced",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-slice").ActorQueryOperationSlice)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#slice",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-union").ActorQueryOperationUnion)({mediatorRdfMetadataAccumulate:ie,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#union",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-path-alt").ActorQueryOperationPathAlt)({mediatorRdfMetadataAccumulate:ie,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#path-alt",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-path-inv").ActorQueryOperationPathInv)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#path-inv",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-path-link").ActorQueryOperationPathLink)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#path-link",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-path-nps").ActorQueryOperationPathNps)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#path-nps",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-update-clear").ActorQueryOperationClear)({mediatorUpdateQuads:pe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#update-clear",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-update-compositeupdate").ActorQueryOperationUpdateCompositeUpdate)({mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#update-composite",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-update-create").ActorQueryOperationCreate)({mediatorUpdateQuads:pe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#update-create",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-update-drop").ActorQueryOperationDrop)({mediatorUpdateQuads:pe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#update-drop",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-update-load").ActorQueryOperationLoad)({mediatorUpdateQuads:pe,mediatorQuerySourceIdentify:Se,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#update-load",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-source-identify-serialized").ActorQuerySourceIdentifySerialized)({mediatorRdfParse:ae,mediatorQuerySourceIdentify:Se,name:"urn:comunica:default:query-source-identify/actors#serialized",bus:O,busFailMessage:"Query source identification failed: none of the configured actors were able to identify ${action.querySourceUnidentified.value}"}),new(require("@comunica/actor-query-operation-join").ActorQueryOperationJoin)({mediatorJoin:xe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#join",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-leftjoin").ActorQueryOperationLeftJoin)({mediatorJoin:xe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#leftjoin",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-minus").ActorQueryOperationMinus)({mediatorJoin:xe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#minus",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-path-seq").ActorQueryOperationPathSeq)({mediatorJoin:xe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#path-seq",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-rdf-join-inner-multi-smallest").ActorRdfJoinMultiSmallest)({mediatorJoinEntriesSort:te,mediatorJoin:xe,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#inner-multi-smallest",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"})),De=(new(require("@comunica/actor-bindings-aggregator-factory-max").ActorBindingsAggregatorFactoryMax)({mediatorTermComparatorFactory:Ie,mediatorExpressionEvaluatorFactory:ye,name:"urn:comunica:default:bindings-aggregator-factory/actors#max",bus:E,busFailMessage:"Creation of Aggregator failed: none of the configured actors were able to handle ${action.expr.aggregator}"}),new(require("@comunica/actor-bindings-aggregator-factory-min").ActorBindingsAggregatorFactoryMin)({mediatorTermComparatorFactory:Ie,mediatorExpressionEvaluatorFactory:ye,name:"urn:comunica:default:bindings-aggregator-factory/actors#min",bus:E,busFailMessage:"Creation of Aggregator failed: none of the configured actors were able to handle ${action.expr.aggregator}"}),new(require("@comunica/actor-query-operation-orderby").ActorQueryOperationOrderBy)({mediatorExpressionEvaluatorFactory:ye,mediatorTermComparatorFactory:Ie,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#orderby",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-optimize-query-operation-filter-pushdown").ActorOptimizeQueryOperationFilterPushdown)({aggressivePushdown:!1,maxIterations:10,splitConjunctive:!0,mergeConjunctive:!0,pushIntoLeftJoins:!0,pushEqualityIntoPatterns:!0,name:"urn:comunica:default:optimize-query-operation/actors#filter-pushdown",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[B]})),Le=(new(require("@comunica/actor-dereference-http").ActorDereferenceHttp)({mediatorHttp:be,maxAcceptHeaderLength:1024,maxAcceptHeaderLengthBrowser:128,name:"urn:comunica:default:dereference/actors#http",bus:f,busFailMessage:"Dereferencing failed: none of the configured actors were able to handle ${action.url}",beforeActors:[Y]}),new(require("@comunica/actor-init-query").ActorInitQuery)({mediatorQueryProcess:ve,mediatorQueryResultSerialize:K,mediatorQueryResultSerializeMediaTypeCombiner:W,mediatorQueryResultSerializeMediaTypeFormatCombiner:J,mediatorHttpInvalidate:Ae,defaultQueryInputFormat:"sparql",allowNoSources:!0,name:"urn:comunica:default:init/actors#query",bus:t,busFailMessage:"Initialization failed: none of the configured actors were to initialize"})),Ue=(new(require("@comunica/actor-rdf-parse-jsonld").ActorRdfParseJsonLd)({cacheSize:128,httpInvalidator:Ee,mediatorHttp:be,mediaTypePriorities:{"application/json":.15,"application/ld+json":1},mediaTypeFormats:{"application/json":"http://www.w3.org/ns/formats/JSON-LD","application/ld+json":"http://www.w3.org/ns/formats/JSON-LD"},priorityScale:.9,name:"urn:comunica:default:rdf-parse/actors#jsonld",bus:w,busFailMessage:"RDF parsing failed: none of the configured parsers were able to handle the media type ${action.handle.mediaType} for ${action.handle.url}"}),new(require("@comunica/actor-rdf-update-quads-hypermedia").ActorRdfUpdateQuadsHypermedia)({cacheSize:100,httpInvalidator:Re,mediatorDereferenceRdf:ee,mediatorMetadata:ne,mediatorMetadataExtract:oe,mediatorRdfUpdateHypermedia:fe,name:"urn:comunica:default:rdf-update-quads/actors#hypermedia",bus:T,busFailMessage:"RDF updating failed: none of the configured actors were able to handle an update"}),new(require("@comunica/actor-http-fetch").ActorHttpFetch)({cacheMaxSize:104857600,cacheMaxCount:1e3,cacheMaxEntrySize:5242880,httpInvalidator:Ne,agentOptions:{keepAlive:!0,maxSockets:5},name:"urn:comunica:default:http/actors#fetch",bus:j,busFailMessage:"HTTP request failed: none of the configured actors were able to handle ${action.input}"})),ze=new(require("@comunica/actor-query-result-serialize-sparql-json").ActionObserverHttp)({httpInvalidator:Ce,observedActors:["urn:comunica:default:http/actors#fetch"],name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-query-result-serialize-sparql-json/^5.0.0/components/ActorQueryResultSerializeSparqlJson.jsonld#ActorQueryResultSerializeSparqlJson_default_observer",bus:j}),Be=new(require("@comunica/actor-query-result-serialize-stats").ActionObserverHttp)({httpInvalidator:Pe,observedActors:["urn:comunica:default:http/actors#fetch"],name:"https://linkedsoftwaredependencies.org/bundles/npm/@comunica/actor-query-result-serialize-stats/^5.0.0/components/ActorQueryResultSerializeStats.jsonld#ActorQueryResultSerializeStats_default_observer",bus:j}),Qe=(new(require("@comunica/actor-query-source-identify-hypermedia-qpf").ActorQuerySourceIdentifyHypermediaQpf)({mediatorMetadata:ne,mediatorMetadataExtract:oe,mediatorDereferenceRdf:ee,mediatorMergeBindingsContext:Oe,subjectUri:"http://www.w3.org/1999/02/22-rdf-syntax-ns#subject",predicateUri:"http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate",objectUri:"http://www.w3.org/1999/02/22-rdf-syntax-ns#object",graphUri:"http://www.w3.org/ns/sparql-service-description#graph",name:"urn:comunica:default:query-source-identify-hypermedia/actors#qpf",bus:h,busFailMessage:"Query source hypermedia identification failed: none of the configured actors were able to identify ${action.url}"}),new(require("@comunica/actor-query-source-identify-hypermedia-sparql").ActorQuerySourceIdentifyHypermediaSparql)({mediatorHttp:be,mediatorMergeBindingsContext:Oe,mediatorQuerySerialize:G,checkUrlSuffix:!0,forceHttpGet:!1,cacheSize:1024,forceSourceType:!1,bindMethod:"values",countTimeout:3e3,cardinalityCountQueries:!0,cardinalityEstimateConstruction:!1,forceGetIfUrlLengthBelow:600,name:"urn:comunica:default:query-source-identify-hypermedia/actors#sparql",bus:h,busFailMessage:"Query source hypermedia identification failed: none of the configured actors were able to identify ${action.url}"}),new(require("@comunica/actor-query-source-identify-hypermedia-none").ActorQuerySourceIdentifyHypermediaNone)({mediatorMergeBindingsContext:Oe,name:"urn:comunica:default:query-source-identify-hypermedia/actors#none",bus:h,busFailMessage:"Query source hypermedia identification failed: none of the configured actors were able to identify ${action.url}"})),He=(new(require("@comunica/actor-expression-evaluator-factory-default").ActorExpressionEvaluatorFactoryDefault)({mediatorQueryOperation:we,mediatorFunctionFactory:ge,mediatorMergeBindingsContext:Oe,name:"urn:comunica:default:expression-evaluator-factory/actors#default",bus:R,busFailMessage:"Creation of Expression Evaluator failed"}),new(require("@comunica/actor-query-operation-group").ActorQueryOperationGroup)({mediatorMergeBindingsContext:Oe,mediatorBindingsAggregatorFactory:me,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#group",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-nop").ActorQueryOperationNop)({mediatorMergeBindingsContext:Oe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#nop",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-values").ActorQueryOperationValues)({mediatorMergeBindingsContext:Oe,name:"urn:comunica:default:query-operation/actors#values",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-path-one-or-more").ActorQueryOperationPathOneOrMore)({mediatorMergeBindingsContext:Oe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#path-one-or-more",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-path-zero-or-more").ActorQueryOperationPathZeroOrMore)({mediatorMergeBindingsContext:Oe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#path-zero-or-more",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-path-zero-or-one").ActorQueryOperationPathZeroOrOne)({mediatorMergeBindingsContext:Oe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#path-zero-or-one",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-operation-update-deleteinsert").ActorQueryOperationUpdateDeleteInsert)({mediatorUpdateQuads:pe,mediatorMergeBindingsContext:Oe,mediatorQueryOperation:we,name:"urn:comunica:default:query-operation/actors#update-delete-insert",bus:C,busFailMessage:"Query operation processing failed: none of the configured actors were able to handle the operation type ${action.operation.type}"}),new(require("@comunica/actor-query-process-sequential").ActorQueryProcessSequential)({mediatorContextPreprocess:L,mediatorQueryParse:H,mediatorOptimizeQueryOperation:Q,mediatorQueryOperation:we,mediatorMergeBindingsContext:Oe,name:"urn:comunica:default:query-process/actors#sequential",bus:P,busFailMessage:'Query processing failed: none of the configured actor were process to the query "${action.query}"'})),Ke=new(require("@comunica/actor-query-source-identify-hypermedia").ActorQuerySourceIdentifyHypermedia)({cacheSize:2048,maxIterators:64,mediatorMetadataAccumulate:ie,mediatorQuerySourceDereferenceLink:V,mediatorRdfResolveHypermediaLinks:ce,mediatorRdfResolveHypermediaLinksQueue:ue,mediatorMergeBindingsContext:Oe,name:"urn:comunica:default:query-source-identify/actors#hypermedia",bus:O,busFailMessage:"Query source identification failed: none of the configured actors were able to identify ${action.querySourceUnidentified.value}"}),We=(new(require("@comunica/actor-query-source-identify-rdfjs").ActorQuerySourceIdentifyRdfJs)({mediatorMergeBindingsContext:Oe,name:"urn:comunica:default:query-source-identify/actors#rdfjs",bus:O,busFailMessage:"Query source identification failed: none of the configured actors were able to identify ${action.querySourceUnidentified.value}"}),new(require("@comunica/actor-rdf-join-inner-none").ActorRdfJoinNone)({mediatorMergeBindingsContext:Oe,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#inner-none",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-rdf-join-optional-bind").ActorRdfJoinOptionalBind)({bindOrder:"depth-first",selectivityModifier:1e-6,mediatorQueryOperation:we,mediatorMergeBindingsContext:Oe,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#optional-bind",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}"}),new(require("@comunica/actor-term-comparator-factory-expression-evaluator").ActorTermComparatorFactoryExpressionEvaluator)({mediatorQueryOperation:we,mediatorFunctionFactory:ge,mediatorMergeBindingsContext:Oe,name:"urn:comunica:default:term-comparator-factory/actors#expression-evaluator",bus:q,busFailMessage:"Creation of term comparator failed"}),new(require("@comunica/actor-query-source-dereference-link-force-sparql").ActorQuerySourceDereferenceLinkForceSparql)({mediatorMetadataAccumulate:ie,mediatorQuerySourceIdentifyHypermedia:X,name:"urn:comunica:default:query-source-dereference-link/actors#force-sparql",bus:d,busFailMessage:"Query source dereference link failed: none of the configured actors were able to resolve ${action.link.url}",beforeActors:[Me]}),new(require("@comunica/actor-rdf-join-inner-multi-bind").ActorRdfJoinMultiBind)({bindOrder:"breadth-first",selectivityModifier:1e-4,minMaxCardinalityRatio:60,subQueryCost:100,mediatorJoinEntriesSort:te,mediatorQueryOperation:we,mediatorMergeBindingsContext:Oe,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#inner-multi-bind",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}",beforeActors:[$e,Fe,qe]})),Je=(new(require("@comunica/actor-rdf-join-inner-multi-smallest-filter-bindings").ActorRdfJoinMultiSmallestFilterBindings)({selectivityModifier:1e-4,blockSize:64,mediatorJoinEntriesSort:te,mediatorJoin:xe,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#inner-multi-smallest-filter-bindings",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}",beforeActors:[$e,Fe,qe]}),new(require("@comunica/actor-extract-links-solid-type-index").ActorExtractLinksSolidTypeIndex)({typeIndexPredicates:["http://www.w3.org/ns/solid/terms#publicTypeIndex","http://www.w3.org/ns/solid/terms#privateTypeIndex"],onlyMatchingTypes:!0,inference:!1,actorInitQuery:Le,mediatorDereferenceRdf:ee,name:"urn:comunica:default:extract-links/actors#solid-type-index",bus:r}),new(require("@comunica/actor-query-result-serialize-sparql-json").ActorQueryResultSerializeSparqlJson)({emitMetadata:!0,httpObserver:ze,mediaTypePriorities:{"application/sparql-results+json":.8},mediaTypeFormats:{"application/sparql-results+json":"http://www.w3.org/ns/formats/SPARQL_Results_JSON"},name:"urn:comunica:default:query-result-serialize/actors#sparql-json",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/actor-query-result-serialize-stats").ActorQueryResultSerializeStats)({httpObserver:Be,mediaTypePriorities:{stats:.5},mediaTypeFormats:{stats:"https://comunica.linkeddatafragments.org/#results_stats"},name:"urn:comunica:default:query-result-serialize/actors#stats",bus:u,busFailMessage:"Query result serialization failed: none of the configured actors were able to serialize for type ${action.handle.type}"}),new(require("@comunica/actor-query-process-explain-parsed").ActorQueryProcessExplainParsed)({queryProcessor:He,name:"urn:comunica:default:query-process/actors#explain-parsed",bus:P,busFailMessage:'Query processing failed: none of the configured actor were process to the query "${action.query}"'}),new(require("@comunica/actor-query-process-explain-logical").ActorQueryProcessExplainLogical)({queryProcessor:He,name:"urn:comunica:default:query-process/actors#explain-logical",bus:P,busFailMessage:'Query processing failed: none of the configured actor were process to the query "${action.query}"'}),new(require("@comunica/actor-query-process-explain-query").ActorQueryProcessExplainQuery)({queryProcessor:He,mediatorQuerySerialize:G,name:"urn:comunica:default:query-process/actors#explain-query",bus:P,busFailMessage:'Query processing failed: none of the configured actor were process to the query "${action.query}"'}),new(require("@comunica/actor-query-process-explain-physical").ActorQueryProcessExplainPhysical)({queryProcessor:He,name:"urn:comunica:default:query-process/actors#explain-physical",bus:P,busFailMessage:'Query processing failed: none of the configured actor were process to the query "${action.query}"'}),new(require("@comunica/actor-optimize-query-operation-prune-empty-source-operations").ActorOptimizeQueryOperationPruneEmptySourceOperations)({useAskIfSupported:!1,name:"urn:comunica:default:optimize-query-operation/actors#prune-empty-source-operations",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[De]})),Ge=(new(require("@comunica/actor-optimize-query-operation-leftjoin-expression-pushdown").ActorOptimizeQueryOperationLeftjoinExpressionPushdown)({name:"urn:comunica:default:optimize-query-operation/actors#leftjoin-expression-pushdown",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[De]}),new(require("@comunica/actor-http-inrupt-solid-client-authn").ActorHttpInruptSolidClientAuthn)({mediatorHttp:be,name:"urn:comunica:default:http/actors#inrupt-solid-client-authn",bus:j,busFailMessage:"HTTP request failed: none of the configured actors were able to handle ${action.input}",beforeActors:[Ue]})),Ve=(new(require("@comunica/actor-query-source-identify-hypermedia-none-lazy").ActorQuerySourceIdentifyHypermediaNoneLazy)({mediatorQuerySourceIdentifyHypermedia:X,name:"urn:comunica:default:query-source-identify-hypermedia/actors#none-lazy",bus:h,busFailMessage:"Query source hypermedia identification failed: none of the configured actors were able to identify ${action.url}",beforeActors:[Qe]}),new(require("@comunica/actor-query-source-identify-link-traversal").ActorQuerySourceIdentifyLinkTraversal)({name:"urn:comunica:default:query-source-identify/actors#link-traversal",bus:O,busFailMessage:"Query source identification failed: none of the configured actors were able to identify ${action.querySourceUnidentified.value}",beforeActors:[Ke]}),new(require("@comunica/actor-rdf-join-inner-multi-bind-source").ActorRdfJoinMultiBindSource)({selectivityModifier:1e-4,blockSize:16,mediatorJoinEntriesSort:te,mediatorJoinSelectivity:re,name:"urn:comunica:default:rdf-join/actors#inner-multi-bind-source",bus:F,busFailMessage:"RDF joining failed: none of the configured actors were able to handle the join type ${action.type}",beforeActors:[$e,We,Fe,qe]}),new(require("@comunica/actor-optimize-query-operation-join-connected").ActorOptimizeQueryOperationJoinConnected)({name:"urn:comunica:default:optimize-query-operation/actors#join-connected",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[Je]})),Xe=new(require("@comunica/actor-http-proxy").ActorHttpProxy)({mediatorHttp:be,name:"urn:comunica:default:http/actors#proxy",bus:j,busFailMessage:"HTTP request failed: none of the configured actors were able to handle ${action.input}",beforeActors:[Ue,Ge]}),Ye=new(require("@comunica/actor-optimize-query-operation-bgp-to-join").ActorOptimizeQueryOperationBgpToJoin)({name:"urn:comunica:default:optimize-query-operation/actors#bgp-to-join",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[Ve]}),Ze=(new(require("@comunica/actor-http-limit-rate").ActorHttpLimitRate)({mediatorHttp:be,httpInvalidator:ke,correctionMultiplier:.1,failureMultiplier:10,limitByDefault:!1,allowOverlap:!1,name:"urn:comunica:default:http/actors#limit-rate",bus:j,busFailMessage:"HTTP request failed: none of the configured actors were able to handle ${action.input}",beforeActors:[Xe]}),new(require("@comunica/actor-http-retry").ActorHttpRetry)({mediatorHttp:be,httpInvalidator:je,name:"urn:comunica:default:http/actors#retry",bus:j,busFailMessage:"HTTP request failed: none of the configured actors were able to handle ${action.input}",beforeActors:[Xe]}),new(require("@comunica/actor-optimize-query-operation-join-bgp").ActorOptimizeQueryOperationJoinBgp)({name:"urn:comunica:default:optimize-query-operation/actors#join-bgp",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[Ye]})),et=new(require("@comunica/actor-optimize-query-operation-assign-sources-exhaustive").ActorOptimizeQueryOperationAssignSourcesExhaustive)({name:"urn:comunica:default:optimize-query-operation/actors#assign-sources-exhaustive",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[Ze]}),tt=new(require("@comunica/actor-optimize-query-operation-query-source-skolemize").ActorOptimizeQueryOperationQuerySourceSkolemize)({name:"urn:comunica:default:optimize-query-operation/actors#query-source-skolemize",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[et]}),rt=new(require("@comunica/actor-optimize-query-operation-query-source-identify").ActorOptimizeQueryOperationQuerySourceIdentify)({serviceForceSparqlEndpoint:!1,cacheSize:100,httpInvalidator:Te,mediatorQuerySourceIdentify:Se,mediatorContextPreprocess:L,name:"urn:comunica:default:optimize-query-operation/actors#query-source-identify",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[tt]}),nt=(new(require("@comunica/actor-optimize-query-operation-describe-to-constructs-subject").ActorOptimizeQueryOperationDescribeToConstructsSubject)({name:"urn:comunica:default:optimize-query-operation/actors#describe-to-constructs-subject",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[rt]}),new(require("@comunica/actor-optimize-query-operation-initialize-link-traversal-manager").ActorOptimizeQueryOperationInitializeLinkTraversalManager)({linkParallelization:64,linkParallelizationLimit:2,mediatorRdfResolveHypermediaLinks:ce,mediatorRdfResolveHypermediaLinksQueue:ue,mediatorQuerySourceDereferenceLink:V,mediatorMergeBindingsContext:Oe,mediatorFactoryAggregatedStore:U,name:"urn:comunica:default:optimize-query-operation/actors#initialize-link-traversal-manager",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[rt]}));return new(require("@comunica/actor-optimize-query-operation-set-seed-sources-quadpattern-iris").ActorOptimizeQueryOperationSetSeedSourcesQuadpatternIris)({extractSubjects:!0,extractPredicates:!1,extractObjects:!0,extractGraphs:!0,extractVocabIris:!1,name:"urn:comunica:default:optimize-query-operation/actors#set-seed-sources-quadpattern-iris",bus:s,busFailMessage:"Query optimization failed: none of the configured actors were able to optimize",beforeActors:[nt]}),Le}(),dh=new Uint8Array(16);const hh=[];for(let e=0;e<256;++e)hh.push((e+256).toString(16).slice(1));function fh(e,t=0){return(hh[e[t+0]]+hh[e[t+1]]+hh[e[t+2]]+hh[e[t+3]]+"-"+hh[e[t+4]]+hh[e[t+5]]+"-"+hh[e[t+6]]+hh[e[t+7]]+"-"+hh[e[t+8]]+hh[e[t+9]]+"-"+hh[e[t+10]]+hh[e[t+11]]+hh[e[t+12]]+hh[e[t+13]]+hh[e[t+14]]+hh[e[t+15]]).toLowerCase()}const ph=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){e=e||{};const n=e.random??e.rng?.()??crypto.getRandomValues(dh);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 fh(n)}(e,t,r):crypto.randomUUID()};class StorageUtilityBrowser extends StorageUtility{constructor(e,t){super(e,t)}}class ClientAuthentication extends dist_ClientAuthentication{login=async(e,t)=>{"none"!==e.prompt&&await this.sessionInfoManager.clear(e.sessionId);const r=e.redirectUrl??function(e){const t=Bo(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}(window.location.href);if(!zo(r))throw new Error(`${r} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:r,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return void 0===t||void 0===t.clientAppId||void 0===t.issuer||function(e){return void 0!==e.clientExpiresAt&&0!==e.clientExpiresAt&&e.clientExpiresAt<Math.floor(Date.now()/1e3)}(t)?null:t};handleIncomingRedirect=async(e,t)=>{try{const r=await this.redirectHandler.handle(e,t,void 0);return this.fetch=r.fetch.bind(window),this.boundLogout=r.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:r.isLoggedIn,webId:r.webId,sessionId:r.sessionId,expirationDate:r.expirationDate,clientAppId:r.clientAppId}}catch(r){return await this.cleanUrlAfterRedirect(e),void t.emit(Co,"redirect",r)}};async cleanUrlAfterRedirect(e){const t=Bo(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(e=>{setTimeout(()=>e(),1)})}}function mh(e){return"string"==typeof e.oidcIssuer}function yh(e){return"string"==typeof e.redirectUrl}class OidcLoginHandler{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 mh(e)&&yh(e)}async handle(e){if(!mh(e))throw new ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!yh(e))throw new ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await Jo(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([...Lo,...i.filter(e=>"string"==typeof e&&!e.includes(" "))])):Lo)};var i;return this.oidcHandler.handle(n)}}class AuthorizationCodeWithPkceOidcHandler extends AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){const t=e.redirectUrl??"",r={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:t,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,prompt:e.prompt??"consent"},n=new La(r);try{const t=await n.createSigninRequest({});return await this.setupRedirectHandler({oidcLoginOptions:e,state:t.state.id,codeVerifier:t.state.code_verifier??"",targetUrl:t.url.toString()})}catch(e){console.error(e)}}}const gh={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 IssuerConfigFetcher{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=>{gh[r]&&(t[gh[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await n.json())}catch(t){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function _h(e,t){await Ho(e,t),await async function(){const e=new Ia({});await ka.clearStaleState(e,900);const t=window.localStorage,r=[];for(let e=0;e<=t.length;e+=1){const n=t.key(e);n&&(n.match(/^oidc\..+$/)||n.match(/^solidClientAuthenticationUser:.+$/))&&r.push(n)}r.forEach(e=>t.removeItem(e))}()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,r,n,i,o,a,s,c,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}),this.storageUtility.getForUser(e,"expiresAt",{secure:!1})]);if("string"!=typeof o||zo(o)){if(void 0!==c&&("string"!=typeof(l=c)||!["DPoP","Bearer"].includes(l)))throw new Error(`Tokens of type [${c}] are not supported.`);var l;if(void 0!==n||void 0!==t||void 0!==r||void 0!==a)return{sessionId:e,webId:r,isLoggedIn:"true"===t,redirectUrl:o,refreshToken:a,issuer:s,clientAppId:n,clientAppSecret:i,tokenType:c??"DPoP",clientExpiresAt:void 0!==u?Number.parseInt(u,10):void 0}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return _h(e,this.storageUtility)}}class FallbackRedirectHandler{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 Qo()}}class AuthCodeRedirectHandler{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:o,codeVerifier:a,redirectUrl:s,dpop:c}=await Vo(i,this.storageUtility,this.issuerConfigFetcher),u=r.searchParams.get("iss");if("string"==typeof u&&u!==o.issuer)throw new Error(`The value of the iss parameter (${u}) does not match the issuer identifier of the authorization server (${o.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(void 0===a)throw new Error(`The code verifier for session ${i} is missing from storage.`);if(void 0===s)throw new Error(`The redirect URL for session ${i} is missing from storage.`);const l=await this.clientRegistrar.getClient({sessionId:i},o),d=Date.now(),h=await Ha(o,l,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:a,redirectUrl:s},c);let f;window.localStorage.removeItem(`oidc.${n}`),void 0!==h.refreshToken&&(f={sessionId:i,refreshToken:h.refreshToken,tokenRefresher:this.tokerRefresher});const p=ra(h.accessToken,{dpopKey:h.dpopKey,refreshOptions:f,eventEmitter:t,expiresIn:h.expiresIn});await async function(e,t,r,n,i,o,a,s){void 0!==o&&await e.setForUser(t,{refreshToken:o},{secure:a}),void 0!==r&&await e.setForUser(t,{webId:r},{secure:a}),void 0!==n&&await e.setForUser(t,{clientId:n},{secure:a}),void 0!==i&&await e.setForUser(t,{isLoggedIn:i},{secure:a}),void 0!==s&&await e.setForUser(t,{publicKey:JSON.stringify(s.publicKey),privateKey:JSON.stringify(await co(s.privateKey))},{secure:a})}(this.storageUtility,i,h.webId,h.clientId,"true",void 0,!0);const m=await this.sessionInfoManager.get(i);if(!m)throw new Error(`Could not retrieve session: [${i}].`);return Object.assign(m,{fetch:p,getLogoutUrl:Ko({idTokenHint:h.idToken,endSessionEndpoint:o.endSessionEndpoint}),expirationDate:"number"==typeof h.expiresIn?d+1e3*h.expiresIn:void 0})}}class AggregateRedirectHandler extends AggregateHandler{constructor(e){super(e)}}class BrowserStorage{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 Redirector{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class dist_ClientRegistrar{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[r,n,i,o,a]=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})]),s=void 0!==i?Number.parseInt(i,10):-1,c=void 0!==n&&0!==s&&Math.floor(Date.now()/1e3)>s;if(r&&("string"==typeof(u=a)&&["dynamic","static","solid-oidc"].includes(u))&&!c)return void 0!==n?{clientId:r,clientSecret:n,clientName:o,clientType:"dynamic",expiresAt:s}:{clientId:r,clientName:o,clientType:a};var u;try{const r=await za(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 ErrorOidcHandler{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(Co,n,i)}return Qo()}}class TokenRefresher{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 Vo(e,this.storageUtility,this.issuerConfigFetcher),o=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 a=await Ka(t,i.issuerConfig,o,r);return void 0!==a.refreshToken&&n?.emit(Fo,a.refreshToken),a}}function bh(e){const t=new InMemoryStorage,r=e.secureStorage||t,n=e.insecureStorage||new BrowserStorage,i=new StorageUtilityBrowser(r,n),o=new IssuerConfigFetcher(i),a=new dist_ClientRegistrar(i),s=new SessionInfoManager(i),c=new TokenRefresher(i,o,a),u=new Redirector,l=new OidcLoginHandler(i,new AuthorizationCodeWithPkceOidcHandler(i,u),o,a),d=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(i,s,o,a,c),new FallbackRedirectHandler]);return new ClientAuthentication(l,d,new IWaterfallLogoutHandler(s,u),s,o)}const wh=`${jo}currentSession`,vh=`${jo}currentUrl`;class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;constructor(e={},t=void 0){this.events=new Js,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=bh({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=bh({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??ph(),isLoggedIn:!1},this.events.on(Po,()=>window.localStorage.setItem(wh,this.info.sessionId)),this.events.on(qo,()=>this.internalLogout(!1)),this.events.on(Co,()=>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(wh),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(Oo)};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(vh);null===e?this.events.emit(Po):(window.localStorage.removeItem(vh),this.events.emit($o,e))}else if(!0===t.restorePreviousSession){const e=window.localStorage.getItem(wh);if(null!==e){if(await async function(e,t,r){const n=await t.validateCurrentSession(e);return null!==n&&(window.localStorage.setItem(vh,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(Mo,e=>{this.info.expirationDate=Date.now()+1e3*e})}}const Sh={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 IssuerConfigFetcher_IssuerConfigFetcher{constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}fetchConfig(e){return E(this,void 0,void 0,function*(){let t;const r=new URL(".well-known/openid-configuration",e.endsWith("/")?e:`${e}/`).href;try{const e=yield fetch(r);t=function(e){const t={};return Object.keys(e).forEach(r=>{Sh[r]&&(t[Sh[r].toKey]=e[r])}),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(yield e.json())}catch(t){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return yield this.storageUtility.set(IssuerConfigFetcher_IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t})}}class SolidClientService extends SolidService{constructor(e){var t;super(e),this.options.autoLogin=null!==(t=this.options.autoLogin)&&void 0!==t&&t,this.once("build",this._initialize.bind(this))}get session(){return this._session}set session(e){this._session=e}_initialize(){return new Promise(e=>{this.issuerConfigFetcher=new IssuerConfigFetcher_IssuerConfigFetcher(this.storageUtility),this.handleLogin().then(()=>{e()}).catch(t=>{this.emit("error",t),e()}).finally(()=>{this.emitAsync("ready")})})}login(e=this.options.defaultOidcIssuer,t=!1){return new Promise((t,r)=>{const n=this.createSession({insecureStorage:this.storage,secureStorage:this.storage});this.storage.set("currentSession",n.info.sessionId).then(()=>{const i=this.options.handleRedirect?e=>this.options.handleRedirect(e,e=>{if(e){if(!n.info.isLoggedIn)return void r(e);this.emit("error",e)}t()}):void 0;return n.login({oidcIssuer:e,clientName:this.options.clientName,clientId:this.options.clientId,clientSecret:this.options.clientSecret,redirectUrl:this.options.redirectUrl?this.options.redirectUrl:window.location.href,handleRedirect:i})}).then(()=>{t()}).catch(r)})}handleLogin(){return new Promise((e,t)=>{let r,n,i;this.storage.get("currentSession").then(t=>{if(t){const e="solidClientAuthn:currentSession",r=window.localStorage.getItem(e);r&&t!==r&&window.localStorage.setItem(e,t)}if(t)return i=t,this.findSessionInfoById(t);e(void 0)}).then(e=>E(this,void 0,void 0,function*(){return r=e,n=this.createSession({sessionInfo:Object.assign({sessionId:i},r),insecureStorage:this.storage,secureStorage:this.storage}),this.handleRedirect(n)})).then(e=>E(this,void 0,void 0,function*(){if(e&&e.isLoggedIn){this.session=n,yield this.storage.set("currentSession",e.sessionId);const t=new oh(e.webId);return t.sessionId=e.sessionId,this.storeProfile(t)}throw yield this.storage.delete("currentSession"),new Error("Unable to log in to Solid Pod!")})).then(()=>{this.emit("login",this.session),e(this.session)}).catch(t)})}handleRedirect(e){return E(this,void 0,void 0,function*(){try{const t=new URL(window.location.href);if(null===t.searchParams.get("code")&&null===t.searchParams.get("state")){if(!e)return;const r=yield this.storage.get(`solidClientAuthenticationUser:${e.info.sessionId}:tokens`);if(r){const t=JSON.parse(r),n=yield ra(t.accessToken,{fetch,dpopKey:t.dpopKey,refreshOptions:void 0,eventEmitter:void 0,expiresIn:t.expiresIn}),i=yield this.findSessionInfoById(e.info.sessionId);if(!i)throw new Error(`Could not retrieve session: [${e.info.sessionId}].`);const{issuerConfig:o}=yield Vo(e.info.sessionId,this.storageUtility,this.issuerConfigFetcher);return Object.assign(i,{fetch:n,getLogoutUrl:Ko({idTokenHint:t.idToken,endSessionEndpoint:o.endSessionEndpoint}),expirationDate:t.expirationDate}),Object.assign(e.info,i)}return e.handleIncomingRedirect(t.href)}const r=t.searchParams.get("state"),n=yield this.storageUtility.getForUser(r,"sessionId",{errorIfNull:!0}),{issuerConfig:i,codeVerifier:o,redirectUrl:a,dpop:s}=yield Vo(n,this.storageUtility,this.issuerConfigFetcher),c=t.searchParams.get("iss");if("string"==typeof c&&c!==i.issuer)throw new Error(`The value of the iss parameter (${c}) does not match the issuer identifier of the authorization server (${i.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 ${n} is missing from storage.`);if(void 0===a)throw new Error(`The redirect URL for session ${n} is missing from storage.`);const u=yield this.clientRegistrar.getClient({sessionId:n},i),l=Date.now(),d=yield Ha(i,u,{grantType:"authorization_code",code:t.searchParams.get("code"),codeVerifier:o,redirectUrl:a},s),h="number"==typeof d.expiresIn?l+1e3*d.expiresIn:void 0;yield this.storage.set(`solidClientAuthenticationUser:${n}:tokens`,JSON.stringify(Object.assign(Object.assign({},d),{expirationDate:h})));const f=yield ra(d.accessToken,{fetch,dpopKey:d.dpopKey,refreshOptions:void 0,eventEmitter:void 0,expiresIn:d.expiresIn});yield this.storageUtility.setForUser(n,{webId:d.webId,isLoggedIn:"true"},{secure:!0});const p=yield this.findSessionInfoById(n);if(!p)throw new Error(`Could not retrieve session: [${n}].`);return window.history.replaceState({},document.title,a),Object.assign(p,{fetch:f,getLogoutUrl:Ko({idTokenHint:d.idToken,endSessionEndpoint:i.endSessionEndpoint}),expirationDate:h}),Object.assign(e.info,p)}catch(e){return void this.emit("error",e)}})}createSession(e){return new Session(e)}}})(),o})());
3
3
  //# sourceMappingURL=openhps-solid.min.js.map