From 1d71a78cd9109b9b17a2fc0935ade9b52df0bb1c Mon Sep 17 00:00:00 2001 From: Ilya Kreymer Date: Tue, 20 Jun 2023 11:24:04 -0700 Subject: [PATCH] fix redirect loop (fixes #184): - loading: fix redirect loop on 404s (via wabac.js 2.16.2) - misc: additional check before autoupdate, update build deps to support Node 20 bump to 1.8.2 --- CHANGES.md | 4 ++++ _data/package.json | 8 ++++---- package.json | 8 ++++---- src/coll.js | 2 +- sw.js | 2 +- ui.js | 6 +++--- yarn.lock | 30 ++++++++++++------------------ 7 files changed, 29 insertions(+), 31 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 848fa924..ffe3ca68 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,9 @@ ## CHANGES +v1.8.2 +- Loading: fix redirect loop on 404s (via wabac.js 2.16.2) +- Misc: additional check before autoupdate, update build deps to support Node 20 + v1.8.1 - Loading: Resolve sourceUrl to absolute url when computing default id diff --git a/_data/package.json b/_data/package.json index 75a3be2c..3be035fb 100644 --- a/_data/package.json +++ b/_data/package.json @@ -1,7 +1,7 @@ { "name": "replaywebpage", "productName": "ReplayWeb.page", - "version": "1.8.1", + "version": "1.8.2", "description": "Serverless Web Archive Replay", "repository": "https://github.com/webrecorder/replayweb.page", "homepage": "https://replayweb.page/", @@ -9,7 +9,7 @@ "license": "AGPL-3.0-or-later", "dependencies": { "@fortawesome/fontawesome-free": "^5.15.4", - "@webrecorder/wabac": "^2.16.1", + "@webrecorder/wabac": "^2.16.2", "bulma": "^0.9.3", "electron-log": "^4.4.1", "electron-updater": "^5.3.0", @@ -36,9 +36,9 @@ "eslint": "^8.23.1", "http-server": "^13.0.2", "mini-css-extract-plugin": "^2.3.0", - "node-sass": "^8.0.0", + "node-sass": "^9.0.0", "raw-loader": "^4.0.2", - "sass-loader": "^12.1.0", + "sass-loader": "^13.3.2", "style-loader": "^3.2.1", "svg-inline-loader": "^0.8.2", "webpack": "^5.75.0", diff --git a/package.json b/package.json index 75a3be2c..3be035fb 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "replaywebpage", "productName": "ReplayWeb.page", - "version": "1.8.1", + "version": "1.8.2", "description": "Serverless Web Archive Replay", "repository": "https://github.com/webrecorder/replayweb.page", "homepage": "https://replayweb.page/", @@ -9,7 +9,7 @@ "license": "AGPL-3.0-or-later", "dependencies": { "@fortawesome/fontawesome-free": "^5.15.4", - "@webrecorder/wabac": "^2.16.1", + "@webrecorder/wabac": "^2.16.2", "bulma": "^0.9.3", "electron-log": "^4.4.1", "electron-updater": "^5.3.0", @@ -36,9 +36,9 @@ "eslint": "^8.23.1", "http-server": "^13.0.2", "mini-css-extract-plugin": "^2.3.0", - "node-sass": "^8.0.0", + "node-sass": "^9.0.0", "raw-loader": "^4.0.2", - "sass-loader": "^12.1.0", + "sass-loader": "^13.3.2", "style-loader": "^3.2.1", "svg-inline-loader": "^0.8.2", "webpack": "^5.75.0", diff --git a/src/coll.js b/src/coll.js index 7cc345fb..742cc879 100644 --- a/src/coll.js +++ b/src/coll.js @@ -149,7 +149,7 @@ class Coll extends LitElement async runUpdateLoop() { try { // only autoupdate if interval is set, and number of pages < 100 to avoid messing up scrolling - while (this.editable && this.autoUpdateInterval && (!this.collInfo || this.collInfo.pages.length < 100)) { + while (this.editable && this.autoUpdateInterval && (!this.collInfo || !this.collInfo.pages || this.collInfo.pages.length < 100)) { await new Promise(resolve => setTimeout(resolve, this.autoUpdateInterval * 1000)); await this.doUpdateInfo(true); } diff --git a/sw.js b/sw.js index 492b125e..1c6657df 100644 --- a/sw.js +++ b/sw.js @@ -118,4 +118,4 @@ var ff=function(t,e){return ff=Object.setPrototypeOf||{__proto__:[]}instanceof A * SOFTWARE. * */ -const Wg="crypto.algorithm";const jg="crypto.algorithmProvider";var zg;Uf.registerSingleton(jg,class{getAlgorithms(){return Uf.resolveAll(Wg)}toAsnAlgorithm(t){for(const e of this.getAlgorithms()){const r=e.toAsnAlgorithm(t);if(r)return r}if(/[0-9.]+/.test(t.name)){const e=new Oh({algorithm:t.name});if("parameters"in t){const r=t;e.parameters=r.parameters}return e}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(t){for(const e of this.getAlgorithms()){const r=e.toWebAlgorithm(t);if(r)return r}return{name:t.algorithm,parameters:t.parameters}}});const Gg="1.3.36.3.3.2.8.1.1",qg=`${Gg}.1`,Qg=`${Gg}.2`,Vg=`${Gg}.3`,Kg=`${Gg}.4`,Yg=`${Gg}.5`,Jg=`${Gg}.6`,Xg=`${Gg}.7`,Zg=`${Gg}.8`,$g=`${Gg}.9`,tw=`${Gg}.10`,ew=`${Gg}.11`,rw=`${Gg}.12`,iw=`${Gg}.13`,nw=`${Gg}.14`,sw="brainpoolP160r1",ow="brainpoolP160t1",aw="brainpoolP192r1",cw="brainpoolP192t1",lw="brainpoolP224r1",uw="brainpoolP224t1",hw="brainpoolP256r1",pw="brainpoolP256t1",dw="brainpoolP320r1",fw="brainpoolP320t1",gw="brainpoolP384r1",ww="brainpoolP384t1",yw="brainpoolP512r1",mw="brainpoolP512t1",bw="ECDSA";let Aw=zg=class{toAsnAlgorithm(t){if(t.name.toLowerCase()===bw.toLowerCase())if("hash"in t){switch(("string"==typeof t.hash?t.hash:t.hash.name).toLowerCase()){case"sha-1":return Sd;case"sha-256":return Id;case"sha-384":return Cd;case"sha-512":return Rd}}else if("namedCurve"in t){let e="";switch(t.namedCurve){case"P-256":e=Ed;break;case"K-256":e=zg.SECP256K1;break;case"P-384":e=_d;break;case"P-521":e=vd;break;case sw:e=qg;break;case ow:e=Qg;break;case aw:e=Vg;break;case cw:e=Kg;break;case lw:e=Yg;break;case uw:e=Jg;break;case hw:e=Xg;break;case pw:e=Zg;break;case dw:e=$g;break;case fw:e=tw;break;case gw:e=ew;break;case ww:e=rw;break;case yw:e=iw;break;case mw:e=nw}if(e)return new Oh({algorithm:gd,parameters:Kl.serialize(new xd({namedCurve:e}))})}return null}toWebAlgorithm(t){switch(t.algorithm){case wd:return{name:bw,hash:{name:"SHA-1"}};case md:return{name:bw,hash:{name:"SHA-256"}};case bd:return{name:bw,hash:{name:"SHA-384"}};case Ad:return{name:bw,hash:{name:"SHA-512"}};case gd:if(!t.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Kl.parse(t.parameters,xd).namedCurve){case Ed:return{name:bw,namedCurve:"P-256"};case zg.SECP256K1:return{name:bw,namedCurve:"K-256"};case _d:return{name:bw,namedCurve:"P-384"};case vd:return{name:bw,namedCurve:"P-521"};case qg:return{name:bw,namedCurve:sw};case Qg:return{name:bw,namedCurve:ow};case Vg:return{name:bw,namedCurve:aw};case Kg:return{name:bw,namedCurve:cw};case Yg:return{name:bw,namedCurve:lw};case Jg:return{name:bw,namedCurve:uw};case Xg:return{name:bw,namedCurve:hw};case Zg:return{name:bw,namedCurve:pw};case $g:return{name:bw,namedCurve:dw};case tw:return{name:bw,namedCurve:fw};case ew:return{name:bw,namedCurve:gw};case rw:return{name:bw,namedCurve:ww};case iw:return{name:bw,namedCurve:yw};case nw:return{name:bw,namedCurve:mw}}}return null}};Aw.SECP256K1="1.3.132.0.10",Aw=zg=hf([Ff()],Aw),Uf.registerSingleton(Wg,Aw);const Ew=Symbol("name"),_w=Symbol("value");class vw{constructor(t,e={},r=""){this[Ew]=t,this[_w]=r;for(const t in e)this[t]=e[t]}}vw.NAME=Ew,vw.VALUE=_w;class Tw{static toString(t){const e=this.items[t];return e||t}}Tw.items={[Qd]:"sha1",[Vd]:"sha224",[Kd]:"sha256",[Yd]:"sha384",[Jd]:"sha512",[Bd]:"rsaEncryption",[Fd]:"sha1WithRSAEncryption",[Hd]:"sha224WithRSAEncryption",[Wd]:"sha256WithRSAEncryption",[jd]:"sha384WithRSAEncryption",[zd]:"sha512WithRSAEncryption",[gd]:"ecPublicKey",[wd]:"ecdsaWithSHA1",[yd]:"ecdsaWithSHA224",[md]:"ecdsaWithSHA256",[bd]:"ecdsaWithSHA384",[Ad]:"ecdsaWithSHA512",[Ju]:"TLS WWW server authentication",[Xu]:"TLS WWW client authentication",[Zu]:"Code Signing",[$u]:"E-mail Protection",[th]:"Time Stamping",[eh]:"OCSP Signing","1.2.840.113549.1.7.2":"Signed Data"};class Sw{static serialize(t){return this.serializeObj(t).join("\n")}static pad(t=0){return"".padStart(2*t," ")}static serializeObj(t,e=0){const r=[];let i=this.pad(e++),n="";const s=t[vw.VALUE];s&&(n=` ${s}`),r.push(`${i}${t[vw.NAME]}:${n}`),i=this.pad(e);for(const n in t){if("symbol"==typeof n)continue;const s=t[n],o=n?`${n}: `:"";if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)r.push(`${i}${o}${s}`);else if(s instanceof Date)r.push(`${i}${o}${s.toUTCString()}`);else if(Array.isArray(s))for(const t of s)t[vw.NAME]=n,r.push(...this.serializeObj(t,e));else if(s instanceof vw)s[vw.NAME]=n,r.push(...this.serializeObj(s,e));else if(Ko.vJ.isBufferSource(s))n?(r.push(`${i}${o}`),r.push(...this.serializeBufferSource(s,e+1))):r.push(...this.serializeBufferSource(s,e));else{if(!("toTextObject"in s))throw new TypeError("Cannot serialize data in text format. Unsupported type.");{const t=s.toTextObject();t[vw.NAME]=n,r.push(...this.serializeObj(t,e))}}}return r}static serializeBufferSource(t,e=0){const r=this.pad(e),i=Ko.vJ.toUint8Array(t),n=[];for(let t=0;t255)return!1}return!0}getField(t){const e=this.extraNames.findId(t)||Bw.findId(t),r=[];for(const t of this.asn)for(const i of t)i.type===e&&r.push(i.value.toString());return r}getName(t){return this.extraNames.get(t)||Bw.get(t)}toString(){return this.asn.map((t=>t.map((t=>{const e=this.getName(t.type)||t.type,r=t.value.anyValue?`#${Ko.ep.ToHex(t.value.anyValue)}`:function(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,Dw)}(t.value.toString());return`${e}=${r}`})).join("+"))).join(", ")}toJSON(){var t;const e=[];for(const r of this.asn){const i={};for(const e of r){const r=this.getName(e.type)||e.type;null!==(t=i[r])&&void 0!==t||(i[r]=[]),i[r].push(e.value.anyValue?`#${Ko.ep.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(i)}return e}fromString(t){const e=new ou,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let i=null,n=",";for(;i=r.exec(`${t},`);){let[,t,r]=i;const s=r[r.length-1];","!==s&&"+"!==s||(r=r.slice(0,r.length-1),i[3]=s);const o=i[3];if(/[\d.]+/.test(t)||(t=this.getName(t)||""),!t)throw new Error(`Cannot get OID for name type '${t}'`);const a=new iu({type:t});if("#"===r.charAt(0))a.value.anyValue=Ko.ep.FromHex(r.slice(1));else{const e=/"(.*?[^\\])?"/.exec(r);e&&(r=e[1]),r=r.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1"),t===this.getName("E")||t===this.getName("DC")?a.value.ia5String=r:Lw.isASCII(r)?a.value.printableString=r:a.value.utf8String=r}"+"===n?e[e.length-1].push(a):e.push(new nu([a])),n=o}return e}fromJSON(t){const e=new ou;for(const r of t){const t=new nu;for(const e in r){let i=e;if(/[\d.]+/.test(e)||(i=this.getName(e)||""),!i)throw new Error(`Cannot get OID for name type '${e}'`);const n=r[e];for(const e of n){const r=new iu({type:i});if("object"==typeof e)for(const t in e)switch(t){case"ia5String":r.value.ia5String=e[t];break;case"utf8String":r.value.utf8String=e[t];break;case"universalString":r.value.universalString=e[t];break;case"bmpString":r.value.bmpString=e[t];break;case"printableString":r.value.printableString=e[t]}else"#"===e[0]?r.value.anyValue=Ko.ep.FromHex(e.slice(1)):i===this.getName("E")||i===this.getName("DC")?r.value.ia5String=e:r.value.printableString=e;t.push(r)}}e.push(t)}return e}toArrayBuffer(){return Kl.serialize(this.asn)}async getThumbprint(...t){var e;let r,i="SHA-1";return t.length>=1&&!(null===(e=t[0])||void 0===e?void 0:e.subtle)?(i=t[0]||i,r=t[1]||Nw.get()):r=t[0]||Nw.get(),await r.subtle.digest(i,this.toArrayBuffer())}}const Pw="Cannot initialize GeneralName from ASN.1 data.",Uw=`${Pw} Unsupported string format in use.`,Mw=`${Pw} Value doesn't match to GUID regular expression.`,Fw=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Hw="1.3.6.1.4.1.311.25.1",Ww="1.3.6.1.4.1.311.20.2.3",jw="dns",zw="dn",Gw="email",qw="ip",Qw="url",Vw="guid",Kw="upn",Yw="id";class Jw extends Iw{constructor(...t){let e;if(2===t.length)switch(t[0]){case zw:{const r=new Lw(t[1]).toArrayBuffer(),i=Kl.parse(r,ou);e=new uu({directoryName:i});break}case jw:e=new uu({dNSName:t[1]});break;case Gw:e=new uu({rfc822Name:t[1]});break;case Vw:{const r=new RegExp(Fw,"i").exec(t[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const i=r.slice(1).map(((t,e)=>e<3?Ko.ep.ToHex(new Uint8Array(Ko.ep.FromHex(t)).reverse()):t)).join("");e=new uu({otherName:new cu({typeId:Hw,value:Kl.serialize(new hl(Ko.ep.FromHex(i)))})});break}case qw:e=new uu({iPAddress:t[1]});break;case Yw:e=new uu({registeredID:t[1]});break;case Kw:e=new uu({otherName:new cu({typeId:Ww,value:Kl.serialize(_l.toASN(t[1]))})});break;case Qw:e=new uu({uniformResourceIdentifier:t[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else e=Ko.vJ.isBufferSource(t[0])?Kl.parse(t[0],uu):t[0];super(e)}onInit(t){if(null!=t.dNSName)this.type=jw,this.value=t.dNSName;else if(null!=t.rfc822Name)this.type=Gw,this.value=t.rfc822Name;else if(null!=t.iPAddress)this.type=qw,this.value=t.iPAddress;else if(null!=t.uniformResourceIdentifier)this.type=Qw,this.value=t.uniformResourceIdentifier;else if(null!=t.registeredID)this.type=Yw,this.value=t.registeredID;else if(null!=t.directoryName)this.type=zw,this.value=new Lw(t.directoryName).toString();else{if(null==t.otherName)throw new Error(Uw);if(t.otherName.typeId===Hw){this.type=Vw;const e=Kl.parse(t.otherName.value,hl),r=new RegExp(Fw,"i").exec(Ko.ep.ToHex(e));if(!r)throw new Error(Mw);this.value=r.slice(1).map(((t,e)=>e<3?Ko.ep.ToHex(new Uint8Array(Ko.ep.FromHex(t)).reverse()):t)).join("-")}else{if(t.otherName.typeId!==Ww)throw new Error(Uw);this.type=Kw,this.value=Kl.parse(t.otherName.value,eu).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let t;switch(this.type){case zw:case jw:case Vw:case qw:case Yw:case Kw:case Qw:t=this.type.toUpperCase();break;case Gw:t="Email";break;default:throw new Error("Unsupported GeneralName type")}let e=this.value;return this.type===Yw&&(e=Tw.toString(e)),new vw(t,void 0,e)}}class Xw extends Iw{constructor(t){let e;if(t instanceof _u)e=t;else if(Array.isArray(t)){const r=[];for(const e of t)if(e instanceof uu)r.push(e);else{const t=Kl.parse(new Jw(e.type,e.value).rawData,uu);r.push(t)}e=new _u(r)}else{if(!Ko.vJ.isBufferSource(t))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");e=Kl.parse(t,_u)}super(e)}onInit(t){const e=[];for(const r of t){let t=null;try{t=new Jw(r)}catch{continue}e.push(t)}this.items=e}toJSON(){return this.items.map((t=>t.toJSON()))}toTextObject(){const t=super.toTextObjectEmpty();for(const e of this.items){const r=e.toTextObject();let i=t[r[vw.NAME]];Array.isArray(i)||(i=[],t[r[vw.NAME]]=i),i.push(r)}return t}}Xw.NAME="GeneralNames";const Zw="\\n",$w="-{5}BEGIN ([^\\n]+(?=-{5}))-{5}\\n(?:((?:[^:\\n]+: (?:[^\\n]+\\n(?: +[^\\n]+\\n)*))+))?\\n?((?:[a-zA-Z0-9=+/]+\\n)+)-{5}END \\1-{5}";class ty{static isPem(t){return"string"==typeof t&&new RegExp($w,"g").test(t)}static decodeWithHeaders(t){t=t.replace(/\r/g,"");const e=new RegExp($w,"g"),r=[];let i=null;for(;i=e.exec(t);){const t=i[3].replace(new RegExp("[\\n]+","g"),""),e={type:i[1],headers:[],rawData:Ko.ep.FromBase64(t)},n=i[2];if(n){const t=n.split(new RegExp(Zw,"g"));let r=null;for(const i of t){const[t,n]=i.split(/:(.*)/);if(void 0===n){if(!r)throw new Error("Cannot parse PEM string. Incorrect header value");r.value+=t.trim()}else r&&e.headers.push(r),r={key:t,value:n.trim()}}r&&e.headers.push(r)}r.push(e)}return r}static decode(t){return this.decodeWithHeaders(t).map((t=>t.rawData))}static decodeFirst(t){const e=this.decode(t);if(!e.length)throw new RangeError("PEM string doesn't contain any objects");return e[0]}static encode(t,e){if(Array.isArray(t)){const r=new Array;return e?t.forEach((t=>{if(!Ko.vJ.isBufferSource(t))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:e,rawData:Ko.vJ.toArrayBuffer(t)}))})):t.forEach((t=>{if(!("type"in t))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(t))})),r.join("\n")}if(!e)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:e,rawData:Ko.vJ.toArrayBuffer(t)})}static encodeStruct(t){var e;const r=t.type.toLocaleUpperCase(),i=[];if(i.push(`-----BEGIN ${r}-----`),null===(e=t.headers)||void 0===e?void 0:e.length){for(const e of t.headers)i.push(`${e.key}: ${e.value}`);i.push("")}const n=Ko.ep.ToBase64(t.rawData);let s,o=0;const a=Array();for(;o1?(i=t[0]||i,r=t[1]||r,e=t[2]||Nw.get()):e=t[0]||Nw.get(),e.subtle.importKey("spki",this.rawData,i,!0,r)}onInit(t){const e=Uf.resolve(jg),r=this.algorithm=e.toWebAlgorithm(t.algorithm);switch(t.algorithm.algorithm){case Bd:{const e=Kl.parse(t.subjectPublicKey,uf),i=Ko.vJ.toUint8Array(e.modulus);r.publicExponent=Ko.vJ.toUint8Array(e.publicExponent),r.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3;break}}}async getThumbprint(...t){var e;let r,i="SHA-1";return t.length>=1&&!(null===(e=t[0])||void 0===e?void 0:e.subtle)?(i=t[0]||i,r=t[1]||Nw.get()):r=t[0]||Nw.get(),await r.subtle.digest(i,this.rawData)}async getKeyIdentifier(t){t||(t=Nw.get());const e=Kl.parse(this.rawData,kh);return await t.subtle.digest("SHA-1",e.subjectPublicKey)}toTextObject(){const t=this.toTextObjectEmpty(),e=Kl.parse(this.rawData,kh);if(t.Algorithm=Sw.serializeAlgorithm(e.algorithm),e.algorithm.algorithm===gd)t["EC Point"]=e.subjectPublicKey;else t["Raw Data"]=e.subjectPublicKey;return t}}class iy{static register(t,e){this.items.set(t,e)}static create(t){const e=new Cw(t),r=this.items.get(e.type);return r?new r(t):e}}iy.items=new Map;const ny="crypto.signatureFormatter";class sy extends ey{constructor(t){ey.isAsnEncoded(t)?super(t,Wh):super(t),this.tag=ty.CertificateTag}onInit(t){const e=t.tbsCertificate;this.tbs=Kl.serialize(e),this.serialNumber=Ko.ep.ToHex(e.serialNumber),this.subjectName=new Lw(e.subject),this.subject=new Lw(e.subject).toString(),this.issuerName=new Lw(e.issuer),this.issuer=this.issuerName.toString();const r=Uf.resolve(jg);this.signatureAlgorithm=r.toWebAlgorithm(t.signatureAlgorithm),this.signature=t.signatureValue;const i=e.validity.notBefore.utcTime||e.validity.notBefore.generalTime;if(!i)throw new Error("Cannot get 'notBefore' value");this.notBefore=i;const n=e.validity.notAfter.utcTime||e.validity.notAfter.generalTime;if(!n)throw new Error("Cannot get 'notAfter' value");this.notAfter=n,this.extensions=[],e.extensions&&(this.extensions=e.extensions.map((t=>iy.create(Kl.serialize(t))))),this.publicKey=new ry(e.subjectPublicKeyInfo)}getExtension(t){for(const e of this.extensions)if("string"==typeof t){if(e.type===t)return e}else if(e instanceof t)return e;return null}getExtensions(t){return this.extensions.filter((e=>"string"==typeof t?e.type===t:e instanceof t))}async verify(t={},e=Nw.get()){let r,i;const n=t.publicKey;try{if(n)if("publicKey"in n)r={...n.publicKey.algorithm,...this.signatureAlgorithm},i=await n.publicKey.export(r,["verify"]);else if(n instanceof ry)r={...n.algorithm,...this.signatureAlgorithm},i=await n.export(r,["verify"]);else if(Ko.vJ.isBufferSource(n)){const t=new ry(n);r={...t.algorithm,...this.signatureAlgorithm},i=await t.export(r,["verify"])}else r={...n.algorithm,...this.signatureAlgorithm},i=n;else r={...this.publicKey.algorithm,...this.signatureAlgorithm},i=await this.publicKey.export(r,["verify"],e)}catch(t){return!1}const s=Uf.resolveAll(ny).reverse();let o=null;for(const t of s)if(o=t.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const a=await e.subtle.verify(this.signatureAlgorithm,i,o,this.tbs);if(t.signatureOnly)return a;{const e=(t.date||new Date).getTime();return a&&this.notBefore.getTime()t))}else{const e=new Yu(t[0]);super(Ku,t[1],Kl.serialize(e)),this.usages=t[0]}}toTextObject(){const t=this.toTextObjectWithoutValue();return t[""]=this.usages.map((t=>Tw.toString(t))).join(", "),t}}uy.NAME="Extended Key Usages",function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"}(ly||(ly={}));class hy extends Cw{constructor(...t){if(Ko.vJ.isBufferSource(t[0])){super(t[0]);const e=Kl.parse(this.value,lh);this.usages=e.toNumber()}else{const e=new lh(t[0]);super(oh,t[1],Kl.serialize(e)),this.usages=t[0]}}toTextObject(){const t=this.toTextObjectWithoutValue(),e=Kl.parse(this.value,lh);return t[""]=e.toJSON().join(", "),t}}hy.NAME="Key Usages";class py extends Cw{constructor(...t){if(Ko.vJ.isBufferSource(t[0])){super(t[0]);const e=Kl.parse(this.value,Th);this.keyId=Ko.ep.ToHex(e)}else{const e="string"==typeof t[0]?Ko.ep.FromHex(t[0]):t[0],r=new Th(e);super(vh,t[1],Kl.serialize(r)),this.keyId=Ko.ep.ToHex(e)}}static async create(t,e=!1,r=Nw.get()){let i;i=t instanceof ry?t.rawData:"publicKey"in t?t.publicKey.rawData:Ko.vJ.isBufferSource(t)?t:await r.subtle.exportKey("spki",t);const n=new ry(i),s=await n.getKeyIdentifier(r);return new py(Ko.ep.ToHex(s),e)}toTextObject(){const t=this.toTextObjectWithoutValue(),e=Kl.parse(this.value,Th);return t[""]=e,t}}py.NAME="Subject Key Identifier";class dy extends Cw{constructor(...t){Ko.vJ.isBufferSource(t[0])?super(t[0]):super(mh,t[1],new Xw(t[0]||[]).rawData)}onInit(t){super.onInit(t);const e=Kl.parse(t.extnValue,bh);this.names=new Xw(e)}toTextObject(){const t=this.toTextObjectWithoutValue(),e=this.names.toTextObject();for(const r in e)t[r]=e[r];return t}}dy.NAME="Subject Alternative Name";class fy extends Cw{constructor(...t){var e;if(Ko.vJ.isBufferSource(t[0])){super(t[0]);const e=Kl.parse(this.value,Bu);this.policies=e.map((t=>t.policyIdentifier))}else{const r=t[0],i=null!==(e=t[1])&&void 0!==e&&e,n=new Bu(r.map((t=>new ku({policyIdentifier:t}))));super(Iu,i,Kl.serialize(n)),this.policies=r}}toTextObject(){const t=this.toTextObjectWithoutValue();return t.Policy=this.policies.map((t=>new vw("",{},Tw.toString(t)))),t}}fy.NAME="Certificate Policies",iy.register(Iu,fy);class gy extends Iw{constructor(...t){let e;if(Ko.vJ.isBufferSource(t[0]))e=Ko.vJ.toArrayBuffer(t[0]);else{const r=t[0],i=Array.isArray(t[1])?t[1].map((t=>Ko.vJ.toArrayBuffer(t))):[];e=Kl.serialize(new Ah({type:r,values:i}))}super(e,Ah)}onInit(t){this.type=t.type,this.values=t.values}toTextObject(){const t=this.toTextObjectWithoutValue();return t.Value=this.values.map((t=>new vw("",{"":t}))),t}toTextObjectWithoutValue(){const t=this.toTextObjectEmpty();return t[vw.NAME]===gy.NAME&&(t[vw.NAME]=Tw.toString(this.type)),t}}gy.NAME="Attribute";class wy extends gy{constructor(...t){var e;if(Ko.vJ.isBufferSource(t[0]))super(t[0]);else{const e=new Og({printableString:t[0]});super(pg,[Kl.serialize(e)])}null!==(e=this.password)&&void 0!==e||(this.password="")}onInit(t){if(super.onInit(t),this.values[0]){const t=Kl.parse(this.values[0],Og);this.password=t.toString()}}toTextObject(){const t=this.toTextObjectWithoutValue();return t[vw.VALUE]=this.password,t}}wy.NAME="Challenge Password";class yy extends gy{constructor(...t){var e;if(Ko.vJ.isBufferSource(t[0]))super(t[0]);else{const e=t[0],r=new Uh;for(const t of e)r.push(Kl.parse(t.rawData,Ph));super(dg,[Kl.serialize(r)])}null!==(e=this.items)&&void 0!==e||(this.items=[])}onInit(t){if(super.onInit(t),this.values[0]){const t=Kl.parse(this.values[0],Uh);this.items=t.map((t=>iy.create(Kl.serialize(t))))}}toTextObject(){const t=this.toTextObjectWithoutValue(),e=this.items.map((t=>t.toTextObject()));for(const r of e)t[r[vw.NAME]]=r;return t}}yy.NAME="Extensions";class my{static register(t,e){this.items.set(t,e)}static create(t){const e=new gy(t),r=this.items.get(e.type);return r?new r(t):e}}my.items=new Map;let by=class{toAsnAlgorithm(t){if("rsassa-pkcs1-v1_5"===t.name.toLowerCase()){if(!t.hash)return new Oh({algorithm:Bd,parameters:null});switch(t.hash.name.toLowerCase()){case"sha-1":return new Oh({algorithm:Fd,parameters:null});case"sha-256":return new Oh({algorithm:Wd,parameters:null});case"sha-384":return new Oh({algorithm:jd,parameters:null});case"sha-512":return new Oh({algorithm:zd,parameters:null})}}return null}toWebAlgorithm(t){switch(t.algorithm){case Bd:return{name:"RSASSA-PKCS1-v1_5"};case Fd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Wd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case jd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case zd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}}}return null}};by=hf([Ff()],by),Uf.registerSingleton(Wg,by);class Ay{addPadding(t,e){const r=Ko.vJ.toUint8Array(e),i=new Uint8Array(t);return i.set(r,t-r.length),i}removePadding(t,e=!1){let r=Ko.vJ.toUint8Array(t);for(let t=0;t127){const t=new Uint8Array(r.length+1);return t.set(r,1),t.buffer}return r.buffer}toAsnSignature(t,e){if("ECDSA"===t.name){const r=t.namedCurve,i=Ay.namedCurveSize.get(r)||Ay.defaultNamedCurveSize,n=new Od,s=Ko.vJ.toUint8Array(e);return n.r=this.removePadding(s.slice(0,i),!0),n.s=this.removePadding(s.slice(i,i+i),!0),Kl.serialize(n)}return null}toWebSignature(t,e){if("ECDSA"===t.name){const r=Kl.parse(e,Od),i=t.namedCurve,n=Ay.namedCurveSize.get(i)||Ay.defaultNamedCurveSize,s=this.addPadding(n,this.removePadding(r.r)),o=this.addPadding(n,this.removePadding(r.s));return(0,Ko.$e)(s,o)}return null}}Ay.namedCurveSize=new Map,Ay.defaultNamedCurveSize=32;const Ey="1.3.101.110",_y="1.3.101.111",vy="1.3.101.112",Ty="1.3.101.113";let Sy=class{toAsnAlgorithm(t){let e=null;switch(t.name.toLowerCase()){case"eddsa":switch(t.namedCurve.toLowerCase()){case"ed25519":e=vy;break;case"ed448":e=Ty}break;case"ecdh-es":switch(t.namedCurve.toLowerCase()){case"x25519":e=Ey;break;case"x448":e=_y}}return e?new Oh({algorithm:e}):null}toWebAlgorithm(t){switch(t.algorithm){case vy:return{name:"EdDSA",namedCurve:"Ed25519"};case Ty:return{name:"EdDSA",namedCurve:"Ed448"};case Ey:return{name:"ECDH-ES",namedCurve:"X25519"};case _y:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Sy=hf([Ff()],Sy),Uf.registerSingleton(Wg,Sy);class Iy extends ey{constructor(t){ey.isAsnEncoded(t)?super(t,Hg):super(t),this.tag=ty.CertificateRequestTag}onInit(t){this.tbs=Kl.serialize(t.certificationRequestInfo),this.publicKey=new ry(t.certificationRequestInfo.subjectPKInfo);const e=Uf.resolve(jg);this.signatureAlgorithm=e.toWebAlgorithm(t.signatureAlgorithm),this.signature=t.signature,this.attributes=t.certificationRequestInfo.attributes.map((t=>my.create(Kl.serialize(t))));const r=this.getAttribute(dg);this.extensions=[],r instanceof yy&&(this.extensions=r.items),this.subjectName=new Lw(t.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(t){for(const e of this.attributes)if(e.type===t)return e;return null}getAttributes(t){return this.attributes.filter((e=>e.type===t))}getExtension(t){for(const e of this.extensions)if(e.type===t)return e;return null}getExtensions(t){return this.extensions.filter((e=>e.type===t))}async verify(t=Nw.get()){const e={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(e,["verify"],t),i=Uf.resolveAll(ny).reverse();let n=null;for(const t of i)if(n=t.toWebSignature(e,this.signature),n)break;if(!n)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await t.subtle.verify(this.signatureAlgorithm,r,n,this.tbs)}toTextObject(){const t=this.toTextObjectEmpty(),e=Kl.parse(this.rawData,Hg),r=e.certificationRequestInfo,i=new vw("",{Version:`${Mh[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const t=new vw("");for(const e of this.attributes){const r=e.toTextObject();t[r[vw.NAME]]=r}i.Attributes=t}return t.Data=i,t.Signature=new vw("",{Algorithm:Sw.serializeAlgorithm(e.signatureAlgorithm),"":e.signature}),t}}Iy.NAME="PKCS#10 Certificate Request";var Cy;!function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"}(Cy||(Cy={}));iy.register(bu,ay),iy.register(Ku,uy),iy.register(oh,hy),iy.register(vh,py),iy.register(wu,oy),iy.register(mh,dy),my.register(pg,wy),my.register(dg,yy),Uf.registerSingleton(ny,class{toAsnSignature(t,e){return Ko.vJ.toArrayBuffer(e)}toWebSignature(t,e){return Ko.vJ.toArrayBuffer(e)}}),Uf.registerSingleton(ny,Ay),Ay.namedCurveSize.set("P-256",32),Ay.namedCurveSize.set("K-256",32),Ay.namedCurveSize.set("P-384",48),Ay.namedCurveSize.set("P-521",66);const Ry=/-{5}(BEGIN|END) .*-{5}/gm;async function xy({hash:t,signature:e,publicKey:r,domain:i,domainCert:n,created:s,software:o}={}){let a;const c=[];if(e=(0,Vo.toByteArray)(e),n&&i&&!r){const t=n.split("\n\n"),i=(0,Vo.toByteArray)(t[0].replace(Ry,"").replace(/\s/gm,"")),s=f(await crypto.subtle.digest("SHA-256",i));c.push({id:"certFingerprint",expected:s,matched:null});const o=new sy(i);r=await o.publicKey.export();const l=(0,Vo.fromByteArray)(new Uint8Array(o.publicKey.rawData));c.push({id:"publicKey",expected:l,matched:null}),o.subject&&o.subject.startsWith("CN=")&&(a=o.subject.split(3)),e=function(t){try{const e=ql.parse(t,Od),r=0===e.r[0]?e.r.slice(1):e.r,i=0===e.s[0]?e.s.slice(1):e.s;t=z([r,i],r.length+i.length)}catch(t){console.log(t)}return t}(e)}else{const t={name:"ECDSA",namedCurve:"P-384"};c.push({id:"publicKey",expected:r,matched:null}),r=await crypto.subtle.importKey("spki",(0,Vo.toByteArray)(r),t,!0,["verify"])}const l=new TextEncoder,u=await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},r,e,l.encode(t));return c.push({id:"signature",expected:!0,matched:u}),s&&c.push({id:"created",expected:s,matched:null}),o&&c.push({id:"software",expected:o,matched:null}),i&&c.push({id:"domain",expected:i,matched:a}),c}const Ny="pages/pages.jsonl",Oy="pages/extraPages.jsonl",ky="datapackage.json",By="datapackage-digest.json",Dy="webarchive.yaml";class Ly{constructor(t,e,r=!0){this.file=e,this.waczname=e.waczname,this.store=t,this.isRoot=r}async loadFileFromWACZ(t,e){return this.store.loadFileFromWACZ?await this.store.loadFileFromWACZ(this.file,t,e):await this.file.loadFile(t,e)}async load(){let t,e=null;return this.file.containsFile(By)&&(e=await this.loadDigestData(By)),this.file.containsFile(ky)?t=await this.loadPackage(ky,e):this.file.containsFile(Dy)&&(t=await this.loadOldPackageYAML(Dy)),t||{}}async loadTextFileFromWACZ(t,e=!1){const{reader:r,hasher:i}=await this.loadFileFromWACZ(t,{computeHash:!!e}),n=(new TextDecoder).decode(await r.readFully());return e&&i&&await this.store.addVerifyData(this.waczname,t,e,i.getHash()),n}async loadDigestData(t){try{const e=JSON.parse(await this.loadTextFileFromWACZ(t));let r;e.path===ky&&e.hash&&(r=e.hash);const i=this.store,n=this.isRoot?"":this.waczname+":";if(!e.signedData||e.signedData.hash!==r)return void await i.addVerifyData(n,"signature");await i.addVerifyData(n,"datapackageHash",r);const s=await xy(e.signedData);return await i.addVerifyDataList(n,s),r}catch(t){console.warn(t)}}async loadPackage(t,e){const r=await this.loadTextFileFromWACZ(t,e),i=JSON.parse(r);switch(this.isRoot&&void 0!==i.config&&this.store.initConfig(i.config),i.profile){case"data-package":case"wacz-package":case void 0:case null:return await this.loadLeafWACZPackage(i);case"multi-wacz-package":return await this.loadMultiWACZPackage(i);default:throw new Error(`Unknown package profile: ${i.profile}`)}}async loadMultiWACZPackage(t){return this.file.markAsMultiWACZ(),await this.store.loadWACZFiles(t,this.file),t}async loadLeafWACZPackage(t){const e=t.metadata||{};let r=null;for(const e of t.resources)e.path===Ny?(r=e.hash,await this.store.addVerifyData(this.waczname,e.path,e.hash)):(e.path.endsWith(".idx")||e.path.endsWith(".cdx"))&&await this.store.addVerifyData(this.waczname,e.path,e.hash);if(this.file.containsFile(Ny)){(await this.loadPages(Ny,r)).hasText&&(this.store.textIndex=e.textIndex=Ny)}return this.file.containsFile(Oy)&&(this.store.textIndex=e.textIndex=Oy),e}async loadOldPackageYAML(t){const e=await this.loadTextFileFromWACZ(t),r=Qo.load(e),i={desc:r.desc,title:r.title};r.textIndex&&(i.textIndex=r.textIndex,r.config||(r.config={}),r.config.textIndex=r.textIndex),this.isRoot&&void 0!==r.config&&this.store.initConfig(r.config),i.title||(i.title=this.store.config.sourceName);const n=r.pages||[];n&&n.length&&await this.store.addPages(n);const s=r.pageLists||[];return s&&s.length&&await this.store.addCuratedPageLists(s,"pages","show"),i}async loadPages(t=Ny,e=null){const{reader:r,hasher:i}=await this.loadFileFromWACZ(t,{unzip:!0,computeHash:!0});let n=null,s=[];for await(const t of r.iterLines()){const e=JSON.parse(t);this.waczname&&(e.wacz=this.waczname),n?(s.push(e),500===s.length&&(await this.store.addPages(s),s=[])):n=e}return s.length&&await this.store.addPages(s),i&&e&&await this.store.addVerifyData(this.waczname,t,e,i.getHash()),n}}class Py{constructor(t,e,r=null){this.loader=t,this.loadId=r,this.loadUrl=e.loadUrl}async load(t){t.fullConfig&&this.loader.arrayBuffer&&this.loader.arrayBuffer.byteLength<=a&&(t.fullConfig.extra||(t.fullConfig.extra={}),t.fullConfig.extra.arrayBuffer=this.loader.arrayBuffer);const e=this.loadUrl,r=this.loader;return await t.addNewWACZ({name:"default",path:e,loader:r})}}class Uy{constructor(t,e,r=null){this.config=e,this.loadId=r,this.loader=t}async load(t,e=null,r=0){const i=new jn({loader:this.loader});await i.init();const n=i.zipreader,s=new Ly(t,i),o=await s.load();let a=0;const c=(t,i,n)=>{n+=a,e&&r&&e(Math.round(100*n/r),null,n,r)};for(const e of i.iterContainedFiles()){const r=n.getCompressedSize(e);(e.endsWith(".warc.gz")||e.endsWith(".warc"))&&await this.loadWARC(t,n,e,c,r),a+=r}return o||{}}async loadWARC(t,e,r,i,n){const{reader:s}=await e.loadFile(r,{unzip:!0}),o=new si(s,null,r);return o.detectPages=!1,await o.load(t,i,n)}}class My{constructor(t){this.response=t}async load(t){return await t.loadFromJSON(this.response)}}class Fy{constructor(t,{cloneResponse:e=!1,allowBody:r=!1,hostProxyOnly:i=!1}={}){if(t=t||{},this.prefix=t.prefix||"",this.proxyPathOnly=t.proxyPathOnly||!1,this.isLive=void 0===t.isLive||t.isLive,this.archivePrefix=t.archivePrefix||"",this.cloneResponse=e,this.allowBody=r,this.hostProxy=t.hostProxy,this.hostProxy instanceof Array){const t={};for(const e of this.hostProxy)t[e.host]=e;this.hostProxy=t}this.hostProxyOnly=i}async getAllPages(){return[]}getFetchUrl(t,e,r){let i;if(this.hostProxy){i=new URL(t);const e=this.hostProxy[i.host];if(e)return r.set("X-Proxy-Host",i.host),e.prefix+(e.pathOnly?i.pathname+i.search:t)}return this.hostProxyOnly?null:this.proxyPathOnly?(i||(i=new URL(t)),this.prefix+i.pathname+i.search):this.isLive||!e.timestamp?this.prefix+t:this.prefix+this.archivePrefix+e.timestamp+"id_/"+t}async getResource(t,e){const{headers:r,credentials:i,url:n}=t.prepareProxyRequest(e,!0),s=this.getFetchUrl(n,t,r);if(!s)return null;let o=null;!this.allowBody||"POST"!==t.method&&"PUT"!==t.method||(o=await t.getBody());const a=await fetch(s,{method:t.method,body:o,headers:r,credentials:i,mode:"cors",redirect:"follow"});let c=null;this.cloneResponse&&(c=a.clone());const l=mt.fromResponse({url:n,response:a,date:new Date,noRW:!1,isLive:this.isLive});return c&&(l.clonedResponse=c),l}}const Hy=/^([\w-]+,)*[\w-]+(:\d+)?,?\)\//;class Wy extends rn{constructor(t,e,r="wacz"){super(t.dbname,t.noCache),this.config=t,this.waczfiles={},this.waczNameForHash={},this.ziploadercache={},this.updating=null,this.rootSourceType=r,this.sourceLoader=e,this.externalSource=null,this.fuzzyUrlRules=[],this.textIndex=t&&t.metadata&&t.metadata.textIndex,t.extraConfig&&this.initConfig(t.extraConfig)}initConfig(t){if(void 0!==t.decodeResponses&&(this.config.decode=t.decodeResponses),t.hostProxy&&(this.externalSource=new Fy(t,{hostProxyOnly:!0})),t.fuzzy)for(const[e,r]of t.fuzzy){const t=new RegExp(e);this.fuzzyUrlRules.push({match:t,replace:r})}t.textIndex&&(this.textIndex=t.textIndex)}updateHeaders(t){this.sourceLoader&&(this.sourceLoader.headers=t)}_initDB(t,e,r,i){super._initDB(t,e,r,i),e||(t.createObjectStore("ziplines",{keyPath:["waczname","prefix"]}),t.createObjectStore("waczfiles",{keyPath:"waczname"}),t.createObjectStore("verification",{keyPath:"id"})),2===e&&this.convertV2WACZDB(t,i),3===e&&t.createObjectStore("verification",{keyPath:"id"})}async convertV2WACZDB(t,e){try{const r=await e.objectStore("ziplines").getAll(),i=await e.objectStore("zipEntries").getAll();t.deleteObjectStore("ziplines"),t.deleteObjectStore("zipEntries"),t.createObjectStore("ziplines",{keyPath:["waczname","prefix"]}),t.createObjectStore("waczfiles",{keyPath:"waczname"}),t.createObjectStore("verification",{keyPath:"id"});const n=this.config.loadUrl;for(const t of r)t.waczname=n,e.objectStore("ziplines").put(t);const s=r.length>0?2:1,o=await this.computeHash(n),a=new jn({waczname:n,hash:o,url:n,entries:i,indexType:s});e.objectStore("waczfiles").put(a.serialize()),await e.done}catch(t){console.warn(t)}}addWACZFile(t){return this.waczfiles[t.waczname]=new jn(t),this.waczNameForHash[t.hash]=t.waczname,this.waczfiles[t.waczname]}async init(){await super.init();const t=await this.db.getAll("waczfiles")||[];for(const e of t)this.addWACZFile({...e,parent:this});for(const[t,e]of Object.entries(this.waczfiles)){e.path=e.path||t;const r=e.path.lastIndexOf("#!/");if(r>0){const t=e.path.slice(0,r),i=this.waczfiles[t];e.parent=i}else"json"!==this.rootSourceType&&(e.loader=this.sourceLoader)}await this.checkUpdates()}async close(){super.close(),caches.delete("cache:"+this.name.slice("db:".length))}async clearZipData(){const t=["waczfiles","ziplines"];for(const e of t)await this.db.clear(e)}async addVerifyData(t="",e,r,i,n=!1){let s=null;t&&(e=t+e),i&&(s=r===i,n&&console.log(`verify ${e}: ${s}`)),await this.db.put("verification",{id:e,expected:r,matched:s})}async addVerifyDataList(t,e){const r=this.db.transaction("verification","readwrite");for(const i of e)t&&(i.id=t+i.id),r.store.put(i);try{await r.done}catch(t){console.warn(t)}}async getVerifyInfo(){const t=await this.db.getAll("verification");let e=0,r=0,i={};const n=["domain","created","certFingerprint","software","datapackageHash","publicKey"];for(const s of t)n.includes(s.id)?i[s.id]=s.expected:"signature"===s.id||!0===s.matched?e++:!1===s.matched&&r++;return i.numInvalid=r,i.numValid=e,i}async getVerifyExpected(t){const e=await this.db.get("verification",t);return e&&e.expected}async clearAll(){await super.clearAll(),await this.clearZipData()}async loadRecordFromSource(t){const{start:e,length:r,path:i,wacz:n}=t.source,s={offset:e,length:r,unzip:!0,computeHash:!0},o=n,{reader:a,hasher:c}=await this.loadFileFromNamedWACZ(o,"archive/"+i,s),l=new oi(a,c);await this.waczfiles[o].save(this.db);const u=await l.load();return t[un]&&(u.respHeaders["x-wabac-preset-cookie"]=t[un]),{remote:u,hasher:c}}async loadIndex(t){if(!this.waczfiles[t])throw new Error("unknown waczfile: "+t);if(this.waczfiles[t].indexType)return{indexType:this.waczfiles[t].indexType,isNew:!1};let e=0;for(const r of this.waczfiles[t].iterContainedFiles())r.endsWith(".cdx")||r.endsWith(".cdxj")?(console.log(`Loading CDX for ${t}`),await this.loadCDX(r,t),e=1):r.endsWith(".idx")&&(console.log(`Loading IDX for ${t}`),await this.loadIDX(r,t),e=2);return this.waczfiles[t].indexType=e,await this.waczfiles[t].save(this.db,!0),{indexType:e,isNew:!0}}async loadCDX(t,e,r,i){const{reader:n,hasher:s}=await this.loadFileFromNamedWACZ(e,t,{computeHash:!0}),o=new pn(n,null,e,{wacz:e}),a=await o.load(this,r,i);if(s){const r=await this.getVerifyExpected(t);r&&this.addVerifyData(e,t,r,s.getHash())}return a}async loadIDX(t,e,r,i){const{reader:n,hasher:s}=await this.loadFileFromNamedWACZ(e,t,{computeHash:!0});let o=[],a="",c=!0,l=0;for await(const t of n.iterLines()){if(l+=t.length,l===t.length&&t.startsWith("!meta")){const e=t.indexOf(" {");if(e<0){console.warn("Invalid Meta Line: "+t);continue}const r=JSON.parse(t.slice(e));r.filename&&(a=r.filename),"cdxj-gzip-1.0"!==r.format&&console.log(`Unknown CDXJ format "${r.format}", archive may not parse correctly`);continue}let n;if(t.indexOf("\t")>0){let[r,i,s,o]=t.split("\t");s=Number(s),o=Number(o),n={waczname:e,prefix:r,filename:i,offset:s,length:o,loaded:!1},c=!1}else{const r=t.indexOf(" {");if(r<0){console.log("Invalid Index Line: "+t);continue}const i=t.slice(0,r);let{offset:s,length:o,filename:l,digest:u}=JSON.parse(t.slice(r));c=c&&!Hy.test(i),l=l||a,n={waczname:e,prefix:i,filename:l,offset:s,length:o,digest:u,loaded:!1}}r&&r(l/i,l,i),o.push(n)}if(s){const r=await this.getVerifyExpected(t);r&&this.addVerifyData(e,t,r,s.getHash())}const u=this.db.transaction("ziplines","readwrite");for(const t of o)u.store.put(t);try{await u.done}catch(t){console.log("Error loading ziplines index: ",t)}c&&c!==this.waczfiles[e].nonSurt&&(this.waczfiles[e].nonSurt=c,await this.waczfiles[e].save(this.db,!0))}async loadCDXFromIDX(t,e,r=0,i=!1){const n=this.waczfiles[t].nonSurt?e:M(e),s=i?this.prefixUpperBound(n):n+" 9999",o=IDBKeyRange.upperBound([t,s],!0),a=this.db.transaction("ziplines","readonly"),c=[];for await(const e of a.store.iterate(o,"prev")){if(e.value.waczname!==t)break;if(c.unshift(e.value),!e.value.prefix.split(" ")[0].startsWith(n))break}await a.done;const l=[];c.length>3&&r&&c.sort(((t,e)=>{const i=t.prefix.split(" ")[1],n=e.prefix.split(" ")[1];if(!i||!n)return 0;const s=Math.abs(d(i).getTime()-r),o=Math.abs(d(n).getTime()-r);return s===o?0:s3)break}return l.length&&await Promise.allSettled(l),await this.waczfiles[t].save(this.db),l.length>0}async doCDXLoad(t,e,r){try{const i="indexes/"+e.filename,n={offset:e.offset,length:e.length,unzip:!0,computeHash:!!e.digest},{reader:s,hasher:o}=await this.loadFileFromNamedWACZ(r,i,n),a=new pn(s,null,null,{wacz:r});if(await a.load(this),o){const t=o.getHash(),n=`${i}:${e.offset}-${e.length}`;await this.addVerifyData(r,n,e.digest,t)}e.loaded=!0,await this.db.put("ziplines",e)}catch(t){await T(t,this.config)||console.warn(t)}finally{delete this.ziploadercache[t]}}async findPageAtUrl(t,e){const r=await this.db.getAllFromIndex("pages","url",t);let i=null,n=Number.MAX_SAFE_INTEGER;for(const t of r){const r=Math.abs(t.ts-e);if(r<1e3)return t;r0)return r;for(const i of Object.keys(this.waczfiles))if(i&&"local"!==i){const{indexType:n,isNew:s}=await this.loadIndex(i);switch(n){case 2:if(!await this.loadCDXFromIDX(i,t,0,!0))continue;break;case 1:if(!s)continue;break;default:continue}const o=await super.resourcesByUrlAndMime(t,...e);o&&o.length&&(r=r.concat(o))}return r}async loadFileFromWACZ(t,e,r){try{return await t.loadFile(e,r)}catch(i){if(await this.retryLoad(i))return await t.loadFile(e,r);throw i}}async loadFileFromNamedWACZ(t,e,r){const i=this.waczfiles[t];if(!i)throw new Error("No WACZ Found for: "+t);return await this.loadFileFromWACZ(i,e,r)}async addNewWACZ({name:t,hash:e,path:r,parent:i=null,loader:n=null}={}){const s=t||r;e?e.indexOf(":")>0&&(e=e.split(":")[1]):e=await g(s,"sha-256","");const o=this.addWACZFile({waczname:s,hash:e,path:r,parent:i,loader:n},!0);await o.init(),await o.save(this.db,!0);const a=new Ly(this,o,!i);return await a.load()}async loadWACZFiles(t,e=this){const r=[],i=async(t,e)=>{await this.waczfiles[t].init(e),await this.waczfiles[t].save(this.db,!0)},n=t.resources.map((t=>{const r=e.getLoadPath(t.path);return{name:e.getName(t.name),hash:t.hash,path:r}}));for(const{name:t,hash:s,path:o}of n)this.waczfiles[t]?this.waczfiles[t].path!==o&&r.push(i(t,o)):r.push(this.addNewWACZ({name:t,hash:s,path:o,parent:e}));r.length&&await Promise.allSettled(r)}async getTextIndex(){const t={"Content-Type":"application/ndjson"},e=Object.keys(this.waczfiles);if(!this.textIndex||!e.length)return new Response("",{headers:t});const r=e[0];let i;try{i=await this.loadFileFromNamedWACZ(r,this.textIndex,{unzip:!0})}catch(e){return new Response("",{headers:t})}const{reader:n}=i,s=this.waczfiles[r].getSizeOf(this.textIndex);return s>0&&(t["Content-Length"]=""+s),new Response(n.getReadableStream(),{headers:t})}async getResource(t,e,r,{pageId:i}={}){if(await this.initing,this.externalSource){const i=await this.externalSource.getResource(t,e,r);if(i)return i}const n="navigate"===r.request.mode;let s=i,o=null,a=null;if(s){if(o=this.waczNameForHash[s],!o)return null;a=await super.getResource(t,e,r,{waczname:o})}if(a||!n)return a;for(const[i,n]of Object.entries(this.waczfiles))if(n.fileType===Wn&&(a=await super.getResource(t,e,r,{waczname:i,noFuzzyCheck:!0}),a)){o=i,s=n.hash;break}if(o)return Response.redirect(`${e}:${s}/${t.timestamp}mp_/${t.url}`);if(this.fuzzyUrlRules.length)for(const{match:i,replace:n}of this.fuzzyUrlRules){const s=decodeURIComponent(t.url.replace(i,n));if(s&&s!==t.url){t.url=s;const i=await super.getResource(t,e,r);if(i)return i}}return null}async retryLoad(t){return"json"===this.rootSourceType&&(t instanceof x?(this.updating||(this.updating=this.checkUpdates()),await this.updating,this.updating=null,!0):await T(t,this.config))}async checkUpdates(){"json"===this.rootSourceType&&await this.loadFromJSON()}async loadFromJSON(t=null){if(!t){t=(await this.sourceLoader.doInitialFetch(!1)).response}if(206!==t.status&&200!==t.status)return console.warn("WACZ update failed from: "+this.config.loadUrl),{};const e=await t.json();return e.profile,await this.loadWACZFiles(e),e}getLoadPath(t){return new URL(t,this.config.loadUrl).href}getName(t){return t}async createLoader(t){return await Vi(t)}}class jy{constructor(t){const e=t.extraConfig||{};this.sourceUrl=e.prefix,this.type=e.sourceType||"kiwix",this.notFoundPageUrl=e.notFoundPageUrl}async getAllPages(){return[]}async getResource(t,e){const{url:r,headers:i}=t.prepareProxyRequest(e);let n=i;if("kiwix"===this.type){let e=await this.resolveHeaders(r);if(!e)for(const t of Zr.getFuzzyCanonsWithArgs(r))if(t!==r&&(e=await this.resolveHeaders(t),e))break;if(!e){if(this.notFoundPageUrl&&"navigate"===t.mode){const t=await fetch(this.notFoundPageUrl);if(200===t.status){const e={"Content-Type":"text/html"},i=await t.text();return new Response(i.replace("$URL",r),{status:404,headers:e})}}return null}let{headers:i,encodedUrl:s,date:o,status:a,statusText:c,hasPayload:l}=e;if(n.has("Range")){const t=n.get("Range");n={Range:t}}let u=null,h=null;l&&(h=await fetch(this.sourceUrl+"A/"+s,{headers:n}),h.body&&(u=new K(h.body.getReader(),!1)),206===h.status&&(a=206,c="Partial Content",i.set("Content-Length",h.headers.get("Content-Length")),i.set("Content-Range",h.headers.get("Content-Range")),i.set("Accept-Ranges","bytes"))),u||(u=new Uint8Array([])),o||(o=new Date),i||(i=new Headers);return new mt({payload:u,status:a,statusText:c,headers:i,url:r,date:o,noRW:!1,isLive:!1})}}async resolveHeaders(t){const e=t.slice(t.indexOf("//")+2);let r=encodeURI(e);r=encodeURIComponent(e);let i=await fetch(this.sourceUrl+"H/"+r);if(200!==i.status)return null;let n=null,s=null,o=null,a=null,c=!1;try{const e=await ct.parse(i.body);if("revisit"===e.warcType){const r=e.warcHeaders.headers.get("WARC-Refers-To-Target-URI");if(r&&r!==t)return await this.resolveHeaders(r)}s=new Date(e.warcDate),e.httpHeaders?(n=e.httpHeaders.headers,o=Number(e.httpHeaders.statusCode),a=e.httpHeaders.statusText,c="0"!==e.httpHeaders.headers.get("Content-Length")):"resource"===e.warcType&&(n=new Headers,n.set("Content-Type",e.warcContentType),n.set("Content-Length",e.warcContentLength),o=200,a="OK",c=e.warcContentLength>0),o||(o=200)}catch(e){console.warn(e),console.warn("Ignoring headers, error parsing headers response for: "+t)}return{encodedUrl:r,headers:n,date:s,status:o,statusText:a,hasPayload:c}}}const zy=Qy([80,75,3,4]),Gy=Qy([31,139,8]),qy=Qy([87,65,82,67]);function Qy(t){return e=>{for(const[r,i]of t.entries())if(i!==e[r])return!1;return!0}}async function Vy(t){const e=t.body.getReader();let r="";const{value:i,done:n}=await e.read();var s;return!n&&i.length>=4&&(s=i.slice(0,4),r=zy(s)?".wacz":qy(s)?".warc":Gy(s)?".warc.gz":void 0,r||(r=function(t){try{const e=(new TextDecoder).decode(t).split("\n");if(e>1&&e.indexOf(" {"))return".cdxj"}catch(t){return""}}(i))),n||e.cancel(),r}globalThis.self||(globalThis.self=globalThis),self.interruptLoads={};class Ky extends class{constructor(){this.colldb=null,this.root=null,this.checkIpfs=!0,this._init_db=this._initDB()}async _initDB(){this.colldb=await Dr("collDB",1,{upgrade:t=>{t.createObjectStore("colls",{keyPath:"name"}).createIndex("type","type")}})}async loadAll(t){if(await this._init_db,t)for(const e of t.split(",")){const t=e.split(":");if(2===t.length){const e={dbname:t[1],sourceName:t[1],decode:!1},r={name:t[0],type:"archive",config:e};console.log("Adding Coll: "+JSON.stringify(r)),await this.colldb.put("colls",r)}}try{const t=(await this.listAll()).map((t=>this._initColl(t)));await Promise.all(t)}catch(t){console.warn(t.toString())}return!0}async listAll(){return await this._init_db,await this.colldb.getAll("colls")}async loadColl(t){await this._init_db;const e=await this.colldb.get("colls",t);return e?await this._initColl(e):null}async reload(t){return this.loadColl(t)}async deleteColl(t){await this._init_db;const e=await this.colldb.get("colls",t);if(!e)return!1;if(e.config.dbname)try{await Lr(e.config.dbname,{blocked(t,r){console.log(`Unable to delete ${e.config.dbname}, blocked: ${r}`)}})}catch(t){return console.warn(t),!1}return await this.colldb.delete("colls",t),!0}async updateAuth(t,e){await this._init_db;const r=await this.colldb.get("colls",t);return!!r&&(r.config.headers=e,await this.colldb.put("colls",r),!0)}async updateMetadata(t,e){await this._init_db;const r=await this.colldb.get("colls",t);return!!r&&(r.config.metadata={...r.config.metadata,...e},await this.colldb.put("colls",r),r.config.metadata)}async updateSize(t,e,r,i){await this._init_db;const n=await this.colldb.get("colls",t);if(!n)return!1;const s=n.config.metadata;return s.fullSize=(s.fullSize||0)+e,s.size=(s.size||0)+r,s.mtime=(new Date).getTime(),void 0!==i&&(n.config.decode=i),await this.colldb.put("colls",n),s}async initNewColl(t,e={},r="archive"){await this._init_db;const i=m(),n="local://"+i,s={name:i,type:r,config:{dbname:"db:"+i,ctime:(new Date).getTime(),decode:!1,metadata:t,sourceUrl:n,extraConfig:e}},o=await this._initColl(s);return await this.colldb.put("colls",s),o}async _initColl(t){const e=await this._initStore(t.type,t.config),r=t.name,i=t.config;return t.config.root&&!this.root&&(this.root=r),this._createCollection({name:r,store:e,config:i})}async _initStore(t,e){let r=null,i=null;switch(t){case"archive":i=new ei(e.dbname);break;case"remotesource":r=await Vi({url:e.loadUrl,headers:e.headers,size:e.size,extra:e.extra}),i=new nn(e.dbname,r,e.noCache);break;case"remoteprefix":i=new sn(e.dbname,e.remotePrefix,e.headers,e.noCache);break;case"wacz":case"remotezip":case"multiwacz":r=await Vi({url:e.loadUrl||e.sourceUrl,headers:e.headers,extra:e.extra}),i=new Wy(e,r,"multiwacz"===t?"json":"wacz");break;case"remotewarcproxy":i=new jy(e);break;case"live":i=new Fy(e.extraConfig)}return i?(i.initing&&await i.initing,i):(console.log("no store found: "+t),null)}_createCollection(t){return t}}{constructor(t){super(),this.registerListener(t)}async hasCollection(t){return await this._init_db,null!=await this.colldb.getKey("colls",t)}registerListener(t){t.addEventListener("message",(t=>{t.waitUntil?t.waitUntil(this._handleMessage(t)):this._handleMessage(t)}))}async _handleMessage(t){await this._init_db;const e=t.source||self;switch(t.data.msg_type){case"addColl":{const r=t.data.name,i=(t,i,n,s,o=null,a=null)=>{e.postMessage({msg_type:"collProgress",name:r,percent:t,error:i,currentSize:n,totalSize:s,fileHandle:o,extraMsg:a})};let n;try{if(n=await this.colldb.get("colls",r),n?t.data.skipExisting||(await this.deleteColl(r),n=await this.addCollection(t.data,i)):n=await this.addCollection(t.data,i),!n){if(t.data.name)try{await Lr("db:"+t.data.name,{blocked(e,r){console.log(`Load failed and unable to delete ${t.data.name}: ${r}`)}})}catch(t){console.warn(t)}return}}catch(t){if(t instanceof R)return console.warn(t),void i(0,"permission_needed",null,null,t.info&&t.info.fileHandle);if("ConstraintError"!==t.name)return console.warn(t),void i(0,"An unexpected error occured: "+t.toString());console.log("already being added, just continue..."),n=await this.colldb.get("colls",r)}e.postMessage({msg_type:"collAdded",name:r,sourceUrl:n.config.sourceUrl});break}case"cancelLoad":{const e=t.data.name,r=new Promise((t=>self.interruptLoads[e]=t));await r,await this.deleteColl(e),delete self.interruptLoads[e];break}case"removeColl":{const r=t.data.name;await this.hasCollection(r)&&(await this.deleteColl(r),this.doListAll(e));break}case"listAll":this.doListAll(e);break;case"reload":this.reload(t.data.name)}}async doListAll(t){const e=[],r=await this.listAll();for(const t of r)e.push({name:t.name,prefix:t.name,pageList:[],sourceName:t.config.sourceName});t.postMessage({msg_type:"listAll",colls:e})}async addCollection(t,e){let r=t.name,i=null,n={root:t.root||!1},s=null,o=null;const c=t.file;if(!c||!c.sourceUrl)return e(0,"Invalid Load Request"),!1;if(n.dbname="db:"+r,c.sourceUrl.startsWith("proxy:"))n.sourceUrl=c.sourceUrl.slice("proxy:".length),n.extraConfig=t.extraConfig,n.extraConfig.prefix||(n.extraConfig.prefix=n.sourceUrl),n.topTemplateUrl=t.topTemplateUrl,n.metadata={},i=t.type||n.extraConfig.type||"remotewarcproxy",s=await this._initStore(i,n);else{let l=null;if(c.newFullImport&&(r=m(),c.loadUrl=c.loadUrl||c.sourceUrl,c.name=c.name||c.sourceUrl,c.sourceUrl="local://"+r),i="archive",c.newFullImport&&c.importCollId){const t=await this.colldb.get("colls",c.importCollId);if(!t||"archive"!==t.type)return void e(0,"Invalid Existing Collection: "+c.importCollId);n.dbname=t.config.dbname,o=t.config,o.decode=!0}let u=c.loadUrl||c.sourceUrl;u.match(/[\w]+:\/\//)||(u=new URL(u,self.location.href).href),n.decode=!0,n.onDemand=!1,n.loadUrl=u,n.sourceUrl=c.sourceUrl,n.sourceName=c.name||c.sourceUrl;try{if(n.sourceName.match(/https?:\/\//)){const t=new URL(n.sourceName);n.sourceName=t.pathname+t.hash}}catch(t){}if(n.sourceName=n.sourceName.slice(n.sourceName.lastIndexOf("/")+1),n.size="number"==typeof c.size?c.size:null,n.extra=c.extra,n.loadUrl.startsWith("file://")&&!c.blob&&!n.extra){if(!this._fileHandles||!this._fileHandles[n.sourceUrl])return void e(0,"missing_local_file");n.extra={fileHandle:this._fileHandles[n.sourceUrl]}}n.extraConfig=t.extraConfig,n.headers=c.headers||n.extraConfig&&n.extraConfig.headers,n.noCache=c.noCache;let h=await Vi({url:u,headers:n.headers,size:c.size,extra:n.extra,blob:c.blob});if(c.loadEager){const{response:t}=await h.doInitialFetch(!1,!0),e={arrayBuffer:new Uint8Array(await t.arrayBuffer())};c.newFullImport=!0,h=await Vi({url:u,headers:n.headers,size:c.size,extra:e})}let p=function(t){const e=[".warc",".warc.gz",".cdx",".cdxj",".har",".json",".wacz",".zip"];for(const r of e)if(t.endsWith(r))return r;return""}(n.sourceName),{abort:d,response:f}=await h.doInitialFetch(".wacz"===p);p||(p=await Vy(await f.clone()));const g=f.body;if(n.onDemand=h.canLoadOnDemand&&!c.newFullImport,!h.isValid){const t=h.length<=1e3?await f.text():"";return e(0,`Sorry, this URL could not be loaded.\nMake sure this is a valid URL and you have access to this file.\nStatus: ${f.status} ${f.statusText}\nError Details:\n${t}`),d&&d.abort(),!1}if(!h.length)return e(0,"Sorry, this URL could not be loaded because the size of the file is not accessible.\nMake sure this is a valid URL and you have access to this file."),d&&d.abort(),!1;const w=h.length;if(".wacz"===p)if(n.onDemand)l=new Py(h,n,r),s=new Wy(n,h,"wacz"),i="wacz";else{if(!h.canLoadOnDemand||!c.newFullImport)return e(0,"Sorry, can't load this WACZ file due to lack of range request support on the server"),d&&d.abort(),!1;l=new Uy(h,n,r),s=null,delete n.extra}else".warc"===p||".warc.gz"===p?n.noCache||!(w300&&e<400)return;let s=null;void 0===this.timeRanges[n]?(s={count:0,children:[]},this.timeRanges[n]=s,r.referrer.indexOf("mp_/")>0&&self.clients.matchAll({type:"window"}).then((t=>this.updateStatsParent(n,r.referrer,t)))):s=this.timeRanges[n];const o=t.getTime();(!s.min||os.max)&&(s.max=o),s.count++}updateStatsParent(t,e,r){for(let i of r)if(i.url===e){this.timeRanges[i.id]?this.timeRanges[i.id].children[t]=1:this.timeRanges[i.id]={count:0,children:{id:1}};break}}async getStats(t){const e=new URL(t.request.url);let r=0;const i=new URLSearchParams(e.search).get("url"),n=await self.clients.matchAll({type:"window"}),s={};for(let t of n)t.url===i&&(r=t.id),s[t.id]=1;const o=this.timeRanges[r]||{},a={count:o.count||0,min:o.min,max:o.max},c=this.timeRanges[r]&&Object.keys(this.timeRanges[r].children)||[];for(let t of c){const e=this.timeRanges[t];e&&((!a.min||e.mina.max)&&(a.max=e.max),a.count+=e.count)}for(let t of Object.keys(this.timeRanges))s[t]||delete this.timeRanges[t];return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}}var Jy=function(){return Jy=Object.assign||function(t){for(var e,r=1,i=arguments.length;r$)/g,""):"[a-zA-Z0-9-_.~%':|=+\\*@$]+")+")"},um=[{name:"url-parameter",pattern:/^:([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})(<(.+?)>)?/,regex:function(t){return new RegExp(lm(t[2]))}},{name:"url-parameter-splat",pattern:/^\*([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})/,regex:/([^?]*)/},{name:"url-parameter-matrix",pattern:/^;([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})(<(.+?)>)?/,regex:function(t){return new RegExp(";"+t[1]+"="+lm(t[2]))}},{name:"query-parameter",pattern:/^(?:\?|&)(?::)?([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})/},{name:"delimiter",pattern:/^(\/|\?)/,regex:function(t){return new RegExp("\\"+t[0])}},{name:"sub-delimiter",pattern:/^(!|&|-|_|\.|;)/,regex:function(t){return new RegExp(t[0])}},{name:"fragment",pattern:/^([0-9a-zA-Z]+)/,regex:function(t){return new RegExp(t[0])}}],hm=function t(e,r){if(void 0===r&&(r=[]),!um.some((function(i){var n=e.match(i.pattern);return!!n&&(r.push({type:i.name,match:n[0],val:n.slice(1,2),otherVal:n.slice(2),regex:i.regex instanceof Function?i.regex(n):i.regex}),n[0].length0,this.hasSpatParam=this.tokens.filter((function(t){return/splat$/.test(t.type)})).length>0,this.hasMatrixParams=this.tokens.filter((function(t){return/matrix$/.test(t.type)})).length>0,this.hasQueryParams=this.tokens.filter((function(t){return/^query-parameter/.test(t.type)})).length>0,this.spatParams=this.getParams("url-parameter-splat"),this.urlParams=this.getParams(/^url-parameter/),this.queryParams=this.getParams("query-parameter"),this.params=this.urlParams.concat(this.queryParams),this.source=this.tokens.filter((function(t){return void 0!==t.regex})).map((function(t){return t.regex.source})).join("")}return t.createPath=function(e,r){return new t(e,r)},t.prototype.isQueryParam=function(t){return-1!==this.queryParams.indexOf(t)},t.prototype.isSpatParam=function(t){return-1!==this.spatParams.indexOf(t)},t.prototype.test=function(t,e){var r=this,i=Jy(Jy({caseSensitive:!1,strictTrailingSlash:!1},this.options),e),n=function(t,e){return e||"\\/"===t?t:t.replace(/\\\/$/,"")+"(?:\\/)?"}(this.source,i.strictTrailingSlash),s=this.urlTest(t,n+(this.hasQueryParams?"(\\?.*$|$)":"$"),i.caseSensitive,i.urlParamsEncoding);if(!s||!this.hasQueryParams)return s;var o=im(t,i.queryParams);return 0===Object.keys(o).filter((function(t){return!r.isQueryParam(t)})).length?(Object.keys(o).forEach((function(t){return s[t]=o[t]})),s):null},t.prototype.partialTest=function(t,e){var r=this,i=Jy(Jy({caseSensitive:!1,delimited:!0},this.options),e),n=function(t,e){return e?/(\/)$/.test(t)?t:t+"(\\/|\\?|\\.|;|$)":t}(this.source,i.delimited),s=this.urlTest(t,n,i.caseSensitive,i.urlParamsEncoding);if(!s)return s;if(!this.hasQueryParams)return s;var o=im(t,i.queryParams);return Object.keys(o).filter((function(t){return r.isQueryParam(t)})).forEach((function(t){return function(t,e,r){void 0===r&&(r="");var i=t[e];return t[e]=void 0===i?r:Array.isArray(i)?i.concat(r):[i,r],t}(s,t,o[t])})),s},t.prototype.build=function(t,e){var r=this;void 0===t&&(t={});var i=Jy(Jy({ignoreConstraints:!1,ignoreSearch:!1,queryParams:{}},this.options),e),n=Object.keys(t).filter((function(t){return!r.isQueryParam(t)})).reduce((function(e,n){if(!pm(t[n]))return e;var s=t[n],o=r.isSpatParam(n);return"boolean"==typeof s?e[n]=s:Array.isArray(s)?e[n]=s.map((function(t){return cm(t,i.urlParamsEncoding,o)})):e[n]=cm(s,i.urlParamsEncoding,o),e}),{});if(this.urlParams.some((function(e){return!pm(t[e])}))){var s=this.urlParams.filter((function(e){return!pm(t[e])}));throw new Error("Cannot build path: '"+this.path+"' requires missing parameters { "+s.join(", ")+" }")}if(!i.ignoreConstraints&&!this.tokens.filter((function(t){return/^url-parameter/.test(t.type)&&!/-splat$/.test(t.type)})).every((function(t){return new RegExp("^"+lm(t.otherVal[0])+"$").test(n[t.val])})))throw new Error("Some parameters of '"+this.path+"' are of invalid format");var o=this.tokens.filter((function(t){return!1===/^query-parameter/.test(t.type)})).map((function(t){return"url-parameter-matrix"===t.type?";"+t.val+"="+n[t.val[0]]:/^url-parameter/.test(t.type)?n[t.val[0]]:t.match})).join("");if(i.ignoreSearch)return o;var a=function(t,e){var r=Xy(e);return Object.keys(t).filter((function(e){return function(t){return void 0!==t}(t[e])})).map((function(e){return tm(e,t[e],r)})).filter(Boolean).join("&")}(this.queryParams.filter((function(e){return-1!==Object.keys(t).indexOf(e)})).reduce((function(e,r){return e[r]=t[r],e}),{}),i.queryParams);return a?o+"?"+a:o},t.prototype.getParams=function(t){var e=t instanceof RegExp?function(e){return t.test(e.type)}:function(e){return e.type===t};return this.tokens.filter(e).map((function(t){return t.val[0]}))},t.prototype.urlTest=function(t,e,r,i){var n=this,s=new RegExp("^"+e,r?"":"i"),o=t.match(s);return o?this.urlParams.length?o.slice(1,this.urlParams.length+1).reduce((function(t,e,r){return t[n.urlParams[r]]=(am[i]||decodeURIComponent)(e),t}),{}):{}:null},t}();class gm{constructor(t){this.routes={};for(const[e,r]of Object.entries(t)){let t,i;r instanceof Array?(t=r[0],i=r[1]||"GET"):(t=r,i="GET"),this.routes[i]=this.routes[i]||{},this.routes[i][e]=new fm(t)}}match(t,e="GET"){for(const[r,i]of Object.entries(this.routes[e]||[])){const e=t.split("?",2),n=e[0],s=i.test(n);if(s)return s._route=r,s._query=new URLSearchParams(2===e.length?e[1]:""),s}return{_route:null}}}class wm{constructor(t){this.router=new gm(this.routes),this.collections=t}get routes(){return{index:"coll-index",coll:"c/:coll",urls:"c/:coll/urls",createColl:["c/create","POST"],deleteColl:["c/:coll","DELETE"],updateAuth:["c/:coll/updateAuth","POST"],updateMetadata:["c/:coll/metadata","POST"],curated:"c/:coll/curated/:list",pages:"c/:coll/pages",textIndex:"c/:coll/textIndex",deletePage:["c/:coll/page/:page","DELETE"]}}async apiResponse(t,e,r){const i=this.router.match(t,e.method),n=await this.handleApi(e,i,r);if(n instanceof Response)return n;const s=n.error?404:200;return this.makeResponse(n,s)}async handleApi(t,e){switch(e._route){case"index":return await this.listAll(e._query.get("filter"));case"createColl":{const e=await t.json();return I(await this.collections.initNewColl(e.metadata||{},e.extraConfig||{}))}case"coll":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=I(t);return"1"===e._query.get("all")?(t.store.db?(r.pages=await t.store.getAllPages(),r.lists=await t.store.db.getAll("pageLists"),r.curatedPages=await t.store.db.getAll("curatedPages")):(r.pages=[],r.lists=[],r.curatedPages=[]),r.verify=await t.store.getVerifyInfo()):(r.numLists=await t.store.db.count("pageLists"),r.numPages=await t.store.db.count("pages")),t.config.metadata.ipfsPins&&(r.ipfsPins=t.config.metadata.ipfsPins),r}case"deleteColl":{const t="1"===e._query.get("reload");return await this.collections.deleteColl(e.coll,t)?await this.listAll():{error:"collection_not_found"}}case"updateAuth":{const r=await t.json();return{success:await this.collections.updateAuth(e.coll,r.headers)}}case"updateMetadata":{const r=await t.json();return{metadata:await this.collections.updateMetadata(e.coll,r)}}case"urls":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=e._query.get("url"),i=Number(e._query.get("count")||100),n=e._query.get("mime"),s="1"===e._query.get("prefix"),o=e._query.get("fromUrl"),a=e._query.get("fromTs"),c=e._query.get("fromMime"),l=Number(e._query.get("fromStatus")||0);if(!t.store.resourcesByMime)return{urls:[]};let u;return u=r?await t.store.resourcesByUrlAndMime(r,n,i,s,o,a):await t.store.resourcesByMime(n,i,c,o,l),u=u||[],{urls:u}}case"pages":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};return{pages:await t.store.getAllPages()}}case"textIndex":{const t=await this.collections.getColl(e.coll);return t?t.store.getTextIndex?await t.store.getTextIndex():{}:{error:"collection_not_found"}}case"curated":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=Number(e.list);return{curated:await t.store.db.getAllFromIndex("curatedPages","listPages",IDBKeyRange.bound([r],[r+1]))}}case"deletePage":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const{pageSize:r,deleteSize:i}=t.store.deletePage(e.page);return this.collections.updateSize(e.coll,r,i),{pageSize:r,deleteSize:i}}default:return{error:"not_found"}}}async listAll(t){const e=await this.collections.listAll(),r=[];return e.forEach((e=>{"live"!==e.type&&"remoteproxy"!==e.type&&(t&&0!==e.type.indexOf(t)||r.push(I(e)))})),{colls:r}}makeResponse(t,e=200){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":"application/json"}})}}const ym=/^(?::([\w-]+)\/)?(\d*)([a-z]+_|[$][a-z0-9:.-]+)?(?:\/|\||%7C|%7c)(.+)/;class mm{constructor(t,e,{isRoot:r=!1,mod:i="",ts:n="",proxyOrigin:s=null,localOrigin:o=null}={}){const a=ym.exec(t);if(this.url="",this.timestamp=n,this.mod=i,this.pageId="",this.hash="",!a&&(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("blob:")))this.url=t;else if(!a&&r)this.url="https://"+t;else{if(!a)return void(this.url=null);this.pageId=a[1]||"",this.timestamp=a[2],this.mod=a[3],this.url=a[4]}if(s&&o){const t=new URL(this.url);t.origin===o&&(this.url=s+t.pathname+(t.search?t.search:""))}const c=this.url.indexOf("#");c>0&&(this.hash=this.url.slice(c),this.url=this.url.substring(0,c)),this.request=e,this.method=e.method,this.mode=e.mode,this._postToGetConverted=!1}get headers(){return this.request.headers}get destination(){return this.request.destination}get referrer(){return this.request.referrer}async convertPostToGet(){if(this._postToGetConverted)return this.url;const t=this.request;if("POST"!==t.method&&"PUT"!==t.method)return this.url;const e={method:t.method,postData:await t.text(),headers:t.headers,url:this.url};return F(e)&&(this.url=e.url,this.method="GET",this.mode="navigate"===this.request.mode?"same-origin":this.request.mode,this._postToGetConverted=!0),this.url}prepareProxyRequest(t,e=!0){let r,i,n;if(e){r=new Headers(this.request.headers),i=this.request.referrer;const e=i.indexOf("/http",t.length-1);e>0&&(i=i.slice(e+1),r.set("X-Proxy-Referer",i)),n=this.request.credentials,this.cookie&&r.set("X-Proxy-Cookie",this.cookie)}else r=new Headers,n="omit";let s=this.url;if(s.startsWith("//"))try{s=new URL(i).protocol+s}catch(t){s="https:"+s}return{referrer:i,headers:r,credentials:n,url:s}}async getBody(){const t=this.request.clone();return new Uint8Array(await t.arrayBuffer())}}const bm="x-wabac-is-ajax-req";class Am extends Ky{constructor(t,e=null,r={}){super(self),this.prefixes=t,this.colls={},this.inited=null,this.root=e,this.defaultConfig=r,this._fileHandles={}}_createCollection(t){return new br(t,this.prefixes,this.defaultConfig)}loadAll(t){return this.colls={},this.inited=super.loadAll(t),this.inited}async getColl(t){return this.colls[t]||(this.colls[t]=await this.loadColl(t)),this.colls[t]}async reload(t){delete this.colls[t],await this.getColl(t)}async addCollection(t,e){const r=await super.addCollection(t,e);return r&&r.name&&(this.colls[r.name]=this._createCollection(r)),r}async deleteColl(t,e=!1){return this.colls[t]&&(this.colls[t].store&&this.colls[t].store.delete&&await this.colls[t].store.delete(),e&&this.colls[t].config&&this.colls[t].config.extra&&this.colls[t].config.extra.fileHandle&&(this._fileHandles[this.colls[t].config.sourceUrl]=this.colls[t].config.extra.fileHandle)),!!await super.deleteColl(t)&&(delete this.colls[t],!0)}async initNewColl(t,e={},r="archive"){const i=await super.initNewColl(t,e,r);return i&&(this.colls[i.name]=i),i}async updateAuth(t,e){this.colls[t]&&this.colls[t].store.updateHeaders&&this.colls[t].store.updateHeaders(e),await super.updateAuth(t,e)}async updateMetadata(t,e){const r=await super.updateMetadata(t,e);return this.colls[t]&&r&&(this.colls[t].config.metadata=r,this.colls[t].metadata=r),r}async updateSize(t,e,r,i){const n=await super.updateSize(t,e,r,i);return this.colls[t]&&n&&(this.colls[t].config.metadata=n,this.colls[t].metadata=n),void 0!==i&&this.colls[t]&&(this.colls[t].config.decode=i),n}}class Em{constructor({staticData:t=null,ApiClass:e=wm,defaultConfig:r={},CollectionsClass:i=Am}={}){this.prefix=self.registration?self.registration.scope:"",this.replayPrefix=this.prefix;const n=new URLSearchParams(self.location.search);let s="w";n.has("replayPrefix")&&(s=n.get("replayPrefix")),s&&(this.replayPrefix+=s+"/"),this.staticPrefix=this.prefix+"static/",this.distPrefix=this.prefix+"dist/";const o={static:this.staticPrefix,root:this.prefix,main:this.replayPrefix};this.staticData=t||new Map,this.staticData.set(this.staticPrefix+"wombat.js",{type:"application/javascript",content:'/*! wombat.js is part of Webrecorder project. Copyright (C) 2020-2023, Webrecorder Software. Licensed under the Affero General Public License v3. */(()=>{"use strict";function t(){this._map=[]}function e(t,e){void 0!==self.Symbol&&void 0!==self.Symbol.toStringTag&&Object.defineProperty(t.prototype,self.Symbol.toStringTag,{value:e,enumerable:!1})}function r(t){for(var e,r,i=t.__proto__||t.constructor.prototype||t.prototype,o=Object.getOwnPropertyNames(i),n=o.length,s=0;s=0?this._map.splice(e,1)[0][1]:null},t.prototype.map=function(t){for(var e=0;et+=String.fromCharCode(e)),""):t?t.toString():"";try{return"__wb_post_data="+btoa(e)}catch{return"__wb_post_data="}}function _(t){let{method:e,headers:r,postData:i}=t;if("GET"===e)return!1;function o(t){return t instanceof Uint8Array&&(t=(new TextDecoder).decode(t)),t}let n="";switch((r.get("content-type")||"").split(";")[0]){case"application/x-www-form-urlencoded":n=o(i);break;case"application/json":n=d(o(i));break;case"text/plain":try{n=d(o(i),!1)}catch{n=l(i)}break;case"multipart/form-data":{let t=r.get("content-type");if(!t)throw new Error("utils cannot call postToGetURL when missing content-type header");n=function(t,e){return function(t,e){let r=new URLSearchParams;t instanceof Uint8Array&&(t=(new TextDecoder).decode(t));try{let i=e.split("boundary=")[1],o=t.split(new RegExp("-*"+i+"-*","mi"));for(let t of o){let e=t.trim().match(/name="([^"]+)"\\r\\n\\r\\n(.*)/im);e&&r.set(e[1],e[2])}}catch{}return r}(t,e).toString()}(o(i),t);break}default:n=l(i)}return null!==n&&(t.url=function(t,e,r){if(!r)return t;let i=t.indexOf("?")>0?"&":"?";return`${t}${i}__wb_method=${r}&${e}`}(t.url,n,t.method),t.method="GET",t.requestBody=n,!0)}function u(t,e=!0){if("string"==typeof t)try{t=JSON.parse(t)}catch{t={}}let r=new URLSearchParams,i={};try{JSON.stringify(t,((t,e)=>(["object","function"].includes(typeof e)||r.set((t=>r.has(t)?(t in i||(i[t]=1),t+"."+ ++i[t]+"_"):t)(t),e),e)))}catch(t){if(!e)throw t}return r}function d(t,e=!0){return u(t,e).toString()}function f(e,i){if(!(this instanceof f))return new f(e,i);this.debug_rw=!1,this.$wbwindow=e,this.WBWindow=Window,this.origHost=e.location.host,this.origHostname=e.location.hostname,this.origProtocol=e.location.protocol,this.HTTP_PREFIX="http://",this.HTTPS_PREFIX="https://",this.REL_PREFIX="//",this.VALID_PREFIXES=[this.HTTP_PREFIX,this.HTTPS_PREFIX,this.REL_PREFIX],this.IGNORE_PREFIXES=["#","about:","data:","blob:","mailto:","javascript:","{","*"],"ignore_prefixes"in i&&(this.IGNORE_PREFIXES=this.IGNORE_PREFIXES.concat(i.ignore_prefixes)),this.WB_CHECK_THIS_FUNC="_____WB$wombat$check$this$function_____",this.WB_ASSIGN_FUNC="_____WB$wombat$assign$function_____",this.wb_setAttribute=e.Element.prototype.setAttribute,this.wb_getAttribute=e.Element.prototype.getAttribute,this.wb_funToString=Function.prototype.toString,this.WBAutoFetchWorker=null,this.wbUseAFWorker=i.enable_auto_fetch&&null!=e.Worker&&i.is_live,this.wb_rel_prefix="",this.wb_wombat_updating=!1,this.message_listeners=new t,this.storage_listeners=new t,this.linkAsTypes={script:"js_",worker:"js_",style:"cs_",image:"im_",document:"if_",fetch:"mp_",font:"oe_",audio:"oe_",video:"oe_",embed:"oe_",object:"oe_",track:"oe_","":"mp_",null:"mp_",undefined:"mp_"},this.linkTagMods={linkRelToAs:{import:this.linkAsTypes,preload:this.linkAsTypes},stylesheet:"cs_",null:"mp_",undefined:"mp_","":"mp_"},this.tagToMod={A:{href:"mp_"},AREA:{href:"mp_"},AUDIO:{src:"oe_",poster:"im_"},BASE:{href:"mp_"},EMBED:{src:"oe_"},FORM:{action:"mp_"},FRAME:{src:"fr_"},IFRAME:{src:"if_"},IMAGE:{href:"im_","xlink:href":"im_"},IMG:{src:"im_",srcset:"im_"},INPUT:{src:"oe_"},INS:{cite:"mp_"},META:{content:"mp_"},OBJECT:{data:"oe_",codebase:"oe_"},Q:{cite:"mp_"},SCRIPT:{src:"js_","xlink:href":"js_"},SOURCE:{src:"oe_",srcset:"oe_"},TRACK:{src:"oe_"},VIDEO:{src:"oe_",poster:"im_"},image:{href:"im_","xlink:href":"im_"}},this.URL_PROPS=["href","hash","pathname","host","hostname","protocol","origin","search","port"],this.wb_info=i,this.wb_opts=i.wombat_opts,this.wb_replay_prefix=i.prefix,this.wb_is_proxy=this.wb_info.proxy_magic||!this.wb_replay_prefix,this.wb_info.top_host=this.wb_info.top_host||"*",this.wb_curr_host=e.location.protocol+"//"+e.location.host,this.wb_info.wombat_opts=this.wb_info.wombat_opts||{},this.wb_orig_scheme=this.wb_info.wombat_scheme+"://",this.wb_orig_origin=this.wb_orig_scheme+this.wb_info.wombat_host,this.wb_abs_prefix=this.wb_replay_prefix,this.wb_capture_date_part="",!this.wb_info.is_live&&this.wb_info.wombat_ts&&(this.wb_capture_date_part="/"+this.wb_info.wombat_ts+"/"),this.BAD_PREFIXES=["http:"+this.wb_replay_prefix,"https:"+this.wb_replay_prefix,"http:/"+this.wb_replay_prefix,"https:/"+this.wb_replay_prefix],this.hostnamePortRe=/^[\\w-]+(\\.[\\w-_]+)+(:\\d+)(\\/|$)/,this.ipPortRe=/^\\d+\\.\\d+\\.\\d+\\.\\d+(:\\d+)?(\\/|$)/,this.workerBlobRe=/__WB_pmw\\(.*?\\)\\.(?=postMessage\\()/g,this.rmCheckThisInjectRe=/_____WB\\$wombat\\$check\\$this\\$function_____\\(.*?\\)/g,this.STYLE_REGEX=/(url\\s*\\(\\s*[\\\\"\']*)([^)\'"]+)([\\\\"\']*\\s*\\))/gi,this.IMPORT_REGEX=/(@import\\s*[\\\\"\']*)([^)\'";]+)([\\\\"\']*\\s*;?)/gi,this.IMPORT_JS_REGEX=/^(import\\s*\\([\'"]+)([^\'"]+)(["\'])/i,this.no_wombatRe=/WB_wombat_/g,this.srcsetRe=/\\s*(\\S*\\s+[\\d.]+[wx]),|(?:\\s*,(?:\\s+|(?=https?:)))/,this.cookie_path_regex=/\\bPath=\'?"?([^;\'"\\s]+)/i,this.cookie_domain_regex=/\\bDomain=([^;\'"\\s]+)/i,this.cookie_expires_regex=/\\bExpires=([^;\'"]+)/gi,this.SetCookieRe=/,(?![|])/,this.IP_RX=/^(\\d)+\\.(\\d)+\\.(\\d)+\\.(\\d)+$/,this.FullHTMLRegex=/^\\s*<(?:html|head|body|!doctype html)/i,this.IsTagRegex=/^\\s*0&&e.preserveMedia(r)}))},w.prototype.terminate=function(){this.worker.terminate()},w.prototype.justFetch=function(t){this.worker.postMessage({type:"fetch-all",values:t})},w.prototype.fetchAsPage=function(t,e,r){if(t){var i={"X-Wombat-History-Page":e};if(r){var o=encodeURIComponent(r.trim());r&&(i["X-Wombat-History-Title"]=o)}var n={url:t,options:{headers:i,cache:"no-store"}};this.justFetch([n])}},w.prototype.postMessage=function(t,e){if(e){var r=this;Promise.resolve().then((function(){r.worker.postMessage(t)}))}else this.worker.postMessage(t)},w.prototype.preserveSrcset=function(t,e){this.postMessage({type:"values",srcset:{value:t,mod:e,presplit:!0}},!0)},w.prototype.preserveDataSrcset=function(t){this.postMessage({type:"values",srcset:{value:t.dataset.srcset,mod:this.rwMod(t),presplit:!1}},!0)},w.prototype.preserveMedia=function(t){this.postMessage({type:"values",media:t},!0)},w.prototype.getSrcset=function(t){return this.wombat.wb_getAttribute?this.wombat.wb_getAttribute.call(t,"srcset"):t.getAttribute("srcset")},w.prototype.rwMod=function(t){switch(t.tagName){case"SOURCE":return t.parentElement&&"PICTURE"===t.parentElement.tagName?"im_":"oe_";case"IMG":return"im_"}return"oe_"},w.prototype.extractFromLocalDoc=function(){var t=this;Promise.resolve().then((function(){for(var e={type:"values",context:{docBaseURI:document.baseURI}},r=[],i=0,o=document.styleSheets;i=0||t.indexOf("ecmascript")>=0)&&(t.indexOf("json")>=0||t.indexOf("text/")>=0))},f.prototype.skipWrapScriptTextBasedOnText=function(t){if(!t||t.indexOf(this.WB_ASSIGN_FUNC)>=0||0===t.indexOf("<"))return!0;for(var e=["window","self","document","location","top","parent","frames","opener"],r=0;r=0)return!1;return!0},f.prototype.nodeHasChildren=function(t){if(!t)return!1;if("function"==typeof t.hasChildNodes)return t.hasChildNodes();var e=t.children||t.childNodes;return!!e&&e.length>0},f.prototype.rwModForElement=function(t,e){if(t){var r="mp_";if("LINK"===t.tagName&&"href"===e){if(t.rel){var i=t.rel.trim().toLowerCase(),o=this.wb_getAttribute.call(t,"as");if(o&&null!=this.linkTagMods.linkRelToAs[i])r=this.linkTagMods.linkRelToAs[i][o.toLowerCase()];else null!=this.linkTagMods[i]&&(r=this.linkTagMods[i])}}else{var n=this.tagToMod[t.tagName];null!=n&&(r=n[e])}return r}},f.prototype.removeWBOSRC=function(t){"SCRIPT"!==t.tagName||t.__$removedWBOSRC$__||(t.hasAttribute("__wb_orig_src")&&t.removeAttribute("__wb_orig_src"),t.__$removedWBOSRC$__=!0)},f.prototype.retrieveWBOSRC=function(t){var e;if("SCRIPT"===t.tagName&&!t.__$removedWBOSRC$__)return null==(e=this.wb_getAttribute?this.wb_getAttribute.call(t,"__wb_orig_src"):t.getAttribute("__wb_orig_src"))&&(t.__$removedWBOSRC$__=!0),e},f.prototype.wrapScriptTextJsProxy=function(t){return\'var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };\\nif (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }\\n{\\nlet window = _____WB$wombat$assign$function_____("window");\\nlet globalThis = _____WB$wombat$assign$function_____("globalThis");\\nlet self = _____WB$wombat$assign$function_____("self");\\nlet document = _____WB$wombat$assign$function_____("document");\\nlet location = _____WB$wombat$assign$function_____("location");\\nlet top = _____WB$wombat$assign$function_____("top");\\nlet parent = _____WB$wombat$assign$function_____("parent");\\nlet frames = _____WB$wombat$assign$function_____("frames");\\nlet opener = _____WB$wombat$assign$function_____("opener");\\n{\\n\'+t.replace(this.DotPostMessageRe,".__WB_pmw(self.window)$1")+"\\n\\n}}"},f.prototype.watchElem=function(t,e){if(!this.$wbwindow.MutationObserver)return!1;new this.$wbwindow.MutationObserver((function(t,r){for(var i=0;i"},f.prototype.getFinalUrl=function(t,e,r){var i=t?this.wb_rel_prefix:this.wb_abs_prefix;return null==e&&(e=this.wb_info.mod),this.wb_info.is_live||(i+=this.wb_info.wombat_ts),"/"!==(i+=e)[i.length-1]&&(i+="/"),i+r},f.prototype.resolveRelUrl=function(t,e){var r=e||this.$wbwindow.document,i=this.makeParser(r.baseURI,r),o=i.href.lastIndexOf("#"),n=o>=0?i.href.substring(0,o):i.href,s=n.lastIndexOf("/");return s>=0&&s!==n.length-1?i.href=n.substring(0,s+1)+t:i.href=n+t,i.href},f.prototype.extractOriginalURL=function(t){if(!t)return"";if(this.wb_is_proxy)return t;var e,r=t.toString(),i=r;if(this.startsWithOneOf(i,this.IGNORE_PREFIXES))return i;if(i.startsWith(this.wb_info.static_prefix))return i;e=this.startsWith(i,this.wb_abs_prefix)?this.wb_abs_prefix.length:this.wb_rel_prefix&&this.startsWith(i,this.wb_rel_prefix)?this.wb_rel_prefix.length:this.wb_rel_prefix?1:0;var o=i.indexOf("/http",e);return o<0&&(o=i.indexOf("///",e)),o<0&&(o=i.indexOf("/blob:",e)),o<0&&(o=i.indexOf("/about:blank",e)),o>=0?i=i.substr(o+1):((o=i.indexOf(this.wb_replay_prefix))>=0&&(i=i.substr(o+this.wb_replay_prefix.length)),i.length>4&&"_"===i.charAt(2)&&"/"===i.charAt(3)&&(i=i.substr(4)),i===r||this.startsWithOneOf(i,this.VALID_PREFIXES)||this.startsWith(i,"blob:")||(i=this.wb_orig_scheme+i)),"/"===r.charAt(0)&&"/"!==r.charAt(1)&&this.startsWith(i,this.wb_orig_origin)&&(i=i.substr(this.wb_orig_origin.length)),this.startsWith(i,this.REL_PREFIX)?this.wb_info.wombat_scheme+":"+i:i},f.prototype.makeParser=function(t,e){var r=this.extractOriginalURL(t),i=e;return e||(i="about:blank"===this.$wbwindow.location.href&&this.$wbwindow.opener?this.$wbwindow.opener.document:this.$wbwindow.document),this._makeURLParser(r,i)},f.prototype._makeURLParser=function(t,e){try{return new this.$wbwindow.URL(t,e.baseURI)}catch(t){}var r=e.createElement("a");return r._no_rewrite=!0,r.href=t,r},f.prototype.defProp=function(t,e,r,i,o){var n=Object.getOwnPropertyDescriptor(t,e);if(n&&!n.configurable)return!1;if(!i)return!1;var s={configurable:!0,enumerable:o||!1,get:i};r&&(s.set=r);try{return Object.defineProperty(t,e,s),!0}catch(t){return console.warn("Failed to redefine property %s",e,t.message),!1}},f.prototype.defGetterProp=function(t,e,r,i){var o=Object.getOwnPropertyDescriptor(t,e);if(o&&!o.configurable)return!1;if(!r)return!1;try{return Object.defineProperty(t,e,{configurable:!0,enumerable:i||!1,get:r}),!0}catch(t){return console.warn("Failed to redefine property %s",e,t.message),!1}},f.prototype.getOrigGetter=function(t,e){var r;if(t.__lookupGetter__&&(r=t.__lookupGetter__(e)),!r&&Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(t,e);i&&(r=i.get)}return r},f.prototype.getOrigSetter=function(t,e){var r;if(t.__lookupSetter__&&(r=t.__lookupSetter__(e)),!r&&Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(t,e);i&&(r=i.set)}return r},f.prototype.getAllOwnProps=function(t){for(var e=[],r=Object.getOwnPropertyNames(t),i=0;i "+n),r.href=n}}},f.prototype.checkLocationChange=function(t,e){var r=typeof t,i=e?this.$wbwindow.__WB_replay_top.location:this.$wbwindow.location;"string"===r?this.updateLocation(t,i.href,i):"object"===r&&this.updateLocation(t.href,t._orig_href,i)},f.prototype.checkAllLocations=function(){if(this.wb_wombat_updating)return!1;this.wb_wombat_updating=!0,this.checkLocationChange(this.$wbwindow.WB_wombat_location,!1),this.$wbwindow.WB_wombat_location!=this.$wbwindow.__WB_replay_top.WB_wombat_location&&this.checkLocationChange(this.$wbwindow.__WB_replay_top.WB_wombat_location,!0),this.wb_wombat_updating=!1},f.prototype.proxyToObj=function(t){if(t)try{var e=t.__WBProxyRealObj__;if(e)return e}catch(t){}return t},f.prototype.objToProxy=function(t){if(t)try{var e=t._WB_wombat_obj_proxy;if(e)return e}catch(t){}return t},f.prototype.defaultProxyGet=function(t,e,r,i){switch(e){case"__WBProxyRealObj__":return t;case"location":case"WB_wombat_location":return t.WB_wombat_location;case"_WB_wombat_obj_proxy":return t._WB_wombat_obj_proxy;case"__WB_pmw":case this.WB_ASSIGN_FUNC:case this.WB_CHECK_THIS_FUNC:return t[e];case"origin":return t.WB_wombat_location.origin;case"constructor":return t.constructor}var o=t[e],n=typeof o;if("function"===n&&-1!==r.indexOf(e)){switch(e){case"requestAnimationFrame":case"cancelAnimationFrame":if(!this.isNativeFunction(o))return o;break;case"eval":if(this.isNativeFunction(o))return this.wrappedEval(o)}var s=i[e];return s&&s.original===o||(s={original:o,boundFn:o.bind(t)},i[e]=s),s.boundFn}return"object"===n&&o&&o._WB_wombat_obj_proxy?(o instanceof this.WBWindow&&this.initNewWindowWombat(o),o._WB_wombat_obj_proxy):o},f.prototype.setLoc=function(t,e){var r=this.makeParser(e,t.ownerDocument);t._orig_href=e,t._parser=r;var i=r.href;t._hash=r.hash,t._href=i,t._host=r.host,t._hostname=r.hostname,r.origin?t._origin=r.host?r.origin:"null":t._origin=r.protocol+"//"+r.hostname+(r.port?":"+r.port:""),t._pathname=r.pathname,t._port=r.port,t._protocol=r.protocol,t._search=r.search,Object.defineProperty||(t.href=i,t.hash=r.hash,t.host=t._host,t.hostname=t._hostname,t.origin=t._origin,t.pathname=t._pathname,t.port=t._port,t.protocol=t._protocol,t.search=t._search)},f.prototype.makeGetLocProp=function(t,e){var r=this;return function(){if(this._no_rewrite)return e.call(this,t);var i=e.call(this,"href");return"href"===t?r.extractOriginalURL(i):"ancestorOrigins"===t?[]:(this._orig_href!==i&&r.setLoc(this,i),this["_"+t])}},f.prototype.makeSetLocProp=function(t,e,r){var i=this;return function(o){if(this._no_rewrite)return e.call(this,t,o);if(this["_"+t]!==o){if(this["_"+t]=o,!this._parser){var n=r.call(this);this._parser=i.makeParser(n,this.ownerDocument)}var s=!1;if("href"===t&&"string"==typeof o)if(o&&this._parser instanceof URL)try{o=new URL(o,this._parser).href}catch(t){console.warn("Error resolving URL",t)}else o&&("."===o[0]||"#"===o[0]?o=i.resolveRelUrl(o,this.ownerDocument):"/"===o[0]&&(o.length>1&&"/"===o[1]?o=this._parser.protocol+o:(s=!0,o=WB_wombat_location.origin+o)));try{this._parser[t]=o}catch(e){console.log("Error setting "+t+" = "+o)}"hash"===t?(o=this._parser[t],e.call(this,"hash",o)):(s=s||o===this._parser.pathname,o=i.rewriteUrl(this._parser.href,s),e.call(this,"href",o))}}},f.prototype.styleReplacer=function(t,e,r,i,o,n){return e+this.rewriteUrl(r)+i},f.prototype.domConstructorErrorChecker=function(t,e,r,i){var o,n="number"==typeof i?i:1;if(t instanceof this.WBWindow?o="Failed to construct \'"+e+"\': Please use the \'new\' operator, this DOM object constructor cannot be called as a function.":r&&r.length=0)return o;if(0===o.indexOf(this.wb_rel_prefix)&&o.indexOf("http")>1){var a=o.indexOf(":/");return a>0&&"/"!==o[a+2]?o.substring(0,a+2)+"/"+o.substring(a+2):o}return this.getFinalUrl(!0,r,this.wb_orig_origin+o)}"."===o.charAt(0)&&(o=this.resolveRelUrl(o,i));var h=this.startsWithOneOf(o.toLowerCase(),this.VALID_PREFIXES);if(h){var w=this.replayTopHost,p=this.replayTopProtocol,c=h+w+"/";if(this.startsWith(o,c)){if(this.startsWith(o,this.wb_replay_prefix))return o;var l=p+"//",_=o.substring(c.length),u=!1;return _.indexOf(this.wb_rel_prefix)<0&&o.indexOf("/static/")<0&&(_=this.getFinalUrl(!0,r,WB_wombat_location.origin+"/"+_),u=!0),h!==l&&h!==this.REL_PREFIX&&(u=!0),u&&(o=e?"":l+w,_&&"/"!==_[0]&&(o+="/"),o+=_),o}return this.getFinalUrl(e,r,o)}return(h=this.startsWithOneOf(o,this.BAD_PREFIXES))?this.getFinalUrl(e,r,this.extractOriginalURL(o)):o},f.prototype.rewriteUrl=function(t,e,r,i){var o=this.rewriteUrl_(t,e,r,i);return this.debug_rw&&(t!==o?console.log("REWRITE: "+t+" -> "+o):console.log("NOT REWRITTEN "+t)),o},f.prototype.performAttributeRewrite=function(t,e,r,i){switch(e){case"innerHTML":case"outerHTML":return this.rewriteHtml(r);case"filter":return this.rewriteInlineStyle(r);case"style":return this.rewriteStyle(r);case"srcset":return this.rewriteSrcset(r,t)}if(i&&!this.startsWithOneOf(r,this.VALID_PREFIXES))return r;var o=this.rwModForElement(t,e);return this.wbUseAFWorker&&this.WBAutoFetchWorker&&this.isSavedDataSrcSrcset(t)&&this.WBAutoFetchWorker.preserveDataSrcset(t),this.rewriteUrl(r,!1,o,t.ownerDocument)},f.prototype.rewriteAttr=function(t,e,r){var i=!1;if(!t||!t.getAttribute||t._no_rewrite||t["_"+e])return i;var o=this.wb_getAttribute.call(t,e);if(!o||this.startsWith(o,"javascript:"))return i;var n=this.performAttributeRewrite(t,e,o,r);return n!==o&&(this.removeWBOSRC(t),this.wb_setAttribute.call(t,e,n),i=!0),i},f.prototype.noExceptRewriteStyle=function(t){try{return this.rewriteStyle(t)}catch(e){return t}},f.prototype.rewriteStyle=function(t){if(!t)return t;var e=t;return"object"==typeof t&&(e=t.toString()),"string"==typeof e?e.replace(this.STYLE_REGEX,this.styleReplacer).replace(this.IMPORT_REGEX,this.styleReplacer).replace(this.no_wombatRe,""):e},f.prototype.rewriteSrcset=function(t,e){if(!t)return"";for(var r=t.split(this.srcsetRe),i=[],o=this.rwModForElement(e,"srcset"),n=0;n=0){var o="javascript:";r=o+"window.parent._wb_wombat.initNewWindowWombat(window);"+i.substr(o.length)}return r||(r=this.rewriteUrl(i,!1,this.rwModForElement(t,e))),r!==i&&(this.wb_setAttribute.call(t,e,r),!0)},f.prototype.rewriteScript=function(t){if(t.hasAttribute("src")||!t.textContent||!this.$wbwindow.Proxy)return this.rewriteAttr(t,"src");if(this.skipWrapScriptBasedOnType(t.type))return!1;var e=t.textContent.trim();return!this.skipWrapScriptTextBasedOnText(e)&&(t.textContent=this.wrapScriptTextJsProxy(e),!0)},f.prototype.rewriteSVGElem=function(t){var e=this.rewriteAttr(t,"filter");return e=this.rewriteAttr(t,"style")||e,e=this.rewriteAttr(t,"xlink:href")||e,e=this.rewriteAttr(t,"href")||e,e=this.rewriteAttr(t,"src")||e},f.prototype.rewriteElem=function(t){var e=!1;if(!t)return e;if(t instanceof SVGElement)e=this.rewriteSVGElem(t);else switch(t.tagName){case"META":var r=this.wb_getAttribute.call(t,"http-equiv");r&&"content-security-policy"===r.toLowerCase()&&(this.wb_setAttribute.call(t,"http-equiv","_"+r),e=!0);break;case"STYLE":var i=this.rewriteStyle(t.textContent);t.textContent!==i&&(t.textContent=i,e=!0,this.wbUseAFWorker&&this.WBAutoFetchWorker&&null!=t.sheet&&this.WBAutoFetchWorker.deferredSheetExtraction(t.sheet));break;case"LINK":e=this.rewriteAttr(t,"href"),this.wbUseAFWorker&&"stylesheet"===t.rel&&this._addEventListener(t,"load",this.utilFns.wbSheetMediaQChecker);break;case"IMG":e=this.rewriteAttr(t,"src"),e=this.rewriteAttr(t,"srcset")||e,e=this.rewriteAttr(t,"style")||e,this.wbUseAFWorker&&this.WBAutoFetchWorker&&t.dataset.srcset&&this.WBAutoFetchWorker.preserveDataSrcset(t);break;case"OBJECT":if(this.wb_info.isSW&&t.parentElement&&"application/pdf"===t.getAttribute("type")){for(var o=this.$wbwindow.document.createElement("IFRAME"),n=0;n0;)for(var i=r.shift(),o=0;o"+r+"","text/html");if(!i||!this.nodeHasChildren(i.head)||!i.head.children[0].content)return r;var o=i.head.children[0];if(o._no_rewrite=!0,this.recurseRewriteElem(o.content)){var n=o.innerHTML;if(e){var s=o.content.children&&o.content.children[0];if(s){var a="";this.endsWith(n,a)&&!this.endsWith(r.toLowerCase(),a)&&(n=n.substring(0,n.length-a.length))}else if("<"!==r[0]||">"!==r[r.length-1])return void(this.write_buff+=r)}return n}return r},f.prototype.rewriteHtmlFull=function(t,e){var r=(new DOMParser).parseFromString(t,"text/html");if(!r)return t;for(var i=!1,o=0;o=0)r.documentElement._no_rewrite=!0,n=this.reconstructDocType(r.doctype)+r.documentElement.outerHTML;else{r.head._no_rewrite=!0,r.body._no_rewrite=!0;var s=this.nodeHasChildren(r.head),a=this.nodeHasChildren(r.body);if(n=(s?r.head.outerHTML:"")+(a?r.body.outerHTML:""),e)if(r.all.length>3){var h="";this.endsWith(n,h)&&!this.endsWith(t.toLowerCase(),h)&&(n=n.substring(0,n.length-h.length))}else if("<"!==t[0]||">"!==t[t.length-1])return void(this.write_buff+=t);n=this.reconstructDocType(r.doctype)+n}return n}return t},f.prototype.rewriteInlineStyle=function(t){var e;try{e=decodeURIComponent(t)}catch(r){e=t}if(e!==t){var r=this.rewriteStyle(e).split(",",2);return r[0]+","+encodeURIComponent(r[1])}return this.rewriteStyle(t)},f.prototype.rewriteCookie=function(t){var e=this,r=t.replace(this.wb_abs_prefix,"").replace(this.wb_rel_prefix,"");return r=r.replace(this.cookie_domain_regex,(function(t,i){var o={domain:i,cookie:r,wb_type:"cookie"};return e.sendTopMessage(o,!0),e.$wbwindow.location.hostname.indexOf(".")>=0&&!e.IP_RX.test(e.$wbwindow.location.hostname)?"Domain=."+e.$wbwindow.location.hostname:""})).replace(this.cookie_path_regex,(function(t,r){var i=e.rewriteUrl(r);return 0===i.indexOf(e.wb_curr_host)&&(i=i.substring(e.wb_curr_host.length)),"Path="+i})),"https:"!==e.$wbwindow.location.protocol&&(r=r.replace("secure","")),r.replace(",|",",")},f.prototype.rewriteWorker=function(t){if(!t)return t;var e=0===(t=t.toString()).indexOf("blob:"),r=0===t.indexOf("javascript:");if(!e&&!r){if(!this.startsWithOneOf(t,this.VALID_PREFIXES)&&!this.startsWith(t,"/")&&!this.startsWithOneOf(t,this.BAD_PREFIXES)){var i=this.resolveRelUrl(t,this.$wbwindow.document);return this.rewriteUrl(i,!1,"wkr_",this.$wbwindow.document)}return this.rewriteUrl(t,!1,"wkr_",this.$wbwindow.document)}var o=r?t.replace("javascript:",""):null;if(e){var n=new XMLHttpRequest;this.utilFns.XHRopen.call(n,"GET",t,!1),this.utilFns.XHRsend.call(n),o=n.responseText.replace(this.workerBlobRe,"").replace(this.rmCheckThisInjectRe,"this")}if(this.wb_info.static_prefix||this.wb_info.ww_rw_script){var s=this.$wbwindow.document.baseURI;o="(function() { self.importScripts(\'"+(this.wb_info.ww_rw_script||this.wb_info.static_prefix+"wombatWorkers.js")+"\'); new WBWombat({\'prefix\': \'"+this.wb_abs_prefix+"\', \'prefixMod\': \'"+this.wb_abs_prefix+"wkrf_/\', \'originalURL\': \'"+s+"\'}); })();"+o}var a=new Blob([o],{type:"application/javascript"});return URL.createObjectURL(a)},f.prototype.rewriteTextNodeFn=function(t,e,r){var i,o=this.proxyToObj(t);if(r.length>0&&o.parentElement&&"STYLE"===o.parentElement.tagName){i=new Array(r.length);var n=r.length-1;2===n?(i[0]=r[0],i[1]=r[1]):1===n&&(i[0]=r[0]),i[n]=this.rewriteStyle(r[n])}else i=r;return e.__WB_orig_apply?e.__WB_orig_apply(o,i):e.apply(o,i)},f.prototype.rewriteChildNodeFn=function(t,e,r){var i=this.proxyToObj(t);if(0===r.length)return e.call(i);var o=this.rewriteElementsInArguments(r);return e.__WB_orig_apply?e.__WB_orig_apply(i,o):e.apply(i,o)},f.prototype.rewriteInsertAdjHTMLOrElemArgs=function(t,e,r,i,o){var n=this.proxyToObj(t);return n._no_rewrite?e.call(n,r,i):o?e.call(n,r,this.rewriteHtml(i)):(this.rewriteElemComplete(i),e.call(n,r,i))},f.prototype.rewriteSetTimeoutInterval=function(t,e,r){var i=this.isString(r[0]),o=i?new Array(r.length):r;if(i){this.$wbwindow.Proxy?o[0]=this.wrapScriptTextJsProxy(r[0]):o[0]=r[0].replace(/\\blocation\\b/g,"WB_wombat_$&");for(var n=1;n(t.includes(r)&&(i=o.rewriteStyle(i)),e[r]=i,!0),get(t,i,n){var s=t[i];return"function"!=typeof s||"setProperty"!==i&&!o.isNativeFunction(s)?s:(r[i]||(r[i]=s.bind(e)),r[i])}})}))},f.prototype.overrideIframeContentAccess=function(t){if(this.$wbwindow.HTMLIFrameElement&&this.$wbwindow.HTMLIFrameElement.prototype){var e=this.$wbwindow.HTMLIFrameElement.prototype,r=this.getOrigGetter(e,t);if(r){var i=this.getOrigSetter(e,t),o=this;this.defProp(e,t,i,(function(){return o.initIframeWombat(this),o.objToProxy(r.call(this))})),e["_get_"+t]=r}}},f.prototype.overrideFramesAccess=function(t){if(!t.Proxy||t!==t.frames){t.__wb_frames=t.frames;var e=this,r=function(){for(var t=0;t0&&i(this.$wbwindow.CSSStyleValue,"parse"),this.$wbwindow.CSSStyleValue.parseAll&&this.$wbwindow.CSSStyleValue.parseAll.toString().indexOf("[native code]")>0&&i(this.$wbwindow.CSSStyleValue,"parseAll")}if(this.$wbwindow.CSSKeywordValue&&this.$wbwindow.CSSKeywordValue.prototype){var o=this.$wbwindow.CSSKeywordValue;this.$wbwindow.CSSKeywordValue=(t=this.$wbwindow.CSSKeywordValue,function(e){return r.domConstructorErrorChecker(this,"CSSKeywordValue",arguments),new t(r.rewriteStyle(e))}),this.$wbwindow.CSSKeywordValue.prototype=o.prototype,Object.defineProperty(this.$wbwindow.CSSKeywordValue.prototype,"constructor",{value:this.$wbwindow.CSSKeywordValue}),e(this.$wbwindow.CSSKeywordValue,"CSSKeywordValue")}if(this.$wbwindow.StylePropertyMap&&this.$wbwindow.StylePropertyMap.prototype){var n=this.$wbwindow.StylePropertyMap.prototype.set;this.$wbwindow.StylePropertyMap.prototype.set=function(){if(arguments.length<=1)return n.__WB_orig_apply?n.__WB_orig_apply(this,arguments):n.apply(this,arguments);var t=new Array(arguments.length);t[0]=arguments[0];for(var e=1;e")&&(e[0]=r.rewriteHtml(e[0]),i.type="text/html"),new t(e,i)}),this.$wbwindow.Blob.prototype=e.prototype}},f.prototype.initWSOverride=function(){this.$wbwindow.WebSocket&&this.$wbwindow.WebSocket.prototype&&(this.$wbwindow.WebSocket=function(t){function e(t,e){this.addEventListener=function(){},this.removeEventListener=function(){},this.close=function(){},this.send=function(t){console.log("ws send",t)},this.protocol=e&&e.length?e[0]:"",this.url=t,this.readyState=0}return e.CONNECTING=0,e.OPEN=1,e.CLOSING=2,e.CLOSED=3,e}(this.$wbwindow.WebSocket),Object.defineProperty(this.$wbwindow.WebSocket.prototype,"constructor",{value:this.$wbwindow.WebSocket}),e(this.$wbwindow.WebSocket,"WebSocket"))},f.prototype.initDocTitleOverride=function(){var t=this.getOrigGetter(this.$wbwindow.document,"title"),e=this.getOrigSetter(this.$wbwindow.document,"title"),r=this;this.defProp(this.$wbwindow.document,"title",(function(t){var i=e.call(this,t),o={wb_type:"title",title:t};return r.sendTopMessage(o),i}),t)},f.prototype.initFontFaceOverride=function(){if(this.$wbwindow.FontFace){var t,r=this,i=this.$wbwindow.FontFace;this.$wbwindow.FontFace=(t=this.$wbwindow.FontFace,function(e,i,o){r.domConstructorErrorChecker(this,"FontFace",arguments,2);var n=i;return null!=i&&(n="string"!=typeof i?r.rewriteInlineStyle(i.toString()):r.rewriteInlineStyle(i)),new t(e,n,o)}),this.$wbwindow.FontFace.prototype=i.prototype,Object.defineProperty(this.$wbwindow.FontFace.prototype,"constructor",{value:this.$wbwindow.FontFace}),e(this.$wbwindow.FontFace,"FontFace")}},f.prototype.initFixedRatio=function(t){try{this.$wbwindow.devicePixelRatio=t}catch(t){}if(Object.defineProperty)try{Object.defineProperty(this.$wbwindow,"devicePixelRatio",{value:t,writable:!1})}catch(t){}},f.prototype.initPaths=function(t){t.wombat_opts=t.wombat_opts||{},Object.assign(this.wb_info,t),this.wb_opts=t.wombat_opts,this.wb_replay_prefix=t.prefix,this.wb_is_proxy=t.proxy_magic||!this.wb_replay_prefix,this.wb_info.top_host=this.wb_info.top_host||"*",this.wb_curr_host=this.$wbwindow.location.protocol+"//"+this.$wbwindow.location.host,this.wb_info.wombat_opts=this.wb_info.wombat_opts||{},this.wb_orig_scheme=t.wombat_scheme+"://",this.wb_orig_origin=this.wb_orig_scheme+t.wombat_host,this.wb_abs_prefix=this.wb_replay_prefix,!t.is_live&&t.wombat_ts?this.wb_capture_date_part="/"+t.wombat_ts+"/":this.wb_capture_date_part="",this.initBadPrefixes(this.wb_replay_prefix),this.initCookiePreset()},f.prototype.initSeededRandom=function(t){this.$wbwindow.Math.seed=parseInt(t);var e=this;this.$wbwindow.Math.random=function(){return e.$wbwindow.Math.seed=(9301*e.$wbwindow.Math.seed+49297)%233280,e.$wbwindow.Math.seed/233280}},f.prototype.initHistoryOverrides=function(){this.overrideHistoryFunc("pushState"),this.overrideHistoryFunc("replaceState");var t=this;this.$wbwindow.addEventListener("popstate",(function(e){t.sendHistoryUpdate(t.$wbwindow.WB_wombat_location.href,t.$wbwindow.document.title)}))},f.prototype.initCookiePreset=function(){if(this.wb_info.presetCookie)for(var t=this.wb_info.presetCookie.split(";"),e=0;e2&&!this.__WB_xhr_open_arguments[2]&&-1===navigator.userAgent.indexOf("Firefox")&&(this.__WB_xhr_open_arguments[2]=!0,console.warn("wombat.js: Sync XHR not supported in SW-based replay in this browser, converted to async")),this._no_rewrite||(this.__WB_xhr_open_arguments[1]=i.rewriteUrl(this.__WB_xhr_open_arguments[1])),o.apply(this,this.__WB_xhr_open_arguments),!i.startsWith(this.__WB_xhr_open_arguments[1],"data:")){for(const[t,e]of this.__WB_xhr_headers.entries())n.call(this,t,e);n.call(this,"X-Pywb-Requested-With","XMLHttpRequest")}return s.call(this,t)}}else if(this.$wbwindow.XMLHttpRequest.prototype.open){var h=this.$wbwindow.XMLHttpRequest.prototype.open;this.utilFns.XHRopen=h,this.utilFns.XHRsend=this.$wbwindow.XMLHttpRequest.prototype.send,this.$wbwindow.XMLHttpRequest.prototype.open=function(t,e,r,o,n){var s=this._no_rewrite?e:i.rewriteUrl(e),a=!0;null==r||r||(a=!1),h.call(this,t,s,a,o,n),i.startsWith(s,"data:")||this.setRequestHeader("X-Pywb-Requested-With","XMLHttpRequest")}}if(this.$wbwindow.fetch){var w=this.$wbwindow.fetch;this.$wbwindow.fetch=function(t,e){var r=t,o=typeof t;if("string"===o)r=i.rewriteUrl(t);else if("object"===o&&t.url){var n=i.rewriteUrl(t.url);n!==t.url&&(r=new Request(n,e))}else"object"===o&&t.href&&(r=i.rewriteUrl(t.href));if(e||(e={}),void 0===e.credentials)try{e.credentials="include"}catch(t){}return w.call(i.proxyToObj(this),r,e)}}if(this.$wbwindow.Request&&this.$wbwindow.Request.prototype){var p=this.$wbwindow.Request;this.$wbwindow.Request=(t=this.$wbwindow.Request,function(e,r){i.domConstructorErrorChecker(this,"Request",arguments);var o=r||{},n=e,s=typeof e;switch(s){case"string":n=i.rewriteUrl(e);break;case"object":if(n=e,e.url){var a=i.rewriteUrl(e.url);a!==e.url&&(n=new t(a,e))}else e.href&&(n=i.rewriteUrl(e.toString(),!0))}return o.credentials="include",o.referrer&&(o.referrer=i.rewriteUrl(o.referrer)),new t(n,o)}),this.$wbwindow.Request.prototype=p.prototype,Object.defineProperty(this.$wbwindow.Request.prototype,"constructor",{value:this.$wbwindow.Request}),this.overridePropExtract(this.$wbwindow.Request.prototype,"url"),this.overridePropExtract(this.$wbwindow.Request.prototype,"referrer")}if(this.$wbwindow.Response&&this.$wbwindow.Response.prototype){var c=this.$wbwindow.Response.prototype.redirect;this.$wbwindow.Response.prototype.redirect=function(t,e){var r=i.rewriteUrl(t,!0,null,i.$wbwindow.document);return c.call(this,r,e)},this.overridePropExtract(this.$wbwindow.Response.prototype,"url")}if(this.$wbwindow.EventSource&&this.$wbwindow.EventSource.prototype){var l=this.$wbwindow.EventSource;this.$wbwindow.EventSource=(r=this.$wbwindow.EventSource,function(t,e){i.domConstructorErrorChecker(this,"EventSource",arguments);var o=t;return null!=t&&(o=i.rewriteUrl(t)),new r(o,e)}),this.$wbwindow.EventSource.prototype=l.prototype,Object.defineProperty(this.$wbwindow.EventSource.prototype,"constructor",{value:this.$wbwindow.EventSource}),e(this.$wbwindow.EventSource,"EventSource")}},f.prototype.initElementGetSetAttributeOverride=function(){if(!this.wb_opts.skip_setAttribute&&this.$wbwindow.Element&&this.$wbwindow.Element.prototype){var t=this,e=this.$wbwindow.Element.prototype;if(e.setAttribute){var r=e.setAttribute;e._orig_setAttribute=r,e.setAttribute=function(e,i){var o=i;if(e&&"string"==typeof o){var n=e.toLowerCase();if("LINK"===this.tagName&&"href"===n&&0===o.indexOf("data:text/css"))o=t.rewriteInlineStyle(i);else if("style"===n)o=t.rewriteStyle(i);else if("srcset"===n||"imagesrcset"===n&&"LINK"===this.tagName)o=t.rewriteSrcset(i,this);else{t.shouldRewriteAttr(this.tagName,n)&&(t.removeWBOSRC(this),this._no_rewrite||(o=t.rewriteUrl(i,!1,t.rwModForElement(this,n))))}}return r.call(this,e,o)}}if(e.getAttribute){var i=e.getAttribute;this.wb_getAttribute=i,e.getAttribute=function(e){var r=i.call(this,e);if(null===r)return r;var o=e;if(e&&(o=e.toLowerCase()),t.shouldRewriteAttr(this.tagName,o)){var n=t.retrieveWBOSRC(this);return n||t.extractOriginalURL(r)}return t.startsWith(o,"data-")&&t.startsWithOneOf(r,t.wb_prefixes)?t.extractOriginalURL(r):r}}}},f.prototype.initSvgImageOverrides=function(){if(this.$wbwindow.SVGImageElement){var t=this.$wbwindow.SVGImageElement.prototype,e=t.getAttribute,r=t.getAttributeNS,i=t.setAttribute,o=t.setAttributeNS,n=this;t.getAttribute=function(t){var r=e.call(this,t);return t.indexOf("xlink:href")>=0||"href"===t?n.extractOriginalURL(r):r},t.getAttributeNS=function(t,e){var i=r.call(this,t,e);return e.indexOf("xlink:href")>=0||"href"===e?n.extractOriginalURL(i):i},t.setAttribute=function(t,e){var r=e;return(t.indexOf("xlink:href")>=0||"href"===t)&&(r=n.rewriteUrl(e)),i.call(this,t,r)},t.setAttributeNS=function(t,e,r){var i=r;return(e.indexOf("xlink:href")>=0||"href"===e)&&(i=n.rewriteUrl(r)),o.call(this,t,e,i)}}},f.prototype.initCreateElementNSFix=function(){if(this.$wbwindow.document.createElementNS&&this.$wbwindow.Document.prototype.createElementNS){var t=this.$wbwindow.document.createElementNS,e=this,r=function(r,i){return t.call(e.proxyToObj(this),e.extractOriginalURL(r),i)};this.$wbwindow.Document.prototype.createElementNS=r,this.$wbwindow.document.createElementNS=r}},f.prototype.initInsertAdjacentElementHTMLOverrides=function(){var t=this.$wbwindow.Element;if(t&&t.prototype){var e=t.prototype,r=this.rewriteInsertAdjHTMLOrElemArgs;if(e.insertAdjacentHTML){var i=e.insertAdjacentHTML;e.insertAdjacentHTML=function(t,e){return r(this,i,t,e,!0)}}if(e.insertAdjacentElement){var o=e.insertAdjacentElement;e.insertAdjacentElement=function(t,e){return r(this,o,t,e,!1)}}}},f.prototype.initDomOverride=function(){var t=this.$wbwindow.Node;if(t&&t.prototype){var e=this.rewriteNodeFuncArgs;if(t.prototype.appendChild){var r=t.prototype.appendChild;t.prototype.appendChild=function(t,i){return e(this,r,t,i)}}if(t.prototype.insertBefore){var i=t.prototype.insertBefore;t.prototype.insertBefore=function(t,r){return e(this,i,t,r)}}if(t.prototype.replaceChild){var o=t.prototype.replaceChild;t.prototype.replaceChild=function(t,r){return e(this,o,t,r)}}this.overridePropToProxy(t.prototype,"ownerDocument"),this.overridePropToProxy(this.$wbwindow.HTMLHtmlElement.prototype,"parentNode"),this.overridePropToProxy(this.$wbwindow.Event.prototype,"target")}this.$wbwindow.Element&&this.$wbwindow.Element.prototype&&(this.overrideParentNodeAppendPrepend(this.$wbwindow.Element),this.overrideChildNodeInterface(this.$wbwindow.Element,!1)),this.$wbwindow.DocumentFragment&&this.$wbwindow.DocumentFragment.prototype&&this.overrideParentNodeAppendPrepend(this.$wbwindow.DocumentFragment)},f.prototype.initDocOverrides=function(t){if(Object.defineProperty){this.overrideReferrer(t),this.defGetterProp(t,"origin",(function(){return this.WB_wombat_location.origin})),this.defGetterProp(this.$wbwindow,"origin",(function(){return this.WB_wombat_location.origin}));var e=this;this.defProp(t,"domain",(function(t){var r=this.WB_wombat_location;r&&e.endsWith(r.hostname,t)&&(this.__wb_domain=t)}),(function(){return this.__wb_domain||this.WB_wombat_location.hostname}))}},f.prototype.initDocWriteOpenCloseOverride=function(){if(this.$wbwindow.DOMParser){var t=this.$wbwindow.Document.prototype,e=this.$wbwindow.document;this._writeBuff="";var r=this,i=e.write,o=function(){return d(this,i,u(arguments))};e.write=o,t.write=o;var n=e.writeln,s=function(){return d(this,n,u(arguments))};e.writeln=s,t.writeln=s;var a=e.open,h=function(){var t,e=r.proxyToObj(this);if(3===arguments.length){var i=r.rewriteUrl(arguments[0],!1,"mp_");t=a.call(e,i,arguments[1],arguments[2]),r.initNewWindowWombat(t,arguments[0])}else t=a.call(e),_()?r._writeBuff="":r.initNewWindowWombat(e.defaultView);return t};e.open=h,t.open=h;var w=e.close,p=function(){if(r._writeBuff)return r.blobUrlForIframe(r.$wbwindow.frameElement,r._writeBuff),void(r._writeBuff="");var t=r.proxyToObj(this);return r.initNewWindowWombat(t.defaultView),w.__WB_orig_apply?w.__WB_orig_apply(t,arguments):w.apply(t,arguments)};e.close=p,t.close=p;var c=this.getOrigGetter(t,"body"),l=this.getOrigSetter(t,"body");c&&l&&this.defProp(t,"body",(function(t){return t&&(t instanceof HTMLBodyElement||t instanceof HTMLFrameSetElement)&&r.rewriteElemComplete(t),l.call(r.proxyToObj(this),t)}),c)}function _(){return r.wb_info.isSW&&r.$wbwindow.frameElement}function u(t){return 0===t.length?"":1===t.length?t[0]:Array.prototype.join.call(t,"")}function d(t,e,i){r.$wbwindow;if(!_()){i=r.rewriteHtml(i,!0);var o=r.proxyToObj(t),n=e.call(o,i);return r.initNewWindowWombat(o.defaultView),n}r._writeBuff+=i}},f.prototype.initIframeWombat=function(t){var e;e=t._get_contentWindow?t._get_contentWindow.call(t):t.contentWindow;try{if(!e||e===this.$wbwindow||e._skip_wombat||e._wb_wombat)return}catch(t){return}var r=t.src;this.initNewWindowWombat(e,r)},f.prototype.initNewWindowWombat=function(t,e){var r=!1;if(t&&!t._wb_wombat){if(e&&""!==e&&!this.startsWithOneOf(e,["about:blank","javascript:"])||(r=!0),!r&&this.wb_info.isSW){var i=this.extractOriginalURL(e);("about:blank"===i||i.startsWith("srcdoc:")||i.startsWith("blob:"))&&(r=!0)}if(r){var o={};Object.assign(o,this.wb_info);var n=new f(t,o);t._wb_wombat=n.wombatInit()}else this.initProtoPmOrigin(t),this.initPostMessageOverride(t),this.initMessageEventOverride(t),this.initCheckThisFunc(t),this.initImportWrapperFunc(t)}},f.prototype.initTimeoutIntervalOverrides=function(){var t=this.rewriteSetTimeoutInterval;if(this.$wbwindow.setTimeout&&!this.$wbwindow.setTimeout.__$wbpatched$__){var e=this.$wbwindow.setTimeout;this.$wbwindow.setTimeout=function(){return t(this,e,arguments)},this.$wbwindow.setTimeout.__$wbpatched$__=!0}if(this.$wbwindow.setInterval&&!this.$wbwindow.setInterval.__$wbpatched$__){var r=this.$wbwindow.setInterval;this.$wbwindow.setInterval=function(){return t(this,r,arguments)},this.$wbwindow.setInterval.__$wbpatched$__=!0}},f.prototype.initWorkerOverrides=function(){var t,e,r=this;if(this.$wbwindow.Worker&&!this.$wbwindow.Worker._wb_worker_overridden){var i=this.$wbwindow.Worker;this.$wbwindow.Worker=(t=i,function(e,i){return r.domConstructorErrorChecker(this,"Worker",arguments),new t(r.rewriteWorker(e),i)}),this.$wbwindow.Worker.prototype=i.prototype,Object.defineProperty(this.$wbwindow.Worker.prototype,"constructor",{value:this.$wbwindow.Worker}),this.$wbwindow.Worker._wb_worker_overridden=!0}if(this.$wbwindow.SharedWorker&&!this.$wbwindow.SharedWorker.__wb_sharedWorker_overridden){var o=this.$wbwindow.SharedWorker;this.$wbwindow.SharedWorker=(e=o,function(t,i){return r.domConstructorErrorChecker(this,"SharedWorker",arguments),new e(r.rewriteWorker(t),i)}),this.$wbwindow.SharedWorker.prototype=o.prototype,Object.defineProperty(this.$wbwindow.SharedWorker.prototype,"constructor",{value:this.$wbwindow.SharedWorker}),this.$wbwindow.SharedWorker.__wb_sharedWorker_overridden=!0}if(this.$wbwindow.ServiceWorkerContainer&&this.$wbwindow.ServiceWorkerContainer.prototype&&this.$wbwindow.ServiceWorkerContainer.prototype.register){var n=this.$wbwindow.ServiceWorkerContainer.prototype.register;this.$wbwindow.ServiceWorkerContainer.prototype.register=function(t,e){var i=new URL(t,r.$wbwindow.document.baseURI).href,o=r.getPageUnderModifier();return e&&e.scope?e.scope=r.rewriteUrl(e.scope,!1,o):e={scope:r.rewriteUrl("/",!1,o)},n.call(this,r.rewriteUrl(i,!1,"sw_"),e)}}if(this.$wbwindow.Worklet&&this.$wbwindow.Worklet.prototype&&this.$wbwindow.Worklet.prototype.addModule&&!this.$wbwindow.Worklet.__wb_workerlet_overridden){var s=this.$wbwindow.Worklet.prototype.addModule;this.$wbwindow.Worklet.prototype.addModule=function(t,e){var i=r.rewriteUrl(t,!1,"js_");return s.call(this,i,e)},this.$wbwindow.Worklet.__wb_workerlet_overridden=!0}},f.prototype.initLocOverride=function(t,e,r){if(Object.defineProperty)for(var i=0;i=0&&i.splice(n,1)}return i}})}catch(t){console.log(t)}},f.prototype.initHashChange=function(){if(this.$wbwindow.__WB_top_frame){var t=this;this.$wbwindow.addEventListener("message",(function(e){if(e.data&&e.data.from_top){var r=e.data.message;r.wb_type&&"outer_hashchange"===r.wb_type&&t.$wbwindow.location.hash!=r.hash&&(t.$wbwindow.location.hash=r.hash)}})),this.$wbwindow.addEventListener("hashchange",(function(){var e={wb_type:"hashchange",hash:t.$wbwindow.location.hash};t.sendTopMessage(e)}))}},f.prototype.initPostMessageOverride=function(t){if(t.postMessage&&!t.__orig_postMessage){var e=t.postMessage,r=this;t.__orig_postMessage=e;var i=function(i,o,n,s){var a,h,w=r.proxyToObj(this);if(w||((w=t).__WB_source=t),w.__WB_source&&w.__WB_source.WB_wombat_location){var p=w.__WB_source;if(a=p.WB_wombat_location.origin,w.__WB_win_id||(w.__WB_win_id={},w.__WB_counter=0),!p.__WB_id){var c=w.__WB_counter;p.__WB_id=c+p.WB_wombat_location.href,w.__WB_counter+=1}w.__WB_win_id[p.__WB_id]=p,h=p.__WB_id,w.__WB_source=void 0}else a=window.WB_wombat_location.origin;var l=o;l===w.location.origin&&(l=a);var _={from:a,to_origin:l,src_id:h,message:i,from_top:s};if("*"!==o){if("null"===w.location.origin||""===w.location.origin)return;o=w.location.origin}return e.call(w,_,o,n)};t.postMessage=i,t.Window.prototype.postMessage=i;var o=null,n=(o=t.EventTarget&&t.EventTarget.prototype?t.EventTarget.prototype:t).addEventListener;o.addEventListener=function(t,e,i){var o,s=r.proxyToObj(this);if("message"===t?o=r.message_listeners.add_or_get(e,(function(){return c(e,s,r)})):"storage"===t?r.storage_listeners.add_or_get(e,(function(){return p(e,s)})):o=e,o)return n.call(s,t,o,i)};var s=o.removeEventListener;o.removeEventListener=function(t,e,i){var o,n=r.proxyToObj(this);if("message"===t?o=r.message_listeners.remove(e):"storage"===t?r.storage_listeners.remove(e):o=e,o)return s.call(n,t,o,i)};var a=function(e,i){var o=r.getOrigSetter(t,e);r.defProp(t,e,(function(t){this["__orig_"+e]=t;var n=r.proxyToObj(this),s=t?i(t,n,r):t;return o.call(n,s)}),(function(){return this["__orig_"+e]}))};a("onmessage",c),a("onstorage",p)}},f.prototype.initMessageEventOverride=function(t){t.MessageEvent&&!t.MessageEvent.prototype.__extended&&(this.addEventOverride("target"),this.addEventOverride("srcElement"),this.addEventOverride("currentTarget"),this.addEventOverride("eventPhase"),this.addEventOverride("path"),this.overridePropToProxy(t.MessageEvent.prototype,"source"),t.MessageEvent.prototype.__extended=!0)},f.prototype.initUIEventsOverrides=function(){this.overrideAnUIEvent("UIEvent"),this.overrideAnUIEvent("MouseEvent"),this.overrideAnUIEvent("TouchEvent"),this.overrideAnUIEvent("FocusEvent"),this.overrideAnUIEvent("KeyboardEvent"),this.overrideAnUIEvent("WheelEvent"),this.overrideAnUIEvent("InputEvent"),this.overrideAnUIEvent("CompositionEvent")},f.prototype.initOpenOverride=function(){var t=this.$wbwindow.open;this.$wbwindow.Window.prototype.open&&(t=this.$wbwindow.Window.prototype.open);var e=this,r=function(r,i,o){i&&(i=e.rewriteAttrTarget(i));var n=e.rewriteUrl(r,!1),s=t.call(e.proxyToObj(this),n,i,o);return e.initNewWindowWombat(s,r),s};this.$wbwindow.open=r,this.$wbwindow.Window.prototype.open&&(this.$wbwindow.Window.prototype.open=r);for(var i=0;i}\n */\nWBWombat.prototype.rewriteArgs = function(argsObj) {\n // recreate the original arguments object just with URLs rewritten\n var newArgObj = new Array(argsObj.length);\n for (var i = 0; i < newArgObj.length; i++) {\n newArgObj[i] = this.rewriteURL(argsObj[i]);\n }\n return newArgObj;\n};\n\n/**\n * Rewrites the input to one of the Fetch APIs\n * @param {*|string|Request} input\n * @return {*|string|Request}\n */\nWBWombat.prototype.rewriteFetchApi = function(input) {\n var rwInput = input;\n switch (typeof input) {\n case 'string':\n rwInput = this.rewriteURL(input);\n break;\n case 'object':\n if (input.url) {\n var new_url = this.rewriteURL(input.url);\n if (new_url !== input.url) {\n // not much we can do here Request.url is read only\n // https://developer.mozilla.org/en-US/docs/Web/API/Request/url\n rwInput = new Request(new_url, input);\n }\n } else if (input.href) {\n // it is likely that input is either self.location or self.URL\n // we cant do anything here so just let it go\n rwInput = input.href;\n }\n break;\n }\n return rwInput;\n};\n\n/**\n * Rewrites the input to one of the Cache APIs\n * @param {*|string|Request} request\n * @return {*|string|Request}\n */\nWBWombat.prototype.rewriteCacheApi = function(request) {\n var rwRequest = request;\n if (typeof request === 'string') {\n rwRequest = this.rewriteURL(request);\n }\n return rwRequest;\n};\n\n/**\n * Applies an override to the importScripts function\n * @see https://html.spec.whatwg.org/multipage/workers.html#dom-workerglobalscope-importscripts\n */\nWBWombat.prototype.initImportScriptsRewrite = function() {\n if (!self.importScripts) return;\n var wombat = this;\n var origImportScripts = self.importScripts;\n self.importScripts = function importScripts() {\n // rewrite the arguments object and call original function via fn.apply\n var rwArgs = wombat.rewriteArgs(arguments);\n return origImportScripts.apply(this, rwArgs);\n };\n};\n\n/**\n * Applies overrides to the XMLHttpRequest.open and XMLHttpRequest.responseURL\n * in order to ensure URLs are rewritten.\n *\n * Applies an override to window.fetch in order to rewrite URLs and URLs of\n * the supplied Request objects used as arguments to fetch.\n *\n * Applies overrides to window.Request, window.Response, window.EventSource,\n * and window.WebSocket in order to ensure URLs they operate on are rewritten.\n *\n * @see https://xhr.spec.whatwg.org/\n * @see https://fetch.spec.whatwg.org/\n * @see https://html.spec.whatwg.org/multipage/web-sockets.html#websocket\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface\n */\nWBWombat.prototype.initHTTPOverrides = function() {\n var wombat = this;\n if (\n self.XMLHttpRequest &&\n self.XMLHttpRequest.prototype &&\n self.XMLHttpRequest.prototype.open\n ) {\n var oXHROpen = self.XMLHttpRequest.prototype.open;\n self.XMLHttpRequest.prototype.open = function open(\n method,\n url,\n async,\n user,\n password\n ) {\n var rwURL = wombat.rewriteURL(url);\n var openAsync = true;\n if (async != null && !async) openAsync = false;\n oXHROpen.call(this, method, rwURL, openAsync, user, password);\n if (rwURL.indexOf('data:') === -1) {\n this.setRequestHeader('X-Pywb-Requested-With', 'XMLHttpRequest');\n }\n };\n }\n\n if (self.fetch != null) {\n // this fetch is Worker.fetch\n var orig_fetch = self.fetch;\n self.fetch = function fetch(input, init_opts) {\n var rwInput = wombat.rewriteFetchApi(input);\n var newInitOpts = init_opts || {};\n newInitOpts['credentials'] = 'include';\n return orig_fetch.call(this, rwInput, newInitOpts);\n };\n }\n\n if (self.Request && self.Request.prototype) {\n var orig_request = self.Request;\n self.Request = (function(Request_) {\n return function Request(input, init_opts) {\n var newInitOpts = init_opts || {};\n var newInput = wombat.rewriteFetchApi(input);\n newInitOpts['credentials'] = 'include';\n return new Request_(newInput, newInitOpts);\n };\n })(self.Request);\n self.Request.prototype = orig_request.prototype;\n }\n\n if (self.Response && self.Response.prototype) {\n var originalRedirect = self.Response.prototype.redirect;\n self.Response.prototype.redirect = function redirect(url, status) {\n var rwURL = wombat.rewriteUrl(url);\n return originalRedirect.call(this, rwURL, status);\n };\n }\n\n if (self.EventSource && self.EventSource.prototype) {\n var origEventSource = self.EventSource;\n self.EventSource = (function(EventSource_) {\n return function EventSource(url, configuration) {\n var rwURL = url;\n if (url != null) {\n rwURL = wombat.rewriteUrl(url);\n }\n return new EventSource_(rwURL, configuration);\n };\n })(self.EventSource);\n self.EventSource.prototype = origEventSource.prototype;\n Object.defineProperty(self.EventSource.prototype, 'constructor', {\n value: self.EventSource\n });\n }\n\n if (self.WebSocket && self.WebSocket.prototype) {\n var origWebSocket = self.WebSocket;\n self.WebSocket = (function(WebSocket_) {\n return function WebSocket(url, configuration) {\n var rwURL = url;\n if (url != null) {\n rwURL = wombat.rewriteWSURL(url);\n }\n return new WebSocket_(rwURL, configuration);\n };\n })(self.WebSocket);\n self.WebSocket.prototype = origWebSocket.prototype;\n Object.defineProperty(self.WebSocket.prototype, 'constructor', {\n value: self.WebSocket\n });\n }\n};\n\n/**\n * Applies an override to Clients.openWindow and WindowClient.navigate that rewrites\n * the supplied URL that represents a controlled window\n * @see https://w3c.github.io/ServiceWorker/#window-client-interface\n * @see https://w3c.github.io/ServiceWorker/#clients-interface\n */\nWBWombat.prototype.initClientApisOverride = function() {\n var wombat = this;\n if (\n self.Clients &&\n self.Clients.prototype &&\n self.Clients.prototype.openWindow\n ) {\n var oClientsOpenWindow = self.Clients.prototype.openWindow;\n self.Clients.prototype.openWindow = function openWindow(url) {\n var rwURL = wombat.rewriteClientWindowURL(url);\n return oClientsOpenWindow.call(this, rwURL);\n };\n }\n\n if (\n self.WindowClient &&\n self.WindowClient.prototype &&\n self.WindowClient.prototype.navigate\n ) {\n var oWinClientNavigate = self.WindowClient.prototype.navigate;\n self.WindowClient.prototype.navigate = function navigate(url) {\n var rwURL = wombat.rewriteClientWindowURL(url, this);\n return oWinClientNavigate.call(this, rwURL);\n };\n }\n};\n\n/**\n * Applies overrides to the CacheStorage and Cache interfaces in order\n * to rewrite the URLs they operate on\n * @see https://w3c.github.io/ServiceWorker/#cachestorage\n * @see https://w3c.github.io/ServiceWorker/#cache-interface\n */\nWBWombat.prototype.initCacheApisOverride = function() {\n var wombat = this;\n if (\n self.CacheStorage &&\n self.CacheStorage.prototype &&\n self.CacheStorage.prototype.match\n ) {\n var oCacheStorageMatch = self.CacheStorage.prototype.match;\n self.CacheStorage.prototype.match = function match(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheStorageMatch.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache && self.Cache.prototype) {\n if (self.Cache.prototype.match) {\n var oCacheMatch = self.Cache.prototype.match;\n self.Cache.prototype.match = function match(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheMatch.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache.prototype.matchAll) {\n var oCacheMatchAll = self.Cache.prototype.matchAll;\n self.Cache.prototype.matchAll = function matchAll(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheMatchAll.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache.prototype.add) {\n var oCacheAdd = self.Cache.prototype.add;\n self.Cache.prototype.add = function add(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheAdd.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache.prototype.addAll) {\n var oCacheAddAll = self.Cache.prototype.addAll;\n self.Cache.prototype.addAll = function addAll(requests) {\n var rwRequests = requests;\n if (Array.isArray(requests)) {\n rwRequests = new Array(requests.length);\n for (var i = 0; i < requests.length; i++) {\n rwRequests[i] = wombat.rewriteCacheApi(requests[i]);\n }\n }\n return oCacheAddAll.call(this, rwRequests);\n };\n }\n\n if (self.Cache.prototype.put) {\n var oCachePut = self.Cache.prototype.put;\n self.Cache.prototype.put = function put(request, response) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCachePut.call(this, rwRequest, response);\n };\n }\n\n if (self.Cache.prototype.delete) {\n var oCacheDelete = self.Cache.prototype.delete;\n self.Cache.prototype.delete = function newCacheDelete(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheDelete.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache.prototype.keys) {\n var oCacheKeys = self.Cache.prototype.keys;\n self.Cache.prototype.keys = function keys(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheKeys.call(this, rwRequest, options);\n };\n }\n }\n};\n\nself.WBWombat = WBWombat;\n"}),r.injectScripts&&(r.injectScripts=r.injectScripts.map((t=>this.staticPrefix+"proxy/"+t))),this.collections=new i(o,n.get("root"),r),this.collections.loadAll(n.get("dbColl")),this.proxyOriginMode=!!n.get("proxyOriginMode"),this.api=new e(this.collections),this.apiPrefix=this.replayPrefix+"api/",this.allowRewrittenCache=!!n.get("allowCache"),this.stats=n.get("stats")?new Yy:null,self.addEventListener("install",(()=>{self.skipWaiting()})),self.addEventListener("activate",(t=>{t.waitUntil(self.clients.claim()),console.log("Activate!")})),self.addEventListener("fetch",(t=>{t.respondWith(this.handleFetch(t))})),self.addEventListener("message",(t=>{"reload_all"===t.data.msg_type&&t.waitUntil(this.collections.loadAll())}))}handleFetch(t){const e=t.request.url;if(this.proxyOriginMode)return this.getResponseFor(t.request,t);if(!e.startsWith(this.prefix))return"chrome-extension://invalid/"===e?S(t.request,"Invalid URL"):this.defaultFetch(t.request);if(this.collections.root&&e.slice(this.prefix.length).indexOf("/")<0)return this.defaultFetch(t.request);if(e.startsWith(this.staticPrefix+"proxy/"))return this.staticPathProxy(e,t.request);if(e.startsWith(this.replayPrefix)&&!e.startsWith(this.staticPrefix))return this.getResponseFor(t.request,t);const r=new URL(e);r.search="",r.hash="";const i=r.href;for(const t of this.staticData.keys())if(t===i){const{content:e,type:r}=this.staticData.get(t);return new Response(e,{headers:{"Content-Type":r}})}return("http:"==r.protocol||"https:"==r.protocol)&&r.pathname.indexOf("/",1)<0?this.handleOffline(t.request):this.defaultFetch(t.request)}staticPathProxy(t,e){return t=t.slice((this.staticPrefix+"proxy/").length),t=new URL(t,self.location.href).href,e=new Request(t),this.defaultFetch(e)}defaultFetch(t){const e={};return"only-if-cached"===t.cache&&"same-origin"!==t.mode&&(e.cache="default"),self.fetch(t,e)}async ensureCached(t){const e=await caches.open("wabac-offline");for(let r of t){r=new URL(r,self.location.href).href;let t=await e.match(r,{ignoreSearch:!0});if(!t)try{t=await this.defaultFetch(r),await e.put(r,t)}catch(t){console.warn(`Failed to Auto Cache: ${r}`,t)}}}async handleOffline(t){let e=null;const r=await caches.open("wabac-offline");try{e=await this.defaultFetch(t)}catch(i){return e=await r.match(t,{ignoreSearch:!0}),e||(e=S(t,"Sorry, this url was not cached for offline use")),e}if(t.url.startsWith(this.prefix+"?"))return e;if(200===e.status){const i=e.clone();await r.put(t,i)}else console.warn(`Not Cacheing ${t.url} - Status ${e.status}`);return e}async getResponseFor(t,e){if(!this.proxyOriginMode&&t.url.startsWith(this.apiPrefix))return this.stats&&t.url.startsWith(this.apiPrefix+"stats.json")?await this.stats.getStats(e):await this.api.apiResponse(t.url.slice(this.apiPrefix.length),t,e);await this.collections.inited;const r=v(t),i=t.headers.get("range");try{if(this.allowRewrittenCache&&!i){const e=await self.caches.match(t);if(e&&!!e.headers.get(bm)===r)return e}}catch(t){}let n=this.collections.root;n||(n=t.url.slice(this.replayPrefix.length).split("/",1)[0]);const s=await this.collections.getColl(n);if(!s||!this.proxyOriginMode&&!t.url.startsWith(s.prefix))return S(t);const o=this.proxyOriginMode?t.url:t.url.substring(s.prefix.length),a={isRoot:!!this.collections.root};this.proxyOriginMode&&(a.mod="id_",a.proxyOrigin=s.config.extraConfig.proxyOrigin,a.localOrigin=self.location.origin);const c=new mm(o,t,a);if(!c.url)return S(t,`Replay URL ${o} not found`);const l=await s.handleRequest(c,e);if(l){if(this.stats&&this.stats.updateStats(l.date,l.status,t,e),this.allowRewrittenCache&&200===l.status)try{const e=await self.caches.open("wabac-"+s.name);r&&l.headers.set(bm,"true");const i=l.clone();await e.put(t,i)}catch(t){console.warn(t)}return l}return i&&console.log("Not Found Range!: "+i),S(t)}}if(self.registration){const t=new Map,r=self.registration.scope;t.set(r,{type:"text/html",content:e}),t.set(r+"index.html",{type:"text/html",content:e});const i={injectScripts:["ruffle/ruffle.js"]};self.ipfsCustomPreload=!0,self.sw=new Em({staticData:t,defaultConfig:i})}else new Ky(self)})();var n=self;for(var s in i)n[s]=i[s];i.__esModule&&Object.defineProperty(n,"__esModule",{value:!0})})(); \ No newline at end of file +const Wg="crypto.algorithm";const jg="crypto.algorithmProvider";var zg;Uf.registerSingleton(jg,class{getAlgorithms(){return Uf.resolveAll(Wg)}toAsnAlgorithm(t){for(const e of this.getAlgorithms()){const r=e.toAsnAlgorithm(t);if(r)return r}if(/[0-9.]+/.test(t.name)){const e=new Oh({algorithm:t.name});if("parameters"in t){const r=t;e.parameters=r.parameters}return e}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(t){for(const e of this.getAlgorithms()){const r=e.toWebAlgorithm(t);if(r)return r}return{name:t.algorithm,parameters:t.parameters}}});const Gg="1.3.36.3.3.2.8.1.1",qg=`${Gg}.1`,Qg=`${Gg}.2`,Vg=`${Gg}.3`,Kg=`${Gg}.4`,Yg=`${Gg}.5`,Jg=`${Gg}.6`,Xg=`${Gg}.7`,Zg=`${Gg}.8`,$g=`${Gg}.9`,tw=`${Gg}.10`,ew=`${Gg}.11`,rw=`${Gg}.12`,iw=`${Gg}.13`,nw=`${Gg}.14`,sw="brainpoolP160r1",ow="brainpoolP160t1",aw="brainpoolP192r1",cw="brainpoolP192t1",lw="brainpoolP224r1",uw="brainpoolP224t1",hw="brainpoolP256r1",pw="brainpoolP256t1",dw="brainpoolP320r1",fw="brainpoolP320t1",gw="brainpoolP384r1",ww="brainpoolP384t1",yw="brainpoolP512r1",mw="brainpoolP512t1",bw="ECDSA";let Aw=zg=class{toAsnAlgorithm(t){if(t.name.toLowerCase()===bw.toLowerCase())if("hash"in t){switch(("string"==typeof t.hash?t.hash:t.hash.name).toLowerCase()){case"sha-1":return Sd;case"sha-256":return Id;case"sha-384":return Cd;case"sha-512":return Rd}}else if("namedCurve"in t){let e="";switch(t.namedCurve){case"P-256":e=Ed;break;case"K-256":e=zg.SECP256K1;break;case"P-384":e=_d;break;case"P-521":e=vd;break;case sw:e=qg;break;case ow:e=Qg;break;case aw:e=Vg;break;case cw:e=Kg;break;case lw:e=Yg;break;case uw:e=Jg;break;case hw:e=Xg;break;case pw:e=Zg;break;case dw:e=$g;break;case fw:e=tw;break;case gw:e=ew;break;case ww:e=rw;break;case yw:e=iw;break;case mw:e=nw}if(e)return new Oh({algorithm:gd,parameters:Kl.serialize(new xd({namedCurve:e}))})}return null}toWebAlgorithm(t){switch(t.algorithm){case wd:return{name:bw,hash:{name:"SHA-1"}};case md:return{name:bw,hash:{name:"SHA-256"}};case bd:return{name:bw,hash:{name:"SHA-384"}};case Ad:return{name:bw,hash:{name:"SHA-512"}};case gd:if(!t.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Kl.parse(t.parameters,xd).namedCurve){case Ed:return{name:bw,namedCurve:"P-256"};case zg.SECP256K1:return{name:bw,namedCurve:"K-256"};case _d:return{name:bw,namedCurve:"P-384"};case vd:return{name:bw,namedCurve:"P-521"};case qg:return{name:bw,namedCurve:sw};case Qg:return{name:bw,namedCurve:ow};case Vg:return{name:bw,namedCurve:aw};case Kg:return{name:bw,namedCurve:cw};case Yg:return{name:bw,namedCurve:lw};case Jg:return{name:bw,namedCurve:uw};case Xg:return{name:bw,namedCurve:hw};case Zg:return{name:bw,namedCurve:pw};case $g:return{name:bw,namedCurve:dw};case tw:return{name:bw,namedCurve:fw};case ew:return{name:bw,namedCurve:gw};case rw:return{name:bw,namedCurve:ww};case iw:return{name:bw,namedCurve:yw};case nw:return{name:bw,namedCurve:mw}}}return null}};Aw.SECP256K1="1.3.132.0.10",Aw=zg=hf([Ff()],Aw),Uf.registerSingleton(Wg,Aw);const Ew=Symbol("name"),_w=Symbol("value");class vw{constructor(t,e={},r=""){this[Ew]=t,this[_w]=r;for(const t in e)this[t]=e[t]}}vw.NAME=Ew,vw.VALUE=_w;class Tw{static toString(t){const e=this.items[t];return e||t}}Tw.items={[Qd]:"sha1",[Vd]:"sha224",[Kd]:"sha256",[Yd]:"sha384",[Jd]:"sha512",[Bd]:"rsaEncryption",[Fd]:"sha1WithRSAEncryption",[Hd]:"sha224WithRSAEncryption",[Wd]:"sha256WithRSAEncryption",[jd]:"sha384WithRSAEncryption",[zd]:"sha512WithRSAEncryption",[gd]:"ecPublicKey",[wd]:"ecdsaWithSHA1",[yd]:"ecdsaWithSHA224",[md]:"ecdsaWithSHA256",[bd]:"ecdsaWithSHA384",[Ad]:"ecdsaWithSHA512",[Ju]:"TLS WWW server authentication",[Xu]:"TLS WWW client authentication",[Zu]:"Code Signing",[$u]:"E-mail Protection",[th]:"Time Stamping",[eh]:"OCSP Signing","1.2.840.113549.1.7.2":"Signed Data"};class Sw{static serialize(t){return this.serializeObj(t).join("\n")}static pad(t=0){return"".padStart(2*t," ")}static serializeObj(t,e=0){const r=[];let i=this.pad(e++),n="";const s=t[vw.VALUE];s&&(n=` ${s}`),r.push(`${i}${t[vw.NAME]}:${n}`),i=this.pad(e);for(const n in t){if("symbol"==typeof n)continue;const s=t[n],o=n?`${n}: `:"";if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)r.push(`${i}${o}${s}`);else if(s instanceof Date)r.push(`${i}${o}${s.toUTCString()}`);else if(Array.isArray(s))for(const t of s)t[vw.NAME]=n,r.push(...this.serializeObj(t,e));else if(s instanceof vw)s[vw.NAME]=n,r.push(...this.serializeObj(s,e));else if(Ko.vJ.isBufferSource(s))n?(r.push(`${i}${o}`),r.push(...this.serializeBufferSource(s,e+1))):r.push(...this.serializeBufferSource(s,e));else{if(!("toTextObject"in s))throw new TypeError("Cannot serialize data in text format. Unsupported type.");{const t=s.toTextObject();t[vw.NAME]=n,r.push(...this.serializeObj(t,e))}}}return r}static serializeBufferSource(t,e=0){const r=this.pad(e),i=Ko.vJ.toUint8Array(t),n=[];for(let t=0;t255)return!1}return!0}getField(t){const e=this.extraNames.findId(t)||Bw.findId(t),r=[];for(const t of this.asn)for(const i of t)i.type===e&&r.push(i.value.toString());return r}getName(t){return this.extraNames.get(t)||Bw.get(t)}toString(){return this.asn.map((t=>t.map((t=>{const e=this.getName(t.type)||t.type,r=t.value.anyValue?`#${Ko.ep.ToHex(t.value.anyValue)}`:function(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,Dw)}(t.value.toString());return`${e}=${r}`})).join("+"))).join(", ")}toJSON(){var t;const e=[];for(const r of this.asn){const i={};for(const e of r){const r=this.getName(e.type)||e.type;null!==(t=i[r])&&void 0!==t||(i[r]=[]),i[r].push(e.value.anyValue?`#${Ko.ep.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(i)}return e}fromString(t){const e=new ou,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let i=null,n=",";for(;i=r.exec(`${t},`);){let[,t,r]=i;const s=r[r.length-1];","!==s&&"+"!==s||(r=r.slice(0,r.length-1),i[3]=s);const o=i[3];if(/[\d.]+/.test(t)||(t=this.getName(t)||""),!t)throw new Error(`Cannot get OID for name type '${t}'`);const a=new iu({type:t});if("#"===r.charAt(0))a.value.anyValue=Ko.ep.FromHex(r.slice(1));else{const e=/"(.*?[^\\])?"/.exec(r);e&&(r=e[1]),r=r.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1"),t===this.getName("E")||t===this.getName("DC")?a.value.ia5String=r:Lw.isASCII(r)?a.value.printableString=r:a.value.utf8String=r}"+"===n?e[e.length-1].push(a):e.push(new nu([a])),n=o}return e}fromJSON(t){const e=new ou;for(const r of t){const t=new nu;for(const e in r){let i=e;if(/[\d.]+/.test(e)||(i=this.getName(e)||""),!i)throw new Error(`Cannot get OID for name type '${e}'`);const n=r[e];for(const e of n){const r=new iu({type:i});if("object"==typeof e)for(const t in e)switch(t){case"ia5String":r.value.ia5String=e[t];break;case"utf8String":r.value.utf8String=e[t];break;case"universalString":r.value.universalString=e[t];break;case"bmpString":r.value.bmpString=e[t];break;case"printableString":r.value.printableString=e[t]}else"#"===e[0]?r.value.anyValue=Ko.ep.FromHex(e.slice(1)):i===this.getName("E")||i===this.getName("DC")?r.value.ia5String=e:r.value.printableString=e;t.push(r)}}e.push(t)}return e}toArrayBuffer(){return Kl.serialize(this.asn)}async getThumbprint(...t){var e;let r,i="SHA-1";return t.length>=1&&!(null===(e=t[0])||void 0===e?void 0:e.subtle)?(i=t[0]||i,r=t[1]||Nw.get()):r=t[0]||Nw.get(),await r.subtle.digest(i,this.toArrayBuffer())}}const Pw="Cannot initialize GeneralName from ASN.1 data.",Uw=`${Pw} Unsupported string format in use.`,Mw=`${Pw} Value doesn't match to GUID regular expression.`,Fw=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Hw="1.3.6.1.4.1.311.25.1",Ww="1.3.6.1.4.1.311.20.2.3",jw="dns",zw="dn",Gw="email",qw="ip",Qw="url",Vw="guid",Kw="upn",Yw="id";class Jw extends Iw{constructor(...t){let e;if(2===t.length)switch(t[0]){case zw:{const r=new Lw(t[1]).toArrayBuffer(),i=Kl.parse(r,ou);e=new uu({directoryName:i});break}case jw:e=new uu({dNSName:t[1]});break;case Gw:e=new uu({rfc822Name:t[1]});break;case Vw:{const r=new RegExp(Fw,"i").exec(t[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const i=r.slice(1).map(((t,e)=>e<3?Ko.ep.ToHex(new Uint8Array(Ko.ep.FromHex(t)).reverse()):t)).join("");e=new uu({otherName:new cu({typeId:Hw,value:Kl.serialize(new hl(Ko.ep.FromHex(i)))})});break}case qw:e=new uu({iPAddress:t[1]});break;case Yw:e=new uu({registeredID:t[1]});break;case Kw:e=new uu({otherName:new cu({typeId:Ww,value:Kl.serialize(_l.toASN(t[1]))})});break;case Qw:e=new uu({uniformResourceIdentifier:t[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else e=Ko.vJ.isBufferSource(t[0])?Kl.parse(t[0],uu):t[0];super(e)}onInit(t){if(null!=t.dNSName)this.type=jw,this.value=t.dNSName;else if(null!=t.rfc822Name)this.type=Gw,this.value=t.rfc822Name;else if(null!=t.iPAddress)this.type=qw,this.value=t.iPAddress;else if(null!=t.uniformResourceIdentifier)this.type=Qw,this.value=t.uniformResourceIdentifier;else if(null!=t.registeredID)this.type=Yw,this.value=t.registeredID;else if(null!=t.directoryName)this.type=zw,this.value=new Lw(t.directoryName).toString();else{if(null==t.otherName)throw new Error(Uw);if(t.otherName.typeId===Hw){this.type=Vw;const e=Kl.parse(t.otherName.value,hl),r=new RegExp(Fw,"i").exec(Ko.ep.ToHex(e));if(!r)throw new Error(Mw);this.value=r.slice(1).map(((t,e)=>e<3?Ko.ep.ToHex(new Uint8Array(Ko.ep.FromHex(t)).reverse()):t)).join("-")}else{if(t.otherName.typeId!==Ww)throw new Error(Uw);this.type=Kw,this.value=Kl.parse(t.otherName.value,eu).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let t;switch(this.type){case zw:case jw:case Vw:case qw:case Yw:case Kw:case Qw:t=this.type.toUpperCase();break;case Gw:t="Email";break;default:throw new Error("Unsupported GeneralName type")}let e=this.value;return this.type===Yw&&(e=Tw.toString(e)),new vw(t,void 0,e)}}class Xw extends Iw{constructor(t){let e;if(t instanceof _u)e=t;else if(Array.isArray(t)){const r=[];for(const e of t)if(e instanceof uu)r.push(e);else{const t=Kl.parse(new Jw(e.type,e.value).rawData,uu);r.push(t)}e=new _u(r)}else{if(!Ko.vJ.isBufferSource(t))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");e=Kl.parse(t,_u)}super(e)}onInit(t){const e=[];for(const r of t){let t=null;try{t=new Jw(r)}catch{continue}e.push(t)}this.items=e}toJSON(){return this.items.map((t=>t.toJSON()))}toTextObject(){const t=super.toTextObjectEmpty();for(const e of this.items){const r=e.toTextObject();let i=t[r[vw.NAME]];Array.isArray(i)||(i=[],t[r[vw.NAME]]=i),i.push(r)}return t}}Xw.NAME="GeneralNames";const Zw="\\n",$w="-{5}BEGIN ([^\\n]+(?=-{5}))-{5}\\n(?:((?:[^:\\n]+: (?:[^\\n]+\\n(?: +[^\\n]+\\n)*))+))?\\n?((?:[a-zA-Z0-9=+/]+\\n)+)-{5}END \\1-{5}";class ty{static isPem(t){return"string"==typeof t&&new RegExp($w,"g").test(t)}static decodeWithHeaders(t){t=t.replace(/\r/g,"");const e=new RegExp($w,"g"),r=[];let i=null;for(;i=e.exec(t);){const t=i[3].replace(new RegExp("[\\n]+","g"),""),e={type:i[1],headers:[],rawData:Ko.ep.FromBase64(t)},n=i[2];if(n){const t=n.split(new RegExp(Zw,"g"));let r=null;for(const i of t){const[t,n]=i.split(/:(.*)/);if(void 0===n){if(!r)throw new Error("Cannot parse PEM string. Incorrect header value");r.value+=t.trim()}else r&&e.headers.push(r),r={key:t,value:n.trim()}}r&&e.headers.push(r)}r.push(e)}return r}static decode(t){return this.decodeWithHeaders(t).map((t=>t.rawData))}static decodeFirst(t){const e=this.decode(t);if(!e.length)throw new RangeError("PEM string doesn't contain any objects");return e[0]}static encode(t,e){if(Array.isArray(t)){const r=new Array;return e?t.forEach((t=>{if(!Ko.vJ.isBufferSource(t))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:e,rawData:Ko.vJ.toArrayBuffer(t)}))})):t.forEach((t=>{if(!("type"in t))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(t))})),r.join("\n")}if(!e)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:e,rawData:Ko.vJ.toArrayBuffer(t)})}static encodeStruct(t){var e;const r=t.type.toLocaleUpperCase(),i=[];if(i.push(`-----BEGIN ${r}-----`),null===(e=t.headers)||void 0===e?void 0:e.length){for(const e of t.headers)i.push(`${e.key}: ${e.value}`);i.push("")}const n=Ko.ep.ToBase64(t.rawData);let s,o=0;const a=Array();for(;o1?(i=t[0]||i,r=t[1]||r,e=t[2]||Nw.get()):e=t[0]||Nw.get(),e.subtle.importKey("spki",this.rawData,i,!0,r)}onInit(t){const e=Uf.resolve(jg),r=this.algorithm=e.toWebAlgorithm(t.algorithm);switch(t.algorithm.algorithm){case Bd:{const e=Kl.parse(t.subjectPublicKey,uf),i=Ko.vJ.toUint8Array(e.modulus);r.publicExponent=Ko.vJ.toUint8Array(e.publicExponent),r.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3;break}}}async getThumbprint(...t){var e;let r,i="SHA-1";return t.length>=1&&!(null===(e=t[0])||void 0===e?void 0:e.subtle)?(i=t[0]||i,r=t[1]||Nw.get()):r=t[0]||Nw.get(),await r.subtle.digest(i,this.rawData)}async getKeyIdentifier(t){t||(t=Nw.get());const e=Kl.parse(this.rawData,kh);return await t.subtle.digest("SHA-1",e.subjectPublicKey)}toTextObject(){const t=this.toTextObjectEmpty(),e=Kl.parse(this.rawData,kh);if(t.Algorithm=Sw.serializeAlgorithm(e.algorithm),e.algorithm.algorithm===gd)t["EC Point"]=e.subjectPublicKey;else t["Raw Data"]=e.subjectPublicKey;return t}}class iy{static register(t,e){this.items.set(t,e)}static create(t){const e=new Cw(t),r=this.items.get(e.type);return r?new r(t):e}}iy.items=new Map;const ny="crypto.signatureFormatter";class sy extends ey{constructor(t){ey.isAsnEncoded(t)?super(t,Wh):super(t),this.tag=ty.CertificateTag}onInit(t){const e=t.tbsCertificate;this.tbs=Kl.serialize(e),this.serialNumber=Ko.ep.ToHex(e.serialNumber),this.subjectName=new Lw(e.subject),this.subject=new Lw(e.subject).toString(),this.issuerName=new Lw(e.issuer),this.issuer=this.issuerName.toString();const r=Uf.resolve(jg);this.signatureAlgorithm=r.toWebAlgorithm(t.signatureAlgorithm),this.signature=t.signatureValue;const i=e.validity.notBefore.utcTime||e.validity.notBefore.generalTime;if(!i)throw new Error("Cannot get 'notBefore' value");this.notBefore=i;const n=e.validity.notAfter.utcTime||e.validity.notAfter.generalTime;if(!n)throw new Error("Cannot get 'notAfter' value");this.notAfter=n,this.extensions=[],e.extensions&&(this.extensions=e.extensions.map((t=>iy.create(Kl.serialize(t))))),this.publicKey=new ry(e.subjectPublicKeyInfo)}getExtension(t){for(const e of this.extensions)if("string"==typeof t){if(e.type===t)return e}else if(e instanceof t)return e;return null}getExtensions(t){return this.extensions.filter((e=>"string"==typeof t?e.type===t:e instanceof t))}async verify(t={},e=Nw.get()){let r,i;const n=t.publicKey;try{if(n)if("publicKey"in n)r={...n.publicKey.algorithm,...this.signatureAlgorithm},i=await n.publicKey.export(r,["verify"]);else if(n instanceof ry)r={...n.algorithm,...this.signatureAlgorithm},i=await n.export(r,["verify"]);else if(Ko.vJ.isBufferSource(n)){const t=new ry(n);r={...t.algorithm,...this.signatureAlgorithm},i=await t.export(r,["verify"])}else r={...n.algorithm,...this.signatureAlgorithm},i=n;else r={...this.publicKey.algorithm,...this.signatureAlgorithm},i=await this.publicKey.export(r,["verify"],e)}catch(t){return!1}const s=Uf.resolveAll(ny).reverse();let o=null;for(const t of s)if(o=t.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const a=await e.subtle.verify(this.signatureAlgorithm,i,o,this.tbs);if(t.signatureOnly)return a;{const e=(t.date||new Date).getTime();return a&&this.notBefore.getTime()t))}else{const e=new Yu(t[0]);super(Ku,t[1],Kl.serialize(e)),this.usages=t[0]}}toTextObject(){const t=this.toTextObjectWithoutValue();return t[""]=this.usages.map((t=>Tw.toString(t))).join(", "),t}}uy.NAME="Extended Key Usages",function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"}(ly||(ly={}));class hy extends Cw{constructor(...t){if(Ko.vJ.isBufferSource(t[0])){super(t[0]);const e=Kl.parse(this.value,lh);this.usages=e.toNumber()}else{const e=new lh(t[0]);super(oh,t[1],Kl.serialize(e)),this.usages=t[0]}}toTextObject(){const t=this.toTextObjectWithoutValue(),e=Kl.parse(this.value,lh);return t[""]=e.toJSON().join(", "),t}}hy.NAME="Key Usages";class py extends Cw{constructor(...t){if(Ko.vJ.isBufferSource(t[0])){super(t[0]);const e=Kl.parse(this.value,Th);this.keyId=Ko.ep.ToHex(e)}else{const e="string"==typeof t[0]?Ko.ep.FromHex(t[0]):t[0],r=new Th(e);super(vh,t[1],Kl.serialize(r)),this.keyId=Ko.ep.ToHex(e)}}static async create(t,e=!1,r=Nw.get()){let i;i=t instanceof ry?t.rawData:"publicKey"in t?t.publicKey.rawData:Ko.vJ.isBufferSource(t)?t:await r.subtle.exportKey("spki",t);const n=new ry(i),s=await n.getKeyIdentifier(r);return new py(Ko.ep.ToHex(s),e)}toTextObject(){const t=this.toTextObjectWithoutValue(),e=Kl.parse(this.value,Th);return t[""]=e,t}}py.NAME="Subject Key Identifier";class dy extends Cw{constructor(...t){Ko.vJ.isBufferSource(t[0])?super(t[0]):super(mh,t[1],new Xw(t[0]||[]).rawData)}onInit(t){super.onInit(t);const e=Kl.parse(t.extnValue,bh);this.names=new Xw(e)}toTextObject(){const t=this.toTextObjectWithoutValue(),e=this.names.toTextObject();for(const r in e)t[r]=e[r];return t}}dy.NAME="Subject Alternative Name";class fy extends Cw{constructor(...t){var e;if(Ko.vJ.isBufferSource(t[0])){super(t[0]);const e=Kl.parse(this.value,Bu);this.policies=e.map((t=>t.policyIdentifier))}else{const r=t[0],i=null!==(e=t[1])&&void 0!==e&&e,n=new Bu(r.map((t=>new ku({policyIdentifier:t}))));super(Iu,i,Kl.serialize(n)),this.policies=r}}toTextObject(){const t=this.toTextObjectWithoutValue();return t.Policy=this.policies.map((t=>new vw("",{},Tw.toString(t)))),t}}fy.NAME="Certificate Policies",iy.register(Iu,fy);class gy extends Iw{constructor(...t){let e;if(Ko.vJ.isBufferSource(t[0]))e=Ko.vJ.toArrayBuffer(t[0]);else{const r=t[0],i=Array.isArray(t[1])?t[1].map((t=>Ko.vJ.toArrayBuffer(t))):[];e=Kl.serialize(new Ah({type:r,values:i}))}super(e,Ah)}onInit(t){this.type=t.type,this.values=t.values}toTextObject(){const t=this.toTextObjectWithoutValue();return t.Value=this.values.map((t=>new vw("",{"":t}))),t}toTextObjectWithoutValue(){const t=this.toTextObjectEmpty();return t[vw.NAME]===gy.NAME&&(t[vw.NAME]=Tw.toString(this.type)),t}}gy.NAME="Attribute";class wy extends gy{constructor(...t){var e;if(Ko.vJ.isBufferSource(t[0]))super(t[0]);else{const e=new Og({printableString:t[0]});super(pg,[Kl.serialize(e)])}null!==(e=this.password)&&void 0!==e||(this.password="")}onInit(t){if(super.onInit(t),this.values[0]){const t=Kl.parse(this.values[0],Og);this.password=t.toString()}}toTextObject(){const t=this.toTextObjectWithoutValue();return t[vw.VALUE]=this.password,t}}wy.NAME="Challenge Password";class yy extends gy{constructor(...t){var e;if(Ko.vJ.isBufferSource(t[0]))super(t[0]);else{const e=t[0],r=new Uh;for(const t of e)r.push(Kl.parse(t.rawData,Ph));super(dg,[Kl.serialize(r)])}null!==(e=this.items)&&void 0!==e||(this.items=[])}onInit(t){if(super.onInit(t),this.values[0]){const t=Kl.parse(this.values[0],Uh);this.items=t.map((t=>iy.create(Kl.serialize(t))))}}toTextObject(){const t=this.toTextObjectWithoutValue(),e=this.items.map((t=>t.toTextObject()));for(const r of e)t[r[vw.NAME]]=r;return t}}yy.NAME="Extensions";class my{static register(t,e){this.items.set(t,e)}static create(t){const e=new gy(t),r=this.items.get(e.type);return r?new r(t):e}}my.items=new Map;let by=class{toAsnAlgorithm(t){if("rsassa-pkcs1-v1_5"===t.name.toLowerCase()){if(!t.hash)return new Oh({algorithm:Bd,parameters:null});switch(t.hash.name.toLowerCase()){case"sha-1":return new Oh({algorithm:Fd,parameters:null});case"sha-256":return new Oh({algorithm:Wd,parameters:null});case"sha-384":return new Oh({algorithm:jd,parameters:null});case"sha-512":return new Oh({algorithm:zd,parameters:null})}}return null}toWebAlgorithm(t){switch(t.algorithm){case Bd:return{name:"RSASSA-PKCS1-v1_5"};case Fd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Wd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case jd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case zd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}}}return null}};by=hf([Ff()],by),Uf.registerSingleton(Wg,by);class Ay{addPadding(t,e){const r=Ko.vJ.toUint8Array(e),i=new Uint8Array(t);return i.set(r,t-r.length),i}removePadding(t,e=!1){let r=Ko.vJ.toUint8Array(t);for(let t=0;t127){const t=new Uint8Array(r.length+1);return t.set(r,1),t.buffer}return r.buffer}toAsnSignature(t,e){if("ECDSA"===t.name){const r=t.namedCurve,i=Ay.namedCurveSize.get(r)||Ay.defaultNamedCurveSize,n=new Od,s=Ko.vJ.toUint8Array(e);return n.r=this.removePadding(s.slice(0,i),!0),n.s=this.removePadding(s.slice(i,i+i),!0),Kl.serialize(n)}return null}toWebSignature(t,e){if("ECDSA"===t.name){const r=Kl.parse(e,Od),i=t.namedCurve,n=Ay.namedCurveSize.get(i)||Ay.defaultNamedCurveSize,s=this.addPadding(n,this.removePadding(r.r)),o=this.addPadding(n,this.removePadding(r.s));return(0,Ko.$e)(s,o)}return null}}Ay.namedCurveSize=new Map,Ay.defaultNamedCurveSize=32;const Ey="1.3.101.110",_y="1.3.101.111",vy="1.3.101.112",Ty="1.3.101.113";let Sy=class{toAsnAlgorithm(t){let e=null;switch(t.name.toLowerCase()){case"eddsa":switch(t.namedCurve.toLowerCase()){case"ed25519":e=vy;break;case"ed448":e=Ty}break;case"ecdh-es":switch(t.namedCurve.toLowerCase()){case"x25519":e=Ey;break;case"x448":e=_y}}return e?new Oh({algorithm:e}):null}toWebAlgorithm(t){switch(t.algorithm){case vy:return{name:"EdDSA",namedCurve:"Ed25519"};case Ty:return{name:"EdDSA",namedCurve:"Ed448"};case Ey:return{name:"ECDH-ES",namedCurve:"X25519"};case _y:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Sy=hf([Ff()],Sy),Uf.registerSingleton(Wg,Sy);class Iy extends ey{constructor(t){ey.isAsnEncoded(t)?super(t,Hg):super(t),this.tag=ty.CertificateRequestTag}onInit(t){this.tbs=Kl.serialize(t.certificationRequestInfo),this.publicKey=new ry(t.certificationRequestInfo.subjectPKInfo);const e=Uf.resolve(jg);this.signatureAlgorithm=e.toWebAlgorithm(t.signatureAlgorithm),this.signature=t.signature,this.attributes=t.certificationRequestInfo.attributes.map((t=>my.create(Kl.serialize(t))));const r=this.getAttribute(dg);this.extensions=[],r instanceof yy&&(this.extensions=r.items),this.subjectName=new Lw(t.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(t){for(const e of this.attributes)if(e.type===t)return e;return null}getAttributes(t){return this.attributes.filter((e=>e.type===t))}getExtension(t){for(const e of this.extensions)if(e.type===t)return e;return null}getExtensions(t){return this.extensions.filter((e=>e.type===t))}async verify(t=Nw.get()){const e={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(e,["verify"],t),i=Uf.resolveAll(ny).reverse();let n=null;for(const t of i)if(n=t.toWebSignature(e,this.signature),n)break;if(!n)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await t.subtle.verify(this.signatureAlgorithm,r,n,this.tbs)}toTextObject(){const t=this.toTextObjectEmpty(),e=Kl.parse(this.rawData,Hg),r=e.certificationRequestInfo,i=new vw("",{Version:`${Mh[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const t=new vw("");for(const e of this.attributes){const r=e.toTextObject();t[r[vw.NAME]]=r}i.Attributes=t}return t.Data=i,t.Signature=new vw("",{Algorithm:Sw.serializeAlgorithm(e.signatureAlgorithm),"":e.signature}),t}}Iy.NAME="PKCS#10 Certificate Request";var Cy;!function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"}(Cy||(Cy={}));iy.register(bu,ay),iy.register(Ku,uy),iy.register(oh,hy),iy.register(vh,py),iy.register(wu,oy),iy.register(mh,dy),my.register(pg,wy),my.register(dg,yy),Uf.registerSingleton(ny,class{toAsnSignature(t,e){return Ko.vJ.toArrayBuffer(e)}toWebSignature(t,e){return Ko.vJ.toArrayBuffer(e)}}),Uf.registerSingleton(ny,Ay),Ay.namedCurveSize.set("P-256",32),Ay.namedCurveSize.set("K-256",32),Ay.namedCurveSize.set("P-384",48),Ay.namedCurveSize.set("P-521",66);const Ry=/-{5}(BEGIN|END) .*-{5}/gm;async function xy({hash:t,signature:e,publicKey:r,domain:i,domainCert:n,created:s,software:o}={}){let a;const c=[];if(e=(0,Vo.toByteArray)(e),n&&i&&!r){const t=n.split("\n\n"),i=(0,Vo.toByteArray)(t[0].replace(Ry,"").replace(/\s/gm,"")),s=f(await crypto.subtle.digest("SHA-256",i));c.push({id:"certFingerprint",expected:s,matched:null});const o=new sy(i);r=await o.publicKey.export();const l=(0,Vo.fromByteArray)(new Uint8Array(o.publicKey.rawData));c.push({id:"publicKey",expected:l,matched:null}),o.subject&&o.subject.startsWith("CN=")&&(a=o.subject.split(3)),e=function(t){try{const e=ql.parse(t,Od),r=0===e.r[0]?e.r.slice(1):e.r,i=0===e.s[0]?e.s.slice(1):e.s;t=z([r,i],r.length+i.length)}catch(t){console.log(t)}return t}(e)}else{const t={name:"ECDSA",namedCurve:"P-384"};c.push({id:"publicKey",expected:r,matched:null}),r=await crypto.subtle.importKey("spki",(0,Vo.toByteArray)(r),t,!0,["verify"])}const l=new TextEncoder,u=await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},r,e,l.encode(t));return c.push({id:"signature",expected:!0,matched:u}),s&&c.push({id:"created",expected:s,matched:null}),o&&c.push({id:"software",expected:o,matched:null}),i&&c.push({id:"domain",expected:i,matched:a}),c}const Ny="pages/pages.jsonl",Oy="pages/extraPages.jsonl",ky="datapackage.json",By="datapackage-digest.json",Dy="webarchive.yaml";class Ly{constructor(t,e,r=!0){this.file=e,this.waczname=e.waczname,this.store=t,this.isRoot=r}async loadFileFromWACZ(t,e){return this.store.loadFileFromWACZ?await this.store.loadFileFromWACZ(this.file,t,e):await this.file.loadFile(t,e)}async load(){let t,e=null;return this.file.containsFile(By)&&(e=await this.loadDigestData(By)),this.file.containsFile(ky)?t=await this.loadPackage(ky,e):this.file.containsFile(Dy)&&(t=await this.loadOldPackageYAML(Dy)),t||{}}async loadTextFileFromWACZ(t,e=!1){const{reader:r,hasher:i}=await this.loadFileFromWACZ(t,{computeHash:!!e}),n=(new TextDecoder).decode(await r.readFully());return e&&i&&await this.store.addVerifyData(this.waczname,t,e,i.getHash()),n}async loadDigestData(t){try{const e=JSON.parse(await this.loadTextFileFromWACZ(t));let r;e.path===ky&&e.hash&&(r=e.hash);const i=this.store,n=this.isRoot?"":this.waczname+":";if(!e.signedData||e.signedData.hash!==r)return void await i.addVerifyData(n,"signature");await i.addVerifyData(n,"datapackageHash",r);const s=await xy(e.signedData);return await i.addVerifyDataList(n,s),r}catch(t){console.warn(t)}}async loadPackage(t,e){const r=await this.loadTextFileFromWACZ(t,e),i=JSON.parse(r);switch(this.isRoot&&void 0!==i.config&&this.store.initConfig(i.config),i.profile){case"data-package":case"wacz-package":case void 0:case null:return await this.loadLeafWACZPackage(i);case"multi-wacz-package":return await this.loadMultiWACZPackage(i);default:throw new Error(`Unknown package profile: ${i.profile}`)}}async loadMultiWACZPackage(t){return this.file.markAsMultiWACZ(),await this.store.loadWACZFiles(t,this.file),t}async loadLeafWACZPackage(t){const e=t.metadata||{};let r=null;for(const e of t.resources)e.path===Ny?(r=e.hash,await this.store.addVerifyData(this.waczname,e.path,e.hash)):(e.path.endsWith(".idx")||e.path.endsWith(".cdx"))&&await this.store.addVerifyData(this.waczname,e.path,e.hash);if(this.file.containsFile(Ny)){(await this.loadPages(Ny,r)).hasText&&(this.store.textIndex=e.textIndex=Ny)}return this.file.containsFile(Oy)&&(this.store.textIndex=e.textIndex=Oy),e}async loadOldPackageYAML(t){const e=await this.loadTextFileFromWACZ(t),r=Qo.load(e),i={desc:r.desc,title:r.title};r.textIndex&&(i.textIndex=r.textIndex,r.config||(r.config={}),r.config.textIndex=r.textIndex),this.isRoot&&void 0!==r.config&&this.store.initConfig(r.config),i.title||(i.title=this.store.config.sourceName);const n=r.pages||[];n&&n.length&&await this.store.addPages(n);const s=r.pageLists||[];return s&&s.length&&await this.store.addCuratedPageLists(s,"pages","show"),i}async loadPages(t=Ny,e=null){const{reader:r,hasher:i}=await this.loadFileFromWACZ(t,{unzip:!0,computeHash:!0});let n=null,s=[];for await(const t of r.iterLines()){const e=JSON.parse(t);this.waczname&&(e.wacz=this.waczname),n?(s.push(e),500===s.length&&(await this.store.addPages(s),s=[])):n=e}return s.length&&await this.store.addPages(s),i&&e&&await this.store.addVerifyData(this.waczname,t,e,i.getHash()),n}}class Py{constructor(t,e,r=null){this.loader=t,this.loadId=r,this.loadUrl=e.loadUrl}async load(t){t.fullConfig&&this.loader.arrayBuffer&&this.loader.arrayBuffer.byteLength<=a&&(t.fullConfig.extra||(t.fullConfig.extra={}),t.fullConfig.extra.arrayBuffer=this.loader.arrayBuffer);const e=this.loadUrl,r=this.loader;return await t.addNewWACZ({name:"default",path:e,loader:r})}}class Uy{constructor(t,e,r=null){this.config=e,this.loadId=r,this.loader=t}async load(t,e=null,r=0){const i=new jn({loader:this.loader});await i.init();const n=i.zipreader,s=new Ly(t,i),o=await s.load();let a=0;const c=(t,i,n)=>{n+=a,e&&r&&e(Math.round(100*n/r),null,n,r)};for(const e of i.iterContainedFiles()){const r=n.getCompressedSize(e);(e.endsWith(".warc.gz")||e.endsWith(".warc"))&&await this.loadWARC(t,n,e,c,r),a+=r}return o||{}}async loadWARC(t,e,r,i,n){const{reader:s}=await e.loadFile(r,{unzip:!0}),o=new si(s,null,r);return o.detectPages=!1,await o.load(t,i,n)}}class My{constructor(t){this.response=t}async load(t){return await t.loadFromJSON(this.response)}}class Fy{constructor(t,{cloneResponse:e=!1,allowBody:r=!1,hostProxyOnly:i=!1}={}){if(t=t||{},this.prefix=t.prefix||"",this.proxyPathOnly=t.proxyPathOnly||!1,this.isLive=void 0===t.isLive||t.isLive,this.archivePrefix=t.archivePrefix||"",this.cloneResponse=e,this.allowBody=r,this.hostProxy=t.hostProxy,this.hostProxy instanceof Array){const t={};for(const e of this.hostProxy)t[e.host]=e;this.hostProxy=t}this.hostProxyOnly=i}async getAllPages(){return[]}getFetchUrl(t,e,r){let i;if(this.hostProxy){i=new URL(t);const e=this.hostProxy[i.host];if(e)return r.set("X-Proxy-Host",i.host),e.prefix+(e.pathOnly?i.pathname+i.search:t)}return this.hostProxyOnly?null:this.proxyPathOnly?(i||(i=new URL(t)),this.prefix+i.pathname+i.search):this.isLive||!e.timestamp?this.prefix+t:this.prefix+this.archivePrefix+e.timestamp+"id_/"+t}async getResource(t,e){const{headers:r,credentials:i,url:n}=t.prepareProxyRequest(e,!0),s=this.getFetchUrl(n,t,r);if(!s)return null;let o=null;!this.allowBody||"POST"!==t.method&&"PUT"!==t.method||(o=await t.getBody());const a=await fetch(s,{method:t.method,body:o,headers:r,credentials:i,mode:"cors",redirect:"follow"});let c=null;this.cloneResponse&&(c=a.clone());const l=mt.fromResponse({url:n,response:a,date:new Date,noRW:!1,isLive:this.isLive});return c&&(l.clonedResponse=c),l}}const Hy=/^([\w-]+,)*[\w-]+(:\d+)?,?\)\//;class Wy extends rn{constructor(t,e,r="wacz"){super(t.dbname,t.noCache),this.config=t,this.waczfiles={},this.waczNameForHash={},this.ziploadercache={},this.updating=null,this.rootSourceType=r,this.sourceLoader=e,this.externalSource=null,this.fuzzyUrlRules=[],this.textIndex=t&&t.metadata&&t.metadata.textIndex,t.extraConfig&&this.initConfig(t.extraConfig)}initConfig(t){if(void 0!==t.decodeResponses&&(this.config.decode=t.decodeResponses),t.hostProxy&&(this.externalSource=new Fy(t,{hostProxyOnly:!0})),t.fuzzy)for(const[e,r]of t.fuzzy){const t=new RegExp(e);this.fuzzyUrlRules.push({match:t,replace:r})}t.textIndex&&(this.textIndex=t.textIndex)}updateHeaders(t){this.sourceLoader&&(this.sourceLoader.headers=t)}_initDB(t,e,r,i){super._initDB(t,e,r,i),e||(t.createObjectStore("ziplines",{keyPath:["waczname","prefix"]}),t.createObjectStore("waczfiles",{keyPath:"waczname"}),t.createObjectStore("verification",{keyPath:"id"})),2===e&&this.convertV2WACZDB(t,i),3===e&&t.createObjectStore("verification",{keyPath:"id"})}async convertV2WACZDB(t,e){try{const r=await e.objectStore("ziplines").getAll(),i=await e.objectStore("zipEntries").getAll();t.deleteObjectStore("ziplines"),t.deleteObjectStore("zipEntries"),t.createObjectStore("ziplines",{keyPath:["waczname","prefix"]}),t.createObjectStore("waczfiles",{keyPath:"waczname"}),t.createObjectStore("verification",{keyPath:"id"});const n=this.config.loadUrl;for(const t of r)t.waczname=n,e.objectStore("ziplines").put(t);const s=r.length>0?2:1,o=await this.computeHash(n),a=new jn({waczname:n,hash:o,url:n,entries:i,indexType:s});e.objectStore("waczfiles").put(a.serialize()),await e.done}catch(t){console.warn(t)}}addWACZFile(t){return this.waczfiles[t.waczname]=new jn(t),this.waczNameForHash[t.hash]=t.waczname,this.waczfiles[t.waczname]}async init(){await super.init();const t=await this.db.getAll("waczfiles")||[];for(const e of t)this.addWACZFile({...e,parent:this});for(const[t,e]of Object.entries(this.waczfiles)){e.path=e.path||t;const r=e.path.lastIndexOf("#!/");if(r>0){const t=e.path.slice(0,r),i=this.waczfiles[t];e.parent=i}else"json"!==this.rootSourceType&&(e.loader=this.sourceLoader)}await this.checkUpdates()}async close(){super.close(),caches.delete("cache:"+this.name.slice("db:".length))}async clearZipData(){const t=["waczfiles","ziplines"];for(const e of t)await this.db.clear(e)}async addVerifyData(t="",e,r,i,n=!1){let s=null;t&&(e=t+e),i&&(s=r===i,n&&console.log(`verify ${e}: ${s}`)),await this.db.put("verification",{id:e,expected:r,matched:s})}async addVerifyDataList(t,e){const r=this.db.transaction("verification","readwrite");for(const i of e)t&&(i.id=t+i.id),r.store.put(i);try{await r.done}catch(t){console.warn(t)}}async getVerifyInfo(){const t=await this.db.getAll("verification");let e=0,r=0,i={};const n=["domain","created","certFingerprint","software","datapackageHash","publicKey"];for(const s of t)n.includes(s.id)?i[s.id]=s.expected:"signature"===s.id||!0===s.matched?e++:!1===s.matched&&r++;return i.numInvalid=r,i.numValid=e,i}async getVerifyExpected(t){const e=await this.db.get("verification",t);return e&&e.expected}async clearAll(){await super.clearAll(),await this.clearZipData()}async loadRecordFromSource(t){const{start:e,length:r,path:i,wacz:n}=t.source,s={offset:e,length:r,unzip:!0,computeHash:!0},o=n,{reader:a,hasher:c}=await this.loadFileFromNamedWACZ(o,"archive/"+i,s),l=new oi(a,c);await this.waczfiles[o].save(this.db);const u=await l.load();return t[un]&&(u.respHeaders["x-wabac-preset-cookie"]=t[un]),{remote:u,hasher:c}}async loadIndex(t){if(!this.waczfiles[t])throw new Error("unknown waczfile: "+t);if(this.waczfiles[t].indexType)return{indexType:this.waczfiles[t].indexType,isNew:!1};let e=0;for(const r of this.waczfiles[t].iterContainedFiles())r.endsWith(".cdx")||r.endsWith(".cdxj")?(console.log(`Loading CDX for ${t}`),await this.loadCDX(r,t),e=1):r.endsWith(".idx")&&(console.log(`Loading IDX for ${t}`),await this.loadIDX(r,t),e=2);return this.waczfiles[t].indexType=e,await this.waczfiles[t].save(this.db,!0),{indexType:e,isNew:!0}}async loadCDX(t,e,r,i){const{reader:n,hasher:s}=await this.loadFileFromNamedWACZ(e,t,{computeHash:!0}),o=new pn(n,null,e,{wacz:e}),a=await o.load(this,r,i);if(s){const r=await this.getVerifyExpected(t);r&&this.addVerifyData(e,t,r,s.getHash())}return a}async loadIDX(t,e,r,i){const{reader:n,hasher:s}=await this.loadFileFromNamedWACZ(e,t,{computeHash:!0});let o=[],a="",c=!0,l=0;for await(const t of n.iterLines()){if(l+=t.length,l===t.length&&t.startsWith("!meta")){const e=t.indexOf(" {");if(e<0){console.warn("Invalid Meta Line: "+t);continue}const r=JSON.parse(t.slice(e));r.filename&&(a=r.filename),"cdxj-gzip-1.0"!==r.format&&console.log(`Unknown CDXJ format "${r.format}", archive may not parse correctly`);continue}let n;if(t.indexOf("\t")>0){let[r,i,s,o]=t.split("\t");s=Number(s),o=Number(o),n={waczname:e,prefix:r,filename:i,offset:s,length:o,loaded:!1},c=!1}else{const r=t.indexOf(" {");if(r<0){console.log("Invalid Index Line: "+t);continue}const i=t.slice(0,r);let{offset:s,length:o,filename:l,digest:u}=JSON.parse(t.slice(r));c=c&&!Hy.test(i),l=l||a,n={waczname:e,prefix:i,filename:l,offset:s,length:o,digest:u,loaded:!1}}r&&r(l/i,l,i),o.push(n)}if(s){const r=await this.getVerifyExpected(t);r&&this.addVerifyData(e,t,r,s.getHash())}const u=this.db.transaction("ziplines","readwrite");for(const t of o)u.store.put(t);try{await u.done}catch(t){console.log("Error loading ziplines index: ",t)}c&&c!==this.waczfiles[e].nonSurt&&(this.waczfiles[e].nonSurt=c,await this.waczfiles[e].save(this.db,!0))}async loadCDXFromIDX(t,e,r=0,i=!1){const n=this.waczfiles[t].nonSurt?e:M(e),s=i?this.prefixUpperBound(n):n+" 9999",o=IDBKeyRange.upperBound([t,s],!0),a=this.db.transaction("ziplines","readonly"),c=[];for await(const e of a.store.iterate(o,"prev")){if(e.value.waczname!==t)break;if(c.unshift(e.value),!e.value.prefix.split(" ")[0].startsWith(n))break}await a.done;const l=[];c.length>3&&r&&c.sort(((t,e)=>{const i=t.prefix.split(" ")[1],n=e.prefix.split(" ")[1];if(!i||!n)return 0;const s=Math.abs(d(i).getTime()-r),o=Math.abs(d(n).getTime()-r);return s===o?0:s3)break}return l.length&&await Promise.allSettled(l),await this.waczfiles[t].save(this.db),l.length>0}async doCDXLoad(t,e,r){try{const i="indexes/"+e.filename,n={offset:e.offset,length:e.length,unzip:!0,computeHash:!!e.digest},{reader:s,hasher:o}=await this.loadFileFromNamedWACZ(r,i,n),a=new pn(s,null,null,{wacz:r});if(await a.load(this),o){const t=o.getHash(),n=`${i}:${e.offset}-${e.length}`;await this.addVerifyData(r,n,e.digest,t)}e.loaded=!0,await this.db.put("ziplines",e)}catch(t){await T(t,this.config)||console.warn(t)}finally{delete this.ziploadercache[t]}}async findPageAtUrl(t,e){const r=await this.db.getAllFromIndex("pages","url",t);let i=null,n=Number.MAX_SAFE_INTEGER;for(const t of r){const r=Math.abs(t.ts-e);if(r<1e3)return t;r0)return r;for(const i of Object.keys(this.waczfiles))if(i&&"local"!==i){const{indexType:n,isNew:s}=await this.loadIndex(i);switch(n){case 2:if(!await this.loadCDXFromIDX(i,t,0,!0))continue;break;case 1:if(!s)continue;break;default:continue}const o=await super.resourcesByUrlAndMime(t,...e);o&&o.length&&(r=r.concat(o))}return r}async loadFileFromWACZ(t,e,r){try{return await t.loadFile(e,r)}catch(i){if(await this.retryLoad(i))return await t.loadFile(e,r);throw i}}async loadFileFromNamedWACZ(t,e,r){const i=this.waczfiles[t];if(!i)throw new Error("No WACZ Found for: "+t);return await this.loadFileFromWACZ(i,e,r)}async addNewWACZ({name:t,hash:e,path:r,parent:i=null,loader:n=null}={}){const s=t||r;e?e.indexOf(":")>0&&(e=e.split(":")[1]):e=await g(s,"sha-256","");const o=this.addWACZFile({waczname:s,hash:e,path:r,parent:i,loader:n},!0);await o.init(),await o.save(this.db,!0);const a=new Ly(this,o,!i);return await a.load()}async loadWACZFiles(t,e=this){const r=[],i=async(t,e)=>{await this.waczfiles[t].init(e),await this.waczfiles[t].save(this.db,!0)},n=t.resources.map((t=>{const r=e.getLoadPath(t.path);return{name:e.getName(t.name),hash:t.hash,path:r}}));for(const{name:t,hash:s,path:o}of n)this.waczfiles[t]?this.waczfiles[t].path!==o&&r.push(i(t,o)):r.push(this.addNewWACZ({name:t,hash:s,path:o,parent:e}));r.length&&await Promise.allSettled(r)}async getTextIndex(){const t={"Content-Type":"application/ndjson"},e=Object.keys(this.waczfiles);if(!this.textIndex||!e.length)return new Response("",{headers:t});const r=e[0];let i;try{i=await this.loadFileFromNamedWACZ(r,this.textIndex,{unzip:!0})}catch(e){return new Response("",{headers:t})}const{reader:n}=i,s=this.waczfiles[r].getSizeOf(this.textIndex);return s>0&&(t["Content-Length"]=""+s),new Response(n.getReadableStream(),{headers:t})}async getResource(t,e,r,{pageId:i}={}){if(await this.initing,this.externalSource){const i=await this.externalSource.getResource(t,e,r);if(i)return i}const n="navigate"===r.request.mode;let s=i,o=null,a=null;if(s){if(o=this.waczNameForHash[s],!o)return null;a=await super.getResource(t,e,r,{waczname:o})}if(a||!n)return a;let c=null;for(const[i,n]of Object.entries(this.waczfiles))if(n.fileType===Wn&&(a=await super.getResource(t,e,r,{waczname:i,noFuzzyCheck:!0}),a)){o=i,c=n.hash;break}if(o)return Response.redirect(`${e}:${c}/${t.timestamp}mp_/${t.url}`);if(this.fuzzyUrlRules.length)for(const{match:i,replace:n}of this.fuzzyUrlRules){const s=decodeURIComponent(t.url.replace(i,n));if(s&&s!==t.url){t.url=s;const i=await super.getResource(t,e,r);if(i)return i}}return null}async retryLoad(t){return"json"===this.rootSourceType&&(t instanceof x?(this.updating||(this.updating=this.checkUpdates()),await this.updating,this.updating=null,!0):await T(t,this.config))}async checkUpdates(){"json"===this.rootSourceType&&await this.loadFromJSON()}async loadFromJSON(t=null){if(!t){t=(await this.sourceLoader.doInitialFetch(!1)).response}if(206!==t.status&&200!==t.status)return console.warn("WACZ update failed from: "+this.config.loadUrl),{};const e=await t.json();return e.profile,await this.loadWACZFiles(e),e}getLoadPath(t){return new URL(t,this.config.loadUrl).href}getName(t){return t}async createLoader(t){return await Vi(t)}}class jy{constructor(t){const e=t.extraConfig||{};this.sourceUrl=e.prefix,this.type=e.sourceType||"kiwix",this.notFoundPageUrl=e.notFoundPageUrl}async getAllPages(){return[]}async getResource(t,e){const{url:r,headers:i}=t.prepareProxyRequest(e);let n=i;if("kiwix"===this.type){let e=await this.resolveHeaders(r);if(!e)for(const t of Zr.getFuzzyCanonsWithArgs(r))if(t!==r&&(e=await this.resolveHeaders(t),e))break;if(!e){if(this.notFoundPageUrl&&"navigate"===t.mode){const t=await fetch(this.notFoundPageUrl);if(200===t.status){const e={"Content-Type":"text/html"},i=await t.text();return new Response(i.replace("$URL",r),{status:404,headers:e})}}return null}let{headers:i,encodedUrl:s,date:o,status:a,statusText:c,hasPayload:l}=e;if(n.has("Range")){const t=n.get("Range");n={Range:t}}let u=null,h=null;l&&(h=await fetch(this.sourceUrl+"A/"+s,{headers:n}),h.body&&(u=new K(h.body.getReader(),!1)),206===h.status&&(a=206,c="Partial Content",i.set("Content-Length",h.headers.get("Content-Length")),i.set("Content-Range",h.headers.get("Content-Range")),i.set("Accept-Ranges","bytes"))),u||(u=new Uint8Array([])),o||(o=new Date),i||(i=new Headers);return new mt({payload:u,status:a,statusText:c,headers:i,url:r,date:o,noRW:!1,isLive:!1})}}async resolveHeaders(t){const e=t.slice(t.indexOf("//")+2);let r=encodeURI(e);r=encodeURIComponent(e);let i=await fetch(this.sourceUrl+"H/"+r);if(200!==i.status)return null;let n=null,s=null,o=null,a=null,c=!1;try{const e=await ct.parse(i.body);if("revisit"===e.warcType){const r=e.warcHeaders.headers.get("WARC-Refers-To-Target-URI");if(r&&r!==t)return await this.resolveHeaders(r)}s=new Date(e.warcDate),e.httpHeaders?(n=e.httpHeaders.headers,o=Number(e.httpHeaders.statusCode),a=e.httpHeaders.statusText,c="0"!==e.httpHeaders.headers.get("Content-Length")):"resource"===e.warcType&&(n=new Headers,n.set("Content-Type",e.warcContentType),n.set("Content-Length",e.warcContentLength),o=200,a="OK",c=e.warcContentLength>0),o||(o=200)}catch(e){console.warn(e),console.warn("Ignoring headers, error parsing headers response for: "+t)}return{encodedUrl:r,headers:n,date:s,status:o,statusText:a,hasPayload:c}}}const zy=Qy([80,75,3,4]),Gy=Qy([31,139,8]),qy=Qy([87,65,82,67]);function Qy(t){return e=>{for(const[r,i]of t.entries())if(i!==e[r])return!1;return!0}}async function Vy(t){const e=t.body.getReader();let r="";const{value:i,done:n}=await e.read();var s;return!n&&i.length>=4&&(s=i.slice(0,4),r=zy(s)?".wacz":qy(s)?".warc":Gy(s)?".warc.gz":void 0,r||(r=function(t){try{const e=(new TextDecoder).decode(t).split("\n");if(e>1&&e.indexOf(" {"))return".cdxj"}catch(t){return""}}(i))),n||e.cancel(),r}globalThis.self||(globalThis.self=globalThis),self.interruptLoads={};class Ky extends class{constructor(){this.colldb=null,this.root=null,this.checkIpfs=!0,this._init_db=this._initDB()}async _initDB(){this.colldb=await Dr("collDB",1,{upgrade:t=>{t.createObjectStore("colls",{keyPath:"name"}).createIndex("type","type")}})}async loadAll(t){if(await this._init_db,t)for(const e of t.split(",")){const t=e.split(":");if(2===t.length){const e={dbname:t[1],sourceName:t[1],decode:!1},r={name:t[0],type:"archive",config:e};console.log("Adding Coll: "+JSON.stringify(r)),await this.colldb.put("colls",r)}}try{const t=(await this.listAll()).map((t=>this._initColl(t)));await Promise.all(t)}catch(t){console.warn(t.toString())}return!0}async listAll(){return await this._init_db,await this.colldb.getAll("colls")}async loadColl(t){await this._init_db;const e=await this.colldb.get("colls",t);return e?await this._initColl(e):null}async reload(t){return this.loadColl(t)}async deleteColl(t){await this._init_db;const e=await this.colldb.get("colls",t);if(!e)return!1;if(e.config.dbname)try{await Lr(e.config.dbname,{blocked(t,r){console.log(`Unable to delete ${e.config.dbname}, blocked: ${r}`)}})}catch(t){return console.warn(t),!1}return await this.colldb.delete("colls",t),!0}async updateAuth(t,e){await this._init_db;const r=await this.colldb.get("colls",t);return!!r&&(r.config.headers=e,await this.colldb.put("colls",r),!0)}async updateMetadata(t,e){await this._init_db;const r=await this.colldb.get("colls",t);return!!r&&(r.config.metadata={...r.config.metadata,...e},await this.colldb.put("colls",r),r.config.metadata)}async updateSize(t,e,r,i){await this._init_db;const n=await this.colldb.get("colls",t);if(!n)return!1;const s=n.config.metadata;return s.fullSize=(s.fullSize||0)+e,s.size=(s.size||0)+r,s.mtime=(new Date).getTime(),void 0!==i&&(n.config.decode=i),await this.colldb.put("colls",n),s}async initNewColl(t,e={},r="archive"){await this._init_db;const i=m(),n="local://"+i,s={name:i,type:r,config:{dbname:"db:"+i,ctime:(new Date).getTime(),decode:!1,metadata:t,sourceUrl:n,extraConfig:e}},o=await this._initColl(s);return await this.colldb.put("colls",s),o}async _initColl(t){const e=await this._initStore(t.type,t.config),r=t.name,i=t.config;return t.config.root&&!this.root&&(this.root=r),this._createCollection({name:r,store:e,config:i})}async _initStore(t,e){let r=null,i=null;switch(t){case"archive":i=new ei(e.dbname);break;case"remotesource":r=await Vi({url:e.loadUrl,headers:e.headers,size:e.size,extra:e.extra}),i=new nn(e.dbname,r,e.noCache);break;case"remoteprefix":i=new sn(e.dbname,e.remotePrefix,e.headers,e.noCache);break;case"wacz":case"remotezip":case"multiwacz":r=await Vi({url:e.loadUrl||e.sourceUrl,headers:e.headers,extra:e.extra}),i=new Wy(e,r,"multiwacz"===t?"json":"wacz");break;case"remotewarcproxy":i=new jy(e);break;case"live":i=new Fy(e.extraConfig)}return i?(i.initing&&await i.initing,i):(console.log("no store found: "+t),null)}_createCollection(t){return t}}{constructor(t){super(),this.registerListener(t)}async hasCollection(t){return await this._init_db,null!=await this.colldb.getKey("colls",t)}registerListener(t){t.addEventListener("message",(t=>{t.waitUntil?t.waitUntil(this._handleMessage(t)):this._handleMessage(t)}))}async _handleMessage(t){await this._init_db;const e=t.source||self;switch(t.data.msg_type){case"addColl":{const r=t.data.name,i=(t,i,n,s,o=null,a=null)=>{e.postMessage({msg_type:"collProgress",name:r,percent:t,error:i,currentSize:n,totalSize:s,fileHandle:o,extraMsg:a})};let n;try{if(n=await this.colldb.get("colls",r),n?t.data.skipExisting||(await this.deleteColl(r),n=await this.addCollection(t.data,i)):n=await this.addCollection(t.data,i),!n){if(t.data.name)try{await Lr("db:"+t.data.name,{blocked(e,r){console.log(`Load failed and unable to delete ${t.data.name}: ${r}`)}})}catch(t){console.warn(t)}return}}catch(t){if(t instanceof R)return console.warn(t),void i(0,"permission_needed",null,null,t.info&&t.info.fileHandle);if("ConstraintError"!==t.name)return console.warn(t),void i(0,"An unexpected error occured: "+t.toString());console.log("already being added, just continue..."),n=await this.colldb.get("colls",r)}e.postMessage({msg_type:"collAdded",name:r,sourceUrl:n.config.sourceUrl});break}case"cancelLoad":{const e=t.data.name,r=new Promise((t=>self.interruptLoads[e]=t));await r,await this.deleteColl(e),delete self.interruptLoads[e];break}case"removeColl":{const r=t.data.name;await this.hasCollection(r)&&(await this.deleteColl(r),this.doListAll(e));break}case"listAll":this.doListAll(e);break;case"reload":this.reload(t.data.name)}}async doListAll(t){const e=[],r=await this.listAll();for(const t of r)e.push({name:t.name,prefix:t.name,pageList:[],sourceName:t.config.sourceName});t.postMessage({msg_type:"listAll",colls:e})}async addCollection(t,e){let r=t.name,i=null,n={root:t.root||!1},s=null,o=null;const c=t.file;if(!c||!c.sourceUrl)return e(0,"Invalid Load Request"),!1;if(n.dbname="db:"+r,c.sourceUrl.startsWith("proxy:"))n.sourceUrl=c.sourceUrl.slice("proxy:".length),n.extraConfig=t.extraConfig,n.extraConfig.prefix||(n.extraConfig.prefix=n.sourceUrl),n.topTemplateUrl=t.topTemplateUrl,n.metadata={},i=t.type||n.extraConfig.type||"remotewarcproxy",s=await this._initStore(i,n);else{let l=null;if(c.newFullImport&&(r=m(),c.loadUrl=c.loadUrl||c.sourceUrl,c.name=c.name||c.sourceUrl,c.sourceUrl="local://"+r),i="archive",c.newFullImport&&c.importCollId){const t=await this.colldb.get("colls",c.importCollId);if(!t||"archive"!==t.type)return void e(0,"Invalid Existing Collection: "+c.importCollId);n.dbname=t.config.dbname,o=t.config,o.decode=!0}let u=c.loadUrl||c.sourceUrl;u.match(/[\w]+:\/\//)||(u=new URL(u,self.location.href).href),n.decode=!0,n.onDemand=!1,n.loadUrl=u,n.sourceUrl=c.sourceUrl,n.sourceName=c.name||c.sourceUrl;try{if(n.sourceName.match(/https?:\/\//)){const t=new URL(n.sourceName);n.sourceName=t.pathname+t.hash}}catch(t){}if(n.sourceName=n.sourceName.slice(n.sourceName.lastIndexOf("/")+1),n.size="number"==typeof c.size?c.size:null,n.extra=c.extra,n.loadUrl.startsWith("file://")&&!c.blob&&!n.extra){if(!this._fileHandles||!this._fileHandles[n.sourceUrl])return void e(0,"missing_local_file");n.extra={fileHandle:this._fileHandles[n.sourceUrl]}}n.extraConfig=t.extraConfig,n.headers=c.headers||n.extraConfig&&n.extraConfig.headers,n.noCache=c.noCache;let h=await Vi({url:u,headers:n.headers,size:c.size,extra:n.extra,blob:c.blob});if(c.loadEager){const{response:t}=await h.doInitialFetch(!1,!0),e={arrayBuffer:new Uint8Array(await t.arrayBuffer())};c.newFullImport=!0,h=await Vi({url:u,headers:n.headers,size:c.size,extra:e})}let p=function(t){const e=[".warc",".warc.gz",".cdx",".cdxj",".har",".json",".wacz",".zip"];for(const r of e)if(t.endsWith(r))return r;return""}(n.sourceName),{abort:d,response:f}=await h.doInitialFetch(".wacz"===p);p||(p=await Vy(await f.clone()));const g=f.body;if(n.onDemand=h.canLoadOnDemand&&!c.newFullImport,!h.isValid){const t=h.length<=1e3?await f.text():"";return e(0,`Sorry, this URL could not be loaded.\nMake sure this is a valid URL and you have access to this file.\nStatus: ${f.status} ${f.statusText}\nError Details:\n${t}`),d&&d.abort(),!1}if(!h.length)return e(0,"Sorry, this URL could not be loaded because the size of the file is not accessible.\nMake sure this is a valid URL and you have access to this file."),d&&d.abort(),!1;const w=h.length;if(".wacz"===p)if(n.onDemand)l=new Py(h,n,r),s=new Wy(n,h,"wacz"),i="wacz";else{if(!h.canLoadOnDemand||!c.newFullImport)return e(0,"Sorry, can't load this WACZ file due to lack of range request support on the server"),d&&d.abort(),!1;l=new Uy(h,n,r),s=null,delete n.extra}else".warc"===p||".warc.gz"===p?n.noCache||!(w300&&e<400)return;let s=null;void 0===this.timeRanges[n]?(s={count:0,children:[]},this.timeRanges[n]=s,r.referrer.indexOf("mp_/")>0&&self.clients.matchAll({type:"window"}).then((t=>this.updateStatsParent(n,r.referrer,t)))):s=this.timeRanges[n];const o=t.getTime();(!s.min||os.max)&&(s.max=o),s.count++}updateStatsParent(t,e,r){for(let i of r)if(i.url===e){this.timeRanges[i.id]?this.timeRanges[i.id].children[t]=1:this.timeRanges[i.id]={count:0,children:{id:1}};break}}async getStats(t){const e=new URL(t.request.url);let r=0;const i=new URLSearchParams(e.search).get("url"),n=await self.clients.matchAll({type:"window"}),s={};for(let t of n)t.url===i&&(r=t.id),s[t.id]=1;const o=this.timeRanges[r]||{},a={count:o.count||0,min:o.min,max:o.max},c=this.timeRanges[r]&&Object.keys(this.timeRanges[r].children)||[];for(let t of c){const e=this.timeRanges[t];e&&((!a.min||e.mina.max)&&(a.max=e.max),a.count+=e.count)}for(let t of Object.keys(this.timeRanges))s[t]||delete this.timeRanges[t];return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}}var Jy=function(){return Jy=Object.assign||function(t){for(var e,r=1,i=arguments.length;r$)/g,""):"[a-zA-Z0-9-_.~%':|=+\\*@$]+")+")"},um=[{name:"url-parameter",pattern:/^:([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})(<(.+?)>)?/,regex:function(t){return new RegExp(lm(t[2]))}},{name:"url-parameter-splat",pattern:/^\*([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})/,regex:/([^?]*)/},{name:"url-parameter-matrix",pattern:/^;([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})(<(.+?)>)?/,regex:function(t){return new RegExp(";"+t[1]+"="+lm(t[2]))}},{name:"query-parameter",pattern:/^(?:\?|&)(?::)?([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})/},{name:"delimiter",pattern:/^(\/|\?)/,regex:function(t){return new RegExp("\\"+t[0])}},{name:"sub-delimiter",pattern:/^(!|&|-|_|\.|;)/,regex:function(t){return new RegExp(t[0])}},{name:"fragment",pattern:/^([0-9a-zA-Z]+)/,regex:function(t){return new RegExp(t[0])}}],hm=function t(e,r){if(void 0===r&&(r=[]),!um.some((function(i){var n=e.match(i.pattern);return!!n&&(r.push({type:i.name,match:n[0],val:n.slice(1,2),otherVal:n.slice(2),regex:i.regex instanceof Function?i.regex(n):i.regex}),n[0].length0,this.hasSpatParam=this.tokens.filter((function(t){return/splat$/.test(t.type)})).length>0,this.hasMatrixParams=this.tokens.filter((function(t){return/matrix$/.test(t.type)})).length>0,this.hasQueryParams=this.tokens.filter((function(t){return/^query-parameter/.test(t.type)})).length>0,this.spatParams=this.getParams("url-parameter-splat"),this.urlParams=this.getParams(/^url-parameter/),this.queryParams=this.getParams("query-parameter"),this.params=this.urlParams.concat(this.queryParams),this.source=this.tokens.filter((function(t){return void 0!==t.regex})).map((function(t){return t.regex.source})).join("")}return t.createPath=function(e,r){return new t(e,r)},t.prototype.isQueryParam=function(t){return-1!==this.queryParams.indexOf(t)},t.prototype.isSpatParam=function(t){return-1!==this.spatParams.indexOf(t)},t.prototype.test=function(t,e){var r=this,i=Jy(Jy({caseSensitive:!1,strictTrailingSlash:!1},this.options),e),n=function(t,e){return e||"\\/"===t?t:t.replace(/\\\/$/,"")+"(?:\\/)?"}(this.source,i.strictTrailingSlash),s=this.urlTest(t,n+(this.hasQueryParams?"(\\?.*$|$)":"$"),i.caseSensitive,i.urlParamsEncoding);if(!s||!this.hasQueryParams)return s;var o=im(t,i.queryParams);return 0===Object.keys(o).filter((function(t){return!r.isQueryParam(t)})).length?(Object.keys(o).forEach((function(t){return s[t]=o[t]})),s):null},t.prototype.partialTest=function(t,e){var r=this,i=Jy(Jy({caseSensitive:!1,delimited:!0},this.options),e),n=function(t,e){return e?/(\/)$/.test(t)?t:t+"(\\/|\\?|\\.|;|$)":t}(this.source,i.delimited),s=this.urlTest(t,n,i.caseSensitive,i.urlParamsEncoding);if(!s)return s;if(!this.hasQueryParams)return s;var o=im(t,i.queryParams);return Object.keys(o).filter((function(t){return r.isQueryParam(t)})).forEach((function(t){return function(t,e,r){void 0===r&&(r="");var i=t[e];return t[e]=void 0===i?r:Array.isArray(i)?i.concat(r):[i,r],t}(s,t,o[t])})),s},t.prototype.build=function(t,e){var r=this;void 0===t&&(t={});var i=Jy(Jy({ignoreConstraints:!1,ignoreSearch:!1,queryParams:{}},this.options),e),n=Object.keys(t).filter((function(t){return!r.isQueryParam(t)})).reduce((function(e,n){if(!pm(t[n]))return e;var s=t[n],o=r.isSpatParam(n);return"boolean"==typeof s?e[n]=s:Array.isArray(s)?e[n]=s.map((function(t){return cm(t,i.urlParamsEncoding,o)})):e[n]=cm(s,i.urlParamsEncoding,o),e}),{});if(this.urlParams.some((function(e){return!pm(t[e])}))){var s=this.urlParams.filter((function(e){return!pm(t[e])}));throw new Error("Cannot build path: '"+this.path+"' requires missing parameters { "+s.join(", ")+" }")}if(!i.ignoreConstraints&&!this.tokens.filter((function(t){return/^url-parameter/.test(t.type)&&!/-splat$/.test(t.type)})).every((function(t){return new RegExp("^"+lm(t.otherVal[0])+"$").test(n[t.val])})))throw new Error("Some parameters of '"+this.path+"' are of invalid format");var o=this.tokens.filter((function(t){return!1===/^query-parameter/.test(t.type)})).map((function(t){return"url-parameter-matrix"===t.type?";"+t.val+"="+n[t.val[0]]:/^url-parameter/.test(t.type)?n[t.val[0]]:t.match})).join("");if(i.ignoreSearch)return o;var a=function(t,e){var r=Xy(e);return Object.keys(t).filter((function(e){return function(t){return void 0!==t}(t[e])})).map((function(e){return tm(e,t[e],r)})).filter(Boolean).join("&")}(this.queryParams.filter((function(e){return-1!==Object.keys(t).indexOf(e)})).reduce((function(e,r){return e[r]=t[r],e}),{}),i.queryParams);return a?o+"?"+a:o},t.prototype.getParams=function(t){var e=t instanceof RegExp?function(e){return t.test(e.type)}:function(e){return e.type===t};return this.tokens.filter(e).map((function(t){return t.val[0]}))},t.prototype.urlTest=function(t,e,r,i){var n=this,s=new RegExp("^"+e,r?"":"i"),o=t.match(s);return o?this.urlParams.length?o.slice(1,this.urlParams.length+1).reduce((function(t,e,r){return t[n.urlParams[r]]=(am[i]||decodeURIComponent)(e),t}),{}):{}:null},t}();class gm{constructor(t){this.routes={};for(const[e,r]of Object.entries(t)){let t,i;r instanceof Array?(t=r[0],i=r[1]||"GET"):(t=r,i="GET"),this.routes[i]=this.routes[i]||{},this.routes[i][e]=new fm(t)}}match(t,e="GET"){for(const[r,i]of Object.entries(this.routes[e]||[])){const e=t.split("?",2),n=e[0],s=i.test(n);if(s)return s._route=r,s._query=new URLSearchParams(2===e.length?e[1]:""),s}return{_route:null}}}class wm{constructor(t){this.router=new gm(this.routes),this.collections=t}get routes(){return{index:"coll-index",coll:"c/:coll",urls:"c/:coll/urls",createColl:["c/create","POST"],deleteColl:["c/:coll","DELETE"],updateAuth:["c/:coll/updateAuth","POST"],updateMetadata:["c/:coll/metadata","POST"],curated:"c/:coll/curated/:list",pages:"c/:coll/pages",textIndex:"c/:coll/textIndex",deletePage:["c/:coll/page/:page","DELETE"]}}async apiResponse(t,e,r){const i=this.router.match(t,e.method),n=await this.handleApi(e,i,r);if(n instanceof Response)return n;const s=n.error?404:200;return this.makeResponse(n,s)}async handleApi(t,e){switch(e._route){case"index":return await this.listAll(e._query.get("filter"));case"createColl":{const e=await t.json();return I(await this.collections.initNewColl(e.metadata||{},e.extraConfig||{}))}case"coll":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=I(t);return"1"===e._query.get("all")?(t.store.db?(r.pages=await t.store.getAllPages(),r.lists=await t.store.db.getAll("pageLists"),r.curatedPages=await t.store.db.getAll("curatedPages")):(r.pages=[],r.lists=[],r.curatedPages=[]),r.verify=await t.store.getVerifyInfo()):(r.numLists=await t.store.db.count("pageLists"),r.numPages=await t.store.db.count("pages")),t.config.metadata.ipfsPins&&(r.ipfsPins=t.config.metadata.ipfsPins),r}case"deleteColl":{const t="1"===e._query.get("reload");return await this.collections.deleteColl(e.coll,t)?await this.listAll():{error:"collection_not_found"}}case"updateAuth":{const r=await t.json();return{success:await this.collections.updateAuth(e.coll,r.headers)}}case"updateMetadata":{const r=await t.json();return{metadata:await this.collections.updateMetadata(e.coll,r)}}case"urls":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=e._query.get("url"),i=Number(e._query.get("count")||100),n=e._query.get("mime"),s="1"===e._query.get("prefix"),o=e._query.get("fromUrl"),a=e._query.get("fromTs"),c=e._query.get("fromMime"),l=Number(e._query.get("fromStatus")||0);if(!t.store.resourcesByMime)return{urls:[]};let u;return u=r?await t.store.resourcesByUrlAndMime(r,n,i,s,o,a):await t.store.resourcesByMime(n,i,c,o,l),u=u||[],{urls:u}}case"pages":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};return{pages:await t.store.getAllPages()}}case"textIndex":{const t=await this.collections.getColl(e.coll);return t?t.store.getTextIndex?await t.store.getTextIndex():{}:{error:"collection_not_found"}}case"curated":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=Number(e.list);return{curated:await t.store.db.getAllFromIndex("curatedPages","listPages",IDBKeyRange.bound([r],[r+1]))}}case"deletePage":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const{pageSize:r,deleteSize:i}=t.store.deletePage(e.page);return this.collections.updateSize(e.coll,r,i),{pageSize:r,deleteSize:i}}default:return{error:"not_found"}}}async listAll(t){const e=await this.collections.listAll(),r=[];return e.forEach((e=>{"live"!==e.type&&"remoteproxy"!==e.type&&(t&&0!==e.type.indexOf(t)||r.push(I(e)))})),{colls:r}}makeResponse(t,e=200){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":"application/json"}})}}const ym=/^(?::([\w-]+)\/)?(\d*)([a-z]+_|[$][a-z0-9:.-]+)?(?:\/|\||%7C|%7c)(.+)/;class mm{constructor(t,e,{isRoot:r=!1,mod:i="",ts:n="",proxyOrigin:s=null,localOrigin:o=null}={}){const a=ym.exec(t);if(this.url="",this.timestamp=n,this.mod=i,this.pageId="",this.hash="",!a&&(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("blob:")))this.url=t;else if(!a&&r)this.url="https://"+t;else{if(!a)return void(this.url=null);this.pageId=a[1]||"",this.timestamp=a[2],this.mod=a[3],this.url=a[4]}if(s&&o){const t=new URL(this.url);t.origin===o&&(this.url=s+t.pathname+(t.search?t.search:""))}const c=this.url.indexOf("#");c>0&&(this.hash=this.url.slice(c),this.url=this.url.substring(0,c)),this.request=e,this.method=e.method,this.mode=e.mode,this._postToGetConverted=!1}get headers(){return this.request.headers}get destination(){return this.request.destination}get referrer(){return this.request.referrer}async convertPostToGet(){if(this._postToGetConverted)return this.url;const t=this.request;if("POST"!==t.method&&"PUT"!==t.method)return this.url;const e={method:t.method,postData:await t.text(),headers:t.headers,url:this.url};return F(e)&&(this.url=e.url,this.method="GET",this.mode="navigate"===this.request.mode?"same-origin":this.request.mode,this._postToGetConverted=!0),this.url}prepareProxyRequest(t,e=!0){let r,i,n;if(e){r=new Headers(this.request.headers),i=this.request.referrer;const e=i.indexOf("/http",t.length-1);e>0&&(i=i.slice(e+1),r.set("X-Proxy-Referer",i)),n=this.request.credentials,this.cookie&&r.set("X-Proxy-Cookie",this.cookie)}else r=new Headers,n="omit";let s=this.url;if(s.startsWith("//"))try{s=new URL(i).protocol+s}catch(t){s="https:"+s}return{referrer:i,headers:r,credentials:n,url:s}}async getBody(){const t=this.request.clone();return new Uint8Array(await t.arrayBuffer())}}const bm="x-wabac-is-ajax-req";class Am extends Ky{constructor(t,e=null,r={}){super(self),this.prefixes=t,this.colls={},this.inited=null,this.root=e,this.defaultConfig=r,this._fileHandles={}}_createCollection(t){return new br(t,this.prefixes,this.defaultConfig)}loadAll(t){return this.colls={},this.inited=super.loadAll(t),this.inited}async getColl(t){return this.colls[t]||(this.colls[t]=await this.loadColl(t)),this.colls[t]}async reload(t){delete this.colls[t],await this.getColl(t)}async addCollection(t,e){const r=await super.addCollection(t,e);return r&&r.name&&(this.colls[r.name]=this._createCollection(r)),r}async deleteColl(t,e=!1){return this.colls[t]&&(this.colls[t].store&&this.colls[t].store.delete&&await this.colls[t].store.delete(),e&&this.colls[t].config&&this.colls[t].config.extra&&this.colls[t].config.extra.fileHandle&&(this._fileHandles[this.colls[t].config.sourceUrl]=this.colls[t].config.extra.fileHandle)),!!await super.deleteColl(t)&&(delete this.colls[t],!0)}async initNewColl(t,e={},r="archive"){const i=await super.initNewColl(t,e,r);return i&&(this.colls[i.name]=i),i}async updateAuth(t,e){this.colls[t]&&this.colls[t].store.updateHeaders&&this.colls[t].store.updateHeaders(e),await super.updateAuth(t,e)}async updateMetadata(t,e){const r=await super.updateMetadata(t,e);return this.colls[t]&&r&&(this.colls[t].config.metadata=r,this.colls[t].metadata=r),r}async updateSize(t,e,r,i){const n=await super.updateSize(t,e,r,i);return this.colls[t]&&n&&(this.colls[t].config.metadata=n,this.colls[t].metadata=n),void 0!==i&&this.colls[t]&&(this.colls[t].config.decode=i),n}}class Em{constructor({staticData:t=null,ApiClass:e=wm,defaultConfig:r={},CollectionsClass:i=Am}={}){this.prefix=self.registration?self.registration.scope:"",this.replayPrefix=this.prefix;const n=new URLSearchParams(self.location.search);let s="w";n.has("replayPrefix")&&(s=n.get("replayPrefix")),s&&(this.replayPrefix+=s+"/"),this.staticPrefix=this.prefix+"static/",this.distPrefix=this.prefix+"dist/";const o={static:this.staticPrefix,root:this.prefix,main:this.replayPrefix};this.staticData=t||new Map,this.staticData.set(this.staticPrefix+"wombat.js",{type:"application/javascript",content:'/*! wombat.js is part of Webrecorder project. Copyright (C) 2020-2023, Webrecorder Software. Licensed under the Affero General Public License v3. */(()=>{"use strict";function t(){this._map=[]}function e(t,e){void 0!==self.Symbol&&void 0!==self.Symbol.toStringTag&&Object.defineProperty(t.prototype,self.Symbol.toStringTag,{value:e,enumerable:!1})}function r(t){for(var e,r,i=t.__proto__||t.constructor.prototype||t.prototype,o=Object.getOwnPropertyNames(i),n=o.length,s=0;s=0?this._map.splice(e,1)[0][1]:null},t.prototype.map=function(t){for(var e=0;et+=String.fromCharCode(e)),""):t?t.toString():"";try{return"__wb_post_data="+btoa(e)}catch{return"__wb_post_data="}}function _(t){let{method:e,headers:r,postData:i}=t;if("GET"===e)return!1;function o(t){return t instanceof Uint8Array&&(t=(new TextDecoder).decode(t)),t}let n="";switch((r.get("content-type")||"").split(";")[0]){case"application/x-www-form-urlencoded":n=o(i);break;case"application/json":n=d(o(i));break;case"text/plain":try{n=d(o(i),!1)}catch{n=l(i)}break;case"multipart/form-data":{let t=r.get("content-type");if(!t)throw new Error("utils cannot call postToGetURL when missing content-type header");n=function(t,e){return function(t,e){let r=new URLSearchParams;t instanceof Uint8Array&&(t=(new TextDecoder).decode(t));try{let i=e.split("boundary=")[1],o=t.split(new RegExp("-*"+i+"-*","mi"));for(let t of o){let e=t.trim().match(/name="([^"]+)"\\r\\n\\r\\n(.*)/im);e&&r.set(e[1],e[2])}}catch{}return r}(t,e).toString()}(o(i),t);break}default:n=l(i)}return null!==n&&(t.url=function(t,e,r){if(!r)return t;let i=t.indexOf("?")>0?"&":"?";return`${t}${i}__wb_method=${r}&${e}`}(t.url,n,t.method),t.method="GET",t.requestBody=n,!0)}function u(t,e=!0){if("string"==typeof t)try{t=JSON.parse(t)}catch{t={}}let r=new URLSearchParams,i={};try{JSON.stringify(t,((t,e)=>(["object","function"].includes(typeof e)||r.set((t=>r.has(t)?(t in i||(i[t]=1),t+"."+ ++i[t]+"_"):t)(t),e),e)))}catch(t){if(!e)throw t}return r}function d(t,e=!0){return u(t,e).toString()}function f(e,i){if(!(this instanceof f))return new f(e,i);this.debug_rw=!1,this.$wbwindow=e,this.WBWindow=Window,this.origHost=e.location.host,this.origHostname=e.location.hostname,this.origProtocol=e.location.protocol,this.HTTP_PREFIX="http://",this.HTTPS_PREFIX="https://",this.REL_PREFIX="//",this.VALID_PREFIXES=[this.HTTP_PREFIX,this.HTTPS_PREFIX,this.REL_PREFIX],this.IGNORE_PREFIXES=["#","about:","data:","blob:","mailto:","javascript:","{","*"],"ignore_prefixes"in i&&(this.IGNORE_PREFIXES=this.IGNORE_PREFIXES.concat(i.ignore_prefixes)),this.WB_CHECK_THIS_FUNC="_____WB$wombat$check$this$function_____",this.WB_ASSIGN_FUNC="_____WB$wombat$assign$function_____",this.wb_setAttribute=e.Element.prototype.setAttribute,this.wb_getAttribute=e.Element.prototype.getAttribute,this.wb_funToString=Function.prototype.toString,this.WBAutoFetchWorker=null,this.wbUseAFWorker=i.enable_auto_fetch&&null!=e.Worker&&i.is_live,this.wb_rel_prefix="",this.wb_wombat_updating=!1,this.message_listeners=new t,this.storage_listeners=new t,this.linkAsTypes={script:"js_",worker:"js_",style:"cs_",image:"im_",document:"if_",fetch:"mp_",font:"oe_",audio:"oe_",video:"oe_",embed:"oe_",object:"oe_",track:"oe_","":"mp_",null:"mp_",undefined:"mp_"},this.linkTagMods={linkRelToAs:{import:this.linkAsTypes,preload:this.linkAsTypes},stylesheet:"cs_",null:"mp_",undefined:"mp_","":"mp_"},this.tagToMod={A:{href:"mp_"},AREA:{href:"mp_"},AUDIO:{src:"oe_",poster:"im_"},BASE:{href:"mp_"},EMBED:{src:"oe_"},FORM:{action:"mp_"},FRAME:{src:"fr_"},IFRAME:{src:"if_"},IMAGE:{href:"im_","xlink:href":"im_"},IMG:{src:"im_",srcset:"im_"},INPUT:{src:"oe_"},INS:{cite:"mp_"},META:{content:"mp_"},OBJECT:{data:"oe_",codebase:"oe_"},Q:{cite:"mp_"},SCRIPT:{src:"js_","xlink:href":"js_"},SOURCE:{src:"oe_",srcset:"oe_"},TRACK:{src:"oe_"},VIDEO:{src:"oe_",poster:"im_"},image:{href:"im_","xlink:href":"im_"}},this.URL_PROPS=["href","hash","pathname","host","hostname","protocol","origin","search","port"],this.wb_info=i,this.wb_opts=i.wombat_opts,this.wb_replay_prefix=i.prefix,this.wb_is_proxy=this.wb_info.proxy_magic||!this.wb_replay_prefix,this.wb_info.top_host=this.wb_info.top_host||"*",this.wb_curr_host=e.location.protocol+"//"+e.location.host,this.wb_info.wombat_opts=this.wb_info.wombat_opts||{},this.wb_orig_scheme=this.wb_info.wombat_scheme+"://",this.wb_orig_origin=this.wb_orig_scheme+this.wb_info.wombat_host,this.wb_abs_prefix=this.wb_replay_prefix,this.wb_capture_date_part="",!this.wb_info.is_live&&this.wb_info.wombat_ts&&(this.wb_capture_date_part="/"+this.wb_info.wombat_ts+"/"),this.BAD_PREFIXES=["http:"+this.wb_replay_prefix,"https:"+this.wb_replay_prefix,"http:/"+this.wb_replay_prefix,"https:/"+this.wb_replay_prefix],this.hostnamePortRe=/^[\\w-]+(\\.[\\w-_]+)+(:\\d+)(\\/|$)/,this.ipPortRe=/^\\d+\\.\\d+\\.\\d+\\.\\d+(:\\d+)?(\\/|$)/,this.workerBlobRe=/__WB_pmw\\(.*?\\)\\.(?=postMessage\\()/g,this.rmCheckThisInjectRe=/_____WB\\$wombat\\$check\\$this\\$function_____\\(.*?\\)/g,this.STYLE_REGEX=/(url\\s*\\(\\s*[\\\\"\']*)([^)\'"]+)([\\\\"\']*\\s*\\))/gi,this.IMPORT_REGEX=/(@import\\s*[\\\\"\']*)([^)\'";]+)([\\\\"\']*\\s*;?)/gi,this.IMPORT_JS_REGEX=/^(import\\s*\\([\'"]+)([^\'"]+)(["\'])/i,this.no_wombatRe=/WB_wombat_/g,this.srcsetRe=/\\s*(\\S*\\s+[\\d.]+[wx]),|(?:\\s*,(?:\\s+|(?=https?:)))/,this.cookie_path_regex=/\\bPath=\'?"?([^;\'"\\s]+)/i,this.cookie_domain_regex=/\\bDomain=([^;\'"\\s]+)/i,this.cookie_expires_regex=/\\bExpires=([^;\'"]+)/gi,this.SetCookieRe=/,(?![|])/,this.IP_RX=/^(\\d)+\\.(\\d)+\\.(\\d)+\\.(\\d)+$/,this.FullHTMLRegex=/^\\s*<(?:html|head|body|!doctype html)/i,this.IsTagRegex=/^\\s*0&&e.preserveMedia(r)}))},w.prototype.terminate=function(){this.worker.terminate()},w.prototype.justFetch=function(t){this.worker.postMessage({type:"fetch-all",values:t})},w.prototype.fetchAsPage=function(t,e,r){if(t){var i={"X-Wombat-History-Page":e};if(r){var o=encodeURIComponent(r.trim());r&&(i["X-Wombat-History-Title"]=o)}var n={url:t,options:{headers:i,cache:"no-store"}};this.justFetch([n])}},w.prototype.postMessage=function(t,e){if(e){var r=this;Promise.resolve().then((function(){r.worker.postMessage(t)}))}else this.worker.postMessage(t)},w.prototype.preserveSrcset=function(t,e){this.postMessage({type:"values",srcset:{value:t,mod:e,presplit:!0}},!0)},w.prototype.preserveDataSrcset=function(t){this.postMessage({type:"values",srcset:{value:t.dataset.srcset,mod:this.rwMod(t),presplit:!1}},!0)},w.prototype.preserveMedia=function(t){this.postMessage({type:"values",media:t},!0)},w.prototype.getSrcset=function(t){return this.wombat.wb_getAttribute?this.wombat.wb_getAttribute.call(t,"srcset"):t.getAttribute("srcset")},w.prototype.rwMod=function(t){switch(t.tagName){case"SOURCE":return t.parentElement&&"PICTURE"===t.parentElement.tagName?"im_":"oe_";case"IMG":return"im_"}return"oe_"},w.prototype.extractFromLocalDoc=function(){var t=this;Promise.resolve().then((function(){for(var e={type:"values",context:{docBaseURI:document.baseURI}},r=[],i=0,o=document.styleSheets;i=0||t.indexOf("ecmascript")>=0)&&(t.indexOf("json")>=0||t.indexOf("text/")>=0))},f.prototype.skipWrapScriptTextBasedOnText=function(t){if(!t||t.indexOf(this.WB_ASSIGN_FUNC)>=0||0===t.indexOf("<"))return!0;for(var e=["window","self","document","location","top","parent","frames","opener"],r=0;r=0)return!1;return!0},f.prototype.nodeHasChildren=function(t){if(!t)return!1;if("function"==typeof t.hasChildNodes)return t.hasChildNodes();var e=t.children||t.childNodes;return!!e&&e.length>0},f.prototype.rwModForElement=function(t,e){if(t){var r="mp_";if("LINK"===t.tagName&&"href"===e){if(t.rel){var i=t.rel.trim().toLowerCase(),o=this.wb_getAttribute.call(t,"as");if(o&&null!=this.linkTagMods.linkRelToAs[i])r=this.linkTagMods.linkRelToAs[i][o.toLowerCase()];else null!=this.linkTagMods[i]&&(r=this.linkTagMods[i])}}else{var n=this.tagToMod[t.tagName];null!=n&&(r=n[e])}return r}},f.prototype.removeWBOSRC=function(t){"SCRIPT"!==t.tagName||t.__$removedWBOSRC$__||(t.hasAttribute("__wb_orig_src")&&t.removeAttribute("__wb_orig_src"),t.__$removedWBOSRC$__=!0)},f.prototype.retrieveWBOSRC=function(t){var e;if("SCRIPT"===t.tagName&&!t.__$removedWBOSRC$__)return null==(e=this.wb_getAttribute?this.wb_getAttribute.call(t,"__wb_orig_src"):t.getAttribute("__wb_orig_src"))&&(t.__$removedWBOSRC$__=!0),e},f.prototype.wrapScriptTextJsProxy=function(t){return\'var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };\\nif (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }\\n{\\nlet window = _____WB$wombat$assign$function_____("window");\\nlet globalThis = _____WB$wombat$assign$function_____("globalThis");\\nlet self = _____WB$wombat$assign$function_____("self");\\nlet document = _____WB$wombat$assign$function_____("document");\\nlet location = _____WB$wombat$assign$function_____("location");\\nlet top = _____WB$wombat$assign$function_____("top");\\nlet parent = _____WB$wombat$assign$function_____("parent");\\nlet frames = _____WB$wombat$assign$function_____("frames");\\nlet opener = _____WB$wombat$assign$function_____("opener");\\n{\\n\'+t.replace(this.DotPostMessageRe,".__WB_pmw(self.window)$1")+"\\n\\n}}"},f.prototype.watchElem=function(t,e){if(!this.$wbwindow.MutationObserver)return!1;new this.$wbwindow.MutationObserver((function(t,r){for(var i=0;i"},f.prototype.getFinalUrl=function(t,e,r){var i=t?this.wb_rel_prefix:this.wb_abs_prefix;return null==e&&(e=this.wb_info.mod),this.wb_info.is_live||(i+=this.wb_info.wombat_ts),"/"!==(i+=e)[i.length-1]&&(i+="/"),i+r},f.prototype.resolveRelUrl=function(t,e){var r=e||this.$wbwindow.document,i=this.makeParser(r.baseURI,r),o=i.href.lastIndexOf("#"),n=o>=0?i.href.substring(0,o):i.href,s=n.lastIndexOf("/");return s>=0&&s!==n.length-1?i.href=n.substring(0,s+1)+t:i.href=n+t,i.href},f.prototype.extractOriginalURL=function(t){if(!t)return"";if(this.wb_is_proxy)return t;var e,r=t.toString(),i=r;if(this.startsWithOneOf(i,this.IGNORE_PREFIXES))return i;if(i.startsWith(this.wb_info.static_prefix))return i;e=this.startsWith(i,this.wb_abs_prefix)?this.wb_abs_prefix.length:this.wb_rel_prefix&&this.startsWith(i,this.wb_rel_prefix)?this.wb_rel_prefix.length:this.wb_rel_prefix?1:0;var o=i.indexOf("/http",e);return o<0&&(o=i.indexOf("///",e)),o<0&&(o=i.indexOf("/blob:",e)),o<0&&(o=i.indexOf("/about:blank",e)),o>=0?i=i.substr(o+1):((o=i.indexOf(this.wb_replay_prefix))>=0&&(i=i.substr(o+this.wb_replay_prefix.length)),i.length>4&&"_"===i.charAt(2)&&"/"===i.charAt(3)&&(i=i.substr(4)),i===r||this.startsWithOneOf(i,this.VALID_PREFIXES)||this.startsWith(i,"blob:")||(i=this.wb_orig_scheme+i)),"/"===r.charAt(0)&&"/"!==r.charAt(1)&&this.startsWith(i,this.wb_orig_origin)&&(i=i.substr(this.wb_orig_origin.length)),this.startsWith(i,this.REL_PREFIX)?this.wb_info.wombat_scheme+":"+i:i},f.prototype.makeParser=function(t,e){var r=this.extractOriginalURL(t),i=e;return e||(i="about:blank"===this.$wbwindow.location.href&&this.$wbwindow.opener?this.$wbwindow.opener.document:this.$wbwindow.document),this._makeURLParser(r,i)},f.prototype._makeURLParser=function(t,e){try{return new this.$wbwindow.URL(t,e.baseURI)}catch(t){}var r=e.createElement("a");return r._no_rewrite=!0,r.href=t,r},f.prototype.defProp=function(t,e,r,i,o){var n=Object.getOwnPropertyDescriptor(t,e);if(n&&!n.configurable)return!1;if(!i)return!1;var s={configurable:!0,enumerable:o||!1,get:i};r&&(s.set=r);try{return Object.defineProperty(t,e,s),!0}catch(t){return console.warn("Failed to redefine property %s",e,t.message),!1}},f.prototype.defGetterProp=function(t,e,r,i){var o=Object.getOwnPropertyDescriptor(t,e);if(o&&!o.configurable)return!1;if(!r)return!1;try{return Object.defineProperty(t,e,{configurable:!0,enumerable:i||!1,get:r}),!0}catch(t){return console.warn("Failed to redefine property %s",e,t.message),!1}},f.prototype.getOrigGetter=function(t,e){var r;if(t.__lookupGetter__&&(r=t.__lookupGetter__(e)),!r&&Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(t,e);i&&(r=i.get)}return r},f.prototype.getOrigSetter=function(t,e){var r;if(t.__lookupSetter__&&(r=t.__lookupSetter__(e)),!r&&Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(t,e);i&&(r=i.set)}return r},f.prototype.getAllOwnProps=function(t){for(var e=[],r=Object.getOwnPropertyNames(t),i=0;i "+n),r.href=n}}},f.prototype.checkLocationChange=function(t,e){var r=typeof t,i=e?this.$wbwindow.__WB_replay_top.location:this.$wbwindow.location;"string"===r?this.updateLocation(t,i.href,i):"object"===r&&this.updateLocation(t.href,t._orig_href,i)},f.prototype.checkAllLocations=function(){if(this.wb_wombat_updating)return!1;this.wb_wombat_updating=!0,this.checkLocationChange(this.$wbwindow.WB_wombat_location,!1),this.$wbwindow.WB_wombat_location!=this.$wbwindow.__WB_replay_top.WB_wombat_location&&this.checkLocationChange(this.$wbwindow.__WB_replay_top.WB_wombat_location,!0),this.wb_wombat_updating=!1},f.prototype.proxyToObj=function(t){if(t)try{var e=t.__WBProxyRealObj__;if(e)return e}catch(t){}return t},f.prototype.objToProxy=function(t){if(t)try{var e=t._WB_wombat_obj_proxy;if(e)return e}catch(t){}return t},f.prototype.defaultProxyGet=function(t,e,r,i){switch(e){case"__WBProxyRealObj__":return t;case"location":case"WB_wombat_location":return t.WB_wombat_location;case"_WB_wombat_obj_proxy":return t._WB_wombat_obj_proxy;case"__WB_pmw":case this.WB_ASSIGN_FUNC:case this.WB_CHECK_THIS_FUNC:return t[e];case"origin":return t.WB_wombat_location.origin;case"constructor":return t.constructor}var o=t[e],n=typeof o;if("function"===n&&-1!==r.indexOf(e)){switch(e){case"requestAnimationFrame":case"cancelAnimationFrame":if(!this.isNativeFunction(o))return o;break;case"eval":if(this.isNativeFunction(o))return this.wrappedEval(o)}var s=i[e];return s&&s.original===o||(s={original:o,boundFn:o.bind(t)},i[e]=s),s.boundFn}return"object"===n&&o&&o._WB_wombat_obj_proxy?(o instanceof this.WBWindow&&this.initNewWindowWombat(o),o._WB_wombat_obj_proxy):o},f.prototype.setLoc=function(t,e){var r=this.makeParser(e,t.ownerDocument);t._orig_href=e,t._parser=r;var i=r.href;t._hash=r.hash,t._href=i,t._host=r.host,t._hostname=r.hostname,r.origin?t._origin=r.host?r.origin:"null":t._origin=r.protocol+"//"+r.hostname+(r.port?":"+r.port:""),t._pathname=r.pathname,t._port=r.port,t._protocol=r.protocol,t._search=r.search,Object.defineProperty||(t.href=i,t.hash=r.hash,t.host=t._host,t.hostname=t._hostname,t.origin=t._origin,t.pathname=t._pathname,t.port=t._port,t.protocol=t._protocol,t.search=t._search)},f.prototype.makeGetLocProp=function(t,e){var r=this;return function(){if(this._no_rewrite)return e.call(this,t);var i=e.call(this,"href");return"href"===t?r.extractOriginalURL(i):"ancestorOrigins"===t?[]:(this._orig_href!==i&&r.setLoc(this,i),this["_"+t])}},f.prototype.makeSetLocProp=function(t,e,r){var i=this;return function(o){if(this._no_rewrite)return e.call(this,t,o);if(this["_"+t]!==o){if(this["_"+t]=o,!this._parser){var n=r.call(this);this._parser=i.makeParser(n,this.ownerDocument)}var s=!1;if("href"===t&&"string"==typeof o)if(o&&this._parser instanceof URL)try{o=new URL(o,this._parser).href}catch(t){console.warn("Error resolving URL",t)}else o&&("."===o[0]||"#"===o[0]?o=i.resolveRelUrl(o,this.ownerDocument):"/"===o[0]&&(o.length>1&&"/"===o[1]?o=this._parser.protocol+o:(s=!0,o=WB_wombat_location.origin+o)));try{this._parser[t]=o}catch(e){console.log("Error setting "+t+" = "+o)}"hash"===t?(o=this._parser[t],e.call(this,"hash",o)):(s=s||o===this._parser.pathname,o=i.rewriteUrl(this._parser.href,s),e.call(this,"href",o))}}},f.prototype.styleReplacer=function(t,e,r,i,o,n){return e+this.rewriteUrl(r)+i},f.prototype.domConstructorErrorChecker=function(t,e,r,i){var o,n="number"==typeof i?i:1;if(t instanceof this.WBWindow?o="Failed to construct \'"+e+"\': Please use the \'new\' operator, this DOM object constructor cannot be called as a function.":r&&r.length=0)return o;if(0===o.indexOf(this.wb_rel_prefix)&&o.indexOf("http")>1){var a=o.indexOf(":/");return a>0&&"/"!==o[a+2]?o.substring(0,a+2)+"/"+o.substring(a+2):o}return this.getFinalUrl(!0,r,this.wb_orig_origin+o)}"."===o.charAt(0)&&(o=this.resolveRelUrl(o,i));var h=this.startsWithOneOf(o.toLowerCase(),this.VALID_PREFIXES);if(h){var w=this.replayTopHost,p=this.replayTopProtocol,c=h+w+"/";if(this.startsWith(o,c)){if(this.startsWith(o,this.wb_replay_prefix))return o;var l=p+"//",_=o.substring(c.length),u=!1;return _.indexOf(this.wb_rel_prefix)<0&&o.indexOf("/static/")<0&&(_=this.getFinalUrl(!0,r,WB_wombat_location.origin+"/"+_),u=!0),h!==l&&h!==this.REL_PREFIX&&(u=!0),u&&(o=e?"":l+w,_&&"/"!==_[0]&&(o+="/"),o+=_),o}return this.getFinalUrl(e,r,o)}return(h=this.startsWithOneOf(o,this.BAD_PREFIXES))?this.getFinalUrl(e,r,this.extractOriginalURL(o)):o},f.prototype.rewriteUrl=function(t,e,r,i){var o=this.rewriteUrl_(t,e,r,i);return this.debug_rw&&(t!==o?console.log("REWRITE: "+t+" -> "+o):console.log("NOT REWRITTEN "+t)),o},f.prototype.performAttributeRewrite=function(t,e,r,i){switch(e){case"innerHTML":case"outerHTML":return this.rewriteHtml(r);case"filter":return this.rewriteInlineStyle(r);case"style":return this.rewriteStyle(r);case"srcset":return this.rewriteSrcset(r,t)}if(i&&!this.startsWithOneOf(r,this.VALID_PREFIXES))return r;var o=this.rwModForElement(t,e);return this.wbUseAFWorker&&this.WBAutoFetchWorker&&this.isSavedDataSrcSrcset(t)&&this.WBAutoFetchWorker.preserveDataSrcset(t),this.rewriteUrl(r,!1,o,t.ownerDocument)},f.prototype.rewriteAttr=function(t,e,r){var i=!1;if(!t||!t.getAttribute||t._no_rewrite||t["_"+e])return i;var o=this.wb_getAttribute.call(t,e);if(!o||this.startsWith(o,"javascript:"))return i;var n=this.performAttributeRewrite(t,e,o,r);return n!==o&&(this.removeWBOSRC(t),this.wb_setAttribute.call(t,e,n),i=!0),i},f.prototype.noExceptRewriteStyle=function(t){try{return this.rewriteStyle(t)}catch(e){return t}},f.prototype.rewriteStyle=function(t){if(!t)return t;var e=t;return"object"==typeof t&&(e=t.toString()),"string"==typeof e?e.replace(this.STYLE_REGEX,this.styleReplacer).replace(this.IMPORT_REGEX,this.styleReplacer).replace(this.no_wombatRe,""):e},f.prototype.rewriteSrcset=function(t,e){if(!t)return"";for(var r=t.split(this.srcsetRe),i=[],o=this.rwModForElement(e,"srcset"),n=0;n=0){var o="javascript:";r=o+"window.parent._wb_wombat.initNewWindowWombat(window);"+i.substr(o.length)}return r||(r=this.rewriteUrl(i,!1,this.rwModForElement(t,e))),r!==i&&(this.wb_setAttribute.call(t,e,r),!0)},f.prototype.rewriteScript=function(t){if(t.hasAttribute("src")||!t.textContent||!this.$wbwindow.Proxy)return this.rewriteAttr(t,"src");if(this.skipWrapScriptBasedOnType(t.type))return!1;var e=t.textContent.trim();return!this.skipWrapScriptTextBasedOnText(e)&&(t.textContent=this.wrapScriptTextJsProxy(e),!0)},f.prototype.rewriteSVGElem=function(t){var e=this.rewriteAttr(t,"filter");return e=this.rewriteAttr(t,"style")||e,e=this.rewriteAttr(t,"xlink:href")||e,e=this.rewriteAttr(t,"href")||e,e=this.rewriteAttr(t,"src")||e},f.prototype.rewriteElem=function(t){var e=!1;if(!t)return e;if(t instanceof SVGElement)e=this.rewriteSVGElem(t);else switch(t.tagName){case"META":var r=this.wb_getAttribute.call(t,"http-equiv");r&&"content-security-policy"===r.toLowerCase()&&(this.wb_setAttribute.call(t,"http-equiv","_"+r),e=!0);break;case"STYLE":var i=this.rewriteStyle(t.textContent);t.textContent!==i&&(t.textContent=i,e=!0,this.wbUseAFWorker&&this.WBAutoFetchWorker&&null!=t.sheet&&this.WBAutoFetchWorker.deferredSheetExtraction(t.sheet));break;case"LINK":e=this.rewriteAttr(t,"href"),this.wbUseAFWorker&&"stylesheet"===t.rel&&this._addEventListener(t,"load",this.utilFns.wbSheetMediaQChecker);break;case"IMG":e=this.rewriteAttr(t,"src"),e=this.rewriteAttr(t,"srcset")||e,e=this.rewriteAttr(t,"style")||e,this.wbUseAFWorker&&this.WBAutoFetchWorker&&t.dataset.srcset&&this.WBAutoFetchWorker.preserveDataSrcset(t);break;case"OBJECT":if(this.wb_info.isSW&&t.parentElement&&"application/pdf"===t.getAttribute("type")){for(var o=this.$wbwindow.document.createElement("IFRAME"),n=0;n0;)for(var i=r.shift(),o=0;o"+r+"","text/html");if(!i||!this.nodeHasChildren(i.head)||!i.head.children[0].content)return r;var o=i.head.children[0];if(o._no_rewrite=!0,this.recurseRewriteElem(o.content)){var n=o.innerHTML;if(e){var s=o.content.children&&o.content.children[0];if(s){var a="";this.endsWith(n,a)&&!this.endsWith(r.toLowerCase(),a)&&(n=n.substring(0,n.length-a.length))}else if("<"!==r[0]||">"!==r[r.length-1])return void(this.write_buff+=r)}return n}return r},f.prototype.rewriteHtmlFull=function(t,e){var r=(new DOMParser).parseFromString(t,"text/html");if(!r)return t;for(var i=!1,o=0;o=0)r.documentElement._no_rewrite=!0,n=this.reconstructDocType(r.doctype)+r.documentElement.outerHTML;else{r.head._no_rewrite=!0,r.body._no_rewrite=!0;var s=this.nodeHasChildren(r.head),a=this.nodeHasChildren(r.body);if(n=(s?r.head.outerHTML:"")+(a?r.body.outerHTML:""),e)if(r.all.length>3){var h="";this.endsWith(n,h)&&!this.endsWith(t.toLowerCase(),h)&&(n=n.substring(0,n.length-h.length))}else if("<"!==t[0]||">"!==t[t.length-1])return void(this.write_buff+=t);n=this.reconstructDocType(r.doctype)+n}return n}return t},f.prototype.rewriteInlineStyle=function(t){var e;try{e=decodeURIComponent(t)}catch(r){e=t}if(e!==t){var r=this.rewriteStyle(e).split(",",2);return r[0]+","+encodeURIComponent(r[1])}return this.rewriteStyle(t)},f.prototype.rewriteCookie=function(t){var e=this,r=t.replace(this.wb_abs_prefix,"").replace(this.wb_rel_prefix,"");return r=r.replace(this.cookie_domain_regex,(function(t,i){var o={domain:i,cookie:r,wb_type:"cookie"};return e.sendTopMessage(o,!0),e.$wbwindow.location.hostname.indexOf(".")>=0&&!e.IP_RX.test(e.$wbwindow.location.hostname)?"Domain=."+e.$wbwindow.location.hostname:""})).replace(this.cookie_path_regex,(function(t,r){var i=e.rewriteUrl(r);return 0===i.indexOf(e.wb_curr_host)&&(i=i.substring(e.wb_curr_host.length)),"Path="+i})),"https:"!==e.$wbwindow.location.protocol&&(r=r.replace("secure","")),r.replace(",|",",")},f.prototype.rewriteWorker=function(t){if(!t)return t;var e=0===(t=t.toString()).indexOf("blob:"),r=0===t.indexOf("javascript:");if(!e&&!r){if(!this.startsWithOneOf(t,this.VALID_PREFIXES)&&!this.startsWith(t,"/")&&!this.startsWithOneOf(t,this.BAD_PREFIXES)){var i=this.resolveRelUrl(t,this.$wbwindow.document);return this.rewriteUrl(i,!1,"wkr_",this.$wbwindow.document)}return this.rewriteUrl(t,!1,"wkr_",this.$wbwindow.document)}var o=r?t.replace("javascript:",""):null;if(e){var n=new XMLHttpRequest;this.utilFns.XHRopen.call(n,"GET",t,!1),this.utilFns.XHRsend.call(n),o=n.responseText.replace(this.workerBlobRe,"").replace(this.rmCheckThisInjectRe,"this")}if(this.wb_info.static_prefix||this.wb_info.ww_rw_script){var s=this.$wbwindow.document.baseURI;o="(function() { self.importScripts(\'"+(this.wb_info.ww_rw_script||this.wb_info.static_prefix+"wombatWorkers.js")+"\'); new WBWombat({\'prefix\': \'"+this.wb_abs_prefix+"\', \'prefixMod\': \'"+this.wb_abs_prefix+"wkrf_/\', \'originalURL\': \'"+s+"\'}); })();"+o}var a=new Blob([o],{type:"application/javascript"});return URL.createObjectURL(a)},f.prototype.rewriteTextNodeFn=function(t,e,r){var i,o=this.proxyToObj(t);if(r.length>0&&o.parentElement&&"STYLE"===o.parentElement.tagName){i=new Array(r.length);var n=r.length-1;2===n?(i[0]=r[0],i[1]=r[1]):1===n&&(i[0]=r[0]),i[n]=this.rewriteStyle(r[n])}else i=r;return e.__WB_orig_apply?e.__WB_orig_apply(o,i):e.apply(o,i)},f.prototype.rewriteChildNodeFn=function(t,e,r){var i=this.proxyToObj(t);if(0===r.length)return e.call(i);var o=this.rewriteElementsInArguments(r);return e.__WB_orig_apply?e.__WB_orig_apply(i,o):e.apply(i,o)},f.prototype.rewriteInsertAdjHTMLOrElemArgs=function(t,e,r,i,o){var n=this.proxyToObj(t);return n._no_rewrite?e.call(n,r,i):o?e.call(n,r,this.rewriteHtml(i)):(this.rewriteElemComplete(i),e.call(n,r,i))},f.prototype.rewriteSetTimeoutInterval=function(t,e,r){var i=this.isString(r[0]),o=i?new Array(r.length):r;if(i){this.$wbwindow.Proxy?o[0]=this.wrapScriptTextJsProxy(r[0]):o[0]=r[0].replace(/\\blocation\\b/g,"WB_wombat_$&");for(var n=1;n(t.includes(r)&&(i=o.rewriteStyle(i)),e[r]=i,!0),get(t,i,n){var s=t[i];return"function"!=typeof s||"setProperty"!==i&&!o.isNativeFunction(s)?s:(r[i]||(r[i]=s.bind(e)),r[i])}})}))},f.prototype.overrideIframeContentAccess=function(t){if(this.$wbwindow.HTMLIFrameElement&&this.$wbwindow.HTMLIFrameElement.prototype){var e=this.$wbwindow.HTMLIFrameElement.prototype,r=this.getOrigGetter(e,t);if(r){var i=this.getOrigSetter(e,t),o=this;this.defProp(e,t,i,(function(){return o.initIframeWombat(this),o.objToProxy(r.call(this))})),e["_get_"+t]=r}}},f.prototype.overrideFramesAccess=function(t){if(!t.Proxy||t!==t.frames){t.__wb_frames=t.frames;var e=this,r=function(){for(var t=0;t0&&i(this.$wbwindow.CSSStyleValue,"parse"),this.$wbwindow.CSSStyleValue.parseAll&&this.$wbwindow.CSSStyleValue.parseAll.toString().indexOf("[native code]")>0&&i(this.$wbwindow.CSSStyleValue,"parseAll")}if(this.$wbwindow.CSSKeywordValue&&this.$wbwindow.CSSKeywordValue.prototype){var o=this.$wbwindow.CSSKeywordValue;this.$wbwindow.CSSKeywordValue=(t=this.$wbwindow.CSSKeywordValue,function(e){return r.domConstructorErrorChecker(this,"CSSKeywordValue",arguments),new t(r.rewriteStyle(e))}),this.$wbwindow.CSSKeywordValue.prototype=o.prototype,Object.defineProperty(this.$wbwindow.CSSKeywordValue.prototype,"constructor",{value:this.$wbwindow.CSSKeywordValue}),e(this.$wbwindow.CSSKeywordValue,"CSSKeywordValue")}if(this.$wbwindow.StylePropertyMap&&this.$wbwindow.StylePropertyMap.prototype){var n=this.$wbwindow.StylePropertyMap.prototype.set;this.$wbwindow.StylePropertyMap.prototype.set=function(){if(arguments.length<=1)return n.__WB_orig_apply?n.__WB_orig_apply(this,arguments):n.apply(this,arguments);var t=new Array(arguments.length);t[0]=arguments[0];for(var e=1;e")&&(e[0]=r.rewriteHtml(e[0]),i.type="text/html"),new t(e,i)}),this.$wbwindow.Blob.prototype=e.prototype}},f.prototype.initWSOverride=function(){this.$wbwindow.WebSocket&&this.$wbwindow.WebSocket.prototype&&(this.$wbwindow.WebSocket=function(t){function e(t,e){this.addEventListener=function(){},this.removeEventListener=function(){},this.close=function(){},this.send=function(t){console.log("ws send",t)},this.protocol=e&&e.length?e[0]:"",this.url=t,this.readyState=0}return e.CONNECTING=0,e.OPEN=1,e.CLOSING=2,e.CLOSED=3,e}(this.$wbwindow.WebSocket),Object.defineProperty(this.$wbwindow.WebSocket.prototype,"constructor",{value:this.$wbwindow.WebSocket}),e(this.$wbwindow.WebSocket,"WebSocket"))},f.prototype.initDocTitleOverride=function(){var t=this.getOrigGetter(this.$wbwindow.document,"title"),e=this.getOrigSetter(this.$wbwindow.document,"title"),r=this;this.defProp(this.$wbwindow.document,"title",(function(t){var i=e.call(this,t),o={wb_type:"title",title:t};return r.sendTopMessage(o),i}),t)},f.prototype.initFontFaceOverride=function(){if(this.$wbwindow.FontFace){var t,r=this,i=this.$wbwindow.FontFace;this.$wbwindow.FontFace=(t=this.$wbwindow.FontFace,function(e,i,o){r.domConstructorErrorChecker(this,"FontFace",arguments,2);var n=i;return null!=i&&(n="string"!=typeof i?r.rewriteInlineStyle(i.toString()):r.rewriteInlineStyle(i)),new t(e,n,o)}),this.$wbwindow.FontFace.prototype=i.prototype,Object.defineProperty(this.$wbwindow.FontFace.prototype,"constructor",{value:this.$wbwindow.FontFace}),e(this.$wbwindow.FontFace,"FontFace")}},f.prototype.initFixedRatio=function(t){try{this.$wbwindow.devicePixelRatio=t}catch(t){}if(Object.defineProperty)try{Object.defineProperty(this.$wbwindow,"devicePixelRatio",{value:t,writable:!1})}catch(t){}},f.prototype.initPaths=function(t){t.wombat_opts=t.wombat_opts||{},Object.assign(this.wb_info,t),this.wb_opts=t.wombat_opts,this.wb_replay_prefix=t.prefix,this.wb_is_proxy=t.proxy_magic||!this.wb_replay_prefix,this.wb_info.top_host=this.wb_info.top_host||"*",this.wb_curr_host=this.$wbwindow.location.protocol+"//"+this.$wbwindow.location.host,this.wb_info.wombat_opts=this.wb_info.wombat_opts||{},this.wb_orig_scheme=t.wombat_scheme+"://",this.wb_orig_origin=this.wb_orig_scheme+t.wombat_host,this.wb_abs_prefix=this.wb_replay_prefix,!t.is_live&&t.wombat_ts?this.wb_capture_date_part="/"+t.wombat_ts+"/":this.wb_capture_date_part="",this.initBadPrefixes(this.wb_replay_prefix),this.initCookiePreset()},f.prototype.initSeededRandom=function(t){this.$wbwindow.Math.seed=parseInt(t);var e=this;this.$wbwindow.Math.random=function(){return e.$wbwindow.Math.seed=(9301*e.$wbwindow.Math.seed+49297)%233280,e.$wbwindow.Math.seed/233280}},f.prototype.initHistoryOverrides=function(){this.overrideHistoryFunc("pushState"),this.overrideHistoryFunc("replaceState");var t=this;this.$wbwindow.addEventListener("popstate",(function(e){t.sendHistoryUpdate(t.$wbwindow.WB_wombat_location.href,t.$wbwindow.document.title)}))},f.prototype.initCookiePreset=function(){if(this.wb_info.presetCookie)for(var t=this.wb_info.presetCookie.split(";"),e=0;e2&&!this.__WB_xhr_open_arguments[2]&&-1===navigator.userAgent.indexOf("Firefox")&&(this.__WB_xhr_open_arguments[2]=!0,console.warn("wombat.js: Sync XHR not supported in SW-based replay in this browser, converted to async")),this._no_rewrite||(this.__WB_xhr_open_arguments[1]=i.rewriteUrl(this.__WB_xhr_open_arguments[1])),o.apply(this,this.__WB_xhr_open_arguments),!i.startsWith(this.__WB_xhr_open_arguments[1],"data:")){for(const[t,e]of this.__WB_xhr_headers.entries())n.call(this,t,e);n.call(this,"X-Pywb-Requested-With","XMLHttpRequest")}return s.call(this,t)}}else if(this.$wbwindow.XMLHttpRequest.prototype.open){var h=this.$wbwindow.XMLHttpRequest.prototype.open;this.utilFns.XHRopen=h,this.utilFns.XHRsend=this.$wbwindow.XMLHttpRequest.prototype.send,this.$wbwindow.XMLHttpRequest.prototype.open=function(t,e,r,o,n){var s=this._no_rewrite?e:i.rewriteUrl(e),a=!0;null==r||r||(a=!1),h.call(this,t,s,a,o,n),i.startsWith(s,"data:")||this.setRequestHeader("X-Pywb-Requested-With","XMLHttpRequest")}}if(this.$wbwindow.fetch){var w=this.$wbwindow.fetch;this.$wbwindow.fetch=function(t,e){var r=t,o=typeof t;if("string"===o)r=i.rewriteUrl(t);else if("object"===o&&t.url){var n=i.rewriteUrl(t.url);n!==t.url&&(r=new Request(n,e))}else"object"===o&&t.href&&(r=i.rewriteUrl(t.href));if(e||(e={}),void 0===e.credentials)try{e.credentials="include"}catch(t){}return w.call(i.proxyToObj(this),r,e)}}if(this.$wbwindow.Request&&this.$wbwindow.Request.prototype){var p=this.$wbwindow.Request;this.$wbwindow.Request=(t=this.$wbwindow.Request,function(e,r){i.domConstructorErrorChecker(this,"Request",arguments);var o=r||{},n=e,s=typeof e;switch(s){case"string":n=i.rewriteUrl(e);break;case"object":if(n=e,e.url){var a=i.rewriteUrl(e.url);a!==e.url&&(n=new t(a,e))}else e.href&&(n=i.rewriteUrl(e.toString(),!0))}return o.credentials="include",o.referrer&&(o.referrer=i.rewriteUrl(o.referrer)),new t(n,o)}),this.$wbwindow.Request.prototype=p.prototype,Object.defineProperty(this.$wbwindow.Request.prototype,"constructor",{value:this.$wbwindow.Request}),this.overridePropExtract(this.$wbwindow.Request.prototype,"url"),this.overridePropExtract(this.$wbwindow.Request.prototype,"referrer")}if(this.$wbwindow.Response&&this.$wbwindow.Response.prototype){var c=this.$wbwindow.Response.prototype.redirect;this.$wbwindow.Response.prototype.redirect=function(t,e){var r=i.rewriteUrl(t,!0,null,i.$wbwindow.document);return c.call(this,r,e)},this.overridePropExtract(this.$wbwindow.Response.prototype,"url")}if(this.$wbwindow.EventSource&&this.$wbwindow.EventSource.prototype){var l=this.$wbwindow.EventSource;this.$wbwindow.EventSource=(r=this.$wbwindow.EventSource,function(t,e){i.domConstructorErrorChecker(this,"EventSource",arguments);var o=t;return null!=t&&(o=i.rewriteUrl(t)),new r(o,e)}),this.$wbwindow.EventSource.prototype=l.prototype,Object.defineProperty(this.$wbwindow.EventSource.prototype,"constructor",{value:this.$wbwindow.EventSource}),e(this.$wbwindow.EventSource,"EventSource")}},f.prototype.initElementGetSetAttributeOverride=function(){if(!this.wb_opts.skip_setAttribute&&this.$wbwindow.Element&&this.$wbwindow.Element.prototype){var t=this,e=this.$wbwindow.Element.prototype;if(e.setAttribute){var r=e.setAttribute;e._orig_setAttribute=r,e.setAttribute=function(e,i){var o=i;if(e&&"string"==typeof o){var n=e.toLowerCase();if("LINK"===this.tagName&&"href"===n&&0===o.indexOf("data:text/css"))o=t.rewriteInlineStyle(i);else if("style"===n)o=t.rewriteStyle(i);else if("srcset"===n||"imagesrcset"===n&&"LINK"===this.tagName)o=t.rewriteSrcset(i,this);else{t.shouldRewriteAttr(this.tagName,n)&&(t.removeWBOSRC(this),this._no_rewrite||(o=t.rewriteUrl(i,!1,t.rwModForElement(this,n))))}}return r.call(this,e,o)}}if(e.getAttribute){var i=e.getAttribute;this.wb_getAttribute=i,e.getAttribute=function(e){var r=i.call(this,e);if(null===r)return r;var o=e;if(e&&(o=e.toLowerCase()),t.shouldRewriteAttr(this.tagName,o)){var n=t.retrieveWBOSRC(this);return n||t.extractOriginalURL(r)}return t.startsWith(o,"data-")&&t.startsWithOneOf(r,t.wb_prefixes)?t.extractOriginalURL(r):r}}}},f.prototype.initSvgImageOverrides=function(){if(this.$wbwindow.SVGImageElement){var t=this.$wbwindow.SVGImageElement.prototype,e=t.getAttribute,r=t.getAttributeNS,i=t.setAttribute,o=t.setAttributeNS,n=this;t.getAttribute=function(t){var r=e.call(this,t);return t.indexOf("xlink:href")>=0||"href"===t?n.extractOriginalURL(r):r},t.getAttributeNS=function(t,e){var i=r.call(this,t,e);return e.indexOf("xlink:href")>=0||"href"===e?n.extractOriginalURL(i):i},t.setAttribute=function(t,e){var r=e;return(t.indexOf("xlink:href")>=0||"href"===t)&&(r=n.rewriteUrl(e)),i.call(this,t,r)},t.setAttributeNS=function(t,e,r){var i=r;return(e.indexOf("xlink:href")>=0||"href"===e)&&(i=n.rewriteUrl(r)),o.call(this,t,e,i)}}},f.prototype.initCreateElementNSFix=function(){if(this.$wbwindow.document.createElementNS&&this.$wbwindow.Document.prototype.createElementNS){var t=this.$wbwindow.document.createElementNS,e=this,r=function(r,i){return t.call(e.proxyToObj(this),e.extractOriginalURL(r),i)};this.$wbwindow.Document.prototype.createElementNS=r,this.$wbwindow.document.createElementNS=r}},f.prototype.initInsertAdjacentElementHTMLOverrides=function(){var t=this.$wbwindow.Element;if(t&&t.prototype){var e=t.prototype,r=this.rewriteInsertAdjHTMLOrElemArgs;if(e.insertAdjacentHTML){var i=e.insertAdjacentHTML;e.insertAdjacentHTML=function(t,e){return r(this,i,t,e,!0)}}if(e.insertAdjacentElement){var o=e.insertAdjacentElement;e.insertAdjacentElement=function(t,e){return r(this,o,t,e,!1)}}}},f.prototype.initDomOverride=function(){var t=this.$wbwindow.Node;if(t&&t.prototype){var e=this.rewriteNodeFuncArgs;if(t.prototype.appendChild){var r=t.prototype.appendChild;t.prototype.appendChild=function(t,i){return e(this,r,t,i)}}if(t.prototype.insertBefore){var i=t.prototype.insertBefore;t.prototype.insertBefore=function(t,r){return e(this,i,t,r)}}if(t.prototype.replaceChild){var o=t.prototype.replaceChild;t.prototype.replaceChild=function(t,r){return e(this,o,t,r)}}this.overridePropToProxy(t.prototype,"ownerDocument"),this.overridePropToProxy(this.$wbwindow.HTMLHtmlElement.prototype,"parentNode"),this.overridePropToProxy(this.$wbwindow.Event.prototype,"target")}this.$wbwindow.Element&&this.$wbwindow.Element.prototype&&(this.overrideParentNodeAppendPrepend(this.$wbwindow.Element),this.overrideChildNodeInterface(this.$wbwindow.Element,!1)),this.$wbwindow.DocumentFragment&&this.$wbwindow.DocumentFragment.prototype&&this.overrideParentNodeAppendPrepend(this.$wbwindow.DocumentFragment)},f.prototype.initDocOverrides=function(t){if(Object.defineProperty){this.overrideReferrer(t),this.defGetterProp(t,"origin",(function(){return this.WB_wombat_location.origin})),this.defGetterProp(this.$wbwindow,"origin",(function(){return this.WB_wombat_location.origin}));var e=this;this.defProp(t,"domain",(function(t){var r=this.WB_wombat_location;r&&e.endsWith(r.hostname,t)&&(this.__wb_domain=t)}),(function(){return this.__wb_domain||this.WB_wombat_location.hostname}))}},f.prototype.initDocWriteOpenCloseOverride=function(){if(this.$wbwindow.DOMParser){var t=this.$wbwindow.Document.prototype,e=this.$wbwindow.document;this._writeBuff="";var r=this,i=e.write,o=function(){return d(this,i,u(arguments))};e.write=o,t.write=o;var n=e.writeln,s=function(){return d(this,n,u(arguments))};e.writeln=s,t.writeln=s;var a=e.open,h=function(){var t,e=r.proxyToObj(this);if(3===arguments.length){var i=r.rewriteUrl(arguments[0],!1,"mp_");t=a.call(e,i,arguments[1],arguments[2]),r.initNewWindowWombat(t,arguments[0])}else t=a.call(e),_()?r._writeBuff="":r.initNewWindowWombat(e.defaultView);return t};e.open=h,t.open=h;var w=e.close,p=function(){if(r._writeBuff)return r.blobUrlForIframe(r.$wbwindow.frameElement,r._writeBuff),void(r._writeBuff="");var t=r.proxyToObj(this);return r.initNewWindowWombat(t.defaultView),w.__WB_orig_apply?w.__WB_orig_apply(t,arguments):w.apply(t,arguments)};e.close=p,t.close=p;var c=this.getOrigGetter(t,"body"),l=this.getOrigSetter(t,"body");c&&l&&this.defProp(t,"body",(function(t){return t&&(t instanceof HTMLBodyElement||t instanceof HTMLFrameSetElement)&&r.rewriteElemComplete(t),l.call(r.proxyToObj(this),t)}),c)}function _(){return r.wb_info.isSW&&r.$wbwindow.frameElement}function u(t){return 0===t.length?"":1===t.length?t[0]:Array.prototype.join.call(t,"")}function d(t,e,i){r.$wbwindow;if(!_()){i=r.rewriteHtml(i,!0);var o=r.proxyToObj(t),n=e.call(o,i);return r.initNewWindowWombat(o.defaultView),n}r._writeBuff+=i}},f.prototype.initIframeWombat=function(t){var e;e=t._get_contentWindow?t._get_contentWindow.call(t):t.contentWindow;try{if(!e||e===this.$wbwindow||e._skip_wombat||e._wb_wombat)return}catch(t){return}var r=t.src;this.initNewWindowWombat(e,r)},f.prototype.initNewWindowWombat=function(t,e){var r=!1;if(t&&!t._wb_wombat){if(e&&""!==e&&!this.startsWithOneOf(e,["about:blank","javascript:"])||(r=!0),!r&&this.wb_info.isSW){var i=this.extractOriginalURL(e);("about:blank"===i||i.startsWith("srcdoc:")||i.startsWith("blob:"))&&(r=!0)}if(r){var o={};Object.assign(o,this.wb_info);var n=new f(t,o);t._wb_wombat=n.wombatInit()}else this.initProtoPmOrigin(t),this.initPostMessageOverride(t),this.initMessageEventOverride(t),this.initCheckThisFunc(t),this.initImportWrapperFunc(t)}},f.prototype.initTimeoutIntervalOverrides=function(){var t=this.rewriteSetTimeoutInterval;if(this.$wbwindow.setTimeout&&!this.$wbwindow.setTimeout.__$wbpatched$__){var e=this.$wbwindow.setTimeout;this.$wbwindow.setTimeout=function(){return t(this,e,arguments)},this.$wbwindow.setTimeout.__$wbpatched$__=!0}if(this.$wbwindow.setInterval&&!this.$wbwindow.setInterval.__$wbpatched$__){var r=this.$wbwindow.setInterval;this.$wbwindow.setInterval=function(){return t(this,r,arguments)},this.$wbwindow.setInterval.__$wbpatched$__=!0}},f.prototype.initWorkerOverrides=function(){var t,e,r=this;if(this.$wbwindow.Worker&&!this.$wbwindow.Worker._wb_worker_overridden){var i=this.$wbwindow.Worker;this.$wbwindow.Worker=(t=i,function(e,i){return r.domConstructorErrorChecker(this,"Worker",arguments),new t(r.rewriteWorker(e),i)}),this.$wbwindow.Worker.prototype=i.prototype,Object.defineProperty(this.$wbwindow.Worker.prototype,"constructor",{value:this.$wbwindow.Worker}),this.$wbwindow.Worker._wb_worker_overridden=!0}if(this.$wbwindow.SharedWorker&&!this.$wbwindow.SharedWorker.__wb_sharedWorker_overridden){var o=this.$wbwindow.SharedWorker;this.$wbwindow.SharedWorker=(e=o,function(t,i){return r.domConstructorErrorChecker(this,"SharedWorker",arguments),new e(r.rewriteWorker(t),i)}),this.$wbwindow.SharedWorker.prototype=o.prototype,Object.defineProperty(this.$wbwindow.SharedWorker.prototype,"constructor",{value:this.$wbwindow.SharedWorker}),this.$wbwindow.SharedWorker.__wb_sharedWorker_overridden=!0}if(this.$wbwindow.ServiceWorkerContainer&&this.$wbwindow.ServiceWorkerContainer.prototype&&this.$wbwindow.ServiceWorkerContainer.prototype.register){var n=this.$wbwindow.ServiceWorkerContainer.prototype.register;this.$wbwindow.ServiceWorkerContainer.prototype.register=function(t,e){var i=new URL(t,r.$wbwindow.document.baseURI).href,o=r.getPageUnderModifier();return e&&e.scope?e.scope=r.rewriteUrl(e.scope,!1,o):e={scope:r.rewriteUrl("/",!1,o)},n.call(this,r.rewriteUrl(i,!1,"sw_"),e)}}if(this.$wbwindow.Worklet&&this.$wbwindow.Worklet.prototype&&this.$wbwindow.Worklet.prototype.addModule&&!this.$wbwindow.Worklet.__wb_workerlet_overridden){var s=this.$wbwindow.Worklet.prototype.addModule;this.$wbwindow.Worklet.prototype.addModule=function(t,e){var i=r.rewriteUrl(t,!1,"js_");return s.call(this,i,e)},this.$wbwindow.Worklet.__wb_workerlet_overridden=!0}},f.prototype.initLocOverride=function(t,e,r){if(Object.defineProperty)for(var i=0;i=0&&i.splice(n,1)}return i}})}catch(t){console.log(t)}},f.prototype.initHashChange=function(){if(this.$wbwindow.__WB_top_frame){var t=this;this.$wbwindow.addEventListener("message",(function(e){if(e.data&&e.data.from_top){var r=e.data.message;r.wb_type&&"outer_hashchange"===r.wb_type&&t.$wbwindow.location.hash!=r.hash&&(t.$wbwindow.location.hash=r.hash)}})),this.$wbwindow.addEventListener("hashchange",(function(){var e={wb_type:"hashchange",hash:t.$wbwindow.location.hash};t.sendTopMessage(e)}))}},f.prototype.initPostMessageOverride=function(t){if(t.postMessage&&!t.__orig_postMessage){var e=t.postMessage,r=this;t.__orig_postMessage=e;var i=function(i,o,n,s){var a,h,w=r.proxyToObj(this);if(w||((w=t).__WB_source=t),w.__WB_source&&w.__WB_source.WB_wombat_location){var p=w.__WB_source;if(a=p.WB_wombat_location.origin,w.__WB_win_id||(w.__WB_win_id={},w.__WB_counter=0),!p.__WB_id){var c=w.__WB_counter;p.__WB_id=c+p.WB_wombat_location.href,w.__WB_counter+=1}w.__WB_win_id[p.__WB_id]=p,h=p.__WB_id,w.__WB_source=void 0}else a=window.WB_wombat_location.origin;var l=o;l===w.location.origin&&(l=a);var _={from:a,to_origin:l,src_id:h,message:i,from_top:s};if("*"!==o){if("null"===w.location.origin||""===w.location.origin)return;o=w.location.origin}return e.call(w,_,o,n)};t.postMessage=i,t.Window.prototype.postMessage=i;var o=null,n=(o=t.EventTarget&&t.EventTarget.prototype?t.EventTarget.prototype:t).addEventListener;o.addEventListener=function(t,e,i){var o,s=r.proxyToObj(this);if("message"===t?o=r.message_listeners.add_or_get(e,(function(){return c(e,s,r)})):"storage"===t?r.storage_listeners.add_or_get(e,(function(){return p(e,s)})):o=e,o)return n.call(s,t,o,i)};var s=o.removeEventListener;o.removeEventListener=function(t,e,i){var o,n=r.proxyToObj(this);if("message"===t?o=r.message_listeners.remove(e):"storage"===t?r.storage_listeners.remove(e):o=e,o)return s.call(n,t,o,i)};var a=function(e,i){var o=r.getOrigSetter(t,e);r.defProp(t,e,(function(t){this["__orig_"+e]=t;var n=r.proxyToObj(this),s=t?i(t,n,r):t;return o.call(n,s)}),(function(){return this["__orig_"+e]}))};a("onmessage",c),a("onstorage",p)}},f.prototype.initMessageEventOverride=function(t){t.MessageEvent&&!t.MessageEvent.prototype.__extended&&(this.addEventOverride("target"),this.addEventOverride("srcElement"),this.addEventOverride("currentTarget"),this.addEventOverride("eventPhase"),this.addEventOverride("path"),this.overridePropToProxy(t.MessageEvent.prototype,"source"),t.MessageEvent.prototype.__extended=!0)},f.prototype.initUIEventsOverrides=function(){this.overrideAnUIEvent("UIEvent"),this.overrideAnUIEvent("MouseEvent"),this.overrideAnUIEvent("TouchEvent"),this.overrideAnUIEvent("FocusEvent"),this.overrideAnUIEvent("KeyboardEvent"),this.overrideAnUIEvent("WheelEvent"),this.overrideAnUIEvent("InputEvent"),this.overrideAnUIEvent("CompositionEvent")},f.prototype.initOpenOverride=function(){var t=this.$wbwindow.open;this.$wbwindow.Window.prototype.open&&(t=this.$wbwindow.Window.prototype.open);var e=this,r=function(r,i,o){i&&(i=e.rewriteAttrTarget(i));var n=e.rewriteUrl(r,!1),s=t.call(e.proxyToObj(this),n,i,o);return e.initNewWindowWombat(s,r),s};this.$wbwindow.open=r,this.$wbwindow.Window.prototype.open&&(this.$wbwindow.Window.prototype.open=r);for(var i=0;i}\n */\nWBWombat.prototype.rewriteArgs = function(argsObj) {\n // recreate the original arguments object just with URLs rewritten\n var newArgObj = new Array(argsObj.length);\n for (var i = 0; i < newArgObj.length; i++) {\n newArgObj[i] = this.rewriteURL(argsObj[i]);\n }\n return newArgObj;\n};\n\n/**\n * Rewrites the input to one of the Fetch APIs\n * @param {*|string|Request} input\n * @return {*|string|Request}\n */\nWBWombat.prototype.rewriteFetchApi = function(input) {\n var rwInput = input;\n switch (typeof input) {\n case 'string':\n rwInput = this.rewriteURL(input);\n break;\n case 'object':\n if (input.url) {\n var new_url = this.rewriteURL(input.url);\n if (new_url !== input.url) {\n // not much we can do here Request.url is read only\n // https://developer.mozilla.org/en-US/docs/Web/API/Request/url\n rwInput = new Request(new_url, input);\n }\n } else if (input.href) {\n // it is likely that input is either self.location or self.URL\n // we cant do anything here so just let it go\n rwInput = input.href;\n }\n break;\n }\n return rwInput;\n};\n\n/**\n * Rewrites the input to one of the Cache APIs\n * @param {*|string|Request} request\n * @return {*|string|Request}\n */\nWBWombat.prototype.rewriteCacheApi = function(request) {\n var rwRequest = request;\n if (typeof request === 'string') {\n rwRequest = this.rewriteURL(request);\n }\n return rwRequest;\n};\n\n/**\n * Applies an override to the importScripts function\n * @see https://html.spec.whatwg.org/multipage/workers.html#dom-workerglobalscope-importscripts\n */\nWBWombat.prototype.initImportScriptsRewrite = function() {\n if (!self.importScripts) return;\n var wombat = this;\n var origImportScripts = self.importScripts;\n self.importScripts = function importScripts() {\n // rewrite the arguments object and call original function via fn.apply\n var rwArgs = wombat.rewriteArgs(arguments);\n return origImportScripts.apply(this, rwArgs);\n };\n};\n\n/**\n * Applies overrides to the XMLHttpRequest.open and XMLHttpRequest.responseURL\n * in order to ensure URLs are rewritten.\n *\n * Applies an override to window.fetch in order to rewrite URLs and URLs of\n * the supplied Request objects used as arguments to fetch.\n *\n * Applies overrides to window.Request, window.Response, window.EventSource,\n * and window.WebSocket in order to ensure URLs they operate on are rewritten.\n *\n * @see https://xhr.spec.whatwg.org/\n * @see https://fetch.spec.whatwg.org/\n * @see https://html.spec.whatwg.org/multipage/web-sockets.html#websocket\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface\n */\nWBWombat.prototype.initHTTPOverrides = function() {\n var wombat = this;\n if (\n self.XMLHttpRequest &&\n self.XMLHttpRequest.prototype &&\n self.XMLHttpRequest.prototype.open\n ) {\n var oXHROpen = self.XMLHttpRequest.prototype.open;\n self.XMLHttpRequest.prototype.open = function open(\n method,\n url,\n async,\n user,\n password\n ) {\n var rwURL = wombat.rewriteURL(url);\n var openAsync = true;\n if (async != null && !async) openAsync = false;\n oXHROpen.call(this, method, rwURL, openAsync, user, password);\n if (rwURL.indexOf('data:') === -1) {\n this.setRequestHeader('X-Pywb-Requested-With', 'XMLHttpRequest');\n }\n };\n }\n\n if (self.fetch != null) {\n // this fetch is Worker.fetch\n var orig_fetch = self.fetch;\n self.fetch = function fetch(input, init_opts) {\n var rwInput = wombat.rewriteFetchApi(input);\n var newInitOpts = init_opts || {};\n newInitOpts['credentials'] = 'include';\n return orig_fetch.call(this, rwInput, newInitOpts);\n };\n }\n\n if (self.Request && self.Request.prototype) {\n var orig_request = self.Request;\n self.Request = (function(Request_) {\n return function Request(input, init_opts) {\n var newInitOpts = init_opts || {};\n var newInput = wombat.rewriteFetchApi(input);\n newInitOpts['credentials'] = 'include';\n return new Request_(newInput, newInitOpts);\n };\n })(self.Request);\n self.Request.prototype = orig_request.prototype;\n }\n\n if (self.Response && self.Response.prototype) {\n var originalRedirect = self.Response.prototype.redirect;\n self.Response.prototype.redirect = function redirect(url, status) {\n var rwURL = wombat.rewriteUrl(url);\n return originalRedirect.call(this, rwURL, status);\n };\n }\n\n if (self.EventSource && self.EventSource.prototype) {\n var origEventSource = self.EventSource;\n self.EventSource = (function(EventSource_) {\n return function EventSource(url, configuration) {\n var rwURL = url;\n if (url != null) {\n rwURL = wombat.rewriteUrl(url);\n }\n return new EventSource_(rwURL, configuration);\n };\n })(self.EventSource);\n self.EventSource.prototype = origEventSource.prototype;\n Object.defineProperty(self.EventSource.prototype, 'constructor', {\n value: self.EventSource\n });\n }\n\n if (self.WebSocket && self.WebSocket.prototype) {\n var origWebSocket = self.WebSocket;\n self.WebSocket = (function(WebSocket_) {\n return function WebSocket(url, configuration) {\n var rwURL = url;\n if (url != null) {\n rwURL = wombat.rewriteWSURL(url);\n }\n return new WebSocket_(rwURL, configuration);\n };\n })(self.WebSocket);\n self.WebSocket.prototype = origWebSocket.prototype;\n Object.defineProperty(self.WebSocket.prototype, 'constructor', {\n value: self.WebSocket\n });\n }\n};\n\n/**\n * Applies an override to Clients.openWindow and WindowClient.navigate that rewrites\n * the supplied URL that represents a controlled window\n * @see https://w3c.github.io/ServiceWorker/#window-client-interface\n * @see https://w3c.github.io/ServiceWorker/#clients-interface\n */\nWBWombat.prototype.initClientApisOverride = function() {\n var wombat = this;\n if (\n self.Clients &&\n self.Clients.prototype &&\n self.Clients.prototype.openWindow\n ) {\n var oClientsOpenWindow = self.Clients.prototype.openWindow;\n self.Clients.prototype.openWindow = function openWindow(url) {\n var rwURL = wombat.rewriteClientWindowURL(url);\n return oClientsOpenWindow.call(this, rwURL);\n };\n }\n\n if (\n self.WindowClient &&\n self.WindowClient.prototype &&\n self.WindowClient.prototype.navigate\n ) {\n var oWinClientNavigate = self.WindowClient.prototype.navigate;\n self.WindowClient.prototype.navigate = function navigate(url) {\n var rwURL = wombat.rewriteClientWindowURL(url, this);\n return oWinClientNavigate.call(this, rwURL);\n };\n }\n};\n\n/**\n * Applies overrides to the CacheStorage and Cache interfaces in order\n * to rewrite the URLs they operate on\n * @see https://w3c.github.io/ServiceWorker/#cachestorage\n * @see https://w3c.github.io/ServiceWorker/#cache-interface\n */\nWBWombat.prototype.initCacheApisOverride = function() {\n var wombat = this;\n if (\n self.CacheStorage &&\n self.CacheStorage.prototype &&\n self.CacheStorage.prototype.match\n ) {\n var oCacheStorageMatch = self.CacheStorage.prototype.match;\n self.CacheStorage.prototype.match = function match(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheStorageMatch.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache && self.Cache.prototype) {\n if (self.Cache.prototype.match) {\n var oCacheMatch = self.Cache.prototype.match;\n self.Cache.prototype.match = function match(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheMatch.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache.prototype.matchAll) {\n var oCacheMatchAll = self.Cache.prototype.matchAll;\n self.Cache.prototype.matchAll = function matchAll(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheMatchAll.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache.prototype.add) {\n var oCacheAdd = self.Cache.prototype.add;\n self.Cache.prototype.add = function add(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheAdd.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache.prototype.addAll) {\n var oCacheAddAll = self.Cache.prototype.addAll;\n self.Cache.prototype.addAll = function addAll(requests) {\n var rwRequests = requests;\n if (Array.isArray(requests)) {\n rwRequests = new Array(requests.length);\n for (var i = 0; i < requests.length; i++) {\n rwRequests[i] = wombat.rewriteCacheApi(requests[i]);\n }\n }\n return oCacheAddAll.call(this, rwRequests);\n };\n }\n\n if (self.Cache.prototype.put) {\n var oCachePut = self.Cache.prototype.put;\n self.Cache.prototype.put = function put(request, response) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCachePut.call(this, rwRequest, response);\n };\n }\n\n if (self.Cache.prototype.delete) {\n var oCacheDelete = self.Cache.prototype.delete;\n self.Cache.prototype.delete = function newCacheDelete(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheDelete.call(this, rwRequest, options);\n };\n }\n\n if (self.Cache.prototype.keys) {\n var oCacheKeys = self.Cache.prototype.keys;\n self.Cache.prototype.keys = function keys(request, options) {\n var rwRequest = wombat.rewriteCacheApi(request);\n return oCacheKeys.call(this, rwRequest, options);\n };\n }\n }\n};\n\nself.WBWombat = WBWombat;\n"}),r.injectScripts&&(r.injectScripts=r.injectScripts.map((t=>this.staticPrefix+"proxy/"+t))),this.collections=new i(o,n.get("root"),r),this.collections.loadAll(n.get("dbColl")),this.proxyOriginMode=!!n.get("proxyOriginMode"),this.api=new e(this.collections),this.apiPrefix=this.replayPrefix+"api/",this.allowRewrittenCache=!!n.get("allowCache"),this.stats=n.get("stats")?new Yy:null,self.addEventListener("install",(()=>{self.skipWaiting()})),self.addEventListener("activate",(t=>{t.waitUntil(self.clients.claim()),console.log("Activate!")})),self.addEventListener("fetch",(t=>{t.respondWith(this.handleFetch(t))})),self.addEventListener("message",(t=>{"reload_all"===t.data.msg_type&&t.waitUntil(this.collections.loadAll())}))}handleFetch(t){const e=t.request.url;if(this.proxyOriginMode)return this.getResponseFor(t.request,t);if(!e.startsWith(this.prefix))return"chrome-extension://invalid/"===e?S(t.request,"Invalid URL"):this.defaultFetch(t.request);if(this.collections.root&&e.slice(this.prefix.length).indexOf("/")<0)return this.defaultFetch(t.request);if(e.startsWith(this.staticPrefix+"proxy/"))return this.staticPathProxy(e,t.request);if(e.startsWith(this.replayPrefix)&&!e.startsWith(this.staticPrefix))return this.getResponseFor(t.request,t);const r=new URL(e);r.search="",r.hash="";const i=r.href;for(const t of this.staticData.keys())if(t===i){const{content:e,type:r}=this.staticData.get(t);return new Response(e,{headers:{"Content-Type":r}})}return("http:"==r.protocol||"https:"==r.protocol)&&r.pathname.indexOf("/",1)<0?this.handleOffline(t.request):this.defaultFetch(t.request)}staticPathProxy(t,e){return t=t.slice((this.staticPrefix+"proxy/").length),t=new URL(t,self.location.href).href,e=new Request(t),this.defaultFetch(e)}defaultFetch(t){const e={};return"only-if-cached"===t.cache&&"same-origin"!==t.mode&&(e.cache="default"),self.fetch(t,e)}async ensureCached(t){const e=await caches.open("wabac-offline");for(let r of t){r=new URL(r,self.location.href).href;let t=await e.match(r,{ignoreSearch:!0});if(!t)try{t=await this.defaultFetch(r),await e.put(r,t)}catch(t){console.warn(`Failed to Auto Cache: ${r}`,t)}}}async handleOffline(t){let e=null;const r=await caches.open("wabac-offline");try{e=await this.defaultFetch(t)}catch(i){return e=await r.match(t,{ignoreSearch:!0}),e||(e=S(t,"Sorry, this url was not cached for offline use")),e}if(t.url.startsWith(this.prefix+"?"))return e;if(200===e.status){const i=e.clone();await r.put(t,i)}else console.warn(`Not Cacheing ${t.url} - Status ${e.status}`);return e}async getResponseFor(t,e){if(!this.proxyOriginMode&&t.url.startsWith(this.apiPrefix))return this.stats&&t.url.startsWith(this.apiPrefix+"stats.json")?await this.stats.getStats(e):await this.api.apiResponse(t.url.slice(this.apiPrefix.length),t,e);await this.collections.inited;const r=v(t),i=t.headers.get("range");try{if(this.allowRewrittenCache&&!i){const e=await self.caches.match(t);if(e&&!!e.headers.get(bm)===r)return e}}catch(t){}let n=this.collections.root;n||(n=t.url.slice(this.replayPrefix.length).split("/",1)[0]);const s=await this.collections.getColl(n);if(!s||!this.proxyOriginMode&&!t.url.startsWith(s.prefix))return S(t);const o=this.proxyOriginMode?t.url:t.url.substring(s.prefix.length),a={isRoot:!!this.collections.root};this.proxyOriginMode&&(a.mod="id_",a.proxyOrigin=s.config.extraConfig.proxyOrigin,a.localOrigin=self.location.origin);const c=new mm(o,t,a);if(!c.url)return S(t,`Replay URL ${o} not found`);const l=await s.handleRequest(c,e);if(l){if(this.stats&&this.stats.updateStats(l.date,l.status,t,e),this.allowRewrittenCache&&200===l.status)try{const e=await self.caches.open("wabac-"+s.name);r&&l.headers.set(bm,"true");const i=l.clone();await e.put(t,i)}catch(t){console.warn(t)}return l}return i&&console.log("Not Found Range!: "+i),S(t)}}if(self.registration){const t=new Map,r=self.registration.scope;t.set(r,{type:"text/html",content:e}),t.set(r+"index.html",{type:"text/html",content:e});const i={injectScripts:["ruffle/ruffle.js"]};self.ipfsCustomPreload=!0,self.sw=new Em({staticData:t,defaultConfig:i})}else new Ky(self)})();var n=self;for(var s in i)n[s]=i[s];i.__esModule&&Object.defineProperty(n,"__esModule",{value:!0})})(); \ No newline at end of file diff --git a/ui.js b/ui.js index aab3f8b7..95cb1115 100644 --- a/ui.js +++ b/ui.js @@ -48,7 +48,7 @@ class oe extends re{constructor(e){if(super(e),this.it=R,e.type!==ie)throw Error * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ -class se extends oe{}se.directiveName="unsafeSVG",se.resultType=2;const le=ae(se),ce=ae(class extends re{constructor(e){var t;if(super(e),e.type!==te||"style"!==e.name||(null===(t=e.strings)||void 0===t?void 0:t.length)>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce(((t,i)=>{const a=e[i];return null==a?t:t+`${i=i.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,"-$&").toLowerCase()}:${a};`}),"")}update(e,[t]){const{style:i}=e.element;if(void 0===this.ct){this.ct=new Set;for(const e in t)this.ct.add(e);return this.render(t)}this.ct.forEach((e=>{null==t[e]&&(this.ct.delete(e),e.includes("-")?i.removeProperty(e):i[e]="")}));for(const e in t){const a=t[e];null!=a&&(this.ct.add(e),e.includes("-")?i.setProperty(e,a):i[e]=a)}return U}});var de=__webpack_require__(6274),he=__webpack_require__(3029),fe=__webpack_require__.n(he);const be=r(de.Z);function ue(e){return[be,e]}const pe=window.IS_APP||window.electron&&window.electron.IS_APP||window.matchMedia("(display-mode: standalone)").matches,me="1.8.1";function ge(e){" "==e.key&&(e.preventDefault(),e.target.click())}class ve extends X{constructor(){super(),this.size="1.1em",this.width=null,this.height=null}static get properties(){return{svg:{type:String},size:{type:String},width:{type:String},height:{type:String}}}static get styles(){return o` +class se extends oe{}se.directiveName="unsafeSVG",se.resultType=2;const le=ae(se),ce=ae(class extends re{constructor(e){var t;if(super(e),e.type!==te||"style"!==e.name||(null===(t=e.strings)||void 0===t?void 0:t.length)>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce(((t,i)=>{const a=e[i];return null==a?t:t+`${i=i.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,"-$&").toLowerCase()}:${a};`}),"")}update(e,[t]){const{style:i}=e.element;if(void 0===this.ct){this.ct=new Set;for(const e in t)this.ct.add(e);return this.render(t)}this.ct.forEach((e=>{null==t[e]&&(this.ct.delete(e),e.includes("-")?i.removeProperty(e):i[e]="")}));for(const e in t){const a=t[e];null!=a&&(this.ct.add(e),e.includes("-")?i.setProperty(e,a):i[e]=a)}return U}});var de=__webpack_require__(6274),he=__webpack_require__(3029),fe=__webpack_require__.n(he);const be=r(de.Z);function ue(e){return[be,e]}const pe=window.IS_APP||window.electron&&window.electron.IS_APP||window.matchMedia("(display-mode: standalone)").matches,me="1.8.2";function ge(e){" "==e.key&&(e.preventDefault(),e.target.click())}class ve extends X{constructor(){super(),this.size="1.1em",this.width=null,this.height=null}static get properties(){return{svg:{type:String},size:{type:String},width:{type:String},height:{type:String}}}static get styles(){return o` :host { display: inline-block; padding: 0; @@ -716,7 +716,7 @@ class se extends oe{}se.directiveName="unsafeSVG",se.resultType=2;const le=ae(se

Collection id

${e.coll} - `}render(){return this.detailed?this.renderDetailed():this.renderSummaryView()}onCopy(e,t){return e.preventDefault(),e.stopPropagation(),navigator.clipboard.writeText(t),!1}onPurge(e){const t={reload:e};this.dispatchEvent(new CustomEvent("coll-purge",{detail:t}))}}function Ke(e){if(!e)return"";e.length<14&&(e+="00000101000000".substr(e.length));const t=e.substring(0,4)+"-"+e.substring(4,6)+"-"+e.substring(6,8)+"T"+e.substring(8,10)+":"+e.substring(10,12)+":"+e.substring(12,14)+"-00:00";return new Date(t)}function Ve(e){let t=null;try{t=new Date(e.ts||e.date)}catch(e){}const i=t&&!isNaN(t)?Ze(t.toISOString()):"";return{date:t,timestamp:i}}function Ze(e){return e.replace(/[-:T]/g,"").slice(0,14)}function Qe(e,t,i){const a=new URLSearchParams;return a.set("view",e),a.set("url",t),a.set("ts",i),"#"+a.toString()}async function Je(e){try{new URL(e)}catch(t){e=new URL(e,window.location.href).href}const t=await async function(e,t){const i=(new TextEncoder).encode(e),a=await crypto.subtle.digest(t,i),r=Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("");return r}(e,"SHA-256");return{url:e,coll:"id-"+t.slice(0,12)}}customElements.define("wr-coll-info",Ge),customElements.define("wr-coll-index",We);var Ye=__webpack_require__(5056),Xe=__webpack_require__.n(Ye),et=__webpack_require__(5732),tt=__webpack_require__.n(et),it=__webpack_require__(8561),at=__webpack_require__.n(it),rt=__webpack_require__(9885),ot=__webpack_require__.n(rt),nt=__webpack_require__(4636),st=__webpack_require__.n(nt),lt=__webpack_require__(1615),ct=__webpack_require__.n(lt),dt=__webpack_require__(2302),ht=__webpack_require__.n(dt),ft=__webpack_require__(6368),bt=__webpack_require__.n(ft),ut=__webpack_require__(9125),pt=__webpack_require__.n(ut),mt=__webpack_require__(9998),gt=__webpack_require__.n(mt),vt=__webpack_require__(2164),wt=__webpack_require__.n(vt),xt=__webpack_require__(426),kt=__webpack_require__.n(xt),yt=__webpack_require__(430),_t=__webpack_require__.n(yt),$t=__webpack_require__(1795),St=__webpack_require__.n($t),zt=__webpack_require__(7529),At=__webpack_require__.n(zt),Ct=__webpack_require__(6873),Dt=__webpack_require__.n(Ct),Et=__webpack_require__(4575),It=__webpack_require__.n(Et);class Pt extends X{constructor(){super(),this.collInfo=null,this.appLogo=null,this.ts=null,this.url=null,this.active=!1}get renderRoot(){return this}static get properties(){return{collInfo:{type:Object},appLogo:{type:Object},url:{type:String},ts:{type:String},active:{type:Boolean}}}static get embedStyles(){return o` + `}render(){return this.detailed?this.renderDetailed():this.renderSummaryView()}onCopy(e,t){return e.preventDefault(),e.stopPropagation(),navigator.clipboard.writeText(t),!1}onPurge(e){const t={reload:e};this.dispatchEvent(new CustomEvent("coll-purge",{detail:t}))}}function Ke(e){if(!e)return"";e.length<14&&(e+="00000101000000".substr(e.length));const t=e.substring(0,4)+"-"+e.substring(4,6)+"-"+e.substring(6,8)+"T"+e.substring(8,10)+":"+e.substring(10,12)+":"+e.substring(12,14)+"-00:00";return new Date(t)}function Ve(e){let t=null;try{t=new Date(e.ts||e.date)}catch(e){}const i=t&&!isNaN(t)?Ze(t.toISOString()):"";return{date:t,timestamp:i}}function Ze(e){return e.replace(/[-:T]/g,"").slice(0,14)}function Qe(e,t,i){const a=new URLSearchParams;return a.set("view",e),a.set("url",t),a.set("ts",i),"#"+a.toString()}async function Je(e){try{new URL(e)}catch(t){e=new URL(e,document.baseURI).href}const t=await async function(e,t){const i=(new TextEncoder).encode(e),a=await crypto.subtle.digest(t,i),r=Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("");return r}(e,"SHA-256");return{url:e,coll:"id-"+t.slice(0,12)}}customElements.define("wr-coll-info",Ge),customElements.define("wr-coll-index",We);var Ye=__webpack_require__(5056),Xe=__webpack_require__.n(Ye),et=__webpack_require__(5732),tt=__webpack_require__.n(et),it=__webpack_require__(8561),at=__webpack_require__.n(it),rt=__webpack_require__(9885),ot=__webpack_require__.n(rt),nt=__webpack_require__(4636),st=__webpack_require__.n(nt),lt=__webpack_require__(1615),ct=__webpack_require__.n(lt),dt=__webpack_require__(2302),ht=__webpack_require__.n(dt),ft=__webpack_require__(6368),bt=__webpack_require__.n(ft),ut=__webpack_require__(9125),pt=__webpack_require__.n(ut),mt=__webpack_require__(9998),gt=__webpack_require__.n(mt),vt=__webpack_require__(2164),wt=__webpack_require__.n(vt),xt=__webpack_require__(426),kt=__webpack_require__.n(xt),yt=__webpack_require__(430),_t=__webpack_require__.n(yt),$t=__webpack_require__(1795),St=__webpack_require__.n($t),zt=__webpack_require__(7529),At=__webpack_require__.n(zt),Ct=__webpack_require__(6873),Dt=__webpack_require__.n(Ct),Et=__webpack_require__(4575),It=__webpack_require__.n(Et);class Pt extends X{constructor(){super(),this.collInfo=null,this.appLogo=null,this.ts=null,this.url=null,this.active=!1}get renderRoot(){return this}static get properties(){return{collInfo:{type:Object},appLogo:{type:Object},url:{type:String},ts:{type:String},active:{type:Boolean}}}static get embedStyles(){return o` rwp-embed-receipt { display: flex; flex-direction: column; @@ -929,7 +929,7 @@ class se extends oe{}se.directiveName="unsafeSVG",se.resultType=2;const le=ae(se - `}onEmbedDrop(e){e.stopPropagation(),this.active=!this.active}}customElements.define("rwp-embed-receipt",Pt);var Lt="undefined"!=typeof window?window:null,Tt=null===Lt,Ut=Tt?void 0:Lt.document,Rt="horizontal",qt=function(){return!1},Mt=Tt?"calc":["","-webkit-","-moz-","-o-"].filter((function(e){var t=Ut.createElement("div");return t.style.cssText="width:"+e+"calc(9px)",!!t.style.length})).shift()+"calc",Ft=function(e){return"string"==typeof e||e instanceof String},jt=function(e){if(Ft(e)){var t=Ut.querySelector(e);if(!t)throw new Error("Selector "+e+" did not match a DOM element");return t}return e},Nt=function(e,t,i){var a=e[t];return void 0!==a?a:i},Ot=function(e,t,i,a){if(t){if("end"===a)return 0;if("center"===a)return e/2}else if(i){if("start"===a)return 0;if("center"===a)return e/2}return e},Bt=function(e,t){var i=Ut.createElement("div");return i.className="gutter gutter-"+t,i},Ht=function(e,t,i){var a={};return Ft(t)?a[e]=t:a[e]=Mt+"("+t+"% - "+i+"px)",a},Wt=function(e,t){var i;return(i={})[e]=t+"px",i};const Gt=function(e,t){if(void 0===t&&(t={}),Tt)return{};var i,a,r,o,n,s,l=e;Array.from&&(l=Array.from(l));var c=jt(l[0]).parentNode,d=getComputedStyle?getComputedStyle(c):null,h=d?d.flexDirection:null,f=Nt(t,"sizes")||l.map((function(){return 100/l.length})),b=Nt(t,"minSize",100),u=Array.isArray(b)?b:l.map((function(){return b})),p=Nt(t,"maxSize",1/0),m=Array.isArray(p)?p:l.map((function(){return p})),g=Nt(t,"expandToMin",!1),v=Nt(t,"gutterSize",10),w=Nt(t,"gutterAlign","center"),x=Nt(t,"snapOffset",30),k=Nt(t,"dragInterval",1),y=Nt(t,"direction",Rt),_=Nt(t,"cursor",y===Rt?"col-resize":"row-resize"),$=Nt(t,"gutter",Bt),S=Nt(t,"elementStyle",Ht),z=Nt(t,"gutterStyle",Wt);function A(e,t,a,r){var o=S(i,t,a,r);Object.keys(o).forEach((function(t){e.style[t]=o[t]}))}function C(){return s.map((function(e){return e.size}))}function D(e){return"touches"in e?e.touches[0][a]:e[a]}function E(e){var t=s[this.a],i=s[this.b],a=t.size+i.size;t.size=e/this.size*a,i.size=a-e/this.size*a,A(t.element,t.size,this._b,t.i),A(i.element,i.size,this._c,i.i)}function I(e){var i,a=s[this.a],r=s[this.b];this.dragging&&(i=D(e)-this.start+(this._b-this.dragOffset),k>1&&(i=Math.round(i/k)*k),i<=a.minSize+x+this._b?i=a.minSize+this._b:i>=this.size-(r.minSize+x+this._c)&&(i=this.size-(r.minSize+this._c)),i>=a.maxSize-x+this._b?i=a.maxSize+this._b:i<=this.size-(r.maxSize-x+this._c)&&(i=this.size-(r.maxSize+this._c)),E.call(this,i),Nt(t,"onDrag",qt)(C()))}function P(){var e=s[this.a].element,t=s[this.b].element,a=e.getBoundingClientRect(),n=t.getBoundingClientRect();this.size=a[i]+n[i]+this._b+this._c,this.start=a[r],this.end=a[o]}function L(e){var t=function(e){if(!getComputedStyle)return null;var t=getComputedStyle(e);if(!t)return null;var i=e[n];return 0===i?null:i-=y===Rt?parseFloat(t.paddingLeft)+parseFloat(t.paddingRight):parseFloat(t.paddingTop)+parseFloat(t.paddingBottom)}(c);if(null===t)return e;if(u.reduce((function(e,t){return e+t}),0)>t)return e;var i=0,a=[],r=e.map((function(r,o){var n=t*r/100,s=Ot(v,0===o,o===e.length-1,w),l=u[o]+s;return n0&&a[r]-i>0){var n=Math.min(i,a[r]-i);i-=n,o=e-n}return o/t*100}))}function T(){var e=this,i=s[e.a].element,a=s[e.b].element;e.dragging&&Nt(t,"onDragEnd",qt)(C()),e.dragging=!1,Lt.removeEventListener("mouseup",e.stop),Lt.removeEventListener("touchend",e.stop),Lt.removeEventListener("touchcancel",e.stop),Lt.removeEventListener("mousemove",e.move),Lt.removeEventListener("touchmove",e.move),e.stop=null,e.move=null,i.removeEventListener("selectstart",qt),i.removeEventListener("dragstart",qt),a.removeEventListener("selectstart",qt),a.removeEventListener("dragstart",qt),i.style.userSelect="",i.style.webkitUserSelect="",i.style.MozUserSelect="",i.style.pointerEvents="",a.style.userSelect="",a.style.webkitUserSelect="",a.style.MozUserSelect="",a.style.pointerEvents="",e.gutter.style.cursor="",e.parent.style.cursor="",Ut.body.style.cursor=""}function U(e){if(!("button"in e)||0===e.button){var i=this,a=s[i.a].element,r=s[i.b].element;i.dragging||Nt(t,"onDragStart",qt)(C()),e.preventDefault(),i.dragging=!0,i.move=I.bind(i),i.stop=T.bind(i),Lt.addEventListener("mouseup",i.stop),Lt.addEventListener("touchend",i.stop),Lt.addEventListener("touchcancel",i.stop),Lt.addEventListener("mousemove",i.move),Lt.addEventListener("touchmove",i.move),a.addEventListener("selectstart",qt),a.addEventListener("dragstart",qt),r.addEventListener("selectstart",qt),r.addEventListener("dragstart",qt),a.style.userSelect="none",a.style.webkitUserSelect="none",a.style.MozUserSelect="none",a.style.pointerEvents="none",r.style.userSelect="none",r.style.webkitUserSelect="none",r.style.MozUserSelect="none",r.style.pointerEvents="none",i.gutter.style.cursor=_,i.parent.style.cursor=_,Ut.body.style.cursor=_,P.call(i),i.dragOffset=D(e)-i.end}}y===Rt?(i="width",a="clientX",r="left",o="right",n="clientWidth"):"vertical"===y&&(i="height",a="clientY",r="top",o="bottom",n="clientHeight"),f=L(f);var R=[];function q(e){var t=e.i===R.length,i=t?R[e.i-1]:R[e.i];P.call(i);var a=t?i.size-e.minSize-i._c:e.minSize+i._b;E.call(i,a)}return s=l.map((function(e,t){var a,r={element:jt(e),size:f[t],minSize:u[t],maxSize:m[t],i:t};if(t>0&&((a={a:t-1,b:t,dragging:!1,direction:y,parent:c})._b=Ot(v,t-1==0,!1,w),a._c=Ot(v,!1,t===l.length-1,w),"row-reverse"===h||"column-reverse"===h)){var o=a.a;a.a=a.b,a.b=o}if(t>0){var n=$(t,y,r.element);!function(e,t,a){var r=z(i,t,a);Object.keys(r).forEach((function(t){e.style[t]=r[t]}))}(n,v,t),a._a=U.bind(a),n.addEventListener("mousedown",a._a),n.addEventListener("touchstart",a._a),c.insertBefore(n,r.element),a.gutter=n}return A(r.element,r.size,Ot(v,0===t,t===l.length-1,w),t),t>0&&R.push(a),r})),s.forEach((function(e){var t=e.element.getBoundingClientRect()[i];t0){var a=R[i-1],r=s[a.a],o=s[a.b];r.size=t[i-1],o.size=e,A(r.element,r.size,a._b,r.i),A(o.element,o.size,a._c,o.i)}}))},getSizes:C,collapse:function(e){q(s[e])},destroy:function(e,t){R.forEach((function(a){if(!0!==t?a.parent.removeChild(a.gutter):(a.gutter.removeEventListener("mousedown",a._a),a.gutter.removeEventListener("touchstart",a._a)),!0!==e){var r=S(i,a.a.size,a._b);Object.keys(r).forEach((function(e){s[a.a].element.style[e]="",s[a.b].element.style[e]=""}))}}))},parent:c,pairs:R}},Kt="search://";class Vt extends X{constructor(){super(),this.sourceUrl=null,this.inited=!1,this.isLoading=!1,this.coll="",this.collInfo=null,this._replaceLoc=!1,this._locUpdateNeeded=!1,this._locationHash="",this.tabData={},this.url="",this.ts="",this.tabNames=["pages","story","resources","info"],this.tabLabels={pages:"Pages",story:"Story",resources:"URLs",info:"Archive Info"},this.menuActive=!1,this.embedDropdownActive=!1,this.hasStory=!1,this.editable=!1,this.browsable=!0,this.clearable=!0,this.showSidebar="1"===localStorage.getItem("pages:showSidebar"),this.splitter=null,this.isVisible=!0,this.favIconUrl="",this.autoUpdateInterval=10,this._autoUpdater=null,this.appName="ReplayWeb.page",this.appVersion=me,this.appLogo=fe()}static get properties(){return{inited:{type:Boolean},sourceUrl:{type:String},loadInfo:{type:Object,attribute:!1},showSidebar:{type:Boolean},collInfo:{type:Object,attribute:!1},coll:{type:String},hasStory:{type:Boolean},isLoading:{type:Boolean},tabData:{type:Object,attribute:!1},url:{type:String},ts:{type:String},isFullscreen:{type:Boolean},menuActive:{type:Boolean},embed:{type:String},embedDropdownActive:{type:Boolean},editable:{type:Boolean},browsable:{type:Boolean},clearable:{type:Boolean},isVisible:{type:Boolean},favIconUrl:{type:String},appName:{type:String},appVersion:{type:String},appLogo:{type:String},autoUpdateInterval:{type:Number},swName:{type:String}}}firstUpdated(){this.inited=!0,window.addEventListener("hashchange",(e=>this.onHashChange(e))),this.addEventListener("fullscreenchange",(()=>{this.isFullscreen=!!document.fullscreenElement})),this.embed&&this.loadInfo&&this.loadInfo.hideOffscreen&&(this.observer=new IntersectionObserver((e=>{this.isVisible=e[0].isIntersecting})),this.observer.observe(this))}async runUpdateLoop(){try{for(;this.editable&&this.autoUpdateInterval&&(!this.collInfo||this.collInfo.pages.length<100);)await new Promise((e=>setTimeout(e,1e3*this.autoUpdateInterval))),await this.doUpdateInfo(!0)}finally{this._autoUpdater=null}}updated(e){if(e.has("sourceUrl")&&this.doUpdateInfo(),e.has("editable")&&this.editable&&this.autoUpdateInterval&&!this._autoUpdater&&(this._autoUpdater=this.runUpdateLoop()),e.has("tabData")){if(!this.collInfo||!this.collInfo.coll)return;Object.keys(this.tabData).forEach((e=>!this.tabData[e]&&delete this.tabData[e]));const t="#"+new URLSearchParams(this.tabData).toString();if(this.tabData.url||(this.url=Kt+decodeURIComponent(this._paramsToString(this.tabData))),t!==this._locationHash){if(this._locationHash=t,this._replaceLoc||0===Object.keys(e.get("tabData")).length){const e=new URL(window.location.href);e.hash=this._locationHash,window.history.replaceState({},"",e.href),this._replaceLoc=!1}else if(window.location.hash=this._locationHash,!this.showSidebar){const e=this.renderRoot.querySelector("wr-coll-replay");e&&e.focus()}this.embed&&window.parent!==window&&window.parent.postMessage(this.tabData,"*")}this._locUpdateNeeded=!1}e.has("showSidebar")&&(this.embed||localStorage.setItem("pages:showSidebar",this.showSidebar?"1":"0")),(e.has("tabData")||e.has("showSidebar"))&&this.configureSplitter()}configureSplitter(){if(this.tabData.url&&this.showSidebar){const e=this.renderRoot.querySelector("#contents"),t=this.renderRoot.querySelector("wr-coll-replay");if(e&&t&&!this.splitter){const i={sizes:[30,70],minSize:[300,300],gutterSize:4,onDragStart(){t.setDisablePointer(!0)},onDragEnd(){t.setDisablePointer(!1)}};this.splitter=Gt([e,t],i)}}else if(this.splitter){try{this.splitter.destroy()}catch(e){}this.splitter=null}}async doUpdateInfo(e=!1){if(e&&this.tabData.url&&!this.showSidebar)return;let t=this.loadInfo&&this.loadInfo.customColl;if(!t){t=(await Je(this.sourceUrl)).coll}this.coll=t;const i="./w/api/c/"+t,a="./w/"+t,r=await fetch(i+"?all=1");if(200!=r.status)return void(this.collInfo={});const o=await r.json();if(this.collInfo={apiPrefix:i,replayPrefix:a,coll:t,...o},this.loadInfo&&this.loadInfo.extraConfig&&this.loadInfo.extraConfig.headers){const e=this.loadInfo.extraConfig.headers;await fetch(`${i}/updateAuth`,{method:"POST",body:JSON.stringify({headers:e})})}this.collInfo.title||(this.collInfo.title=this.collInfo.filename),"replayonly"!==this.embed&&"replay-with-info"!==this.embed||(this.showSidebar=!1),this.hasStory=this.collInfo.desc||this.collInfo.lists.length,this.dispatchEvent(new CustomEvent("coll-loaded",{detail:{collInfo:this.collInfo,alreadyLoaded:!0}})),this.onHashChange()}onCollLoaded(e){this.doUpdateInfo(),this.loadInfo=null,e.detail.sourceUrl&&(this.sourceUrl=e.detail.sourceUrl),this.dispatchEvent(new CustomEvent("coll-loaded",{detail:{sourceUrl:this.sourceUrl,collInfo:this.collInfo}}))}onCollUpdate(e){this.editable&&(this.collInfo={...this.collInfo,...e.detail})}onHashChange(){const e=window.location.hash;if(e&&e!==this._locationHash&&(this.tabData=Object.fromEntries(new URLSearchParams(e.slice(1)).entries()),this._locationHash=e),this.collInfo.coll&&!this.tabNames.includes(this.tabData.view)){const e=this.hasStory?"story":this.editable||this.collInfo.pages.length?"pages":"resources";this.tabData={...this.tabData,view:e}}if(this.tabData.url&&this.tabData.url.startsWith("page:")){const e=Number(this.tabData.url.slice("page:".length));if(!isNaN(e)&&e1&&(i=Math.round(i/k)*k),i<=a.minSize+x+this._b?i=a.minSize+this._b:i>=this.size-(r.minSize+x+this._c)&&(i=this.size-(r.minSize+this._c)),i>=a.maxSize-x+this._b?i=a.maxSize+this._b:i<=this.size-(r.maxSize-x+this._c)&&(i=this.size-(r.maxSize+this._c)),E.call(this,i),Nt(t,"onDrag",qt)(C()))}function P(){var e=s[this.a].element,t=s[this.b].element,a=e.getBoundingClientRect(),n=t.getBoundingClientRect();this.size=a[i]+n[i]+this._b+this._c,this.start=a[r],this.end=a[o]}function L(e){var t=function(e){if(!getComputedStyle)return null;var t=getComputedStyle(e);if(!t)return null;var i=e[n];return 0===i?null:i-=y===Rt?parseFloat(t.paddingLeft)+parseFloat(t.paddingRight):parseFloat(t.paddingTop)+parseFloat(t.paddingBottom)}(c);if(null===t)return e;if(u.reduce((function(e,t){return e+t}),0)>t)return e;var i=0,a=[],r=e.map((function(r,o){var n=t*r/100,s=Ot(v,0===o,o===e.length-1,w),l=u[o]+s;return n0&&a[r]-i>0){var n=Math.min(i,a[r]-i);i-=n,o=e-n}return o/t*100}))}function T(){var e=this,i=s[e.a].element,a=s[e.b].element;e.dragging&&Nt(t,"onDragEnd",qt)(C()),e.dragging=!1,Lt.removeEventListener("mouseup",e.stop),Lt.removeEventListener("touchend",e.stop),Lt.removeEventListener("touchcancel",e.stop),Lt.removeEventListener("mousemove",e.move),Lt.removeEventListener("touchmove",e.move),e.stop=null,e.move=null,i.removeEventListener("selectstart",qt),i.removeEventListener("dragstart",qt),a.removeEventListener("selectstart",qt),a.removeEventListener("dragstart",qt),i.style.userSelect="",i.style.webkitUserSelect="",i.style.MozUserSelect="",i.style.pointerEvents="",a.style.userSelect="",a.style.webkitUserSelect="",a.style.MozUserSelect="",a.style.pointerEvents="",e.gutter.style.cursor="",e.parent.style.cursor="",Ut.body.style.cursor=""}function U(e){if(!("button"in e)||0===e.button){var i=this,a=s[i.a].element,r=s[i.b].element;i.dragging||Nt(t,"onDragStart",qt)(C()),e.preventDefault(),i.dragging=!0,i.move=I.bind(i),i.stop=T.bind(i),Lt.addEventListener("mouseup",i.stop),Lt.addEventListener("touchend",i.stop),Lt.addEventListener("touchcancel",i.stop),Lt.addEventListener("mousemove",i.move),Lt.addEventListener("touchmove",i.move),a.addEventListener("selectstart",qt),a.addEventListener("dragstart",qt),r.addEventListener("selectstart",qt),r.addEventListener("dragstart",qt),a.style.userSelect="none",a.style.webkitUserSelect="none",a.style.MozUserSelect="none",a.style.pointerEvents="none",r.style.userSelect="none",r.style.webkitUserSelect="none",r.style.MozUserSelect="none",r.style.pointerEvents="none",i.gutter.style.cursor=_,i.parent.style.cursor=_,Ut.body.style.cursor=_,P.call(i),i.dragOffset=D(e)-i.end}}y===Rt?(i="width",a="clientX",r="left",o="right",n="clientWidth"):"vertical"===y&&(i="height",a="clientY",r="top",o="bottom",n="clientHeight"),f=L(f);var R=[];function q(e){var t=e.i===R.length,i=t?R[e.i-1]:R[e.i];P.call(i);var a=t?i.size-e.minSize-i._c:e.minSize+i._b;E.call(i,a)}return s=l.map((function(e,t){var a,r={element:jt(e),size:f[t],minSize:u[t],maxSize:m[t],i:t};if(t>0&&((a={a:t-1,b:t,dragging:!1,direction:y,parent:c})._b=Ot(v,t-1==0,!1,w),a._c=Ot(v,!1,t===l.length-1,w),"row-reverse"===h||"column-reverse"===h)){var o=a.a;a.a=a.b,a.b=o}if(t>0){var n=$(t,y,r.element);!function(e,t,a){var r=z(i,t,a);Object.keys(r).forEach((function(t){e.style[t]=r[t]}))}(n,v,t),a._a=U.bind(a),n.addEventListener("mousedown",a._a),n.addEventListener("touchstart",a._a),c.insertBefore(n,r.element),a.gutter=n}return A(r.element,r.size,Ot(v,0===t,t===l.length-1,w),t),t>0&&R.push(a),r})),s.forEach((function(e){var t=e.element.getBoundingClientRect()[i];t0){var a=R[i-1],r=s[a.a],o=s[a.b];r.size=t[i-1],o.size=e,A(r.element,r.size,a._b,r.i),A(o.element,o.size,a._c,o.i)}}))},getSizes:C,collapse:function(e){q(s[e])},destroy:function(e,t){R.forEach((function(a){if(!0!==t?a.parent.removeChild(a.gutter):(a.gutter.removeEventListener("mousedown",a._a),a.gutter.removeEventListener("touchstart",a._a)),!0!==e){var r=S(i,a.a.size,a._b);Object.keys(r).forEach((function(e){s[a.a].element.style[e]="",s[a.b].element.style[e]=""}))}}))},parent:c,pairs:R}},Kt="search://";class Vt extends X{constructor(){super(),this.sourceUrl=null,this.inited=!1,this.isLoading=!1,this.coll="",this.collInfo=null,this._replaceLoc=!1,this._locUpdateNeeded=!1,this._locationHash="",this.tabData={},this.url="",this.ts="",this.tabNames=["pages","story","resources","info"],this.tabLabels={pages:"Pages",story:"Story",resources:"URLs",info:"Archive Info"},this.menuActive=!1,this.embedDropdownActive=!1,this.hasStory=!1,this.editable=!1,this.browsable=!0,this.clearable=!0,this.showSidebar="1"===localStorage.getItem("pages:showSidebar"),this.splitter=null,this.isVisible=!0,this.favIconUrl="",this.autoUpdateInterval=10,this._autoUpdater=null,this.appName="ReplayWeb.page",this.appVersion=me,this.appLogo=fe()}static get properties(){return{inited:{type:Boolean},sourceUrl:{type:String},loadInfo:{type:Object,attribute:!1},showSidebar:{type:Boolean},collInfo:{type:Object,attribute:!1},coll:{type:String},hasStory:{type:Boolean},isLoading:{type:Boolean},tabData:{type:Object,attribute:!1},url:{type:String},ts:{type:String},isFullscreen:{type:Boolean},menuActive:{type:Boolean},embed:{type:String},embedDropdownActive:{type:Boolean},editable:{type:Boolean},browsable:{type:Boolean},clearable:{type:Boolean},isVisible:{type:Boolean},favIconUrl:{type:String},appName:{type:String},appVersion:{type:String},appLogo:{type:String},autoUpdateInterval:{type:Number},swName:{type:String}}}firstUpdated(){this.inited=!0,window.addEventListener("hashchange",(e=>this.onHashChange(e))),this.addEventListener("fullscreenchange",(()=>{this.isFullscreen=!!document.fullscreenElement})),this.embed&&this.loadInfo&&this.loadInfo.hideOffscreen&&(this.observer=new IntersectionObserver((e=>{this.isVisible=e[0].isIntersecting})),this.observer.observe(this))}async runUpdateLoop(){try{for(;this.editable&&this.autoUpdateInterval&&(!this.collInfo||!this.collInfo.pages||this.collInfo.pages.length<100);)await new Promise((e=>setTimeout(e,1e3*this.autoUpdateInterval))),await this.doUpdateInfo(!0)}finally{this._autoUpdater=null}}updated(e){if(e.has("sourceUrl")&&this.doUpdateInfo(),e.has("editable")&&this.editable&&this.autoUpdateInterval&&!this._autoUpdater&&(this._autoUpdater=this.runUpdateLoop()),e.has("tabData")){if(!this.collInfo||!this.collInfo.coll)return;Object.keys(this.tabData).forEach((e=>!this.tabData[e]&&delete this.tabData[e]));const t="#"+new URLSearchParams(this.tabData).toString();if(this.tabData.url||(this.url=Kt+decodeURIComponent(this._paramsToString(this.tabData))),t!==this._locationHash){if(this._locationHash=t,this._replaceLoc||0===Object.keys(e.get("tabData")).length){const e=new URL(window.location.href);e.hash=this._locationHash,window.history.replaceState({},"",e.href),this._replaceLoc=!1}else if(window.location.hash=this._locationHash,!this.showSidebar){const e=this.renderRoot.querySelector("wr-coll-replay");e&&e.focus()}this.embed&&window.parent!==window&&window.parent.postMessage(this.tabData,"*")}this._locUpdateNeeded=!1}e.has("showSidebar")&&(this.embed||localStorage.setItem("pages:showSidebar",this.showSidebar?"1":"0")),(e.has("tabData")||e.has("showSidebar"))&&this.configureSplitter()}configureSplitter(){if(this.tabData.url&&this.showSidebar){const e=this.renderRoot.querySelector("#contents"),t=this.renderRoot.querySelector("wr-coll-replay");if(e&&t&&!this.splitter){const i={sizes:[30,70],minSize:[300,300],gutterSize:4,onDragStart(){t.setDisablePointer(!0)},onDragEnd(){t.setDisablePointer(!1)}};this.splitter=Gt([e,t],i)}}else if(this.splitter){try{this.splitter.destroy()}catch(e){}this.splitter=null}}async doUpdateInfo(e=!1){if(e&&this.tabData.url&&!this.showSidebar)return;let t=this.loadInfo&&this.loadInfo.customColl;if(!t){t=(await Je(this.sourceUrl)).coll}this.coll=t;const i="./w/api/c/"+t,a="./w/"+t,r=await fetch(i+"?all=1");if(200!=r.status)return void(this.collInfo={});const o=await r.json();if(this.collInfo={apiPrefix:i,replayPrefix:a,coll:t,...o},this.loadInfo&&this.loadInfo.extraConfig&&this.loadInfo.extraConfig.headers){const e=this.loadInfo.extraConfig.headers;await fetch(`${i}/updateAuth`,{method:"POST",body:JSON.stringify({headers:e})})}this.collInfo.title||(this.collInfo.title=this.collInfo.filename),"replayonly"!==this.embed&&"replay-with-info"!==this.embed||(this.showSidebar=!1),this.hasStory=this.collInfo.desc||this.collInfo.lists.length,this.dispatchEvent(new CustomEvent("coll-loaded",{detail:{collInfo:this.collInfo,alreadyLoaded:!0}})),this.onHashChange()}onCollLoaded(e){this.doUpdateInfo(),this.loadInfo=null,e.detail.sourceUrl&&(this.sourceUrl=e.detail.sourceUrl),this.dispatchEvent(new CustomEvent("coll-loaded",{detail:{sourceUrl:this.sourceUrl,collInfo:this.collInfo}}))}onCollUpdate(e){this.editable&&(this.collInfo={...this.collInfo,...e.detail})}onHashChange(){const e=window.location.hash;if(e&&e!==this._locationHash&&(this.tabData=Object.fromEntries(new URLSearchParams(e.slice(1)).entries()),this._locationHash=e),this.collInfo.coll&&!this.tabNames.includes(this.tabData.view)){const e=this.hasStory?"story":this.editable||this.collInfo.pages.length?"pages":"resources";this.tabData={...this.tabData,view:e}}if(this.tabData.url&&this.tabData.url.startsWith("page:")){const e=Number(this.tabData.url.slice("page:".length));if(!isNaN(e)&&e