From aa2ee9bfdd4edc25095a3ceb8a942f8c1172ff0b Mon Sep 17 00:00:00 2001 From: Michiel de Jong Date: Wed, 11 Dec 2024 14:19:53 +0100 Subject: [PATCH] Use rs-js from https://github.com/remotestorage/remotestorage.js/pull/1319 --- remotestorage.js | 30 ++---------------------------- remotestorage.js.map | 2 +- 2 files changed, 3 insertions(+), 29 deletions(-) diff --git a/remotestorage.js b/remotestorage.js index abf2f97..c574469 100644 --- a/remotestorage.js +++ b/remotestorage.js @@ -1,29 +1,3 @@ -/*! remotestorage.js 2.0.0-beta.3, https://remotestorage.io, MIT licensed */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("RemoteStorage",[],t):"object"==typeof exports?exports.RemoteStorage=t():e.RemoteStorage=t()}(this,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=17)}([function(e,t,r){"use strict";(function(e,r){Object.defineProperty(t,"__esModule",{value:!0}),t.applyMixins=t.toBase64=t.getTextFromArrayBuffer=t.shouldBeTreatedAsBinary=t.getJSONFromLocalStorage=t.localStorageAvailable=t.pathsFromRoot=t.deepClone=t.equal=t.bindAll=t.cleanPath=t.baseName=t.isDocument=t.isFolder=t.containingFolder=t.extend=t.getGlobalContext=t.globalContext=t.logError=void 0,t.logError=e=>{"string"==typeof e?console.error(e):console.error(e.message,e.stack)},t.globalContext="undefined"!=typeof window?window:"object"==typeof self?self:e,t.getGlobalContext=()=>"undefined"!=typeof window?window:"object"==typeof self?self:e,t.extend=(...e)=>{const t=e[0];return Array.prototype.slice.call(e,1).forEach((function(e){for(const r in e)t[r]=e[r]})),t},t.containingFolder=e=>{if(""===e)return"/";if(!e)throw"Path not given!";return e.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},t.isFolder=e=>"/"===e.substr(-1),t.isDocument=e=>!t.isFolder(e),t.baseName=e=>{const r=e.split("/");return t.isFolder(e)?r[r.length-2]+"/":r[r.length-1]},t.cleanPath=e=>e.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27"),t.bindAll=e=>{for(const t in this)"function"==typeof e[t]&&(e[t]=e[t].bind(e))},t.equal=(e,r,n=[])=>{let o;if(typeof e!=typeof r)return!1;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return e===r;if("function"==typeof e)return e.toString()===r.toString();if(e instanceof ArrayBuffer&&r instanceof ArrayBuffer&&(e=new Uint8Array(e),r=new Uint8Array(r)),e instanceof Array){if(e.length!==r.length)return!1;for(let o=0,i=e.length;o=0)continue;i=n.slice(),i.push(r[o])}if(!t.equal(e[o],r[o],i))return!1}}return!0},t.deepClone=e=>{if(void 0!==e){const t=JSON.parse(JSON.stringify(e));return function e(t,r){if("object"==typeof t&&!Array.isArray(t)&&null!==t)for(const n in t)if("object"==typeof t[n]&&null!==t[n])if("[object ArrayBuffer]"===t[n].toString()){r[n]=new ArrayBuffer(t[n].byteLength);const e=new Int8Array(t[n]);new Int8Array(r[n]).set(e)}else e(t[n],r[n])}(e,t),t}},t.pathsFromRoot=e=>{const t=[e],r=e.replace(/\/$/,"").split("/");for(;r.length>1;)r.pop(),t.push(r.join("/")+"/");return t},t.localStorageAvailable=()=>{const e=t.getGlobalContext();if(!("localStorage"in e))return!1;try{return e.localStorage.setItem("rs-check","1"),e.localStorage.removeItem("rs-check"),!0}catch(e){return!1}},t.getJSONFromLocalStorage=e=>{const r=t.getGlobalContext();try{return JSON.parse(r.localStorage.getItem(e))}catch(e){}},t.shouldBeTreatedAsBinary=(e,t)=>!!(t&&t.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(e)),t.getTextFromArrayBuffer=(e,n)=>new Promise(o=>{if("undefined"==typeof Blob){const t=new r(new Uint8Array(e));o(t.toString(n))}else{let r;const i=t.globalContext;if(i.BlobBuilder=i.BlobBuilder||i.WebKitBlobBuilder,void 0!==i.BlobBuilder){const t=new i.BlobBuilder;t.append(e),r=t.getBlob()}else r=new Blob([e]);const s=new FileReader;"function"==typeof s.addEventListener?s.addEventListener("loadend",(function(e){o(e.target.result)})):s.onloadend=function(e){o(e.target.result)},s.readAsText(r,n)}}),t.toBase64=e=>{const n=t.getGlobalContext();return"btoa"in n?n.btoa(e):r.from(e).toString("base64")},t.applyMixins=function(e,t){t.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(r=>{Object.defineProperty(e.prototype,r,Object.getOwnPropertyDescriptor(t.prototype,r))})})}}).call(this,r(5),r(19).Buffer)},function(e,t,r){"use strict";const n=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(3));e.exports=function(...e){n.default.logging&&console.log(...e)}},function(e,t,r){"use strict";const n=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(1));e.exports=class{addEvents(e){e.forEach(e=>this._addEvent(e))}addEventListener(e,t){if("string"!=typeof e)throw new Error("Argument eventName should be a string");if("function"!=typeof t)throw new Error("Argument handler should be a function");n.default("[EventHandling] Adding event listener",e),this._validateEvent(e),this._handlers[e].push(t)}on(e,t){return this.addEventListener(e,t)}removeEventListener(e,t){this._validateEvent(e);const r=this._handlers[e].length;for(let n=0;n{e.apply(this,t)})}_validateEvent(e){if(!(e in this._handlers))throw new Error("Unknown event: "+e)}_delegateEvent(e,t){t.on(e,t=>{this._emit(e,t)})}_addEvent(e){void 0===this._handlers&&(this._handlers={}),this._handlers[e]=[]}}},function(e,t,r){"use strict";const n={cache:!0,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},cordovaRedirectUri:void 0,logging:!1,modules:[],backgroundSyncInterval:6e4,disableFeatures:[],discoveryTimeout:1e4,isBackground:!1,requestTimeout:3e4,syncInterval:1e4};e.exports=n},function(e,t,r){"use strict";class n extends Error{constructor(e,t={}){super(),this.name="Unauthorized",this.message=void 0===e?"App authorization expired or revoked.":e,void 0!==t.code&&(this.code=t.code),this.stack=(new Error).stack}}e.exports=n},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(1)),i=r(0),s=n(r(4));let a;function u(e){const t=e||c.getLocation().href,r=t.indexOf("#");if(-1===r)return;const n=t.substring(r+1);return n.includes("=")?n.split("&").reduce((function(e,t){const r=t.split("=");if("state"===r[0]&&r[1].match(/rsDiscovery/)){let t=decodeURIComponent(r[1]);const n=t.substr(t.indexOf("rsDiscovery=")).split("&")[0].split("=")[1];e.rsDiscovery=JSON.parse(atob(n)),t=t.replace(new RegExp("&?rsDiscovery="+n),""),t.length>0&&(e.state=t)}else e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]);return e}),{}):void 0}class c{static authorize(e,{authURL:t,scope:r,redirectUri:n,clientId:s}){if(o.default("[Authorize] authURL = ",t,"scope = ",r,"redirectUri = ",n,"clientId = ",s),!i.localStorageAvailable()&&"remotestorage"===e.backend){n+=n.indexOf("#")>0?"&":"#";const t={userAddress:e.remote.userAddress,href:e.remote.href,storageApi:e.remote.storageApi,properties:e.remote.properties};n+="rsDiscovery="+i.toBase64(JSON.stringify(t))}const a=function(e,t,r,n){const o=t.indexOf("#");let i=e;return i+=e.indexOf("?")>0?"&":"?",i+="redirect_uri="+encodeURIComponent(t.replace(/#.*$/,"")),i+="&scope="+encodeURIComponent(r),i+="&client_id="+encodeURIComponent(n),-1!==o&&o+1!==t.length&&(i+="&state="+encodeURIComponent(t.substring(o+1))),i+="&response_type=token",i}(t,n,r,s);i.globalContext.cordova?c.openWindow(a,n,"location=yes,clearsessioncache=yes,clearcache=yes").then(t=>{e.remote.configure({token:t.access_token})}):c.setLocation(a)}static setLocation(e){if("string"==typeof e)document.location.href=e;else{if("object"!=typeof e)throw"Invalid location "+e;document.location=e}}static _rs_supported(){return"undefined"!=typeof document}static _rs_cleanup(e){e.removeEventListener("features-loaded",a)}}c.IMPLIED_FAKE_TOKEN=!1,c.getLocation=function(){return document.location},c.openWindow=function(e,t,r){return new Promise((n,o)=>{const i=open(e,"_blank",r);if(!i||i.closed)return o("Authorization popup was blocked");function s(){return o("Authorization was canceled")}i.addEventListener("loadstart",(function(e){if(0!==e.url.indexOf(t))return;i.removeEventListener("exit",s),i.close();const r=u(e.url);return r?n(r):o("Authorization error")})),i.addEventListener("exit",s)})},c._rs_init=function(e){const t=u();let r;t&&(r=c.getLocation(),r.hash=""),a=function(){let n=!1;if(t){if(t.error)throw"access_denied"===t.error?new s.default("Authorization failed: access denied",{code:"access_denied"}):new s.default("Authorization failed: "+t.error);t.rsDiscovery&&e.remote.configure(t.rsDiscovery),t.access_token&&(e.remote.configure({token:t.access_token}),n=!0),t.remotestorage&&(e.connect(t.remotestorage),n=!0),t.state&&(r=c.getLocation(),c.setLocation(r.href.split("#")[0]+"#"+t.state)),n||e.remote.stopWaitingForToken()}else e.remote.stopWaitingForToken()},e.on("features-loaded",a)},e.exports=c},function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(23)),i=n(r(24)),s=n(r(25)),a=n(r(2)),u=n(r(3)),c=r(0);class h{constructor(e,t){if(this.schemas={configurable:!0,get:function(){return h.Types.inScope(this.moduleName)}},"/"!==t[t.length-1])throw"Not a folder: "+t;"/"===t&&(this.makePath=e=>("/"===e[0]?"":"/")+e),this.storage=e,this.base=t;const r=this.base.split("/");r.length>2?this.moduleName=r[1]:this.moduleName="root",this.addEvents(["change"]),this.on=this.on.bind(this),e.onChange(this.base,this._fireChange.bind(this))}scope(e){return new h(this.storage,this.makePath(e))}getListing(e,t){if("string"!=typeof e)e="";else if(e.length>0&&"/"!==e[e.length-1])return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then((function(e){return 404===e.statusCode?{}:e.body}))}getAll(e,t){if("string"!=typeof e)e="";else if(e.length>0&&"/"!==e[e.length-1])return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then(r=>{if(404===r.statusCode)return{};if("object"==typeof r.body){const n=Object.keys(r.body);if(0===n.length)return{};const o=n.map(n=>this.storage.get(this.makePath(e+n),t).then((function(e){if("string"==typeof e.body)try{e.body=JSON.parse(e.body)}catch(e){}"object"==typeof e.body&&(r.body[n]=e.body)})));return Promise.all(o).then((function(){return r.body}))}})}getFile(e,t){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(e),t).then((function(e){return{data:e.body,contentType:e.contentType,revision:e.revision}}))}storeFile(e,t,r){return"string"!=typeof e?Promise.reject("Argument 'mimeType' of baseClient.storeFile must be a string"):"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof r&&"object"!=typeof r?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(t),r,e).then(e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)))}getObject(e,t){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(e),t).then(t=>{if("object"==typeof t.body)return t.body;if("string"==typeof t.body)try{return JSON.parse(t.body)}catch(t){throw new Error("Not valid JSON: "+this.makePath(e))}else if(void 0!==t.body&&200===t.statusCode)return Promise.reject("Not an object: "+this.makePath(e))})}storeObject(e,t,r){if("string"!=typeof e)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof t)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!=typeof r)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(r,e);try{const e=this.validate(r);if(!e.valid)return Promise.reject(e)}catch(e){return Promise.reject(e)}return this.storage.put(this.makePath(t),JSON.stringify(r),"application/json; charset=UTF-8").then(e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode))}remove(e){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage.delete(this.makePath(e)))}getItemURL(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e=c.cleanPath(this.makePath(e)),this.storage.remote.href+e):void 0}cache(e,t="ALL"){if("string"!=typeof e)throw"Argument 'path' of baseClient.cache must be a string";if("string"!=typeof t)throw"Argument 'strategy' of baseClient.cache must be a string or undefined";if("FLUSH"!==t&&"SEEN"!==t&&"ALL"!==t)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(e),t),this}flush(e){return this.storage.local.flush(e)}declareType(e,t,r){let n;r?n=t:(r=t,n=this._defaultTypeURI(e)),h.Types.declare(this.moduleName,e,n,r)}validate(e){const t=h.Types.getSchema(e["@context"]);if(t)return o.default.validateResult(e,t);throw new s.default(e["@context"])}_defaultTypeURI(e){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(e)}_attachType(e,t){e["@context"]=h.Types.resolveAlias(this.moduleName+"/"+t)||this._defaultTypeURI(t)}makePath(e){return this.base+(e||"")}_fireChange(e){u.default.changeEvents[e.origin]&&(["new","old","lastCommon"].forEach((function(t){if((!e[t+"ContentType"]||/^application\/(.*)json(.*)/.exec(e[t+"ContentType"]))&&"string"==typeof e[t+"Value"])try{e[t+"Value"]=JSON.parse(e[t+"Value"])}catch(e){}})),this._emit("change",e))}static _rs_init(){}}h.Types=i.default,c.applyMixins(h,[a.default]),e.exports=h},function(e,t,r){"use strict";(function(t){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{u(n.next(e))}catch(e){i(e)}}function a(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}u((n=n.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=o(r(6)),s=o(r(2)),a=o(r(4)),u=o(r(3)),c=o(r(1)),h=r(0);let l;const d="remotestorage:wireclient",f={"draft-dejong-remotestorage-00":2,"draft-dejong-remotestorage-01":3,"draft-dejong-remotestorage-02":4,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":1};let p;if("function"==typeof(t||window).ArrayBufferView)p=function(e){return e&&e instanceof(t||window).ArrayBufferView};else{const e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];p=function(t){for(let r=0;r<8;r++)if(t instanceof e[r])return!0;return!1}}function m(e){return"string"!=typeof e?e:"*"===e?"*":'"'+e+'"'}function g(e){return"string"!=typeof e?e:e.replace(/^["']|["']$/g,"")}class y{constructor(e){if(this._revisionCache={},l=h.localStorageAvailable(),this.rs=e,this.connected=!1,this.addEvents(["connected","not-connected"]),l){const e=function(){const e=h.getJSONFromLocalStorage(d)||{},{userAddress:t,href:r,storageApi:n,token:o,properties:i}=e;return{userAddress:t,href:r,storageApi:n,token:o,properties:i}}();e&&setTimeout(()=>{this.configure(e)},0)}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}get storageType(){if(this.storageApi){const e=this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);return e?e[1]:"2012.04"}}_request(e,t,r,o,s,u,l){return n(this,void 0,void 0,(function*(){if(function(e,t){return("PUT"===e||"DELETE"===e)&&h.isFolder(t)}(e,t))return Promise.reject(`Don't use ${e} on directories!`);let n;return r!==i.default.IMPLIED_FAKE_TOKEN&&(o.Authorization="Bearer "+r),this.rs._emit("wire-busy",{method:e,isFolder:h.isFolder(t)}),y.request(e,t,{body:s,headers:o,responseType:"arraybuffer"}).then(r=>{if(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:h.isFolder(t),success:!0}),o=r.status,[401,403,404,412].indexOf(o)>=0)return c.default("[WireClient] Error response status",r.status),n=u?g(r.getResponseHeader("ETag")):void 0,401===r.status&&this.rs._emit("error",new a.default),Promise.resolve({statusCode:r.status,revision:n});if(function(e){return[201,204,304].indexOf(e)>=0}(r.status)||200===r.status&&"GET"!==e)return n=g(r.getResponseHeader("ETag")),c.default("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,revision:n});{const e=r.getResponseHeader("Content-Type");n=u?g(r.getResponseHeader("ETag")):200===r.status?l:void 0;const t=function(e){let t,r="UTF-8";return e&&(t=e.match(/charset=(.+)$/),t&&(r=t[1])),r}(e);return h.shouldBeTreatedAsBinary(r.response,e)?(c.default("[WireClient] Successful request with unknown or binary mime-type",n),Promise.resolve({statusCode:r.status,body:r.response,contentType:e,revision:n})):h.getTextFromArrayBuffer(r.response,t).then(t=>(c.default("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,body:t,contentType:e,revision:n})))}var o},r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:h.isFolder(t),success:!1}),Promise.reject(r)))}))}configure(e){if("object"!=typeof e)throw new Error("WireClient configure settings parameter should be an object");if(void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.href=e.href),void 0!==e.storageApi&&(this.storageApi=e.storageApi),void 0!==e.token&&(this.token=e.token),void 0!==e.properties&&(this.properties=e.properties),"string"==typeof this.storageApi){const e=f[this.storageApi]||5;this.supportsRevs=e>=2}this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,l&&(localStorage[d]=JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))}stopWaitingForToken(){this.connected||this._emit("not-connected")}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r={};return this.supportsRevs&&t.ifNoneMatch&&(r["If-None-Match"]=m(t.ifNoneMatch)),this._request("GET",this.href+h.cleanPath(e),this.token,r,void 0,this.supportsRevs,this._revisionCache[e]).then(t=>{if(!h.isFolder(e))return Promise.resolve(t);let r={};if(void 0!==t.body)try{t.body=JSON.parse(t.body)}catch(t){return Promise.reject("Folder description at "+this.href+h.cleanPath(e)+" is not JSON")}if(200===t.statusCode&&"object"==typeof t.body){if(0===Object.keys(t.body).length)t.statusCode=404;else if("http://remotestorage.io/spec/folder-description"===(n=t.body)["@context"]&&"object"==typeof n.items){for(const r in t.body.items)this._revisionCache[e+r]=t.body.items[r].ETag;r=t.body.items}else Object.keys(t.body).forEach(n=>{this._revisionCache[e+n]=t.body[n],r[n]={ETag:t.body[n]}});return t.body=r,Promise.resolve(t)}return Promise.resolve(t);var n})}put(e,t,r,n={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");!r.match(/charset=/)&&(t instanceof ArrayBuffer||p(t))&&(r+="; charset=binary");const o={"Content-Type":r};return this.supportsRevs&&(n.ifMatch&&(o["If-Match"]=m(n.ifMatch)),n.ifNoneMatch&&(o["If-None-Match"]=m(n.ifNoneMatch))),this._request("PUT",this.href+h.cleanPath(e),this.token,o,t,this.supportsRevs)}delete(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");t||(t={});const r={};return this.supportsRevs&&t.ifMatch&&(r["If-Match"]=m(t.ifMatch)),this._request("DELETE",this.href+h.cleanPath(e),this.token,r,void 0,this.supportsRevs)}static request(e,t,r){return n(this,void 0,void 0,(function*(){return"function"==typeof fetch?y._fetchRequest(e,t,r):"function"==typeof XMLHttpRequest?y._xhrRequest(e,t,r):(c.default("[WireClient] You need to add a polyfill for fetch or XMLHttpRequest"),Promise.reject("[WireClient] You need to add a polyfill for fetch or XMLHttpRequest"))}))}static _fetchRequest(e,t,r){let n;const o={};let i;"function"==typeof AbortController&&(i=new AbortController);const s=fetch(t,{method:e,headers:r.headers,body:r.body,signal:i?i.signal:void 0}).then(e=>{switch(c.default("[WireClient fetch]",e),e.headers.forEach((e,t)=>{o[t.toUpperCase()]=e}),n={readyState:4,status:e.status,statusText:e.statusText,response:void 0,getResponseHeader:e=>o[e.toUpperCase()]||null,responseType:r.responseType,responseURL:t},r.responseType){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json();case void 0:case"":case"text":return e.text();default:throw new Error("responseType 'document' is not currently supported using fetch")}}).then(e=>(n.response=e,r.responseType&&"text"!==r.responseType||(n.responseText=e),n)),a=new Promise((e,t)=>{setTimeout(()=>{t("timeout"),i&&i.abort()},u.default.requestTimeout)});return Promise.race([s,a])}static _xhrRequest(e,t,r){return new Promise((n,o)=>{c.default("[WireClient]",e,t);let i=!1;const s=setTimeout(()=>{i=!0,o("timeout")},u.default.requestTimeout),a=new XMLHttpRequest;if(a.open(e,t,!0),r.responseType&&(a.responseType=r.responseType),r.headers)for(const e in r.headers)a.setRequestHeader(e,r.headers[e]);a.onload=()=>{i||(clearTimeout(s),n(a))},a.onerror=e=>{i||(clearTimeout(s),o(e))};let h=r.body;"object"==typeof h&&!p(h)&&h instanceof ArrayBuffer&&(h=new Uint8Array(h)),a.send(h)})}static _rs_init(e){e.remote=new y(e),e.remote.online=!0}static _rs_supported(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest}static _rs_cleanup(){l&&delete localStorage[d]}}y.isArrayBufferView=p,h.applyMixins(y,[s.default]),e.exports=y}).call(this,r(5))},function(e,t,r){"use strict";class n extends Error{constructor(e){super(),this.name="SyncError",this.message="Sync failed: ","string"==typeof e?this.message+=e:(this.message+=e.message,this.stack=e.stack,this.originalError=e)}}e.exports=n},function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(2)),i=n(r(3)),s=n(r(1)),a=r(0);class u{constructor(){this._updateNodesRunning=!1,this._updateNodesQueued=[]}get(e,t,r){return"number"==typeof t?this.getNodes(a.pathsFromRoot(e)).then(n=>{const o=c(n[e]);return h(n,t)?r(e):o?{statusCode:200,body:o.body||o.itemsMap,contentType:o.contentType}:{statusCode:404}}):this.getNodes([e]).then(t=>{const r=c(t[e]);if(r){if(a.isFolder(e))for(const e in r.itemsMap)r.itemsMap.hasOwnProperty(e)&&!1===r.itemsMap[e]&&delete r.itemsMap[e];return{statusCode:200,body:r.body||r.itemsMap,contentType:r.contentType}}return{statusCode:404}})}put(e,t,r){const n=a.pathsFromRoot(e);return this._updateNodes(n,(function(e,n){try{for(let o=0,i=e.length;o0)break}else console.error("Cannot delete non-existing node "+n)}return t}))}flush(e){return this._getAllDescendentPaths(e).then(e=>this.getNodes(e)).then(e=>{for(const t in e){const r=e[t];r&&r.common&&r.local&&this._emitChange({path:r.path,origin:"local",oldValue:!1===r.local.body?void 0:r.local.body,newValue:!1===r.common.body?void 0:r.common.body}),e[t]=void 0}return this.setNodes(e)})}_emitChange(e){i.default.changeEvents[e.origin]&&this._emit("change",e)}fireInitial(){i.default.changeEvents.local&&this.forAllNodes(e=>{if(a.isDocument(e.path)){const t=c(e);t&&this._emitChange({path:e.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:t.body,newContentType:t.contentType})}}).then(()=>{this._emit("local-events-done")})}onDiff(e){this.diffHandler=e}migrate(e){return"object"!=typeof e||e.common||(e.common={},"string"==typeof e.path?"/"===e.path.substr(-1)&&"object"==typeof e.body&&(e.common.itemsMap=e.body):(e.local||(e.local={}),e.local.body=e.body,e.local.contentType=e.contentType)),e}_updateNodes(e,t){return new Promise((r,n)=>{this._doUpdateNodes(e,t,{resolve:r,reject:n})})}_doUpdateNodes(e,t,r){this._updateNodesRunning?this._updateNodesQueued.push({paths:e,cb:t,promise:r}):(this._updateNodesRunning=!0,this.getNodes(e).then(n=>{const o=a.deepClone(n),i=[];n=t(e,n);for(const e in n){const t=n[e];a.equal(t,o[e])?delete n[e]:a.isDocument(e)&&(a.equal(t.local.body,t.local.previousBody)&&t.local.contentType===t.local.previousContentType||i.push({path:e,origin:"window",oldValue:t.local.previousBody,newValue:!1===t.local.body?void 0:t.local.body,oldContentType:t.local.previousContentType,newContentType:t.local.contentType}),delete t.local.previousBody,delete t.local.previousContentType)}this.setNodes(n).then(()=>{this._emitChangeEvents(i),r.resolve({statusCode:200})})}).then(()=>Promise.resolve(),e=>{r.reject(e)}).then(()=>{this._updateNodesRunning=!1;const e=this._updateNodesQueued.shift();e&&this._doUpdateNodes(e.paths,e.cb,e.promise)}))}_emitChangeEvents(e){for(let t=0,r=e.length;t{const r=[e],n=c(t[e]),o=Object.keys(n.itemsMap).map(t=>this._getAllDescendentPaths(e+t).then(e=>{for(let t=0,n=e.length;tr)}):Promise.resolve([e])}_getInternals(){return{getLatest:c,makeNode:l,isOutdated:h}}}function c(e){if("object"==typeof e&&"string"==typeof e.path)if(a.isFolder(e.path)){if(e.local&&e.local.itemsMap)return e.local;if(e.common&&e.common.itemsMap)return e.common}else{if(e.local){if(e.local.body&&e.local.contentType)return e.local;if(!1===e.local.body)return}if(e.common&&e.common.body&&e.common.contentType)return e.common;if(e.body&&e.contentType)return{body:e.body,contentType:e.contentType}}}function h(e,t){for(const r in e){if(e[r]&&e[r].remote)return!0;const n=c(e[r]);if(n&&n.timestamp&&(new Date).getTime()-n.timestamp<=t)return!1;if(!n)return!0}return!0}function l(e){const t={path:e,common:{}};return a.isFolder(e)&&(t.common.itemsMap={}),t}function d(e,t){return e.common||(e.common={itemsMap:{}}),e.common.itemsMap||(e.common.itemsMap={}),e.local||(e.local=a.deepClone(e.common)),e.local.itemsMap||(e.local.itemsMap=e.common.itemsMap),e.local.itemsMap[t]=!0,e}a.applyMixins(u,[o.default]),e.exports=u},function(e,t,r){"use strict";e.exports=class{constructor(){this.reset()}static _rs_init(){}get scopes(){return Object.keys(this.scopeModeMap).map(e=>({name:e,mode:this.scopeModeMap[e]}))}get scopeParameter(){return this.scopes.map(e=>`${this._scopeNameForParameter(e)}:${e.mode}`).join(" ")}claim(e,t){if("string"!=typeof e||-1!==e.indexOf("/")||0===e.length)throw new Error("Scope should be a non-empty string without forward slashes");if(!t.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(e),this.scopeModeMap[e]=t}get(e){return this.scopeModeMap[e]}remove(e){const t={};for(const e in this.scopeModeMap)t[e]=this.scopeModeMap[e];this.reset(),delete t[e];for(const e in t)this.claim(e,t[e])}checkPermission(e,t){const r=this.get(e);return r&&("r"===t||"rw"===r)}checkPathPermission(e,t){if(this.checkPermission("*",t))return!0;const r=this._getModuleName(e);return!!this.checkPermission(r,t)}reset(){this.rootPaths=[],this.scopeModeMap={}}_getModuleName(e){if("/"!==e[0])throw new Error("Path should start with a slash");const t=e.replace(/^\/public/,"").match(/^\/([^/]*)\//);return t?t[1]:"*"}_adjustRootPaths(e){"*"in this.scopeModeMap||"*"===e?this.rootPaths=["/"]:e in this.scopeModeMap||(this.rootPaths.push("/"+e+"/"),this.rootPaths.push("/public/"+e+"/"))}_scopeNameForParameter(e){if("*"===e.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return e.name}setStorageType(e){this.storageType=e}}},function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=r(0),i=n(r(1));e.exports=class{constructor(){this.pendingActivations=[],this.reset()}set(e,t){if("string"!=typeof e)throw new Error("path should be a string");if(!o.isFolder(e))throw new Error("path should be a folder");if(!t.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[e]=t,"ALL"===t&&(this.activateHandler?this.activateHandler(e):this.pendingActivations.push(e))}enable(e){this.set(e,"ALL")}disable(e){this.set(e,"FLUSH")}onActivate(e){i.default("[Caching] Setting activate handler",e,this.pendingActivations),this.activateHandler=e;for(let t=0;t=r-this.maxAge?t.v:void 0}set(e,t){this._items[e]={v:t,t:(new Date).getTime()}}}class y{constructor(e,t){if(this.connected=!1,this.online=!0,this.addEvents(["connected","not-connected"]),this.rs=e,this.clientId=t,this._fileIdCache=new g(300),h=a.localStorageAvailable(),h){const e=a.getJSONFromLocalStorage(c);e&&this.configure(e)}}configure(e){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);const t=function(){h&&localStorage.setItem(c,JSON.stringify({userAddress:this.userAddress,token:this.token}))},r=function(){this.connected=!1,delete this.token,h&&localStorage.removeItem(c)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),t.apply(this)):this.info().then(e=>{this.userAddress=e.user.emailAddress,this._emit("connected"),t.apply(this)}).catch(()=>{r.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))})):r.apply(this)}connect(){this.rs.setBackend("googledrive"),this.rs.authorize({authURL:"https://accounts.google.com/o/oauth2/auth",scope:"https://www.googleapis.com/auth/drive",clientId:this.clientId})}stopWaitingForToken(){this.connected||this._emit("not-connected")}get(e,t){return a.isFolder(e)?this._getFolder(p(e)):this._getFile(p(e),t)}put(e,t,r,n){const o=p(e);function i(e){if(e.status>=200&&e.status<300){const t=JSON.parse(e.responseText),r=m(t.etag);return Promise.resolve({statusCode:200,contentType:t.mimeType,revision:r})}return 412===e.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+e.status+" ("+e.responseText+")")}return this._getFileId(o).then(e=>e?n&&"*"===n.ifNoneMatch?i({status:412}):this._updateFile(e,o,t,r,n).then(i):this._createFile(o,t,r).then(i))}delete(e,t){const r=p(e);return this._getFileId(r).then(e=>e?this._getMeta(e).then(r=>{let n;return"object"==typeof r&&"string"==typeof r.etag&&(n=m(r.etag)),t&&t.ifMatch&&t.ifMatch!==n?{statusCode:412,revision:n}:this._request("DELETE",u+"/drive/v2/files/"+e,{}).then(e=>200===e.status||204===e.status?{statusCode:200}:Promise.reject("Delete failed: "+e.status+" ("+e.responseText+")"))}):Promise.resolve({statusCode:200}))}info(){return this._request("GET","https://www.googleapis.com/drive/v2/about?fields=user",{}).then((function(e){try{const t=JSON.parse(e.responseText);return Promise.resolve(t)}catch(e){return Promise.reject(e)}}))}_updateFile(e,t,r,n,o){const i={mimeType:n},s={"Content-Type":"application/json; charset=UTF-8"};return o&&o.ifMatch&&(s["If-Match"]='"'+o.ifMatch+'"'),this._request("PUT",u+"/upload/drive/v2/files/"+e+"?uploadType=resumable",{body:JSON.stringify(i),headers:s}).then(e=>412===e.status?e:this._request("PUT",e.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(r):r}))}_createFile(e,t,r){return this._getParentId(e).then(n=>{const o={title:l(f(e)),mimeType:r,parents:[{kind:"drive#fileLink",id:n}]};return this._request("POST",u+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(o),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(e=>this._request("POST",e.getResponseHeader("Location"),{body:r.match(/^application\/json/)?JSON.stringify(t):t}))})}_getFile(e,t){return this._getFileId(e).then(e=>this._getMeta(e).then(e=>{let r;if("object"==typeof e&&"string"==typeof e.etag&&(r=m(e.etag)),t&&t.ifNoneMatch&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304});if(!e.downloadUrl){if(!e.exportLinks||!e.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:e.mimeType,revision:r});e.mimeType+=";export=text/html",e.downloadUrl=e.exportLinks["text/html"]}return this._request("GET",e.downloadUrl,{responseType:"arraybuffer"}).then(t=>a.getTextFromArrayBuffer(t.response,"UTF-8").then((function(n){let o=n;if(e.mimeType.match(/^application\/json/))try{o=JSON.parse(o)}catch(e){}else a.shouldBeTreatedAsBinary(n,e.mimeType)&&(o=t.response);return{statusCode:200,body:o,contentType:e.mimeType,revision:r}})))}))}_getFolder(e){return this._getFileId(e).then(t=>{let r,n,o;if(!t)return Promise.resolve({statusCode:404});const i="'"+t+"' in parents";return this._request("GET",u+"/drive/v2/files?q="+encodeURIComponent(i)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title,labels)")+"&maxResults=1000&trashed=false",{}).then(t=>{var i;if(200!==t.status)return Promise.reject("request failed or something: "+t.status);try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject("non-JSON response from GoogleDrive")}o={};for(const t of r.items)(null===(i=t.labels)||void 0===i?void 0:i.trashed)||(n=m(t.etag),"application/vnd.google-apps.folder"===t.mimeType?(this._fileIdCache.set(e+a.cleanPath(t.title)+"/",t.id),o[t.title+"/"]={ETag:n}):(this._fileIdCache.set(e+a.cleanPath(t.title),t.id),o[t.title]={ETag:n,"Content-Type":t.mimeType,"Content-Length":t.fileSize}));return Promise.resolve({statusCode:200,body:o,contentType:"application/json; charset=UTF-8",revision:void 0})})})}_getParentId(e){const t=d(e);return this._getFileId(t).then(e=>e?Promise.resolve(e):this._createFolder(t))}_createFolder(e){return this._getParentId(e).then(t=>this._request("POST",u+"/drive/v2/files",{body:JSON.stringify({title:l(f(e)),mimeType:"application/vnd.google-apps.folder",parents:[{id:t}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(e=>{const t=JSON.parse(e.responseText);return Promise.resolve(t.id)}))}_getFileId(e){let t;return"/"===e?Promise.resolve("root"):(t=this._fileIdCache.get(e))?Promise.resolve(t):this._getFolder(d(e)).then(()=>(t=this._fileIdCache.get(e),t?Promise.resolve(t):"/"===e.substr(-1)?this._createFolder(e).then(()=>this._getFileId(e)):Promise.resolve()))}_getMeta(e){return this._request("GET",u+"/drive/v2/files/"+e,{}).then((function(t){return 200===t.status?Promise.resolve(JSON.parse(t.responseText)):Promise.reject("request (getting metadata for "+e+") failed with status: "+t.status)}))}_request(e,t,r){return r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:e,isFolder:a.isFolder(t)}),i.default.request.call(this,e,t,r).then(r=>r&&401===r.status?void this.connect():(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:a.isFolder(t),success:!0}),Promise.resolve(r)),r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:a.isFolder(t),success:!1}),Promise.reject(r)))}static _rs_init(e){const t=e.apiKeys.googledrive;var r;t&&(e.googledrive=new y(e,t.clientId),"googledrive"===e.backend&&(e._origRemote=e.remote,e.remote=e.googledrive,(r=e)._origBaseClientGetItemURL||(r._origBaseClientGetItemURL=o.default.prototype.getItemURL,o.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(o.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}a.applyMixins(y,[s.default]),e.exports=y},function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{u(n.next(e))}catch(e){i(e)}}function a(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}u((n=n.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=o(r(2)),s=o(r(8)),a=o(r(7)),u=o(r(26)),c=o(r(9)),h=o(r(4)),l=r(0);let d;const f="remotestorage:dropbox";function p(e){return l.cleanPath("/remotestorage/"+e).replace(/\/$/,"")}function m(e,t){return new RegExp("^"+t.join("\\/")+"(\\/|$)").test(e.error_summary)}function g(e){return e instanceof ArrayBuffer||s.default.isArrayBufferView(e)}class y{constructor(e){if(this.rs=e,this.connected=!1,this.online=!0,this._initialFetchDone=!1,this.addEvents(["connected","not-connected"]),this.clientId=e.apiKeys.dropbox.appKey,this._revCache=new u.default("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},d=l.localStorageAvailable(),d){const e=l.getJSONFromLocalStorage(f);e&&this.configure(e),this._itemRefs=l.getJSONFromLocalStorage(f+":shares")||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}connect(){this.rs.setBackend("dropbox"),this.token?b(this.rs):this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"",clientId:this.clientId})}configure(e){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);const t=function(){d&&localStorage.setItem(f,JSON.stringify({userAddress:this.userAddress,token:this.token}))},r=function(){this.connected=!1,d&&localStorage.removeItem(f)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),t.apply(this)):this.info().then(function(e){this.userAddress=e.email,this._emit("connected"),t.apply(this)}.bind(this)).catch(function(){r.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))}.bind(this))):r.apply(this)}stopWaitingForToken(){this.connected||this._emit("not-connected")}_getFolder(e){const t=this._revCache,r=r=>{let o;if(200!==r.status&&409!==r.status)return Promise.reject("Unexpected response status: "+r.status);try{o=JSON.parse(r.responseText)}catch(e){return Promise.reject(e)}if(409===r.status)return m(o,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+o.error_summary));const i=o.entries.reduce((r,n)=>{const o="folder"===n[".tag"],i=n.path_lower.split("/").slice(-1)[0]+(o?"/":"");return o?r[i]={ETag:t.get(e+i)}:(r[i]={ETag:n.rev},this._revCache.set(e+i,n.rev)),r},{});return o.has_more?n(o.cursor).then((function(e){return Object.assign(i,e)})):Promise.resolve(i)},n=e=>{const t={body:{cursor:e}};return this._request("POST","https://api.dropboxapi.com/2/files/list_folder/continue",t).then(r)};return this._request("POST","https://api.dropboxapi.com/2/files/list_folder",{body:{path:p(e)}}).then(r).then((function(r){return Promise.resolve({statusCode:200,body:r,contentType:"application/json; charset=UTF-8",revision:t.get(e)})}))}get(e,t){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r=this._revCache.get(e);if(null===r)return Promise.resolve({statusCode:404});if(t&&t.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then(()=>this.get(e,t));if(r&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===e.substr(-1))return this._getFolder(e);const n={headers:{"Dropbox-API-Arg":JSON.stringify({path:p(e)})},responseType:"arraybuffer"};return t&&t.ifNoneMatch&&(n.headers["If-None-Match"]=t.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",n).then(t=>{const r=t.status;let n,o,i,s;return 200!==r&&409!==r?Promise.resolve({statusCode:r}):(n=t.getResponseHeader("Dropbox-API-Result"),l.getTextFromArrayBuffer(t.response,"UTF-8").then(a=>{o=a,409===r&&(n=o);try{n=JSON.parse(n)}catch(e){return Promise.reject(e)}if(409===r)return m(n,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+e+'"): '+n.error_summary));if(i=t.getResponseHeader("Content-Type"),s=n.rev,this._revCache.set(e,s),this._shareIfNeeded(e),l.shouldBeTreatedAsBinary(a,i))o=t.response;else try{o=JSON.parse(o),i="application/json; charset=UTF-8"}catch(e){}return{statusCode:r,body:o,contentType:i,revision:s}}))})}put(e,t,r,n){if(!this.connected)throw new Error("not connected (path: "+e+")");const o=this._revCache.get(e);if(n&&n.ifMatch&&o&&o!==n.ifMatch)return Promise.resolve({statusCode:412,revision:o});if(n&&"*"===n.ifNoneMatch&&o&&"rev"!==o)return Promise.resolve({statusCode:412,revision:o});if(!r.match(/charset=/)&&g(t)&&(r+="; charset=binary"),t.length>157286400)return Promise.reject(new Error("Cannot upload file larger than 150MB"));let i;const s=n&&(n.ifMatch||"*"===n.ifNoneMatch),a={body:t,contentType:r,path:e};return i=s?this._getMetadata(e).then(e=>n&&"*"===n.ifNoneMatch&&e||n&&n.ifMatch&&e&&e.rev!==n.ifMatch?Promise.resolve({statusCode:412,revision:e.rev}):this._uploadSimple(a)):this._uploadSimple(a),i.then(t=>(this._shareIfNeeded(e),t))}delete(e,t){if(!this.connected)throw new Error("not connected (path: "+e+")");const r=this._revCache.get(e);return t&&t.ifMatch&&r&&t.ifMatch!==r?Promise.resolve({statusCode:412,revision:r}):t&&t.ifMatch?this._getMetadata(e).then(r=>t&&t.ifMatch&&r&&r.rev!==t.ifMatch?Promise.resolve({statusCode:412,revision:r.rev}):this._deleteSimple(e)):this._deleteSimple(e)}_shareIfNeeded(e){e.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[e]&&this.share(e)}share(e){const t={body:{path:p(e)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",t).then(t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status:"+t.status));let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?m(r,["shared_link_already_exists"])?this._getSharedLink(e):Promise.reject(new Error("API error: "+r.error_summary)):Promise.resolve(r.url)}).then(t=>(this._itemRefs[e]=t,d&&localStorage.setItem(f+":shares",JSON.stringify(this._itemRefs)),Promise.resolve(t)),t=>(t.message='Sharing Dropbox file or folder ("'+e+'") failed: '+t.message,Promise.reject(t)))}info(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then((function(e){let t=e.responseText;try{t=JSON.parse(t)}catch(e){return Promise.reject(new Error("Could not query current account info: Invalid API response: "+t))}return Promise.resolve({email:t.email})}))}_request(e,t,r){return r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,"object"!=typeof r.body||g(r.body)||(r.body=JSON.stringify(r.body),r.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:e,isFolder:l.isFolder(t)}),s.default.request.call(this,e,t,r).then(n=>n&&503===n.status?(this.online&&(this.online=!1,this.rs._emit("network-offline")),setTimeout(this._request(e,t,r),3210)):(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:l.isFolder(t),success:!0}),Promise.resolve(n)),r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:l.isFolder(t),success:!1}),Promise.reject(r)))}fetchDelta(...e){if(this._fetchDeltaPromise)return this._fetchDeltaPromise;const t=r=>{let n,o="https://api.dropboxapi.com/2/files/list_folder";return"string"==typeof r?(o+="/continue",n={cursor:r}):n={path:"/remotestorage",recursive:!0,include_deleted:!0},this._request("POST",o,{body:n}).then(n=>{if(401===n.status)return this.rs._emit("error",new h.default),Promise.resolve(e);if(200!==n.status&&409!==n.status)return Promise.reject(new Error("Invalid response status: "+n.status));let o;try{o=JSON.parse(n.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+n.responseText))}if(409===n.status){if(!m(o,["path","not_found"]))return Promise.reject(new Error("API returned an error: "+o.error_summary));o={cursor:null,entries:[],has_more:!1}}if(r||this._revCache.deactivatePropagation(),o.entries.forEach(e=>{const t=e.path_lower.substr("/remotestorage".length);"deleted"===e[".tag"]?(this._revCache.delete(t),this._revCache.delete(t+"/")):"file"===e[".tag"]&&this._revCache.set(t,e.rev)}),this._fetchDeltaCursor=o.cursor,o.has_more)return t(o.cursor);this._revCache.activatePropagation(),this._initialFetchDone=!0}).catch(e=>"timeout"===e||e instanceof ProgressEvent?Promise.resolve():Promise.reject(e))};return this._fetchDeltaPromise=t(this._fetchDeltaCursor).catch(e=>("object"==typeof e&&"message"in e?e.message="Dropbox: fetchDelta: "+e.message:e="Dropbox: fetchDelta: "+e,this._fetchDeltaPromise=null,Promise.reject(e))).then(()=>(this._fetchDeltaPromise=null,Promise.resolve(e))),this._fetchDeltaPromise}_getMetadata(e){const t={path:p(e)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:t}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?m(t,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve(t)}).then(void 0,t=>(t.message='Could not load metadata for file or folder ("'+e+'"): '+t.message,Promise.reject(t)))}_uploadSimple(e){const t={path:p(e.path),mode:{".tag":"overwrite",update:void 0},mute:!0};return e.ifMatch&&(t.mode={".tag":"update",update:e.ifMatch}),this._request("POST","https://content.dropboxapi.com/2/files/upload",{body:e.body,headers:{"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify(t)}}).then(t=>{if(200!==t.status&&409!==t.status)return Promise.resolve({statusCode:t.status});let r=t.responseText;try{r=JSON.parse(r)}catch(e){return Promise.reject(new Error("Invalid API result: "+r))}return 409===t.status?m(r,["path","conflict"])?this._getMetadata(e.path).then((function(e){return Promise.resolve({statusCode:412,revision:e.rev})})):Promise.reject(new Error("API error: "+r.error_summary)):(this._revCache.set(e.path,r.rev),Promise.resolve({statusCode:t.status,revision:r.rev}))})}_deleteSimple(e){const t={path:p(e)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:t}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});let t=e.responseText;try{t=JSON.parse(t)}catch(e){return Promise.reject(new Error("Invalid response body: "+t))}return 409===e.status?m(t,["path_lookup","not_found"])?Promise.resolve({statusCode:404}):Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve({statusCode:200})}).then(t=>(200!==t.statusCode&&404!==t.statusCode||(this._revCache.delete(e),delete this._itemRefs[e]),Promise.resolve(t)),t=>(t.message='Could not delete Dropbox file or folder ("'+e+'"): '+t.message,Promise.reject(t)))}_getSharedLink(e){return n(this,void 0,void 0,(function*(){const t={body:{path:p(e),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",t).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status: "+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?Promise.reject(new Error("API error: "+e.error_summary)):t.links.length?Promise.resolve(t.links[0].url):Promise.reject(new Error("No links returned"))},t=>(t.message='Could not get link to a shared file or folder ("'+e+'"): '+t.message,Promise.reject(t)))}))}static _rs_init(e){d=l.localStorageAvailable(),e.apiKeys.dropbox&&(e.dropbox=new y(e)),"dropbox"===e.backend&&b(e)}static _rs_supported(){return!0}static _rs_cleanup(e){!function(e){(function(e){e._origRemote&&(e.remote=e._origRemote,delete e._origRemote)})(e),function(e){if(!e._dropboxOrigSync)return;e.sync.sync=e._dropboxOrigSync,delete e._dropboxOrigSync}(e),function(e){if(!e._origBaseClientGetItemURL)return;a.default.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL}(e),_(e)}(e),d&&localStorage.removeItem(f),e.setBackend(void 0)}}function v(e,...t){e._dropboxOrigSync||(e._dropboxOrigSync=e.sync.sync.bind(e.sync),e.sync.sync=function(){return this.dropbox.fetchDelta(e,...t).then(e._dropboxOrigSync,(function(t){e._emit("error",new c.default(t)),e._emit("sync-done")}))}.bind(e))}function _(e){e._dropboxOrigSyncCycle&&(e.syncCycle=e._dropboxOrigSyncCycle,delete e._dropboxOrigSyncCycle)}function b(e){!function(e){e._origRemote||(e._origRemote=e.remote,e.remote=e.dropbox)}(e),e.sync?v(e):function(e,...t){e._dropboxOrigSyncCycle||(e._dropboxOrigSyncCycle=e.syncCycle,e.syncCycle=()=>{if(!e.sync)throw new Error("expected sync to be initialized by now");v(e),e._dropboxOrigSyncCycle(e,...t),_(e)})}(e),function(e){e._origBaseClientGetItemURL||(e._origBaseClientGetItemURL=a.default.prototype.getItemURL,a.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(e)}l.applyMixins(y,[i.default]),e.exports=y},function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(27)),i=n(r(1)),s=r(0);let a,u;let c={};const h=function(e){return new Promise((t,r)=>{if(e in c)return t(c[e]);return new o.default({tls_only:!1,uri_fallback:!0,request_timeout:5e3}).lookup(e,(function(n,o){if(n)return r(n);if("object"!=typeof o.idx.links.remotestorage||"number"!=typeof o.idx.links.remotestorage.length||o.idx.links.remotestorage.length<=0)return i.default("[Discover] WebFinger record for "+e+" does not have remotestorage defined in the links section ",JSON.stringify(o.json)),r("WebFinger record for "+e+" does not have remotestorage defined in the links section.");const s=o.idx.links.remotestorage[0],a=s.properties["http://tools.ietf.org/html/rfc6749#section-4.2"]||s.properties["auth-endpoint"],h=s.properties["http://remotestorage.io/spec/version"]||s.type;return c[e]={href:s.href,storageApi:h,authURL:a,properties:s.properties},u&&(localStorage["remotestorage:discover"]=JSON.stringify({cache:c})),t(c[e])}))})};(h.DiscoveryError=function(e){this.name="DiscoveryError",this.message=e,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),h.DiscoveryError.prototype.constructor=h.DiscoveryError,h._rs_init=function(){if(u=s.localStorageAvailable(),u)try{const e=JSON.parse(localStorage["remotestorage:discover"]);c=e.cache}catch(e){}},h._rs_supported=function(){return a=Object.prototype.hasOwnProperty.call(s.globalContext,"XMLHttpRequest"),a},h._rs_cleanup=function(){u&&delete localStorage["remotestorage:discover"]},e.exports=h},function(e,t,r){"use strict";const n=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(2)),o=r(0);class i{constructor(){this.addEvents(["background","foreground"]),this.mode="undefined"!=typeof window?"browser":"node","browser"===this.mode&&(this.setBrowserPrefixedNames(),document.addEventListener(this.visibilityChangeEvent,this.setVisibility.bind(this),!1),this.setVisibility())}setBrowserPrefixedNames(){"browser"===this.mode&&(void 0!==document.hidden?(this.hiddenProperty="hidden",this.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(this.hiddenProperty="mozHidden",this.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(this.hiddenProperty="msHidden",this.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(this.hiddenProperty="webkitHidden",this.visibilityChangeEvent="webkitvisibilitychange"))}setVisibility(){document[this.hiddenProperty]?this.goBackground():this.goForeground()}isBrowser(){return"browser"===this.mode}isNode(){return"node"===this.mode}goBackground(){this._emit("background")}goForeground(){this._emit("foreground")}static _rs_init(){}static _rs_cleanup(){}}o.applyMixins(i,[n.default]),e.exports=i},function(e,t,r){e.exports=r(18)},function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.hasOwnProperty.call(e,r)&&n(t,e,r);return o(t,e),t},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const a=s(r(3)),u=s(r(1)),c=r(0),h=s(r(11)),l=s(r(6)),d=s(r(7)),f=s(r(12)),p=s(r(2)),m=s(r(13)),g=s(r(14)),y=s(r(15)),v=s(r(9)),_=s(r(4)),b=s(r(29)),w=i(r(0)),P=c.getGlobalContext();let E;function T(e){return 403!==e.statusCode&&401!==e.statusCode||this._emit("error",new _.default),Promise.resolve(e)}function A(e){return"number"==typeof e&&e>=2e3&&e<=36e5}class R{constructor(e){this._pending=[],this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this._init=b.default.loadFeatures,this.features=b.default.features,this.loadFeature=b.default.loadFeature,this.featureSupported=b.default.featureSupported,this.featureDone=b.default.featureDone,this.featuresDone=b.default.featuresDone,this.featuresLoaded=b.default.featuresLoaded,this.featureInitialized=b.default.featureInitialized,this.featureFailed=b.default.featureFailed,this.hasFeature=b.default.hasFeature,this._setCachingModule=b.default._setCachingModule,this._collectCleanupFunctions=b.default._collectCleanupFunctions,this._fireReady=b.default._fireReady,this.initFeature=b.default.initFeature,"object"==typeof e&&c.extend(a.default,e),this.addEvents(["ready","authing","connecting","connected","disconnected","not-connected","conflict","error","features-loaded","sync-interval-change","sync-req-done","sync-done","wire-busy","wire-done","network-offline","network-online"]),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")}),E=c.localStorageAvailable(),E&&(this.apiKeys=c.getJSONFromLocalStorage("remotestorage:api-keys")||{},this.setBackend(localStorage.getItem("remotestorage:backend")||"remotestorage"));const t=this.on;this.on=function(e,r){if(this._allLoaded)switch(e){case"features-loaded":setTimeout(r,0);break;case"ready":this.remote&&setTimeout(r,0);break;case"connected":this.remote&&this.remote.connected&&setTimeout(r,0);break;case"not-connected":this.remote&&!this.remote.connected&&setTimeout(r,0)}return t.call(this,e,r)},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this)),this.loadModules()}get connected(){return this.remote.connected}loadModules(){a.default.modules.forEach(this.addModule.bind(this))}authorize(e){if(this.access.setStorageType(this.remote.storageApi),void 0===e.scope&&(e.scope=this.access.scopeParameter),P.cordova)e.redirectUri=a.default.cordovaRedirectUri;else{const t=l.default.getLocation();let r=t.origin;"/"!==t.pathname&&(r+=t.pathname),e.redirectUri=r}void 0===e.clientId&&(e.clientId=e.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),l.default.authorize(this,e)}impliedauth(e,t){e=e||this.remote.storageApi,t=t||String(document.location),u.default("ImpliedAuth proceeding due to absent authURL; storageApi = "+e+" redirectUri = "+t),this.remote.configure({token:l.default.IMPLIED_FAKE_TOKEN}),document.location.href=t}connect(e,t){if(this.setBackend("remotestorage"),e.indexOf("@")<0&&!e.match(/^(https?:\/\/)?[^\s\/$\.?#]+\.[^\s]*$/))return void this._emit("error",new R.DiscoveryError("Not a valid user address or URL."));if(e.indexOf("@")<0&&!e.match(/^https?:\/\//)&&(e="https://"+e),P.cordova){if("string"!=typeof a.default.cordovaRedirectUri)return void this._emit("error",new R.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!P.cordova.InAppBrowser)return void this._emit("error",new R.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:e}),this._emit("connecting");const r=setTimeout(()=>{this._emit("error",new R.DiscoveryError("No storage information found for this user address."))},a.default.discoveryTimeout);y.default(e).then(n=>{if(clearTimeout(r),this._emit("authing"),n.userAddress=e,this.remote.configure(n),!this.remote.connected)if(n.authURL)if(void 0===t)this.authorize({authURL:n.authURL});else{if("string"!=typeof t)throw new Error("Supplied bearer token must be a string");u.default("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:t})}else this.impliedauth()},()=>{clearTimeout(r),this._emit("error",new R.DiscoveryError("No storage information found for this user address."))})}reconnect(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()}disconnect(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")});const e=this._cleanups.length;let t=0;const r=()=>{t++,t>=e&&(this._init(),this._emit("disconnected"))};e>0?this._cleanups.forEach(e=>{const t=e(this);"object"==typeof t&&"function"==typeof t.then?t.then(r):r()}):r()}setBackend(e){this.backend=e,E&&(e?localStorage.setItem("remotestorage:backend",e):localStorage.removeItem("remotestorage:backend"))}onChange(e,t){this._pathHandlers.change[e]||(this._pathHandlers.change[e]=[]),this._pathHandlers.change[e].push(t)}enableLog(){a.default.logging=!0}disableLog(){a.default.logging=!1}log(...e){u.default.apply(R,e)}setApiKeys(e){const t=[S.GOOGLE,S.DROPBOX];if("object"!=typeof e||!Object.keys(e).every(e=>t.includes(e)))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(e).forEach(t=>{const r=e[t];if(r){switch(t){case S.DROPBOX:this.apiKeys[S.DROPBOX]={appKey:r},void 0!==this.dropbox&&this.dropbox.clientId===r||g.default._rs_init(this);break;case S.GOOGLE:this.apiKeys[S.GOOGLE]={clientId:r},void 0!==this.googledrive&&this.googledrive.clientId===r||m.default._rs_init(this)}return!0}delete this.apiKeys[t]}),E&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))}setCordovaRedirectUri(e){if("string"!=typeof e||!e.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");a.default.cordovaRedirectUri=e}_setGPD(e,t){function r(e){return function(...r){return e.apply(t,r).then(T.bind(this))}}this.get=r(e.get),this.put=r(e.put),this.delete=r(e.delete)}_pendingGPD(e){return(...t)=>{const r=Array.prototype.slice.call(t);return new Promise((t,n)=>{this._pending.push({method:e,args:r,promise:{resolve:t,reject:n}})})}}_processPending(){this._pending.forEach(e=>{try{this[e.method](...e.args).then(e.promise.resolve,e.promise.reject)}catch(t){e.promise.reject(t)}}),this._pending=[]}_bindChange(e){e.on("change",this._dispatchEvent.bind(this,"change"))}_dispatchEvent(e,t){Object.keys(this._pathHandlers[e]).forEach(r=>{const n=r.length;t.path.substr(0,n)===r&&this._pathHandlers[e][r].forEach(e=>{const n={};for(const e in t)n[e]=t[e];n.relativePath=t.path.replace(new RegExp("^"+r),"");try{e(n)}catch(e){console.error("'change' handler failed: ",e,e.stack),this._emit("error",e)}})})}scope(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.scope must be a string";return this.access.checkPathPermission(e,"r")||console.warn("WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestoragejs.readthedocs.io/en/latest/js-api/access.html#claim"),new d.default(this,e)}getSyncInterval(){return a.default.syncInterval}setSyncInterval(e){if(!A(e))throw e+" is not a valid sync interval";const t=a.default.syncInterval;a.default.syncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getBackgroundSyncInterval(){return a.default.backgroundSyncInterval}setBackgroundSyncInterval(e){if(!A(e))throw e+" is not a valid sync interval";const t=a.default.backgroundSyncInterval;a.default.backgroundSyncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getCurrentSyncInterval(){return a.default.isBackground?a.default.backgroundSyncInterval:a.default.syncInterval}getRequestTimeout(){return a.default.requestTimeout}setRequestTimeout(e){if("number"!=typeof e)throw e+" is not a valid request timeout";a.default.requestTimeout=e}syncCycle(){this.sync&&!this.sync.stopped&&(this.on("sync-done",()=>{this.sync&&!this.sync.stopped&&(this._syncTimer&&(clearTimeout(this._syncTimer),this._syncTimer=void 0),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))}),this.sync.sync())}startSync(){return a.default.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())}stopSync(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?this.sync.stopped=!0:this.syncStopped=!0}addModule(e){const t=e.name,r=e.builder;if(Object.defineProperty(this,t,{configurable:!0,get:function(){const e=this._loadModule(t,r);return Object.defineProperty(this,t,{value:e}),e}}),-1!==t.indexOf("-")){const e=t.replace(/\-[a-z]/g,(function(e){return e[1].toUpperCase()}));Object.defineProperty(this,e,{get:function(){return this[t]}})}}_loadModule(e,t){if(t){return t(new d.default(this,"/"+e+"/"),new d.default(this,"/public/"+e+"/")).exports}throw"Unknown module: "+e}}var S;R.Authorize=l.default,R.SyncError=v.default,R.Unauthorized=_.default,R.DiscoveryError=y.default.DiscoveryError,R.util=w,Object.defineProperty(R.prototype,"access",{get:function(){const e=new h.default;return Object.defineProperty(this,"access",{value:e}),e},configurable:!0}),Object.defineProperty(R.prototype,"caching",{configurable:!0,get:function(){const e=new f.default;return Object.defineProperty(this,"caching",{value:e}),e}}),c.applyMixins(R,[p.default]),function(e){e.GOOGLE="googledrive",e.DROPBOX="dropbox"}(S||(S={})),e.exports=R},function(e,t,r){"use strict";(function(e){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -var n=r(20),o=r(21),i=r(22);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function p(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return B(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(n)return B(e).length;t=(""+t).toLowerCase(),n=!0}}function m(e,t,r){var 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 M(this,t,r);case"utf8":case"utf-8":return R(this,t,r);case"ascii":return S(this,t,r);case"latin1":case"binary":return O(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function g(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function y(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:v(e,t,r,n,o);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,n,o){var i,s=1,a=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,u/=2,r/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){var h=-1;for(i=r;ia&&(r=a-u),i=r;i>=0;i--){for(var l=!0,d=0;do&&(n=o):n=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var s=0;s>8,o=r%256,i.push(o),i.push(n);return i}(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 R(e,t,r){r=Math.min(e.length,r);for(var n=[],o=t;o239?4:c>223?3:c>191?2:1;if(o+l<=r)switch(l){case 1:c<128&&(h=c);break;case 2:128==(192&(i=e[o+1]))&&(u=(31&c)<<6|63&i)>127&&(h=u);break;case 3:i=e[o+1],s=e[o+2],128==(192&i)&&128==(192&s)&&(u=(15&c)<<12|(63&i)<<6|63&s)>2047&&(u<55296||u>57343)&&(h=u);break;case 4:i=e[o+1],s=e[o+2],a=e[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(h=u)}null===h?(h=65533,l=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),o+=l}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var r="",n=0;for(;n0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},u.prototype.compare=function(e,t,r,n,o){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(i,s),c=this.slice(n,o),h=e.slice(t,r),l=0;lo)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return _(this,e,t,r);case"utf8":case"utf-8":return b(this,e,t,r);case"ascii":return w(this,e,t,r);case"latin1":case"binary":return P(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function S(e,t,r){var n="";r=Math.min(e.length,r);for(var o=t;on)&&(r=n);for(var o="",i=t;ir)throw new RangeError("Trying to access beyond buffer length")}function I(e,t,r,n,o,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function x(e,t,r,n){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-r,2);o>>8*(n?o:1-o)}function N(e,t,r,n){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-r,4);o>>8*(n?o:3-o)&255}function U(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function j(e,t,r,n,i){return i||U(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function F(e,t,r,n,i){return i||U(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUInt8=function(e,t){return t||C(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||C(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||C(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||C(e,t,this.length);for(var n=this[e],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||C(e,t,this.length);for(var n=t,o=1,i=this[e+--n];n>0&&(o*=256);)i+=this[e+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||C(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){t||C(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||C(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||C(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||C(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||C(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||I(this,e,t,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):x(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):x(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):N(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);I(this,e,t,r,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);I(this,e,t,r,o-1,-o)}var i=r-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s>>0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):x(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):x(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):N(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,r){return j(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return j(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return F(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return F(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--o)e[o+t]=this[o+r];else if(i<1e3||!u.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.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;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function q(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(D,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(e,t,r,n){for(var o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}}).call(this,r(5))},function(e,t,r){"use strict";t.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=c(e),s=n[0],a=n[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,s,a)),h=0,l=a>0?s-4:s;for(r=0;r>16&255,u[h++]=t>>8&255,u[h++]=255&t;2===a&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[h++]=255&t);1===a&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[h++]=t>>8&255,u[h++]=255&t);return u},t.fromByteArray=function(e){for(var t,r=e.length,o=r%3,i=[],s=0,a=r-o;sa?a:s+16383));1===o?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)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 h(e,t,r){for(var o,i,s=[],a=t;a>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},function(e,t){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -t.read=function(e,t,r,n,o){var i,s,a=8*o-n-1,u=(1<>1,h=-7,l=r?o-1:0,d=r?-1:1,f=e[t+l];for(l+=d,i=f&(1<<-h)-1,f>>=-h,h+=a;h>0;i=256*i+e[t+l],l+=d,h-=8);for(s=i&(1<<-h)-1,i>>=-h,h+=n;h>0;s=256*s+e[t+l],l+=d,h-=8);if(0===i)i=1-c;else{if(i===u)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),i-=c}return(f?-1:1)*s*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var s,a,u,c=8*i-o-1,h=(1<>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:i-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?(a=isNaN(t)?1:0,s=h):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+l>=1?d/u:d*Math.pow(2,1-l))*u>=2&&(s++,u/=2),s+l>=h?(a=0,s=h):s+l>=1?(a=(t*u-1)*Math.pow(2,o),s+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,o),s=0));o>=8;e[r+f]=255&a,f+=p,a/=256,o-=8);for(s=s<0;e[r+f]=255&s,f+=p,s/=256,c-=8);e[r+f-p]|=128*m}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},function(e,t,r){var n,o,i;o=[],void 0===(i="function"==typeof(n=function(){var e,t,r,n;Object.keys||(Object.keys=(e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),n=(r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(o){if("object"!=typeof o&&"function"!=typeof o||null===o)throw new TypeError("Object.keys called on non-object");var i=[];for(var s in o)e.call(o,s)&&i.push(s);if(t)for(var a=0;a>>0;if(0===r)return-1;var n=0;if(arguments.length>1&&((n=Number(arguments[1]))!=n?n=0:0!==n&&n!==1/0&&n!==-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=r)return-1;for(var o=n>=0?n:Math.max(r-Math.abs(n),0);o0&&(t+=h.suffices["*"]&&r||",",h.suffices["*"]&&u&&(t+=h.name+"=")),t+=a?encodeURIComponent(l[f]).replace(/!/g,"%21"):s(l[f])}else if("object"==typeof l){u&&!h.suffices["*"]&&(t+=h.name+"=");var p=!0;for(var m in l)p||(t+=h.suffices["*"]&&r||","),p=!1,t+=a?encodeURIComponent(m).replace(/!/g,"%21"):s(m),t+=h.suffices["*"]?"=":",",t+=a?encodeURIComponent(l[m]).replace(/!/g,"%21"):s(l[m])}else u&&(t+=h.name,c&&""===l||(t+="=")),null!=h.truncate&&(l=l.substring(0,h.truncate)),t+=a?encodeURIComponent(l).replace(/!/g,"%21"):s(l)}return t};return b.varNames=h,{prefix:n,substitution:b}}function u(e){if(!(this instanceof u))return new u(e);for(var t=e.split("{"),r=[t.shift()],n=[],o=[],i=[];t.length>0;){var s=t.shift(),c=s.split("}")[0],h=s.substring(c.length+1),l=a(c);o.push(l.substitution),n.push(l.prefix),r.push(h),i=i.concat(l.substitution.varNames)}this.fill=function(e){for(var t=r[0],n=0;n0&&"/"===t.charAt(e.length-1)||"#"===r.charAt(0)||"?"===r.charAt(0))return!0}return!1}(t,e.id)&&void 0===this.schemas[e.id]&&(this.schemas[e.id]=e),e)if("enum"!==n)if("object"==typeof e[n])this.searchSchemas(e[n],t);else if("$ref"===n){var o=m(e[n]);o&&void 0===this.schemas[o]&&void 0===this.missingMap[o]&&(this.missingMap[o]=o)}},c.prototype.addSchema=function(e,t){if("string"!=typeof e||void 0===t){if("object"!=typeof e||"string"!=typeof e.id)return;e=(t=e).id}e===m(e)+"#"&&(e=m(e)),this.schemas[e]=t,delete this.missingMap[e],g(t,e),this.searchSchemas(t,e)},c.prototype.getSchemaMap=function(){var e={};for(var t in this.schemas)e[t]=this.schemas[t];return e},c.prototype.getSchemaUris=function(e){var t=[];for(var r in this.schemas)e&&!e.test(r)||t.push(r);return t},c.prototype.getMissingUris=function(e){var t=[];for(var r in this.missingMap)e&&!e.test(r)||t.push(r);return t},c.prototype.dropSchemas=function(){this.schemas={},this.reset()},c.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},c.prototype.validateAll=function(e,t,r,n,o){var i;if(!(t=this.resolveRefs(t)))return null;if(t instanceof P)return this.errors.push(t),t;var s,a=this.errors.length,u=null,c=null;if(this.checkRecursive&&e&&"object"==typeof e){if(i=!this.scanned.length,e[this.validatedSchemasKey]){var h=e[this.validatedSchemasKey].indexOf(t);if(-1!==h)return this.errors=this.errors.concat(e[this.validationErrorsKey][h]),null}if(Object.isFrozen(e)&&-1!==(s=this.scannedFrozen.indexOf(e))){var l=this.scannedFrozenSchemas[s].indexOf(t);if(-1!==l)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[s][l]),null}if(this.scanned.push(e),Object.isFrozen(e))-1===s&&(s=this.scannedFrozen.length,this.scannedFrozen.push(e),this.scannedFrozenSchemas.push([])),u=this.scannedFrozenSchemas[s].length,this.scannedFrozenSchemas[s][u]=t,this.scannedFrozenValidationErrors[s][u]=[];else{if(!e[this.validatedSchemasKey])try{Object.defineProperty(e,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(e,this.validationErrorsKey,{value:[],configurable:!0})}catch(t){e[this.validatedSchemasKey]=[],e[this.validationErrorsKey]=[]}c=e[this.validatedSchemasKey].length,e[this.validatedSchemasKey][c]=t,e[this.validationErrorsKey][c]=[]}}var d=this.errors.length,f=this.validateBasic(e,t,o)||this.validateNumeric(e,t,o)||this.validateString(e,t,o)||this.validateArray(e,t,o)||this.validateObject(e,t,o)||this.validateCombinations(e,t,o)||this.validateHypermedia(e,t,o)||this.validateFormat(e,t,o)||this.validateDefinedKeywords(e,t,o)||null;if(i){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(f||d!==this.errors.length)for(;r&&r.length||n&&n.length;){var p=r&&r.length?""+r.pop():null,m=n&&n.length?""+n.pop():null;f&&(f=f.prefixWith(p,m)),this.prefixErrors(d,p,m)}return null!==u?this.scannedFrozenValidationErrors[s][u]=this.errors.slice(a):null!==c&&(e[this.validationErrorsKey][c]=this.errors.slice(a)),this.handleError(f)},c.prototype.validateFormat=function(e,t){if("string"!=typeof t.format||!this.formatValidators[t.format])return null;var r=this.formatValidators[t.format].call(null,e,t);return"string"==typeof r||"number"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r},"","/format",null,e,t):r&&"object"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r.message||"?"},r.dataPath||"",r.schemaPath||"/format",null,e,t):null},c.prototype.validateDefinedKeywords=function(e,t,r){for(var n in this.definedKeywords)if(void 0!==t[n])for(var o=this.definedKeywords[n],i=0;i=l&&nt.maximum)return this.createError(v.NUMBER_MAXIMUM,{value:e,maximum:t.maximum},"","/maximum",null,e,t);if(t.exclusiveMaximum&&e===t.maximum)return this.createError(v.NUMBER_MAXIMUM_EXCLUSIVE,{value:e,maximum:t.maximum},"","/exclusiveMaximum",null,e,t)}return null},c.prototype.validateNaN=function(e,t){return"number"!=typeof e?null:!0===isNaN(e)||e===1/0||e===-1/0?this.createError(v.NUMBER_NOT_A_NUMBER,{value:e},"","/type",null,e,t):null},c.prototype.validateString=function(e,t,r){return this.validateStringLength(e,t,r)||this.validateStringPattern(e,t,r)||null},c.prototype.validateStringLength=function(e,t){return"string"!=typeof e?null:void 0!==t.minLength&&e.lengtht.maxLength?this.createError(v.STRING_LENGTH_LONG,{length:e.length,maximum:t.maxLength},"","/maxLength",null,e,t):null},c.prototype.validateStringPattern=function(e,t){if("string"!=typeof e||"string"!=typeof t.pattern&&!(t.pattern instanceof RegExp))return null;var r;if(t.pattern instanceof RegExp)r=t.pattern;else{var n,o="",i=t.pattern.match(/^\/(.+)\/([img]*)$/);i?(n=i[1],o=i[2]):n=t.pattern,r=new RegExp(n,o)}return r.test(e)?null:this.createError(v.STRING_PATTERN,{pattern:t.pattern},"","/pattern",null,e,t)},c.prototype.validateArray=function(e,t,r){return Array.isArray(e)&&(this.validateArrayLength(e,t,r)||this.validateArrayUniqueItems(e,t,r)||this.validateArrayItems(e,t,r))||null},c.prototype.validateArrayLength=function(e,t){var r;return void 0!==t.minItems&&e.lengtht.maxItems&&(r=this.createError(v.ARRAY_LENGTH_LONG,{length:e.length,maximum:t.maxItems},"","/maxItems",null,e,t),this.handleError(r))?r:null},c.prototype.validateArrayUniqueItems=function(e,t){if(t.uniqueItems)for(var r=0;rt.maxProperties&&(r=this.createError(v.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:n.length,maximum:t.maxProperties},"","/maxProperties",null,e,t),this.handleError(r))?r:null},c.prototype.validateObjectRequiredProperties=function(e,t){if(void 0!==t.required)for(var r=0;r 10000");if(void 0!==v[e])throw new Error("Error already defined: "+e+" as "+v[e]);if(void 0!==_[t])throw new Error("Error code already used: "+_[t]+" as "+t);for(var n in v[e]=t,_[t]=e,w[e]=w[t]=r,E){var o=E[n];o[e]&&(o[t]=o[t]||o[e])}},reset:function(){o.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:g,resolveUrl:p,getDocumentUri:m,errorCodes:v};return i.language(t||"en"),i}();return T.addLanguage("en-gb",w),T.tv4=T,T})?n.apply(t,o):n)||(e.exports=i)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClientTypes=void 0;class n{constructor(){this.uris={},this.schemas={},this.aliases={}}declare(e,t,r,n){const o=e+"/"+t;if(n.extends){const t=n.extends.split("/"),r=1===t.length?e+"/"+t.shift():t.join("/"),i=this.uris[r];if(!i)throw"Type '"+o+"' tries to extend unknown schema '"+r+"'";n.extends=this.schemas[i]}this.uris[o]=r,this.aliases[r]=o,this.schemas[r]=n}resolveAlias(e){return this.uris[e]}getSchema(e){return this.schemas[e]}inScope(e){const t=e.length,r={};for(const n in this.uris)if(n.substr(0,t+1)===e+"/"){const e=this.uris[n];r[e]=this.schemas[e]}return r}}t.BaseClientTypes=n;const o=new n;t.default=o},function(e,t,r){"use strict";class n extends Error{constructor(e){super();const t=new Error("Schema not found: "+e);return t.name="SchemaNotFound",t}}e.exports=n},function(e,t,r){"use strict";e.exports=class{constructor(e){this._itemsRev={},this._storage={},this._canPropagate=!1,this.defaultValue=e,this.activatePropagation()}get(e){e=e.toLowerCase();let t=this._storage[e];return void 0===t&&(t=this.defaultValue,this._storage[e]=t),t}set(e,t){return e=e.toLowerCase(),this._storage[e]===t||(this._storage[e]=t,t||delete this._itemsRev[e],this._updateParentFolderItemRev(e,t),this._canPropagate&&this._propagate(e)),t}delete(e){return this.set(e,null)}deactivatePropagation(){return this._canPropagate=!1,!0}activatePropagation(){return this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0),!0}_hashCode(e){let t=0;if(0===e.length)return t;for(let r=0;r0&&(r=this._generateHash(e))}return this.set(e,r),r}}},function(e,t,r){var n; -/*! - * webfinger.js - * version 2.7.0 - * http://github.com/silverbucket/webfinger.js - * - * Developed and Maintained by: - * Nick Jennings 2012 - * - * webfinger.js is released under the AGPL (see LICENSE). - * - * You don't have to do anything special to choose one license or the other and you don't - * have to notify anyone which license you are using. - * Please see the corresponding license file for details of these licenses. - * You are free to use, modify and distribute this software, but all copyright - * information must remain. - * - */"function"!=typeof fetch&&"function"!=typeof XMLHttpRequest&&(XMLHttpRequest=r(28)),function(r){var o={"http://webfist.org/spec/rel":"webfist","http://webfinger.net/rel/avatar":"avatar",remotestorage:"remotestorage","http://tools.ietf.org/id/draft-dejong-remotestorage":"remotestorage",remoteStorage:"remotestorage","http://www.packetizer.com/rel/share":"share","http://webfinger.net/rel/profile-page":"profile",me:"profile",vcard:"vcard",blog:"blog","http://packetizer.com/rel/blog":"blog","http://schemas.google.com/g/2010#updates-from":"updates","https://camlistore.org/rel/server":"camilstore"},i={avatar:[],remotestorage:[],blog:[],vcard:[],updates:[],share:[],profile:[],webfist:[],camlistore:[]},s=["webfinger","host-meta","host-meta.json"];function a(e){return e.toString=function(){return this.message},e}function u(e){"object"!=typeof e&&(e={}),this.config={tls_only:void 0===e.tls_only||e.tls_only,webfist_fallback:void 0!==e.webfist_fallback&&e.webfist_fallback,uri_fallback:void 0!==e.uri_fallback&&e.uri_fallback,request_timeout:void 0!==e.request_timeout?e.request_timeout:1e4}}u.prototype.__fetchJRD=function(e,t,r){if("function"==typeof fetch)return this.__fetchJRD_fetch(e,t,r);if("function"==typeof XMLHttpRequest)return this.__fetchJRD_XHR(e,t,r);throw new Error("add a polyfill for fetch or XMLHttpRequest")},u.prototype.__fetchJRD_fetch=function(e,t,r){var n,o=this;"function"==typeof AbortController&&(n=new AbortController);var i=fetch(e,{headers:{Accept:"application/jrd+json, application/json"},signal:n?n.signal:void 0}).then((function(t){if(t.ok)return t.text();throw 404===t.status?a({message:"resource not found",url:e,status:t.status}):a({message:"error during request",url:e,status:t.status})}),(function(t){throw a({message:"error during request",url:e,status:void 0,err:t})})).then((function(t){if(o.__isValidJSON(t))return t;throw a({message:"invalid json",url:e,status:void 0})})),s=new Promise((function(t,r){setTimeout((function(){r(a({message:"request timed out",url:e,status:void 0})),n&&n.abort()}),o.config.request_timeout)}));Promise.race([i,s]).then((function(e){r(e)})).catch((function(e){t(e)}))},u.prototype.__fetchJRD_XHR=function(e,t,r){var n=this,o=!1,i=new XMLHttpRequest;function s(){if(!o){if(o=!0,200===i.status)return n.__isValidJSON(i.responseText)?r(i.responseText):t(a({message:"invalid json",url:e,status:i.status}));if(404===i.status)return t(a({message:"resource not found",url:e,status:i.status}));if(i.status>=301&&i.status<=302){var s=i.getResponseHeader("Location");return function(e){return"string"==typeof e&&"https"===e.split("://")[0]}(s)?u():t(a({message:"no redirect URL found",url:e,status:i.status}))}return t(a({message:"error during request",url:e,status:i.status}))}}function u(){i.onreadystatechange=function(){4===i.readyState&&s()},i.onload=function(){s()},i.ontimeout=function(){return t(a({message:"request timed out",url:e,status:i.status}))},i.open("GET",e,!0),i.timeout=n.config.request_timeout,i.setRequestHeader("Accept","application/jrd+json, application/json"),i.send()}return u()},u.prototype.__isValidJSON=function(e){try{JSON.parse(e)}catch(e){return!1}return!0},u.prototype.__isLocalhost=function(e){return/^localhost(\.localdomain)?(\:[0-9]+)?$/.test(e)},u.prototype.__processJRD=function(e,t,r,n){var s=JSON.parse(t);if("object"!=typeof s||"object"!=typeof s.links)return void 0!==s.error?r(a({message:s.error,request:e})):r(a({message:"unknown response from server",request:e}));var u=s.links;Array.isArray(u)||(u=[]);var c={object:s,json:t,idx:{}};c.idx.properties={name:void 0},c.idx.links=JSON.parse(JSON.stringify(i)),u.map((function(e,t){if(o.hasOwnProperty(e.rel)&&c.idx.links[o[e.rel]]){var r={};Object.keys(e).map((function(t,n){r[t]=e[t]})),c.idx.links[o[e.rel]].push(r)}}));var h=JSON.parse(t).properties;for(var l in h)h.hasOwnProperty(l)&&"http://packetizer.com/ns/name"===l&&(c.idx.properties.name=h[l]);return n(c)},u.prototype.lookup=function(e,t){if("string"!=typeof e)throw new Error("first parameter must be a user address");if("function"!=typeof t)throw new Error("second parameter must be a callback");var r=this,n="";n=e.indexOf("://")>-1?e.replace(/ /g,"").split("/")[2]:e.replace(/ /g,"").split("@")[1];var o=0,i="https";function a(){var t="";return e.split("://")[1]||(t="acct:"),i+"://"+n+"/.well-known/"+s[o]+"?resource="+t+e}function u(e){if(r.config.uri_fallback&&"webfist.org"!==n&&o!==s.length-1)return o+=1,c();if(!r.config.tls_only&&"https"===i)return o=0,i="http",c();if(!r.config.webfist_fallback||"webfist.org"===n)return t(e);o=0,i="http",n="webfist.org";var u=a();r.__fetchJRD(u,t,(function(e){r.__processJRD(u,e,t,(function(e){"object"==typeof e.idx.links.webfist&&"string"==typeof e.idx.links.webfist[0].href&&r.__fetchJRD(e.idx.links.webfist[0].href,t,(function(e){r.__processJRD(u,e,t,(function(e){return t(null,t)}))}))}))}))}function c(){var e=a();r.__fetchJRD(e,u,(function(n){r.__processJRD(e,n,t,(function(e){t(null,e)}))}))}return r.__isLocalhost(n)&&(i="http"),setTimeout(c,0)},u.prototype.lookupLink=function(e,t,r){if(!i.hasOwnProperty(t))return r("unsupported rel "+t);this.lookup(e,(function(e,n){var o=n.idx.links[t];return e?r(e):0===o.length?r('no links found with rel="'+t+'"'):r(null,o[0])}))},void 0===(n=function(){return u}.apply(t,[]))||(e.exports=n)}()},function(e,t){e.exports=XMLHttpRequest},function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(3)),i=n(r(16)),s=n(r(1)),a=r(0),u=n(r(30)),c=n(r(11)),h=n(r(6)),l=n(r(15)),d=n(r(7)),f=n(r(13)),p=n(r(14)),m=n(r(8)),g=n(r(31)),y=n(r(12)),v=n(r(32)),_=n(r(33)),b=n(r(34)),w={features:[],featuresDone:0,readyFired:!1,loadFeatures(){this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:m.default,Dropbox:p.default,GoogleDrive:f.default,Access:c.default,Discover:l.default,Authorize:h.default,BaseClient:d.default,Env:i.default},o.default.cache&&a.extend(this.featureModules,{Caching:y.default,IndexedDB:v.default,LocalStorage:_.default,InMemoryStorage:b.default,Sync:g.default}),o.default.disableFeatures.forEach(e=>{this.featureModules[e]&&delete this.featureModules[e]}),this._allLoaded=!1;for(const e in this.featureModules)this.loadFeature(e)},hasFeature(e){for(let t=this.features.length-1;t>=0;t--)if(this.features[t].name===e)return this.features[t].supported;return!1},loadFeature(e){const t=this.featureModules[e],r=!t._rs_supported||t._rs_supported();s.default(`[RemoteStorage] [FEATURE ${e}] initializing ...`),"object"==typeof r?r.then(()=>{this.featureSupported(e,!0),this.initFeature(e)},()=>{this.featureSupported(e,!1)}):"boolean"==typeof r?(this.featureSupported(e,r),r&&this.initFeature(e)):this.featureSupported(e,!1)},initFeature(e){const t=this.featureModules[e];let r;try{r=t._rs_init(this)}catch(t){return void this.featureFailed(e,t)}"object"==typeof r&&"function"==typeof r.then?r.then(()=>{this.featureInitialized(e)},t=>{this.featureFailed(e,t)}):this.featureInitialized(e)},featureFailed(e,t){s.default(`[RemoteStorage] [FEATURE ${e}] initialization failed (${t})`),this.featureDone()},featureSupported(e,t){s.default(`[RemoteStorage] [FEATURE ${e}]${t?"":"not "} supported`),t||this.featureDone()},featureInitialized(e){s.default(`[RemoteStorage] [FEATURE ${e}] initialized`),this.features.push({name:e,init:this.featureModules[e]._rs_init,supported:!0,cleanup:this.featureModules[e]._rs_cleanup}),this.featureDone()},featureDone(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule(){["IndexedDB","LocalStorage","InMemoryStorage"].some(e=>{if(this.features.some(t=>t.name===e))return this.features.local=this.featureModules[e],!0})},_fireReady(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(e){console.error("'ready' failed: ",e,e.stack),this._emit("error",e)}},featuresLoaded(){s.default("[RemoteStorage] All features loaded"),this._setCachingModule(),this.local=o.default.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(u.default,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",()=>{this._fireReady(),this._emit("connected")}),this.remote.on("not-connected",()=>{this._fireReady(),this._emit("not-connected")}),this.remote.connected&&(this._fireReady(),this._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(e){a.logError(e),this._emit("error",e)}this._processPending()},_collectCleanupFunctions(){this._cleanups=[];for(let e=0;e(this._emit("wire-done",{success:!0}),Promise.resolve(e)),e=>(this._emit("wire-done",{success:!1}),Promise.reject(e)))}))}};e.exports=s},function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{u(n.next(e))}catch(e){i(e)}}function a(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}u((n=n.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=o(r(3)),s=o(r(16)),a=o(r(2)),u=o(r(1)),c=o(r(6)),h=o(r(9)),l=o(r(4)),d=r(0);let f,p;function m(e,t,r){return{action:e,path:t,promise:r}}function g(e,t){return e.common.revision!==t&&(!e.remote||e.remote.revision!==t)}function y(e){return e.common&&e.common.revision}class v{constructor(e){this.rs=e,this._tasks={},this._running={},this._timeStarted={},this.numThreads=10,this.rs.local.onDiff(e=>{this.addTask(e),this.doTasks()}),this.rs.caching.onActivate(e=>{this.addTask(e),this.doTasks()}),this.addEvents(["done","req-done"])}now(){return(new Date).getTime()}queueGetRequest(e){return new Promise((t,r)=>{this.rs.remote.connected?this.rs.remote.online?(this.addTask(e,function(){this.rs.local.get(e).then(e=>t(e))}.bind(this)),this.doTasks()):r("cannot fulfill maxAge requirement - remote is not online"):r("cannot fulfill maxAge requirement - remote is not connected")})}corruptServerItemsMap(e,t){if("object"!=typeof e||Array.isArray(e))return!0;for(const r in e){const n=e[r];if("object"!=typeof n)return!0;if("string"!=typeof n.ETag)return!0;if(d.isFolder(r)){if(-1!==r.substring(0,r.length-1).indexOf("/"))return!0}else{if(-1!==r.indexOf("/"))return!0;if(t){if("string"!=typeof n["Content-Type"])return!0;if("number"!=typeof n["Content-Length"])return!0}}}return!1}corruptItemsMap(e){if("object"!=typeof e||Array.isArray(e))return!0;for(const t in e)if("boolean"!=typeof e[t])return!0;return!1}corruptRevision(e){return"object"!=typeof e||Array.isArray(e)||e.revision&&"string"!=typeof e.revision||e.body&&"string"!=typeof e.body&&"object"!=typeof e.body||e.contentType&&"string"!=typeof e.contentType||e.contentLength&&"number"!=typeof e.contentLength||e.timestamp&&"number"!=typeof e.timestamp||e.itemsMap&&this.corruptItemsMap(e.itemsMap)}isCorrupt(e){return"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.path||this.corruptRevision(e.common)||e.local&&this.corruptRevision(e.local)||e.remote&&this.corruptRevision(e.remote)||e.push&&this.corruptRevision(e.push)}hasTasks(){return Object.getOwnPropertyNames(this._tasks).length>0}collectDiffTasks(){return n(this,void 0,void 0,(function*(){let e=0;return this.rs.local.forAllNodes(t=>{e>100||(this.isCorrupt(t)?(u.default("[Sync] WARNING: corrupt node in local cache",t),"object"==typeof t&&t.path&&(this.addTask(t.path),e++)):(this.needsFetch(t)&&this.rs.access.checkPathPermission(t.path,"r")||d.isDocument(t.path)&&this.needsPush(t)&&this.rs.access.checkPathPermission(t.path,"rw"))&&(this.addTask(t.path),e++))}).then(()=>e).catch(e=>{throw e})}))}inConflict(e){return e.local&&e.remote&&(void 0!==e.remote.body||e.remote.itemsMap)}needsRefresh(e){return!!e.common&&(!e.common.timestamp||this.now()-e.common.timestamp>i.default.syncInterval)}needsFetch(e){return!!this.inConflict(e)||(!(!e.common||void 0!==e.common.itemsMap||void 0!==e.common.body)||!(!e.remote||void 0!==e.remote.itemsMap||void 0!==e.remote.body))}needsPush(e){return!this.inConflict(e)&&(!(!e.local||e.push)||void 0)}needsRemotePut(e){return e.local&&e.local.body}needsRemoteDelete(e){return e.local&&!1===e.local.body}getParentPath(e){const t=e.match(/^(.*\/)([^\/]+\/?)$/);if(t)return t[1];throw new Error('Not a valid path: "'+e+'"')}deleteChildPathsFromTasks(){for(const e in this._tasks){const t=d.pathsFromRoot(e);for(let r=1;r{let t;if(this.needsRefresh(e)){try{t=this.getParentPath(e.path)}catch(e){}t&&this.rs.access.checkPathPermission(t,"r")?this.addTask(t):this.rs.access.checkPathPermission(e.path,"r")&&this.addTask(e.path)}}).then(()=>this.deleteChildPathsFromTasks()).catch(e=>{throw e})}))}flush(e){for(const t in e)"FLUSH"===this.rs.caching.checkPath(t)&&e[t]&&!e[t].local&&(u.default("[Sync] Flushing",t),e[t]=void 0);return e}doTask(e){return this.rs.local.getNodes([e]).then(t=>{const r=t[e];return void 0===r||function(e){return e.remote&&e.remote.revision&&!e.remote.itemsMap&&!e.remote.body}(r)?m("get",e,this.rs.remote.get(e)):this.needsRemotePut(r)?(r.push=d.deepClone(r.local),r.push.timestamp=this.now(),this.rs.local.setNodes(this.flush(t)).then(()=>{let t;return t=y(r)?{ifMatch:r.common.revision}:{ifNoneMatch:"*"},m("put",e,this.rs.remote.put(e,r.push.body,r.push.contentType,t))})):this.needsRemoteDelete(r)?(r.push={body:!1,timestamp:this.now()},this.rs.local.setNodes(this.flush(t)).then(()=>y(r)?m("delete",e,this.rs.remote.delete(e,{ifMatch:r.common.revision})):m("get",e,this.rs.remote.get(e)))):y(r)?m("get",e,this.rs.remote.get(e,{ifNoneMatch:r.common.revision})):m("get",e,this.rs.remote.get(e))})}autoMergeFolder(e){if(e.remote.itemsMap&&(e.common=e.remote,delete e.remote,e.common.itemsMap)){for(const t in e.common.itemsMap)e.local.itemsMap[t]||(e.local.itemsMap[t]=!1);d.equal(e.local.itemsMap,e.common.itemsMap)&&delete e.local}return e}autoMergeDocument(e){return!function(e){return(!e.remote||!e.remote.revision||e.remote.revision===e.common.revision)&&(void 0===e.common.body&&!1===e.remote.body||e.remote.body===e.common.body&&e.remote.contentType===e.common.contentType)}(e)?void 0!==e.remote.body&&(u.default("[Sync] Emitting keep/revert"),this.rs.local._emitChange({origin:"conflict",path:e.path,oldValue:e.local.body,newValue:e.remote.body,lastCommonValue:e.common.body,oldContentType:e.local.contentType,newContentType:e.remote.contentType,lastCommonContentType:e.common.contentType}),e.remote.body?e.common=e.remote:e.common={},delete e.remote,delete e.local):delete(e=function(e){return e.remote&&!1===e.remote.body&&e.local&&!1===e.local.body&&delete e.local,e}(e)).remote,e}autoMerge(e){if(e.remote){if(e.local)return d.isFolder(e.path)?this.autoMergeFolder(e):this.autoMergeDocument(e);if(d.isFolder(e.path))void 0!==e.remote.itemsMap&&(e.common=e.remote,delete e.remote);else if(void 0!==e.remote.body){const t={origin:"remote",path:e.path,oldValue:!1===e.common.body?void 0:e.common.body,newValue:!1===e.remote.body?void 0:e.remote.body,oldContentType:e.common.contentType,newContentType:e.remote.contentType};if((t.oldValue||t.newValue)&&this.rs.local._emitChange(t),!e.remote.body)return;e.common=e.remote,delete e.remote}return e}e.common.body&&this.rs.local._emitChange({origin:"remote",path:e.path,oldValue:e.common.body,newValue:void 0,oldContentType:e.common.contentType,newContentType:void 0})}updateCommonTimestamp(e,t){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then(r=>(r[e]&&r[e].common&&r[e].common.revision===t&&(r[e].common.timestamp=this.now()),this.rs.local.setNodes(this.flush(r))))}))}markChildren(e,t,r,o){return n(this,void 0,void 0,(function*(){const n=[],i={},s={};for(const r in t)n.push(e+r),i[e+r]=t[r];for(const t in o)n.push(e+t);return this.rs.local.getNodes(n).then(t=>{let n,a;for(const u in t)if(a=t[u],i[u])a&&a.common?g(a,i[u].ETag)&&(r[u]=d.deepClone(a),r[u].remote={revision:i[u].ETag,timestamp:this.now()},r[u]=this.autoMerge(r[u])):(n=this.rs.caching.checkPath(u),"ALL"===n&&(r[u]={path:u,common:{timestamp:this.now()},remote:{revision:i[u].ETag,timestamp:this.now()}})),r[u]&&i[u]["Content-Type"]&&(r[u].remote.contentType=i[u]["Content-Type"]),r[u]&&i[u]["Content-Length"]&&(r[u].remote.contentLength=i[u]["Content-Length"]);else if(o[u.substring(e.length)]&&a&&a.common){if(a.common.itemsMap)for(const e in a.common.itemsMap)s[u+e]=!0;if(a.local&&a.local.itemsMap)for(const e in a.local.itemsMap)s[u+e]=!0;if(a.remote||d.isFolder(u))r[u]=void 0;else if(r[u]=this.autoMerge(a),void 0===r[u]){const t=this.getParentPath(u),n=r[t],o=u.substring(e.length);n&&n.local&&(delete n.local.itemsMap[o],d.equal(n.local.itemsMap,n.common.itemsMap)&&delete n.local)}}return this.deleteRemoteTrees(Object.keys(s),r).then(e=>this.rs.local.setNodes(this.flush(e)))})}))}deleteRemoteTrees(e,t){return n(this,void 0,void 0,(function*(){return 0===e.length?Promise.resolve(t):this.rs.local.getNodes(e).then(e=>n(this,void 0,void 0,(function*(){const r={};function n(e,t){if(e&&e.itemsMap)for(const n in e.itemsMap)r[t+n]=!0}for(const r in e){const o=e[r];o&&(d.isFolder(r)?(n(o.common,r),n(o.local,r)):o.common&&void 0!==typeof o.common.body&&(t[r]=d.deepClone(o),t[r].remote={body:!1,timestamp:this.now()},t[r]=this.autoMerge(t[r])))}return this.deleteRemoteTrees(Object.keys(r),t).then(e=>this.rs.local.setNodes(this.flush(e)))})))}))}completeFetch(e,t,r,o){return n(this,void 0,void 0,(function*(){let n,i;const s=d.pathsFromRoot(e);return d.isFolder(e)?n=[e]:(i=s[1],n=[e,i]),this.rs.local.getNodes(n).then(n=>{let s,a,u=n[e];const c={};function h(e){if(e&&e.itemsMap)for(s in e.itemsMap)t[s]||(c[s]=!0)}if("object"==typeof u&&u.path===e&&"object"==typeof u.common||(u={path:e,common:{}},n[e]=u),u.remote={revision:o,timestamp:this.now()},d.isFolder(e))for(s in h(u.common),h(u.remote),u.remote.itemsMap={},t)u.remote.itemsMap[s]=!0;else u.remote.body=t,u.remote.contentType=r,a=n[i],a&&a.local&&a.local.itemsMap&&(s=e.substring(i.length),a.local.itemsMap[s]=!0,d.equal(a.local.itemsMap,a.common.itemsMap)&&delete a.local);return n[e]=this.autoMerge(u),{toBeSaved:n,missingChildren:c}})}))}completePush(e,t,r,o){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then(n=>{const i=n[e];if(!i.push)throw this.stopped=!0,new Error("completePush called but no push version!");return r?(u.default("[Sync] We have a conflict"),i.remote&&i.remote.revision===o||(i.remote={revision:o||"conflict",timestamp:this.now()},delete i.push),n[e]=this.autoMerge(i)):(i.common={revision:o,timestamp:this.now()},"put"===t?(i.common.body=i.push.body,i.common.contentType=i.push.contentType,d.equal(i.local.body,i.push.body)&&i.local.contentType===i.push.contentType&&delete i.local,delete i.push):"delete"===t&&(!1===i.local.body?n[e]=void 0:delete i.push)),this.rs.local.setNodes(this.flush(n))})}))}dealWithFailure(e){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then(t=>{if(t[e])return delete t[e].push,this.rs.local.setNodes(this.flush(t))})}))}interpretStatus(e){const t={statusCode:e,successful:void 0,conflict:void 0,unAuth:void 0,notFound:void 0,changed:void 0,networkProblems:void 0};if("string"==typeof e&&("offline"===e||"timeout"===e))return t.successful=!1,t.networkProblems=!0,t;if("number"==typeof e){const r=Math.floor(e/100);return t.successful=2===r||304===e||412===e||404===e,t.conflict=412===e,t.unAuth=401===e&&this.rs.remote.token!==c.default.IMPLIED_FAKE_TOKEN||402===e||403===e,t.notFound=404===e,t.changed=304!==e,t}}handleGetResponse(e,t,r,o,i){return n(this,void 0,void 0,(function*(){return t.notFound&&(r=!!d.isFolder(e)&&{}),t.changed?this.completeFetch(e,r,o,i).then(t=>d.isFolder(e)?this.corruptServerItemsMap(r)?(u.default("[Sync] WARNING: Discarding corrupt folder description from server for "+e),!1):this.markChildren(e,r,t.toBeSaved,t.missingChildren).then(()=>!0):this.rs.local.setNodes(this.flush(t.toBeSaved)).then(()=>!0)):this.updateCommonTimestamp(e,i).then(()=>!0)}))}handleResponse(e,t,r){const n=this.interpretStatus(r.statusCode);if(n.successful){if("get"===t)return this.handleGetResponse(e,n,r.body,r.contentType,r.revision);if("put"===t||"delete"===t)return this.completePush(e,t,n.conflict,r.revision).then((function(){return!0}));throw new Error("cannot handle response for unknown action "+t)}{let t;return t=n.unAuth?new l.default:n.networkProblems?new h.default("Network request failed."):new Error("HTTP response code "+n.statusCode+" received."),this.dealWithFailure(e).then(()=>{throw this.rs._emit("error",t),t})}}finishTask(e){if(void 0!==e.action)return e.promise.then(t=>this.handleResponse(e.path,e.action,t),t=>(u.default("[Sync] wireclient rejects its promise!",e.path,e.action,t),this.handleResponse(e.path,e.action,{statusCode:"offline"}))).then(t=>{if(delete this._timeStarted[e.path],delete this._running[e.path],t&&this._tasks[e.path]){for(let t=0;t{!this.hasTasks()||this.stopped?(u.default("[Sync] Sync is done! Reschedule?",Object.getOwnPropertyNames(this._tasks).length,this.stopped),this.done||(this.done=!0,this.rs._emit("sync-done"))):setTimeout(()=>{this.doTasks()},10)})},t=>{u.default("[Sync] Error",t),delete this._timeStarted[e.path],delete this._running[e.path],this.rs._emit("sync-req-done"),this.done||(this.done=!0,this.rs._emit("sync-done"))});delete this._running[e.path]}doTasks(){let e,t,r=0;e=this.rs.remote.connected?this.rs.remote.online?this.numThreads:1:0;const n=e-Object.getOwnPropertyNames(this._running).length;if(n<=0)return!0;for(t in this._tasks)if(!this._running[t]&&(this._timeStarted[t]=this.now(),this._running[t]=this.doTask(t),this._running[t].then(this.finishTask.bind(this)),r++,r>=n))return!0;return r>=n}collectTasks(e){return n(this,void 0,void 0,(function*(){return this.hasTasks()||this.stopped?Promise.resolve():this.collectDiffTasks().then(t=>t||!1===e?Promise.resolve():this.collectRefreshTasks(),(function(e){throw e}))}))}addTask(e,t){this._tasks[e]||(this._tasks[e]=[]),"function"==typeof t&&this._tasks[e].push(t)}sync(){return this.done=!1,this.doTasks()?Promise.resolve():this.collectTasks().then(()=>{try{this.doTasks()}catch(e){u.default("[Sync] doTasks error",e)}},(function(e){throw u.default("[Sync] Sync error",e),new Error("Local cache unavailable")}))}static _rs_init(e){f=function(){u.default("[Sync] syncCycleCb calling syncCycle");const t=new s.default;t.isBrowser()&&function(e,t){function r(e){const r=t.getCurrentSyncInterval();i.default.isBackground=!e;const n=t.getCurrentSyncInterval();t._emit("sync-interval-change",{oldValue:r,newValue:n})}e.on("background",()=>r(!1)),e.on("foreground",()=>r(!0))}(t,e),e.sync||(e.sync=new v(e),e.syncStopped&&(u.default("[Sync] Instantiating sync stopped"),e.sync.stopped=!0,delete e.syncStopped)),u.default("[Sync] syncCycleCb calling syncCycle"),e.syncCycle()},p=function(){e.removeEventListener("connected",p),e.startSync()},e.on("ready",f),e.on("connected",p)}static _rs_cleanup(e){e.stopSync(),e.removeEventListener("ready",f),e.removeEventListener("connected",p),e.sync=void 0,delete e.sync}}d.applyMixins(v,[a.default]),e.exports=v},function(e,t,r){"use strict";(function(t){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{u(n.next(e))}catch(e){i(e)}}function a(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}u((n=n.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=o(r(2)),s=o(r(10)),a=o(r(1)),u=r(0);let c;class h extends s.default{constructor(e){super(),this.addEvents(["change","local-events-done"]),this.db=e||c,this.db?(this.getsRunning=0,this.putsRunning=0,this.changesQueued={},this.changesRunning={},this.commitSlownessWarning=null):a.default("[IndexedDB] Failed to open DB")}getNodes(e){return n(this,void 0,void 0,(function*(){const t=[],r={};for(let n=0,o=e.length;n0?this.getNodesFromDb(t).then((function(e){for(const t in r)e[t]=r[t];return e})):Promise.resolve(r)}))}setNodes(e){return n(this,void 0,void 0,(function*(){for(const t in e)this.changesQueued[t]=e[t]||!1;return this.maybeFlush(),Promise.resolve()}))}maybeFlush(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=t.setInterval((function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")}),1e4))}flushChangesQueued(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))}getNodesFromDb(e){return new Promise((t,r)=>{const n=this.db.transaction(["nodes"],"readonly"),o=n.objectStore("nodes"),i={};this.getsRunning++,e.map(e=>{o.get(e).onsuccess=t=>{i[e]=t.target.result}}),n.oncomplete=()=>{t(i),this.getsRunning--},n.onerror=n.onabort=()=>{r("get transaction error/abort"),this.getsRunning--}})}setNodesInDb(e){return n(this,void 0,void 0,(function*(){return new Promise((t,r)=>{const n=this.db.transaction(["nodes"],"readwrite"),o=n.objectStore("nodes"),i=(new Date).getTime();this.putsRunning++,a.default("[IndexedDB] Starting put",e,this.putsRunning);for(const t in e){const r=e[t];if("object"==typeof r)try{o.put(r)}catch(e){throw a.default("[IndexedDB] Error while putting",r,e),e}else try{o.delete(t)}catch(e){throw a.default("[IndexedDB] Error while removing",o,r,e),e}}n.oncomplete=()=>{this.putsRunning--,a.default("[IndexedDB] Finished put",e,this.putsRunning,(new Date).getTime()-i+"ms"),t()},n.onerror=()=>{this.putsRunning--,r("transaction error")},n.onabort=()=>{r("transaction abort"),this.putsRunning--}})}))}reset(e){const t=this.db.name;this.db.close(),h.clean(this.db.name,()=>{h.open(t,(t,r)=>{t?a.default("[IndexedDB] Error while resetting local storage",t):this.db=r,"function"==typeof e&&e(self)})})}forAllNodes(e){return n(this,void 0,void 0,(function*(){return new Promise(t=>{this.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=r=>{const n=r.target.result;n?(e(this.migrate(n.value)),n.continue()):t()}})}))}closeDB(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}static open(e,t){const r=setTimeout((function(){t("timeout trying to open db")}),1e4);try{const n=indexedDB.open(e,2);n.onerror=function(){a.default("[IndexedDB] Opening DB failed",n),clearTimeout(r),t(n.error)},n.onupgradeneeded=function(e){const t=n.result;a.default("[IndexedDB] Upgrade: from ",e.oldVersion," to ",e.newVersion),1!==e.oldVersion&&(a.default("[IndexedDB] Creating object store: nodes"),t.createObjectStore("nodes",{keyPath:"path"})),a.default("[IndexedDB] Creating object store: changes"),t.createObjectStore("changes",{keyPath:"path"})},n.onsuccess=function(){clearTimeout(r);const o=n.result;if(!o.objectStoreNames.contains("nodes")||!o.objectStoreNames.contains("changes"))return a.default("[IndexedDB] Missing object store. Resetting the database."),void h.clean(e,(function(){h.open(e,t)}));t(null,n.result)}}catch(n){a.default("[IndexedDB] Failed to open database: "+n),a.default("[IndexedDB] Resetting database and trying again."),clearTimeout(r),h.clean(e,(function(){h.open(e,t)}))}}static clean(e,t){const r=indexedDB.deleteDatabase(e);r.onsuccess=function(){a.default("[IndexedDB] Done removing DB"),t()},r.onerror=r.onabort=function(t){console.error('Failed to remove database "'+e+'"',t)}}static _rs_init(e){return new Promise((t,r)=>{h.open("remotestorage",(function(n,o){n?r(n):(c=o,o.onerror=()=>{e._emit("error",n)},t())}))})}static _rs_supported(){return new Promise((e,t)=>{const r=u.getGlobalContext();let n=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(n=!0)),"indexedDB"in r&&!n)try{const r=indexedDB.open("rs-check");r.onerror=function(){t()},r.onsuccess=function(){r.result.close(),indexedDB.deleteDatabase("rs-check"),e()}}catch(e){t()}else t()})}static _rs_cleanup(e){return new Promise(t=>{e.local&&e.local.closeDB(),h.clean("remotestorage",t)})}diffHandler(){}}u.applyMixins(h,[i.default]),e.exports=h}).call(this,r(5))},function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(10)),i=n(r(2)),s=n(r(1)),a=r(0),u="remotestorage:cache:nodes:";function c(e){return e.substr(0,u.length)===u||"remotestorage:cache:changes:"===e.substr(0,"remotestorage:cache:changes:".length)}class h extends o.default{constructor(){super(),this.addEvents(["change","local-events-done"])}diffHandler(...e){}getNodes(e){const t={};for(let r=0,n=e.length;r{s.default("[LocalStorage] Removing",e),delete localStorage[e]})}}a.applyMixins(h,[i.default]),e.exports=h},function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(2)),i=n(r(10)),s=r(0);class a extends i.default{constructor(){super(),this._storage={},this.addEvents(["change","local-events-done"])}getNodes(e){const t={};for(let r=0,n=e.length;r=G&&(this.string+=this.stringBuffer.toString("utf8"),this.stringBufferOffset=0),this.stringBuffer[this.stringBufferOffset++]=e},Y.appendStringBuf=function(e,t,r){var n=e.length;"number"==typeof t&&(n="number"==typeof r?r<0?e.length-t+r:r-t:e.length-t),n<0&&(n=0),this.stringBufferOffset+n>G&&(this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0),e.copy(this.stringBuffer,this.stringBufferOffset,t,r),this.stringBufferOffset+=n},Y.write=function(e){var t;"string"==typeof e&&(e=new n(e));for(var r=0,i=e.length;r=48&&t<64)this.string=String.fromCharCode(t),this.tState=P;else if(32!==t&&9!==t&&10!==t&&13!==t)return this.charError(e,r)}else if(this.tState===C)if(t=e[r],this.bytes_remaining>0){for(var g=0;g=128){if(t<=193||t>244)return this.onError(new Error("Invalid UTF-8 character at position "+r+" in state "+z.toknam(this.tState)));if(t>=194&&t<=223&&(this.bytes_in_sequence=2),t>=224&&t<=239&&(this.bytes_in_sequence=3),t>=240&&t<=244&&(this.bytes_in_sequence=4),this.bytes_in_sequence+r>e.length){for(var m=0;m<=e.length-1-r;m++)this.temp_buffs[this.bytes_in_sequence][m]=e[r+m];this.bytes_remaining=r+this.bytes_in_sequence-e.length,r=e.length-1}else this.appendStringBuf(e,r,r+this.bytes_in_sequence),r=r+this.bytes_in_sequence-1}else if(34===t)this.tState=y,this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0,this.onToken(p,this.string),this.offset+=n.byteLength(this.string,"utf8")+1,this.string=void 0;else if(92===t)this.tState=k;else{if(!(t>=32))return this.charError(e,r);this.appendStringChar(t)}else if(this.tState===k)if(34===(t=e[r]))this.appendStringChar(t),this.tState=C;else if(92===t)this.appendStringChar(B),this.tState=C;else if(47===t)this.appendStringChar(H),this.tState=C;else if(98===t)this.appendStringChar(W),this.tState=C;else if(102===t)this.appendStringChar($),this.tState=C;else if(110===t)this.appendStringChar(V),this.tState=C;else if(114===t)this.appendStringChar(K),this.tState=C;else if(116===t)this.appendStringChar(J),this.tState=C;else{if(117!==t)return this.charError(e,r);this.unicode="",this.tState=O}else if(this.tState===O||this.tState===F||this.tState===N||this.tState===D){if(!((t=e[r])>=48&&t<64||t>64&&t<=70||t>96&&t<=102))return this.charError(e,r);if(this.unicode+=String.fromCharCode(t),this.tState++===D){var L=parseInt(this.unicode,16);this.unicode=void 0,void 0!==this.highSurrogate&&L>=56320&&L<57344?(this.appendStringBuf(new n(String.fromCharCode(this.highSurrogate,L))),this.highSurrogate=void 0):void 0===this.highSurrogate&&L>=55296&&L<56320?this.highSurrogate=L:(void 0!==this.highSurrogate&&(this.appendStringBuf(new n(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.appendStringBuf(new n(String.fromCharCode(L)))),this.tState=C}}else if(this.tState===x||this.tState===P)switch(t=e[r]){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 46:case 101:case 69:case 43:case 45:this.string+=String.fromCharCode(t),this.tState=P;break;default:this.tState=y;var U=this.numberReviver(this.string,e,r);if(U)return U;this.offset+=this.string.length-1,this.string=void 0,r--}else if(this.tState===v){if(114!==e[r])return this.charError(e,r);this.tState=b}else if(this.tState===b){if(117!==e[r])return this.charError(e,r);this.tState=w}else if(this.tState===w){if(101!==e[r])return this.charError(e,r);this.tState=y,this.onToken(d,!0),this.offset+=3}else if(this.tState===_){if(97!==e[r])return this.charError(e,r);this.tState=S}else if(this.tState===S){if(108!==e[r])return this.charError(e,r);this.tState=E}else if(this.tState===E){if(115!==e[r])return this.charError(e,r);this.tState=A}else if(this.tState===A){if(101!==e[r])return this.charError(e,r);this.tState=y,this.onToken(h,!1),this.offset+=4}else if(this.tState===R){if(117!==e[r])return this.charError(e,r);this.tState=I}else if(this.tState===I){if(108!==e[r])return this.charError(e,r);this.tState=T}else if(this.tState===T){if(108!==e[r])return this.charError(e,r);this.tState=y,this.onToken(f,null),this.offset+=3}},Y.onToken=function(e,t){},Y.parseError=function(e,t){this.tState=m,this.onError(new Error("Unexpected "+z.toknam(e)+(t?"("+JSON.stringify(t)+")":"")+" in state "+z.toknam(this.state)))},Y.push=function(){this.stack.push({value:this.value,key:this.key,mode:this.mode})},Y.pop=function(){var e=this.value,t=this.stack.pop();this.value=t.value,this.key=t.key,this.mode=t.mode,this.emit(e),this.mode||(this.state=L)},Y.emit=function(e){this.mode&&(this.state=u),this.onValue(e)},Y.onValue=function(e){},Y.onToken=function(e,t){if(this.state===L)if(e===p||e===g||e===d||e===h||e===f)this.value&&(this.value[this.key]=t),this.emit(t);else if(e===o)this.push(),this.value?this.value=this.value[this.key]={}:this.value={},this.key=void 0,this.state=U,this.mode=j;else if(e===a)this.push(),this.value?this.value=this.value[this.key]=[]:this.value=[],this.key=0,this.mode=M,this.state=L;else if(e===s){if(this.mode!==j)return this.parseError(e,t);this.pop()}else{if(e!==c)return this.parseError(e,t);if(this.mode!==M)return this.parseError(e,t);this.pop()}else if(this.state===U)if(e===p)this.key=t,this.state=l;else{if(e!==s)return this.parseError(e,t);this.pop()}else if(this.state===l){if(e!==l)return this.parseError(e,t);this.state=L}else{if(this.state!==u)return this.parseError(e,t);if(e===u)this.mode===M?(this.key++,this.state=L):this.mode===j&&(this.state=U);else{if(!(e===c&&this.mode===M||e===s&&this.mode===j))return this.parseError(e,t);this.pop()}}},Y.numberReviver=function(e,t,r){var n=Number(e);if(isNaN(n))return this.charError(t,r);e.match(/[0-9]+/)==e&&n.toString()!=e?this.onToken(p,e):this.onToken(g,n)},z.C=i,e.exports=z},2741:function(e,t,r){"use strict";r.r(t),r.d(t,{CordovaIFrameNavigator:function(){return n.CordovaIFrameNavigator},CordovaPopupNavigator:function(){return n.CordovaPopupNavigator},InMemoryWebStorage:function(){return n.InMemoryWebStorage},Log:function(){return n.Log},OidcClient:function(){return n.OidcClient},SessionMonitor:function(){return n.SessionMonitor},User:function(){return n.User},UserManager:function(){return n.UserManager},Version:function(){return n.Version},WebStorageStateStore:function(){return n.WebStorageStateStore},clearOidcPersistentStorage:function(){return N},getBearerToken:function(){return P},getDpopToken:function(){return C},normalizeCallbackUrl:function(){return F},refresh:function(){return O},registerClient:function(){return I}});var n=r(6516);r(7007),globalThis.fetch;const{fetch:i,Response:o,Request:s,Headers:a}=globalThis;var c=r(9380),l=r(8136),u=r(7248),d=r(7307),h=r(5130),f={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let p;const g=new Uint8Array(16);function y(){if(!p&&(p="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!p))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return p(g)}const m=[];for(let e=0;e<256;++e)m.push((e+256).toString(16).slice(1));var v=function(e,t,r){if(f.randomUUID&&!t&&!e)return f.randomUUID();const n=(e=e||{}).random||(e.rng||y)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return m[e[t+0]]+m[e[t+1]]+m[e[t+2]]+m[e[t+3]]+"-"+m[e[t+4]]+m[e[t+5]]+"-"+m[e[t+6]]+m[e[t+7]]+"-"+m[e[t+8]]+m[e[t+9]]+"-"+m[e[t+10]]+m[e[t+11]]+m[e[t+12]]+m[e[t+13]]+m[e[t+14]]+m[e[t+15]]}(n)};const b=["ES256","RS256"],w=["openid","offline_access","webid"].join(" ");async function _(e,t,r,n){const o=await async function(e,t){const r=await i.call(globalThis,e);if(200!==r.status)throw new Error(`Could not fetch JWKS for [${t}] at [${e}]: ${r.status} ${r.statusText}`);let n;try{n=(await r.json()).keys[0]}catch(r){throw new Error(`Malformed JWKS for [${t}] at [${e}]: ${r.message}`)}return n}(t,r);let s;try{const{payload:t}=await(0,c.V)(e,await(0,l.Og)(o),{issuer:r,audience:n});s=t}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof s.webid)return s.webid;if("string"!=typeof s.sub)throw new Error(`The token ${JSON.stringify(s)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(s.sub),s.sub}catch(e){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${s.sub}] is invalid as a URL - error [${e}].`)}}Error,Error;class S extends Error{constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class E extends Error{constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function A(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function R(e,t,r){return new u.P({htu:A(e),htm:t.toUpperCase(),jti:v()}).setProtectedHeader({alg:b[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function I(e,t){var r;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 n=function(e,t){var r;return null!==(r=t.find((t=>e.includes(t))))&&void 0!==r?r:null}(t.idTokenSigningAlgValuesSupported,b),i={client_name:e.clientName,application_type:"web",redirect_uris:[null===(r=e.redirectUrl)||void 0===r?void 0:r.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:n,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 function(e,t){if(void 0===e.client_id)throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(e)}`);if(t.redirectUrl&&(void 0===e.redirect_uris||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()])}`)}(t,e),{clientId:t.client_id,clientSecret:t.client_secret,idTokenSignedResponseAlg:t.id_token_signed_response_alg,clientType:"dynamic"}}throw 400===o.status&&function(e,t){var r,n,i,o;if("invalid_redirect_uri"===e.error)throw new Error(`Dynamic client registration failed: the provided redirect uri [${null===(r=t.redirectUrl)||void 0===r?void 0:r.toString()}] is invalid - ${null!==(n=e.error_description)&&void 0!==n?n:""}`);if("invalid_client_metadata"===e.error)throw new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(t)} is invalid - ${null!==(i=e.error_description)&&void 0!==i?i:""}`);throw new Error(`Dynamic client registration failed: ${e.error} - ${null!==(o=e.error_description)&&void 0!==o?o:""}`)}(await o.json(),e),new Error(`Dynamic client registration failed: the server returned ${o.status} ${o.statusText} - ${await o.text()}`)}function T(e){return void 0!==e.error_description&&"string"==typeof e.error_description}function x(e,t){if(void 0!==(r=e).error&&"string"==typeof r.error)throw new E(`Token endpoint returned error [${e.error}]${T(e)?`: ${e.error_description}`:""}${function(e){return void 0!==e.error_uri&&"string"==typeof e.error_uri}(e)?` (see ${e.error_uri})`:""}`,e.error,T(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 S(["access_token"]);if(!function(e){return void 0!==e.id_token&&"string"==typeof e.id_token}(e))throw new S(["id_token"]);if(!function(e){return void 0!==e.token_type&&"string"==typeof e.token_type}(e))throw new S(["token_type"]);if(!function(e){return void 0===e.expires_in||"number"==typeof e.expires_in}(e))throw new S(["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 P(e){let t;try{const r=new n.OidcClient({response_mode:"query",loadUserInfo:!1});if(t=await r.processSigninResponse(e),void 0===r.settings.metadata)throw new Error("Cannot retrieve issuer metadata from client information in storage.");if(void 0===r.settings.metadata.jwks_uri)throw new Error("Missing some issuer metadata from client information in storage: 'jwks_uri' is undefined");if(void 0===r.settings.metadata.issuer)throw new Error("Missing some issuer metadata from client information in storage: 'issuer' is undefined");if(void 0===r.settings.client_id)throw new Error("Missing some client information in storage: 'client_id' is undefined");const i=await _(t.id_token,r.settings.metadata.jwks_uri,r.settings.metadata.issuer,r.settings.client_id);return{accessToken:t.access_token,idToken:t.id_token,webId:i,refreshToken:t.refresh_token}}catch(t){throw new Error(`Problem handling Auth Code Grant (Flow) redirect - URL [${e}]: ${t}`)}}async function C(e,t,r){return async function(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 o={"content-type":"application/x-www-form-urlencoded"};let s;n&&(s=await async function(){const{privateKey:e,publicKey:t}=await(0,d.T)(b[0]),r={privateKey:e,publicKey:await(0,h.JU)(t)};return[r.publicKey.alg]=b,r}(),o.DPoP=await R(e.tokenEndpoint,"POST",s)),t.clientSecret&&(o.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},c={method:"POST",headers:o,body:new URLSearchParams(a).toString()},l=await i(e.tokenEndpoint,c),u=x(await l.json(),n),f=await _(u.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:(p=u,void 0!==p.refresh_token&&"string"==typeof p.refresh_token?u.refresh_token:void 0),webId:f,dpopKey:s,expiresIn:u.expires_in};var p}(e,t,r,!0)}const k=e=>{try{return new URL(e),!0}catch(e){return!1}};async function O(e,t,r,n){if(void 0===r.clientId)throw new Error("No client ID available when trying to refresh the access token.");const o={grant_type:"refresh_token",refresh_token:e,scope:w};let s={};void 0!==n&&(s={DPoP:await R(t.tokenEndpoint,"POST",n)});let a={};void 0!==r.clientSecret?a={Authorization:`Basic ${btoa(`${r.clientId}:${r.clientSecret}`)}`}:k(r.clientId)&&(o.client_id=r.clientId);const c=await i(t.tokenEndpoint,{method:"POST",body:new URLSearchParams(o).toString(),headers:{...s,...a,"Content-Type":"application/x-www-form-urlencoded"}});let l;try{l=await c.json()}catch(e){throw new Error(`The token endpoint of issuer ${t.issuer} returned a malformed response.`)}const u=x(l,void 0!==n),d=await _(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:d,dpopKey:n,expiresIn:u.expires_in}}function F(e){const t=function(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}(e);return t.hash="",e.includes(`${t.origin}/`)?t.href:`${t.origin}${t.href.substring(t.origin.length+1)}`}async function N(){const e=new n.OidcClient({response_mode:"query"});await e.clearStaleState(new n.WebStorageStateStore({}));const t=window.localStorage,r=[];for(let e=0;e<=t.length;e+=1){const n=t.key(e);n&&(n.match(/^oidc\..+$/)||n.match(/^solidClientAuthenticationUser:.+$/))&&r.push(n)}r.forEach((e=>t.removeItem(e)))}},6516:function(e){var t;t=function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=22)}([function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r=4){for(var e=arguments.length,t=Array(e),r=0;r=3){for(var e=arguments.length,t=Array(e),r=0;r=2){for(var e=arguments.length,t=Array(e),r=0;r=1){for(var e=arguments.length,t=Array(e),r=0;r1&&void 0!==arguments[1]?arguments[1]:o.JsonService;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw i.Log.error("MetadataService: No settings passed to MetadataService"),new Error("settings");this._settings=t,this._jsonService=new r(["application/jwk-set+json"])}return e.prototype.resetSigningKeys=function(){this._settings=this._settings||{},this._settings.signingKeys=void 0},e.prototype.getMetadata=function(){var e=this;return this._settings.metadata?(i.Log.debug("MetadataService.getMetadata: Returning metadata from settings"),Promise.resolve(this._settings.metadata)):this.metadataUrl?(i.Log.debug("MetadataService.getMetadata: getting metadata from",this.metadataUrl),this._jsonService.getJson(this.metadataUrl).then((function(t){i.Log.debug("MetadataService.getMetadata: json received");var r=e._settings.metadataSeed||{};return e._settings.metadata=Object.assign({},r,t),e._settings.metadata}))):(i.Log.error("MetadataService.getMetadata: No authority or metadataUrl configured on settings"),Promise.reject(new Error("No authority or metadataUrl configured on settings")))},e.prototype.getIssuer=function(){return this._getMetadataProperty("issuer")},e.prototype.getAuthorizationEndpoint=function(){return this._getMetadataProperty("authorization_endpoint")},e.prototype.getUserInfoEndpoint=function(){return this._getMetadataProperty("userinfo_endpoint")},e.prototype.getTokenEndpoint=function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._getMetadataProperty("token_endpoint",e)},e.prototype.getCheckSessionIframe=function(){return this._getMetadataProperty("check_session_iframe",!0)},e.prototype.getEndSessionEndpoint=function(){return this._getMetadataProperty("end_session_endpoint",!0)},e.prototype.getRevocationEndpoint=function(){return this._getMetadataProperty("revocation_endpoint",!0)},e.prototype.getKeysEndpoint=function(){return this._getMetadataProperty("jwks_uri",!0)},e.prototype._getMetadataProperty=function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return i.Log.debug("MetadataService.getMetadataProperty for: "+e),this.getMetadata().then((function(r){if(i.Log.debug("MetadataService.getMetadataProperty: metadata recieved"),void 0===r[e]){if(!0===t)return void i.Log.warn("MetadataService.getMetadataProperty: Metadata does not contain optional property "+e);throw i.Log.error("MetadataService.getMetadataProperty: Metadata does not contain property "+e),new Error("Metadata does not contain property "+e)}return r[e]}))},e.prototype.getSigningKeys=function(){var e=this;return this._settings.signingKeys?(i.Log.debug("MetadataService.getSigningKeys: Returning signingKeys from settings"),Promise.resolve(this._settings.signingKeys)):this._getMetadataProperty("jwks_uri").then((function(t){return i.Log.debug("MetadataService.getSigningKeys: jwks_uri received",t),e._jsonService.getJson(t).then((function(t){if(i.Log.debug("MetadataService.getSigningKeys: key set received",t),!t.keys)throw i.Log.error("MetadataService.getSigningKeys: Missing keys on keyset"),new Error("Missing keys on keyset");return e._settings.signingKeys=t.keys,e._settings.signingKeys}))}))},n(e,[{key:"metadataUrl",get:function(){return this._metadataUrl||(this._settings.metadataUrl?this._metadataUrl=this._settings.metadataUrl:(this._metadataUrl=this._settings.authority,this._metadataUrl&&this._metadataUrl.indexOf(s)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=s))),this._metadataUrl}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UrlUtility=void 0;var n=r(0),i=r(1);t.UrlUtility=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.addQueryParam=function(e,t,r){return e.indexOf("?")<0&&(e+="?"),"?"!==e[e.length-1]&&(e+="&"),e+=encodeURIComponent(t),(e+="=")+encodeURIComponent(r)},e.parseUrlFragment=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"#",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.Global;"string"!=typeof e&&(e=r.location.href);var o=e.lastIndexOf(t);o>=0&&(e=e.substr(o+1)),"?"===t&&(o=e.indexOf("#"))>=0&&(e=e.substr(0,o));for(var s,a={},c=/([^&=]+)=([^&]*)/g,l=0;s=c.exec(e);)if(a[decodeURIComponent(s[1])]=decodeURIComponent(s[2].replace(/\+/g," ")),l++>50)return n.Log.error("UrlUtility.parseUrlFragment: response exceeded expected number of parameters",e),{error:"Response exceeded expected number of parameters"};for(var u in a)return a;return{}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JoseUtil=void 0;var n=r(26),i=function(e){return e&&e.__esModule?e:{default:e}}(r(33));t.JoseUtil=(0,i.default)({jws:n.jws,KeyUtil:n.KeyUtil,X509:n.X509,crypto:n.crypto,hextob64u:n.hextob64u,b64tohex:n.b64tohex,AllowedSigningAlgs:n.AllowedSigningAlgs})},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OidcClientSettings=void 0;var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},r=t.authority,i=t.metadataUrl,o=t.metadata,u=t.signingKeys,d=t.metadataSeed,h=t.client_id,f=t.client_secret,p=t.response_type,g=void 0===p?"id_token":p,y=t.scope,m=void 0===y?"openid":y,v=t.redirect_uri,b=t.post_logout_redirect_uri,w=t.client_authentication,_=void 0===w?"client_secret_post":w,S=t.prompt,E=t.display,A=t.max_age,R=t.ui_locales,I=t.acr_values,T=t.resource,x=t.response_mode,P=t.filterProtocolClaims,C=void 0===P||P,k=t.loadUserInfo,O=void 0===k||k,F=t.staleStateAge,N=void 0===F?900:F,D=t.clockSkew,L=void 0===D?300:D,U=t.clockService,j=void 0===U?new s.ClockService:U,M=t.userInfoJwtIssuer,B=void 0===M?"OP":M,H=t.mergeClaims,W=void 0!==H&&H,$=t.stateStore,V=void 0===$?new a.WebStorageStateStore:$,K=t.ResponseValidatorCtor,J=void 0===K?c.ResponseValidator:K,G=t.MetadataServiceCtor,q=void 0===G?l.MetadataService:G,z=t.extraQueryParams,Y=void 0===z?{}:z,Q=t.extraTokenParams,X=void 0===Q?{}:Q;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._authority=r,this._metadataUrl=i,this._metadata=o,this._metadataSeed=d,this._signingKeys=u,this._client_id=h,this._client_secret=f,this._response_type=g,this._scope=m,this._redirect_uri=v,this._post_logout_redirect_uri=b,this._client_authentication=_,this._prompt=S,this._display=E,this._max_age=A,this._ui_locales=R,this._acr_values=I,this._resource=T,this._response_mode=x,this._filterProtocolClaims=!!C,this._loadUserInfo=!!O,this._staleStateAge=N,this._clockSkew=L,this._clockService=j,this._userInfoJwtIssuer=B,this._mergeClaims=!!W,this._stateStore=V,this._validator=new J(this),this._metadataService=new q(this),this._extraQueryParams="object"===(void 0===Y?"undefined":n(Y))?Y:{},this._extraTokenParams="object"===(void 0===X?"undefined":n(X))?X:{}}return e.prototype.getEpochTime=function(){return this._clockService.getEpochTime()},i(e,[{key:"client_id",get:function(){return this._client_id},set:function(e){if(this._client_id)throw o.Log.error("OidcClientSettings.set_client_id: client_id has already been assigned."),new Error("client_id has already been assigned.");this._client_id=e}},{key:"client_secret",get:function(){return this._client_secret}},{key:"response_type",get:function(){return this._response_type}},{key:"scope",get:function(){return this._scope}},{key:"redirect_uri",get:function(){return this._redirect_uri}},{key:"post_logout_redirect_uri",get:function(){return this._post_logout_redirect_uri}},{key:"client_authentication",get:function(){return this._client_authentication}},{key:"prompt",get:function(){return this._prompt}},{key:"display",get:function(){return this._display}},{key:"max_age",get:function(){return this._max_age}},{key:"ui_locales",get:function(){return this._ui_locales}},{key:"acr_values",get:function(){return this._acr_values}},{key:"resource",get:function(){return this._resource}},{key:"response_mode",get:function(){return this._response_mode}},{key:"authority",get:function(){return this._authority},set:function(e){if(this._authority)throw o.Log.error("OidcClientSettings.set_authority: authority has already been assigned."),new Error("authority has already been assigned.");this._authority=e}},{key:"metadataUrl",get:function(){return this._metadataUrl||(this._metadataUrl=this.authority,this._metadataUrl&&this._metadataUrl.indexOf(u)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=u)),this._metadataUrl}},{key:"metadata",get:function(){return this._metadata},set:function(e){this._metadata=e}},{key:"metadataSeed",get:function(){return this._metadataSeed},set:function(e){this._metadataSeed=e}},{key:"signingKeys",get:function(){return this._signingKeys},set:function(e){this._signingKeys=e}},{key:"filterProtocolClaims",get:function(){return this._filterProtocolClaims}},{key:"loadUserInfo",get:function(){return this._loadUserInfo}},{key:"staleStateAge",get:function(){return this._staleStateAge}},{key:"clockSkew",get:function(){return this._clockSkew}},{key:"userInfoJwtIssuer",get:function(){return this._userInfoJwtIssuer}},{key:"mergeClaims",get:function(){return this._mergeClaims}},{key:"stateStore",get:function(){return this._stateStore}},{key:"validator",get:function(){return this._validator}},{key:"metadataService",get:function(){return this._metadataService}},{key:"extraQueryParams",get:function(){return this._extraQueryParams},set:function(e){"object"===(void 0===e?"undefined":n(e))?this._extraQueryParams=e:this._extraQueryParams={}}},{key:"extraTokenParams",get:function(){return this._extraTokenParams},set:function(e){"object"===(void 0===e?"undefined":n(e))?this._extraTokenParams=e:this._extraTokenParams={}}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebStorageStateStore=void 0;var n=r(0),i=r(1);t.WebStorageStateStore=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.prefix,n=void 0===r?"oidc.":r,o=t.store,s=void 0===o?i.Global.localStorage:o;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._store=s,this._prefix=n}return e.prototype.set=function(e,t){return n.Log.debug("WebStorageStateStore.set",e),e=this._prefix+e,this._store.setItem(e,t),Promise.resolve()},e.prototype.get=function(e){n.Log.debug("WebStorageStateStore.get",e),e=this._prefix+e;var t=this._store.getItem(e);return Promise.resolve(t)},e.prototype.remove=function(e){n.Log.debug("WebStorageStateStore.remove",e),e=this._prefix+e;var t=this._store.getItem(e);return this._store.removeItem(e),Promise.resolve(t)},e.prototype.getAllKeys=function(){n.Log.debug("WebStorageStateStore.getAllKeys");for(var e=[],t=0;t0&&void 0!==arguments[0]?arguments[0]:null,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i.Global.XMLHttpRequest,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),t&&Array.isArray(t)?this._contentTypes=t.slice():this._contentTypes=[],this._contentTypes.push("application/json"),n&&this._contentTypes.push("application/jwt"),this._XMLHttpRequest=r,this._jwtHandler=n}return e.prototype.getJson=function(e,t){var r=this;if(!e)throw n.Log.error("JsonService.getJson: No url passed"),new Error("url");return n.Log.debug("JsonService.getJson, url: ",e),new Promise((function(i,o){var s=new r._XMLHttpRequest;s.open("GET",e);var a=r._contentTypes,c=r._jwtHandler;s.onload=function(){if(n.Log.debug("JsonService.getJson: HTTP response received, status",s.status),200===s.status){var t=s.getResponseHeader("Content-Type");if(t){var r=a.find((function(e){if(t.startsWith(e))return!0}));if("application/jwt"==r)return void c(s).then(i,o);if(r)try{return void i(JSON.parse(s.responseText))}catch(e){return n.Log.error("JsonService.getJson: Error parsing JSON response",e.message),void o(e)}}o(Error("Invalid response Content-Type: "+t+", from URL: "+e))}else o(Error(s.statusText+" ("+s.status+")"))},s.onerror=function(){n.Log.error("JsonService.getJson: network error"),o(Error("Network Error"))},t&&(n.Log.debug("JsonService.getJson: token passed, setting Authorization header"),s.setRequestHeader("Authorization","Bearer "+t)),s.send()}))},e.prototype.postForm=function(e,t,r){var i=this;if(!e)throw n.Log.error("JsonService.postForm: No url passed"),new Error("url");return n.Log.debug("JsonService.postForm, url: ",e),new Promise((function(o,s){var a=new i._XMLHttpRequest;a.open("POST",e);var c=i._contentTypes;a.onload=function(){if(n.Log.debug("JsonService.postForm: HTTP response received, status",a.status),200!==a.status){if(400===a.status&&(r=a.getResponseHeader("Content-Type"))&&c.find((function(e){if(r.startsWith(e))return!0})))try{var t=JSON.parse(a.responseText);if(t&&t.error)return n.Log.error("JsonService.postForm: Error from server: ",t.error),void s(new Error(t.error))}catch(e){return n.Log.error("JsonService.postForm: Error parsing JSON response",e.message),void s(e)}s(Error(a.statusText+" ("+a.status+")"))}else{var r;if((r=a.getResponseHeader("Content-Type"))&&c.find((function(e){if(r.startsWith(e))return!0})))try{return void o(JSON.parse(a.responseText))}catch(e){return n.Log.error("JsonService.postForm: Error parsing JSON response",e.message),void s(e)}s(Error("Invalid response Content-Type: "+r+", from URL: "+e))}},a.onerror=function(){n.Log.error("JsonService.postForm: network error"),s(Error("Network Error"))};var l="";for(var u in t){var d=t[u];d&&(l.length>0&&(l+="&"),l+=encodeURIComponent(u),l+="=",l+=encodeURIComponent(d))}a.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),void 0!==r&&a.setRequestHeader("Authorization","Basic "+btoa(r)),a.send(l)}))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SigninRequest=void 0;var n=r(0),i=r(3),o=r(13);t.SigninRequest=function(){function e(t){var r=t.url,s=t.client_id,a=t.redirect_uri,c=t.response_type,l=t.scope,u=t.authority,d=t.data,h=t.prompt,f=t.display,p=t.max_age,g=t.ui_locales,y=t.id_token_hint,m=t.login_hint,v=t.acr_values,b=t.resource,w=t.response_mode,_=t.request,S=t.request_uri,E=t.extraQueryParams,A=t.request_type,R=t.client_secret,I=t.extraTokenParams,T=t.skipUserInfo;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!r)throw n.Log.error("SigninRequest.ctor: No url passed"),new Error("url");if(!s)throw n.Log.error("SigninRequest.ctor: No client_id passed"),new Error("client_id");if(!a)throw n.Log.error("SigninRequest.ctor: No redirect_uri passed"),new Error("redirect_uri");if(!c)throw n.Log.error("SigninRequest.ctor: No response_type passed"),new Error("response_type");if(!l)throw n.Log.error("SigninRequest.ctor: No scope passed"),new Error("scope");if(!u)throw n.Log.error("SigninRequest.ctor: No authority passed"),new Error("authority");var x=e.isOidc(c),P=e.isCode(c);w||(w=e.isCode(c)?"query":null),this.state=new o.SigninState({nonce:x,data:d,client_id:s,authority:u,redirect_uri:a,code_verifier:P,request_type:A,response_mode:w,client_secret:R,scope:l,extraTokenParams:I,skipUserInfo:T}),r=i.UrlUtility.addQueryParam(r,"client_id",s),r=i.UrlUtility.addQueryParam(r,"redirect_uri",a),r=i.UrlUtility.addQueryParam(r,"response_type",c),r=i.UrlUtility.addQueryParam(r,"scope",l),r=i.UrlUtility.addQueryParam(r,"state",this.state.id),x&&(r=i.UrlUtility.addQueryParam(r,"nonce",this.state.nonce)),P&&(r=i.UrlUtility.addQueryParam(r,"code_challenge",this.state.code_challenge),r=i.UrlUtility.addQueryParam(r,"code_challenge_method","S256"));var C={prompt:h,display:f,max_age:p,ui_locales:g,id_token_hint:y,login_hint:m,acr_values:v,resource:b,request:_,request_uri:S,response_mode:w};for(var k in C)C[k]&&(r=i.UrlUtility.addQueryParam(r,k,C[k]));for(var O in E)r=i.UrlUtility.addQueryParam(r,O,E[O]);this.url=r}return e.isOidc=function(e){return!!e.split(/\s+/g).filter((function(e){return"id_token"===e}))[0]},e.isOAuth=function(e){return!!e.split(/\s+/g).filter((function(e){return"token"===e}))[0]},e.isCode=function(e){return!!e.split(/\s+/g).filter((function(e){return"code"===e}))[0]},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.State=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},r=t.id,n=t.data,i=t.created,s=t.request_type;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._id=r||(0,o.default)(),this._data=n,this._created="number"==typeof i&&i>0?i:parseInt(Date.now()/1e3),this._request_type=s}return e.prototype.toStorageString=function(){return i.Log.debug("State.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})},e.fromStorageString=function(t){return i.Log.debug("State.fromStorageString"),new e(JSON.parse(t))},e.clearStaleState=function(t,r){var n=Date.now()/1e3-r;return t.getAllKeys().then((function(r){i.Log.debug("State.clearStaleState: got keys",r);for(var o=[],s=function(s){var a=r[s];c=t.get(a).then((function(r){var o=!1;if(r)try{var s=e.fromStorageString(r);i.Log.debug("State.clearStaleState: got item from key: ",a,s.created),s.created<=n&&(o=!0)}catch(e){i.Log.error("State.clearStaleState: Error parsing state for key",a,e.message),o=!0}else i.Log.debug("State.clearStaleState: no item in storage for key: ",a),o=!0;if(o)return i.Log.debug("State.clearStaleState: removed item for key: ",a),t.remove(a)})),o.push(c)},a=0;a0&&void 0!==arguments[0]?arguments[0]:{};(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),t instanceof o.OidcClientSettings?this._settings=t:this._settings=new o.OidcClientSettings(t)}return e.prototype.createSigninRequest=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.response_type,n=t.scope,o=t.redirect_uri,s=t.data,c=t.state,l=t.prompt,u=t.display,d=t.max_age,h=t.ui_locales,f=t.id_token_hint,p=t.login_hint,g=t.acr_values,y=t.resource,m=t.request,v=t.request_uri,b=t.response_mode,w=t.extraQueryParams,_=t.extraTokenParams,S=t.request_type,E=t.skipUserInfo,A=arguments[1];i.Log.debug("OidcClient.createSigninRequest");var R=this._settings.client_id;r=r||this._settings.response_type,n=n||this._settings.scope,o=o||this._settings.redirect_uri,l=l||this._settings.prompt,u=u||this._settings.display,d=d||this._settings.max_age,h=h||this._settings.ui_locales,g=g||this._settings.acr_values,y=y||this._settings.resource,b=b||this._settings.response_mode,w=w||this._settings.extraQueryParams,_=_||this._settings.extraTokenParams;var I=this._settings.authority;return a.SigninRequest.isCode(r)&&"code"!==r?Promise.reject(new Error("OpenID Connect hybrid flow is not supported")):this._metadataService.getAuthorizationEndpoint().then((function(t){i.Log.debug("OidcClient.createSigninRequest: Received authorization endpoint",t);var T=new a.SigninRequest({url:t,client_id:R,redirect_uri:o,response_type:r,scope:n,data:s||c,authority:I,prompt:l,display:u,max_age:d,ui_locales:h,id_token_hint:f,login_hint:p,acr_values:g,resource:y,request:m,request_uri:v,extraQueryParams:w,extraTokenParams:_,request_type:S,response_mode:b,client_secret:e._settings.client_secret,skipUserInfo:E}),x=T.state;return(A=A||e._stateStore).set(x.id,x.toStorageString()).then((function(){return T}))}))},e.prototype.readSigninResponseState=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];i.Log.debug("OidcClient.readSigninResponseState");var n="query"===this._settings.response_mode||!this._settings.response_mode&&a.SigninRequest.isCode(this._settings.response_type)?"?":"#",o=new c.SigninResponse(e,n);return o.state?(t=t||this._stateStore,(r?t.remove.bind(t):t.get.bind(t))(o.state).then((function(e){if(!e)throw i.Log.error("OidcClient.readSigninResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:d.SigninState.fromStorageString(e),response:o}}))):(i.Log.error("OidcClient.readSigninResponseState: No state in response"),Promise.reject(new Error("No state in response")))},e.prototype.processSigninResponse=function(e,t){var r=this;return i.Log.debug("OidcClient.processSigninResponse"),this.readSigninResponseState(e,t,!0).then((function(e){var t=e.state,n=e.response;return i.Log.debug("OidcClient.processSigninResponse: Received state from storage; validating response"),r._validator.validateSigninResponse(t,n)}))},e.prototype.createSignoutRequest=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.id_token_hint,n=t.data,o=t.state,s=t.post_logout_redirect_uri,a=t.extraQueryParams,c=t.request_type,u=arguments[1];return i.Log.debug("OidcClient.createSignoutRequest"),s=s||this._settings.post_logout_redirect_uri,a=a||this._settings.extraQueryParams,this._metadataService.getEndSessionEndpoint().then((function(t){if(!t)throw i.Log.error("OidcClient.createSignoutRequest: No end session endpoint url returned"),new Error("no end session endpoint");i.Log.debug("OidcClient.createSignoutRequest: Received end session endpoint",t);var d=new l.SignoutRequest({url:t,id_token_hint:r,post_logout_redirect_uri:s,data:n||o,extraQueryParams:a,request_type:c}),h=d.state;return h&&(i.Log.debug("OidcClient.createSignoutRequest: Signout request has state to persist"),(u=u||e._stateStore).set(h.id,h.toStorageString())),d}))},e.prototype.readSignoutResponseState=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];i.Log.debug("OidcClient.readSignoutResponseState");var n=new u.SignoutResponse(e);if(!n.state)return i.Log.debug("OidcClient.readSignoutResponseState: No state in response"),n.error?(i.Log.warn("OidcClient.readSignoutResponseState: Response was error: ",n.error),Promise.reject(new s.ErrorResponse(n))):Promise.resolve({state:void 0,response:n});var o=n.state;return t=t||this._stateStore,(r?t.remove.bind(t):t.get.bind(t))(o).then((function(e){if(!e)throw i.Log.error("OidcClient.readSignoutResponseState: No matching state found in storage"),new Error("No matching state found in storage");return{state:h.State.fromStorageString(e),response:n}}))},e.prototype.processSignoutResponse=function(e,t){var r=this;return i.Log.debug("OidcClient.processSignoutResponse"),this.readSignoutResponseState(e,t,!0).then((function(e){var t=e.state,n=e.response;return t?(i.Log.debug("OidcClient.processSignoutResponse: Received state from storage; validating response"),r._validator.validateSignoutResponse(t,n)):(i.Log.debug("OidcClient.processSignoutResponse: No state from storage; skipping validating response"),n)}))},e.prototype.clearStaleState=function(e){return i.Log.debug("OidcClient.clearStaleState"),e=e||this._stateStore,h.State.clearStaleState(e,this.settings.staleStateAge)},n(e,[{key:"_stateStore",get:function(){return this.settings.stateStore}},{key:"_validator",get:function(){return this.settings.validator}},{key:"_metadataService",get:function(){return this.settings.metadataService}},{key:"settings",get:function(){return this._settings}},{key:"metadataService",get:function(){return this._metadataService}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TokenClient=void 0;var n=r(7),i=r(2),o=r(0);t.TokenClient=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.JsonService,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw o.Log.error("TokenClient.ctor: No settings passed"),new Error("settings");this._settings=t,this._jsonService=new r,this._metadataService=new s(this._settings)}return e.prototype.exchangeCode=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(t=Object.assign({},t)).grant_type=t.grant_type||"authorization_code",t.client_id=t.client_id||this._settings.client_id,t.client_secret=t.client_secret||this._settings.client_secret,t.redirect_uri=t.redirect_uri||this._settings.redirect_uri;var r=void 0,n=t._client_authentication||this._settings._client_authentication;return delete t._client_authentication,t.code?t.redirect_uri?t.code_verifier?t.client_id?t.client_secret||"client_secret_basic"!=n?("client_secret_basic"==n&&(r=t.client_id+":"+t.client_secret,delete t.client_id,delete t.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(n){return o.Log.debug("TokenClient.exchangeCode: Received token endpoint"),e._jsonService.postForm(n,t,r).then((function(e){return o.Log.debug("TokenClient.exchangeCode: response received"),e}))}))):(o.Log.error("TokenClient.exchangeCode: No client_secret passed"),Promise.reject(new Error("A client_secret is required"))):(o.Log.error("TokenClient.exchangeCode: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(o.Log.error("TokenClient.exchangeCode: No code_verifier passed"),Promise.reject(new Error("A code_verifier is required"))):(o.Log.error("TokenClient.exchangeCode: No redirect_uri passed"),Promise.reject(new Error("A redirect_uri is required"))):(o.Log.error("TokenClient.exchangeCode: No code passed"),Promise.reject(new Error("A code is required")))},e.prototype.exchangeRefreshToken=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(t=Object.assign({},t)).grant_type=t.grant_type||"refresh_token",t.client_id=t.client_id||this._settings.client_id,t.client_secret=t.client_secret||this._settings.client_secret;var r=void 0,n=t._client_authentication||this._settings._client_authentication;return delete t._client_authentication,t.refresh_token?t.client_id?("client_secret_basic"==n&&(r=t.client_id+":"+t.client_secret,delete t.client_id,delete t.client_secret),this._metadataService.getTokenEndpoint(!1).then((function(n){return o.Log.debug("TokenClient.exchangeRefreshToken: Received token endpoint"),e._jsonService.postForm(n,t,r).then((function(e){return o.Log.debug("TokenClient.exchangeRefreshToken: response received"),e}))}))):(o.Log.error("TokenClient.exchangeRefreshToken: No client_id passed"),Promise.reject(new Error("A client_id is required"))):(o.Log.error("TokenClient.exchangeRefreshToken: No refresh_token passed"),Promise.reject(new Error("A refresh_token is required")))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorResponse=void 0;var n=r(0);t.ErrorResponse=function(e){function t(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=r.error,o=r.error_description,s=r.error_uri,a=r.state,c=r.session_state;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),!i)throw n.Log.error("No error passed to ErrorResponse"),new Error("error");var l=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,o||i));return l.name="ErrorResponse",l.error=i,l.error_description=o,l.error_uri=s,l.state=a,l.session_state=c,l}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t}(Error)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SigninState=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=r.nonce,i=r.authority,o=r.client_id,c=r.redirect_uri,l=r.code_verifier,u=r.response_mode,d=r.client_secret,h=r.scope,f=r.extraTokenParams,p=r.skipUserInfo;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var g=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,arguments[0]));if(!0===n?g._nonce=(0,a.default)():n&&(g._nonce=n),!0===l?g._code_verifier=(0,a.default)()+(0,a.default)()+(0,a.default)():l&&(g._code_verifier=l),g.code_verifier){var y=s.JoseUtil.hashString(g.code_verifier,"SHA256");g._code_challenge=s.JoseUtil.hexToBase64Url(y)}return g._redirect_uri=c,g._authority=i,g._client_id=o,g._response_mode=u,g._client_secret=d,g._scope=h,g._extraTokenParams=f,g._skipUserInfo=p,g}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.toStorageString=function(){return i.Log.debug("SigninState.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,nonce:this.nonce,code_verifier:this.code_verifier,redirect_uri:this.redirect_uri,authority:this.authority,client_id:this.client_id,response_mode:this.response_mode,client_secret:this.client_secret,scope:this.scope,extraTokenParams:this.extraTokenParams,skipUserInfo:this.skipUserInfo})},t.fromStorageString=function(e){return i.Log.debug("SigninState.fromStorageString"),new t(JSON.parse(e))},n(t,[{key:"nonce",get:function(){return this._nonce}},{key:"authority",get:function(){return this._authority}},{key:"client_id",get:function(){return this._client_id}},{key:"redirect_uri",get:function(){return this._redirect_uri}},{key:"code_verifier",get:function(){return this._code_verifier}},{key:"code_challenge",get:function(){return this._code_challenge}},{key:"response_mode",get:function(){return this._response_mode}},{key:"client_secret",get:function(){return this._client_secret}},{key:"scope",get:function(){return this._scope}},{key:"extraTokenParams",get:function(){return this._extraTokenParams}},{key:"skipUserInfo",get:function(){return this._skipUserInfo}}]),t}(o.State)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return("undefined"!=n&&null!==n&&void 0!==n.getRandomValues?i:o)().replace(/-/g,"")};var n="undefined"!=typeof window?window.crypto||window.msCrypto:null;function i(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(e){return(e^n.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16)}))}function o(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(function(e){return(e^16*Math.random()>>e/4).toString(16)}))}e.exports=t.default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.User=void 0;var n=function(){function e(e,t){for(var r=0;r0){var r=parseInt(Date.now()/1e3);this.expires_at=r+t}}},{key:"expired",get:function(){var e=this.expires_in;if(void 0!==e)return e<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessTokenEvents=void 0;var n=r(0),i=r(46);t.AccessTokenEvents=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.accessTokenExpiringNotificationTime,n=void 0===r?60:r,o=t.accessTokenExpiringTimer,s=void 0===o?new i.Timer("Access token expiring"):o,a=t.accessTokenExpiredTimer,c=void 0===a?new i.Timer("Access token expired"):a;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._accessTokenExpiringNotificationTime=n,this._accessTokenExpiring=s,this._accessTokenExpired=c}return e.prototype.load=function(e){if(e.access_token&&void 0!==e.expires_in){var t=e.expires_in;if(n.Log.debug("AccessTokenEvents.load: access token present, remaining duration:",t),t>0){var r=t-this._accessTokenExpiringNotificationTime;r<=0&&(r=1),n.Log.debug("AccessTokenEvents.load: registering expiring timer in:",r),this._accessTokenExpiring.init(r)}else n.Log.debug("AccessTokenEvents.load: canceling existing expiring timer becase we're past expiration."),this._accessTokenExpiring.cancel();var i=t+1;n.Log.debug("AccessTokenEvents.load: registering expired timer in:",i),this._accessTokenExpired.init(i)}else this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},e.prototype.unload=function(){n.Log.debug("AccessTokenEvents.unload: canceling existing access token timers"),this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},e.prototype.addAccessTokenExpiring=function(e){this._accessTokenExpiring.addHandler(e)},e.prototype.removeAccessTokenExpiring=function(e){this._accessTokenExpiring.removeHandler(e)},e.prototype.addAccessTokenExpired=function(e){this._accessTokenExpired.addHandler(e)},e.prototype.removeAccessTokenExpired=function(e){this._accessTokenExpired.removeHandler(e)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Event=void 0;var n=r(0);t.Event=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._name=t,this._callbacks=[]}return e.prototype.addHandler=function(e){this._callbacks.push(e)},e.prototype.removeHandler=function(e){var t=this._callbacks.findIndex((function(t){return t===e}));t>=0&&this._callbacks.splice(t,1)},e.prototype.raise=function(){n.Log.debug("Event: Raising event: "+this._name);for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:o.CheckSessionIFrame,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.Global.timer;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw i.Log.error("SessionMonitor.ctor: No user manager passed to SessionMonitor"),new Error("userManager");this._userManager=t,this._CheckSessionIFrameCtor=n,this._timer=a,this._userManager.events.addUserLoaded(this._start.bind(this)),this._userManager.events.addUserUnloaded(this._stop.bind(this)),Promise.resolve(this._userManager.getUser().then((function(e){e?r._start(e):r._settings.monitorAnonymousSession&&r._userManager.querySessionStatus().then((function(e){var t={session_state:e.session_state};e.sub&&e.sid&&(t.profile={sub:e.sub,sid:e.sid}),r._start(t)})).catch((function(e){i.Log.error("SessionMonitor ctor: error from querySessionStatus:",e.message)}))})).catch((function(e){i.Log.error("SessionMonitor ctor: error from getUser:",e.message)})))}return e.prototype._start=function(e){var t=this,r=e.session_state;r&&(e.profile?(this._sub=e.profile.sub,this._sid=e.profile.sid,i.Log.debug("SessionMonitor._start: session_state:",r,", sub:",this._sub)):(this._sub=void 0,this._sid=void 0,i.Log.debug("SessionMonitor._start: session_state:",r,", anonymous user")),this._checkSessionIFrame?this._checkSessionIFrame.start(r):this._metadataService.getCheckSessionIframe().then((function(e){if(e){i.Log.debug("SessionMonitor._start: Initializing check session iframe");var n=t._client_id,o=t._checkSessionInterval,s=t._stopCheckSessionOnError;t._checkSessionIFrame=new t._CheckSessionIFrameCtor(t._callback.bind(t),n,e,o,s),t._checkSessionIFrame.load().then((function(){t._checkSessionIFrame.start(r)}))}else i.Log.warn("SessionMonitor._start: No check session iframe found in the metadata")})).catch((function(e){i.Log.error("SessionMonitor._start: Error from getCheckSessionIframe:",e.message)})))},e.prototype._stop=function(){var e=this;if(this._sub=void 0,this._sid=void 0,this._checkSessionIFrame&&(i.Log.debug("SessionMonitor._stop"),this._checkSessionIFrame.stop()),this._settings.monitorAnonymousSession)var t=this._timer.setInterval((function(){e._timer.clearInterval(t),e._userManager.querySessionStatus().then((function(t){var r={session_state:t.session_state};t.sub&&t.sid&&(r.profile={sub:t.sub,sid:t.sid}),e._start(r)})).catch((function(e){i.Log.error("SessionMonitor: error from querySessionStatus:",e.message)}))}),1e3)},e.prototype._callback=function(){var e=this;this._userManager.querySessionStatus().then((function(t){var r=!0;t?t.sub===e._sub?(r=!1,e._checkSessionIFrame.start(t.session_state),t.sid===e._sid?i.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",t.session_state):(i.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",t.session_state),e._userManager.events._raiseUserSessionChanged())):i.Log.debug("SessionMonitor._callback: Different subject signed into OP:",t.sub):i.Log.debug("SessionMonitor._callback: Subject no longer signed into OP"),r&&(e._sub?(i.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed out event"),e._userManager.events._raiseUserSignedOut()):(i.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed in event"),e._userManager.events._raiseUserSignedIn()))})).catch((function(t){e._sub&&(i.Log.debug("SessionMonitor._callback: Error calling queryCurrentSigninSession; raising signed out event",t.message),e._userManager.events._raiseUserSignedOut())}))},n(e,[{key:"_settings",get:function(){return this._userManager.settings}},{key:"_metadataService",get:function(){return this._userManager.metadataService}},{key:"_client_id",get:function(){return this._settings.client_id}},{key:"_checkSessionInterval",get:function(){return this._settings.checkSessionInterval}},{key:"_stopCheckSessionOnError",get:function(){return this._settings.stopCheckSessionOnError}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckSessionIFrame=void 0;var n=r(0);t.CheckSessionIFrame=function(){function e(t,r,n,i){var o=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._callback=t,this._client_id=r,this._url=n,this._interval=i||2e3,this._stopOnError=o;var s=n.indexOf("/",n.indexOf("//")+2);this._frame_origin=n.substr(0,s),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=n}return e.prototype.load=function(){var e=this;return new Promise((function(t){e._frame.onload=function(){t()},window.document.body.appendChild(e._frame),e._boundMessageEvent=e._message.bind(e),window.addEventListener("message",e._boundMessageEvent,!1)}))},e.prototype._message=function(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(n.Log.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(n.Log.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):n.Log.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))},e.prototype.start=function(e){var t=this;if(this._session_state!==e){n.Log.debug("CheckSessionIFrame.start"),this.stop(),this._session_state=e;var r=function(){t._frame.contentWindow.postMessage(t._client_id+" "+t._session_state,t._frame_origin)};r(),this._timer=window.setInterval(r,this._interval)}},e.prototype.stop=function(){this._session_state=null,this._timer&&(n.Log.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TokenRevocationClient=void 0;var n=r(0),i=r(2),o=r(1);t.TokenRevocationClient=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o.Global.XMLHttpRequest,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw n.Log.error("TokenRevocationClient.ctor: No settings provided"),new Error("No settings provided.");this._settings=t,this._XMLHttpRequestCtor=r,this._metadataService=new s(this._settings)}return e.prototype.revoke=function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"access_token";if(!e)throw n.Log.error("TokenRevocationClient.revoke: No token provided"),new Error("No token provided.");if("access_token"!==i&&"refresh_token"!=i)throw n.Log.error("TokenRevocationClient.revoke: Invalid token type"),new Error("Invalid token type.");return this._metadataService.getRevocationEndpoint().then((function(o){if(o){n.Log.debug("TokenRevocationClient.revoke: Revoking "+i);var s=r._settings.client_id,a=r._settings.client_secret;return r._revoke(o,s,a,e,i)}if(t)throw n.Log.error("TokenRevocationClient.revoke: Revocation not supported"),new Error("Revocation not supported")}))},e.prototype._revoke=function(e,t,r,i,o){var s=this;return new Promise((function(a,c){var l=new s._XMLHttpRequestCtor;l.open("POST",e),l.onload=function(){n.Log.debug("TokenRevocationClient.revoke: HTTP response received, status",l.status),200===l.status?a():c(Error(l.statusText+" ("+l.status+")"))},l.onerror=function(){n.Log.debug("TokenRevocationClient.revoke: Network Error."),c("Network Error")};var u="client_id="+encodeURIComponent(t);r&&(u+="&client_secret="+encodeURIComponent(r)),u+="&token_type_hint="+encodeURIComponent(o),u+="&token="+encodeURIComponent(i),l.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),l.send(u)}))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CordovaPopupWindow=void 0;var n=function(){function e(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:o.MetadataService,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.UserInfoService,c=arguments.length>3&&void 0!==arguments[3]?arguments[3]:l.JoseUtil,u=arguments.length>4&&void 0!==arguments[4]?arguments[4]:a.TokenClient;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw i.Log.error("ResponseValidator.ctor: No settings passed to ResponseValidator"),new Error("settings");this._settings=t,this._metadataService=new r(this._settings),this._userInfoService=new n(this._settings),this._joseUtil=c,this._tokenClient=new u(this._settings)}return e.prototype.validateSigninResponse=function(e,t){var r=this;return i.Log.debug("ResponseValidator.validateSigninResponse"),this._processSigninParams(e,t).then((function(t){return i.Log.debug("ResponseValidator.validateSigninResponse: state processed"),r._validateTokens(e,t).then((function(t){return i.Log.debug("ResponseValidator.validateSigninResponse: tokens validated"),r._processClaims(e,t).then((function(e){return i.Log.debug("ResponseValidator.validateSigninResponse: claims processed"),e}))}))}))},e.prototype.validateSignoutResponse=function(e,t){return e.id!==t.state?(i.Log.error("ResponseValidator.validateSignoutResponse: State does not match"),Promise.reject(new Error("State does not match"))):(i.Log.debug("ResponseValidator.validateSignoutResponse: state validated"),t.state=e.data,t.error?(i.Log.warn("ResponseValidator.validateSignoutResponse: Response was error",t.error),Promise.reject(new c.ErrorResponse(t))):Promise.resolve(t))},e.prototype._processSigninParams=function(e,t){if(e.id!==t.state)return i.Log.error("ResponseValidator._processSigninParams: State does not match"),Promise.reject(new Error("State does not match"));if(!e.client_id)return i.Log.error("ResponseValidator._processSigninParams: No client_id on state"),Promise.reject(new Error("No client_id on state"));if(!e.authority)return i.Log.error("ResponseValidator._processSigninParams: No authority on state"),Promise.reject(new Error("No authority on state"));if(this._settings.authority){if(this._settings.authority&&this._settings.authority!==e.authority)return i.Log.error("ResponseValidator._processSigninParams: authority mismatch on settings vs. signin state"),Promise.reject(new Error("authority mismatch on settings vs. signin state"))}else this._settings.authority=e.authority;if(this._settings.client_id){if(this._settings.client_id&&this._settings.client_id!==e.client_id)return i.Log.error("ResponseValidator._processSigninParams: client_id mismatch on settings vs. signin state"),Promise.reject(new Error("client_id mismatch on settings vs. signin state"))}else this._settings.client_id=e.client_id;return i.Log.debug("ResponseValidator._processSigninParams: state validated"),t.state=e.data,t.error?(i.Log.warn("ResponseValidator._processSigninParams: Response was error",t.error),Promise.reject(new c.ErrorResponse(t))):e.nonce&&!t.id_token?(i.Log.error("ResponseValidator._processSigninParams: Expecting id_token in response"),Promise.reject(new Error("No id_token in response"))):!e.nonce&&t.id_token?(i.Log.error("ResponseValidator._processSigninParams: Not expecting id_token in response"),Promise.reject(new Error("Unexpected id_token in response"))):e.code_verifier&&!t.code?(i.Log.error("ResponseValidator._processSigninParams: Expecting code in response"),Promise.reject(new Error("No code in response"))):!e.code_verifier&&t.code?(i.Log.error("ResponseValidator._processSigninParams: Not expecting code in response"),Promise.reject(new Error("Unexpected code in response"))):(t.scope||(t.scope=e.scope),Promise.resolve(t))},e.prototype._processClaims=function(e,t){var r=this;if(t.isOpenIdConnect){if(i.Log.debug("ResponseValidator._processClaims: response is OIDC, processing claims"),t.profile=this._filterProtocolClaims(t.profile),!0!==e.skipUserInfo&&this._settings.loadUserInfo&&t.access_token)return i.Log.debug("ResponseValidator._processClaims: loading user info"),this._userInfoService.getClaims(t.access_token).then((function(e){return i.Log.debug("ResponseValidator._processClaims: user info claims received from user info endpoint"),e.sub!==t.profile.sub?(i.Log.error("ResponseValidator._processClaims: sub from user info endpoint does not match sub in id_token"),Promise.reject(new Error("sub from user info endpoint does not match sub in id_token"))):(t.profile=r._mergeClaims(t.profile,e),i.Log.debug("ResponseValidator._processClaims: user info claims received, updated profile:",t.profile),t)}));i.Log.debug("ResponseValidator._processClaims: not loading user info")}else i.Log.debug("ResponseValidator._processClaims: response is not OIDC, not processing claims");return Promise.resolve(t)},e.prototype._mergeClaims=function(e,t){var r=Object.assign({},e);for(var i in t){var o=t[i];Array.isArray(o)||(o=[o]);for(var s=0;s1)return i.Log.error("ResponseValidator._validateIdToken: No kid found in id_token and more than one key found in metadata"),Promise.reject(new Error("No kid found in id_token and more than one key found in metadata"));o=r[0]}return Promise.resolve(o)}))},e.prototype._getSigningKeyForJwtWithSingleRetry=function(e){var t=this;return this._getSigningKeyForJwt(e).then((function(r){return r?Promise.resolve(r):(t._metadataService.resetSigningKeys(),t._getSigningKeyForJwt(e))}))},e.prototype._validateIdToken=function(e,t){var r=this;if(!e.nonce)return i.Log.error("ResponseValidator._validateIdToken: No nonce on state"),Promise.reject(new Error("No nonce on state"));var n=this._joseUtil.parseJwt(t.id_token);return n&&n.header&&n.payload?e.nonce!==n.payload.nonce?(i.Log.error("ResponseValidator._validateIdToken: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"))):this._metadataService.getIssuer().then((function(o){return i.Log.debug("ResponseValidator._validateIdToken: Received issuer"),r._getSigningKeyForJwtWithSingleRetry(n).then((function(s){if(!s)return i.Log.error("ResponseValidator._validateIdToken: No key matching kid or alg found in signing keys"),Promise.reject(new Error("No key matching kid or alg found in signing keys"));var a=e.client_id,c=r._settings.clockSkew;return i.Log.debug("ResponseValidator._validateIdToken: Validaing JWT; using clock skew (in seconds) of: ",c),r._joseUtil.validateJwt(t.id_token,s,o,a,c).then((function(){return i.Log.debug("ResponseValidator._validateIdToken: JWT validation successful"),n.payload.sub?(t.profile=n.payload,t):(i.Log.error("ResponseValidator._validateIdToken: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))}))}))})):(i.Log.error("ResponseValidator._validateIdToken: Failed to parse id_token",n),Promise.reject(new Error("Failed to parse id_token")))},e.prototype._filterByAlg=function(e,t){var r=null;if(t.startsWith("RS"))r="RSA";else if(t.startsWith("PS"))r="PS";else{if(!t.startsWith("ES"))return i.Log.debug("ResponseValidator._filterByAlg: alg not supported: ",t),[];r="EC"}return i.Log.debug("ResponseValidator._filterByAlg: Looking for keys that match kty: ",r),e=e.filter((function(e){return e.kty===r})),i.Log.debug("ResponseValidator._filterByAlg: Number of keys that match kty: ",r,e.length),e},e.prototype._validateAccessToken=function(e){if(!e.profile)return i.Log.error("ResponseValidator._validateAccessToken: No profile loaded from id_token"),Promise.reject(new Error("No profile loaded from id_token"));if(!e.profile.at_hash)return i.Log.error("ResponseValidator._validateAccessToken: No at_hash in id_token"),Promise.reject(new Error("No at_hash in id_token"));if(!e.id_token)return i.Log.error("ResponseValidator._validateAccessToken: No id_token"),Promise.reject(new Error("No id_token"));var t=this._joseUtil.parseJwt(e.id_token);if(!t||!t.header)return i.Log.error("ResponseValidator._validateAccessToken: Failed to parse id_token",t),Promise.reject(new Error("Failed to parse id_token"));var r=t.header.alg;if(!r||5!==r.length)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",r),Promise.reject(new Error("Unsupported alg: "+r));var n=r.substr(2,3);if(!n)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",r,n),Promise.reject(new Error("Unsupported alg: "+r));if(256!==(n=parseInt(n))&&384!==n&&512!==n)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",r,n),Promise.reject(new Error("Unsupported alg: "+r));var o="sha"+n,s=this._joseUtil.hashString(e.access_token,o);if(!s)return i.Log.error("ResponseValidator._validateAccessToken: access_token hash failed:",o),Promise.reject(new Error("Failed to validate at_hash"));var a=s.substr(0,s.length/2),c=this._joseUtil.hexToBase64Url(a);return c!==e.profile.at_hash?(i.Log.error("ResponseValidator._validateAccessToken: Failed to validate at_hash",c,e.profile.at_hash),Promise.reject(new Error("Failed to validate at_hash"))):(i.Log.debug("ResponseValidator._validateAccessToken: success"),Promise.resolve(e))},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserInfoService=void 0;var n=r(7),i=r(2),o=r(0),s=r(4);t.UserInfoService=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.JsonService,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.MetadataService,c=arguments.length>3&&void 0!==arguments[3]?arguments[3]:s.JoseUtil;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw o.Log.error("UserInfoService.ctor: No settings passed"),new Error("settings");this._settings=t,this._jsonService=new r(void 0,void 0,this._getClaimsFromJwt.bind(this)),this._metadataService=new a(this._settings),this._joseUtil=c}return e.prototype.getClaims=function(e){var t=this;return e?this._metadataService.getUserInfoEndpoint().then((function(r){return o.Log.debug("UserInfoService.getClaims: received userinfo url",r),t._jsonService.getJson(r,e).then((function(e){return o.Log.debug("UserInfoService.getClaims: claims received",e),e}))})):(o.Log.error("UserInfoService.getClaims: No token passed"),Promise.reject(new Error("A token is required")))},e.prototype._getClaimsFromJwt=function e(t){var r=this;try{var n=this._joseUtil.parseJwt(t.responseText);if(!n||!n.header||!n.payload)return o.Log.error("UserInfoService._getClaimsFromJwt: Failed to parse JWT",n),Promise.reject(new Error("Failed to parse id_token"));var i=n.header.kid,s=void 0;switch(this._settings.userInfoJwtIssuer){case"OP":s=this._metadataService.getIssuer();break;case"ANY":s=Promise.resolve(n.payload.iss);break;default:s=Promise.resolve(this._settings.userInfoJwtIssuer)}return s.then((function(e){return o.Log.debug("UserInfoService._getClaimsFromJwt: Received issuer:"+e),r._metadataService.getSigningKeys().then((function(s){if(!s)return o.Log.error("UserInfoService._getClaimsFromJwt: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));o.Log.debug("UserInfoService._getClaimsFromJwt: Received signing keys");var a=void 0;if(i)a=s.filter((function(e){return e.kid===i}))[0];else{if((s=r._filterByAlg(s,n.header.alg)).length>1)return o.Log.error("UserInfoService._getClaimsFromJwt: No kid found in id_token and more than one key found in metadata"),Promise.reject(new Error("No kid found in id_token and more than one key found in metadata"));a=s[0]}if(!a)return o.Log.error("UserInfoService._getClaimsFromJwt: No key matching kid or alg found in signing keys"),Promise.reject(new Error("No key matching kid or alg found in signing keys"));var c=r._settings.client_id,l=r._settings.clockSkew;return o.Log.debug("UserInfoService._getClaimsFromJwt: Validaing JWT; using clock skew (in seconds) of: ",l),r._joseUtil.validateJwt(t.responseText,a,e,c,l,void 0,!0).then((function(){return o.Log.debug("UserInfoService._getClaimsFromJwt: JWT validation successful"),n.payload}))}))}))}catch(e){return o.Log.error("UserInfoService._getClaimsFromJwt: Error parsing JWT response",e.message),void reject(e)}},e.prototype._filterByAlg=function(e,t){var r=null;if(t.startsWith("RS"))r="RSA";else if(t.startsWith("PS"))r="PS";else{if(!t.startsWith("ES"))return o.Log.debug("UserInfoService._filterByAlg: alg not supported: ",t),[];r="EC"}return o.Log.debug("UserInfoService._filterByAlg: Looking for keys that match kty: ",r),e=e.filter((function(e){return e.kty===r})),o.Log.debug("UserInfoService._filterByAlg: Number of keys that match kty: ",r,e.length),e},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AllowedSigningAlgs=t.b64tohex=t.hextob64u=t.crypto=t.X509=t.KeyUtil=t.jws=void 0;var n=r(27);t.jws=n.jws,t.KeyUtil=n.KEYUTIL,t.X509=n.X509,t.crypto=n.crypto,t.hextob64u=n.hextob64u,t.b64tohex=n.b64tohex,t.AllowedSigningAlgs=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"]},function(e,t,r){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});var r,n,i,o,s,a,c,l,u,d,h,f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p={userAgent:!1},g={},y=y||(r=Math,i=(n={}).lib={},o=i.Base=function(){function e(){}return{extend:function(t){e.prototype=this;var r=new e;return t&&r.mixIn(t),r.hasOwnProperty("init")||(r.init=function(){r.$super.init.apply(this,arguments)}),r.init.prototype=r,r.$super=this,r},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),s=i.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=s<<24-(n+o)%4*8}else for(o=0;o>>2]=r[o>>>2];return this.sigBytes+=i,this},clamp:function(){var e=this.words,t=this.sigBytes;e[t>>>2]&=4294967295<<32-t%4*8,e.length=r.ceil(t/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],n=0;n>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(r,t/2)}},l=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(r,t)}},u=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(l.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return l.parse(unescape(encodeURIComponent(e)))}},d=i.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(e){var t=this._data,n=t.words,i=t.sigBytes,o=this.blockSize,a=i/(4*o),c=(a=e?r.ceil(a):r.max((0|a)-this._minBufferSize,0))*o,l=r.min(4*c,i);if(c){for(var u=0;u>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,s=0;4>s&&i+.75*s>>6*(3-s)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var r=e.length,n=this._map;(i=n.charAt(64))&&-1!=(i=e.indexOf(i))&&(r=i);for(var i=[],o=0,s=0;s>>6-s%4*2;i[o>>>2]|=(a|c)<<24-o%4*8,o++}return t.create(i,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){for(var t=y,r=(i=t.lib).WordArray,n=i.Hasher,i=t.algo,o=[],s=[],a=function(e){return 4294967296*(e-(0|e))|0},c=2,l=0;64>l;){var u;e:{u=c;for(var d=e.sqrt(u),h=2;h<=d;h++)if(!(u%h)){u=!1;break e}u=!0}u&&(8>l&&(o[l]=a(e.pow(c,.5))),s[l]=a(e.pow(c,1/3)),l++),c++}var f=[];i=i.SHA256=n.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],a=r[3],c=r[4],l=r[5],u=r[6],d=r[7],h=0;64>h;h++){if(16>h)f[h]=0|e[t+h];else{var p=f[h-15],g=f[h-2];f[h]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+f[h-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+f[h-16]}p=d+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&l^~c&u)+s[h]+f[h],g=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&i^n&o^i&o),d=u,u=l,l=c,c=a+p|0,a=o,o=i,i=n,n=p+g|0}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+a|0,r[4]=r[4]+c|0,r[5]=r[5]+l|0,r[6]=r[6]+u|0,r[7]=r[7]+d|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;return r[i>>>5]|=128<<24-i%32,r[14+(i+64>>>9<<4)]=e.floor(n/4294967296),r[15+(i+64>>>9<<4)]=n,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}}),t.SHA256=n._createHelper(i),t.HmacSHA256=n._createHmacHelper(i)}(Math),function(){function e(){return n.create.apply(n,arguments)}for(var t=y,r=t.lib.Hasher,n=(o=t.x64).Word,i=o.WordArray,o=t.algo,s=[e(1116352408,3609767458),e(1899447441,602891725),e(3049323471,3964484399),e(3921009573,2173295548),e(961987163,4081628472),e(1508970993,3053834265),e(2453635748,2937671579),e(2870763221,3664609560),e(3624381080,2734883394),e(310598401,1164996542),e(607225278,1323610764),e(1426881987,3590304994),e(1925078388,4068182383),e(2162078206,991336113),e(2614888103,633803317),e(3248222580,3479774868),e(3835390401,2666613458),e(4022224774,944711139),e(264347078,2341262773),e(604807628,2007800933),e(770255983,1495990901),e(1249150122,1856431235),e(1555081692,3175218132),e(1996064986,2198950837),e(2554220882,3999719339),e(2821834349,766784016),e(2952996808,2566594879),e(3210313671,3203337956),e(3336571891,1034457026),e(3584528711,2466948901),e(113926993,3758326383),e(338241895,168717936),e(666307205,1188179964),e(773529912,1546045734),e(1294757372,1522805485),e(1396182291,2643833823),e(1695183700,2343527390),e(1986661051,1014477480),e(2177026350,1206759142),e(2456956037,344077627),e(2730485921,1290863460),e(2820302411,3158454273),e(3259730800,3505952657),e(3345764771,106217008),e(3516065817,3606008344),e(3600352804,1432725776),e(4094571909,1467031594),e(275423344,851169720),e(430227734,3100823752),e(506948616,1363258195),e(659060556,3750685593),e(883997877,3785050280),e(958139571,3318307427),e(1322822218,3812723403),e(1537002063,2003034995),e(1747873779,3602036899),e(1955562222,1575990012),e(2024104815,1125592928),e(2227730452,2716904306),e(2361852424,442776044),e(2428436474,593698344),e(2756734187,3733110249),e(3204031479,2999351573),e(3329325298,3815920427),e(3391569614,3928383900),e(3515267271,566280711),e(3940187606,3454069534),e(4118630271,4000239992),e(116418474,1914138554),e(174292421,2731055270),e(289380356,3203993006),e(460393269,320620315),e(685471733,587496836),e(852142971,1086792851),e(1017036298,365543100),e(1126000580,2618297676),e(1288033470,3409855158),e(1501505948,4234509866),e(1607167915,987167468),e(1816402316,1246189591)],a=[],c=0;80>c;c++)a[c]=e();o=o.SHA512=r.extend({_doReset:function(){this._hash=new i.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var r=(d=this._hash.words)[0],n=d[1],i=d[2],o=d[3],c=d[4],l=d[5],u=d[6],d=d[7],h=r.high,f=r.low,p=n.high,g=n.low,y=i.high,m=i.low,v=o.high,b=o.low,w=c.high,_=c.low,S=l.high,E=l.low,A=u.high,R=u.low,I=d.high,T=d.low,x=h,P=f,C=p,k=g,O=y,F=m,N=v,D=b,L=w,U=_,j=S,M=E,B=A,H=R,W=I,$=T,V=0;80>V;V++){var K=a[V];if(16>V)var J=K.high=0|e[t+2*V],G=K.low=0|e[t+2*V+1];else{J=((G=(J=a[V-15]).high)>>>1|(q=J.low)<<31)^(G>>>8|q<<24)^G>>>7;var q=(q>>>1|G<<31)^(q>>>8|G<<24)^(q>>>7|G<<25),z=((G=(z=a[V-2]).high)>>>19|(Y=z.low)<<13)^(G<<3|Y>>>29)^G>>>6,Y=(Y>>>19|G<<13)^(Y<<3|G>>>29)^(Y>>>6|G<<26),Q=(G=a[V-7]).high,X=(Z=a[V-16]).high,Z=Z.low;J=(J=(J=J+Q+((G=q+G.low)>>>0>>0?1:0))+z+((G+=Y)>>>0>>0?1:0))+X+((G+=Z)>>>0>>0?1:0),K.high=J,K.low=G}Q=L&j^~L&B,Z=U&M^~U&H,K=x&C^x&O^C&O;var ee=P&k^P&F^k&F,te=(q=(x>>>28|P<<4)^(x<<30|P>>>2)^(x<<25|P>>>7),z=(P>>>28|x<<4)^(P<<30|x>>>2)^(P<<25|x>>>7),(Y=s[V]).high),re=Y.low;X=W+((L>>>14|U<<18)^(L>>>18|U<<14)^(L<<23|U>>>9))+((Y=$+((U>>>14|L<<18)^(U>>>18|L<<14)^(U<<23|L>>>9)))>>>0<$>>>0?1:0),W=B,$=H,B=j,H=M,j=L,M=U,L=N+(X=(X=(X=X+Q+((Y+=Z)>>>0>>0?1:0))+te+((Y+=re)>>>0>>0?1:0))+J+((Y+=G)>>>0>>0?1:0))+((U=D+Y|0)>>>0>>0?1:0)|0,N=O,D=F,O=C,F=k,C=x,k=P,x=X+(K=q+K+((G=z+ee)>>>0>>0?1:0))+((P=Y+G|0)>>>0>>0?1:0)|0}f=r.low=f+P,r.high=h+x+(f>>>0

>>0?1:0),g=n.low=g+k,n.high=p+C+(g>>>0>>0?1:0),m=i.low=m+F,i.high=y+O+(m>>>0>>0?1:0),b=o.low=b+D,o.high=v+N+(b>>>0>>0?1:0),_=c.low=_+U,c.high=w+L+(_>>>0>>0?1:0),E=l.low=E+M,l.high=S+j+(E>>>0>>0?1:0),R=u.low=R+H,u.high=A+B+(R>>>0>>0?1:0),T=d.low=T+$,d.high=I+W+(T>>>0<$>>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(r/4294967296),t[31+(n+128>>>10<<5)]=r,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32}),t.SHA512=r._createHelper(o),t.HmacSHA512=r._createHmacHelper(o)}(),function(){var e=y,t=(i=e.x64).Word,r=i.WordArray,n=(i=e.algo).SHA512,i=i.SHA384=n.extend({_doReset:function(){this._hash=new r.init([new t.init(3418070365,3238371032),new t.init(1654270250,914150663),new t.init(2438529370,812702999),new t.init(355462360,4144912697),new t.init(1731405415,4290775857),new t.init(2394180231,1750603025),new t.init(3675008525,1694076839),new t.init(1203062813,3204075428)])},_doFinalize:function(){var e=n._doFinalize.call(this);return e.sigBytes-=16,e}});e.SHA384=n._createHelper(i),e.HmacSHA384=n._createHmacHelper(i)}();var m,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function b(e){var t,r,n="";for(t=0;t+3<=e.length;t+=3)r=parseInt(e.substring(t,t+3),16),n+=v.charAt(r>>6)+v.charAt(63&r);for(t+1==e.length?(r=parseInt(e.substring(t,t+1),16),n+=v.charAt(r<<2)):t+2==e.length&&(r=parseInt(e.substring(t,t+2),16),n+=v.charAt(r>>2)+v.charAt((3&r)<<4));(3&n.length)>0;)n+="=";return n}function w(e){var t,r,n,i="",o=0;for(t=0;t>2),r=3&n,o=1):1==o?(i+=T(r<<2|n>>4),r=15&n,o=2):2==o?(i+=T(r),i+=T(n>>2),r=3&n,o=3):(i+=T(r<<2|n>>4),i+=T(15&n),o=0));return 1==o&&(i+=T(r<<2)),i}function _(e){var t,r=w(e),n=new Array;for(t=0;2*t>15;--o>=0;){var c=32767&this[e],l=this[e++]>>15,u=a*c+l*s;i=((c=s*c+((32767&u)<<15)+r[n]+(1073741823&i))>>>30)+(u>>>15)+a*l+(i>>>30),r[n++]=1073741823&c}return i},m=30):"Netscape"!=p.appName?(S.prototype.am=function(e,t,r,n,i,o){for(;--o>=0;){var s=t*this[e++]+r[n]+i;i=Math.floor(s/67108864),r[n++]=67108863&s}return i},m=26):(S.prototype.am=function(e,t,r,n,i,o){for(var s=16383&t,a=t>>14;--o>=0;){var c=16383&this[e],l=this[e++]>>14,u=a*c+l*s;i=((c=s*c+((16383&u)<<14)+r[n]+i)>>28)+(u>>14)+a*l,r[n++]=268435455&c}return i},m=28),S.prototype.DB=m,S.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function k(e){this.m=e}function O(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),!(255&e)&&(e>>=8,t+=8),!(15&e)&&(e>>=4,t+=4),!(3&e)&&(e>>=2,t+=2),!(1&e)&&++t,t}function j(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function M(){}function B(e){return e}function H(e){this.r2=E(),this.q3=E(),S.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}k.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},k.prototype.revert=function(e){return e},k.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},k.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},k.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},O.prototype.convert=function(e){var t=E();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(S.ZERO)>0&&this.m.subTo(t,t),t},O.prototype.revert=function(e){var t=E();return e.copyTo(t),this.reduce(t),t},O.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,n,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},O.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},O.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},S.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},S.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},S.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,o=0;--n>=0;){var s=8==r?255&e[n]:x(e,n);s<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==o?this[this.t++]=s:o+r>this.DB?(this[this.t-1]|=(s&(1<>this.DB-o):this[this.t-1]|=s<=this.DB&&(o-=this.DB))}8==r&&!!(128&e[0])&&(this.s=-1,o>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==e;)--this.t},S.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s},S.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t[r+s+1]=this[r]>>i|a,a=(this[r]&o)<=0;--r)t[r]=0;t[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()},S.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,o=(1<>n;for(var s=r+1;s>n;n>0&&(t[this.t-r-1]|=(this.s&o)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t[r++]=this.DV+n:n>0&&(t[r++]=n),t.t=r,t.clamp()},S.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t[i]=0;for(i=0;i=0;)e[r]=0;for(r=0;r=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()},S.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(c,o),i.lShiftTo(c,r)):(n.copyTo(o),i.copyTo(r));var l=o.t,u=o[l-1];if(0!=u){var d=u*(1<1?o[l-2]>>this.F2:0),h=this.FV/d,f=(1<=0&&(r[r.t++]=1,r.subTo(m,r)),S.ONE.dlShiftTo(l,m),m.subTo(o,o);o.t=0;){var v=r[--g]==u?this.DM:Math.floor(r[g]*h+(r[g-1]+p)*f);if((r[g]+=o.am(0,v,r,y,0,l))0&&r.rShiftTo(c,r),s<0&&S.ZERO.subTo(r,r)}}},S.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},S.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},S.prototype.exp=function(e,t){if(e>4294967295||e<1)return S.ONE;var r=E(),n=E(),i=t.convert(this),o=C(e)-1;for(i.copyTo(r);--o>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var s=r;r=n,n=s}return t.revert(r)},S.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,o=T(r));s>=0;)a>(a+=this.DB-t)):(r=this[s]>>(a-=t)&n,a<=0&&(a+=this.DB,--s)),r>0&&(i=!0),i&&(o+=T(r));return i?o:"0"},S.prototype.negate=function(){var e=E();return S.ZERO.subTo(this,e),e},S.prototype.abs=function(){return this.s<0?this.negate():this},S.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0},S.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+C(this[this.t-1]^this.s&this.DM)},S.prototype.mod=function(e){var t=E();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(S.ZERO)>0&&e.subTo(t,t),t},S.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new k(t):new O(t),this.exp(e,r)},S.ZERO=P(0),S.ONE=P(1),M.prototype.convert=B,M.prototype.revert=B,M.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},M.prototype.sqrTo=function(e,t){e.squareTo(t)},H.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=E();return e.copyTo(t),this.reduce(t),t},H.prototype.revert=function(e){return e},H.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},H.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},H.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var W,$,V,K=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],J=(1<<26)/K[K.length-1];function G(){this.i=0,this.j=0,this.S=new Array}function q(){!function(e){$[V++]^=255&e,$[V++]^=e>>8&255,$[V++]^=e>>16&255,$[V++]^=e>>24&255,V>=256&&(V-=256)}((new Date).getTime())}if(S.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},S.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=P(r),i=E(),o=E(),s="";for(this.divRemTo(n,i,o);i.signum()>0;)s=(r+o.intValue()).toString(e).substr(1)+s,i.divRemTo(n,i,o);return o.intValue().toString(e)+s},S.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,o=0,s=0,a=0;a=r&&(this.dMultiply(n),this.dAddOffset(s,0),o=0,s=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(s,0)),i&&S.ZERO.subTo(this,this)},S.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(S.ONE.shiftLeft(e-1),N,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(S.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t[r++]=n:n<-1&&(t[r++]=this.DV+n),t.t=r,t.clamp()},S.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},S.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},S.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i=0;)r[n]=0;for(n=Math.max(t-this.t,0);n0)if(0==t)r=this[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this[n])%e;return r},S.prototype.millerRabin=function(e){var t=this.subtract(S.ONE),r=t.getLowestSetBit();if(r<=0)return!1;var n=t.shiftRight(r);(e=e+1>>1)>K.length&&(e=K.length);for(var i=E(),o=0;o>24},S.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},S.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},S.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this[e]&(1<>(n+=this.DB-8)):(r=this[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),!!(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},S.prototype.equals=function(e){return 0==this.compareTo(e)},S.prototype.min=function(e){return this.compareTo(e)<0?this:e},S.prototype.max=function(e){return this.compareTo(e)>0?this:e},S.prototype.and=function(e){var t=E();return this.bitwiseTo(e,F,t),t},S.prototype.or=function(e){var t=E();return this.bitwiseTo(e,N,t),t},S.prototype.xor=function(e){var t=E();return this.bitwiseTo(e,D,t),t},S.prototype.andNot=function(e){var t=E();return this.bitwiseTo(e,L,t),t},S.prototype.not=function(){for(var e=E(),t=0;t=this.t?0!=this.s:!!(this[t]&1<1){var u=E();for(n.sqrTo(s[1],u);a<=l;)s[a]=E(),n.mulTo(u,s[a-2],s[a]),a+=2}var d,h,f=e.t-1,p=!0,g=E();for(i=C(e[f])-1;f>=0;){for(i>=c?d=e[f]>>i-c&l:(d=(e[f]&(1<0&&(d|=e[f-1]>>this.DB+i-c)),a=r;!(1&d);)d>>=1,--a;if((i-=a)<0&&(i+=this.DB,--f),p)s[d].copyTo(o),p=!1;else{for(;a>1;)n.sqrTo(o,g),n.sqrTo(g,o),a-=2;a>0?n.sqrTo(o,g):(h=o,o=g,g=h),n.mulTo(g,s[d],o)}for(;f>=0&&!(e[f]&1<=0?(r.subTo(n,r),t&&i.subTo(s,i),o.subTo(a,o)):(n.subTo(r,n),t&&s.subTo(i,s),a.subTo(o,a))}return 0!=n.compareTo(S.ONE)?S.ZERO:a.compareTo(e)>=0?a.subtract(e):a.signum()<0?(a.addTo(e,a),a.signum()<0?a.add(e):a):a},S.prototype.pow=function(e){return this.exp(e,new M)},S.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),o=r.getLowestSetBit();if(o<0)return t;for(i0&&(t.rShiftTo(o,t),r.rShiftTo(o,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return o>0&&r.lShiftTo(o,r),r},S.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=K[K.length-1]){for(t=0;t>>8,$[V++]=255&z;V=0,q()}function Z(){if(null==W){for(q(),(W=new G).init($),V=0;V<$.length;++V)$[V]=0;V=0}return W.next()}function ee(){}function te(e,t){return new S(e,t)}function re(e,t,r){for(var n="",i=0;n.length>24,(16711680&i)>>16,(65280&i)>>8,255&i]))),i+=1;return n}function ne(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}function ie(e,t){this.x=t,this.q=e}function oe(e,t,r,n){this.curve=e,this.x=t,this.y=r,this.z=null==n?S.ONE:n,this.zinv=null}function se(e,t,r){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(r),this.infinity=new oe(this,null,null)}ee.prototype.nextBytes=function(e){var t;for(t=0;t0&&t.length>0))throw"Invalid RSA public key";this.n=te(e,16),this.e=parseInt(t,16)}},ne.prototype.encrypt=function(e){var t=function(e,t){if(t=0&&t>0;){var i=e.charCodeAt(n--);i<128?r[--t]=i:i>127&&i<2048?(r[--t]=63&i|128,r[--t]=i>>6|192):(r[--t]=63&i|128,r[--t]=i>>6&63|128,r[--t]=i>>12|224)}r[--t]=0;for(var o=new ee,s=new Array;t>2;){for(s[0]=0;0==s[0];)o.nextBytes(s);r[--t]=s[0]}return r[--t]=2,r[--t]=0,new S(r)}(e,this.n.bitLength()+7>>3);if(null==t)return null;var r=this.doPublic(t);if(null==r)return null;var n=r.toString(16);return 1&n.length?"0"+n:n},ne.prototype.encryptOAEP=function(e,t,r){var n=function(e,t,r,n){var i=ce.crypto.MessageDigest,o=ce.crypto.Util,s=null;if(r||(r="sha1"),"string"==typeof r&&(s=i.getCanonicalAlgName(r),n=i.getHashLength(s),r=function(e){return Se(o.hashHex(Ee(e),s))}),e.length+2*n+2>t)throw"Message too long for RSA";var a,c="";for(a=0;a>3,t,r);if(null==n)return null;var i=this.doPublic(n);if(null==i)return null;var o=i.toString(16);return 1&o.length?"0"+o:o},ne.prototype.type="RSA",ie.prototype.equals=function(e){return e==this||this.q.equals(e.q)&&this.x.equals(e.x)},ie.prototype.toBigInteger=function(){return this.x},ie.prototype.negate=function(){return new ie(this.q,this.x.negate().mod(this.q))},ie.prototype.add=function(e){return new ie(this.q,this.x.add(e.toBigInteger()).mod(this.q))},ie.prototype.subtract=function(e){return new ie(this.q,this.x.subtract(e.toBigInteger()).mod(this.q))},ie.prototype.multiply=function(e){return new ie(this.q,this.x.multiply(e.toBigInteger()).mod(this.q))},ie.prototype.square=function(){return new ie(this.q,this.x.square().mod(this.q))},ie.prototype.divide=function(e){return new ie(this.q,this.x.multiply(e.toBigInteger().modInverse(this.q)).mod(this.q))},oe.prototype.getX=function(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))},oe.prototype.getY=function(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))},oe.prototype.equals=function(e){return e==this||(this.isInfinity()?e.isInfinity():e.isInfinity()?this.isInfinity():!!e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(S.ZERO)&&e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q).equals(S.ZERO))},oe.prototype.isInfinity=function(){return null==this.x&&null==this.y||this.z.equals(S.ZERO)&&!this.y.toBigInteger().equals(S.ZERO)},oe.prototype.negate=function(){return new oe(this.curve,this.x,this.y.negate(),this.z)},oe.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(e.z)).mod(this.curve.q),r=e.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(e.z)).mod(this.curve.q);if(S.ZERO.equals(r))return S.ZERO.equals(t)?this.twice():this.curve.getInfinity();var n=new S("3"),i=this.x.toBigInteger(),o=this.y.toBigInteger(),s=(e.x.toBigInteger(),e.y.toBigInteger(),r.square()),a=s.multiply(r),c=i.multiply(s),l=t.square().multiply(this.z),u=l.subtract(c.shiftLeft(1)).multiply(e.z).subtract(a).multiply(r).mod(this.curve.q),d=c.multiply(n).multiply(t).subtract(o.multiply(a)).subtract(l.multiply(t)).multiply(e.z).add(t.multiply(a)).mod(this.curve.q),h=a.multiply(this.z).multiply(e.z).mod(this.curve.q);return new oe(this.curve,this.curve.fromBigInteger(u),this.curve.fromBigInteger(d),h)},oe.prototype.twice=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=new S("3"),t=this.x.toBigInteger(),r=this.y.toBigInteger(),n=r.multiply(this.z),i=n.multiply(r).mod(this.curve.q),o=this.curve.a.toBigInteger(),s=t.square().multiply(e);S.ZERO.equals(o)||(s=s.add(this.z.square().multiply(o)));var a=(s=s.mod(this.curve.q)).square().subtract(t.shiftLeft(3).multiply(i)).shiftLeft(1).multiply(n).mod(this.curve.q),c=s.multiply(e).multiply(t).subtract(i.shiftLeft(1)).shiftLeft(2).multiply(i).subtract(s.square().multiply(s)).mod(this.curve.q),l=n.square().multiply(n).shiftLeft(3).mod(this.curve.q);return new oe(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(c),l)},oe.prototype.multiply=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new S("3")),i=this.negate(),o=this,s=this.curve.q.subtract(e),a=s.multiply(new S("3")),c=new oe(this.curve,this.x,this.y),l=c.negate();for(t=n.bitLength()-2;t>0;--t){o=o.twice();var u=n.testBit(t);u!=r.testBit(t)&&(o=o.add(u?this:i))}for(t=a.bitLength()-2;t>0;--t){c=c.twice();var d=a.testBit(t);d!=s.testBit(t)&&(c=c.add(d?c:l))}return o},oe.prototype.multiplyTwo=function(e,t,r){var n;n=e.bitLength()>r.bitLength()?e.bitLength()-1:r.bitLength()-1;for(var i=this.curve.getInfinity(),o=this.add(t);n>=0;)i=i.twice(),e.testBit(n)?i=r.testBit(n)?i.add(o):i.add(this):r.testBit(n)&&(i=i.add(t)),--n;return i},se.prototype.getQ=function(){return this.q},se.prototype.getA=function(){return this.a},se.prototype.getB=function(){return this.b},se.prototype.equals=function(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)},se.prototype.getInfinity=function(){return this.infinity},se.prototype.fromBigInteger=function(e){return new ie(this.q,e)},se.prototype.decodePointHex=function(e){switch(parseInt(e.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:default:return null;case 4:case 6:case 7:var t=(e.length-2)/2,r=e.substr(2,t),n=e.substr(t+2,t);return new oe(this,this.fromBigInteger(new S(r,16)),this.fromBigInteger(new S(n,16)))}},ie.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},oe.prototype.getEncoded=function(e){var t=function(e,t){var r=e.toByteArrayUnsigned();if(tr.length;)r.unshift(0);return r},r=this.getX().toBigInteger(),n=this.getY().toBigInteger(),i=t(r,32);return e?n.isEven()?i.unshift(2):i.unshift(3):(i.unshift(4),i=i.concat(t(n,32))),i},oe.decodeFrom=function(e,t){t[0];var r=t.length-1,n=t.slice(1,1+r/2),i=t.slice(1+r/2,1+r);n.unshift(0),i.unshift(0);var o=new S(n),s=new S(i);return new oe(e,e.fromBigInteger(o),e.fromBigInteger(s))},oe.decodeFromHex=function(e,t){t.substr(0,2);var r=t.length-2,n=t.substr(2,r/2),i=t.substr(2+r/2,r/2),o=new S(n,16),s=new S(i,16);return new oe(e,e.fromBigInteger(o),e.fromBigInteger(s))},oe.prototype.add2D=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;if(this.x.equals(e.x))return this.y.equals(e.y)?this.twice():this.curve.getInfinity();var t=e.x.subtract(this.x),r=e.y.subtract(this.y).divide(t),n=r.square().subtract(this.x).subtract(e.x),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new oe(this.curve,n,i)},oe.prototype.twice2D=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=this.curve.fromBigInteger(S.valueOf(2)),t=this.curve.fromBigInteger(S.valueOf(3)),r=this.x.square().multiply(t).add(this.curve.a).divide(this.y.multiply(e)),n=r.square().subtract(this.x.multiply(e)),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new oe(this.curve,n,i)},oe.prototype.multiply2D=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new S("3")),i=this.negate(),o=this;for(t=n.bitLength()-2;t>0;--t){o=o.twice();var s=n.testBit(t);s!=r.testBit(t)&&(o=o.add2D(s?this:i))}return o},oe.prototype.isOnCurve=function(){var e=this.getX().toBigInteger(),t=this.getY().toBigInteger(),r=this.curve.getA().toBigInteger(),n=this.curve.getB().toBigInteger(),i=this.curve.getQ(),o=t.multiply(t).mod(i),s=e.multiply(e).multiply(e).add(r.multiply(e)).add(n).mod(i);return o.equals(s)},oe.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},oe.prototype.validate=function(){var e=this.curve.getQ();if(this.isInfinity())throw new Error("Point is at infinity.");var t=this.getX().toBigInteger(),r=this.getY().toBigInteger();if(t.compareTo(S.ONE)<0||t.compareTo(e.subtract(S.ONE))>0)throw new Error("x coordinate out of bounds");if(r.compareTo(S.ONE)<0||r.compareTo(e.subtract(S.ONE))>0)throw new Error("y coordinate out of bounds");if(!this.isOnCurve())throw new Error("Point is not on the curve.");if(this.multiply(e).isInfinity())throw new Error("Point is not a scalar multiple of G.");return!0};var ae=function(){var e=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)|(?:"(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))*"))',"g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),r={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function n(e,t,n){return t?r[t]:String.fromCharCode(parseInt(n,16))}var i=new String(""),o=Object.hasOwnProperty;return function(r,s){var a,c,l=r.match(e),u=l[0],d=!1;"{"===u?a={}:"["===u?a=[]:(a=[],d=!0);for(var h=[a],p=1-d,g=l.length;p=0;)delete n[i[l]]}return s.call(t,r,n)}({"":a},"")),a}}();void 0!==ce&&ce||(t.KJUR=ce={}),void 0!==ce.asn1&&ce.asn1||(ce.asn1={}),ce.asn1.ASN1Util=new function(){this.integerToByteHex=function(e){var t=e.toString(16);return t.length%2==1&&(t="0"+t),t},this.bigIntToMinTwosComplementsHex=function(e){var t=e.toString(16);if("-"!=t.substr(0,1))t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t);else{var r=t.substr(1).length;r%2==1?r+=1:t.match(/^[0-7]/)||(r+=2);for(var n="",i=0;i15)throw"ASN.1 length too long to represent by 8x: n = "+e.toString(16);return(128+r).toString(16)+t},this.getEncodedHex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getValueHex=function(){return this.getEncodedHex(),this.hV},this.getFreshValueHex=function(){return""},this.setByParam=function(e){this.params=e},null!=e&&null!=e.tlv&&(this.hTLV=e.tlv,this.isModified=!1)},ce.asn1.DERAbstractString=function(e){ce.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=we(this.s).toLowerCase()},this.setStringHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?this.setString(e):void 0!==e.str?this.setString(e.str):void 0!==e.hex&&this.setStringHex(e.hex))},He(ce.asn1.DERAbstractString,ce.asn1.ASN1Object),ce.asn1.DERAbstractTime=function(e){ce.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(e){var t=e.getTime()+6e4*e.getTimezoneOffset();return new Date(t)},this.formatDate=function(e,t,r){var n=this.zeroPadding,i=this.localDateToUTC(e),o=String(i.getFullYear());"utc"==t&&(o=o.substr(2,2));var s=o+n(String(i.getMonth()+1),2)+n(String(i.getDate()),2)+n(String(i.getHours()),2)+n(String(i.getMinutes()),2)+n(String(i.getSeconds()),2);if(!0===r){var a=i.getMilliseconds();if(0!=a){var c=n(String(a),3);s=s+"."+(c=c.replace(/[0]+$/,""))}}return s+"Z"},this.zeroPadding=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=ge(e)},this.setByDateValue=function(e,t,r,n,i,o){var s=new Date(Date.UTC(e,t-1,r,n,i,o,0));this.setByDate(s)},this.getFreshValueHex=function(){return this.hV}},He(ce.asn1.DERAbstractTime,ce.asn1.ASN1Object),ce.asn1.DERAbstractStructured=function(e){ce.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array=e},this.appendASN1Object=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array.push(e)},this.asn1Array=new Array,void 0!==e&&void 0!==e.array&&(this.asn1Array=e.array)},He(ce.asn1.DERAbstractStructured,ce.asn1.ASN1Object),ce.asn1.DERBoolean=function(e){ce.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},He(ce.asn1.DERBoolean,ce.asn1.ASN1Object),ce.asn1.DERInteger=function(e){ce.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=ce.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new S(String(e),10);this.setByBigInteger(t)},this.setValueHex=function(e){this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.bigint?this.setByBigInteger(e.bigint):void 0!==e.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},He(ce.asn1.DERInteger,ce.asn1.ASN1Object),ce.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=ce.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.getEncodedHex()}ce.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(e){this.hTLV=null,this.isModified=!0,this.hV=e},this.setUnusedBitsAndHexValue=function(e,t){if(e<0||7i.length&&(i=n[r]);return(e=e.replace(i,"::")).slice(1,-1)}function De(e){var t="malformed hex value";if(!e.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw t;if(8!=e.length)return 32==e.length?Ne(e):e;try{return parseInt(e.substr(0,2),16)+"."+parseInt(e.substr(2,2),16)+"."+parseInt(e.substr(4,2),16)+"."+parseInt(e.substr(6,2),16)}catch(e){throw t}}function Le(e){return e.match(/.{4}/g).map((function(e){var t=parseInt(e.substr(0,2),16),r=parseInt(e.substr(2),16);if(0==t&r<128)return String.fromCharCode(r);if(t<8){var n=128|63&r;return _e((192|(7&t)<<3|(192&r)>>6).toString(16)+n.toString(16))}n=128|(15&t)<<2|(192&r)>>6;var i=128|63&r;return _e((224|(240&t)>>4).toString(16)+n.toString(16)+i.toString(16))})).join("")}function Ue(e){for(var t=encodeURIComponent(e),r="",n=0;n"7"?"00"+e:e}de.getLblen=function(e,t){if("8"!=e.substr(t+2,1))return 1;var r=parseInt(e.substr(t+3,1));return 0==r?-1:0=n)break}return s},de.getNthChildIdx=function(e,t,r){return de.getChildIdx(e,t)[r]},de.getIdxbyList=function(e,t,r,n){var i,o,s=de;return 0==r.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(i=r.shift())>=(o=s.getChildIdx(e,t)).length?-1:s.getIdxbyList(e,o[i],r,n)},de.getIdxbyListEx=function(e,t,r,n){var i,o,s=de;if(0==r.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;i=r.shift(),o=s.getChildIdx(e,t);for(var a=0,c=0;c=e.length?null:i.getTLV(e,o)},de.getTLVbyListEx=function(e,t,r,n){var i=de,o=i.getIdxbyListEx(e,t,r,n);return-1==o?null:i.getTLV(e,o)},de.getVbyList=function(e,t,r,n,i){var o,s,a=de;return-1==(o=a.getIdxbyList(e,t,r,n))||o>=e.length?null:(s=a.getV(e,o),!0===i&&(s=s.substr(2)),s)},de.getVbyListEx=function(e,t,r,n,i){var o,s,a=de;return-1==(o=a.getIdxbyListEx(e,t,r,n))?null:(s=a.getV(e,o),"03"==e.substr(o,2)&&!1!==i&&(s=s.substr(2)),s)},de.getInt=function(e,t,r){null==r&&(r=-1);try{var n=e.substr(t,2);if("02"!=n&&"03"!=n)return r;var i=de.getV(e,t);return"02"==n?parseInt(i,16):function(e){try{var t=e.substr(0,2);if("00"==t)return parseInt(e.substr(2),16);var r=parseInt(t,16),n=e.substr(2),i=parseInt(n,16).toString(2);return"0"==i&&(i="00000000"),i=i.slice(0,0-r),parseInt(i,2)}catch(e){return-1}}(i)}catch(e){return r}},de.getOID=function(e,t,r){null==r&&(r=null);try{return"06"!=e.substr(t,2)?r:function(e){if(!je(e))return null;try{var t=[],r=e.substr(0,2),n=parseInt(r,16);t[0]=new String(Math.floor(n/40)),t[1]=new String(n%40);for(var i=e.substr(2),o=[],s=0;s0&&(l=l+"."+a.join(".")),l}catch(e){return null}}(de.getV(e,t))}catch(e){return r}},de.getOIDName=function(e,t,r){null==r&&(r=null);try{var n=de.getOID(e,t,r);if(n==r)return r;var i=ce.asn1.x509.OID.oid2name(n);return""==i?n:i}catch(e){return r}},de.getString=function(e,t,r){null==r&&(r=null);try{return Se(de.getV(e,t))}catch(e){return r}},de.hextooidstr=function(e){var t=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},r=[],n=e.substr(0,2),i=parseInt(n,16);r[0]=new String(Math.floor(i/40)),r[1]=new String(i%40);for(var o=e.substr(2),s=[],a=0;a0&&(u=u+"."+c.join(".")),u},de.dump=function(e,t,r,n){var i=de,o=i.getV,s=i.dump,a=i.getChildIdx,c=e;e instanceof ce.asn1.ASN1Object&&(c=e.getEncodedHex());var l=function(e,t){return e.length<=2*t?e:e.substr(0,t)+"..(total "+e.length/2+"bytes).."+e.substr(e.length-t,t)};void 0===t&&(t={ommit_long_octet:32}),void 0===r&&(r=0),void 0===n&&(n="");var u,d=t.ommit_long_octet;if("01"==(u=c.substr(r,2)))return"00"==(h=o(c,r))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==u)return n+"INTEGER "+l(h=o(c,r),d)+"\n";if("03"==u){var h=o(c,r);return i.isASN1HEX(h.substr(2))?(_=n+"BITSTRING, encapsulates\n")+s(h.substr(2),t,0,n+" "):n+"BITSTRING "+l(h,d)+"\n"}if("04"==u)return h=o(c,r),i.isASN1HEX(h)?(_=n+"OCTETSTRING, encapsulates\n")+s(h,t,0,n+" "):n+"OCTETSTRING "+l(h,d)+"\n";if("05"==u)return n+"NULL\n";if("06"==u){var f=o(c,r),p=ce.asn1.ASN1Util.oidHexToInt(f),g=ce.asn1.x509.OID.oid2name(p),y=p.replace(/\./g," ");return""!=g?n+"ObjectIdentifier "+g+" ("+y+")\n":n+"ObjectIdentifier ("+y+")\n"}if("0a"==u)return n+"ENUMERATED "+parseInt(o(c,r))+"\n";if("0c"==u)return n+"UTF8String '"+_e(o(c,r))+"'\n";if("13"==u)return n+"PrintableString '"+_e(o(c,r))+"'\n";if("14"==u)return n+"TeletexString '"+_e(o(c,r))+"'\n";if("16"==u)return n+"IA5String '"+_e(o(c,r))+"'\n";if("17"==u)return n+"UTCTime "+_e(o(c,r))+"\n";if("18"==u)return n+"GeneralizedTime "+_e(o(c,r))+"\n";if("1a"==u)return n+"VisualString '"+_e(o(c,r))+"'\n";if("1e"==u)return n+"BMPString '"+Le(o(c,r))+"'\n";if("30"==u){if("3000"==c.substr(r,4))return n+"SEQUENCE {}\n";_=n+"SEQUENCE\n";var m=t;if((2==(w=a(c,r)).length||3==w.length)&&"06"==c.substr(w[0],2)&&"04"==c.substr(w[w.length-1],2)){g=i.oidname(o(c,w[0]));var v=JSON.parse(JSON.stringify(t));v.x509ExtName=g,m=v}for(var b=0;b31)&&128==(192&r)&&(31&r)==n}catch(e){return!1}},de.isASN1HEX=function(e){var t=de;if(e.length%2==1)return!1;var r=t.getVblen(e,0),n=e.substr(0,2),i=t.getL(e,0);return e.length-n.length-i.length==2*r},de.checkStrictDER=function(e,t,r,n,i){var o=de;if(void 0===r){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!ce.lang.String.isHex(e))throw new Error("not hex string");r=e.length,i=(n=e.length/2)<128?1:Math.ceil(n.toString(16))+1}if(o.getL(e,t).length>2*i)throw new Error("L of TLV too long: idx="+t);var s=o.getVblen(e,t);if(s>n)throw new Error("value of L too long than hex: idx="+t);var a=o.getTLV(e,t),c=a.length-2-o.getL(e,t).length;if(c!==2*s)throw new Error("V string length and L's value not the same:"+c+"/"+2*s);if(0===t&&e.length!=a.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+a.length);var l=e.substr(t,2);if("02"===l){var u=o.getVidx(e,t);if("00"==e.substr(u,2)&&e.charCodeAt(u+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(l,16)){for(var d=o.getVblen(e,t),h=0,f=o.getChildIdx(e,t),p=0;p=t?e:new Array(t-e.length+1).join(r)+e};function He(e,t){var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.superclass=t.prototype,t.prototype.constructor==Object.prototype.constructor&&(t.prototype.constructor=t)}void 0!==ce&&ce||(t.KJUR=ce={}),void 0!==ce.crypto&&ce.crypto||(ce.crypto={}),ce.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414"},this.DEFAULTPROVIDER={md5:"cryptojs",sha1:"cryptojs",sha224:"cryptojs",sha256:"cryptojs",sha384:"cryptojs",sha512:"cryptojs",ripemd160:"cryptojs",hmacmd5:"cryptojs",hmacsha1:"cryptojs",hmacsha224:"cryptojs",hmacsha256:"cryptojs",hmacsha384:"cryptojs",hmacsha512:"cryptojs",hmacripemd160:"cryptojs",MD5withRSA:"cryptojs/jsrsa",SHA1withRSA:"cryptojs/jsrsa",SHA224withRSA:"cryptojs/jsrsa",SHA256withRSA:"cryptojs/jsrsa",SHA384withRSA:"cryptojs/jsrsa",SHA512withRSA:"cryptojs/jsrsa",RIPEMD160withRSA:"cryptojs/jsrsa",MD5withECDSA:"cryptojs/jsrsa",SHA1withECDSA:"cryptojs/jsrsa",SHA224withECDSA:"cryptojs/jsrsa",SHA256withECDSA:"cryptojs/jsrsa",SHA384withECDSA:"cryptojs/jsrsa",SHA512withECDSA:"cryptojs/jsrsa",RIPEMD160withECDSA:"cryptojs/jsrsa",SHA1withDSA:"cryptojs/jsrsa",SHA224withDSA:"cryptojs/jsrsa",SHA256withDSA:"cryptojs/jsrsa",MD5withRSAandMGF1:"cryptojs/jsrsa",SHAwithRSAandMGF1:"cryptojs/jsrsa",SHA1withRSAandMGF1:"cryptojs/jsrsa",SHA224withRSAandMGF1:"cryptojs/jsrsa",SHA256withRSAandMGF1:"cryptojs/jsrsa",SHA384withRSAandMGF1:"cryptojs/jsrsa",SHA512withRSAandMGF1:"cryptojs/jsrsa",RIPEMD160withRSAandMGF1:"cryptojs/jsrsa"},this.CRYPTOJSMESSAGEDIGESTNAME={md5:y.algo.MD5,sha1:y.algo.SHA1,sha224:y.algo.SHA224,sha256:y.algo.SHA256,sha384:y.algo.SHA384,sha512:y.algo.SHA512,ripemd160:y.algo.RIPEMD160},this.getDigestInfoHex=function(e,t){if(void 0===this.DIGESTINFOHEAD[t])throw"alg not supported in Util.DIGESTINFOHEAD: "+t;return this.DIGESTINFOHEAD[t]+e},this.getPaddedDigestInfoHex=function(e,t,r){var n=this.getDigestInfoHex(e,t),i=r/4;if(n.length+22>i)throw"key is too short for SigAlg: keylen="+r+","+t;for(var o="00"+n,s="",a=i-4-o.length,c=0;c=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(o)>=0)return!1;var a=n.modInverse(o),c=e.multiply(a).mod(o),l=t.multiply(a).mod(o);return s.multiply(c).add(i.multiply(l)).getX().toBigInteger().mod(o).equals(t)},this.serializeSig=function(e,t){var r=e.toByteArraySigned(),n=t.toByteArraySigned(),i=[];return i.push(2),i.push(r.length),(i=i.concat(r)).push(2),i.push(n.length),(i=i.concat(n)).unshift(i.length),i.unshift(48),i},this.parseSig=function(e){var t;if(48!=e[0])throw new Error("Signature not a valid DERSequence");if(2!=e[t=2])throw new Error("First element in signature must be a DERInteger");var n=e.slice(t+2,t+2+e[t+1]);if(2!=e[t+=2+e[t+1]])throw new Error("Second element in signature must be a DERInteger");var i=e.slice(t+2,t+2+e[t+1]);return t+=2+e[t+1],{r:r.fromByteArrayUnsigned(n),s:r.fromByteArrayUnsigned(i)}},this.parseSigCompact=function(e){if(65!==e.length)throw"Signature has the wrong length";var t=e[0]-27;if(t<0||t>7)throw"Invalid signature type";var n=this.ecparams.n;return{r:r.fromByteArrayUnsigned(e.slice(1,33)).mod(n),s:r.fromByteArrayUnsigned(e.slice(33,65)).mod(n),i:t}},this.readPKCS5PrvKeyHex=function(e){if(!1===l(e))throw new Error("not ASN.1 hex string");var t,r,n;try{t=c(e,0,["[0]",0],"06"),r=c(e,0,[1],"04");try{n=c(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=s(t),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(r),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n,i;try{c(e,0,[1,0],"06"),r=c(e,0,[1,1],"06"),n=c(e,0,[2,0,1],"04");try{i=c(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=s(r),void 0===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n;try{c(e,0,[0,0],"06"),r=c(e,0,[0,1],"06"),n=c(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=s(r),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,r){if(!1===l(e))throw new t("not ASN.1 hex string");var n,i;try{n=c(e,0,[0,5,0,1],"06"),i=c(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=s(n),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i)},void 0!==e&&void 0!==e.curve&&(this.curveName=e.curve),void 0===this.curveName&&(this.curveName="secp256r1"),this.setNamedCurve(this.curveName),void 0!==e&&(void 0!==e.prv&&this.setPrivateKeyHex(e.prv),void 0!==e.pub&&this.setPublicKeyHex(e.pub))},ce.crypto.ECDSA.parseSigHex=function(e){var t=ce.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new S(t.r,16),s:new S(t.s,16)}},ce.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=de,r=t.getChildIdx,n=t.getV;if(t.checkStrictDER(e,0),"30"!=e.substr(0,2))throw new Error("signature is not a ASN.1 sequence");var i=r(e,0);if(2!=i.length)throw new Error("signature shall have two elements");var o=i[0],s=i[1];if("02"!=e.substr(o,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(s,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,o),s:n(e,s)}},ce.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=ce.crypto.ECDSA.parseSigHexInHexRS(e),r=t.r,n=t.s;if("00"==r.substr(0,2)&&r.length%32==2&&(r=r.substr(2)),"00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),r.length%32==30&&(r="00"+r),n.length%32==30&&(n="00"+n),r.length%32!=0)throw"unknown ECDSA sig r length error";if(n.length%32!=0)throw"unknown ECDSA sig s length error";return r+n},ce.crypto.ECDSA.concatSigToASN1Sig=function(e){if(e.length/2*8%128!=0)throw"unknown ECDSA concatinated r-s sig length error";var t=e.substr(0,e.length/2),r=e.substr(e.length/2);return ce.crypto.ECDSA.hexRSSigToASN1Sig(t,r)},ce.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var r=new S(e,16),n=new S(t,16);return ce.crypto.ECDSA.biRSSigToASN1Sig(r,n)},ce.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var r=ce.asn1,n=new r.DERInteger({bigint:e}),i=new r.DERInteger({bigint:t});return new r.DERSequence({array:[n,i]}).getEncodedHex()},ce.crypto.ECDSA.getName=function(e){return"2b8104001f"===e?"secp192k1":"2a8648ce3d030107"===e?"secp256r1":"2b8104000a"===e?"secp256k1":"2b81040021"===e?"secp224r1":"2b81040022"===e?"secp384r1":-1!=="|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(e)?"secp256r1":-1!=="|secp256k1|".indexOf(e)?"secp256k1":-1!=="|secp224r1|NIST P-224|P-224|".indexOf(e)?"secp224r1":-1!=="|secp384r1|NIST P-384|P-384|".indexOf(e)?"secp384r1":null},void 0!==ce&&ce||(t.KJUR=ce={}),void 0!==ce.crypto&&ce.crypto||(ce.crypto={}),ce.crypto.ECParameterDB=new function(){var e={},t={};function r(e){return new S(e,16)}this.getByName=function(r){var n=r;if(void 0!==t[n]&&(n=t[r]),void 0!==e[n])return e[n];throw"unregistered EC curve name: "+n},this.regist=function(n,i,o,s,a,c,l,u,d,h,f,p){e[n]={};var g=r(o),y=r(s),m=r(a),v=r(c),b=r(l),w=new se(g,y,m),_=w.decodePointHex("04"+u+d);e[n].name=n,e[n].keylen=i,e[n].curve=w,e[n].G=_,e[n].n=v,e[n].h=b,e[n].oid=f,e[n].info=p;for(var S=0;S=2*a)break}var d={};return d.keyhex=c.substr(0,2*i[e].keylen),d.ivhex=c.substr(2*i[e].keylen,2*i[e].ivlen),d},a=function(e,t,r,n){var o=y.enc.Base64.parse(e),s=y.enc.Hex.stringify(o);return(0,i[t].proc)(s,r,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return o(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,r){return s(e,t,r)},decryptKeyB64:function(e,t,r,n){return a(e,t,r,n)},getDecryptedKeyHex:function(e,t){var r=o(e),n=(r.type,r.cipher),i=r.ivsalt,c=r.data,l=s(n,t,i).keyhex;return a(c,n,l,i)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,r,n,o){var a="";if(void 0!==n&&null!=n||(n="AES-256-CBC"),void 0===i[n])throw new Error("KEYUTIL unsupported algorithm: "+n);void 0!==o&&null!=o||(o=function(e){var t=y.lib.WordArray.random(e);return y.enc.Hex.stringify(t)}(i[n].ivlen).toUpperCase());var c=function(e,t,r,n){return(0,i[t].eproc)(e,r,n)}(t,n,s(n,r,o).keyhex,o);return a="-----BEGIN "+e+" PRIVATE KEY-----\r\n",a+="Proc-Type: 4,ENCRYPTED\r\n",a+="DEK-Info: "+n+","+o+"\r\n",a+="\r\n",(a+=c.replace(/(.{64})/g,"$1\r\n"))+"\r\n-----END "+e+" PRIVATE KEY-----\r\n"},parseHexOfEncryptedPKCS8:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={},o=r(e,0);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+o.length);i.ciphertext=n(e,o[1]);var s=r(e,o[0]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+s.length);if("2a864886f70d01050d"!=n(e,s[0]))throw new Error("this only supports pkcs5PBES2");var a=r(e,s[1]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+a.length);var c=r(e,a[1]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+c.length);if("2a864886f70d0307"!=n(e,c[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=n(e,c[1]);var l=r(e,a[0]);if(2!=l.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+l.length);if("2a864886f70d01050c"!=n(e,l[0]))throw new Error("this only supports pkcs5PBKDF2");var u=r(e,l[1]);if(u.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+u.length);i.pbkdf2Salt=n(e,u[0]);var d=n(e,u[1]);try{i.pbkdf2Iter=parseInt(d,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+d)}return i},getPBKDF2KeyHexFromParam:function(e,t){var r=y.enc.Hex.parse(e.pbkdf2Salt),n=e.pbkdf2Iter,i=y.PBKDF2(t,r,{keySize:6,iterations:n});return y.enc.Hex.stringify(i)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(e,t){var r=xe(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(r),i=We.getPBKDF2KeyHexFromParam(n,t),o={};o.ciphertext=y.enc.Hex.parse(n.ciphertext);var s=y.enc.Hex.parse(i),a=y.enc.Hex.parse(n.encryptionSchemeIV),c=y.TripleDES.decrypt(o,s,{iv:a});return y.enc.Hex.stringify(c)},getKeyFromEncryptedPKCS8PEM:function(e,t){var r=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(r)},parsePlainPrivatePKCS8Hex:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={algparam:null};if("30"!=e.substr(0,2))throw new Error("malformed plain PKCS8 private key(code:001)");var o=r(e,0);if(o.length<3)throw new Error("malformed plain PKCS8 private key(code:002)");if("30"!=e.substr(o[1],2))throw new Error("malformed PKCS8 private key(code:003)");var s=r(e,o[1]);if(2!=s.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(s[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(i.algoid=n(e,s[0]),"06"==e.substr(s[1],2)&&(i.algparam=n(e,s[1])),"04"!=e.substr(o[2],2))throw new Error("malformed PKCS8 private key(code:006)");return i.keyidx=t.getVidx(e,o[2]),i},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=xe(e,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(t)},getKeyFromPlainPrivatePKCS8Hex:function(e){var t,r=this.parsePlainPrivatePKCS8Hex(e);if("2a864886f70d010101"==r.algoid)t=new ne;else if("2a8648ce380401"==r.algoid)t=new ce.crypto.DSA;else{if("2a8648ce3d0201"!=r.algoid)throw new Error("unsupported private key algorithm");t=new ce.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,r=de.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===r)t=new ne;else if("2a8648ce380401"===r)t=new ce.crypto.DSA;else{if("2a8648ce3d0201"!==r)throw new Error("unsupported PKCS#8 public key hex");t=new ce.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var o=r(e,0);if(2!=o.length)throw new Error("malformed RSA key(code:002)");if("02"!=e.substr(o[0],2))throw new Error("malformed RSA key(code:003)");if(i.n=n(e,o[0]),"02"!=e.substr(o[1],2))throw new Error("malformed RSA key(code:004)");return i.e=n(e,o[1]),i},parsePublicPKCS8Hex:function(e){var t=de,r=t.getChildIdx,n=t.getV,i={algparam:null},o=r(e,0);if(2!=o.length)throw new Error("outer DERSequence shall have 2 elements: "+o.length);var s=o[0];if("30"!=e.substr(s,2))throw new Error("malformed PKCS8 public key(code:001)");var a=r(e,s);if(2!=a.length)throw new Error("malformed PKCS8 public key(code:002)");if("06"!=e.substr(a[0],2))throw new Error("malformed PKCS8 public key(code:003)");if(i.algoid=n(e,a[0]),"06"==e.substr(a[1],2)?i.algparam=n(e,a[1]):"30"==e.substr(a[1],2)&&(i.algparam={},i.algparam.p=t.getVbyList(e,a[1],[0],"02"),i.algparam.q=t.getVbyList(e,a[1],[1],"02"),i.algparam.g=t.getVbyList(e,a[1],[2],"02")),"03"!=e.substr(o[1],2))throw new Error("malformed PKCS8 public key(code:004)");return i.key=n(e,o[1]).substr(2),i}}}();function $e(e,t){for(var r="",n=t/4-e.length,i=0;i>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function Ke(e){for(var t in ce.crypto.Util.DIGESTINFOHEAD){var r=ce.crypto.Util.DIGESTINFOHEAD[t],n=r.length;if(e.substring(0,n)==r)return[t,e.substring(n)]}return[]}function Je(e){var t,r=de,n=r.getChildIdx,i=r.getV,o=r.getTLV,s=r.getVbyList,a=r.getVbyListEx,c=r.getTLVbyList,l=r.getTLVbyListEx,u=r.getIdxbyList,d=r.getIdxbyListEx,h=r.getVidx,f=r.getInt,p=r.oidname,g=r.hextooidstr,y=xe;try{t=ce.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV}catch(e){}this.HEX2STAG={"0c":"utf8",13:"prn",16:"ia5","1a":"vis","1e":"bmp"},this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){if(null===this.hex||0!==this.version)return this.version;var e=c(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=c(e,0,[0]),r=f(t,0);if(r<0||21){var a=o(e,s[1]),c=this.getGeneralName(a);null!=c.uri&&(i.uri=c.uri)}if(s.length>2){var l=o(e,s[2]);"0101ff"==l&&(i.reqauth=!0),"010100"==l&&(i.reqauth=!1)}return i},this.getX500NameRule=function(e){for(var t=null,r=[],n=0;n0&&(e.ext=this.getExtParamArray()),e.sighex=this.getSignatureValueHex(),e},this.getExtParamArray=function(e){null==e&&-1!=d(this.hex,0,[0,"[3]"])&&(e=l(this.hex,0,[0,"[3]",0],"30"));for(var t=[],r=n(e,0),i=0;i2&&"04"===y.substr(g[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(P=new a).readPKCS5PrvKeyHex(y)}return P}if("pkcs8prv"===r)return d.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===r)return d._getKeyFromPublicPKCS8Hex(e);if("x509pub"===r)return Je.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return Je.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var v=xe(e,"PUBLIC KEY");return d._getKeyFromPublicPKCS8Hex(v)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var b=u(e,"RSA PRIVATE KEY");return d.getKey(b,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var w=o(n=u(e,"DSA PRIVATE KEY"),0,[1],"02"),_=o(n,0,[2],"02"),E=o(n,0,[3],"02"),A=o(n,0,[4],"02"),R=o(n,0,[5],"02");return(P=new c).setPrivate(new S(w,16),new S(_,16),new S(E,16),new S(A,16),new S(R,16)),P}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED"))return b=u(e,"EC PRIVATE KEY"),d.getKey(b,null,"pkcs5prv");if(-1!=e.indexOf("-END PRIVATE KEY-"))return d.getKeyFromPlainPrivatePKCS8PEM(e);if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var I=d.getDecryptedKeyHex(e,t),T=new ne;return T.readPKCS5PrvKeyHex(I),T}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var x,P=o(n=d.getDecryptedKeyHex(e,t),0,[1],"04"),C=o(n,0,[2,0],"06"),k=o(n,0,[3,0],"03").substr(2);if(void 0===ce.crypto.OID.oidhex2name[C])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+C);return(x=new a({curve:ce.crypto.OID.oidhex2name[C]})).setPublicKeyHex(k),x.setPrivateKeyHex(P),x.isPublic=!1,x}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED"))return w=o(n=d.getDecryptedKeyHex(e,t),0,[1],"02"),_=o(n,0,[2],"02"),E=o(n,0,[3],"02"),A=o(n,0,[4],"02"),R=o(n,0,[5],"02"),(P=new c).setPrivate(new S(w,16),new S(_,16),new S(E,16),new S(A,16),new S(R,16)),P;if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return d.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},We.generateKeypair=function(e,t){if("RSA"==e){var r=t;(s=new ne).generate(r,"10001"),s.isPrivate=!0,s.isPublic=!0;var n=new ne,i=s.n.toString(16),o=s.e.toString(16);return n.setPublic(i,o),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}if("EC"==e){var s,a,c=t,l=new ce.crypto.ECDSA({curve:c}).generateKeyPairHex();return(s=new ce.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),s.setPrivateKeyHex(l.ecprvhex),s.isPrivate=!0,s.isPublic=!1,(n=new ce.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}throw new Error("unknown algorithm: "+e)},We.getPEM=function(e,t,r,n,i,o){var s=ce,a=s.asn1,c=a.DERObjectIdentifier,l=a.DERInteger,u=a.ASN1Util.newObject,d=a.x509.SubjectPublicKeyInfo,h=s.crypto,f=h.DSA,p=h.ECDSA,g=ne;function m(e){return u({seq:[{int:0},{int:{bigint:e.n}},{int:e.e},{int:{bigint:e.d}},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.dmp1}},{int:{bigint:e.dmq1}},{int:{bigint:e.coeff}}]})}function v(e){return u({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a0",!0,{oid:{name:e.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]})}function b(e){return u({seq:[{int:0},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}},{int:{bigint:e.y}},{int:{bigint:e.x}}]})}if((void 0!==g&&e instanceof g||void 0!==f&&e instanceof f||void 0!==p&&e instanceof p)&&1==e.isPublic&&(void 0===t||"PKCS8PUB"==t))return Te(E=new d(e).getEncodedHex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===r||null==r)&&1==e.isPrivate)return Te(E=m(e).getEncodedHex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===r||null==r)&&1==e.isPrivate){var w=new c({name:e.curveName}).getEncodedHex(),_=v(e).getEncodedHex(),S="";return(S+=Te(w,"EC PARAMETERS"))+Te(_,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==f&&e instanceof f&&(void 0===r||null==r)&&1==e.isPrivate)return Te(E=b(e).getEncodedHex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==r&&null!=r&&1==e.isPrivate){var E=m(e).getEncodedHex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",E,r,n,o)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==r&&null!=r&&1==e.isPrivate)return E=v(e).getEncodedHex(),void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",E,r,n,o);if("PKCS5PRV"==t&&void 0!==f&&e instanceof f&&void 0!==r&&null!=r&&1==e.isPrivate)return E=b(e).getEncodedHex(),void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",E,r,n,o);var A=function(e,t){var r=R(e,t);return new u({seq:[{seq:[{oid:{name:"pkcs5PBES2"}},{seq:[{seq:[{oid:{name:"pkcs5PBKDF2"}},{seq:[{octstr:{hex:r.pbkdf2Salt}},{int:r.pbkdf2Iter}]}]},{seq:[{oid:{name:"des-EDE3-CBC"}},{octstr:{hex:r.encryptionSchemeIV}}]}]}]},{octstr:{hex:r.ciphertext}}]}).getEncodedHex()},R=function(e,t){var r=y.lib.WordArray.random(8),n=y.lib.WordArray.random(8),i=y.PBKDF2(t,r,{keySize:6,iterations:100}),o=y.enc.Hex.parse(e),s=y.TripleDES.encrypt(o,i,{iv:n})+"",a={};return a.ciphertext=s,a.pbkdf2Salt=y.enc.Hex.stringify(r),a.pbkdf2Iter=100,a.encryptionSchemeAlg="DES-EDE3-CBC",a.encryptionSchemeIV=y.enc.Hex.stringify(n),a};if("PKCS8PRV"==t&&null!=g&&e instanceof g&&1==e.isPrivate){var I=m(e).getEncodedHex();return E=u({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:I}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=A(E,r),"ENCRYPTED PRIVATE KEY")}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate)return I=new u({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]}).getEncodedHex(),E=u({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:I}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=A(E,r),"ENCRYPTED PRIVATE KEY");if("PKCS8PRV"==t&&void 0!==f&&e instanceof f&&1==e.isPrivate)return I=new l({bigint:e.x}).getEncodedHex(),E=u({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:I}}]}).getEncodedHex(),void 0===r||null==r?Te(E,"PRIVATE KEY"):Te(_=A(E,r),"ENCRYPTED PRIVATE KEY");throw new Error("unsupported object nor format")},We.getKeyFromCSRPEM=function(e){var t=xe(e,"CERTIFICATE REQUEST");return We.getKeyFromCSRHex(t)},We.getKeyFromCSRHex=function(e){var t=We.parseCSRHex(e);return We.getKey(t.p8pubkeyhex,null,"pkcs8pub")},We.parseCSRHex=function(e){var t=de,r=t.getChildIdx,n=t.getTLV,i={},o=e;if("30"!=o.substr(0,2))throw new Error("malformed CSR(code:001)");var s=r(o,0);if(s.length<1)throw new Error("malformed CSR(code:002)");if("30"!=o.substr(s[0],2))throw new Error("malformed CSR(code:003)");var a=r(o,s[0]);if(a.length<3)throw new Error("malformed CSR(code:004)");return i.p8pubkeyhex=n(o,a[2]),i},We.getKeyID=function(e){var t=We,r=de;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=xe(t.getPEM(e)),i=r.getIdxbyList(n,0,[1]),o=r.getV(n,i).substring(2);return ce.crypto.Util.hashHex(o,"sha1")},We.getJWKFromKey=function(e){var t={};if(e instanceof ne&&e.isPrivate)return t.kty="RSA",t.n=ve(e.n.toString(16)),t.e=ve(e.e.toString(16)),t.d=ve(e.d.toString(16)),t.p=ve(e.p.toString(16)),t.q=ve(e.q.toString(16)),t.dp=ve(e.dmp1.toString(16)),t.dq=ve(e.dmq1.toString(16)),t.qi=ve(e.coeff.toString(16)),t;if(e instanceof ne&&e.isPublic)return t.kty="RSA",t.n=ve(e.n.toString(16)),t.e=ve(e.e.toString(16)),t;if(e instanceof ce.crypto.ECDSA&&e.isPrivate){if("P-256"!==(n=e.getShortNISTPCurveName())&&"P-384"!==n)throw new Error("unsupported curve name for JWT: "+n);var r=e.getPublicKeyXYHex();return t.kty="EC",t.crv=n,t.x=ve(r.x),t.y=ve(r.y),t.d=ve(e.prvKeyHex),t}if(e instanceof ce.crypto.ECDSA&&e.isPublic){var n;if("P-256"!==(n=e.getShortNISTPCurveName())&&"P-384"!==n)throw new Error("unsupported curve name for JWT: "+n);return r=e.getPublicKeyXYHex(),t.kty="EC",t.crv=n,t.x=ve(r.x),t.y=ve(r.y),t}throw new Error("not supported key object")},ne.getPosArrayOfChildrenFromHex=function(e){return de.getChildIdx(e,0)},ne.getHexValueArrayOfChildrenFromHex=function(e){var t,r=de.getV,n=r(e,(t=ne.getPosArrayOfChildrenFromHex(e))[0]),i=r(e,t[1]),o=r(e,t[2]),s=r(e,t[3]),a=r(e,t[4]),c=r(e,t[5]),l=r(e,t[6]),u=r(e,t[7]),d=r(e,t[8]);return(t=new Array).push(n,i,o,s,a,c,l,u,d),t},ne.prototype.readPrivateKeyFromPEMString=function(e){var t=xe(e),r=ne.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8])},ne.prototype.readPKCS5PrvKeyHex=function(e){var t=ne.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},ne.prototype.readPKCS8PrvKeyHex=function(e){var t,r,n,i,o,s,a,c,l=de,u=l.getVbyListEx;if(!1===l.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=u(e,0,[2,0,1],"02"),r=u(e,0,[2,0,2],"02"),n=u(e,0,[2,0,3],"02"),i=u(e,0,[2,0,4],"02"),o=u(e,0,[2,0,5],"02"),s=u(e,0,[2,0,6],"02"),a=u(e,0,[2,0,7],"02"),c=u(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,r,n,i,o,s,a,c)},ne.prototype.readPKCS5PubKeyHex=function(e){var t=de,r=t.getV;if(!1===t.isASN1HEX(e))throw new Error("keyHex is not ASN.1 hex string");var n=t.getChildIdx(e,0);if(2!==n.length||"02"!==e.substr(n[0],2)||"02"!==e.substr(n[1],2))throw new Error("wrong hex for PKCS#5 public key");var i=r(e,n[0]),o=r(e,n[1]);this.setPublic(i,o)},ne.prototype.readPKCS8PubKeyHex=function(e){var t=de;if(!1===t.isASN1HEX(e))throw new Error("not ASN.1 hex string");if("06092a864886f70d010101"!==t.getTLVbyListEx(e,0,[0,0]))throw new Error("not PKCS8 RSA public key");var r=t.getTLVbyListEx(e,0,[1,0]);this.readPKCS5PubKeyHex(r)},ne.prototype.readCertPubKeyHex=function(e,t){var r,n;(r=new Je).readCertHex(e),n=r.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)},new RegExp("[^0-9a-f]","gi"),ne.prototype.sign=function(e,t){var r=function(e){return ce.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(r,t)},ne.prototype.signWithMessageHash=function(e,t){var r=te(ce.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return $e(this.doPrivate(r).toString(16),this.n.bitLength())},ne.prototype.signPSS=function(e,t,r){var n=function(e){return ce.crypto.Util.hashHex(e,t)}(Ee(e));return void 0===r&&(r=-1),this.signWithMessageHashPSS(n,t,r)},ne.prototype.signWithMessageHashPSS=function(e,t,r){var n,i=Se(e),o=i.length,s=this.n.bitLength()-1,a=Math.ceil(s/8),c=function(e){return ce.crypto.Util.hashHex(e,t)};if(-1===r||void 0===r)r=o;else if(-2===r)r=a-o-2;else if(r<-2)throw new Error("invalid salt length");if(a0&&(l=new Array(r),(new ee).nextBytes(l),l=String.fromCharCode.apply(String,l));var u=Se(c(Ee("\0\0\0\0\0\0\0\0"+i+l))),d=[];for(n=0;n>8*a-s&255;for(p[0]&=~g,n=0;nn)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var o=Ke(i.replace(/^1f+00/,""));if(0==o.length)return!1;var s=o[0];return o[1]==function(e){return ce.crypto.Util.hashString(e,s)}(e)},ne.prototype.verifyWithMessageHash=function(e,t){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var r=te(t,16);if(r.bitLength()>this.n.bitLength())return 0;var n=Ke(this.doPublic(r).toString(16).replace(/^1f+00/,""));return 0!=n.length&&(n[0],n[1]==e)},ne.prototype.verifyPSS=function(e,t,r,n){var i=function(e){return ce.crypto.Util.hashHex(e,r)}(Ee(e));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(i,t,r,n)},ne.prototype.verifyWithMessageHashPSS=function(e,t,r,n){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var i,o=new S(t,16),s=function(e){return ce.crypto.Util.hashHex(e,r)},a=Se(e),c=a.length,l=this.n.bitLength()-1,u=Math.ceil(l/8);if(-1===n||void 0===n)n=c;else if(-2===n)n=u-c-2;else if(n<-2)throw new Error("invalid salt length");if(u>8*u-l&255;if(h.charCodeAt(0)&p)throw new Error("bits beyond keysize not zero");var g=Ve(f,h.length,s),y=[];for(i=0;i0&&-1==(":"+r.join(":")+":").indexOf(":"+m+":"))throw"algorithm '"+m+"' not accepted in the list";if("none"!=m&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=We.getKey(t)),!("RS"!=h&&"PS"!=h||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==h&&!(t instanceof c))throw"key shall be a ECDSA obj for ES* algs";var v=null;if(void 0===o.jwsalg2sigalg[y.alg])throw"unsupported alg name: "+m;if("none"==(v=o.jwsalg2sigalg[m]))throw"not supported";if("Hmac"==v.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var b=new l({alg:v,pass:t});return b.updateString(p),g==b.doFinal()}if(-1!=v.indexOf("withECDSA")){var w,_=null;try{_=c.concatSigToASN1Sig(g)}catch(e){return!1}return(w=new u({alg:v})).init(t),w.updateString(p),w.verify(_)}return(w=new u({alg:v})).init(t),w.updateString(p),w.verify(g)},ce.jws.JWS.parse=function(e){var t,r,n,i=e.split("."),o={};if(2!=i.length&&3!=i.length)throw"malformed sJWS: wrong number of '.' splitted elements";return t=i[0],r=i[1],3==i.length&&(n=i[2]),o.headerObj=ce.jws.JWS.readSafeJSONString(ue(t)),o.payloadObj=ce.jws.JWS.readSafeJSONString(ue(r)),o.headerPP=JSON.stringify(o.headerObj,null," "),null==o.payloadObj?o.payloadPP=ue(r):o.payloadPP=JSON.stringify(o.payloadObj,null," "),void 0!==n&&(o.sigHex=be(n)),o},ce.jws.JWS.verifyJWT=function(e,t,r){var n=ce.jws,i=n.JWS,o=i.readSafeJSONString,s=i.inArray,a=i.includedArray,c=e.split("."),l=c[0],u=c[1],d=(be(c[2]),o(ue(l))),h=o(ue(u));if(void 0===d.alg)return!1;if(void 0===r.alg)throw"acceptField.alg shall be specified";if(!s(d.alg,r.alg))return!1;if(void 0!==h.iss&&"object"===f(r.iss)&&!s(h.iss,r.iss))return!1;if(void 0!==h.sub&&"object"===f(r.sub)&&!s(h.sub,r.sub))return!1;if(void 0!==h.aud&&"object"===f(r.aud))if("string"==typeof h.aud){if(!s(h.aud,r.aud))return!1}else if("object"==f(h.aud)&&!a(h.aud,r.aud))return!1;var p=n.IntDate.getNow();return void 0!==r.verifyAt&&"number"==typeof r.verifyAt&&(p=r.verifyAt),void 0!==r.gracePeriod&&"number"==typeof r.gracePeriod||(r.gracePeriod=0),!(void 0!==h.exp&&"number"==typeof h.exp&&h.exp+r.gracePeriodt.length&&(r=t.length);for(var n=0;n=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function p(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0: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 W(e).length;default:if(n)return H(e).length;t=(""+t).toLowerCase(),n=!0}}function g(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,r);case"utf8":case"utf-8":return I(this,t,r);case"ascii":return x(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return R(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function m(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(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:v(e,t,r,n,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,n,i){var o,s=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;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var u=-1;for(o=r;oa&&(r=a-c),o=r;o>=0;o--){for(var d=!0,h=0;hi&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function R(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function I(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:l>223?3:l>191?2:1;if(i+d<=r)switch(d){case 1:l<128&&(u=l);break;case 2:128==(192&(o=e[i+1]))&&(c=(31&l)<<6|63&o)>127&&(u=c);break;case 3:o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(c=(15&l)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(u=c);break;case 4:o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&l)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(u=c)}null===u?(u=65533,d=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),i+=d}return function(e){var t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);for(var r="",n=0;n0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},c.prototype.compare=function(e,t,r,n,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");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;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(o,s),l=this.slice(n,i),u=e.slice(t,r),d=0;di)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return b(this,e,t,r);case"utf8":case"utf-8":return w(this,e,t,r);case"ascii":return _(this,e,t,r);case"latin1":case"binary":return S(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(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)}};var T=4096;function x(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function F(e,t,r,n,i,o){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function D(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function L(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 U(e,t,r,n,o){return o||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,o){return o||L(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},c.prototype.readUInt8=function(e,t){return t||O(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||O(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||O(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},c.prototype.readInt8=function(e,t){return t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||O(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){t||O(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return t||O(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 t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||O(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||O(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||O(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||O(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,r,n){e=+e,t|=0,r|=0,n||F(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+r},c.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):D(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);F(this,e,t,r,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),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||F(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):D(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||F(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+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=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(M,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function $(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}}).call(this,r(29))},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){"use strict";t.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=c(e),s=n[0],a=n[1],l=new o(function(e,t,r){return 3*(t+r)/4-r}(0,s,a)),u=0,d=a>0?s-4:s;for(r=0;r>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,l[u++]=255&t),1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],s=16383,a=0,c=r-i;ac?c:a+s));return 1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)n[a]=s[a],i[s.charCodeAt(a)]=a;function c(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 l(e,t,r){for(var i,o,s=[],a=t;a>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,c=(1<>1,u=-7,d=r?i-1:0,h=r?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-u)-1,f>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=l}return(f?-1:1)*s*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var s,a,c,l=8*o-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,i),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(s=s<0;e[r+f]=255&s,f+=p,s/=256,l-=8);e[r+f-p]|=128*g}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.jws,r=e.KeyUtil,i=e.X509,o=e.crypto,s=e.hextob64u,a=e.b64tohex,c=e.AllowedSigningAlgs;return function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return e.parseJwt=function e(r){n.Log.debug("JoseUtil.parseJwt");try{var i=t.JWS.parse(r);return{header:i.headerObj,payload:i.payloadObj}}catch(e){n.Log.error(e)}},e.validateJwt=function(t,o,s,c,l,u,d){n.Log.debug("JoseUtil.validateJwt");try{if("RSA"===o.kty)if(o.e&&o.n)o=r.getKey(o);else{if(!o.x5c||!o.x5c.length)return n.Log.error("JoseUtil.validateJwt: RSA key missing key material",o),Promise.reject(new Error("RSA key missing key material"));var h=a(o.x5c[0]);o=i.getPublicKeyFromCertHex(h)}else{if("EC"!==o.kty)return n.Log.error("JoseUtil.validateJwt: Unsupported key type",o&&o.kty),Promise.reject(new Error(o.kty));if(!(o.crv&&o.x&&o.y))return n.Log.error("JoseUtil.validateJwt: EC key missing key material",o),Promise.reject(new Error("EC key missing key material"));o=r.getKey(o)}return e._validateJwt(t,o,s,c,l,u,d)}catch(e){return n.Log.error(e&&e.message||e),Promise.reject("JWT validation failed")}},e.validateJwtAttributes=function(t,r,i,o,s,a){o||(o=0),s||(s=parseInt(Date.now()/1e3));var c=e.parseJwt(t).payload;if(!c.iss)return n.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(c.iss!==r)return n.Log.error("JoseUtil._validateJwt: Invalid issuer in token",c.iss),Promise.reject(new Error("Invalid issuer in token: "+c.iss));if(!c.aud)return n.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(c.aud===i||Array.isArray(c.aud)&&c.aud.indexOf(i)>=0))return n.Log.error("JoseUtil._validateJwt: Invalid audience in token",c.aud),Promise.reject(new Error("Invalid audience in token: "+c.aud));if(c.azp&&c.azp!==i)return n.Log.error("JoseUtil._validateJwt: Invalid azp in token",c.azp),Promise.reject(new Error("Invalid azp in token: "+c.azp));if(!a){var l=s+o,u=s-o;if(!c.iat)return n.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(l1&&void 0!==arguments[1]?arguments[1]:"#";!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var n=i.UrlUtility.parseUrlFragment(t,r);this.error=n.error,this.error_description=n.error_description,this.error_uri=n.error_uri,this.code=n.code,this.state=n.state,this.id_token=n.id_token,this.session_state=n.session_state,this.access_token=n.access_token,this.token_type=n.token_type,this.scope=n.scope,this.profile=void 0,this.expires_in=n.expires_in}return n(e,[{key:"expires_in",get:function(){if(this.expires_at){var e=parseInt(Date.now()/1e3);return this.expires_at-e}},set:function(e){var t=parseInt(e);if("number"==typeof t&&t>0){var r=parseInt(Date.now()/1e3);this.expires_at=r+t}}},{key:"expired",get:function(){var e=this.expires_in;if(void 0!==e)return e<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignoutRequest=void 0;var n=r(0),i=r(3),o=r(9);t.SignoutRequest=function e(t){var r=t.url,s=t.id_token_hint,a=t.post_logout_redirect_uri,c=t.data,l=t.extraQueryParams,u=t.request_type;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!r)throw n.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var d in s&&(r=i.UrlUtility.addQueryParam(r,"id_token_hint",s)),a&&(r=i.UrlUtility.addQueryParam(r,"post_logout_redirect_uri",a),c&&(this.state=new o.State({data:c,request_type:u}),r=i.UrlUtility.addQueryParam(r,"state",this.state.id))),l)r=i.UrlUtility.addQueryParam(r,d,l[d]);this.url=r}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignoutResponse=void 0;var n=r(3);t.SignoutResponse=function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var r=n.UrlUtility.parseUrlFragment(t,"?");this.error=r.error,this.error_description=r.error_description,this.error_uri=r.error_uri,this.state=r.state}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InMemoryWebStorage=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:l.SilentRenewService,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u.SessionMonitor,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:h.TokenRevocationClient,d=arguments.length>4&&void 0!==arguments[4]?arguments[4]:f.TokenClient,g=arguments.length>5&&void 0!==arguments[5]?arguments[5]:p.JoseUtil;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,t),r instanceof s.UserManagerSettings||(r=new s.UserManagerSettings(r));var y=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r));return y._events=new c.UserManagerEvents(r),y._silentRenewService=new n(y),y.settings.automaticSilentRenew&&(i.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),y.startSilentRenew()),y.settings.monitorSession&&(i.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),y._sessionMonitor=new o(y)),y._tokenRevocationClient=new a(y._settings),y._tokenClient=new d(y._settings),y._joseUtil=g,y}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.getUser=function(){var e=this;return this._loadUser().then((function(t){return t?(i.Log.info("UserManager.getUser: user loaded"),e._events.load(t,!1),t):(i.Log.info("UserManager.getUser: user not found in storage"),null)}))},t.prototype.removeUser=function(){var e=this;return this.storeUser(null).then((function(){i.Log.info("UserManager.removeUser: user removed from storage"),e._events.unload()}))},t.prototype.signinRedirect=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="si:r";var t={useReplaceToNavigate:e.useReplaceToNavigate};return this._signinStart(e,this._redirectNavigator,t).then((function(){i.Log.info("UserManager.signinRedirect: successful")}))},t.prototype.signinRedirectCallback=function(e){return this._signinEnd(e||this._redirectNavigator.url).then((function(e){return e.profile&&e.profile.sub?i.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinRedirectCallback: no sub"),e}))},t.prototype.signinPopup=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="si:p";var t=e.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return t?(e.redirect_uri=t,e.display="popup",this._signin(e,this._popupNavigator,{startUrl:t,popupWindowFeatures:e.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:e.popupWindowTarget||this.settings.popupWindowTarget}).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinPopup: no sub")),e}))):(i.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},t.prototype.signinPopupCallback=function(e){return this._signinCallback(e,this._popupNavigator).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinPopupCallback: no sub")),e})).catch((function(e){i.Log.error(e.message)}))},t.prototype.signinSilent=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=Object.assign({},t),this._loadUser().then((function(r){return r&&r.refresh_token?(t.refresh_token=r.refresh_token,e._useRefreshToken(t)):(t.request_type="si:s",t.id_token_hint=t.id_token_hint||e.settings.includeIdTokenInSilentRenew&&r&&r.id_token,r&&e._settings.validateSubOnSilentRenew&&(i.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",r.profile.sub),t.current_sub=r.profile.sub),e._signinSilentIframe(t))}))},t.prototype._useRefreshToken=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(t).then((function(t){return t?t.access_token?e._loadUser().then((function(r){if(r){var n=Promise.resolve();return t.id_token&&(n=e._validateIdTokenFromTokenRefreshToken(r.profile,t.id_token)),n.then((function(){return i.Log.debug("UserManager._useRefreshToken: refresh token response success"),r.id_token=t.id_token||r.id_token,r.access_token=t.access_token,r.refresh_token=t.refresh_token||r.refresh_token,r.expires_in=t.expires_in,e.storeUser(r).then((function(){return e._events.load(r),r}))}))}return null})):(i.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(i.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},t.prototype._validateIdTokenFromTokenRefreshToken=function(e,t){var r=this;return this._metadataService.getIssuer().then((function(n){return r.settings.getEpochTime().then((function(o){return r._joseUtil.validateJwtAttributes(t,n,r._settings.client_id,r._settings.clockSkew,o).then((function(t){return t?t.sub!==e.sub?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub"),Promise.reject(new Error("sub in id_token does not match current sub"))):t.auth_time&&t.auth_time!==e.auth_time?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time"),Promise.reject(new Error("auth_time in id_token does not match original auth_time"))):t.azp&&t.azp!==e.azp?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp"),Promise.reject(new Error("azp in id_token does not match original azp"))):!t.azp&&e.azp?(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token"),Promise.reject(new Error("azp not in id_token, but present in original id_token"))):void 0:(i.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},t.prototype._signinSilentIframe=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return t?(e.redirect_uri=t,e.prompt=e.prompt||"none",this._signin(e,this._iframeNavigator,{startUrl:t,silentRequestTimeout:e.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinSilent: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinSilent: no sub")),e}))):(i.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},t.prototype.signinSilentCallback=function(e){return this._signinCallback(e,this._iframeNavigator).then((function(e){return e&&(e.profile&&e.profile.sub?i.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",e.profile.sub):i.Log.info("UserManager.signinSilentCallback: no sub")),e}))},t.prototype.signinCallback=function(e){var t=this;return this.readSigninResponseState(e).then((function(r){var n=r.state;return r.response,"si:r"===n.request_type?t.signinRedirectCallback(e):"si:p"===n.request_type?t.signinPopupCallback(e):"si:s"===n.request_type?t.signinSilentCallback(e):Promise.reject(new Error("invalid response_type in state"))}))},t.prototype.signoutCallback=function(e,t){var r=this;return this.readSignoutResponseState(e).then((function(n){var i=n.state,o=n.response;return i?"so:r"===i.request_type?r.signoutRedirectCallback(e):"so:p"===i.request_type?r.signoutPopupCallback(e,t):Promise.reject(new Error("invalid response_type in state")):o}))},t.prototype.querySessionStatus=function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(t=Object.assign({},t)).request_type="si:s";var r=t.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return r?(t.redirect_uri=r,t.prompt="none",t.response_type=t.response_type||this.settings.query_status_response_type,t.scope=t.scope||"openid",t.skipUserInfo=!0,this._signinStart(t,this._iframeNavigator,{startUrl:r,silentRequestTimeout:t.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(t){return e.processSigninResponse(t.url).then((function(e){if(i.Log.debug("UserManager.querySessionStatus: got signin response"),e.session_state&&e.profile.sub)return i.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",e.profile.sub),{session_state:e.session_state,sub:e.profile.sub,sid:e.profile.sid};i.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(t){if(t.session_state&&e.settings.monitorAnonymousSession&&("login_required"==t.message||"consent_required"==t.message||"interaction_required"==t.message||"account_selection_required"==t.message))return i.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:t.session_state};throw t}))}))):(i.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},t.prototype._signin=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signinStart(e,t,n).then((function(t){return r._signinEnd(t.url,e)}))},t.prototype._signinStart=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return t.prepare(n).then((function(t){return i.Log.debug("UserManager._signinStart: got navigator window handle"),r.createSigninRequest(e).then((function(e){return i.Log.debug("UserManager._signinStart: got signin request"),n.url=e.url,n.id=e.state.id,t.navigate(n)})).catch((function(e){throw t.close&&(i.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),t.close()),e}))}))},t.prototype._signinEnd=function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.processSigninResponse(e).then((function(e){i.Log.debug("UserManager._signinEnd: got signin response");var n=new a.User(e);if(r.current_sub){if(r.current_sub!==n.profile.sub)return i.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",n.profile.sub),Promise.reject(new Error("login_required"));i.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return t.storeUser(n).then((function(){return i.Log.debug("UserManager._signinEnd: user stored"),t._events.load(n),n}))}))},t.prototype._signinCallback=function(e,t){i.Log.debug("UserManager._signinCallback");var r="query"===this._settings.response_mode||!this._settings.response_mode&&d.SigninRequest.isCode(this._settings.response_type)?"?":"#";return t.callback(e,void 0,r)},t.prototype.signoutRedirect=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="so:r";var t=e.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;t&&(e.post_logout_redirect_uri=t);var r={useReplaceToNavigate:e.useReplaceToNavigate};return this._signoutStart(e,this._redirectNavigator,r).then((function(){i.Log.info("UserManager.signoutRedirect: successful")}))},t.prototype.signoutRedirectCallback=function(e){return this._signoutEnd(e||this._redirectNavigator.url).then((function(e){return i.Log.info("UserManager.signoutRedirectCallback: successful"),e}))},t.prototype.signoutPopup=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e=Object.assign({},e)).request_type="so:p";var t=e.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return e.post_logout_redirect_uri=t,e.display="popup",e.post_logout_redirect_uri&&(e.state=e.state||{}),this._signout(e,this._popupNavigator,{startUrl:t,popupWindowFeatures:e.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:e.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){i.Log.info("UserManager.signoutPopup: successful")}))},t.prototype.signoutPopupCallback=function(e,t){return void 0===t&&"boolean"==typeof e&&(t=e,e=null),this._popupNavigator.callback(e,t,"?").then((function(){i.Log.info("UserManager.signoutPopupCallback: successful")}))},t.prototype._signout=function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signoutStart(e,t,n).then((function(e){return r._signoutEnd(e.url)}))},t.prototype._signoutStart=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return arguments[1].prepare(r).then((function(n){return i.Log.debug("UserManager._signoutStart: got navigator window handle"),t._loadUser().then((function(o){return i.Log.debug("UserManager._signoutStart: loaded current user from storage"),(t._settings.revokeAccessTokenOnSignout?t._revokeInternal(o):Promise.resolve()).then((function(){var s=e.id_token_hint||o&&o.id_token;return s&&(i.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),e.id_token_hint=s),t.removeUser().then((function(){return i.Log.debug("UserManager._signoutStart: user removed, creating signout request"),t.createSignoutRequest(e).then((function(e){return i.Log.debug("UserManager._signoutStart: got signout request"),r.url=e.url,e.state&&(r.id=e.state.id),n.navigate(r)}))}))}))})).catch((function(e){throw n.close&&(i.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),n.close()),e}))}))},t.prototype._signoutEnd=function(e){return this.processSignoutResponse(e).then((function(e){return i.Log.debug("UserManager._signoutEnd: got signout response"),e}))},t.prototype.revokeAccessToken=function(){var e=this;return this._loadUser().then((function(t){return e._revokeInternal(t,!0).then((function(r){if(r)return i.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),t.access_token=null,t.refresh_token=null,t.expires_at=null,t.token_type=null,e.storeUser(t).then((function(){i.Log.debug("UserManager.revokeAccessToken: user stored"),e._events.load(t)}))}))})).then((function(){i.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},t.prototype._revokeInternal=function(e,t){var r=this;if(e){var n=e.access_token,o=e.refresh_token;return this._revokeAccessTokenInternal(n,t).then((function(e){return r._revokeRefreshTokenInternal(o,t).then((function(t){return e||t||i.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),e||t}))}))}return Promise.resolve(!1)},t.prototype._revokeAccessTokenInternal=function(e,t){return!e||e.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(e,t).then((function(){return!0}))},t.prototype._revokeRefreshTokenInternal=function(e,t){return e?this._tokenRevocationClient.revoke(e,t,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},t.prototype.startSilentRenew=function(){this._silentRenewService.start()},t.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},t.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(e){return e?(i.Log.debug("UserManager._loadUser: user storageString loaded"),a.User.fromStorageString(e)):(i.Log.debug("UserManager._loadUser: no user storageString"),null)}))},t.prototype.storeUser=function(e){if(e){i.Log.debug("UserManager.storeUser: storing user");var t=e.toStorageString();return this._userStore.set(this._userStoreKey,t)}return i.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},n(t,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),t}(o.OidcClient)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManagerSettings=void 0;var n=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=r.popup_redirect_uri,i=r.popup_post_logout_redirect_uri,d=r.popupWindowFeatures,h=r.popupWindowTarget,f=r.silent_redirect_uri,p=r.silentRequestTimeout,g=r.automaticSilentRenew,y=void 0!==g&&g,m=r.validateSubOnSilentRenew,v=void 0!==m&&m,b=r.includeIdTokenInSilentRenew,w=void 0===b||b,_=r.monitorSession,S=void 0===_||_,E=r.monitorAnonymousSession,A=void 0!==E&&E,R=r.checkSessionInterval,I=void 0===R?2e3:R,T=r.stopCheckSessionOnError,x=void 0===T||T,P=r.query_status_response_type,C=r.revokeAccessTokenOnSignout,k=void 0!==C&&C,O=r.accessTokenExpiringNotificationTime,F=void 0===O?60:O,N=r.redirectNavigator,D=void 0===N?new o.RedirectNavigator:N,L=r.popupNavigator,U=void 0===L?new s.PopupNavigator:L,j=r.iframeNavigator,M=void 0===j?new a.IFrameNavigator:j,B=r.userStore,H=void 0===B?new c.WebStorageStateStore({store:l.Global.sessionStorage}):B;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var W=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,arguments[0]));return W._popup_redirect_uri=n,W._popup_post_logout_redirect_uri=i,W._popupWindowFeatures=d,W._popupWindowTarget=h,W._silent_redirect_uri=f,W._silentRequestTimeout=p,W._automaticSilentRenew=y,W._validateSubOnSilentRenew=v,W._includeIdTokenInSilentRenew=w,W._accessTokenExpiringNotificationTime=F,W._monitorSession=S,W._monitorAnonymousSession=A,W._checkSessionInterval=I,W._stopCheckSessionOnError=x,P?W._query_status_response_type=P:arguments[0]&&arguments[0].response_type?W._query_status_response_type=u.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":W._query_status_response_type="id_token",W._revokeAccessTokenOnSignout=k,W._redirectNavigator=D,W._popupNavigator=U,W._iframeNavigator=M,W._userStore=H,W}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),n(t,[{key:"popup_redirect_uri",get:function(){return this._popup_redirect_uri}},{key:"popup_post_logout_redirect_uri",get:function(){return this._popup_post_logout_redirect_uri}},{key:"popupWindowFeatures",get:function(){return this._popupWindowFeatures}},{key:"popupWindowTarget",get:function(){return this._popupWindowTarget}},{key:"silent_redirect_uri",get:function(){return this._silent_redirect_uri}},{key:"silentRequestTimeout",get:function(){return this._silentRequestTimeout}},{key:"automaticSilentRenew",get:function(){return this._automaticSilentRenew}},{key:"validateSubOnSilentRenew",get:function(){return this._validateSubOnSilentRenew}},{key:"includeIdTokenInSilentRenew",get:function(){return this._includeIdTokenInSilentRenew}},{key:"accessTokenExpiringNotificationTime",get:function(){return this._accessTokenExpiringNotificationTime}},{key:"monitorSession",get:function(){return this._monitorSession}},{key:"monitorAnonymousSession",get:function(){return this._monitorAnonymousSession}},{key:"checkSessionInterval",get:function(){return this._checkSessionInterval}},{key:"stopCheckSessionOnError",get:function(){return this._stopCheckSessionOnError}},{key:"query_status_response_type",get:function(){return this._query_status_response_type}},{key:"revokeAccessTokenOnSignout",get:function(){return this._revokeAccessTokenOnSignout}},{key:"redirectNavigator",get:function(){return this._redirectNavigator}},{key:"popupNavigator",get:function(){return this._popupNavigator}},{key:"iframeNavigator",get:function(){return this._iframeNavigator}},{key:"userStore",get:function(){return this._userStore}}]),t}(i.OidcClientSettings)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedirectNavigator=void 0;var n=function(){function e(e,t){for(var r=0;r1&&void 0!==arguments[1])||arguments[1];n.Log.debug("UserManagerEvents.load"),e.prototype.load.call(this,t),r&&this._userLoaded.raise(t)},t.prototype.unload=function(){n.Log.debug("UserManagerEvents.unload"),e.prototype.unload.call(this),this._userUnloaded.raise()},t.prototype.addUserLoaded=function(e){this._userLoaded.addHandler(e)},t.prototype.removeUserLoaded=function(e){this._userLoaded.removeHandler(e)},t.prototype.addUserUnloaded=function(e){this._userUnloaded.addHandler(e)},t.prototype.removeUserUnloaded=function(e){this._userUnloaded.removeHandler(e)},t.prototype.addSilentRenewError=function(e){this._silentRenewError.addHandler(e)},t.prototype.removeSilentRenewError=function(e){this._silentRenewError.removeHandler(e)},t.prototype._raiseSilentRenewError=function(e){n.Log.debug("UserManagerEvents._raiseSilentRenewError",e.message),this._silentRenewError.raise(e)},t.prototype.addUserSignedIn=function(e){this._userSignedIn.addHandler(e)},t.prototype.removeUserSignedIn=function(e){this._userSignedIn.removeHandler(e)},t.prototype._raiseUserSignedIn=function(){n.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},t.prototype.addUserSignedOut=function(e){this._userSignedOut.addHandler(e)},t.prototype.removeUserSignedOut=function(e){this._userSignedOut.removeHandler(e)},t.prototype._raiseUserSignedOut=function(){n.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},t.prototype.addUserSessionChanged=function(e){this._userSessionChanged.addHandler(e)},t.prototype.removeUserSessionChanged=function(e){this._userSessionChanged.removeHandler(e)},t.prototype._raiseUserSessionChanged=function(){n.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},t}(i.AccessTokenEvents)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timer=void 0;var n=function(){function e(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:o.Global.timer,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var s=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,e.call(this,r));return s._timer=n,s._nowFunc=i||function(){return Date.now()/1e3},s}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t.prototype.init=function(e){e<=0&&(e=1),e=parseInt(e);var t=this.now+e;if(this.expiration===t&&this._timerHandle)i.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),i.Log.debug("Timer.init timer "+this._name+" for duration:",e),this._expiration=t;var r=5;e{var r,i;await this.sessionInfoManager.clear(e.sessionId);const o=null!==(r=e.redirectUrl)&&void 0!==r?r:s.normalizeCallbackUrl(window.location.href);if(!n.isValidRedirectUrl(o))throw new Error(`${o} 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:o,clientName:null!==(i=e.clientName)&&void 0!==i?i:e.clientId,eventEmitter:t})},this.validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return void 0===t||void 0===t.clientAppId||void 0===t.issuer?null:t},this.handleIncomingRedirect=async(e,t)=>{try{const r=await this.redirectHandler.handle(e,t);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}}catch(r){return await this.cleanUrlAfterRedirect(e),void t.emit(n.EVENTS.ERROR,"redirect",r)}}}async cleanUrlAfterRedirect(e){const t=n.removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise((e=>{setTimeout((()=>e()),1)}))}}function u(e){return"string"==typeof e.oidcIssuer}function d(e){return"string"==typeof e.redirectUrl}class h{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 u(e)&&d(e)}async handle(e){if(!u(e))throw new n.ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!d(e))throw new n.ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),r=await n.handleRegistration(e,t,this.storageUtility,this.clientRegistrar),i={issuer:t.issuer,dpop:"dpop"===e.tokenType.toLowerCase(),...e,issuerConfiguration:t,client:r};return this.oidcHandler.handle(i)}}class f extends n.AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){var t;const r={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl.toString(),post_logout_redirect_uri:e.redirectUrl.toString(),response_type:"code",scope:n.DEFAULT_SCOPES,filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:null!==(t=e.prompt)&&void 0!==t?t:"consent"},i=new s.OidcClient(r);try{const t=await i.createSigninRequest();return await this.handleRedirect({oidcLoginOptions:e,state:t.state._id,codeVerifier:t.state._code_verifier,targetUrl:t.url.toString()})}catch(e){console.error(e)}}}const p={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 g{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,i=await a.fetch.call(globalThis,r);try{t=function(e){const t={};return Object.keys(e).forEach((r=>{p[r]&&(t[p[r].toKey]=e[r])})),Array.isArray(t.scopesSupported)||(t.scopesSupported=["openid"]),t}(await i.json())}catch(t){throw new n.ConfigurationError(`[${e.toString()}] has an invalid configuration: ${t.message}`)}return await this.storageUtility.set(g.getLocalStorageKey(e),JSON.stringify(t)),t}}class y extends n.SessionInfoManagerBase{async get(e){const[t,r,i,o,s,a,c,l]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1})]);if("string"!=typeof s||n.isValidRedirectUrl(s)){if(void 0!==l&&!n.isSupportedTokenType(l))throw new Error(`Tokens of type [${l}] are not supported.`);if(void 0!==i||void 0!==t||void 0!==r||void 0!==a)return{sessionId:e,webId:r,isLoggedIn:"true"===t,redirectUrl:s,refreshToken:a,issuer:c,clientAppId:i,clientAppSecret:o,tokenType:null!=l?l:"DPoP"}}else await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})])}async clear(e){return async function(e,t){await n.clear(e,t),await s.clearOidcPersistentStorage()}(e,this.storageUtility)}}class m{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 n.getUnauthenticatedSession()}}const v=(...e)=>a.fetch.call(globalThis,...e);class b{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),i=r.searchParams.get("state"),o=await this.storageUtility.getForUser(i,"sessionId",{errorIfNull:!0}),{issuerConfig:a,codeVerifier:c,redirectUrl:l,dpop:u}=await n.loadOidcContextFromStorage(o,this.storageUtility,this.issuerConfigFetcher),d=r.searchParams.get("iss");if("string"==typeof d&&d!==a.issuer)throw new Error(`The value of the iss parameter (${d}) does not match the issuer identifier of the authorization server (${a.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(void 0===c)throw new Error(`The code verifier for session ${o} is missing from storage.`);if(void 0===l)throw new Error(`The redirect URL for session ${o} is missing from storage.`);const h=await this.clientRegistrar.getClient({sessionId:o},a);let f;const p=Date.now();let g;u?(f=await s.getDpopToken(a,h,{grantType:"authorization_code",code:r.searchParams.get("code"),codeVerifier:c,redirectUrl:l}),window.localStorage.removeItem(`oidc.${i}`)):f=await s.getBearerToken(r.toString()),void 0!==f.refreshToken&&(g={sessionId:o,refreshToken:f.refreshToken,tokenRefresher:this.tokerRefresher});const y=await n.buildAuthenticatedFetch(v,f.accessToken,{dpopKey:f.dpopKey,refreshOptions:g,eventEmitter:t,expiresIn:f.expiresIn});await this.storageUtility.setForUser(o,{webId:f.webId,isLoggedIn:"true"},{secure:!0});const m=await this.sessionInfoManager.get(o);if(!m)throw new Error(`Could not retrieve session: [${o}].`);return Object.assign(m,{fetch:y,getLogoutUrl:n.maybeBuildRpInitiatedLogout({idTokenHint:f.idToken,endSessionEndpoint:a.endSessionEndpoint}),expirationDate:"number"==typeof f.expiresIn?p+1e3*f.expiresIn:void 0})}}class w extends n.AggregateHandler{constructor(e){super(e)}}class _{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 S{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class E{constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[r,n]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1})]);if(r)return{clientId:r,clientSecret:n,clientType:"dynamic"};try{const r=await s.registerClient(e,t),n={clientId:r.clientId};return r.clientSecret&&(n.clientSecret=r.clientSecret),r.idTokenSignedResponseAlg&&(n.idTokenSignedResponseAlg=r.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,n,{secure:!1}),r}catch(e){throw new Error(`Client registration failed: [${e}]`)}}}class A{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),i=r.searchParams.get("error"),o=r.searchParams.get("error_description");t.emit(n.EVENTS.ERROR,i,o)}return n.getUnauthenticatedSession()}}class R{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,i){const o=await n.loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),a=await this.clientRegistrar.getClient({sessionId:e},o.issuerConfig);if(void 0===t)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(o.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 c=await s.refresh(t,o.issuerConfig,a,r);return void 0!==c.refreshToken&&(null==i||i.emit(n.EVENTS.NEW_REFRESH_TOKEN,c.refreshToken),await this.storageUtility.setForUser(e,{refreshToken:c.refreshToken})),c}}function I(e){const t=new n.InMemoryStorage,r=e.secureStorage||t,i=e.insecureStorage||new _,o=new c(r,i),s=new g(o),a=new E(o),u=new y(o),d=new R(o,s,a),p=new S,v=new h(o,new f(o,p),s,a),I=new w([new A,new b(o,u,s,a,d),new m]);return new l(v,I,new n.IWaterfallLogoutHandler(u,p),u,s)}const T=`${n.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,x=`${n.SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;class P extends o{constructor(e={},t=void 0){super(),this.tokenRequestInProgress=!1,this.login=async e=>{var t;return await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:null!==(t=e.tokenType)&&void 0!==t?t:"DPoP"},this.events),new Promise((()=>{}))},this.fetch=(e,t)=>this.clientAuthentication.fetch(e,t),this.internalLogout=async(e,t)=>{window.localStorage.removeItem(T),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(n.EVENTS.LOGOUT)},this.logout=async e=>this.internalLogout(!0,e),this.handleIncomingRedirect=async(e={})=>{var t;if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const r="string"==typeof e?{url:e}:e,i=null!==(t=r.url)&&void 0!==t?t:window.location.href;this.tokenRequestInProgress=!0;const o=await this.clientAuthentication.handleIncomingRedirect(i,this.events);if(function(e){return!!(null==e?void 0:e.isLoggedIn)}(o)){this.setSessionInfo(o);const e=window.localStorage.getItem(x);null===e?this.events.emit(n.EVENTS.LOGIN):(window.localStorage.removeItem(x),this.events.emit(n.EVENTS.SESSION_RESTORED,e))}else if(!0===r.restorePreviousSession){const e=window.localStorage.getItem(T);if(null!==e){const t=await async function(e,t,r){var n;const i=await t.validateCurrentSession(e);return null!==i&&(window.localStorage.setItem(x,window.location.href),await t.login({sessionId:e,prompt:"none",oidcIssuer:i.issuer,redirectUrl:i.redirectUrl,clientId:i.clientAppId,clientSecret:i.clientAppSecret,tokenType:null!==(n=i.tokenType)&&void 0!==n?n:"DPoP"},r.events),!0)}(e,this.clientAuthentication,this);if(t)return new Promise((()=>{}))}}return this.tokenRequestInProgress=!1,o},this.events=new Proxy(this,n.buildProxyHandler(P.prototype,"events only implements ISessionEventListener")),e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=I({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage}):this.clientAuthentication=I({}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId}:this.info={sessionId:null!=t?t:i.v4(),isLoggedIn:!1},this.events.on(n.EVENTS.LOGIN,(()=>window.localStorage.setItem(T,this.info.sessionId))),this.events.on(n.EVENTS.SESSION_EXPIRED,(()=>this.internalLogout(!1))),this.events.on(n.EVENTS.ERROR,(()=>this.internalLogout(!1)))}onLogin(e){this.events.on(n.EVENTS.LOGIN,e)}onLogout(e){this.events.on(n.EVENTS.LOGOUT,e)}onError(e){this.events.on(n.EVENTS.ERROR,e)}onSessionRestore(e){this.events.on(n.EVENTS.SESSION_RESTORED,e)}onSessionExpiration(e){this.events.on(n.EVENTS.SESSION_EXPIRED,e)}setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.expirationDate=e.expirationDate,this.events.on(n.EVENTS.SESSION_EXTENDED,(e=>{this.info.expirationDate=Date.now()+1e3*e}))}}let C;function k(){return void 0===C&&(C=new P),C}Object.defineProperty(t,"ConfigurationError",{enumerable:!0,get:function(){return n.ConfigurationError}}),Object.defineProperty(t,"EVENTS",{enumerable:!0,get:function(){return n.EVENTS}}),Object.defineProperty(t,"InMemoryStorage",{enumerable:!0,get:function(){return n.InMemoryStorage}}),Object.defineProperty(t,"NotImplementedError",{enumerable:!0,get:function(){return n.NotImplementedError}}),t.Session=P,t.events=()=>k().events,t.fetch=(...e)=>k().fetch(...e),t.getClientAuthenticationWithDependencies=I,t.getDefaultSession=k,t.handleIncomingRedirect=(...e)=>k().handleIncomingRedirect(...e),t.login=(...e)=>k().login(...e),t.logout=(...e)=>k().logout(...e),t.onLogin=(...e)=>k().onLogin(...e),t.onLogout=(...e)=>k().onLogout(...e),t.onSessionRestore=(...e)=>k().onSessionRestore(...e)},4667:function(e,t,r){"use strict";var n=r(7007),i=r(5914),o=r(6438),s=r(2831);const a=["ES256","RS256"],c={ERROR:"error",LOGIN:"login",LOGOUT:"logout",NEW_REFRESH_TOKEN:"newRefreshToken",SESSION_EXPIRED:"sessionExpired",SESSION_EXTENDED:"sessionExtended",SESSION_RESTORED:"sessionRestore",TIMEOUT_SET:"timeoutSet"},l=["openid","offline_access","webid"].join(" ");async function u(e,t){const r=await i.fetch.call(globalThis,e);if(200!==r.status)throw new Error(`Could not fetch JWKS for [${t}] at [${e}]: ${r.status} ${r.statusText}`);let n;try{n=(await r.json()).keys[0]}catch(r){throw new Error(`Malformed JWKS for [${t}] at [${e}]: ${r.message}`)}return n}class d{constructor(e){this.sessionInfoManager=e,this.sessionInfoManager=e}async canHandle(){return!0}async handle(e){await this.sessionInfoManager.clear(e)}}class h{constructor(e){this.redirector=e,this.redirector=e}async canHandle(e,t){return"idp"===(null==t?void 0:t.logoutType)}async handle(e,t){if("idp"!==(null==t?void 0: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})}}async function f(e,t){await Promise.all([t.deleteAllUserData(e,{secure:!1}),t.deleteAllUserData(e,{secure:!0})])}function p({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()}function g(e){try{return new URL(e),!0}catch(e){return!1}}const y=(e,t)=>i.fetch.call(globalThis,e,t);class m{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((null==t?void 0:t.secure)?this.secureStorage:this.insecureStorage).get(e);if(void 0===r&&(null==t?void 0:t.errorIfNull))throw new Error(`[${e}] is not stored`);return r}async set(e,t,r){return((null==r?void 0:r.secure)?this.secureStorage:this.insecureStorage).set(e,t)}async delete(e,t){return((null==t?void 0:t.secure)?this.secureStorage:this.insecureStorage).delete(e)}async getForUser(e,t,r){const n=await this.getUserData(e,null==r?void 0:r.secure);let i;if(n&&n[t]||(i=void 0),i=n[t],void 0===i&&(null==r?void 0: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,null==r?void 0:r.secure)}catch(e){n={}}await this.setUserData(e,{...n,...t},null==r?void 0:r.secure)}async deleteForUser(e,t,r){const n=await this.getUserData(e,null==r?void 0:r.secure);delete n[t],await this.setUserData(e,n,null==r?void 0:r.secure)}async deleteAllUserData(e,t){await((null==t?void 0:t.secure)?this.secureStorage:this.insecureStorage).delete(this.getKey(e))}}class v extends Error{constructor(e){super(e)}}class b extends Error{constructor(e){super(`[${e}] is not implemented`)}}class w extends Error{constructor(e){super(`Invalid response from OIDC provider: missing fields ${e}`),this.missingFields=e}}class _ extends Error{constructor(e,t,r){super(e),this.error=t,this.errorDescription=r}}function S(e){const t=new URL(e);return new URL(t.pathname,t.origin).toString()}async function E(e,t,r){return new o.SignJWT({htu:S(e),htm:t.toUpperCase(),jti:s.v4()}).setProtectedHeader({alg:a[0],jwk:r.publicKey,typ:"dpop+jwt"}).setIssuedAt().sign(r.privateKey,{})}async function A(e,t,r,n,o){return e(r,await async function(e,t,r,n){if(void 0!==r)return async function(e,t,r,n){var o;const s=new i.Headers(null==n?void 0:n.headers);return s.set("Authorization",`DPoP ${t}`),s.set("DPoP",await E(e,null!==(o=null==n?void 0:n.method)&&void 0!==o?o:"get",r)),{...n,headers:s}}(e,t,r,n);const o=new i.Headers(null==n?void 0:n.headers);return o.set("Authorization",`Bearer ${t}`),{...n,headers:o}}(r.toString(),t,o,n))}const R=e=>void 0!==e?e-5>0?e-5:e:600,I="getResponse",T={get:async(e,t)=>I,set:async(e,t)=>{},delete:async e=>{},getForUser:async(e,t,r)=>I,setForUser:async(e,t,r)=>{},deleteForUser:async(e,t,r)=>{},deleteAllUserData:async(e,t)=>{}},x=e=>{const t=e;return{get:async e=>{if(void 0!==t[e])return"string"==typeof t[e]?t[e]:JSON.stringify(t[e])},set:async(e,r)=>{t[e]=r},delete:async e=>{delete t[e]}}};t.AggregateHandler=class{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{try{return JSON.stringify(e)}catch(t){return e.toString()}})).join(", ")}`)}},t.AuthorizationCodeWithPkceOidcHandlerBase=class{constructor(e,t){this.storageUtility=e,this.redirector=t,this.storageUtility=e,this.redirector=t}async canHandle(e){return!!(e.issuerConfiguration.grantTypesSupported&&e.issuerConfiguration.grantTypesSupported.indexOf("authorization_code")>-1)}async handleRedirect({oidcLoginOptions:e,state:t,codeVerifier:r,targetUrl:n}){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:e.dpop?"true":"false"})]),this.redirector.redirect(n,{handleRedirect:e.handleRedirect})}},t.ClientAuthentication=class{constructor(e,t,r,n,i){this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i,this.fetch=y,this.logout=async(e,t)=>{await this.logoutHandler.handle(e,"idp"===(null==t?void 0:t.logoutType)?{...t,toLogoutUrl:this.boundLogout}:t),this.fetch=y,delete this.boundLogout},this.getSessionInfo=async e=>this.sessionInfoManager.get(e),this.getAllSessionInfo=async()=>this.sessionInfoManager.getAll(),this.loginHandler=e,this.redirectHandler=t,this.logoutHandler=r,this.sessionInfoManager=n,this.issuerConfigFetcher=i}},t.ConfigurationError=v,t.DEFAULT_SCOPES=l,t.EVENTS=c,t.GeneralLogoutHandler=d,t.IRpLogoutHandler=h,t.IWaterfallLogoutHandler=class{constructor(e,t){this.handlers=[new d(e),new h(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)}},t.InMemoryStorage=class{constructor(){this.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]}},t.InvalidResponseError=w,t.NotImplementedError=b,t.OidcProviderError=_,t.PREFERRED_SIGNING_ALG=a,t.REFRESH_BEFORE_EXPIRATION_SECONDS=5,t.SOLID_CLIENT_AUTHN_KEY_PREFIX="solidClientAuthn:",t.SessionInfoManagerBase=class{constructor(e){this.storageUtility=e,this.storageUtility=e}update(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 f(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")}},t.StorageUtility=m,t.StorageUtilityGetResponse=I,t.StorageUtilityMock=T,t.USER_SESSION_PREFIX="solidClientAuthenticationUser",t.buildAuthenticatedFetch=async function(e,t,r){var n;let i,o=t;const s=null==r?void 0:r.refreshOptions;if(void 0!==s){const e=async()=>{var t,n,a,l;try{const{accessToken:n,refreshToken:a,expiresIn:l}=await async function(e,t,r){var n;const i=await e.tokenRefresher.refresh(e.sessionId,e.refreshToken,t);return null==r||r.emit(c.SESSION_EXTENDED,null!==(n=i.expiresIn)&&void 0!==n?n:600),"string"==typeof i.refreshToken&&(null==r||r.emit(c.NEW_REFRESH_TOKEN,i.refreshToken)),{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn}}(s,r.dpopKey,r.eventEmitter);o=n,void 0!==a&&(s.refreshToken=a),clearTimeout(i),i=setTimeout(e,1e3*R(l)),null===(t=r.eventEmitter)||void 0===t||t.emit(c.TIMEOUT_SET,i)}catch(e){e instanceof _&&(null===(n=null==r?void 0:r.eventEmitter)||void 0===n||n.emit(c.ERROR,e.error,e.errorDescription),null===(a=null==r?void 0:r.eventEmitter)||void 0===a||a.emit(c.SESSION_EXPIRED)),e instanceof w&&e.missingFields.includes("access_token")&&(null===(l=null==r?void 0:r.eventEmitter)||void 0===l||l.emit(c.SESSION_EXPIRED))}};i=setTimeout(e,1e3*R(r.expiresIn)),null===(n=r.eventEmitter)||void 0===n||n.emit(c.TIMEOUT_SET,i)}else if(void 0!==r&&void 0!==r.eventEmitter){const e=setTimeout((()=>{r.eventEmitter.emit(c.SESSION_EXPIRED)}),1e3*R(r.expiresIn));r.eventEmitter.emit(c.TIMEOUT_SET,e)}return async(t,n)=>{let i=await A(e,o,t,n,null==r?void 0:r.dpopKey);const s=!i.ok&&(a=i.status,![401,403].includes(a));var a;return i.ok||s||i.url!==t&&void 0!==(null==r?void 0:r.dpopKey)&&(i=await A(e,o,i.url,n,r.dpopKey)),i}},t.buildProxyHandler=(e,t)=>({get(r,i,o){if(!Object.getOwnPropertyNames(n.EventEmitter).includes(i)&&Object.getOwnPropertyNames(e).includes(i))throw new Error(`${t}: [${i}] is not supported`);return Reflect.get(r,i,o)}}),t.clear=f,t.createDpopHeader=E,t.determineSigningAlg=function(e,t){var r;return null!==(r=t.find((t=>e.includes(t))))&&void 0!==r?r:null},t.fetchJwks=u,t.generateDpopKeyPair=async function(){const{privateKey:e,publicKey:t}=await o.generateKeyPair(a[0]),r={privateKey:e,publicKey:await o.exportJWK(t)};return[r.publicKey.alg]=a,r},t.getEndSessionUrl=p,t.getSessionIdFromOauthState=async function(e,t){return e.getForUser(t,"sessionId")},t.getUnauthenticatedSession=function(){return{isLoggedIn:!1,sessionId:s.v4(),fetch:(...e)=>i.fetch.call(globalThis,...e)}},t.getWebidFromTokenPayload=async function(e,t,r,n){const i=await u(t,r);let s;try{const{payload:t}=await o.jwtVerify(e,await o.importJWK(i),{issuer:r,audience:n});s=t}catch(e){throw new Error(`Token verification failed: ${e.stack}`)}if("string"==typeof s.webid)return s.webid;if("string"!=typeof s.sub)throw new Error(`The token ${JSON.stringify(s)} is invalid: it has no 'webid' claim and no 'sub' claim.`);try{return new URL(s.sub),s.sub}catch(e){throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${s.sub}] is invalid as a URL - error [${e}].`)}},t.handleRegistration=async function(e,t,r,n){const i=function(e,t){return void 0===e.clientId||g(e.clientId)?t.scopesSupported.includes("webid")&&void 0!==e.clientId&&g(e.clientId)?"solid-oidc":"dynamic":"static"}(e,t);return"dynamic"===i?n.getClient({sessionId:e.sessionId,clientName:e.clientName,redirectUrl:e.redirectUrl},t):(await r.setForUser(e.sessionId,{clientId:e.clientId}),e.clientSecret&&await r.setForUser(e.sessionId,{clientSecret:e.clientSecret}),e.clientName&&await r.setForUser(e.sessionId,{clientName:e.clientName}),{clientId:e.clientId,clientSecret:e.clientSecret,clientName:e.clientName,clientType:i})},t.isSupportedTokenType=function(e){return"string"==typeof e&&["DPoP","Bearer"].includes(e)},t.isValidRedirectUrl=function(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}},t.loadOidcContextFromStorage=async function(e,t,r){try{const[n,i,o,s]=await Promise.all([t.getForUser(e,"issuer",{errorIfNull:!0}),t.getForUser(e,"codeVerifier"),t.getForUser(e,"redirectUrl"),t.getForUser(e,"dpop",{errorIfNull:!0})]);return await t.deleteForUser(e,"codeVerifier"),{codeVerifier:i,redirectUrl:o,issuerConfig:await r.fetchConfig(n),dpop:"true"===s}}catch(t){throw new Error(`Failed to retrieve OIDC context from storage associated with session [${e}]: ${t}`)}},t.maybeBuildRpInitiatedLogout=function({endSessionEndpoint:e,idTokenHint:t}){if(void 0!==e)return function({state:r,postLogoutUrl:n}){return p({endSessionEndpoint:e,idTokenHint:t,state:r,postLogoutRedirectUri:n})}},t.mockStorage=x,t.mockStorageUtility=(e,t=!1)=>t?new m(x(e),x({})):new m(x({}),x(e)),t.removeOpenIdParams=function(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},t.saveSessionInfoToStorage=async function(e,t,r,n,i,s,a){void 0!==i&&await e.setForUser(t,{refreshToken:i},{secure:s}),void 0!==r&&await e.setForUser(t,{webId:r},{secure:s}),void 0!==n&&await e.setForUser(t,{isLoggedIn:n},{secure:s}),void 0!==a&&await e.setForUser(t,{publicKey:JSON.stringify(a.publicKey),privateKey:JSON.stringify(await o.exportJWK(a.privateKey))},{secure:s})}},4848:function(e,t,r){"use strict";var n=r(8690),i=r(2395),o=r(5914),s=r(2384),a=r(8518),c=r(4727),l=r(6565),u=r(2831);function d(e){return"object"==typeof e&&"object"==typeof e.internal_resourceInfo}function h(e){const t=e;return"object"==typeof t&&"object"==typeof t.internal_resourceInfo&&"object"==typeof t.internal_resourceInfo.linkedResources}function f(e){const t=e;return"object"==typeof t.internal_changeLog&&Array.isArray(t.internal_changeLog.additions)&&Array.isArray(t.internal_changeLog.deletions)}class p extends Error{}function g(e){return"string"==typeof e?e:e.value}const y=o.fetch.bind(globalThis);function m(e){var t,r,n,i,o;const a=null!==(r=null===(t=e.headers.get("Content-Type"))||void 0===t?void 0:t.split(";"))&&void 0!==r?r:[],c=a.length>0&&["text/turtle","application/ld+json"].includes(a[0]),l={sourceIri:e.url,isRawData:!c,contentLocation:null!==(n=e.headers.get("Content-Location"))&&void 0!==n?n:void 0,contentType:null!==(i=e.headers.get("Content-Type"))&&void 0!==i?i:void 0,linkedResources:{},location:null!==(o=e.headers.get("Location"))&&void 0!==o?o:void 0},u=e.headers.get("Link");if(u){const e=s.parse(u),t=e.get("rel","acl");1===t.length&&(l.aclUrl=new URL(t[0].uri,l.sourceIri).href),l.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,l.sourceIri).href),e}),l.linkedResources)}const d=e.headers.get("WAC-Allow");return d&&(l.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)),l}function v(e){let t;return t="function"==typeof e.slice?Object.assign(e.slice(),{...e}):{...e},t}function b(e){return!e.ok}const w="http://www.w3.org/ns/auth/acl#Authorization",_="http://www.w3.org/ns/auth/acl#accessTo",S="http://www.w3.org/ns/auth/acl#agent",E="http://www.w3.org/ns/auth/acl#agentGroup",A="http://www.w3.org/ns/auth/acl#agentClass",R="http://www.w3.org/ns/auth/acl#default",I="http://www.w3.org/ns/auth/acl#defaultForNew",T="http://www.w3.org/ns/auth/acl#mode",x="http://www.w3.org/ns/auth/acl#origin",P="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",C="http://www.w3.org/ns/ldp#BasicContainer",k="http://www.w3.org/ns/ldp#Resource",O="http://www.w3.org/ns/ldp#contains",F="http://xmlns.com/foaf/0.1/Agent",N={AccessControlResource:"http://www.w3.org/ns/solid/acp#AccessControlResource",Policy:"http://www.w3.org/ns/solid/acp#Policy",AccessControl:"http://www.w3.org/ns/solid/acp#AccessControl",Read:"http://www.w3.org/ns/solid/acp#Read",Append:"http://www.w3.org/ns/solid/acp#Append",Write:"http://www.w3.org/ns/solid/acp#Write",Rule:"http://www.w3.org/ns/solid/acp#Rule",Matcher:"http://www.w3.org/ns/solid/acp#Matcher",accessControl:"http://www.w3.org/ns/solid/acp#accessControl",memberAccessControl:"http://www.w3.org/ns/solid/acp#memberAccessControl",apply:"http://www.w3.org/ns/solid/acp#apply",applyMembers:"http://www.w3.org/ns/solid/acp#applyMembers",allow:"http://www.w3.org/ns/solid/acp#allow",deny:"http://www.w3.org/ns/solid/acp#deny",allOf:"http://www.w3.org/ns/solid/acp#allOf",anyOf:"http://www.w3.org/ns/solid/acp#anyOf",noneOf:"http://www.w3.org/ns/solid/acp#noneOf",access:"http://www.w3.org/ns/solid/acp#access",accessMembers:"http://www.w3.org/ns/solid/acp#accessMembers",agent:"http://www.w3.org/ns/solid/acp#agent",group:"http://www.w3.org/ns/solid/acp#group",client:"http://www.w3.org/ns/solid/acp#client",PublicAgent:"http://www.w3.org/ns/solid/acp#PublicAgent",AuthenticatedAgent:"http://www.w3.org/ns/solid/acp#AuthenticatedAgent",CreatorAgent:"http://www.w3.org/ns/solid/acp#CreatorAgent"},D="http://www.w3.org/ns/solid/terms#PublicOidcClient",L="https://w3id.org/security#publicKey",U="http://www.w3.org/ns/pim/space#storage",j={fetch:y};async function M(e,t={...j,ignoreAuthenticationErrors:!1}){var r;const n={...j,...t};return B(await n.fetch(e,{method:"HEAD"}),{ignoreAuthenticationErrors:null!==(r=t.ignoreAuthenticationErrors)&&void 0!==r&&r})}function B(e,t={ignoreAuthenticationErrors:!1}){if(b(e)&&(!function(e){return 401===e.status||403===e.status}(e)||!t.ignoreAuthenticationErrors))throw new G(`Fetching the metadata of the Resource at [${e.url}] failed: [${e.status}] [${e.statusText}].`,e);return{internal_resourceInfo:m(e)}}function H(e){return(d(e)?$(e):g(e)).endsWith("/")}function W(e){var t;return null!==(t=e.internal_resourceInfo.contentType)&&void 0!==t?t:null}function $(e){return d(e)?e.internal_resourceInfo.sourceIri:null}const V=$;function K(e){var t;if(!h(e))return null;const r=null!==(t=J(e)["http://www.w3.org/ns/solid/terms#podOwner"])&&void 0!==t?t:[];return 1===r.length?r[0]:null}function J(e){return e.internal_resourceInfo.linkedResources}class G extends p{get statusCode(){return this.response.status}get statusText(){return this.response.statusText}constructor(e,t){super(e),this.response=t}}const q=()=>{const e=[],t=[],r=[];return{onQuad:t=>{e.push(t)},onError:e=>{r.push(e)},onComplete:e=>{t.push(e)},parse:async(o,s)=>new Promise((a=>{const c=new n.JsonLdParser({baseIRI:$(s),documentLoader:new i.FetchDocumentLoader(y)});let l=!1;function u(){l||(l=!0,t.forEach((e=>e())),a())}c.on("end",u),c.on("error",(e=>{r.forEach((t=>t(e))),u()})),e.forEach((e=>c.on("data",e))),c.write(o),c.end()}))}};l.dataset;const z="https://inrupt.com/.well-known/sdk-local-node/",{freeze:Y}=Object;function Q(e){return e.substring(0,46)===z}function X(e){return e.substring(46)}function Z(e){return"string"==typeof e&&"_:"===e.substring(0,2)}function ee(e){return e.substring(2)}function te(e){return`_:${e.value}`}const re="http://www.w3.org/2001/XMLSchema#boolean",ne="http://www.w3.org/2001/XMLSchema#dateTime",ie="http://www.w3.org/2001/XMLSchema#date",oe="http://www.w3.org/2001/XMLSchema#time",se="http://www.w3.org/2001/XMLSchema#decimal",ae="http://www.w3.org/2001/XMLSchema#integer",ce="http://www.w3.org/2001/XMLSchema#string",le="http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";function ue(e){return"true"===e||"1"===e||"false"!==e&&"0"!==e&&null}function de(e){if(!/\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const[t,r]=pe(e),[n,i,o]=t.split(":");let s=Number.parseInt(n,10),a=Number.parseInt(i,10);const[c,l]=o.split("."),u=Number.parseInt(c,10),d=l?Number.parseInt(l,10):void 0;a>=60&&(s+=1,a-=60);const h={hour:s,minute:a,second:u};if("number"==typeof d&&(h.millisecond=d),"string"==typeof r){const[e,t]=ge(r);if("number"!=typeof e||e>24||"number"!=typeof t||t>59)return null;h.timezoneHourOffset=e,h.timezoneMinuteOffset=t}return h}function he(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,s,a]=i.split("-"),c=Number.parseInt(o,10)*n,l=Number.parseInt(s,10)-1,u=Number.parseInt(a,10),[d,h]=pe(r),[f,p]="string"==typeof h?ge(h):[0,0],[g,y,m]=d.split(":"),v=Number.parseInt(g,10)+f,b=Number.parseInt(y,10)+p,[w,_]=m.split("."),S=Number.parseInt(w,10),E=_?Number.parseInt(_,10):0,A=new Date(Date.UTC(c,l,u,v,b,S,E));return c>=0&&c<100&&A.setUTCFullYear(A.getUTCFullYear()-1900),A}function fe(e){if(!/-?\d{4,}-\d\d-\d\d(Z|(\+|-)\d\d:\d\d)?/.test(e))return null;const t=e,[r,n]="-"===t.charAt(0)?[-1,t.substring(1)]:[1,t],[i,o,s]=n.split("-"),a=s.length>2?s.substring(0,2):s,c=Number.parseInt(i,10)*r,l=Number.parseInt(o,10)-1,u=Number.parseInt(a,10),d=new Date(Date.UTC(c,l,u,12));return c>=0&&c<100&&d.setUTCFullYear(d.getUTCFullYear()-1900),d}function pe(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 ge(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 ye(e){const t=Number.parseFloat(e);return Number.isNaN(t)?null:t}function me(e){const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function ve(e){return e.toLowerCase()}function be(e){return we(e)&&"NamedNode"===e.termType}function we(e){return null!==e&&"object"==typeof e&&"string"==typeof e.termType&&"string"==typeof e.value&&"function"==typeof e.equals}function _e(e){return be(e)&&Q(e.value)}function Se(e){const t=g(e);if("function"!=typeof URL)return!0;try{return new URL(t),!0}catch(e){return!1}}function Ee(e,t){return Re.namedNode(Ae(X(e.value),t))}function Ae(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}const Re=c;function Ie(e,t,r={}){var n;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 i="DefaultGraph"===t.graph.termType?"default":t.graph.value,o=null!==(n=e.graphs[i])&&void 0!==n?n:{};return Y({...e,graphs:Y({...e.graphs,[i]:Te(o,t,r)})})}function Te(e,t,r){var n;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 i="BlankNode"===t.subject.termType?`_:${t.subject.value}`:t.subject.value,o=null!==(n=e[i])&&void 0!==n?n:{type:"Subject",url:i,predicates:{}};return Y({...e,[i]:xe(o,t,r)})}function xe(e,t,r){return Y({...e,predicates:Pe(e.predicates,t,r)})}function Pe(e,t,r){var n;if(!["NamedNode"].includes(t.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${t.predicate.termType}] as their Predicate node.`);const i=t.predicate.value,o=null!==(n=e[i])&&void 0!==n?n:{};return Y({...e,[i]:Ce(o,t,r)})}function Ce(e,t,r){var n,i,o,s,a,c,l,u;if("NamedNode"===t.object.termType){const r=Y([...null!==(n=e.namedNodes)&&void 0!==n?n:[],t.object.value]);return Y({...e,namedNodes:r})}if("Literal"===t.object.termType){if(t.object.datatype.value===le){const r=t.object.language.toLowerCase(),n=Y([...null!==(o=null===(i=e.langStrings)||void 0===i?void 0:i[r])&&void 0!==o?o:[],t.object.value]),a=Y({...null!==(s=e.langStrings)&&void 0!==s?s:{},[r]:n});return Y({...e,langStrings:a})}const r=Y([...null!==(c=null===(a=e.literals)||void 0===a?void 0:a[t.object.datatype.value])&&void 0!==c?c:[],t.object.value]),n=Y({...null!==(l=e.literals)&&void 0!==l?l:{},[t.object.datatype.value]:r});return Y({...e,literals:n})}if("BlankNode"===t.object.termType){const n=ke(t.object,r),i=Y([...null!==(u=e.blankNodes)&&void 0!==u?u:[],n]);return Y({...e,blankNodes:i})}throw new Error(`Objects of type [${t.object.termType}] are not supported.`)}function ke(e,t){var r,n;if(void 0===(null!==(r=t.chainBlankNodes)&&void 0!==r?r:[]).find((t=>t.equals(e))))return te(e);const i=(null!==(n=t.otherQuads)&&void 0!==n?n:[]).filter((t=>t.subject.equals(e))),o=i.filter((e=>!Le(e.object))).reduce(((e,r)=>{var n;if(!["NamedNode"].includes(r.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${r.predicate.termType}] as their Predicate node.`);const i=null!==(n=e[r.predicate.value])&&void 0!==n?n:{};return Y({...e,[r.predicate.value]:Ce(i,r,t)})}),{});return i.filter((e=>Le(e.object))).reduce(((e,r)=>{var n,i;if(!["NamedNode"].includes(r.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${r.predicate.termType}] as their Predicate node.`);const o=null!==(n=e[r.predicate.value])&&void 0!==n?n:{},s=null!==(i=o.blankNodes)&&void 0!==i?i:[];return Y({...e,[r.predicate.value]:{...o,blankNodes:[...s,ke(r.object,t)]}})}),o)}function Oe(e){const t=e.map((e=>e.subject)).filter(Le),r=e.map((e=>e.object)).filter(Le),n=[];return r.forEach((t=>{n.push(...De(t,e))})),t.concat(r).filter((t=>{if(n.some((e=>e.equals(t))))return!1;const r=e.filter((e=>e.object.equals(t))).map((e=>e.subject));return r.length>0&&(i=r).every((e=>i.every((t=>e.equals(t)))));var i}))}function Fe(e,t={}){var r;const n=[],i=null!==(r=t.dataFactory)&&void 0!==r?r:c;return Object.keys(e.graphs).forEach((r=>{const o=e.graphs[r],s="default"===r?i.defaultGraph():i.namedNode(r);Object.keys(o).forEach((e=>{const{predicates:r}=o[e],a=Z(e)?i.blankNode(ee(e)):i.namedNode(e);n.push(...Ne(r,a,s,t))}))})),n}function Ne(e,t,r,n={}){var i;const o=[],s=null!==(i=n.dataFactory)&&void 0!==i?i:c;return Object.keys(e).forEach((n=>{var i,a,c,l;const u=s.namedNode(n),d=null!==(i=e[n].langStrings)&&void 0!==i?i:{},h=null!==(a=e[n].namedNodes)&&void 0!==a?a:[],f=null!==(c=e[n].literals)&&void 0!==c?c:{},p=null!==(l=e[n].blankNodes)&&void 0!==l?l:[];Object.keys(f).forEach((e=>{const n=s.namedNode(e);f[e].forEach((e=>{const i=s.literal(e,n);o.push(s.quad(t,u,i,r))}))})),Object.keys(d).forEach((e=>{d[e].forEach((n=>{const i=s.literal(n,e);o.push(s.quad(t,u,i,r))}))})),h.forEach((e=>{const n=s.namedNode(e);o.push(s.quad(t,u,n,r))})),p.forEach((e=>{if(Z(e)){const n=s.blankNode(ee(e));o.push(s.quad(t,u,n,r))}else{const n=s.blankNode(),i=s.quad(t,u,n,r),a=Ne(e,n,r);o.push(i),o.push(...a)}}))})),o}function De(e,t,r=[]){if(void 0!==r.find((t=>t.equals(e))))return r;const n=t.filter((t=>t.subject.equals(e)&&Le(t.object))).map((e=>e.object));if(0===n.length)return[];const i=[...r,e],o=n.map((e=>De(e,t,i))),s=[];for(const e of o)s.push(...e);return s}function Le(e){return"BlankNode"===e.termType}const Ue=()=>{const e=[],t=[],r=[];return{onQuad:t=>{e.push(t)},onError:e=>{r.push(e)},onComplete:e=>{t.push(e)},parse:async(n,i)=>{(await async function(e){return new a.Parser({format:"text/turtle",baseIRI:e})}($(i))).parse(n,((n,i)=>{n?r.forEach((e=>e(n))):i?e.forEach((e=>e(i))):t.forEach((e=>e()))}))}}};async function je(e,t){const r=new a.Writer({format:"text/turtle",prefixes:null==t?void 0:t.prefixes}),n=e.map((e=>Re.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 Me={acl:"http://www.w3.org/ns/auth/acl#",acp:"http://www.w3.org/ns/solid/acp#",cc:"http://creativecommons.org/ns#",cert:"http://www.w3.org/ns/auth/cert#",csvw:"http://www.w3.org/ns/csvw#",current:"#",dc:"http://purl.org/dc/terms/",dcam:"http://purl.org/dc/dcam/",dcat:"http://www.w3.org/ns/dcat#",dctype:"http://purl.org/dc/dcmitype/",foaf:"http://xmlns.com/foaf/0.1/",ldp:"http://www.w3.org/ns/ldp#",owl:"http://www.w3.org/2002/07/owl#",posixstat:"http://www.w3.org/ns/posix/stat#",rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",schema:"https://schema.org/",shacl:"http://www.w3.org/ns/shacl#",skos:"http://www.w3.org/2004/02/skos/core#",skosxl:"http://www.w3.org/2008/05/skos-xl#",solid:"http://www.w3.org/ns/solid/terms#",swapdoc:"http://www.w3.org/2000/10/swap/pim/doc#",ui:"http://www.w3.org/ns/ui#",vann:"http://purl.org/vocab/vann/",vcard:"http://www.w3.org/2006/vcard/ns#",ws:"http://www.w3.org/ns/pim/space#",xsd:"http://www.w3.org/2001/XMLSchema#"},Be=l.dataset;function He(e,t={}){var r,n;return(null!==(n=null===(r=t.datasetFactory)||void 0===r?void 0:r.dataset)&&void 0!==n?n:Be)(Fe(e,t))}var We=Object.freeze({__proto__:null,getJsonLdParser:q,getTurtleParser:Ue,solidDatasetAsTurtle:async function(e,t){const{prefixes:r=Me,thing:n}={...t},i=new a.Writer({format:"application/turtle",prefixes:r}),o=n?new a.NamedNode(n):void 0;for(const t of He(e).match(o))i.addQuad(t);return new Promise(((e,t)=>{i.end(((r,n)=>{r?t(r):e(n)}))}))}});const $e={fetch:y},Ve=["Slug","If-None-Match","Content-Type"];async function Ke(e,t=$e){const r={...$e,...t},n=g(e),i=await r.fetch(n,r.init);if(b(i))throw new G(`Fetching the File failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=m(i),s=await i.blob();return Object.assign(s,{internal_resourceInfo:o})}async function Je(e,t,r=$e){const n=g(e),i=await Ge(n,t,"PUT",r);if(b(i))throw new G(`Overwriting the file at [${n}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=v(t),s=m(i);return s.sourceIri=n,s.isRawData=!0,Object.assign(o,{internal_resourceInfo:s})}async function Ge(e,t,r,n){var i,o;const s={...$e,...n},a=function(e){if(void 0===e)return{};let t={};var r;return r=e,Array.isArray(r)?e.forEach((([e,r])=>{t[e]=r})):function(e){return"function"==typeof e.forEach}(e)?e.forEach(((e,r)=>{t[r]=e})):t=e,t}(null!==(o=null===(i=s.init)||void 0===i?void 0:i.headers)&&void 0!==o?o:{});if(c=a,Ve.some((e=>void 0!==c[e])))throw new Error(`No reserved header (${Ve.join(", ")}) should be set in the optional RequestInit.`);var c;void 0!==s.slug&&(a.Slug=s.slug),a["Content-Type"]=qe(t,n.contentType);const l=g(e);return s.fetch(l,{...s.init,headers:a,method:r,body:t})}function qe(e,t){if("string"==typeof t)return t;const r="object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&e.type.length>0?e.type:void 0;return null!=r?r:"application/octet-stream"}function ze(e){var t,r,n,i,o,s,a,c;if(be(e))return`<${e.value}> (URL)`;if(function(e){return we(e)&&"Literal"===e.termType}(e)){if(!be(e.datatype))return`[${e.value}] (RDF/JS Literal of unknown type)`;let l;switch(e.datatype.value){case re:return l=null!==(r=null===(t=ue(e.value))||void 0===t?void 0:t.valueOf())&&void 0!==r?r:`Invalid data: \`${e.value}\``,`${l} (boolean)`;case ne:return l=null!==(i=null===(n=he(e.value))||void 0===n?void 0:n.toUTCString())&&void 0!==i?i:`Invalid data: \`${e.value}\``,`${l} (datetime)`;case se:return l=null!==(s=null===(o=ye(e.value))||void 0===o?void 0:o.toString())&&void 0!==s?s:`Invalid data: \`${e.value}\``,`${l} (decimal)`;case ae:return l=null!==(c=null===(a=me(e.value))||void 0===a?void 0:a.toString())&&void 0!==c?c:`Invalid data: \`${e.value}\``,`${l} (integer)`;case le:return`"${e.value}" (${e.language} string)`;case ce: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 Ye(e){if(!bt(e))throw new At(e)}function Qe(e,t){const r=f(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.filter((e=>!Xe(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 Y({...e,internal_changeLog:{additions:n,deletions:i}})}function Xe(e){return"BlankNode"===e.subject.termType||"BlankNode"===e.object.termType}function Ze(e,t){var r,n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=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===s?null:Q(s)?`#${X(s)}`:s}const et=Ze;function tt(e,t){var r,n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(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=>Q(e)?`#${X(e)}`:e)))&&void 0!==i?i:[]}const rt=tt;function nt(e,t,r){var n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(i=null===(n=e.predicates[o])||void 0===n?void 0:n.langStrings)&&void 0!==i?i:{},a=Object.keys(s).find((e=>e.toLowerCase()===r.toLowerCase()&&Array.isArray(s[e])&&s[e].length>0));return"string"==typeof a?s[a][0]:null}function it(e,t,r){var n,i;if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(i=null===(n=e.predicates[o])||void 0===n?void 0:n.langStrings)&&void 0!==i?i:{},a=Object.keys(s).find((e=>e.toLowerCase()===r.toLowerCase()&&Array.isArray(s[e])&&s[e].length>0));return"string"==typeof a?[...s[a]]:[]}function ot(e,t){return Ye(e),ft(e,t,ce)}function st(e,t){const r=et(e,t);return null===r?null:Re.namedNode(r)}function at(e,t){return rt(e,t).map((e=>Re.namedNode(e)))}function ct(e,t){var r,n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t),a=null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{},c=Object.keys(a);if(c.length>0){const e=c.find((e=>Array.isArray(a[e])&&a[e].length>0));if("string"==typeof e)return Re.literal(a[e][0],e)}const l=null!==(o=null===(i=e.predicates[s])||void 0===i?void 0:i.literals)&&void 0!==o?o:{},u=Object.keys(l);if(u.length>0){const e=u.find((e=>Array.isArray(l[e])&&l[e].length>0));if("string"==typeof e)return Re.literal(l[e][0],Re.namedNode(e))}return null}function lt(e,t){var r,n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t);let a=[];const c=null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{},l=Object.keys(c);for(const e of l){const t=c[e].map((t=>Re.literal(t,e)));a=a.concat(t)}const u=null!==(o=null===(i=e.predicates[s])||void 0===i?void 0:i.literals)&&void 0!==o?o:{},d=Object.keys(u);for(const e of d){const t=u[e],r=Re.namedNode(e),n=t.map((e=>Re.literal(e,r)));a=a.concat(n)}return a}function ut(e,t){var r,n;Ye(e);const i=st(e,t);if(null!==i)return i;const o=ct(e,t);if(null!==o)return o;const s=g(t),a=null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.blankNodes)&&void 0!==n?n:[];if(a.length>0){const e=Z(a[0])?ee(a[0]):void 0;return Re.blankNode(e)}return null}function dt(e,t){var r,n;Ye(e);const i=at(e,t),o=lt(e,t),s=g(t),a=(null!==(n=null===(r=e.predicates[s])||void 0===r?void 0:r.blankNodes)&&void 0!==n?n:[]).map((e=>{const t=Z(e)?ee(e):void 0;return Re.blankNode(t)}));return i.concat(o).concat(a)}function ht(e,t,r){var n,i,o,s;if(!Se(t))throw new Rt(t);const a=g(t);return null!==(s=null===(o=null===(i=null===(n=e.predicates[a])||void 0===n?void 0:n.literals)||void 0===i?void 0:i[r])||void 0===o?void 0:o[0])&&void 0!==s?s:null}function ft(e,t,r){var n,i,o;if(!Se(t))throw new Rt(t);const s=g(t);return[...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?o:[]]}function pt(e,t,r={}){var n;if(!Se(t))throw new Tt(t);const i=void 0!==r.scope?g(r.scope):"default",o=null!==(n=e.graphs[i])&&void 0!==n?n:{},s=g(t),a=o[Q(s)&&h(e)?Ae(X(s),$(e)):s];return void 0===a?null:a}function gt(e,t={acceptBlankNodes:!1}){var r;const n=void 0!==t.scope?g(t.scope):"default",i=null!==(r=e.graphs[n])&&void 0!==r?r:{};return Object.values(i).filter((e=>!Z(e.url)||t.acceptBlankNodes))}function yt(e,t){var r;const n=Et(t)&&h(e)?Ae(X(t.url),$(e)):t.url,i=e.graphs.default,o=Y({...i,[n]:Y({...t,url:n})}),s=Y({...e.graphs,default:o}),a=Re.namedNode(n),c=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,l=void 0!==c?Ne(c,a,Re.defaultGraph()):[],u=Ne(t.predicates,a,Re.defaultGraph());return function(e,t){const r=f(e)?e.internal_changeLog:{additions:[],deletions:[]},[n,i]=t.filter((e=>!Xe(e))).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 Y({...e,internal_changeLog:{additions:n,deletions:i}})}(Qe(Y({...e,graphs:s}),l),u)}function mt(e,t){var r;let n;n=be(t)?t.value:"string"==typeof t?Q(t)&&h(e)?Ae(X(t),$(e)):t:Et(t)?t.url:_t(t);const i={...e.graphs.default};delete i[n];const o=Y({...e.graphs,default:Y(i)}),s=Re.namedNode(n),a=null===(r=e.graphs.default[n])||void 0===r?void 0:r.predicates,c=void 0!==a?Ne(a,s,Re.defaultGraph()):[];return Qe(Y({...e,graphs:o}),c)}function vt(e={}){var t;if(void 0!==e.url){const{url:t}=e;if(!Se(t))throw new Tt(t);return Y({type:"Subject",predicates:Y({}),url:t})}const r=null!==(t=e.name)&&void 0!==t?t:xt(),n=`${z}${r}`;return Y({type:"Subject",predicates:Y({}),url:n})}function bt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.type&&"Subject"===e.type}function wt(e,t){if(Et(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 Ae(X(e.url),t)}return e.url}const _t=wt;function St(e){let t="";Et(e)?t+=`## Thing (no URL yet — identifier: \`#${X(e.url)}\`)\n`:t+=`## Thing: ${e.url}\n`;const r=Object.keys(e.predicates);if(0===r.length)t+="\n\n";else for(const n of r)t+=`\nProperty: ${n}\n`,t+=dt(e,n).reduce(((e,t)=>`${e}- ${ze(t)}\n`),"");return t}function Et(e){return Q(e.url)}class At extends p{constructor(e){super(`Expected a Thing, but received: [${e}].`),this.receivedValue=e}}class Rt extends p{constructor(e){const t=be(e)?e.value:e;super(`Expected a valid URL to identify a property, but received: [${t}].`),this.receivedProperty=t}}class It extends p{constructor(e){const t=be(e)?e.value:e;super(`Expected a valid URL value, but received: [${t}].`),this.receivedValue=t}}class Tt extends p{constructor(e){const t=be(e)?e.value:e;super(`Expected a valid URL to identify a Thing, but received: [${t}].`),this.receivedValue=t}}const xt=()=>u.v4();function Pt(e){const t=new URL(e);return t.hash="",t.href}function Ct(){return Y({type:"Dataset",graphs:{default:{}}})}async function kt(e,t={}){if(b(e))throw new G(`Fetching the SolidDataset at [${e.url}] failed: [${e.status}] [${e.statusText}] ${await e.text()}.`,e);const r=B(e),n={"text/turtle":Ue(),...t.parsers},i=W(r);if(null===i)throw new Error(`Could not determine the content type of the Resource at [${$(r)}].`);const o=i.split(";")[0],s=n[o];if(void 0===s)throw new Error(`The Resource at [${$(r)}] has a MIME type of [${o}], but the only parsers available are for the following MIME types: [${Object.keys(n).join(", ")}].`);const a=await e.text();return new Promise(((e,t)=>{let n=Y({graphs:Y({default:Y({})}),type:"Dataset"});const o=[],c=[];s.onError((e=>{t(new Error(`Encountered an error parsing the Resource at [${$(r)}] with content type [${i}]: ${e}`))})),s.onQuad((e=>{c.push(e),"BlankNode"===e.subject.termType||"BlankNode"===e.object.termType?o.push(e):n=Ie(n,e)})),s.onComplete((async()=>{const t=o.length<=20?Oe(o):[],i=o.filter((e=>t.every((t=>!t.equals(e.subject)))));n=i.reduce(((e,r)=>Ie(e,r,{otherQuads:c,chainBlankNodes:t})),n);const s=Y({...n,...r});e(s)})),s.parse(a,r)}))}async function Ot(e,t=j){var r;e=g(e);const n={...j,...t},i=Object.keys(null!==(r=t.parsers)&&void 0!==r?r:{}),o=i.length>0?i.join(", "):"text/turtle",s=await n.fetch(e,{headers:{Accept:o}});if(b(s))throw new G(`Fetching the Resource at [${e}] failed: [${s.status}] [${s.statusText}] ${await s.text()}.`,s);return await kt(s,t)}async function Ft(e,t,r=j){e=g(e);const n={...j,...r},i=function(e){return f(e)?e:Y({...e,internal_changeLog:{additions:[],deletions:[]}})}(t),o=Nt(i,e)?await async function(e){return{method:"PATCH",body:`${e.internal_changeLog.deletions.length>0?`DELETE DATA {${(await je(e.internal_changeLog.deletions.map(jt))).trim()}};`:""} ${e.internal_changeLog.additions.length>0?`INSERT DATA {${(await je(e.internal_changeLog.additions.map(jt))).trim()}};`:""}`,headers:{"Content-Type":"application/sparql-update"}}}(i):await async function(e,t){return{method:"PUT",body:await je(Fe(e).map(jt),t),headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:`<${k}>; rel="type"`}}}(i,r),s=await n.fetch(e,o);if(b(s)){const t=Nt(i,e)?`The changes that were sent to the Pod are listed below.\n\n${Ut(i)}`:`The SolidDataset that was sent to the Pod is listed below.\n\n${Lt(i)}`;throw new G(`Storing the Resource at [${e}] failed: [${s.status}] [${s.statusText}] ${await s.text()}.\n\n${t}`,s)}const a={...m(s),isRawData:!1};return Bt(Y({...t,internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:a}))}function Nt(e,t){return f(e)&&d(e)&&"string"==typeof e.internal_resourceInfo.sourceIri&&(r=t,Pt(e.internal_resourceInfo.sourceIri)===Pt(r));var r}function Dt(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 Lt(e){let t="";d(e)?t+=`# SolidDataset: ${$(e)}\n`:t+="# SolidDataset (no URL yet)\n";const r=gt(e);return 0===r.length?t+="\n\n":r.forEach((r=>{t+=`\n${St(r)}`,f(e)&&(t+=`\n${function(e,t){const r=Re.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 Ut(e){if(!d(e))return"This is a newly initialized SolidDataset, so there is no source to compare it to.";if(!f(e)||0===e.internal_changeLog.additions.length&&0===e.internal_changeLog.deletions.length)return`## Changes compared to ${$(e)}\n\nThis SolidDataset has not been modified since it was fetched from ${$(e)}.\n`;let t=`## Changes compared to ${$(e)}\n`;const r=function(e){const t=Object.create(null);return e.internal_changeLog.deletions.forEach((r=>{var n,i,o;const s=_e(r.subject)?Ee(r.subject,$(e)):r.subject;if(!be(s)||!be(r.predicate))return;const a=g(s),c=g(r.predicate);null!==(n=t[a])&&void 0!==n||(t[a]=Object.create(null)),null!==(i=(o=t[a])[c])&&void 0!==i||(o[c]={added:[],deleted:[]}),t[a][c].deleted.push(r.object)})),e.internal_changeLog.additions.forEach((r=>{var n,i,o;const s=_e(r.subject)?Ee(r.subject,$(e)):r.subject;if(!be(s)||!be(r.predicate))return;const a=g(s),c=g(r.predicate);null!==(n=t[a])&&void 0!==n||(t[a]=Object.create(null)),null!==(i=(o=t[a])[c])&&void 0!==i||(o[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} - ${ze(t)}\n`),"")),i.length>0&&(t+="- Added:\n",t+=i.reduce(((e,t)=>`${e} - ${ze(t)}\n`),""))}))})),t}function jt(e){const t=be(e.subject)?Mt(e.subject):e.subject,r=be(e.object)?Mt(e.object):e.object;return Re.quad(t,e.predicate,r,e.graph)}function Mt(e){return Q(e.value)?Re.namedNode(`#${X(e.value)}`):e}function Bt(e){const t=$(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=>!Q(e))))return e;const o=Y(i.map((e=>Q(e)?`${t}#${X(e)}`:e))),s=Y({...e[r],namedNodes:o});return Y({...e,[r]:s})}),e.predicates);return Y({...e,predicates:r,url:Q(e.url)?`${t}#${X(e.url)}`:e.url})}(e[r],t),i=Q(r)?`${t}#${X(r)}`:r,o={...e};return delete o[r],o[i]=n,Y(o)}),r),i=Y({...e.graphs,default:n});return Y({...e,graphs:i})}function Ht(e){return{...Ct(),internal_resourceInfo:{sourceIri:g(e),isRawData:!1,contentType:"text/turtle",linkedResources:{}}}}function Wt(e){const t=g(e);if(!t.endsWith("/"))throw new Error("A Container's URL should end in a slash. Please update your tests.");return Ht(t)}const $t=(e,t,r)=>{var n,i;if(Ye(e),!Se(t))throw new Rt(t);if(!bt(r)&&!Se(r))throw new It(r);const o=g(t),s=null!==(n=e.predicates[o])&&void 0!==n?n:{},a=null!==(i=s.namedNodes)&&void 0!==i?i:[];let c;c=be(r)?r.value:"string"==typeof r?r:Et(r)?r.url:_t(r);const l=Y(a.concat(g(c))),u=Y({...s,namedNodes:l}),d=Y({...e.predicates,[o]:u});return Y({...e,predicates:d})},Vt=$t,Kt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e?"true":"false"}(r),re)),Jt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e.toISOString()}(r),ne)),Gt=(e,t,r)=>(Ye(e),rr(e,t,function(e){const t=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),[,i]=pe(e.toISOString());return`${t}-${String(r).padStart(2,"0")}-${String(n).padStart(2,"0")}${i}`}(r),ie)),qt=(e,t,r)=>(Ye(e),rr(e,t,function(e){let t,r;if(e.millisecond&&(t=e.millisecond<10?`00${e.millisecond}`:e.millisecond<100?`0${e.millisecond}`:e.millisecond),"number"==typeof e.timezoneHourOffset){const t=Math.abs(e.timezoneHourOffset)<10?`0${Math.abs(e.timezoneHourOffset)}`:Math.abs(e.timezoneHourOffset);r=e.timezoneHourOffset>=0?`+${t}`:`-${t}`,e.timezoneMinuteOffset?r=`${r}:${e.timezoneMinuteOffset<10?`0${e.timezoneMinuteOffset}`:e.timezoneMinuteOffset}`:r+=":00"}return`${e.hour<10?`0${e.hour}`:e.hour}:${e.minute<10?`0${e.minute}`:e.minute}:${e.second<10?`0${e.second}`:e.second}${e.millisecond?`.${t}`:""}${r||""}`}(r),oe)),zt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e.toString()}(r),se)),Yt=(e,t,r)=>(Ye(e),rr(e,t,function(e){return e.toString()}(r),ae));function Qt(e,t,r,n){var i,o,s;if(Ye(e),!Se(t))throw new Rt(t);const a=g(t),c=ve(n),l=null!==(i=e.predicates[a])&&void 0!==i?i:{},u=null!==(o=l.langStrings)&&void 0!==o?o:{},d=null!==(s=u[c])&&void 0!==s?s:[],h=Y(d.concat(r)),f=Y({...u,[c]:h}),p=Y({...l,langStrings:f}),y=Y({...e.predicates,[a]:p});return Y({...e,predicates:y})}const Xt=(e,t,r)=>(Ye(e),rr(e,t,r,ce));function Zt(e,t,r){return $t(e,t,r.value)}function er(e,t,r){if(Ye(e),!Se(t))throw new Rt(t);return r.datatype.value===le?Qt(e,t,r.value,r.language):rr(e,t,r.value,r.datatype.value)}function tr(e,t,r){var n,i;if("NamedNode"===r.termType)return Zt(e,t,r);if("Literal"===r.termType)return er(e,t,r);if("BlankNode"===r.termType){if(Ye(e),!Se(t))throw new Rt(t);const o=g(t),s=null!==(n=e.predicates[o])&&void 0!==n?n:{},a=null!==(i=s.blankNodes)&&void 0!==i?i:[],c=Y(a.concat(te(r))),l=Y({...s,blankNodes:c}),u=Y({...e.predicates,[o]:l});return Y({...e,predicates:u})}throw new Error(`Term type [${r.termType}] is not supported by @inrupt/solid-client.`)}function rr(e,t,r,n){var i,o,s;if(Ye(e),!Se(t))throw new Rt(t);const a=g(t),c=null!==(i=e.predicates[a])&&void 0!==i?i:{},l=null!==(o=c.literals)&&void 0!==o?o:{},u=null!==(s=l[n])&&void 0!==s?s:[],d=Y(u.concat(r)),h=Y({...l,[n]:d}),f=Y({...c,literals:h}),p=Y({...e.predicates,[a]:f});return Y({...e,predicates:p})}function nr(e,t){if(Ye(e),!Se(t))throw new Rt(t);const r=g(t),n={...e.predicates};return delete n[r],Y({...e,predicates:Y(n)})}const ir=(e,t,r)=>{var n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t);if(!bt(r)&&!Se(r))throw new It(r);const a=bt(r)?_t(r):g(r),c=Y(null!==(o=null===(i=null===(n=e.predicates[s])||void 0===n?void 0:n.namedNodes)||void 0===i?void 0:i.filter((e=>e.toLowerCase()!==a.toLowerCase())))&&void 0!==o?o:[]),l=Y({...e.predicates[s],namedNodes:c}),u=Y({...e.predicates,[s]:l});return Y({...e,predicates:u})},or=ir,sr=(e,t,r)=>(Ye(e),yr(e,t,re,(e=>ue(e)===r))),ar=(e,t,r)=>(Ye(e),yr(e,t,ne,(e=>{var t;return(null===(t=he(e))||void 0===t?void 0:t.getTime())===r.getTime()}))),cr=(e,t,r)=>(Ye(e),yr(e,t,ie,(function(e){const t=fe(e);return!!t&&t.getFullYear()===r.getFullYear()&&t.getMonth()===r.getMonth()&&t.getUTCDate()===r.getUTCDate()}))),lr=(e,t,r)=>(Ye(e),yr(e,t,oe,(function(e){const t=de(e);return!!t&&t.hour===r.hour&&t.minute===r.minute&&t.second===r.second&&t.millisecond===r.millisecond&&t.timezoneHourOffset===r.timezoneHourOffset&&t.timezoneMinuteOffset===r.timezoneMinuteOffset}))),ur=(e,t,r)=>(Ye(e),yr(e,t,se,(e=>ye(e)===r))),dr=(e,t,r)=>(Ye(e),yr(e,t,ae,(e=>me(e)===r)));function hr(e,t,r,n){var i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=g(t),a=null!==(o=null===(i=e.predicates[s])||void 0===i?void 0:i.langStrings)&&void 0!==o?o:{},c=Object.keys(a).find((e=>ve(e)===ve(n)&&Array.isArray(a[e])&&a[e].length>0));if("string"!=typeof c)return e;const l=a[c],u=Y(l.filter((e=>e!==r))),d=Y({...a,[c]:u}),h=Y({...e.predicates[s],langStrings:d}),f=Y({...e.predicates,[s]:h});return Y({...e,predicates:f})}const fr=(e,t,r)=>(Ye(e),yr(e,t,ce,(e=>e===r)));function pr(e,t,r){return ir(e,t,r.value)}function gr(e,t,r){var n,i,o;if(Ye(e),!Se(t))throw new Rt(t);const s=r.datatype.value;if(s===le)return hr(e,t,r.value,r.language);const a=g(t),c=null!==(n=e.predicates[a])&&void 0!==n?n:{},l=null!==(i=c.literals)&&void 0!==i?i:{},u=null!==(o=l[s])&&void 0!==o?o:[],d=Y(u.filter((e=>e!==r.value))),h=Y({...l,[s]:d}),f=Y({...c,literals:h}),p=Y({...e.predicates,[a]:f});return Y({...e,predicates:p})}function yr(e,t,r,n){var i,o,s;if(!Se(t))throw new Rt(t);const a=g(t),c=null!==(i=e.predicates[a])&&void 0!==i?i:{},l=null!==(o=c.literals)&&void 0!==o?o:{},u=null!==(s=l[r])&&void 0!==s?s:[],d=Y(u.filter((e=>!n(e)))),h=Y({...l,[r]:d}),f=Y({...c,literals:h}),p=Y({...e.predicates,[a]:f});return Y({...e,predicates:p})}const mr=(e,t,r)=>{if(Ye(e),!Se(t))throw new Rt(t);if(!bt(r)&&!Se(r))throw new It(r);return $t(nr(e,t),t,r)},vr=mr,br=(e,t,r)=>(Ye(e),Kt(nr(e,t),t,r)),wr=(e,t,r)=>(Ye(e),Jt(nr(e,t),t,r)),_r=(e,t,r)=>(Ye(e),Gt(nr(e,t),t,r)),Sr=(e,t,r)=>(Ye(e),qt(nr(e,t),t,r)),Er=(e,t,r)=>(Ye(e),zt(nr(e,t),t,r)),Ar=(e,t,r)=>(Ye(e),Yt(nr(e,t),t,r));function Rr(e,t,r,n){return Ye(e),Qt(nr(e,t),t,r,n)}const Ir=(e,t,r)=>(Ye(e),Xt(nr(e,t),t,r));function Tr(e,t,r){return Ye(e),Zt(nr(e,t),t,r)}function xr(e,t,r){return Ye(e),er(nr(e,t),t,r)}function Pr(e,t,r){if(Ye(e),!Se(t))throw new Rt(t);return tr(nr(e,t),t,r)}function Cr(e=vt()){let t=bt(e)?e:vt(e);function r(e){return(r,n)=>(t=e(t,r,n),o)}function n(e){return(r,n)=>(t=e(t,r,n),o)}function i(e){return(r,n)=>(t=e(t,r,n),o)}const o={build:()=>t,addUrl:r($t),addIri:r(Vt),addBoolean:r(Kt),addDatetime:r(Jt),addDate:r(Gt),addTime:r(qt),addDecimal:r(zt),addInteger:r(Yt),addStringNoLocale:r(Xt),addStringEnglish:(e,r)=>(t=Qt(t,e,r,"en"),o),addStringWithLocale:(e,r,n)=>(t=Qt(t,e,r,n),o),addNamedNode:r(Zt),addLiteral:r(er),addTerm:r(tr),setUrl:n(mr),setIri:n(vr),setBoolean:n(br),setDatetime:n(wr),setDate:n(_r),setTime:n(Sr),setDecimal:n(Er),setInteger:n(Ar),setStringNoLocale:n(Ir),setStringEnglish:(e,r)=>(t=Rr(t,e,r,"en"),o),setStringWithLocale:(e,r,n)=>(t=Rr(t,e,r,n),o),setNamedNode:n(Tr),setLiteral:n(xr),setTerm:n(Pr),removeAll:e=>(t=nr(t,e),o),removeUrl:i(ir),removeIri:i(or),removeBoolean:i(sr),removeDatetime:i(ar),removeDate:i(cr),removeTime:i(lr),removeDecimal:i(ur),removeInteger:i(dr),removeStringNoLocale:i(fr),removeStringEnglish:(e,r)=>Cr(hr(t,e,r,"en")),removeStringWithLocale:(e,r,n)=>Cr(hr(t,e,r,n)),removeNamedNode:i(pr),removeLiteral:i(gr)};return o}function kr(e){const t=J(e).type;return Array.isArray(t)&&t.includes(N.AccessControlResource)}async function Or(e,t=j){if(!sn(e))return{resourceAcl:null,fallbackAcl:null};try{const r=await Fr(e,t);return null===r?{resourceAcl:null,fallbackAcl:await Nr(e,t)}:{resourceAcl:r,fallbackAcl:null}}catch(e){if(e instanceof Qr)return{resourceAcl:null,fallbackAcl:null};throw e}}async function Fr(e,t=j){if(!sn(e))return null;try{const r=await Ot(e.internal_resourceInfo.aclUrl,t);if(kr(r))throw new Qr(e,r);return Y({...r,internal_accessTo:$(e)})}catch(e){if(e instanceof Qr)throw e;return null}}async function Nr(e,t=j){const r=new URL($(e)),n=r.pathname;if("/"===n)return null;const i=Dr(n),o=new URL(i,r.origin).href,s=await M(o,t);if(!sn(s))return null;const a=await Fr(s,t);return null===a?Nr(s,t):a}function Dr(e){const t="/"===e.substring(e.length-1)?e.substring(0,e.length-1):e;return`${e.substring(0,t.lastIndexOf("/"))}/`}function Lr(e){return gt(e).filter(Ur)}function Ur(e){return rt(e,P).includes(w)}function jr(e,t){return e.filter((e=>function(e,t){return rt(e,_).includes(t)}(e,t)))}function Mr(e,t){return e.filter((e=>function(e,t){return rt(e,R).includes(t)||rt(e,I).includes(t)}(e,t)))}function Br(e){const t=rt(e,T);return t.includes($r.write)?{read:t.includes($r.read),append:!0,write:!0,control:t.includes($r.control)}:{read:t.includes($r.read),append:t.includes($r.append),write:!1,control:t.includes($r.control)}}function Hr(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 Wr(e){return!Ne(e.predicates,Re.namedNode(e.url),Re.defaultGraph()).some((e=>!function(e){const{predicate:t}=e,{object:r}=e;return!(!t.equals(Re.namedNode(P))||!r.equals(Re.namedNode(w)))||(!!(t.equals(Re.namedNode(_))||t.equals(Re.namedNode(R))||t.equals(Re.namedNode(I)))||(!(!t.equals(Re.namedNode(T))||!Object.values($r).some((e=>r.equals(Re.namedNode(e)))))||(!!(t.equals(Re.namedNode(S))||t.equals(Re.namedNode(E))||t.equals(Re.namedNode(A)))||!!t.equals(Re.namedNode(x)))))}(e)))&&(null===et(e,_)&&null===et(e,R)&&null===et(e,I)||null===et(e,T)||null===et(e,S)&&null===et(e,E)&&null===et(e,A))}const $r={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 Vr(e,t,r){return e.filter((e=>rt(e,r).includes(t)))}function Kr(e,t){const r={};return e.forEach((e=>{const n=rt(e,t),i=Br(e);n.forEach((e=>{r[e]=void 0===r[e]?i:Hr([r[e],i])}))})),r}function Jr(e){let t=vt();return t=vr(t,P,w),e.read&&(t=Vt(t,T,$r.read)),e.append&&!e.write&&(t=Vt(t,T,$r.append)),e.write&&(t=Vt(t,T,$r.write)),e.control&&(t=Vt(t,T,$r.control)),t}function Gr(e,t){return Object.assign(v(e),{internal_acl:t})}const qr=[S,A,E,x];function zr(e,t,r,n,i){let o=e;gt(e).forEach((t=>{const[s,a]=function(e,t,r,n,i){if(!rt(e,r).includes(t))return[e,Jr({read:!1,append:!1,write:!1,control:!1})];const o=or(e,r,t);let s=function(e){let t=vt();function r(e,t,r){return rt(e,r).reduce(((e,t)=>Vt(e,r,t)),t)}return t=vr(t,P,w),t=r(e,t,_),t=r(e,t,R),t=r(e,t,I),t=r(e,t,S),t=r(e,t,E),t=r(e,t,A),t=r(e,t,x),t=r(e,t,T),t}(e);return s=or(s,"resource"===i?_:R,n),"default"===i&&(s=or(s,I,n)),s=vr(s,r,t),qr.filter((e=>e!==r)).forEach((e=>{s=nr(s,e)})),[o,s]}(t,i,r,e.internal_accessTo,n);o=yt(o,s),o=yt(o,a)}));let s=Jr(t);return s=vr(s,"resource"===n?_:R,e.internal_accessTo),s=vr(s,r,i),function(e){return Lr(e).filter(Wr).reduce(mt,e)}(yt(o,s))}function Yr(e,t){return Gr(e,{resourceAcl:t,fallbackAcl:null})}class Qr extends Error{constructor(e,t){super(`[${V(e)}] is governed by Access Control Policies in [${V(t)}] rather than by Web Access Control.`)}}function Xr(e){return null!==e.internal_acl.resourceAcl&&$(e)===e.internal_acl.resourceAcl.internal_accessTo&&e.internal_resourceInfo.aclUrl===$(e.internal_acl.resourceAcl)}function Zr(e){return Xr(e)?e.internal_acl.resourceAcl:null}function en(e){return null!==e.internal_acl.fallbackAcl}function tn(e){return en(e)?e.internal_acl.fallbackAcl:null}function rn(e){return Y({...Ct(),internal_accessTo:$(e),internal_resourceInfo:{sourceIri:e.internal_resourceInfo.aclUrl,isRawData:!1,linkedResources:{}}})}function nn(e){const t=rn(e);return Mr(Lr(e.internal_acl.fallbackAcl),e.internal_acl.fallbackAcl.internal_accessTo).map((t=>(t=nr(t,R),t=nr(t,I),t=vr(t,_,$(e)),vr(t,R,$(e))))).reduce(yt,t)}async function on(e,t,r=j){if(!sn(e))throw new Error(`Could not determine the location of the ACL for the Resource at [${$(e)}]; possibly the current user does not have Control access to that Resource. Try calling \`hasAccessibleAcl()\` before calling \`saveAclFor()\`.`);return{...await Ft(e.internal_resourceInfo.aclUrl,t,r),internal_accessTo:$(e)}}function sn(e){return"string"==typeof e.internal_resourceInfo.aclUrl}function an(e,t){return Xr(e)?ln(e.internal_acl.resourceAcl,t):en(e)?hn(e.internal_acl.fallbackAcl,t):null}function cn(e){return Xr(e)?un(Zr(e)):en(e)?fn(tn(e)):null}function ln(e,t){return Hr(pn(jr(Lr(e),e.internal_accessTo),t).map(Br))}function un(e){return mn(gn(jr(Lr(e),e.internal_accessTo)))}function dn(e,t,r){return zr(e,r,S,"resource",t)}function hn(e,t){return Hr(pn(Mr(Lr(e),e.internal_accessTo),t).map(Br))}function fn(e){return mn(gn(Mr(Lr(e),e.internal_accessTo)))}function pn(e,t){return Vr(e,t,S)}function gn(e){return e.filter(yn)}function yn(e){return null!==et(e,S)}function mn(e){return Kr(e,S)}function vn(e,t){return Xr(e)?wn(e.internal_acl.resourceAcl,t):en(e)?Sn(e.internal_acl.fallbackAcl,t):null}function bn(e){return Xr(e)?_n(Zr(e)):en(e)?En(tn(e)):null}function wn(e,t){return Hr(An(jr(Lr(e),e.internal_accessTo),t).map(Br))}function _n(e){return Rn(jr(Lr(e),e.internal_accessTo))}function Sn(e,t){return Hr(An(Mr(Lr(e),e.internal_accessTo),t).map(Br))}function En(e){return Rn(Mr(Lr(e),e.internal_accessTo))}function An(e,t){return Vr(e,t,E)}function Rn(e){return Kr(e,E)}function In(e,t,r){return zr(e,r,E,"resource",t)}function Tn(e){return Xr(e)?xn(e.internal_acl.resourceAcl):en(e)?Pn(e.internal_acl.fallbackAcl):null}function xn(e){return Hr(kn(jr(Lr(e),e.internal_accessTo),F).map(Br))}function Pn(e){return Hr(kn(Mr(Lr(e),e.internal_accessTo),F).map(Br))}function Cn(e,t){return zr(e,t,A,"resource",F)}function kn(e,t){return e.filter((e=>function(e,t){return rt(e,A).includes(t)}(e,t)))}function On(e,t){const r=pt(e,t);if(null===r)throw new Error(`Profile document [${$(e)}] does not include WebID [${t}]`);return r}function Fn(e,t){return Ze(On(e,t),L)}async function Nn(e,t,r=j){const n={...j,...r},i=await n.fetch(t);if(!i.ok)throw new Error(`Fetching [${t}] returned an error: ${i.status} ${i.statusText}`);try{const r=await i.json();if(!(e=>void 0!==e.keys)(r))throw new Error(`[${t}] does not dereference to a valid JWKS: ${JSON.stringify(r)}`);return{keys:[...r.keys,e]}}catch(e){throw new Error(`Parsing the document at [${t}] failed: ${e}`)}}function Dn(e,t){const r=pt(t,e),n=gt(t).filter((e=>rt(e,"http://xmlns.com/foaf/0.1/primaryTopic").length>0)).map(_t).concat(r?rt(r,"http://www.w3.org/2000/01/rdf-schema#seeAlso"):[]).concat(r?rt(r,"http://xmlns.com/foaf/0.1/isPrimaryTopicOf"):[]).filter((e=>e!==V(t)));return Array.from(new Set(n))}async function Ln(e,t=j){var r,n;const i=null!==(r=t.fetch)&&void 0!==r?r:y,o=null!==(n=t.webIdProfile)&&void 0!==n?n:await Ot(e,{fetch:y});return{webIdProfile:o,altProfileAll:(await Promise.allSettled(Dn(e,o).map((e=>Ot(e,{fetch:i}))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value))}}function Un(e,t){const r=new Set;return[e.webIdProfile,...e.altProfileAll].forEach((e=>{const n=pt(e,t);null!==n&&rt(n,U).forEach((e=>r.add(e)))})),Array.from(r)}function jn(e){if(!Hi(e))throw new Error(`An Access Control Resource for [${$(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 Mn(e,t){return Object.assign(v(e),{internal_acp:{...e.internal_acp,acr:t}})}function Bn(e){let t=vt(e);return t=vr(t,P,N.AccessControl),t}function Hn(e,t){const r=gt(jn(e),t),n=r.filter((e=>rt(e,P).includes(N.AccessControl))),i=r.filter((e=>rt(e,N.accessControl).length>0)).map((e=>vt({url:rt(e,N.accessControl)[0]})));return n.concat(i)}function Wn(e,t){return Mn(e,yt(jn(e),t))}function $n(e,t){return Vt(e,N.apply,t)}function Vn(e){return rt(e,N.apply)}function Kn(e,t){return or(e,N.apply,t)}function Jn(e){return nr(e,N.apply)}function Gn(e,t){return Vt(e,N.applyMembers,t)}function qn(e){return rt(e,N.applyMembers)}function zn(e){return nr(e,N.applyMembers)}function Yn(e){const t=Hn(e);return 0===t.length?Bn():t[0]}function Qn(e){return h(e)&&Array.isArray(e.internal_resourceInfo.linkedResources[N.accessControl])&&1===e.internal_resourceInfo.linkedResources[N.accessControl].length}function Xn(e,t){var r;const n=jn(e),i=$(n);let o=null!==(r=pt(n,i))&&void 0!==r?r:vt({url:i});return o=Vt(o,N.access,t),Mn(e,yt(n,o))}function Zn(e,t){var r;const n=jn(e),i=$(n);let o=null!==(r=pt(n,i))&&void 0!==r?r:vt({url:i});return o=Vt(o,N.accessMembers,t),Mn(e,yt(n,o))}function ei(e){const t=jn(e),r=pt(t,$(t));return null===r?[]:rt(r,N.access)}function ti(e){const t=jn(e),r=pt(t,$(t));return null===r?[]:rt(r,N.accessMembers)}function ri(e,t){const r=jn(e),n=pt(r,$(r));return null===n?e:Mn(e,yt(r,or(n,N.access,t)))}function ni(e,t){const r=jn(e),n=pt(r,$(r));return null===n?e:Mn(e,yt(r,or(n,N.accessMembers,t)))}function ii(e){const t=jn(e),r=pt(t,$(t));return null===r?e:Mn(e,yt(t,nr(r,N.access)))}function oi(e){const t=jn(e),r=pt(t,$(t));return null===r?e:Mn(e,yt(t,nr(r,N.accessMembers)))}function si(e,t){return Wn(e,$n(Yn(e),t))}function ai(e,t){return Wn(e,Gn(Yn(e),t))}function ci(e){const t=Hn(e).map((e=>Vn(e))),r=new Set;return t.forEach((e=>{e.forEach((e=>r.add(e)))})),Array.from(r)}function li(e){const t=Hn(e).map((e=>qn(e))),r=new Set;return t.forEach((e=>{e.forEach((e=>r.add(e)))})),Array.from(r)}function ui(e,t){return Hn(e).map((e=>Kn(e,t))).reduce(Wn,e)}function di(e,t){const r=Hn(e).map((e=>function(e,t){return or(e,N.applyMembers,t)}(e,t)));return r.reduce(Wn,e)}function hi(e){return Hn(e).map((e=>Jn(e))).reduce(Wn,e)}function fi(e){return Hn(e).map((e=>zn(e))).reduce(Wn,e)}function pi(e){let t=`# Access controls for ${$(e)}\n`;const r=ci(e),n=li(e),i=ei(e),o=ti(e);return 0===r.length&&0===n.length&&0===i.length&&0===o.length&&(t+="\n\n"),r.length>0&&(t+="\nThe following policies apply to this resource:\n- ",t+=`${r.join("\n- ")}\n`),i.length>0&&(t+="\nThe following policies apply to the access control resource for this resource:\n- ",t+=`${i.join("\n- ")}\n`),n.length>0&&(t+="\nThe following policies apply to the children of this resource:\n- ",t+=`${n.join("\n- ")}\n`),o.length>0&&(t+="\nThe following policies apply to the access control resources for children of this resource:\n- ",t+=`${o.join("\n- ")}\n`),t}const gi="http://www.w3.org/ns/solid/acp#",yi={AccessControl:gi.concat("AccessControl"),AccessControlResource:gi.concat("AccessControlResource"),AuthenticatedAgent:gi.concat("AuthenticatedAgent"),CreatorAgent:gi.concat("CreatorAgent"),Matcher:gi.concat("Matcher"),Policy:gi.concat("Policy"),PublicAgent:gi.concat("PublicAgent"),access:gi.concat("access"),accessControl:gi.concat("accessControl"),agent:gi.concat("agent"),allOf:gi.concat("allOf"),allow:gi.concat("allow"),anyOf:gi.concat("anyOf"),apply:gi.concat("apply"),client:gi.concat("client"),deny:gi.concat("deny"),memberAccessControl:gi.concat("memberAccessControl"),noneOf:gi.concat("noneOf"),vc:gi.concat("vc")},mi="http://www.w3.org/ns/auth/acl#",vi={Append:mi.concat("Append"),Control:mi.concat("Control"),Read:mi.concat("Read"),Write:mi.concat("Write")};function bi(e){const t=jn(e);return pt(t,$(t))}const wi="defaultAccessControl",_i="defaultAcrAccessControl",Si="defaultMemberAccessControl",Ei="defaultMemberAcrAccessControl";function Ai(e,t){return $(jn(e)).concat("#").concat(t)}function Ri(e,t){const r=jn(e),n=Ai(e,t),i=pt(r,n);return null==i?vt({url:n}):i}function Ii(e,t){const r=rt(e,t);return{read:r.includes(vi.Read),append:r.includes(vi.Append),write:r.includes(vi.Write),controlRead:!1,controlWrite:!1}}function Ti(e,t,r){let n=nr(e,r);return(t.read||t.controlRead)&&(n=Vt(n,r,vi.Read)),t.append&&(n=Vt(n,r,vi.Append)),(t.write||t.controlWrite)&&(n=Vt(n,r,vi.Write)),n}const xi="defaultVcPolicy",Pi="defaultVcMatcher";function Ci(e,t,r={inherit:!1}){var n;let i=jn(e);const o=`${V(i)}#${xi}`,s=`${V(i)}#${Pi}`,{policy:a,matcher:c}=function(e,t,r,n){var i;let o=pt(e,t);null===o&&(o=Cr({url:t}).addIri(P,yi.Policy).addIri(yi.anyOf,r).build());const s=null!==(i=pt(e,r))&&void 0!==i?i:Cr({url:r}).addIri(P,yi.Matcher).addIri(yi.vc,"http://www.w3.org/ns/solid/vc#SolidAccessGrant").build();return o=Ti(o,{...Ii(o,yi.allow),...n},yi.allow),{matcher:s,policy:o}}(i,o,s,t);let l=Ri(e,"defaultAccessControl");rt(l,yi.apply).includes(_t(a))||(l=Vt(l,yi.apply,a));let u=Ri(e,"defaultMemberAccessControl"),d=null!==(n=bi(e))&&void 0!==n?n:vt({url:V(i)});return rt(d,yi.accessControl).includes(_t(l))||(d=Vt(d,yi.accessControl,l)),i=[d,l,a,c].reduce(yt,i),r.inherit&&(rt(u,yi.apply).includes(_t(a))||(u=Vt(u,yi.apply,a)),rt(d,yi.memberAccessControl).includes(_t(u))||(d=Vt(d,yi.memberAccessControl,u)),i=[d,u].reduce(yt,i)),function(e,t){return Object.assign(v(e),{internal_acp:{acr:t}})}(e,i)}const ki={read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1},Oi=(e,t,r)=>rt(e,t).includes(_t(r));function Fi(e){const t=jn(e),r=Ri(e,"defaultAccessControl"),n=bi(e);if(null===n||!Oi(n,yi.accessControl,r))return ki;const i=pt(t,`${V(t)}#${xi}`);if(null===i||!Oi(r,yi.apply,i))return ki;const o=pt(t,`${V(t)}#${Pi}`);return null!==o&&Oi(i,yi.anyOf,o)?Ii(i,yi.allow):ki}async function Ni(e,t=j){const r=g(e),n={...j,...t},i=await Ot(r,n),o=await Wi(i,n);return{...i,...o}}async function Di(e,t=j){const r=g(e),n={...j,...t},i=await Ke(r,n),o=await Wi(i,n);return Object.assign(i,o)}async function Li(e,t=j){const r=g(e),n={...j,...t},i=await M(r,n),o=await Wi(i,n);return{...i,...o}}async function Ui(e,t=j){const r=g(e),n={...j,...t},i=await Ot(r,n);if(sn(i))return Gr(i,await Or(i,n));const o=await Wi(i,n);return{...i,...o}}async function ji(e,t=j){const r=g(e),n={...j,...t},i=await Ke(r,n);if(sn(i))return Gr(i,await Or(i,n));const o=await Wi(i,n);return Object.assign(i,o)}async function Mi(e,t=j){const r=g(e),n={...j,...t},i=await M(r,n);if(sn(i))return Gr(i,await Or(i,n));const o=await Wi(i,n);return{...i,...o}}async function Bi(e,t=j){const r=jn(e),n={...j,...t};return Mn(e,await Ft($(r),r,n))}function Hi(e){return"object"==typeof e.internal_acp&&null!==e.internal_acp&&"object"==typeof e.internal_acp.acr&&null!==e.internal_acp.acr}async function Wi(e,t){let r,n;if(Qn(e)){const{linkedResources:t}=e.internal_resourceInfo;[r]=t[N.accessControl]}else if(sn(e)){let n;try{n=await M(e.internal_resourceInfo.aclUrl,t)}catch(e){}n&&kr(n)&&(r=$(n))}if("string"!=typeof r)return{internal_acp:{acr:null}};try{n=await Ot(r,t)}catch(e){return{internal_acp:{acr:null}}}return{internal_acp:{acr:{...n,accessTo:$(e)}}}}function $i(e){const t=ci(e).map(Pt).concat(li(e).map(Pt)).concat(ei(e).map(Pt)).concat(ti(e).map(Pt));return Array.from(new Set(t))}async function Vi(e,t=j){const r=g(e),n={...j,...t},i=await M(r,n);return Hi(await Wi(i,n))}function Ki(e){if(h(e))return[N.accessControl,"acl"].map((t=>{if(Array.isArray(e.internal_resourceInfo.linkedResources[t])&&1===e.internal_resourceInfo.linkedResources[t].length)return e.internal_resourceInfo.linkedResources[t][0]})).find((e=>void 0!==e))}function Ji(e){return rt(e,P).includes(N.Rule)}function Gi(e,t){return Vt(e,N.allOf,t)}function qi(e,t){return or(e,N.allOf,t)}function zi(e,t){return vr(e,N.allOf,t)}function Yi(e){return rt(e,N.allOf)}function Qi(e,t){return Vt(e,N.anyOf,t)}function Xi(e,t){return or(e,N.anyOf,t)}function Zi(e,t){return vr(e,N.anyOf,t)}function eo(e){return rt(e,N.anyOf)}function to(e,t){return Vt(e,N.noneOf,t)}function ro(e,t){return or(e,N.noneOf,t)}function no(e,t){return vr(e,N.noneOf,t)}function io(e){return rt(e,N.noneOf)}function oo(e){let t=vt({url:g(e)});return t=mr(t,P,N.Rule),t}function so(e,t){const r=jn(e),n=new URL($(r));n.hash=`#${t}`;let i=vt({url:n.href});return i=mr(i,P,N.Rule),i}function ao(e,t){const r=pt(e,t);return null===r||Ze(r,P)!==N.Rule?null:r}function co(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return null!==o&&Ji(o)?o:null}function lo(e){return gt(e).filter(Ji)}function uo(e){return gt(jn(e)).filter(Ji)}function ho(e,t){return mt(e,t)}function fo(e,t){const r=jn(e);let n;if("string"==typeof t)if(Se(t))n=t;else{const e=new URL($(r));e.hash=`#${t}`,n=e.href}else n=be(t)?g(t):wt(t);const i=co(e,new URL(n).hash.substring(1));return null===i?e:Mn(e,mt(r,i))}function po(e,t){return yt(e,t)}function go(e,t){return Mn(e,yt(jn(e),t))}function yo(e){return rt(e,N.agent).filter((e=>e!==N.PublicAgent&&e!==N.AuthenticatedAgent&&e!==N.CreatorAgent))}function mo(e,t){const r=Ao(e),n=To(e),i=Co(e);let o=vr(e,N.agent,t);return r&&(o=Ro(o)),n&&(o=xo(o)),i&&(o=ko(o)),o}function vo(e,t){return Vt(e,N.agent,t)}function bo(e,t){return or(e,N.agent,t)}function wo(e){return rt(e,N.group)}function _o(e,t){return vr(e,N.group,t)}function So(e,t){return Vt(e,N.group,t)}function Eo(e,t){return or(e,N.group,t)}function Ao(e){return rt(e,N.agent).filter((e=>e===N.PublicAgent)).length>0}function Ro(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead.");return Vt(e,N.agent,N.PublicAgent)}function Io(e){return or(e,N.agent,N.PublicAgent)}function To(e){return rt(e,N.agent).filter((e=>e===N.AuthenticatedAgent)).length>0}function xo(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead.");return Vt(e,N.agent,N.AuthenticatedAgent)}function Po(e){return or(e,N.agent,N.AuthenticatedAgent)}function Co(e){return rt(e,N.agent).filter((e=>e===N.CreatorAgent)).length>0}function ko(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead.");return Vt(e,N.agent,N.CreatorAgent)}function Oo(e){return or(e,N.agent,N.CreatorAgent)}function Fo(e){return rt(e,N.client).filter((e=>e!==D))}function No(e,t){const r=Uo(e);let n=vr(e,N.client,t);return r&&(n=jo(n)),n}function Do(e,t){return Vt(e,N.client,t)}function Lo(e,t){return or(e,N.client,t)}function Uo(e){return rt(e,N.client).filter((e=>e===D)).length>0}function jo(e){return Vt(e,N.client,D)}function Mo(e){return or(e,N.client,D)}function Bo(e){let t=`## Rule: ${wt(e)}\n\n`,r="";Ao(e)&&(r+="- Everyone\n"),To(e)&&(r+="- All authenticated agents\n"),Co(e)&&(r+="- The creator of this resource\n"),Uo(e)&&(r+="- Users of any client application\n");const n=yo(e);n.length>0&&(r+="- The following agents:\n - ",r+=`${n.join("\n - ")}\n`);const i=wo(e);i.length>0&&(r+="- Members of the following groups:\n - ",r+=`${i.join("\n - ")}\n`);const o=Fo(e);return o.length>0&&(r+="- Users of the following client applications:\n - ",r+=`${o.join("\n - ")}\n`),t+=r.length>0?`This rule applies to:\n${r}`:"\n",t}function Ho(e){return rt(e,P).includes(N.Policy)}function Wo(e){let t=vt({url:g(e)});return t=mr(t,P,N.Policy),t}function $o(e,t){const r=pt(e,t);return null!==r&&Ho(r)?r:null}function Vo(e){return gt(e).filter((e=>!Et(e)&&Ho(e)))}function Ko(e,t){return mt(e,t)}function Jo(e,t){return yt(e,t)}function Go(e,t){let r=nr(e,N.allow);return!0===t.read&&(r=Vt(r,N.allow,$r.read)),!0===t.append&&(r=Vt(r,N.allow,$r.append)),!0===t.write&&(r=Vt(r,N.allow,$r.write)),r}function qo(e,t){let r=nr(e,N.allow);return!0===t.read&&(r=Vt(r,N.allow,N.Read)),!0===t.append&&(r=Vt(r,N.allow,N.Append)),!0===t.write&&(r=Vt(r,N.allow,N.Write)),r}function zo(e){const t=rt(e,N.allow);return{read:t.includes($r.read),append:t.includes($r.append),write:t.includes($r.write)}}function Yo(e){const t=rt(e,N.allow);return{read:t.includes(N.Read),append:t.includes(N.Append),write:t.includes(N.Write)}}function Qo(e,t){let r=nr(e,N.deny);return!0===t.read&&(r=Vt(r,N.deny,$r.read)),!0===t.append&&(r=Vt(r,N.deny,$r.append)),!0===t.write&&(r=Vt(r,N.deny,$r.write)),r}function Xo(e,t){let r=nr(e,N.deny);return!0===t.read&&(r=Vt(r,N.deny,N.Read)),!0===t.append&&(r=Vt(r,N.deny,N.Append)),!0===t.write&&(r=Vt(r,N.deny,N.Write)),r}function Zo(e){const t=rt(e,N.deny);return{read:t.includes($r.read),append:t.includes($r.append),write:t.includes($r.write)}}function es(e){const t=rt(e,N.deny);return{read:t.includes(N.Read),append:t.includes(N.Append),write:t.includes(N.Write)}}function ts(e,t){const r=jn(e),n=new URL($(r));n.hash=`#${t}`;let i=vt({url:n.href});return i=mr(i,P,N.Policy),i}function rs(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return ci(e).includes(i.href)&&null!==o&&Ho(o)?o:null}function ns(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return ei(e).includes(i.href)&&null!==o&&Ho(o)?o:null}function is(e){const t=jn(e);return ci(e).map((e=>pt(t,e))).filter((e=>null!==e&&Ho(e)))}function os(e){const t=jn(e);return ei(e).map((e=>pt(t,e))).filter((e=>null!==e&&Ho(e)))}function ss(e,t){const r=jn(e);let n,i=t;if("string"==typeof i&&!1===Se(i)){const e=new URL($(r));e.hash=`#${t}`,i=e.href}return n="string"==typeof i?i:be(i)?g(i):wt(i,$(r)),null===rs(e,new URL(n).hash.substring(1))?e:ui(Mn(e,mt(r,i)),n)}function as(e,t){const r=jn(e);let n,i=t;if("string"==typeof i&&!1===Se(i)){const e=new URL($(r));e.hash=`#${t}`,i=e.href}return n="string"==typeof i?i:be(i)?g(i):wt(i,$(r)),null===ns(e,new URL(n).hash.substring(1))?e:ri(Mn(e,mt(r,i)),n)}function cs(e,t){const r=jn(e);return si(Mn(e,yt(r,t)),wt(t,$(r)))}function ls(e,t){const r=jn(e);return Xn(Mn(e,yt(r,t)),wt(t,$(r)))}function us(e){function t(e,t){return t?"denied":e?"allowed":"unspecified"}const r=Yo(e),n=es(e);let i=`## Policy: ${wt(e)}\n\n`;i+=`- Read: ${t(r.read,n.read)}\n`,i+=`- Append: ${t(r.append,n.append)}\n`,i+=`- Write: ${t(r.write,n.write)}\n`;const o=Yi(e),s=eo(e),a=io(e);return 0===o.length&&0===s.length&&0===a.length&&(i+="\n\n"),o.length>0&&(i+="\nAll of these rules should match:\n",i+=`- ${o.join("\n- ")}\n`),s.length>0&&(i+="\nAt least one of these rules should match:\n",i+=`- ${s.join("\n- ")}\n`),a.length>0&&(i+="\nNone of these rules should match:\n",i+=`- ${a.join("\n- ")}\n`),i}function ds(e){return{...Ht(new URL("access-control-resource",e).href),accessTo:e}}function hs(e,t=ds($(e))){return Object.assign(v(e),{internal_acp:{acr:t,aprs:{}}})}function fs(e,t){return t?Ro(e):Io(e)}function ps(e,t){return t?xo(e):Po(e)}function gs(e,t){return t?ko(e):Oo(e)}const ys={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,acrAsMarkdown:pi,addAcrPolicyUrl:Xn,addMemberAcrPolicyUrl:Zn,addMemberPolicyUrl:ai,addPolicyUrl:si,getAcrPolicyUrlAll:ei,getMemberAcrPolicyUrlAll:ti,getMemberPolicyUrlAll:li,getPolicyUrlAll:ci,hasLinkedAcr:Qn,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:di,removeMemberPolicyUrlAll:fi,removePolicyUrl:ui,removePolicyUrlAll:hi,createPolicy:Wo,getAllowModes:Yo,getDenyModes:es,getPolicy:$o,getPolicyAll:Vo,policyAsMarkdown:us,removePolicy:Ko,setAllowModes:qo,setDenyModes:Xo,setPolicy:Jo,addAgent:vo,addForbiddenRuleUrl:to,addGroup:So,addOptionalRuleUrl:Qi,addRequiredRuleUrl:Gi,createRule:oo,getAgentAll:yo,getForbiddenRuleUrlAll:io,getGroupAll:wo,getOptionalRuleUrlAll:eo,getRequiredRuleUrlAll:Yi,getRule:ao,getRuleAll:lo,hasAuthenticated:To,hasCreator:Co,hasPublic:Ao,removeAgent:bo,removeForbiddenRuleUrl:ro,removeGroup:Eo,removeOptionalRuleUrl:Xi,removeRequiredRuleUrl:qi,removeRule:ho,ruleAsMarkdown:Bo,setAgent:mo,setForbiddenRuleUrl:no,setGroup:_o,setOptionalRuleUrl:Zi,setRequiredRuleUrl:zi,setRule:po,addMockAcrTo:hs,mockAcrFor:ds,getForbiddenRuleurlAll:io,setPublic:fs,setAuthenticated:ps,setCreator:gs},ms={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,createPolicy:Wo,getAllowModes:Yo,getDenyModes:es,getPolicy:$o,getPolicyAll:Vo,policyAsMarkdown:us,removePolicy:Ko,setAllowModes:qo,setDenyModes:Xo,setPolicy:Jo,addAgent:vo,addForbiddenRuleUrl:to,addGroup:So,addOptionalRuleUrl:Qi,addRequiredRuleUrl:Gi,createRule:oo,getAgentAll:yo,getForbiddenRuleUrlAll:io,getGroupAll:wo,getOptionalRuleUrlAll:eo,getRequiredRuleUrlAll:Yi,getRule:ao,getRuleAll:lo,hasAuthenticated:To,hasCreator:Co,hasPublic:Ao,removeAgent:bo,removeForbiddenRuleUrl:ro,removeGroup:Eo,removeOptionalRuleUrl:Xi,removeRequiredRuleUrl:qi,removeRule:ho,ruleAsMarkdown:Bo,setAgent:mo,setForbiddenRuleUrl:no,setGroup:_o,setOptionalRuleUrl:Zi,setRequiredRuleUrl:zi,setRule:po,addMockAcrTo:hs,mockAcrFor:ds,hasLinkedAcr:Qn,addAcrPolicyUrl:Xn,addMemberAcrPolicyUrl:Zn,getAcrPolicyUrlAll:ei,getMemberAcrPolicyUrlAll:ti,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,createControl:Bn,getControl:function(e,t,r){const n=pt(jn(e),t,r);return null!==n&&rt(n,P).includes(N.AccessControl)?n:null},getAllControl:Hn,getControlAll:Hn,setControl:Wn,removeControl:function(e,t){return Mn(e,mt(jn(e),t))},addPolicyUrl:$n,getPolicyUrlAll:Vn,removePolicyUrl:Kn,removePolicyUrlAll:Jn,addMemberPolicyUrl:Gn,getMemberPolicyUrlAll:qn,removeMemberPolicyUrl:qn,removeMemberPolicyUrlAll:zn,getForbiddenRuleurlAll:io,setPublic:fs,setAuthenticated:ps,setCreator:gs},vs={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getLinkedAcrUrl:Ki,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,isAcpControlled:Vi,acrAsMarkdown:pi,addAcrPolicyUrl:Xn,addMemberAcrPolicyUrl:Zn,addMemberPolicyUrl:ai,addPolicyUrl:si,getAcrPolicyUrlAll:ei,getMemberAcrPolicyUrlAll:ti,getMemberPolicyUrlAll:li,getPolicyUrlAll:ci,hasLinkedAcr:Qn,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:di,removeMemberPolicyUrlAll:fi,removePolicyUrl:ui,removePolicyUrlAll:hi,createPolicy:Wo,getAllowModes:Yo,getDenyModes:es,getPolicy:$o,getPolicyAll:Vo,policyAsMarkdown:us,removePolicy:Ko,setAllowModes:qo,setDenyModes:Xo,setPolicy:Jo,createResourcePolicyFor:ts,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourcePolicy:rs,getResourcePolicyAll:is,removeResourceAcrPolicy:as,removeResourcePolicy:ss,setResourceAcrPolicy:ls,setResourcePolicy:cs,addAgent:vo,addGroup:So,createRule:oo,getAgentAll:yo,getGroupAll:wo,getRule:ao,getRuleAll:lo,removeAgent:bo,removeGroup:Eo,removeRule:ho,ruleAsMarkdown:Bo,setAgent:mo,setGroup:_o,setRule:po,addClient:Do,getClientAll:Fo,hasAnyClient:Uo,removeClient:Lo,setAnyClient:jo,setClient:No,removeAnyClient:Mo,hasAuthenticated:To,hasCreator:Co,hasPublic:Ao,setAuthenticated:xo,setCreator:ko,setPublic:Ro,removeAuthenticated:Po,removeCreator:Oo,removePublic:Io,getAnyOfRuleUrlAll:eo,addAnyOfRuleUrl:Qi,removeAnyOfRuleUrl:Xi,setAnyOfRuleUrl:Zi,getAllOfRuleUrlAll:Yi,addAllOfRuleUrl:Gi,removeAllOfRuleUrl:qi,setAllOfRuleUrl:zi,getNoneOfRuleUrlAll:io,addNoneOfRuleUrl:to,removeNoneOfRuleUrl:ro,setNoneOfRuleUrl:no,createResourceRuleFor:so,getResourceRule:co,getResourceRuleAll:uo,removeResourceRule:fo,setResourceRule:go,addMockAcrTo:hs,mockAcrFor:ds};function bs(e,t){return Object.assign(v(e),{internal_acp:{...e.internal_acp,acr:yt(e.internal_acp.acr,t)}})}function ws(e){return e.includes("Member")?yi.memberAccessControl:yi.accessControl}function _s(e,t){const r=Ai(e,t),n=jn(e);let i=bi(e);return null==i&&(i=vt({url:$(n)})),rt(i,ws(t)).includes(r)?e:(i=Cr(i).addUrl(ws(t),r).build(),bs(e,i))}function Ss(e,t){const r=_s(e,_i);return bs(r,Cr(Ri(r,_i)).addUrl(yi.access,t).build())}function Es(e,t){const r=_s(e,Ei);return bs(r,Cr(Ri(r,Ei)).addUrl(yi.access,t).build())}function As(e,t){const r=_s(e,Si);return bs(r,Cr(Ri(r,Si)).addUrl(yi.apply,t).build())}function Rs(e,t){const r=_s(e,wi);return bs(r,Cr(Ri(r,wi)).addUrl(yi.apply,t).build())}function Is(e){const t=bi(e);return null===t?[]:rt(t,yi.accessControl)}function Ts(e,t,r){const n=jn(e);return Array.from(new Set(t.map((e=>{const t=pt(n,e);return null!==t?rt(t,r):[]})).reduce(((e,t)=>e.concat(t)),[])))}function xs(e){return Ts(e,Is(e),yi.access)}function Ps(e){const t=bi(e);return null===t?[]:rt(t,yi.memberAccessControl)}function Cs(e){return Ts(e,Ps(e),yi.access)}function ks(e){return Ts(e,Ps(e),yi.apply)}function Os(e){return Ts(e,Is(e),yi.apply)}function Fs(e,t){const r=Ri(e,_i);return bs(e,or(r,yi.access,t))}function Ns(e,t){const r=Ri(e,Ei);return bs(e,or(r,yi.access,t))}function Ds(e,t){const r=Ri(e,Si);return bs(e,or(r,yi.apply,t))}function Ls(e,t){const r=Ri(e,wi);return bs(e,or(r,yi.apply,t))}function Us(e,t){return bs(e,t)}function js(e){return rt(e,P).includes(N.Matcher)}function Ms(e,t){return Vt(e,N.allOf,t)}function Bs(e,t){return or(e,N.allOf,t)}function Hs(e,t){return vr(e,N.allOf,t)}function Ws(e){return rt(e,N.allOf)}function $s(e,t){return Vt(e,N.anyOf,t)}function Vs(e,t){return or(e,N.anyOf,t)}function Ks(e,t){return vr(e,N.anyOf,t)}function Js(e){return rt(e,N.anyOf)}function Gs(e,t){return Vt(e,N.noneOf,t)}function qs(e,t){return or(e,N.noneOf,t)}function zs(e,t){return vr(e,N.noneOf,t)}function Ys(e){return rt(e,N.noneOf)}function Qs(e){let t=vt({url:g(e)});return t=mr(t,P,N.Matcher),t}function Xs(e,t){const r=jn(e),n=new URL($(r));n.hash=`#${t}`;let i=vt({url:n.href});return i=mr(i,P,N.Matcher),i}function Zs(e,t){const r=pt(e,t);return null!==r&&js(r)?r:null}function ea(e,t){const r=jn(e),n=$(r),i=new URL(n);i.hash=`#${t}`;const o=pt(r,i.href);return null!==o&&js(o)?o:null}function ta(e){return gt(e).filter(js)}function ra(e){return gt(jn(e)).filter(js)}function na(e,t){return mt(e,t)}function ia(e,t){const r=jn(e);let n;if("string"==typeof t)if(Se(t))n=t;else{const e=new URL($(r));e.hash=`#${t}`,n=e.href}else n=be(t)?g(t):wt(t);const i=ea(e,new URL(n).hash.substring(1));return null===i?e:Mn(e,mt(r,i))}function oa(e,t){return yt(e,t)}function sa(e,t){return Mn(e,yt(jn(e),t))}function aa(e){return rt(e,N.agent).filter((e=>e!==N.PublicAgent&&e!==N.AuthenticatedAgent&&e!==N.CreatorAgent))}function ca(e,t){const r=da(e),n=pa(e),i=ma(e);let o=vr(e,N.agent,t);return r&&(o=ha(o)),n&&(o=ga(o)),i&&(o=va(o)),o}function la(e,t){return Vt(e,N.agent,t)}function ua(e,t){return or(e,N.agent,t)}function da(e){return rt(e,N.agent).filter((e=>e===N.PublicAgent)).length>0}function ha(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead.");return Vt(e,N.agent,N.PublicAgent)}function fa(e){return or(e,N.agent,N.PublicAgent)}function pa(e){return rt(e,N.agent).filter((e=>e===N.AuthenticatedAgent)).length>0}function ga(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead.");return Vt(e,N.agent,N.AuthenticatedAgent)}function ya(e){return or(e,N.agent,N.AuthenticatedAgent)}function ma(e){return rt(e,N.agent).filter((e=>e===N.CreatorAgent)).length>0}function va(e){if("object"==typeof arguments&&"boolean"==typeof arguments[1])throw new Error("The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead.");return Vt(e,N.agent,N.CreatorAgent)}function ba(e){return or(e,N.agent,N.CreatorAgent)}function wa(e){return rt(e,N.client).filter((e=>e!==D)).concat(ot(e,N.client))}function _a(e,t){return Se(t)?Vt(e,N.client,t):Xt(e,N.client,t)}function Sa(e,t){return Se(t)?or(e,N.client,t):fr(e,N.client,t)}function Ea(e){return rt(e,N.client).filter((e=>e===D)).length>0}function Aa(e){return Vt(e,N.client,D)}const Ra={getFileWithAccessDatasets:ji,getFileWithAcr:Di,getReferencedPolicyUrlAll:$i,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,saveAcrFor:Bi,isAcpControlled:Vi,getVcAccess:Fi,setVcAccess:Ci,addAcrPolicyUrl:Ss,addMemberAcrPolicyUrl:Es,addMemberPolicyUrl:As,addPolicyUrl:Rs,getAcrPolicyUrlAll:xs,getMemberAcrPolicyUrlAll:Cs,getMemberPolicyUrlAll:ks,getPolicyUrlAll:Os,hasLinkedAcr:Qn,removeAcrPolicyUrl:Fs,removeAcrPolicyUrlAll:ii,removeMemberAcrPolicyUrl:Ns,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:Ds,removeMemberPolicyUrlAll:fi,removePolicyUrl:Ls,removePolicyUrlAll:hi,createPolicy:Wo,getAllowModes:zo,getDenyModes:Zo,getPolicy:$o,getPolicyAll:Vo,removePolicy:Ko,setAllowModes:Go,setDenyModes:Qo,setPolicy:Jo,createResourcePolicyFor:ts,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourcePolicy:rs,getResourcePolicyAll:is,removeResourceAcrPolicy:as,removeResourcePolicy:ss,setResourcePolicy:Us,addAgent:la,createMatcher:Qs,getAgentAll:aa,getMatcher:Zs,getMatcherAll:ta,removeAgent:ua,removeMatcher:na,setAgent:ca,setMatcher:oa,addClient:_a,getClientAll:wa,hasAnyClient:Ea,removeClient:Sa,setAnyClient:Aa,setClient:function(e,t){const r=Ea(e);let n=vr(e,N.client,t);return r&&(n=Aa(n)),n},removeAnyClient:function(e){return or(e,N.client,D)},hasAuthenticated:pa,hasCreator:ma,hasPublic:da,setAuthenticated:ga,setCreator:va,setPublic:ha,removeAuthenticated:ya,removeCreator:ba,removePublic:fa,getAnyOfMatcherUrlAll:Js,addAnyOfMatcherUrl:$s,removeAnyOfMatcherUrl:Vs,setAnyOfMatcherUrl:Ks,getAllOfMatcherUrlAll:Ws,addAllOfMatcherUrl:Ms,removeAllOfMatcherUrl:Bs,setAllOfMatcherUrl:Hs,getNoneOfMatcherUrlAll:Ys,addNoneOfMatcherUrl:Gs,removeNoneOfMatcherUrl:qs,setNoneOfMatcherUrl:zs,createResourceMatcherFor:Xs,getResourceMatcher:ea,getResourceMatcherAll:ra,removeResourceMatcher:ia,setResourceMatcher:sa,addMockAcrTo:hs,mockAcrFor:ds},Ia=[N.agent,N.group];function Ta(e,t,r){if(e.inaccessibleUrls.length>0)return null;const n=e.acrPolicies.filter((n=>xa(n,t,r,e))),i=e.policies.filter((n=>xa(n,t,r,e))),o=n.reduce(((e,t)=>{const r={...e},n=Yo(t);return n.read&&(r.controlRead=!0),n.write&&(r.controlWrite=!0),r}),{read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1}),s=i.reduce(((e,t)=>{const r={...e},n=Yo(t);return n.read&&(r.read=!0),n.append&&(r.append=!0),n.write&&(r.write=!0),r}),o),a=n.reduce(((e,t)=>{const r={...e},n=es(t);return!0===n.read&&(r.controlRead=!1),!0===n.write&&(r.controlWrite=!1),r}),s);return i.reduce(((e,t)=>{const r={...e},n=es(t);return!0===n.read&&(r.read=!1),!0===n.append&&(r.append=!1),!0===n.write&&(r.write=!1),r}),a)}function xa(e,t,r,n){const i=rt(e,N.allow),o=rt(e,N.deny);if(i.length+o.length===0)return!1;const s=Yi(e).map((e=>n.rules.find((t=>_t(t)===e)))),a=eo(e).map((e=>n.rules.find((t=>_t(t)===e)))),c=io(e).map((e=>n.rules.find((t=>_t(t)===e))));return s.every((e=>Ca(e,t,r)))&&(0===a.length||a.some((e=>Ca(e,t,r))))&&0===c.length}function Pa(e,t){const r=rt(e,N.allow),n=rt(e,N.deny);return!0===t.read&&n.includes(N.Read)||!1===t.read&&r.includes(N.Read)&&!n.includes(N.Read)||!0===t.append&&n.includes(N.Append)||!1===t.append&&r.includes(N.Append)&&!n.includes(N.Append)||!0===t.write&&n.includes(N.Write)||!1===t.write&&r.includes(N.Write)&&!n.includes(N.Write)}function Ca(e,t,r){let n=!0;return Ia.forEach((t=>{n&&(n=null===et(e,t))})),n||rt(e,t).includes(r)}function ka(e,t){if(e.inaccessibleUrls.length>0)return null;const r={},n=function(e,t){const r=new Set;return e.rules.forEach((e=>{rt(e,t).filter((e=>![N.PublicAgent,N.CreatorAgent,N.AuthenticatedAgent].includes(e)||t!==N.agent)).forEach((e=>r.add(e)))})),r}(e,t);return n.forEach((n=>{const i=Ta(e,t,n);r[n]=i})),r}function Oa(e,t,r,n,i){var o,s,a,c,l;if(!Hi(e)||t.inaccessibleUrls.length>0)return null;const d=Ta(t,r,n);if(null===d)return null;const h=t.acrPolicies.filter((e=>xa(e,r,n,t))),f=t.policies.filter((e=>xa(e,r,n,t))),p=h.filter((e=>Pa(e,{read:i.controlRead,write:i.controlWrite}))),g=f.filter((e=>Pa(e,{read:i.read,append:i.append,write:i.write}))),y=p.filter((e=>Fa(e,r,n,t))),m=g.filter((e=>Fa(e,r,n,t))),v=Ta({...t,acrPolicies:t.acrPolicies.filter((e=>!y.includes(e))),policies:t.policies.filter((e=>!m.includes(e)))},r,n);if(null===v)return null;let b=e;y.forEach((i=>{const[o,s]=Da(i,e,t,r,n);b=ls(b,o),b=s.reduce(go,b)})),m.forEach((i=>{const[o,s]=Da(i,e,t,r,n);b=cs(b,o),b=s.reduce(go,b)}));const w=`rule_${encodeURIComponent(`${r}_${n}`)}`;let _=so(e,w);_=vr(_,r,n);const S=null!==(o=i.controlRead)&&void 0!==o?o:d.controlRead,E=null!==(s=i.controlWrite)&&void 0!==s?s:d.controlWrite;let A=y;if(S!==v.controlRead||E!==v.controlWrite){const t=u.v4();let r=ts(e,t);r=qo(r,{read:!0===S,append:!1,write:!0===E}),r=Vt(r,N.allOf,_),b=ls(b,r),b=go(b,_),A=p}const R=null!==(a=i.read)&&void 0!==a?a:d.read,I=null!==(c=i.append)&&void 0!==c?c:d.append,T=null!==(l=i.write)&&void 0!==l?l:d.write;let x=m;if(R!==v.read||I!==v.append||T!==v.write){const t=u.v4();let r=ts(e,t);r=qo(r,{read:!0===R,append:!0===I,write:!0===T}),r=Vt(r,N.allOf,_),b=cs(b,r),b=go(b,_),x=g}return A.forEach((e=>{b=ri(b,_t(e))})),x.forEach((e=>{b=ui(b,_t(e))})),b}function Fa(e,t,r,n){const i=rt(e,N.allOf).map((e=>n.rules.find((t=>_t(t)===e)))).some((e=>Na(e,t,r))),o=rt(e,N.anyOf).map((e=>n.rules.find((t=>_t(t)===e)))).some((e=>Na(e,t,r))),s=rt(e,N.noneOf).map((e=>n.rules.find((t=>_t(t)===e)))).some((e=>Na(e,t,r)));return i||o||s}function Na(e,t,r){const n=[];return Ia.forEach((i=>{const o=rt(e,i).filter((e=>e!==r||i!==t));n.push(...o)})),n.length>0}function Da(e,t,r,n,i){const o=u.v4(),s=La(rt(e,N.allOf),t,r,o,n,i),a=La(rt(e,N.anyOf),t,r,o,n,i),c=La(rt(e,N.noneOf),t,r,o,n,i);let l=ts(t,encodeURI(_t(e))+o);return rt(e,N.allow).forEach((e=>{l=Vt(l,N.allow,e)})),rt(e,N.deny).forEach((e=>{l=Vt(l,N.deny,e)})),s.forEach((e=>{l=Vt(l,N.allOf,e)})),a.forEach((e=>{l=Vt(l,N.anyOf,e)})),c.forEach((e=>{l=Vt(l,N.noneOf,e)})),[l,s.concat(a).concat(c)]}function La(e,t,r,n,i,o){return e.map((e=>{const s=r.rules.find((t=>_t(t)===e));if(void 0===s)return null;let a=so(t,encodeURI(_t(s))+n),c=!1;return Ia.forEach((e=>{rt(s,e).forEach((t=>{e===i&&t===o||(c=!0,a=Vt(a,e,t))}))})),c?a:null})).filter(Ua)}function Ua(e){return null!==e}async function ja(e,t=j){const r=ei(e),n=ci(e),i=Ba(r).concat(Ba(n)),o=await Ha(i,t),s=Wa(r,o).filter(Ua),a=Wa(n,o).filter(Ua),c=new Set;s.forEach((e=>{$a(e).forEach((e=>{c.add(e)}))})),a.forEach((e=>{$a(e).forEach((e=>{c.add(e)}))}));const l=Array.from(c),u=l.map((e=>Ma(e))).filter((e=>!i.includes(e))),d=await Ha(u,t),h={...o,...d},f=Wa(l,h).filter(Ua);return{inaccessibleUrls:Object.keys(h).filter((e=>null===h[e])),acrPolicies:s,policies:a,rules:f}}function Ma(e){const t=new URL(e);return t.hash="",t.href}function Ba(e){const t=[];return e.forEach((e=>{const r=Ma(e);t.includes(r)||t.push(r)})),t}async function Ha(e,t){const r=Array.from(new Set(e)),n={};return await Promise.all(r.map((async e=>{try{const r=await Ot(e,t);n[e]=r}catch(t){n[e]=null}}))),n}function Wa(e,t){return e.map((e=>{const r=Ma(e),n=t[r];return n?pt(n,e):null}))}function $a(e){return Yi(e).concat(eo(e)).concat(io(e))}function Va(e,t){var r,n,i,o;if(e.controlRead!==e.controlWrite)throw new Error("For Pods using Web Access Control, controlRead and controlWrite must be equal.");return{read:null!==(r=e.read)&&void 0!==r?r:t.read,append:null!==(n=e.append)&&void 0!==n?n:t.append,write:null!==(i=e.write)&&void 0!==i?i:t.write,control:null!==(o=e.controlRead)&&void 0!==o?o:t.control}}function Ka(e){return{read:e.read,write:e.write,append:e.append,controlRead:e.control,controlWrite:e.control}}async function Ja(e,t,r,n){const i=r(Gr(e,await Or(e,n)),t);return null===i?null:Ka(i)}async function Ga(e,t,r){const n=t(Gr(e,await Or(e,r)));if(null===n)return null;const i={};for(const[e,t]of Object.entries(n))i[e]=Ka(t);return i}function qa(e,t,r=j){return Ja(e,t,an,r)}function za(e,t,r=j){return Ja(e,t,vn,r)}function Ya(e,t=j){return async function(e,t,r){const n=t(Gr(e,await Or(e,r)));return null===n?null:Ka(n)}(e,Tn,t)}function Qa(e,t=j){return Ga(e,cn,t)}async function Xa(e,t){if(!sn(e))return null;const r=Gr(e,await Or(e,t));let n;if(Xr(r))n=function(e){return e.internal_acl.resourceAcl}(r);else{if(!en(r))return null;n=nn(r)}return Yr(r,n)}async function Za(e,t,r){let n=null;try{return n=await on(e,t,r),Yr(e,n)}catch(e){return null}}async function ec(e,t,r,n,i,o){const s=await Xa(e,o);if(null===s)return null;const a=n(s,t);return Za(s,i(Zr(s),t,Va(r,a)),o)}async function tc(e,t,r,n=j){return ec(e,t,r,an,dn,n)}async function rc(e,t,r=j){return async function(e,t,r,n,i){const o=await Xa(e,i);return null===o?null:Za(o,n(Zr(o),Va(t,r(o))),i)}(e,t,Tn,Cn,r)}var nc=Object.freeze({__proto__:null,getAccessFor:ic,getAccessForAll:oc,getAgentAccess:ac,getAgentAccessAll:lc,getGroupAccess:uc,getGroupAccessAll:dc,getPublicAccess:fc,setAccessFor:sc,setAgentAccess:cc,setGroupAccess:hc,setPublicAccess:pc});async function ic(e,t,r=j,n=j){if("agent"===t){if("string"!=typeof r)throw new Error("When reading Agent-specific access, the given agent cannot be left undefined.");return ac(e,r,n)}if("group"===t){if("string"!=typeof r)throw new Error("When reading Group-specific access, the given group cannot be left undefined.");return uc(e,r,n)}if("public"===t){if("string"==typeof r)throw new Error(`When reading public access, no actor type should be specified (here [${r}]).`);return fc(e,r)}return null}async function oc(e,t,r=j){return"agent"===t?lc(e,r):"group"===t?dc(e,r):null}async function sc(e,t,r,n=j,i=j){if("agent"===t){if("string"!=typeof n)throw new Error("When writing Agent-specific access, the given agent cannot be left undefined.");return cc(e,n,r,i)}if("group"===t){if("string"!=typeof n)throw new Error("When writing Group-specific access, the given group cannot be left undefined.");return hc(e,n,r,i)}if("public"===t){if("string"==typeof n)throw new Error(`When writing public access, no actor type should be specified (here [${n}]).`);return pc(e,r,n)}return null}async function ac(e,t,r=j){const n=await Li(e,r);return Hi(n)?function(e,t){return Ta(e,N.agent,t)}(await ja(n,r),t):sn(n)?qa(n,t,r):null}async function cc(e,t,r,n=j){const i=await Li(e,n);if(Hi(i)){const o=function(e,t,r,n){return Oa(e,t,N.agent,r,n)}(i,await ja(i,n),t,r);if(o)try{return await Bi(o,n),await ac(e,t,n)}catch(e){return null}return null}if(sn(i)){if(r.controlRead!==r.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(i)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=r;return await tc(i,t,e,n),qa(i,t,n)}return null}async function lc(e,t=j){const r=await Li(e,t);return Hi(r)?ka(await ja(r,t),N.agent):sn(r)?Qa(r,t):null}async function uc(e,t,r=j){const n=await Li(e,r);return Hi(n)?(i=await ja(n,r),o=t,Ta(i,N.group,o)):sn(n)?za(n,t,r):null;var i,o}async function dc(e,t=j){const r=await Li(e,t);return Hi(r)?ka(await ja(r,t),N.group):sn(r)?function(e,t=j){return Ga(e,bn,t)}(r,t):null}async function hc(e,t,r,n=j){const i=await Li(e,n);if(Hi(i)){const o=function(e,t,r,n){return Oa(e,t,N.group,r,n)}(i,await ja(i,n),t,r);if(o)try{return await Bi(o,n),await uc(e,t,n)}catch(e){return null}return null}if(sn(i)){if(r.controlRead!==r.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(i)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=r;return await async function(e,t,r,n=j){return ec(e,t,r,vn,In,n)}(i,t,e,n),za(i,t,n)}return null}async function fc(e,t=j){const r=await Li(e,t);return Hi(r)?Ta(await ja(r,t),N.agent,N.PublicAgent):sn(r)?Ya(r,t):null}async function pc(e,t,r=j){const n=await Li(e,r);if(Hi(n)){const i=function(e,t,r){return Oa(e,t,N.agent,N.PublicAgent,r)}(n,await ja(n,r),t);if(i)try{return await Bi(i,r),await fc(e,r)}catch(e){return null}return null}if(sn(n)){if(t.controlRead!==t.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(n)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=t;return await rc(n,e,r),Ya(n,r)}return null}var gc=Object.freeze({__proto__:null,getAccessFor:ic,getAccessForAll:oc,getAgentAccess:ac,getAgentAccessAll:lc,getGroupAccess:uc,getGroupAccessAll:dc,getPublicAccess:fc,setAccessFor:sc,setAgentAccess:cc,setGroupAccess:hc,setPublicAccess:pc});const yc=[N.agent];function mc(e,t,r){if(e.inaccessibleUrls.length>0)return null;const n=e.acrPolicies.filter((n=>vc(n,t,r,e))),i=e.policies.filter((n=>vc(n,t,r,e))),o=n.reduce(((e,t)=>{const r={...e},n=zo(t);return n.read&&(r.controlRead=!0),n.write&&(r.controlWrite=!0),r}),{read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1}),s=i.reduce(((e,t)=>{const r={...e},n=zo(t);return n.read&&(r.read=!0),n.append&&(r.append=!0),n.write&&(r.write=!0),r}),o),a=n.reduce(((e,t)=>{const r={...e},n=Zo(t);return!0===n.read&&(r.controlRead=!1),!0===n.write&&(r.controlWrite=!1),r}),s);return i.reduce(((e,t)=>{const r={...e},n=Zo(t);return!0===n.read&&(r.read=!1),!0===n.append&&(r.append=!1),!0===n.write&&(r.write=!1),r}),a)}function vc(e,t,r,n){const i=rt(e,N.allow),o=rt(e,N.deny);if(i.length+o.length===0)return!1;const s=Ws(e).map((e=>n.matchers.find((t=>_t(t)===e)))),a=Js(e).map((e=>n.matchers.find((t=>_t(t)===e)))),c=Ys(e).map((e=>n.matchers.find((t=>_t(t)===e))));return s.every((e=>wc(e,t,r)))&&(0===a.length||a.some((e=>wc(e,t,r))))&&s.length+a.length>0&&0===c.length}function bc(e,t){const r=rt(e,N.allow),n=rt(e,N.deny);return!0===t.read&&n.includes($r.read)||!1===t.read&&r.includes($r.read)&&!n.includes($r.read)||!0===t.append&&n.includes($r.append)||!1===t.append&&r.includes($r.append)&&!n.includes($r.append)||!0===t.write&&n.includes($r.write)||!1===t.write&&r.includes($r.write)&&!n.includes($r.write)}function wc(e,t,r){return rt(e,t).includes(r)}function _c(e,t,r,n,i){var o,s,a,c,l;if(!Hi(e)||t.inaccessibleUrls.length>0)return null;const d=mc(t,r,n);if(null===d)return null;const h=t.acrPolicies.filter((e=>vc(e,r,n,t))),f=t.policies.filter((e=>vc(e,r,n,t))),p=h.filter((e=>bc(e,{read:i.controlRead,write:i.controlWrite}))),g=f.filter((e=>bc(e,{read:i.read,append:i.append,write:i.write}))),y=p.filter((e=>Sc(e,r,n,t))),m=g.filter((e=>Sc(e,r,n,t))),v=mc({...t,acrPolicies:t.acrPolicies.filter((e=>!y.includes(e))),policies:t.policies.filter((e=>!m.includes(e)))},r,n);if(null===v)return null;let b=e;y.forEach((i=>{const[o,s]=Ac(i,e,t,r,n);b=ls(b,o),b=s.reduce(sa,b)})),m.forEach((i=>{const[o,s]=Ac(i,e,t,r,n);b=cs(b,o),b=s.reduce(sa,b)}));const w=`matcher_${encodeURIComponent(`${r}_${n}`)}`;let _=Xs(e,w);_=vr(_,r,n);const S=null!==(o=i.controlRead)&&void 0!==o?o:d.controlRead,E=null!==(s=i.controlWrite)&&void 0!==s?s:d.controlWrite;let A=y;if(S!==v.controlRead||E!==v.controlWrite){const t=u.v4();let r=ts(e,t);r=Go(r,{read:!0===S,append:!1,write:!0===E}),r=Vt(r,N.allOf,_),b=ls(b,r),b=sa(b,_),A=p}const R=null!==(a=i.read)&&void 0!==a?a:d.read,I=null!==(c=i.append)&&void 0!==c?c:d.append,T=null!==(l=i.write)&&void 0!==l?l:d.write;let x=m;if(R!==v.read||I!==v.append||T!==v.write){const t=u.v4();let r=ts(e,t);r=Go(r,{read:!0===R,append:!0===I,write:!0===T}),r=Vt(r,N.allOf,_),b=cs(b,r),b=sa(b,_),x=g}return A.forEach((e=>{b=ri(b,_t(e))})),x.forEach((e=>{b=ui(b,_t(e))})),b}function Sc(e,t,r,n){const i=rt(e,N.allOf).map((e=>n.matchers.find((t=>_t(t)===e)))).some((e=>Ec(e,t,r))),o=rt(e,N.anyOf).map((e=>n.matchers.find((t=>_t(t)===e)))).some((e=>Ec(e,t,r))),s=rt(e,N.noneOf).map((e=>n.matchers.find((t=>_t(t)===e)))).some((e=>Ec(e,t,r)));return i||o||s}function Ec(e,t,r){const n=[];return yc.forEach((i=>{const o=rt(e,i).filter((e=>e!==r||i!==t));n.push(...o)})),n.length>0}function Ac(e,t,r,n,i){const o=u.v4(),s=Rc(rt(e,N.allOf),t,r,o,n,i),a=Rc(rt(e,N.anyOf),t,r,o,n,i),c=Rc(rt(e,N.noneOf),t,r,o,n,i);let l=ts(t,encodeURI(_t(e))+o);return rt(e,N.allow).forEach((e=>{l=Vt(l,N.allow,e)})),rt(e,N.deny).forEach((e=>{l=Vt(l,N.deny,e)})),s.forEach((e=>{l=Vt(l,N.allOf,e)})),a.forEach((e=>{l=Vt(l,N.anyOf,e)})),c.forEach((e=>{l=Vt(l,N.noneOf,e)})),[l,s.concat(a).concat(c)]}function Rc(e,t,r,n,i,o){return e.map((e=>{const s=r.matchers.find((t=>_t(t)===e));if(void 0===s)return null;let a=Xs(t,encodeURI(_t(s))+n),c=!1;return yc.forEach((e=>{rt(s,e).forEach((t=>{e===i&&t===o||(c=!0,a=Vt(a,e,t))}))})),c?a:null})).filter(Ic)}function Ic(e){return null!==e}async function Tc(e,t=j){const r=ei(e),n=ci(e),i=Pc(r).concat(Pc(n)),o=await Cc(i,t),s=kc(r,o).filter(Ic),a=kc(n,o).filter(Ic),c=new Set;s.forEach((e=>{Oc(e).forEach((e=>{c.add(e)}))})),a.forEach((e=>{Oc(e).forEach((e=>{c.add(e)}))}));const l=Array.from(c),u=l.map((e=>xc(e))).filter((e=>!i.includes(e))),d=await Cc(u,t),h={...o,...d},f=kc(l,h).filter(Ic);return{inaccessibleUrls:Object.keys(h).filter((e=>null===h[e])),acrPolicies:s,policies:a,matchers:f}}function xc(e){const t=new URL(e);return t.hash="",t.href}function Pc(e){const t=[];return e.forEach((e=>{const r=xc(e);t.includes(r)||t.push(r)})),t}async function Cc(e,t){const r=Array.from(new Set(e)),n={};return await Promise.all(r.map((async e=>{try{const r=await Ot(e,t);n[e]=r}catch(t){n[e]=null}}))),n}function kc(e,t){return e.map((e=>{const r=xc(e),n=t[r];return n?pt(n,e):null}))}function Oc(e){return Ws(e).concat(Js(e)).concat(Ys(e))}async function Fc(e,t,r=j){const n=await Li(e,r);return Hi(n)?function(e,t){return mc(e,N.agent,t)}(await Tc(n,r),t):sn(n)?qa(n,t,r):null}async function Nc(e,t=j){const r=await Li(e,t);return Hi(r)?mc(await Tc(r,t),N.agent,N.PublicAgent):sn(r)?Ya(r,t):null}var Dc=Object.freeze({__proto__:null,getAccessFor:ic,getAccessForAll:oc,getAgentAccess:Fc,getAgentAccessAll:async function(e,t=j){const r=await Li(e,t);return Hi(r)?function(e,t){if(e.inaccessibleUrls.length>0)return null;const r={},n=function(e,t){const r=new Set;return e.matchers.forEach((e=>{rt(e,t).filter((e=>![N.PublicAgent,N.CreatorAgent,N.AuthenticatedAgent].includes(e)||t!==N.agent)).forEach((e=>r.add(e)))})),r}(e,t);return n.forEach((n=>{const i=mc(e,t,n);r[n]=i})),r}(await Tc(r,t),N.agent):sn(r)?Qa(r,t):null},getPublicAccess:Nc,setAccessFor:sc,setAgentAccess:async function(e,t,r,n=j){const i=await Li(e,n);if(Hi(i)){const o=function(e,t,r,n){return _c(e,t,N.agent,r,n)}(i,await Tc(i,n),t,r);if(o)try{return await Bi(o,n),await Fc(e,t,n)}catch(e){return null}return null}if(sn(i)){if(r.controlRead!==r.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(i)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=r;return await tc(i,t,e,n),qa(i,t,n)}return null},setPublicAccess:async function(e,t,r=j){const n=await Li(e,r);if(Hi(n)){const i=function(e,t,r){return _c(e,t,N.agent,N.PublicAgent,r)}(n,await Tc(n,r),t);if(i)try{return await Bi(i,r),await Nc(e,r)}catch(e){return null}return null}if(sn(n)){if(t.controlRead!==t.controlWrite)throw new Error(`When setting access for a Resource in a Pod implementing Web Access Control (i.e. [${V(n)}]), \`controlRead\` and \`controlWrite\` should have the same value.`);const e=t;return await rc(n,e,r),Ya(n,r)}return null}});async function Lc(e,t){if("string"!=typeof e.internal_resourceInfo.aclUrl)return null;try{return await M(e.internal_resourceInfo.aclUrl,t)}catch(e){return null}}function Uc(e,t,r){const n=tt(t,yi.allOf).map((t=>pt(jn(e),t))).filter((e=>null!==e)),i=n.every((e=>tt(e,yi.agent).includes(r))),o=tt(t,yi.anyOf).map((t=>pt(jn(e),t))).filter((e=>null!==e)),s=o.some((e=>tt(e,yi.agent).includes(r))),a=tt(t,yi.noneOf).map((t=>pt(jn(e),t))).filter((e=>null!==e)),c=a.some((e=>tt(e,yi.agent).includes(r)));return n.length+o.length>0&&(0===n.length||i)&&(0===o.length||s)&&(0===a.length||!c)}function jc(e,t,r){const n=function(e){return Ii(e,yi.allow)}(e),i=function(e){return Ii(e,yi.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 Mc(e,t){let r={read:!1,append:!1,write:!1,controlRead:!1,controlWrite:!1};return Os(e).map((t=>pt(jn(e),t))).filter((e=>null!==e)).forEach((n=>{Uc(e,n,t)&&(r=jc(n,r,"resource"))})),xs(e).map((t=>pt(jn(e),t))).filter((e=>null!==e)).forEach((n=>{Uc(e,n,t)&&(r=jc(n,r,"control"))})),r}async function Bc(e,t){const r=await async function(e,t){const r=function(e){const t=e.internal_resourceInfo.linkedResources[yi.accessControl];return Array.isArray(t)&&1===t.length?t[0]:null}(e);if(null!==r)return r;const n=await Lc(e,t);if(null===n)return null;const i=J(n).type;return Array.isArray(i)&&i.includes(yi.AccessControlResource)?$(n):null}(e,t);if(null===r)return null;let n;try{n=await Ot(r,t)}catch(e){return null}return{...e,internal_acp:{acr:{...n,accessTo:$(e)}}}}async function Hc(e,t,r){const n=await M(e,r),i=await Bc(n,r);return null===i?qa(n,t,r):Mc(i,t)}async function Wc(e,t){const r=await M(e,t),n=await Bc(r,t);return null===n?Ya(r,t):async function(e){return Mc(e,yi.PublicAgent)}(n)}function $c(e,t,r){return Ai(e,t).concat("AgentMatcher").concat(r.charAt(0).toUpperCase()+r.slice(1)).concat("Policy")}function Vc(e,t,r){return $c(e,t,r).concat("Matcher")}const Kc=yi.anyOf;function Jc(e,t,r,n,i){var o;const s=Vc(e,r,n),a=function(e,t,r){const n=$c(e,t,r),i=Vc(e,t,r);let o=pt(jn(e),n);return o||(e=function(e,t,r){const n=$c(e,t,r);return n.includes("Acr")?Ss(e,n):Rs(e,n)}(e,t,r),o=vt({url:n}),o=Ti(o,{[r]:!0},yi.allow)),rt(o,Kc).includes(i)?e:(o=Cr(o).addUrl(Kc,i).build(),bs(e,o))}(e,r,n),c=null!==(o=pt(jn(a),s))&&void 0!==o?o:vt({url:s});return bs(a,"add"===i?la(c,t):ua(c,t))}async function Gc(e,t,r){const n=await Mc(e,t);return"boolean"==typeof r.read&&n.read!==r.read&&(e=Jc(e,t,wi,"read",r.read?"add":"remove")),"boolean"==typeof r.append&&n.append!==r.append&&(e=Jc(e,t,wi,"append",r.append?"add":"remove")),"boolean"==typeof r.write&&n.write!==r.write&&(e=Jc(e,t,wi,"write",r.write?"add":"remove")),"boolean"==typeof r.controlRead&&n.controlRead!==r.controlRead&&(e=Jc(e,t,_i,"controlRead",r.controlRead?"add":"remove")),"boolean"==typeof r.controlWrite&&n.controlWrite!==r.controlWrite&&(e=Jc(e,t,_i,"controlWrite",r.controlWrite?"add":"remove")),e}var qc=Object.freeze({__proto__:null,getAclServerResourceInfo:Lc,getAgentAccess:Hc,getAgentAccessAll:async function(e,t){const r=await M(e,t),n=await Bc(r,t);return null===n?Qa(r,t):async function(e){return(await Promise.all((t=e,Array.from(new Set(gt(jn(t)).map((e=>tt(e,yi.agent))).reduce(((e,t)=>e.concat(t)),[])))).map((async t=>({[t]:await Mc(e,t)}))))).reduce(((e,t)=>({...e,...t})),{});var t}(n)},getPublicAccess:Wc,setAgentAccess:async function(e,t,r,n){const i=await M(e,n),o=await Bc(i,n);if(null===o)return await tc(i,t,r,n),qa(i,t,n);try{return await Bi(await Gc(o,t,r),n),await Hc(e,t,n)}catch(e){return null}},setPublicAccess:async function(e,t,r){const n=await M(e,r),i=await Bc(n,r);if(null===i)return await rc(n,t,r),Ya(n,r);try{return await Bi(await async function(e,t){return Gc(e,yi.PublicAgent,t)}(i,t),r),await Wc(e,r)}catch(e){return null}}}),zc=Object.freeze({__proto__:null,acrAsMarkdown:pi,addAcrPolicyUrl:Xn,addAgent:vo,addAllOfRuleUrl:Gi,addAnyOfRuleUrl:Qi,addClient:Do,addGroup:So,addMemberAcrPolicyUrl:Zn,addMemberPolicyUrl:ai,addMockAcrTo:hs,addNoneOfRuleUrl:to,addPolicyUrl:si,createPolicy:Wo,createResourcePolicyFor:ts,createResourceRuleFor:so,createRule:oo,getAcrPolicyUrlAll:ei,getAgentAll:yo,getAllOfRuleUrlAll:Yi,getAllowModes:Yo,getAnyOfRuleUrlAll:eo,getClientAll:Fo,getDenyModes:es,getFileWithAccessDatasets:ji,getFileWithAcr:Di,getGroupAll:wo,getLinkedAcrUrl:Ki,getMemberAcrPolicyUrlAll:ti,getMemberPolicyUrlAll:li,getNoneOfRuleUrlAll:io,getPolicy:$o,getPolicyAll:Vo,getPolicyUrlAll:ci,getReferencedPolicyUrlAll:$i,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getResourcePolicy:rs,getResourcePolicyAll:is,getResourceRule:co,getResourceRuleAll:uo,getRule:ao,getRuleAll:lo,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,hasAccessibleAcr:Hi,hasAnyClient:Uo,hasAuthenticated:To,hasCreator:Co,hasLinkedAcr:Qn,hasPublic:Ao,isAcpControlled:Vi,mockAcrFor:ds,policyAsMarkdown:us,removeAcrPolicyUrl:ri,removeAcrPolicyUrlAll:ii,removeAgent:bo,removeAllOfRuleUrl:qi,removeAnyClient:Mo,removeAnyOfRuleUrl:Xi,removeAuthenticated:Po,removeClient:Lo,removeCreator:Oo,removeGroup:Eo,removeMemberAcrPolicyUrl:ni,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:di,removeMemberPolicyUrlAll:fi,removeNoneOfRuleUrl:ro,removePolicy:Ko,removePolicyUrl:ui,removePolicyUrlAll:hi,removePublic:Io,removeResourceAcrPolicy:as,removeResourcePolicy:ss,removeResourceRule:fo,removeRule:ho,ruleAsMarkdown:Bo,saveAcrFor:Bi,setAgent:mo,setAllOfRuleUrl:zi,setAllowModes:qo,setAnyClient:jo,setAnyOfRuleUrl:Zi,setAuthenticated:xo,setClient:No,setCreator:ko,setDenyModes:Xo,setGroup:_o,setNoneOfRuleUrl:no,setPolicy:Jo,setPublic:Ro,setResourceAcrPolicy:ls,setResourcePolicy:cs,setResourceRule:go,setRule:po}),Yc=Object.freeze({__proto__:null,addAcrPolicyUrl:Ss,addAgent:la,addAllOfMatcherUrl:Ms,addAnyOfMatcherUrl:$s,addClient:_a,addMemberAcrPolicyUrl:Es,addMemberPolicyUrl:As,addMockAcrTo:hs,addNoneOfMatcherUrl:Gs,addPolicyUrl:Rs,createMatcher:Qs,createPolicy:Wo,createResourceMatcherFor:Xs,createResourcePolicyFor:ts,getAcrPolicyUrlAll:xs,getAgentAll:aa,getAllOfMatcherUrlAll:Ws,getAllowModes:zo,getAnyOfMatcherUrlAll:Js,getClientAll:wa,getDenyModes:Zo,getFileWithAccessDatasets:ji,getFileWithAcr:Di,getLinkedAcrUrl:Ki,getMatcher:Zs,getMatcherAll:ta,getMemberAcrPolicyUrlAll:Cs,getMemberPolicyUrlAll:ks,getNoneOfMatcherUrlAll:Ys,getPolicy:$o,getPolicyAll:Vo,getPolicyUrlAll:Os,getReferencedPolicyUrlAll:$i,getResourceAcrPolicy:ns,getResourceAcrPolicyAll:os,getResourceInfoWithAccessDatasets:Mi,getResourceInfoWithAcr:Li,getResourceMatcher:ea,getResourceMatcherAll:ra,getResourcePolicy:rs,getResourcePolicyAll:is,getSolidDatasetWithAccessDatasets:Ui,getSolidDatasetWithAcr:Ni,getVcAccess:Fi,hasAccessibleAcr:Hi,hasAuthenticated:pa,hasCreator:ma,hasLinkedAcr:Qn,hasPublic:da,isAcpControlled:Vi,mockAcrFor:ds,removeAcrPolicyUrl:Fs,removeAcrPolicyUrlAll:ii,removeAgent:ua,removeAllOfMatcherUrl:Bs,removeAnyOfMatcherUrl:Vs,removeAuthenticated:ya,removeClient:Sa,removeCreator:ba,removeMatcher:na,removeMemberAcrPolicyUrl:Ns,removeMemberAcrPolicyUrlAll:oi,removeMemberPolicyUrl:Ds,removeMemberPolicyUrlAll:fi,removeNoneOfMatcherUrl:qs,removePolicy:Ko,removePolicyUrl:Ls,removePolicyUrlAll:hi,removePublic:fa,removeResourceAcrPolicy:as,removeResourceMatcher:ia,removeResourcePolicy:ss,saveAcrFor:Bi,setAgent:ca,setAllOfMatcherUrl:Hs,setAllowModes:Go,setAnyOfMatcherUrl:Ks,setAuthenticated:ga,setCreator:va,setDenyModes:Qo,setMatcher:oa,setNoneOfMatcherUrl:zs,setPolicy:Jo,setPublic:ha,setResourceMatcher:sa,setResourcePolicy:Us,setVcAccess:Ci});const{getJsonLdParser:Qc,getTurtleParser:Xc,solidDatasetAsTurtle:Zc}=We;t.FetchError=G,t.SolidClientError=p,t.ThingExpectedError=At,t.access=nc,t.access_v1=gc,t.access_v2=Dc,t.acp_ess_1=zc,t.acp_ess_2=Yc,t.acp_v1=ms,t.acp_v2=ys,t.acp_v3=vs,t.acp_v4=Ra,t.addBoolean=Kt,t.addDate=Gt,t.addDatetime=Jt,t.addDecimal=zt,t.addInteger=Yt,t.addIri=Vt,t.addJwkToJwks=Nn,t.addLiteral=er,t.addMockFallbackAclTo=function(e){const t=Dr(V(e)),r=`${t}.acl`,n=rn(function(e,t){return Object.assign(v(e),{internal_resourceInfo:{...e.internal_resourceInfo,aclUrl:t}})}(Wt(t),r));return Gr(v(e),{resourceAcl:null,fallbackAcl:n})},t.addMockResourceAclTo=function(e){var t;const r=null!==(t=e.internal_resourceInfo.aclUrl)&&void 0!==t?t:"https://your.pod/mock-acl.ttl",n=Object.assign(v(e),{internal_resourceInfo:{...e.internal_resourceInfo,aclUrl:r}});return Gr(n,{resourceAcl:rn(n),fallbackAcl:null})},t.addNamedNode=Zt,t.addPublicKeyToProfileJwks=async function(e,t,r=j){const n=await Ot(t,{fetch:r.fetch});if(null===n)throw new Error(`The profile document associated with WebID [${t}] could not be retrieved.`);const i=Fn(n,t);if(null===i)throw new Error(`No key set is declared for the property [${L}] in the profile of [${t}]`);const o=await Nn(e,i,r);return Je(i,new Blob([JSON.stringify(o)]),{contentType:"application/json",fetch:r.fetch})},t.addStringEnglish=function(e,t,r){return Qt(e,t,r,"en")},t.addStringNoLocale=Xt,t.addStringWithLocale=Qt,t.addTerm=tr,t.addTime=qt,t.addUrl=$t,t.asIri=_t,t.asUrl=wt,t.buildThing=Cr,t.changeLogAsMarkdown=Ut,t.createAcl=rn,t.createAclFromFallbackAcl=nn,t.createContainerAt=async function(e,t=j){var r;e=(e=g(e)).endsWith("/")?e:`${e}/`;const n={...j,...t},i=await n.fetch(e,{method:"PUT",body:n.initialContent?await je(Fe(n.initialContent).map(jt)):void 0,headers:{Accept:"text/turtle","Content-Type":"text/turtle","If-None-Match":"*",Link:`<${C}>; rel="type"`}});if(b(i)){const t=void 0===n.initialContent?"empty":"non-empty";throw new G(`Creating the ${t} Container at [${e}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)}const o=m(i);return Y({...null!==(r=t.initialContent)&&void 0!==r?r:Ct(),internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:o})},t.createContainerInContainer=async function(e,t=j){e=g(e);const r={...j,...t},n={"Content-Type":"text/turtle",Link:`<${C}>; rel="type"`};t.slugSuggestion&&(n.slug=t.slugSuggestion);const i=await r.fetch(e,{method:"POST",headers:n});if(b(i))throw new G(`Creating an empty Container in the Container at [${e}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=m(i);if(!o.location)throw new Error("Could not determine the location of the newly created Container.");try{const e=new URL(o.location).toString();return Y({...Ct(),internal_resourceInfo:{...o,sourceIri:e}})}catch(e){}return Y({...Ct(),internal_resourceInfo:{...o,sourceIri:new URL(o.location,i.url).href}})},t.createSolidDataset=Ct,t.createThing=vt,t.deleteAclFor=async function(e,t=j){const r={...j,...t},n=await r.fetch(e.internal_resourceInfo.aclUrl,{method:"DELETE"});if(!n.ok)throw new Error(`Deleting the ACL of the Resource at [${$(e)}] failed: [${n.status}] [${n.statusText}].`);return Object.assign(v(e),{acl:{resourceAcl:null}})},t.deleteContainer=async function(e,t=j){const r=d(e)?g($(e)):g(e);if(!H(e))throw new Error(`You're trying to delete the Container at [${r}], but Container URLs should end in a \`/\`. Are you sure this is a Container?`);const n={...j,...t},i=await n.fetch(r,{method:"DELETE"});if(b(i))throw new G(`Deleting the Container at [${r}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)},t.deleteFile=async function(e,t=$e){const r={...$e,...t},n=d(e)?g(V(e)):g(e),i=await r.fetch(n,{...r.init,method:"DELETE"});if(b(i))throw new G(`Deleting the file at [${n}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)},t.deleteSolidDataset=async function(e,t=j){const r={...j,...t},n=d(e)?g($(e)):g(e),i=await r.fetch(n,{method:"DELETE"});if(b(i))throw new G(`Deleting the SolidDataset at [${n}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i)},t.fromRdfJsDataset=function(e){const t=Array.from(e),r=Oe(t);return t.filter((e=>r.every((t=>!t.equals(e.subject))))).reduce(((e,n)=>Ie(e,n,{otherQuads:t,chainBlankNodes:r})),{graphs:{default:{}},type:"Dataset"})},t.getAgentAccess=an,t.getAgentAccessAll=cn,t.getAgentDefaultAccess=hn,t.getAgentDefaultAccessAll=fn,t.getAgentResourceAccess=ln,t.getAgentResourceAccessAll=un,t.getAltProfileUrlAllFrom=Dn,t.getBoolean=function(e,t){Ye(e);const r=ht(e,t,re);return null===r?null:ue(r)},t.getBooleanAll=function(e,t){return Ye(e),ft(e,t,re).map(ue).filter((e=>null!==e))},t.getContainedResourceUrlAll=function(e){const t=$(e),r=pt(e,t);return null===r?[]:rt(r,O).filter((e=>Dt(e,t)))},t.getContentType=W,t.getDate=function(e,t){Ye(e);const r=ht(e,t,ie);return null===r?null:fe(r)},t.getDateAll=function(e,t){return Ye(e),ft(e,t,ie).map(fe).filter((e=>null!==e))},t.getDatetime=function(e,t){Ye(e);const r=ht(e,t,ne);return null===r?null:he(r)},t.getDatetimeAll=function(e,t){return Ye(e),ft(e,t,ne).map(he).filter((e=>null!==e))},t.getDecimal=function(e,t){Ye(e);const r=ht(e,t,se);return null===r?null:ye(r)},t.getDecimalAll=function(e,t){return Ye(e),ft(e,t,se).map((e=>ye(e))).filter((e=>null!==e))},t.getEffectiveAccess=function(e){var t,r,n,i,o,s,a;if("object"==typeof e.internal_resourceInfo.permissions)return{user:{read:e.internal_resourceInfo.permissions.user.read,append:e.internal_resourceInfo.permissions.user.append,write:e.internal_resourceInfo.permissions.user.write},public:{read:e.internal_resourceInfo.permissions.public.read,append:e.internal_resourceInfo.permissions.public.append,write:e.internal_resourceInfo.permissions.public.write}};const c=J(e);return{user:{read:null!==(r=null===(t=c[N.allow])||void 0===t?void 0:t.includes(N.Read))&&void 0!==r&&r,append:null!==(o=(null===(n=c[N.allow])||void 0===n?void 0:n.includes(N.Append))||(null===(i=c[N.allow])||void 0===i?void 0:i.includes(N.Write)))&&void 0!==o&&o,write:null!==(a=null===(s=c[N.allow])||void 0===s?void 0:s.includes(N.Write))&&void 0!==a&&a}}},t.getFallbackAcl=tn,t.getFile=Ke,t.getFileWithAcl=async function(e,t=j){const r=await Ke(e,t);return Gr(r,await Or(r,t))},t.getGroupAccess=vn,t.getGroupAccessAll=bn,t.getGroupDefaultAccess=Sn,t.getGroupDefaultAccessAll=En,t.getGroupResourceAccess=wn,t.getGroupResourceAccessAll=_n,t.getInteger=function(e,t){Ye(e);const r=ht(e,t,ae);return null===r?null:me(r)},t.getIntegerAll=function(e,t){return Ye(e),ft(e,t,ae).map((e=>me(e))).filter((e=>null!==e))},t.getIri=et,t.getIriAll=rt,t.getJsonLdParser=Qc,t.getLinkedResourceUrlAll=J,t.getLiteral=ct,t.getLiteralAll=lt,t.getNamedNode=st,t.getNamedNodeAll=at,t.getPodOwner=K,t.getPodUrlAll=async function(e,t=j){return Un(await Ln(e,t),e)},t.getPodUrlAllFrom=Un,t.getProfileAll=Ln,t.getProfileJwksIri=Fn,t.getPropertyAll=function(e){return Object.keys(e.predicates).filter((t=>null!==ut(e,t)))},t.getPublicAccess=Tn,t.getPublicDefaultAccess=Pn,t.getPublicResourceAccess=xn,t.getResourceAcl=Zr,t.getResourceInfo=M,t.getResourceInfoWithAcl=async function(e,t=j){const r=await M(e,t);return Gr(r,await Or(r,t))},t.getSolidDataset=Ot,t.getSolidDatasetWithAcl=async function(e,t=j){const r=await Ot(e,t);return Gr(r,await Or(r,t))},t.getSourceIri=V,t.getSourceUrl=$,t.getStringByLocaleAll=function(e,t){var r,n;if(Ye(e),!Se(t))throw new Rt(t);const i=g(t),o=null!==(n=null===(r=e.predicates[i])||void 0===r?void 0:r.langStrings)&&void 0!==n?n:{};return new Map(Object.entries(o).map((([e,t])=>[e,[...t]])))},t.getStringEnglish=function(e,t){return nt(e,t,"en")},t.getStringEnglishAll=function(e,t){return it(e,t,"en")},t.getStringNoLocale=function(e,t){return Ye(e),ht(e,t,ce)},t.getStringNoLocaleAll=ot,t.getStringWithLocale=nt,t.getStringWithLocaleAll=it,t.getTerm=ut,t.getTermAll=dt,t.getThing=pt,t.getThingAll=gt,t.getTime=function(e,t){Ye(e);const r=ht(e,t,oe);return null===r?null:de(r)},t.getTimeAll=function(e,t){return Ye(e),ft(e,t,oe).map(de).filter((e=>null!==e))},t.getTurtleParser=Xc,t.getUrl=Ze,t.getUrlAll=tt,t.getWebIdDataset=async function(e){return Ot(e,{fetch:y})},t.getWellKnownSolid=async function(e,t=j){const r=g(e);try{const e=new URL("/.well-known/solid",new URL(r).origin).href;return await Ot(e,{fetch:y})}catch(e){}const n=J(await M(r,{fetch:t.fetch,ignoreAuthenticationErrors:!0}))[U],i=1===(null==n?void 0:n.length)?n[0]:null;if(null!==i)return Ot(new URL(".well-known/solid",i.endsWith("/")?i:`${i}/`).href,{...t,parsers:{"application/ld+json":q()}});throw new Error("Could not determine storage root or well-known solid resource.")},t.hasAccessibleAcl=sn,t.hasAcl=function(e){return"object"==typeof e.internal_acl},t.hasFallbackAcl=en,t.hasResourceAcl=Xr,t.hasResourceInfo=d,t.hasServerResourceInfo=h,t.isContainer=H,t.isPodOwner=function(e,t){const r=K(t);return"string"!=typeof r?null:r===e},t.isRawData=function(e){return e.internal_resourceInfo.isRawData},t.isThing=bt,t.isThingLocal=Et,t.mockContainerFrom=Wt,t.mockFetchError=function(e,t=404,r="Not Found"){const n=new o.Response(void 0,{status:t,statusText:r});return new G(`Fetching the Resource at [${e}] failed: [${n.status}] [${n.statusText}].`,n)},t.mockFileFrom=function(e,t){const r=new Blob;return Object.assign(r,{internal_resourceInfo:{sourceIri:g(e),isRawData:!0,contentType:null==t?void 0:t.contentType,linkedResources:{}}})},t.mockSolidDatasetFrom=Ht,t.mockThingFrom=function(e){return{type:"Subject",predicates:{},url:g(e)}},t.overwriteFile=Je,t.removeAll=nr,t.removeBoolean=sr,t.removeDate=cr,t.removeDatetime=ar,t.removeDecimal=ur,t.removeInteger=dr,t.removeIri=or,t.removeLiteral=gr,t.removeNamedNode=pr,t.removeStringEnglish=function(e,t,r){return hr(e,t,r,"en")},t.removeStringNoLocale=fr,t.removeStringWithLocale=hr,t.removeThing=mt,t.removeTime=lr,t.removeUrl=ir,t.responseToResourceInfo=B,t.responseToSolidDataset=kt,t.saveAclFor=on,t.saveFileInContainer=async function(e,t,r=$e){const n=g(e),i=await Ge(n,t,"POST",r);if(b(i))throw new G(`Saving the file in [${e}] failed: [${i.status}] [${i.statusText}] ${await i.text()}.`,i);const o=i.headers.get("Location");if(null===o)throw new Error("Could not determine the location of the newly saved file.");const s=new URL(o,new URL(n).origin).href,a=v(t),c={internal_resourceInfo:{isRawData:!0,sourceIri:s,contentType:qe(t,r.contentType)}};return Object.assign(a,c)},t.saveSolidDatasetAt=Ft,t.saveSolidDatasetInContainer=async function(e,t,r=j){const n={...j,...r};e=g(e);const i=await je(Fe(t).map(jt)),o={"Content-Type":"text/turtle",Link:`<${k}>; rel="type"`};r.slugSuggestion&&(o.slug=r.slugSuggestion);const s=await n.fetch(e,{method:"POST",body:i,headers:o});if(b(s))throw new G(`Storing the Resource in the Container at [${e}] failed: [${s.status}] [${s.statusText}] ${await s.text()}.\n\nThe SolidDataset that was sent to the Pod is listed below.\n\n${Lt(t)}`,s);const a=m(s);if(!a.location)throw new Error("Could not determine the location of the newly saved SolidDataset.");let c;try{c=new URL(a.location).href}catch(e){c=new URL(a.location,s.url).href}const l={internal_resourceInfo:{isRawData:!1,sourceIri:c}};return Bt(Y({...t,...l}))},t.setAgentDefaultAccess=function(e,t,r){return zr(e,r,S,"default",t)},t.setAgentResourceAccess=dn,t.setBoolean=br,t.setDate=_r,t.setDatetime=wr,t.setDecimal=Er,t.setGroupDefaultAccess=function(e,t,r){return zr(e,r,E,"default",t)},t.setGroupResourceAccess=In,t.setInteger=Ar,t.setIri=vr,t.setLiteral=xr,t.setNamedNode=Tr,t.setProfileJwks=function(e,t,r){return yt(e,vr(On(e,t),L,r))},t.setPublicDefaultAccess=function(e,t){return zr(e,t,A,"default",F)},t.setPublicResourceAccess=Cn,t.setStringNoLocale=Ir,t.setStringWithLocale=Rr,t.setTerm=Pr,t.setThing=yt,t.setTime=Sr,t.setUrl=mr,t.solidDatasetAsMarkdown=Lt,t.solidDatasetAsTurtle=Zc,t.thingAsMarkdown=St,t.toRdfJsDataset=He,t.universalAccess=qc,t.validateContainedResourceAll=function(e){const t=$(e),r=pt(e,t);if(null===r)return{isValid:!0,invalidContainedResources:[]};const n=rt(r,O).filter((e=>!Dt(e,t)));return n.length>0?{isValid:!1,invalidContainedResources:n}:{isValid:!0,invalidContainedResources:[]}}},5914:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=globalThis.fetch;const{fetch:n,Response:i,Request:o,Headers:s}=globalThis;t.Headers=s,t.Request=o,t.Response=i,t.default=r,t.fetch=n},4727:function(e,t,r){const n=r(37);e.exports=n},377:function(e){class t{constructor(e){this.value=e||"b"+ ++t.nextId}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}t.prototype.termType="BlankNode",t.nextId=0,e.exports=t},37:function(e,t,r){const n=r(377),i=r(8144),o=r(3257),s=r(2704),a=r(9938),c=r(5304),l=r(7427),u={namedNode:function(e){return new a(e)},blankNode:function(e){return new n(e)},literal:function(e,t){return"string"==typeof t?-1===t.indexOf(":")?new s(e,t):new s(e,null,u.namedNode(t)):new s(e,null,t)},variable:function(e){return new l(e)},defaultGraph:function(){return u.defaultGraphInstance},triple:function(e,t,r){return u.quad(e,t,r)},quad:function(e,t,r,n){return new c(e,t,r,n||u.defaultGraphInstance)},fromTerm:function(e){return o.call(u,e)},fromQuad:function(e){return o.call(u,e)},defaultGraphInstance:new i};e.exports=u},8144:function(e){class t{equals(e){return!!e&&e.termType===this.termType}}t.prototype.termType="DefaultGraph",t.prototype.value="",e.exports=t},2704:function(e,t,r){const n=r(9938);class i{constructor(e,t,r){this.value=e,this.datatype=i.stringDatatype,this.language="",t?(this.language=t,this.datatype=i.langStringDatatype):r&&(this.datatype=r)}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value&&e.language===this.language&&e.datatype.equals(this.datatype)}}i.prototype.termType="Literal",i.langStringDatatype=new n("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),i.stringDatatype=new n("http://www.w3.org/2001/XMLSchema#string"),e.exports=i},9938:function(e){class t{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}t.prototype.termType="NamedNode",e.exports=t},5304:function(e,t,r){const n=r(8144);class i{constructor(e,t,r,i){this.subject=e,this.predicate=t,this.object=r,this.graph=i||new n}equals(e){return!!e&&("Quad"===e.termType||!e.termType)&&e.subject.equals(this.subject)&&e.predicate.equals(this.predicate)&&e.object.equals(this.object)&&e.graph.equals(this.graph)}}i.prototype.termType="Quad",i.prototype.value="",e.exports=i},7427:function(e){class t{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}t.prototype.termType="Variable",e.exports=t},3257:function(e){e.exports=function(e){if(!e)return null;if("BlankNode"===e.termType)return this.blankNode(e.value);if("DefaultGraph"===e.termType)return this.defaultGraph();if("Literal"===e.termType)return this.literal(e.value,e.language||this.namedNode(e.datatype.value));if("NamedNode"===e.termType)return this.namedNode(e.value);if("Quad"===e.termType){const t=this.fromTerm(e.subject),r=this.fromTerm(e.predicate),n=this.fromTerm(e.object),i=this.fromTerm(e.graph);return this.quad(t,r,n,i)}if("Variable"===e.termType)return this.variable(e.value);throw new Error(`unknown termType ${e.termType}`)}},2442:function(e){function t(e){return"string"==typeof e||e instanceof String}function r(e){if("string"==typeof e)return e;if(!e)return"";if(void 0!==e.id&&"Quad"!==e.termType)return e.id;let t,n,o,s;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.language?`"${e.value}"@${e.language}`:`"${e.value}"${e.datatype&&"http://www.w3.org/2001/XMLSchema#string"!==e.datatype.value?`^^${e.datatype.value}`:""}`;case"Quad":return t=i(r(e.subject)),n=i(r(e.predicate)),o=i(r(e.object)),s="DefaultGraph"===e.graph.termType?"":` ${r(e.graph)}`,`<<${t} ${n} ${o}${s}>>`;default:throw new Error(`Unexpected termType: ${e.termType}`)}}const n=/^"(.*".*)(?="[^"]*$)/;function i(e){return e.replace(n,((e,t)=>`"${t.replace(/"/g,'""')}`))}class o{constructor(e){if(this._size=0,this._graphs=Object.create(null),this._id=0,this._ids=Object.create(null),this._ids["><"]=0,this._entities=Object.create(null),this._quads=new Map,e)for(const t of e)this.add(t)}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,this._size}add(e){let t=r(e.subject),n=r(e.predicate),i=r(e.object);const o=r(e.graph);let s=this._graphs[o];s||(s=this._graphs[o]={subjects:{},predicates:{},objects:{}},Object.freeze(s));const a=this._ids,c=this._entities;return t=a[t]||(a[c[++this._id]=t]=this._id),n=a[n]||(a[c[++this._id]=n]=this._id),i=a[i]||(a[c[++this._id]=i]=this._id),this._addToIndex(s.subjects,t,n,i),this._addToIndex(s.predicates,n,i,t),this._addToIndex(s.objects,i,t,n),this._setQuad(t,n,i,o,e),this._size=null,this}delete(e){let t=r(e.subject),n=r(e.predicate),i=r(e.object);const o=r(e.graph),s=this._ids,a=this._graphs;let c,l,u;if(!((t=s[t])&&(n=s[n])&&(i=s[i])&&(c=a[o])&&(l=c.subjects[t])&&(u=l[n])&&i in u))return this;for(t in this._removeFromIndex(c.subjects,t,n,i),this._removeFromIndex(c.predicates,n,i,t),this._removeFromIndex(c.objects,i,t,n),null!==this._size&&this._size--,this._deleteQuad(t,n,i,o),c.subjects)return this;return delete a[o],this}has(e){const n=r(e.subject),i=r(e.predicate),o=r(e.object),s=r(e.graph),a=this._graphs[s];if(!a)return!1;const c=this._ids;let l,u,d;return!(t(n)&&!(l=c[n])||t(i)&&!(u=c[i])||t(o)&&!(d=c[o]))&&1===this._countInIndex(a.objects,d,l,u)}match(e,t,r,n){return this._createDataset(this._match(e,t,r,n))}[Symbol.iterator](){return this._match()[Symbol.iterator]()}_addToIndex(e,t,r,n){const i=e[t]||(e[t]={}),o=i[r]||(i[r]={}),s=n in o;return s||(o[n]=null),!s}_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,s,a,c,l){let u,d,h;t&&((u=e,e={})[t]=u[t]);for(const t in e)if(d=e[t],d){r&&((u=d,d={})[r]=u[r]);for(const e in d)if(h=d[e],h){const r=n?n in h?[n]:[]:Object.keys(h);for(let n=0;n0?s-4:s;for(r=0;r>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[u++]=255&t),1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,o=[],s=16383,a=0,l=n-i;al?l:a+s));return 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]+"=")),o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=o[s],n[o.charCodeAt(s)]=s;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,t,n){for(var i,o,s=[],a=t;a>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},8849:function(e,t,r){"use strict";r.r(t);var n=void 0!==n?n:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,i=function(){try{return 2===new Blob(["hi"]).size}catch(e){return!1}}(),o=i&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(e){return!1}}(),s=n&&n.prototype.append&&n.prototype.getBlob;function a(e){return e.map((function(e){if(e.buffer instanceof ArrayBuffer){var t=e.buffer;if(e.byteLength!==t.byteLength){var r=new Uint8Array(e.byteLength);r.set(new Uint8Array(t,e.byteOffset,e.byteLength)),t=r.buffer}return t}return e}))}function c(e,t){t=t||{};var r=new n;return a(e).forEach((function(e){r.append(e)})),t.type?r.getBlob(t.type):r.getBlob()}function l(e,t){return new Blob(a(e),t||{})}"undefined"!=typeof Blob&&(c.prototype=Blob.prototype,l.prototype=Blob.prototype),t.default=i?o?Blob:l:s?c:void 0},8287:function(e,t,r){"use strict";const n=r(7526),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){return+e!=e&&(e=0),c.alloc(+e)},t.INSPECT_MAX_BYTES=50;const s=2147483647;function a(e){if(e>s)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 l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|g(e,t);let n=a(r);const i=n.write(e,t);return i!==r&&(n=n.slice(0,i)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(z(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(z(e,ArrayBuffer)||e&&z(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(z(e,SharedArrayBuffer)||e&&z(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}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(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 u(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 u(e),a(e<0?0:0|p(e))}function h(e){const t=e.length<0?0:0|p(e.length),r=a(t);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function g(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||z(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 J(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(i)return n?-1:J(e).length;t=(""+t).toLowerCase(),i=!0}}function y(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,r);case"utf8":case"utf-8":return I(this,t,r);case"ascii":return x(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return R(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function m(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function v(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),Y(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,s=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;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let n=-1;for(o=r;oa&&(r=a-c),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=t.length;let s;for(n>o/2&&(n=o/2),s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function R(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function I(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i239?4:t>223?3:t>191?2:1;if(i+s<=r){let r,n,a,c;switch(s){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],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&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.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=g,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;tr&&(e+=" ... "),""},o&&(c.prototype[o]=c.prototype.inspect),c.prototype.compare=function(e,t,r,n,i){if(z(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),s=(r>>>=0)-(t>>>=0);const a=Math.min(o,s),l=this.slice(n,i),u=e.slice(t,r);for(let e=0;e>>=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 _(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(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 T=4096;function x(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;in)&&(r=n);let i="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function F(e,t,r,n,i,o){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n,i){W(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 s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function D(e,t,r,n,i){W(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 s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function L(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 U(e,t,r,n,o){return t=+t,r>>>=0,o||L(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,o){return t=+t,r>>>=0,o||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>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e],i=1,o=0;for(;++o>>=0,t>>>=0,r||O(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||O(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(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||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||O(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||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||O(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||O(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||O(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||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||O(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||F(this,e,t,r,Math.pow(2,8*r)-1,0);let i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n||F(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||F(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||F(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||F(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||F(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||F(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=X((function(e,t=0){return N(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeBigUInt64BE=X((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);F(this,e,t,r,n-1,-n)}let i=0,o=1,s=0;for(this[t]=255&e;++i>>=0,!n){const n=Math.pow(2,8*r-1);F(this,e,t,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||F(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||F(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||F(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||F(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||F(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=X((function(e,t=0){return N(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeBigInt64BE=X((function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return j(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=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>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function W(e,t,r,n,i,o){if(e>r||e3?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 M.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){$(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,i,o)}function $(e,t){if("number"!=typeof e)throw new M.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw $(e,r),new M.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new M.ERR_BUFFER_OUT_OF_BOUNDS;throw new M.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}B("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),B("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),B("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n}),RangeError);const K=/[^+/0-9A-Za-z-_]/g;function J(e,t){let r;t=t||1/0;const n=e.length;let i=null;const o=[];for(let s=0;s55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+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 G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,r,n){let i;for(i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function z(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}const Q=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 X(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},2341:function(e){"use strict";e.exports=function e(t){return null===t||"object"!=typeof t||null!=t.toJSON?JSON.stringify(t):Array.isArray(t)?"["+t.reduce(((t,r,n)=>t+(0===n?"":",")+e(void 0===r||"symbol"==typeof r?null:r)),"")+"]":"{"+Object.keys(t).sort().reduce(((r,n,i)=>void 0===t[n]||"symbol"==typeof t[n]?r:r+(0===r.length?"":",")+e(n)+":"+e(t[n])),"")+"}"}},6547:function(){!function(e){!function(t){var r="URLSearchParams"in e,n="Symbol"in e&&"iterator"in Symbol,i="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),o="FormData"in e,s="ArrayBuffer"in e;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function l(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return n&&(t[Symbol.iterator]=function(){return t}),t}function h(e){this.map={},e instanceof h?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function f(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function p(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=p(t);return t.readAsArrayBuffer(e),r}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():s&&i&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=y(e):this._bodyText=e=Object.prototype.toString.call(e):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):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=f(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(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var e,t,r,n=f(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,r=p(t=new FileReader),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?n:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function w(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 _(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})},m.call(b.prototype),m.call(_.prototype),_.prototype.clone=function(){return new _(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},_.error=function(){var e=new _(null,{status:0,statusText:""});return e.type="error",e};var S=[301,302,303,307,308];_.redirect=function(e,t){if(-1===S.indexOf(t))throw new RangeError("Invalid status code");return new _(null,{status:t,headers:{location:e}})},t.DOMException=e.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(n,o){var s=new b(e,r);if(s.signal&&s.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new h,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;n(new _(i,r))},a.onerror=function(){o(new TypeError("Network request failed"))},a.ontimeout=function(){o(new TypeError("Network request failed"))},a.onabort=function(){o(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),s.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),s.signal&&(s.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",c)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}E.polyfill=!0,e.fetch||(e.fetch=E,e.Headers=h,e.Request=b,e.Response=_),t.Headers=h,t.Request=b,t.Response=_,t.fetch=E,Object.defineProperty(t,"__esModule",{value:!0})}({})}("undefined"!=typeof self?self:this)},7007:function(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))}g(e,t,o,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&g(e,"error",t,{once:!0})}(e,i)}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=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?o.defaultMaxListeners:e._maxListeners}function l(e,t,r,n){var i,o,s,l;if(a(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),s=o[t]),void 0===s)s=o[t]=r,++e._eventsCount;else if("function"==typeof s?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(i=c(e))>0&&s.length>i&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,l=u,console&&console.warn&&console.warn(l)}return e}function u(){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=u.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;r0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var l=c.length,u=p(c,l);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=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):[]}},2384:function(e){"use strict";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=/[;,"]/,s=/[;,"]|\s/,a=/^[!#$%&'*+\-\.^_`|~\da-zA-Z]+$/;function c(e){return e.replace(r,"")}function l(e){return n.test(e)}function u(e,t){for(;l(e[t]);)t++;return t}function d(e){return s.test(e)||!a.test(e)}class h{constructor(e){this.refs=[],e&&this.parse(e)}rel(e){for(var t=[],r=e.toLowerCase(),n=0;n{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",t)))throw new Error("Expected end of URI delimiter at offset "+t);s={uri:e.slice(t+1,f)},t=f,r=2,t++}else if(2===r){if(l(e[t])){t++;continue}if(";"===e[t])r=4,t++;else{if(","!==e[t])throw new Error('Unexpected character "'+e[t]+'" at offset '+t);r=1,t++}}else{if(4!==r)throw new Error('Unknown parser state "'+r+'"');if(";"===e[t]||l(e[t])){t++;continue}-1===(f=e.indexOf("=",t))&&(f=e.indexOf(";",t)),-1===f&&(f=e.length);var a=c(e.slice(t,f)).toLowerCase(),d="";if('"'===e[t=u(e,t=f+1)])for(t++;t"),e.push(t);return e.join(", ")}}h.isCompatibleEncoding=function(e){return t.test(e)},h.parse=function(e,t){return(new h).parse(e,t)},h.isSingleOccurenceAttr=function(e){return"rel"===e||"type"===e||"media"===e||"title"===e||"title*"===e},h.isTokenAttr=function(e){return"rel"===e||"type"===e||"anchor"===e},h.escapeQuotes=function(e){return e.replace(/"/g,'\\"')},h.expandRelations=function(e){return e.rel.split(" ").map((function(t){var r=Object.assign({},e);return r.rel=t,r}))},h.parseExtendedValue=function(e){var t=/([^']+)?(?:'([^']*)')?(.+)/.exec(e);return{language:t[2].toLowerCase(),encoding:h.isCompatibleEncoding(t[1])?null:t[1].toLowerCase(),value:h.isCompatibleEncoding(t[1])?decodeURIComponent(t[3]):t[3]}},h.formatExtendedAttribute=function(e,t){var r=(t.encoding||"utf-8").toUpperCase();return e+"="+r+"'"+(t.language||"en")+"'"+(Buffer.isBuffer(t.value)&&h.isCompatibleEncoding(r)?t.value.toString(r):Buffer.isBuffer(t.value)?t.value.toString("hex").replace(/[0-9a-f]{2}/gi,"%$1"):encodeURIComponent(t.value))},h.formatAttribute=function(e,t){return Array.isArray(t)?t.map((t=>h.formatAttribute(e,t))).join("; "):"*"===e[e.length-1]||"string"!=typeof t?h.formatExtendedAttribute(e,t):(h.isTokenAttr(e)?t=d(t)?'"'+h.escapeQuotes(t)+'"':h.escapeQuotes(t):d(t)&&(t='"'+(t=(t=encodeURIComponent(t)).replace(/%20/g," ").replace(/%2C/g,",").replace(/%3B/g,";"))+'"'),e+"="+t)},e.exports=h},251:function(e,t){t.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,c=(1<>1,u=-7,d=r?i-1:0,h=r?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-u)-1,f>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=l}return(f?-1:1)*s*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var s,a,c,l=8*o-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,i),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[r+f]=255&a,f+=p,a/=256,i-=8);for(s=s<0;e[r+f]=255&s,f+=p,s/=256,l-=8);e[r+f-p]|=128*g}},2395:function(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(2803),t),i(r(5094),t),i(r(585),t),i(r(9146),t),i(r(5086),t),i(r(5215),t),i(r(4931),t)},2803:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextParser=void 0,r(6547);const n=r(742),i=r(5094),o=r(585),s=r(5215),a=r(4931);class c{constructor(e){e=e||{},this.documentLoader=e.documentLoader||new o.FetchDocumentLoader,this.documentCache={},this.validateContext=!e.skipValidation,this.expandContentTypeToBase=!!e.expandContentTypeToBase,this.remoteContextsDepthLimit=e.remoteContextsDepthLimit||32,this.redirectSchemaOrgHttps=!("redirectSchemaOrgHttps"in e)||!!e.redirectSchemaOrgHttps}static validateLanguage(e,t,r){if("string"!=typeof e)throw new i.ErrorCoded(`The value of an '@language' must be a string, got '${JSON.stringify(e)}'`,r);if(!a.Util.REGEX_LANGUAGE_TAG.test(e)){if(t)throw new i.ErrorCoded(`The value of an '@language' must be a valid language tag, got '${JSON.stringify(e)}'`,r);return!1}return!0}static validateDirection(e,t){if("string"!=typeof e)throw new i.ErrorCoded(`The value of an '@direction' must be a string, got '${JSON.stringify(e)}'`,i.ERROR_CODES.INVALID_BASE_DIRECTION);if(!a.Util.REGEX_DIRECTION_TAG.test(e)){if(t)throw new i.ErrorCoded(`The value of an '@direction' must be 'ltr' or 'rtl', got '${JSON.stringify(e)}'`,i.ERROR_CODES.INVALID_BASE_DIRECTION);return!1}return!0}idifyReverseTerms(e){for(const t of Object.keys(e)){let r=e[t];if(r&&"object"==typeof r&&r["@reverse"]&&!r["@id"]){if("string"!=typeof r["@reverse"]||a.Util.isValidKeyword(r["@reverse"]))throw new i.ErrorCoded(`Invalid @reverse value, must be absolute IRI or blank node: '${r["@reverse"]}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);r=e[t]=Object.assign(Object.assign({},r),{"@id":r["@reverse"]}),r["@id"]=r["@reverse"],a.Util.isPotentialKeyword(r["@reverse"])?delete r["@reverse"]:r["@reverse"]=!0}}return e}expandPrefixedTerms(e,t,r){const n=e.getContextRaw();for(const o of r||Object.keys(n))if(a.Util.EXPAND_KEYS_BLACKLIST.indexOf(o)<0&&!a.Util.isReservedInternalKeyword(o)){const r=n[o];if(a.Util.isPotentialKeyword(o)&&a.Util.ALIAS_DOMAIN_BLACKLIST.indexOf(o)>=0&&("@type"!==o||"object"==typeof n[o]&&!n[o]["@protected"]&&"@set"!==n[o]["@container"]))throw new i.ErrorCoded(`Keywords can not be aliased to something else.\nTried mapping ${o} to ${JSON.stringify(r)}`,i.ERROR_CODES.KEYWORD_REDEFINITION);if(a.Util.ALIAS_RANGE_BLACKLIST.indexOf(a.Util.getContextValueId(r))>=0)throw new i.ErrorCoded(`Aliasing to certain keywords is not allowed.\nTried mapping ${o} to ${JSON.stringify(r)}`,i.ERROR_CODES.INVALID_KEYWORD_ALIAS);if(r&&a.Util.isPotentialKeyword(a.Util.getContextValueId(r))&&!0===r["@prefix"])throw new i.ErrorCoded(`Tried to use keyword aliases as prefix: '${o}': '${JSON.stringify(r)}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);for(;a.Util.isPrefixValue(n[o]);){const r=n[o];let i=!1;if("string"==typeof r)n[o]=e.expandTerm(r,!0),i=i||r!==n[o];else{const s=r["@id"],c=r["@type"],l=!("@prefix"in r)||a.Util.isValidIri(o);if("@id"in r)null!=s&&"string"==typeof s&&(n[o]=Object.assign(Object.assign({},n[o]),{"@id":e.expandTerm(s,!0)}),i=i||s!==n[o]["@id"]);else if(!a.Util.isPotentialKeyword(o)&&l){const t=e.expandTerm(o,!0);t!==o&&(n[o]=Object.assign(Object.assign({},n[o]),{"@id":t}),i=!0)}if(c&&"string"==typeof c&&"@vocab"!==c&&(!r["@container"]||!r["@container"]["@type"])&&l){let r=e.expandTerm(c,!0);t&&c===r&&(r=e.expandTerm(c,!1)),r!==c&&(i=!0,n[o]=Object.assign(Object.assign({},n[o]),{"@type":r}))}}if(!i)break}}}normalize(e,{processingMode:t,normalizeLanguageTags:r}){if(r||1===t)for(const t of Object.keys(e))if("@language"===t&&"string"==typeof e[t])e[t]=e[t].toLowerCase();else{const r=e[t];if(r&&"object"==typeof r&&"string"==typeof r["@language"]){const n=r["@language"].toLowerCase();n!==r["@language"]&&(e[t]=Object.assign(Object.assign({},r),{"@language":n}))}}}containersToHash(e){for(const t of Object.keys(e)){const r=e[t];if(r&&"object"==typeof r)if("string"==typeof r["@container"])e[t]=Object.assign(Object.assign({},r),{"@container":{[r["@container"]]:!0}});else if(Array.isArray(r["@container"])){const n={};for(const e of r["@container"])n[e]=!0;e[t]=Object.assign(Object.assign({},r),{"@container":n})}}}applyScopedProtected(e,{processingMode:t},r){if(t&&t>=1.1&&e["@protected"]){for(const t of Object.keys(e))if(!a.Util.isReservedInternalKeyword(t)&&!a.Util.isPotentialKeyword(t)&&!a.Util.isTermProtected(e,t)){const n=e[t];n&&"object"==typeof n?"@protected"in e[t]||(e[t]=Object.assign(Object.assign({},e[t]),{"@protected":!0})):(e[t]={"@id":n,"@protected":!0},a.Util.isSimpleTermDefinitionPrefix(n,r)&&(e[t]=Object.assign(Object.assign({},e[t]),{"@prefix":!0})))}delete e["@protected"]}}validateKeywordRedefinitions(e,t,r,n){for(const r of null!=n?n:Object.keys(t))if(a.Util.isTermProtected(e,r)&&("string"==typeof t[r]?t[r]={"@id":t[r],"@protected":!0}:t[r]=Object.assign(Object.assign({},t[r]),{"@protected":!0}),!a.Util.deepEqual(e[r],t[r])))throw new i.ErrorCoded(`Attempted to override the protected keyword ${r} from ${JSON.stringify(a.Util.getContextValueId(e[r]))} to ${JSON.stringify(a.Util.getContextValueId(t[r]))}`,i.ERROR_CODES.PROTECTED_TERM_REDEFINITION)}validate(e,{processingMode:t}){for(const r of Object.keys(e)){if(a.Util.isReservedInternalKeyword(r))continue;if(""===r)throw new i.ErrorCoded(`The empty term is not allowed, got: '${r}': '${JSON.stringify(e[r])}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);const n=e[r],o=typeof n;if(a.Util.isPotentialKeyword(r)){switch(r.substr(1)){case"vocab":if(null!==n&&"string"!==o)throw new i.ErrorCoded(`Found an invalid @vocab IRI: ${n}`,i.ERROR_CODES.INVALID_VOCAB_MAPPING);break;case"base":if(null!==n&&"string"!==o)throw new i.ErrorCoded(`Found an invalid @base IRI: ${e[r]}`,i.ERROR_CODES.INVALID_BASE_IRI);break;case"language":null!==n&&c.validateLanguage(n,!0,i.ERROR_CODES.INVALID_DEFAULT_LANGUAGE);break;case"version":if(null!==n&&"number"!==o)throw new i.ErrorCoded(`Found an invalid @version number: ${n}`,i.ERROR_CODES.INVALID_VERSION_VALUE);break;case"direction":null!==n&&c.validateDirection(n,!0);break;case"propagate":if(1===t)throw new i.ErrorCoded(`Found an illegal @propagate keyword: ${n}`,i.ERROR_CODES.INVALID_CONTEXT_ENTRY);if(null!==n&&"boolean"!==o)throw new i.ErrorCoded(`Found an invalid @propagate value: ${n}`,i.ERROR_CODES.INVALID_PROPAGATE_VALUE)}if(a.Util.isValidKeyword(r)&&a.Util.isValidKeyword(a.Util.getContextValueId(n)))throw new i.ErrorCoded(`Illegal keyword alias in term value, found: '${r}': '${a.Util.getContextValueId(n)}'`,i.ERROR_CODES.KEYWORD_REDEFINITION)}else if(null!==n)switch(o){case"string":if(a.Util.getPrefix(n,e)===r)throw new i.ErrorCoded(`Detected cyclical IRI mapping in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.CYCLIC_IRI_MAPPING);if(a.Util.isValidIriWeak(r)){if("@type"===n)throw new i.ErrorCoded(`IRIs can not be mapped to @type, found: '${r}': '${n}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.isValidIri(n)&&n!==new s.JsonLdContextNormalized(e).expandTerm(r))throw new i.ErrorCoded(`IRIs can not be mapped to other IRIs, found: '${r}': '${n}'`,i.ERROR_CODES.INVALID_IRI_MAPPING)}break;case"object":if(!(a.Util.isCompactIri(r)||"@id"in n||("@id"===n["@type"]?e["@base"]:e["@vocab"])))throw new i.ErrorCoded(`Missing @id in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);for(const l of Object.keys(n)){const u=n[l];if(u)switch(l){case"@id":if(a.Util.isValidKeyword(u)&&"@type"!==u&&"@id"!==u&&"@graph"!==u&&"@nest"!==u)throw new i.ErrorCoded(`Illegal keyword alias in term value, found: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.isValidIriWeak(r)){if("@type"===u)throw new i.ErrorCoded(`IRIs can not be mapped to @type, found: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.isValidIri(u)&&u!==new s.JsonLdContextNormalized(e).expandTerm(r))throw new i.ErrorCoded(`IRIs can not be mapped to other IRIs, found: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING)}if("string"!=typeof u)throw new i.ErrorCoded(`Detected non-string @id in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING);if(a.Util.getPrefix(u,e)===r)throw new i.ErrorCoded(`Detected cyclical IRI mapping in context entry: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.CYCLIC_IRI_MAPPING);break;case"@type":if("@type"===n["@container"]&&"@id"!==u&&"@vocab"!==u)throw new i.ErrorCoded(`@container: @type only allows @type: @id or @vocab, but got: '${r}': '${u}'`,i.ERROR_CODES.INVALID_TYPE_MAPPING);if("string"!=typeof u)throw new i.ErrorCoded(`The value of an '@type' must be a string, got '${JSON.stringify(o)}'`,i.ERROR_CODES.INVALID_TYPE_MAPPING);if(!("@id"===u||"@vocab"===u||1!==t&&"@json"===u||1!==t&&"@none"===u||"_"!==u[0]&&a.Util.isValidIri(u)))throw new i.ErrorCoded(`A context @type must be an absolute IRI, found: '${r}': '${u}'`,i.ERROR_CODES.INVALID_TYPE_MAPPING);break;case"@reverse":if("string"==typeof u&&n["@id"]&&n["@id"]!==u)throw new i.ErrorCoded(`Found non-matching @id and @reverse term values in '${r}':'${u}' and '${n["@id"]}'`,i.ERROR_CODES.INVALID_REVERSE_PROPERTY);if("@nest"in n)throw new i.ErrorCoded(`@nest is not allowed in the reverse property '${r}'`,i.ERROR_CODES.INVALID_REVERSE_PROPERTY);break;case"@container":if(1===t&&(Object.keys(u).length>1||a.Util.CONTAINERS_1_0.indexOf(Object.keys(u)[0])<0))throw new i.ErrorCoded(`Invalid term @container for '${r}' ('${Object.keys(u)}') in 1.0, must be only one of ${a.Util.CONTAINERS_1_0.join(", ")}`,i.ERROR_CODES.INVALID_CONTAINER_MAPPING);for(const e of Object.keys(u)){if("@list"===e&&n["@reverse"])throw new i.ErrorCoded(`Term value can not be @container: @list and @reverse at the same time on '${r}'`,i.ERROR_CODES.INVALID_REVERSE_PROPERTY);if(a.Util.CONTAINERS.indexOf(e)<0)throw new i.ErrorCoded(`Invalid term @container for '${r}' ('${e}'), must be one of ${a.Util.CONTAINERS.join(", ")}`,i.ERROR_CODES.INVALID_CONTAINER_MAPPING)}break;case"@language":c.validateLanguage(u,!0,i.ERROR_CODES.INVALID_LANGUAGE_MAPPING);break;case"@direction":c.validateDirection(u,!0);break;case"@prefix":if(null!==u&&"boolean"!=typeof u)throw new i.ErrorCoded(`Found an invalid term @prefix boolean in: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_PREFIX_VALUE);if(!("@id"in n)&&!a.Util.isValidIri(r))throw new i.ErrorCoded(`Invalid @prefix definition for '${r}' ('${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);break;case"@index":if(1===t||!n["@container"]||!n["@container"]["@index"])throw new i.ErrorCoded(`Attempt to add illegal key to value object: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION);break;case"@nest":if(a.Util.isPotentialKeyword(u)&&"@nest"!==u)throw new i.ErrorCoded(`Found an invalid term @nest value in: '${r}': '${JSON.stringify(n)}'`,i.ERROR_CODES.INVALID_NEST_VALUE)}}break;default:throw new i.ErrorCoded(`Found an invalid term value: '${r}': '${n}'`,i.ERROR_CODES.INVALID_TERM_DEFINITION)}}}applyBaseEntry(e,t,r){return"string"==typeof e||(r&&!("@base"in e)&&t.parentContext&&"object"==typeof t.parentContext&&"@base"in t.parentContext&&(e["@base"]=t.parentContext["@base"],t.parentContext["@__baseDocument"]&&(e["@__baseDocument"]=!0)),t.baseIRI&&!t.external&&("@base"in e?null===e["@base"]||"string"!=typeof e["@base"]||a.Util.isValidIri(e["@base"])||(e["@base"]=(0,n.resolve)(e["@base"],t.parentContext&&t.parentContext["@base"]||t.baseIRI)):(e["@base"]=t.baseIRI,e["@__baseDocument"]=!0))),e}normalizeContextIri(e,t){if(!a.Util.isValidIri(e))try{e=(0,n.resolve)(e,t)}catch(t){throw new Error(`Invalid context IRI: ${e}`)}return this.redirectSchemaOrgHttps&&e.startsWith("http://schema.org")&&(e="https://schema.org/"),e}async parseInnerContexts(e,t,r){for(const n of null!=r?r:Object.keys(e)){const r=e[n];if(r&&"object"==typeof r&&"@context"in r&&null!==r["@context"]&&!t.ignoreScopedContexts){if(this.validateContext)try{const i=Object.assign(Object.assign({},e),{[n]:Object.assign({},e[n])});delete i[n]["@context"],await this.parse(r["@context"],Object.assign(Object.assign({},t),{external:!1,parentContext:i,ignoreProtection:!0,ignoreRemoteScopedContexts:!0,ignoreScopedContexts:!0}))}catch(e){throw new i.ErrorCoded(e.message,i.ERROR_CODES.INVALID_SCOPED_CONTEXT)}e[n]=Object.assign(Object.assign({},r),{"@context":(await this.parse(r["@context"],Object.assign(Object.assign({},t),{external:!1,minimalProcessing:!0,ignoreRemoteScopedContexts:!0,parentContext:e}))).getContextRaw()})}}return e}async parse(e,t={},r={}){const{baseIRI:n,parentContext:o,external:l,processingMode:u=c.DEFAULT_PROCESSING_MODE,normalizeLanguageTags:d,ignoreProtection:h,minimalProcessing:f}=t,p=t.remoteContexts||{};if(Object.keys(p).length>=this.remoteContextsDepthLimit)throw new i.ErrorCoded("Detected an overflow in remote context inclusions: "+Object.keys(p),i.ERROR_CODES.CONTEXT_OVERFLOW);if(null==e){if(!h&&o&&a.Util.hasProtectedTerms(o))throw new i.ErrorCoded("Illegal context nullification when terms are protected",i.ERROR_CODES.INVALID_CONTEXT_NULLIFICATION);return new s.JsonLdContextNormalized(this.applyBaseEntry({},t,!1))}if("string"==typeof e){const r=this.normalizeContextIri(e,n),i=this.getOverriddenLoad(r,t);if(i)return new s.JsonLdContextNormalized(i);const o=await this.parse(await this.load(r),Object.assign(Object.assign({},t),{baseIRI:r,external:!0,remoteContexts:Object.assign(Object.assign({},p),{[r]:!0})}));return this.applyBaseEntry(o.getContextRaw(),t,!0),o}if(Array.isArray(e)){const r=[],i=await Promise.all(e.map(((e,i)=>{if("string"==typeof e){const o=this.normalizeContextIri(e,n);r[i]=o;return this.getOverriddenLoad(o,t)||this.load(o)}return e})));if(f)return new s.JsonLdContextNormalized(i);const a=await i.reduce(((e,n,o)=>e.then((e=>this.parse(n,Object.assign(Object.assign({},t),{baseIRI:r[o]||t.baseIRI,external:!!r[o]||t.external,parentContext:e.getContextRaw(),remoteContexts:r[o]?Object.assign(Object.assign({},p),{[r[o]]:!0}):p}),{skipValidation:o=1.1))throw new i.ErrorCoded("Context importing is not supported in JSON-LD 1.0",i.ERROR_CODES.INVALID_CONTEXT_ENTRY);if("string"!=typeof e["@import"])throw new i.ErrorCoded("An @import value must be a string, but got "+typeof e["@import"],i.ERROR_CODES.INVALID_IMPORT_VALUE);p=await this.loadImportContext(this.normalizeContextIri(e["@import"],n)),delete e["@import"]}this.applyScopedProtected(p,{processingMode:u},s.defaultExpandOptions);const g=Object.assign(p,e);this.idifyReverseTerms(g),this.normalize(g,{processingMode:u,normalizeLanguageTags:d}),this.applyScopedProtected(g,{processingMode:u},s.defaultExpandOptions);const y=Object.keys(g),m=[];if("object"==typeof o)for(const e in o)e in g?m.push(e):g[e]=o[e];await this.parseInnerContexts(g,t,y);const v=new s.JsonLdContextNormalized(g);return(g&&g["@version"]||c.DEFAULT_PROCESSING_MODE)>=1.1&&(e["@vocab"]&&"string"==typeof e["@vocab"]||""===e["@vocab"])&&(o&&"@vocab"in o&&e["@vocab"].indexOf(":")<0?g["@vocab"]=o["@vocab"]+e["@vocab"]:(a.Util.isCompactIri(e["@vocab"])||e["@vocab"]in g)&&(g["@vocab"]=v.expandTerm(e["@vocab"],!0))),this.expandPrefixedTerms(v,this.expandContentTypeToBase,y),!h&&o&&u>=1.1&&this.validateKeywordRedefinitions(o,g,s.defaultExpandOptions,m),this.validateContext&&!r.skipValidation&&this.validate(g,{processingMode:u}),v}throw new i.ErrorCoded(`Tried parsing a context that is not a string, array or object, but got ${e}`,i.ERROR_CODES.INVALID_LOCAL_CONTEXT)}async load(e){const t=this.documentCache[e];if(t)return t;let r;try{r=await this.documentLoader.load(e)}catch(t){throw new i.ErrorCoded(`Failed to load remote context ${e}: ${t.message}`,i.ERROR_CODES.LOADING_REMOTE_CONTEXT_FAILED)}if(!("@context"in r))throw new i.ErrorCoded(`Missing @context in remote context at ${e}`,i.ERROR_CODES.INVALID_REMOTE_CONTEXT);return this.documentCache[e]=r["@context"]}getOverriddenLoad(e,t){if(e in(t.remoteContexts||{})){if(t.ignoreRemoteScopedContexts)return e;throw new i.ErrorCoded("Detected a cyclic context inclusion of "+e,i.ERROR_CODES.RECURSIVE_CONTEXT_INCLUSION)}return null}async loadImportContext(e){let t=await this.load(e);if("object"!=typeof t||Array.isArray(t))throw new i.ErrorCoded("An imported context must be a single object: "+e,i.ERROR_CODES.INVALID_REMOTE_CONTEXT);if("@import"in t)throw new i.ErrorCoded("An imported context can not import another context: "+e,i.ERROR_CODES.INVALID_CONTEXT_ENTRY);return t=Object.assign({},t),this.containersToHash(t),t}}c.DEFAULT_PROCESSING_MODE=1.1,t.ContextParser=c},5094:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_CODES=t.ErrorCoded=void 0;class r extends Error{constructor(e,t){super(e),this.code=t}}var n;t.ErrorCoded=r,(n=t.ERROR_CODES||(t.ERROR_CODES={})).COLLIDING_KEYWORDS="colliding keywords",n.CONFLICTING_INDEXES="conflicting indexes",n.CYCLIC_IRI_MAPPING="cyclic IRI mapping",n.INVALID_ID_VALUE="invalid @id value",n.INVALID_INDEX_VALUE="invalid @index value",n.INVALID_NEST_VALUE="invalid @nest value",n.INVALID_PREFIX_VALUE="invalid @prefix value",n.INVALID_PROPAGATE_VALUE="invalid @propagate value",n.INVALID_REVERSE_VALUE="invalid @reverse value",n.INVALID_IMPORT_VALUE="invalid @import value",n.INVALID_VERSION_VALUE="invalid @version value",n.INVALID_BASE_IRI="invalid base IRI",n.INVALID_CONTAINER_MAPPING="invalid container mapping",n.INVALID_CONTEXT_ENTRY="invalid context entry",n.INVALID_CONTEXT_NULLIFICATION="invalid context nullification",n.INVALID_DEFAULT_LANGUAGE="invalid default language",n.INVALID_INCLUDED_VALUE="invalid @included value",n.INVALID_IRI_MAPPING="invalid IRI mapping",n.INVALID_JSON_LITERAL="invalid JSON literal",n.INVALID_KEYWORD_ALIAS="invalid keyword alias",n.INVALID_LANGUAGE_MAP_VALUE="invalid language map value",n.INVALID_LANGUAGE_MAPPING="invalid language mapping",n.INVALID_LANGUAGE_TAGGED_STRING="invalid language-tagged string",n.INVALID_LANGUAGE_TAGGED_VALUE="invalid language-tagged value",n.INVALID_LOCAL_CONTEXT="invalid local context",n.INVALID_REMOTE_CONTEXT="invalid remote context",n.INVALID_REVERSE_PROPERTY="invalid reverse property",n.INVALID_REVERSE_PROPERTY_MAP="invalid reverse property map",n.INVALID_REVERSE_PROPERTY_VALUE="invalid reverse property value",n.INVALID_SCOPED_CONTEXT="invalid scoped context",n.INVALID_SCRIPT_ELEMENT="invalid script element",n.INVALID_SET_OR_LIST_OBJECT="invalid set or list object",n.INVALID_TERM_DEFINITION="invalid term definition",n.INVALID_TYPE_MAPPING="invalid type mapping",n.INVALID_TYPE_VALUE="invalid type value",n.INVALID_TYPED_VALUE="invalid typed value",n.INVALID_VALUE_OBJECT="invalid value object",n.INVALID_VALUE_OBJECT_VALUE="invalid value object value",n.INVALID_VOCAB_MAPPING="invalid vocab mapping",n.IRI_CONFUSED_WITH_PREFIX="IRI confused with prefix",n.KEYWORD_REDEFINITION="keyword redefinition",n.LOADING_DOCUMENT_FAILED="loading document failed",n.LOADING_REMOTE_CONTEXT_FAILED="loading remote context failed",n.MULTIPLE_CONTEXT_LINK_HEADERS="multiple context link headers",n.PROCESSING_MODE_CONFLICT="processing mode conflict",n.PROTECTED_TERM_REDEFINITION="protected term redefinition",n.CONTEXT_OVERFLOW="context overflow",n.INVALID_BASE_DIRECTION="invalid base direction",n.RECURSIVE_CONTEXT_INCLUSION="recursive context inclusion",n.INVALID_STREAMING_KEY_ORDER="invalid streaming key order",n.INVALID_EMBEDDED_NODE="invalid embedded node",n.INVALID_ANNOTATION="invalid annotation"},585:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FetchDocumentLoader=void 0,r(6547);const n=r(5094),i=r(2384),o=r(742);t.FetchDocumentLoader=class{constructor(e){this.fetcher=e}async load(e){const t=await(this.fetcher||fetch)(e,{headers:new Headers({accept:"application/ld+json"})});if(t.ok&&t.headers){let r=t.headers.get("Content-Type");if(r){const e=r.indexOf(";");e>0&&(r=r.substr(0,e))}if("application/ld+json"===r)return await t.json();if(t.headers.has("Link")){let r;if(t.headers.forEach(((t,n)=>{if("link"===n){const n=(0,i.parse)(t);for(const t of n.get("type","application/ld+json"))if("alternate"===t.rel){if(r)throw new Error("Multiple JSON-LD alternate links were found on "+e);r=(0,o.resolve)(t.uri,e)}}})),r)return this.load(r)}throw new n.ErrorCoded(`Unsupported JSON-LD media type ${r}`,n.ERROR_CODES.LOADING_DOCUMENT_FAILED)}throw new Error(t.statusText||`Status code: ${t.status}`)}}},9146:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5086:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5215:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultExpandOptions=t.JsonLdContextNormalized=void 0;const n=r(742),i=r(5094),o=r(4931);t.JsonLdContextNormalized=class{constructor(e){this.contextRaw=e}getContextRaw(){return this.contextRaw}expandTerm(e,r,s=t.defaultExpandOptions){const a=this.contextRaw[e];if(null===a||a&&null===a["@id"])return null;let c=!0;if(a&&r){const t=o.Util.getContextValueId(a);if(t&&t!==e){if("string"==typeof t&&(o.Util.isValidIri(t)||o.Util.isValidKeyword(t)))return t;o.Util.isPotentialKeyword(t)||(c=!1)}}const l=o.Util.getPrefix(e,this.contextRaw),u=this.contextRaw["@vocab"],d=(!!u||""===u)&&u.indexOf(":")<0,h=this.contextRaw["@base"],f=o.Util.isPotentialKeyword(e);if(l){const t=this.contextRaw[l],r=o.Util.getContextValueId(t);if(r){if("string"!=typeof t&&s.allowPrefixForcing){if("_"!==r[0]&&!f&&!t["@prefix"]&&!(e in this.contextRaw))return e}else if(!o.Util.isSimpleTermDefinitionPrefix(r,s))return e;return r+e.substr(l.length+1)}}else{if(r&&(u||""===u||s.allowVocabRelativeToBase&&h&&d)&&!f&&!o.Util.isCompactIri(e)){if(d){if(s.allowVocabRelativeToBase)return(u||h?(0,n.resolve)(u,h):"")+e;throw new i.ErrorCoded(`Relative vocab expansion for term '${e}' with vocab '${u}' is not allowed.`,i.ERROR_CODES.INVALID_VOCAB_MAPPING)}return u+e}if(!r&&h&&!f&&!o.Util.isCompactIri(e))return(0,n.resolve)(e,h)}if(c)return e;throw new i.ErrorCoded(`Invalid IRI mapping found for context entry '${e}': '${JSON.stringify(a)}'`,i.ERROR_CODES.INVALID_IRI_MAPPING)}compactIri(e,t){if(t&&this.contextRaw["@vocab"]&&e.startsWith(this.contextRaw["@vocab"]))return e.substr(this.contextRaw["@vocab"].length);if(!t&&this.contextRaw["@base"]&&e.startsWith(this.contextRaw["@base"]))return e.substr(this.contextRaw["@base"].length);const r={prefix:"",suffix:e};for(const n in this.contextRaw){const i=this.contextRaw[n];if(i&&!o.Util.isPotentialKeyword(n)){const s=o.Util.getContextValueId(i);if(e.startsWith(s)){const i=e.substr(s.length);if(i)i.length0&&!(e&&"#"===e[0])}static getPrefix(e,t){if(e&&"#"===e[0])return null;const r=e.indexOf(":");if(r>=0){if(e.length>r+1&&"/"===e.charAt(r+1)&&"/"===e.charAt(r+2))return null;const n=e.substr(0,r);if("_"===n)return null;if(t[n])return n}return null}static getContextValueId(e){if(null===e||"string"==typeof e)return e;return e["@id"]||null}static isSimpleTermDefinitionPrefix(e,t){return!r.isPotentialKeyword(e)&&(t.allowPrefixNonGenDelims||"string"==typeof e&&("_"===e[0]||r.isPrefixIriEndingWithGenDelim(e)))}static isPotentialKeyword(e){return"string"==typeof e&&r.KEYWORD_REGEX.test(e)}static isPrefixIriEndingWithGenDelim(e){return r.ENDS_WITH_GEN_DELIM.test(e)}static isPrefixValue(e){return e&&("string"==typeof e||e&&"object"==typeof e)}static isValidIri(e){return Boolean(e&&r.IRI_REGEX.test(e))}static isValidIriWeak(e){return!!e&&":"!==e[0]&&r.IRI_REGEX_WEAK.test(e)}static isValidKeyword(e){return r.VALID_KEYWORDS[e]}static isTermProtected(e,t){const r=e[t];return!("string"==typeof r)&&r&&r["@protected"]}static hasProtectedTerms(e){for(const t of Object.keys(e))if(r.isTermProtected(e,t))return!0;return!1}static isReservedInternalKeyword(e){return e.startsWith("@__")}static deepEqual(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every((r=>{const n=e[r],i=t[r];return n===i||null!==n&&null!==i&&"object"==typeof n&&"object"==typeof i&&this.deepEqual(n,i)}))}}r.IRI_REGEX=/^([A-Za-z][A-Za-z0-9+-.]*|_):[^ "<>{}|\\\[\]`#]*(#[^#]*)?$/,r.IRI_REGEX_WEAK=/(?::[^:])|\//,r.KEYWORD_REGEX=/^@[a-z]+$/i,r.ENDS_WITH_GEN_DELIM=/[:/?#\[\]@]$/,r.REGEX_LANGUAGE_TAG=/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/,r.REGEX_DIRECTION_TAG=/^(ltr)|(rtl)$/,r.VALID_KEYWORDS={"@annotation":!0,"@base":!0,"@container":!0,"@context":!0,"@direction":!0,"@graph":!0,"@id":!0,"@import":!0,"@included":!0,"@index":!0,"@json":!0,"@language":!0,"@list":!0,"@nest":!0,"@none":!0,"@prefix":!0,"@propagate":!0,"@protected":!0,"@reverse":!0,"@set":!0,"@type":!0,"@value":!0,"@version":!0,"@vocab":!0},r.EXPAND_KEYS_BLACKLIST=["@base","@vocab","@language","@version","@direction"],r.ALIAS_DOMAIN_BLACKLIST=["@container","@graph","@id","@index","@list","@nest","@none","@prefix","@reverse","@set","@type","@value","@version"],r.ALIAS_RANGE_BLACKLIST=["@context","@preserve"],r.CONTAINERS=["@list","@set","@index","@language","@graph","@id","@type"],r.CONTAINERS_1_0=["@list","@set","@index"],t.Util=r},8690:function(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(2277),t)},4405:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextTree=void 0;class r{constructor(){this.subTrees={}}getContext(e){if(e.length>0){const[t,...r]=e,n=this.subTrees[t];if(n){const e=n.getContext(r);if(e)return e.then((({context:e,depth:t})=>({context:e,depth:t+1})))}}return this.context?this.context.then((e=>({context:e,depth:0}))):null}setContext(e,t){if(0===e.length)this.context=t;else{const[n,...i]=e;let o=this.subTrees[n];o||(o=this.subTrees[n]=new r),o.setContext(i,t)}}removeContext(e){this.setContext(e,null)}}t.ContextTree=r},2277:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonLdParser=void 0;const n=r(608),i=r(2395),o=r(2225),s=r(9693),a=r(4860),c=r(2386),l=r(6970),u=r(3809),d=r(5998),h=r(5517),f=r(736),p=r(4910),g=r(2036),y=r(6454),m=r(3283),v=r(3099),b=r(888),w=r(2384),_=r(6105);class S extends o.Transform{constructor(e){super({readableObjectMode:!0}),e=e||{},this.options=e,this.parsingContext=new v.ParsingContext(Object.assign({parser:this},e)),this.util=new b.Util({dataFactory:e.dataFactory,parsingContext:this.parsingContext}),this.jsonParser=new n,this.contextJobs=[],this.typeJobs=[],this.contextAwaitingJobs=[],this.lastDepth=0,this.lastKeys=[],this.lastOnValueJob=Promise.resolve(),this.attachJsonParserListeners(),this.on("end",(()=>{void 0!==this.jsonParser.mode&&this.emit("error",new Error("Unclosed document"))}))}static fromHttpResponse(e,t,r,n){let o,s,a=["application/activity+json"];if(n&&n.wellKnownMediaTypes&&(a=n.wellKnownMediaTypes),"application/ld+json"!==t&&!a.includes(t)){if("application/json"!==t&&!t.endsWith("+json"))throw new i.ErrorCoded(`Unsupported JSON-LD media type ${t}`,i.ERROR_CODES.LOADING_DOCUMENT_FAILED);if(r&&r.has("Link")&&r.forEach(((t,r)=>{if("link"===r){const r=(0,w.parse)(t);for(const t of r.get("rel","http://www.w3.org/ns/json-ld#context")){if(o)throw new i.ErrorCoded("Multiple JSON-LD context link headers were found on "+e,i.ERROR_CODES.MULTIPLE_CONTEXT_LINK_HEADERS);o=t.uri}}})),!o&&!(null==n?void 0:n.ignoreMissingContextLinkHeader))throw new i.ErrorCoded(`Missing context link header for media type ${t} on ${e}`,i.ERROR_CODES.LOADING_DOCUMENT_FAILED)}if(r&&r.has("Content-Type")){const e=r.get("Content-Type"),t=/; *profile=([^"]*)/.exec(e);t&&"http://www.w3.org/ns/json-ld#streaming"===t[1]&&(s=!0)}return new S(Object.assign({baseIRI:e,context:o,streamingProfile:s},n||{}))}import(e){if("pipe"in e){e.on("error",(e=>t.emit("error",e)));const t=e.pipe(new S(this.options));return t}{const t=new o.PassThrough({readableObjectMode:!0});e.on("error",(e=>r.emit("error",e))),e.on("data",(e=>t.push(e))),e.on("end",(()=>t.push(null)));const r=t.pipe(new S(this.options));return r}}_transform(e,t,r){this.jsonParser.write(e),this.lastOnValueJob.then((()=>r()),(e=>r(e)))}async newOnValueJob(e,t,r,n){let o=!0;if(n&&r1&&(u=this.parsingContext.validationStack[this.parsingContext.validationStack.length-1].property);for(let t=Math.max(1,this.parsingContext.validationStack.length-1);t=0?this.parsingContext.idStack[e-r-1]:[await this.util.getGraphContainerValue(t,e)];if(o)for(const t of o){this.parsingContext.emittedStack[e]=!0;for(const r of n)this.util.emitQuadChecked(e,i,r.predicate,r.object,t,r.reverse,r.isEmbedded)}else{const r=this.parsingContext.getUnidentifiedGraphBufferSafe(e-await this.util.getDepthOffsetGraph(e,t)-1);for(const e of n)e.reverse?r.push({object:i,predicate:e.predicate,subject:e.object,isEmbedded:e.isEmbedded}):r.push({object:e.object,predicate:e.predicate,subject:i,isEmbedded:e.isEmbedded})}}this.parsingContext.unidentifiedValuesBuffer.splice(e,1),this.parsingContext.literalStack.splice(e,1),this.parsingContext.jsonLiteralStack.splice(e,1)}const o=this.parsingContext.unidentifiedGraphsBuffer[e];if(o){for(const t of r){const r=1!==e||"BlankNode"!==t.termType||this.parsingContext.topLevelProperties?t:this.util.getDefaultGraph();this.parsingContext.emittedStack[e]=!0;for(const t of o)this.parsingContext.emitQuad(e,this.util.dataFactory.quad(t.subject,t.predicate,t.object,r))}this.parsingContext.unidentifiedGraphsBuffer.splice(e,1)}const s=this.parsingContext.annotationsBuffer[e];if(s){s.length>0&&1===e&&this.parsingContext.emitError(new i.ErrorCoded("Annotations can not be made on top-level nodes",i.ERROR_CODES.INVALID_ANNOTATION));const t=this.parsingContext.getAnnotationsBufferSafe(e-1);for(const e of s)t.push(e);delete this.parsingContext.annotationsBuffer[e]}}async validateKey(e,t,r){for(const n of S.ENTRY_HANDLERS)if(await n.validate(this.parsingContext,this.util,e,t,r))return{valid:!0,property:r||n.isPropertyHandler()};return{valid:!1,property:!1}}attachJsonParserListeners(){this.jsonParser.onValue=e=>{const t=this.jsonParser.stack.length,r=new Array(t+1).fill(0).map(((e,r)=>r===t?this.jsonParser.key:this.jsonParser.stack[r].key));if(!this.isParsingContextInner(t)){const n=()=>this.newOnValueJob(r,e,t,!0);if(this.parsingContext.streamingProfile||this.parsingContext.contextTree.getContext(r.slice(0,-1)))this.lastOnValueJob=this.lastOnValueJob.then(n);else if("@context"===r[t]){let e=this.contextJobs[t];e||(e=this.contextJobs[t]=[]),e.push(n)}else this.contextAwaitingJobs.push({job:n,keys:r,depth:t});this.parsingContext.streamingProfile||0!==t||(this.lastOnValueJob=this.lastOnValueJob.then((()=>this.executeBufferedJobs())))}},this.jsonParser.onError=e=>{this.emit("error",e)}}isParsingContextInner(e){for(let t=e;t>0;t--)if("@context"===this.jsonParser.stack[t-1].key)return!0;return!1}async executeBufferedJobs(){for(const e of this.contextJobs)if(e)for(const t of e)await t();this.parsingContext.unaliasedKeywordCacheStack.splice(0);const e=[];for(const t of this.contextAwaitingJobs)"@type"===await this.util.unaliasKeyword(t.keys[t.depth],t.keys,t.depth,!0)||"number"==typeof t.keys[t.depth]&&"@type"===await this.util.unaliasKeyword(t.keys[t.depth-1],t.keys,t.depth-1,!0)?this.typeJobs.push({job:t.job,keys:t.keys.slice(0,t.keys.length-1)}):e.push(t);for(const t of e){if(this.typeJobs.length>0){const e=[],r=[];for(let n=0;ne.keys.length-t.keys.length));for(const e of n)await e.job();const i=r.sort().reverse();for(const e of i)this.typeJobs.splice(e,1)}await t.job()}}}S.DEFAULT_PROCESSING_MODE="1.1",S.ENTRY_HANDLERS=[new s.EntryHandlerArrayValue,new u.EntryHandlerKeywordContext,new h.EntryHandlerKeywordId,new f.EntryHandlerKeywordIncluded,new d.EntryHandlerKeywordGraph,new p.EntryHandlerKeywordNest,new g.EntryHandlerKeywordType,new m.EntryHandlerKeywordValue,new _.EntryHandlerKeywordAnnotation,new a.EntryHandlerContainer,new y.EntryHandlerKeywordUnknownFallback,new l.EntryHandlerPredicate,new c.EntryHandlerInvalidFallback],t.JsonLdParser=S},3099:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ParsingContext=void 0;const n=r(2395),i=r(5094),o=r(4405),s=r(2277);class a{constructor(e){this.contextParser=new n.ContextParser({documentLoader:e.documentLoader,skipValidation:e.skipContextValidation}),this.streamingProfile=!!e.streamingProfile,this.baseIRI=e.baseIRI,this.produceGeneralizedRdf=!!e.produceGeneralizedRdf,this.allowSubjectList=!!e.allowSubjectList,this.processingMode=e.processingMode||s.JsonLdParser.DEFAULT_PROCESSING_MODE,this.strictValues=!!e.strictValues,this.validateValueIndexes=!!e.validateValueIndexes,this.defaultGraph=e.defaultGraph,this.rdfDirection=e.rdfDirection,this.normalizeLanguageTags=e.normalizeLanguageTags,this.streamingProfileAllowOutOfOrderPlainType=e.streamingProfileAllowOutOfOrderPlainType,this.rdfstar=!1!==e.rdfstar,this.rdfstarReverseInEmbedded=e.rdfstarReverseInEmbedded,this.topLevelProperties=!1,this.activeProcessingMode=parseFloat(this.processingMode),this.processingStack=[],this.processingType=[],this.emittedStack=[],this.idStack=[],this.graphStack=[],this.graphContainerTermStack=[],this.listPointerStack=[],this.contextTree=new o.ContextTree,this.literalStack=[],this.validationStack=[],this.unaliasedKeywordCacheStack=[],this.jsonLiteralStack=[],this.unidentifiedValuesBuffer=[],this.unidentifiedGraphsBuffer=[],this.annotationsBuffer=[],this.pendingContainerFlushBuffers=[],this.parser=e.parser,e.context?(this.rootContext=this.parseContext(e.context),this.rootContext.then((e=>this.validateContext(e)))):this.rootContext=Promise.resolve(new n.JsonLdContextNormalized(this.baseIRI?{"@base":this.baseIRI,"@__baseDocument":!0}:{}))}async parseContext(e,t,r){return this.contextParser.parse(e,{baseIRI:this.baseIRI,ignoreProtection:r,normalizeLanguageTags:this.normalizeLanguageTags,parentContext:t,processingMode:this.activeProcessingMode})}validateContext(e){const t=e.getContextRaw()["@version"];if(t){if(this.activeProcessingMode&&t>this.activeProcessingMode)throw new i.ErrorCoded(`Unsupported JSON-LD version '${t}' under active processing mode ${this.activeProcessingMode}.`,i.ERROR_CODES.PROCESSING_MODE_CONFLICT);if(this.activeProcessingMode&&t0&&!1===i.context.getContextRaw()["@propagate"]&&i.depth!==t&&!r);return 0===i.depth&&!1===i.context.getContextRaw()["@propagate"]&&i.depth!==t&&(i.context=new n.JsonLdContextNormalized({})),i}async newOnValueJob(e,t,r,n){await this.parser.newOnValueJob(e,t,r,n)}async handlePendingContainerFlushBuffers(){if(this.pendingContainerFlushBuffers.length>0){for(const e of this.pendingContainerFlushBuffers)await this.parser.flushBuffer(e.depth,e.keys),this.parser.flushStacks(e.depth);return this.pendingContainerFlushBuffers.splice(0,this.pendingContainerFlushBuffers.length),!0}return!1}emitQuad(e,t){1===e&&(this.topLevelProperties=!0),this.parser.push(t)}emitError(e){this.parser.emit("error",e)}emitContext(e){this.parser.emit("context",e)}getUnidentifiedValueBufferSafe(e){let t=this.unidentifiedValuesBuffer[e];return t||(t=[],this.unidentifiedValuesBuffer[e]=t),t}getUnidentifiedGraphBufferSafe(e){let t=this.unidentifiedGraphsBuffer[e];return t||(t=[],this.unidentifiedGraphsBuffer[e]=t),t}getAnnotationsBufferSafe(e){let t=this.annotationsBuffer[e];return t||(t=[],this.annotationsBuffer[e]=t),t}getExpandOptions(){return a.EXPAND_OPTIONS[this.activeProcessingMode]}shiftStack(e,t){const r=this.idStack[e+t];if(r&&(this.idStack[e]=r,this.emittedStack[e]=!0,delete this.idStack[e+t]),this.pendingContainerFlushBuffers.length)for(const r of this.pendingContainerFlushBuffers)r.depth>=e+t&&(r.depth-=t,r.keys.splice(e,t));this.unidentifiedValuesBuffer[e+t]&&(this.unidentifiedValuesBuffer[e]=this.unidentifiedValuesBuffer[e+t],delete this.unidentifiedValuesBuffer[e+t]),this.annotationsBuffer[e+t-1]&&(this.annotationsBuffer[e-1]||(this.annotationsBuffer[e-1]=[]),this.annotationsBuffer[e-1]=[...this.annotationsBuffer[e-1],...this.annotationsBuffer[e+t-1]],delete this.annotationsBuffer[e+t-1])}}a.EXPAND_OPTIONS={1:{allowPrefixForcing:!1,allowPrefixNonGenDelims:!1,allowVocabRelativeToBase:!1},1.1:{allowPrefixForcing:!0,allowPrefixNonGenDelims:!1,allowVocabRelativeToBase:!0}},t.ParsingContext=a},888:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Util=void 0;const n=r(2395),i=r(7793),o=r(4860),s=r(2341);class a{constructor(e){this.parsingContext=e.parsingContext,this.dataFactory=e.dataFactory||new i.DataFactory,this.rdfFirst=this.dataFactory.namedNode(a.RDF+"first"),this.rdfRest=this.dataFactory.namedNode(a.RDF+"rest"),this.rdfNil=this.dataFactory.namedNode(a.RDF+"nil"),this.rdfType=this.dataFactory.namedNode(a.RDF+"type"),this.rdfJson=this.dataFactory.namedNode(a.RDF+"JSON")}static getContextValue(e,t,r,n){const i=e.getContextRaw()[r];if(!i)return n;const o=i[t];return void 0===o?n:o}static getContextValueContainer(e,t){return a.getContextValue(e,"@container",t,{"@set":!0})}static getContextValueType(e,t){const r=a.getContextValue(e,"@type",t,null);return"@none"===r?null:r}static getContextValueLanguage(e,t){return a.getContextValue(e,"@language",t,e.getContextRaw()["@language"]||null)}static getContextValueDirection(e,t){return a.getContextValue(e,"@direction",t,e.getContextRaw()["@direction"]||null)}static isContextValueReverse(e,t){return!!a.getContextValue(e,"@reverse",t,null)}static getContextValueIndex(e,t){return a.getContextValue(e,"@index",t,e.getContextRaw()["@index"]||null)}static isPropertyReverse(e,t,r){return"@reverse"===r!==a.isContextValueReverse(e,t)}static isPropertyInEmbeddedNode(e){return"@id"===e}static isPropertyInAnnotationObject(e){return"@annotation"===e}static isValidIri(e){return null!==e&&n.Util.isValidIri(e)}static isPrefixArray(e,t){if(e.length>t.length)return!1;for(let r=0;r1)throw new n.ErrorCoded(`Found illegal neighbouring entries next to @set for key: '${t}'`,n.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT);return[]}if("@list"in r){if(Object.keys(r).length>1)throw new n.ErrorCoded(`Found illegal neighbouring entries next to @list for key: '${t}'`,n.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT);const e=r["@list"];return Array.isArray(e)?0===e.length?[this.rdfNil]:this.parsingContext.idStack[i+1]||[]:await this.valueToTerm(await this.parsingContext.getContext(o),t,e,i-1,o.slice(0,-1))}if("@reverse"in r&&"boolean"==typeof r["@reverse"])return[];if("@graph"in a.getContextValueContainer(await this.parsingContext.getContext(o),t)){const e=this.parsingContext.graphContainerTermStack[i+1];return e?Object.values(e):[this.dataFactory.blankNode()]}if("@id"in r){if(Object.keys(r).length>1&&(e=await this.parsingContext.getContext(o,0)),"@context"in r&&(e=await this.parsingContext.parseContext(r["@context"],e.getContextRaw())),"@vocab"===r["@type"])return this.nullableTermToArray(this.createVocabOrBaseTerm(e,r["@id"]));{const t=r["@id"];let o;if("object"==typeof t){if(!this.parsingContext.rdfstar)throw new n.ErrorCoded(`Found illegal @id '${r}'`,n.ERROR_CODES.INVALID_ID_VALUE);o=this.parsingContext.idStack[i+1][0]}else o=this.resourceToTerm(e,t);return this.nullableTermToArray(o)}}return this.parsingContext.emittedStack[i+1]||r&&"object"==typeof r&&0===Object.keys(r).length?this.parsingContext.idStack[i+1]||(this.parsingContext.idStack[i+1]=[this.dataFactory.blankNode()]):[];case"string":return this.nullableTermToArray(this.stringValueToTerm(i,await this.getContextSelfOrPropertyScoped(e,t),t,r,null));case"boolean":return this.nullableTermToArray(this.stringValueToTerm(i,await this.getContextSelfOrPropertyScoped(e,t),t,Boolean(r).toString(),this.dataFactory.namedNode(a.XSD_BOOLEAN)));case"number":return this.nullableTermToArray(this.stringValueToTerm(i,await this.getContextSelfOrPropertyScoped(e,t),t,r,this.dataFactory.namedNode(r%1==0&&r<1e21?a.XSD_INTEGER:a.XSD_DOUBLE)));default:return this.parsingContext.emitError(new Error(`Could not determine the RDF type of a ${s}`)),[]}}async getContextSelfOrPropertyScoped(e,t){const r=e.getContextRaw()[t];return r&&"object"==typeof r&&"@context"in r&&(e=await this.parsingContext.parseContext(r,e.getContextRaw(),!0)),e}nullableTermToArray(e){return e?[e]:[]}predicateToTerm(e,t){const r=e.expandTerm(t,!0,this.parsingContext.getExpandOptions());return r?"_"===r[0]&&":"===r[1]?this.parsingContext.produceGeneralizedRdf?this.dataFactory.blankNode(r.substr(2)):null:a.isValidIri(r)?this.dataFactory.namedNode(r):r&&this.parsingContext.strictValues?(this.parsingContext.emitError(new n.ErrorCoded(`Invalid predicate IRI: ${r}`,n.ERROR_CODES.INVALID_IRI_MAPPING)),null):null:null}resourceToTerm(e,t){if(t.startsWith("_:"))return this.dataFactory.blankNode(t.substr(2));const r=e.expandTerm(t,!1,this.parsingContext.getExpandOptions());if(!a.isValidIri(r)){if(!r||!this.parsingContext.strictValues)return null;this.parsingContext.emitError(new Error(`Invalid resource IRI: ${r}`))}return this.dataFactory.namedNode(r)}createVocabOrBaseTerm(e,t){if(t.startsWith("_:"))return this.dataFactory.blankNode(t.substr(2));const r=this.parsingContext.getExpandOptions();let n=e.expandTerm(t,!0,r);if(n===t&&(n=e.expandTerm(t,!1,r)),!a.isValidIri(n)){if(!n||!this.parsingContext.strictValues||n.startsWith("@"))return null;this.parsingContext.emitError(new Error(`Invalid term IRI: ${n}`))}return this.dataFactory.namedNode(n)}intToString(e,t){return"number"==typeof e?Number.isFinite(e)?e%1!=0||t&&t.value===a.XSD_DOUBLE?e.toExponential(15).replace(/(\d)0*e\+?/,"$1E"):Number(e).toString():e>0?"INF":"-INF":e}stringValueToTerm(e,t,r,n,i){const o=a.getContextValueType(t,r);if(o)if("@id"===o){if(!i)return this.resourceToTerm(t,this.intToString(n,i))}else if("@vocab"===o){if(!i)return this.createVocabOrBaseTerm(t,this.intToString(n,i))}else i=this.dataFactory.namedNode(o);if(!i){const o=a.getContextValueLanguage(t,r),s=a.getContextValueDirection(t,r);return s&&this.parsingContext.rdfDirection?this.createLanguageDirectionLiteral(e,this.intToString(n,i),o,s):this.dataFactory.literal(this.intToString(n,i),o)}return this.dataFactory.literal(this.intToString(n,i),i)}createLanguageDirectionLiteral(e,t,r,n){if("i18n-datatype"===this.parsingContext.rdfDirection)return r||(r=""),this.dataFactory.literal(t,this.dataFactory.namedNode(`https://www.w3.org/ns/i18n#${r}_${n}`));{const i=this.dataFactory.blankNode(),o=this.getDefaultGraph();return this.parsingContext.emitQuad(e,this.dataFactory.quad(i,this.dataFactory.namedNode(a.RDF+"value"),this.dataFactory.literal(t),o)),r&&this.parsingContext.emitQuad(e,this.dataFactory.quad(i,this.dataFactory.namedNode(a.RDF+"language"),this.dataFactory.literal(r),o)),this.parsingContext.emitQuad(e,this.dataFactory.quad(i,this.dataFactory.namedNode(a.RDF+"direction"),this.dataFactory.literal(n),o)),i}}valueToJsonString(e){return s(e)}async unaliasKeyword(e,t,r,i,o){if(Number.isInteger(e))return e;if(!i){const e=this.parsingContext.unaliasedKeywordCacheStack[r];if(e)return e}if(!n.Util.isPotentialKeyword(e)){let r=(o=o||await this.parsingContext.getContext(t)).getContextRaw()[e];r&&"object"==typeof r&&(r=r["@id"]),n.Util.isValidKeyword(r)&&(e=r)}return i?e:this.parsingContext.unaliasedKeywordCacheStack[r]=e}async unaliasKeywordParent(e,t){return await this.unaliasKeyword(t>0&&e[t-1],e,t-1)}async unaliasKeywords(e,t,r,n){const i={};for(const o in e)i[await this.unaliasKeyword(o,t,r+1,!0,n)]=e[o];return i}async isLiteral(e,t){for(let r=t;r>=0;r--){if("@annotation"===await this.unaliasKeyword(e[r],e,r))return!1;if(this.parsingContext.literalStack[r]||this.parsingContext.jsonLiteralStack[r])return!0}return!1}async getDepthOffsetGraph(e,t){for(let r=e-1;r>0;r--)if("@graph"===await this.unaliasKeyword(t[r],t,r)){const n=(await o.EntryHandlerContainer.getContainerHandler(this.parsingContext,t,r)).containers;return o.EntryHandlerContainer.isComplexGraphContainer(n)?-1:e-r-1}return-1}validateReverseSubject(e){if("Literal"===e.termType)throw new n.ErrorCoded(`Found illegal literal in subject position: ${e.value}`,n.ERROR_CODES.INVALID_REVERSE_PROPERTY_VALUE)}getDefaultGraph(){return this.parsingContext.defaultGraph||this.dataFactory.defaultGraph()}async getGraphContainerValue(e,t){let r=this.getDefaultGraph();const{containers:n,depth:i}=await o.EntryHandlerContainer.getContainerHandler(this.parsingContext,e,t);if("@graph"in n){const t=o.EntryHandlerContainer.getContainerGraphIndex(n,i,e),s=this.parsingContext.graphContainerTermStack[i];if(r=s?s[t]:null,!r){let o=null;if("@id"in n){const t=await this.getContainerKey(e[i],e,i);null!==t&&(o=await this.resourceToTerm(await this.parsingContext.getContext(e),t))}o||(o=this.dataFactory.blankNode()),this.parsingContext.graphContainerTermStack[i]||(this.parsingContext.graphContainerTermStack[i]={}),r=this.parsingContext.graphContainerTermStack[i][t]=o}}return r}async getPropertiesDepth(e,t){let r=t;for(let n=t-1;n>0;n--)if("number"!=typeof e[n]){const t=await this.unaliasKeyword(e[n],e,n);if("@reverse"===t)return n;if("@nest"!==t)return r;r=n}return r}async getContainerKey(e,t,r){const n=await this.unaliasKeyword(e,t,r);return"@none"===n?null:n}validateReverseInEmbeddedNode(e,t,r){if(r&&t&&!this.parsingContext.rdfstarReverseInEmbedded)throw new n.ErrorCoded(`Illegal reverse property in embedded node in ${e}`,n.ERROR_CODES.INVALID_EMBEDDED_NODE)}emitQuadChecked(e,t,r,i,o,s,a){let c;if(s?(this.validateReverseSubject(i),c=this.dataFactory.quad(i,r,t,o)):c=this.dataFactory.quad(t,r,i,o),a){if("DefaultGraph"!==c.graph.termType&&(c=this.dataFactory.quad(c.subject,c.predicate,c.object)),this.parsingContext.idStack[e-1])throw new n.ErrorCoded("Illegal multiple properties in an embedded node",n.ERROR_CODES.INVALID_EMBEDDED_NODE);this.parsingContext.idStack[e-1]=[c]}else this.parsingContext.emitQuad(e,c);const l=this.parsingContext.annotationsBuffer[e];if(l){for(const t of l)this.emitAnnotation(e,c,t);delete this.parsingContext.annotationsBuffer[e]}}emitAnnotation(e,t,r){let n;r.reverse?(this.validateReverseSubject(r.object),n=this.dataFactory.quad(r.object,r.predicate,t)):n=this.dataFactory.quad(t,r.predicate,r.object),this.parsingContext.emitQuad(e,n);for(const t of r.nestedAnnotations)this.emitAnnotation(e,n,t)}}a.XSD="http://www.w3.org/2001/XMLSchema#",a.XSD_BOOLEAN=a.XSD+"boolean",a.XSD_INTEGER=a.XSD+"integer",a.XSD_DOUBLE=a.XSD+"double",a.RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",t.Util=a},7986:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerIdentifier=void 0,t.ContainerHandlerIdentifier=class{canCombineWithGraph(){return!0}async handle(e,t,r,n,i,o){let s;if(t.emittedStack[o+1]&&t.idStack[o+1])s=t.idStack[o+1][0];else{const e=null!==await r.getContainerKey(n[o],n,o)?await r.resourceToTerm(await t.getContext(n),n[o]):r.dataFactory.blankNode();if(!e)return void(t.emittedStack[o]=!1);s=e,t.idStack[o+1]=[s]}let a=t.idStack[o];a||(a=t.idStack[o]=[]),a.some((e=>e.equals(s)))||a.push(s),await t.handlePendingContainerFlushBuffers()||(t.emittedStack[o]=!1)}}},1977:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerIndex=void 0;const n=r(2395),i=r(6970),o=r(888);t.ContainerHandlerIndex=class{canCombineWithGraph(){return!0}async handle(e,t,r,s,a,c){if(!Array.isArray(a)){const l="@graph"in e,u=await t.getContext(s),d=s[c-1],h=o.Util.getContextValueIndex(u,d);if(h){if(n.Util.isPotentialKeyword(h))throw new n.ErrorCoded(`Keywords can not be used as @index value, got: ${h}`,n.ERROR_CODES.INVALID_TERM_DEFINITION);if("string"!=typeof h)throw new n.ErrorCoded(`@index values must be strings, got: ${h}`,n.ERROR_CODES.INVALID_TERM_DEFINITION);if("object"!=typeof a){if("@id"!==o.Util.getContextValueType(u,d))throw new n.ErrorCoded(`Property-based index containers require nodes as values or strings with @type: @id, but got: ${a}`,n.ERROR_CODES.INVALID_VALUE_OBJECT);const e=r.resourceToTerm(u,a);e&&(t.idStack[c+1]=[e])}const e=r.createVocabOrBaseTerm(u,h);if(e){const n=await r.valueToTerm(u,h,await r.getContainerKey(s[c],s,c),c,s);if(l){const i=await r.getGraphContainerValue(s,c+1);for(const o of n)t.emitQuad(c,r.dataFactory.quad(i,e,o,r.getDefaultGraph()))}else for(const o of n)await i.EntryHandlerPredicate.handlePredicateObject(t,r,s,c+1,e,o,!1,!1,!1)}}const f=l?2:1;await t.newOnValueJob(s.slice(0,s.length-f),a,c-f,!0),await t.handlePendingContainerFlushBuffers()}t.emittedStack[c]=!1}}},3847:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerLanguage=void 0;const n=r(2395);t.ContainerHandlerLanguage=class{canCombineWithGraph(){return!1}async handle(e,t,r,i,o,s){const a=await r.getContainerKey(i[s],i,s);if(Array.isArray(o))o=o.map((e=>({"@value":e,"@language":a})));else{if("string"!=typeof o)throw new n.ErrorCoded(`Got invalid language map value, got '${JSON.stringify(o)}', but expected string`,n.ERROR_CODES.INVALID_LANGUAGE_MAP_VALUE);o={"@value":o,"@language":a}}await t.newOnValueJob(i.slice(0,i.length-1),o,s-1,!0),t.emittedStack[s]=!1}}},7229:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContainerHandlerType=void 0;const n=r(6970),i=r(888);t.ContainerHandlerType=class{canCombineWithGraph(){return!1}async handle(e,t,r,o,s,a){if(!Array.isArray(s)){if("string"==typeof s){const e=await t.getContext(o),n="@vocab"===i.Util.getContextValueType(e,o[a-1])?await r.createVocabOrBaseTerm(e,s):await r.resourceToTerm(e,s);if(n){const e={"@id":"NamedNode"===n.termType?n.value:s};await t.newOnValueJob(o.slice(0,o.length-1),e,a-1,!0),t.idStack[a+1]=[n]}}else{const e=!!t.idStack[a+1];e||delete t.idStack[a],await t.newOnValueJob(o.slice(0,o.length-1),s,a-1,!0),e||(t.idStack[a+1]=t.idStack[a])}const e=await r.getContainerKey(o[a],o,a),c=null!==e?r.createVocabOrBaseTerm(await t.getContext(o),e):null;c&&await n.EntryHandlerPredicate.handlePredicateObject(t,r,o,a+1,r.rdfType,c,!1,!1,!1),await t.handlePendingContainerFlushBuffers()}t.emittedStack[a]=!1}}},9693:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerArrayValue=void 0;const n=r(888),i=r(2395);t.EntryHandlerArrayValue=class{isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return this.test(e,t,null,r,n)}async test(e,t,r,n,i){return"number"==typeof n[i]}async handle(e,t,r,i,o,s){let a=await t.unaliasKeywordParent(i,s);if("@list"===a){let r=null,n=0;for(let e=s-2;e>0;e--){const t=i[e];if("string"==typeof t||"number"==typeof t){n=e,r=t;break}}if(null!==r){const a=await t.valueToTerm(await e.getContext(i),r,o,s,i);for(const r of a)await this.handleListElement(e,t,r,o,s,i.slice(0,n),n);0===a.length&&await this.handleListElement(e,t,null,o,s,i.slice(0,n),n)}}else if("@set"===a)await e.newOnValueJob(i.slice(0,-2),o,s-2,!1);else if(void 0!==a&&"@type"!==a){for(let e=s-1;e>0;e--)if("number"!=typeof i[e]){a=await t.unaliasKeyword(i[e],i,e);break}const r=await e.getContext(i.slice(0,-1));if("@list"in n.Util.getContextValueContainer(r,a)){e.emittedStack[s+1]=!0;const r=await t.valueToTerm(await e.getContext(i),a,o,s,i);for(const n of r)await this.handleListElement(e,t,n,o,s,i.slice(0,-1),s-1);0===r.length&&await this.handleListElement(e,t,null,o,s,i.slice(0,-1),s-1)}else e.shiftStack(s,1),await e.newOnValueJob(i.slice(0,-1),o,s-1,!1),e.contextTree.removeContext(i.slice(0,-1))}}async handleListElement(e,t,r,n,o,s,a){let c=e.listPointerStack[o];if(null!==n&&null!==(await t.unaliasKeywords(n,s,o))["@value"]){if(c&&c.value){const r=t.dataFactory.blankNode();e.emitQuad(o,t.dataFactory.quad(c.value,t.rdfRest,r,t.getDefaultGraph())),c.value=r}else{const e=t.dataFactory.blankNode();c={value:e,listRootDepth:a,listId:e}}r&&e.emitQuad(o,t.dataFactory.quad(c.value,t.rdfFirst,r,t.getDefaultGraph()))}else c||(c={listRootDepth:a,listId:t.rdfNil});e.listPointerStack[o]=c,e.rdfstar&&e.annotationsBuffer[o]&&e.emitError(new i.ErrorCoded("Found an illegal annotation inside a list",i.ERROR_CODES.INVALID_ANNOTATION))}}},4860:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerContainer=void 0;const n=r(7986),i=r(1977),o=r(3847),s=r(7229),a=r(888);class c{static isSimpleGraphContainer(e){return"@graph"in e&&("@set"in e&&2===Object.keys(e).length||1===Object.keys(e).length)}static isComplexGraphContainer(e){return"@graph"in e&&("@set"in e&&Object.keys(e).length>2||!("@set"in e)&&Object.keys(e).length>1)}static getContainerGraphIndex(e,t,r){let n=c.isSimpleGraphContainer(e),i="";for(let e=t;e=0;e--)if("number"!=typeof t[e]){const r=a.Util.getContextValue(o,"@container",t[e],!1);if(r&&c.isSimpleGraphContainer(r))return{containers:r,depth:e+1,fallback:!1};const s=a.Util.getContextValue(o,"@container",t[e-1],!1);if(s){const t="@graph"in s;for(const r in c.CONTAINER_HANDLERS)if(s[r])return t?c.CONTAINER_HANDLERS[r].canCombineWithGraph()?{containers:s,depth:e,fallback:!1}:n:i?n:{containers:s,depth:e,fallback:!1};return n}if(i)return n;i=!0}return n}static async isBufferableContainerHandler(e,t,r){const n=await c.getContainerHandler(e,t,r);return!n.fallback&&!("@graph"in n.containers)}isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return!!await this.test(e,t,null,r,n)}async test(e,t,r,n,i){const o=a.Util.getContextValueContainer(await e.getContext(n,2),n[i-1]);for(const e in c.CONTAINER_HANDLERS)if(o[e])return{containers:o,handler:c.CONTAINER_HANDLERS[e]};return null}async handle(e,t,r,n,i,o,s){return s.handler.handle(s.containers,e,t,n,i,o)}}c.CONTAINER_HANDLERS={"@id":new n.ContainerHandlerIdentifier,"@index":new i.ContainerHandlerIndex,"@language":new o.ContainerHandlerLanguage,"@type":new s.ContainerHandlerType},t.EntryHandlerContainer=c},2386:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerInvalidFallback=void 0,t.EntryHandlerInvalidFallback=class{isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return!1}async test(e,t,r,n,i){return!0}async handle(e,t,r,n,i,o){e.emittedStack[o]=!1}}},6970:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerPredicate=void 0;const n=r(2395),i=r(888);class o{static async handlePredicateObject(e,t,r,i,o,s,a,c,l){const u=await t.getPropertiesDepth(r,i),d=await t.getDepthOffsetGraph(i,r),h=i-d,f=e.idStack[u];if(f&&!l)for(const n of f)if(d>=0){const r=e.idStack[h-1];if(r)for(const e of r)t.emitQuadChecked(i,n,o,s,e,a,c);else a?(t.validateReverseSubject(s),e.getUnidentifiedGraphBufferSafe(h-1).push({subject:s,predicate:o,object:n,isEmbedded:c})):e.getUnidentifiedGraphBufferSafe(h-1).push({subject:n,predicate:o,object:s,isEmbedded:c})}else{const e=await t.getGraphContainerValue(r,u);t.emitQuadChecked(i,n,o,s,e,a,c)}else if(a&&t.validateReverseSubject(s),l){if(e.rdfstar){e.idStack[i]&&e.emitError(new n.ErrorCoded(`Found an illegal @id inside an annotation: ${e.idStack[i][0].value}`,n.ERROR_CODES.INVALID_ANNOTATION));for(let o=0;o=0;e--){const t=c[e];t.depth>u&&(l.nestedAnnotations.push(t),c.splice(e,1))}}}else e.getUnidentifiedValueBufferSafe(u).push({predicate:o,object:s,reverse:a,isEmbedded:c})}isPropertyHandler(){return!0}isStackProcessor(){return!0}async validate(e,t,r,n,o){const s=r[n];if(s){const o=await e.getContext(r);if(!e.jsonLiteralStack[n]&&await t.predicateToTerm(o,r[n]))return"@json"===i.Util.getContextValueType(o,s)&&(e.jsonLiteralStack[n+1]=!0),!0}return!1}async test(e,t,r,n,i){return n[i]}async handle(e,t,r,s,a,c,l){const u=s[c],d=await e.getContext(s),h=await t.predicateToTerm(d,r);if(h){const l=await t.valueToTerm(d,r,a,c,s);if(l.length)for(let f of l){let l=await t.unaliasKeywordParent(s,c);const p=i.Util.isPropertyReverse(d,u,l);let g=0;for(;"@reverse"===l||"number"==typeof l;)"number"==typeof l?g++:c--,l=await t.unaliasKeywordParent(s,c-g);const y=i.Util.isPropertyInEmbeddedNode(l);t.validateReverseInEmbeddedNode(r,p,y);const m=i.Util.isPropertyInAnnotationObject(l);if(a){const o="@list"in i.Util.getContextValueContainer(d,r);if(o||a["@list"]){if((o&&!Array.isArray(a)&&!a["@list"]||a["@list"]&&!Array.isArray(a["@list"]))&&f!==t.rdfNil){const r=t.dataFactory.blankNode();e.emitQuad(c,t.dataFactory.quad(r,t.rdfRest,t.rdfNil,t.getDefaultGraph())),e.emitQuad(c,t.dataFactory.quad(r,t.rdfFirst,f,t.getDefaultGraph())),f=r}if(p&&!e.allowSubjectList)throw new n.ErrorCoded(`Found illegal list value in subject position at ${r}`,n.ERROR_CODES.INVALID_REVERSE_PROPERTY_VALUE)}}await o.handlePredicateObject(e,t,s,c,h,f,p,y,m)}}}}t.EntryHandlerPredicate=o},1548:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeyword=void 0,t.EntryHandlerKeyword=class{constructor(e){this.keyword=e}isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,n,i){return!1}async test(e,t,r,n,i){return r===this.keyword}}},6105:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordAnnotation=void 0;const n=r(1548),i=r(2395);class o extends n.EntryHandlerKeyword{constructor(){super("@annotation")}async handle(e,t,r,n,o,s){("string"==typeof o||"object"==typeof o&&o["@value"])&&e.emitError(new i.ErrorCoded(`Found illegal annotation value: ${JSON.stringify(o)}`,i.ERROR_CODES.INVALID_ANNOTATION))}}t.EntryHandlerKeywordAnnotation=o},3809:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordContext=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@context")}isStackProcessor(){return!1}async handle(e,t,r,i,o,s){e.streamingProfile&&(e.processingStack[s]||e.processingType[s]||void 0!==e.idStack[s])&&e.emitError(new n.ErrorCoded("Found an out-of-order context, while streaming is enabled.(disable `streamingProfile`)",n.ERROR_CODES.INVALID_STREAMING_KEY_ORDER));const a=e.getContext(i),c=e.parseContext(o,(await a).getContextRaw());e.contextTree.setContext(i.slice(0,-1),c),e.emitContext(o),await e.validateContext(await c)}}t.EntryHandlerKeywordContext=o},5998:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordGraph=void 0;const n=r(1548);class i extends n.EntryHandlerKeyword{constructor(){super("@graph")}async handle(e,t,r,n,i,o){e.graphStack[o+1]=!0}}t.EntryHandlerKeywordGraph=i},5517:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordId=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@id")}isStackProcessor(){return!1}async handle(e,t,r,i,o,s){if("string"!=typeof o){if(e.rdfstar&&"object"==typeof o){const t=Object.keys(o);1===t.length&&"@id"===t[0]&&e.emitError(new n.ErrorCoded(`Invalid embedded node without property with @id ${o["@id"]}`,n.ERROR_CODES.INVALID_EMBEDDED_NODE))}else e.emitError(new n.ErrorCoded(`Found illegal @id '${o}'`,n.ERROR_CODES.INVALID_ID_VALUE));return}const a=await t.getPropertiesDepth(i,s);if(void 0!==e.idStack[a]&&(e.idStack[a][0].listHead?e.emitError(new n.ErrorCoded(`Found illegal neighbouring entries next to @list for key: '${i[s-1]}'`,n.ERROR_CODES.INVALID_SET_OR_LIST_OBJECT)):e.emitError(new n.ErrorCoded(`Found duplicate @ids '${e.idStack[a][0].value}' and '${o}'`,n.ERROR_CODES.COLLIDING_KEYWORDS))),e.rdfstar&&e.annotationsBuffer[s])for(const t of e.annotationsBuffer[s])t.depth===s&&e.emitError(new n.ErrorCoded(`Found an illegal @id inside an annotation: ${o}`,n.ERROR_CODES.INVALID_ANNOTATION));e.idStack[a]=t.nullableTermToArray(await t.resourceToTerm(await e.getContext(i),o))}}t.EntryHandlerKeywordId=o},736:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordIncluded=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@included")}async handle(e,t,r,i,o,s){"object"!=typeof o&&e.emitError(new n.ErrorCoded(`Found illegal @included '${o}'`,n.ERROR_CODES.INVALID_INCLUDED_VALUE));const a=await t.unaliasKeywords(o,i,s,await e.getContext(i));"@value"in a&&e.emitError(new n.ErrorCoded(`Found an illegal @included @value node '${JSON.stringify(o)}'`,n.ERROR_CODES.INVALID_INCLUDED_VALUE)),"@list"in a&&e.emitError(new n.ErrorCoded(`Found an illegal @included @list node '${JSON.stringify(o)}'`,n.ERROR_CODES.INVALID_INCLUDED_VALUE)),e.emittedStack[s]=!1}}t.EntryHandlerKeywordIncluded=o},4910:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordNest=void 0;const n=r(2395),i=r(1548);class o extends i.EntryHandlerKeyword{constructor(){super("@nest")}async handle(e,t,r,i,o,s){"object"!=typeof o&&e.emitError(new n.ErrorCoded(`Found invalid @nest entry for '${r}': '${o}'`,n.ERROR_CODES.INVALID_NEST_VALUE)),"@value"in await t.unaliasKeywords(o,i,s,await e.getContext(i))&&e.emitError(new n.ErrorCoded(`Found an invalid @value node for '${r}'`,n.ERROR_CODES.INVALID_NEST_VALUE)),e.emittedStack[s]=!1}}t.EntryHandlerKeywordNest=o},2036:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordType=void 0;const n=r(2395),i=r(888),o=r(6970),s=r(1548);class a extends s.EntryHandlerKeyword{constructor(){super("@type")}isStackProcessor(){return!1}async handle(e,t,r,s,a,c){const l=s[c],u=await e.getContext(s),d=t.rdfType,h=await t.unaliasKeywordParent(s,c),f=i.Util.isPropertyReverse(u,l,h),p=i.Util.isPropertyInEmbeddedNode(h);t.validateReverseInEmbeddedNode(r,f,p);const g=i.Util.isPropertyInAnnotationObject(h),y=Array.isArray(a)?a:[a];for(const r of y){"string"!=typeof r&&e.emitError(new n.ErrorCoded(`Found illegal @type '${r}'`,n.ERROR_CODES.INVALID_TYPE_VALUE));const i=t.createVocabOrBaseTerm(u,r);i&&await o.EntryHandlerPredicate.handlePredicateObject(e,t,s,c,d,i,f,p,g)}let m=Promise.resolve(u),v=!1;for(const t of y.sort()){const r=i.Util.getContextValue(u,"@context",t,null);r&&(v=!0,m=m.then((t=>e.parseContext(r,t.getContextRaw()))))}!e.streamingProfile||!v&&e.streamingProfileAllowOutOfOrderPlainType||!e.processingStack[c]&&!e.idStack[c]||e.emitError(new n.ErrorCoded("Found an out-of-order type-scoped context, while streaming is enabled.(disable `streamingProfile`)",n.ERROR_CODES.INVALID_STREAMING_KEY_ORDER)),v&&(m=m.then((e=>!0!==e.getContextRaw()["@propagate"]?new n.JsonLdContextNormalized(Object.assign(Object.assign({},e.getContextRaw()),{"@propagate":!1,"@__propagateFallback":u.getContextRaw()})):e)),e.contextTree.setContext(s.slice(0,s.length-1),m)),e.processingType[c]=!0}}t.EntryHandlerKeywordType=a},6454:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordUnknownFallback=void 0;const n=r(2395);class i{isPropertyHandler(){return!1}isStackProcessor(){return!0}async validate(e,t,r,i,o){const s=await t.unaliasKeyword(r[i],r,i);return!(!n.Util.isPotentialKeyword(s)||!o&&"@list"===s)}async test(e,t,r,i,o){return n.Util.isPotentialKeyword(r)}async handle(e,t,r,o,s,a){const c=i.VALID_KEYWORDS_TYPES[r];void 0!==c?c&&typeof s!==c.type&&e.emitError(new n.ErrorCoded(`Invalid value type for '${r}' with value '${s}'`,c.errorCode)):e.strictValues&&e.emitError(new Error(`Unknown keyword '${r}' with value '${s}'`)),e.emittedStack[a]=!1}}i.VALID_KEYWORDS_TYPES={"@index":{type:"string",errorCode:n.ERROR_CODES.INVALID_INDEX_VALUE},"@list":null,"@reverse":{type:"object",errorCode:n.ERROR_CODES.INVALID_REVERSE_VALUE},"@set":null,"@value":null},t.EntryHandlerKeywordUnknownFallback=i},3283:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryHandlerKeywordValue=void 0;const n=r(1548);class i extends n.EntryHandlerKeyword{constructor(){super("@value")}async validate(e,t,r,n,i){const o=r[n];return o&&!e.literalStack[n]&&await this.test(e,t,o,r,n)&&(e.literalStack[n]=!0),super.validate(e,t,r,n,i)}async test(e,t,r,n,i){return"@value"===await t.unaliasKeyword(n[i],n.slice(0,n.length-1),i-1,!0)}async handle(e,t,r,n,i,o){e.literalStack[o]=!0,delete e.unidentifiedValuesBuffer[o],delete e.unidentifiedGraphsBuffer[o],e.emittedStack[o]=!1}}t.EntryHandlerKeywordValue=i},2194:function(e,t,r){"use strict";const{SymbolDispose:n}=r(2057),{AbortError:i,codes:o}=r(54),{isNodeStream:s,isWebStream:a,kControllerErrorFunction:c}=r(9232),l=r(3789),{ERR_INVALID_ARG_TYPE:u}=o;let d;e.exports.addAbortSignal=function(t,r){if((e=>{if("object"!=typeof e||!("aborted"in e))throw new u("signal","AbortSignal",e)})(t),!s(r)&&!a(r))throw new u("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=s(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(6745).addAbortListener;const i=d(e,o);l(t,i[n])}return t}},6442:function(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:o,Uint8Array:s}=r(2057),{Buffer:a}=r(8287),{inspect:c}=r(6745);e.exports=class{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;)o(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(eo.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=a.allocUnsafe(e),r=e;let n=this.head,i=0;do{const a=n.data;if(!(e>a.length)){e===a.length?(o(t,a,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(o(t,new s(a.buffer,a.byteOffset,e),r-e),this.head=n,n.data=a.slice(e));break}o(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})}}},769:function(e,t,r){"use strict";const{pipeline:n}=r(5783),i=r(399),{destroyer:o}=r(2295),{isNodeStream:s,isReadable:a,isWritable:c,isWebStream:l,isTransformStream:u,isWritableStream:d,isReadableStream:h}=r(9232),{AbortError:f,codes:{ERR_INVALID_ARG_VALUE:p,ERR_MISSING_ARGS:g}}=r(54),y=r(3789);e.exports=function(...e){if(0===e.length)throw new g("streams");if(1===e.length)return i.from(e[0]);const t=[...e];if("function"==typeof e[0]&&(e[0]=i.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=i.from(e[t])}for(let r=0;r0&&!(c(e[r])||d(e[r])||u(e[r])))throw new p(`streams[${r}]`,t[r],"must be writable")}let r,m,v,b,w;const _=e[0],S=n(e,(function(e){const t=b;b=null,t?t(e):e?w.destroy(e):A||E||w.destroy()})),E=!!(c(_)||d(_)||u(_)),A=!!(a(S)||h(S)||u(S));if(w=new i({writableObjectMode:!(null==_||!_.writableObjectMode),readableObjectMode:!(null==S||!S.readableObjectMode),writable:E,readable:A}),E){if(s(_))w._write=function(e,t,n){_.write(e,t)?n():r=n},w._final=function(e){_.end(),m=e},_.on("drain",(function(){if(r){const e=r;r=null,e()}}));else if(l(_)){const e=(u(_)?_.writable:_).getWriter();w._write=async function(t,r,n){try{await e.ready,e.write(t).catch((()=>{})),n()}catch(e){n(e)}},w._final=async function(t){try{await e.ready,e.close().catch((()=>{})),m=t}catch(e){t(e)}}}const e=u(S)?S.readable:S;y(e,(()=>{if(m){const e=m;m=null,e()}}))}if(A)if(s(S))S.on("readable",(function(){if(v){const e=v;v=null,e()}})),S.on("end",(function(){w.push(null)})),w._read=function(){for(;;){const e=S.read();if(null===e)return void(v=w._read);if(!w.push(e))return}};else if(l(S)){const e=(u(S)?S.readable:S).getReader();w._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!w.push(t))return;if(r)return void w.push(null)}catch{return}}}return w._destroy=function(e,t){e||null===b||(e=new f),v=null,r=null,m=null,null===b?t(e):(b=t,s(S)&&o(S,e))},w}},2295:function(e,t,r){"use strict";const n=r(5606),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:s}=r(54),{Symbol:a}=r(2057),{kIsDestroyed:c,isDestroyed:l,isFinished:u,isServerRequest:d}=r(9232),h=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 g(e,t,r){let i=!1;function o(t){if(i)return;i=!0;const o=e._readableState,s=e._writableState;p(t,s,o),s&&(s.closed=!0),o&&(o.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(y,e,t):n.nextTick(m,e)}try{e._destroy(t||null,o)}catch(t){o(t)}}function y(e,t){v(e,t),m(e)}function m(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 v(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(v,e,t):v(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,s=e._writableState,a=s||i;i&&(i.constructed=!0),s&&(s.constructed=!0),a.destroyed?e.emit(h,r):r?b(e,r,!0):n.nextTick(_,e)}try{e._construct((e=>{n.nextTick(r,e)}))}catch(e){n.nextTick(r,e)}}function _(e){e.emit(f)}function S(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function E(e){e.emit("close")}function A(e,t){e.emit("error",t),n.nextTick(E,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&&!l(e)&&(t||u(e)||(t=new s),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(A,e,t):n.nextTick(E,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?g(this,e,t):this.once(h,(function(r){g(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}},399:function(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:o,ObjectSetPrototypeOf:s}=r(2057);e.exports=l;const a=r(5277),c=r(4461);s(l.prototype,a.prototype),s(l,a);{const e=o(c.prototype);for(let t=0;t{d=!1,e&&v(t,e),h(e)})),l._write=function(e,t,i){r.write(e,t)?i():n=i},l._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()}}))),u&&(p(t,(e=>{u=!1,e&&v(t,e),h(e)})),t.on("readable",(function(){if(a){const e=a;a=null,e()}})),t.on("end",(function(){l.push(null)})),l._read=function(){for(;;){const e=t.read();if(null===e)return void(a=l._read);if(!l.push(e))return}}),l._destroy=function(e,o){e||null===c||(e=new g),a=null,n=null,i=null,null===c?o(e):(c=o,v(r,e),v(t,e))},l}e.exports=function e(t,r){if(d(t))return t;if(l(t))return P({readable:t});if(u(t))return P({writable:t});if(c(t))return P({writable:!1,readable:!1});if(h(t))return P({readable:w.fromWeb(t)});if(f(t))return P({writable:_.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:o,destroy:s}=function(e){let{promise:t,resolve:r}=S();const i=new I,o=i.signal;return{value:e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:s,cb:a}=await e;if(n.nextTick(a),s)return;if(o.aborted)throw new g(void 0,{cause:o.reason});({promise:t,resolve:r}=S()),yield i}}(),{signal: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 E(x,e,{objectMode:!0,write:i,final:o,destroy:s});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=T(c,e,(e=>{if(null!=e)throw new m("nully","body",e)}),(e=>{v(t,e)}));return t=new x({objectMode:!0,readable:!1,write:i,final(e){o((async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}}))},destroy:s})}throw new m("Iterable, AsyncIterable or AsyncFunction",r,e)}if(R(t))return e(t.arrayBuffer());if(a(t))return E(x,t,{objectMode:!0,writable:!1});if(h(null==t?void 0:t.readable)&&f(null==t?void 0:t.writable))return x.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable))return P({readable:null!=t&&t.readable?l(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?u(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 T(i,t,(t=>{null!=t&&e.push(t),e.push(null)}),(t=>{v(e,t)})),e=new x({objectMode:!0,writable:!1,read(){}})}throw new y(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},3789:function(e,t,r){const n=r(5606),{AbortError:i,codes:o}=r(54),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_PREMATURE_CLOSE:a}=o,{kEmptyObject:c,once:l}=r(6745),{validateAbortSignal:u,validateFunction:d,validateObject:h,validateBoolean:f}=r(5432),{Promise:p,PromisePrototypeThen:g,SymbolDispose:y}=r(2057),{isClosed:m,isReadable:v,isReadableNodeStream:b,isReadableStream:w,isReadableFinished:_,isReadableErrored:S,isWritable:E,isWritableNodeStream:A,isWritableStream:R,isWritableFinished:I,isWritableErrored:T,isNodeStream:x,willEmitClose:P,kIsClosedPromise:C}=r(9232);let k;const O=()=>{};function F(e,t,o){var f,p;if(2===arguments.length?(o=t,t=c):null==t?t=c:h(t,"options"),d(o,"callback"),u(t.signal,"options.signal"),o=l(o),w(e)||R(e))return function(e,t,o){let s=!1,a=O;if(t.signal)if(a=()=>{s=!0,o.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(a);else{k=k||r(6745).addAbortListener;const n=k(t.signal,a),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}const c=(...t)=>{s||n.nextTick((()=>o.apply(e,t)))};return g(e[C].promise,c,c),O}(e,t,o);if(!x(e))throw new s("stream",["ReadableStream","WritableStream","Stream"],e);const F=null!==(f=t.readable)&&void 0!==f?f:b(e),N=null!==(p=t.writable)&&void 0!==p?p:A(e),D=e._writableState,L=e._readableState,U=()=>{e.writable||B()};let j=P(e)&&b(e)===F&&A(e)===N,M=I(e,!1);const B=()=>{M=!0,e.destroyed&&(j=!1),(!j||e.readable&&!F)&&(F&&!H||o.call(e))};let H=_(e,!1);const W=()=>{H=!0,e.destroyed&&(j=!1),(!j||e.writable&&!N)&&(N&&!M||o.call(e))},$=t=>{o.call(e,t)};let V=m(e);const K=()=>{V=!0;const t=T(e)||S(e);return t&&"boolean"!=typeof t?o.call(e,t):F&&!H&&b(e,!0)&&!_(e,!1)?o.call(e,new a):!N||M||I(e,!1)?void o.call(e):o.call(e,new a)},J=()=>{V=!0;const t=T(e)||S(e);if(t&&"boolean"!=typeof t)return o.call(e,t);o.call(e)},G=()=>{e.req.on("finish",B)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?N&&!D&&(e.on("end",U),e.on("close",U)):(e.on("complete",B),j||e.on("abort",K),e.req?G():e.on("request",G)),j||"boolean"!=typeof e.aborted||e.on("aborted",K),e.on("end",W),e.on("finish",B),!1!==t.error&&e.on("error",$),e.on("close",K),V?n.nextTick(K):null!=D&&D.errorEmitted||null!=L&&L.errorEmitted?j||n.nextTick(J):(F||j&&!v(e)||!M&&!1!==E(e))&&(N||j&&!E(e)||!H&&!1!==v(e))?L&&e.req&&e.aborted&&n.nextTick(J):n.nextTick(J);const q=()=>{o=O,e.removeListener("aborted",K),e.removeListener("complete",B),e.removeListener("abort",K),e.removeListener("request",G),e.req&&e.req.removeListener("finish",B),e.removeListener("end",U),e.removeListener("close",U),e.removeListener("finish",B),e.removeListener("end",W),e.removeListener("error",$),e.removeListener("close",K)};if(t.signal&&!V){const s=()=>{const r=o;q(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(s);else{k=k||r(6745).addAbortListener;const n=k(t.signal,s),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}}return q}e.exports=F,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=F(e,t,(e=>{n&&o(),e?i(e):r()}))}))}},4181:function(e,t,r){"use strict";const n=r(5606),{PromisePrototypeThen:i,SymbolAsyncIterator:o,SymbolIterator:s}=r(2057),{Buffer:a}=r(8287),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:l}=r(54).codes;e.exports=function(e,t,r){let u,d;if("string"==typeof t||t instanceof a)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[o])d=!0,u=t[o]();else{if(!t||!t[s])throw new c("iterable",["Iterable"],t);d=!1,u=t[s]()}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 u.next():u.next();if(t)h.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw f=!1,new l;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 u.throw;if(t&&r){const{value:t,done:r}=await u.throw(e);if(await t,r)return}if("function"==typeof u.return){const{value:e}=await u.return();await e}}(e),(()=>n.nextTick(t,e)),(r=>n.nextTick(t,r||e)))},h}},9526:function(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(2057),{EventEmitter:o}=r(7007);function s(e){o.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(s.prototype,o.prototype),i(s,o),s.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",l));let s=!1;function c(){s||(s=!0,e.end())}function l(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function u(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",l),r.removeListener("error",u),e.removeListener("error",u),r.removeListener("end",d),r.removeListener("close",d),e.removeListener("close",d)}return a(r,"error",u),a(e,"error",u),r.on("end",d),r.on("close",d),e.on("close",d),e.emit("pipe",r),e},e.exports={Stream:s,prependListener:a}},2892:function(e,t,r){"use strict";const n=globalThis.AbortController||r(5568).AbortController,{codes:{ERR_INVALID_ARG_VALUE:i,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:s,ERR_OUT_OF_RANGE:a},AbortError:c}=r(54),{validateAbortSignal:l,validateInteger:u,validateObject:d}=r(5432),h=r(2057).Symbol("kWeak"),f=r(2057).Symbol("kResistStopPropagation"),{finished:p}=r(3789),g=r(769),{addAbortSignalNoValidate:y}=r(2194),{isWritable:m,isNodeStream:v}=r(9232),{deprecate:b}=r(6745),{ArrayPrototypePush:w,Boolean:_,MathFloor:S,Number:E,NumberIsNaN:A,Promise:R,PromiseReject:I,PromiseResolve:T,PromisePrototypeThen:x,Symbol:P}=r(2057),C=P("kEmpty"),k=P("kEof");function O(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal");let n=1;null!=(null==t?void 0:t.concurrency)&&(n=S(t.concurrency));let i=n-1;return null!=(null==t?void 0:t.highWaterMark)&&(i=S(t.highWaterMark)),u(n,"options.concurrency",1),u(i,"options.highWaterMark",0),i+=n,async function*(){const o=r(6745).AbortSignalAny([null==t?void 0:t.signal].filter(_)),s=this,a=[],l={signal:o};let u,d,h=!1,f=0;function p(){h=!0,g()}function g(){f-=1,y()}function y(){d&&!h&&f=i||f>=n)&&await new R((e=>{d=e}))}a.push(k)}catch(e){const t=I(e);x(t,g,p),a.push(t)}finally{h=!0,u&&(u(),u=null)}}();try{for(;;){for(;a.length>0;){const e=await a[0];if(e===k)return;if(o.aborted)throw new c;e!==C&&(yield e),a.shift(),y()}await new R((e=>{u=e}))}}finally{h=!0,d&&(d(),d=null)}}.call(this)}async function F(e,t=void 0){for await(const r of N.call(this,e,t))return!0;return!1}function N(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return O.call(this,(async function(t,r){return await e(t,r)?t:C}),t)}class D extends s{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function L(e){if(e=E(e),A(e))return 0;if(e<0)throw new a("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:b((function(e=void 0){return null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(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 c({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&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;e--<=0&&(yield r)}}.call(this)},filter:N,flatMap:function(e,t){const r=O.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:O,take:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),v(e)&&!m(e))throw new i("stream",e,"must be writable");const r=g(this,e);return null!=t&&t.signal&&y(t.signal,r),r}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new o("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 o("fn",["Function","AsyncFunction"],e);for await(const r of O.call(this,(async function(t,r){return await e(t,r),C}),t));},reduce:async function(e,t,r){var i;if("function"!=typeof e)throw new o("reducer",["Function","AsyncFunction"],e);null!=r&&d(r,"options"),null!=(null==r?void 0:r.signal)&&l(r.signal,"options.signal");let s=arguments.length>1;if(null!=r&&null!==(i=r.signal)&&void 0!==i&&i.aborted){const e=new c(void 0,{cause:r.signal.reason});throw this.once("error",(()=>{})),await p(this.destroy(e)),e}const a=new n,u=a.signal;if(null!=r&&r.signal){const e={once:!0,[h]:this,[f]:!0};r.signal.addEventListener("abort",(()=>a.abort()),e)}let g=!1;try{for await(const n of this){var y;if(g=!0,null!=r&&null!==(y=r.signal)&&void 0!==y&&y.aborted)throw new c;s?t=await e(t,n,{signal:u}):(t=n,s=!0)}if(!g&&!s)throw new D}finally{a.abort()}return t},toArray:async function(e){null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(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 c(void 0,{cause:e.signal.reason});w(t,n)}return t},some:F,find:async function(e,t){for await(const r of N.call(this,e,t))return r}}},2163:function(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(2057);e.exports=o;const i=r(97);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)}},5783:function(e,t,r){const n=r(5606),{ArrayIsArray:i,Promise:o,SymbolAsyncIterator:s,SymbolDispose:a}=r(2057),c=r(3789),{once:l}=r(6745),u=r(2295),d=r(399),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:p,ERR_MISSING_ARGS:g,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:m},AbortError:v}=r(54),{validateFunction:b,validateAbortSignal:w}=r(5432),{isIterable:_,isReadable:S,isReadableNodeStream:E,isNodeStream:A,isTransformStream:R,isWebStream:I,isReadableStream:T,isReadableFinished:x}=r(9232),P=globalThis.AbortController||r(5568).AbortController;let C,k,O;function F(e,t,r){let n=!1;return e.on("close",(()=>{n=!0})),{destroy:t=>{n||(n=!0,u.destroyer(e,t||new y("pipe")))},cleanup:c(e,{readable:t,writable:r},(e=>{n=!e}))}}function N(e){if(_(e))return e;if(E(e))return async function*(e){k||(k=r(5277)),yield*k.prototype[s].call(e)}(e);throw new f("val",["Readable","Iterable","AsyncIterable"],e)}async function D(e,t,r,{end:n}){let i,s=null;const a=e=>{if(e&&(i=e),s){const e=s;s=null,e()}},l=()=>new o(((e,t)=>{i?t(i):s=()=>{i?t(i):e()}}));t.on("drain",a);const u=c(t,{readable:!1},a);try{t.writableNeedDrain&&await l();for await(const r of e)t.write(r)||await l();n&&(t.end(),await l()),r()}catch(e){r(i!==e?h(i,e):e)}finally{u(),t.off("drain",a)}}async function L(e,t,r,{end:n}){R(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 U(e,t,o){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new g("streams");const s=new P,c=s.signal,l=null==o?void 0:o.signal,u=[];function h(){B(new v)}let y,m,b;w(l,"options.signal"),O=O||r(6745).addAbortListener,l&&(y=O(l,h));const x=[];let k,U=0;function M(e){B(e,0==--U)}function B(e,r){var i;if(!e||m&&"ERR_STREAM_PREMATURE_CLOSE"!==m.code||(m=e),m||r){for(;x.length;)x.shift()(m);null===(i=y)||void 0===i||i[a](),s.abort(),r&&(m||u.forEach((e=>e())),n.nextTick(t,m,b))}}for(let V=0;V0,q=J||!1!==(null==o?void 0:o.end),z=V===e.length-1;if(A(K)){if(q){const{destroy:Y,cleanup:Q}=F(K,J,G);x.push(Y),S(K)&&z&&u.push(Q)}function H(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&M(e)}K.on("error",H),S(K)&&z&&u.push((()=>{K.removeListener("error",H)}))}if(0===V)if("function"==typeof K){if(k=K({signal:c}),!_(k))throw new p("Iterable, AsyncIterable or Stream","source",k)}else k=_(K)||E(K)||R(K)?K:d.from(K);else if("function"==typeof K){var W;if(k=R(k)?N(null===(W=k)||void 0===W?void 0:W.readable):N(k),k=K(k,{signal:c}),J){if(!_(k,!0))throw new p("AsyncIterable",`transform[${V-1}]`,k)}else{var $;C||(C=r(2163));const X=new C({objectMode:!0}),Z=null===($=k)||void 0===$?void 0:$.then;if("function"==typeof Z)U++,Z.call(k,(e=>{b=e,null!=e&&X.write(e),q&&X.end(),n.nextTick(M)}),(e=>{X.destroy(e),n.nextTick(M,e)}));else if(_(k,!0))U++,D(k,X,M,{end:q});else{if(!T(k)&&!R(k))throw new p("AsyncIterable or Promise","destination",k);{const re=k.readable||k;U++,D(re,X,M,{end:q})}}k=X;const{destroy:ee,cleanup:te}=F(k,!1,!0);x.push(ee),z&&u.push(te)}}else if(A(K)){if(E(k)){U+=2;const ne=j(k,K,M,{end:q});S(K)&&z&&u.push(ne)}else if(R(k)||T(k)){const ie=k.readable||k;U++,D(ie,K,M,{end:q})}else{if(!_(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,D(k,K,M,{end:q})}k=K}else if(I(K)){if(E(k))U++,L(N(k),K,M,{end:q});else if(T(k)||_(k))U++,L(k,K,M,{end:q});else{if(!R(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,L(k.readable,K,M,{end:q})}k=K}else k=d.from(K)}return(null!=c&&c.aborted||null!=l&&l.aborted)&&n.nextTick(h),k}function j(e,t,r,{end:i}){let o=!1;if(t.on("close",(()=>{o||r(new m)})),e.pipe(t,{end:!1}),i){function s(){o=!0,t.end()}x(e)?n.nextTick(s):e.once("end",s)}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:U,pipeline:function(...e){return U(e,l(function(e){return b(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},5277:function(e,t,r){const n=r(5606),{ArrayPrototypeIndexOf:i,NumberIsInteger:o,NumberIsNaN:s,NumberParseInt:a,ObjectDefineProperties:c,ObjectKeys:l,ObjectSetPrototypeOf:u,Promise:d,SafeSet:h,SymbolAsyncDispose:f,SymbolAsyncIterator:p,Symbol:g}=r(2057);e.exports=G,G.ReadableState=J;const{EventEmitter:y}=r(7007),{Stream:m,prependListener:v}=r(9526),{Buffer:b}=r(8287),{addAbortSignal:w}=r(2194),_=r(3789);let S=r(6745).debuglog("stream",(e=>{S=e}));const E=r(6442),A=r(2295),{getHighWaterMark:R,getDefaultHighWaterMark:I}=r(936),{aggregateTwoErrors:T,codes:{ERR_INVALID_ARG_TYPE:x,ERR_METHOD_NOT_IMPLEMENTED:P,ERR_OUT_OF_RANGE:C,ERR_STREAM_PUSH_AFTER_EOF:k,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:O},AbortError:F}=r(54),{validateObject:N}=r(5432),D=g("kPaused"),{StringDecoder:L}=r(704),U=r(4181);u(G.prototype,m.prototype),u(G,m);const j=()=>{},{errorOrDestroy:M}=A,B=1,H=16,W=32,$=2048,V=4096;function K(e){return{enumerable:!1,get(){return!!(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function J(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(399)),this.state=$|V|H|W,e&&e.objectMode&&(this.state|=B),n&&e&&e.readableObjectMode&&(this.state|=B),this.highWaterMark=e?R(this,e,"readableHighWaterMark",n):I(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[D]=null,e&&!1===e.emitClose&&(this.state&=~$),e&&!1===e.autoDestroy&&(this.state&=~V),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 G(e){if(!(this instanceof G))return new G(e);const t=this instanceof r(399);this._readableState=new J(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)),m.call(this,e),A.construct(this,(()=>{this._readableState.needReadable&&Z(this,this._readableState)}))}function q(e,t,r,n){S("readableAddChunk",t);const i=e._readableState;let o;if(i.state&B||("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="":m._isUint8Array(t)?(t=m._uint8ArrayToBuffer(t),r=""):null!=t&&(o=new x("chunk",["string","Buffer","Uint8Array"],t))),o)M(e,o);else if(null===t)i.state&=-9,function(e,t){if(S("onEofChunk"),!t.ended){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?Q(e):(t.needReadable=!1,t.emittedReadable=!0,X(e))}}(e,i);else if(i.state&B||t&&t.length>0)if(n)if(4&i.state)M(e,new O);else{if(i.destroyed||i.errored)return!1;z(e,i,t,!0)}else if(i.ended)M(e,new k);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?z(e,i,t,!1):Z(e,i)):z(e,i,t,!1)}else n||(i.state&=-9,Z(e,i));return!i.ended&&(i.length0?(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&&Q(e)),Z(e,t)}function Y(e,t){return e<=0||0===t.length&&t.ended?0:t.state&B?1:s(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function Q(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(X,e))}function X(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,ie(e)}function Z(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(ee,e,t))}function ee(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!1===t[D]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function re(e){S("readable nexttick read 0"),e.read(0)}function ne(e,t){S("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),ie(e),t.flowing&&!t.reading&&e.read(0)}function ie(e){const t=e._readableState;for(S("flow",t.flowing);t.flowing&&null!==e.read(););}function oe(e,t){"function"!=typeof e.read&&(e=G.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=j;function i(t){this===e?(n(),n=j):n=t}e.on("readable",i);const o=_(e,{writable:!1},(e=>{r=e?T(r,e):null,n(),n=j}));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=T(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),o()):A.destroyer(e,null)}}(e,t);return r.stream=e,r}function se(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 ae(e){const t=e._readableState;S("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(ce,t,e))}function ce(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(le,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function le(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let ue;function de(){return void 0===ue&&(ue={}),ue}c(J.prototype,{objectMode:K(B),ended:K(2),endEmitted:K(4),reading:K(8),constructed:K(H),sync:K(W),needReadable:K(64),emittedReadable:K(128),readableListening:K(256),resumeScheduled:K(512),errorEmitted:K(1024),emitClose:K($),autoDestroy:K(V),destroyed:K(8192),closed:K(16384),closeEmitted:K(32768),multiAwaitDrain:K(65536),readingMore:K(1<<17),dataEmitted:K(1<<18)}),G.prototype.destroy=A.destroy,G.prototype._undestroy=A.undestroy,G.prototype._destroy=function(e,t){t(e)},G.prototype[y.captureRejectionSymbol]=function(e){this.destroy(e)},G.prototype[f]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new F,this.destroy(e)),new d(((t,r)=>_(this,(n=>n&&n!==e?r(n):t(null)))))},G.prototype.push=function(e,t){return q(this,e,t,!1)},G.prototype.unshift=function(e,t){return q(this,e,t,!0)},G.prototype.isPaused=function(){const e=this._readableState;return!0===e[D]||!1===e.flowing},G.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},G.prototype.read=function(e){S("read",e),void 0===e?e=NaN:o(e)||(e=a(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new C("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?ae(this):Q(this),null;if(0===(e=Y(e,t))&&t.ended)return 0===t.length&&ae(this),null;let n,i=!!(64&t.state);if(S("need readable",i),(0===t.length||t.length-e0?se(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&&ae(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},G.prototype._read=function(e){throw new P("_read()")},G.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?g:s;function s(){S("onend"),e.end()}let a;i.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",(function t(n,o){S("onunpipe"),n===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,S("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),a&&e.removeListener("drain",a),e.removeListener("error",d),e.removeListener("unpipe",t),r.removeListener("end",s),r.removeListener("end",g),r.removeListener("data",u),c=!0,a&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&a())}));let c=!1;function l(){c||(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()),a||(a=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",a))}function u(t){S("ondata");const r=e.write(t);S("dest.write",r),!1===r&&l()}function d(t){if(S("onerror",t),g(),e.removeListener("error",d),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?M(e,t):e.emit("error",t)}}function f(){e.removeListener("finish",p),g()}function p(){S("onfinish"),e.removeListener("close",f),g()}function g(){S("unpipe"),r.unpipe(e)}return r.on("data",u),v(e,"error",d),e.once("close",f),e.once("finish",p),e.emit("pipe",r),!0===e.writableNeedDrain?l():i.flowing||(S("pipe resume"),r.resume()),e},G.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;t0,!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?Q(this):i.reading||n.nextTick(re,this))),r},G.prototype.addListener=G.prototype.on,G.prototype.removeListener=function(e,t){const r=m.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(te,this),r},G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=function(e){const t=m.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(te,this),t},G.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(ne,e,t))}(this,e)),e[D]=!1,this},G.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},G.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=l(e);for(let t=1;t{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())}))}function d(){this._final!==u&&u.call(this)}l.prototype._final=u,l.prototype._transform=function(e,t,r){throw new o("_transform()")},l.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{const e=this._writableState;e.writing||W(this,e),V(this,e)}))}function D(e,t,r,i){const o=e._writableState;if("function"==typeof r)i=r,r=o.defaultEncoding;else{if(r){if("buffer"!==r&&!g.isEncoding(r))throw new x(r)}else r=o.defaultEncoding;"function"!=typeof i&&(i=C)}if(null===t)throw new I;if(!o.objectMode)if("string"==typeof t)!1!==o.decodeStrings&&(t=g.from(t,r),r="buffer");else if(t instanceof g)r="buffer";else{if(!p._isUint8Array(t))throw new w("chunk",["string","Buffer","Uint8Array"],t);t=p._uint8ArrayToBuffer(t),r="buffer"}let s;return o.ending?s=new T:o.destroyed&&(s=new A("write")),s?(n.nextTick(i,s),P(e,s,!0),s):(o.pendingcb++,function(e,t,r,n,i){const o=t.objectMode?1:r.length;t.length+=o;const s=t.lengthr.bufferedIndex&&W(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(M,r.afterWriteTickInfo)):B(e,r,1,o))):P(e,new S)}function M({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,B(e,t,r,n)}function B(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&&H(t),V(e,t)}function H(e){if(e.writing)return;for(let r=e.bufferedIndex;r1&&e._writev){t.pendingcb-=s-1;const n=t.allNoop?C:e=>{for(let t=a;t256?(r.splice(0,a),t.bufferedIndex=0):t.bufferedIndex=a}t.bufferProcessing=!1}function $(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 V(e,t,r){$(t)&&(function(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)P(e,null!=i?i:S());else if(r=!0,t.pendingcb--,i){const r=t[k].splice(0);for(let e=0;e{$(t)?K(e,t):t.pendingcb--}),e,t)):$(t)&&(t.pendingcb++,K(e,t))))}function K(e,t){t.pendingcb--,t.finished=!0;const r=t[k].splice(0);for(let e=0;e{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),P=m(((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),C=m(((e,t,r=!1)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);const n=r?1:0,i=4294967295;if(ei)throw new _(t,`>= ${n} && <= ${i}`,e)}));function k(e,t){if("string"!=typeof e)throw new b(t,"string",e)}const O=m(((e,t,r)=>{if(!i(r,e)){const n=o(s(r,(e=>"string"==typeof e?`'${e}'`:p(e))),", ");throw new w(t,e,"must be one of: "+n)}}));function F(e,t){if("boolean"!=typeof e)throw new b(t,"boolean",e)}function N(e,t,r){return null!=e&&h(e,t)?e[t]:r}const D=m(((e,t,r=null)=>{const i=N(r,"allowArray",!1),o=N(r,"allowFunction",!1);if(!N(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!o||"function"!=typeof e))throw new b(t,"Object",e)})),L=m(((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new b(t,"a dictionary",e)})),U=m(((e,t,r=0)=>{if(!n(e))throw new b(t,"Array",e);if(e.length{if(!R(e))throw new b(t,["Buffer","TypedArray","DataView"],e)})),M=m(((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new b(t,"AbortSignal",e)})),B=m(((e,t)=>{if("function"!=typeof e)throw new b(t,"Function",e)})),H=m(((e,t)=>{if("function"!=typeof e||A(e))throw new b(t,"Function",e)})),W=m(((e,t)=>{if(void 0!==e)throw new b(t,"undefined",e)})),$=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function V(e,t){if(void 0===e||!f($,e))throw new w(t,e,'must be an array or string of format "; rel=preload; as=style"')}e.exports={isInt32:function(e){return e===(0|e)},isUint32:function(e){return e===e>>>0},parseFileMode:function(e,t,r){if(void 0===e&&(e=r),"string"==typeof e){if(null===f(T,e))throw new w(t,e,"must be a 32-bit unsigned integer or an octal string");e=d(e,8)}return C(e,t),e},validateArray:U,validateStringArray:function(e,t){U(e,t);for(let r=0;rn||(null!=r||null!=n)&&c(e))throw new _(t,`${null!=r?`>= ${r}`:""}${null!=r&&null!=n?" && ":""}${null!=n?`<= ${n}`:""}`,e)},validateObject:D,validateOneOf:O,validatePlainFunction:H,validatePort:function(e,t="Port",r=!0){if("number"!=typeof e&&"string"!=typeof e||"string"==typeof e&&0===y(e).length||+e!=+e>>>0||e>65535||0===e&&!r)throw new v(t,e,r);return 0|e},validateSignalName:function(e,t="signal"){if(k(e,t),void 0===I[e]){if(void 0!==I[g(e)])throw new S(e+" (signals must use all capital letters)");throw new S(e)}},validateString:k,validateUint32:C,validateUndefined:W,validateUnion:function(e,t,r){if(!i(r,e))throw new b(t,`('${o(r,"|")}')`,e)},validateAbortSignal:M,validateLinkHeaderValue:function(e){if("string"==typeof e)return V(e,"hints"),e;if(n(e)){const t=e.length;let r="";if(0===t)return r;for(let n=0;n; rel=preload; as=style"')}}},2225:function(e,t,r){"use strict";const n=r(6897),i=r(7698),o=n.Readable.destroy;e.exports=n.Readable,e.exports._uint8ArrayToBuffer=n._uint8ArrayToBuffer,e.exports._isUint8Array=n._isUint8Array,e.exports.isDisturbed=n.isDisturbed,e.exports.isErrored=n.isErrored,e.exports.isReadable=n.isReadable,e.exports.Readable=n.Readable,e.exports.Writable=n.Writable,e.exports.Duplex=n.Duplex,e.exports.Transform=n.Transform,e.exports.PassThrough=n.PassThrough,e.exports.addAbortSignal=n.addAbortSignal,e.exports.finished=n.finished,e.exports.destroy=n.destroy,e.exports.destroy=o,e.exports.pipeline=n.pipeline,e.exports.compose=n.compose,Object.defineProperty(n,"promises",{configurable:!0,enumerable:!0,get(){return i}}),e.exports.Stream=n.Stream,e.exports.default=e.exports},54:function(e,t,r){"use strict";const{format:n,inspect:i,AggregateError:o}=r(6745),s=globalThis.AggregateError||o,a=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,u={};function d(e,t){if(!e)throw new u.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 i 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(i.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}}),i.prototype.code=e,i.prototype[a]=!0,u[e]=i}function p(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class g extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new u.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=[],s=[],a=[];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()):l.test(e)?s.push(e):(d("object"!==e,'The value "object" should be written as "Object"'),a.push(e));if(s.length>0){const e=o.indexOf("object");-1!==e&&(o.splice(o,e,1),s.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}`}}(s.length>0||a.length>0)&&(n+=" or ")}if(s.length>0){switch(s.length){case 1:n+=`an instance of ${s[0]}`;break;case 2:n+=`an instance of ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`an instance of ${s.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 u;null!==(u=r.constructor)&&void 0!==u&&u.name?n+=`. Received an instance of ${r.constructor.name}`: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);return n.length>128&&(n=n.slice(0,128)+"..."),`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;return d(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32?n=h(String(r)):"bigint"==typeof r?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=h(n)),n+="n"):n=i(r),`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:g,aggregateTwoErrors:p((function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new s([t,e],t.message);return r.code=t.code,r}return e||t})),hideStackFrames:p,codes:u}},2057:function(e){"use strict";e.exports={ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error:Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number: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){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise:Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String:String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol: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){return e.set(t,r)},Boolean:Boolean,Uint8Array:Uint8Array}},6745:function(e,t,r){"use strict";const n=r(8287),{kResistStopPropagation:i,SymbolDispose:o}=r(2057),s=globalThis.AbortSignal||r(5568).AbortSignal,a=globalThis.AbortController||r(5568).AbortController,c=Object.getPrototypeOf((async function(){})).constructor,l=globalThis.Blob||n.Blob,u=void 0!==l?function(e){return e instanceof l}:function(e){return!1},d=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new ERR_INVALID_ARG_TYPE(t,"AbortSignal",e)};class h 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=r,t=n})),resolve:e,reject:t}},promisify(e){return new Promise(((t,r)=>{e(((e,...n)=>e?r(e):t(...n)))}))},debuglog(){return function(){}},format(e,...t){return e.replace(/%([sdifj])/g,(function(...[e,r]){const n=t.shift();return"f"===r?n.toFixed(6):"j"===r?JSON.stringify(n):"s"===r&&"object"==typeof n?`${n.constructor!==Object?n.constructor.name:""} {}`.trim():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"{}"}},types:{isAsyncFunction(e){return e instanceof c},isArrayBufferView(e){return ArrayBuffer.isView(e)}},isBlob:u,deprecate(e,t){return e},addAbortListener:r(7007).addAbortListener||function(e,t){if(void 0===e)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);let r;return d(e,"signal"),(e=>{if("function"!=typeof e)throw new ERR_INVALID_ARG_TYPE("listener","Function",e)})(t),e.aborted?queueMicrotask((()=>t())):(e.addEventListener("abort",t,{__proto__:null,once:!0,[i]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[o](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:s.any||function(e){if(1===e.length)return e[0];const t=new a,r=()=>t.abort();return e.forEach((e=>{d(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")},6897:function(e,t,r){const{Buffer:n}=r(8287),{ObjectDefineProperty:i,ObjectKeys:o,ReflectApply:s}=r(2057),{promisify:{custom:a}}=r(6745),{streamReturningOperators:c,promiseReturningOperators:l}=r(2892),{codes:{ERR_ILLEGAL_CONSTRUCTOR:u}}=r(54),d=r(769),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:f}=r(936),{pipeline:p}=r(5783),{destroyer:g}=r(2295),y=r(3789),m=r(7698),v=r(9232),b=e.exports=r(9526).Stream;b.isDestroyed=v.isDestroyed,b.isDisturbed=v.isDisturbed,b.isErrored=v.isErrored,b.isReadable=v.isReadable,b.isWritable=v.isWritable,b.Readable=r(5277);for(const S of o(c)){const E=c[S];function w(...e){if(new.target)throw u();return b.Readable.from(s(E,this,e))}i(w,"name",{__proto__:null,value:E.name}),i(w,"length",{__proto__:null,value:E.length}),i(b.Readable.prototype,S,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}for(const A of o(l)){const R=l[A];function w(...e){if(new.target)throw u();return s(R,this,e)}i(w,"name",{__proto__:null,value:R.name}),i(w,"length",{__proto__:null,value:R.length}),i(b.Readable.prototype,A,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}b.Writable=r(4461),b.Duplex=r(399),b.Transform=r(97),b.PassThrough=r(2163),b.pipeline=p;const{addAbortSignal:_}=r(2194);b.addAbortSignal=_,b.finished=y,b.destroy=g,b.compose=d,b.setDefaultHighWaterMark=h,b.getDefaultHighWaterMark=f,i(b,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return m}}),i(p,a,{__proto__:null,enumerable:!0,get(){return m.pipeline}}),i(y,a,{__proto__:null,enumerable:!0,get(){return m.finished}}),b.Stream=b,b._isUint8Array=function(e){return e instanceof Uint8Array},b._uint8ArrayToBuffer=function(e){return n.from(e.buffer,e.byteOffset,e.byteLength)}},7698:function(e,t,r){"use strict";const{ArrayPrototypePop:n,Promise:i}=r(2057),{isIterable:o,isNodeStream:s,isWebStream:a}=r(9232),{pipelineImpl:c}=r(5783),{finished:l}=r(3789);r(6897),e.exports={finished:l,pipeline:function(...e){return new i(((t,r)=>{let i,l;const u=e[e.length-1];if(u&&"object"==typeof u&&!s(u)&&!o(u)&&!a(u)){const t=n(e);i=t.signal,l=t.end}c(e,((e,n)=>{e?r(e):t(n)}),{signal:i,end:l})}))}}},8572:function(e,t,r){var n=r(8287),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.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},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},704:function(e,t,r){"use strict";var n=r(8572).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=l,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=u,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 s(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 l(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 u(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=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):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}},810:function(e,t,r){"use strict";const{SymbolDispose:n}=r(4641),{AbortError:i,codes:o}=r(8526),{isNodeStream:s,isWebStream:a,kControllerErrorFunction:c}=r(136),l=r(9365),{ERR_INVALID_ARG_TYPE:u}=o;let d;e.exports.addAbortSignal=function(t,r){if((e=>{if("object"!=typeof e||!("aborted"in e))throw new u("signal","AbortSignal",e)})(t),!s(r)&&!a(r))throw new u("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=s(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(6017).addAbortListener;const i=d(e,o);l(t,i[n])}return t}},5586:function(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:o,Uint8Array:s}=r(4641),{Buffer:a}=r(8287),{inspect:c}=r(6017);e.exports=class{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;)o(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(eo.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=a.allocUnsafe(e),r=e;let n=this.head,i=0;do{const a=n.data;if(!(e>a.length)){e===a.length?(o(t,a,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(o(t,new s(a.buffer,a.byteOffset,e),r-e),this.head=n,n.data=a.slice(e));break}o(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})}}},8489:function(e,t,r){"use strict";const{pipeline:n}=r(8431),i=r(3559),{destroyer:o}=r(7647),{isNodeStream:s,isReadable:a,isWritable:c,isWebStream:l,isTransformStream:u,isWritableStream:d,isReadableStream:h}=r(136),{AbortError:f,codes:{ERR_INVALID_ARG_VALUE:p,ERR_MISSING_ARGS:g}}=r(8526),y=r(9365);e.exports=function(...e){if(0===e.length)throw new g("streams");if(1===e.length)return i.from(e[0]);const t=[...e];if("function"==typeof e[0]&&(e[0]=i.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=i.from(e[t])}for(let r=0;r0&&!(c(e[r])||d(e[r])||u(e[r])))throw new p(`streams[${r}]`,t[r],"must be writable")}let r,m,v,b,w;const _=e[0],S=n(e,(function(e){const t=b;b=null,t?t(e):e?w.destroy(e):A||E||w.destroy()})),E=!!(c(_)||d(_)||u(_)),A=!!(a(S)||h(S)||u(S));if(w=new i({writableObjectMode:!(null==_||!_.writableObjectMode),readableObjectMode:!(null==S||!S.readableObjectMode),writable:E,readable:A}),E){if(s(_))w._write=function(e,t,n){_.write(e,t)?n():r=n},w._final=function(e){_.end(),m=e},_.on("drain",(function(){if(r){const e=r;r=null,e()}}));else if(l(_)){const e=(u(_)?_.writable:_).getWriter();w._write=async function(t,r,n){try{await e.ready,e.write(t).catch((()=>{})),n()}catch(e){n(e)}},w._final=async function(t){try{await e.ready,e.close().catch((()=>{})),m=t}catch(e){t(e)}}}const e=u(S)?S.readable:S;y(e,(()=>{if(m){const e=m;m=null,e()}}))}if(A)if(s(S))S.on("readable",(function(){if(v){const e=v;v=null,e()}})),S.on("end",(function(){w.push(null)})),w._read=function(){for(;;){const e=S.read();if(null===e)return void(v=w._read);if(!w.push(e))return}};else if(l(S)){const e=(u(S)?S.readable:S).getReader();w._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!w.push(t))return;if(r)return void w.push(null)}catch{return}}}return w._destroy=function(e,t){e||null===b||(e=new f),v=null,r=null,m=null,null===b?t(e):(b=t,s(S)&&o(S,e))},w}},7647:function(e,t,r){"use strict";const n=r(5606),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:s}=r(8526),{Symbol:a}=r(4641),{kIsDestroyed:c,isDestroyed:l,isFinished:u,isServerRequest:d}=r(136),h=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 g(e,t,r){let i=!1;function o(t){if(i)return;i=!0;const o=e._readableState,s=e._writableState;p(t,s,o),s&&(s.closed=!0),o&&(o.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(y,e,t):n.nextTick(m,e)}try{e._destroy(t||null,o)}catch(t){o(t)}}function y(e,t){v(e,t),m(e)}function m(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 v(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(v,e,t):v(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,s=e._writableState,a=s||i;i&&(i.constructed=!0),s&&(s.constructed=!0),a.destroyed?e.emit(h,r):r?b(e,r,!0):n.nextTick(_,e)}try{e._construct((e=>{n.nextTick(r,e)}))}catch(e){n.nextTick(r,e)}}function _(e){e.emit(f)}function S(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function E(e){e.emit("close")}function A(e,t){e.emit("error",t),n.nextTick(E,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&&!l(e)&&(t||u(e)||(t=new s),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(A,e,t):n.nextTick(E,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?g(this,e,t):this.once(h,(function(r){g(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}},3559:function(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:o,ObjectSetPrototypeOf:s}=r(4641);e.exports=l;const a=r(3125),c=r(7221);s(l.prototype,a.prototype),s(l,a);{const e=o(c.prototype);for(let t=0;t{d=!1,e&&v(t,e),h(e)})),l._write=function(e,t,i){r.write(e,t)?i():n=i},l._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()}}))),u&&(p(t,(e=>{u=!1,e&&v(t,e),h(e)})),t.on("readable",(function(){if(a){const e=a;a=null,e()}})),t.on("end",(function(){l.push(null)})),l._read=function(){for(;;){const e=t.read();if(null===e)return void(a=l._read);if(!l.push(e))return}}),l._destroy=function(e,o){e||null===c||(e=new g),a=null,n=null,i=null,null===c?o(e):(c=o,v(r,e),v(t,e))},l}e.exports=function e(t,r){if(d(t))return t;if(l(t))return P({readable:t});if(u(t))return P({writable:t});if(c(t))return P({writable:!1,readable:!1});if(h(t))return P({readable:w.fromWeb(t)});if(f(t))return P({writable:_.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:o,destroy:s}=function(e){let{promise:t,resolve:r}=S();const i=new I,o=i.signal;return{value:e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:s,cb:a}=await e;if(n.nextTick(a),s)return;if(o.aborted)throw new g(void 0,{cause:o.reason});({promise:t,resolve:r}=S()),yield i}}(),{signal: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 E(x,e,{objectMode:!0,write:i,final:o,destroy:s});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=T(c,e,(e=>{if(null!=e)throw new m("nully","body",e)}),(e=>{v(t,e)}));return t=new x({objectMode:!0,readable:!1,write:i,final(e){o((async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}}))},destroy:s})}throw new m("Iterable, AsyncIterable or AsyncFunction",r,e)}if(R(t))return e(t.arrayBuffer());if(a(t))return E(x,t,{objectMode:!0,writable:!1});if(h(null==t?void 0:t.readable)&&f(null==t?void 0:t.writable))return x.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable))return P({readable:null!=t&&t.readable?l(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?u(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 T(i,t,(t=>{null!=t&&e.push(t),e.push(null)}),(t=>{v(e,t)})),e=new x({objectMode:!0,writable:!1,read(){}})}throw new y(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},9365:function(e,t,r){const n=r(5606),{AbortError:i,codes:o}=r(8526),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_PREMATURE_CLOSE:a}=o,{kEmptyObject:c,once:l}=r(6017),{validateAbortSignal:u,validateFunction:d,validateObject:h,validateBoolean:f}=r(2224),{Promise:p,PromisePrototypeThen:g,SymbolDispose:y}=r(4641),{isClosed:m,isReadable:v,isReadableNodeStream:b,isReadableStream:w,isReadableFinished:_,isReadableErrored:S,isWritable:E,isWritableNodeStream:A,isWritableStream:R,isWritableFinished:I,isWritableErrored:T,isNodeStream:x,willEmitClose:P,kIsClosedPromise:C}=r(136);let k;const O=()=>{};function F(e,t,o){var f,p;if(2===arguments.length?(o=t,t=c):null==t?t=c:h(t,"options"),d(o,"callback"),u(t.signal,"options.signal"),o=l(o),w(e)||R(e))return function(e,t,o){let s=!1,a=O;if(t.signal)if(a=()=>{s=!0,o.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(a);else{k=k||r(6017).addAbortListener;const n=k(t.signal,a),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}const c=(...t)=>{s||n.nextTick((()=>o.apply(e,t)))};return g(e[C].promise,c,c),O}(e,t,o);if(!x(e))throw new s("stream",["ReadableStream","WritableStream","Stream"],e);const F=null!==(f=t.readable)&&void 0!==f?f:b(e),N=null!==(p=t.writable)&&void 0!==p?p:A(e),D=e._writableState,L=e._readableState,U=()=>{e.writable||B()};let j=P(e)&&b(e)===F&&A(e)===N,M=I(e,!1);const B=()=>{M=!0,e.destroyed&&(j=!1),(!j||e.readable&&!F)&&(F&&!H||o.call(e))};let H=_(e,!1);const W=()=>{H=!0,e.destroyed&&(j=!1),(!j||e.writable&&!N)&&(N&&!M||o.call(e))},$=t=>{o.call(e,t)};let V=m(e);const K=()=>{V=!0;const t=T(e)||S(e);return t&&"boolean"!=typeof t?o.call(e,t):F&&!H&&b(e,!0)&&!_(e,!1)?o.call(e,new a):!N||M||I(e,!1)?void o.call(e):o.call(e,new a)},J=()=>{V=!0;const t=T(e)||S(e);if(t&&"boolean"!=typeof t)return o.call(e,t);o.call(e)},G=()=>{e.req.on("finish",B)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?N&&!D&&(e.on("end",U),e.on("close",U)):(e.on("complete",B),j||e.on("abort",K),e.req?G():e.on("request",G)),j||"boolean"!=typeof e.aborted||e.on("aborted",K),e.on("end",W),e.on("finish",B),!1!==t.error&&e.on("error",$),e.on("close",K),V?n.nextTick(K):null!=D&&D.errorEmitted||null!=L&&L.errorEmitted?j||n.nextTick(J):(F||j&&!v(e)||!M&&!1!==E(e))&&(N||j&&!E(e)||!H&&!1!==v(e))?L&&e.req&&e.aborted&&n.nextTick(J):n.nextTick(J);const q=()=>{o=O,e.removeListener("aborted",K),e.removeListener("complete",B),e.removeListener("abort",K),e.removeListener("request",G),e.req&&e.req.removeListener("finish",B),e.removeListener("end",U),e.removeListener("close",U),e.removeListener("finish",B),e.removeListener("end",W),e.removeListener("error",$),e.removeListener("close",K)};if(t.signal&&!V){const s=()=>{const r=o;q(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(s);else{k=k||r(6017).addAbortListener;const n=k(t.signal,s),i=o;o=l(((...t)=>{n[y](),i.apply(e,t)}))}}return q}e.exports=F,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=F(e,t,(e=>{n&&o(),e?i(e):r()}))}))}},333:function(e,t,r){"use strict";const n=r(5606),{PromisePrototypeThen:i,SymbolAsyncIterator:o,SymbolIterator:s}=r(4641),{Buffer:a}=r(8287),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:l}=r(8526).codes;e.exports=function(e,t,r){let u,d;if("string"==typeof t||t instanceof a)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[o])d=!0,u=t[o]();else{if(!t||!t[s])throw new c("iterable",["Iterable"],t);d=!1,u=t[s]()}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 u.next():u.next();if(t)h.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw f=!1,new l;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 u.throw;if(t&&r){const{value:t,done:r}=await u.throw(e);if(await t,r)return}if("function"==typeof u.return){const{value:e}=await u.return();await e}}(e),(()=>n.nextTick(t,e)),(r=>n.nextTick(t,r||e)))},h}},334:function(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(4641),{EventEmitter:o}=r(7007);function s(e){o.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(s.prototype,o.prototype),i(s,o),s.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",l));let s=!1;function c(){s||(s=!0,e.end())}function l(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function u(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",l),r.removeListener("error",u),e.removeListener("error",u),r.removeListener("end",d),r.removeListener("close",d),e.removeListener("close",d)}return a(r,"error",u),a(e,"error",u),r.on("end",d),r.on("close",d),e.on("close",d),e.emit("pipe",r),e},e.exports={Stream:s,prependListener:a}},1284:function(e,t,r){"use strict";const n=globalThis.AbortController||r(5568).AbortController,{codes:{ERR_INVALID_ARG_VALUE:i,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:s,ERR_OUT_OF_RANGE:a},AbortError:c}=r(8526),{validateAbortSignal:l,validateInteger:u,validateObject:d}=r(2224),h=r(4641).Symbol("kWeak"),f=r(4641).Symbol("kResistStopPropagation"),{finished:p}=r(9365),g=r(8489),{addAbortSignalNoValidate:y}=r(810),{isWritable:m,isNodeStream:v}=r(136),{deprecate:b}=r(6017),{ArrayPrototypePush:w,Boolean:_,MathFloor:S,Number:E,NumberIsNaN:A,Promise:R,PromiseReject:I,PromiseResolve:T,PromisePrototypeThen:x,Symbol:P}=r(4641),C=P("kEmpty"),k=P("kEof");function O(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal");let n=1;null!=(null==t?void 0:t.concurrency)&&(n=S(t.concurrency));let i=n-1;return null!=(null==t?void 0:t.highWaterMark)&&(i=S(t.highWaterMark)),u(n,"options.concurrency",1),u(i,"options.highWaterMark",0),i+=n,async function*(){const o=r(6017).AbortSignalAny([null==t?void 0:t.signal].filter(_)),s=this,a=[],l={signal:o};let u,d,h=!1,f=0;function p(){h=!0,g()}function g(){f-=1,y()}function y(){d&&!h&&f=i||f>=n)&&await new R((e=>{d=e}))}a.push(k)}catch(e){const t=I(e);x(t,g,p),a.push(t)}finally{h=!0,u&&(u(),u=null)}}();try{for(;;){for(;a.length>0;){const e=await a[0];if(e===k)return;if(o.aborted)throw new c;e!==C&&(yield e),a.shift(),y()}await new R((e=>{u=e}))}}finally{h=!0,d&&(d(),d=null)}}.call(this)}async function F(e,t=void 0){for await(const r of N.call(this,e,t))return!0;return!1}function N(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return O.call(this,(async function(t,r){return await e(t,r)?t:C}),t)}class D extends s{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function L(e){if(e=E(e),A(e))return 0;if(e<0)throw new a("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:b((function(e=void 0){return null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(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 c({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&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;e--<=0&&(yield r)}}.call(this)},filter:N,flatMap:function(e,t){const r=O.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:O,take:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=L(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),v(e)&&!m(e))throw new i("stream",e,"must be writable");const r=g(this,e);return null!=t&&t.signal&&y(t.signal,r),r}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new o("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 o("fn",["Function","AsyncFunction"],e);for await(const r of O.call(this,(async function(t,r){return await e(t,r),C}),t));},reduce:async function(e,t,r){var i;if("function"!=typeof e)throw new o("reducer",["Function","AsyncFunction"],e);null!=r&&d(r,"options"),null!=(null==r?void 0:r.signal)&&l(r.signal,"options.signal");let s=arguments.length>1;if(null!=r&&null!==(i=r.signal)&&void 0!==i&&i.aborted){const e=new c(void 0,{cause:r.signal.reason});throw this.once("error",(()=>{})),await p(this.destroy(e)),e}const a=new n,u=a.signal;if(null!=r&&r.signal){const e={once:!0,[h]:this,[f]:!0};r.signal.addEventListener("abort",(()=>a.abort()),e)}let g=!1;try{for await(const n of this){var y;if(g=!0,null!=r&&null!==(y=r.signal)&&void 0!==y&&y.aborted)throw new c;s?t=await e(t,n,{signal:u}):(t=n,s=!0)}if(!g&&!s)throw new D}finally{a.abort()}return t},toArray:async function(e){null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(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 c(void 0,{cause:e.signal.reason});w(t,n)}return t},some:F,find:async function(e,t){for await(const r of N.call(this,e,t))return r}}},2091:function(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(4641);e.exports=o;const i=r(8649);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)}},8431:function(e,t,r){const n=r(5606),{ArrayIsArray:i,Promise:o,SymbolAsyncIterator:s,SymbolDispose:a}=r(4641),c=r(9365),{once:l}=r(6017),u=r(7647),d=r(3559),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:p,ERR_MISSING_ARGS:g,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:m},AbortError:v}=r(8526),{validateFunction:b,validateAbortSignal:w}=r(2224),{isIterable:_,isReadable:S,isReadableNodeStream:E,isNodeStream:A,isTransformStream:R,isWebStream:I,isReadableStream:T,isReadableFinished:x}=r(136),P=globalThis.AbortController||r(5568).AbortController;let C,k,O;function F(e,t,r){let n=!1;return e.on("close",(()=>{n=!0})),{destroy:t=>{n||(n=!0,u.destroyer(e,t||new y("pipe")))},cleanup:c(e,{readable:t,writable:r},(e=>{n=!e}))}}function N(e){if(_(e))return e;if(E(e))return async function*(e){k||(k=r(3125)),yield*k.prototype[s].call(e)}(e);throw new f("val",["Readable","Iterable","AsyncIterable"],e)}async function D(e,t,r,{end:n}){let i,s=null;const a=e=>{if(e&&(i=e),s){const e=s;s=null,e()}},l=()=>new o(((e,t)=>{i?t(i):s=()=>{i?t(i):e()}}));t.on("drain",a);const u=c(t,{readable:!1},a);try{t.writableNeedDrain&&await l();for await(const r of e)t.write(r)||await l();n&&(t.end(),await l()),r()}catch(e){r(i!==e?h(i,e):e)}finally{u(),t.off("drain",a)}}async function L(e,t,r,{end:n}){R(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 U(e,t,o){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new g("streams");const s=new P,c=s.signal,l=null==o?void 0:o.signal,u=[];function h(){B(new v)}let y,m,b;w(l,"options.signal"),O=O||r(6017).addAbortListener,l&&(y=O(l,h));const x=[];let k,U=0;function M(e){B(e,0==--U)}function B(e,r){var i;if(!e||m&&"ERR_STREAM_PREMATURE_CLOSE"!==m.code||(m=e),m||r){for(;x.length;)x.shift()(m);null===(i=y)||void 0===i||i[a](),s.abort(),r&&(m||u.forEach((e=>e())),n.nextTick(t,m,b))}}for(let V=0;V0,q=J||!1!==(null==o?void 0:o.end),z=V===e.length-1;if(A(K)){if(q){const{destroy:Y,cleanup:Q}=F(K,J,G);x.push(Y),S(K)&&z&&u.push(Q)}function H(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&M(e)}K.on("error",H),S(K)&&z&&u.push((()=>{K.removeListener("error",H)}))}if(0===V)if("function"==typeof K){if(k=K({signal:c}),!_(k))throw new p("Iterable, AsyncIterable or Stream","source",k)}else k=_(K)||E(K)||R(K)?K:d.from(K);else if("function"==typeof K){var W;if(k=R(k)?N(null===(W=k)||void 0===W?void 0:W.readable):N(k),k=K(k,{signal:c}),J){if(!_(k,!0))throw new p("AsyncIterable",`transform[${V-1}]`,k)}else{var $;C||(C=r(2091));const X=new C({objectMode:!0}),Z=null===($=k)||void 0===$?void 0:$.then;if("function"==typeof Z)U++,Z.call(k,(e=>{b=e,null!=e&&X.write(e),q&&X.end(),n.nextTick(M)}),(e=>{X.destroy(e),n.nextTick(M,e)}));else if(_(k,!0))U++,D(k,X,M,{end:q});else{if(!T(k)&&!R(k))throw new p("AsyncIterable or Promise","destination",k);{const re=k.readable||k;U++,D(re,X,M,{end:q})}}k=X;const{destroy:ee,cleanup:te}=F(k,!1,!0);x.push(ee),z&&u.push(te)}}else if(A(K)){if(E(k)){U+=2;const ne=j(k,K,M,{end:q});S(K)&&z&&u.push(ne)}else if(R(k)||T(k)){const ie=k.readable||k;U++,D(ie,K,M,{end:q})}else{if(!_(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,D(k,K,M,{end:q})}k=K}else if(I(K)){if(E(k))U++,L(N(k),K,M,{end:q});else if(T(k)||_(k))U++,L(k,K,M,{end:q});else{if(!R(k))throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],k);U++,L(k.readable,K,M,{end:q})}k=K}else k=d.from(K)}return(null!=c&&c.aborted||null!=l&&l.aborted)&&n.nextTick(h),k}function j(e,t,r,{end:i}){let o=!1;if(t.on("close",(()=>{o||r(new m)})),e.pipe(t,{end:!1}),i){function s(){o=!0,t.end()}x(e)?n.nextTick(s):e.once("end",s)}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:U,pipeline:function(...e){return U(e,l(function(e){return b(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},3125:function(e,t,r){const n=r(5606),{ArrayPrototypeIndexOf:i,NumberIsInteger:o,NumberIsNaN:s,NumberParseInt:a,ObjectDefineProperties:c,ObjectKeys:l,ObjectSetPrototypeOf:u,Promise:d,SafeSet:h,SymbolAsyncDispose:f,SymbolAsyncIterator:p,Symbol:g}=r(4641);e.exports=G,G.ReadableState=J;const{EventEmitter:y}=r(7007),{Stream:m,prependListener:v}=r(334),{Buffer:b}=r(8287),{addAbortSignal:w}=r(810),_=r(9365);let S=r(6017).debuglog("stream",(e=>{S=e}));const E=r(5586),A=r(7647),{getHighWaterMark:R,getDefaultHighWaterMark:I}=r(3920),{aggregateTwoErrors:T,codes:{ERR_INVALID_ARG_TYPE:x,ERR_METHOD_NOT_IMPLEMENTED:P,ERR_OUT_OF_RANGE:C,ERR_STREAM_PUSH_AFTER_EOF:k,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:O},AbortError:F}=r(8526),{validateObject:N}=r(2224),D=g("kPaused"),{StringDecoder:L}=r(6600),U=r(333);u(G.prototype,m.prototype),u(G,m);const j=()=>{},{errorOrDestroy:M}=A,B=1,H=16,W=32,$=2048,V=4096;function K(e){return{enumerable:!1,get(){return!!(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function J(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(3559)),this.state=$|V|H|W,e&&e.objectMode&&(this.state|=B),n&&e&&e.readableObjectMode&&(this.state|=B),this.highWaterMark=e?R(this,e,"readableHighWaterMark",n):I(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[D]=null,e&&!1===e.emitClose&&(this.state&=~$),e&&!1===e.autoDestroy&&(this.state&=~V),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 G(e){if(!(this instanceof G))return new G(e);const t=this instanceof r(3559);this._readableState=new J(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)),m.call(this,e),A.construct(this,(()=>{this._readableState.needReadable&&Z(this,this._readableState)}))}function q(e,t,r,n){S("readableAddChunk",t);const i=e._readableState;let o;if(i.state&B||("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="":m._isUint8Array(t)?(t=m._uint8ArrayToBuffer(t),r=""):null!=t&&(o=new x("chunk",["string","Buffer","Uint8Array"],t))),o)M(e,o);else if(null===t)i.state&=-9,function(e,t){if(S("onEofChunk"),!t.ended){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?Q(e):(t.needReadable=!1,t.emittedReadable=!0,X(e))}}(e,i);else if(i.state&B||t&&t.length>0)if(n)if(4&i.state)M(e,new O);else{if(i.destroyed||i.errored)return!1;z(e,i,t,!0)}else if(i.ended)M(e,new k);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?z(e,i,t,!1):Z(e,i)):z(e,i,t,!1)}else n||(i.state&=-9,Z(e,i));return!i.ended&&(i.length0?(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&&Q(e)),Z(e,t)}function Y(e,t){return e<=0||0===t.length&&t.ended?0:t.state&B?1:s(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function Q(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(X,e))}function X(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,ie(e)}function Z(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(ee,e,t))}function ee(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!1===t[D]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function re(e){S("readable nexttick read 0"),e.read(0)}function ne(e,t){S("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),ie(e),t.flowing&&!t.reading&&e.read(0)}function ie(e){const t=e._readableState;for(S("flow",t.flowing);t.flowing&&null!==e.read(););}function oe(e,t){"function"!=typeof e.read&&(e=G.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=j;function i(t){this===e?(n(),n=j):n=t}e.on("readable",i);const o=_(e,{writable:!1},(e=>{r=e?T(r,e):null,n(),n=j}));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=T(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),o()):A.destroyer(e,null)}}(e,t);return r.stream=e,r}function se(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 ae(e){const t=e._readableState;S("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(ce,t,e))}function ce(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(le,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function le(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let ue;function de(){return void 0===ue&&(ue={}),ue}c(J.prototype,{objectMode:K(B),ended:K(2),endEmitted:K(4),reading:K(8),constructed:K(H),sync:K(W),needReadable:K(64),emittedReadable:K(128),readableListening:K(256),resumeScheduled:K(512),errorEmitted:K(1024),emitClose:K($),autoDestroy:K(V),destroyed:K(8192),closed:K(16384),closeEmitted:K(32768),multiAwaitDrain:K(65536),readingMore:K(1<<17),dataEmitted:K(1<<18)}),G.prototype.destroy=A.destroy,G.prototype._undestroy=A.undestroy,G.prototype._destroy=function(e,t){t(e)},G.prototype[y.captureRejectionSymbol]=function(e){this.destroy(e)},G.prototype[f]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new F,this.destroy(e)),new d(((t,r)=>_(this,(n=>n&&n!==e?r(n):t(null)))))},G.prototype.push=function(e,t){return q(this,e,t,!1)},G.prototype.unshift=function(e,t){return q(this,e,t,!0)},G.prototype.isPaused=function(){const e=this._readableState;return!0===e[D]||!1===e.flowing},G.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},G.prototype.read=function(e){S("read",e),void 0===e?e=NaN:o(e)||(e=a(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new C("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?ae(this):Q(this),null;if(0===(e=Y(e,t))&&t.ended)return 0===t.length&&ae(this),null;let n,i=!!(64&t.state);if(S("need readable",i),(0===t.length||t.length-e0?se(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&&ae(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},G.prototype._read=function(e){throw new P("_read()")},G.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?g:s;function s(){S("onend"),e.end()}let a;i.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",(function t(n,o){S("onunpipe"),n===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,S("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),a&&e.removeListener("drain",a),e.removeListener("error",d),e.removeListener("unpipe",t),r.removeListener("end",s),r.removeListener("end",g),r.removeListener("data",u),c=!0,a&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&a())}));let c=!1;function l(){c||(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()),a||(a=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",a))}function u(t){S("ondata");const r=e.write(t);S("dest.write",r),!1===r&&l()}function d(t){if(S("onerror",t),g(),e.removeListener("error",d),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?M(e,t):e.emit("error",t)}}function f(){e.removeListener("finish",p),g()}function p(){S("onfinish"),e.removeListener("close",f),g()}function g(){S("unpipe"),r.unpipe(e)}return r.on("data",u),v(e,"error",d),e.once("close",f),e.once("finish",p),e.emit("pipe",r),!0===e.writableNeedDrain?l():i.flowing||(S("pipe resume"),r.resume()),e},G.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;t0,!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?Q(this):i.reading||n.nextTick(re,this))),r},G.prototype.addListener=G.prototype.on,G.prototype.removeListener=function(e,t){const r=m.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(te,this),r},G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=function(e){const t=m.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(te,this),t},G.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(ne,e,t))}(this,e)),e[D]=!1,this},G.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},G.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=l(e);for(let t=1;t{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())}))}function d(){this._final!==u&&u.call(this)}l.prototype._final=u,l.prototype._transform=function(e,t,r){throw new o("_transform()")},l.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{const e=this._writableState;e.writing||W(this,e),V(this,e)}))}function D(e,t,r,i){const o=e._writableState;if("function"==typeof r)i=r,r=o.defaultEncoding;else{if(r){if("buffer"!==r&&!g.isEncoding(r))throw new x(r)}else r=o.defaultEncoding;"function"!=typeof i&&(i=C)}if(null===t)throw new I;if(!o.objectMode)if("string"==typeof t)!1!==o.decodeStrings&&(t=g.from(t,r),r="buffer");else if(t instanceof g)r="buffer";else{if(!p._isUint8Array(t))throw new w("chunk",["string","Buffer","Uint8Array"],t);t=p._uint8ArrayToBuffer(t),r="buffer"}let s;return o.ending?s=new T:o.destroyed&&(s=new A("write")),s?(n.nextTick(i,s),P(e,s,!0),s):(o.pendingcb++,function(e,t,r,n,i){const o=t.objectMode?1:r.length;t.length+=o;const s=t.lengthr.bufferedIndex&&W(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(M,r.afterWriteTickInfo)):B(e,r,1,o))):P(e,new S)}function M({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,B(e,t,r,n)}function B(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&&H(t),V(e,t)}function H(e){if(e.writing)return;for(let r=e.bufferedIndex;r1&&e._writev){t.pendingcb-=s-1;const n=t.allNoop?C:e=>{for(let t=a;t256?(r.splice(0,a),t.bufferedIndex=0):t.bufferedIndex=a}t.bufferProcessing=!1}function $(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 V(e,t,r){$(t)&&(function(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)P(e,null!=i?i:S());else if(r=!0,t.pendingcb--,i){const r=t[k].splice(0);for(let e=0;e{$(t)?K(e,t):t.pendingcb--}),e,t)):$(t)&&(t.pendingcb++,K(e,t))))}function K(e,t){t.pendingcb--,t.finished=!0;const r=t[k].splice(0);for(let e=0;e{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),P=m(((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);if(en)throw new _(t,`>= ${r} && <= ${n}`,e)})),C=m(((e,t,r=!1)=>{if("number"!=typeof e)throw new b(t,"number",e);if(!a(e))throw new _(t,"an integer",e);const n=r?1:0,i=4294967295;if(ei)throw new _(t,`>= ${n} && <= ${i}`,e)}));function k(e,t){if("string"!=typeof e)throw new b(t,"string",e)}const O=m(((e,t,r)=>{if(!i(r,e)){const n=o(s(r,(e=>"string"==typeof e?`'${e}'`:p(e))),", ");throw new w(t,e,"must be one of: "+n)}}));function F(e,t){if("boolean"!=typeof e)throw new b(t,"boolean",e)}function N(e,t,r){return null!=e&&h(e,t)?e[t]:r}const D=m(((e,t,r=null)=>{const i=N(r,"allowArray",!1),o=N(r,"allowFunction",!1);if(!N(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!o||"function"!=typeof e))throw new b(t,"Object",e)})),L=m(((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new b(t,"a dictionary",e)})),U=m(((e,t,r=0)=>{if(!n(e))throw new b(t,"Array",e);if(e.length{if(!R(e))throw new b(t,["Buffer","TypedArray","DataView"],e)})),M=m(((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new b(t,"AbortSignal",e)})),B=m(((e,t)=>{if("function"!=typeof e)throw new b(t,"Function",e)})),H=m(((e,t)=>{if("function"!=typeof e||A(e))throw new b(t,"Function",e)})),W=m(((e,t)=>{if(void 0!==e)throw new b(t,"undefined",e)})),$=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function V(e,t){if(void 0===e||!f($,e))throw new w(t,e,'must be an array or string of format "; rel=preload; as=style"')}e.exports={isInt32:function(e){return e===(0|e)},isUint32:function(e){return e===e>>>0},parseFileMode:function(e,t,r){if(void 0===e&&(e=r),"string"==typeof e){if(null===f(T,e))throw new w(t,e,"must be a 32-bit unsigned integer or an octal string");e=d(e,8)}return C(e,t),e},validateArray:U,validateStringArray:function(e,t){U(e,t);for(let r=0;rn||(null!=r||null!=n)&&c(e))throw new _(t,`${null!=r?`>= ${r}`:""}${null!=r&&null!=n?" && ":""}${null!=n?`<= ${n}`:""}`,e)},validateObject:D,validateOneOf:O,validatePlainFunction:H,validatePort:function(e,t="Port",r=!0){if("number"!=typeof e&&"string"!=typeof e||"string"==typeof e&&0===y(e).length||+e!=+e>>>0||e>65535||0===e&&!r)throw new v(t,e,r);return 0|e},validateSignalName:function(e,t="signal"){if(k(e,t),void 0===I[e]){if(void 0!==I[g(e)])throw new S(e+" (signals must use all capital letters)");throw new S(e)}},validateString:k,validateUint32:C,validateUndefined:W,validateUnion:function(e,t,r){if(!i(r,e))throw new b(t,`('${o(r,"|")}')`,e)},validateAbortSignal:M,validateLinkHeaderValue:function(e){if("string"==typeof e)return V(e,"hints"),e;if(n(e)){const t=e.length;let r="";if(0===t)return r;for(let n=0;n; rel=preload; as=style"')}}},5721:function(e,t,r){"use strict";const n=r(2825),i=r(5018),o=n.Readable.destroy;e.exports=n.Readable,e.exports._uint8ArrayToBuffer=n._uint8ArrayToBuffer,e.exports._isUint8Array=n._isUint8Array,e.exports.isDisturbed=n.isDisturbed,e.exports.isErrored=n.isErrored,e.exports.isReadable=n.isReadable,e.exports.Readable=n.Readable,e.exports.Writable=n.Writable,e.exports.Duplex=n.Duplex,e.exports.Transform=n.Transform,e.exports.PassThrough=n.PassThrough,e.exports.addAbortSignal=n.addAbortSignal,e.exports.finished=n.finished,e.exports.destroy=n.destroy,e.exports.destroy=o,e.exports.pipeline=n.pipeline,e.exports.compose=n.compose,Object.defineProperty(n,"promises",{configurable:!0,enumerable:!0,get(){return i}}),e.exports.Stream=n.Stream,e.exports.default=e.exports},8526:function(e,t,r){"use strict";const{format:n,inspect:i,AggregateError:o}=r(6017),s=globalThis.AggregateError||o,a=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,u={};function d(e,t){if(!e)throw new u.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 i 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(i.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}}),i.prototype.code=e,i.prototype[a]=!0,u[e]=i}function p(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class g extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new u.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=[],s=[],a=[];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()):l.test(e)?s.push(e):(d("object"!==e,'The value "object" should be written as "Object"'),a.push(e));if(s.length>0){const e=o.indexOf("object");-1!==e&&(o.splice(o,e,1),s.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}`}}(s.length>0||a.length>0)&&(n+=" or ")}if(s.length>0){switch(s.length){case 1:n+=`an instance of ${s[0]}`;break;case 2:n+=`an instance of ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`an instance of ${s.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 u;null!==(u=r.constructor)&&void 0!==u&&u.name?n+=`. Received an instance of ${r.constructor.name}`: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);return n.length>128&&(n=n.slice(0,128)+"..."),`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;return d(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32?n=h(String(r)):"bigint"==typeof r?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=h(n)),n+="n"):n=i(r),`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:g,aggregateTwoErrors:p((function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new s([t,e],t.message);return r.code=t.code,r}return e||t})),hideStackFrames:p,codes:u}},4641:function(e){"use strict";e.exports={ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error:Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number: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){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise:Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String:String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol: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){return e.set(t,r)},Boolean:Boolean,Uint8Array:Uint8Array}},6017:function(e,t,r){"use strict";const n=r(8287),{kResistStopPropagation:i,SymbolDispose:o}=r(4641),s=globalThis.AbortSignal||r(5568).AbortSignal,a=globalThis.AbortController||r(5568).AbortController,c=Object.getPrototypeOf((async function(){})).constructor,l=globalThis.Blob||n.Blob,u=void 0!==l?function(e){return e instanceof l}:function(e){return!1},d=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new ERR_INVALID_ARG_TYPE(t,"AbortSignal",e)};class h 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=r,t=n})),resolve:e,reject:t}},promisify(e){return new Promise(((t,r)=>{e(((e,...n)=>e?r(e):t(...n)))}))},debuglog(){return function(){}},format(e,...t){return e.replace(/%([sdifj])/g,(function(...[e,r]){const n=t.shift();return"f"===r?n.toFixed(6):"j"===r?JSON.stringify(n):"s"===r&&"object"==typeof n?`${n.constructor!==Object?n.constructor.name:""} {}`.trim():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"{}"}},types:{isAsyncFunction(e){return e instanceof c},isArrayBufferView(e){return ArrayBuffer.isView(e)}},isBlob:u,deprecate(e,t){return e},addAbortListener:r(7007).addAbortListener||function(e,t){if(void 0===e)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);let r;return d(e,"signal"),(e=>{if("function"!=typeof e)throw new ERR_INVALID_ARG_TYPE("listener","Function",e)})(t),e.aborted?queueMicrotask((()=>t())):(e.addEventListener("abort",t,{__proto__:null,once:!0,[i]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[o](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:s.any||function(e){if(1===e.length)return e[0];const t=new a,r=()=>t.abort();return e.forEach((e=>{d(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")},2825:function(e,t,r){const{Buffer:n}=r(8287),{ObjectDefineProperty:i,ObjectKeys:o,ReflectApply:s}=r(4641),{promisify:{custom:a}}=r(6017),{streamReturningOperators:c,promiseReturningOperators:l}=r(1284),{codes:{ERR_ILLEGAL_CONSTRUCTOR:u}}=r(8526),d=r(8489),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:f}=r(3920),{pipeline:p}=r(8431),{destroyer:g}=r(7647),y=r(9365),m=r(5018),v=r(136),b=e.exports=r(334).Stream;b.isDestroyed=v.isDestroyed,b.isDisturbed=v.isDisturbed,b.isErrored=v.isErrored,b.isReadable=v.isReadable,b.isWritable=v.isWritable,b.Readable=r(3125);for(const S of o(c)){const E=c[S];function w(...e){if(new.target)throw u();return b.Readable.from(s(E,this,e))}i(w,"name",{__proto__:null,value:E.name}),i(w,"length",{__proto__:null,value:E.length}),i(b.Readable.prototype,S,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}for(const A of o(l)){const R=l[A];function w(...e){if(new.target)throw u();return s(R,this,e)}i(w,"name",{__proto__:null,value:R.name}),i(w,"length",{__proto__:null,value:R.length}),i(b.Readable.prototype,A,{__proto__:null,value:w,enumerable:!1,configurable:!0,writable:!0})}b.Writable=r(7221),b.Duplex=r(3559),b.Transform=r(8649),b.PassThrough=r(2091),b.pipeline=p;const{addAbortSignal:_}=r(810);b.addAbortSignal=_,b.finished=y,b.destroy=g,b.compose=d,b.setDefaultHighWaterMark=h,b.getDefaultHighWaterMark=f,i(b,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return m}}),i(p,a,{__proto__:null,enumerable:!0,get(){return m.pipeline}}),i(y,a,{__proto__:null,enumerable:!0,get(){return m.finished}}),b.Stream=b,b._isUint8Array=function(e){return e instanceof Uint8Array},b._uint8ArrayToBuffer=function(e){return n.from(e.buffer,e.byteOffset,e.byteLength)}},5018:function(e,t,r){"use strict";const{ArrayPrototypePop:n,Promise:i}=r(4641),{isIterable:o,isNodeStream:s,isWebStream:a}=r(136),{pipelineImpl:c}=r(8431),{finished:l}=r(9365);r(2825),e.exports={finished:l,pipeline:function(...e){return new i(((t,r)=>{let i,l;const u=e[e.length-1];if(u&&"object"==typeof u&&!s(u)&&!o(u)&&!a(u)){const t=n(e);i=t.signal,l=t.end}c(e,((e,n)=>{e?r(e):t(n)}),{signal:i,end:l})}))}}},2692:function(e,t,r){var n=r(8287),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.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},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},6600:function(e,t,r){"use strict";var n=r(2692).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=l,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=u,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 s(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 l(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 u(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=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):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}},8518:function(e,t,r){"use strict";r.r(t),r.d(t,{BlankNode:function(){return T},DataFactory:function(){return E},DefaultGraph:function(){return P},EntityIndex:function(){return fe},Lexer:function(){return m},Literal:function(){return I},NamedNode:function(){return R},Parser:function(){return H},Quad:function(){return O},Reasoner:function(){return be},Store:function(){return pe},StoreFactory:function(){return me},StreamParser:function(){return Se},StreamWriter:function(){return Ee},Term:function(){return A},Triple:function(){return O},Util:function(){return n},Variable:function(){return x},Writer:function(){return oe},default:function(){return Ae},getRulesFromDataset:function(){return ve},termFromId:function(){return C},termToId:function(){return k}});var n={};r.r(n),r.d(n,{inDefaultGraph:function(){return z},isBlankNode:function(){return K},isDefaultGraph:function(){return q},isLiteral:function(){return J},isNamedNode:function(){return V},isVariable:function(){return G},prefix:function(){return Y},prefixes:function(){return Q}});var i=r(8287),o=r(9596),s=r.n(o);const a="http://www.w3.org/1999/02/22-rdf-syntax-ns#",c="http://www.w3.org/2001/XMLSchema#",l="http://www.w3.org/2000/10/swap/";var u={xsd:{decimal:`${c}decimal`,boolean:`${c}boolean`,double:`${c}double`,integer:`${c}integer`,string:`${c}string`},rdf:{type:`${a}type`,nil:`${a}nil`,first:`${a}first`,rest:`${a}rest`,langString:`${a}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${l}reify#forSome`,forAll:`${l}reify#forAll`},log:{implies:`${l}log#implies`}};const{xsd:d}=u,h=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,f={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},p=/[\x00-\x20<>\\"\{\}\|\^\`]/,g={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},y=/$0^/;class m{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._lineMode=!!e.lineMode){this._n3Mode=!1;for(const e in this)!(e in g)&&this[e]instanceof RegExp&&(this[e]=y)}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,s;for(;e=this._newline.exec(r);)this.comments&&(s=this._comment.exec(e[0]))&&i("comment",s[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&&(s=this._comment.exec(r))&&i("comment",s[1],"",this._line,r.length),r=null,i("eof","","",this._line,0)),this._input=r;const a=this._line,c=r[0];let l="",u="",h="",f=null,g=0,y=!1;switch(c){case"^":if(r.length<3)break;if("^"!==r[1]){this._n3Mode&&(g=1,l="^");break}if(this._previousMarker="^^",r=r.substr(2),"<"!==r[0]){y=!0;break}case"<":if(f=this._unescapedIri.exec(r))l="IRI",u=f[1];else if(f=this._iri.exec(r)){if(u=this._unescape(f[1]),null===u||p.test(u))return o(this);l="IRI"}else r.length>1&&"<"===r[1]?(l="<<",g=2):this._n3Mode&&r.length>1&&"="===r[1]&&(l="inverse",g=2,u=">");break;case">":r.length>1&&">"===r[1]&&(l=">>",g=2);break;case"_":((f=this._blank.exec(r))||t&&(f=this._blank.exec(`${r} `)))&&(l="blank",h="_",u=f[1]);break;case'"':if(f=this._simpleQuotedString.exec(r))u=f[1];else if(({value:u,matchLength:g}=this._parseLiteral(r)),null===u)return o(this);null===f&&0===g||(l="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(f=this._simpleApostropheString.exec(r))u=f[1];else if(({value:u,matchLength:g}=this._parseLiteral(r)),null===u)return o(this);null===f&&0===g||(l="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(f=this._variable.exec(r))&&(l="var",u=f[0]);break;case"@":"literal"===this._previousMarker&&(f=this._langcode.exec(r))?(l="langcode",u=f[1]):(f=this._keyword.exec(r))&&(l=f[0]);break;case".":if(1===r.length?t:r[1]<"0"||r[1]>"9"){l=".",g=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(f=this._number.exec(r)||t&&(f=this._number.exec(`${r} `)))&&(l="literal",u=f[0],h="string"==typeof f[1]?d.double:"string"==typeof f[2]?d.decimal:d.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(f=this._sparqlKeyword.exec(r))?l=f[0].toUpperCase():y=!0;break;case"f":case"t":(f=this._boolean.exec(r))?(l="literal",u=f[0],h=d.boolean):y=!0;break;case"a":(f=this._shortPredicates.exec(r))?(l="abbreviation",u="a"):y=!0;break;case"=":this._n3Mode&&r.length>1&&(l="abbreviation",">"!==r[1]?(g=1,u="="):(g=2,u=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(g=1,l=c);break;case"{":!this._lineMode&&r.length>=2&&("|"===r[1]?(l="{|",g=2):(l=c,g=1));break;case"|":r.length>=2&&"}"===r[1]&&(l="|}",g=2);break;default:y=!0}if(y&&("@prefix"!==this._previousMarker&&"PREFIX"!==this._previousMarker||!(f=this._prefix.exec(r))?((f=this._prefixed.exec(r))||t&&(f=this._prefixed.exec(`${r} `)))&&(l="prefixed",h=f[1]||"",u=this._unescape(f[2])):(l="prefix",u=f[1]||"")),"^^"===this._previousMarker)switch(l){case"prefixed":l="type";break;case"IRI":l="typeIRI";break;default:l=""}if(!l)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?o(this):this._input=r;const m=g||f[0].length,v=i(l,u,h,a,m);this.previousToken=v,this._previousMarker=l,r=r.substr(m,r.length)}function i(t,i,o,s,a){const c=r?n-r.length:n,l={type:t,value:i,prefix:o,line:s,start:c,end:c+a};return e(null,l),l}function o(t){e(t._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(h,((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 f?f[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,t){if(this._line=1,"string"==typeof e){if(this._input=this._readStartingBom(e),"function"!=typeof t){const e=[];let t;if(this._tokenizeToEnd(((r,n)=>r?t=r:e.push(n)),!0),t)throw t;return e}s()((()=>this._tokenizeToEnd(t,!0)))}else this._pendingBuffer=null,"function"==typeof e.setEncoding&&e.setEncoding("utf8"),e.on("data",(e=>{null!==this._input&&0!==e.length&&(this._pendingBuffer&&(e=i.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(t,!1)))})),e.on("end",(()=>{"string"==typeof this._input&&this._tokenizeToEnd(t,!0)})),e.on("error",t)}}const{rdf:v,xsd:b}=u;let w,_=0;const S={namedNode:F,blankNode:N,variable:L,literal:D,defaultGraph:function(){return w},quad:U,triple:U,fromTerm:j,fromQuad:M};var E=S;class A{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof A?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 R extends A{get termType(){return"NamedNode"}}class I extends A{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 t0?"INF":"-INF")))),""===r||r===b.string?new I(`"${e}"`):new I(`"${e}"^^${r}`)}function L(e){return new x(e)}function U(e,t,r,n){return new O(e,t,r,n)}function j(e){if(e instanceof A)return e;switch(e.termType){case"NamedNode":return F(e.value);case"BlankNode":return N(e.value);case"Variable":return L(e.value);case"DefaultGraph":return w;case"Literal":return D(e.value,e.language||e.datatype);case"Quad":return M(e);default:throw new Error(`Unexpected termType: ${e.termType}`)}}function M(e){if(e instanceof O)return e;if("Quad"!==e.termType)throw new Error(`Unexpected termType: ${e.termType}`);return U(j(e.subject),j(e.predicate),j(e.object),j(e.graph))}let B=0;class H{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&$(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),s=this._n3Mode=/n3/.test(t),a=i||o;(this._supportsNamedGraphs=!(r||s))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||n||i||s),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 m({lineMode:a,n3:s}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){B=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,s=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===s.predicate?s.subject=r:s.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,s=this._object;this._subject=this._factory.quad(n,o,s,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=W}_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,s="/";for(;n=i&&(r=r.substr(0,o)),"/"!==s)return`${r}/${e.substr(n+1)}`;o=n+1}}}s=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${B++}_`,this._prefixCallback=i||W,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 s=(e,t)=>{null!==e?(this._callback(e),this._callback=W):this._readCallback&&(this._readCallback=this._readCallback(t))};o&&(this._lexer.comments=!0,s=(e,t)=>{null!==e?(this._callback(e),this._callback=W):this._readCallback&&("comment"===t.type?o(t.value):this._readCallback=this._readCallback(t))}),this._callback=n,this._lexer.tokenize(e,s)}}function W(){}function $(e,t){e._factory=t,e.DEFAULTGRAPH=t.defaultGraph(),e.RDF_FIRST=t.namedNode(u.rdf.first),e.RDF_REST=t.namedNode(u.rdf.rest),e.RDF_NIL=t.namedNode(u.rdf.nil),e.N3_FORALL=t.namedNode(u.r.forAll),e.N3_FORSOME=t.namedNode(u.r.forSome),e.ABBREVIATIONS={a:t.namedNode(u.rdf.type),"=":t.namedNode(u.owl.sameAs),">":t.namedNode(u.log.implies)},e.QUANTIFIERS_GRAPH=t.namedNode("urn:n3:quantifiers")}function V(e){return!!e&&"NamedNode"===e.termType}function K(e){return!!e&&"BlankNode"===e.termType}function J(e){return!!e&&"Literal"===e.termType}function G(e){return!!e&&"Variable"===e.termType}function q(e){return!!e&&"DefaultGraph"===e.termType}function z(e){return q(e.graph)}function Y(e,t){return Q({"":e.value||e},t)("")}function Q(e,t){const r=Object.create(null);for(const t in e)n(t,e[t]);function n(e,n){if("string"==typeof n){const i=Object.create(null);r[e]=e=>i[e]||(i[e]=t.namedNode(n+e))}else if(!(e in r))throw new Error(`Unknown prefix: ${e}`);return r[e]}return t=t||E,n}$(H.prototype,E);const X=E.defaultGraph(),{rdf:Z,xsd:ee}=u,te=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,re=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,ne={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class ie extends A{equals(e){return e===this}}class oe{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=X,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseMatcher=new RegExp(`^${ae(t.baseIRI)}${t.baseIRI.endsWith("/")?"":"[#?]"}`),this._baseLength=t.baseIRI.length))}get _inDefaultGraph(){return X.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")+(X.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._baseMatcher&&this._baseMatcher.test(t)&&(t=t.substr(this._baseLength)),te.test(t)&&(t=t.replace(re,se));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(te.test(t)&&(t=t.replace(re,se)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===ee.string)return`"${t}"`}else switch(e.datatype.value){case ee.string:return`"${t}"`;case ee.boolean:if("true"===t||"false"===t)return t;break;case ee.integer:if(/^[+-]?\d+$/.test(t))return t;break;case ee.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case ee.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===Z.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)}${q(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,X,n):this._writeQuad(e,t,r,n||X,i)}addQuads(e){for(let t=0;t.\n`)}if(r){let e="",t="";for(const r in this._prefixIRIs)e+=e?`|${r}`:r,t+=(t?"|":"")+this._prefixIRIs[r];e=ae(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 ie("[]");case 1:if(r=i[0],!(r.object instanceof ie))return new ie(`[ ${this._encodePredicate(r.predicate)} ${this._encodeObject(r.object)} ]`);default:let t="[";for(let o=0;o{t=null,e(r,n)});if(this._endStream)try{return this._outputStream.end(t)}catch(e){}t&&t()}}function se(e){let t=ne[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 ae(e){return e.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}var ce=r(5721);const le=Symbol("iter");function ue(e,t,r=4){if(0===r)return Object.assign(e,t);for(const n in t)e[n]=ue(e[n]||Object.create(null),t[n],r-1);return e}function de(e,t,r=4){let n=!1;for(const i in e)if(i in t){const o=0===r?null:de(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 he(e,t,r=4){let n=!1;for(const i in e)if(i in t){if(0!==r){const o=he(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:ue({},e[i],r-1);return n}class fe{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||E}_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 C(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&&(q(e.graph)||(i=this._termToNumericId(e.graph)))&&this._ids[i?`.${t}.${r}.${n}.${i}`:`.${t}.${r}.${n}`]}return this._ids[k(e)]}_termToNewNumericId(e){const t=e&&"Quad"===e.termType?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${q(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:k(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 pe{constructor(e,t){this._size=0,this._graphs=Object.create(null),t||!e||e[0]||(t=e,e=null),t=t||{},this._factory=t.factory||E,this._entityIndex=t.entityIndex||new fe({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.addQuads(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]={}),s=n in o;return s||(o[n]=null),!s}_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,s,a){let c,l,u;const d=this._entities,h=this._termFromId(d[a]),f={subject:null,predicate:null,object:null};t&&((c=e,e={})[t]=c[t]);for(const t in e)if(l=e[t]){f[i]=this._termFromId(d[t]),r&&((c=l,l={})[r]=c[r]);for(const e in l)if(u=l[e]){f[o]=this._termFromId(d[e]);const t=n?n in u?[n]:[]:Object.keys(u);for(let e=0;e{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{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,s,a;if(!((e=e&&this._termToNumericId(e))&&(t=t&&this._termToNumericId(t))&&(r=r&&this._termToNumericId(r))&&(o=i[n])&&(s=o.subjects[e])&&(a=s[t])&&r in a))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{this.removeQuad(e)})),e}removeMatches(e,t,r,n){const i=new ce.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,s,a,c;if(!(e&&!(s=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(const e in i)(o=i[e])&&(s?c?yield*this._findInIndex(o.objects,c,s,a,"object","subject","predicate",e):yield*this._findInIndex(o.subjects,s,a,null,"subject","predicate","object",e):a?yield*this._findInIndex(o.predicates,a,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 ye(this,e,t,r,n,{entityIndex:this._entityIndex})}countQuads(e,t,r,n){const i=this._getGraphs(n);let o,s,a,c,l=0;if(e&&!(s=this._termToNumericId(e))||t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r)))return 0;for(const n in i)(o=i[n])&&(l+=e?r?this._countInIndex(o.objects,c,s,a):this._countInIndex(o.subjects,s,a,c):t?this._countInIndex(o.predicates,a,c,s):this._countInIndex(o.objects,c,s,a));return l}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))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,s,a;if(e=this._uniqueEntities(e),!(t&&!(s=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(o=i[n])&&(s?a?this._loopBy2Keys(o.predicates,s,a,e):this._loopByKey1(o.subjects,s,e):a?this._loopByKey0(o.objects,a,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,s,a;if(e=this._uniqueEntities(e),!(t&&!(s=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(o=i[n])&&(s?a?this._loopBy2Keys(o.objects,a,s,e):this._loopByKey0(o.subjects,s,e):a?this._loopByKey1(o.predicates,a,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,s,a;if(e=this._uniqueEntities(e),!(t&&!(s=this._termToNumericId(t))||r&&!(a=this._termToNumericId(r))))for(n in i)(o=i[n])&&(s?a?this._loopBy2Keys(o.subjects,s,a,e):this._loopByKey1(o.objects,s,e):a?this._loopByKey0(o.predicates,a,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,u.rdf.rest,u.rdf.nil,null),o=e?[...i]:[];return i.forEach((t=>{const i=[];let s,a,c=!1;const l=t.graph;let d=t.subject;for(;d&&!c;){const e=this.getQuads(null,null,d,null),t=this.getQuads(d,null,null,null);let r,h=null,f=null,p=null;for(let i=0;ithis.has(e)));const t=this._graphs,r=e._graphs;let n,i,o,s,a;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 s=i[t]){if(!(a=o[e]))return!1;for(const t in s[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 ye&&(e=e.filtered),e===this)return new pe({entityIndex:this._entityIndex});if(e instanceof pe&&e._entityIndex===this._entityIndex){const t=new pe({entityIndex:this._entityIndex}),r=he(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 ye&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new pe({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof ye&&(e=e.filtered),e===this){const e=new pe({entityIndex:this._entityIndex});return e._graphs=ue(Object.create(null),this._graphs),e._size=this._size,e}if(e instanceof pe&&this._entityIndex===e._entityIndex){const t=new pe({entityIndex:this._entityIndex}),r=de(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 pe({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 oe).quadsToString(this)}union(e){const t=new pe({entityIndex:this._entityIndex});return t._graphs=ue(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}}function ge(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:ge(e[o],t,r+1);!1!==n&&(i=i||Object.create(null),i[o]=n)}return i}class ye extends ce.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 pe({factory:e._factory,entityIndex:this.options.entityIndex});let s,a,c;if(i&&!(s=o._termToNumericId(i))||n&&!(a=o._termToNumericId(n))||r&&!(c=o._termToNumericId(r)))return o;const l=e._getGraphs(t);for(const e in l){let t,r,n;!s&&a?(r=ge(l[e].predicates,[a,c,s]))&&(t=ge(l[e].subjects,[s,a,c]),n=ge(l[e].objects,[c,s,a])):c?(n=ge(l[e].objects,[c,s,a]))&&(t=ge(l[e].subjects,[s,a,c]),r=ge(l[e].predicates,[a,c,s])):(t=ge(l[e].subjects,[s,a,c]))&&(r=ge(l[e].predicates,[a,c,s]),n=ge(l[e].objects,[c,s,a])),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[le]&&(this[le]=this[Symbol.iterator]());const t=this[le];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 oe).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 ye(this.filtered,e,t,r,n,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}class me{dataset(e){return new pe(e)}}function ve(e){const t=[];for(const{subject:r,object:n}of e.match(null,E.namedNode("http://www.w3.org/2000/10/swap/log#implies"),null,E.defaultGraph())){const i=[...e.match(null,null,null,r)],o=[...e.match(null,null,null,n)];t.push({premise:i,conclusion:o})}return t}class be{constructor(e){this._store=e}_add(e,t,r,n,i){this._store._addToIndex(n.subjects,e,t,r)&&(this._store._addToIndex(n.predicates,t,r,e),this._store._addToIndex(n.objects,r,e,t),i())}_evaluatePremise(e,t,r,n=0){let i,o,s,a,c;const[l,u,d]=e.premise[n].value,h=t[e.premise[n].content],f=!(s=l.value);for(s in f?h:{[s]:h[s]})if(a=h[s]){for(s in f&&(l.value=Number(s)),i=!(s=u.value),i?a:{[s]:a[s]})if(c=a[s]){for(s in i&&(u.value=Number(s)),o=!(s=d.value),o?c:{[s]:c[s]})o&&(d.value=Number(s)),n===e.premise.length-1?e.conclusion.forEach((e=>{this._add(e.subject.value,e.predicate.value,e.object.value,t,(()=>{r(e)}))})):this._evaluatePremise(e,t,r,n+1);o&&(d.value=null)}i&&(u.value=null)}f&&(l.value=null)}_evaluateRules(e,t,r){for(let n=0;n{r.push([e.subject.value,e.predicate.value,e.object.value,t])}))}const i=e=>{e.forEach((e=>{this._add(e.subject.value,e.predicate.value,e.object.value,t,(()=>{n(e)}))}))};let o;for(this._evaluateRules(e,t,n);void 0!==(o=r.pop());){const[e,r,s,a]=o,c=a.basePremise.subject.value;c||(a.basePremise.subject.value=e);const l=a.basePremise.predicate.value;l||(a.basePremise.predicate.value=r);const u=a.basePremise.object.value;u||(a.basePremise.object.value=s),0===a.premise.length?i(a.conclusion):this._evaluatePremise(a,t,n),c||(a.basePremise.subject.value=null),l||(a.basePremise.predicate.value=null),u||(a.basePremise.object.value=null)}}_createRule({premise:e,conclusion:t}){const r={},n=e=>"Variable"===e.termType?r[e.value]=r[e.value]||{}:{value:this._store._termToNewNumericId(e)},i=e=>({subject:n(e.subject),predicate:n(e.predicate),object:n(e.object)});return{premise:e.map((e=>i(e))),conclusion:t.map((e=>i(e))),variables:Object.values(r)}}reason(e){Array.isArray(e)||(e=ve(e)),e=e.map((e=>this._createRule(e)));for(const t of e)for(const r of e)for(let e=0;e{e.value=null}))}}for(const t of e){const e=new Set;t.premise=t.premise.map((t=>we(t,e)))}const t=this._store._getGraphs();for(const r in t)this._reasonGraphNaive(e,t[r]);this._store._size=null}}function we({subject:e,predicate:t,object:r},n){const i=e.value||n.has(e)||(n.add(e),!1),o=t.value||n.has(t)||(n.add(t),!1),s=r.value||n.has(r)||(n.add(r),!1);return!i&&o?{content:"predicates",value:[t,r,e]}:s?{content:"objects",value:[r,e,t]}:{content:"subjects",value:[e,t,r]}}function _e(e,t){return null===e.value&&(e.value=t.value),e.value===t.value}class Se extends ce.Transform{constructor(e){super({decodeStrings:!0}),this._readableState.objectMode=!0;const t=new H(e);let r,n;const i={onQuad:(e,t)=>{e&&this.emit("error",e)||t&&this.push(t)},onPrefix:(e,t)=>{this.emit("prefix",e,t)}};e&&e.comments&&(i.onComment=e=>{this.emit("comment",e)}),t.parse({on:(e,t)=>{switch(e){case"data":r=t;break;case"end":n=t}}},i),this._transform=(e,t,n)=>{r(e),n()},this._flush=e=>{n(),e()}}import(e){return e.on("data",(e=>{this.write(e)})),e.on("end",(()=>{this.end()})),e.on("error",(e=>{this.emit("error",e)})),this}}class Ee extends ce.Transform{constructor(e){super({encoding:"utf8",writableObjectMode:!0});const t=this._writer=new oe({write:(e,t,r)=>{this.push(e),r&&r()},end:e=>{this.push(null),e&&e()}},e);this._transform=(e,r,n)=>{t.addQuad(e,n)},this._flush=e=>{t.end(e)}}import(e){return e.on("data",(e=>{this.write(e)})),e.on("end",(()=>{this.end()})),e.on("error",(e=>{this.emit("error",e)})),e.on("prefix",((e,t)=>{this._writer.addPrefix(e,t)})),this}}var Ae={Lexer:m,Parser:H,Writer:oe,Store:pe,StoreFactory:me,EntityIndex:fe,StreamParser:Se,StreamWriter:Ee,Util:n,Reasoner:be,DataFactory:E,Term:A,NamedNode:R,Literal:I,BlankNode:T,Variable:x,DefaultGraph:P,Quad:O,Triple:O,termFromId:C,termToId:k}},5606:function(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 s(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 a,c=[],l=!1,u=-1;function d(){l&&a&&(l=!1,a.length?c=a.concat(c):u=-1,c.length&&h())}function h(){if(!l){var e=s(d);l=!0;for(var t=c.length;t;){for(a=c,c=[];++u1)for(var r=1;r(n||(n=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))},7793:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}: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(9931),t),i(r(8483),t),i(r(2142),t),i(r(2426),t),i(r(3988),t),i(r(6754),t),i(r(8401),t)},9931:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BlankNode=void 0,t.BlankNode=class{constructor(e){this.termType="BlankNode",this.value=e}equals(e){return!!e&&"BlankNode"===e.termType&&e.value===this.value}}},8483:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataFactory=void 0;const n=r(9931),i=r(2142),o=r(2426),s=r(3988),a=r(6754),c=r(8401);let l=0;t.DataFactory=class{constructor(e){this.blankNodeCounter=0,e=e||{},this.blankNodePrefix=e.blankNodePrefix||`df_${l++}_`}namedNode(e){return new s.NamedNode(e)}blankNode(e){return new n.BlankNode(e||`${this.blankNodePrefix}${this.blankNodeCounter++}`)}literal(e,t){return new o.Literal(e,t)}variable(e){return new c.Variable(e)}defaultGraph(){return i.DefaultGraph.INSTANCE}quad(e,t,r,n){return new a.Quad(e,t,r,n||this.defaultGraph())}fromTerm(e){switch(e.termType){case"NamedNode":return this.namedNode(e.value);case"BlankNode":return this.blankNode(e.value);case"Literal":return e.language?this.literal(e.value,e.language):e.datatype.equals(o.Literal.XSD_STRING)?this.literal(e.value):this.literal(e.value,this.fromTerm(e.datatype));case"Variable":return this.variable(e.value);case"DefaultGraph":return this.defaultGraph();case"Quad":return this.quad(this.fromTerm(e.subject),this.fromTerm(e.predicate),this.fromTerm(e.object),this.fromTerm(e.graph))}}fromQuad(e){return this.fromTerm(e)}resetBlankNodeCounter(){this.blankNodeCounter=0}}},2142:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultGraph=void 0;class r{constructor(){this.termType="DefaultGraph",this.value=""}equals(e){return!!e&&"DefaultGraph"===e.termType}}t.DefaultGraph=r,r.INSTANCE=new r},2426:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Literal=void 0;const n=r(3988);class i{constructor(e,t){this.termType="Literal",this.value=e,"string"==typeof t?(this.language=t,this.datatype=i.RDF_LANGUAGE_STRING):t?(this.language="",this.datatype=t):(this.language="",this.datatype=i.XSD_STRING)}equals(e){return!!e&&"Literal"===e.termType&&e.value===this.value&&e.language===this.language&&this.datatype.equals(e.datatype)}}t.Literal=i,i.RDF_LANGUAGE_STRING=new n.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),i.XSD_STRING=new n.NamedNode("http://www.w3.org/2001/XMLSchema#string")},3988:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NamedNode=void 0,t.NamedNode=class{constructor(e){this.termType="NamedNode",this.value=e}equals(e){return!!e&&"NamedNode"===e.termType&&e.value===this.value}}},6754:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Quad=void 0,t.Quad=class{constructor(e,t,r,n){this.termType="Quad",this.value="",this.subject=e,this.predicate=t,this.object=r,this.graph=n}equals(e){return!!e&&("Quad"===e.termType||!e.termType)&&this.subject.equals(e.subject)&&this.predicate.equals(e.predicate)&&this.object.equals(e.object)&&this.graph.equals(e.graph)}}},8401:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Variable=void 0,t.Variable=class{constructor(e){this.termType="Variable",this.value=e}equals(e){return!!e&&"Variable"===e.termType&&e.value===this.value}}},742:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}: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(4806),t)},4806:function(e,t){"use strict";function r(e){const t=[];let r=0;for(;re.join(""))).join("/")}function n(e,t){let n=t+1;t>=0?"/"===e[t+1]&&"/"===e[t+2]&&(n=t+3):"/"===e[0]&&"/"===e[1]&&(n=2);const i=e.indexOf("/",n);return i<0?e:e.substr(0,i)+r(e.substr(i))}function i(e){return!e||"#"===e||"?"===e||"/"===e}Object.defineProperty(t,"__esModule",{value:!0}),t.removeDotSegmentsOfPath=t.removeDotSegments=t.resolve=void 0,t.resolve=function(e,t){const i=(t=t||"").indexOf("#");if(i>0&&(t=t.substr(0,i)),!e.length){if(t.indexOf(":")<0)throw new Error(`Found invalid baseIRI '${t}' for value '${e}'`);return t}if(e.startsWith("?")){const r=t.indexOf("?");return r>0&&(t=t.substr(0,r)),t+e}if(e.startsWith("#"))return t+e;if(!t.length){const t=e.indexOf(":");if(t<0)throw new Error(`Found invalid relative IRI '${e}' for a missing baseIRI`);return n(e,t)}const o=e.indexOf(":");if(o>=0)return n(e,o);const s=t.indexOf(":");if(s<0)throw new Error(`Found invalid baseIRI '${t}' for value '${e}'`);const a=t.substr(0,s+1);if(0===e.indexOf("//"))return a+n(e,o);let c;if(t.indexOf("//",s)===s+1){if(c=t.indexOf("/",s+3),c<0)return t.length>s+3?t+"/"+n(e,o):a+n(e,o)}else if(c=t.indexOf("/",s+1),c<0)return a+n(e,o);if(0===e.indexOf("/"))return t.substr(0,c)+r(e);let l=t.substr(c);const u=l.lastIndexOf("/");return u>=0&&u({name:e,mode:this.scopeModeMap[e]})))}get scopeParameter(){return this.scopes.map((e=>`${this._scopeNameForParameter(e)}:${e.mode}`)).join(" ")}claim(e,t){if("string"!=typeof e||-1!==e.indexOf("/")||0===e.length)throw new Error("Scope should be a non-empty string without forward slashes");if(!t.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(e),this.scopeModeMap[e]=t}get(e){return this.scopeModeMap[e]}remove(e){const t={};for(const e in this.scopeModeMap)t[e]=this.scopeModeMap[e];this.reset(),delete t[e];for(const e in t)this.claim(e,t[e])}checkPermission(e,t){const r=this.get(e);return r&&("r"===t||"rw"===r)}checkPathPermission(e,t){if(this.checkPermission("*",t))return!0;const r=this._getModuleName(e);return!!this.checkPermission(r,t)}reset(){this.rootPaths=[],this.scopeModeMap={}}_getModuleName(e){if("/"!==e[0])throw new Error("Path should start with a slash");const t=e.replace(/^\/public/,"").match(/^\/([^/]*)\//);return t?t[1]:"*"}_adjustRootPaths(e){"*"in this.scopeModeMap||"*"===e?this.rootPaths=["/"]:e in this.scopeModeMap||(this.rootPaths.push("/"+e+"/"),this.rootPaths.push("/public/"+e+"/"))}_scopeNameForParameter(e){if("*"===e.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return e.name}setStorageType(e){this.storageType=e}}t.Access=r,t.default=r},3275:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Authorize=void 0;const o=i(r(3334)),s=r(7746),a=i(r(5503)),c=r(368);let l;function u(e){const t=e||d.getLocation().href,r={};for(const[e,n]of new URL(t).searchParams)r[e]=n;const n=t.indexOf("#");if(-1===n)return r;const i=t.substring(n+1);return i.includes("=")?i.split("&").reduce((function(e,t){const r=t.split("=");if("state"===r[0]&&r[1].match(/rsDiscovery/)){let t=decodeURIComponent(r[1]);const n=t.substr(t.indexOf("rsDiscovery=")).split("&")[0].split("=")[1];e.rsDiscovery=JSON.parse(atob(n)),t=t.replace(new RegExp("&?rsDiscovery="+n),""),t.length>0&&(e.state=t)}else e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]);return e}),r):r}class d{static authorize(e,t){if((0,o.default)("[Authorize] authURL = ",t.authURL,"scope = ",t.scope,"redirectUri = ",t.redirectUri,"clientId = ",t.clientId,"response_type =",t.response_type),!t.scope)throw new Error("Cannot authorize due to undefined or empty scope; did you forget to access.claim()?");if(!(0,s.localStorageAvailable)()&&"remotestorage"===e.backend){t.redirectUri+=t.redirectUri.indexOf("#")>0?"&":"#";const r={userAddress:e.remote.userAddress,href:e.remote.href,storageApi:e.remote.storageApi,properties:e.remote.properties};t.redirectUri+="rsDiscovery="+(0,s.toBase64)(JSON.stringify(r))}const r=function(e){const t=new URL(e.redirectUri);e.state||(e.state=t.hash?t.hash.substring(1):""),e.response_type||(e.response_type="token");const r=new URL(e.authURL);r.searchParams.set("redirect_uri",e.redirectUri.replace(/#.*$/,"")),r.searchParams.set("scope",e.scope),r.searchParams.set("client_id",e.clientId);for(const t of["state","response_type","code_challenge","code_challenge_method","token_access_type"]){const n=e[t];n&&r.searchParams.set(t,n)}return r.href}(t);s.globalContext.cordova?d.openWindow(r,t.redirectUri,"location=yes,clearsessioncache=yes,clearcache=yes").then((t=>{e.remote.configure({token:t.access_token})})):d.setLocation(r)}static refreshAccessToken(e,t,r){return n(this,void 0,void 0,(function*(){var e,n,i;yield t.configure({token:null,tokenType:null});const s=new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:r}),l=yield(0,c.requestWithTimeout)("POST",t.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString(),responseType:"json"});if(200!==(null==l?void 0:l.status))throw yield t.configure({refreshToken:null}),new a.default("refresh token rejected:"+JSON.stringify(l.response));{(0,o.default)(`[Authorize] access token good for ${null===(e=null==l?void 0:l.response)||void 0===e?void 0:e.expires_in} seconds`);const r={token:null===(n=null==l?void 0:l.response)||void 0===n?void 0:n.access_token,tokenType:null===(i=null==l?void 0:l.response)||void 0===i?void 0:i.token_type};if(!r.token)throw new Error(`no access_token in "successful" refresh: ${l.response}`);yield t.configure(r)}}))}static setLocation(e){if("string"==typeof e)document.location.href=e;else{if("object"!=typeof e)throw"Invalid location "+e;document.location=e}}static _rs_supported(){return"undefined"!=typeof document}static _rs_cleanup(e){e.removeEventListener("features-loaded",l)}}t.Authorize=d,d.IMPLIED_FAKE_TOKEN=!1,d.getLocation=function(){return document.location},d.openWindow=function(e,t,r){return new Promise(((n,i)=>{const o=open(e,"_blank",r);function s(){i("Authorization was canceled")}o&&!o.closed?(o.addEventListener("loadstart",(function(e){if(0!==e.url.indexOf(t))return;o.removeEventListener("exit",s),o.close();const r=u(e.url);r?n(r):i("Authorization error")})),o.addEventListener("exit",s)):i("Authorization popup was blocked")}))},d._rs_init=function(e){const t=u();let r;t&&(r=d.getLocation(),r.hash=""),l=function(){let i=!1;if(t){if(t.error)throw"access_denied"===t.error?new a.default("Authorization failed: access denied",{code:"access_denied"}):new a.default(`Authorization failed: ${t.error}`);t.rsDiscovery&&e.remote.configure(t.rsDiscovery),t.access_token&&(e.remote.configure({token:t.access_token}),i=!0),t.remotestorage&&(e.connect(t.remotestorage),i=!0),t.state&&(r=d.getLocation(),d.setLocation(r.href.split("#")[0]+"#"+t.state)),t.code&&(function(t){n(this,void 0,void 0,(function*(){var n,i,s,a;const l=sessionStorage.getItem("remotestorage:codeVerifier");if(!l)return void(0,o.default)("[Authorize] Ignoring OAuth code parameter, because no PKCE code verifier found in sessionStorage");r=d.getLocation();let u=r.origin;"/"!==r.pathname&&(u+=r.pathname);const h=new URLSearchParams({code:t,grant_type:"authorization_code",client_id:e.remote.clientId,redirect_uri:u,code_verifier:l}),f=yield(0,c.requestWithTimeout)("POST",e.remote.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:h.toString(),responseType:"json"});if(200===f.status){(0,o.default)(`[Authorize] access token good for ${null===(n=null==f?void 0:f.response)||void 0===n?void 0:n.expires_in} seconds`);const t={token:null===(i=null==f?void 0:f.response)||void 0===i?void 0:i.access_token,refreshToken:null===(s=null==f?void 0:f.response)||void 0===s?void 0:s.refresh_token,tokenType:null===(a=null==f?void 0:f.response)||void 0===a?void 0:a.token_type};t.token?e.remote.configure(t):e._emit("error",new Error(`no access_token in "successful" response: ${f.response}`)),sessionStorage.removeItem("remotestorage:codeVerifier")}else e._emit("error",new Error(`${f.statusText}: ${f.response}`))}))}(t.code),i=!0),i||e.remote.stopWaitingForToken()}else e.remote.stopWaitingForToken()},e.on("features-loaded",l)},t.default=d},6424:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClient=void 0;const o=i(r(439)),s=i(r(1613)),a=i(r(6491)),c=i(r(93)),l=i(r(7028)),u=r(7746);class d{constructor(e,t){if(this.schemas={configurable:!0,get(){return d.Types.inScope(this.moduleName)}},"/"!==t[t.length-1])throw"Not a folder: "+t;"/"===t&&(this.makePath=e=>("/"===e[0]?"":"/")+e),this.storage=e,this.base=t,this.moduleName=function(e){const t=e.split("/");return e.length>2?t[1]:"root"}(this.base),this.addEvents(["change"]),this.on=this.on.bind(this),e.onChange(this.base,this._fireChange.bind(this))}scope(e){return new d(this.storage,this.makePath(e))}getListing(e,t){return n(this,void 0,void 0,(function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then((e=>404===e.statusCode?{}:e.body))}))}getAll(e,t){return n(this,void 0,void 0,(function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then((r=>{if(404===r.statusCode)return{};if("object"==typeof r.body){const n=Object.keys(r.body);if(0===n.length)return{};const i=n.map((n=>this.storage.get(this.makePath(e+n),t).then((e=>{if("string"==typeof e.body)try{e.body=JSON.parse(e.body)}catch(e){}"object"==typeof e.body&&(r.body[n]=e.body)}))));return Promise.all(i).then((()=>r.body))}}))}))}getFile(e,t){return n(this,void 0,void 0,(function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(e),t).then((e=>({data:e.body,contentType:e.contentType,revision:e.revision})))}))}storeFile(e,t,r){return n(this,void 0,void 0,(function*(){return"string"!=typeof e?Promise.reject("Argument 'mimeType' of baseClient.storeFile must be a string"):"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof r&&"object"!=typeof r?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(t),r,e).then((e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode))))}))}getObject(e,t){return n(this,void 0,void 0,(function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(e),t).then((t=>{if("object"==typeof t.body)return t.body;if("string"==typeof t.body)try{return JSON.parse(t.body)}catch(t){throw new Error("Not valid JSON: "+this.makePath(e))}else if(void 0!==t.body&&200===t.statusCode)return Promise.reject("Not an object: "+this.makePath(e))}))}))}storeObject(e,t,r){return n(this,void 0,void 0,(function*(){if("string"!=typeof e)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof t)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!=typeof r)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(r,e);try{const e=this.validate(r);if(!e.valid)return Promise.reject(e)}catch(e){return Promise.reject(e)}return this.storage.put(this.makePath(t),JSON.stringify(r),"application/json; charset=UTF-8").then((e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)))}))}remove(e){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage.delete(this.makePath(e)))}getItemURL(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e=(0,u.cleanPath)(this.makePath(e)),this.storage.remote.href+e):void 0}cache(e,t="ALL"){if("string"!=typeof e)throw"Argument 'path' of baseClient.cache must be a string";if("string"!=typeof t)throw"Argument 'strategy' of baseClient.cache must be a string or undefined";if("FLUSH"!==t&&"SEEN"!==t&&"ALL"!==t)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(e),t),this}declareType(e,t,r){let n;if(r&&"string"==typeof t)n=t;else if(r||"string"==typeof t){if(!r&&"string"==typeof t)throw new Error("declareType() requires a JSON Schema object to be passed, in order to validate object types/formats")}else r=t,n=this._defaultTypeURI(e);d.Types.declare(this.moduleName,e,n,r)}validate(e){const t=d.Types.getSchema(e["@context"]);if(t)return o.default.validateResult(e,t);throw new a.default(e["@context"])}_defaultTypeURI(e){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(e)}_attachType(e,t){e["@context"]=d.Types.resolveAlias(this.moduleName+"/"+t)||this._defaultTypeURI(t)}makePath(e){return this.base+(e||"")}_fireChange(e){l.default.changeEvents[e.origin]&&(["new","old","lastCommon"].forEach((function(t){if((!e[t+"ContentType"]||/^application\/(.*)json(.*)/.exec(e[t+"ContentType"]))&&"string"==typeof e[t+"Value"])try{e[t+"Value"]=JSON.parse(e[t+"Value"])}catch(e){}})),this._emit("change",e))}static _rs_init(){}}t.BaseClient=d,d.Types=s.default,(0,u.applyMixins)(d,[c.default]),t.default=d},7285:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Caching=void 0;const i=r(7746),o=n(r(3334));class s{constructor(){this.pendingActivations=[],this.reset()}set(e,t){if("string"!=typeof e)throw new Error("path should be a string");if(!(0,i.isFolder)(e))throw new Error("path should be a folder");if(!t.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[e]=t,"ALL"===t&&(this.activateHandler?this.activateHandler(e):this.pendingActivations.push(e))}enable(e){this.set(e,"ALL")}disable(e){this.set(e,"FLUSH")}onActivate(e){(0,o.default)("[Caching] Setting activate handler",e,this.pendingActivations),this.activateHandler=e;for(let t=0;t{const i=l(n[e]);return u(n,t)?r(e):i?{statusCode:200,body:i.body||i.itemsMap,contentType:i.contentType}:{statusCode:404}})):this.getNodes([e]).then((t=>{const r=l(t[e]);if(r){if((0,c.isFolder)(e))for(const e in r.itemsMap)r.itemsMap.hasOwnProperty(e)&&!1===r.itemsMap[e]&&delete r.itemsMap[e];return{statusCode:200,body:r.body||r.itemsMap,contentType:r.contentType}}return{statusCode:404}}))}))}put(e,t,r){return n(this,void 0,void 0,(function*(){const n=(0,c.pathsFromRoot)(e);return this._updateNodes(n,(function(e,n){try{for(let i=0,o=e.length;i0)break}else console.error("Cannot delete non-existing node "+n)}return t}))}flush(e){return this._getAllDescendentPaths(e).then((e=>this.getNodes(e))).then((e=>{for(const t in e){const r=e[t];r&&r.common&&r.local&&this._emitChange({path:r.path,origin:"local",oldValue:!1===r.local.body?void 0:r.local.body,newValue:!1===r.common.body?void 0:r.common.body}),e[t]=void 0}return this.setNodes(e)}))}_emitChange(e){s.default.changeEvents[e.origin]&&this._emit("change",e)}fireInitial(){s.default.changeEvents.local&&this.forAllNodes((e=>{if((0,c.isDocument)(e.path)){const t=l(e);t&&this._emitChange({path:e.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:t.body,newContentType:t.contentType})}})).then((()=>{this._emit("local-events-done")}))}onDiff(e){this.diffHandler=e}migrate(e){return"object"!=typeof e||e.common||(e.common={},"string"==typeof e.path?"/"===e.path.substr(-1)&&"object"==typeof e.body&&(e.common.itemsMap=e.body):(e.local||(e.local={}),e.local.body=e.body,e.local.contentType=e.contentType)),e}_updateNodes(e,t){return new Promise(((r,n)=>{this._doUpdateNodes(e,t,{resolve:r,reject:n})}))}_doUpdateNodes(e,t,r){this._updateNodesRunning?this._updateNodesQueued.push({paths:e,cb:t,promise:r}):(this._updateNodesRunning=!0,this.getNodes(e).then((n=>{const i=(0,c.deepClone)(n),o=[];n=t(e,n);for(const e in n){const t=n[e];(0,c.equal)(t,i[e])?delete n[e]:(0,c.isDocument)(e)&&((0,c.equal)(t.local.body,t.local.previousBody)&&t.local.contentType===t.local.previousContentType||o.push({path:e,origin:"window",oldValue:t.local.previousBody,newValue:!1===t.local.body?void 0:t.local.body,oldContentType:t.local.previousContentType,newContentType:t.local.contentType}),delete t.local.previousBody,delete t.local.previousContentType)}this.setNodes(n).then((()=>{this._emitChangeEvents(o),r.resolve({statusCode:200})}))})).then((()=>Promise.resolve()),(e=>{r.reject(e)})).then((()=>{this._updateNodesRunning=!1;const e=this._updateNodesQueued.shift();e&&this._doUpdateNodes(e.paths,e.cb,e.promise)})))}_emitChangeEvents(e){for(let t=0,r=e.length;t{const r=[e],n=l(t[e]),i=Object.keys(n.itemsMap).map((t=>this._getAllDescendentPaths(e+t).then((e=>{for(let t=0,n=e.length;tr))})):Promise.resolve([e])}_getInternals(){return{getLatest:l,makeNode:d,isOutdated:u}}}(0,c.applyMixins)(f,[o.default]),e.exports=f},7028:function(e){"use strict";e.exports={cache:!0,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},cordovaRedirectUri:void 0,logging:!1,modules:[],backgroundSyncInterval:6e4,disableFeatures:[],discoveryTimeout:5e3,isBackground:!1,requestTimeout:3e4,syncInterval:1e4}},5373:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(4199)),o=n(r(7028)),s=n(r(3334)),a=r(7746);let c;const l="remotestorage:discover";let u={};const d=function(e){return new Promise(((t,r)=>{if(e in u)return t(u[e]);const n=new i.default({tls_only:!1,uri_fallback:!0,request_timeout:o.default.discoveryTimeout});return setTimeout((()=>r(new Error("timed out"))),o.default.discoveryTimeout),n.lookup(e,(function(n,i){if(n)return r(n);if("object"!=typeof i.idx.links.remotestorage||"number"!=typeof i.idx.links.remotestorage.length||i.idx.links.remotestorage.length<=0)return(0,s.default)("[Discover] WebFinger record for "+e+" does not have remotestorage defined in the links section ",JSON.stringify(i.json)),r("WebFinger record for "+e+" does not have remotestorage defined in the links section.");const o=i.idx.links.remotestorage[0],a=o.properties["http://tools.ietf.org/html/rfc6749#section-4.2"]||o.properties["auth-endpoint"],d=o.properties["http://remotestorage.io/spec/version"]||o.type;return u[e]={href:o.href,storageApi:d,authURL:a,properties:o.properties},c&&localStorage.setItem(l,JSON.stringify({cache:u})),t(u[e])}))}))};(d.DiscoveryError=function(e){this.name="DiscoveryError",this.message=e,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),d.DiscoveryError.prototype.constructor=d.DiscoveryError,d._rs_init=function(){if(c=(0,a.localStorageAvailable)(),c)try{const e=JSON.parse(localStorage[l]);u=e.cache}catch(e){}},d._rs_supported=function(){return Object.prototype.hasOwnProperty.call(a.globalContext,"fetch")||Object.prototype.hasOwnProperty.call(a.globalContext,"XMLHttpRequest")},d._rs_cleanup=function(){c&&delete localStorage[l]},e.exports=d},5706:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(6424)),a=i(r(6941)),c=i(r(6982)),l=i(r(5503)),u=r(7746),d=r(368),h=r(3684),f=i(r(3275));let p;const g="remotestorage:dropbox",y="https://api.dropboxapi.com/2/files/list_folder",m="https://api.dropboxapi.com/2/files/list_folder/continue",v="/remotestorage";function b(e){return(v+"/"+e).replace(/\/+$/,"").replace(/\/+/g,"/")}const w=/[\u007f-\uffff]/g;function _(e){return JSON.stringify(e).replace(w,(function(e){return"\\u"+("000"+e.charCodeAt(0).toString(16)).slice(-4)}))}function S(e,t){return new RegExp("^"+t.join("\\/")+"(\\/|$)").test(e.error_summary)}function E(e){return e instanceof ArrayBuffer||(0,d.isArrayBufferView)(e)}class A extends h.RemoteBase{constructor(e){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this._initialFetchDone=!1,this.addEvents(["connected","not-connected"]),this.clientId=e.apiKeys.dropbox.appKey,this.TOKEN_URL="https://api.dropboxapi.com/oauth2/token",this._revCache=new a.default("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},p=(0,u.localStorageAvailable)(),p){const e=(0,u.getJSONFromLocalStorage)(g);e&&this.configure(e),this._itemRefs=(0,u.getJSONFromLocalStorage)(`${g}:shares`)||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}connect(){return n(this,void 0,void 0,(function*(){try{if(this.rs.setBackend("dropbox"),this.token)T(this.rs);else{const{codeVerifier:e,codeChallenge:t,state:r}=yield(0,u.generateCodeVerifier)();sessionStorage.setItem("remotestorage:codeVerifier",e),sessionStorage.setItem("remotestorage:state",r),this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"account_info.read files.content.read files.content.write files.metadata.read files.metadata.write",clientId:this.clientId,response_type:"code",state:r,code_challenge:t,code_challenge_method:"S256",token_access_type:"offline"})}}catch(e){throw this.rs._emit("error",e),this.rs.setBackend(void 0),e}}))}configure(e){return n(this,void 0,void 0,(function*(){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token),void 0!==e.refreshToken&&(this.refreshToken=e.refreshToken),void 0!==e.tokenType&&(this.tokenType=e.tokenType);const t=()=>{p&&localStorage.setItem(g,JSON.stringify({userAddress:this.userAddress,token:this.token,refreshToken:this.refreshToken,tokenType:this.tokenType}))};if(this.refreshToken||this.token)if(this.connected=!0,this.userAddress)this._emit("connected"),t();else try{const e=yield this.info();this.userAddress=e.email,this._emit("connected"),t()}catch(e){this.connected=!1,this.rs._emit("error",new Error("Could not fetch user info.")),t.apply(this)}else(()=>{this.connected=!1,p&&localStorage.removeItem(g),this.rs.setBackend(void 0)})()}))}_getFolder(e){const t=this._revCache,r=r=>{let i;if(200!==r.status&&409!==r.status)return Promise.reject("Unexpected response status: "+r.status);try{i=JSON.parse(r.responseText)}catch(e){return Promise.reject(e)}if(409===r.status)return S(i,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+i.error_summary));const o=i.entries.reduce(((r,n)=>{try{const i="folder"===n[".tag"],o=n.path_display.split("/").slice(-1)[0]+(i?"/":"");if(i)r[o]={ETag:t.get(e+o)};else{const t=new Date(n.server_modified);r[o]={ETag:n.rev,"Content-Length":n.size,"Last-Modified":t.toUTCString()},this._revCache.set(e+o,n.rev)}}catch(t){console.error(`[Dropbox] folder “${e}” has entry ${JSON.stringify(n)}:`,t)}return r}),{});return i.has_more?n(i.cursor).then((function(e){return Object.assign(o,e)})):Promise.resolve(o)},n=e=>{const t={body:{cursor:e}};return this._request("POST",m,t).then(r)};return this._request("POST",y,{body:{path:b(e)}}).then(r).then((function(r){return Promise.resolve({statusCode:200,body:r,contentType:"application/json; charset=UTF-8",revision:t.get(e)})}))}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r=this._revCache.get(e);if(null===r)return Promise.resolve({statusCode:404});if(t&&t.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then((()=>this.get(e,t)));if(r&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===e.slice(-1))return this._getFolder(e);const n={headers:{"Dropbox-API-Arg":_({path:b(e)})},responseType:"arraybuffer"};return t&&t.ifNoneMatch&&(n.headers["If-None-Match"]=t.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",n).then((t=>{const r=t.status;let n,i,o,s;return 200!==r&&409!==r?Promise.resolve({statusCode:r}):(n=t.getResponseHeader("Dropbox-API-Result"),(0,u.getTextFromArrayBuffer)(t.response,"UTF-8").then((a=>{i=a,409===r&&(n=i);try{n=JSON.parse(n)}catch(e){return Promise.reject(e)}if(409===r)return S(n,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+e+'"): '+n.error_summary));if(o=t.getResponseHeader("Content-Type"),s=n.rev,this._revCache.set(e,s),this._shareIfNeeded(e),(0,u.shouldBeTreatedAsBinary)(a,o))i=t.response;else try{i=JSON.parse(i),o="application/json; charset=UTF-8"}catch(e){}return{statusCode:r,body:i,contentType:o,revision:s}})))}))}put(e,t,r){return n(this,arguments,void 0,(function*(e,t,r,n={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const i=this._revCache.get(e);if(n&&n.ifMatch&&i&&i!==n.ifMatch)return{statusCode:412,revision:i};if(n&&"*"===n.ifNoneMatch&&i&&"rev"!==i)return{statusCode:412,revision:i};if(!r.match(/charset=/)&&E(t)&&(r+="; charset=binary"),t.length>157286400)throw new Error("Cannot upload file larger than 150MB");const o={body:t,contentType:r,path:e};if(n&&(n.ifMatch||"*"===n.ifNoneMatch)){const t=yield this._getMetadata(e);if(n&&"*"===n.ifNoneMatch&&t)return{statusCode:412,revision:t.rev};if(n&&n.ifMatch&&t&&t.rev!==n.ifMatch)return{statusCode:412,revision:t.rev}}const s=yield this._uploadSimple(o);return this._shareIfNeeded(e),s}))}delete(e){return n(this,arguments,void 0,(function*(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const r=this._revCache.get(e);if((null==t?void 0:t.ifMatch)&&r&&t.ifMatch!==r)return{statusCode:412,revision:r};if(null==t?void 0:t.ifMatch){const r=yield this._getMetadata(e);if((null==t?void 0:t.ifMatch)&&r&&r.rev!==t.ifMatch)return{statusCode:412,revision:r.rev}}return this._deleteSimple(e)}))}_shareIfNeeded(e){if(e.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[e])return this.share(e)}share(e){const t={body:{path:b(e)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",t).then((t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status:"+t.status));let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?S(r,["shared_link_already_exists"])?this._getSharedLink(e):Promise.reject(new Error("API error: "+r.error_summary)):Promise.resolve(r.url)})).then((t=>(this._itemRefs[e]=t,p&&localStorage.setItem(g+":shares",JSON.stringify(this._itemRefs)),Promise.resolve(t))),(t=>(t.message='Sharing Dropbox file or folder ("'+e+'") failed: '+t.message,Promise.reject(t))))}info(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then((function(e){let t;try{const r=JSON.parse(e.responseText);t=null==r?void 0:r.email}catch(t){return Promise.reject(new Error("Could not query current account info: Invalid API response: "+e.responseText))}return Promise.resolve({email:t})}))}_request(e,t,r){return n(this,arguments,void 0,(function*(e,t,r,n=1){if(this.isForbiddenRequestMethod(e,t))throw`Don't use ${e} on directories!`;if(!this.token)throw new l.default("No access token");r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,"object"!=typeof r.body||E(r.body)||(r.body=JSON.stringify(r.body),r.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)});try{const i=yield(0,d.requestWithTimeout)(e,t,r);return this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),401===(null==i?void 0:i.status)&&this.refreshToken?n>=3?(console.error(`Abandoned after ${n} attempts: ${e} ${t}`),i):(this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)}),yield f.default.refreshAccessToken(this.rs,this,this.refreshToken),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),this._request(e,t,r,n+1)):[503,429].includes(null==i?void 0:i.status)?(this.online&&(this.online=!1,this.rs._emit("network-offline")),n>=3?(console.warn(`Abandoned after ${n} attempts: ${e} ${t}`),i):(yield new Promise((e=>setTimeout(e,(0,d.retryAfterMs)(i)))),this._request(e,t,r,n+1))):i}catch(r){throw this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!1}),r}}))}fetchDelta(...e){if(this._fetchDeltaPromise)return this._fetchDeltaPromise;const t=e=>n(this,void 0,void 0,(function*(){let r,n;"string"==typeof e?(r=m,n={cursor:e}):(r=y,n={path:v,recursive:!0,include_deleted:!0});try{const i=yield this._request("POST",r,{body:n});if(401===i.status)throw new l.default;if(200!==i.status&&409!==i.status)throw new Error("Invalid response status: "+i.status);let o;try{o=JSON.parse(i.responseText)}catch(e){throw new Error("Invalid response body: "+i.responseText)}if(409===i.status){if(!S(o,["path","not_found"]))throw new Error("API returned an error: "+o.error_summary);o={cursor:null,entries:[],has_more:!1}}if(e||this._revCache.deactivatePropagation(),o.entries.forEach((e=>{const t=e.path_display.slice(14);"deleted"===e[".tag"]?(this._revCache.delete(t),this._revCache.delete(t+"/")):"file"===e[".tag"]&&this._revCache.set(t,e.rev)})),this._fetchDeltaCursor=o.cursor,o.has_more)return t(o.cursor);this._revCache.activatePropagation(),this._initialFetchDone=!0}catch(e){if("timeout"===e)return;throw e}}));return this._fetchDeltaPromise=t(this._fetchDeltaCursor).catch((e=>("object"==typeof e&&"message"in e?e.message="Dropbox: fetchDelta: "+e.message:e=`Dropbox: fetchDelta: ${e}`,this.rs._emit("error",e),this._fetchDeltaPromise=null,Promise.reject(e)))).then((()=>(this._fetchDeltaPromise=null,Promise.resolve(e)))),this._fetchDeltaPromise}_getMetadata(e){const t={path:b(e)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:t}).then((e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?S(t,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve(t)})).then(void 0,(t=>(t.message='Could not load metadata for file or folder ("'+e+'"): '+t.message,Promise.reject(t))))}_uploadSimple(e){const t={path:b(e.path),mode:{".tag":"overwrite",update:void 0},mute:!0};return e.ifMatch&&(t.mode={".tag":"update",update:e.ifMatch}),this._request("POST","https://content.dropboxapi.com/2/files/upload",{body:e.body,headers:{"Content-Type":"application/octet-stream","Dropbox-API-Arg":_(t)}}).then((t=>{if(200!==t.status&&409!==t.status)return Promise.resolve({statusCode:t.status});let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid API result: "+t.responseText))}return 409===t.status?S(r,["path","conflict"])?this._getMetadata(e.path).then((function(e){return Promise.resolve({statusCode:412,revision:e.rev})})):(this.rs._emit("error",new Error(r.error_summary)),Promise.resolve({statusCode:t.status})):(this._revCache.set(e.path,r.rev),Promise.resolve({statusCode:t.status,revision:r.rev}))}))}_deleteSimple(e){const t={path:b(e)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:t}).then((e=>{if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}if(409===e.status){if(S(t,["path_lookup","not_found"]))return Promise.resolve({statusCode:404});this.rs._emit("error",new Error(t.error_summary))}return Promise.resolve({statusCode:e.status})})).then((t=>(200!==t.statusCode&&404!==t.statusCode||(this._revCache.delete(e),delete this._itemRefs[e]),Promise.resolve(t))),(t=>(t.message='Could not delete Dropbox file or folder ("'+e+'"): '+t.message,Promise.reject(t))))}_getSharedLink(e){return n(this,void 0,void 0,(function*(){const t={body:{path:b(e),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",t).then((e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status: "+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?Promise.reject(new Error("API error: "+(null==t?void 0:t.error_summary)||0)):t.links.length?Promise.resolve(t.links[0].url):Promise.reject(new Error("No links returned"))}),(t=>(t.message='Could not get link to a shared file or folder ("'+e+'"): '+t.message,Promise.reject(t))))}))}static _rs_init(e){p=(0,u.localStorageAvailable)(),e.apiKeys.dropbox&&(e.dropbox=new A(e)),"dropbox"===e.backend&&T(e)}static _rs_supported(){return!0}static _rs_cleanup(e){!function(e){(function(e){e._origRemote&&(e.remote=e._origRemote,delete e._origRemote)})(e),function(e){e._dropboxOrigSync&&(e.sync.sync=e._dropboxOrigSync,delete e._dropboxOrigSync)}(e),function(e){e._origBaseClientGetItemURL&&(s.default.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}(e),I(e)}(e),p&&localStorage.removeItem(g),e.setBackend(void 0)}}function R(e,...t){e._dropboxOrigSync||(e._dropboxOrigSync=e.sync.sync.bind(e.sync),e.sync.sync=function(){return this.dropbox.fetchDelta(e,...t).then(e._dropboxOrigSync,(function(t){e._emit("error",new c.default(t)),e._emit("sync-done")}))}.bind(e))}function I(e){e._dropboxOrigSyncCycle&&(e.syncCycle=e._dropboxOrigSyncCycle,delete e._dropboxOrigSyncCycle)}function T(e){!function(e){e._origRemote||(e._origRemote=e.remote,e.remote=e.dropbox)}(e),e.sync?R(e):function(e,...t){e._dropboxOrigSyncCycle||(e._dropboxOrigSyncCycle=e.syncCycle,e.syncCycle=()=>{if(!e.sync)throw new Error("expected sync to be initialized by now");R(e),e._dropboxOrigSyncCycle(e,...t),I(e)})}(e),function(e){e._origBaseClientGetItemURL||(e._origBaseClientGetItemURL=s.default.prototype.getItemURL,s.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(e)}(0,u.applyMixins)(A,[o.default]),e.exports=A},9451:function(e,t,r){"use strict";const n=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(93)),i=r(7746);class o{constructor(){this.addEvents(["background","foreground"]),this.mode="undefined"!=typeof window?"browser":"node","browser"===this.mode&&(this.setBrowserPrefixedNames(),document.addEventListener(this.visibilityChangeEvent,this.setVisibility.bind(this),!1),this.setVisibility())}setBrowserPrefixedNames(){"browser"===this.mode&&(void 0!==document.hidden?(this.hiddenProperty="hidden",this.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(this.hiddenProperty="mozHidden",this.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(this.hiddenProperty="msHidden",this.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(this.hiddenProperty="webkitHidden",this.visibilityChangeEvent="webkitvisibilitychange"))}setVisibility(){document[this.hiddenProperty]?this.goBackground():this.goForeground()}isBrowser(){return"browser"===this.mode}isNode(){return"node"===this.mode}goBackground(){this._emit("background")}goForeground(){this._emit("foreground")}static _rs_init(){}static _rs_cleanup(){}}(0,i.applyMixins)(o,[n.default]),e.exports=o},93:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.EventHandling=void 0;const i=n(r(3334));class o{addEvents(e){e.forEach((e=>this._addEvent(e)))}addEventListener(e,t){if("string"!=typeof e)throw new Error("Argument eventName should be a string");if("function"!=typeof t)throw new Error("Argument handler should be a function");(0,i.default)("[EventHandling] Adding event listener",e),this._validateEvent(e),this._handlers[e].push(t)}on(e,t){return this.addEventListener(e,t)}removeEventListener(e,t){this._validateEvent(e);const r=this._handlers[e].length;for(let n=0;n{e.apply(this,t)}))}_validateEvent(e){if(!(e in this._handlers))throw new Error("Unknown event: "+e)}_delegateEvent(e,t){t.on(e,(t=>{this._emit(e,t)}))}_addEvent(e){void 0===this._handlers&&(this._handlers={}),this._handlers[e]=[]}}t.EventHandling=o,t.default=o},6545:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(7028)),o=n(r(9451)),s=n(r(3334)),a=r(7746),c=n(r(1370)),l=n(r(2548)),u=n(r(3275)),d=n(r(5373)),h=n(r(6424)),f=n(r(1801)),p=n(r(5706)),g=n(r(6467)),y=n(r(600)),m=n(r(313)),v=n(r(7285)),b=n(r(8567)),w=n(r(7794)),_=n(r(8365)),S={features:[],featuresDone:0,readyFired:!1,loadFeatures(){this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:y.default,Dropbox:p.default,GoogleDrive:f.default,Solid:g.default,Access:l.default,Discover:d.default,Authorize:u.default,BaseClient:h.default,Env:o.default},i.default.cache&&(0,a.extend)(this.featureModules,{Caching:v.default,IndexedDB:b.default,LocalStorage:w.default,InMemoryStorage:_.default,Sync:m.default}),i.default.disableFeatures.forEach((e=>{this.featureModules[e]&&delete this.featureModules[e]})),this._allLoaded=!1;for(const e in this.featureModules)this.loadFeature(e)},hasFeature(e){for(let t=this.features.length-1;t>=0;t--)if(this.features[t].name===e)return this.features[t].supported;return!1},loadFeature(e){const t=this.featureModules[e],r=!t._rs_supported||t._rs_supported();(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initializing ...`),"object"==typeof r?r.then((()=>{this.featureSupported(e,!0),this.initFeature(e)}),(()=>{this.featureSupported(e,!1)})):"boolean"==typeof r?(this.featureSupported(e,r),r&&this.initFeature(e)):this.featureSupported(e,!1)},initFeature(e){const t=this.featureModules[e];let r;try{r=t._rs_init(this)}catch(t){return void this.featureFailed(e,t)}"object"==typeof r&&"function"==typeof r.then?r.then((()=>{this.featureInitialized(e)}),(t=>{this.featureFailed(e,t)})):this.featureInitialized(e)},featureFailed(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialization failed (${t})`),this.featureDone()},featureSupported(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}]${t?"":"not "} supported`),t||this.featureDone()},featureInitialized(e){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialized`),this.features.push({name:e,init:this.featureModules[e]._rs_init,supported:!0,cleanup:this.featureModules[e]._rs_cleanup}),this.featureDone()},featureDone(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule(){["IndexedDB","LocalStorage","InMemoryStorage"].some((e=>{if(this.features.some((t=>t.name===e)))return this.features.local=this.featureModules[e],!0}))},_fireReady(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(e){console.error("'ready' failed: ",e,e.stack),this._emit("error",e)}},featuresLoaded(){(0,s.default)("[RemoteStorage] All features loaded"),this._setCachingModule(),this.local=i.default.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(c.default,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",(()=>{this._fireReady(),this._emit("connected")})),this.remote.on("not-connected",(()=>{this._fireReady(),this._emit("not-connected")})),this.remote.connected&&(this._fireReady(),this._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(e){(0,a.logError)(e),this._emit("error",e)}this._processPending()},_collectCleanupFunctions(){this._cleanups=[];for(let e=0;e=r-this.maxAge?t.v:void 0}set(e,t){this._items[e]={v:t,t:(new Date).getTime()}}}class v extends c.RemoteBase{constructor(e,t){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this.addEvents(["connected","not-connected"]),this.clientId=t,this._fileIdCache=new m(300),h=(0,s.localStorageAvailable)(),h){const e=(0,s.getJSONFromLocalStorage)(u);e&&this.configure(e)}}configure(e){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);const t=function(){h&&localStorage.setItem(u,JSON.stringify({userAddress:this.userAddress,token:this.token}))},r=function(){this.connected=!1,delete this.token,h&&localStorage.removeItem(u)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),t.apply(this)):this.info().then((e=>{this.userAddress=e.user.emailAddress,this._emit("connected"),t.apply(this)})).catch((()=>{r.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))}))):r.apply(this)}connect(){this.rs.setBackend("googledrive"),this.rs.authorize({authURL:"https://accounts.google.com/o/oauth2/auth",scope:"https://www.googleapis.com/auth/drive",clientId:this.clientId})}get(e,t={}){return(0,s.isFolder)(e)?this._getFolder(y(e)):this._getFile(y(e),t)}put(e,t,r,n={}){const i=y(e);function o(e){if(e.status>=200&&e.status<300){const t=JSON.parse(e.responseText),r=this.stripQuotes(t.etag);return Promise.resolve({statusCode:200,contentType:t.mimeType,revision:r})}return 412===e.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+e.status+" ("+e.responseText+")")}return this._getFileId(i).then((e=>e?n&&"*"===n.ifNoneMatch?o({status:412}):this._updateFile(e,i,t,r,n).then(o):this._createFile(i,t,r).then(o)))}delete(e,t={}){const r=y(e);return this._getFileId(r).then((e=>e?this._getMeta(e).then((r=>{let n;return"object"==typeof r&&"string"==typeof r.etag&&(n=this.stripQuotes(r.etag)),t&&t.ifMatch&&t.ifMatch!==n?{statusCode:412,revision:n}:this._request("DELETE",l+"/drive/v2/files/"+e,{}).then((e=>200===e.status||204===e.status?{statusCode:200}:Promise.reject("Delete failed: "+e.status+" ("+e.responseText+")")))})):Promise.resolve({statusCode:200})))}info(){const e=l+"/drive/v2/about?fields=user";return this._request("GET",e,{}).then((function(e){try{const t=JSON.parse(e.responseText);return Promise.resolve(t)}catch(e){return Promise.reject(e)}}))}_updateFile(e,t,r,n,i){const o={mimeType:n},s={"Content-Type":"application/json; charset=UTF-8"};return i&&i.ifMatch&&(s["If-Match"]=this.addQuotes(i.ifMatch)),this._request("PUT",l+"/upload/drive/v2/files/"+e+"?uploadType=resumable",{body:JSON.stringify(o),headers:s}).then((e=>412===e.status?e:this._request("PUT",e.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(r):r})))}_createFile(e,t,r){return this._getParentId(e).then((n=>{const i={title:f(g(e)),mimeType:r,parents:[{kind:"drive#fileLink",id:n}]};return this._request("POST",l+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(i),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then((e=>this._request("POST",e.getResponseHeader("Location"),{body:r.match(/^application\/json/)?JSON.stringify(t):t})))}))}_getFile(e,t){return this._getFileId(e).then((e=>this._getMeta(e).then((e=>{let r;if("object"==typeof e&&"string"==typeof e.etag&&(r=this.stripQuotes(e.etag)),t&&t.ifNoneMatch&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304});if(!e.downloadUrl){if(!e.exportLinks||!e.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:e.mimeType,revision:r});e.mimeType+=";export=text/html",e.downloadUrl=e.exportLinks["text/html"]}return this._request("GET",e.downloadUrl,{responseType:"arraybuffer"}).then((t=>(0,s.getTextFromArrayBuffer)(t.response,"UTF-8").then((function(n){let i=n;if(e.mimeType.match(/^application\/json/))try{i=JSON.parse(i)}catch(e){}else(0,s.shouldBeTreatedAsBinary)(n,e.mimeType)&&(i=t.response);return{statusCode:200,body:i,contentType:e.mimeType,revision:r}}))))}))))}_getFolder(e){return this._getFileId(e).then((t=>{let r,n,i;if(!t)return Promise.resolve({statusCode:404});const o="'"+t+"' in parents";return this._request("GET",l+"/drive/v2/files?q="+encodeURIComponent(o)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title,labels)")+"&maxResults=1000&trashed=false",{}).then((t=>{var o;if(200!==t.status)return Promise.reject("request failed or something: "+t.status);try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject("non-JSON response from GoogleDrive")}i={};for(const t of r.items)(null===(o=t.labels)||void 0===o?void 0:o.trashed)||(n=this.stripQuotes(t.etag),t.mimeType===d?(this._fileIdCache.set(e+(0,s.cleanPath)(t.title)+"/",t.id),i[t.title+"/"]={ETag:n}):(this._fileIdCache.set(e+(0,s.cleanPath)(t.title),t.id),i[t.title]={ETag:n,"Content-Type":t.mimeType,"Content-Length":t.fileSize}));return Promise.resolve({statusCode:200,body:i,contentType:"application/json; charset=UTF-8",revision:void 0})}))}))}_getParentId(e){const t=p(e);return this._getFileId(t).then((e=>e?Promise.resolve(e):this._createFolder(t)))}_createFolder(e){return this._getParentId(e).then((t=>this._request("POST",l+"/drive/v2/files",{body:JSON.stringify({title:f(g(e)),mimeType:d,parents:[{id:t}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then((e=>{const t=JSON.parse(e.responseText);return Promise.resolve(t.id)}))))}_getFileId(e){let t;return"/"===e?Promise.resolve("root"):(t=this._fileIdCache.get(e))?Promise.resolve(t):this._getFolder(p(e)).then((()=>(t=this._fileIdCache.get(e),t?Promise.resolve(t):"/"===e.substr(-1)?this._createFolder(e).then((()=>this._getFileId(e))):Promise.resolve())))}_getMeta(e){return this._request("GET",l+"/drive/v2/files/"+e,{}).then((function(t){return 200===t.status?Promise.resolve(JSON.parse(t.responseText)):Promise.reject("request (getting metadata for "+e+") failed with status: "+t.status)}))}_request(e,t,r){return this.isForbiddenRequestMethod(e,t)?Promise.reject(`Don't use ${e} on directories!`):(r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:e,isFolder:(0,s.isFolder)(t)}),(0,a.requestWithTimeout)(e,t,r).then((r=>r&&401===r.status?void this.connect():(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!0}),Promise.resolve(r))),(r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!1}),Promise.reject(r)))))}static _rs_init(e){const t=e.apiKeys.googledrive;var r;t&&(e.googledrive=new v(e,t.clientId),"googledrive"===e.backend&&(e._origRemote=e.remote,e.remote=e.googledrive,(r=e)._origBaseClientGetItemURL||(r._origBaseClientGetItemURL=i.default.prototype.getItemURL,i.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(i.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}(0,s.applyMixins)(v,[o.default]),e.exports=v},8567:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(3496)),a=i(r(3334)),c=r(7746),l="remotestorage";let u;class d extends s.default{constructor(e){super(),this.addEvents(["change","local-events-done"]),this.db=e||u,this.db?(this.getsRunning=0,this.putsRunning=0,this.changesQueued={},this.changesRunning={},this.commitSlownessWarning=null):(0,a.default)("[IndexedDB] Failed to open DB")}getNodes(e){return n(this,void 0,void 0,(function*(){const t=[],r={};for(let n=0,i=e.length;n0?this.getNodesFromDb(t).then((function(e){for(const t in r)e[t]=r[t];return e})):Promise.resolve(r)}))}setNodes(e){return n(this,void 0,void 0,(function*(){for(const t in e)this.changesQueued[t]=e[t]||!1;return this.maybeFlush(),Promise.resolve()}))}maybeFlush(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=r.g.setInterval((function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")}),1e4))}flushChangesQueued(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))}getNodesFromDb(e){return new Promise(((t,r)=>{const n=this.db.transaction(["nodes"],"readonly"),i=n.objectStore("nodes"),o={};this.getsRunning++,e.map((e=>{i.get(e).onsuccess=t=>{o[e]=t.target.result}})),n.oncomplete=()=>{t(o),this.getsRunning--},n.onerror=n.onabort=()=>{r("get transaction error/abort"),this.getsRunning--}}))}setNodesInDb(e){return n(this,void 0,void 0,(function*(){return new Promise(((t,r)=>{const n=this.db.transaction(["nodes"],"readwrite"),i=n.objectStore("nodes"),o=(new Date).getTime();this.putsRunning++,(0,a.default)("[IndexedDB] Starting put",e,this.putsRunning);for(const t in e){const r=e[t];if("object"==typeof r)try{i.put(r)}catch(e){throw(0,a.default)("[IndexedDB] Error while putting",r,e),e}else try{i.delete(t)}catch(e){throw(0,a.default)("[IndexedDB] Error while removing",i,r,e),e}}n.oncomplete=()=>{this.putsRunning--,(0,a.default)("[IndexedDB] Finished put",e,this.putsRunning,(new Date).getTime()-o+"ms"),t()},n.onerror=()=>{this.putsRunning--,r("transaction error")},n.onabort=()=>{r("transaction abort"),this.putsRunning--}}))}))}reset(e){const t=this.db.name;this.db.close(),d.clean(this.db.name,(()=>{d.open(t,((t,r)=>{t?(0,a.default)("[IndexedDB] Error while resetting local storage",t):this.db=r,"function"==typeof e&&e(self)}))}))}forAllNodes(e){return n(this,void 0,void 0,(function*(){return new Promise((t=>{this.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=r=>{const n=r.target.result;n?(e(this.migrate(n.value)),n.continue()):t()}}))}))}closeDB(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}static open(e,t){const r=setTimeout((function(){t("timeout trying to open db")}),1e4);try{const n=indexedDB.open(e,2);n.onerror=function(){(0,a.default)("[IndexedDB] Opening DB failed",n),clearTimeout(r),t(n.error)},n.onupgradeneeded=function(e){const t=n.result;(0,a.default)("[IndexedDB] Upgrade: from ",e.oldVersion," to ",e.newVersion),1!==e.oldVersion&&((0,a.default)("[IndexedDB] Creating object store: nodes"),t.createObjectStore("nodes",{keyPath:"path"})),(0,a.default)("[IndexedDB] Creating object store: changes"),t.createObjectStore("changes",{keyPath:"path"})},n.onsuccess=function(){clearTimeout(r);const i=n.result;if(!i.objectStoreNames.contains("nodes")||!i.objectStoreNames.contains("changes"))return(0,a.default)("[IndexedDB] Missing object store. Resetting the database."),void d.clean(e,(function(){d.open(e,t)}));t(null,n.result)}}catch(n){(0,a.default)("[IndexedDB] Failed to open database: "+n),(0,a.default)("[IndexedDB] Resetting database and trying again."),clearTimeout(r),d.clean(e,(function(){d.open(e,t)}))}}static clean(e,t){const r=indexedDB.deleteDatabase(e);r.onsuccess=function(){(0,a.default)("[IndexedDB] Done removing DB"),t()},r.onerror=r.onabort=function(t){console.error('Failed to remove database "'+e+'"',t)}}static _rs_init(e){return new Promise(((t,r)=>{d.open(l,(function(n,i){n?r(n):(u=i,i.onerror=()=>{e._emit("error",n)},t())}))}))}static _rs_supported(){return new Promise(((e,t)=>{const r=(0,c.getGlobalContext)();let n=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(n=!0)),"indexedDB"in r&&!n)try{const r=indexedDB.open("rs-check");r.onerror=function(){t()},r.onsuccess=function(){r.result.close(),indexedDB.deleteDatabase("rs-check"),e()}}catch(e){t()}else t()}))}static _rs_cleanup(e){return new Promise((t=>{e.local&&e.local.closeDB(),d.clean(l,t)}))}diffHandler(){}}(0,c.applyMixins)(d,[o.default]),e.exports=d},8365:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(93)),o=n(r(3496)),s=r(7746);class a extends o.default{constructor(){super(),this._storage={},this.addEvents(["change","local-events-done"])}getNodes(e){const t={};for(let r=0,n=e.length;r{(0,s.default)("[LocalStorage] Removing",e),delete localStorage[e]}))}}(0,a.applyMixins)(u,[o.default]),e.exports=u},3334:function(e,t,r){"use strict";const n=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(7028));e.exports=function(...e){n.default.logging&&console.log(...e)}},3684:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteBase=void 0;const i=n(r(93)),o=r(7746);class s extends i.default{constructor(e){super(),this.rs=e,this.connected=!1}stopWaitingForToken(){this.connected||this._emit("not-connected")}addQuotes(e){return"string"!=typeof e?e:"*"===e?"*":'"'+e+'"'}stripQuotes(e){return"string"!=typeof e?e:e.replace(/^["']|["']$/g,"")}isForbiddenRequestMethod(e,t){return("PUT"===e||"DELETE"===e)&&(0,o.isFolder)(t)}}t.RemoteBase=s},423:function(e,t,r){"use strict";var n,i=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]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s=2e3&&e<=36e5}var x;!function(e){e.GOOGLE="googledrive",e.DROPBOX="dropbox"}(x||(x={}));class P{constructor(e){if(this._pending=[],this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this._init=S.default.loadFeatures,this.features=S.default.features,this.loadFeature=S.default.loadFeature,this.featureSupported=S.default.featureSupported,this.featureDone=S.default.featureDone,this.featuresDone=S.default.featuresDone,this.featuresLoaded=S.default.featuresLoaded,this.featureInitialized=S.default.featureInitialized,this.featureFailed=S.default.featureFailed,this.hasFeature=S.default.hasFeature,this._setCachingModule=S.default._setCachingModule,this._collectCleanupFunctions=S.default._collectCleanupFunctions,this._fireReady=S.default._fireReady,this.initFeature=S.default.initFeature,"object"==typeof e&&(0,u.extend)(c.default,e),this.addEvents(["ready","authing","connecting","pod-not-selected","connected","disconnected","not-connected","conflict","error","features-loaded","sync-interval-change","sync-req-done","sync-done","wire-busy","wire-done","network-offline","network-online"]),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")}),R=(0,u.localStorageAvailable)(),R){this.apiKeys=(0,u.getJSONFromLocalStorage)("remotestorage:api-keys")||{};const e=localStorage.getItem("remotestorage:backend");"dropbox"===e||"googledrive"===e||"solid"===e?this.setBackend(e):this.setBackend("remotestorage")}const t=this.on;this.on=function(e,r){if(this._allLoaded)switch(e){case"features-loaded":setTimeout(r,0);break;case"ready":this.remote&&setTimeout(r,0);break;case"connected":this.remote&&this.remote.connected&&setTimeout(r,0);break;case"not-connected":this.remote&&!this.remote.connected&&setTimeout(r,0);break;case"pod-not-selected":this.remote instanceof v.default&&this.remote.getPodURLs().length>0&&null===this.remote.getPodURL()&&setTimeout(r,0)}return t.call(this,e,r)},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this)),this.loadModules()}get connected(){return this.remote.connected}loadModules(){c.default.modules.forEach(this.addModule.bind(this))}authorize(e){if(this.access.setStorageType(this.remote.storageApi),void 0===e.scope&&(e.scope=this.access.scopeParameter),A.cordova)e.redirectUri=c.default.cordovaRedirectUri;else{const t=h.default.getLocation();let r=t.origin;"/"!==t.pathname&&(r+=t.pathname),e.redirectUri=r}void 0===e.clientId&&(e.clientId=e.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),h.default.authorize(this,e)}impliedauth(e,t){e=e||this.remote.storageApi,t=t||String(document.location),(0,l.default)("ImpliedAuth proceeding due to absent authURL; storageApi = "+e+" redirectUri = "+t),this.remote.configure({token:h.default.IMPLIED_FAKE_TOKEN}),document.location.href=t}connect(e,t){if(this.setBackend("remotestorage"),e.indexOf("@")<0&&!e.match(/^(https?:\/\/)?[^\s\/$\.?#]+\.[^\s]*$/))this._emit("error",new P.DiscoveryError("Not a valid user address or URL."));else{if(e.indexOf("@")<0&&!e.match(/^https?:\/\//)&&(e=`https://${e}`),A.cordova){if("string"!=typeof c.default.cordovaRedirectUri)return void this._emit("error",new P.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!A.cordova.InAppBrowser)return void this._emit("error",new P.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:e}),this._emit("connecting"),(0,b.default)(e).then((r=>{if(this._emit("authing"),r.userAddress=e,this.remote.configure(r),!this.remote.connected)if(r.authURL)if(void 0===t)this.authorize({authURL:r.authURL});else{if("string"!=typeof t)throw new Error("Supplied bearer token must be a string");(0,l.default)("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:t})}else this.impliedauth()}),(()=>{this._emit("error",new P.DiscoveryError("No storage information found for this user address."))}))}}reconnect(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()}disconnect(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")});const e=this._cleanups.length;let t=0;const r=()=>{t++,t>=e&&(this._init(),this._emit("disconnected"))};e>0?this._cleanups.forEach((e=>{const t=e(this);"object"==typeof t&&"function"==typeof t.then?t.then(r):r()})):r()}setBackend(e){this.backend=e,R&&(void 0!==e?localStorage.setItem("remotestorage:backend",e):localStorage.removeItem("remotestorage:backend"))}onChange(e,t){this._pathHandlers.change[e]||(this._pathHandlers.change[e]=[]),this._pathHandlers.change[e].push(t)}enableLog(){c.default.logging=!0}disableLog(){c.default.logging=!1}log(...e){l.default.apply(P,e)}setApiKeys(e){const t=[x.GOOGLE,x.DROPBOX];if("object"!=typeof e||!Object.keys(e).every((e=>t.includes(e))))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(e).forEach((t=>{const r=e[t];if(r){switch(t){case x.DROPBOX:this.apiKeys[x.DROPBOX]={appKey:r},void 0!==this.dropbox&&this.dropbox.clientId===r||m.default._rs_init(this);break;case x.GOOGLE:this.apiKeys[x.GOOGLE]={clientId:r},void 0!==this.googledrive&&this.googledrive.clientId===r||y.default._rs_init(this)}return!0}delete this.apiKeys[t]})),R&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))}setCordovaRedirectUri(e){if("string"!=typeof e||!e.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");c.default.cordovaRedirectUri=e}_setGPD(e,t){function r(e){return function(...r){return e.apply(t,r).then(I.bind(this))}}this.get=r(e.get),this.put=r(e.put),this.delete=r(e.delete)}_pendingGPD(e){return(...t)=>{const r=Array.prototype.slice.call(t);return new Promise(((t,n)=>{this._pending.push({method:e,args:r,promise:{resolve:t,reject:n}})}))}}_processPending(){this._pending.forEach((e=>{try{this[e.method](...e.args).then(e.promise.resolve,e.promise.reject)}catch(t){e.promise.reject(t)}})),this._pending=[]}_bindChange(e){e.on("change",this._dispatchEvent.bind(this,"change"))}_dispatchEvent(e,t){Object.keys(this._pathHandlers[e]).forEach((r=>{const n=r.length;t.path.substr(0,n)===r&&this._pathHandlers[e][r].forEach((e=>{const n={};for(const e in t)n[e]=t[e];n.relativePath=t.path.replace(new RegExp("^"+r),"");try{e(n)}catch(e){console.error("'change' handler failed: ",e,e.stack),this._emit("error",e)}}))}))}scope(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.scope must be a string";return this.access.checkPathPermission(e,"r")||console.warn("WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestoragejs.readthedocs.io/en/latest/js-api/access.html#claim"),new f.default(this,e)}getSyncInterval(){return c.default.syncInterval}setSyncInterval(e){if(!T(e))throw e+" is not a valid sync interval";const t=c.default.syncInterval;c.default.syncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getBackgroundSyncInterval(){return c.default.backgroundSyncInterval}setBackgroundSyncInterval(e){if(!T(e))throw e+" is not a valid sync interval";const t=c.default.backgroundSyncInterval;c.default.backgroundSyncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getCurrentSyncInterval(){return c.default.isBackground?c.default.backgroundSyncInterval:c.default.syncInterval}getRequestTimeout(){return c.default.requestTimeout}setRequestTimeout(e){if("number"!=typeof e)throw e+" is not a valid request timeout";c.default.requestTimeout=e}syncCycle(){this.sync&&!this.sync.stopped&&(this.on("sync-done",(()=>{this.sync&&!this.sync.stopped&&(this._syncTimer&&(clearTimeout(this._syncTimer),this._syncTimer=void 0),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))})),this.sync.sync())}startSync(){return c.default.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())}stopSync(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?this.sync.stopped=!0:this.syncStopped=!0}addModule(e){const t=e.name,r=e.builder;if(Object.defineProperty(this,t,{configurable:!0,get:function(){const e=this._loadModule(t,r);return Object.defineProperty(this,t,{value:e}),e}}),-1!==t.indexOf("-")){const e=t.replace(/\-[a-z]/g,(function(e){return e[1].toUpperCase()}));Object.defineProperty(this,e,{get:function(){return this[t]}})}}_loadModule(e,t){if(t)return t(new f.default(this,"/"+e+"/"),new f.default(this,"/public/"+e+"/")).exports;throw"Unknown module: "+e}}t.RemoteStorage=P,P.Authorize=h.default,P.SyncError=w.default,P.Unauthorized=_.default,P.DiscoveryError=b.default.DiscoveryError,P.util=E,Object.defineProperty(P.prototype,"access",{get:function(){const e=new d.default;return Object.defineProperty(this,"access",{value:e}),e},configurable:!0}),Object.defineProperty(P.prototype,"caching",{configurable:!0,get:function(){const e=new p.default;return Object.defineProperty(this,"caching",{value:e}),e}}),(0,u.applyMixins)(P,[g.EventHandling]),t.default=P},368:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isArrayBufferView=void 0,t.retryAfterMs=function(e){const t=1e3*parseInt(e.getResponseHeader("Retry-After"));return t>=1e3?t:Math.max(1500,Math.min(6e4,Math.round(s.default.syncInterval/(2.9+.2*Math.random()))))},t.requestWithTimeout=function(e,r,i){return n(this,void 0,void 0,(function*(){return"function"==typeof fetch?function(e,t,r){return n(this,void 0,void 0,(function*(){const n="function"==typeof AbortController?new AbortController:null;let i;const a=new Promise(((e,t)=>{i=setTimeout((()=>{n&&n.abort(),t("timeout")}),s.default.requestTimeout)}));let c;const l={},u=fetch(t,{method:e,headers:r.headers,body:r.body,signal:n?n.signal:void 0}).then((e=>{switch((0,o.default)("[requests fetch]",e),e.headers.forEach(((e,t)=>{l[t.toUpperCase()]=e})),c={readyState:4,status:e.status,statusText:e.statusText,response:void 0,getResponseHeader:e=>l[e.toUpperCase()]||null,responseType:r.responseType,responseURL:t},r.responseType){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json();case void 0:case"":case"text":return e.text();default:throw new Error("responseType 'document' is not currently supported using fetch")}})).then((e=>(c.response=e,r.responseType&&"text"!==r.responseType||(c.responseText=e),c))).finally((()=>{clearTimeout(i)}));return Promise.race([u,a])}))}(e,r,i):"function"==typeof XMLHttpRequest?function(e,r,i){return n(this,void 0,void 0,(function*(){return new Promise(((n,a)=>{(0,o.default)("[requests XHR]",e,r);let c=!1;const l=setTimeout((()=>{c=!0,a("timeout")}),s.default.requestTimeout),u=new XMLHttpRequest;if(u.open(e,r,!0),i.responseType&&(u.responseType=i.responseType),i.headers)for(const e in i.headers)u.setRequestHeader(e,i.headers[e]);u.onload=()=>{c||(clearTimeout(l),n(u))},u.onerror=e=>{c||(clearTimeout(l),a(e))};let d=i.body;"object"==typeof d&&!(0,t.isArrayBufferView)(d)&&d instanceof ArrayBuffer&&(d=new Uint8Array(d)),u.send(d)}))}))}(e,r,i):Promise.reject("[Requests] You need to add a polyfill for fetch or XMLHttpRequest")}))};const o=i(r(3334)),s=i(r(7028));if("function"==typeof(r.g||window).ArrayBufferView)t.isArrayBufferView=function(e){return e&&e instanceof(r.g||window).ArrayBufferView};else{const e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];t.isArrayBufferView=function(t){for(let r=0;r<8;r++)if(t instanceof e[r])return!0;return!1}}},6941:function(e){"use strict";e.exports=class{constructor(e){this._itemsRev={},this._storage={},this._canPropagate=!1,this.defaultValue=e,this.activatePropagation()}get(e){e=e.toLowerCase();let t=this._storage[e];return void 0===t&&(t=this.defaultValue,this._storage[e]=t),t}set(e,t){return e=e.toLowerCase(),this._storage[e]===t||(this._storage[e]=t,t||delete this._itemsRev[e],this._updateParentFolderItemRev(e,t),this._canPropagate&&this._propagate(e)),t}delete(e){return this.set(e,null)}deactivatePropagation(){return this._canPropagate=!1,!0}activatePropagation(){return this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0),!0}_hashCode(e){let t=0;if(0===e.length)return t;for(let r=0;r0&&(r=this._generateHash(e))}return this.set(e,r),r}}},6491:function(e){"use strict";class t extends Error{constructor(e){super();const t=new Error("Schema not found: "+e);return t.name="SchemaNotFound",t}}e.exports=t},6467:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=r(2452),s=r(4848),a=i(r(6424)),c=i(r(93)),l=r(7746),u=r(3684),d=i(r(7398)),h=i(r(8849)),f="remotestorage:solid";let p;class g extends u.RemoteBase{constructor(e){if(super(e),this.podURLs=null,this.online=!0,this.addEvents(["connected","not-connected","pod-not-selected"]),this.configStorage=new d.default(this),this.session=new o.Session({secureStorage:new o.InMemoryStorage,insecureStorage:this.configStorage},"any"),p=(0,l.localStorageAvailable)(),p){const e=(0,l.getJSONFromLocalStorage)(f);e&&this.configure(e)}}onConfigChanged(e){if(e){const t=JSON.parse(e);if(void 0!==t.clientSecret){let e=(0,l.getJSONFromLocalStorage)(f);return e||(e={}),e.href=this.authURL,e.properties={sessionProperties:t,podURL:this.selectedPodURL},this.sessionProperties=t,void localStorage.setItem(f,JSON.stringify(e))}}this.podURLs=null,localStorage.removeItem(f)}configure(e){if(void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.authURL=e.href),void 0!==e.properties){const t=e.properties;t?(void 0!==t.sessionProperties?this.sessionProperties=t.sessionProperties:this.sessionProperties=null,void 0!==t.podURL?this.selectedPodURL=t.podURL:this.selectedPodURL=null):(this.sessionProperties=null,this.selectedPodURL=null)}this.sessionProperties?(this.configStorage.setConfig(JSON.stringify(this.sessionProperties)),this.connected=this.session.info&&this.session.info.isLoggedIn,function(){p&&localStorage.setItem(f,JSON.stringify({userAddress:this.userAddress,href:this.authURL,properties:{sessionProperties:this.sessionProperties,podURL:this.selectedPodURL}}))}.apply(this)):function(){this.connected=!1,this.sessionProperties=null,this.podURLs=null,p&&localStorage.removeItem(f)}.apply(this)}setAuthURL(e){this.authURL=e}getPodURLs(){return this.podURLs}setPodURL(e){if(this.selectedPodURL!==e&&(this.selectedPodURL=e,this.session.info&&this.session.info.isLoggedIn))if(this.selectedPodURL){let e=(0,l.getJSONFromLocalStorage)(f);e||(e={}),e.userAddress=this.session.info.webId,e.href=this.authURL,e.properties={sessionProperties:this.sessionProperties,podURL:this.selectedPodURL},localStorage.setItem(f,JSON.stringify(e)),this.connected=!0,this._emit("connected")}else this.connected=!1,this.rs._emit("pod-not-selected")}getPodURL(){return this.selectedPodURL}connect(){this.rs.setBackend("solid"),this.authURL?this.session.login({oidcIssuer:this.authURL,redirectUrl:new URL("/",window.location.href).toString(),clientName:"Remote Storage"}):this.rs._emit("error",new Error("No authURL is configured."))}getSession(){return this.session.info&&this.session.info.isLoggedIn?this.session:null}getFileURL(e){return e.startsWith("/")&&(e=e.substring(1)),0===e.length&&(e="/"),this.selectedPodURL+e}get(e,t={}){const r=this.getFileURL(e);return"/"===e.slice(-1)?(0,s.getSolidDataset)(r,{fetch:this.session.fetch}).then((e=>{const t=(0,s.getContainedResourceUrlAll)(e).reduce(((t,n)=>{const i=n.substring(r.length);if("/"===i.slice(-1))t[i]={};else{const r=(0,s.getThing)(e,n);t[i]={"Content-Length":(0,s.getInteger)(r,"http://www.w3.org/ns/posix/stat#size"),"Last-Modified":(0,s.getDatetime)(r,"http://purl.org/dc/terms/modified").toUTCString()}}return t}),{});return Promise.resolve({statusCode:200,body:t,contentType:"application/json; charset=UTF-8"})})).catch((e=>e instanceof s.FetchError&&404===e.statusCode?Promise.resolve({statusCode:200,body:{},contentType:"application/json; charset=UTF-8"}):Promise.reject("Failed to get container: "+e.message))):(0,s.getFile)(r,{fetch:this.session.fetch}).then((e=>({statusCode:200,body:e,contentType:(0,s.getContentType)(e)}))).catch((e=>{const t=e.statusCode;return 401===t||403===t||404===t?{statusCode:t}:Promise.reject("Failed to get the file: "+e.message)}))}put(e,t,r,n={}){const i=this.getFileURL(e),o=this.session.fetch,a=function(){const e=function(e){if("object"==typeof e){if(e instanceof h.default)return e;if(e instanceof DataView)return new h.default([e],{type:"application/octet-stream"});if(e instanceof ArrayBuffer)return new h.default([new DataView(e)]);if(ArrayBuffer.isView(e))return new h.default([e],{type:"application/octet-stream"});if(e instanceof FormData)return new h.default([new URLSearchParams([JSON.parse(JSON.stringify(e.entries()))]).toString()],{type:"application/x-www-form-urlencoded"});if(e instanceof URLSearchParams)return new h.default([e.toString()],{type:"application/x-www-form-urlencoded"})}return"string"==typeof e?new h.default([e],{type:"plain/text"}):new h.default([JSON.stringify(e)],{type:"application/json"})}(t);return(0,s.overwriteFile)(i,e,{contentType:r,fetch:o}).then((e=>({statusCode:201}))).catch((e=>Promise.reject("PUT failed with status "+e.statusCode+" ("+e.message+")")))};return(0,s.getFile)(i,{fetch:o}).then((e=>n&&"*"===n.ifNoneMatch?{statusCode:412,revision:"conflict"}:a())).catch((e=>{const t=e.statusCode;return 404===t?a():Promise.reject("PUT failed with status "+t+" ("+e.message+")")}))}delete(e,t={}){const r=this.getFileURL(e);return(0,s.deleteFile)(r,{fetch:this.session.fetch}).then((()=>({statusCode:200}))).catch((e=>{const t=e.statusCode;return 404===t?{statusCode:200}:Promise.reject("DELETE failed with status "+t+" ("+e.message+")")}))}static _rs_init(e){const t=new g(e);var r;e.solid=t,"solid"===e.backend&&(e._origRemote=e.remote,e.remote=e.solid,(r=e)._origBaseClientGetItemURL||(r._origBaseClientGetItemURL=a.default.prototype.getItemURL,a.default.prototype.getItemURL=function(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e.startsWith("/")&&(e=e.substring(1)),this.selectedPodURL+(0,l.cleanPath)(e)):void 0}),(()=>{n(this,void 0,void 0,(function*(){const r=t.session;if(yield r.handleIncomingRedirect(),r.info.isLoggedIn){const n=r.info.webId;t.userAddress=n,t.selectedPodURL?t._emit("connected"):(t.podURLs=yield(0,s.getPodUrlAll)(n,{fetch:fetch}),e._emit("pod-not-selected"))}else t.sessionProperties&&t.connect()}))})())}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(a.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}(0,l.applyMixins)(g,[c.default]),e.exports=g},7398:function(e,t){"use strict";var r=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});class n{get storage(){return window.localStorage}get(e){return r(this,void 0,void 0,(function*(){return this.storage.getItem(e)||void 0}))}set(e,t){return r(this,void 0,void 0,(function*(){this.storage.setItem(e,t)}))}delete(e){return r(this,void 0,void 0,(function*(){this.storage.removeItem(e)}))}}t.default=class{constructor(e){this.browserStorage=new n,this.observer=e}isConfigKey(e){return e.startsWith("solidClientAuthenticationUser")}setConfig(e){this.config=e}get(e){return r(this,void 0,void 0,(function*(){if(this.isConfigKey(e))return this.config;this.browserStorage.get(e)}))}set(e,t){return r(this,void 0,void 0,(function*(){if(this.isConfigKey(e)){if(this.config){const e=JSON.parse(this.config),r=JSON.parse(t),n=Object.assign(Object.assign({},e),r);this.config=JSON.stringify(n)}else this.config=t;this.observer.onConfigChanged(this.config)}else this.browserStorage.set(e,t)}))}delete(e){return r(this,void 0,void 0,(function*(){this.isConfigKey(e)?(this.config=void 0,this.observer.onConfigChanged(this.config)):this.browserStorage.delete(e)}))}}},6982:function(e){"use strict";class t extends Error{constructor(e){super(),this.name="SyncError",this.message="Sync failed: ","string"==typeof e?this.message+=e:(this.message+=e.message,this.stack=e.stack,this.originalError=e)}}e.exports=t},313:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Sync=void 0;const o=i(r(7028)),s=i(r(9451)),a=i(r(93)),c=i(r(3334)),l=i(r(3275)),u=i(r(6982)),d=i(r(5503)),h=r(7746);let f,p;function g(e,t,r){return{action:e,path:t,promise:r}}function y(e,t){return e.common.revision!==t&&(!e.remote||e.remote.revision!==t)}function m(e){return e.common&&e.common.revision}class v{constructor(e){this._finishedTasks=[],this.rs=e,this._tasks={},this._running={},this._timeStarted={},this.numThreads=10,this.rs.local.onDiff((e=>{this.addTask(e),this.doTasks()})),this.rs.caching.onActivate((e=>{this.addTask(e),this.doTasks()})),this.addEvents(["done","req-done"])}now(){return(new Date).getTime()}queueGetRequest(e){return new Promise(((t,r)=>{this.rs.remote.connected?this.rs.remote.online?(this.addTask(e,function(){this.rs.local.get(e).then((e=>t(e)))}.bind(this)),this.doTasks()):r("cannot fulfill maxAge requirement - remote is not online"):r("cannot fulfill maxAge requirement - remote is not connected")}))}corruptServerItemsMap(e,t){if("object"!=typeof e||Array.isArray(e))return!0;for(const r in e){const n=e[r];if("object"!=typeof n)return!0;if("string"!=typeof n.ETag)return!0;if((0,h.isFolder)(r)){if(-1!==r.substring(0,r.length-1).indexOf("/"))return!0}else{if(-1!==r.indexOf("/"))return!0;if(t){if("string"!=typeof n["Content-Type"])return!0;if("number"!=typeof n["Content-Length"])return!0}}}return!1}corruptItemsMap(e){if("object"!=typeof e||Array.isArray(e))return!0;for(const t in e)if("boolean"!=typeof e[t])return!0;return!1}corruptRevision(e){return"object"!=typeof e||Array.isArray(e)||e.revision&&"string"!=typeof e.revision||e.body&&"string"!=typeof e.body&&"object"!=typeof e.body||e.contentType&&"string"!=typeof e.contentType||e.contentLength&&"number"!=typeof e.contentLength||e.timestamp&&"number"!=typeof e.timestamp||e.itemsMap&&this.corruptItemsMap(e.itemsMap)}isCorrupt(e){return"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.path||this.corruptRevision(e.common)||e.local&&this.corruptRevision(e.local)||e.remote&&this.corruptRevision(e.remote)||e.push&&this.corruptRevision(e.push)}hasTasks(){return Object.getOwnPropertyNames(this._tasks).length>0}collectDiffTasks(){return n(this,void 0,void 0,(function*(){let e=0;return this.rs.local.forAllNodes((t=>{e>100||(this.isCorrupt(t)?((0,c.default)("[Sync] WARNING: corrupt node in local cache",t),"object"==typeof t&&t.path&&(this.addTask(t.path),e++)):(this.needsFetch(t)&&this.rs.access.checkPathPermission(t.path,"r")||(0,h.isDocument)(t.path)&&this.needsPush(t)&&this.rs.access.checkPathPermission(t.path,"rw"))&&(this.addTask(t.path),e++))})).then((()=>e)).catch((e=>{throw e}))}))}inConflict(e){return e.local&&e.remote&&(void 0!==e.remote.body||e.remote.itemsMap)}needsRefresh(e){return!!e.common&&(!e.common.timestamp||this.now()-e.common.timestamp>o.default.syncInterval)}needsFetch(e){return!!this.inConflict(e)||!(!e.common||void 0!==e.common.itemsMap||void 0!==e.common.body)||!(!e.remote||void 0!==e.remote.itemsMap||void 0!==e.remote.body)}needsPush(e){return!this.inConflict(e)&&(!(!e.local||e.push)||void 0)}needsRemotePut(e){return e.local&&e.local.body}needsRemoteDelete(e){return e.local&&!1===e.local.body}getParentPath(e){const t=e.match(/^(.*\/)([^\/]+\/?)$/);if(t)return t[1];throw new Error('Not a valid path: "'+e+'"')}deleteChildPathsFromTasks(){for(const e in this._tasks){const t=(0,h.pathsFromRoot)(e);for(let r=1;r{let t;if(this.needsRefresh(e)){try{t=this.getParentPath(e.path)}catch(e){}t&&this.rs.access.checkPathPermission(t,"r")?this.addTask(t):this.rs.access.checkPathPermission(e.path,"r")&&this.addTask(e.path)}})).then((()=>this.deleteChildPathsFromTasks())).catch((e=>{throw e}))}))}flush(e){for(const t in e)"FLUSH"===this.rs.caching.checkPath(t)&&e[t]&&!e[t].local&&((0,c.default)("[Sync] Flushing",t),e[t]=void 0);return e}doTask(e){return this.rs.local.getNodes([e]).then((t=>{const r=t[e];return void 0===r||function(e){return e.remote&&e.remote.revision&&!e.remote.itemsMap&&!e.remote.body}(r)?g("get",e,this.rs.remote.get(e)):this.needsRemotePut(r)?(r.push=(0,h.deepClone)(r.local),r.push.timestamp=this.now(),this.rs.local.setNodes(this.flush(t)).then((()=>{let t;return t=m(r)?{ifMatch:r.common.revision}:{ifNoneMatch:"*"},g("put",e,this.rs.remote.put(e,r.push.body,r.push.contentType,t))}))):this.needsRemoteDelete(r)?(r.push={body:!1,timestamp:this.now()},this.rs.local.setNodes(this.flush(t)).then((()=>m(r)?g("delete",e,this.rs.remote.delete(e,{ifMatch:r.common.revision})):g("get",e,this.rs.remote.get(e))))):m(r)?g("get",e,this.rs.remote.get(e,{ifNoneMatch:r.common.revision})):g("get",e,this.rs.remote.get(e))}))}autoMergeFolder(e){if(e.remote.itemsMap&&(e.common=e.remote,delete e.remote,e.common.itemsMap)){for(const t in e.common.itemsMap)e.local.itemsMap[t]||(e.local.itemsMap[t]=!1);(0,h.equal)(e.local.itemsMap,e.common.itemsMap)&&delete e.local}return e}autoMergeDocument(e){return function(e){return(!e.remote||!e.remote.revision||e.remote.revision===e.common.revision)&&(void 0===e.common.body&&!1===e.remote.body||e.remote.body===e.common.body&&e.remote.contentType===e.common.contentType)}(e)?delete(e=function(e){return e.remote&&!1===e.remote.body&&e.local&&!1===e.local.body&&delete e.local,e}(e)).remote:void 0!==e.remote.body&&((0,c.default)("[Sync] Emitting keep/revert"),this.rs.local._emitChange({origin:"conflict",path:e.path,oldValue:e.local.body,newValue:e.remote.body,lastCommonValue:e.common.body,oldContentType:e.local.contentType,newContentType:e.remote.contentType,lastCommonContentType:e.common.contentType}),e.remote.body?e.common=e.remote:e.common={},delete e.remote,delete e.local),e}autoMerge(e){if(e.remote){if(e.local)return(0,h.isFolder)(e.path)?this.autoMergeFolder(e):this.autoMergeDocument(e);if((0,h.isFolder)(e.path))void 0!==e.remote.itemsMap&&(e.common=e.remote,delete e.remote);else if(void 0!==e.remote.body){const t={origin:"remote",path:e.path,oldValue:!1===e.common.body?void 0:e.common.body,newValue:!1===e.remote.body?void 0:e.remote.body,oldContentType:e.common.contentType,newContentType:e.remote.contentType};if((t.oldValue||t.newValue)&&this.rs.local._emitChange(t),!e.remote.body)return;e.common=e.remote,delete e.remote}return e}e.common.body&&this.rs.local._emitChange({origin:"remote",path:e.path,oldValue:e.common.body,newValue:void 0,oldContentType:e.common.contentType,newContentType:void 0})}updateCommonTimestamp(e,t){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then((r=>(r[e]&&r[e].common&&r[e].common.revision===t&&(r[e].common.timestamp=this.now()),this.rs.local.setNodes(this.flush(r)))))}))}markChildren(e,t,r,i){return n(this,void 0,void 0,(function*(){const n=[],o={},s={};for(const r in t)n.push(e+r),o[e+r]=t[r];for(const t in i)n.push(e+t);return this.rs.local.getNodes(n).then((t=>{let n,a;for(const c in t)if(a=t[c],o[c])a&&a.common?y(a,o[c].ETag)&&(r[c]=(0,h.deepClone)(a),r[c].remote={revision:o[c].ETag,timestamp:this.now()},r[c]=this.autoMerge(r[c])):(n=this.rs.caching.checkPath(c),"ALL"===n&&(r[c]={path:c,common:{timestamp:this.now()},remote:{revision:o[c].ETag,timestamp:this.now()}})),r[c]&&o[c]["Content-Type"]&&(r[c].remote.contentType=o[c]["Content-Type"]),r[c]&&o[c]["Content-Length"]&&(r[c].remote.contentLength=o[c]["Content-Length"]);else if(i[c.substring(e.length)]&&a&&a.common){if(a.common.itemsMap)for(const e in a.common.itemsMap)s[c+e]=!0;if(a.local&&a.local.itemsMap)for(const e in a.local.itemsMap)s[c+e]=!0;if(a.remote||(0,h.isFolder)(c))r[c]=void 0;else if(r[c]=this.autoMerge(a),void 0===r[c]){const t=this.getParentPath(c),n=r[t],i=c.substring(e.length);n&&n.local&&(delete n.local.itemsMap[i],(0,h.equal)(n.local.itemsMap,n.common.itemsMap)&&delete n.local)}}return this.deleteRemoteTrees(Object.keys(s),r).then((e=>this.rs.local.setNodes(this.flush(e))))}))}))}deleteRemoteTrees(e,t){return n(this,void 0,void 0,(function*(){return 0===e.length?Promise.resolve(t):this.rs.local.getNodes(e).then((e=>n(this,void 0,void 0,(function*(){const r={};function n(e,t){if(e&&e.itemsMap)for(const n in e.itemsMap)r[t+n]=!0}for(const r in e){const i=e[r];i&&((0,h.isFolder)(r)?(n(i.common,r),n(i.local,r)):i.common&&void 0!==typeof i.common.body&&(t[r]=(0,h.deepClone)(i),t[r].remote={body:!1,timestamp:this.now()},t[r]=this.autoMerge(t[r])))}return this.deleteRemoteTrees(Object.keys(r),t).then((e=>this.rs.local.setNodes(this.flush(e))))}))))}))}completeFetch(e,t,r,i){return n(this,void 0,void 0,(function*(){let n,o;const s=(0,h.pathsFromRoot)(e);return(0,h.isFolder)(e)?n=[e]:(o=s[1],n=[e,o]),this.rs.local.getNodes(n).then((n=>{let s,a,c=n[e];const l={};function u(e){if(e&&e.itemsMap)for(s in e.itemsMap)t[s]||(l[s]=!0)}if("object"==typeof c&&c.path===e&&"object"==typeof c.common||(c={path:e,common:{}},n[e]=c),c.remote={revision:i,timestamp:this.now()},(0,h.isFolder)(e))for(s in u(c.common),u(c.remote),c.remote.itemsMap={},t)c.remote.itemsMap[s]=!0;else c.remote.body=t,c.remote.contentType=r,a=n[o],a&&a.local&&a.local.itemsMap&&(s=e.substring(o.length),a.local.itemsMap[s]=!0,(0,h.equal)(a.local.itemsMap,a.common.itemsMap)&&delete a.local);return n[e]=this.autoMerge(c),{toBeSaved:n,missingChildren:l}}))}))}completePush(e,t,r,i){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then((n=>{const o=n[e];if(!o.push)throw this.stopped=!0,new Error("completePush called but no push version!");return r?((0,c.default)("[Sync] We have a conflict"),o.remote&&o.remote.revision===i||(o.remote={revision:i||"conflict",timestamp:this.now()},delete o.push),n[e]=this.autoMerge(o)):(o.common={revision:i,timestamp:this.now()},"put"===t?(o.common.body=o.push.body,o.common.contentType=o.push.contentType,(0,h.equal)(o.local.body,o.push.body)&&o.local.contentType===o.push.contentType&&delete o.local,delete o.push):"delete"===t&&(!1===o.local.body?n[e]=void 0:delete o.push)),this.rs.local.setNodes(this.flush(n))}))}))}dealWithFailure(e){return n(this,void 0,void 0,(function*(){return this.rs.local.getNodes([e]).then((t=>{if(t[e])return delete t[e].push,this.rs.local.setNodes(this.flush(t))}))}))}interpretStatus(e){const t={statusCode:e,successful:void 0,conflict:void 0,unAuth:void 0,notFound:void 0,changed:void 0,networkProblems:void 0};if("string"==typeof e&&("offline"===e||"timeout"===e))return t.successful=!1,t.networkProblems=!0,t;if("number"==typeof e){const r=Math.floor(e/100);return t.successful=2===r||304===e||412===e||404===e,t.conflict=412===e,t.unAuth=401===e&&this.rs.remote.token!==l.default.IMPLIED_FAKE_TOKEN||402===e||403===e,t.notFound=404===e,t.changed=304!==e,t}}handleGetResponse(e,t,r,i,o){return n(this,void 0,void 0,(function*(){return t.notFound&&(r=!!(0,h.isFolder)(e)&&{}),t.changed?this.completeFetch(e,r,i,o).then((t=>(0,h.isFolder)(e)?this.corruptServerItemsMap(r)?((0,c.default)("[Sync] WARNING: Discarding corrupt folder description from server for "+e),!1):this.markChildren(e,r,t.toBeSaved,t.missingChildren).then((()=>!0)):this.rs.local.setNodes(this.flush(t.toBeSaved)).then((()=>!0)))):this.updateCommonTimestamp(e,o).then((()=>!0))}))}handleResponse(e,t,r){const n=this.interpretStatus(r.statusCode);if(n.successful){if("get"===t)return this.handleGetResponse(e,n,r.body,r.contentType,r.revision);if("put"===t||"delete"===t)return this.completePush(e,t,n.conflict,r.revision).then((function(){return!0}));throw new Error(`cannot handle response for unknown action ${t}`)}{let t;return t=n.unAuth?new d.default:n.networkProblems?new u.default("Network request failed."):new Error("HTTP response code "+n.statusCode+" received."),this.dealWithFailure(e).then((()=>{throw this.rs._emit("error",t),t}))}}finishTask(e,t=!0){if(void 0!==e.action){if(!(t&&((0,c.default)("[Sync] queue finished task:",e.path),this._finishedTasks.push(e),this._finishedTasks.length>1)))return(0,c.default)("[Sync] run task:",e.path),e.promise.then((t=>this.handleResponse(e.path,e.action,t)),(t=>((0,c.default)("[Sync] wireclient rejects its promise!",e.path,e.action,t),this.handleResponse(e.path,e.action,{statusCode:"offline"})))).then((t=>n(this,void 0,void 0,(function*(){if(this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],t&&this._tasks[e.path]){for(let t=0;t0?this.finishTask(this._finishedTasks[0],!1):yield this.collectTasks(!1).then((()=>{!this.hasTasks()||this.stopped?((0,c.default)("[Sync] Sync is done! Reschedule?",Object.getOwnPropertyNames(this._tasks).length,this.stopped),this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!0}))):setTimeout((()=>{this.doTasks()}),10)}))}))),(t=>{(0,c.default)("[Sync] Error",t),this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],this.rs._emit("sync-req-done",{tasksRemaining:Object.keys(this._tasks).length}),this._finishedTasks.length>0?this.finishTask(this._finishedTasks[0],!1):this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!1}))}));(0,c.default)("[Sync] delaying finished task:",e.path)}else delete this._running[e.path]}doTasks(){let e,t,r=0;e=this.rs.remote.connected?this.rs.remote.online?this.numThreads:1:0;const n=e-Object.getOwnPropertyNames(this._running).length;if(n<=0)return!0;for(t in this._tasks)if(!this._running[t]&&(this._timeStarted[t]=this.now(),this._running[t]=this.doTask(t),this._running[t].then(this.finishTask.bind(this)),r++,r>=n))return!0;return r>=n}collectTasks(e){return n(this,void 0,void 0,(function*(){return this.hasTasks()||this.stopped?Promise.resolve():this.collectDiffTasks().then((t=>t||!1===e?Promise.resolve():this.collectRefreshTasks()),(function(e){throw e}))}))}addTask(e,t){this._tasks[e]||(this._tasks[e]=[]),"function"==typeof t&&this._tasks[e].push(t)}sync(){return this.done=!1,this.doTasks()?Promise.resolve():this.collectTasks().then((()=>{try{this.doTasks()}catch(e){(0,c.default)("[Sync] doTasks error",e)}}),(function(e){throw(0,c.default)("[Sync] Sync error",e),new Error("Local cache unavailable")}))}static _rs_init(e){f=function(){(0,c.default)("[Sync] syncCycleCb calling syncCycle");const t=new s.default;t.isBrowser()&&function(e,t){function r(e){const r=t.getCurrentSyncInterval();o.default.isBackground=!e;const n=t.getCurrentSyncInterval();t._emit("sync-interval-change",{oldValue:r,newValue:n})}e.on("background",(()=>r(!1))),e.on("foreground",(()=>r(!0)))}(t,e),e.sync||(e.sync=new v(e),e.syncStopped&&((0,c.default)("[Sync] Instantiating sync stopped"),e.sync.stopped=!0,delete e.syncStopped)),(0,c.default)("[Sync] syncCycleCb calling syncCycle"),e.syncCycle()},p=function(){e.removeEventListener("connected",p),e.startSync()},e.on("ready",f),e.on("connected",p)}static _rs_cleanup(e){e.stopSync(),e.removeEventListener("ready",f),e.removeEventListener("connected",p),e.sync=void 0,delete e.sync}}t.Sync=v,(0,h.applyMixins)(v,[a.default]),t.default=v},1370:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))};const i=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(3334));function o(e){return"dropbox"===this.backend&&!!e.match(/^\/public\/.*[^\/]$/)}const s={get:function(e,t){if(this.local){if(void 0===t)t="object"==typeof(r=this).remote&&r.remote.connected&&r.remote.online?2*r.getSyncInterval():((0,i.default)("Not setting default maxAge, because remote is offline or not connected"),!1);else if("number"!=typeof t&&!1!==t)return Promise.reject("Argument 'maxAge' must be 'false' or a number");return this.local.get(e,t,this.sync.queueGetRequest.bind(this.sync))}return this.remote.get(e);var r},put:function(e,t,r){return o.bind(this)(e)?s._wrapBusyDone.call(this,this.remote.put(e,t,r)):this.local?this.local.put(e,t,r):s._wrapBusyDone.call(this,this.remote.put(e,t,r))},delete:function(e){return this.local?this.local.delete(e):s._wrapBusyDone.call(this,this.remote.delete(e))},_wrapBusyDone:function(e){return n(this,void 0,void 0,(function*(){return this._emit("wire-busy"),e.then((e=>(this._emit("wire-done",{success:!0}),Promise.resolve(e))),(e=>(this._emit("wire-done",{success:!1}),Promise.reject(e))))}))}};e.exports=s},1613:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClientTypes=void 0;class r{constructor(){this.uris={},this.schemas={},this.aliases={}}declare(e,t,r,n){const i=e+"/"+t;if(n.extends){const t=n.extends.split("/"),r=1===t.length?e+"/"+t.shift():t.join("/"),o=this.uris[r];if(!o)throw"Type '"+i+"' tries to extend unknown schema '"+r+"'";n.extends=this.schemas[o]}this.uris[i]=r,this.aliases[r]=i,this.schemas[r]=n}resolveAlias(e){return this.uris[e]}getSchema(e){return this.schemas[e]}inScope(e){const t=e.length,r={};for(const n in this.uris)if(n.substr(0,t+1)===e+"/"){const e=this.uris[n];r[e]=this.schemas[e]}return r}}t.BaseClientTypes=r;const n=new r;t.default=n},5503:function(e){"use strict";class t extends Error{constructor(e,t={}){super(),this.name="Unauthorized",this.message=void 0===e?"App authorization expired or revoked.":e,void 0!==t.code&&(this.code=t.code),this.stack=(new Error).stack}}e.exports=t},7746:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))};function i(e,t){if("object"==typeof e&&!Array.isArray(e)&&null!==e)for(const r in e)if("object"==typeof e[r]&&null!==e[r])if("[object ArrayBuffer]"===e[r].toString()){t[r]=new ArrayBuffer(e[r].byteLength);const n=new Int8Array(e[r]);new Int8Array(t[r]).set(n)}else i(e[r],t[r])}Object.defineProperty(t,"__esModule",{value:!0}),t.toBase64=t.getTextFromArrayBuffer=t.shouldBeTreatedAsBinary=t.getJSONFromLocalStorage=t.localStorageAvailable=t.pathsFromRoot=t.deepClone=t.equal=t.bindAll=t.cleanPath=t.baseName=t.isDocument=t.isFolder=t.containingFolder=t.extend=t.getGlobalContext=t.globalContext=t.logError=void 0,t.generateCodeVerifier=function(){return n(this,arguments,void 0,(function*(e=128){const t=new Uint8Array(e);crypto.getRandomValues(t);const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=Array.from(t).map((e=>r[e%66])),i=n.join(""),o=Uint8Array.from(n.map((e=>e.charCodeAt(0)))),s=(a=yield crypto.subtle.digest("SHA-256",o),btoa(String.fromCharCode.apply(null,new Uint8Array(a))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""));var a;return crypto.getRandomValues(t),{codeVerifier:i,codeChallenge:s,state:Array.from(t).map((e=>r[e%66])).join("")}}))},t.applyMixins=function(e,t){t.forEach((t=>{Object.getOwnPropertyNames(t.prototype).forEach((r=>{Object.defineProperty(e.prototype,r,Object.getOwnPropertyDescriptor(t.prototype,r))}))}))},t.logError=e=>{"string"==typeof e?console.error(e):console.error(e.message,e.stack)},t.globalContext="undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.getGlobalContext=()=>"undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.extend=(...e)=>{const t=e[0];return Array.prototype.slice.call(e,1).forEach((function(e){for(const r in e)t[r]=e[r]})),t},t.containingFolder=e=>{if(""===e)return"/";if(!e)throw"Path not given!";return e.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},t.isFolder=e=>"/"===e.slice(-1),t.isDocument=e=>!(0,t.isFolder)(e),t.baseName=e=>{const r=e.split("/");return(0,t.isFolder)(e)?r[r.length-2]+"/":r[r.length-1]},t.cleanPath=e=>e.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27"),t.bindAll=e=>{for(const t in this)"function"==typeof e[t]&&(e[t]=e[t].bind(e))},t.equal=(e,r,n=[])=>{let i;if(typeof e!=typeof r)return!1;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return e===r;if("function"==typeof e)return e.toString()===r.toString();if(e instanceof ArrayBuffer&&r instanceof ArrayBuffer&&(e=new Uint8Array(e),r=new Uint8Array(r)),e instanceof Array){if(e.length!==r.length)return!1;for(let i=0,o=e.length;i=0)continue;o=n.slice(),o.push(r[i])}if(!(0,t.equal)(e[i],r[i],o))return!1}}return!0},t.deepClone=e=>{if(void 0!==e){const t=JSON.parse(JSON.stringify(e));return i(e,t),t}},t.pathsFromRoot=e=>{const t=[e],r=e.replace(/\/$/,"").split("/");for(;r.length>1;)r.pop(),t.push(r.join("/")+"/");return t},t.localStorageAvailable=()=>{const e=(0,t.getGlobalContext)();if(!("localStorage"in e))return!1;try{return e.localStorage.setItem("rs-check","1"),e.localStorage.removeItem("rs-check"),!0}catch(e){return!1}},t.getJSONFromLocalStorage=e=>{const r=(0,t.getGlobalContext)();try{return JSON.parse(r.localStorage.getItem(e))}catch(e){}},t.shouldBeTreatedAsBinary=(e,t)=>!!(t&&t.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(e)),t.getTextFromArrayBuffer=(e,r)=>new Promise((n=>{if("undefined"==typeof Blob||"undefined"==typeof FileReader){const t=Buffer.from(e);n(t.toString(r))}else{let i;const o=t.globalContext;if(o.BlobBuilder=o.BlobBuilder||o.WebKitBlobBuilder,void 0!==o.BlobBuilder){const t=new o.BlobBuilder;t.append(e),i=t.getBlob()}else i=new Blob([e]);const s=new FileReader;"function"==typeof s.addEventListener?s.addEventListener("loadend",(function(e){n(e.target.result)})):s.onloadend=function(e){n(e.target.result)},s.readAsText(i,r)}})),t.toBase64=e=>{const r=(0,t.getGlobalContext)();return"btoa"in r?r.btoa(e):Buffer.from(e).toString("base64")}},600:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(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(s,a)}c((n=n.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(3275)),s=i(r(93)),a=i(r(5503)),c=i(r(3334)),l=r(7746),u=r(368),d=r(3684);let h;const f="remotestorage:wireclient",p={"draft-dejong-remotestorage-00":2,"draft-dejong-remotestorage-01":3,"draft-dejong-remotestorage-02":4,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":1};class g extends d.RemoteBase{constructor(e){if(super(e),this._revisionCache={},h=(0,l.localStorageAvailable)(),this.addEvents(["connected","not-connected"]),h){const e=function(){const e=(0,l.getJSONFromLocalStorage)(f)||{},{userAddress:t,href:r,storageApi:n,token:i,properties:o}=e;return{userAddress:t,href:r,storageApi:n,token:i,properties:o}}();e&&setTimeout((()=>{this.configure(e)}),0)}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}get storageType(){if(this.storageApi){const e=this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);return e?e[1]:"2012.04"}}_request(e,t,r,i,s,d,h){return n(this,void 0,void 0,(function*(){if(this.isForbiddenRequestMethod(e,t))return Promise.reject(`Don't use ${e} on directories!`);let n;return r!==o.default.IMPLIED_FAKE_TOKEN&&(i.Authorization="Bearer "+r),this.rs._emit("wire-busy",{method:e,isFolder:(0,l.isFolder)(t)}),(0,u.requestWithTimeout)(e,t,{body:s,headers:i,responseType:"arraybuffer"}).then((r=>{if(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,l.isFolder)(t),success:!0}),i=r.status,[401,403,404,412].indexOf(i)>=0)return(0,c.default)("[WireClient] Error response status",r.status),n=d?this.stripQuotes(r.getResponseHeader("ETag")):void 0,401===r.status&&this.rs._emit("error",new a.default),Promise.resolve({statusCode:r.status,revision:n});if(function(e){return[201,204,304].indexOf(e)>=0}(r.status)||200===r.status&&"GET"!==e)return n=this.stripQuotes(r.getResponseHeader("ETag")),(0,c.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,revision:n});{const e=r.getResponseHeader("Content-Type");n=d?this.stripQuotes(r.getResponseHeader("ETag")):200===r.status?h:void 0;const t=function(e){let t,r="utf-8";return e&&(t=e.match(/charset=(.+)$/),t&&(r=t[1])),r}(e);return(0,l.shouldBeTreatedAsBinary)(r.response,e)?((0,c.default)("[WireClient] Successful request with unknown or binary mime-type",n),Promise.resolve({statusCode:r.status,body:r.response,contentType:e,revision:n})):(0,l.getTextFromArrayBuffer)(r.response,t).then((t=>((0,c.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,body:t,contentType:e,revision:n}))))}var i}),(r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,l.isFolder)(t),success:!1}),Promise.reject(r))))}))}configure(e){if("object"!=typeof e)throw new Error("WireClient configure settings parameter should be an object");if(void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.href=e.href),void 0!==e.storageApi&&(this.storageApi=e.storageApi),void 0!==e.token&&(this.token=e.token),void 0!==e.properties&&(this.properties=e.properties),"string"==typeof this.storageApi){const e=p[this.storageApi]||5;this.supportsRevs=e>=2}this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,h&&(localStorage[f]=JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r={};return this.supportsRevs&&t.ifNoneMatch&&(r["If-None-Match"]=this.addQuotes(t.ifNoneMatch)),this._request("GET",this.href+(0,l.cleanPath)(e),this.token,r,void 0,this.supportsRevs,this._revisionCache[e]).then((t=>{if(!(0,l.isFolder)(e))return Promise.resolve(t);let r={};if(void 0!==t.body)try{t.body=JSON.parse(t.body)}catch(t){return Promise.reject("Folder description at "+this.href+(0,l.cleanPath)(e)+" is not JSON")}if(200===t.statusCode&&"object"==typeof t.body){if(0===Object.keys(t.body).length)t.statusCode=404;else if("http://remotestorage.io/spec/folder-description"===(n=t.body)["@context"]&&"object"==typeof n.items){for(const r in t.body.items)this._revisionCache[e+r]=t.body.items[r].ETag;r=t.body.items}else Object.keys(t.body).forEach((n=>{this._revisionCache[e+n]=t.body[n],r[n]={ETag:t.body[n]}}));return t.body=r,Promise.resolve(t)}return Promise.resolve(t);var n}))}put(e,t,r,n={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");!r.match(/charset=/)&&(t instanceof ArrayBuffer||(0,u.isArrayBufferView)(t))&&(r+="; charset=binary");const i={"Content-Type":r};return this.supportsRevs&&(n.ifMatch&&(i["If-Match"]=this.addQuotes(n.ifMatch)),n.ifNoneMatch&&(i["If-None-Match"]=this.addQuotes(n.ifNoneMatch))),this._request("PUT",this.href+(0,l.cleanPath)(e),this.token,i,t,this.supportsRevs)}delete(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");t||(t={});const r={};return this.supportsRevs&&t.ifMatch&&(r["If-Match"]=this.addQuotes(t.ifMatch)),this._request("DELETE",this.href+(0,l.cleanPath)(e),this.token,r,void 0,this.supportsRevs)}static _rs_init(e){e.remote=new g(e),e.remote.online=!0}static _rs_supported(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest}static _rs_cleanup(){h&&delete localStorage[f]}}(0,l.applyMixins)(g,[s.default]),e.exports=g},439:function(e,t){var r,n;r=function(){var e,t,r,n;Object.keys||(Object.keys=(e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),n=(r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(i){if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError("Object.keys called on non-object");var o=[];for(var s in i)e.call(i,s)&&o.push(s);if(t)for(var a=0;a>>0;if(0===r)return-1;var n=0;if(arguments.length>1&&((n=Number(arguments[1]))!=n?n=0:0!==n&&n!==1/0&&n!==-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=r)return-1;for(var i=n>=0?n:Math.max(r-Math.abs(n),0);i0&&(t+=u.suffices["*"]&&r||",",u.suffices["*"]&&c&&(t+=u.name+"=")),t+=a?encodeURIComponent(d[f]).replace(/!/g,"%21"):s(d[f])}else if("object"==typeof d){c&&!u.suffices["*"]&&(t+=u.name+"=");var p=!0;for(var g in d)p||(t+=u.suffices["*"]&&r||","),p=!1,t+=a?encodeURIComponent(g).replace(/!/g,"%21"):s(g),t+=u.suffices["*"]?"=":",",t+=a?encodeURIComponent(d[g]).replace(/!/g,"%21"):s(d[g])}else c&&(t+=u.name,l&&""===d||(t+="=")),null!=u.truncate&&(d=d.substring(0,u.truncate)),t+=a?encodeURIComponent(d).replace(/!/g,"%21"):s(d)}return t};return w.varNames=u,{prefix:n,substitution:w}}function c(e){if(!(this instanceof c))return new c(e);for(var t=e.split("{"),r=[t.shift()],n=[],i=[],o=[];t.length>0;){var s=t.shift(),l=s.split("}")[0],u=s.substring(l.length+1),d=a(l);i.push(d.substitution),n.push(d.prefix),r.push(u),o=o.concat(d.substitution.varNames)}this.fill=function(e){for(var t=r[0],n=0;n0&&"/"===t.charAt(e.length-1)||"#"===r.charAt(0)||"?"===r.charAt(0))return!0}return!1}(t,e.id)&&void 0===this.schemas[e.id]&&(this.schemas[e.id]=e),e)if("enum"!==n)if("object"==typeof e[n])this.searchSchemas(e[n],t);else if("$ref"===n){var i=g(e[n]);i&&void 0===this.schemas[i]&&void 0===this.missingMap[i]&&(this.missingMap[i]=i)}},l.prototype.addSchema=function(e,t){if("string"!=typeof e||void 0===t){if("object"!=typeof e||"string"!=typeof e.id)return;e=(t=e).id}e===g(e)+"#"&&(e=g(e)),this.schemas[e]=t,delete this.missingMap[e],y(t,e),this.searchSchemas(t,e)},l.prototype.getSchemaMap=function(){var e={};for(var t in this.schemas)e[t]=this.schemas[t];return e},l.prototype.getSchemaUris=function(e){var t=[];for(var r in this.schemas)e&&!e.test(r)||t.push(r);return t},l.prototype.getMissingUris=function(e){var t=[];for(var r in this.missingMap)e&&!e.test(r)||t.push(r);return t},l.prototype.dropSchemas=function(){this.schemas={},this.reset()},l.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},l.prototype.validateAll=function(e,t,r,n,i){var o;if(!(t=this.resolveRefs(t)))return null;if(t instanceof S)return this.errors.push(t),t;var s,a=this.errors.length,c=null,l=null;if(this.checkRecursive&&e&&"object"==typeof e){if(o=!this.scanned.length,e[this.validatedSchemasKey]){var u=e[this.validatedSchemasKey].indexOf(t);if(-1!==u)return this.errors=this.errors.concat(e[this.validationErrorsKey][u]),null}if(Object.isFrozen(e)&&-1!==(s=this.scannedFrozen.indexOf(e))){var d=this.scannedFrozenSchemas[s].indexOf(t);if(-1!==d)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[s][d]),null}if(this.scanned.push(e),Object.isFrozen(e))-1===s&&(s=this.scannedFrozen.length,this.scannedFrozen.push(e),this.scannedFrozenSchemas.push([])),c=this.scannedFrozenSchemas[s].length,this.scannedFrozenSchemas[s][c]=t,this.scannedFrozenValidationErrors[s][c]=[];else{if(!e[this.validatedSchemasKey])try{Object.defineProperty(e,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(e,this.validationErrorsKey,{value:[],configurable:!0})}catch(t){e[this.validatedSchemasKey]=[],e[this.validationErrorsKey]=[]}l=e[this.validatedSchemasKey].length,e[this.validatedSchemasKey][l]=t,e[this.validationErrorsKey][l]=[]}}var h=this.errors.length,f=this.validateBasic(e,t,i)||this.validateNumeric(e,t,i)||this.validateString(e,t,i)||this.validateArray(e,t,i)||this.validateObject(e,t,i)||this.validateCombinations(e,t,i)||this.validateHypermedia(e,t,i)||this.validateFormat(e,t,i)||this.validateDefinedKeywords(e,t,i)||null;if(o){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(f||h!==this.errors.length)for(;r&&r.length||n&&n.length;){var p=r&&r.length?""+r.pop():null,g=n&&n.length?""+n.pop():null;f&&(f=f.prefixWith(p,g)),this.prefixErrors(h,p,g)}return null!==c?this.scannedFrozenValidationErrors[s][c]=this.errors.slice(a):null!==l&&(e[this.validationErrorsKey][l]=this.errors.slice(a)),this.handleError(f)},l.prototype.validateFormat=function(e,t){if("string"!=typeof t.format||!this.formatValidators[t.format])return null;var r=this.formatValidators[t.format].call(null,e,t);return"string"==typeof r||"number"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r},"","/format",null,e,t):r&&"object"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r.message||"?"},r.dataPath||"",r.schemaPath||"/format",null,e,t):null},l.prototype.validateDefinedKeywords=function(e,t,r){for(var n in this.definedKeywords)if(void 0!==t[n])for(var i=this.definedKeywords[n],o=0;o=d&&nt.maximum)return this.createError(v.NUMBER_MAXIMUM,{value:e,maximum:t.maximum},"","/maximum",null,e,t);if(t.exclusiveMaximum&&e===t.maximum)return this.createError(v.NUMBER_MAXIMUM_EXCLUSIVE,{value:e,maximum:t.maximum},"","/exclusiveMaximum",null,e,t)}return null},l.prototype.validateNaN=function(e,t){return"number"!=typeof e?null:!0===isNaN(e)||e===1/0||e===-1/0?this.createError(v.NUMBER_NOT_A_NUMBER,{value:e},"","/type",null,e,t):null},l.prototype.validateString=function(e,t,r){return this.validateStringLength(e,t,r)||this.validateStringPattern(e,t,r)||null},l.prototype.validateStringLength=function(e,t){return"string"!=typeof e?null:void 0!==t.minLength&&e.lengtht.maxLength?this.createError(v.STRING_LENGTH_LONG,{length:e.length,maximum:t.maxLength},"","/maxLength",null,e,t):null},l.prototype.validateStringPattern=function(e,t){if("string"!=typeof e||"string"!=typeof t.pattern&&!(t.pattern instanceof RegExp))return null;var r;if(t.pattern instanceof RegExp)r=t.pattern;else{var n,i="",o=t.pattern.match(/^\/(.+)\/([img]*)$/);o?(n=o[1],i=o[2]):n=t.pattern,r=new RegExp(n,i)}return r.test(e)?null:this.createError(v.STRING_PATTERN,{pattern:t.pattern},"","/pattern",null,e,t)},l.prototype.validateArray=function(e,t,r){return Array.isArray(e)&&(this.validateArrayLength(e,t,r)||this.validateArrayUniqueItems(e,t,r)||this.validateArrayItems(e,t,r))||null},l.prototype.validateArrayLength=function(e,t){var r;return void 0!==t.minItems&&e.lengtht.maxItems&&(r=this.createError(v.ARRAY_LENGTH_LONG,{length:e.length,maximum:t.maxItems},"","/maxItems",null,e,t),this.handleError(r))?r:null},l.prototype.validateArrayUniqueItems=function(e,t){if(t.uniqueItems)for(var r=0;rt.maxProperties&&(r=this.createError(v.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:n.length,maximum:t.maxProperties},"","/maxProperties",null,e,t),this.handleError(r))?r:null},l.prototype.validateObjectRequiredProperties=function(e,t){if(void 0!==t.required)for(var r=0;r 10000");if(void 0!==v[e])throw new Error("Error already defined: "+e+" as "+v[e]);if(void 0!==b[t])throw new Error("Error code already used: "+b[t]+" as "+t);for(var n in v[e]=t,b[t]=e,_[e]=_[t]=r,E){var i=E[n];i[e]&&(i[t]=i[t]||i[e])}},reset:function(){i.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:y,resolveUrl:p,getDocumentUri:g,errorCodes:v};return o.language(t||"en"),o}();return A.addLanguage("en-gb",_),A.tv4=A,A},void 0===(n=r.apply(t,[]))||(e.exports=n)},2831:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NIL",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(t,"v1",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(t,"v3",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(t,"v4",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(t,"v5",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(t,"validate",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(t,"version",{enumerable:!0,get:function(){return c.default}});var n=h(r(3518)),i=h(r(4948)),o=h(r(5073)),s=h(r(7186)),a=h(r(4808)),c=h(r(7775)),l=h(r(7037)),u=h(r(9910)),d=h(r(6792));function h(e){return e&&e.__esModule?e:{default:e}}},2311:function(e,t){"use strict";function r(e){return 14+(e+64>>>9<<4)+1}function n(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function i(e,t,r,i,o,s){return n((a=n(n(t,e),n(i,s)))<<(c=o)|a>>>32-c,r);var a,c}function o(e,t,r,n,o,s,a){return i(t&r|~t&n,e,t,o,s,a)}function s(e,t,r,n,o,s,a){return i(t&n|r&~n,e,t,o,s,a)}function a(e,t,r,n,o,s,a){return i(t^r^n,e,t,o,s,a)}function c(e,t,r,n,o,s,a){return i(r^(t|~n),e,t,o,s,a)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let r=0;r>5]>>>i%32&255,o=parseInt(n.charAt(r>>>4&15)+n.charAt(15&r),16);t.push(o)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[r/8])<>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}},7656:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},2858:function(e,t){"use strict";let r;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){if(!r&&(r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!r))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return r(n)};const n=new Uint8Array(16)},9042:function(e,t){"use strict";function r(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function n(e,t){return e<>>32-t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],i=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let r=0;r>>0;d=u,u=l,l=n(c,30)>>>0,c=s,s=a}i[0]=i[0]+s>>>0,i[1]=i[1]+c>>>0,i[2]=i[2]+l>>>0,i[3]=i[3]+u>>>0,i[4]=i[4]+d>>>0}return[i[0]>>24&255,i[0]>>16&255,i[0]>>8&255,255&i[0],i[1]>>24&255,i[1]>>16&255,i[1]>>8&255,255&i[1],i[2]>>24&255,i[2]>>16&255,i[2]>>8&255,255&i[2],i[3]>>24&255,i[3]>>16&255,i[3]>>8&255,255&i[3],i[4]>>24&255,i[4]>>16&255,i[4]>>8&255,255&i[4]]}},9910:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.unsafeStringify=s;var n,i=(n=r(7037))&&n.__esModule?n:{default:n};const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));function s(e,t=0){return o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]}t.default=function(e,t=0){const r=s(e,t);if(!(0,i.default)(r))throw TypeError("Stringified UUID is invalid");return r}},3518:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,i=(n=r(2858))&&n.__esModule?n:{default:n},o=r(9910);let s,a,c=0,l=0;t.default=function(e,t,r){let n=t&&r||0;const u=t||new Array(16);let d=(e=e||{}).node||s,h=void 0!==e.clockseq?e.clockseq:a;if(null==d||null==h){const t=e.random||(e.rng||i.default)();null==d&&(d=s=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==h&&(h=a=16383&(t[6]<<8|t[7]))}let f=void 0!==e.msecs?e.msecs:Date.now(),p=void 0!==e.nsecs?e.nsecs:l+1;const g=f-c+(p-l)/1e4;if(g<0&&void 0===e.clockseq&&(h=h+1&16383),(g<0||f>c)&&void 0===e.nsecs&&(p=0),p>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");c=f,l=p,a=h,f+=122192928e5;const y=(1e4*(268435455&f)+p)%4294967296;u[n++]=y>>>24&255,u[n++]=y>>>16&255,u[n++]=y>>>8&255,u[n++]=255&y;const m=f/4294967296*1e4&268435455;u[n++]=m>>>8&255,u[n++]=255&m,u[n++]=m>>>24&15|16,u[n++]=m>>>16&255,u[n++]=h>>>8|128,u[n++]=255&h;for(let e=0;e<6;++e)u[n+e]=d[e];return t||(0,o.unsafeStringify)(u)}},4948:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=o(r(9025)),i=o(r(2311));function o(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v3",48,i.default);t.default=s},9025:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URL=t.DNS=void 0,t.default=function(e,t,r){function n(e,n,s,a){var c;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let r=0;r=301&&o.status<=302?function(e){return"string"==typeof e&&"https"===e.split("://")[0]}(o.getResponseHeader("Location"))?c():t(s({message:"no redirect URL found",url:e,status:o.status})):t(s({message:"error during request",url:e,status:o.status}))}function c(){o.onreadystatechange=function(){4===o.readyState&&a()},o.onload=function(){a()},o.ontimeout=function(){return t(s({message:"request timed out",url:e,status:o.status}))},o.open("GET",e,!0),o.timeout=n.config.request_timeout,o.setRequestHeader("Accept","application/jrd+json, application/json"),o.send()}return c()},a.prototype.__isValidJSON=function(e){try{JSON.parse(e)}catch(e){return!1}return!0},a.prototype.__isLocalhost=function(e){return/^localhost(\.localdomain)?(\:[0-9]+)?$/.test(e)},a.prototype.__processJRD=function(e,t,n,o){var a=JSON.parse(t);if("object"!=typeof a||"object"!=typeof a.links)return void 0!==a.error?n(s({message:a.error,request:e})):n(s({message:"unknown response from server",request:e}));var c=a.links;Array.isArray(c)||(c=[]);var l={object:a,json:t,idx:{}};l.idx.properties={name:void 0},l.idx.links=JSON.parse(JSON.stringify(i)),c.map((function(e,t){if(r.hasOwnProperty(e.rel)&&l.idx.links[r[e.rel]]){var n={};Object.keys(e).map((function(t,r){n[t]=e[t]})),l.idx.links[r[e.rel]].push(n)}}));var u=JSON.parse(t).properties;for(var d in u)u.hasOwnProperty(d)&&"http://packetizer.com/ns/name"===d&&(l.idx.properties.name=u[d]);return o(l)},a.prototype.lookup=function(e,t){if("string"!=typeof e)throw new Error("first parameter must be a user address");if("function"!=typeof t)throw new Error("second parameter must be a callback");var r=this,n="";n=e.indexOf("://")>-1?e.replace(/ /g,"").split("/")[2]:e.replace(/ /g,"").split("@")[1];var i=0,s="https";function a(){var t="";return e.split("://")[1]||(t="acct:"),s+"://"+n+"/.well-known/"+o[i]+"?resource="+t+e}function c(e){if(r.config.uri_fallback&&"webfist.org"!==n&&i!==o.length-1)return i+=1,l();if(!r.config.tls_only&&"https"===s)return i=0,s="http",l();if(!r.config.webfist_fallback||"webfist.org"===n)return t(e);i=0,s="http",n="webfist.org";var c=a();r.__fetchJRD(c,t,(function(e){r.__processJRD(c,e,t,(function(e){"object"==typeof e.idx.links.webfist&&"string"==typeof e.idx.links.webfist[0].href&&r.__fetchJRD(e.idx.links.webfist[0].href,t,(function(e){r.__processJRD(c,e,t,(function(e){return t(null,t)}))}))}))}))}function l(){var e=a();r.__fetchJRD(e,c,(function(n){r.__processJRD(e,n,t,(function(e){t(null,e)}))}))}return r.__isLocalhost(n)&&(s="http"),setTimeout(l,0)},a.prototype.lookupLink=function(e,t,r){if(!i.hasOwnProperty(t))return r("unsupported rel "+t);this.lookup(e,(function(e,n){var i=n.idx.links[t];return e?r(e):0===i.length?r('no links found with rel="'+t+'"'):r(null,i[0])}))},void 0===(n=function(){return a}.apply(t,[]))||(e.exports=n)}()},4317:function(e){e.exports=XMLHttpRequest},6438:function(e,t,r){"use strict";r.r(t),r.d(t,{CompactEncrypt:function(){return ee},CompactSign:function(){return te.T},EmbeddedJWK:function(){return he},EncryptJWT:function(){return ae},FlattenedEncrypt:function(){return K},FlattenedSign:function(){return re.n},GeneralEncrypt:function(){return G},GeneralSign:function(){return ie},SignJWT:function(){return oe.P},UnsecuredJWT:function(){return we},base64url:function(){return n},calculateJwkThumbprint:function(){return ue},calculateJwkThumbprintUri:function(){return de},compactDecrypt:function(){return B},compactVerify:function(){return q.B},createLocalJWKSet:function(){return me},createRemoteJWKSet:function(){return be},cryptoRuntime:function(){return xe},decodeJwt:function(){return Ae},decodeProtectedHeader:function(){return Ee},errors:function(){return s},exportJWK:function(){return W.JU},exportPKCS8:function(){return W.Yp},exportSPKI:function(){return W.Y5},flattenedDecrypt:function(){return M},flattenedVerify:function(){return z.Z},generalDecrypt:function(){return H},generalVerify:function(){return Y},generateKeyPair:function(){return Re.T},generateSecret:function(){return Te},importJWK:function(){return F.Og},importPKCS8:function(){return F.Lf},importSPKI:function(){return F.jU},importX509:function(){return F.Mh},jwtDecrypt:function(){return Z},jwtVerify:function(){return Q.V}});var n={};r.r(n),r.d(n,{decode:function(){return Se},encode:function(){return _e}});var i=r(1436),o=r(9095),s=r(7493),a=r(8057);function c(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new s.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}var l=e=>(0,a.A)(new Uint8Array(c(e)>>3)),u=(e,t)=>{if(t.length<<3!==c(e))throw new s.JWEInvalid("Invalid Initialization Vector length")},d=(e,t)=>{const r=e.byteLength<<3;if(r!==t)throw new s.JWEInvalid(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},h=r(7991),f=r(2698),p=r(1575),g=r(5994),y=async(e,t,r,n,i,a)=>{if(!((0,h.R)(t)||t instanceof Uint8Array))throw new TypeError((0,p.A)(t,...g.g,"Uint8Array"));switch(u(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&d(t,parseInt(e.slice(-3),10)),async function(e,t,r,n,i,a){if(!(t instanceof Uint8Array))throw new TypeError((0,p.A)(t,"Uint8Array"));const c=parseInt(e.slice(1,4),10),l=await h.A.subtle.importKey("raw",t.subarray(c>>3),"AES-CBC",!1,["decrypt"]),u=await h.A.subtle.importKey("raw",t.subarray(0,c>>3),{hash:"SHA-"+(c<<1),name:"HMAC"},!1,["sign"]),d=(0,o.xW)(a,n,r,(0,o.mx)(a.length<<3)),f=new Uint8Array((await h.A.subtle.sign("HMAC",u,d)).slice(0,c>>3));let g,y;try{g=((e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");const r=e.length;let n=0,i=-1;for(;++i{throw new s.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},v=async()=>{throw new s.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')};var b=r(9874),w=r(149),_=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]];function S(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function E(e,t,r){if((0,h.R)(e))return(0,f.$)(e,t,r),e;if(e instanceof Uint8Array)return h.A.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError((0,p.A)(e,...g.g,"Uint8Array"))}const A=async(e,t,r)=>{const n=await E(t,e,"wrapKey");S(n,e);const i=await h.A.subtle.importKey("raw",r,..._);return new Uint8Array(await h.A.subtle.wrapKey("raw",i,n,"AES-KW"))},R=async(e,t,r)=>{const n=await E(t,e,"unwrapKey");S(n,e);const i=await h.A.subtle.unwrapKey("raw",r,n,"AES-KW",..._);return new Uint8Array(await h.A.subtle.exportKey("raw",i))};async function I(e,t,r,n,i=new Uint8Array(0),s=new Uint8Array(0)){if(!(0,h.R)(e))throw new TypeError((0,p.A)(e,...g.g));if((0,f.$)(e,"ECDH"),!(0,h.R)(t))throw new TypeError((0,p.A)(t,...g.g));(0,f.$)(t,"ECDH","deriveBits");const a=(0,o.xW)((0,o.Kp)(o.Rd.encode(r)),(0,o.Kp)(i),(0,o.Kp)(s),(0,o.VS)(n));let c;c="X25519"===e.algorithm.name?256:"X448"===e.algorithm.name?448:Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;const l=new Uint8Array(await h.A.subtle.deriveBits({name:e.algorithm.name,public:e},t,c));return(0,o.yI)(l,n,a)}function T(e){if(!(0,h.R)(e))throw new TypeError((0,p.A)(e,...g.g));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||"X25519"===e.algorithm.name||"X448"===e.algorithm.name}async function x(e,t,r,n){!function(e){if(!(e instanceof Uint8Array)||e.length<8)throw new s.JWEInvalid("PBES2 Salt Input must be 8 or more octets")}(e);const i=(0,o.MT)(t,e),a=parseInt(t.slice(13,16),10),c={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},l={length:a,name:"AES-KW"},u=await function(e,t){if(e instanceof Uint8Array)return h.A.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if((0,h.R)(e))return(0,f.$)(e,t,"deriveBits","deriveKey"),e;throw new TypeError((0,p.A)(e,...g.g,"Uint8Array"))}(n,t);if(u.usages.includes("deriveBits"))return new Uint8Array(await h.A.subtle.deriveBits(c,u,a));if(u.usages.includes("deriveKey"))return h.A.subtle.deriveKey(c,u,l,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}function P(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new s.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var C=r(4495);function k(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new s.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}var O=e=>(0,a.A)(new Uint8Array(k(e)>>3)),F=r(8136),N=r(8858),D=async(e,t,r,n,i)=>{if(!((0,h.R)(r)||r instanceof Uint8Array))throw new TypeError((0,p.A)(r,...g.g,"Uint8Array"));switch(u(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&d(r,parseInt(e.slice(-3),10)),async function(e,t,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError((0,p.A)(r,"Uint8Array"));const s=parseInt(e.slice(1,4),10),a=await h.A.subtle.importKey("raw",r.subarray(s>>3),"AES-CBC",!1,["encrypt"]),c=await h.A.subtle.importKey("raw",r.subarray(0,s>>3),{hash:"SHA-"+(s<<1),name:"HMAC"},!1,["sign"]),l=new Uint8Array(await h.A.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),u=(0,o.xW)(i,n,l,(0,o.mx)(i.length<<3));return{ciphertext:l,tag:new Uint8Array((await h.A.subtle.sign("HMAC",c,u)).slice(0,s>>3))}}(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&d(r,parseInt(e.slice(1,4),10)),async function(e,t,r,n,i){let o;r instanceof Uint8Array?o=await h.A.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):((0,f.$)(r,e,"encrypt"),o=r);const s=new Uint8Array(await h.A.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},o,t)),a=s.slice(-16);return{ciphertext:s.slice(0,-16),tag:a}}(e,t,r,n,i);default:throw new s.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}},L=async function(e,t,r,n,o){switch((0,N.A)(e,t,"decrypt"),e){case"dir":if(void 0!==r)throw new s.JWEInvalid("Encountered unexpected JWE Encrypted Key");return t;case"ECDH-ES":if(void 0!==r)throw new s.JWEInvalid("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!(0,w.A)(n.epk))throw new s.JWEInvalid('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!T(t))throw new s.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");const o=await(0,F.Og)(n.epk,e);let a,c;if(void 0!==n.apu){if("string"!=typeof n.apu)throw new s.JWEInvalid('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{a=(0,i.D4)(n.apu)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the apu")}}if(void 0!==n.apv){if("string"!=typeof n.apv)throw new s.JWEInvalid('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{c=(0,i.D4)(n.apv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the apv")}}const l=await I(o,t,"ECDH-ES"===e?n.enc:e,"ECDH-ES"===e?k(n.enc):parseInt(e.slice(-5,-2),10),a,c);if("ECDH-ES"===e)return l;if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return R(e.slice(-6),l,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return(async(e,t,r)=>{if(!(0,h.R)(t))throw new TypeError((0,p.A)(t,...g.g));if((0,f.$)(t,e,"decrypt","unwrapKey"),(0,C.A)(e,t),t.usages.includes("decrypt"))return new Uint8Array(await h.A.subtle.decrypt(P(e),t,r));if(t.usages.includes("unwrapKey")){const n=await h.A.subtle.unwrapKey("raw",r,t,P(e),..._);return new Uint8Array(await h.A.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')})(e,t,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");if("number"!=typeof n.p2c)throw new s.JWEInvalid('JOSE Header "p2c" (PBES2 Count) missing or invalid');const a=(null==o?void 0:o.maxPBES2Count)||1e4;if(n.p2c>a)throw new s.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof n.p2s)throw new s.JWEInvalid('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let c;try{c=(0,i.D4)(n.p2s)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the p2s")}return(async(e,t,r,n,i)=>{const o=await x(i,e,n,t);return R(e.slice(-6),o,r)})(e,t,r,n.p2c,c)}case"A128KW":case"A192KW":case"A256KW":if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return R(e,t,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");if("string"!=typeof n.iv)throw new s.JWEInvalid('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof n.tag)throw new s.JWEInvalid('JOSE Header "tag" (Authentication Tag) missing or invalid');let o,a;try{o=(0,i.D4)(n.iv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the iv")}try{a=(0,i.D4)(n.tag)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the tag")}return async function(e,t,r,n,i){const o=e.slice(0,7);return y(o,t,r,n,i,new Uint8Array(0))}(e,t,r,o,a)}default:throw new s.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}},U=r(2168),j=r(4618);async function M(e,t,r){var n;if(!(0,w.A)(e))throw new s.JWEInvalid("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new s.JWEInvalid("JOSE Header missing");if("string"!=typeof e.iv)throw new s.JWEInvalid("JWE Initialization Vector missing or incorrect type");if("string"!=typeof e.ciphertext)throw new s.JWEInvalid("JWE Ciphertext missing or incorrect type");if("string"!=typeof e.tag)throw new s.JWEInvalid("JWE Authentication Tag missing or incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new s.JWEInvalid("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new s.JWEInvalid("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new s.JWEInvalid("JWE AAD incorrect type");if(void 0!==e.header&&!(0,w.A)(e.header))throw new s.JWEInvalid("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!(0,w.A)(e.unprotected))throw new s.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");let a;if(e.protected)try{const t=(0,i.D4)(e.protected);a=JSON.parse(o.D0.decode(t))}catch(e){throw new s.JWEInvalid("JWE Protected Header is invalid")}if(!(0,b.A)(a,e.header,e.unprotected))throw new s.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");const c={...a,...e.header,...e.unprotected};if((0,U.A)(s.JWEInvalid,new Map,null==r?void 0:r.crit,a,c),void 0!==c.zip){if(!a||!a.zip)throw new s.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==c.zip)throw new s.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}const{alg:l,enc:u}=c;if("string"!=typeof l||!l)throw new s.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof u||!u)throw new s.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");const d=r&&(0,j.A)("keyManagementAlgorithms",r.keyManagementAlgorithms),h=r&&(0,j.A)("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(d&&!d.has(l))throw new s.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(h&&!h.has(u))throw new s.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed');let f;if(void 0!==e.encrypted_key)try{f=(0,i.D4)(e.encrypted_key)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the encrypted_key")}let p,g,v,_=!1;"function"==typeof t&&(t=await t(a,e),_=!0);try{p=await L(l,t,f,c,r)}catch(e){if(e instanceof TypeError||e instanceof s.JWEInvalid||e instanceof s.JOSENotSupported)throw e;p=O(u)}try{g=(0,i.D4)(e.iv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the iv")}try{v=(0,i.D4)(e.tag)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the tag")}const S=o.Rd.encode(null!==(n=e.protected)&&void 0!==n?n:"");let E,A;E=void 0!==e.aad?(0,o.xW)(S,o.Rd.encode("."),o.Rd.encode(e.aad)):S;try{A=(0,i.D4)(e.ciphertext)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the ciphertext")}let R=await y(u,p,A,g,v,E);"DEF"===c.zip&&(R=await((null==r?void 0:r.inflateRaw)||m)(R));const I={plaintext:R};if(void 0!==e.protected&&(I.protectedHeader=a),void 0!==e.aad)try{I.additionalAuthenticatedData=(0,i.D4)(e.aad)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the aad")}return void 0!==e.unprotected&&(I.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(I.unprotectedHeader=e.header),_?{...I,key:t}:I}async function B(e,t,r){if(e instanceof Uint8Array&&(e=o.D0.decode(e)),"string"!=typeof e)throw new s.JWEInvalid("Compact JWE must be a string or Uint8Array");const{0:n,1:i,2:a,3:c,4:l,length:u}=e.split(".");if(5!==u)throw new s.JWEInvalid("Invalid Compact JWE");const d=await M({ciphertext:c,iv:a||void 0,protected:n||void 0,tag:l||void 0,encrypted_key:i||void 0},t,r),h={plaintext:d.plaintext,protectedHeader:d.protectedHeader};return"function"==typeof t?{...h,key:d.key}:h}async function H(e,t,r){if(!(0,w.A)(e))throw new s.JWEInvalid("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(w.A))throw new s.JWEInvalid("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new s.JWEInvalid("JWE Recipients has no members");for(const n of e.recipients)try{return await M({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch(e){}throw new s.JWEDecryptionFailed}var W=r(5130),$=async function(e,t,r,n,o={}){let c,u,d;switch((0,N.A)(e,r,"encrypt"),e){case"dir":d=r;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!T(r))throw new s.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");const{apu:a,apv:l}=o;let{epk:f}=o;f||(f=(await async function(e){if(!(0,h.R)(e))throw new TypeError((0,p.A)(e,...g.g));return h.A.subtle.generateKey(e.algorithm,!0,["deriveBits"])}(r)).privateKey);const{x:y,y:m,crv:v,kty:b}=await(0,W.JU)(f),w=await I(r,f,"ECDH-ES"===e?t:e,"ECDH-ES"===e?k(t):parseInt(e.slice(-5,-2),10),a,l);if(u={epk:{x:y,crv:v,kty:b}},"EC"===b&&(u.epk.y=m),a&&(u.apu=(0,i.lF)(a)),l&&(u.apv=(0,i.lF)(l)),"ECDH-ES"===e){d=w;break}d=n||O(t);const _=e.slice(-6);c=await A(_,w,d);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":d=n||O(t),c=await(async(e,t,r)=>{if(!(0,h.R)(t))throw new TypeError((0,p.A)(t,...g.g));if((0,f.$)(t,e,"encrypt","wrapKey"),(0,C.A)(e,t),t.usages.includes("encrypt"))return new Uint8Array(await h.A.subtle.encrypt(P(e),t,r));if(t.usages.includes("wrapKey")){const n=await h.A.subtle.importKey("raw",r,..._);return new Uint8Array(await h.A.subtle.wrapKey("raw",n,t,P(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')})(e,r,d);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{d=n||O(t);const{p2c:s,p2s:l}=o;({encryptedKey:c,...u}=await(async(e,t,r,n=2048,o=(0,a.A)(new Uint8Array(16)))=>{const s=await x(o,e,n,t);return{encryptedKey:await A(e.slice(-6),s,r),p2c:n,p2s:(0,i.lF)(o)}})(e,r,d,s,l));break}case"A128KW":case"A192KW":case"A256KW":d=n||O(t),c=await A(e,r,d);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{d=n||O(t);const{iv:s}=o;({encryptedKey:c,...u}=await async function(e,t,r,n){const o=e.slice(0,7);n||(n=l(o));const{ciphertext:s,tag:a}=await D(o,r,t,n,new Uint8Array(0));return{encryptedKey:s,iv:(0,i.lF)(n),tag:(0,i.lF)(a)}}(e,r,d,s));break}default:throw new s.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:d,encryptedKey:c,parameters:u}};const V=Symbol();class K{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,t){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new s.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!(0,b.A)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new s.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if((0,U.A)(s.JWEInvalid,new Map,null==t?void 0:t.crit,this._protectedHeader,r),void 0!==r.zip){if(!this._protectedHeader||!this._protectedHeader.zip)throw new s.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==r.zip)throw new s.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}const{alg:n,enc:a}=r;if("string"!=typeof n||!n)throw new s.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof a||!a)throw new s.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let c,u,d,h,f,p,g;if("dir"===n){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if("ECDH-ES"===n&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");{let r;({cek:u,encryptedKey:c,parameters:r}=await $(n,a,e,this._cek,this._keyManagementParameters)),r&&(t&&V in t?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...r}:this.setUnprotectedHeader(r):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...r}:this.setProtectedHeader(r))}if(this._iv||(this._iv=l(a)),h=this._protectedHeader?o.Rd.encode((0,i.lF)(JSON.stringify(this._protectedHeader))):o.Rd.encode(""),this._aad?(f=(0,i.lF)(this._aad),d=(0,o.xW)(h,o.Rd.encode("."),o.Rd.encode(f))):d=h,"DEF"===r.zip){const e=await((null==t?void 0:t.deflateRaw)||v)(this._plaintext);({ciphertext:p,tag:g}=await D(a,e,u,this._iv,d))}else({ciphertext:p,tag:g}=await D(a,this._plaintext,u,this._iv,d));const y={ciphertext:(0,i.lF)(p),iv:(0,i.lF)(this._iv),tag:(0,i.lF)(g)};return c&&(y.encrypted_key=(0,i.lF)(c)),f&&(y.aad=f),this._protectedHeader&&(y.protected=o.D0.decode(h)),this._sharedUnprotectedHeader&&(y.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(y.header=this._unprotectedHeader),y}}class J{constructor(e,t,r){this.parent=e,this.key=t,this.options=r}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}}class G{constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,t){const r=new J(this,e,{crit:null==t?void 0:t.crit});return this._recipients.push(r),r}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(e){var t,r,n;if(!this._recipients.length)throw new s.JWEInvalid("at least one recipient must be added");if(e={deflateRaw:null==e?void 0:e.deflateRaw},1===this._recipients.length){const[t]=this._recipients,r=await new K(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(t.unprotectedHeader).encrypt(t.key,{...t.options,...e});let n={ciphertext:r.ciphertext,iv:r.iv,recipients:[{}],tag:r.tag};return r.aad&&(n.aad=r.aad),r.protected&&(n.protected=r.protected),r.unprotected&&(n.unprotected=r.unprotected),r.encrypted_key&&(n.recipients[0].encrypted_key=r.encrypted_key),r.header&&(n.recipients[0].header=r.header),n}let o;for(let e=0;e{if("string"!=typeof e||!e)throw new s.JWKInvalid(`${t} missing or invalid`)};async function ue(e,t){if(!(0,w.A)(e))throw new TypeError("JWK must be an object");if(null!=t||(t="sha256"),"sha256"!==t&&"sha384"!==t&&"sha512"!==t)throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":le(e.crv,'"crv" (Curve) Parameter'),le(e.x,'"x" (X Coordinate) Parameter'),le(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":le(e.crv,'"crv" (Subtype of Key Pair) Parameter'),le(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":le(e.e,'"e" (Exponent) Parameter'),le(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":le(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new s.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')}const n=o.Rd.encode(JSON.stringify(r));return(0,i.lF)(await(0,ce.A)(t,n))}async function de(e,t){null!=t||(t="sha256");const r=await ue(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function he(e,t){const r={...e,...null==t?void 0:t.header};if(!(0,w.A)(r.jwk))throw new s.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');const n=await(0,F.Og)({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||"public"!==n.type)throw new s.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function fe(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(pe)}function pe(e){return(0,w.A)(e)}class ge{constructor(e){if(this._cached=new WeakMap,!fe(e))throw new s.JWKSInvalid("JSON Web Key Set malformed");var t;this._jwks=(t=e,"function"==typeof structuredClone?structuredClone(t):JSON.parse(JSON.stringify(t)))}async getKey(e,t){const{alg:r,kid:n}={...e,...null==t?void 0:t.header},i=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new s.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}(r),o=this._jwks.keys.filter((e=>{let t=i===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t&&"EdDSA"===r&&(t="Ed25519"===e.crv||"Ed448"===e.crv),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv}return t})),{0:a,length:c}=o;if(0===c)throw new s.JWKSNoMatchingKey;if(1!==c){const e=new s.JWKSMultipleMatchingKeys,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of o)try{yield await ye(t,e,r)}catch(e){continue}},e}return ye(this._cached,a,r)}}async function ye(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await(0,F.Og)({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new s.JWKSInvalid("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function me(e){const t=new ge(e);return async function(e,r){return t.getKey(e,r)}}class ve extends ge{constructor(e,t){if(super({keys:[]}),this._jwks=void 0,!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:null==t?void 0:t.agent,headers:null==t?void 0:t.headers},this._timeoutDuration="number"==typeof(null==t?void 0:t.timeoutDuration)?null==t?void 0:t.timeoutDuration:5e3,this._cooldownDuration="number"==typeof(null==t?void 0:t.cooldownDuration)?null==t?void 0:t.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof(null==t?void 0:t.cacheMaxAge)?null==t?void 0:t.cacheMaxAge:6e5}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now(){let n,i,o=!1;"function"==typeof AbortController&&(n=new AbortController,i=setTimeout((()=>{o=!0,n.abort()}),t));const a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch((e=>{if(o)throw new s.JWKSTimeout;throw e}));if(void 0!==i&&clearTimeout(i),200!==a.status)throw new s.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch(e){throw new s.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}})(this._url,this._timeoutDuration,this._options).then((e=>{if(!fe(e))throw new s.JWKSInvalid("JSON Web Key Set malformed");this._jwks={keys:e.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0})).catch((e=>{throw this._pendingFetch=void 0,e}))),await this._pendingFetch}}function be(e,t){const r=new ve(e,t);return async function(e,t){return r.getKey(e,t)}}class we extends se.G{encode(){return`${i.lF(JSON.stringify({alg:"none"}))}.${i.lF(JSON.stringify(this._payload))}.`}static decode(e,t){if("string"!=typeof e)throw new s.JWTInvalid("Unsecured JWT must be a string");const{0:r,1:n,2:a,length:c}=e.split(".");if(3!==c||""!==a)throw new s.JWTInvalid("Invalid Unsecured JWT");let l;try{if(l=JSON.parse(o.D0.decode(i.D4(r))),"none"!==l.alg)throw new Error}catch(e){throw new s.JWTInvalid("Invalid Unsecured JWT")}return{payload:(0,X.A)(l,i.D4(n),t),header:l}}}const _e=i.lF,Se=i.D4;function Ee(e){let t;if("string"==typeof e){const r=e.split(".");3!==r.length&&5!==r.length||([t]=r)}else if("object"==typeof e&&e){if(!("protected"in e))throw new TypeError("Token does not contain a Protected Header");t=e.protected}try{if("string"!=typeof t||!t)throw new Error;const e=JSON.parse(o.D0.decode(Se(t)));if(!(0,w.A)(e))throw new Error;return e}catch(e){throw new TypeError("Invalid Token or Protected Header formatting")}}function Ae(e){if("string"!=typeof e)throw new s.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new s.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new s.JWTInvalid("Invalid JWT");if(!t)throw new s.JWTInvalid("JWTs must contain a payload");let n,i;try{n=Se(t)}catch(e){throw new s.JWTInvalid("Failed to base64url decode the payload")}try{i=JSON.parse(o.D0.decode(n))}catch(e){throw new s.JWTInvalid("Failed to parse the decoded payload as JSON")}if(!(0,w.A)(i))throw new s.JWTInvalid("Invalid JWT Claims Set");return i}var Re=r(7307),Ie=r(8793);async function Te(e,t){return(0,Ie.K)(e,t)}var xe="WebCryptoAPI"},2609:function(e,t,r){"use strict";r.d(t,{T:function(){return i}});var n=r(5550);class i{constructor(e){this._flattened=new n.n(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}},5609:function(e,t,r){"use strict";r.d(t,{B:function(){return s}});var n=r(6711),i=r(7493),o=r(9095);async function s(e,t,r){if(e instanceof Uint8Array&&(e=o.D0.decode(e)),"string"!=typeof e)throw new i.JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:s,1:a,2:c,length:l}=e.split(".");if(3!==l)throw new i.JWSInvalid("Invalid Compact JWS");const u=await(0,n.Z)({payload:a,protected:s,signature:c},t,r),d={payload:u.payload,protectedHeader:u.protectedHeader};return"function"==typeof t?{...d,key:u.key}:d}},5550:function(e,t,r){"use strict";r.d(t,{n:function(){return f}});var n=r(1436),i=r(1020),o=r(7991),s=r(4495),a=r(676),c=r(9874),l=r(7493),u=r(9095),d=r(8858),h=r(2168);class f{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new l.JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!(0,c.A)(this._protectedHeader,this._unprotectedHeader))throw new l.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let f=!0;if((0,h.A)(l.JWSInvalid,new Map([["b64",!0]]),null==t?void 0:t.crit,this._protectedHeader,r).has("b64")&&(f=this._protectedHeader.b64,"boolean"!=typeof f))throw new l.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:p}=r;if("string"!=typeof p||!p)throw new l.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');(0,d.A)(p,e,"sign");let g,y=this._payload;f&&(y=u.Rd.encode((0,n.lF)(y))),g=this._protectedHeader?u.Rd.encode((0,n.lF)(JSON.stringify(this._protectedHeader))):u.Rd.encode("");const m=(0,u.xW)(g,u.Rd.encode("."),y),v=await(async(e,t,r)=>{const n=await(0,a.A)(e,t,"sign");(0,s.A)(e,n);const c=await o.A.subtle.sign((0,i.A)(e,n.algorithm),n,r);return new Uint8Array(c)})(p,e,m),b={signature:(0,n.lF)(v),payload:""};return f&&(b.payload=u.D0.decode(y)),this._unprotectedHeader&&(b.header=this._unprotectedHeader),this._protectedHeader&&(b.protected=u.D0.decode(g)),b}}},6711:function(e,t,r){"use strict";r.d(t,{Z:function(){return y}});var n=r(1436),i=r(1020),o=r(7991),s=r(4495),a=r(676),c=async(e,t,r,n)=>{const c=await(0,a.A)(e,t,"verify");(0,s.A)(e,c);const l=(0,i.A)(e,c.algorithm);try{return await o.A.subtle.verify(l,c,r,n)}catch(e){return!1}},l=r(7493),u=r(9095),d=r(9874),h=r(149),f=r(8858),p=r(2168),g=r(4618);async function y(e,t,r){var i;if(!(0,h.A)(e))throw new l.JWSInvalid("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new l.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new l.JWSInvalid("JWS Protected Header incorrect type");if(void 0===e.payload)throw new l.JWSInvalid("JWS Payload missing");if("string"!=typeof e.signature)throw new l.JWSInvalid("JWS Signature missing or incorrect type");if(void 0!==e.header&&!(0,h.A)(e.header))throw new l.JWSInvalid("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=(0,n.D4)(e.protected);o=JSON.parse(u.D0.decode(t))}catch(e){throw new l.JWSInvalid("JWS Protected Header is invalid")}if(!(0,d.A)(o,e.header))throw new l.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...o,...e.header};let a=!0;if((0,p.A)(l.JWSInvalid,new Map([["b64",!0]]),null==r?void 0:r.crit,o,s).has("b64")&&(a=o.b64,"boolean"!=typeof a))throw new l.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:y}=s;if("string"!=typeof y||!y)throw new l.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');const m=r&&(0,g.A)("algorithms",r.algorithms);if(m&&!m.has(y))throw new l.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(a){if("string"!=typeof e.payload)throw new l.JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new l.JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let v=!1;"function"==typeof t&&(t=await t(o,e),v=!0),(0,f.A)(y,t,"verify");const b=(0,u.xW)(u.Rd.encode(null!==(i=e.protected)&&void 0!==i?i:""),u.Rd.encode("."),"string"==typeof e.payload?u.Rd.encode(e.payload):e.payload);let w,_;try{w=(0,n.D4)(e.signature)}catch(e){throw new l.JWSInvalid("Failed to base64url decode the signature")}if(!await c(y,t,w,b))throw new l.JWSSignatureVerificationFailed;if(a)try{_=(0,n.D4)(e.payload)}catch(e){throw new l.JWSInvalid("Failed to base64url decode the payload")}else _="string"==typeof e.payload?u.Rd.encode(e.payload):e.payload;const S={payload:_};return void 0!==e.protected&&(S.protectedHeader=o),void 0!==e.header&&(S.unprotectedHeader=e.header),v?{...S,key:t}:S}},3085:function(e,t,r){"use strict";r.d(t,{G:function(){return s}});var n=r(2222),i=r(149),o=r(6957);class s{constructor(e){if(!(0,i.A)(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return this._payload="number"==typeof e?{...this._payload,nbf:e}:{...this._payload,nbf:(0,n.A)(new Date)+(0,o.A)(e)},this}setExpirationTime(e){return this._payload="number"==typeof e?{...this._payload,exp:e}:{...this._payload,exp:(0,n.A)(new Date)+(0,o.A)(e)},this}setIssuedAt(e){return this._payload=void 0===e?{...this._payload,iat:(0,n.A)(new Date)}:{...this._payload,iat:e},this}}},7248:function(e,t,r){"use strict";r.d(t,{P:function(){return a}});var n=r(2609),i=r(7493),o=r(9095),s=r(3085);class a extends s.G{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){var r;const s=new n.T(o.Rd.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(null===(r=this._protectedHeader)||void 0===r?void 0:r.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new i.JWTInvalid("JWTs MUST NOT use unencoded payload");return s.sign(e,t)}}},9380:function(e,t,r){"use strict";r.d(t,{V:function(){return s}});var n=r(5609),i=r(9803),o=r(7493);async function s(e,t,r){var s;const a=await(0,n.B)(e,t,r);if((null===(s=a.protectedHeader.crit)||void 0===s?void 0:s.includes("b64"))&&!1===a.protectedHeader.b64)throw new o.JWTInvalid("JWTs MUST NOT use unencoded payload");const c={payload:(0,i.A)(a.protectedHeader,a.payload,r),protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}},5130:function(e,t,r){"use strict";r.d(t,{JU:function(){return d},Yp:function(){return u},Y5:function(){return l}});var n=r(5141),i=r(7991),o=r(1575),s=r(1436),a=r(5994),c=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:(0,s.lF)(e)};if(!(0,i.R)(e))throw new TypeError((0,o.A)(e,...a.g,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:c,...l}=await i.A.subtle.exportKey("jwk",e);return l};async function l(e){return(0,n.Nj)(e)}async function u(e){return(0,n.Jq)(e)}async function d(e){return c(e)}},7307:function(e,t,r){"use strict";r.d(t,{T:function(){return i}});var n=r(8793);async function i(e,t){return(0,n.T)(e,t)}},8136:function(e,t,r){"use strict";r.d(t,{Og:function(){return h},Lf:function(){return d},jU:function(){return l},Mh:function(){return u}});var n=r(1436),i=r(5141),o=r(7991),s=r(7493),a=async e=>{var t,r;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:i,keyUsages:a}=function(e){let t,r;switch(e.kty){case"oct":switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new s.JOSENotSupported(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),c=[i,null!==(t=e.ext)&&void 0!==t&&t,null!==(r=e.key_ops)&&void 0!==r?r:a];if("PBKDF2"===i.name)return o.A.subtle.importKey("raw",(0,n.D4)(e.k),...c);const l={...e};return delete l.alg,delete l.use,o.A.subtle.importKey("jwk",l,...c)},c=r(149);async function l(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw new TypeError('"spki" must be SPKI formatted string');return(0,i.sc)(e,t,r)}async function u(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw new TypeError('"x509" must be X.509 formatted string');return(0,i.zp)(e,t,r)}async function d(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return(0,i.IG)(e,t,r)}async function h(e,t,r){var i;if(!(0,c.A)(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return null!=r||(r=!0!==e.ext),r?a({...e,alg:t,ext:null!==(i=e.ext)&&void 0!==i&&i}):(0,n.D4)(e.k);case"RSA":if(void 0!==e.oth)throw new s.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return a({...e,alg:t});default:throw new s.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}}},9095:function(e,t,r){"use strict";r.d(t,{D0:function(){return o},Kp:function(){return h},MT:function(){return c},Rd:function(){return i},VS:function(){return d},mx:function(){return u},xW:function(){return a},yI:function(){return f}});var n=r(610);const i=new TextEncoder,o=new TextDecoder,s=2**32;function a(...e){const t=e.reduce(((e,{length:t})=>e+t),0),r=new Uint8Array(t);let n=0;return e.forEach((e=>{r.set(e,n),n+=e.length})),r}function c(e,t){return a(i.encode(e),new Uint8Array([0]),t)}function l(e,t,r){if(t<0||t>=s)throw new RangeError(`value must be >= 0 and <= ${s-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,255&t],r)}function u(e){const t=Math.floor(e/s),r=e%s,n=new Uint8Array(8);return l(n,t,0),l(n,r,4),n}function d(e){const t=new Uint8Array(4);return l(t,e),t}function h(e){return a(d(e.length),e)}async function f(e,t,r){const i=Math.ceil((t>>3)/32),o=new Uint8Array(32*i);for(let t=0;t>3)}},8858:function(e,t,r){"use strict";var n=r(1575),i=r(5994);t.A=(e,t,r)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?((e,t)=>{if(!(t instanceof Uint8Array)){if(!(0,i.A)(t))throw new TypeError((0,n.t)(e,t,...i.g,"Uint8Array"));if("secret"!==t.type)throw new TypeError(`${i.g.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}})(e,t):((e,t,r)=>{if(!(0,i.A)(t))throw new TypeError((0,n.t)(e,t,...i.g));if("secret"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${i.g.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)})(e,t,r)}},2698:function(e,t,r){"use strict";function n(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function i(e,t){return e.name===t}function o(e){return parseInt(e.name.slice(4),10)}function s(e,t){if(t.length&&!t.some((t=>e.usages.includes(t)))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}function a(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!i(e.algorithm,"HMAC"))throw n("HMAC");const r=parseInt(t.slice(2),10);if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!i(e.algorithm,"RSASSA-PKCS1-v1_5"))throw n("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!i(e.algorithm,"RSA-PSS"))throw n("RSA-PSS");const r=parseInt(t.slice(2),10);if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw n("Ed25519 or Ed448");break;case"ES256":case"ES384":case"ES512":{if(!i(e.algorithm,"ECDSA"))throw n("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw n(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}s(e,r)}function c(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!i(e.algorithm,"AES-GCM"))throw n("AES-GCM");const r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw n(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!i(e.algorithm,"AES-KW"))throw n("AES-KW");const r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw n(r,"algorithm.length");break}case"ECDH":switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw n("ECDH, X25519, or X448")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!i(e.algorithm,"PBKDF2"))throw n("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!i(e.algorithm,"RSA-OAEP"))throw n("RSA-OAEP");const r=parseInt(t.slice(9),10)||1;if(o(e.algorithm.hash)!==r)throw n(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}s(e,r)}r.d(t,{$:function(){return c},Y:function(){return a}})},2222:function(e,t){"use strict";t.A=e=>Math.floor(e.getTime()/1e3)},1575:function(e,t,r){"use strict";function n(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&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function i(e,t,...r){return n(`Key for the ${e} algorithm must be `,t,...r)}r.d(t,{t:function(){return i}}),t.A=(e,...t)=>n("Key must be ",e,...t)},9874:function(e,t){"use strict";t.A=(...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0}},149:function(e,t,r){"use strict";function n(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}r.d(t,{A:function(){return n}})},9803:function(e,t,r){"use strict";var n=r(7493),i=r(9095),o=r(2222),s=r(6957),a=r(149);const c=e=>e.toLowerCase().replace(/^application\//,"");t.A=(e,t,r={})=>{const{typ:l}=r;if(l&&("string"!=typeof e.typ||c(e.typ)!==c(l)))throw new n.JWTClaimValidationFailed('unexpected "typ" JWT header value',"typ","check_failed");let u;try{u=JSON.parse(i.D0.decode(t))}catch(e){}if(!(0,a.A)(u))throw new n.JWTInvalid("JWT Claims Set must be a top-level JSON object");const{requiredClaims:d=[],issuer:h,subject:f,audience:p,maxTokenAge:g}=r;void 0!==g&&d.push("iat"),void 0!==p&&d.push("aud"),void 0!==f&&d.push("sub"),void 0!==h&&d.push("iss");for(const e of new Set(d.reverse()))if(!(e in u))throw new n.JWTClaimValidationFailed(`missing required "${e}" claim`,e,"missing");if(h&&!(Array.isArray(h)?h:[h]).includes(u.iss))throw new n.JWTClaimValidationFailed('unexpected "iss" claim value',"iss","check_failed");if(f&&u.sub!==f)throw new n.JWTClaimValidationFailed('unexpected "sub" claim value',"sub","check_failed");if(p&&(m="string"==typeof p?[p]:p,!("string"==typeof(y=u.aud)?m.includes(y):Array.isArray(y)&&m.some(Set.prototype.has.bind(new Set(y))))))throw new n.JWTClaimValidationFailed('unexpected "aud" claim value',"aud","check_failed");var y,m;let v;switch(typeof r.clockTolerance){case"string":v=(0,s.A)(r.clockTolerance);break;case"number":v=r.clockTolerance;break;case"undefined":v=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:b}=r,w=(0,o.A)(b||new Date);if((void 0!==u.iat||g)&&"number"!=typeof u.iat)throw new n.JWTClaimValidationFailed('"iat" claim must be a number',"iat","invalid");if(void 0!==u.nbf){if("number"!=typeof u.nbf)throw new n.JWTClaimValidationFailed('"nbf" claim must be a number',"nbf","invalid");if(u.nbf>w+v)throw new n.JWTClaimValidationFailed('"nbf" claim timestamp check failed',"nbf","check_failed")}if(void 0!==u.exp){if("number"!=typeof u.exp)throw new n.JWTClaimValidationFailed('"exp" claim must be a number',"exp","invalid");if(u.exp<=w-v)throw new n.JWTExpired('"exp" claim timestamp check failed',"exp","check_failed")}if(g){const e=w-u.iat;if(e-v>("number"==typeof g?g:(0,s.A)(g)))throw new n.JWTExpired('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(e<0-v)throw new n.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return u}},6957:function(e,t){"use strict";const r=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;t.A=e=>{const t=r.exec(e);if(!t)throw new TypeError("Invalid time period format");const n=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(n);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(60*n);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(3600*n);case"day":case"days":case"d":return Math.round(86400*n);case"week":case"weeks":case"w":return Math.round(604800*n);default:return Math.round(31557600*n)}}},4618:function(e,t){"use strict";t.A=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some((e=>"string"!=typeof e))))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}},2168:function(e,t,r){"use strict";var n=r(7493);t.A=function(e,t,r,i,o){if(void 0!==o.crit&&void 0===i.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||void 0===i.crit)return new Set;if(!Array.isArray(i.crit)||0===i.crit.length||i.crit.some((e=>"string"!=typeof e||0===e.length)))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of i.crit){if(!s.has(t))throw new n.JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===i[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(i.crit)}},5141:function(e,t,r){"use strict";r.d(t,{IG:function(){return g},sc:function(){return y},zp:function(){return b},Jq:function(){return d},Nj:function(){return u}});var n=r(7991),i=r(1575),o=r(1436),s=(e,t)=>`-----BEGIN ${t}-----\n${(e.match(/.{1,64}/g)||[]).join("\n")}\n-----END ${t}-----`,a=r(7493),c=r(5994);const l=async(e,t,r)=>{if(!(0,n.R)(r))throw new TypeError((0,i.A)(r,...c.g));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return s((0,o.WG)(new Uint8Array(await n.A.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},u=e=>l("public","spki",e),d=e=>l("private","pkcs8",e),h=(e,t,r=0)=>{0===r&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(-1===n)return!1;const i=e.subarray(n,n+t.length);return i.length===t.length&&(i.every(((e,r)=>e===t[r]))||h(e,t,n+1))},f=e=>{switch(!0){case h(e,[42,134,72,206,61,3,1,7]):return"P-256";case h(e,[43,129,4,0,34]):return"P-384";case h(e,[43,129,4,0,35]):return"P-521";case h(e,[43,101,110]):return"X25519";case h(e,[43,101,111]):return"X448";case h(e,[43,101,112]):return"Ed25519";case h(e,[43,101,113]):return"Ed448";default:throw new a.JOSENotSupported("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},p=async(e,t,r,i,o)=>{var s;let c,l;const u=new Uint8Array(atob(r.replace(e,"")).split("").map((e=>e.charCodeAt(0)))),d="spki"===t;switch(i){case"PS256":case"PS384":case"PS512":c={name:"RSA-PSS",hash:`SHA-${i.slice(-3)}`},l=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":c={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${i.slice(-3)}`},l=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":c={name:"RSA-OAEP",hash:`SHA-${parseInt(i.slice(-3),10)||1}`},l=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":c={name:"ECDSA",namedCurve:"P-256"},l=d?["verify"]:["sign"];break;case"ES384":c={name:"ECDSA",namedCurve:"P-384"},l=d?["verify"]:["sign"];break;case"ES512":c={name:"ECDSA",namedCurve:"P-521"},l=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=f(u);c=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},l=d?[]:["deriveBits"];break}case"EdDSA":c={name:f(u)},l=d?["verify"]:["sign"];break;default:throw new a.JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value')}return n.A.subtle.importKey(t,u,c,null!==(s=null==o?void 0:o.extractable)&&void 0!==s&&s,l)},g=(e,t,r)=>p(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),y=(e,t,r)=>p(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function m(e){let t=[],r=0;for(;r=128;)r=128*r+e[t]-128,t++;r=128*r+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else{if(128===n){for(n=0;0!==e[t+n]||0!==e[t+n+1];){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}const r=t+n+2;return{byteLength:r,contents:e.subarray(t,t+n),raw:e.subarray(0,r)}}{let r=127&e[t];t++,n=0;for(let i=0;i{let n;try{n=function(e){const t=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=(0,o.y4)(t);return s(function(e){const t=m(m(v(e).contents)[0].contents);return(0,o.WG)(t[160===t[0].raw[0]?6:5].raw)}(r),"PUBLIC KEY")}(e)}catch(e){throw new TypeError("Failed to parse the X.509 certificate",{cause:e})}return y(n,t,r)}},1436:function(e,t,r){"use strict";r.d(t,{D4:function(){return a},WG:function(){return i},lF:function(){return o},y4:function(){return s}});var n=r(9095);const i=e=>{let t=e;"string"==typeof t&&(t=n.Rd.encode(t));const r=[];for(let e=0;ei(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),s=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e{let t=e;t instanceof Uint8Array&&(t=n.D0.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return s(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}},4495:function(e,t){"use strict";t.A=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}},610:function(e,t,r){"use strict";var n=r(7991);t.A=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await n.A.subtle.digest(r,t))}},8793:function(e,t,r){"use strict";r.d(t,{K:function(){return s},T:function(){return c}});var n=r(7991),i=r(7493),o=r(8057);async function s(e,t){var r;let s,a,c;switch(e){case"HS256":case"HS384":case"HS512":s=parseInt(e.slice(-3),10),a={name:"HMAC",hash:`SHA-${s}`,length:s},c=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return s=parseInt(e.slice(-3),10),(0,o.A)(new Uint8Array(s>>3));case"A128KW":case"A192KW":case"A256KW":s=parseInt(e.slice(1,4),10),a={name:"AES-KW",length:s},c=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":s=parseInt(e.slice(1,4),10),a={name:"AES-GCM",length:s},c=["encrypt","decrypt"];break;default:throw new i.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return n.A.subtle.generateKey(a,null!==(r=null==t?void 0:t.extractable)&&void 0!==r&&r,c)}function a(e){var t;const r=null!==(t=null==e?void 0:e.modulusLength)&&void 0!==t?t:2048;if("number"!=typeof r||r<2048)throw new i.JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function c(e,t){var r,o,s;let c,l;switch(e){case"PS256":case"PS384":case"PS512":c={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:a(t)},l=["sign","verify"];break;case"RS256":case"RS384":case"RS512":c={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:a(t)},l=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":c={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:a(t)},l=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":c={name:"ECDSA",namedCurve:"P-256"},l=["sign","verify"];break;case"ES384":c={name:"ECDSA",namedCurve:"P-384"},l=["sign","verify"];break;case"ES512":c={name:"ECDSA",namedCurve:"P-521"},l=["sign","verify"];break;case"EdDSA":l=["sign","verify"];const n=null!==(r=null==t?void 0:t.crv)&&void 0!==r?r:"Ed25519";switch(n){case"Ed25519":case"Ed448":c={name:n};break;default:throw new i.JOSENotSupported("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{l=["deriveKey","deriveBits"];const e=null!==(o=null==t?void 0:t.crv)&&void 0!==o?o:"P-256";switch(e){case"P-256":case"P-384":case"P-521":c={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":c={name:e};break;default:throw new i.JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new i.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return n.A.subtle.generateKey(c,null!==(s=null==t?void 0:t.extractable)&&void 0!==s&&s,l)}},676:function(e,t,r){"use strict";r.d(t,{A:function(){return a}});var n=r(7991),i=r(2698),o=r(1575),s=r(5994);function a(e,t,r){if((0,n.R)(t))return(0,i.Y)(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError((0,o.A)(t,...s.g));return n.A.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError((0,o.A)(t,...s.g,"Uint8Array"))}},5994:function(e,t,r){"use strict";r.d(t,{g:function(){return i}});var n=r(7991);t.A=e=>(0,n.R)(e);const i=["CryptoKey"]},8057:function(e,t,r){"use strict";var n=r(7991);t.A=n.A.getRandomValues.bind(n.A)},1020:function(e,t,r){"use strict";r.d(t,{A:function(){return i}});var n=r(7493);function i(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new n.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}},7991:function(e,t,r){"use strict";r.d(t,{R:function(){return n}}),t.A=crypto;const n=e=>e instanceof CryptoKey},7493:function(e,t,r){"use strict";r.r(t),r.d(t,{JOSEAlgNotAllowed:function(){return s},JOSEError:function(){return n},JOSENotSupported:function(){return a},JWEDecompressionFailed:function(){return l},JWEDecryptionFailed:function(){return c},JWEInvalid:function(){return u},JWKInvalid:function(){return f},JWKSInvalid:function(){return p},JWKSMultipleMatchingKeys:function(){return y},JWKSNoMatchingKey:function(){return g},JWKSTimeout:function(){return m},JWSInvalid:function(){return d},JWSSignatureVerificationFailed:function(){return v},JWTClaimValidationFailed:function(){return i},JWTExpired:function(){return o},JWTInvalid:function(){return h}});class n extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(e){var t;super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor)}}class i extends n{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(e,t="unspecified",r="unspecified"){super(e),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=r}}class o extends n{static get code(){return"ERR_JWT_EXPIRED"}constructor(e,t="unspecified",r="unspecified"){super(e),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=r}}class s extends n{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}}class a extends n{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class c extends n{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}}class l extends n{constructor(){super(...arguments),this.code="ERR_JWE_DECOMPRESSION_FAILED",this.message="decompression operation failed"}static get code(){return"ERR_JWE_DECOMPRESSION_FAILED"}}class u extends n{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}}class d extends n{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class h extends n{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}class f extends n{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}}class p extends n{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}}class g extends n{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}}class y extends n{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Symbol.asyncIterator;class m extends n{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}}class v extends n{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n=r(423);return n.default}()})); //# sourceMappingURL=remotestorage.js.map \ No newline at end of file diff --git a/remotestorage.js.map b/remotestorage.js.map index 603e735..9343745 100644 --- a/remotestorage.js.map +++ b/remotestorage.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://RemoteStorage/webpack/universalModuleDefinition","webpack://RemoteStorage/webpack/bootstrap","webpack://RemoteStorage/./src/util.ts","webpack://RemoteStorage/./src/log.ts","webpack://RemoteStorage/./src/eventhandling.ts","webpack://RemoteStorage/./src/config.ts","webpack://RemoteStorage/./src/unauthorized-error.ts","webpack://RemoteStorage/(webpack)/buildin/global.js","webpack://RemoteStorage/./src/authorize.ts","webpack://RemoteStorage/./src/baseclient.ts","webpack://RemoteStorage/./src/wireclient.ts","webpack://RemoteStorage/./src/sync-error.ts","webpack://RemoteStorage/./src/cachinglayer.ts","webpack://RemoteStorage/./src/access.ts","webpack://RemoteStorage/./src/caching.ts","webpack://RemoteStorage/./src/googledrive.ts","webpack://RemoteStorage/./src/dropbox.ts","webpack://RemoteStorage/./src/discover.ts","webpack://RemoteStorage/./src/env.ts","webpack://RemoteStorage/./src/remotestorage.ts","webpack://RemoteStorage/./node_modules/buffer/index.js","webpack://RemoteStorage/./node_modules/base64-js/index.js","webpack://RemoteStorage/./node_modules/ieee754/index.js","webpack://RemoteStorage/./node_modules/isarray/index.js","webpack://RemoteStorage/./node_modules/tv4/tv4.js","webpack://RemoteStorage/./src/types.ts","webpack://RemoteStorage/./src/schema-not-found-error.ts","webpack://RemoteStorage/./src/revisioncache.ts","webpack://RemoteStorage/./node_modules/webfinger.js/src/webfinger.js","webpack://RemoteStorage/./node_modules/webfinger.js/node_modules/xhr2/lib/browser.js","webpack://RemoteStorage/./src/features.ts","webpack://RemoteStorage/./src/syncedgetputdelete.ts","webpack://RemoteStorage/./src/sync.ts","webpack://RemoteStorage/./src/indexeddb.ts","webpack://RemoteStorage/./src/localstorage.ts","webpack://RemoteStorage/./src/inmemorystorage.ts"],"names":["root","factory","exports","module","define","amd","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","logError","error","console","message","stack","globalContext","window","self","global","getGlobalContext","extend","args","target","Array","slice","forEach","source","containingFolder","path","replace","isFolder","substr","isDocument","baseName","parts","split","length","cleanPath","map","encodeURIComponent","join","bindAll","equal","a","b","seen","toString","ArrayBuffer","Uint8Array","seenArg","indexOf","push","deepClone","obj","undefined","clone","JSON","parse","stringify","_fixArrayBuffers","srcObj","dstObj","isArray","field","byteLength","srcArr","Int8Array","set","pathsFromRoot","paths","pop","localStorageAvailable","context","localStorage","setItem","removeItem","getJSONFromLocalStorage","getItem","e","shouldBeTreatedAsBinary","content","mimeType","match","test","getTextFromArrayBuffer","arrayBuffer","encoding","Promise","resolve","Blob","buffer","Buffer","blob","gc","BlobBuilder","WebKitBlobBuilder","bb","append","getBlob","fileReader","FileReader","addEventListener","evt","result","onloadend","readAsText","toBase64","str","from","derivedCtor","baseCtors","baseCtor","getOwnPropertyNames","getOwnPropertyDescriptor","logging","log","additionalEvents","evName","_addEvent","eventName","handler","Error","_validateEvent","_handlers","hl","splice","apply","on","event","_emit","config","cache","changeEvents","local","remote","conflict","cordovaRedirectUri","backgroundSyncInterval","disableFeatures","discoveryTimeout","isBackground","requestTimeout","syncInterval","UnauthorizedError","options","super","code","g","Function","onFeaturesLoaded","extractParams","url","location","Authorize","getLocation","href","hashPos","urlFragment","substring","includes","reduce","params","kvs","kv","stateValue","decodeURIComponent","encodedData","atob","RegExp","remoteStorage","authURL","scope","redirectUri","clientId","backend","discoveryData","userAddress","storageApi","properties","buildOAuthURL","openWindow","then","authResult","configure","token","access_token","setLocation","document","removeEventListener","IMPLIED_FAKE_TOKEN","reject","newWindow","open","closed","handleExit","close","_rs_init","hash","authParamsUsed","rsDiscovery","remotestorage","connect","state","stopWaitingForToken","BaseClient","storage","base","schemas","configurable","Types","inScope","moduleName","makePath","addEvents","onChange","_fireChange","maxAge","statusCode","body","keys","calls","all","data","contentType","revision","access","checkPathPermission","warn","put","typeAlias","_attachType","validationResult","validate","valid","exc","delete","connected","strategy","caching","flush","alias","uriOrSchema","schema","uri","_defaultTypeURI","declare","getSchema","validateResult","resolveAlias","origin","fieldNamePrefix","exec","applyMixins","hasLocalStorage","SETTINGS_KEY","STORAGE_APIS","isArrayBufferView","ArrayBufferView","arrayBufferViews","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","addQuotes","stripQuotes","WireClient","rs","_revisionCache","settings","readSettings","setTimeout","spec","method","headers","getEtag","fakeRevision","isForbiddenRequestMethod","request","responseType","response","online","success","status","getResponseHeader","isSuccessStatus","charset","charsetMatch","determineCharset","textContent","_storageApi","supportsRevs","ifNoneMatch","_request","itemsMap","item","items","ETag","ifMatch","fetch","_fetchRequest","XMLHttpRequest","_xhrRequest","syntheticXhr","responseHeaders","abortController","AbortController","networkPromise","signal","headerName","toUpperCase","readyState","statusText","responseURL","json","text","processedBody","responseText","timeoutPromise","abort","race","timedOut","timer","xhr","setRequestHeader","onload","clearTimeout","onerror","send","SyncError","originalError","CachingLayer","_updateNodesRunning","_updateNodesQueued","queueGetRequest","getNodes","objs","node","getLatest","isOutdated","_updateNodes","nodePaths","nodes","len","nodePath","previous","makeNode","previousBody","previousContentType","updateFolderNodeWithItemName","common","itemName","_getAllDescendentPaths","_emitChange","oldValue","newValue","setNodes","forAllNodes","latest","oldContentType","newContentType","diffHandler","_processNodes","_doUpdateNodes","promise","cb","existingNodes","_emitChangeEvents","err","nextJob","shift","events","allPaths","nodeVersion","timestamp","Date","getTime","reset","scopeModeMap","scopes","_scopeNameForParameter","_adjustRootPaths","savedMap","claim","actualMode","checkPermission","_getModuleName","rootPaths","moduleMatch","newScope","storageType","type","pendingActivations","_rootPaths","activateHandler","checkPath","BASE_URL","metaTitleFromFileName","filename","parentPath","googleDrivePath","removeQuotes","FileIdCache","_items","now","v","GoogleDrive","_fileIdCache","writeSettingsToCache","handleError","info","user","emailAddress","catch","setBackend","authorize","_getFolder","_getFile","fullPath","putDone","meta","etagWithoutQuotes","etag","_getFileId","id","_updateFile","_createFile","_getMeta","resp","metadata","_getParentId","parentId","title","parents","kind","downloadUrl","exportLinks","query","labels","trashed","fileSize","foldername","_createFolder","apiKeys","googledrive","_origRemote","_origBaseClientGetItemURL","getItemURL","getDropboxPath","PATH_PREFIX","compareApiError","expect","error_summary","isBinaryData","Dropbox","_initialFetchDone","dropbox","appKey","_revCache","_fetchDeltaCursor","_fetchDeltaPromise","_itemRefs","hookIt","email","revCache","processResponse","listing","entries","isDir","path_lower","rev","has_more","loadNext","cursor","nextListing","assign","savedRev","fetchDelta","mime","_shareIfNeeded","needsMetadata","uploadParams","_getMetadata","_uploadSimple","res","_deleteSimple","share","_getSharedLink","link","requestBody","recursive","include_deleted","responseBody","deactivatePropagation","entry","activatePropagation","ProgressEvent","update","mute","direct_only","links","unHookRemote","_dropboxOrigSync","sync","unHookSync","unHookGetItemURL","unHookSyncCycle","unHookIt","hookSync","_dropboxOrigSyncCycle","syncCycle","hookRemote","hookSyncCycle","hookGetItemURL","haveXMLHttpRequest","cachedInfo","Discover","tls_only","uri_fallback","request_timeout","lookup","idx","DiscoveryError","constructor","_rs_supported","_rs_cleanup","Env","setBrowserPrefixedNames","visibilityChangeEvent","setVisibility","hidden","hiddenProperty","goBackground","goForeground","emitUnauthorized","isValidInterval","interval","RemoteStorage","cfg","_pending","_cleanups","_pathHandlers","change","_init","loadFeatures","features","loadFeature","featureSupported","featureDone","featuresDone","featuresLoaded","featureInitialized","featureFailed","hasFeature","_setCachingModule","_collectCleanupFunctions","_fireReady","initFeature","_setGPD","_pendingGPD","origOn","_allLoaded","fireInitial","loadModules","addModule","setStorageType","scopeParameter","cordova","pathname","String","InAppBrowser","impliedauth","oneDone","cleanup","cleanupResult","what","validTypes","ApiKeyType","GOOGLE","DROPBOX","every","impl","wrap","func","methodName","methodArguments","pending","_dispatchEvent","pl","ev","relativePath","timeout","stopped","_syncTimer","getCurrentSyncInterval","syncStopped","moduleBuilder","builder","instance","_loadModule","camelizedName","Unauthorized","util","base64","ieee754","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","that","RangeError","__proto__","arg","encodingOrOffset","allocUnsafe","TypeError","array","byteOffset","fromArrayLike","fromArrayBuffer","string","isEncoding","actual","write","fromString","isBuffer","checked","copy","val","fromObject","assertSize","size","isView","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","start","end","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","isNaN","arrayIndexOf","lastIndexOf","arr","indexSize","arrLength","valLength","read","buf","readUInt16BE","foundIndex","found","j","hexWrite","offset","Number","remaining","strLen","parsed","parseInt","utf8Write","blitBuffer","asciiWrite","byteArray","charCodeAt","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","Math","min","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","fromCharCode","decodeCodePointsArray","SlowBuffer","alloc","INSPECT_MAX_BYTES","foo","subarray","typedArraySupport","poolSize","_augment","species","fill","allocUnsafeSlow","_isBuffer","compare","x","y","concat","list","pos","swap16","swap32","swap64","arguments","equals","inspect","max","thisStart","thisEnd","thisCopy","targetCopy","isFinite","toJSON","_arr","ret","out","toHex","bytes","checkOffset","ext","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","pow","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","floor","writeUInt16LE","writeUInt16BE","writeUInt32LE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","INVALID_BASE64_RE","Infinity","leadSurrogate","toByteArray","trim","stringtrim","base64clean","src","dst","b64","lens","getLens","validLen","placeHoldersLen","tmp","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","len2","encodeChunk","num","output","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","abs","LN2","hasDontEnumBug","dontEnums","dontEnumsLength","propertyIsEnumerable","prop","F","vArg","searchElement","k","isFrozen","random","uriTemplateGlobalModifiers","uriTemplateSuffices","notReallyPercentEncode","encodeURI","doubleEncoded","uriTemplateSubstitution","modifier","charAt","separator","prefix","shouldEscape","showVariables","trimEmptyString","varNames","varList","varSpecs","varSpecMap","varName","truncate","suffices","varSpec","subFunction","valueFunction","startIndex","first","substitution","UriTemplate","template","textParts","prefixes","substitutions","part","remainder","funcs","fillFromObject","ValidatorContext","parent","collectMultiple","errorReporter","checkRecursive","trackUnknownProperties","missing","missingMap","formatValidators","errors","collectError","returnError","scanned","scannedFrozen","scannedFrozenSchemas","scannedFrozenValidationErrors","validatedSchemasKey","validationErrorsKey","knownPropertyPaths","unknownPropertyPaths","defaultErrorReporter","definedKeywords","recursiveCompare","A","B","defineKeyword","keyword","keywordFunction","createError","messageParams","dataPath","schemaPath","subErrors","ValidationError","prefixErrors","prefixWith","banUnknownProperties","unknownPath","ErrorCodes","UNKNOWN_PROPERTY","addFormat","format","validator","resolveRefs","urlHistory","CIRCULAR_REFERENCE","urls","baseUrl","fragment","pointerPath","component","searchSchemas","testUrl","isTrustedUrl","getDocumentUri","addSchema","normSchema","getSchemaMap","getSchemaUris","filterRegExp","getMissingUris","dropSchemas","validateAll","dataPathParts","schemaPathParts","dataPointerPath","topLevel","frozenIndex","startErrorCount","scannedFrozenSchemaIndex","scannedSchemasIndex","schemaIndex","frozenSchemaIndex","errorCount","validateBasic","validateNumeric","validateString","validateArray","validateObject","validateCombinations","validateHypermedia","validateFormat","validateDefinedKeywords","dataPart","schemaPart","errorMessage","FORMAT_CUSTOM","validationFunctions","KEYWORD_CUSTOM","validateType","validateEnum","dataType","allowedTypes","INVALID_TYPE","expected","ENUM_MISMATCH","validateMultipleOf","validateMinMax","validateNaN","CLOSE_ENOUGH_LOW","CLOSE_ENOUGH_HIGH","parseURI","protocol","authority","host","hostname","port","search","resolveUrl","input","baseUri","language","errorMessages","languages","messageTemplate","ErrorMessagesDefault","whole","subValue","multipleOf","divisibleBy","NUMBER_MULTIPLE_OF","minimum","NUMBER_MINIMUM","exclusiveMinimum","NUMBER_MINIMUM_EXCLUSIVE","maximum","NUMBER_MAXIMUM","exclusiveMaximum","NUMBER_MAXIMUM_EXCLUSIVE","NUMBER_NOT_A_NUMBER","validateStringLength","validateStringPattern","minLength","STRING_LENGTH_SHORT","maxLength","STRING_LENGTH_LONG","pattern","regexp","flags","literal","STRING_PATTERN","validateArrayLength","validateArrayUniqueItems","validateArrayItems","minItems","ARRAY_LENGTH_SHORT","maxItems","ARRAY_LENGTH_LONG","uniqueItems","ARRAY_UNIQUE","match1","match2","additionalItems","ARRAY_ADDITIONAL_ITEMS","validateObjectMinMaxProperties","validateObjectRequiredProperties","validateObjectProperties","validateObjectDependencies","minProperties","OBJECT_PROPERTIES_MINIMUM","propertyCount","maxProperties","OBJECT_PROPERTIES_MAXIMUM","required","OBJECT_REQUIRED","keyPointerPath","foundMatch","patternProperties","patternKey","additionalProperties","OBJECT_ADDITIONAL_PROPERTIES","dependencies","depKey","dep","OBJECT_DEPENDENCY_KEY","requiredKey","validateAllOf","validateAnyOf","validateOneOf","validateNot","allOf","subSchema","anyOf","oldUnknownPropertyPaths","oldKnownPropertyPaths","errorAtEnd","knownKey","unknownKey","ANY_OF_MISSING","oneOf","validIndex","ONE_OF_MULTIPLE","index1","index2","ONE_OF_MISSING","not","oldErrorCount","notErrors","NOT_PASSED","ldo","rel","allPresent","ErrorCodeLookup","stacktrace","dataPrefix","schemaPrefix","tv4","createApi","currentLanguage","customErrorReporter","api","setErrorReporter","reporter","addLanguage","messageMap","rootCode","freshApi","def","validateMultiple","defineError","codeName","codeNumber","defaultMessage","langCode","errorCodes","BaseClientTypes","uris","aliases","fullAlias","extends","extendedAlias","extendedUri","ml","SchemaNotFound","defaultValue","_itemsRev","_storage","_canPropagate","stored","_updateParentFolderItemRev","_propagate","_generateFolderRev","files","sort","_hashCode","parentFolder","_getParentFolder","parentFolderItemsRev","hashItems","newRev","_generateHash","folder","itemsRev","hashItem","LINK_URI_MAPS","LINK_PROPERTIES","URIS","generateErrorObject","WebFinger","webfist_fallback","__fetchJRD","errorHandler","sucessHandler","__fetchJRD_fetch","__fetchJRD_XHR","webfinger","ok","__isValidJSON","handlerSpent","__processState","isSecure","__makeRequest","onreadystatechange","ontimeout","__isLocalhost","__processJRD","URL","JRD","successHandler","parsedJRD","props","address","uri_index","__buildURL","__fallbackChecks","__call","webfist","lookupLink","Features","readyFired","featureModules","feature","featureName","supported","initResult","init","some","cachingLayer","_bindChange","_processPending","shareFirst","SyncedGetPutDelete","getSyncInterval","_wrapBusyDone","syncCycleCb","syncOnConnect","taskFor","action","nodeChanged","hasCommonRevision","Sync","_tasks","_running","_timeStarted","numThreads","onDiff","addTask","doTasks","onActivate","force02","contentLength","corruptItemsMap","corruptRevision","isCorrupt","needsFetch","needsPush","inConflict","needsRefresh","getParentPath","deleteChildPathsFromTasks","isStaleChild","needsRemotePut","needsRemoteDelete","hasNoRemoteChanges","lastCommonValue","lastCommonContentType","mergeMutualDeletion","autoMergeFolder","autoMergeDocument","changedNodes","missingChildren","recurse","childName","cachingStrategy","autoMerge","commonItem","localItem","parentNode","deleteRemoteTrees","changedObjs2","subPaths","collectSubPaths","changedNodes2","bodyOrItemsMap","pathsFromRootArr","collectMissingChildren","toBeSaved","successful","unAuth","notFound","changed","networkProblems","series","completeFetch","dataFromFetch","corruptServerItemsMap","markChildren","updateCommonTimestamp","interpretStatus","handleGetResponse","completePush","dealWithFailure","task","handleResponse","completed","collectTasks","hasTasks","done","numToHave","numAdded","numToAdd","doTask","finishTask","alsoCheckRefresh","collectDiffTasks","numDiffs","collectRefreshTasks","env","isBrowser","handleChange","isForeground","handleVisibility","startSync","stopSync","DEFAULT_DB","IndexedDB","database","db","getsRunning","putsRunning","changesQueued","changesRunning","commitSlownessWarning","misses","fromCache","getNodesFromDb","maybeFlush","flushChangesQueued","setInterval","clearInterval","setNodesInDb","transaction","objectStore","retrievedNodes","onsuccess","oncomplete","onabort","nodesStore","startTime","callback","dbName","clean","other","openCursor","migrate","continue","closeDB","req","indexedDB","onupgradeneeded","oldVersion","newVersion","createObjectStore","keyPath","objectStoreNames","contains","databaseName","deleteDatabase","poorIndexedDbSupport","navigator","userAgent","check","NODES_PREFIX","isRemoteStorageKey","LocalStorage","InMemoryStorage"],"mappings":";CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,gBAAiB,GAAIH,GACF,iBAAZC,QACdA,QAAuB,cAAID,IAE3BD,EAAoB,cAAIC,IAR1B,CASGK,MAAM,WACT,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,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,OAAO3P,QAAQC,UAQjB,mBASA,uBACE,OAAO,EAAAjB,wBAUT,qBACE,MAAMoJ,EAAO,GAEb,IAAK,IAAIjP,EAAI,EAAG8W,EAAM/Q,aAAarC,OAAQ1D,EAAI8W,EAAK9W,IAAK,CACvD,MAAMuB,EAAMwE,aAAaxE,IAAIvB,GACzBmzC,EAAmB5xC,IACrB0N,EAAKxK,KAAKlD,GAId0N,EAAKlM,QAASxB,IACZ,UAAI,0BAA2BA,UACxBwE,aAAaxE,MAO1B,EAAA2P,YAAYkiC,EAAc,CAAC,YAE3B,UAASA,G,iHCxHT,gBACA,WACA,OASA,MAAMC,UAAwB,UAI5B,cACE9oC,QAHM,KAAA67B,SAAmC,GAIzCxmC,KAAK+O,UAAU,CAAC,SAAU,sBAG5B,SAAShJ,GACP,MAAMkR,EAAiB,GAEvB,IAAK,IAAI7W,EAAI,EAAG8W,EAAMnR,EAAMjC,OAAQ1D,EAAI8W,EAAK9W,IAC3C6W,EAAMlR,EAAM3F,IAAMJ,KAAKwmC,SAASzgC,EAAM3F,IAGxC,OAAO6G,QAAQC,QAAQ+P,GAGzB,SAASA,GACP,IAAK,MAAM3T,KAAQ2T,OACGjS,IAAhBiS,EAAM3T,UACDtD,KAAKwmC,SAASljC,GAErBtD,KAAKwmC,SAASljC,GAAQ2T,EAAM3T,GAIhC,OAAO2D,QAAQC,UAGjB,YAAYsR,GACV,IAAK,MAAMlV,KAAQtD,KAAKwmC,SACtBhuB,EAAGxY,KAAKoyC,QAAQpyC,KAAKwmC,SAASljC,KAEhC,OAAO2D,QAAQC,UAGjB,eAWU,mBAWA,uBAER,OAAO,EAQC,uBAOZ,EAAAoK,YAAYmiC,EAAiB,CAAC,YAE9B,UAASA","file":"remotestorage.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"RemoteStorage\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"RemoteStorage\"] = factory();\n\telse\n\t\troot[\"RemoteStorage\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 17);\n","// Reusable utility functions\n\nimport Global = NodeJS.Global;\n\n/**\n * Takes an object and its copy as produced by the _deepClone function\n * below, and finds and fixes any ArrayBuffers that were cast to `{}` instead\n * of being cloned to new ArrayBuffers with the same content.\n *\n * It recurses into sub-objects, but skips arrays if they occur.\n */\nfunction _fixArrayBuffers(srcObj: object, dstObj: object) {\n if (typeof (srcObj) !== 'object' || Array.isArray(srcObj) || srcObj === null) {\n return;\n }\n for (const field in srcObj) {\n if (typeof (srcObj[field]) === 'object' && srcObj[field] !== null) {\n if (srcObj[field].toString() === '[object ArrayBuffer]') {\n dstObj[field] = new ArrayBuffer(srcObj[field].byteLength);\n const srcArr = new Int8Array(srcObj[field]);\n const dstArr = new Int8Array(dstObj[field]);\n dstArr.set(srcArr);\n } else {\n _fixArrayBuffers(srcObj[field], dstObj[field]);\n }\n }\n }\n}\n\nexport const logError = (error: string | Error): void => {\n if (typeof (error) === 'string') {\n console.error(error);\n } else {\n console.error(error.message, error.stack);\n }\n};\n\nexport const globalContext = (typeof (window) !== 'undefined' ? window : (typeof self === 'object' ? self : global));\n\nexport const getGlobalContext = (): any => {\n return (typeof (window) !== 'undefined' ? window : (typeof self === 'object' ? self : global));\n};\n\n// TODO Remove in favor of modern JS:\n// `const mergedObject = { ...obj1, ..obj2 }`\nexport const extend = (...args): unknown => {\n const target = args[0];\n const sources = Array.prototype.slice.call(args, 1);\n sources.forEach(function (source) {\n for (const key in source) {\n target[key] = source[key];\n }\n });\n return target;\n};\n\nexport const containingFolder = (path: string): string => {\n if (path === '') {\n return '/';\n }\n if (!path) {\n throw \"Path not given!\";\n }\n\n return path.replace(/\\/+/g, '/')\n .replace(/[^\\/]+\\/?$/, '');\n};\n\nexport const isFolder = (path: string): boolean => {\n return path.substr(-1) === '/';\n};\n\nexport const isDocument = (path: string): boolean => {\n return !isFolder(path);\n};\n\nexport const baseName = (path: string): string => {\n const parts = path.split('/');\n if (isFolder(path)) {\n return parts[parts.length - 2] + '/';\n } else {\n return parts[parts.length - 1];\n }\n};\n\nexport const cleanPath = (path: string): string => {\n return path.replace(/\\/+/g, '/')\n .split('/').map(encodeURIComponent).join('/')\n .replace(/'/g, '%27');\n};\n\nexport const bindAll = (object: object) => {\n for (const key in this) {\n if (typeof (object[key]) === 'function') {\n object[key] = object[key].bind(object);\n }\n }\n};\n\nexport const equal = (a: any, b: any, seen = []): boolean => {\n let key;\n\n if (typeof (a) !== typeof (b)) {\n return false;\n }\n\n if (typeof (a) === 'number' || typeof (a) === 'boolean' || typeof (a) === 'string') {\n return a === b;\n }\n\n if (typeof (a) === 'function') {\n return a.toString() === b.toString();\n }\n\n if (a instanceof ArrayBuffer && b instanceof ArrayBuffer) {\n // Without the following conversion the browsers wouldn't be able to\n // tell the ArrayBuffer instances apart.\n a = new Uint8Array(a);\n b = new Uint8Array(b);\n }\n\n // If this point has been reached, a and b are either arrays or objects.\n\n if (a instanceof Array) {\n if (a.length !== b.length) {\n return false;\n }\n\n for (let i = 0, c = a.length; i < c; i++) {\n if (!equal(a[i], b[i], seen)) {\n return false;\n }\n }\n } else {\n // Check that keys from a exist in b\n for (key in a) {\n if (a.hasOwnProperty(key) && !(key in b)) {\n return false;\n }\n }\n\n // Check that keys from b exist in a, and compare the values\n for (key in b) {\n if (!b.hasOwnProperty(key)) {\n continue;\n }\n\n if (!(key in a)) {\n return false;\n }\n\n let seenArg;\n\n if (typeof (b[key]) === 'object') {\n if (seen.indexOf(b[key]) >= 0) {\n // Circular reference, don't attempt to compare this object.\n // If nothing else returns false, the objects match.\n continue;\n }\n\n seenArg = seen.slice();\n seenArg.push(b[key]);\n }\n\n if (!equal(a[key], b[key], seenArg)) {\n return false;\n }\n }\n }\n\n return true;\n};\n\nexport const deepClone = (obj: any): any => {\n if (obj === undefined) {\n return undefined;\n } else {\n const clone = JSON.parse(JSON.stringify(obj));\n _fixArrayBuffers(obj, clone);\n return clone;\n }\n};\n\nexport const pathsFromRoot = (path: string): string[] => {\n const paths = [path];\n const parts = path.replace(/\\/$/, '').split('/');\n\n while (parts.length > 1) {\n parts.pop();\n paths.push(parts.join('/') + '/');\n }\n return paths;\n};\n\nexport const localStorageAvailable = (): boolean => {\n const context = getGlobalContext();\n\n if (!('localStorage' in context)) {\n return false;\n }\n\n try {\n context.localStorage.setItem('rs-check', '1');\n context.localStorage.removeItem('rs-check');\n return true;\n } catch (error) {\n return false;\n }\n};\n\n/**\n * Extract and parse JSON data from localStorage.\n *\n * @param {string} key - localStorage key\n *\n * @returns {object} parsed object or undefined\n */\nexport const getJSONFromLocalStorage = (key: string): { [key: string]: any } => {\n const context = getGlobalContext() as Window;\n\n try {\n return JSON.parse(context.localStorage.getItem(key));\n } catch (e) {\n // no JSON stored\n }\n};\n\n/**\n * Decide if data should be treated as binary based on the content (presence of non-printable characters\n * or replacement character) and content-type.\n *\n * @param {string} content - The data\n * @param {string} mimeType - The data's content-type\n *\n * @returns {boolean}\n */\nexport const shouldBeTreatedAsBinary = (content: string | ArrayBuffer, mimeType: string): boolean => {\n // eslint-disable-next-line no-control-regex\n return !!((mimeType && mimeType.match(/charset=binary/)) || /[\\x00-\\x08\\x0E-\\x1F\\uFFFD]/.test(content as string));\n};\n\n/**\n * Read data from an ArrayBuffer and return it as a string\n * @param {ArrayBuffer} arrayBuffer\n * @param {string} encoding\n * @returns {Promise} Resolves with a string containing the data\n */\nexport const getTextFromArrayBuffer = (arrayBuffer: ArrayBuffer, encoding: string): Promise => {\n return new Promise((resolve/*, reject*/) => {\n if (typeof Blob === 'undefined') {\n const buffer = new Buffer(new Uint8Array(arrayBuffer));\n resolve(buffer.toString(encoding));\n } else {\n let blob;\n const gc = globalContext as any;\n // TODO fix as BlobBuilder is not available in all browsers\n // @see https://developer.mozilla.org/en-US/docs/Web/API/BlobBuilder\n gc.BlobBuilder = gc.BlobBuilder || gc.WebKitBlobBuilder;\n if (typeof gc.BlobBuilder !== 'undefined') {\n const bb = new gc.BlobBuilder();\n bb.append(arrayBuffer);\n blob = bb.getBlob();\n } else {\n blob = new Blob([arrayBuffer]);\n }\n\n const fileReader = new FileReader();\n if (typeof fileReader.addEventListener === 'function') {\n fileReader.addEventListener('loadend', function (evt) {\n resolve(evt.target.result);\n });\n } else {\n fileReader.onloadend = function (evt) {\n resolve(evt.target.result);\n };\n }\n fileReader.readAsText(blob, encoding);\n }\n });\n};\n\n/**\n * Encode string in base64\n * @param {String} str\n * @returns {String} base64-encoded string\n */\nexport const toBase64 = (str: string): string => {\n const context = getGlobalContext();\n if ('btoa' in context) {\n return context['btoa'](str);\n } else {\n return Buffer.from(str).toString('base64');\n }\n};\n\n/*\n * Apply mixins to an object\n *\n * https://www.typescriptlang.org/docs/handbook/mixins.html\n *\n * @param {object} Parent object\n * @param {Array} Mixins to apply methods from\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function applyMixins(derivedCtor: any, baseCtors: any[]): void {\n baseCtors.forEach(baseCtor => {\n Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {\n Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));\n });\n });\n}\n","import config from './config';\n\n/**\n * Log using console.log, when remoteStorage logging is enabled.\n *\n * You can enable logging with ``RemoteStorage#enableLog``.\n *\n * (You can also enable logging during remoteStorage object creation. See:\n * {@link RemoteStorage}).\n */\nfunction log(...args): void {\n if (config.logging) {\n // eslint-disable-next-line no-console\n console.log(...args);\n }\n}\n\nexport = log;\n","import log from './log';\n\n// TODO add real type for event\ntype EventHandler = (event?: unknown) => void;\n\nclass EventHandling {\n _handlers: { [key: string]: EventHandler[] };\n\n /**\n * Register event names\n *\n * TODO see if necessary, or can be done on the fly in addEventListener\n */\n addEvents(additionalEvents: string[]): void {\n additionalEvents.forEach(evName => this._addEvent(evName));\n }\n\n /**\n * Install an event handler for the given event name\n */\n addEventListener (eventName: string, handler: EventHandler): void {\n // Check type for public consumption of API\n if (typeof (eventName) !== 'string') {\n throw new Error('Argument eventName should be a string');\n }\n if (typeof (handler) !== 'function') {\n throw new Error('Argument handler should be a function');\n }\n log('[EventHandling] Adding event listener', eventName);\n this._validateEvent(eventName);\n this._handlers[eventName].push(handler);\n }\n\n /*\n * Alias for addEventListener\n */\n on (eventName: string, handler: EventHandler): void {\n return this.addEventListener(eventName, handler);\n }\n\n /**\n * Remove a previously installed event handler\n */\n removeEventListener (eventName: string, handler: EventHandler): void {\n this._validateEvent(eventName);\n const hl = this._handlers[eventName].length;\n for (let i = 0; i < hl; i++) {\n if (this._handlers[eventName][i] === handler) {\n this._handlers[eventName].splice(i, 1);\n return;\n }\n }\n }\n\n _emit (eventName: string, ...args): void {\n this._validateEvent(eventName);\n this._handlers[eventName].slice().forEach((handler) => {\n handler.apply(this, args);\n });\n }\n\n _validateEvent (eventName: string): void {\n if (!(eventName in this._handlers)) {\n throw new Error(\"Unknown event: \" + eventName);\n }\n }\n\n _delegateEvent (eventName: string, target): void {\n target.on(eventName, (event) => {\n this._emit(eventName, event);\n });\n }\n\n _addEvent (eventName: string): void {\n if (typeof this._handlers === 'undefined') {\n this._handlers = {};\n }\n this._handlers[eventName] = [];\n }\n}\n\nexport = EventHandling;\n","/**\n * The default config, merged with the object passed to the constructor of the\n * RemoteStorage object\n */\nconst config = {\n cache: true,\n changeEvents: {\n local: true,\n window: false,\n remote: true,\n conflict: true\n },\n cordovaRedirectUri: undefined,\n logging: false,\n modules: [],\n // the following are not public and will probably be moved away from the\n // default config\n backgroundSyncInterval: 60000,\n disableFeatures: [],\n discoveryTimeout: 10000,\n isBackground: false,\n requestTimeout: 30000,\n syncInterval: 10000\n};\n\nexport = config;\n","class UnauthorizedError extends Error {\n code: string;\n\n constructor (message?: string, options: {code?: string} = {}) {\n super();\n this.name = 'Unauthorized';\n\n if (typeof message === 'undefined') {\n this.message = 'App authorization expired or revoked.';\n } else {\n this.message = message;\n }\n\n if (typeof options.code !== 'undefined') {\n this.code = options.code;\n }\n\n this.stack = (new Error()).stack;\n };\n}\n\nexport = UnauthorizedError;\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","import log from './log';\nimport { localStorageAvailable, globalContext, toBase64 } from './util';\nimport UnauthorizedError from './unauthorized-error';\n\ninterface AuthOptions {\n authURL: string;\n scope?: string;\n clientId?: string;\n redirectUri?: string;\n}\n\ninterface AuthResult {\n access_token?: string;\n rsDiscovery?: object;\n error?: string;\n remotestorage?: string;\n state?: string;\n}\n\n// This is set in _rs_init and needed for removal in _rs_cleanup\nlet onFeaturesLoaded: Function;\n\nfunction extractParams (url?: string): AuthResult {\n // FF already decodes the URL fragment in document.location.hash, so use this instead:\n const location = url || Authorize.getLocation().href;\n const hashPos = location.indexOf('#');\n if (hashPos === -1) { return; }\n const urlFragment = location.substring(hashPos+1);\n // if hash is not of the form #key=val&key=val, it's probably not for us\n if (!urlFragment.includes('=')) { return; }\n\n return urlFragment.split('&').reduce(function(params, kvs) {\n const kv = kvs.split('=');\n\n if (kv[0] === 'state' && kv[1].match(/rsDiscovery/)) {\n // extract rsDiscovery data from the state param\n let stateValue = decodeURIComponent(kv[1]);\n const encodedData = stateValue.substr(stateValue.indexOf('rsDiscovery='))\n .split('&')[0]\n .split('=')[1];\n\n params['rsDiscovery'] = JSON.parse(atob(encodedData));\n\n // remove rsDiscovery param\n stateValue = stateValue.replace(new RegExp('&?rsDiscovery=' + encodedData), '');\n\n if (stateValue.length > 0) {\n params['state'] = stateValue;\n }\n } else {\n params[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n }\n\n return params;\n }, {});\n}\n\nfunction buildOAuthURL (authURL: string, redirectUri: string, scope: string, clientId: string): string {\n const hashPos = redirectUri.indexOf('#');\n let url = authURL;\n\n url += authURL.indexOf('?') > 0 ? '&' : '?';\n url += 'redirect_uri=' + encodeURIComponent(redirectUri.replace(/#.*$/, ''));\n url += '&scope=' + encodeURIComponent(scope);\n url += '&client_id=' + encodeURIComponent(clientId);\n\n if (hashPos !== - 1 && hashPos+1 !== redirectUri.length) {\n url += '&state=' + encodeURIComponent(redirectUri.substring(hashPos+1));\n }\n url += '&response_type=token';\n\n return url;\n}\n\nclass Authorize {\n static IMPLIED_FAKE_TOKEN = false;\n\n static authorize (remoteStorage, { authURL, scope, redirectUri, clientId }: AuthOptions): void {\n log('[Authorize] authURL = ', authURL, 'scope = ', scope, 'redirectUri = ', redirectUri, 'clientId = ', clientId);\n\n // TODO add a test for this\n // keep track of the discovery data during redirect if we can't save it in localStorage\n if (!localStorageAvailable() && remoteStorage.backend === 'remotestorage') {\n redirectUri += redirectUri.indexOf('#') > 0 ? '&' : '#';\n\n const discoveryData = {\n userAddress: remoteStorage.remote.userAddress,\n href: remoteStorage.remote.href,\n storageApi: remoteStorage.remote.storageApi,\n properties: remoteStorage.remote.properties\n };\n\n redirectUri += 'rsDiscovery=' + toBase64(JSON.stringify(discoveryData));\n }\n\n const url = buildOAuthURL(authURL, redirectUri, scope, clientId);\n\n // FIXME declare potential `cordonva` property on global somehow, so we don't have to\n // use a string accessor here.\n if (globalContext['cordova']) {\n Authorize\n .openWindow(url, redirectUri, 'location=yes,clearsessioncache=yes,clearcache=yes')\n .then((authResult: AuthResult) => {\n remoteStorage.remote.configure({ token: authResult.access_token });\n });\n return;\n }\n\n Authorize.setLocation(url);\n }\n\n /**\n * Get current document location\n *\n * Override this method if access to document.location is forbidden\n */\n static getLocation = function (): Location {\n return document.location;\n };\n\n /**\n * Open new InAppBrowser window for OAuth in Cordova\n */\n static openWindow = function (url, redirectUri, options): Promise {\n return new Promise((resolve, reject): any => {\n\n const newWindow = open(url, '_blank', options);\n\n if (!newWindow || newWindow.closed) {\n return reject('Authorization popup was blocked');\n }\n\n function handleExit () {\n return reject('Authorization was canceled');\n };\n\n function handleLoadstart (event) {\n if (event.url.indexOf(redirectUri) !== 0) {\n return;\n }\n\n newWindow.removeEventListener('exit', handleExit);\n newWindow.close();\n\n const authResult: AuthResult = extractParams(event.url);\n\n if (!authResult) {\n return reject('Authorization error');\n }\n\n return resolve(authResult);\n };\n\n newWindow.addEventListener('loadstart', handleLoadstart);\n newWindow.addEventListener('exit', handleExit);\n });\n };\n\n /**\n * Set current document location\n *\n * Override this method if access to document.location is forbidden\n */\n static setLocation (location: string | Location): void {\n if (typeof location === 'string') {\n document.location.href = location;\n } else if (typeof location === 'object') {\n document.location = location;\n } else {\n throw \"Invalid location \" + location;\n }\n };\n\n static _rs_supported (): boolean {\n return typeof(document) !== 'undefined';\n };\n\n static _rs_init = function (remoteStorage): void {\n const params = extractParams();\n let location;\n\n if (params) {\n location = Authorize.getLocation();\n location.hash = '';\n }\n\n onFeaturesLoaded = function() {\n let authParamsUsed = false;\n\n if (!params) {\n remoteStorage.remote.stopWaitingForToken();\n return;\n };\n\n if (params.error) {\n if (params.error === 'access_denied') {\n throw new UnauthorizedError('Authorization failed: access denied', { code: 'access_denied' });\n } else {\n throw new UnauthorizedError(`Authorization failed: ${params.error}`);\n }\n }\n\n // rsDiscovery came with the redirect, because it couldn't be\n // saved in localStorage\n if (params.rsDiscovery) {\n remoteStorage.remote.configure(params.rsDiscovery);\n }\n\n if (params.access_token) {\n remoteStorage.remote.configure({ token: params.access_token });\n authParamsUsed = true;\n }\n\n if (params.remotestorage) {\n remoteStorage.connect(params.remotestorage);\n authParamsUsed = true;\n }\n\n if (params.state) {\n location = Authorize.getLocation();\n Authorize.setLocation(location.href.split('#')[0]+'#'+params.state);\n }\n\n if (!authParamsUsed) {\n remoteStorage.remote.stopWaitingForToken();\n }\n };\n\n remoteStorage.on('features-loaded', onFeaturesLoaded);\n };\n\n static _rs_cleanup (remoteStorage): void {\n remoteStorage.removeEventListener('features-loaded', onFeaturesLoaded);\n };\n};\n\nexport = Authorize;\n","import tv4 from 'tv4';\nimport type { ChangeObj } from './interfaces/change_obj';\nimport Types from './types';\nimport SchemaNotFound from './schema-not-found-error';\nimport EventHandling from './eventhandling';\nimport config from './config';\nimport { applyMixins, cleanPath } from './util';\nimport RemoteStorage from './remotestorage';\n\n/**\n * Provides a high-level interface to access data below a given root path.\n */\nclass BaseClient {\n /**\n * The instance this operates on.\n */\n storage: RemoteStorage;\n\n /**\n * Base path, which this operates on.\n *\n * For the module's privateClient this would be //, for the\n * corresponding publicClient /public//.\n */\n base: string;\n\n moduleName: string;\n\n constructor(storage: RemoteStorage, base: string) {\n if (base[base.length - 1] !== '/') {\n throw \"Not a folder: \" + base;\n }\n\n if (base === '/') {\n // allow absolute and relative paths for the root scope.\n this.makePath = (path: string): string => {\n return (path[0] === '/' ? '' : '/') + path;\n };\n }\n\n this.storage = storage;\n this.base = base;\n\n /**\n * TODO: document\n */\n const parts = this.base.split('/');\n if (parts.length > 2) {\n this.moduleName = parts[1];\n } else {\n this.moduleName = 'root';\n }\n\n this.addEvents(['change']);\n this.on = this.on.bind(this);\n storage.onChange(this.base, this._fireChange.bind(this));\n }\n\n /**\n * Instantiate a new client, scoped to a subpath of the current client's\n * path.\n *\n * @param path - The path to scope the new client to\n *\n * @returns A new client operating on a subpath of the current base path\n */\n scope (path: string): BaseClient {\n return new BaseClient(this.storage, this.makePath(path));\n }\n\n /**\n * Get a list of child nodes below a given path.\n *\n * @param {string} path - The path to query. It MUST end with a forward slash.\n * @param {number} maxAge - (optional) Either ``false`` or the maximum age of\n * cached listing in milliseconds. See :ref:`max-age`.\n *\n * @returns {Promise} A promise for an object representing child nodes\n */\n // TODO add real return type\n getListing (path: string, maxAge?: false | number): Promise {\n if (typeof (path) !== 'string') {\n path = '';\n } else if (path.length > 0 && path[path.length - 1] !== '/') {\n return Promise.reject(\"Not a folder: \" + path);\n }\n return this.storage.get(this.makePath(path), maxAge).then(\n function (r) {\n return (r.statusCode === 404) ? {} : r.body;\n }\n );\n }\n\n /**\n * Get all objects directly below a given path.\n *\n * @param {string} path - Path to the folder. Must end in a forward slash.\n * @param {number} maxAge - (optional) Either ``false`` or the maximum age of\n * cached objects in milliseconds. See :ref:`max-age`.\n *\n * @returns {Promise} A promise for an object\n */\n // TODO add real return type\n getAll (path: string, maxAge?: false | number): Promise {\n if (typeof (path) !== 'string') {\n path = '';\n } else if (path.length > 0 && path[path.length - 1] !== '/') {\n return Promise.reject(\"Not a folder: \" + path);\n }\n\n return this.storage.get(this.makePath(path), maxAge).then((r) => {\n if (r.statusCode === 404) {\n return {};\n }\n if (typeof (r.body) === 'object') {\n const keys = Object.keys(r.body);\n if (keys.length === 0) {\n // treat this like 404. it probably means a folder listing that\n // has changes that haven't been pushed out yet.\n return {};\n }\n\n const calls = keys.map((key: string) => {\n return this.storage.get(this.makePath(path + key), maxAge)\n .then(function (o) {\n if (typeof (o.body) === 'string') {\n try {\n o.body = JSON.parse(o.body);\n } catch (e) {\n // empty\n }\n }\n if (typeof (o.body) === 'object') {\n r.body[key] = o.body;\n }\n });\n });\n return Promise.all(calls).then(function () {\n return r.body;\n });\n }\n });\n }\n\n /**\n * Get the file at the given path. A file is raw data, as opposed to\n * a JSON object (use :func:`getObject` for that).\n *\n * @param {string} path - Relative path from the module root (without leading\n * slash).\n * @param {number} maxAge - (optional) Either ``false`` or the maximum age of\n * the cached file in milliseconds. See :ref:`max-age`.\n *\n * @returns {Promise} A promise for an object\n */\n // TODO add real return type\n getFile (path: string, maxAge?: false | number): Promise {\n if (typeof (path) !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.getFile must be a string');\n }\n return this.storage.get(this.makePath(path), maxAge).then(function (r) {\n return {\n data: r.body,\n contentType: r.contentType,\n revision: r.revision // (this is new)\n };\n });\n }\n\n /**\n * Store raw data at a given path.\n *\n * @param {string} mimeType - MIME media type of the data being stored\n * @param {string} path - Path relative to the module root\n * @param {string|ArrayBuffer|ArrayBufferView} body - Raw data to store\n *\n * @returns {Promise} A promise for the created/updated revision (ETag)\n */\n storeFile (mimeType: string, path: string, body: string | ArrayBuffer | ArrayBufferView): Promise {\n if (typeof (mimeType) !== 'string') {\n return Promise.reject('Argument \\'mimeType\\' of baseClient.storeFile must be a string');\n }\n if (typeof (path) !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.storeFile must be a string');\n }\n if (typeof (body) !== 'string' && typeof (body) !== 'object') {\n return Promise.reject('Argument \\'body\\' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView');\n }\n if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) {\n console.warn('WARNING: Editing a document to which only read access (\\'r\\') was claimed');\n }\n\n return this.storage.put(this.makePath(path), body, mimeType).then((r) => {\n if (r.statusCode === 200 || r.statusCode === 201) {\n return r.revision;\n } else {\n return Promise.reject(\"Request (PUT \" + this.makePath(path) + \") failed with status: \" + r.statusCode);\n }\n });\n }\n\n /**\n * Get a JSON object from the given path.\n *\n * @param {string} path - Relative path from the module root (without leading\n * slash).\n * @param {number} maxAge - (optional) Either ``false`` or the maximum age of\n * cached object in milliseconds. See :ref:`max-age`.\n *\n * @returns {Promise} A promise, which resolves with the requested object (or ``null``\n * if non-existent)\n */\n\n // TODO add real return type\n getObject (path: string, maxAge?: false | number): Promise {\n if (typeof (path) !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.getObject must be a string');\n }\n return this.storage.get(this.makePath(path), maxAge).then((r) => {\n if (typeof (r.body) === 'object') { // will be the case for documents stored with rs.js <= 0.10.0-beta2\n return r.body;\n } else if (typeof (r.body) === 'string') {\n try {\n return JSON.parse(r.body);\n } catch (e) {\n throw new Error(\"Not valid JSON: \" + this.makePath(path));\n }\n } else if (typeof (r.body) !== 'undefined' && r.statusCode === 200) {\n return Promise.reject(\"Not an object: \" + this.makePath(path));\n }\n });\n }\n\n /**\n * Store object at given path. Triggers synchronization.\n *\n * See ``declareType()`` and :doc:`data types `\n * for an explanation of types\n *\n * For any given `path`, must not be called more frequently than once per second.\n *\n * @param {string} typeAlias - Unique type of this object within this module.\n * @param {string} path - Path relative to the module root.\n * @param {object} object - A JavaScript object to be stored at the given\n * path. Must be serializable as JSON.\n *\n * @returns {Promise} Resolves with revision on success. Rejects with\n * a ValidationError, if validations fail.\n */\n // TODO add real return type\n storeObject (typeAlias: string, path: string, object: object): Promise {\n if (typeof (typeAlias) !== 'string') {\n return Promise.reject('Argument \\'typeAlias\\' of baseClient.storeObject must be a string');\n }\n if (typeof (path) !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.storeObject must be a string');\n }\n if (typeof (object) !== 'object') {\n return Promise.reject('Argument \\'object\\' of baseClient.storeObject must be an object');\n }\n\n this._attachType(object, typeAlias);\n\n try {\n const validationResult = this.validate(object);\n if (!validationResult.valid) {\n return Promise.reject(validationResult);\n }\n } catch (exc) {\n return Promise.reject(exc);\n }\n\n return this.storage.put(this.makePath(path), JSON.stringify(object), 'application/json; charset=UTF-8').then((r) => {\n if (r.statusCode === 200 || r.statusCode === 201) {\n return r.revision;\n } else {\n return Promise.reject(\"Request (PUT \" + this.makePath(path) + \") failed with status: \" + r.statusCode);\n }\n });\n }\n\n /**\n * Remove node at given path from storage. Triggers synchronization.\n *\n * @param {string} path - Path relative to the module root.\n * @returns {Promise}\n */\n // TODO add real return type\n remove (path: string): Promise {\n if (typeof (path) !== 'string') {\n return Promise.reject('Argument \\'path\\' of baseClient.remove must be a string');\n }\n if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) {\n console.warn('WARNING: Removing a document to which only read access (\\'r\\') was claimed');\n }\n\n return this.storage.delete(this.makePath(path));\n }\n\n /**\n * Retrieve full URL of a document. Useful for example for sharing the public\n * URL of an item in the ``/public`` folder.\n *\n * @param {string} path - Path relative to the module root.\n * @returns {string} The full URL of the item, including the storage origin\n */\n getItemURL (path: string): string {\n if (typeof (path) !== 'string') {\n throw 'Argument \\'path\\' of baseClient.getItemURL must be a string';\n }\n if (this.storage.connected) {\n path = cleanPath(this.makePath(path));\n return this.storage.remote.href + path;\n } else {\n return undefined;\n }\n }\n\n /**\n * Set caching strategy for a given path and its children.\n *\n * See :ref:`caching-strategies` for a detailed description of the available\n * strategies.\n *\n * @param {string} path - Path to cache\n * @param {string} strategy - Caching strategy. One of 'ALL', 'SEEN', or\n * 'FLUSH'. Defaults to 'ALL'.\n *\n * @returns {BaseClient} The same instance this is called on to allow for method chaining\n */\n cache (path: string, strategy: 'ALL' | 'SEEN' | 'FLUSH' = 'ALL') {\n if (typeof path !== 'string') {\n throw 'Argument \\'path\\' of baseClient.cache must be a string';\n }\n\n if (typeof strategy !== 'string') {\n throw 'Argument \\'strategy\\' of baseClient.cache must be a string or undefined';\n }\n\n if (strategy !== 'FLUSH' &&\n strategy !== 'SEEN' &&\n strategy !== 'ALL') {\n throw 'Argument \\'strategy\\' of baseclient.cache must be one of '\n + '[\"FLUSH\", \"SEEN\", \"ALL\"]';\n }\n this.storage.caching.set(this.makePath(path), strategy);\n\n return this;\n }\n\n /**\n * TODO: document\n *\n * @param {string} path\n */\n // TODO add return type once known\n flush (path: string): unknown {\n return this.storage.local.flush(path);\n }\n\n /**\n * Declare a remoteStorage object type using a JSON schema.\n *\n * See :doc:`Defining data types ` for more info.\n *\n * @param {string} alias - A type alias/shortname\n * @param {uri} uri - (optional) JSON-LD URI of the schema. Automatically generated if none given\n * @param {object} schema - A JSON Schema object describing the object type\n **/\n declareType (alias: any, uriOrSchema: any, schema?: any): void {\n let uri: string;\n\n if (!schema) {\n schema = uriOrSchema;\n uri = this._defaultTypeURI(alias);\n } else {\n uri = uriOrSchema;\n }\n\n BaseClient.Types.declare(this.moduleName, alias, uri, schema);\n }\n\n /**\n * Validate an object against the associated schema.\n *\n * @param {Object} object - JS object to validate. Must have a ``@context`` property.\n *\n * @returns {Object} An object containing information about validation errors\n **/\n validate (object: {[key: string]: any}): {[key: string]: any} {\n const schema = BaseClient.Types.getSchema(object['@context']);\n if (schema) {\n return tv4.validateResult(object, schema);\n } else {\n throw new SchemaNotFound(object['@context']);\n }\n }\n\n /**\n * TODO document\n *\n * @private\n */\n schemas = {\n configurable: true,\n get: function () {\n return BaseClient.Types.inScope(this.moduleName);\n }\n };\n\n /**\n * The default JSON-LD @context URL for RS types/objects/documents\n *\n * @private\n */\n _defaultTypeURI (alias: string): string {\n return 'http://remotestorage.io/spec/modules/' + encodeURIComponent(this.moduleName) + '/' + encodeURIComponent(alias);\n }\n\n /**\n * Attaches the JSON-LD @content to an object\n *\n * @private\n */\n _attachType (object: object, alias: string): void {\n object['@context'] = BaseClient.Types.resolveAlias(this.moduleName + '/' + alias) || this._defaultTypeURI(alias);\n }\n\n /**\n * TODO: document\n *\n * @private\n */\n makePath (path: string): string {\n return this.base + (path || '');\n }\n\n /**\n * TODO: document\n *\n * @private\n */\n _fireChange (event: ChangeObj) {\n if (config.changeEvents[event.origin]) {\n ['new', 'old', 'lastCommon'].forEach(function (fieldNamePrefix) {\n if ((!event[fieldNamePrefix + 'ContentType'])\n || (/^application\\/(.*)json(.*)/.exec(event[fieldNamePrefix + 'ContentType']))) {\n if (typeof (event[fieldNamePrefix + 'Value']) === 'string') {\n try {\n event[fieldNamePrefix + 'Value'] = JSON.parse(event[fieldNamePrefix + 'Value']);\n } catch (e) {\n // empty\n }\n }\n }\n });\n this._emit('change', event);\n }\n }\n\n static Types = Types;\n\n static _rs_init (): void {\n return;\n }\n}\n\ninterface BaseClient extends EventHandling {};\napplyMixins(BaseClient, [EventHandling]);\n\nexport = BaseClient;\n","/**\n * This file exposes a get/put/delete interface on top of fetch() or XMLHttpRequest.\n * It requires to be configured with parameters about the remotestorage server to\n * connect to.\n * Each instance of WireClient is always associated with a single remotestorage\n * server and access token.\n *\n * Usually the WireClient instance can be accessed via `remoteStorage.remote`.\n *\n * This is the get/put/delete interface:\n *\n * - #get() takes a path and optionally a ifNoneMatch option carrying a version\n * string to check. It returns a promise that will be fulfilled with the HTTP\n * response status, the response body, the MIME type as returned in the\n * 'Content-Type' header and the current revision, as returned in the 'ETag'\n * header.\n * - #put() takes a path, the request body and a content type string. It also\n * accepts the ifMatch and ifNoneMatch options, that map to the If-Match and\n * If-None-Match headers respectively. See the remotestorage-01 specification\n * for details on handling these headers. It returns a promise, fulfilled with\n * the same values as the one for #get().\n * - #delete() takes a path and the ifMatch option as well. It returns a promise\n * fulfilled with the same values as the one for #get().\n *\n * In addition to this, the WireClient has some compatibility features to work with\n * remotestorage 2012.04 compatible storages. For example it will cache revisions\n * from folder listings in-memory and return them accordingly as the \"revision\"\n * parameter in response to #get() requests. Similarly it will return 404 when it\n * receives an empty folder listing, to mimic remotestorage-01 behavior. Note\n * that it is not always possible to know the revision beforehand, hence it may\n * be undefined at times (especially for caching-roots).\n */\nimport RemoteStorage from './remotestorage';\nimport Authorize from './authorize';\nimport EventHandling from './eventhandling';\nimport UnauthorizedError from './unauthorized-error';\nimport config from './config';\nimport log from './log';\nimport {\n applyMixins,\n cleanPath,\n getJSONFromLocalStorage,\n getTextFromArrayBuffer,\n isFolder,\n localStorageAvailable,\n shouldBeTreatedAsBinary\n} from './util';\n\nlet hasLocalStorage;\nconst SETTINGS_KEY = 'remotestorage:wireclient';\n\nconst API_2012 = 1;\nconst API_00 = 2;\nconst API_01 = 3;\nconst API_02 = 4;\nconst API_HEAD = 5;\n\nconst STORAGE_APIS = {\n 'draft-dejong-remotestorage-00': API_00,\n 'draft-dejong-remotestorage-01': API_01,\n 'draft-dejong-remotestorage-02': API_02,\n 'https://www.w3.org/community/rww/wiki/read-write-web-00#simple': API_2012\n};\n\nfunction readSettings () {\n const settings = getJSONFromLocalStorage(SETTINGS_KEY) || {};\n const { userAddress, href, storageApi, token, properties } = settings;\n\n return { userAddress, href, storageApi, token, properties };\n};\n\nlet isArrayBufferView;\n\nif (typeof ((global || window as any).ArrayBufferView) === 'function') {\n isArrayBufferView = function (object) {\n return object && (object instanceof (global || window as any).ArrayBufferView);\n };\n} else {\n const arrayBufferViews = [\n Int8Array, Uint8Array, Int16Array, Uint16Array,\n Int32Array, Uint32Array, Float32Array, Float64Array\n ];\n isArrayBufferView = function (object): boolean {\n for (let i = 0; i < 8; i++) {\n if (object instanceof arrayBufferViews[i]) {\n return true;\n }\n }\n return false;\n };\n}\n\n// TODO double check\ninterface WireClientSettings {\n userAddress: string;\n href: string;\n storageApi: string;\n token: string;\n properties: unknown;\n}\n\ninterface WireRequestResponse {\n statusCode: number;\n revision: string | undefined;\n body?: any;\n}\n\nfunction addQuotes (str: string): string {\n if (typeof (str) !== 'string') {\n return str;\n }\n if (str === '*') {\n return '*';\n }\n\n return '\"' + str + '\"';\n}\n\nfunction stripQuotes (str: string): string {\n if (typeof (str) !== 'string') {\n return str;\n }\n\n return str.replace(/^[\"']|[\"']$/g, '');\n}\n\nfunction determineCharset (mimeType: string): string {\n let charset = 'UTF-8';\n let charsetMatch;\n\n if (mimeType) {\n charsetMatch = mimeType.match(/charset=(.+)$/);\n if (charsetMatch) {\n charset = charsetMatch[1];\n }\n }\n return charset;\n}\n\nfunction isFolderDescription (body: object): boolean {\n return ((body['@context'] === 'http://remotestorage.io/spec/folder-description')\n && (typeof (body['items']) === 'object'));\n}\n\nfunction isSuccessStatus (status: number): boolean {\n return [201, 204, 304].indexOf(status) >= 0;\n}\n\nfunction isErrorStatus (status: number): boolean {\n return [401, 403, 404, 412].indexOf(status) >= 0;\n}\n\nfunction isForbiddenRequestMethod(method: string, uri: string): boolean {\n if (method === 'PUT' || method === 'DELETE') {\n return isFolder(uri);\n } else {\n return false;\n }\n}\n\nclass WireClient {\n rs: RemoteStorage;\n connected: boolean;\n online: boolean;\n userAddress: string;\n\n /**\n * Holds the bearer token of this WireClient, as obtained in the OAuth dance\n *\n * Example:\n * (start code)\n *\n * remoteStorage.remote.token\n * // -> 'DEADBEEF01=='\n */\n token: string;\n\n /**\n * Holds the server's base URL, as obtained in the Webfinger discovery\n *\n * Example:\n * (start code)\n *\n * remoteStorage.remote.href\n * // -> 'https://storage.example.com/users/jblogg/'\n */\n href: string;\n\n /**\n * Holds the spec version the server claims to be compatible with\n *\n * Example:\n * (start code)\n *\n * remoteStorage.remote.storageApi\n * // -> 'draft-dejong-remotestorage-01'\n */\n storageApi: string;\n // TODO implement TS validation for incoming type\n\n supportsRevs: boolean;\n\n _revisionCache: { [key: string]: any } = {};\n\n properties: any;\n\n constructor (rs: RemoteStorage) {\n hasLocalStorage = localStorageAvailable();\n\n this.rs = rs;\n this.connected = false;\n\n /**\n * Event: connected\n * Fired when the wireclient connect method realizes that it is in\n * possession of a token and href\n **/\n this.addEvents(['connected', 'not-connected']);\n\n if (hasLocalStorage) {\n const settings = readSettings();\n if (settings) {\n setTimeout(() => {\n this.configure(settings);\n }, 0);\n }\n }\n\n if (this.connected) {\n setTimeout(this._emit.bind(this), 0, 'connected');\n }\n }\n\n get storageType () {\n if (this.storageApi) {\n const spec = this.storageApi.match(/draft-dejong-(remotestorage-\\d\\d)/);\n return spec ? spec[1] : '2012.04';\n } else {\n return undefined;\n }\n }\n\n async _request (method: string, uri: string, token: string | false, headers: object, body: unknown, getEtag: boolean, fakeRevision?: string): Promise {\n if (isForbiddenRequestMethod(method, uri)) {\n return Promise.reject(`Don't use ${method} on directories!`);\n }\n\n let revision: string | undefined;\n\n if (token !== Authorize.IMPLIED_FAKE_TOKEN) {\n headers['Authorization'] = 'Bearer ' + token;\n }\n\n this.rs._emit('wire-busy', {\n method: method,\n isFolder: isFolder(uri)\n });\n\n return WireClient.request(method, uri, {\n body: body,\n headers: headers,\n responseType: 'arraybuffer'\n }).then((response: XMLHttpRequest): Promise => {\n if (!this.online) {\n this.online = true;\n this.rs._emit('network-online');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(uri),\n success: true\n });\n\n if (isErrorStatus(response.status)) {\n log('[WireClient] Error response status', response.status);\n if (getEtag) {\n revision = stripQuotes(response.getResponseHeader('ETag'));\n } else {\n revision = undefined;\n }\n\n if (response.status === 401) {\n this.rs._emit('error', new UnauthorizedError());\n }\n\n return Promise.resolve({statusCode: response.status, revision: revision});\n } else if (isSuccessStatus(response.status) ||\n (response.status === 200 && method !== 'GET')) {\n revision = stripQuotes(response.getResponseHeader('ETag'));\n log('[WireClient] Successful request', revision);\n return Promise.resolve({statusCode: response.status, revision: revision});\n } else {\n const mimeType = response.getResponseHeader('Content-Type');\n if (getEtag) {\n revision = stripQuotes(response.getResponseHeader('ETag'));\n } else {\n revision = (response.status === 200) ? fakeRevision : undefined;\n }\n\n const charset = determineCharset(mimeType);\n\n if (shouldBeTreatedAsBinary(response.response, mimeType)) {\n log('[WireClient] Successful request with unknown or binary mime-type', revision);\n return Promise.resolve({\n statusCode: response.status,\n body: response.response,\n contentType: mimeType,\n revision: revision\n });\n } else {\n return getTextFromArrayBuffer(response.response, charset)\n .then((textContent) => {\n log('[WireClient] Successful request', revision);\n return Promise.resolve({\n statusCode: response.status,\n body: textContent,\n contentType: mimeType,\n revision: revision\n });\n });\n }\n }\n }, error => {\n if (this.online) {\n this.online = false;\n this.rs._emit('network-offline');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(uri),\n success: false\n });\n\n return Promise.reject(error);\n });\n }\n\n /**\n * Sets the userAddress, href, storageApi, token, and properties of a\n * remote store. Also sets connected and online to true and emits the\n * 'connected' event, if both token and href are present.\n *\n * Parameters:\n * settings - An object that may contain userAddress (string or null),\n * href (string or null), storageApi (string or null), token (string\n * or null), and/or properties (the JSON-parsed properties object\n * from the user's WebFinger record, see section 10 of\n * http://tools.ietf.org/html/draft-dejong-remotestorage-03\n * or null).\n * Fields that are not included (i.e. `undefined`), stay at\n * their current value. To set a field, include that field\n * with a `string` value. To reset a field, for instance when\n * the user disconnected their storage, or you found that the\n * token you have has expired, simply set that field to `null`.\n */\n configure (settings: WireClientSettings): void {\n if (typeof settings !== 'object') {\n throw new Error('WireClient configure settings parameter should be an object');\n }\n if (typeof settings.userAddress !== 'undefined') {\n this.userAddress = settings.userAddress;\n }\n if (typeof settings.href !== 'undefined') {\n this.href = settings.href;\n }\n if (typeof settings.storageApi !== 'undefined') {\n this.storageApi = settings.storageApi;\n }\n if (typeof settings.token !== 'undefined') {\n this.token = settings.token;\n }\n if (typeof settings.properties !== 'undefined') {\n this.properties = settings.properties;\n }\n\n if (typeof this.storageApi === 'string') {\n const _storageApi = STORAGE_APIS[this.storageApi] || API_HEAD;\n this.supportsRevs = _storageApi >= API_00;\n }\n if (this.href && this.token) {\n this.connected = true;\n this.online = true;\n this._emit('connected');\n } else {\n this.connected = false;\n }\n if (hasLocalStorage) {\n localStorage[SETTINGS_KEY] = JSON.stringify({\n userAddress: this.userAddress,\n href: this.href,\n storageApi: this.storageApi,\n token: this.token,\n properties: this.properties\n });\n }\n }\n\n stopWaitingForToken (): void {\n if (!this.connected) {\n this._emit('not-connected');\n }\n }\n\n get (path: string, options: { ifNoneMatch?: string } = {}): Promise {\n if (!this.connected) {\n return Promise.reject('not connected (path: ' + path + ')');\n }\n\n const headers = {};\n if (this.supportsRevs) {\n if (options.ifNoneMatch) {\n headers['If-None-Match'] = addQuotes(options.ifNoneMatch);\n }\n }\n // commenting it out as this is doing nothing and jshint is complaining -les\n // else if (options.ifNoneMatch) {\n // let oldRev = this._revisionCache[path];\n // }\n\n return this._request('GET', this.href + cleanPath(path), this.token, headers,\n undefined, this.supportsRevs, this._revisionCache[path])\n .then((r) => {\n if (!isFolder(path)) {\n return Promise.resolve(r);\n }\n let itemsMap = {};\n if (typeof (r.body) !== 'undefined') {\n try {\n r.body = JSON.parse(r.body);\n } catch (e) {\n return Promise.reject('Folder description at ' + this.href + cleanPath(path) + ' is not JSON');\n }\n }\n\n if (r.statusCode === 200 && typeof (r.body) === 'object') {\n // New folder listing received\n if (Object.keys(r.body).length === 0) {\n // Empty folder listing of any spec\n r.statusCode = 404;\n } else if (isFolderDescription(r.body)) {\n // >= 02 spec\n for (const item in r.body.items) {\n this._revisionCache[path + item] = r.body.items[item].ETag;\n }\n itemsMap = r.body.items;\n } else {\n // < 02 spec\n Object.keys(r.body).forEach((key) => {\n this._revisionCache[path + key] = r.body[key];\n itemsMap[key] = {'ETag': r.body[key]};\n });\n }\n r.body = itemsMap;\n return Promise.resolve(r);\n } else {\n return Promise.resolve(r);\n }\n });\n }\n\n put (path: string, body: unknown, contentType: string, options: { ifMatch?: string; ifNoneMatch?: string } = {}) {\n if (!this.connected) {\n return Promise.reject('not connected (path: ' + path + ')');\n }\n if ((!contentType.match(/charset=/)) && (body instanceof ArrayBuffer || isArrayBufferView(body))) {\n contentType += '; charset=binary';\n }\n const headers = {'Content-Type': contentType};\n if (this.supportsRevs) {\n if (options.ifMatch) {\n headers['If-Match'] = addQuotes(options.ifMatch);\n }\n if (options.ifNoneMatch) {\n headers['If-None-Match'] = addQuotes(options.ifNoneMatch);\n }\n }\n return this._request('PUT', this.href + cleanPath(path), this.token,\n headers, body, this.supportsRevs);\n }\n\n delete (path: string, options: { ifMatch?: string } = {}) {\n if (!this.connected) {\n throw new Error('not connected (path: ' + path + ')');\n }\n if (!options) {\n options = {};\n }\n const headers = {};\n if (this.supportsRevs) {\n if (options.ifMatch) {\n headers['If-Match'] = addQuotes(options.ifMatch);\n }\n }\n return this._request('DELETE', this.href + cleanPath(path), this.token,\n headers,\n undefined, this.supportsRevs);\n }\n\n // Shared isArrayBufferView used by WireClient and Dropbox\n static isArrayBufferView = isArrayBufferView;\n\n // TODO add proper definition for options\n // Shared request function used by WireClient, GoogleDrive and Dropbox.\n static async request (method: string, url: string, options: unknown): Promise {\n if (typeof fetch === 'function') {\n return WireClient._fetchRequest(method, url, options);\n } else if (typeof XMLHttpRequest === 'function') {\n return WireClient._xhrRequest(method, url, options);\n } else {\n log('[WireClient] You need to add a polyfill for fetch or XMLHttpRequest');\n return Promise.reject('[WireClient] You need to add a polyfill for fetch or XMLHttpRequest');\n }\n }\n\n /** options includes body, headers and responseType */\n static _fetchRequest (method: string, url: string, options): Promise {\n let syntheticXhr;\n const responseHeaders = {};\n let abortController;\n if (typeof AbortController === 'function') {\n abortController = new AbortController();\n }\n const networkPromise: Promise = fetch(url, {\n method: method,\n headers: options.headers,\n body: options.body,\n signal: abortController ? abortController.signal : undefined\n }).then((response) => {\n log('[WireClient fetch]', response);\n\n response.headers.forEach((value: string, headerName: string) => {\n responseHeaders[headerName.toUpperCase()] = value;\n });\n\n syntheticXhr = {\n readyState: 4,\n status: response.status,\n statusText: response.statusText,\n response: undefined,\n getResponseHeader: (headerName: string): unknown => {\n return responseHeaders[headerName.toUpperCase()] || null;\n },\n // responseText: 'foo',\n responseType: options.responseType,\n responseURL: url,\n };\n switch (options.responseType) {\n case 'arraybuffer':\n return response.arrayBuffer();\n case 'blob':\n return response.blob();\n case 'json':\n return response.json();\n case undefined:\n case '':\n case 'text':\n return response.text();\n default: // document\n throw new Error(\"responseType 'document' is not currently supported using fetch\");\n }\n }).then((processedBody) => {\n syntheticXhr.response = processedBody;\n if (!options.responseType || options.responseType === 'text') {\n syntheticXhr.responseText = processedBody;\n }\n return syntheticXhr;\n });\n\n const timeoutPromise: Promise = new Promise((resolve, reject) => {\n setTimeout(() => {\n reject('timeout');\n if (abortController) {\n abortController.abort();\n }\n }, config.requestTimeout);\n });\n\n return Promise.race([networkPromise, timeoutPromise]);\n }\n\n static _xhrRequest (method, url, options): Promise {\n return new Promise((resolve, reject) => {\n\n log('[WireClient]', method, url);\n\n let timedOut = false;\n\n const timer = setTimeout(() => {\n timedOut = true;\n reject('timeout');\n }, config.requestTimeout);\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url, true);\n\n if (options.responseType) {\n xhr.responseType = options.responseType;\n }\n\n if (options.headers) {\n for (const key in options.headers) {\n xhr.setRequestHeader(key, options.headers[key]);\n }\n }\n\n xhr.onload = (): void => {\n if (timedOut) {\n return;\n }\n clearTimeout(timer);\n resolve(xhr);\n };\n\n xhr.onerror = (error): void => {\n if (timedOut) {\n return;\n }\n clearTimeout(timer);\n reject(error);\n };\n\n let body = options.body;\n\n if (typeof (body) === 'object' && !isArrayBufferView(body) && body instanceof ArrayBuffer) {\n body = new Uint8Array(body);\n }\n xhr.send(body);\n });\n }\n\n static _rs_init (remoteStorage): void {\n remoteStorage.remote = new WireClient(remoteStorage);\n remoteStorage.remote.online = true;\n }\n\n static _rs_supported (): boolean {\n return typeof fetch === 'function' || typeof XMLHttpRequest === 'function';\n }\n\n static _rs_cleanup (): void {\n if (hasLocalStorage) {\n delete localStorage[SETTINGS_KEY];\n }\n }\n}\n\ninterface WireClient extends EventHandling {};\napplyMixins(WireClient, [EventHandling]);\n\nexport = WireClient;\n","class SyncError extends Error {\n originalError: Error\n\n constructor (originalError: string | Error) {\n super();\n this.name = 'SyncError';\n this.message = 'Sync failed: ';\n if (typeof originalError === 'string') {\n this.message += originalError;\n } else {\n this.message += originalError.message;\n this.stack = originalError.stack;\n this.originalError = originalError;\n }\n }\n}\n\nexport = SyncError;\n","import type { ChangeObj } from './interfaces/change_obj';\nimport type { QueuedRequestResponse } from './interfaces/queued_request_response';\nimport type { RSEvent } from './interfaces/rs_event';\nimport type { RSNode, RSNodes } from './interfaces/rs_node';\nimport EventHandling from './eventhandling';\nimport config from './config';\nimport log from './log';\nimport {\n applyMixins,\n deepClone,\n equal,\n isDocument,\n isFolder,\n pathsFromRoot\n} from './util';\n\n/**\n * This module defines functions that are mixed into remoteStorage.local when\n * it is instantiated (currently one of indexeddb.js, localstorage.js, or\n * inmemorystorage.js).\n *\n * All remoteStorage.local implementations should therefore implement\n * this.getNodes, this.setNodes, and this.forAllNodes. The rest is blended in\n * here to create a GPD (get/put/delete) interface which the BaseClient can\n * talk to.\n *\n * @interface\n */\n\nabstract class CachingLayer {\n // FIXME\n // this process of updating nodes needs to be heavily documented first, then\n // refactored. Right now it's almost impossible to refactor as there's no\n // explanation of why things are implemented certain ways or what the goal(s)\n // of the behavior are. -slvrbckt (+1 -les)\n private _updateNodesRunning = false;\n private _updateNodesQueued = [];\n\n\n // functions that will be overwritten\n // ----------------------------------\n abstract getNodes(paths: string[]): Promise;\n\n abstract diffHandler(...args: any[]);\n\n abstract forAllNodes(cb: (node) => any): Promise;\n\n abstract setNodes(nodes: RSNodes): Promise;\n\n\n // --------------------------------------------------\n\n // TODO: improve our code structure so that this function\n // could call sync.queueGetRequest directly instead of needing\n // this hacky third parameter as a callback\n get (path: string, maxAge: number, queueGetRequest: (path: string) => Promise): Promise {\n\n if (typeof (maxAge) === 'number') {\n\n return this.getNodes(pathsFromRoot(path))\n .then((objs) => {\n const node: RSNode = getLatest(objs[path]);\n if (isOutdated(objs, maxAge)) {\n return queueGetRequest(path);\n } else if (node) {\n return {statusCode: 200, body: node.body || node.itemsMap, contentType: node.contentType};\n } else {\n return {statusCode: 404};\n }\n });\n } else {\n return this.getNodes([path])\n .then((objs) => {\n const node = getLatest(objs[path]);\n if (node) {\n if (isFolder(path)) {\n for (const i in node.itemsMap) {\n // the hasOwnProperty check here is only because our jshint settings require it:\n if (node.itemsMap.hasOwnProperty(i) && node.itemsMap[i] === false) {\n delete node.itemsMap[i];\n }\n }\n }\n return {statusCode: 200, body: node.body || node.itemsMap, contentType: node.contentType};\n } else {\n return {statusCode: 404};\n }\n });\n }\n }\n\n put(path: string, body: any, contentType: string): Promise {\n const paths = pathsFromRoot(path);\n\n function _processNodes(nodePaths, nodes) {\n try {\n for (let i = 0, len = nodePaths.length; i < len; i++) {\n const nodePath = nodePaths[i];\n let node = nodes[nodePath];\n let previous;\n\n if (!node) {\n nodes[nodePath] = node = makeNode(nodePath);\n }\n\n // Document\n if (i === 0) {\n previous = getLatest(node);\n node.local = {\n body: body,\n contentType: contentType,\n previousBody: (previous ? previous.body : undefined),\n previousContentType: (previous ? previous.contentType : undefined),\n };\n }\n // Folder\n else {\n const itemName = nodePaths[i - 1].substring(nodePath.length);\n node = updateFolderNodeWithItemName(node, itemName);\n }\n }\n return nodes;\n } catch (e) {\n log('[Cachinglayer] Error during PUT', nodes, e);\n throw e;\n }\n }\n\n return this._updateNodes(paths, _processNodes);\n }\n\n delete(path: string): unknown {\n const paths = pathsFromRoot(path);\n\n return this._updateNodes(paths, function (nodePaths, nodes) {\n for (let i = 0, len = nodePaths.length; i < len; i++) {\n const nodePath = nodePaths[i];\n const node = nodes[nodePath];\n let previous;\n\n if (!node) {\n console.error('Cannot delete non-existing node ' + nodePath);\n continue;\n }\n\n if (i === 0) {\n // Document\n previous = getLatest(node);\n node.local = {\n body: false,\n previousBody: (previous ? previous.body : undefined),\n previousContentType: (previous ? previous.contentType : undefined),\n };\n } else {\n // Folder\n if (!node.local) {\n node.local = deepClone(node.common);\n }\n const itemName = nodePaths[i - 1].substring(nodePath.length);\n delete node.local.itemsMap[itemName];\n\n if (Object.getOwnPropertyNames(node.local.itemsMap).length > 0) {\n // This folder still contains other items, don't remove any further ancestors\n break;\n }\n }\n }\n return nodes;\n });\n }\n\n flush(path: string): unknown {\n\n return this._getAllDescendentPaths(path).then((paths) => {\n return this.getNodes(paths);\n }).then((nodes: RSNodes) => {\n for (const nodePath in nodes) {\n const node = nodes[nodePath];\n\n if (node && node.common && node.local) {\n this._emitChange({\n path: node.path,\n origin: 'local',\n oldValue: (node.local.body === false ? undefined : node.local.body),\n newValue: (node.common.body === false ? undefined : node.common.body)\n });\n }\n nodes[nodePath] = undefined;\n }\n\n return this.setNodes(nodes);\n });\n }\n\n private _emitChange(obj: ChangeObj) {\n if (config.changeEvents[obj.origin]) {\n this._emit('change', obj);\n }\n }\n\n fireInitial() {\n if (!config.changeEvents.local) {\n return;\n }\n\n this.forAllNodes((node) => {\n\n if (isDocument(node.path)) {\n const latest = getLatest(node);\n if (latest) {\n this._emitChange({\n path: node.path,\n origin: 'local',\n oldValue: undefined,\n oldContentType: undefined,\n newValue: latest.body,\n newContentType: latest.contentType\n });\n }\n }\n }).then(() => {\n this._emit('local-events-done');\n });\n }\n\n // TODO add proper type\n onDiff(diffHandler: any) {\n this.diffHandler = diffHandler;\n }\n\n migrate(node: RSNode): RSNode {\n if (typeof (node) === 'object' && !node.common) {\n node.common = {};\n if (typeof (node.path) === 'string') {\n if (node.path.substr(-1) === '/' && typeof (node.body) === 'object') {\n node.common.itemsMap = node.body;\n }\n } else {\n //save legacy content of document node as local version\n if (!node.local) {\n node.local = {};\n }\n node.local.body = node.body;\n node.local.contentType = node.contentType;\n }\n }\n return node;\n }\n\n\n private _updateNodes(paths: string[], _processNodes): Promise {\n return new Promise((resolve, reject) => {\n this._doUpdateNodes(paths, _processNodes, {\n resolve: resolve,\n reject: reject\n });\n });\n }\n\n private _doUpdateNodes(paths, _processNodes, promise) {\n if (this._updateNodesRunning) {\n this._updateNodesQueued.push({\n paths: paths,\n cb: _processNodes,\n promise: promise\n });\n return;\n } else {\n this._updateNodesRunning = true;\n }\n\n this.getNodes(paths).then((nodes) => {\n const existingNodes = deepClone(nodes);\n const changeEvents = [];\n\n nodes = _processNodes(paths, nodes);\n\n for (const path in nodes) {\n const node = nodes[path];\n if (equal(node, existingNodes[path])) {\n delete nodes[path];\n } else if (isDocument(path)) {\n if (\n !equal(node.local.body, node.local.previousBody) ||\n node.local.contentType !== node.local.previousContentType\n ) {\n changeEvents.push({\n path: path,\n origin: 'window',\n oldValue: node.local.previousBody,\n newValue: node.local.body === false ? undefined : node.local.body,\n oldContentType: node.local.previousContentType,\n newContentType: node.local.contentType\n });\n }\n delete node.local.previousBody;\n delete node.local.previousContentType;\n }\n }\n\n this.setNodes(nodes).then(() => {\n this._emitChangeEvents(changeEvents);\n promise.resolve({statusCode: 200});\n });\n }).then(() => {\n return Promise.resolve();\n }, (err) => {\n promise.reject(err);\n }).then(() => {\n this._updateNodesRunning = false;\n const nextJob = this._updateNodesQueued.shift();\n if (nextJob) {\n this._doUpdateNodes(nextJob.paths, nextJob.cb, nextJob.promise);\n }\n });\n }\n\n private _emitChangeEvents(events: RSEvent[]) {\n for (let i = 0, len = events.length; i < len; i++) {\n this._emitChange(events[i]);\n if (this.diffHandler) {\n this.diffHandler(events[i].path);\n }\n }\n }\n\n private _getAllDescendentPaths(path: string) {\n if (isFolder(path)) {\n return this.getNodes([path]).then((nodes) => {\n const allPaths = [path];\n const latest = getLatest(nodes[path]);\n\n const itemNames = Object.keys(latest.itemsMap);\n const calls = itemNames.map((itemName) => {\n return this._getAllDescendentPaths(path + itemName).then((paths) => {\n for (let i = 0, len = paths.length; i < len; i++) {\n allPaths.push(paths[i]);\n }\n });\n });\n return Promise.all(calls).then(() => {\n return allPaths;\n });\n });\n } else {\n return Promise.resolve([path]);\n }\n }\n\n // treated as private but made public for unit testing\n _getInternals() {\n return {\n getLatest: getLatest,\n makeNode: makeNode,\n isOutdated: isOutdated\n };\n }\n}\n\n\nfunction getLatest(node: RSNode): any {\n if (typeof (node) !== 'object' || typeof (node.path) !== 'string') {\n return;\n }\n if (isFolder(node.path)) {\n if (node.local && node.local.itemsMap) {\n return node.local;\n }\n if (node.common && node.common.itemsMap) {\n return node.common;\n }\n } else {\n if (node.local) {\n if (node.local.body && node.local.contentType) {\n return node.local;\n }\n if (node.local.body === false) {\n return;\n }\n }\n if (node.common && node.common.body && node.common.contentType) {\n return node.common;\n }\n // Migration code! Once all apps use at least this version of the lib, we\n // can publish clean-up code that migrates over any old-format data, and\n // stop supporting it. For now, new apps will support data in both\n // formats, thanks to this:\n if (node.body && node.contentType) {\n return {\n body: node.body,\n contentType: node.contentType\n };\n }\n }\n}\n\nfunction isOutdated(nodes: RSNodes, maxAge: number): boolean {\n for (const path in nodes) {\n if (nodes[path] && nodes[path].remote) {\n return true;\n }\n const nodeVersion = getLatest(nodes[path]);\n if (nodeVersion && nodeVersion.timestamp && (new Date().getTime()) - nodeVersion.timestamp <= maxAge) {\n return false;\n } else if (!nodeVersion) {\n return true;\n }\n }\n return true;\n}\n\n\nfunction makeNode(path: string): RSNode {\n const node: RSNode = {path: path, common: {}};\n\n if (isFolder(path)) {\n node.common.itemsMap = {};\n }\n return node;\n}\n\nfunction updateFolderNodeWithItemName(node: RSNode, itemName: string): RSNode {\n if (!node.common) {\n node.common = {\n itemsMap: {}\n };\n }\n if (!node.common.itemsMap) {\n node.common.itemsMap = {};\n }\n if (!node.local) {\n node.local = deepClone(node.common);\n }\n if (!node.local.itemsMap) {\n node.local.itemsMap = node.common.itemsMap;\n }\n node.local.itemsMap[itemName] = true;\n\n return node;\n}\n\ninterface CachingLayer extends EventHandling {};\napplyMixins(CachingLayer, [EventHandling]);\n\nexport = CachingLayer;\n","// TODO maybe move to common interfaces & types file\n// also worth considering enums\ntype AccessMode = 'r' | 'rw';\ntype AccessScope = string;\n\ninterface ScopeEntry {\n name: string;\n mode: AccessMode;\n}\n\ninterface ScopeModeMap {\n // NOTE: key is actually AccessScope\n [key: string]: AccessMode;\n}\n\n/**\n * @class Access\n *\n * Keeps track of claimed access and scopes.\n */\nclass Access {\n scopeModeMap: ScopeModeMap;\n rootPaths: string[];\n storageType: string;\n\n // TODO create custom type for init function\n static _rs_init(): void {\n return;\n }\n\n constructor() {\n this.reset();\n }\n\n /**\n * Property: scopes\n *\n * Holds an array of claimed scopes in the form\n * > { name: \"\", mode: \"\" }\n */\n get scopes(): ScopeEntry[] {\n return Object.keys(this.scopeModeMap).map((key) => {\n return { name: key, mode: this.scopeModeMap[key] };\n });\n }\n\n get scopeParameter(): string {\n return this.scopes.map((scope) => {\n return `${this._scopeNameForParameter(scope)}:${scope.mode}`;\n }).join(' ');\n }\n\n /**\n * Claim access on a given scope with given mode.\n *\n * @param {string} scope - An access scope, such as \"contacts\" or \"calendar\"\n * @param {string} mode - Access mode. Either \"r\" for read-only or \"rw\" for read/write\n */\n claim (scope: AccessScope, mode: AccessMode): void {\n if (typeof (scope) !== 'string' || scope.indexOf('/') !== -1 || scope.length === 0) {\n throw new Error('Scope should be a non-empty string without forward slashes');\n }\n if (!mode.match(/^rw?$/)) {\n throw new Error('Mode should be either \\'r\\' or \\'rw\\'');\n }\n this._adjustRootPaths(scope);\n this.scopeModeMap[scope] = mode;\n }\n\n /**\n * Get the access mode for a given scope.\n *\n * @param {string} scope - Access scope\n * @returns {string} Access mode\n */\n get (scope: AccessScope): AccessMode {\n return this.scopeModeMap[scope];\n }\n\n\n /**\n * Remove access for the given scope.\n *\n * @param {string} scope - Access scope\n */\n remove (scope: AccessScope): void {\n const savedMap: ScopeModeMap = {};\n for (const name in this.scopeModeMap) {\n savedMap[name] = this.scopeModeMap[name];\n }\n this.reset();\n delete savedMap[scope];\n for (const name in savedMap) {\n this.claim(name as AccessScope, savedMap[name]);\n }\n }\n\n /**\n * Verify permission for a given scope.\n *\n * @param {string} scope - Access scope\n * @param {string} mode - Access mode\n * @returns {boolean} true if the requested access mode is active, false otherwise\n */\n checkPermission (scope: AccessScope, mode: AccessMode): boolean {\n const actualMode = this.get(scope);\n return actualMode && (mode === 'r' || actualMode === 'rw');\n }\n\n /**\n * Verify permission for a given path.\n *\n * @param {string} path - Path\n * @param {string} mode - Access mode\n * @returns {boolean} true if the requested access mode is active, false otherwise\n */\n checkPathPermission (path: string, mode: AccessMode): boolean {\n if (this.checkPermission('*', mode)) {\n return true;\n }\n // TODO check if this is reliable\n const scope = this._getModuleName(path) as AccessScope;\n return !!this.checkPermission(scope, mode);\n }\n\n /**\n * Reset all access permissions.\n */\n reset(): void {\n this.rootPaths = [];\n this.scopeModeMap = {};\n }\n\n /**\n * Return the module name for a given path.\n */\n private _getModuleName (path): string {\n if (path[0] !== '/') {\n throw new Error('Path should start with a slash');\n }\n const moduleMatch = path.replace(/^\\/public/, '').match(/^\\/([^/]*)\\//);\n return moduleMatch ? moduleMatch[1] : '*';\n }\n\n /**\n * TODO: document\n */\n private _adjustRootPaths (newScope: AccessScope): void {\n if ('*' in this.scopeModeMap || newScope === '*') {\n this.rootPaths = ['/'];\n } else if (!(newScope in this.scopeModeMap)) {\n this.rootPaths.push('/' + newScope + '/');\n this.rootPaths.push('/public/' + newScope + '/');\n }\n }\n\n /**\n * TODO: document\n */\n private _scopeNameForParameter (scope: ScopeEntry): string {\n if (scope.name === '*' && this.storageType) {\n if (this.storageType === '2012.04') {\n return '';\n } else if (this.storageType.match(/remotestorage-0[01]/)) {\n return 'root';\n }\n }\n return scope.name;\n }\n\n /**\n * Set the storage type of the remote.\n *\n * @param {string} type - Storage type\n */\n setStorageType (type: string): void {\n this.storageType = type;\n }\n}\n\nexport = Access;\n","import { containingFolder, isFolder } from './util';\nimport log from './log';\n\n/**\n * @class Caching\n *\n * Holds/manages caching configuration.\n **/\nclass Caching {\n pendingActivations: string[] = [];\n // TODO add correct type\n activateHandler: Function;\n\n private _rootPaths: object;\n\n constructor () {\n this.reset();\n }\n\n /**\n * Configure caching for a given path explicitly.\n *\n * Not needed when using ``enable``/``disable``.\n *\n * @param {string} path - Path to cache\n * @param {string} strategy - Caching strategy. One of 'ALL', 'SEEN', or 'FLUSH'.\n */\n set (path: string, strategy: 'ALL' | 'SEEN' | 'FLUSH'): void {\n if (typeof path !== 'string') {\n throw new Error('path should be a string');\n }\n if (!isFolder(path)) {\n throw new Error('path should be a folder');\n }\n // FIXME We need to get to the access instance somehow. But I'm not sure\n // this check is even necessary in the first place. -raucao\n // if (!this._remoteStorage.access.checkPathPermission(path, 'r')) {\n // throw new Error('No access to path \"' + path + '\". You have to claim access to it first.');\n // }\n if (!strategy.match(/^(FLUSH|SEEN|ALL)$/)) {\n throw new Error(\"strategy should be 'FLUSH', 'SEEN', or 'ALL'\");\n }\n\n this._rootPaths[path] = strategy;\n\n if (strategy === 'ALL') {\n if (this.activateHandler) {\n this.activateHandler(path);\n } else {\n this.pendingActivations.push(path);\n }\n }\n }\n\n /**\n * Enable caching for a given path.\n *\n * Uses caching strategy ``ALL``.\n *\n * @param {string} path - Path to enable caching for\n */\n enable (path: string): void {\n this.set(path, 'ALL');\n }\n\n /**\n * Disable caching for a given path.\n *\n * Uses caching strategy ``FLUSH`` (meaning items are only cached until\n * successfully pushed to the remote).\n *\n * @param {string} path - Path to disable caching for\n */\n disable (path: string): void {\n this.set(path, 'FLUSH');\n }\n\n /**\n * Set a callback for when caching is activated for a path.\n *\n * @param {function} cb - Callback function\n */\n onActivate (cb: (firstPending: string) => void): void {\n log('[Caching] Setting activate handler', cb, this.pendingActivations);\n this.activateHandler = cb;\n for (let i = 0; i < this.pendingActivations.length; i++) {\n cb(this.pendingActivations[i]);\n }\n this.pendingActivations = [];\n }\n\n /**\n * Retrieve caching setting for a given path, or its next parent\n * with a caching strategy set.\n *\n * @param {string} path - Path to retrieve setting for\n * @returns {string} caching strategy for the path\n **/\n checkPath (path: string): string {\n if (this._rootPaths[path] !== undefined) {\n return this._rootPaths[path];\n } else if (path === '/') {\n return 'SEEN';\n } else {\n return this.checkPath(containingFolder(path));\n }\n }\n\n /**\n * Reset the state of caching by deleting all caching information.\n **/\n reset (): void {\n this._rootPaths = {};\n }\n\n /**\n * Setup function that is called on initialization.\n *\n * @private\n **/\n static _rs_init (/*remoteStorage*/): void {\n return;\n }\n}\n\nexport = Caching;\n","import BaseClient from './baseclient';\nimport WireClient from './wireclient';\nimport EventHandling from './eventhandling';\nimport {\n applyMixins,\n isFolder,\n cleanPath,\n shouldBeTreatedAsBinary,\n getJSONFromLocalStorage,\n getTextFromArrayBuffer,\n localStorageAvailable\n} from './util';\n\nconst BASE_URL = 'https://www.googleapis.com';\nconst AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';\nconst AUTH_SCOPE = 'https://www.googleapis.com/auth/drive';\nconst SETTINGS_KEY = 'remotestorage:googledrive';\nconst PATH_PREFIX = '/remotestorage';\n\nconst GD_DIR_MIME_TYPE = 'application/vnd.google-apps.folder';\nconst RS_DIR_MIME_TYPE = 'application/json; charset=UTF-8';\n\nlet hasLocalStorage;\n\n/**\n * Produce a title from a filename for metadata.\n *\n * @param {string} filename\n * @returns {string} title\n *\n * @private\n */\nfunction metaTitleFromFileName (filename: string): string {\n if (filename.substr(-1) === '/') {\n filename = filename.substr(0, filename.length - 1);\n }\n\n return decodeURIComponent(filename);\n}\n\n/**\n * Get the parent directory for the given path.\n *\n * @param {string} path\n * @returns {string} parent directory\n *\n * @private\n */\nfunction parentPath (path: string): string {\n return path.replace(/[^\\/]+\\/?$/, '');\n}\n\n/**\n * Get only the filename from a full path.\n *\n * @param {string} path\n * @returns {string} filename\n *\n * @private\n */\nfunction baseName (path: string): string {\n const parts = path.split('/');\n if (path.substr(-1) === '/') {\n return parts[parts.length-2]+'/';\n } else {\n return parts[parts.length-1];\n }\n}\n\n/**\n * Prepend the path with the remoteStorage base directory.\n *\n * @param {string} path - Path\n * @returns {string} Actual path on Google Drive\n *\n * @private\n */\nfunction googleDrivePath (path: string): string {\n return cleanPath(`${PATH_PREFIX}/${path}`);\n}\n\n/**\n * Remove surrounding quotes from a string.\n *\n * @param {string} string - string with surrounding quotes\n * @returns {string} string without surrounding quotes\n *\n * @private\n */\nfunction removeQuotes (str: string): string {\n return str.replace(/^[\"'](.*)[\"']$/, \"$1\");\n}\n\n/**\n * Internal cache object for storing Google file IDs.\n *\n * @param {number} maxAge - Maximum age (in seconds) the content should be cached for\n */\nclass FileIdCache {\n maxAge: number;\n _items = {}\n\n constructor(maxAge?: number) {\n this.maxAge = maxAge;\n this._items = {};\n }\n\n get (key): number | undefined {\n const item = this._items[key];\n const now = new Date().getTime();\n return (item && item.t >= (now - this.maxAge)) ? item.v : undefined;\n }\n\n set (key, value): void {\n this._items[key] = {\n v: value,\n t: new Date().getTime()\n };\n }\n};\n\n/**\n * Overwrite BaseClient's getItemURL with our own implementation\n *\n * TODO: Still needs to be implemented. At the moment it just throws\n * and error saying that it's not implemented yet.\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction hookGetItemURL (rs): void {\n if (rs._origBaseClientGetItemURL) { return; }\n rs._origBaseClientGetItemURL = BaseClient.prototype.getItemURL;\n BaseClient.prototype.getItemURL = function (/* path */): never {\n throw new Error('getItemURL is not implemented for Google Drive yet');\n };\n}\n\n/**\n * Restore BaseClient's getItemURL original implementation\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction unHookGetItemURL (rs): void {\n if (!rs._origBaseClientGetItemURL) { return; }\n BaseClient.prototype.getItemURL = rs._origBaseClientGetItemURL;\n delete rs._origBaseClientGetItemURL;\n}\n\n/**\n * @class GoogleDrive\n *\n * To use this backend, you need to specify the app's client ID like so:\n *\n * @example\n * remoteStorage.setApiKeys({\n * googledrive: 'your-client-id'\n * });\n *\n * A client ID can be obtained by registering your app in the Google\n * Developers Console: https://console.developers.google.com/flows/enableapi?apiid=drive\n *\n * Docs: https://developers.google.com/drive/v3/web/quickstart/js\n**/\nclass GoogleDrive {\n rs: any;\n clientId: string;\n userAddress: string;\n token: string;\n connected = false;\n online = true;\n\n _fileIdCache: FileIdCache;\n\n constructor(remoteStorage, clientId) {\n this.addEvents(['connected', 'not-connected']);\n\n this.rs = remoteStorage;\n this.clientId = clientId;\n\n this._fileIdCache = new FileIdCache(60 * 5); // IDs expire after 5 minutes (is this a good idea?)\n\n hasLocalStorage = localStorageAvailable();\n\n if (hasLocalStorage){\n const settings = getJSONFromLocalStorage(SETTINGS_KEY);\n if (settings) {\n this.configure(settings);\n }\n }\n }\n\n /**\n * Configure the Google Drive backend.\n *\n * Fetches the user info from Google when no ``userAddress`` is given.\n *\n * @param {Object} settings\n * @param {string} [settings.userAddress] - The user's email address\n * @param {string} [settings.token] - Authorization token\n *\n * @protected\n */\n configure (settings) { // Settings parameter compatible with WireClient\n // We only update this.userAddress if settings.userAddress is set to a string or to null\n if (typeof settings.userAddress !== 'undefined') { this.userAddress = settings.userAddress; }\n // Same for this.token. If only one of these two is set, we leave the other one at its existing value\n if (typeof settings.token !== 'undefined') { this.token = settings.token; }\n\n const writeSettingsToCache = function() {\n if (hasLocalStorage) {\n localStorage.setItem(SETTINGS_KEY, JSON.stringify({\n userAddress: this.userAddress,\n token: this.token\n }));\n }\n };\n\n const handleError = function() {\n this.connected = false;\n delete this.token;\n if (hasLocalStorage) {\n localStorage.removeItem(SETTINGS_KEY);\n }\n };\n\n if (this.token) {\n this.connected = true;\n\n if (this.userAddress) {\n this._emit('connected');\n writeSettingsToCache.apply(this);\n } else {\n this.info().then((info) => {\n this.userAddress = info.user.emailAddress;\n this._emit('connected');\n writeSettingsToCache.apply(this);\n }).catch(() => {\n handleError.apply(this);\n this.rs._emit('error', new Error('Could not fetch user info.'));\n });\n }\n } else {\n handleError.apply(this);\n }\n }\n\n /**\n * Initiate the authorization flow's OAuth dance.\n */\n connect (): void {\n this.rs.setBackend('googledrive');\n this.rs.authorize({ authURL: AUTH_URL, scope: AUTH_SCOPE, clientId: this.clientId });\n }\n\n /**\n * Stop the authorization process.\n *\n * @protected\n */\n stopWaitingForToken (): void {\n if (!this.connected) {\n this._emit('not-connected');\n }\n }\n\n /**\n * Request a resource (file or directory).\n *\n * @param {string} path - Path of the resource\n * @param {Object} options - Request options\n * @returns {Promise} Resolves with an object containing the status code,\n * body, content-type and revision\n *\n * @protected\n */\n get (path, options) {\n if (isFolder(path)) {\n return this._getFolder(googleDrivePath(path));\n } else {\n return this._getFile(googleDrivePath(path), options);\n }\n }\n\n /**\n * Create or update a file.\n *\n * @param {string} path - File path\n * @param body - File content\n * @param {string} contentType - File content-type\n * @param {Object} options\n * @param {string} options.ifNoneMatch - Only create of update the file if the\n * current ETag doesn't match this string\n * @returns {Promise} Resolves with an object containing the status code,\n * content-type and revision\n *\n * @protected\n */\n put (path, body, contentType, options) {\n const fullPath = googleDrivePath(path);\n\n function putDone(response) {\n if (response.status >= 200 && response.status < 300) {\n const meta = JSON.parse(response.responseText);\n const etagWithoutQuotes = removeQuotes(meta.etag);\n return Promise.resolve({statusCode: 200, contentType: meta.mimeType, revision: etagWithoutQuotes});\n } else if (response.status === 412) {\n return Promise.resolve({statusCode: 412, revision: 'conflict'});\n } else {\n return Promise.reject(\"PUT failed with status \" + response.status + \" (\" + response.responseText + \")\");\n }\n }\n\n return this._getFileId(fullPath).then((id) => {\n if (id) {\n if (options && (options.ifNoneMatch === '*')) {\n return putDone({ status: 412 });\n }\n return this._updateFile(id, fullPath, body, contentType, options).then(putDone);\n } else {\n return this._createFile(fullPath, body, contentType).then(putDone);\n }\n });\n }\n\n /**\n * Delete a file.\n *\n * @param {string} path - File path\n * @param {Object} options\n * @param {string} options.ifMatch - only delete the file if it's ETag\n * matches this string\n * @returns {Promise} Resolves with an object containing the status code\n *\n * @protected\n */\n delete (path, options) {\n const fullPath = googleDrivePath(path);\n\n return this._getFileId(fullPath).then((id) => {\n if (!id) {\n // File doesn't exist. Ignore.\n return Promise.resolve({statusCode: 200});\n }\n\n return this._getMeta(id).then((meta) => {\n let etagWithoutQuotes;\n if ((typeof meta === 'object') && (typeof meta.etag === 'string')) {\n etagWithoutQuotes = removeQuotes(meta.etag);\n }\n if (options && options.ifMatch && (options.ifMatch !== etagWithoutQuotes)) {\n return {statusCode: 412, revision: etagWithoutQuotes};\n }\n\n return this._request('DELETE', BASE_URL + '/drive/v2/files/' + id, {}).then((response) => {\n if (response.status === 200 || response.status === 204) {\n return {statusCode: 200};\n } else {\n return Promise.reject(\"Delete failed: \" + response.status + \" (\" + response.responseText + \")\");\n }\n });\n });\n });\n }\n\n /**\n * Fetch the user's info from Google.\n *\n * @returns {Promise} resolves with the user's info.\n *\n * @protected\n */\n info () {\n const url = BASE_URL + '/drive/v2/about?fields=user';\n // requesting user info(mainly for userAdress)\n return this._request('GET', url, {}).then(function (resp){\n try {\n const info = JSON.parse(resp.responseText);\n return Promise.resolve(info);\n } catch (e) {\n return Promise.reject(e);\n }\n });\n }\n\n /**\n * Update an existing file.\n *\n * @param {string} id - File ID\n * @param {string} path - File path\n * @param body - File content\n * @param {string} contentType - File content-type\n * @param {Object} options\n * @param {string} options.ifMatch - Only update the file if its ETag\n * matches this string\n * @returns {Promise} Resolves with the response of the network request\n *\n * @private\n */\n _updateFile (id, path, body, contentType, options) {\n const metadata = {\n mimeType: contentType\n };\n const headers = {\n 'Content-Type': 'application/json; charset=UTF-8'\n };\n\n if (options && options.ifMatch) {\n headers['If-Match'] = '\"' + options.ifMatch + '\"';\n }\n\n return this._request('PUT', BASE_URL + '/upload/drive/v2/files/' + id + '?uploadType=resumable', {\n body: JSON.stringify(metadata),\n headers: headers\n }).then((response) => {\n if (response.status === 412) {\n return (response);\n } else {\n return this._request('PUT', response.getResponseHeader('Location'), {\n body: contentType.match(/^application\\/json/) ? JSON.stringify(body) : body\n });\n }\n });\n }\n\n /**\n * Create a new file.\n *\n * @param {string} path - File path\n * @param body - File content\n * @param {string} contentType - File content-type\n * @returns {Promise} Resolves with the response of the network request\n *\n * @private\n */\n _createFile (path, body, contentType) {\n return this._getParentId(path).then((parentId) => {\n const fileName = baseName(path);\n const metadata = {\n title: metaTitleFromFileName(fileName),\n mimeType: contentType,\n parents: [{\n kind: \"drive#fileLink\",\n id: parentId\n }]\n };\n return this._request('POST', BASE_URL + '/upload/drive/v2/files?uploadType=resumable', {\n body: JSON.stringify(metadata),\n headers: {\n 'Content-Type': 'application/json; charset=UTF-8'\n }\n }).then((response) => {\n return this._request('POST', response.getResponseHeader('Location'), {\n body: contentType.match(/^application\\/json/) ? JSON.stringify(body) : body\n });\n });\n });\n }\n\n /**\n * Request a file.\n *\n * @param {string} path - File path\n * @param {Object} options\n * @param {string} [options.ifNoneMath] - Only return the file if its ETag\n * doesn't match the given string\n * @returns {Promise} Resolves with an object containing the status code,\n * body, content-type and revision\n *\n * @private\n */\n _getFile (path, options) {\n return this._getFileId(path).then((id) => {\n return this._getMeta(id).then((meta) => {\n let etagWithoutQuotes;\n if (typeof(meta) === 'object' && typeof(meta.etag) === 'string') {\n etagWithoutQuotes = removeQuotes(meta.etag);\n }\n\n if (options && options.ifNoneMatch && (etagWithoutQuotes === options.ifNoneMatch)) {\n return Promise.resolve({statusCode: 304});\n }\n\n if (!meta.downloadUrl) {\n if (meta.exportLinks && meta.exportLinks['text/html']) {\n // Documents that were generated inside GoogleDocs have no\n // downloadUrl, but you can export them to text/html instead:\n meta.mimeType += ';export=text/html';\n meta.downloadUrl = meta.exportLinks['text/html'];\n } else {\n // empty file\n return Promise.resolve({statusCode: 200, body: '', contentType: meta.mimeType, revision: etagWithoutQuotes});\n }\n }\n\n const params = {\n responseType: 'arraybuffer'\n };\n return this._request('GET', meta.downloadUrl, params).then((response) => {\n //first encode the response as text, and later check if\n //text appears to actually be binary data\n return getTextFromArrayBuffer(response.response, 'UTF-8').then(function (responseText) {\n let body = responseText;\n if (meta.mimeType.match(/^application\\/json/)) {\n try {\n body = JSON.parse(body as string);\n } catch(e) {\n // body couldn't be parsed as JSON, so we'll just return it as is\n }\n } else if (shouldBeTreatedAsBinary(responseText, meta.mimeType)) {\n //return unprocessed response\n body = response.response;\n }\n\n return {\n statusCode: 200,\n body: body,\n contentType: meta.mimeType,\n revision: etagWithoutQuotes\n };\n });\n });\n });\n });\n }\n\n /**\n * Request a directory.\n *\n * @param {string} path - Directory path\n * @param {Object} options\n * @returns {Promise} Resolves with an object containing the status code,\n * body and content-type\n *\n * @private\n */\n _getFolder (path) {\n return this._getFileId(path).then((id) => {\n let data, etagWithoutQuotes, itemsMap;\n if (! id) {\n return Promise.resolve({statusCode: 404});\n }\n\n const query = '\\'' + id + '\\' in parents';\n const fields = 'items(downloadUrl,etag,fileSize,id,mimeType,title,labels)';\n return this._request('GET', BASE_URL + '/drive/v2/files?'\n + 'q=' + encodeURIComponent(query)\n + '&fields=' + encodeURIComponent(fields)\n + '&maxResults=1000'\n + '&trashed=false',\n {})\n .then((response) => {\n if (response.status !== 200) {\n return Promise.reject('request failed or something: ' + response.status);\n }\n\n try {\n data = JSON.parse(response.responseText);\n } catch(e) {\n return Promise.reject('non-JSON response from GoogleDrive');\n }\n\n itemsMap = {};\n for (const item of data.items) {\n if (item.labels?.trashed) { continue; } // ignore deleted files\n\n etagWithoutQuotes = removeQuotes(item.etag);\n if (item.mimeType === GD_DIR_MIME_TYPE) {\n this._fileIdCache.set(path + cleanPath(item.title) + '/', item.id);\n itemsMap[item.title + '/'] = {\n ETag: etagWithoutQuotes\n };\n } else {\n this._fileIdCache.set(path + cleanPath(item.title), item.id);\n itemsMap[item.title] = {\n ETag: etagWithoutQuotes,\n 'Content-Type': item.mimeType,\n 'Content-Length': item.fileSize\n };\n }\n }\n\n // FIXME: add revision of folder!\n return Promise.resolve({statusCode: 200, body: itemsMap, contentType: RS_DIR_MIME_TYPE, revision: undefined});\n });\n });\n }\n\n /**\n * Get the ID of a parent path.\n *\n * Creates the directory if it doesn't exist yet.\n *\n * @param {string} path - Full path of a directory or file\n * @returns {Promise} Resolves with ID of the parent directory.\n *\n * @private\n */\n _getParentId (path) {\n const foldername = parentPath(path);\n\n return this._getFileId(foldername).then((parentId) => {\n if (parentId) {\n return Promise.resolve(parentId);\n } else {\n return this._createFolder(foldername);\n }\n });\n }\n\n /**\n * Create a directory.\n *\n * Creates all parent directories as well if any of them didn't exist yet.\n *\n * @param {string} path - Directory path\n * @returns {Promise} Resolves with the ID of the new directory\n *\n * @private\n */\n _createFolder (path) {\n return this._getParentId(path).then((parentId) => {\n return this._request('POST', BASE_URL + '/drive/v2/files', {\n body: JSON.stringify({\n title: metaTitleFromFileName(baseName(path)),\n mimeType: GD_DIR_MIME_TYPE,\n parents: [{\n id: parentId\n }]\n }),\n headers: {\n 'Content-Type': 'application/json; charset=UTF-8'\n }\n }).then((response) => {\n const meta = JSON.parse(response.responseText);\n return Promise.resolve(meta.id);\n });\n });\n }\n\n /**\n * Get the ID of a file.\n *\n * @param {string} path - File path\n * @returns {Promise} Resolves with the ID\n *\n * @private\n */\n _getFileId (path) {\n let id;\n\n if (path === '/') {\n // \"root\" is a special alias for the fileId of the root folder\n return Promise.resolve('root');\n } else if ((id = this._fileIdCache.get(path))) {\n // id is cached.\n return Promise.resolve(id);\n }\n // id is not cached (or file doesn't exist).\n // load parent folder listing to propagate / update id cache.\n return this._getFolder(parentPath(path)).then(() => {\n id = this._fileIdCache.get(path);\n if (!id) {\n if (path.substr(-1) === '/') {\n return this._createFolder(path).then(() => {\n return this._getFileId(path);\n });\n } else {\n return Promise.resolve();\n }\n }\n return Promise.resolve(id);\n });\n }\n\n /**\n * Get the metadata for a given file ID.\n *\n * @param {string} id - File ID\n * @returns {Promise} Resolves with an object containing the metadata\n *\n * @private\n */\n _getMeta (id) {\n return this._request('GET', BASE_URL + '/drive/v2/files/' + id, {}).then(function (response) {\n if (response.status === 200) {\n return Promise.resolve(JSON.parse(response.responseText));\n } else {\n return Promise.reject(\"request (getting metadata for \" + id + \") failed with status: \" + response.status);\n }\n });\n }\n\n /**\n * Make a network request.\n *\n * @param {string} method - Request method\n * @param {string} url - Target URL\n * @param {Object} options - Request options\n * @returns {Promise} Resolves with the response of the network request\n *\n * @private\n */\n _request (method, url, options) {\n if (! options.headers) { options.headers = {}; }\n options.headers['Authorization'] = 'Bearer ' + this.token;\n\n this.rs._emit('wire-busy', {\n method: method,\n isFolder: isFolder(url)\n });\n\n return WireClient.request.call(this, method, url, options).then((xhr) => {\n // Google tokens expire from time to time...\n if (xhr && xhr.status === 401) {\n this.connect();\n return;\n } else {\n if (!this.online) {\n this.online = true;\n this.rs._emit('network-online');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(url),\n success: true\n });\n\n return Promise.resolve(xhr);\n }\n }, (error) => {\n if (this.online) {\n this.online = false;\n this.rs._emit('network-offline');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(url),\n success: false\n });\n\n return Promise.reject(error);\n });\n }\n\n /**\n * Initialize the Google Drive backend.\n *\n * @param {Object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n static _rs_init (remoteStorage): void {\n const config = remoteStorage.apiKeys.googledrive;\n if (config) {\n remoteStorage.googledrive = new GoogleDrive(remoteStorage, config.clientId);\n if (remoteStorage.backend === 'googledrive') {\n remoteStorage._origRemote = remoteStorage.remote;\n remoteStorage.remote = remoteStorage.googledrive;\n\n hookGetItemURL(remoteStorage);\n }\n }\n }\n\n /**\n * Inform about the availability of the Google Drive backend.\n *\n * @param {Object} rs - RemoteStorage instance\n * @returns {Boolean}\n *\n * @protected\n */\n static _rs_supported (): boolean {\n return true;\n };\n\n /**\n * Remove Google Drive as a backend.\n *\n * @param {Object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n static _rs_cleanup (remoteStorage): void {\n remoteStorage.setBackend(undefined);\n if (remoteStorage._origRemote) {\n remoteStorage.remote = remoteStorage._origRemote;\n delete remoteStorage._origRemote;\n }\n unHookGetItemURL(remoteStorage);\n };\n}\n\ninterface GoogleDrive extends EventHandling {};\napplyMixins(GoogleDrive, [EventHandling]);\n\nexport = GoogleDrive;\n","import EventHandling from './eventhandling';\nimport WireClient from './wireclient';\nimport BaseClient from './baseclient';\nimport RevisionCache from './revisioncache';\nimport SyncError from './sync-error';\nimport UnauthorizedError from './unauthorized-error';\nimport {\n applyMixins,\n cleanPath,\n isFolder,\n shouldBeTreatedAsBinary,\n getJSONFromLocalStorage,\n getTextFromArrayBuffer,\n localStorageAvailable\n} from './util';\n\n/**\n * WORK IN PROGRESS, NOT RECOMMENDED FOR PRODUCTION USE\n *\n * Dropbox backend for RemoteStorage.js\n * This file exposes a get/put/delete interface which is compatible with\n * .\n *\n * When remoteStorage.backend is set to 'dropbox', this backend will\n * initialize and replace remoteStorage.remote with remoteStorage.dropbox.\n *\n * In order to ensure compatibility with the public folder, \n * gets hijacked to return the Dropbox public share URL.\n *\n * To use this backend, you need to specify the Dropbox app key like so:\n *\n * @example\n * remoteStorage.setApiKeys({\n * dropbox: 'your-app-key'\n * });\n *\n * An app key can be obtained by registering your app at https://www.dropbox.com/developers/apps\n *\n * Known issues:\n *\n * - Storing files larger than 150MB is not yet supported\n * - Listing and deleting folders with more than 10'000 files will cause problems\n * - Content-Type is not fully supported due to limitations of the Dropbox API\n * - Dropbox preserves cases but is not case-sensitive\n * - getItemURL is asynchronous which means it returns useful values\n * after the syncCycle\n */\n\nlet hasLocalStorage;\nconst AUTH_URL = 'https://www.dropbox.com/oauth2/authorize';\nconst SETTINGS_KEY = 'remotestorage:dropbox';\nconst PATH_PREFIX = '/remotestorage';\n\n/**\n * Map a local path to a path in Dropbox.\n *\n * @param {string} path - Path\n * @returns {string} Actual path in Dropbox\n *\n * @private\n */\nfunction getDropboxPath (path: string): string {\n return cleanPath(PATH_PREFIX + '/' + path).replace(/\\/$/, '');\n};\n\nfunction compareApiError (response, expect) {\n return new RegExp('^' + expect.join('\\\\/') + '(\\\\/|$)').test(response.error_summary);\n};\n\nfunction isBinaryData (data) {\n return data instanceof ArrayBuffer || WireClient.isArrayBufferView(data);\n};\n\n/**\n * @class\n */\nclass Dropbox {\n rs: any;\n connected: boolean;\n online: boolean;\n clientId: string;\n token: string;\n userAddress: string;\n\n _initialFetchDone: boolean;\n _revCache: RevisionCache;\n _fetchDeltaCursor: any;\n _fetchDeltaPromise: any;\n _itemRefs: any;\n\n // TODO remove when refactoring eventhandling\n _emit: any;\n\n constructor (rs) {\n this.rs = rs;\n this.connected = false;\n this.online = true; // TODO implement offline detection on failed request\n this._initialFetchDone = false;\n\n this.addEvents(['connected', 'not-connected']);\n\n this.clientId = rs.apiKeys.dropbox.appKey;\n this._revCache = new RevisionCache('rev');\n this._fetchDeltaCursor = null;\n this._fetchDeltaPromise = null;\n this._itemRefs = {};\n\n hasLocalStorage = localStorageAvailable();\n\n if (hasLocalStorage){\n const settings = getJSONFromLocalStorage(SETTINGS_KEY);\n if (settings) {\n this.configure(settings);\n }\n this._itemRefs = getJSONFromLocalStorage(`${SETTINGS_KEY}:shares`) || {};\n }\n if (this.connected) {\n setTimeout(this._emit.bind(this), 0, 'connected');\n }\n }\n\n /**\n * Set the backed to 'dropbox' and start the authentication flow in order\n * to obtain an API token from Dropbox.\n */\n connect () {\n // TODO handling when token is already present\n this.rs.setBackend('dropbox');\n if (this.token){\n hookIt(this.rs);\n } else {\n this.rs.authorize({ authURL: AUTH_URL, scope: '', clientId: this.clientId });\n }\n }\n\n /**\n * Sets the connected flag\n * Accepts its parameters according to the .\n * @param {Object} settings\n * @param {string} [settings.userAddress] - The user's email address\n * @param {string} [settings.token] - Authorization token\n *\n * @protected\n **/\n configure (settings) {\n // We only update this.userAddress if settings.userAddress is set to a string or to null:\n if (typeof settings.userAddress !== 'undefined') { this.userAddress = settings.userAddress; }\n // Same for this.token. If only one of these two is set, we leave the other one at its existing value:\n if (typeof settings.token !== 'undefined') { this.token = settings.token; }\n\n const writeSettingsToCache = function() {\n if (hasLocalStorage) {\n localStorage.setItem(SETTINGS_KEY, JSON.stringify({\n userAddress: this.userAddress,\n token: this.token\n }));\n }\n };\n\n const handleError = function() {\n this.connected = false;\n if (hasLocalStorage) {\n localStorage.removeItem(SETTINGS_KEY);\n }\n };\n\n if (this.token) {\n this.connected = true;\n if (this.userAddress) {\n this._emit('connected');\n writeSettingsToCache.apply(this);\n } else {\n this.info().then(function (info){\n this.userAddress = info.email;\n this._emit('connected');\n writeSettingsToCache.apply(this);\n }.bind(this)).catch(function() {\n handleError.apply(this);\n this.rs._emit('error', new Error('Could not fetch user info.'));\n }.bind(this));\n }\n } else {\n handleError.apply(this);\n }\n }\n\n /**\n * Stop waiting for the token and emit not-connected\n *\n * @protected\n */\n stopWaitingForToken () {\n if (!this.connected) {\n this._emit('not-connected');\n }\n }\n\n /**\n * Get all items in a folder.\n *\n * @param path {string} - path of the folder to get, with leading slash\n * @return {Object}\n * statusCode - HTTP status code\n * body - array of the items found\n * contentType - 'application/json; charset=UTF-8'\n * revision - revision of the folder\n *\n * @private\n */\n _getFolder (path) {\n const url = 'https://api.dropboxapi.com/2/files/list_folder';\n const revCache = this._revCache;\n\n const processResponse = (resp) => {\n let body;\n\n if (resp.status !== 200 && resp.status !== 409) {\n return Promise.reject('Unexpected response status: ' + resp.status);\n }\n\n try {\n body = JSON.parse(resp.responseText);\n } catch (e) {\n return Promise.reject(e);\n }\n\n if (resp.status === 409) {\n if (compareApiError(body, ['path', 'not_found'])) {\n // if the folder is not found, handle it as an empty folder\n return Promise.resolve({});\n }\n\n return Promise.reject(new Error('API returned an error: ' + body.error_summary));\n }\n\n const listing = body.entries.reduce((map, item) => {\n const isDir = item['.tag'] === 'folder';\n const itemName = item.path_lower.split('/').slice(-1)[0] + (isDir ? '/' : '');\n if (isDir){\n map[itemName] = { ETag: revCache.get(path+itemName) };\n } else {\n map[itemName] = { ETag: item.rev };\n this._revCache.set(path+itemName, item.rev);\n }\n return map;\n }, {});\n\n if (body.has_more) {\n return loadNext(body.cursor).then(function (nextListing) {\n return Object.assign(listing, nextListing);\n });\n }\n\n return Promise.resolve(listing);\n };\n\n const loadNext = (cursor) => {\n const continueURL = 'https://api.dropboxapi.com/2/files/list_folder/continue';\n const params = {\n body: { cursor: cursor }\n };\n\n return this._request('POST', continueURL, params).then(processResponse);\n };\n\n return this._request('POST', url, {\n body: {\n path: getDropboxPath(path)\n }\n }).then(processResponse).then(function (listing) {\n return Promise.resolve({\n statusCode: 200,\n body: listing,\n contentType: 'application/json; charset=UTF-8',\n revision: revCache.get(path)\n });\n });\n }\n\n /**\n * Checks for the path in ``_revCache`` and decides based on that if file\n * has changed. Calls ``_getFolder`` is the path points to a folder.\n *\n * Calls ``Dropbox.share`` afterwards to fill ``_itemRefs``.\n *\n * Compatible with ``WireClient.get``\n *\n * @param path {string} - path of the folder to get, with leading slash\n * @param options {Object}\n *\n * @protected\n */\n get (path, options) {\n if (! this.connected) { return Promise.reject(\"not connected (path: \" + path + \")\"); }\n const url = 'https://content.dropboxapi.com/2/files/download';\n\n const savedRev = this._revCache.get(path);\n if (savedRev === null) {\n // file was deleted server side\n return Promise.resolve({statusCode: 404});\n }\n if (options && options.ifNoneMatch) {\n // We must wait for local revision cache to be initialized before\n // checking if local revision is outdated\n if (! this._initialFetchDone) {\n return this.fetchDelta().then(() => {\n return this.get(path, options);\n });\n }\n\n if (savedRev && (savedRev === options.ifNoneMatch)) {\n // nothing changed.\n return Promise.resolve({statusCode: 304});\n }\n }\n\n // use _getFolder for folders\n if (path.substr(-1) === '/') {\n return this._getFolder(path);\n }\n\n const params = {\n headers: {\n 'Dropbox-API-Arg': JSON.stringify({path: getDropboxPath(path)}),\n },\n responseType: 'arraybuffer'\n };\n if (options && options.ifNoneMatch) {\n params.headers['If-None-Match'] = options.ifNoneMatch;\n }\n\n return this._request('GET', url, params).then(resp => {\n const status = resp.status;\n let meta, body, mime, rev;\n if (status !== 200 && status !== 409) {\n return Promise.resolve({statusCode: status});\n }\n meta = resp.getResponseHeader('Dropbox-API-Result');\n //first encode the response as text, and later check if \n //text appears to actually be binary data\n return getTextFromArrayBuffer(resp.response, 'UTF-8').then(responseText => {\n body = responseText;\n if (status === 409) {\n meta = body;\n }\n\n try {\n meta = JSON.parse(meta);\n } catch(e) {\n return Promise.reject(e);\n }\n\n if (status === 409) {\n if (compareApiError(meta, ['path', 'not_found'])) {\n return {statusCode: 404};\n }\n return Promise.reject(new Error('API error while downloading file (\"' + path + '\"): ' + meta.error_summary));\n }\n\n mime = resp.getResponseHeader('Content-Type');\n rev = meta.rev;\n this._revCache.set(path, rev);\n this._shareIfNeeded(path);\n\n if (shouldBeTreatedAsBinary(responseText, mime)) {\n // return unprocessed response\n body = resp.response;\n } else {\n // handling json (always try)\n try {\n body = JSON.parse(body);\n mime = 'application/json; charset=UTF-8';\n } catch(e) {\n //Failed parsing Json, assume it is something else then\n }\n }\n\n return {\n statusCode: status,\n body: body,\n contentType: mime,\n revision: rev\n };\n });\n });\n }\n\n /**\n * Checks for the path in ``_revCache`` and decides based on that if file\n * has changed.\n *\n * Compatible with ``WireClient``\n *\n * Calls ``Dropbox.share`` afterwards to fill ``_itemRefs``.\n *\n * @param {string} path - path of the folder to put, with leading slash\n * @param {Object} options\n * @param {string} options.ifNoneMatch - Only create of update the file if the\n * current ETag doesn't match this string\n * @returns {Promise} Resolves with an object containing the status code,\n * content-type and revision\n * @protected\n */\n put (path, body, contentType, options) {\n if (!this.connected) {\n throw new Error(\"not connected (path: \" + path + \")\");\n }\n\n // check if file has changed and return 412\n const savedRev = this._revCache.get(path);\n if (options && options.ifMatch &&\n savedRev && (savedRev !== options.ifMatch)) {\n return Promise.resolve({statusCode: 412, revision: savedRev});\n }\n if (options && (options.ifNoneMatch === '*') &&\n savedRev && (savedRev !== 'rev')) {\n return Promise.resolve({statusCode: 412, revision: savedRev});\n }\n\n if ((!contentType.match(/charset=/)) && isBinaryData(body)) {\n contentType += '; charset=binary';\n }\n\n if (body.length > 150 * 1024 * 1024) {\n //https://www.dropbox.com/developers/core/docs#chunked-upload\n return Promise.reject(new Error(\"Cannot upload file larger than 150MB\"));\n }\n\n let result;\n const needsMetadata = options && (options.ifMatch || (options.ifNoneMatch === '*'));\n const uploadParams = {\n body: body,\n contentType: contentType,\n path: path\n };\n\n if (needsMetadata) {\n result = this._getMetadata(path).then(metadata => {\n if (options && (options.ifNoneMatch === '*') && metadata) {\n // if !!metadata === true, the file exists\n return Promise.resolve({\n statusCode: 412,\n revision: metadata.rev\n });\n }\n\n if (options && options.ifMatch && metadata && (metadata.rev !== options.ifMatch)) {\n return Promise.resolve({\n statusCode: 412,\n revision: metadata.rev\n });\n }\n\n return this._uploadSimple(uploadParams);\n });\n } else {\n result = this._uploadSimple(uploadParams);\n }\n\n return result.then(res => {\n this._shareIfNeeded(path);\n return res;\n });\n }\n\n /**\n * Checks for the path in ``_revCache`` and decides based on that if file\n * has changed.\n *\n * Compatible with ``WireClient.delete``\n *\n * Calls ``Dropbox.share`` afterwards to fill ``_itemRefs``.\n *\n * @param {string} path - path of the folder to delete, with leading slash\n * @param {Object} options\n *\n * @protected\n */\n 'delete' (path, options) {\n if (!this.connected) {\n throw new Error(\"not connected (path: \" + path + \")\");\n }\n\n // check if file has changed and return 412\n const savedRev = this._revCache.get(path);\n if (options && options.ifMatch && savedRev && (options.ifMatch !== savedRev)) {\n return Promise.resolve({ statusCode: 412, revision: savedRev });\n }\n\n if (options && options.ifMatch) {\n return this._getMetadata(path).then((metadata) => {\n if (options && options.ifMatch && metadata && (metadata.rev !== options.ifMatch)) {\n return Promise.resolve({\n statusCode: 412,\n revision: metadata.rev\n });\n }\n\n return this._deleteSimple(path);\n });\n }\n\n return this._deleteSimple(path);\n }\n\n /**\n * Calls share, if the provided path resides in a public folder.\n *\n * @private\n */\n _shareIfNeeded (path) {\n if (path.match(/^\\/public\\/.*[^/]$/) && this._itemRefs[path] === undefined) {\n this.share(path);\n }\n }\n\n /**\n * Gets a publicly-accessible URL for the path from Dropbox and stores it\n * in ``_itemRefs``.\n *\n * @return {Promise} a promise for the URL\n *\n * @private\n */\n share (path) {\n const url = 'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings';\n const options = {\n body: {path: getDropboxPath(path)}\n };\n\n return this._request('POST', url, options).then((response) => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.reject(new Error('Invalid response status:' + response.status));\n }\n\n let body;\n\n try {\n body = JSON.parse(response.responseText);\n } catch (e) {\n return Promise.reject(new Error('Invalid response body: ' + response.responseText));\n }\n\n if (response.status === 409) {\n if (compareApiError(body, ['shared_link_already_exists'])) {\n return this._getSharedLink(path);\n }\n\n return Promise.reject(new Error('API error: ' + body.error_summary));\n }\n\n return Promise.resolve(body.url);\n }).then((link) => {\n this._itemRefs[path] = link;\n\n if (hasLocalStorage) {\n localStorage.setItem(SETTINGS_KEY+':shares', JSON.stringify(this._itemRefs));\n }\n\n return Promise.resolve(link);\n }, (error) => {\n error.message = 'Sharing Dropbox file or folder (\"' + path + '\") failed: ' + error.message;\n return Promise.reject(error);\n });\n }\n\n /**\n * Fetches the user's info from dropbox and returns a promise for it.\n *\n * @return {Promise} a promise for user info object (email - the user's email address)\n *\n * @protected\n */\n info () {\n const url = 'https://api.dropboxapi.com/2/users/get_current_account';\n\n return this._request('POST', url, {}).then(function (response) {\n let info = response.responseText;\n\n try {\n info = JSON.parse(info);\n } catch (e) {\n return Promise.reject(new Error('Could not query current account info: Invalid API response: ' + info));\n }\n\n return Promise.resolve({\n email: info.email\n });\n });\n }\n\n /**\n * Make a network request.\n *\n * @param {string} method - Request method\n * @param {string} url - Target URL\n * @param {object} options - Request options\n * @returns {Promise} Resolves with the response of the network request\n *\n * @private\n */\n _request (method, url, options) {\n if (!options.headers) { options.headers = {}; }\n options.headers['Authorization'] = 'Bearer ' + this.token;\n\n if (typeof options.body === 'object' && !isBinaryData(options.body)) {\n options.body = JSON.stringify(options.body);\n options.headers['Content-Type'] = 'application/json; charset=UTF-8';\n }\n\n this.rs._emit('wire-busy', {\n method: method,\n isFolder: isFolder(url)\n });\n\n return WireClient.request.call(this, method, url, options).then(xhr => {\n // 503 means retry this later\n if (xhr && xhr.status === 503) {\n if (this.online) {\n this.online = false;\n this.rs._emit('network-offline');\n }\n return setTimeout(this._request(method, url, options), 3210);\n } else {\n if (!this.online) {\n this.online = true;\n this.rs._emit('network-online');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(url),\n success: true\n });\n\n return Promise.resolve(xhr);\n }\n }, error => {\n if (this.online) {\n this.online = false;\n this.rs._emit('network-offline');\n }\n this.rs._emit('wire-done', {\n method: method,\n isFolder: isFolder(url),\n success: false\n });\n\n return Promise.reject(error);\n });\n }\n\n /**\n * Fetches the revision of all the files from dropbox API and puts them\n * into ``_revCache``. These values can then be used to determine if\n * something has changed.\n *\n * @private\n */\n fetchDelta (...args) {\n // If fetchDelta was already called, and didn't finish, return the existing\n // promise instead of calling Dropbox API again\n if (this._fetchDeltaPromise) {\n return this._fetchDeltaPromise;\n }\n\n const fetch = (cursor) => {\n let url = 'https://api.dropboxapi.com/2/files/list_folder';\n let requestBody;\n\n if (typeof cursor === 'string') {\n url += '/continue';\n requestBody = { cursor };\n } else {\n requestBody = {\n path: PATH_PREFIX,\n recursive: true,\n include_deleted: true\n };\n }\n\n return this._request('POST', url, { body: requestBody }).then(response => {\n if (response.status === 401) {\n this.rs._emit('error', new UnauthorizedError());\n return Promise.resolve(args);\n }\n\n if (response.status !== 200 && response.status !== 409) {\n return Promise.reject(new Error('Invalid response status: ' + response.status));\n }\n\n let responseBody;\n\n try {\n responseBody = JSON.parse(response.responseText);\n } catch (e) {\n return Promise.reject(new Error('Invalid response body: ' + response.responseText));\n }\n\n if (response.status === 409) {\n if (compareApiError(responseBody, ['path', 'not_found'])) {\n responseBody = {\n cursor: null,\n entries: [],\n has_more: false\n };\n } else {\n return Promise.reject(new Error('API returned an error: ' + responseBody.error_summary));\n }\n }\n\n if (!cursor) {\n //we are doing a complete fetch, so propagation would introduce unnecessary overhead\n this._revCache.deactivatePropagation();\n }\n\n responseBody.entries.forEach(entry => {\n const path = entry.path_lower.substr(PATH_PREFIX.length);\n\n if (entry['.tag'] === 'deleted') {\n // there's no way to know whether the entry was a file or a folder\n this._revCache.delete(path);\n this._revCache.delete(path + '/');\n } else if (entry['.tag'] === 'file') {\n this._revCache.set(path, entry.rev);\n }\n });\n\n this._fetchDeltaCursor = responseBody.cursor;\n if (responseBody.has_more) {\n return fetch(responseBody.cursor);\n } else {\n this._revCache.activatePropagation();\n this._initialFetchDone = true;\n }\n }).catch(error => {\n if (error === 'timeout' || error instanceof ProgressEvent) {\n // Offline is handled elsewhere already, just ignore it here\n return Promise.resolve();\n } else {\n return Promise.reject(error);\n }\n });\n };\n\n this._fetchDeltaPromise = fetch(this._fetchDeltaCursor).catch(error => {\n if (typeof(error) === 'object' && 'message' in error) {\n error.message = 'Dropbox: fetchDelta: ' + error.message;\n } else {\n error = `Dropbox: fetchDelta: ${error}`;\n }\n this._fetchDeltaPromise = null;\n return Promise.reject(error);\n }).then(() => {\n this._fetchDeltaPromise = null;\n return Promise.resolve(args);\n });\n\n return this._fetchDeltaPromise;\n }\n\n /**\n * Gets metadata for a path (can point to either a file or a folder).\n *\n * @param {string} path - the path to get metadata for\n *\n * @returns {Promise} A promise for the metadata\n *\n * @private\n */\n _getMetadata (path) {\n const url = 'https://api.dropboxapi.com/2/files/get_metadata';\n const requestBody = {\n path: getDropboxPath(path)\n };\n\n return this._request('POST', url, { body: requestBody }).then((response) => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.reject(new Error('Invalid response status:' + response.status));\n }\n\n let responseBody;\n\n try {\n responseBody = JSON.parse(response.responseText);\n } catch (e) {\n return Promise.reject(new Error('Invalid response body: ' + response.responseText));\n }\n\n if (response.status === 409) {\n if (compareApiError(responseBody, ['path', 'not_found'])) {\n return Promise.resolve();\n }\n\n return Promise.reject(new Error('API error: ' + responseBody.error_summary));\n }\n\n return Promise.resolve(responseBody);\n }).then(undefined, (error) => {\n error.message = 'Could not load metadata for file or folder (\"' + path + '\"): ' + error.message;\n return Promise.reject(error);\n });\n }\n\n /**\n * Upload a simple file (the size is no more than 150MB).\n *\n * @param {Object} params\n * @param {string} options.ifMatch - Only update the file if its ETag\n * matches this string\n * @param {string} options.path - path of the file\n * @param {string} options.body - contents of the file to upload\n * @param {string} options.contentType - mime type of the file\n *\n * @return {Promise} A promise for an object with the following structure:\n * statusCode - HTTP status code\n * revision - revision of the newly-created file, if any\n *\n * @private\n */\n _uploadSimple (params) {\n const url = 'https://content.dropboxapi.com/2/files/upload';\n const args = {\n path: getDropboxPath(params.path),\n mode: { '.tag': 'overwrite', update: undefined },\n mute: true\n };\n\n if (params.ifMatch) {\n args.mode = { '.tag': 'update', update: params.ifMatch };\n }\n\n return this._request('POST', url, {\n body: params.body,\n headers: {\n 'Content-Type': 'application/octet-stream',\n 'Dropbox-API-Arg': JSON.stringify(args)\n }\n }).then(response => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.resolve({statusCode: response.status});\n }\n\n let body = response.responseText;\n\n try {\n body = JSON.parse(body);\n } catch (e) {\n return Promise.reject(new Error('Invalid API result: ' + body));\n }\n\n if (response.status === 409) {\n if (compareApiError(body, ['path', 'conflict'])) {\n return this._getMetadata(params.path).then(function (metadata) {\n return Promise.resolve({\n statusCode: 412,\n revision: metadata.rev\n });\n });\n }\n return Promise.reject(new Error('API error: ' + body.error_summary));\n }\n\n this._revCache.set(params.path, body.rev);\n\n return Promise.resolve({ statusCode: response.status, revision: body.rev });\n });\n }\n\n /**\n * Deletes a file or a folder.\n *\n * @param {string} path - the path to delete\n *\n * @returns {Promise} A promise for an object with the following structure:\n * statusCode - HTTP status code\n *\n * @private\n */\n _deleteSimple (path) {\n const url = 'https://api.dropboxapi.com/2/files/delete';\n const requestBody = { path: getDropboxPath(path) };\n\n return this._request('POST', url, { body: requestBody }).then((response) => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.resolve({statusCode: response.status});\n }\n\n let responseBody = response.responseText;\n\n try {\n responseBody = JSON.parse(responseBody);\n } catch (e) {\n return Promise.reject(new Error('Invalid response body: ' + responseBody));\n }\n\n if (response.status === 409) {\n if (compareApiError(responseBody, ['path_lookup', 'not_found'])) {\n return Promise.resolve({statusCode: 404});\n }\n return Promise.reject(new Error('API error: ' + responseBody.error_summary));\n }\n\n return Promise.resolve({statusCode: 200});\n }).then(result => {\n if (result.statusCode === 200 || result.statusCode === 404) {\n this._revCache.delete(path);\n delete this._itemRefs[path];\n }\n return Promise.resolve(result);\n }, (error) => {\n error.message = 'Could not delete Dropbox file or folder (\"' + path + '\"): ' + error.message;\n return Promise.reject(error);\n });\n }\n\n /**\n * Requests the link for an already-shared file or folder.\n *\n * @param {string} path - path to the file or folder\n *\n * @returns {Promise} A promise for the shared link\n *\n * @private\n */\n async _getSharedLink (path: string): Promise {\n const url = 'https://api.dropbox.com/2/sharing/list_shared_links';\n const options = {\n body: {\n path: getDropboxPath(path),\n direct_only: true\n }\n };\n\n return this._request('POST', url, options).then((response) => {\n if (response.status !== 200 && response.status !== 409) {\n return Promise.reject(new Error('Invalid response status: ' + response.status));\n }\n\n let body;\n\n try {\n body = JSON.parse(response.responseText);\n } catch (e) {\n return Promise.reject(new Error('Invalid response body: ' + response.responseText));\n }\n\n if (response.status === 409) {\n return Promise.reject(new Error('API error: ' + response.error_summary));\n }\n\n if (!body.links.length) {\n return Promise.reject(new Error('No links returned'));\n }\n\n return Promise.resolve(body.links[0].url);\n }, error => {\n error.message = 'Could not get link to a shared file or folder (\"' + path + '\"): ' + error.message;\n return Promise.reject(error);\n });\n }\n\n /**\n * Initialize the Dropbox backend.\n *\n * @param {object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n static _rs_init (rs): void {\n hasLocalStorage = localStorageAvailable();\n if ( rs.apiKeys.dropbox ) {\n rs.dropbox = new Dropbox(rs);\n }\n if (rs.backend === 'dropbox') {\n hookIt(rs);\n }\n }\n\n /**\n * Inform about the availability of the Dropbox backend.\n *\n * @param {object} rs - RemoteStorage instance\n * @returns {Boolean}\n *\n * @protected\n */\n static _rs_supported (): boolean {\n return true;\n }\n\n /**\n * Remove Dropbox as a backend.\n *\n * @param {object} remoteStorage - RemoteStorage instance\n *\n * @protected\n */\n static _rs_cleanup (rs): void {\n unHookIt(rs);\n if (hasLocalStorage){\n localStorage.removeItem(SETTINGS_KEY);\n }\n rs.setBackend(undefined);\n }\n}\n\n/**\n * Hooking the sync\n *\n * TODO: document\n */\nfunction hookSync(rs, ...args) {\n if (rs._dropboxOrigSync) { return; } // already hooked\n rs._dropboxOrigSync = rs.sync.sync.bind(rs.sync);\n rs.sync.sync = function () {\n return this.dropbox.fetchDelta(rs, ...args).\n then(rs._dropboxOrigSync, function (err) {\n rs._emit('error', new SyncError(err));\n rs._emit('sync-done');\n });\n }.bind(rs);\n}\n\n/**\n * Unhooking the sync\n *\n * TODO: document\n */\nfunction unHookSync(rs) {\n if (! rs._dropboxOrigSync) { return; } // not hooked\n rs.sync.sync = rs._dropboxOrigSync;\n delete rs._dropboxOrigSync;\n}\n\n/**\n * Hook RemoteStorage.syncCycle as it's the first function called\n * after RemoteStorage.sync is initialized, so we can then hook\n * the sync function\n * @param {object} rs RemoteStorage instance\n */\nfunction hookSyncCycle(rs, ...args) {\n if (rs._dropboxOrigSyncCycle) { return; } // already hooked\n rs._dropboxOrigSyncCycle = rs.syncCycle;\n rs.syncCycle = () => {\n if (rs.sync) {\n hookSync(rs);\n rs._dropboxOrigSyncCycle(rs, ...args);\n unHookSyncCycle(rs);\n } else {\n throw new Error('expected sync to be initialized by now');\n }\n };\n}\n\n/**\n * Restore RemoteStorage's syncCycle original implementation\n * @param {object} rs RemoteStorage instance\n */\nfunction unHookSyncCycle(rs) {\n if (!rs._dropboxOrigSyncCycle) { return; } // not hooked\n rs.syncCycle = rs._dropboxOrigSyncCycle;\n delete rs._dropboxOrigSyncCycle;\n}\n\n/**\n * Overwrite BaseClient's getItemURL with our own implementation\n *\n * TODO: getItemURL still needs to be implemented\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction hookGetItemURL (rs) {\n if (rs._origBaseClientGetItemURL) { return; }\n rs._origBaseClientGetItemURL = BaseClient.prototype.getItemURL;\n BaseClient.prototype.getItemURL = function (/*path*/) {\n throw new Error('getItemURL is not implemented for Dropbox yet');\n };\n}\n\n/**\n * Restore BaseClient's getItemURL original implementation\n *\n * @param {object} rs - RemoteStorage instance\n *\n * @private\n */\nfunction unHookGetItemURL(rs){\n if (! rs._origBaseClientGetItemURL) { return; }\n BaseClient.prototype.getItemURL = rs._origBaseClientGetItemURL;\n delete rs._origBaseClientGetItemURL;\n}\n\n/**\n * TODO: document\n */\nfunction hookRemote(rs){\n if (rs._origRemote) { return; }\n rs._origRemote = rs.remote;\n rs.remote = rs.dropbox;\n}\n\n/**\n * TODO: document\n */\nfunction unHookRemote(rs){\n if (rs._origRemote) {\n rs.remote = rs._origRemote;\n delete rs._origRemote;\n }\n}\n\n/**\n * TODO: document\n */\nfunction hookIt(rs){\n hookRemote(rs);\n if (rs.sync) {\n hookSync(rs);\n } else {\n // when sync is not available yet, we hook the syncCycle function which is called\n // right after sync is initialized\n hookSyncCycle(rs);\n }\n hookGetItemURL(rs);\n}\n\n/**\n * TODO: document\n */\nfunction unHookIt(rs){\n unHookRemote(rs);\n unHookSync(rs);\n unHookGetItemURL(rs);\n unHookSyncCycle(rs);\n}\n\ninterface Dropbox extends EventHandling {};\napplyMixins(Dropbox, [EventHandling]);\n\nexport = Dropbox;\n","'use strict';\n\nimport WebFinger from 'webfinger.js';\nimport type { StorageInfo } from './interfaces/storage_info';\nimport log from './log';\nimport { globalContext, localStorageAvailable } from './util';\n\n// feature detection flags\nlet haveXMLHttpRequest, hasLocalStorage;\n\n// used to store settings in localStorage\nconst SETTINGS_KEY = 'remotestorage:discover';\n\n// cache loaded from localStorage\n// TODO use class property\nlet cachedInfo = {};\n\n/**\n * This function deals with the Webfinger lookup, discovering a connecting\n * user's storage details.\n *\n * @param {string} userAddress - user@host or URL\n *\n * @returns {Promise} A promise for an object with the following properties.\n * href - Storage base URL,\n * storageApi - RS protocol version,\n * authUrl - OAuth URL,\n * properties - Webfinger link properties\n **/\n\nconst Discover = function Discover(userAddress: string): Promise {\n return new Promise((resolve, reject) => {\n\n if (userAddress in cachedInfo) {\n return resolve(cachedInfo[userAddress]);\n }\n\n const webFinger = new WebFinger({\n tls_only: false,\n uri_fallback: true,\n request_timeout: 5000\n });\n\n return webFinger.lookup(userAddress, function (err, response) {\n if (err) {\n return reject(err);\n } else if ((typeof response.idx.links.remotestorage !== 'object') ||\n (typeof response.idx.links.remotestorage.length !== 'number') ||\n (response.idx.links.remotestorage.length <= 0)) {\n log(\"[Discover] WebFinger record for \" + userAddress + \" does not have remotestorage defined in the links section \", JSON.stringify(response.json));\n return reject(\"WebFinger record for \" + userAddress + \" does not have remotestorage defined in the links section.\");\n }\n\n const rs = response.idx.links.remotestorage[0];\n const authURL = rs.properties['http://tools.ietf.org/html/rfc6749#section-4.2'] ||\n rs.properties['auth-endpoint'];\n const storageApi = rs.properties['http://remotestorage.io/spec/version'] ||\n rs.type;\n\n // cache fetched data\n cachedInfo[userAddress] = {\n href: rs.href,\n storageApi: storageApi,\n authURL: authURL,\n properties: rs.properties\n };\n\n if (hasLocalStorage) {\n localStorage[SETTINGS_KEY] = JSON.stringify({ cache: cachedInfo });\n }\n\n return resolve(cachedInfo[userAddress]);\n });\n });\n};\n\nDiscover.DiscoveryError = function(message) {\n this.name = 'DiscoveryError';\n this.message = message;\n this.stack = (new Error()).stack;\n};\nDiscover.DiscoveryError.prototype = Object.create(Error.prototype);\nDiscover.DiscoveryError.prototype.constructor = Discover.DiscoveryError;\n\nDiscover._rs_init = function (/*remoteStorage*/): void {\n hasLocalStorage = localStorageAvailable();\n if (hasLocalStorage) {\n try {\n const settings = JSON.parse(localStorage[SETTINGS_KEY]);\n cachedInfo = settings.cache;\n } catch(e) {\n /* empty */\n }\n }\n};\n\nDiscover._rs_supported = function (): boolean {\n haveXMLHttpRequest = Object.prototype.hasOwnProperty.call(globalContext, 'XMLHttpRequest');\n return haveXMLHttpRequest;\n};\n\nDiscover._rs_cleanup = function (): void {\n if (hasLocalStorage) {\n delete localStorage[SETTINGS_KEY];\n }\n};\n\n\nexport = Discover;\n","import EventHandling from './eventhandling';\nimport { applyMixins } from './util';\n\nclass Env {\n hiddenProperty: \"hidden\" | \"mozHidden\" | \"msHidden\" | \"webkitHidden\";\n visibilityChangeEvent: \"visibilitychange\" | \"mozvisibilitychange\" | \"msvisibilitychange\" | \"webkitvisibilitychange\";\n mode: \"browser\" | \"node\";\n\n constructor() {\n this.addEvents([\"background\", \"foreground\"]);\n\n this.mode = typeof(window) !== 'undefined' ? 'browser' : 'node';\n\n if (this.mode === 'browser') {\n this.setBrowserPrefixedNames();\n document.addEventListener(this.visibilityChangeEvent, this.setVisibility.bind(this), false);\n this.setVisibility();\n }\n }\n\n setBrowserPrefixedNames (): void {\n if (this.mode !== 'browser') { return; }\n\n if (typeof document.hidden !== \"undefined\") {\n this.hiddenProperty = \"hidden\";\n this.visibilityChangeEvent = \"visibilitychange\";\n } else if (typeof document[\"mozHidden\"] !== \"undefined\") {\n this.hiddenProperty = \"mozHidden\";\n this.visibilityChangeEvent = \"mozvisibilitychange\";\n } else if (typeof document[\"msHidden\"] !== \"undefined\") {\n this.hiddenProperty = \"msHidden\";\n this.visibilityChangeEvent = \"msvisibilitychange\";\n } else if (typeof document[\"webkitHidden\"] !== \"undefined\") {\n this.hiddenProperty = \"webkitHidden\";\n this.visibilityChangeEvent = \"webkitvisibilitychange\";\n }\n }\n\n setVisibility (): void {\n if (document[this.hiddenProperty]) {\n this.goBackground();\n } else {\n this.goForeground();\n }\n }\n\n isBrowser (): boolean {\n return this.mode === \"browser\";\n }\n\n isNode (): boolean {\n return this.mode === \"node\";\n }\n\n goBackground (): void {\n this._emit(\"background\");\n }\n\n goForeground (): void {\n this._emit(\"foreground\");\n }\n\n static _rs_init (/* remoteStorage */): void {\n return;\n }\n\n static _rs_cleanup (/* remoteStorage */): void {\n return;\n }\n};\n\ninterface Env extends EventHandling {};\napplyMixins(Env, [EventHandling]);\n\nexport = Env;\n","'use strict';\n\nimport type { StorageInfo } from './interfaces/storage_info';\nimport config from './config';\nimport log from './log';\nimport {\n applyMixins,\n getGlobalContext,\n getJSONFromLocalStorage,\n extend,\n localStorageAvailable\n} from './util';\n\nimport Access from './access';\nimport Authorize from './authorize';\nimport BaseClient from './baseclient';\nimport Caching from './caching';\nimport IndexedDB from './indexeddb';\nimport InMemoryStorage from './inmemorystorage';\nimport LocalStorage from './localstorage';\nimport EventHandling from './eventhandling';\nimport GoogleDrive from './googledrive';\nimport Dropbox from './dropbox';\nimport Discover from './discover';\nimport SyncError from './sync-error';\nimport UnauthorizedError from './unauthorized-error';\nimport Features from './features';\n\n// TODO this is assigned to RemoteStorage.util later; check if still needed\nimport * as util from './util';\n\ninterface RSModule {\n name: string;\n builder: Function; // TODO detailed type\n}\n\nconst globalContext = getGlobalContext();\n// declare global {\n// interface Window { cordova: any };\n// }\n\nlet hasLocalStorage: boolean;\n\n// TODO document and/or refactor (seems weird)\nfunction emitUnauthorized(r) {\n if (r.statusCode === 403 || r.statusCode === 401) {\n this._emit('error', new UnauthorizedError());\n }\n return Promise.resolve(r);\n}\n\n/**\n* Check if interval is valid: numeric and between 2s and 1hr inclusive\n*/\nfunction isValidInterval(interval: unknown): interval is number {\n return (typeof interval === 'number' &&\n interval >= 2000 &&\n interval <= 3600000);\n}\n\n/**\n * Constructor for the remoteStorage object/instance\n *\n * This class primarily contains feature detection code and convenience API.\n *\n * Depending on which features are built in, it contains different attributes\n * and functions. See the individual features for more information.\n *\n * @param {object} config - an optional configuration object\n * @class\n */\nclass RemoteStorage {\n /**\n * Pending get/put/delete calls\n * @private\n */\n _pending: {[key: string]: any}[] = [];\n\n /**\n * TODO: document\n */\n _cleanups: [] = [];\n\n /**\n * TODO: document\n */\n _pathHandlers: { [key: string]: any } = { change: {} };\n\n /**\n * Holds OAuth app keys for Dropbox, Google Drive\n */\n apiKeys: object = {};\n\n /**\n * Holds the feature class instance, added by feature initialization\n * TODO use type Access\n */\n access: any;\n /**\n * Holds the feature class instance, added by feature initialization\n * TODO use type Sync\n */\n sync: any;\n /**\n * Holds the feature class instance, added by feature initialization\n */\n caching: Caching;\n\n // TODO use correct types, document\n _syncTimer: any;\n syncStopped: any;\n get: any;\n put: any;\n delete: any;\n\n backend: 'remotestorage' | 'dropbox' | 'googledrive';\n\n /**\n * Holds a WireClient instance, added by feature initialization\n * TODO use correct type\n */\n remote: any;\n\n /*\n * Access to the local caching backend used. Usually either a\n * or instance.\n *\n * Not available, when caching is turned off.\n */\n local: IndexedDB | LocalStorage | InMemoryStorage;\n\n dropbox: Dropbox;\n googledrive: GoogleDrive;\n\n fireInitial: Function;\n\n on: any;\n\n constructor (cfg?: object) {\n // Initial configuration property settings.\n // TODO use modern JS to merge object properties\n if (typeof cfg === 'object') { extend(config, cfg); }\n\n this.addEvents([\n 'ready', 'authing', 'connecting', 'connected', 'disconnected',\n 'not-connected', 'conflict', 'error', 'features-loaded',\n 'sync-interval-change', 'sync-req-done', 'sync-done',\n 'wire-busy', 'wire-done', 'network-offline', 'network-online'\n ]);\n\n this._setGPD({\n get: this._pendingGPD('get'),\n put: this._pendingGPD('put'),\n delete: this._pendingGPD('delete')\n });\n\n hasLocalStorage = localStorageAvailable();\n\n if (hasLocalStorage) {\n this.apiKeys = getJSONFromLocalStorage('remotestorage:api-keys') || {};\n this.setBackend(localStorage.getItem('remotestorage:backend') || 'remotestorage');\n }\n\n // Keep a reference to the orginal `on` function\n const origOn = this.on;\n\n /**\n * Register an event handler. See :ref:`rs-events` for available event names.\n *\n * @param {string} eventName - Name of the event\n * @param {function} handler - Event handler\n */\n this.on = function (eventName: string, handler: Function): void {\n if (this._allLoaded) {\n // check if the handler should be called immediately, because the\n // event has happened already\n switch(eventName) {\n case 'features-loaded':\n setTimeout(handler, 0);\n break;\n case 'ready':\n if (this.remote) {\n setTimeout(handler, 0);\n }\n break;\n case 'connected':\n if (this.remote && this.remote.connected) {\n setTimeout(handler, 0);\n }\n break;\n case 'not-connected':\n if (this.remote && !this.remote.connected) {\n setTimeout(handler, 0);\n }\n break;\n }\n }\n\n return origOn.call(this, eventName, handler);\n };\n\n // load all features and emit `ready`\n this._init();\n\n /**\n * TODO: document\n */\n this.fireInitial = function () {\n if (this.local) {\n setTimeout(this.local.fireInitial.bind(this.local), 0);\n }\n }.bind(this);\n\n this.on('ready', this.fireInitial.bind(this));\n this.loadModules();\n }\n\n /**\n * Indicating if remoteStorage is currently connected.\n */\n get connected (): boolean {\n return this.remote.connected;\n }\n\n // FIXME: Instead of doing this, would be better to only\n // export setAuthURL / getAuthURL from RemoteStorage prototype\n static Authorize = Authorize;\n\n static SyncError = SyncError;\n static Unauthorized = UnauthorizedError;\n static DiscoveryError = Discover.DiscoveryError;\n static util = util;\n\n /**\n * Load all modules passed as arguments\n * @private\n */\n loadModules(): void {\n config.modules.forEach(this.addModule.bind(this));\n }\n\n /**\n * Initiate the OAuth authorization flow.\n *\n * This function is called by custom storage backend implementations\n * (e.g. Dropbox or Google Drive).\n *\n * @param {object} options\n * @param {string} options.authURL - URL of the authorization endpoint\n * @param {string} [options.scope] - access scope\n * @param {string} [options.clientId] - client identifier (defaults to the\n * origin of the redirectUri)\n * @private\n */\n authorize (options: { authURL: string; scope?: string; clientId?: string; redirectUri?: string }): void {\n this.access.setStorageType(this.remote.storageApi);\n if (typeof options.scope === 'undefined') {\n options.scope = this.access.scopeParameter;\n }\n\n if (globalContext.cordova) {\n options.redirectUri = config.cordovaRedirectUri;\n } else {\n const location = Authorize.getLocation();\n let redirectUri = location.origin;\n if (location.pathname !== '/') {\n redirectUri += location.pathname;\n }\n\n options.redirectUri = redirectUri;\n }\n\n if (typeof options.clientId === 'undefined') {\n options.clientId = options.redirectUri.match(/^(https?:\\/\\/[^/]+)/)[0];\n }\n\n Authorize.authorize(this, options);\n }\n\n /**\n * TODO: document\n * @private\n */\n impliedauth (storageApi?: string, redirectUri?: string): void {\n // TODO shouldn't these be default argument values?\n storageApi = storageApi || this.remote.storageApi;\n redirectUri = redirectUri || String(document.location);\n\n log('ImpliedAuth proceeding due to absent authURL; storageApi = ' + storageApi + ' redirectUri = ' + redirectUri);\n // Set a fixed access token, signalling to not send it as Bearer\n this.remote.configure({\n token: Authorize.IMPLIED_FAKE_TOKEN\n });\n document.location.href = redirectUri;\n }\n\n /**\n * @property {object} remote\n *\n * Depending on the chosen backend, this is either an instance of ``WireClient``,\n * ``Dropbox`` or ``GoogleDrive``.\n *\n * @property {boolean} remote.connected - Whether or not a remote store is connected\n * @property {boolean} remote.online - Whether last sync action was successful or not\n * @property {string} remote.userAddress - The user address of the connected user\n * @property {string} remote.properties - The properties of the WebFinger link\n */\n\n /**\n * Connect to a remoteStorage server.\n *\n * Discovers the WebFinger profile of the given user address and initiates\n * the OAuth dance.\n *\n * This method must be called *after* all required access has been claimed.\n * When using the connect widget, it will call this method itself.\n *\n * Special cases:\n *\n * 1. If a bearer token is supplied as second argument, the OAuth dance\n * will be skipped and the supplied token be used instead. This is\n * useful outside of browser environments, where the token has been\n * acquired in a different way.\n *\n * 2. If the Webfinger profile for the given user address doesn't contain\n * an auth URL, the library will assume that client and server have\n * established authorization among themselves, which will omit bearer\n * tokens in all requests later on. This is useful for example when using\n * Kerberos and similar protocols.\n *\n * @param {string} userAddress - The user address (user@host) or URL to connect to.\n * @param {string} token - (optional) A bearer token acquired beforehand\n */\n connect (userAddress: string, token?: string): void {\n this.setBackend('remotestorage');\n if (userAddress.indexOf('@') < 0 && !userAddress.match(/^(https?:\\/\\/)?[^\\s\\/$\\.?#]+\\.[^\\s]*$/)) {\n this._emit('error', new RemoteStorage.DiscoveryError(\"Not a valid user address or URL.\"));\n return;\n }\n\n // Prefix URL with https:// if it's missing\n if (userAddress.indexOf('@') < 0 && !userAddress.match(/^https?:\\/\\//)) {\n userAddress = `https://${userAddress}`;\n }\n\n if (globalContext.cordova) {\n if (typeof config.cordovaRedirectUri !== 'string') {\n this._emit('error', new RemoteStorage.DiscoveryError(\"Please supply a custom HTTPS redirect URI for your Cordova app\"));\n return;\n }\n if (!globalContext.cordova.InAppBrowser) {\n this._emit('error', new RemoteStorage.DiscoveryError(\"Please include the InAppBrowser Cordova plugin to enable OAuth\"));\n return;\n }\n }\n\n this.remote.configure({\n userAddress: userAddress\n });\n this._emit('connecting');\n\n const discoveryTimeout = setTimeout((): void => {\n this._emit('error', new RemoteStorage.DiscoveryError(\"No storage information found for this user address.\"));\n }, config.discoveryTimeout);\n\n Discover(userAddress).then((info: StorageInfo): void => {\n clearTimeout(discoveryTimeout);\n this._emit('authing');\n info.userAddress = userAddress;\n this.remote.configure(info);\n if (! this.remote.connected) {\n if (info.authURL) {\n if (typeof token === 'undefined') {\n // Normal authorization step; the default way to connect\n this.authorize({ authURL: info.authURL });\n } else if (typeof token === 'string') {\n // Token supplied directly by app/developer/user\n log('Skipping authorization sequence and connecting with known token');\n this.remote.configure({ token: token });\n } else {\n throw new Error(\"Supplied bearer token must be a string\");\n }\n } else {\n // In lieu of an excplicit authURL, assume that the browser and\n // server handle any authorization needs; for instance, TLS may\n // trigger the browser to use a client certificate, or a 401 Not\n // Authorized response may make the browser send a Kerberos ticket\n // using the SPNEGO method.\n this.impliedauth();\n }\n }\n }, (/*err*/) => {\n clearTimeout(discoveryTimeout);\n this._emit('error', new RemoteStorage.DiscoveryError(\"No storage information found for this user address.\"));\n });\n }\n\n /**\n * Reconnect the remote server to get a new authorization.\n */\n reconnect (): void {\n this.remote.configure({ token: null });\n\n if (this.backend === 'remotestorage') {\n this.connect(this.remote.userAddress);\n } else {\n this.remote.connect();\n }\n }\n\n /**\n * \"Disconnect\" from remote server to terminate current session.\n *\n * This method clears all stored settings and deletes the entire local\n * cache.\n */\n disconnect (): void {\n if (this.remote) {\n this.remote.configure({\n userAddress: null,\n href: null,\n storageApi: null,\n token: null,\n properties: null\n });\n }\n this._setGPD({\n get: this._pendingGPD('get'),\n put: this._pendingGPD('put'),\n delete: this._pendingGPD('delete')\n });\n const n = this._cleanups.length;\n let i = 0;\n\n const oneDone = (): void => {\n i++;\n if (i >= n) {\n this._init();\n // FIXME Re-enable when modules are all imports\n // log('Done cleaning up, emitting disconnected and disconnect events');\n this._emit('disconnected');\n }\n };\n\n if (n > 0) {\n this._cleanups.forEach((cleanup: Function) => {\n const cleanupResult = cleanup(this);\n if (typeof(cleanupResult) === 'object' && typeof(cleanupResult.then) === 'function') {\n cleanupResult.then(oneDone);\n } else {\n oneDone();\n }\n });\n } else {\n oneDone();\n }\n }\n\n /**\n * TODO: document\n * @private\n */\n setBackend (what): void {\n this.backend = what;\n if (hasLocalStorage) {\n if (what) {\n localStorage.setItem('remotestorage:backend', what);\n } else {\n localStorage.removeItem('remotestorage:backend');\n }\n }\n }\n\n /**\n * Add a \"change\" event handler to the given path. Whenever a \"change\"\n * happens (as determined by the backend, such as e.g.\n * ) and the affected path is equal to or below the\n * given 'path', the given handler is called.\n *\n * You should usually not use this method directly, but instead use the\n * \"change\" events provided by :doc:`BaseClient `\n *\n * @param {string} path - Absolute path to attach handler to\n * @param {function} handler - Handler function\n */\n onChange (path: string, handler: Function): void {\n if (! this._pathHandlers.change[path]) {\n this._pathHandlers.change[path] = [];\n }\n this._pathHandlers.change[path].push(handler);\n }\n\n /**\n * TODO: do we still need this, now that we always instantiate the prototype?\n *\n * Enable remoteStorage logging.\n */\n enableLog (): void {\n config.logging = true;\n }\n\n /**\n * TODO: do we still need this, now that we always instantiate the prototype?\n *\n * Disable remoteStorage logging\n */\n disableLog (): void {\n config.logging = false;\n }\n\n /**\n * log\n *\n * The same as .\n */\n log (...args): void {\n log.apply(RemoteStorage, args);\n }\n\n /**\n * Set the OAuth key/ID for either GoogleDrive or Dropbox backend support.\n *\n * @param {Object} apiKeys - A config object with these properties:\n * @param {string} [apiKeys.type] - Backend type: 'googledrive' or 'dropbox'\n * @param {string} [apiKeys.key] - Client ID for GoogleDrive, or app key for Dropbox\n */\n setApiKeys (apiKeys: {[key in ApiKeyType]?: string}): void | boolean {\n const validTypes: string[] = [ApiKeyType.GOOGLE, ApiKeyType.DROPBOX];\n if (typeof apiKeys !== 'object' || !Object.keys(apiKeys).every(type => validTypes.includes(type))) {\n console.error('setApiKeys() was called with invalid arguments') ;\n return false;\n }\n\n Object.keys(apiKeys).forEach(type => {\n const key = apiKeys[type];\n if (!key) { delete this.apiKeys[type]; return; }\n\n switch(type) {\n case ApiKeyType.DROPBOX:\n this.apiKeys[ApiKeyType.DROPBOX] = { appKey: key };\n if (typeof this.dropbox === 'undefined' ||\n this.dropbox.clientId !== key) {\n Dropbox._rs_init(this);\n }\n break;\n case ApiKeyType.GOOGLE:\n this.apiKeys[ApiKeyType.GOOGLE] = { clientId: key };\n if (typeof this.googledrive === 'undefined' ||\n this.googledrive.clientId !== key) {\n GoogleDrive._rs_init(this);\n }\n break;\n }\n return true;\n });\n\n if (hasLocalStorage) {\n localStorage.setItem('remotestorage:api-keys', JSON.stringify(this.apiKeys));\n }\n\n }\n\n /**\n * Set redirect URI to be used for the OAuth redirect within the\n * in-app-browser window in Cordova apps.\n *\n * @param uri - A valid HTTP(S) URI\n */\n setCordovaRedirectUri (uri: string): void {\n if (typeof uri !== 'string' || !uri.match(/http(s)?:\\/\\//)) {\n throw new Error(\"Cordova redirect URI must be a URI string\");\n }\n config.cordovaRedirectUri = uri;\n }\n\n //\n // FEATURES INITIALIZATION\n //\n\n _init = Features.loadFeatures;\n features = Features.features;\n loadFeature = Features.loadFeature;\n featureSupported = Features.featureSupported;\n featureDone = Features.featureDone;\n featuresDone = Features.featuresDone;\n featuresLoaded = Features.featuresLoaded;\n featureInitialized = Features.featureInitialized;\n featureFailed = Features.featureFailed;\n hasFeature = Features.hasFeature;\n _setCachingModule = Features._setCachingModule;\n _collectCleanupFunctions = Features._collectCleanupFunctions;\n _fireReady = Features._fireReady;\n initFeature = Features.initFeature;\n\n //\n // GET/PUT/DELETE INTERFACE HELPERS\n //\n\n /**\n * TODO: document\n * @private\n */\n _setGPD (impl, context?) {\n function wrap(func) {\n return function (...args) {\n return func.apply(context, args)\n .then(emitUnauthorized.bind(this));\n };\n }\n this.get = wrap(impl.get);\n this.put = wrap(impl.put);\n this.delete = wrap(impl.delete);\n }\n\n /**\n * TODO: document\n * @private\n */\n _pendingGPD (methodName): Function {\n return (...args) => {\n const methodArguments = Array.prototype.slice.call(args);\n return new Promise((resolve, reject) => {\n this._pending.push({\n method: methodName,\n args: methodArguments,\n promise: {\n resolve: resolve,\n reject: reject\n }\n });\n });\n };\n }\n\n /**\n * TODO: document\n * @private\n */\n _processPending (): void {\n this._pending.forEach((pending) => {\n try {\n this[pending.method](...pending.args).then(pending.promise.resolve, pending.promise.reject);\n } catch(e) {\n pending.promise.reject(e);\n }\n });\n this._pending = [];\n }\n\n //\n // CHANGE EVENT HANDLING\n //\n\n /**\n * TODO: document\n * @private\n */\n _bindChange (object: { on: Function }): void {\n object.on('change', this._dispatchEvent.bind(this, 'change'));\n }\n\n /**\n * TODO: document\n * @private\n */\n _dispatchEvent (eventName: string, event): void {\n Object.keys(this._pathHandlers[eventName]).forEach((path: string) => {\n const pl = path.length;\n if (event.path.substr(0, pl) === path) {\n this._pathHandlers[eventName][path].forEach((handler: Function) => {\n const ev: { relativePath?: string } = {};\n for (const key in event) { ev[key] = event[key]; }\n ev.relativePath = event.path.replace(new RegExp('^' + path), '');\n try {\n handler(ev);\n } catch(e) {\n console.error(\"'change' handler failed: \", e, e.stack);\n this._emit('error', e);\n }\n });\n }\n });\n }\n\n /**\n * This method enables you to quickly instantiate a BaseClient, which you can\n * use to directly read and manipulate data in the connected storage account.\n *\n * Please use this method only for debugging and development, and choose or\n * create a :doc:`data module ` for your app to use.\n *\n * @param path - The base directory of the BaseClient that will be returned\n * (with a leading and a trailing slash)\n *\n * @returns A client with the specified scope (category/base directory)\n */\n scope (path: string): BaseClient {\n if (typeof(path) !== 'string') {\n throw 'Argument \\'path\\' of baseClient.scope must be a string';\n }\n if (!this.access.checkPathPermission(path, 'r')) {\n console.warn('WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestoragejs.readthedocs.io/en/latest/js-api/access.html#claim');\n }\n return new BaseClient(this, path);\n }\n\n /**\n * Get the value of the sync interval when application is in the foreground\n *\n * @returns {number} A number of milliseconds\n */\n getSyncInterval (): number {\n return config.syncInterval;\n }\n\n /**\n * Set the value of the sync interval when application is in the foreground\n *\n * @param interval - Sync interval in milliseconds (between 2000 and 3600000 [1 hour])\n */\n setSyncInterval (interval: number): void {\n if (!isValidInterval(interval)) {\n throw interval + \" is not a valid sync interval\";\n }\n const oldValue = config.syncInterval;\n config.syncInterval = interval;\n this._emit('sync-interval-change', {oldValue: oldValue, newValue: interval});\n }\n\n /**\n * Get the value of the sync interval when application is in the background\n *\n * @returns A number of milliseconds\n */\n getBackgroundSyncInterval (): number {\n return config.backgroundSyncInterval;\n }\n\n /**\n * Set the value of the sync interval when the application is in the\n * background\n *\n * @param interval - Sync interval in milliseconds (between 2000 and 3600000 [1 hour])\n */\n setBackgroundSyncInterval (interval: number): void {\n if (!isValidInterval(interval)) {\n throw interval + \" is not a valid sync interval\";\n }\n const oldValue = config.backgroundSyncInterval;\n config.backgroundSyncInterval = interval;\n this._emit('sync-interval-change', {oldValue: oldValue, newValue: interval});\n }\n\n /**\n * Get the value of the current sync interval. Can be background or\n * foreground, custom or default.\n *\n * @returns {number} A number of milliseconds\n */\n getCurrentSyncInterval (): number {\n return config.isBackground ? config.backgroundSyncInterval : config.syncInterval;\n }\n\n /**\n * Get the value of the current network request timeout\n *\n * @returns {number} A number of milliseconds\n */\n getRequestTimeout (): number {\n return config.requestTimeout;\n }\n\n /**\n * Set the timeout for network requests.\n *\n * @param timeout - Timeout in milliseconds\n */\n setRequestTimeout (timeout: number): void {\n if (typeof timeout !== 'number') {\n throw timeout + \" is not a valid request timeout\";\n }\n config.requestTimeout = timeout;\n }\n\n /**\n * TODO: document\n * @private\n */\n syncCycle (): void {\n if (!this.sync || this.sync.stopped) { return; }\n\n this.on('sync-done', (): void => {\n // FIXME Re-enable when modules are all imports\n // log('[Sync] Sync done. Setting timer to', this.getCurrentSyncInterval());\n if (this.sync && !this.sync.stopped) {\n if (this._syncTimer) {\n clearTimeout(this._syncTimer);\n this._syncTimer = undefined;\n }\n this._syncTimer = setTimeout(this.sync.sync.bind(this.sync), this.getCurrentSyncInterval());\n }\n });\n\n this.sync.sync();\n }\n\n /**\n * Start synchronization with remote storage, downloading and uploading any\n * changes within the cached paths.\n *\n * Please consider: local changes will attempt sync immediately, and remote\n * changes should also be synced timely when using library defaults. So\n * this is mostly useful for letting users sync manually, when pressing a\n * sync button for example. This might feel safer to them sometimes, esp.\n * when shifting between offline and online a lot.\n *\n * @returns {Promise} A Promise which resolves when the sync has finished\n */\n startSync (): Promise {\n if (!config.cache) {\n console.warn('Nothing to sync, because caching is disabled.');\n return Promise.resolve();\n }\n this.sync.stopped = false;\n this.syncStopped = false;\n return this.sync.sync();\n }\n\n /**\n * Stop the periodic synchronization.\n */\n stopSync (): void {\n clearTimeout(this._syncTimer);\n this._syncTimer = undefined;\n\n if (this.sync) {\n // FIXME Re-enable when modules are all imports\n // log('[Sync] Stopping sync');\n this.sync.stopped = true;\n } else {\n // The sync class has not been initialized yet, so we make sure it will\n // not start the syncing process as soon as it's initialized.\n // FIXME Re-enable when modules are all imports\n // log('[Sync] Will instantiate sync stopped');\n this.syncStopped = true;\n }\n }\n\n /*\n * Add remoteStorage data module\n *\n * @param {Object} module - module object needs following properies:\n * @param {string} [module.name] - Name of the module\n * @param {function} [module.builder] - Builder function defining the module\n *\n * The module builder function should return an object containing another\n * object called exports, which will be exported to this \n * instance under the module's name. So when defining a locations module,\n * like in the example below, it would be accessible via\n * `remoteStorage.locations`, which would in turn have a `features` and a\n * `collections` property.\n *\n * The function receives a private and a public client, which are both\n * instances of . In the following example, the\n * scope of privateClient is `/locations` and the scope of publicClient is\n * `/public/locations`.\n *\n * @example\n * RemoteStorage.addModule({name: 'locations', builder: function (privateClient, publicClient) {\n * return {\n * exports: {\n * features: privateClient.scope('features/').defaultType('feature'),\n * collections: privateClient.scope('collections/').defaultType('feature-collection')\n * }\n * };\n * }});\n */\n addModule (module: RSModule): void {\n const moduleName = module.name;\n const moduleBuilder = module.builder;\n\n Object.defineProperty(this, moduleName, {\n configurable: true,\n get: function () {\n const instance = this._loadModule(moduleName, moduleBuilder);\n Object.defineProperty(this, moduleName, {\n value: instance\n });\n return instance;\n }\n });\n\n if (moduleName.indexOf('-') !== -1) {\n const camelizedName = moduleName.replace(/\\-[a-z]/g, function (s) {\n return s[1].toUpperCase();\n });\n\n Object.defineProperty(this, camelizedName, {\n get: function () {\n return this[moduleName];\n }\n });\n }\n }\n\n /**\n * Load module\n * @private\n */\n _loadModule (moduleName: string, moduleBuilder: Function): { [key: string]: unknown } {\n if (moduleBuilder) {\n const module = moduleBuilder(\n new BaseClient(this, '/' + moduleName + '/'),\n new BaseClient(this, '/public/' + moduleName + '/')\n );\n return module.exports;\n } else {\n throw \"Unknown module: \" + moduleName;\n }\n }\n}\n\n/**\n * @property access\n *\n * Tracking claimed access scopes. A instance.\n*/\nObject.defineProperty(RemoteStorage.prototype, 'access', {\n get: function() {\n const access = new Access();\n Object.defineProperty(this, 'access', {\n value: access\n });\n return access;\n },\n configurable: true\n});\n\n// TODO Clean up/harmonize how modules are loaded and/or document this architecture properly\n//\n// At this point the remoteStorage object has not been created yet.\n// Only its prototype exists so far, so we define a self-constructing\n// property on there:\n\n/**\n * Property: caching\n *\n * Caching settings. A instance.\n */\n// FIXME Was in rs_init of Caching but don't want to require RemoteStorage from there.\nObject.defineProperty(RemoteStorage.prototype, 'caching', {\n configurable: true,\n get: function () {\n const caching = new Caching();\n Object.defineProperty(this, 'caching', {\n value: caching\n });\n return caching;\n }\n});\n\ninterface RemoteStorage extends EventHandling {};\napplyMixins(RemoteStorage, [EventHandling]);\n\nenum ApiKeyType {\n GOOGLE = 'googledrive',\n DROPBOX = 'dropbox'\n}\n\nexport = RemoteStorage;\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","/*\r\nAuthor: Geraint Luff and others\r\nYear: 2013\r\n\r\nThis code is released into the \"public domain\" by its author(s). Anybody may use, alter and distribute the code without restriction. The author makes no guarantees, and takes no liability of any kind for use of this code.\r\n\r\nIf you find a bug or make an improvement, it would be courteous to let the author know, but it is not compulsory.\r\n*/\r\n(function (global, factory) {\r\n if (typeof define === 'function' && define.amd) {\r\n // AMD. Register as an anonymous module.\r\n define([], factory);\r\n } else if (typeof module !== 'undefined' && module.exports){\r\n // CommonJS. Define export.\r\n module.exports = factory();\r\n } else {\r\n // Browser globals\r\n global.tv4 = factory();\r\n }\r\n}(this, function () {\r\n\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FObject%2Fkeys\r\nif (!Object.keys) {\r\n\tObject.keys = (function () {\r\n\t\tvar hasOwnProperty = Object.prototype.hasOwnProperty,\r\n\t\t\thasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),\r\n\t\t\tdontEnums = [\r\n\t\t\t\t'toString',\r\n\t\t\t\t'toLocaleString',\r\n\t\t\t\t'valueOf',\r\n\t\t\t\t'hasOwnProperty',\r\n\t\t\t\t'isPrototypeOf',\r\n\t\t\t\t'propertyIsEnumerable',\r\n\t\t\t\t'constructor'\r\n\t\t\t],\r\n\t\t\tdontEnumsLength = dontEnums.length;\r\n\r\n\t\treturn function (obj) {\r\n\t\t\tif (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {\r\n\t\t\t\tthrow new TypeError('Object.keys called on non-object');\r\n\t\t\t}\r\n\r\n\t\t\tvar result = [];\r\n\r\n\t\t\tfor (var prop in obj) {\r\n\t\t\t\tif (hasOwnProperty.call(obj, prop)) {\r\n\t\t\t\t\tresult.push(prop);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (hasDontEnumBug) {\r\n\t\t\t\tfor (var i=0; i < dontEnumsLength; i++) {\r\n\t\t\t\t\tif (hasOwnProperty.call(obj, dontEnums[i])) {\r\n\t\t\t\t\t\tresult.push(dontEnums[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn result;\r\n\t\t};\r\n\t})();\r\n}\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create\r\nif (!Object.create) {\r\n\tObject.create = (function(){\r\n\t\tfunction F(){}\r\n\r\n\t\treturn function(o){\r\n\t\t\tif (arguments.length !== 1) {\r\n\t\t\t\tthrow new Error('Object.create implementation only accepts one parameter.');\r\n\t\t\t}\r\n\t\t\tF.prototype = o;\r\n\t\t\treturn new F();\r\n\t\t};\r\n\t})();\r\n}\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FisArray\r\nif(!Array.isArray) {\r\n\tArray.isArray = function (vArg) {\r\n\t\treturn Object.prototype.toString.call(vArg) === \"[object Array]\";\r\n\t};\r\n}\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FindexOf\r\nif (!Array.prototype.indexOf) {\r\n\tArray.prototype.indexOf = function (searchElement /*, fromIndex */ ) {\r\n\t\tif (this === null) {\r\n\t\t\tthrow new TypeError();\r\n\t\t}\r\n\t\tvar t = Object(this);\r\n\t\tvar len = t.length >>> 0;\r\n\r\n\t\tif (len === 0) {\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\tvar n = 0;\r\n\t\tif (arguments.length > 1) {\r\n\t\t\tn = Number(arguments[1]);\r\n\t\t\tif (n !== n) { // shortcut for verifying if it's NaN\r\n\t\t\t\tn = 0;\r\n\t\t\t} else if (n !== 0 && n !== Infinity && n !== -Infinity) {\r\n\t\t\t\tn = (n > 0 || -1) * Math.floor(Math.abs(n));\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (n >= len) {\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\tvar k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);\r\n\t\tfor (; k < len; k++) {\r\n\t\t\tif (k in t && t[k] === searchElement) {\r\n\t\t\t\treturn k;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn -1;\r\n\t};\r\n}\r\n\r\n// Grungey Object.isFrozen hack\r\nif (!Object.isFrozen) {\r\n\tObject.isFrozen = function (obj) {\r\n\t\tvar key = \"tv4_test_frozen_key\";\r\n\t\twhile (obj.hasOwnProperty(key)) {\r\n\t\t\tkey += Math.random();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tobj[key] = true;\r\n\t\t\tdelete obj[key];\r\n\t\t\treturn false;\r\n\t\t} catch (e) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n}\r\n// Based on: https://github.com/geraintluff/uri-templates, but with all the de-substitution stuff removed\r\n\r\nvar uriTemplateGlobalModifiers = {\r\n\t\"+\": true,\r\n\t\"#\": true,\r\n\t\".\": true,\r\n\t\"/\": true,\r\n\t\";\": true,\r\n\t\"?\": true,\r\n\t\"&\": true\r\n};\r\nvar uriTemplateSuffices = {\r\n\t\"*\": true\r\n};\r\n\r\nfunction notReallyPercentEncode(string) {\r\n\treturn encodeURI(string).replace(/%25[0-9][0-9]/g, function (doubleEncoded) {\r\n\t\treturn \"%\" + doubleEncoded.substring(3);\r\n\t});\r\n}\r\n\r\nfunction uriTemplateSubstitution(spec) {\r\n\tvar modifier = \"\";\r\n\tif (uriTemplateGlobalModifiers[spec.charAt(0)]) {\r\n\t\tmodifier = spec.charAt(0);\r\n\t\tspec = spec.substring(1);\r\n\t}\r\n\tvar separator = \"\";\r\n\tvar prefix = \"\";\r\n\tvar shouldEscape = true;\r\n\tvar showVariables = false;\r\n\tvar trimEmptyString = false;\r\n\tif (modifier === '+') {\r\n\t\tshouldEscape = false;\r\n\t} else if (modifier === \".\") {\r\n\t\tprefix = \".\";\r\n\t\tseparator = \".\";\r\n\t} else if (modifier === \"/\") {\r\n\t\tprefix = \"/\";\r\n\t\tseparator = \"/\";\r\n\t} else if (modifier === '#') {\r\n\t\tprefix = \"#\";\r\n\t\tshouldEscape = false;\r\n\t} else if (modifier === ';') {\r\n\t\tprefix = \";\";\r\n\t\tseparator = \";\";\r\n\t\tshowVariables = true;\r\n\t\ttrimEmptyString = true;\r\n\t} else if (modifier === '?') {\r\n\t\tprefix = \"?\";\r\n\t\tseparator = \"&\";\r\n\t\tshowVariables = true;\r\n\t} else if (modifier === '&') {\r\n\t\tprefix = \"&\";\r\n\t\tseparator = \"&\";\r\n\t\tshowVariables = true;\r\n\t}\r\n\r\n\tvar varNames = [];\r\n\tvar varList = spec.split(\",\");\r\n\tvar varSpecs = [];\r\n\tvar varSpecMap = {};\r\n\tfor (var i = 0; i < varList.length; i++) {\r\n\t\tvar varName = varList[i];\r\n\t\tvar truncate = null;\r\n\t\tif (varName.indexOf(\":\") !== -1) {\r\n\t\t\tvar parts = varName.split(\":\");\r\n\t\t\tvarName = parts[0];\r\n\t\t\ttruncate = parseInt(parts[1], 10);\r\n\t\t}\r\n\t\tvar suffices = {};\r\n\t\twhile (uriTemplateSuffices[varName.charAt(varName.length - 1)]) {\r\n\t\t\tsuffices[varName.charAt(varName.length - 1)] = true;\r\n\t\t\tvarName = varName.substring(0, varName.length - 1);\r\n\t\t}\r\n\t\tvar varSpec = {\r\n\t\t\ttruncate: truncate,\r\n\t\t\tname: varName,\r\n\t\t\tsuffices: suffices\r\n\t\t};\r\n\t\tvarSpecs.push(varSpec);\r\n\t\tvarSpecMap[varName] = varSpec;\r\n\t\tvarNames.push(varName);\r\n\t}\r\n\tvar subFunction = function (valueFunction) {\r\n\t\tvar result = \"\";\r\n\t\tvar startIndex = 0;\r\n\t\tfor (var i = 0; i < varSpecs.length; i++) {\r\n\t\t\tvar varSpec = varSpecs[i];\r\n\t\t\tvar value = valueFunction(varSpec.name);\r\n\t\t\tif (value === null || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof value === 'object' && Object.keys(value).length === 0)) {\r\n\t\t\t\tstartIndex++;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif (i === startIndex) {\r\n\t\t\t\tresult += prefix;\r\n\t\t\t} else {\r\n\t\t\t\tresult += (separator || \",\");\r\n\t\t\t}\r\n\t\t\tif (Array.isArray(value)) {\r\n\t\t\t\tif (showVariables) {\r\n\t\t\t\t\tresult += varSpec.name + \"=\";\r\n\t\t\t\t}\r\n\t\t\t\tfor (var j = 0; j < value.length; j++) {\r\n\t\t\t\t\tif (j > 0) {\r\n\t\t\t\t\t\tresult += varSpec.suffices['*'] ? (separator || \",\") : \",\";\r\n\t\t\t\t\t\tif (varSpec.suffices['*'] && showVariables) {\r\n\t\t\t\t\t\t\tresult += varSpec.name + \"=\";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(value[j]).replace(/!/g, \"%21\") : notReallyPercentEncode(value[j]);\r\n\t\t\t\t}\r\n\t\t\t} else if (typeof value === \"object\") {\r\n\t\t\t\tif (showVariables && !varSpec.suffices['*']) {\r\n\t\t\t\t\tresult += varSpec.name + \"=\";\r\n\t\t\t\t}\r\n\t\t\t\tvar first = true;\r\n\t\t\t\tfor (var key in value) {\r\n\t\t\t\t\tif (!first) {\r\n\t\t\t\t\t\tresult += varSpec.suffices['*'] ? (separator || \",\") : \",\";\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfirst = false;\r\n\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(key).replace(/!/g, \"%21\") : notReallyPercentEncode(key);\r\n\t\t\t\t\tresult += varSpec.suffices['*'] ? '=' : \",\";\r\n\t\t\t\t\tresult += shouldEscape ? encodeURIComponent(value[key]).replace(/!/g, \"%21\") : notReallyPercentEncode(value[key]);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (showVariables) {\r\n\t\t\t\t\tresult += varSpec.name;\r\n\t\t\t\t\tif (!trimEmptyString || value !== \"\") {\r\n\t\t\t\t\t\tresult += \"=\";\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (varSpec.truncate != null) {\r\n\t\t\t\t\tvalue = value.substring(0, varSpec.truncate);\r\n\t\t\t\t}\r\n\t\t\t\tresult += shouldEscape ? encodeURIComponent(value).replace(/!/g, \"%21\"): notReallyPercentEncode(value);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t};\r\n\tsubFunction.varNames = varNames;\r\n\treturn {\r\n\t\tprefix: prefix,\r\n\t\tsubstitution: subFunction\r\n\t};\r\n}\r\n\r\nfunction UriTemplate(template) {\r\n\tif (!(this instanceof UriTemplate)) {\r\n\t\treturn new UriTemplate(template);\r\n\t}\r\n\tvar parts = template.split(\"{\");\r\n\tvar textParts = [parts.shift()];\r\n\tvar prefixes = [];\r\n\tvar substitutions = [];\r\n\tvar varNames = [];\r\n\twhile (parts.length > 0) {\r\n\t\tvar part = parts.shift();\r\n\t\tvar spec = part.split(\"}\")[0];\r\n\t\tvar remainder = part.substring(spec.length + 1);\r\n\t\tvar funcs = uriTemplateSubstitution(spec);\r\n\t\tsubstitutions.push(funcs.substitution);\r\n\t\tprefixes.push(funcs.prefix);\r\n\t\ttextParts.push(remainder);\r\n\t\tvarNames = varNames.concat(funcs.substitution.varNames);\r\n\t}\r\n\tthis.fill = function (valueFunction) {\r\n\t\tvar result = textParts[0];\r\n\t\tfor (var i = 0; i < substitutions.length; i++) {\r\n\t\t\tvar substitution = substitutions[i];\r\n\t\t\tresult += substitution(valueFunction);\r\n\t\t\tresult += textParts[i + 1];\r\n\t\t}\r\n\t\treturn result;\r\n\t};\r\n\tthis.varNames = varNames;\r\n\tthis.template = template;\r\n}\r\nUriTemplate.prototype = {\r\n\ttoString: function () {\r\n\t\treturn this.template;\r\n\t},\r\n\tfillFromObject: function (obj) {\r\n\t\treturn this.fill(function (varName) {\r\n\t\t\treturn obj[varName];\r\n\t\t});\r\n\t}\r\n};\r\nvar ValidatorContext = function ValidatorContext(parent, collectMultiple, errorReporter, checkRecursive, trackUnknownProperties) {\r\n\tthis.missing = [];\r\n\tthis.missingMap = {};\r\n\tthis.formatValidators = parent ? Object.create(parent.formatValidators) : {};\r\n\tthis.schemas = parent ? Object.create(parent.schemas) : {};\r\n\tthis.collectMultiple = collectMultiple;\r\n\tthis.errors = [];\r\n\tthis.handleError = collectMultiple ? this.collectError : this.returnError;\r\n\tif (checkRecursive) {\r\n\t\tthis.checkRecursive = true;\r\n\t\tthis.scanned = [];\r\n\t\tthis.scannedFrozen = [];\r\n\t\tthis.scannedFrozenSchemas = [];\r\n\t\tthis.scannedFrozenValidationErrors = [];\r\n\t\tthis.validatedSchemasKey = 'tv4_validation_id';\r\n\t\tthis.validationErrorsKey = 'tv4_validation_errors_id';\r\n\t}\r\n\tif (trackUnknownProperties) {\r\n\t\tthis.trackUnknownProperties = true;\r\n\t\tthis.knownPropertyPaths = {};\r\n\t\tthis.unknownPropertyPaths = {};\r\n\t}\r\n\tthis.errorReporter = errorReporter || defaultErrorReporter('en');\r\n\tif (typeof this.errorReporter === 'string') {\r\n\t\tthrow new Error('debug');\r\n\t}\r\n\tthis.definedKeywords = {};\r\n\tif (parent) {\r\n\t\tfor (var key in parent.definedKeywords) {\r\n\t\t\tthis.definedKeywords[key] = parent.definedKeywords[key].slice(0);\r\n\t\t}\r\n\t}\r\n};\r\nValidatorContext.prototype.defineKeyword = function (keyword, keywordFunction) {\r\n\tthis.definedKeywords[keyword] = this.definedKeywords[keyword] || [];\r\n\tthis.definedKeywords[keyword].push(keywordFunction);\r\n};\r\nValidatorContext.prototype.createError = function (code, messageParams, dataPath, schemaPath, subErrors, data, schema) {\r\n\tvar error = new ValidationError(code, messageParams, dataPath, schemaPath, subErrors);\r\n\terror.message = this.errorReporter(error, data, schema);\r\n\treturn error;\r\n};\r\nValidatorContext.prototype.returnError = function (error) {\r\n\treturn error;\r\n};\r\nValidatorContext.prototype.collectError = function (error) {\r\n\tif (error) {\r\n\t\tthis.errors.push(error);\r\n\t}\r\n\treturn null;\r\n};\r\nValidatorContext.prototype.prefixErrors = function (startIndex, dataPath, schemaPath) {\r\n\tfor (var i = startIndex; i < this.errors.length; i++) {\r\n\t\tthis.errors[i] = this.errors[i].prefixWith(dataPath, schemaPath);\r\n\t}\r\n\treturn this;\r\n};\r\nValidatorContext.prototype.banUnknownProperties = function (data, schema) {\r\n\tfor (var unknownPath in this.unknownPropertyPaths) {\r\n\t\tvar error = this.createError(ErrorCodes.UNKNOWN_PROPERTY, {path: unknownPath}, unknownPath, \"\", null, data, schema);\r\n\t\tvar result = this.handleError(error);\r\n\t\tif (result) {\r\n\t\t\treturn result;\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.addFormat = function (format, validator) {\r\n\tif (typeof format === 'object') {\r\n\t\tfor (var key in format) {\r\n\t\t\tthis.addFormat(key, format[key]);\r\n\t\t}\r\n\t\treturn this;\r\n\t}\r\n\tthis.formatValidators[format] = validator;\r\n};\r\nValidatorContext.prototype.resolveRefs = function (schema, urlHistory) {\r\n\tif (schema['$ref'] !== undefined) {\r\n\t\turlHistory = urlHistory || {};\r\n\t\tif (urlHistory[schema['$ref']]) {\r\n\t\t\treturn this.createError(ErrorCodes.CIRCULAR_REFERENCE, {urls: Object.keys(urlHistory).join(', ')}, '', '', null, undefined, schema);\r\n\t\t}\r\n\t\turlHistory[schema['$ref']] = true;\r\n\t\tschema = this.getSchema(schema['$ref'], urlHistory);\r\n\t}\r\n\treturn schema;\r\n};\r\nValidatorContext.prototype.getSchema = function (url, urlHistory) {\r\n\tvar schema;\r\n\tif (this.schemas[url] !== undefined) {\r\n\t\tschema = this.schemas[url];\r\n\t\treturn this.resolveRefs(schema, urlHistory);\r\n\t}\r\n\tvar baseUrl = url;\r\n\tvar fragment = \"\";\r\n\tif (url.indexOf('#') !== -1) {\r\n\t\tfragment = url.substring(url.indexOf(\"#\") + 1);\r\n\t\tbaseUrl = url.substring(0, url.indexOf(\"#\"));\r\n\t}\r\n\tif (typeof this.schemas[baseUrl] === 'object') {\r\n\t\tschema = this.schemas[baseUrl];\r\n\t\tvar pointerPath = decodeURIComponent(fragment);\r\n\t\tif (pointerPath === \"\") {\r\n\t\t\treturn this.resolveRefs(schema, urlHistory);\r\n\t\t} else if (pointerPath.charAt(0) !== \"/\") {\r\n\t\t\treturn undefined;\r\n\t\t}\r\n\t\tvar parts = pointerPath.split(\"/\").slice(1);\r\n\t\tfor (var i = 0; i < parts.length; i++) {\r\n\t\t\tvar component = parts[i].replace(/~1/g, \"/\").replace(/~0/g, \"~\");\r\n\t\t\tif (schema[component] === undefined) {\r\n\t\t\t\tschema = undefined;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tschema = schema[component];\r\n\t\t}\r\n\t\tif (schema !== undefined) {\r\n\t\t\treturn this.resolveRefs(schema, urlHistory);\r\n\t\t}\r\n\t}\r\n\tif (this.missing[baseUrl] === undefined) {\r\n\t\tthis.missing.push(baseUrl);\r\n\t\tthis.missing[baseUrl] = baseUrl;\r\n\t\tthis.missingMap[baseUrl] = baseUrl;\r\n\t}\r\n};\r\nValidatorContext.prototype.searchSchemas = function (schema, url) {\r\n\tif (Array.isArray(schema)) {\r\n\t\tfor (var i = 0; i < schema.length; i++) {\r\n\t\t\tthis.searchSchemas(schema[i], url);\r\n\t\t}\r\n\t} else if (schema && typeof schema === \"object\") {\r\n\t\tif (typeof schema.id === \"string\") {\r\n\t\t\tif (isTrustedUrl(url, schema.id)) {\r\n\t\t\t\tif (this.schemas[schema.id] === undefined) {\r\n\t\t\t\t\tthis.schemas[schema.id] = schema;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (var key in schema) {\r\n\t\t\tif (key !== \"enum\") {\r\n\t\t\t\tif (typeof schema[key] === \"object\") {\r\n\t\t\t\t\tthis.searchSchemas(schema[key], url);\r\n\t\t\t\t} else if (key === \"$ref\") {\r\n\t\t\t\t\tvar uri = getDocumentUri(schema[key]);\r\n\t\t\t\t\tif (uri && this.schemas[uri] === undefined && this.missingMap[uri] === undefined) {\r\n\t\t\t\t\t\tthis.missingMap[uri] = uri;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\nValidatorContext.prototype.addSchema = function (url, schema) {\r\n\t//overload\r\n\tif (typeof url !== 'string' || typeof schema === 'undefined') {\r\n\t\tif (typeof url === 'object' && typeof url.id === 'string') {\r\n\t\t\tschema = url;\r\n\t\t\turl = schema.id;\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\tif (url === getDocumentUri(url) + \"#\") {\r\n\t\t// Remove empty fragment\r\n\t\turl = getDocumentUri(url);\r\n\t}\r\n\tthis.schemas[url] = schema;\r\n\tdelete this.missingMap[url];\r\n\tnormSchema(schema, url);\r\n\tthis.searchSchemas(schema, url);\r\n};\r\n\r\nValidatorContext.prototype.getSchemaMap = function () {\r\n\tvar map = {};\r\n\tfor (var key in this.schemas) {\r\n\t\tmap[key] = this.schemas[key];\r\n\t}\r\n\treturn map;\r\n};\r\n\r\nValidatorContext.prototype.getSchemaUris = function (filterRegExp) {\r\n\tvar list = [];\r\n\tfor (var key in this.schemas) {\r\n\t\tif (!filterRegExp || filterRegExp.test(key)) {\r\n\t\t\tlist.push(key);\r\n\t\t}\r\n\t}\r\n\treturn list;\r\n};\r\n\r\nValidatorContext.prototype.getMissingUris = function (filterRegExp) {\r\n\tvar list = [];\r\n\tfor (var key in this.missingMap) {\r\n\t\tif (!filterRegExp || filterRegExp.test(key)) {\r\n\t\t\tlist.push(key);\r\n\t\t}\r\n\t}\r\n\treturn list;\r\n};\r\n\r\nValidatorContext.prototype.dropSchemas = function () {\r\n\tthis.schemas = {};\r\n\tthis.reset();\r\n};\r\nValidatorContext.prototype.reset = function () {\r\n\tthis.missing = [];\r\n\tthis.missingMap = {};\r\n\tthis.errors = [];\r\n};\r\n\r\nValidatorContext.prototype.validateAll = function (data, schema, dataPathParts, schemaPathParts, dataPointerPath) {\r\n\tvar topLevel;\r\n\tschema = this.resolveRefs(schema);\r\n\tif (!schema) {\r\n\t\treturn null;\r\n\t} else if (schema instanceof ValidationError) {\r\n\t\tthis.errors.push(schema);\r\n\t\treturn schema;\r\n\t}\r\n\r\n\tvar startErrorCount = this.errors.length;\r\n\tvar frozenIndex, scannedFrozenSchemaIndex = null, scannedSchemasIndex = null;\r\n\tif (this.checkRecursive && data && typeof data === 'object') {\r\n\t\ttopLevel = !this.scanned.length;\r\n\t\tif (data[this.validatedSchemasKey]) {\r\n\t\t\tvar schemaIndex = data[this.validatedSchemasKey].indexOf(schema);\r\n\t\t\tif (schemaIndex !== -1) {\r\n\t\t\t\tthis.errors = this.errors.concat(data[this.validationErrorsKey][schemaIndex]);\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (Object.isFrozen(data)) {\r\n\t\t\tfrozenIndex = this.scannedFrozen.indexOf(data);\r\n\t\t\tif (frozenIndex !== -1) {\r\n\t\t\t\tvar frozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].indexOf(schema);\r\n\t\t\t\tif (frozenSchemaIndex !== -1) {\r\n\t\t\t\t\tthis.errors = this.errors.concat(this.scannedFrozenValidationErrors[frozenIndex][frozenSchemaIndex]);\r\n\t\t\t\t\treturn null;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.scanned.push(data);\r\n\t\tif (Object.isFrozen(data)) {\r\n\t\t\tif (frozenIndex === -1) {\r\n\t\t\t\tfrozenIndex = this.scannedFrozen.length;\r\n\t\t\t\tthis.scannedFrozen.push(data);\r\n\t\t\t\tthis.scannedFrozenSchemas.push([]);\r\n\t\t\t}\r\n\t\t\tscannedFrozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].length;\r\n\t\t\tthis.scannedFrozenSchemas[frozenIndex][scannedFrozenSchemaIndex] = schema;\r\n\t\t\tthis.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = [];\r\n\t\t} else {\r\n\t\t\tif (!data[this.validatedSchemasKey]) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tObject.defineProperty(data, this.validatedSchemasKey, {\r\n\t\t\t\t\t\tvalue: [],\r\n\t\t\t\t\t\tconfigurable: true\r\n\t\t\t\t\t});\r\n\t\t\t\t\tObject.defineProperty(data, this.validationErrorsKey, {\r\n\t\t\t\t\t\tvalue: [],\r\n\t\t\t\t\t\tconfigurable: true\r\n\t\t\t\t\t});\r\n\t\t\t\t} catch (e) {\r\n\t\t\t\t\t//IE 7/8 workaround\r\n\t\t\t\t\tdata[this.validatedSchemasKey] = [];\r\n\t\t\t\t\tdata[this.validationErrorsKey] = [];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tscannedSchemasIndex = data[this.validatedSchemasKey].length;\r\n\t\t\tdata[this.validatedSchemasKey][scannedSchemasIndex] = schema;\r\n\t\t\tdata[this.validationErrorsKey][scannedSchemasIndex] = [];\r\n\t\t}\r\n\t}\r\n\r\n\tvar errorCount = this.errors.length;\r\n\tvar error = this.validateBasic(data, schema, dataPointerPath)\r\n\t\t|| this.validateNumeric(data, schema, dataPointerPath)\r\n\t\t|| this.validateString(data, schema, dataPointerPath)\r\n\t\t|| this.validateArray(data, schema, dataPointerPath)\r\n\t\t|| this.validateObject(data, schema, dataPointerPath)\r\n\t\t|| this.validateCombinations(data, schema, dataPointerPath)\r\n\t\t|| this.validateHypermedia(data, schema, dataPointerPath)\r\n\t\t|| this.validateFormat(data, schema, dataPointerPath)\r\n\t\t|| this.validateDefinedKeywords(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n\r\n\tif (topLevel) {\r\n\t\twhile (this.scanned.length) {\r\n\t\t\tvar item = this.scanned.pop();\r\n\t\t\tdelete item[this.validatedSchemasKey];\r\n\t\t}\r\n\t\tthis.scannedFrozen = [];\r\n\t\tthis.scannedFrozenSchemas = [];\r\n\t}\r\n\r\n\tif (error || errorCount !== this.errors.length) {\r\n\t\twhile ((dataPathParts && dataPathParts.length) || (schemaPathParts && schemaPathParts.length)) {\r\n\t\t\tvar dataPart = (dataPathParts && dataPathParts.length) ? \"\" + dataPathParts.pop() : null;\r\n\t\t\tvar schemaPart = (schemaPathParts && schemaPathParts.length) ? \"\" + schemaPathParts.pop() : null;\r\n\t\t\tif (error) {\r\n\t\t\t\terror = error.prefixWith(dataPart, schemaPart);\r\n\t\t\t}\r\n\t\t\tthis.prefixErrors(errorCount, dataPart, schemaPart);\r\n\t\t}\r\n\t}\r\n\r\n\tif (scannedFrozenSchemaIndex !== null) {\r\n\t\tthis.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = this.errors.slice(startErrorCount);\r\n\t} else if (scannedSchemasIndex !== null) {\r\n\t\tdata[this.validationErrorsKey][scannedSchemasIndex] = this.errors.slice(startErrorCount);\r\n\t}\r\n\r\n\treturn this.handleError(error);\r\n};\r\nValidatorContext.prototype.validateFormat = function (data, schema) {\r\n\tif (typeof schema.format !== 'string' || !this.formatValidators[schema.format]) {\r\n\t\treturn null;\r\n\t}\r\n\tvar errorMessage = this.formatValidators[schema.format].call(null, data, schema);\r\n\tif (typeof errorMessage === 'string' || typeof errorMessage === 'number') {\r\n\t\treturn this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage}, '', '/format', null, data, schema);\r\n\t} else if (errorMessage && typeof errorMessage === 'object') {\r\n\t\treturn this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage.message || \"?\"}, errorMessage.dataPath || '', errorMessage.schemaPath || \"/format\", null, data, schema);\r\n\t}\r\n\treturn null;\r\n};\r\nValidatorContext.prototype.validateDefinedKeywords = function (data, schema, dataPointerPath) {\r\n\tfor (var key in this.definedKeywords) {\r\n\t\tif (typeof schema[key] === 'undefined') {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tvar validationFunctions = this.definedKeywords[key];\r\n\t\tfor (var i = 0; i < validationFunctions.length; i++) {\r\n\t\t\tvar func = validationFunctions[i];\r\n\t\t\tvar result = func(data, schema[key], schema, dataPointerPath);\r\n\t\t\tif (typeof result === 'string' || typeof result === 'number') {\r\n\t\t\t\treturn this.createError(ErrorCodes.KEYWORD_CUSTOM, {key: key, message: result}, '', '', null, data, schema).prefixWith(null, key);\r\n\t\t\t} else if (result && typeof result === 'object') {\r\n\t\t\t\tvar code = result.code;\r\n\t\t\t\tif (typeof code === 'string') {\r\n\t\t\t\t\tif (!ErrorCodes[code]) {\r\n\t\t\t\t\t\tthrow new Error('Undefined error code (use defineError): ' + code);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcode = ErrorCodes[code];\r\n\t\t\t\t} else if (typeof code !== 'number') {\r\n\t\t\t\t\tcode = ErrorCodes.KEYWORD_CUSTOM;\r\n\t\t\t\t}\r\n\t\t\t\tvar messageParams = (typeof result.message === 'object') ? result.message : {key: key, message: result.message || \"?\"};\r\n\t\t\t\tvar schemaPath = result.schemaPath || (\"/\" + key.replace(/~/g, '~0').replace(/\\//g, '~1'));\r\n\t\t\t\treturn this.createError(code, messageParams, result.dataPath || null, schemaPath, null, data, schema);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nfunction recursiveCompare(A, B) {\r\n\tif (A === B) {\r\n\t\treturn true;\r\n\t}\r\n\tif (A && B && typeof A === \"object\" && typeof B === \"object\") {\r\n\t\tif (Array.isArray(A) !== Array.isArray(B)) {\r\n\t\t\treturn false;\r\n\t\t} else if (Array.isArray(A)) {\r\n\t\t\tif (A.length !== B.length) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\tfor (var i = 0; i < A.length; i++) {\r\n\t\t\t\tif (!recursiveCompare(A[i], B[i])) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tvar key;\r\n\t\t\tfor (key in A) {\r\n\t\t\t\tif (B[key] === undefined && A[key] !== undefined) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (key in B) {\r\n\t\t\t\tif (A[key] === undefined && B[key] !== undefined) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (key in A) {\r\n\t\t\t\tif (!recursiveCompare(A[key], B[key])) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nValidatorContext.prototype.validateBasic = function validateBasic(data, schema, dataPointerPath) {\r\n\tvar error;\r\n\tif (error = this.validateType(data, schema, dataPointerPath)) {\r\n\t\treturn error.prefixWith(null, \"type\");\r\n\t}\r\n\tif (error = this.validateEnum(data, schema, dataPointerPath)) {\r\n\t\treturn error.prefixWith(null, \"type\");\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateType = function validateType(data, schema) {\r\n\tif (schema.type === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar dataType = typeof data;\r\n\tif (data === null) {\r\n\t\tdataType = \"null\";\r\n\t} else if (Array.isArray(data)) {\r\n\t\tdataType = \"array\";\r\n\t}\r\n\tvar allowedTypes = schema.type;\r\n\tif (!Array.isArray(allowedTypes)) {\r\n\t\tallowedTypes = [allowedTypes];\r\n\t}\r\n\r\n\tfor (var i = 0; i < allowedTypes.length; i++) {\r\n\t\tvar type = allowedTypes[i];\r\n\t\tif (type === dataType || (type === \"integer\" && dataType === \"number\" && (data % 1 === 0))) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\treturn this.createError(ErrorCodes.INVALID_TYPE, {type: dataType, expected: allowedTypes.join(\"/\")}, '', '', null, data, schema);\r\n};\r\n\r\nValidatorContext.prototype.validateEnum = function validateEnum(data, schema) {\r\n\tif (schema[\"enum\"] === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tfor (var i = 0; i < schema[\"enum\"].length; i++) {\r\n\t\tvar enumVal = schema[\"enum\"][i];\r\n\t\tif (recursiveCompare(data, enumVal)) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\treturn this.createError(ErrorCodes.ENUM_MISMATCH, {value: (typeof JSON !== 'undefined') ? JSON.stringify(data) : data}, '', '', null, data, schema);\r\n};\r\n\r\nValidatorContext.prototype.validateNumeric = function validateNumeric(data, schema, dataPointerPath) {\r\n\treturn this.validateMultipleOf(data, schema, dataPointerPath)\r\n\t\t|| this.validateMinMax(data, schema, dataPointerPath)\r\n\t\t|| this.validateNaN(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nvar CLOSE_ENOUGH_LOW = Math.pow(2, -51);\r\nvar CLOSE_ENOUGH_HIGH = 1 - CLOSE_ENOUGH_LOW;\r\nValidatorContext.prototype.validateMultipleOf = function validateMultipleOf(data, schema) {\r\n\tvar multipleOf = schema.multipleOf || schema.divisibleBy;\r\n\tif (multipleOf === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tif (typeof data === \"number\") {\r\n\t\tvar remainder = (data/multipleOf)%1;\r\n\t\tif (remainder >= CLOSE_ENOUGH_LOW && remainder < CLOSE_ENOUGH_HIGH) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MULTIPLE_OF, {value: data, multipleOf: multipleOf}, '', '', null, data, schema);\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateMinMax = function validateMinMax(data, schema) {\r\n\tif (typeof data !== \"number\") {\r\n\t\treturn null;\r\n\t}\r\n\tif (schema.minimum !== undefined) {\r\n\t\tif (data < schema.minimum) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MINIMUM, {value: data, minimum: schema.minimum}, '', '/minimum', null, data, schema);\r\n\t\t}\r\n\t\tif (schema.exclusiveMinimum && data === schema.minimum) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MINIMUM_EXCLUSIVE, {value: data, minimum: schema.minimum}, '', '/exclusiveMinimum', null, data, schema);\r\n\t\t}\r\n\t}\r\n\tif (schema.maximum !== undefined) {\r\n\t\tif (data > schema.maximum) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MAXIMUM, {value: data, maximum: schema.maximum}, '', '/maximum', null, data, schema);\r\n\t\t}\r\n\t\tif (schema.exclusiveMaximum && data === schema.maximum) {\r\n\t\t\treturn this.createError(ErrorCodes.NUMBER_MAXIMUM_EXCLUSIVE, {value: data, maximum: schema.maximum}, '', '/exclusiveMaximum', null, data, schema);\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateNaN = function validateNaN(data, schema) {\r\n\tif (typeof data !== \"number\") {\r\n\t\treturn null;\r\n\t}\r\n\tif (isNaN(data) === true || data === Infinity || data === -Infinity) {\r\n\t\treturn this.createError(ErrorCodes.NUMBER_NOT_A_NUMBER, {value: data}, '', '/type', null, data, schema);\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateString = function validateString(data, schema, dataPointerPath) {\r\n\treturn this.validateStringLength(data, schema, dataPointerPath)\r\n\t\t|| this.validateStringPattern(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nValidatorContext.prototype.validateStringLength = function validateStringLength(data, schema) {\r\n\tif (typeof data !== \"string\") {\r\n\t\treturn null;\r\n\t}\r\n\tif (schema.minLength !== undefined) {\r\n\t\tif (data.length < schema.minLength) {\r\n\t\t\treturn this.createError(ErrorCodes.STRING_LENGTH_SHORT, {length: data.length, minimum: schema.minLength}, '', '/minLength', null, data, schema);\r\n\t\t}\r\n\t}\r\n\tif (schema.maxLength !== undefined) {\r\n\t\tif (data.length > schema.maxLength) {\r\n\t\t\treturn this.createError(ErrorCodes.STRING_LENGTH_LONG, {length: data.length, maximum: schema.maxLength}, '', '/maxLength', null, data, schema);\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateStringPattern = function validateStringPattern(data, schema) {\r\n\tif (typeof data !== \"string\" || (typeof schema.pattern !== \"string\" && !(schema.pattern instanceof RegExp))) {\r\n\t\treturn null;\r\n\t}\r\n\tvar regexp;\r\n\tif (schema.pattern instanceof RegExp) {\r\n\t regexp = schema.pattern;\r\n\t}\r\n\telse {\r\n\t var body, flags = '';\r\n\t // Check for regular expression literals\r\n\t // @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5\r\n\t var literal = schema.pattern.match(/^\\/(.+)\\/([img]*)$/);\r\n\t if (literal) {\r\n\t body = literal[1];\r\n\t flags = literal[2];\r\n\t }\r\n\t else {\r\n\t body = schema.pattern;\r\n\t }\r\n\t regexp = new RegExp(body, flags);\r\n\t}\r\n\tif (!regexp.test(data)) {\r\n\t\treturn this.createError(ErrorCodes.STRING_PATTERN, {pattern: schema.pattern}, '', '/pattern', null, data, schema);\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateArray = function validateArray(data, schema, dataPointerPath) {\r\n\tif (!Array.isArray(data)) {\r\n\t\treturn null;\r\n\t}\r\n\treturn this.validateArrayLength(data, schema, dataPointerPath)\r\n\t\t|| this.validateArrayUniqueItems(data, schema, dataPointerPath)\r\n\t\t|| this.validateArrayItems(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nValidatorContext.prototype.validateArrayLength = function validateArrayLength(data, schema) {\r\n\tvar error;\r\n\tif (schema.minItems !== undefined) {\r\n\t\tif (data.length < schema.minItems) {\r\n\t\t\terror = this.createError(ErrorCodes.ARRAY_LENGTH_SHORT, {length: data.length, minimum: schema.minItems}, '', '/minItems', null, data, schema);\r\n\t\t\tif (this.handleError(error)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (schema.maxItems !== undefined) {\r\n\t\tif (data.length > schema.maxItems) {\r\n\t\t\terror = this.createError(ErrorCodes.ARRAY_LENGTH_LONG, {length: data.length, maximum: schema.maxItems}, '', '/maxItems', null, data, schema);\r\n\t\t\tif (this.handleError(error)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateArrayUniqueItems = function validateArrayUniqueItems(data, schema) {\r\n\tif (schema.uniqueItems) {\r\n\t\tfor (var i = 0; i < data.length; i++) {\r\n\t\t\tfor (var j = i + 1; j < data.length; j++) {\r\n\t\t\t\tif (recursiveCompare(data[i], data[j])) {\r\n\t\t\t\t\tvar error = this.createError(ErrorCodes.ARRAY_UNIQUE, {match1: i, match2: j}, '', '/uniqueItems', null, data, schema);\r\n\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateArrayItems = function validateArrayItems(data, schema, dataPointerPath) {\r\n\tif (schema.items === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar error, i;\r\n\tif (Array.isArray(schema.items)) {\r\n\t\tfor (i = 0; i < data.length; i++) {\r\n\t\t\tif (i < schema.items.length) {\r\n\t\t\t\tif (error = this.validateAll(data[i], schema.items[i], [i], [\"items\", i], dataPointerPath + \"/\" + i)) {\r\n\t\t\t\t\treturn error;\r\n\t\t\t\t}\r\n\t\t\t} else if (schema.additionalItems !== undefined) {\r\n\t\t\t\tif (typeof schema.additionalItems === \"boolean\") {\r\n\t\t\t\t\tif (!schema.additionalItems) {\r\n\t\t\t\t\t\terror = (this.createError(ErrorCodes.ARRAY_ADDITIONAL_ITEMS, {}, '/' + i, '/additionalItems', null, data, schema));\r\n\t\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (error = this.validateAll(data[i], schema.additionalItems, [i], [\"additionalItems\"], dataPointerPath + \"/\" + i)) {\r\n\t\t\t\t\treturn error;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t} else {\r\n\t\tfor (i = 0; i < data.length; i++) {\r\n\t\t\tif (error = this.validateAll(data[i], schema.items, [i], [\"items\"], dataPointerPath + \"/\" + i)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateObject = function validateObject(data, schema, dataPointerPath) {\r\n\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\r\n\t\treturn null;\r\n\t}\r\n\treturn this.validateObjectMinMaxProperties(data, schema, dataPointerPath)\r\n\t\t|| this.validateObjectRequiredProperties(data, schema, dataPointerPath)\r\n\t\t|| this.validateObjectProperties(data, schema, dataPointerPath)\r\n\t\t|| this.validateObjectDependencies(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nValidatorContext.prototype.validateObjectMinMaxProperties = function validateObjectMinMaxProperties(data, schema) {\r\n\tvar keys = Object.keys(data);\r\n\tvar error;\r\n\tif (schema.minProperties !== undefined) {\r\n\t\tif (keys.length < schema.minProperties) {\r\n\t\t\terror = this.createError(ErrorCodes.OBJECT_PROPERTIES_MINIMUM, {propertyCount: keys.length, minimum: schema.minProperties}, '', '/minProperties', null, data, schema);\r\n\t\t\tif (this.handleError(error)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (schema.maxProperties !== undefined) {\r\n\t\tif (keys.length > schema.maxProperties) {\r\n\t\t\terror = this.createError(ErrorCodes.OBJECT_PROPERTIES_MAXIMUM, {propertyCount: keys.length, maximum: schema.maxProperties}, '', '/maxProperties', null, data, schema);\r\n\t\t\tif (this.handleError(error)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateObjectRequiredProperties = function validateObjectRequiredProperties(data, schema) {\r\n\tif (schema.required !== undefined) {\r\n\t\tfor (var i = 0; i < schema.required.length; i++) {\r\n\t\t\tvar key = schema.required[i];\r\n\t\t\tif (data[key] === undefined) {\r\n\t\t\t\tvar error = this.createError(ErrorCodes.OBJECT_REQUIRED, {key: key}, '', '/required/' + i, null, data, schema);\r\n\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\treturn error;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateObjectProperties = function validateObjectProperties(data, schema, dataPointerPath) {\r\n\tvar error;\r\n\tfor (var key in data) {\r\n\t\tvar keyPointerPath = dataPointerPath + \"/\" + key.replace(/~/g, '~0').replace(/\\//g, '~1');\r\n\t\tvar foundMatch = false;\r\n\t\tif (schema.properties !== undefined && schema.properties[key] !== undefined) {\r\n\t\t\tfoundMatch = true;\r\n\t\t\tif (error = this.validateAll(data[key], schema.properties[key], [key], [\"properties\", key], keyPointerPath)) {\r\n\t\t\t\treturn error;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (schema.patternProperties !== undefined) {\r\n\t\t\tfor (var patternKey in schema.patternProperties) {\r\n\t\t\t\tvar regexp = new RegExp(patternKey);\r\n\t\t\t\tif (regexp.test(key)) {\r\n\t\t\t\t\tfoundMatch = true;\r\n\t\t\t\t\tif (error = this.validateAll(data[key], schema.patternProperties[patternKey], [key], [\"patternProperties\", patternKey], keyPointerPath)) {\r\n\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!foundMatch) {\r\n\t\t\tif (schema.additionalProperties !== undefined) {\r\n\t\t\t\tif (this.trackUnknownProperties) {\r\n\t\t\t\t\tthis.knownPropertyPaths[keyPointerPath] = true;\r\n\t\t\t\t\tdelete this.unknownPropertyPaths[keyPointerPath];\r\n\t\t\t\t}\r\n\t\t\t\tif (typeof schema.additionalProperties === \"boolean\") {\r\n\t\t\t\t\tif (!schema.additionalProperties) {\r\n\t\t\t\t\t\terror = this.createError(ErrorCodes.OBJECT_ADDITIONAL_PROPERTIES, {key: key}, '', '/additionalProperties', null, data, schema).prefixWith(key, null);\r\n\t\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (error = this.validateAll(data[key], schema.additionalProperties, [key], [\"additionalProperties\"], keyPointerPath)) {\r\n\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else if (this.trackUnknownProperties && !this.knownPropertyPaths[keyPointerPath]) {\r\n\t\t\t\tthis.unknownPropertyPaths[keyPointerPath] = true;\r\n\t\t\t}\r\n\t\t} else if (this.trackUnknownProperties) {\r\n\t\t\tthis.knownPropertyPaths[keyPointerPath] = true;\r\n\t\t\tdelete this.unknownPropertyPaths[keyPointerPath];\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateObjectDependencies = function validateObjectDependencies(data, schema, dataPointerPath) {\r\n\tvar error;\r\n\tif (schema.dependencies !== undefined) {\r\n\t\tfor (var depKey in schema.dependencies) {\r\n\t\t\tif (data[depKey] !== undefined) {\r\n\t\t\t\tvar dep = schema.dependencies[depKey];\r\n\t\t\t\tif (typeof dep === \"string\") {\r\n\t\t\t\t\tif (data[dep] === undefined) {\r\n\t\t\t\t\t\terror = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: dep}, '', '', null, data, schema).prefixWith(null, depKey).prefixWith(null, \"dependencies\");\r\n\t\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (Array.isArray(dep)) {\r\n\t\t\t\t\tfor (var i = 0; i < dep.length; i++) {\r\n\t\t\t\t\t\tvar requiredKey = dep[i];\r\n\t\t\t\t\t\tif (data[requiredKey] === undefined) {\r\n\t\t\t\t\t\t\terror = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: requiredKey}, '', '/' + i, null, data, schema).prefixWith(null, depKey).prefixWith(null, \"dependencies\");\r\n\t\t\t\t\t\t\tif (this.handleError(error)) {\r\n\t\t\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (error = this.validateAll(data, dep, [], [\"dependencies\", depKey], dataPointerPath)) {\r\n\t\t\t\t\t\treturn error;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateCombinations = function validateCombinations(data, schema, dataPointerPath) {\r\n\treturn this.validateAllOf(data, schema, dataPointerPath)\r\n\t\t|| this.validateAnyOf(data, schema, dataPointerPath)\r\n\t\t|| this.validateOneOf(data, schema, dataPointerPath)\r\n\t\t|| this.validateNot(data, schema, dataPointerPath)\r\n\t\t|| null;\r\n};\r\n\r\nValidatorContext.prototype.validateAllOf = function validateAllOf(data, schema, dataPointerPath) {\r\n\tif (schema.allOf === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar error;\r\n\tfor (var i = 0; i < schema.allOf.length; i++) {\r\n\t\tvar subSchema = schema.allOf[i];\r\n\t\tif (error = this.validateAll(data, subSchema, [], [\"allOf\", i], dataPointerPath)) {\r\n\t\t\treturn error;\r\n\t\t}\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateAnyOf = function validateAnyOf(data, schema, dataPointerPath) {\r\n\tif (schema.anyOf === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar errors = [];\r\n\tvar startErrorCount = this.errors.length;\r\n\tvar oldUnknownPropertyPaths, oldKnownPropertyPaths;\r\n\tif (this.trackUnknownProperties) {\r\n\t\toldUnknownPropertyPaths = this.unknownPropertyPaths;\r\n\t\toldKnownPropertyPaths = this.knownPropertyPaths;\r\n\t}\r\n\tvar errorAtEnd = true;\r\n\tfor (var i = 0; i < schema.anyOf.length; i++) {\r\n\t\tif (this.trackUnknownProperties) {\r\n\t\t\tthis.unknownPropertyPaths = {};\r\n\t\t\tthis.knownPropertyPaths = {};\r\n\t\t}\r\n\t\tvar subSchema = schema.anyOf[i];\r\n\r\n\t\tvar errorCount = this.errors.length;\r\n\t\tvar error = this.validateAll(data, subSchema, [], [\"anyOf\", i], dataPointerPath);\r\n\r\n\t\tif (error === null && errorCount === this.errors.length) {\r\n\t\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\r\n\t\t\tif (this.trackUnknownProperties) {\r\n\t\t\t\tfor (var knownKey in this.knownPropertyPaths) {\r\n\t\t\t\t\toldKnownPropertyPaths[knownKey] = true;\r\n\t\t\t\t\tdelete oldUnknownPropertyPaths[knownKey];\r\n\t\t\t\t}\r\n\t\t\t\tfor (var unknownKey in this.unknownPropertyPaths) {\r\n\t\t\t\t\tif (!oldKnownPropertyPaths[unknownKey]) {\r\n\t\t\t\t\t\toldUnknownPropertyPaths[unknownKey] = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t// We need to continue looping so we catch all the property definitions, but we don't want to return an error\r\n\t\t\t\terrorAtEnd = false;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (error) {\r\n\t\t\terrors.push(error.prefixWith(null, \"\" + i).prefixWith(null, \"anyOf\"));\r\n\t\t}\r\n\t}\r\n\tif (this.trackUnknownProperties) {\r\n\t\tthis.unknownPropertyPaths = oldUnknownPropertyPaths;\r\n\t\tthis.knownPropertyPaths = oldKnownPropertyPaths;\r\n\t}\r\n\tif (errorAtEnd) {\r\n\t\terrors = errors.concat(this.errors.slice(startErrorCount));\r\n\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\t\treturn this.createError(ErrorCodes.ANY_OF_MISSING, {}, \"\", \"/anyOf\", errors, data, schema);\r\n\t}\r\n};\r\n\r\nValidatorContext.prototype.validateOneOf = function validateOneOf(data, schema, dataPointerPath) {\r\n\tif (schema.oneOf === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar validIndex = null;\r\n\tvar errors = [];\r\n\tvar startErrorCount = this.errors.length;\r\n\tvar oldUnknownPropertyPaths, oldKnownPropertyPaths;\r\n\tif (this.trackUnknownProperties) {\r\n\t\toldUnknownPropertyPaths = this.unknownPropertyPaths;\r\n\t\toldKnownPropertyPaths = this.knownPropertyPaths;\r\n\t}\r\n\tfor (var i = 0; i < schema.oneOf.length; i++) {\r\n\t\tif (this.trackUnknownProperties) {\r\n\t\t\tthis.unknownPropertyPaths = {};\r\n\t\t\tthis.knownPropertyPaths = {};\r\n\t\t}\r\n\t\tvar subSchema = schema.oneOf[i];\r\n\r\n\t\tvar errorCount = this.errors.length;\r\n\t\tvar error = this.validateAll(data, subSchema, [], [\"oneOf\", i], dataPointerPath);\r\n\r\n\t\tif (error === null && errorCount === this.errors.length) {\r\n\t\t\tif (validIndex === null) {\r\n\t\t\t\tvalidIndex = i;\r\n\t\t\t} else {\r\n\t\t\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\t\t\t\treturn this.createError(ErrorCodes.ONE_OF_MULTIPLE, {index1: validIndex, index2: i}, \"\", \"/oneOf\", null, data, schema);\r\n\t\t\t}\r\n\t\t\tif (this.trackUnknownProperties) {\r\n\t\t\t\tfor (var knownKey in this.knownPropertyPaths) {\r\n\t\t\t\t\toldKnownPropertyPaths[knownKey] = true;\r\n\t\t\t\t\tdelete oldUnknownPropertyPaths[knownKey];\r\n\t\t\t\t}\r\n\t\t\t\tfor (var unknownKey in this.unknownPropertyPaths) {\r\n\t\t\t\t\tif (!oldKnownPropertyPaths[unknownKey]) {\r\n\t\t\t\t\t\toldUnknownPropertyPaths[unknownKey] = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else if (error) {\r\n\t\t\terrors.push(error);\r\n\t\t}\r\n\t}\r\n\tif (this.trackUnknownProperties) {\r\n\t\tthis.unknownPropertyPaths = oldUnknownPropertyPaths;\r\n\t\tthis.knownPropertyPaths = oldKnownPropertyPaths;\r\n\t}\r\n\tif (validIndex === null) {\r\n\t\terrors = errors.concat(this.errors.slice(startErrorCount));\r\n\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\t\treturn this.createError(ErrorCodes.ONE_OF_MISSING, {}, \"\", \"/oneOf\", errors, data, schema);\r\n\t} else {\r\n\t\tthis.errors = this.errors.slice(0, startErrorCount);\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateNot = function validateNot(data, schema, dataPointerPath) {\r\n\tif (schema.not === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\tvar oldErrorCount = this.errors.length;\r\n\tvar oldUnknownPropertyPaths, oldKnownPropertyPaths;\r\n\tif (this.trackUnknownProperties) {\r\n\t\toldUnknownPropertyPaths = this.unknownPropertyPaths;\r\n\t\toldKnownPropertyPaths = this.knownPropertyPaths;\r\n\t\tthis.unknownPropertyPaths = {};\r\n\t\tthis.knownPropertyPaths = {};\r\n\t}\r\n\tvar error = this.validateAll(data, schema.not, null, null, dataPointerPath);\r\n\tvar notErrors = this.errors.slice(oldErrorCount);\r\n\tthis.errors = this.errors.slice(0, oldErrorCount);\r\n\tif (this.trackUnknownProperties) {\r\n\t\tthis.unknownPropertyPaths = oldUnknownPropertyPaths;\r\n\t\tthis.knownPropertyPaths = oldKnownPropertyPaths;\r\n\t}\r\n\tif (error === null && notErrors.length === 0) {\r\n\t\treturn this.createError(ErrorCodes.NOT_PASSED, {}, \"\", \"/not\", null, data, schema);\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nValidatorContext.prototype.validateHypermedia = function validateCombinations(data, schema, dataPointerPath) {\r\n\tif (!schema.links) {\r\n\t\treturn null;\r\n\t}\r\n\tvar error;\r\n\tfor (var i = 0; i < schema.links.length; i++) {\r\n\t\tvar ldo = schema.links[i];\r\n\t\tif (ldo.rel === \"describedby\") {\r\n\t\t\tvar template = new UriTemplate(ldo.href);\r\n\t\t\tvar allPresent = true;\r\n\t\t\tfor (var j = 0; j < template.varNames.length; j++) {\r\n\t\t\t\tif (!(template.varNames[j] in data)) {\r\n\t\t\t\t\tallPresent = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (allPresent) {\r\n\t\t\t\tvar schemaUrl = template.fillFromObject(data);\r\n\t\t\t\tvar subSchema = {\"$ref\": schemaUrl};\r\n\t\t\t\tif (error = this.validateAll(data, subSchema, [], [\"links\", i], dataPointerPath)) {\r\n\t\t\t\t\treturn error;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\n// parseURI() and resolveUrl() are from https://gist.github.com/1088850\r\n// - released as public domain by author (\"Yaffle\") - see comments on gist\r\n\r\nfunction parseURI(url) {\r\n\tvar m = String(url).replace(/^\\s+|\\s+$/g, '').match(/^([^:\\/?#]+:)?(\\/\\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\\/?#]*)(?::(\\d*))?))?([^?#]*)(\\?[^#]*)?(#[\\s\\S]*)?/);\r\n\t// authority = '//' + user + ':' + pass '@' + hostname + ':' port\r\n\treturn (m ? {\r\n\t\thref : m[0] || '',\r\n\t\tprotocol : m[1] || '',\r\n\t\tauthority: m[2] || '',\r\n\t\thost : m[3] || '',\r\n\t\thostname : m[4] || '',\r\n\t\tport : m[5] || '',\r\n\t\tpathname : m[6] || '',\r\n\t\tsearch : m[7] || '',\r\n\t\thash : m[8] || ''\r\n\t} : null);\r\n}\r\n\r\nfunction resolveUrl(base, href) {// RFC 3986\r\n\r\n\tfunction removeDotSegments(input) {\r\n\t\tvar output = [];\r\n\t\tinput.replace(/^(\\.\\.?(\\/|$))+/, '')\r\n\t\t\t.replace(/\\/(\\.(\\/|$))+/g, '/')\r\n\t\t\t.replace(/\\/\\.\\.$/, '/../')\r\n\t\t\t.replace(/\\/?[^\\/]*/g, function (p) {\r\n\t\t\t\tif (p === '/..') {\r\n\t\t\t\t\toutput.pop();\r\n\t\t\t\t} else {\r\n\t\t\t\t\toutput.push(p);\r\n\t\t\t\t}\r\n\t\t});\r\n\t\treturn output.join('').replace(/^\\//, input.charAt(0) === '/' ? '/' : '');\r\n\t}\r\n\r\n\thref = parseURI(href || '');\r\n\tbase = parseURI(base || '');\r\n\r\n\treturn !href || !base ? null : (href.protocol || base.protocol) +\r\n\t\t(href.protocol || href.authority ? href.authority : base.authority) +\r\n\t\tremoveDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +\r\n\t\t(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +\r\n\t\thref.hash;\r\n}\r\n\r\nfunction getDocumentUri(uri) {\r\n\treturn uri.split('#')[0];\r\n}\r\nfunction normSchema(schema, baseUri) {\r\n\tif (schema && typeof schema === \"object\") {\r\n\t\tif (baseUri === undefined) {\r\n\t\t\tbaseUri = schema.id;\r\n\t\t} else if (typeof schema.id === \"string\") {\r\n\t\t\tbaseUri = resolveUrl(baseUri, schema.id);\r\n\t\t\tschema.id = baseUri;\r\n\t\t}\r\n\t\tif (Array.isArray(schema)) {\r\n\t\t\tfor (var i = 0; i < schema.length; i++) {\r\n\t\t\t\tnormSchema(schema[i], baseUri);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif (typeof schema['$ref'] === \"string\") {\r\n\t\t\t\tschema['$ref'] = resolveUrl(baseUri, schema['$ref']);\r\n\t\t\t}\r\n\t\t\tfor (var key in schema) {\r\n\t\t\t\tif (key !== \"enum\") {\r\n\t\t\t\t\tnormSchema(schema[key], baseUri);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction defaultErrorReporter(language) {\r\n\tlanguage = language || 'en';\r\n\r\n\tvar errorMessages = languages[language];\r\n\r\n\treturn function (error) {\r\n\t\tvar messageTemplate = errorMessages[error.code] || ErrorMessagesDefault[error.code];\r\n\t\tif (typeof messageTemplate !== 'string') {\r\n\t\t\treturn \"Unknown error code \" + error.code + \": \" + JSON.stringify(error.messageParams);\r\n\t\t}\r\n\t\tvar messageParams = error.params;\r\n\t\t// Adapted from Crockford's supplant()\r\n\t\treturn messageTemplate.replace(/\\{([^{}]*)\\}/g, function (whole, varName) {\r\n\t\t\tvar subValue = messageParams[varName];\r\n\t\t\treturn typeof subValue === 'string' || typeof subValue === 'number' ? subValue : whole;\r\n\t\t});\r\n\t};\r\n}\r\n\r\nvar ErrorCodes = {\r\n\tINVALID_TYPE: 0,\r\n\tENUM_MISMATCH: 1,\r\n\tANY_OF_MISSING: 10,\r\n\tONE_OF_MISSING: 11,\r\n\tONE_OF_MULTIPLE: 12,\r\n\tNOT_PASSED: 13,\r\n\t// Numeric errors\r\n\tNUMBER_MULTIPLE_OF: 100,\r\n\tNUMBER_MINIMUM: 101,\r\n\tNUMBER_MINIMUM_EXCLUSIVE: 102,\r\n\tNUMBER_MAXIMUM: 103,\r\n\tNUMBER_MAXIMUM_EXCLUSIVE: 104,\r\n\tNUMBER_NOT_A_NUMBER: 105,\r\n\t// String errors\r\n\tSTRING_LENGTH_SHORT: 200,\r\n\tSTRING_LENGTH_LONG: 201,\r\n\tSTRING_PATTERN: 202,\r\n\t// Object errors\r\n\tOBJECT_PROPERTIES_MINIMUM: 300,\r\n\tOBJECT_PROPERTIES_MAXIMUM: 301,\r\n\tOBJECT_REQUIRED: 302,\r\n\tOBJECT_ADDITIONAL_PROPERTIES: 303,\r\n\tOBJECT_DEPENDENCY_KEY: 304,\r\n\t// Array errors\r\n\tARRAY_LENGTH_SHORT: 400,\r\n\tARRAY_LENGTH_LONG: 401,\r\n\tARRAY_UNIQUE: 402,\r\n\tARRAY_ADDITIONAL_ITEMS: 403,\r\n\t// Custom/user-defined errors\r\n\tFORMAT_CUSTOM: 500,\r\n\tKEYWORD_CUSTOM: 501,\r\n\t// Schema structure\r\n\tCIRCULAR_REFERENCE: 600,\r\n\t// Non-standard validation options\r\n\tUNKNOWN_PROPERTY: 1000\r\n};\r\nvar ErrorCodeLookup = {};\r\nfor (var key in ErrorCodes) {\r\n\tErrorCodeLookup[ErrorCodes[key]] = key;\r\n}\r\nvar ErrorMessagesDefault = {\r\n\tINVALID_TYPE: \"Invalid type: {type} (expected {expected})\",\r\n\tENUM_MISMATCH: \"No enum match for: {value}\",\r\n\tANY_OF_MISSING: \"Data does not match any schemas from \\\"anyOf\\\"\",\r\n\tONE_OF_MISSING: \"Data does not match any schemas from \\\"oneOf\\\"\",\r\n\tONE_OF_MULTIPLE: \"Data is valid against more than one schema from \\\"oneOf\\\": indices {index1} and {index2}\",\r\n\tNOT_PASSED: \"Data matches schema from \\\"not\\\"\",\r\n\t// Numeric errors\r\n\tNUMBER_MULTIPLE_OF: \"Value {value} is not a multiple of {multipleOf}\",\r\n\tNUMBER_MINIMUM: \"Value {value} is less than minimum {minimum}\",\r\n\tNUMBER_MINIMUM_EXCLUSIVE: \"Value {value} is equal to exclusive minimum {minimum}\",\r\n\tNUMBER_MAXIMUM: \"Value {value} is greater than maximum {maximum}\",\r\n\tNUMBER_MAXIMUM_EXCLUSIVE: \"Value {value} is equal to exclusive maximum {maximum}\",\r\n\tNUMBER_NOT_A_NUMBER: \"Value {value} is not a valid number\",\r\n\t// String errors\r\n\tSTRING_LENGTH_SHORT: \"String is too short ({length} chars), minimum {minimum}\",\r\n\tSTRING_LENGTH_LONG: \"String is too long ({length} chars), maximum {maximum}\",\r\n\tSTRING_PATTERN: \"String does not match pattern: {pattern}\",\r\n\t// Object errors\r\n\tOBJECT_PROPERTIES_MINIMUM: \"Too few properties defined ({propertyCount}), minimum {minimum}\",\r\n\tOBJECT_PROPERTIES_MAXIMUM: \"Too many properties defined ({propertyCount}), maximum {maximum}\",\r\n\tOBJECT_REQUIRED: \"Missing required property: {key}\",\r\n\tOBJECT_ADDITIONAL_PROPERTIES: \"Additional properties not allowed\",\r\n\tOBJECT_DEPENDENCY_KEY: \"Dependency failed - key must exist: {missing} (due to key: {key})\",\r\n\t// Array errors\r\n\tARRAY_LENGTH_SHORT: \"Array is too short ({length}), minimum {minimum}\",\r\n\tARRAY_LENGTH_LONG: \"Array is too long ({length}), maximum {maximum}\",\r\n\tARRAY_UNIQUE: \"Array items are not unique (indices {match1} and {match2})\",\r\n\tARRAY_ADDITIONAL_ITEMS: \"Additional items not allowed\",\r\n\t// Format errors\r\n\tFORMAT_CUSTOM: \"Format validation failed ({message})\",\r\n\tKEYWORD_CUSTOM: \"Keyword failed: {key} ({message})\",\r\n\t// Schema structure\r\n\tCIRCULAR_REFERENCE: \"Circular $refs: {urls}\",\r\n\t// Non-standard validation options\r\n\tUNKNOWN_PROPERTY: \"Unknown property (not in schema)\"\r\n};\r\n\r\nfunction ValidationError(code, params, dataPath, schemaPath, subErrors) {\r\n\tError.call(this);\r\n\tif (code === undefined) {\r\n\t\tthrow new Error (\"No error code supplied: \" + schemaPath);\r\n\t}\r\n\tthis.message = '';\r\n\tthis.params = params;\r\n\tthis.code = code;\r\n\tthis.dataPath = dataPath || \"\";\r\n\tthis.schemaPath = schemaPath || \"\";\r\n\tthis.subErrors = subErrors || null;\r\n\r\n\tvar err = new Error(this.message);\r\n\tthis.stack = err.stack || err.stacktrace;\r\n\tif (!this.stack) {\r\n\t\ttry {\r\n\t\t\tthrow err;\r\n\t\t}\r\n\t\tcatch(err) {\r\n\t\t\tthis.stack = err.stack || err.stacktrace;\r\n\t\t}\r\n\t}\r\n}\r\nValidationError.prototype = Object.create(Error.prototype);\r\nValidationError.prototype.constructor = ValidationError;\r\nValidationError.prototype.name = 'ValidationError';\r\n\r\nValidationError.prototype.prefixWith = function (dataPrefix, schemaPrefix) {\r\n\tif (dataPrefix !== null) {\r\n\t\tdataPrefix = dataPrefix.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\r\n\t\tthis.dataPath = \"/\" + dataPrefix + this.dataPath;\r\n\t}\r\n\tif (schemaPrefix !== null) {\r\n\t\tschemaPrefix = schemaPrefix.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\r\n\t\tthis.schemaPath = \"/\" + schemaPrefix + this.schemaPath;\r\n\t}\r\n\tif (this.subErrors !== null) {\r\n\t\tfor (var i = 0; i < this.subErrors.length; i++) {\r\n\t\t\tthis.subErrors[i].prefixWith(dataPrefix, schemaPrefix);\r\n\t\t}\r\n\t}\r\n\treturn this;\r\n};\r\n\r\nfunction isTrustedUrl(baseUrl, testUrl) {\r\n\tif(testUrl.substring(0, baseUrl.length) === baseUrl){\r\n\t\tvar remainder = testUrl.substring(baseUrl.length);\r\n\t\tif ((testUrl.length > 0 && testUrl.charAt(baseUrl.length - 1) === \"/\")\r\n\t\t\t|| remainder.charAt(0) === \"#\"\r\n\t\t\t|| remainder.charAt(0) === \"?\") {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvar languages = {};\r\nfunction createApi(language) {\r\n\tvar globalContext = new ValidatorContext();\r\n\tvar currentLanguage;\r\n\tvar customErrorReporter;\r\n\tvar api = {\r\n\t\tsetErrorReporter: function (reporter) {\r\n\t\t\tif (typeof reporter === 'string') {\r\n\t\t\t\treturn this.language(reporter);\r\n\t\t\t}\r\n\t\t\tcustomErrorReporter = reporter;\r\n\t\t\treturn true;\r\n\t\t},\r\n\t\taddFormat: function () {\r\n\t\t\tglobalContext.addFormat.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tlanguage: function (code) {\r\n\t\t\tif (!code) {\r\n\t\t\t\treturn currentLanguage;\r\n\t\t\t}\r\n\t\t\tif (!languages[code]) {\r\n\t\t\t\tcode = code.split('-')[0]; // fall back to base language\r\n\t\t\t}\r\n\t\t\tif (languages[code]) {\r\n\t\t\t\tcurrentLanguage = code;\r\n\t\t\t\treturn code; // so you can tell if fall-back has happened\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t},\r\n\t\taddLanguage: function (code, messageMap) {\r\n\t\t\tvar key;\r\n\t\t\tfor (key in ErrorCodes) {\r\n\t\t\t\tif (messageMap[key] && !messageMap[ErrorCodes[key]]) {\r\n\t\t\t\t\tmessageMap[ErrorCodes[key]] = messageMap[key];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tvar rootCode = code.split('-')[0];\r\n\t\t\tif (!languages[rootCode]) { // use for base language if not yet defined\r\n\t\t\t\tlanguages[code] = messageMap;\r\n\t\t\t\tlanguages[rootCode] = messageMap;\r\n\t\t\t} else {\r\n\t\t\t\tlanguages[code] = Object.create(languages[rootCode]);\r\n\t\t\t\tfor (key in messageMap) {\r\n\t\t\t\t\tif (typeof languages[rootCode][key] === 'undefined') {\r\n\t\t\t\t\t\tlanguages[rootCode][key] = messageMap[key];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tlanguages[code][key] = messageMap[key];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn this;\r\n\t\t},\r\n\t\tfreshApi: function (language) {\r\n\t\t\tvar result = createApi();\r\n\t\t\tif (language) {\r\n\t\t\t\tresult.language(language);\r\n\t\t\t}\r\n\t\t\treturn result;\r\n\t\t},\r\n\t\tvalidate: function (data, schema, checkRecursive, banUnknownProperties) {\r\n\t\t\tvar def = defaultErrorReporter(currentLanguage);\r\n\t\t\tvar errorReporter = customErrorReporter ? function (error, data, schema) {\r\n\t\t\t\treturn customErrorReporter(error, data, schema) || def(error, data, schema);\r\n\t\t\t} : def;\r\n\t\t\tvar context = new ValidatorContext(globalContext, false, errorReporter, checkRecursive, banUnknownProperties);\r\n\t\t\tif (typeof schema === \"string\") {\r\n\t\t\t\tschema = {\"$ref\": schema};\r\n\t\t\t}\r\n\t\t\tcontext.addSchema(\"\", schema);\r\n\t\t\tvar error = context.validateAll(data, schema, null, null, \"\");\r\n\t\t\tif (!error && banUnknownProperties) {\r\n\t\t\t\terror = context.banUnknownProperties(data, schema);\r\n\t\t\t}\r\n\t\t\tthis.error = error;\r\n\t\t\tthis.missing = context.missing;\r\n\t\t\tthis.valid = (error === null);\r\n\t\t\treturn this.valid;\r\n\t\t},\r\n\t\tvalidateResult: function () {\r\n\t\t\tvar result = {toString: function () {\r\n\t\t\t\treturn this.valid ? 'valid' : this.error.message;\r\n\t\t\t}};\r\n\t\t\tthis.validate.apply(result, arguments);\r\n\t\t\treturn result;\r\n\t\t},\r\n\t\tvalidateMultiple: function (data, schema, checkRecursive, banUnknownProperties) {\r\n\t\t\tvar def = defaultErrorReporter(currentLanguage);\r\n\t\t\tvar errorReporter = customErrorReporter ? function (error, data, schema) {\r\n\t\t\t\treturn customErrorReporter(error, data, schema) || def(error, data, schema);\r\n\t\t\t} : def;\r\n\t\t\tvar context = new ValidatorContext(globalContext, true, errorReporter, checkRecursive, banUnknownProperties);\r\n\t\t\tif (typeof schema === \"string\") {\r\n\t\t\t\tschema = {\"$ref\": schema};\r\n\t\t\t}\r\n\t\t\tcontext.addSchema(\"\", schema);\r\n\t\t\tcontext.validateAll(data, schema, null, null, \"\");\r\n\t\t\tif (banUnknownProperties) {\r\n\t\t\t\tcontext.banUnknownProperties(data, schema);\r\n\t\t\t}\r\n\t\t\tvar result = {toString: function () {\r\n\t\t\t\treturn this.valid ? 'valid' : this.error.message;\r\n\t\t\t}};\r\n\t\t\tresult.errors = context.errors;\r\n\t\t\tresult.missing = context.missing;\r\n\t\t\tresult.valid = (result.errors.length === 0);\r\n\t\t\treturn result;\r\n\t\t},\r\n\t\taddSchema: function () {\r\n\t\t\treturn globalContext.addSchema.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tgetSchema: function () {\r\n\t\t\treturn globalContext.getSchema.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tgetSchemaMap: function () {\r\n\t\t\treturn globalContext.getSchemaMap.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tgetSchemaUris: function () {\r\n\t\t\treturn globalContext.getSchemaUris.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tgetMissingUris: function () {\r\n\t\t\treturn globalContext.getMissingUris.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tdropSchemas: function () {\r\n\t\t\tglobalContext.dropSchemas.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tdefineKeyword: function () {\r\n\t\t\tglobalContext.defineKeyword.apply(globalContext, arguments);\r\n\t\t},\r\n\t\tdefineError: function (codeName, codeNumber, defaultMessage) {\r\n\t\t\tif (typeof codeName !== 'string' || !/^[A-Z]+(_[A-Z]+)*$/.test(codeName)) {\r\n\t\t\t\tthrow new Error('Code name must be a string in UPPER_CASE_WITH_UNDERSCORES');\r\n\t\t\t}\r\n\t\t\tif (typeof codeNumber !== 'number' || codeNumber%1 !== 0 || codeNumber < 10000) {\r\n\t\t\t\tthrow new Error('Code number must be an integer > 10000');\r\n\t\t\t}\r\n\t\t\tif (typeof ErrorCodes[codeName] !== 'undefined') {\r\n\t\t\t\tthrow new Error('Error already defined: ' + codeName + ' as ' + ErrorCodes[codeName]);\r\n\t\t\t}\r\n\t\t\tif (typeof ErrorCodeLookup[codeNumber] !== 'undefined') {\r\n\t\t\t\tthrow new Error('Error code already used: ' + ErrorCodeLookup[codeNumber] + ' as ' + codeNumber);\r\n\t\t\t}\r\n\t\t\tErrorCodes[codeName] = codeNumber;\r\n\t\t\tErrorCodeLookup[codeNumber] = codeName;\r\n\t\t\tErrorMessagesDefault[codeName] = ErrorMessagesDefault[codeNumber] = defaultMessage;\r\n\t\t\tfor (var langCode in languages) {\r\n\t\t\t\tvar language = languages[langCode];\r\n\t\t\t\tif (language[codeName]) {\r\n\t\t\t\t\tlanguage[codeNumber] = language[codeNumber] || language[codeName];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t},\r\n\t\treset: function () {\r\n\t\t\tglobalContext.reset();\r\n\t\t\tthis.error = null;\r\n\t\t\tthis.missing = [];\r\n\t\t\tthis.valid = true;\r\n\t\t},\r\n\t\tmissing: [],\r\n\t\terror: null,\r\n\t\tvalid: true,\r\n\t\tnormSchema: normSchema,\r\n\t\tresolveUrl: resolveUrl,\r\n\t\tgetDocumentUri: getDocumentUri,\r\n\t\terrorCodes: ErrorCodes\r\n\t};\r\n\tapi.language(language || 'en');\r\n\treturn api;\r\n}\r\n\r\nvar tv4 = createApi();\r\ntv4.addLanguage('en-gb', ErrorMessagesDefault);\r\n\r\n//legacy property\r\ntv4.tv4 = tv4;\r\n\r\nreturn tv4; // used by _header.js to globalise.\r\n\r\n}));","type JsonSchemas = { [key: string]: tv4.JsonSchema };\n\n/**\n * - Manages and validates types of remoteStorage objects, using JSON-LD and\n * JSON Schema\n * - Adds schema declaration/validation methods to BaseClient instances.\n **/\nexport class BaseClientTypes {\n /**\n * -> \n */\n uris: { [key: string]: string } = {};\n\n /**\n * Contains schema objects of all types known to the BaseClient instance\n *\n * -> \n */\n schemas: JsonSchemas = {};\n\n /**\n * -> \n */\n aliases: { [key: string]: string } = {};\n\n /**\n * Called via public function BaseClient.declareType()\n *\n * @private\n */\n declare (moduleName: string, alias: string, uri: string, schema: tv4.JsonSchema): void {\n const fullAlias = moduleName + '/' + alias;\n\n if (schema.extends) {\n const parts = schema.extends.split('/');\n const extendedAlias = (parts.length === 1)\n ? moduleName + '/' + parts.shift()\n : parts.join('/');\n\n const extendedUri = this.uris[extendedAlias];\n if (!extendedUri) {\n throw \"Type '\" + fullAlias + \"' tries to extend unknown schema '\" + extendedAlias + \"'\";\n }\n schema.extends = this.schemas[extendedUri];\n }\n\n this.uris[fullAlias] = uri;\n this.aliases[uri] = fullAlias;\n this.schemas[uri] = schema;\n }\n\n resolveAlias (alias: string): string {\n return this.uris[alias];\n }\n\n getSchema (uri: string): tv4.JsonSchema {\n return this.schemas[uri];\n }\n\n inScope (moduleName: string): JsonSchemas {\n const ml = moduleName.length;\n const schemas = {};\n for (const alias in this.uris) {\n if (alias.substr(0, ml + 1) === moduleName + '/') {\n const uri = this.uris[alias];\n schemas[uri] = this.schemas[uri];\n }\n }\n return schemas;\n }\n}\n\nconst Types = new BaseClientTypes();\nexport default Types;\n","class SchemaNotFound extends Error {\n constructor(uri: string) {\n super();\n const error = new Error(\"Schema not found: \" + uri);\n error.name = \"SchemaNotFound\";\n return error;\n }\n}\n\nexport = SchemaNotFound;\n","/**\n * A cache which can propagate changes up to parent folders and generate new\n * revision ids for them. The generated revision id is consistent across\n * different sessions. The keys for the cache are case-insensitive.\n *\n * @param defaultValue {string} the value that is returned for all keys that\n * don't exist in the cache\n * @class\n */\n\nclass RevisionCache {\n defaultValue: string;\n\n private _itemsRev: { [key: string]: any } = {};\n private _storage: { [key: string]: string } = {};\n private _canPropagate = false;\n\n constructor(defaultValue: string) {\n this.defaultValue = defaultValue;\n this.activatePropagation();\n }\n\n\n /**\n * Get a value from the cache or defaultValue, if the key is not in the\n * cache\n */\n get(key: string): string {\n key = key.toLowerCase();\n let stored = this._storage[key];\n if (typeof stored === 'undefined') {\n stored = this.defaultValue;\n this._storage[key] = stored;\n }\n return stored;\n }\n\n /**\n * Set a value\n */\n set(key: string, value): unknown {\n key = key.toLowerCase();\n if (this._storage[key] === value) {\n return value;\n }\n this._storage[key] = value;\n if (!value) {\n delete this._itemsRev[key];\n }\n this._updateParentFolderItemRev(key, value);\n if (this._canPropagate) {\n this._propagate(key);\n }\n return value;\n }\n\n /**\n * Delete a value\n */\n delete(key: string): unknown {\n return this.set(key, null);\n }\n\n /**\n * Disables automatic update of folder revisions when a key value is updated\n */\n deactivatePropagation(): true {\n this._canPropagate = false;\n return true;\n }\n\n /**\n * Enables automatic update of folder revisions when a key value is updated\n * and refreshes the folder revision ids for entire tree.\n */\n activatePropagation(): true {\n if (this._canPropagate) {\n return true;\n }\n this._generateFolderRev(\"/\");\n this._canPropagate = true;\n return true;\n }\n\n /**\n * Returns a hash code for a string.\n */\n private _hashCode(str: string): number {\n let hash = 0;\n if (str.length === 0) {\n return hash;\n }\n for (let i = 0; i < str.length; i++) {\n const chr = str.charCodeAt(i);\n // eslint-disable-next-line no-bitwise\n hash = ((hash << 5) - hash) + chr;\n // eslint-disable-next-line no-bitwise\n hash |= 0; // Convert to 32bit integer\n }\n return hash;\n }\n\n /**\n * Takes an array of strings and returns a hash of the items\n */\n private _generateHash(items: string[]): string {\n // We sort the items before joining them to ensure correct hash generation\n // every time\n const files = items.sort().join('|');\n const hash = \"\" + this._hashCode(files);\n return hash;\n }\n\n /**\n * Update the revision of a key in it's parent folder data\n */\n private _updateParentFolderItemRev(key: string, rev): void {\n if (key !== '/') {\n const parentFolder = this._getParentFolder(key);\n if (!this._itemsRev[parentFolder]) {\n this._itemsRev[parentFolder] = {};\n }\n const parentFolderItemsRev = this._itemsRev[parentFolder];\n if (!rev) {\n delete parentFolderItemsRev[key];\n } else {\n parentFolderItemsRev[key] = rev;\n }\n //reset revision until root\n this._updateParentFolderItemRev(parentFolder, this.defaultValue);\n }\n }\n\n private _getParentFolder(key: string): string {\n return key.substr(0, key.lastIndexOf('/', key.length - 2) + 1);\n }\n\n /**\n * Propagate the changes to the parent folders and generate new revision ids\n * for them\n */\n private _propagate(key: string): void {\n if (key !== '/') {\n const parentFolder = this._getParentFolder(key);\n const parentFolderItemsRev = this._itemsRev[parentFolder];\n const hashItems = [];\n for (const path in parentFolderItemsRev) {\n hashItems.push(parentFolderItemsRev[path]);\n }\n const newRev = this._generateHash(hashItems);\n this.set(parentFolder, newRev);\n }\n }\n\n /**\n * Generate revision id for a folder and it's subfolders, by hashing it's\n * listing\n */\n private _generateFolderRev(folder: string): string {\n const itemsRev = this._itemsRev[folder];\n let hash = this.defaultValue;\n if (itemsRev) {\n const hashItems = [];\n for (const path in itemsRev) {\n const isDir: boolean = (path.substr(-1) === '/');\n let hashItem;\n if (isDir) {\n hashItem = this._generateFolderRev(path);\n } else {\n hashItem = itemsRev[path];\n }\n hashItems.push(hashItem);\n }\n if (hashItems.length > 0) {\n hash = this._generateHash(hashItems);\n }\n }\n this.set(folder, hash);\n return hash;\n }\n}\n\nexport = RevisionCache;\n","/* global define */\n/*!\n * webfinger.js\n * version 2.7.0\n * http://github.com/silverbucket/webfinger.js\n *\n * Developed and Maintained by:\n * Nick Jennings 2012\n *\n * webfinger.js is released under the AGPL (see LICENSE).\n *\n * You don't have to do anything special to choose one license or the other and you don't\n * have to notify anyone which license you are using.\n * Please see the corresponding license file for details of these licenses.\n * You are free to use, modify and distribute this software, but all copyright\n * information must remain.\n *\n */\n\nif (typeof fetch !== 'function' && typeof XMLHttpRequest !== 'function') {\n // XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;\n XMLHttpRequest = require('xhr2');\n}\n\n(function (global) {\n\n // URI to property name map\n var LINK_URI_MAPS = {\n 'http://webfist.org/spec/rel': 'webfist',\n 'http://webfinger.net/rel/avatar': 'avatar',\n 'remotestorage': 'remotestorage',\n 'http://tools.ietf.org/id/draft-dejong-remotestorage': 'remotestorage',\n 'remoteStorage': 'remotestorage',\n 'http://www.packetizer.com/rel/share': 'share',\n 'http://webfinger.net/rel/profile-page': 'profile',\n 'me': 'profile',\n 'vcard': 'vcard',\n 'blog': 'blog',\n 'http://packetizer.com/rel/blog': 'blog',\n 'http://schemas.google.com/g/2010#updates-from': 'updates',\n 'https://camlistore.org/rel/server': 'camilstore'\n };\n\n var LINK_PROPERTIES = {\n 'avatar': [],\n 'remotestorage': [],\n 'blog': [],\n 'vcard': [],\n 'updates': [],\n 'share': [],\n 'profile': [],\n 'webfist': [],\n 'camlistore': []\n };\n\n // list of endpoints to try, fallback from beginning to end.\n var URIS = ['webfinger', 'host-meta', 'host-meta.json'];\n\n function generateErrorObject(obj) {\n obj.toString = function () {\n return this.message;\n };\n return obj;\n }\n\n // given a URL ensures it's HTTPS.\n // returns false for null string or non-HTTPS URL.\n function isSecure(url) {\n if (typeof url !== 'string') {\n return false;\n }\n var parts = url.split('://');\n if (parts[0] === 'https') {\n return true;\n }\n return false;\n }\n\n /**\n * Function: WebFinger\n *\n * WebFinger constructor\n *\n * Returns:\n *\n * return WebFinger object\n */\n function WebFinger(config) {\n if (typeof config !== 'object') {\n config = {};\n }\n\n this.config = {\n tls_only: (typeof config.tls_only !== 'undefined') ? config.tls_only : true,\n webfist_fallback: (typeof config.webfist_fallback !== 'undefined') ? config.webfist_fallback : false,\n uri_fallback: (typeof config.uri_fallback !== 'undefined') ? config.uri_fallback : false,\n request_timeout: (typeof config.request_timeout !== 'undefined') ? config.request_timeout : 10000\n };\n }\n\n // make an http request and look for JRD response, fails if request fails\n // or response not json.\n WebFinger.prototype.__fetchJRD = function (url, errorHandler, sucessHandler) {\n if (typeof fetch === 'function') {\n return this.__fetchJRD_fetch(url, errorHandler, sucessHandler);\n } else if (typeof XMLHttpRequest === 'function') {\n return this.__fetchJRD_XHR(url, errorHandler, sucessHandler);\n } else {\n throw new Error(\"add a polyfill for fetch or XMLHttpRequest\");\n }\n };\n WebFinger.prototype.__fetchJRD_fetch = function (url, errorHandler, sucessHandler) {\n var webfinger = this;\n var abortController;\n if (typeof AbortController === 'function') {\n abortController = new AbortController();\n }\n var networkPromise = fetch(url, {\n headers: {'Accept': 'application/jrd+json, application/json'},\n signal: abortController ? abortController.signal : undefined\n }).\n then(function (response) {\n if (response.ok) {\n return response.text();\n } else if (response.status === 404) {\n throw generateErrorObject({\n message: 'resource not found',\n url: url,\n status: response.status\n });\n } else { // other HTTP status (redirects are handled transparently)\n throw generateErrorObject({\n message: 'error during request',\n url: url,\n status: response.status\n });\n }\n },\n function (err) { // connection refused, etc.\n throw generateErrorObject({\n message: 'error during request',\n url: url,\n status: undefined,\n err: err\n })\n }).\n then(function (responseText) {\n if (webfinger.__isValidJSON(responseText)) {\n return responseText;\n } else {\n throw generateErrorObject({\n message: 'invalid json',\n url: url,\n status: undefined\n });\n }\n });\n\n var timeoutPromise = new Promise(function (resolve, reject) {\n setTimeout(function () {\n reject(generateErrorObject({\n message: 'request timed out',\n url: url,\n status: undefined\n }));\n if (abortController) {\n abortController.abort();\n }\n }, webfinger.config.request_timeout);\n });\n\n Promise.race([networkPromise, timeoutPromise]).\n then(function (responseText) {\n sucessHandler(responseText);\n }).catch(function (err) {\n errorHandler(err);\n });\n };\n WebFinger.prototype.__fetchJRD_XHR = function (url, errorHandler, sucessHandler) {\n var self = this;\n var handlerSpent = false;\n var xhr = new XMLHttpRequest();\n\n function __processState() {\n if (handlerSpent){\n return;\n }else{\n handlerSpent = true;\n }\n\n if (xhr.status === 200) {\n if (self.__isValidJSON(xhr.responseText)) {\n return sucessHandler(xhr.responseText);\n } else {\n return errorHandler(generateErrorObject({\n message: 'invalid json',\n url: url,\n status: xhr.status\n }));\n }\n } else if (xhr.status === 404) {\n return errorHandler(generateErrorObject({\n message: 'resource not found',\n url: url,\n status: xhr.status\n }));\n } else if ((xhr.status >= 301) && (xhr.status <= 302)) {\n var location = xhr.getResponseHeader('Location');\n if (isSecure(location)) {\n return __makeRequest(location); // follow redirect\n } else {\n return errorHandler(generateErrorObject({\n message: 'no redirect URL found',\n url: url,\n status: xhr.status\n }));\n }\n } else {\n return errorHandler(generateErrorObject({\n message: 'error during request',\n url: url,\n status: xhr.status\n }));\n }\n }\n\n function __makeRequest() {\n xhr.onreadystatechange = function () {\n if (xhr.readyState === 4) {\n __processState();\n }\n };\n\n xhr.onload = function () {\n __processState();\n };\n\n xhr.ontimeout = function () {\n return errorHandler(generateErrorObject({\n message: 'request timed out',\n url: url,\n status: xhr.status\n }));\n };\n\n xhr.open('GET', url, true);\n xhr.timeout = self.config.request_timeout;\n xhr.setRequestHeader('Accept', 'application/jrd+json, application/json');\n xhr.send();\n }\n\n return __makeRequest();\n };\n\n WebFinger.prototype.__isValidJSON = function (str) {\n try {\n JSON.parse(str);\n } catch (e) {\n return false;\n }\n return true;\n };\n\n WebFinger.prototype.__isLocalhost = function (host) {\n var local = /^localhost(\\.localdomain)?(\\:[0-9]+)?$/;\n return local.test(host);\n };\n\n // processes JRD object as if it's a webfinger response object\n // looks for known properties and adds them to profile datat struct.\n WebFinger.prototype.__processJRD = function (URL, JRD, errorHandler, successHandler) {\n var parsedJRD = JSON.parse(JRD);\n if ((typeof parsedJRD !== 'object') ||\n (typeof parsedJRD.links !== 'object')) {\n if (typeof parsedJRD.error !== 'undefined') {\n return errorHandler(generateErrorObject({ message: parsedJRD.error, request: URL }));\n } else {\n return errorHandler(generateErrorObject({ message: 'unknown response from server', request: URL }));\n }\n }\n\n var links = parsedJRD.links;\n if (!Array.isArray(links)) {\n links = [];\n }\n var result = { // webfinger JRD - object, json, and our own indexing\n object: parsedJRD,\n json: JRD,\n idx: {}\n };\n\n result.idx.properties = {\n 'name': undefined\n };\n result.idx.links = JSON.parse(JSON.stringify(LINK_PROPERTIES));\n\n // process links\n links.map(function (link, i) {\n if (LINK_URI_MAPS.hasOwnProperty(link.rel)) {\n if (result.idx.links[LINK_URI_MAPS[link.rel]]) {\n var entry = {};\n Object.keys(link).map(function (item, n) {\n entry[item] = link[item];\n });\n result.idx.links[LINK_URI_MAPS[link.rel]].push(entry);\n }\n }\n });\n\n // process properties\n var props = JSON.parse(JRD).properties;\n for (var key in props) {\n if (props.hasOwnProperty(key)) {\n if (key === 'http://packetizer.com/ns/name') {\n result.idx.properties.name = props[key];\n }\n }\n }\n return successHandler(result);\n };\n\n WebFinger.prototype.lookup = function (address, cb) {\n if (typeof address !== 'string') {\n throw new Error('first parameter must be a user address');\n } else if (typeof cb !== 'function') {\n throw new Error('second parameter must be a callback');\n }\n\n var self = this;\n var host = '';\n if (address.indexOf('://') > -1) {\n // other uri format\n host = address.replace(/ /g,'').split('/')[2];\n } else {\n // useraddress\n host = address.replace(/ /g,'').split('@')[1];\n }\n var uri_index = 0; // track which URIS we've tried already\n var protocol = 'https'; // we use https by default\n\n if (self.__isLocalhost(host)) {\n protocol = 'http';\n }\n\n function __buildURL() {\n var uri = '';\n if (! address.split('://')[1]) {\n // the URI has not been defined, default to acct\n uri = 'acct:';\n }\n return protocol + '://' + host + '/.well-known/' +\n URIS[uri_index] + '?resource=' + uri + address;\n }\n\n // control flow for failures, what to do in various cases, etc.\n function __fallbackChecks(err) {\n if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try\n uri_index = uri_index + 1;\n return __call();\n } else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http\n uri_index = 0;\n protocol = 'http';\n return __call();\n } else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt\n uri_index = 0;\n protocol = 'http';\n host = 'webfist.org';\n // webfist will\n // 1. make a query to the webfist server for the users account\n // 2. from the response, get a link to the actual webfinger json data\n // (stored somewhere in control of the user)\n // 3. make a request to that url and get the json\n // 4. process it like a normal webfinger response\n var URL = __buildURL();\n self.__fetchJRD(URL, cb, function (data) { // get link to users JRD\n self.__processJRD(URL, data, cb, function (result) {\n if ((typeof result.idx.links.webfist === 'object') &&\n (typeof result.idx.links.webfist[0].href === 'string')) {\n self.__fetchJRD(result.idx.links.webfist[0].href, cb, function (JRD) {\n self.__processJRD(URL, JRD, cb, function (result) {\n return cb(null, cb);\n });\n });\n }\n });\n });\n } else {\n return cb(err);\n }\n }\n\n function __call() {\n // make request\n var URL = __buildURL();\n self.__fetchJRD(URL, __fallbackChecks, function (JRD) {\n self.__processJRD(URL, JRD, cb, function (result) { cb(null, result); });\n });\n }\n\n return setTimeout(__call, 0);\n };\n\n WebFinger.prototype.lookupLink = function (address, rel, cb) {\n if (LINK_PROPERTIES.hasOwnProperty(rel)) {\n this.lookup(address, function (err, p) {\n var links = p.idx.links[rel];\n if (err) {\n return cb(err);\n } else if (links.length === 0) {\n return cb('no links found with rel=\"' + rel + '\"');\n } else {\n return cb(null, links[0]);\n }\n });\n } else {\n return cb('unsupported rel ' + rel);\n }\n };\n\n\n\n // AMD support\n if (typeof define === 'function' && define.amd) {\n define([], function () { return WebFinger; });\n // CommonJS and Node.js module support.\n } else if (typeof exports !== 'undefined') {\n // Support Node.js specific `module.exports` (which can be a function)\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = WebFinger;\n }\n // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)\n exports.WebFinger = WebFinger;\n } else {\n // browser