=0&&d0&&r.push(t.slice(e).join(s)),r}async function ie(i,s){let e=0;for(let t=0;t=i.length){let{value:n}=await s.next();if(!n)break;let a=new Uint8Array(n.length+i.length);a.set(i,0),a.set(n,i.length),i=a}if(i[r+1]===10&&i[r+2]===13&&i[r+3]===10)return[r+3,i];e=r+1}return[-1,i]}async function ae(i){let s=[],e=0,t=0,r=null,n=i[Symbol.asyncIterator]();for await(let a of n){if([t,a]=await ie(a,n),t>=0){r=a;break}s.push(a),e+=a.byteLength}if(r){let[a,o]=R(r,t+1);s.push(a),e+=a.byteLength,i.unread(o)}else if(!s.length)return"";return se.decode(y(s,e))}var le=new TextDecoder("utf-8"),de=new TextEncoder,N="WARC/1.1",v="WARC/1.0",ce="http://netpreserve.org/warc/1.0/revisit/identical-payload-digest",ue="http://netpreserve.org/warc/1.1/revisit/identical-payload-digest",he={warcinfo:"application/warc-fields",response:"application/http; msgtype=response",revisit:"application/http; msgtype=response",request:"application/http; msgtype=request",metadata:"application/warc-fields"},g=class extends h{constructor({warcHeaders:e,reader:t}){super();this._offset=0;this._length=0;this.method="";this.requestBody="";this._urlkey="";this.warcHeaders=e,this._reader=t,this._contentReader=null,this.payload=null,this.httpHeaders=null,this.consumed="",this.fixUp()}static create({url:e,date:t,type:r,warcHeaders:n={},filename:a="",httpHeaders:o={},statusline:l="HTTP/1.1 200 OK",warcVersion:d=v,keepHeadersCase:f=!0,refersToUrl:p=void 0,refersToDate:T=void 0}={},u){function U(x){let Y=x;return d===v&&(x=x.split(".")[0],x.charAt(Y.length-1)!="Z"&&(x+="Z")),x}t=U(t||new Date().toISOString()),n={...n},r==="warcinfo"?a&&(n["WARC-Filename"]=a):n["WARC-Target-URI"]=e,n["WARC-Date"]=t,n["WARC-Type"]=r,r==="revisit"&&(n["WARC-Profile"]=d===N?ue:ce,n["WARC-Refers-To-Target-URI"]=p,n["WARC-Refers-To-Date"]=U(T||new Date().toISOString())),n=new _({statusline:d,headers:f?new Map(Object.entries(n)):new Headers(n)}),n.headers.get("WARC-Record-ID")||n.headers.set("WARC-Record-ID",``),n.headers.get("Content-Type")||n.headers.set("Content-Type",r&&he[r]||"application/octet-stream"),u||(u=async function*(){}());let M=new g({warcHeaders:n,reader:u}),Q=null,D=[];switch(r){case"response":case"request":case"revisit":D=Object.entries(o),Q=f?new Map(D):new Headers(o),(D.length>0||r!=="revisit")&&(M.httpHeaders=new _({statusline:l,headers:Q}));break}return M}static createWARCInfo(e={},t){async function*r(){for(let[n,a]of Object.entries(t))yield de.encode(`${n}: ${a}\r
+`)}return e.type="warcinfo",g.create(e,r())}getResponseInfo(){let e=this.httpHeaders;return e?{headers:e.headers,status:e.statusCode,statusText:e.statusText}:null}fixUp(){let e=this.warcHeaders.headers.get("WARC-Target-URI");e&&e.startsWith("<")&&e.endsWith(">")&&this.warcHeaders.headers.set("WARC-Target-URI",e.slice(1,-1))}async readFully(e=!1){if(this.httpHeaders){if(this.payload&&!this.payload.length)return this.payload;if(this._contentReader&&!e)throw new TypeError("WARC Record decoding already started, but requesting raw payload");if(e&&this.consumed==="raw"&&this.payload)return await this._createDecodingReader([this.payload]).readFully()}return this.payload?this.payload:(e?(this.payload=await super.readFully(),this.consumed="content"):(this.payload=await g.readFully(this._reader),this.consumed="raw"),this.payload)}get reader(){if(this._contentReader)throw new TypeError("WARC Record decoding already started, but requesting raw payload");return this._reader}get contentReader(){return this.httpHeaders?(this._contentReader||(this._contentReader=this._createDecodingReader(this._reader)),this._contentReader):this._reader}_createDecodingReader(e){if(!this.httpHeaders)throw new Error("WARCRecord cannot call _createDecodingReader when this.httpHeaders === null");let t=this.httpHeaders.headers.get("Content-Encoding"),r=this.httpHeaders.headers.get("Transfer-Encoding"),n=r==="chunked";return!t&&!n&&(t=r),new c(e,t,n)}async readlineRaw(e){if(this.consumed)throw new Error("Record already consumed.. Perhaps a promise was not awaited?");if(this.contentReader instanceof h)return this.contentReader.readlineRaw(e);throw new Error("WARCRecord cannot call readlineRaw on this.contentReader if it does not extend BaseAsyncIterReader")}async contentText(){let e=await this.readFully(!0);return le.decode(e)}async*[Symbol.asyncIterator](){for await(let e of this.contentReader)if(yield e,this.consumed)throw new Error("Record already consumed.. Perhaps a promise was not awaited?");this.consumed="content"}async skipFully(){if(!this.consumed){if(this._reader instanceof m){let e=await this._reader.skipFully();return this.consumed="skipped",e}throw new Error("WARCRecord cannot call skipFully on this._reader if it is not a LimitReader")}}warcHeader(e){return this.warcHeaders.headers.get(e)}get warcType(){return this.warcHeaders.headers.get("WARC-Type")}get warcTargetURI(){return this.warcHeaders.headers.get("WARC-Target-URI")}get warcDate(){return this.warcHeaders.headers.get("WARC-Date")}get warcRefersToTargetURI(){return this.warcHeaders.headers.get("WARC-Refers-To-Target-URI")}get warcRefersToDate(){return this.warcHeaders.headers.get("WARC-Refers-To-Date")}get warcPayloadDigest(){return this.warcHeaders.headers.get("WARC-Payload-Digest")}get warcBlockDigest(){return this.warcHeaders.headers.get("WARC-Block-Digest")}get warcContentType(){return this.warcHeaders.headers.get("Content-Type")}get warcContentLength(){return Number(this.warcHeaders.headers.get("Content-Length"))}};var V=new TextDecoder,dist_$=new Uint8Array([]),w=class{static parse(s,e){return new w(s,e).parse()}static iterRecords(s,e){return new w(s,e)[Symbol.asyncIterator]()}constructor(s,{keepHeadersCase:e=!1,parseHttp:t=!0}={}){this._offset=0,this._warcHeadersLength=0,this._headersClass=e?Map:Headers,this._parseHttp=t,s instanceof c?this._reader=s:this._reader=new c(s),this._record=null}async readToNextRecord(){if(!this._reader||!this._record)return dist_$;await this._record.skipFully(),this._reader.compressed&&(this._offset=this._reader.getRawOffset());let s=await this._reader.readlineRaw(),e=0;if(!s)s=dist_$;else{if(e=s.byteLength-1,e===9&&V.decode(s).startsWith("WARC/"))return s;for(;e>0;){let t=s[e-1];if(t!==10&&t!==13)break;e--}e&&console.warn(`Content-Length Too Small: Record not followed by newline, Remainder Length: ${e}, Offset: ${this._reader.getRawOffset()-s.byteLength}`)}if(this._reader.compressed)await this._reader.skipSize(2),s=dist_$;else{for(s=await this._reader.readlineRaw();s&&s.byteLength===2;)s=await this._reader.readlineRaw();this._offset=this._reader.getRawOffset(),s&&(this._offset-=s.length)}return s}_initRecordReader(s){return new m(this._reader,Number(s.headers.get("Content-Length")||0))}async parse(){let s=await this.readToNextRecord(),e=s?V.decode(s):"",t=new k,r=await t.parse(this._reader,{firstLine:e,headersClass:this._headersClass});if(!r)return null;this._warcHeadersLength=this._reader.getReadOffset();let n=new g({warcHeaders:r,reader:this._initRecordReader(r)});if(this._record=n,this._parseHttp)switch(n.warcType){case"response":case"request":await this._addHttpHeaders(n,t);break;case"revisit":n.warcContentLength>0&&await this._addHttpHeaders(n,t);break}return n}get offset(){return this._offset}get recordLength(){return this._reader.getRawLength(this._offset)}async*[Symbol.asyncIterator](){let s=null;for(;(s=await this.parse())!==null;)yield s;this._record=null}async _addHttpHeaders(s,e){let t=await e.parse(this._reader,{headersClass:this._headersClass});s.httpHeaders=t;let r=this._reader.getReadOffset()-this._warcHeadersLength;s.reader instanceof m&&s.reader.setLimitSkip(s.warcContentLength-r)}};var K=new TextEncoder,S=class extends (/* unused pure expression or super */ null && (h)){constructor(e,t={}){super();this.gzip=!1;this.digestAlgo="";this.digestAlgoPrefix="";this.digestBase32=!1;this.record=e,this.gzip=Boolean(t.gzip);let r=t&&t.digest||{};e.warcType!=="revisit"&&e.warcType!=="warcinfo"&&(!e.warcPayloadDigest||!e.warcBlockDigest)?(this.digestAlgo=r?.algo||"sha-256",this.digestAlgoPrefix=r?.prefix||"sha256:",this.digestBase32=Boolean(r?.base32)):this.digestAlgo=""}static async serialize(e,t){return await new S(e,t).readFully()}static base16(e){return Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("")}async*[Symbol.asyncIterator](){if(!this.gzip){yield*this.generateRecord();return}let e=null;"CompressionStream"in globalThis?(e=new globalThis.CompressionStream("gzip"),yield*this.streamCompress(e)):yield*this.pakoCompress()}async readlineRaw(e){return null}async*pakoCompress(){let e=new pe.Deflate({gzip:!0}),t=null;for await(let r of this.generateRecord())for(t&&t.length>0&&e.push(t),t=r;e.chunks.length;)yield e.chunks.shift();t&&e.push(t,!0),yield e.result}async*streamCompress(e){let t=this.generateRecord();new ReadableStream({async pull(o){let l=await t.next();l.done?o.close():o.enqueue(l.value)}}).pipeThrough(e);let n=null,a=e.readable.getReader();for(;(n=await a.read())&&!n.done;)yield n.value}async digestMessage(e){let t=await crypto.subtle.digest(this.digestAlgo,e);return this.digestAlgoPrefix+(this.digestBase32?fe(t,"RFC4648"):S.base16(t))}async*generateRecord(){let e=0,t=null;this.record.httpHeaders&&(t=K.encode(this.record.httpHeaders.toString()+`\r
+`),e+=t.length);let r=await this.record.readFully();if(e+=r.length,this.digestAlgo){let a=await this.digestMessage(r),o=t?await this.digestMessage(y([t,r],e)):a;this.record.warcHeaders.headers.set("WARC-Payload-Digest",a),this.record.warcHeaders.headers.set("WARC-Block-Digest",o)}this.record.warcHeaders.headers.set("Content-Length",e.toString()),yield K.encode(this.record.warcHeaders.toString()),yield z,t&&(yield t),yield r,yield J}};var ye=["offset","warc-type","warc-target-uri"],j=class{constructor(s={}){this.opts=s,this.fields=s&&s.fields?s.fields.split(","):ye,this.parseHttp=!1}serialize(s){return JSON.stringify(s)+`
+`}write(s,e){e.write(this.serialize(s))}async writeAll(s,e){for await(let t of this.iterIndex(s))this.write(t,e)}async*iterIndex(s){let e={strictHeaders:!0,parseHttp:this.parseHttp};for(let{filename:t,reader:r}of s){let n=new w(r,e);yield*this.iterRecords(n,t)}}async*iterRecords(s,e){for await(let t of s){await t.skipFully();let r=this.indexRecord(t,s,e);r&&(yield r)}}indexRecord(s,e,t){if(this.filterRecord&&!this.filterRecord(s))return null;let r={},n=e.offset,a=e.recordLength,o={offset:n,length:a,filename:t};for(let l of this.fields)l in o?r[l]=o[l]:this.setField(l,s,r);return r}setField(s,e,t){let r=this.getField(s,e);r!==null&&(t[s]=r)}getField(s,e){return s==="http:status"?e.httpHeaders&&(e.warcType==="response"||e.warcType==="revisit")?e.httpHeaders.statusCode:null:s.startsWith("http:")?e.httpHeaders?e.httpHeaders.headers.get(s.slice(5)):null:e.warcHeaders.headers.get(s)||null}},I=class extends j{constructor(s){super(s);for(let e of this.fields)if(e.startsWith("http:")){this.parseHttp=!0;break}}},ge="urlkey,timestamp,url,mime,status,digest,length,offset,filename".split(","),Re="urlkey,timestamp,url,mime,status,digest,redirect,meta,length,offset,filename".split(","),W=class extends I{constructor(e){super(e);switch(this.includeAll=Boolean(e?.all),this.overrideIndexForAll=Boolean(e?.all),this.fields=ge,this.parseHttp=!0,this.noSurt=Boolean(e?.noSurt),this._lastRecord=null,e?.format){case"cdxj":this.serialize=this.serializeCDXJ;break;case"cdx":this.serialize=this.serializeCDX11;break;case"json":default:break}}async*iterRecords(e,t){this._lastRecord=null;for await(let n of e){await n.readFully();let a=this.indexRecord(n,e,t);a&&(yield a)}let r=this.indexRecord(null,e,t);r&&(yield r)}filterRecord(e){if(this.includeAll)return!0;let t=e.warcType;return!(t==="request"||t==="warcinfo"||(t==="metadata"||t==="resource")&&e.warcContentType==="application/warc-fields")}indexRecord(e,t,r){if(this.overrideIndexForAll)return e?super.indexRecord(e,t,r):null;let n=this._lastRecord;if(this._lastRecord=e,e&&(e._offset=t.offset,e._length=t.recordLength),!n)return null;if(!e||n.warcTargetURI!=e.warcTargetURI)return this.indexRecordPair(n,null,t,r);let a=e.warcType,o=n.warcType;return a==="request"&&(o==="response"||o==="revisit")?(this._lastRecord=null,this.indexRecordPair(n,e,t,r)):(a==="response"||a==="revisit")&&o==="request"?(this._lastRecord=null,this.indexRecordPair(e,n,t,r)):this.indexRecordPair(n,null,t,r)}indexRecordPair(e,t,r,n){let a,o,l=e.warcTargetURI||"";if(t&&t.httpHeaders&&t.httpHeaders.method!=="GET"){let f={url:l,method:t.httpHeaders.method,headers:t.httpHeaders.headers,postData:t.payload};a=f.method,L(f)&&(o=f.requestBody,e.method=a,e.requestBody=o,l=f.url)}e._urlkey=l;let d=super.indexRecord(e,r,n);return d&&(e&&e._offset!==void 0&&(d.offset=e._offset,d.length=e._length),a&&(d.method=a),o&&(d.requestBody=o)),d}serializeCDXJ(e){let{urlkey:t,timestamp:r}=e;return delete e.urlkey,delete e.timestamp,`${t} ${r} ${JSON.stringify(e)}
+`}serializeCDX11(e){let t=[];for(let r of Re)t.push(e[r]!=null?e[r]:"-");return t.join(" ")+`
+`}getField(e,t){let r=null;switch(e){case"urlkey":return r=t._urlkey||t.warcTargetURI||null,this.noSurt||r===null?r:P(r);case"timestamp":return r=t.warcDate??"",r.replace(/[-:T]/g,"").slice(0,14);case"url":return t.warcTargetURI;case"mime":switch(t.warcType){case"revisit":return"warc/revisit";case"response":case"request":e="http:content-type";break;default:e="content-type"}return r=super.getField(e,t),r?r.toString().split(";",1)[0]?.trim():null;case"status":return super.getField("http:status",t);case"digest":return r=t.warcPayloadDigest,r?r.split(":",2)[1]:null;default:return null}}},O=class extends (/* unused pure expression or super */ null && (W)){constructor(s){super(s),this.overrideIndexForAll=!1}indexRecordPair(s,e,t,r){let n=super.indexRecordPair(s,e,t,r);return n&&{cdx:n,record:s,reqRecord:e}}};
+
+;// CONCATENATED MODULE: ./src/rewrite/decoder.js
+
+
+
+
+
+
+
+// ===========================================================================
+async function decodeResponse(response, contentEncoding, transferEncoding, noRW) {
+
+ // use the streaming decoder if gzip only and no rewriting
+ if (response.reader && noRW &&
+ ((contentEncoding === "gzip" && !transferEncoding) ||
+ (!contentEncoding && transferEncoding === "gzip"))) {
+ response.setReader(new c(response.reader));
+ return response;
+ }
+
+ const origContent = new Uint8Array(await response.getBuffer());
+
+ const content = await decodeContent(origContent, contentEncoding, transferEncoding);
+
+ if (origContent !== content) {
+ response.setBuffer(content);
+ }
+
+ return response;
+}
+
+
+// ===========================================================================
+async function decodeContent(content, contentEncoding, transferEncoding) {
+ const origContent = content;
+
+ try {
+ if (transferEncoding === "chunked") {
+ content = dechunkArrayBuffer(content);
+ }
+ } catch (e) {
+ console.log("Chunk-Encoding Ignored: " + e);
+ }
+
+ try {
+ if (contentEncoding === "br") {
+ content = decompress(content);
+
+ // if ended up with zero-length, probably not valid, just use original
+ if (content.length === 0) {
+ content = origContent;
+ }
+
+ } else if (contentEncoding === "gzip" || transferEncoding === "gzip") {
+ const inflator = new inflate.Inflate();
+
+ inflator.push(content, true);
+
+ // if error occurs (eg. not gzip), use original arraybuffer
+ if (inflator.result && !inflator.err) {
+ content = inflator.result;
+ }
+ }
+ } catch(e) {
+ console.log("Content-Encoding Ignored: " + e);
+ }
+
+ return content;
+}
+
+
+// ===========================================================================
+function dechunkArrayBuffer(data) {
+ let readOffset = 0;
+ let writeOffset = 0;
+
+ const decoder = new TextDecoder("utf-8");
+
+ while (readOffset < data.length) {
+ let i = readOffset;
+
+ // check hex digits, 0-9, A-Z, a-z
+ while ((data[i] >= 48 && data[i] <= 57) ||
+ (data[i] >= 65 && data[i] <= 70) ||
+ (data[i] >= 97 && data[i] <= 102)) {
+ i++;
+ }
+
+ // doesn't start with number, return original
+ if (i === 0) {
+ return data;
+ }
+
+ // ensure \r\n\r\n
+ if (data[i] != 13 || data[i + 1] != 10) {
+ return data;
+ }
+
+ i += 2;
+
+ var chunkLength = parseInt(decoder.decode(data.subarray(readOffset, i)), 16);
+
+ if (chunkLength == 0) {
+ break;
+ }
+
+ data.set(data.subarray(i, i + chunkLength), writeOffset);
+
+ i += chunkLength;
+
+ writeOffset += chunkLength;
+
+ if (data[i] == 13 && data[i + 1] == 10) {
+ i += 2;
+ }
+
+ readOffset = i;
+ }
+
+ return data.subarray(0, writeOffset);
+}
+
+
+
+
+
+;// CONCATENATED MODULE: ./src/response.js
+
+
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+
+// ===========================================================================
+class ArchiveResponse
+{
+
+ static fromResponse({url, response, date, noRW, isLive}) {
+ const payload = response.body ? new c(response.body.getReader(), false) : null;
+ const status = Number(response.headers.get("x-redirect-status") || response.status);
+ const statusText = response.headers.get("x-redirect-statusText") || response.statusText;
+
+ let headers = new Headers(response.headers);
+
+ let origLoc = headers.get("x-orig-location");
+ if (origLoc) {
+ if (origLoc.startsWith(self.location.origin)) {
+ origLoc = origLoc.slice(self.location.origin.length);
+ }
+ headers.set("location", origLoc);
+ headers.delete("x-orig-location");
+ headers.delete("x-redirect-status");
+ headers.delete("x-redirect-statusText");
+ }
+
+ let updateTS = null;
+
+ const origTs = headers.get("x-orig-ts");
+ if (origTs) {
+ date = tsToDate(origTs);
+ headers.delete("x-orig-ts");
+
+ // force TS update downstream
+ if (origTs && origLoc) {
+ updateTS = origTs;
+ }
+ }
+ const mementoDt = headers.get("memento-datetime");
+ if (mementoDt) {
+ date = new Date(mementoDt);
+ }
+
+ const cookie = (headers.get("x-proxy-set-cookie"));
+ if (cookie) {
+ const cookies = [];
+ cookie.split(",").forEach((c) => {
+ const cval = c.split(";", 1)[0].trim();
+ if (cval.indexOf("=") > 0) {
+ cookies.push(cval);
+ }
+ });
+ headers.delete("x-proxy-set-cookie");
+
+ if (cookies.length) {
+ headers.set("x-wabac-preset-cookie", cookies.join(";"));
+ //console.log("cookies", cookies.join(";"));
+ }
+ }
+
+ return new ArchiveResponse({payload, status, statusText, headers, url, date, noRW, isLive, updateTS});
+ }
+
+ constructor({payload, status, statusText, headers, url, date, extraOpts = null, noRW = false, isLive = false, updateTS = null}) {
+ this.reader = null;
+ this.buffer = null;
+
+ if (payload && (payload[Symbol.asyncIterator] || payload instanceof h)) {
+ this.reader = payload;
+ } else {
+ this.buffer = payload;
+ }
+
+ this.status = status;
+ this.statusText = statusText;
+ this.headers = headers;
+ this.url = url;
+ this.date = date;
+ this.extraOpts = extraOpts;
+ this.noRW = noRW;
+ this.isLive = isLive;
+ this.updateTS = updateTS;
+ }
+
+ async getText(isUTF8 = false) {
+ const buff = await this.getBuffer();
+ if (typeof(buff) === "string") {
+ return buff;
+ }
+
+ return isUTF8 ? decoder.decode(buff) : decodeLatin1(buff);
+ }
+
+ setText(text, isUTF8 = false) {
+ this.setBuffer(isUTF8 ? encoder.encode(text) : encodeLatin1(text));
+ }
+
+ async getBuffer() {
+ if (this.buffer) {
+ return this.buffer;
+ }
+
+ this.buffer = await this.reader.readFully();
+ return this.buffer;
+ }
+
+ setBuffer(buffer) {
+ this.buffer = buffer;
+ this.reader = null;
+ }
+
+ setReader(reader) {
+ if (reader instanceof h) {
+ this.reader = reader;
+ this.buffer = null;
+ } else if (reader.getReader) {
+ this.reader = new c(reader.getReader());
+ this.buffer = null;
+ }
+ }
+
+ expectedLength() {
+ if (this.buffer) {
+ return this.buffer.length;
+ } else if (this.reader && this.reader.reader) {
+ return this.reader.reader.length;
+ }
+ }
+
+ createIter() {
+ const buffer = this.buffer;
+ const reader = this.reader;
+
+ async function* iter() {
+ if (buffer) {
+ for (let i = 0; i < buffer.length; i += MAX_STREAM_CHUNK_SIZE) {
+ yield buffer.slice(i, i + MAX_STREAM_CHUNK_SIZE);
+ }
+
+ } else if (reader) {
+ yield* reader;
+ }
+ }
+
+ return iter();
+ }
+
+ async* [Symbol.asyncIterator]() {
+ yield* this.createIter();
+ }
+
+ setRange(range) {
+ if (this.status === 206) {
+ const currRange = this.headers.get("Content-Range");
+ if (currRange && !currRange.startsWith("bytes 0-")) {
+ return false;
+ }
+ }
+
+ const bytes = range.match(/^bytes=(\d+)-(\d+)?$/);
+
+ let length = 0;
+
+ if (this.buffer) {
+ length = this.buffer.length;
+ } else if (this.reader) {
+ //length = this.reader.length;
+ length = Number(this.headers.get("content-length"));
+
+ // if length is not known, keep as 200
+ if (!length) {
+ return false;
+ }
+ }
+
+ if (!bytes) {
+ this.status = 416;
+ this.statusText = "Range Not Satisfiable";
+ this.headers.set("Content-Range", `*/${length}`);
+ return false;
+ }
+
+ const start = Number(bytes[1]);
+ const end = Number(bytes[2]) || (length - 1);
+
+ if (this.buffer) {
+ this.buffer = this.buffer.slice(start, end + 1);
+
+ } else if (this.reader) {
+ if (!this.reader.setLimitSkip) {
+ return false;
+ }
+ if (start !== 0 || end !== (length - 1)) {
+ this.reader.setLimitSkip(end - start + 1, start);
+ } else if (this.reader.setRangeAll) {
+ this.reader.setRangeAll(length);
+ }
+ }
+
+ this.headers.set("Content-Range", `bytes ${start}-${end}/${length}`);
+ this.headers.set("Content-Length", end - start + 1);
+
+ this.status = 206;
+ this.statusText = "Partial Content";
+
+ return true;
+ }
+
+ makeResponse(coHeaders = false) {
+ let body = null;
+ if (!isNullBodyStatus(this.status)) {
+ body = this.buffer || !this.reader ? this.buffer : this.reader.getReadableStream();
+ }
+
+ const response = new Response(body, {status: this.status,
+ statusText: this.statusText,
+ headers: this.headers});
+ response.date = this.date;
+ if (coHeaders) {
+ response.headers.set("Cross-Origin-Opener-Policy", "same-origin");
+ response.headers.set("Cross-Origin-Embedder-Policy", "require-corp");
+ }
+ return response;
+ }
+}
+
+
+
+
+
+// EXTERNAL MODULE: ./node_modules/fast-xml-parser/src/parser.js
+var parser = __webpack_require__(6965);
+;// CONCATENATED MODULE: ./src/rewrite/rewriteVideo.js
+
+
+// orig pywb defaults
+const OLD_DEFAULT_MAX_BAND = 2000000;
+const OLD_DEFAULT_MAX_RES = 1280 * 720;
+
+// lower defaults
+const DEFAULT_MAX_BAND = 1000000;
+const DEFAULT_MAX_RES = 860 * 480;
+
+
+// ===========================================================================
+function getMaxResAndBand(opts = {}) {
+ // read opts from warc, if any
+ let maxRes, maxBand;
+
+ const extraOpts = (opts && opts.response && opts.response.extraOpts);
+
+ if (extraOpts) {
+ maxRes = extraOpts.adaptive_max_resolution || extraOpts.maxRes;
+ maxBand = extraOpts.adaptive_max_bandwidth || extraOpts.maxBand;
+ if (maxRes && maxBand) {
+ return {maxRes, maxBand};
+ }
+ }
+
+ const isReplay = opts && opts.response && !opts.response.isLive;
+ let res;
+
+ // if not replay, or unknown, use new lower setting
+ if (!isReplay) {
+ res = {maxRes: DEFAULT_MAX_RES, maxBand: DEFAULT_MAX_BAND};
+ } else {
+ // use existing pywb defaults
+ res = {maxRes: OLD_DEFAULT_MAX_RES, maxBand: OLD_DEFAULT_MAX_BAND};
+ }
+
+ if (opts && opts.save) {
+ opts.save.maxRes = res.maxRes;
+ opts.save.maxBand = res.maxBand;
+ }
+
+ return res;
+}
+
+
+// ===========================================================================
+//HLS
+function rewriteHLS(text, opts) {
+ const EXT_INF = /#EXT-X-STREAM-INF:(?:.*[,])?BANDWIDTH=([\d]+)/;
+ const EXT_RESOLUTION = /RESOLUTION=([\d]+)x([\d]+)/;
+
+ const { maxRes, maxBand} = getMaxResAndBand(opts);
+
+ let indexes = [];
+ let count = 0;
+ let bestIndex = null;
+
+ let bestBand = 0;
+ let bestRes = 0;
+
+ let lines = text.trimEnd().split("\n");
+
+ for (const line of lines) {
+ const m = line.match(EXT_INF);
+ if (!m) {
+ // if has rewriteUrl (not-ajax), then rewrite HLS urls
+ if (opts && opts.rewriteUrl && !line.startsWith("#")) {
+ lines[count] = opts.rewriteUrl(line);
+ }
+ count += 1;
+ continue;
+ }
+
+ indexes.push(count);
+
+ const currBand = Number(m[1]);
+
+ const m2 = line.match(EXT_RESOLUTION);
+ const currRes = m2 ? Number(m2[1]) * Number(m2[2]) : 0;
+
+ if (currRes && maxRes) {
+ if (currRes <= maxRes && currRes > bestRes) {
+ bestRes = currRes;
+ bestBand = currBand;
+ bestIndex = count;
+ }
+ } else if (currBand <= maxBand && currBand > bestBand) {
+ bestRes = currRes;
+ bestBand = currBand;
+ bestIndex = count;
+ }
+
+ count += 1;
+ }
+
+ indexes.reverse();
+
+ for (const inx of indexes) {
+ if (inx !== bestIndex) {
+ lines.splice(inx, 2);
+ }
+ }
+
+ return lines.join("\n");
+}
+
+// ===========================================================================
+// DASH
+const dashOutputOpts = {ignoreAttributes: false, ignoreNameSpace: false, format: false, supressEmptyNode: true};
+
+
+function rewriteDASH(text, opts, bestIds) {
+ try {
+ return _rewriteDASH(text, opts, bestIds);
+ } catch (e) {
+ console.log(e);
+ return text;
+ }
+}
+
+
+function _rewriteDASH(text, opts, bestIds) {
+ const options = dashOutputOpts;
+ const root = parser.parse(text, options);
+
+ const { maxRes, maxBand} = getMaxResAndBand(opts);
+
+ let best = null;
+ let bestRes = 0;
+ let bestBand = 0;
+
+ let adaptSets = null;
+
+ if (!Array.isArray(root.MPD.Period.AdaptationSet)) {
+ adaptSets = [root.MPD.Period.AdaptationSet];
+ } else {
+ adaptSets = root.MPD.Period.AdaptationSet;
+ }
+
+ for (const adaptset of adaptSets) {
+ best = null;
+ bestRes = 0;
+ bestBand = 0;
+
+ let reps = null;
+
+ if (!Array.isArray(adaptset.Representation)) {
+ reps = [adaptset.Representation];
+ } else {
+ reps = adaptset.Representation;
+ }
+
+ for (const repres of reps) {
+ const currRes = Number(repres["@_width"] || "0") * Number(repres["@_height"] || "0");
+ const currBand = Number(repres["@_bandwidth"] || "0");
+
+ if (currRes && maxRes) {
+ if (currRes <= maxRes && currRes > bestRes) {
+ bestRes = currRes;
+ bestBand = currBand;
+ best = repres;
+ }
+ } else if (currBand <= maxBand && currBand > bestBand) {
+ bestRes = currRes;
+ bestBand = currBand;
+ best = repres;
+ }
+ }
+
+ if (best && Array.isArray(bestIds)) {
+ bestIds.push(best["@_id"]);
+ }
+
+ if (best) {
+ adaptset.Representation = [best];
+ }
+ }
+
+ const toXML = new parser.j2xParser(options);
+ const xml = toXML.parse(root);
+
+ return "\n" + xml.trim();
+}
+
+
+// ===========================================================================
+
+
+
+;// CONCATENATED MODULE: ./src/rewrite/dsruleset.js
+//import unescapeJs from "unescape-js";
+const MAX_BITRATE = 5000000;
+
+// ===========================================================================
+const DEFAULT_RULES = [
+ {
+ contains: ["youtube.com", "youtube-nocookie.com"],
+ rxRules: [
+ [/ytplayer.load\(\);/, ruleReplace("ytplayer.config.args.dash = \"0\"; ytplayer.config.args.dashmpd = \"\"; {0}")],
+ [/yt\.setConfig.*PLAYER_CONFIG.*args":\s*{/, ruleReplace("{0} \"dash\": \"0\", dashmpd: \"\", ")],
+ [/(?:"player":|ytplayer\.config).*"args":\s*{/, ruleReplace("{0}\"dash\":\"0\",\"dashmpd\":\"\",")],
+ [/yt\.setConfig.*PLAYER_VARS.*?{/, ruleReplace("{0}\"dash\":\"0\",\"dashmpd\":\"\",")],
+ [/ytplayer.config={args:\s*{/, ruleReplace("{0}\"dash\":\"0\",\"dashmpd\":\"\",")],
+ [/"0"\s*?==\s*?\w+\.dash&&/m, ruleReplace("1&&")],
+ ]
+ },
+ {
+ contains: ["player.vimeo.com/video/"],
+ rxRules: [
+ [/.+/, ruleRewriteVimeoConfig]
+ ]
+ },
+ {
+ contains: ["master.json?query_string_ranges=0", "master.json?base64"],
+ rxRules: [
+ [/.+/, ruleRewriteVimeoDashManifest]
+ ]
+ },
+ {
+ contains: ["facebook.com/"],
+ rxRules: [
+ //[/"dash_manifest":"?.*dash_prefetched_representation_ids"?:(\[.*\]|[^,]+)/, ruleRewriteFBDash],
+ //[/"dash_manifest":"?.*?dash_prefetched_representation_ids"?:(?:null|(?:.+?\]))/, ruleRewriteFBDash],
+
+ [/"dash_/, ruleReplace("\"__nodash__")],
+ [/_dash"/, ruleReplace("__nodash__\"")],
+ [/_dash_/, ruleReplace("__nodash__")],
+ [/"debugNoBatching\s?":(?:false|0)/, ruleReplace("\"debugNoBatching\":true")]
+ ]
+ },
+
+ {
+ contains: ["instagram.com/"],
+ rxRules: [
+ [/"is_dash_eligible":(?:true|1)/, ruleReplace("\"is_dash_eligible\":false")],
+ [/"debugNoBatching\s?":(?:false|0)/, ruleReplace("\"debugNoBatching\":true")]
+ ]
+ },
+
+ {
+ contains: ["api.twitter.com/2/", "twitter.com/i/api/2/", "twitter.com/i/api/graphql/"],
+ rxRules: [
+ [/"video_info":.*?}]}/, ruleRewriteTwitterVideo("\"video_info\":")]
+ ]
+ },
+
+ {
+ contains: ["cdn.syndication.twimg.com/tweet-result"],
+ rxRules: [
+ [/"video":.*?viewCount":\d+}/, ruleRewriteTwitterVideo("\"video\":")]
+ ]
+ },
+
+ {
+ contains: ["/vqlweb.js"],
+ rxRules: [
+ [/\b\w+\.updatePortSize\(\);this\.updateApplicationSize\(\)(?![*])/img, ruleReplace("/*{0}*/")]
+ ]
+ }
+];
+
+// ===========================================================================
+function ruleReplace(string) {
+ return x => string.replace("{0}", x);
+}
+
+// ===========================================================================
+function setMaxBitrate(opts)
+{
+ let maxBitrate = MAX_BITRATE;
+ const extraOpts = opts.response && opts.response.extraOpts;
+
+ if (opts.save) {
+ opts.save.maxBitrate = maxBitrate;
+ } else if (extraOpts && extraOpts.maxBitrate) {
+ maxBitrate = extraOpts.maxBitrate;
+ }
+
+ return maxBitrate;
+}
+
+// ===========================================================================
+function ruleRewriteTwitterVideo(prefix) {
+
+ return (string, opts) => {
+ if (!opts) {
+ return string;
+ }
+
+ const origString = string;
+
+ try {
+ const W_X_H = /([\d]+)x([\d]+)/;
+
+ const maxBitrate = setMaxBitrate(opts);
+
+ string = string.slice(prefix.length);
+
+ const data = JSON.parse(string);
+
+ let bestVariant = null;
+ let bestBitrate = 0;
+
+ for (const variant of data.variants) {
+ if ((variant.content_type && variant.content_type !== "video/mp4") ||
+ (variant.type && variant.type !== "video/mp4")) {
+ continue;
+ }
+
+ if (variant.bitrate && variant.bitrate > bestBitrate && variant.bitrate <= maxBitrate) {
+ bestVariant = variant;
+ bestBitrate = variant.bitrate;
+ } else if (variant.src) {
+ const matched = W_X_H.exec(variant.src);
+ if (matched) {
+ const bitrate = Number(matched[1]) * Number(matched[2]);
+ if (bitrate > bestBitrate) {
+ bestBitrate = bitrate;
+ bestVariant = variant;
+ }
+ }
+ }
+ }
+
+ if (bestVariant) {
+ data.variants = [bestVariant];
+ }
+
+ return prefix + JSON.stringify(data);
+
+ } catch (e) {
+ console.warn("rewriter error: ", e);
+ return origString;
+ }
+ };
+}
+
+// ===========================================================================
+function ruleRewriteVimeoConfig(string) {
+ let config;
+ try {
+ config = JSON.parse(string);
+ } catch (e) {
+ return string;
+ }
+
+ if (config && config.request && config.request.files) {
+ const files = config.request.files;
+ if (typeof(files.progressive) === "object" && files.progressive.length) {
+ if (files.dash) {
+ files.__dash = files.dash;
+ delete files.dash;
+ }
+ if (files.hls) {
+ files.__hls = files.hls;
+ delete files.hls;
+ }
+ return JSON.stringify(config);
+ }
+ }
+
+ return string.replace(/query_string_ranges=1/g, "query_string_ranges=0");
+}
+
+// ===========================================================================
+function ruleRewriteVimeoDashManifest(string, opts) {
+ if (!opts) {
+ return string;
+ }
+
+ let vimeoManifest = null;
+
+ const maxBitrate = setMaxBitrate(opts);
+
+ try {
+ vimeoManifest = JSON.parse(string);
+ console.log("manifest", vimeoManifest);
+ } catch (e) {
+ return string;
+ }
+
+ function filterByBitrate(array, max, mime) {
+ let bestVariant = 0;
+ let bestBitrate = null;
+
+ for (const variant of array) {
+ if (variant.mime_type == mime && variant.bitrate > bestBitrate && variant.bitrate <= max) {
+ bestBitrate = variant.bitrate;
+ bestVariant = variant;
+ }
+ }
+
+ return bestVariant ? [bestVariant] : array;
+ }
+
+ vimeoManifest.video = filterByBitrate(vimeoManifest.video, maxBitrate, "video/mp4");
+ vimeoManifest.audio = filterByBitrate(vimeoManifest.audio, maxBitrate, "audio/mp4");
+
+ return JSON.stringify(vimeoManifest);
+}
+
+// ===========================================================================
+
+// ===========================================================================
+class DomainSpecificRuleSet
+{
+
+ constructor(RewriterCls, rwRules) {
+ this.rwRules = rwRules || DEFAULT_RULES;
+ this.RewriterCls = RewriterCls;
+
+ this._initRules();
+ }
+
+ _initRules() {
+ this.rewriters = new Map();
+
+ for (const rule of this.rwRules) {
+ if (rule.rxRules) {
+ this.rewriters.set(rule, new this.RewriterCls(rule.rxRules));
+ }
+ }
+ this.defaultRewriter = new this.RewriterCls();
+ }
+
+ getRewriter(url) {
+ for (const rule of this.rwRules) {
+ if (!rule.contains) {
+ continue;
+ }
+
+ for (const containsStr of rule.contains) {
+ if (url.indexOf(containsStr) >= 0) {
+ const rewriter = this.rewriters.get(rule);
+ if (rewriter) {
+ return rewriter;
+ }
+ }
+ }
+ }
+
+ return this.defaultRewriter;
+ }
+}
+
+
+
+
+;// CONCATENATED MODULE: ./src/rewrite/rxrewriter.js
+
+// ===========================================================================
+class RxRewriter
+{
+ constructor(rules) {
+ this.rules = rules || null;
+ if (this.rules) {
+ this.compileRules();
+ } else {
+ this.rx = null;
+ }
+ }
+
+ compileRules() {
+ let rxBuff = "";
+
+ for (let rule of this.rules) {
+ if (rxBuff) {
+ rxBuff += "|";
+ }
+ rxBuff += `(${rule[0].source})`;
+ }
+
+ const rxString = `(?:${rxBuff})`;
+
+ this.rx = new RegExp(rxString, "gm");
+ }
+
+ doReplace(params, opts) {
+ const offset = params[params.length - 2];
+ const string = params[params.length - 1];
+
+ for (let i = 0; i < this.rules.length; i++) {
+ const curr = params[i];
+ if (!curr) {
+ continue;
+ }
+
+ const result = this.rules[i][1].call(this, curr, opts, offset, string);
+ if (result) {
+ return result;
+ }
+ }
+ }
+
+ rewrite(text, opts) {
+ if (!this.rx) {
+ return text;
+ }
+
+ return text.replace(this.rx, (match, ...params) => this.doReplace(params, opts));
+ }
+}
+
+
+
+
+;// CONCATENATED MODULE: ./src/rewrite/jsrewriter.js
+
+
+const IMPORT_RX = /^\s*?import\s*?[{"'*]/;
+const EXPORT_RX = /^\s*?export\s*?({([\s\w,$\n]+?)}[\s;]*|default|class)\s+/m;
+
+const IMPORT_MATCH_RX = /^\s*?import(?:['"\s]*(?:[\w*${}\s,]+from\s*)?['"\s]?['"\s])(?:.*?)['"\s]/;
+
+const IMPORT_HTTP_RX = /(import(?:['"\s]*(?:[\w*${}\s,]+from\s*)?['"\s]?['"\s]))((?:https?|[./]).*?)(['"\s])/;
+
+
+const GLOBAL_OVERRIDES = [
+ "window",
+ "globalThis",
+ "self",
+ "document",
+ "location",
+ "top",
+ "parent",
+ "frames",
+ "opener"
+];
+
+const GLOBALS_CONCAT_STR = GLOBAL_OVERRIDES.map((x) => `(?:^|[^$.])\\b${x}\\b(?:$|[^$])`).join("|");
+
+const GLOBALS_RX = new RegExp(`(${GLOBALS_CONCAT_STR})`);
+
+// ===========================================================================
+const createJSRules = () => {
+
+ const thisRw = "_____WB$wombat$check$this$function_____(this)";
+
+ const checkLoc = "((self.__WB_check_loc && self.__WB_check_loc(location, arguments)) || {}).href = ";
+
+ const evalStr = "WB_wombat_runEval2((_______eval_arg, isGlobal) => { var ge = eval; return isGlobal ? ge(_______eval_arg) : eval(_______eval_arg); }).eval(this, (function() { return arguments })(),";
+
+ function addPrefix(prefix) {
+ return x => prefix + x;
+ }
+
+ function replacePrefixFrom(prefix, match) {
+ return (x) => {
+ const start = x.indexOf(match);
+ if (start === 0) {
+ return prefix;
+ } else {
+ return x.slice(0, start) + prefix;
+ }
+ };
+ }
+
+ function addSuffix(suffix) {
+ return (x, _opts, offset, string) => {
+ if (offset > 0) {
+ const prev = string[offset - 1];
+ if (prev === "." || prev === "$") {
+ return x;
+ }
+ }
+ return x + suffix;
+ };
+ }
+
+ function replaceThis() {
+ return x => x.replace("this", thisRw);
+ }
+
+ function replace(src, target) {
+ return x => x.replace(src, target);
+ }
+
+ function replaceThisProp() {
+ return (x, _opts, offset, string) => {
+ const prev = (offset > 0 ? string[offset - 1] : "");
+ if (prev === "\n") {
+ return x.replace("this", ";" + thisRw);
+ } else if (prev !== "." && prev !== "$") {
+ return x.replace("this", thisRw);
+ } else {
+ return x;
+ }
+ };
+ }
+
+ function replaceImport(src, target) {
+ return (x, opts) => {
+ let res = x.replace(src, target);
+ // if not module, add empty string, otherwise, import.meta.url
+ res += (opts.isModule ? "import.meta.url, " : "\"\", ");
+ return res;
+ };
+ }
+
+ return [
+ // rewriting 'eval(...)' - invocation
+ [/(?:^|\s)\beval\s*\(/, replacePrefixFrom(evalStr, "eval")],
+
+ // rewriting 'x = eval' - no invocation
+ [/[=]\s*\beval\b(?![(:.$])/, replace("eval", "self.eval")],
+
+ // rewriting .postMessage -> __WB_pmw(self).postMessage
+ [/\.postMessage\b\(/, addPrefix(".__WB_pmw(self)")],
+
+ // rewriting 'location = ' to custom expression '(...).href =' assignment
+ [/[^$.]?\s?\blocation\b\s*[=]\s*(?![\s=])/, addSuffix(checkLoc)],
+
+ // rewriting 'return this'
+ [/\breturn\s+this\b\s*(?![\s\w.$])/, replaceThis()],
+
+ // rewriting 'this.' special properties access on new line, with ; prepended
+ // if prev char is '\n', or if prev is not '.' or '$', no semi
+ [new RegExp(`[^$.]\\s?\\bthis\\b(?=(?:\\.(?:${GLOBAL_OVERRIDES.join("|")})\\b))`), replaceThisProp()],
+
+ // rewrite '= this' or ', this'
+ [/[=,]\s*\bthis\b\s*(?![\s\w:.$])/, replaceThis()],
+
+ // rewrite '})(this)'
+ [/\}(?:\s*\))?\s*\(this\)/, replaceThis()],
+
+ // rewrite this in && or || expr?
+ [/[^|&][|&]{2}\s*this\b\s*(?)/, replaceThis()],
+
+ // esm dynamic import, if found, mark as module
+ [/[^$.]\bimport\s*\(/, replaceImport("import", "____wb_rewrite_import__")]
+ ];
+};
+
+// ===========================================================================
+const jsrewriter_DEFAULT_RULES = createJSRules();
+
+
+// ===========================================================================
+class JSRewriter extends RxRewriter {
+ constructor(extraRules) {
+ super();
+ this.extraRules = extraRules;
+
+ this.firstBuff = this.initLocalDecl(GLOBAL_OVERRIDES);
+ this.lastBuff = "\n\n}";
+ }
+
+ initLocalDecl(localDecls) {
+ const assignFunc = "_____WB$wombat$assign$function_____";
+
+ let buffer = `\
+var ${assignFunc} = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
+if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
+{
+`;
+
+ for (let decl of localDecls) {
+ buffer += `let ${decl} = ${assignFunc}("${decl}");\n`;
+ }
+ buffer += "let arguments;\n";
+
+ return buffer + "\n";
+ }
+
+ getModuleDecl(localDecls, prefix) {
+ return `import { ${localDecls.join(", ")} } from "${prefix}__wb_module_decl.js";\n`;
+ }
+
+ detectIsModule(text) {
+ if (text.indexOf("import") >= 0 && text.match(IMPORT_RX)) {
+ return true;
+ }
+
+ if (text.indexOf("export") >= 0 && text.match(EXPORT_RX)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ rewrite(text, opts) {
+ opts = opts || {};
+ if (opts.isModule === undefined || opts.isModule === null) {
+ opts.isModule = this.detectIsModule(text, opts);
+ }
+
+ let rules = jsrewriter_DEFAULT_RULES;
+
+ if (opts.isModule) {
+ rules = [...rules, this.getESMImportRule()];
+ }
+
+ if (this.extraRules && this.extraRules.length) {
+ this.rules = [...rules, ...this.extraRules];
+ } else {
+ this.rules = rules;
+ }
+
+ this.compileRules();
+
+ let newText = super.rewrite(text, opts);
+
+ if (opts.isModule) {
+ return this.getModuleDecl(GLOBAL_OVERRIDES, opts.prefix) + newText;
+ }
+
+ const wrapGlobals = GLOBALS_RX.exec(text);
+
+ if (wrapGlobals) {
+ newText = this.firstBuff + newText + this.lastBuff;
+ }
+
+ if (opts && opts.inline) {
+ newText = newText.replace(/\n/g, " ") ;
+ }
+
+ return newText;
+ }
+
+ getESMImportRule() {
+ // mark as module side-effect + rewrite if http[s] url
+ function rewriteImport() {
+ return (x, opts) => {
+ const prefix = opts.prefix.replace("mp_/", "esm_/");
+
+ return x.replace(IMPORT_HTTP_RX, (_, g1, g2, g3) => {
+ try {
+ g2 = new URL(g2, opts.baseUrl).href;
+ g2 = prefix + g2;
+ } catch (e) {
+ // ignore, keep same url
+ }
+ return g1 + g2 + g3;
+ });
+ };
+ }
+
+ // match and rewrite import statements
+ return [IMPORT_MATCH_RX, rewriteImport()];
+ }
+}
+
+
+
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/common/unicode.js
+const UNDEFINED_CODE_POINTS = new Set([
+ 65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214,
+ 393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894,
+ 720895, 786430, 786431, 851966, 851967, 917502, 917503, 983038, 983039, 1048574,
+ 1048575, 1114110, 1114111,
+]);
+const REPLACEMENT_CHARACTER = '\uFFFD';
+var CODE_POINTS;
+(function (CODE_POINTS) {
+ CODE_POINTS[CODE_POINTS["EOF"] = -1] = "EOF";
+ CODE_POINTS[CODE_POINTS["NULL"] = 0] = "NULL";
+ CODE_POINTS[CODE_POINTS["TABULATION"] = 9] = "TABULATION";
+ CODE_POINTS[CODE_POINTS["CARRIAGE_RETURN"] = 13] = "CARRIAGE_RETURN";
+ CODE_POINTS[CODE_POINTS["LINE_FEED"] = 10] = "LINE_FEED";
+ CODE_POINTS[CODE_POINTS["FORM_FEED"] = 12] = "FORM_FEED";
+ CODE_POINTS[CODE_POINTS["SPACE"] = 32] = "SPACE";
+ CODE_POINTS[CODE_POINTS["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";
+ CODE_POINTS[CODE_POINTS["QUOTATION_MARK"] = 34] = "QUOTATION_MARK";
+ CODE_POINTS[CODE_POINTS["NUMBER_SIGN"] = 35] = "NUMBER_SIGN";
+ CODE_POINTS[CODE_POINTS["AMPERSAND"] = 38] = "AMPERSAND";
+ CODE_POINTS[CODE_POINTS["APOSTROPHE"] = 39] = "APOSTROPHE";
+ CODE_POINTS[CODE_POINTS["HYPHEN_MINUS"] = 45] = "HYPHEN_MINUS";
+ CODE_POINTS[CODE_POINTS["SOLIDUS"] = 47] = "SOLIDUS";
+ CODE_POINTS[CODE_POINTS["DIGIT_0"] = 48] = "DIGIT_0";
+ CODE_POINTS[CODE_POINTS["DIGIT_9"] = 57] = "DIGIT_9";
+ CODE_POINTS[CODE_POINTS["SEMICOLON"] = 59] = "SEMICOLON";
+ CODE_POINTS[CODE_POINTS["LESS_THAN_SIGN"] = 60] = "LESS_THAN_SIGN";
+ CODE_POINTS[CODE_POINTS["EQUALS_SIGN"] = 61] = "EQUALS_SIGN";
+ CODE_POINTS[CODE_POINTS["GREATER_THAN_SIGN"] = 62] = "GREATER_THAN_SIGN";
+ CODE_POINTS[CODE_POINTS["QUESTION_MARK"] = 63] = "QUESTION_MARK";
+ CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_A"] = 65] = "LATIN_CAPITAL_A";
+ CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_F"] = 70] = "LATIN_CAPITAL_F";
+ CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_X"] = 88] = "LATIN_CAPITAL_X";
+ CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_Z"] = 90] = "LATIN_CAPITAL_Z";
+ CODE_POINTS[CODE_POINTS["RIGHT_SQUARE_BRACKET"] = 93] = "RIGHT_SQUARE_BRACKET";
+ CODE_POINTS[CODE_POINTS["GRAVE_ACCENT"] = 96] = "GRAVE_ACCENT";
+ CODE_POINTS[CODE_POINTS["LATIN_SMALL_A"] = 97] = "LATIN_SMALL_A";
+ CODE_POINTS[CODE_POINTS["LATIN_SMALL_F"] = 102] = "LATIN_SMALL_F";
+ CODE_POINTS[CODE_POINTS["LATIN_SMALL_X"] = 120] = "LATIN_SMALL_X";
+ CODE_POINTS[CODE_POINTS["LATIN_SMALL_Z"] = 122] = "LATIN_SMALL_Z";
+ CODE_POINTS[CODE_POINTS["REPLACEMENT_CHARACTER"] = 65533] = "REPLACEMENT_CHARACTER";
+})(CODE_POINTS = CODE_POINTS || (CODE_POINTS = {}));
+const SEQUENCES = {
+ DASH_DASH: '--',
+ CDATA_START: '[CDATA[',
+ DOCTYPE: 'doctype',
+ SCRIPT: 'script',
+ PUBLIC: 'public',
+ SYSTEM: 'system',
+};
+//Surrogates
+function isSurrogate(cp) {
+ return cp >= 55296 && cp <= 57343;
+}
+function isSurrogatePair(cp) {
+ return cp >= 56320 && cp <= 57343;
+}
+function getSurrogatePairCodePoint(cp1, cp2) {
+ return (cp1 - 55296) * 1024 + 9216 + cp2;
+}
+//NOTE: excluding NULL and ASCII whitespace
+function isControlCodePoint(cp) {
+ return ((cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) ||
+ (cp >= 0x7f && cp <= 0x9f));
+}
+function isUndefinedCodePoint(cp) {
+ return (cp >= 64976 && cp <= 65007) || UNDEFINED_CODE_POINTS.has(cp);
+}
+//# sourceMappingURL=unicode.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/common/error-codes.js
+var error_codes_ERR;
+(function (ERR) {
+ ERR["controlCharacterInInputStream"] = "control-character-in-input-stream";
+ ERR["noncharacterInInputStream"] = "noncharacter-in-input-stream";
+ ERR["surrogateInInputStream"] = "surrogate-in-input-stream";
+ ERR["nonVoidHtmlElementStartTagWithTrailingSolidus"] = "non-void-html-element-start-tag-with-trailing-solidus";
+ ERR["endTagWithAttributes"] = "end-tag-with-attributes";
+ ERR["endTagWithTrailingSolidus"] = "end-tag-with-trailing-solidus";
+ ERR["unexpectedSolidusInTag"] = "unexpected-solidus-in-tag";
+ ERR["unexpectedNullCharacter"] = "unexpected-null-character";
+ ERR["unexpectedQuestionMarkInsteadOfTagName"] = "unexpected-question-mark-instead-of-tag-name";
+ ERR["invalidFirstCharacterOfTagName"] = "invalid-first-character-of-tag-name";
+ ERR["unexpectedEqualsSignBeforeAttributeName"] = "unexpected-equals-sign-before-attribute-name";
+ ERR["missingEndTagName"] = "missing-end-tag-name";
+ ERR["unexpectedCharacterInAttributeName"] = "unexpected-character-in-attribute-name";
+ ERR["unknownNamedCharacterReference"] = "unknown-named-character-reference";
+ ERR["missingSemicolonAfterCharacterReference"] = "missing-semicolon-after-character-reference";
+ ERR["unexpectedCharacterAfterDoctypeSystemIdentifier"] = "unexpected-character-after-doctype-system-identifier";
+ ERR["unexpectedCharacterInUnquotedAttributeValue"] = "unexpected-character-in-unquoted-attribute-value";
+ ERR["eofBeforeTagName"] = "eof-before-tag-name";
+ ERR["eofInTag"] = "eof-in-tag";
+ ERR["missingAttributeValue"] = "missing-attribute-value";
+ ERR["missingWhitespaceBetweenAttributes"] = "missing-whitespace-between-attributes";
+ ERR["missingWhitespaceAfterDoctypePublicKeyword"] = "missing-whitespace-after-doctype-public-keyword";
+ ERR["missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers"] = "missing-whitespace-between-doctype-public-and-system-identifiers";
+ ERR["missingWhitespaceAfterDoctypeSystemKeyword"] = "missing-whitespace-after-doctype-system-keyword";
+ ERR["missingQuoteBeforeDoctypePublicIdentifier"] = "missing-quote-before-doctype-public-identifier";
+ ERR["missingQuoteBeforeDoctypeSystemIdentifier"] = "missing-quote-before-doctype-system-identifier";
+ ERR["missingDoctypePublicIdentifier"] = "missing-doctype-public-identifier";
+ ERR["missingDoctypeSystemIdentifier"] = "missing-doctype-system-identifier";
+ ERR["abruptDoctypePublicIdentifier"] = "abrupt-doctype-public-identifier";
+ ERR["abruptDoctypeSystemIdentifier"] = "abrupt-doctype-system-identifier";
+ ERR["cdataInHtmlContent"] = "cdata-in-html-content";
+ ERR["incorrectlyOpenedComment"] = "incorrectly-opened-comment";
+ ERR["eofInScriptHtmlCommentLikeText"] = "eof-in-script-html-comment-like-text";
+ ERR["eofInDoctype"] = "eof-in-doctype";
+ ERR["nestedComment"] = "nested-comment";
+ ERR["abruptClosingOfEmptyComment"] = "abrupt-closing-of-empty-comment";
+ ERR["eofInComment"] = "eof-in-comment";
+ ERR["incorrectlyClosedComment"] = "incorrectly-closed-comment";
+ ERR["eofInCdata"] = "eof-in-cdata";
+ ERR["absenceOfDigitsInNumericCharacterReference"] = "absence-of-digits-in-numeric-character-reference";
+ ERR["nullCharacterReference"] = "null-character-reference";
+ ERR["surrogateCharacterReference"] = "surrogate-character-reference";
+ ERR["characterReferenceOutsideUnicodeRange"] = "character-reference-outside-unicode-range";
+ ERR["controlCharacterReference"] = "control-character-reference";
+ ERR["noncharacterCharacterReference"] = "noncharacter-character-reference";
+ ERR["missingWhitespaceBeforeDoctypeName"] = "missing-whitespace-before-doctype-name";
+ ERR["missingDoctypeName"] = "missing-doctype-name";
+ ERR["invalidCharacterSequenceAfterDoctypeName"] = "invalid-character-sequence-after-doctype-name";
+ ERR["duplicateAttribute"] = "duplicate-attribute";
+ ERR["nonConformingDoctype"] = "non-conforming-doctype";
+ ERR["missingDoctype"] = "missing-doctype";
+ ERR["misplacedDoctype"] = "misplaced-doctype";
+ ERR["endTagWithoutMatchingOpenElement"] = "end-tag-without-matching-open-element";
+ ERR["closingOfElementWithOpenChildElements"] = "closing-of-element-with-open-child-elements";
+ ERR["disallowedContentInNoscriptInHead"] = "disallowed-content-in-noscript-in-head";
+ ERR["openElementsLeftAfterEof"] = "open-elements-left-after-eof";
+ ERR["abandonedHeadElementChild"] = "abandoned-head-element-child";
+ ERR["misplacedStartTagForHeadElement"] = "misplaced-start-tag-for-head-element";
+ ERR["nestedNoscriptInHead"] = "nested-noscript-in-head";
+ ERR["eofInElementThatCanContainOnlyText"] = "eof-in-element-that-can-contain-only-text";
+})(error_codes_ERR = error_codes_ERR || (error_codes_ERR = {}));
+//# sourceMappingURL=error-codes.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/tokenizer/preprocessor.js
+
+
+//Const
+const DEFAULT_BUFFER_WATERLINE = 1 << 16;
+//Preprocessor
+//NOTE: HTML input preprocessing
+//(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#preprocessing-the-input-stream)
+class Preprocessor {
+ constructor(handler) {
+ this.handler = handler;
+ this.html = '';
+ this.pos = -1;
+ // NOTE: Initial `lastGapPos` is -2, to ensure `col` on initialisation is 0
+ this.lastGapPos = -2;
+ this.gapStack = [];
+ this.skipNextNewLine = false;
+ this.lastChunkWritten = false;
+ this.endOfChunkHit = false;
+ this.bufferWaterline = DEFAULT_BUFFER_WATERLINE;
+ this.isEol = false;
+ this.lineStartPos = 0;
+ this.droppedBufferSize = 0;
+ this.line = 1;
+ //NOTE: avoid reporting errors twice on advance/retreat
+ this.lastErrOffset = -1;
+ }
+ /** The column on the current line. If we just saw a gap (eg. a surrogate pair), return the index before. */
+ get col() {
+ return this.pos - this.lineStartPos + Number(this.lastGapPos !== this.pos);
+ }
+ get offset() {
+ return this.droppedBufferSize + this.pos;
+ }
+ getError(code) {
+ const { line, col, offset } = this;
+ return {
+ code,
+ startLine: line,
+ endLine: line,
+ startCol: col,
+ endCol: col,
+ startOffset: offset,
+ endOffset: offset,
+ };
+ }
+ _err(code) {
+ if (this.handler.onParseError && this.lastErrOffset !== this.offset) {
+ this.lastErrOffset = this.offset;
+ this.handler.onParseError(this.getError(code));
+ }
+ }
+ _addGap() {
+ this.gapStack.push(this.lastGapPos);
+ this.lastGapPos = this.pos;
+ }
+ _processSurrogate(cp) {
+ //NOTE: try to peek a surrogate pair
+ if (this.pos !== this.html.length - 1) {
+ const nextCp = this.html.charCodeAt(this.pos + 1);
+ if (isSurrogatePair(nextCp)) {
+ //NOTE: we have a surrogate pair. Peek pair character and recalculate code point.
+ this.pos++;
+ //NOTE: add a gap that should be avoided during retreat
+ this._addGap();
+ return getSurrogatePairCodePoint(cp, nextCp);
+ }
+ }
+ //NOTE: we are at the end of a chunk, therefore we can't infer the surrogate pair yet.
+ else if (!this.lastChunkWritten) {
+ this.endOfChunkHit = true;
+ return CODE_POINTS.EOF;
+ }
+ //NOTE: isolated surrogate
+ this._err(error_codes_ERR.surrogateInInputStream);
+ return cp;
+ }
+ willDropParsedChunk() {
+ return this.pos > this.bufferWaterline;
+ }
+ dropParsedChunk() {
+ if (this.willDropParsedChunk()) {
+ this.html = this.html.substring(this.pos);
+ this.lineStartPos -= this.pos;
+ this.droppedBufferSize += this.pos;
+ this.pos = 0;
+ this.lastGapPos = -2;
+ this.gapStack.length = 0;
+ }
+ }
+ write(chunk, isLastChunk) {
+ if (this.html.length > 0) {
+ this.html += chunk;
+ }
+ else {
+ this.html = chunk;
+ }
+ this.endOfChunkHit = false;
+ this.lastChunkWritten = isLastChunk;
+ }
+ insertHtmlAtCurrentPos(chunk) {
+ this.html = this.html.substring(0, this.pos + 1) + chunk + this.html.substring(this.pos + 1);
+ this.endOfChunkHit = false;
+ }
+ startsWith(pattern, caseSensitive) {
+ // Check if our buffer has enough characters
+ if (this.pos + pattern.length > this.html.length) {
+ this.endOfChunkHit = !this.lastChunkWritten;
+ return false;
+ }
+ if (caseSensitive) {
+ return this.html.startsWith(pattern, this.pos);
+ }
+ for (let i = 0; i < pattern.length; i++) {
+ const cp = this.html.charCodeAt(this.pos + i) | 0x20;
+ if (cp !== pattern.charCodeAt(i)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ peek(offset) {
+ const pos = this.pos + offset;
+ if (pos >= this.html.length) {
+ this.endOfChunkHit = !this.lastChunkWritten;
+ return CODE_POINTS.EOF;
+ }
+ const code = this.html.charCodeAt(pos);
+ return code === CODE_POINTS.CARRIAGE_RETURN ? CODE_POINTS.LINE_FEED : code;
+ }
+ advance() {
+ this.pos++;
+ //NOTE: LF should be in the last column of the line
+ if (this.isEol) {
+ this.isEol = false;
+ this.line++;
+ this.lineStartPos = this.pos;
+ }
+ if (this.pos >= this.html.length) {
+ this.endOfChunkHit = !this.lastChunkWritten;
+ return CODE_POINTS.EOF;
+ }
+ let cp = this.html.charCodeAt(this.pos);
+ //NOTE: all U+000D CARRIAGE RETURN (CR) characters must be converted to U+000A LINE FEED (LF) characters
+ if (cp === CODE_POINTS.CARRIAGE_RETURN) {
+ this.isEol = true;
+ this.skipNextNewLine = true;
+ return CODE_POINTS.LINE_FEED;
+ }
+ //NOTE: any U+000A LINE FEED (LF) characters that immediately follow a U+000D CARRIAGE RETURN (CR) character
+ //must be ignored.
+ if (cp === CODE_POINTS.LINE_FEED) {
+ this.isEol = true;
+ if (this.skipNextNewLine) {
+ // `line` will be bumped again in the recursive call.
+ this.line--;
+ this.skipNextNewLine = false;
+ this._addGap();
+ return this.advance();
+ }
+ }
+ this.skipNextNewLine = false;
+ if (isSurrogate(cp)) {
+ cp = this._processSurrogate(cp);
+ }
+ //OPTIMIZATION: first check if code point is in the common allowed
+ //range (ASCII alphanumeric, whitespaces, big chunk of BMP)
+ //before going into detailed performance cost validation.
+ const isCommonValidRange = this.handler.onParseError === null ||
+ (cp > 0x1f && cp < 0x7f) ||
+ cp === CODE_POINTS.LINE_FEED ||
+ cp === CODE_POINTS.CARRIAGE_RETURN ||
+ (cp > 0x9f && cp < 64976);
+ if (!isCommonValidRange) {
+ this._checkForProblematicCharacters(cp);
+ }
+ return cp;
+ }
+ _checkForProblematicCharacters(cp) {
+ if (isControlCodePoint(cp)) {
+ this._err(error_codes_ERR.controlCharacterInInputStream);
+ }
+ else if (isUndefinedCodePoint(cp)) {
+ this._err(error_codes_ERR.noncharacterInInputStream);
+ }
+ }
+ retreat(count) {
+ this.pos -= count;
+ while (this.pos < this.lastGapPos) {
+ this.lastGapPos = this.gapStack.pop();
+ this.pos--;
+ }
+ this.isEol = false;
+ }
+}
+//# sourceMappingURL=preprocessor.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/common/token.js
+var token_TokenType;
+(function (TokenType) {
+ TokenType[TokenType["CHARACTER"] = 0] = "CHARACTER";
+ TokenType[TokenType["NULL_CHARACTER"] = 1] = "NULL_CHARACTER";
+ TokenType[TokenType["WHITESPACE_CHARACTER"] = 2] = "WHITESPACE_CHARACTER";
+ TokenType[TokenType["START_TAG"] = 3] = "START_TAG";
+ TokenType[TokenType["END_TAG"] = 4] = "END_TAG";
+ TokenType[TokenType["COMMENT"] = 5] = "COMMENT";
+ TokenType[TokenType["DOCTYPE"] = 6] = "DOCTYPE";
+ TokenType[TokenType["EOF"] = 7] = "EOF";
+ TokenType[TokenType["HIBERNATION"] = 8] = "HIBERNATION";
+})(token_TokenType = token_TokenType || (token_TokenType = {}));
+function token_getTokenAttr(token, attrName) {
+ for (let i = token.attrs.length - 1; i >= 0; i--) {
+ if (token.attrs[i].name === attrName) {
+ return token.attrs[i].value;
+ }
+ }
+ return null;
+}
+//# sourceMappingURL=token.js.map
+;// CONCATENATED MODULE: ./node_modules/entities/lib/esm/generated/decode-data-html.js
+// Generated using scripts/write-decode-map.ts
+/* harmony default export */ const decode_data_html = (new Uint16Array(
+// prettier-ignore
+"\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c"
+ .split("")
+ .map((c) => c.charCodeAt(0))));
+//# sourceMappingURL=decode-data-html.js.map
+;// CONCATENATED MODULE: ./node_modules/entities/lib/esm/generated/decode-data-xml.js
+// Generated using scripts/write-decode-map.ts
+/* harmony default export */ const decode_data_xml = (new Uint16Array(
+// prettier-ignore
+"\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022"
+ .split("")
+ .map((c) => c.charCodeAt(0))));
+//# sourceMappingURL=decode-data-xml.js.map
+;// CONCATENATED MODULE: ./node_modules/entities/lib/esm/decode_codepoint.js
+// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134
+var _a;
+const decodeMap = new Map([
+ [0, 65533],
+ // C1 Unicode control character reference replacements
+ [128, 8364],
+ [130, 8218],
+ [131, 402],
+ [132, 8222],
+ [133, 8230],
+ [134, 8224],
+ [135, 8225],
+ [136, 710],
+ [137, 8240],
+ [138, 352],
+ [139, 8249],
+ [140, 338],
+ [142, 381],
+ [145, 8216],
+ [146, 8217],
+ [147, 8220],
+ [148, 8221],
+ [149, 8226],
+ [150, 8211],
+ [151, 8212],
+ [152, 732],
+ [153, 8482],
+ [154, 353],
+ [155, 8250],
+ [156, 339],
+ [158, 382],
+ [159, 376],
+]);
+/**
+ * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point.
+ */
+const fromCodePoint =
+// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins
+(_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function (codePoint) {
+ let output = "";
+ if (codePoint > 0xffff) {
+ codePoint -= 0x10000;
+ output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800);
+ codePoint = 0xdc00 | (codePoint & 0x3ff);
+ }
+ output += String.fromCharCode(codePoint);
+ return output;
+};
+/**
+ * Replace the given code point with a replacement character if it is a
+ * surrogate or is outside the valid range. Otherwise return the code
+ * point unchanged.
+ */
+function replaceCodePoint(codePoint) {
+ var _a;
+ if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) {
+ return 0xfffd;
+ }
+ return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint;
+}
+/**
+ * Replace the code point if relevant, then convert it to a string.
+ *
+ * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead.
+ * @param codePoint The code point to decode.
+ * @returns The decoded code point.
+ */
+function decodeCodePoint(codePoint) {
+ return fromCodePoint(replaceCodePoint(codePoint));
+}
+//# sourceMappingURL=decode_codepoint.js.map
+;// CONCATENATED MODULE: ./node_modules/entities/lib/esm/decode.js
+
+
+
+// Re-export for use by eg. htmlparser2
+
+
+var CharCodes;
+(function (CharCodes) {
+ CharCodes[CharCodes["NUM"] = 35] = "NUM";
+ CharCodes[CharCodes["SEMI"] = 59] = "SEMI";
+ CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS";
+ CharCodes[CharCodes["ZERO"] = 48] = "ZERO";
+ CharCodes[CharCodes["NINE"] = 57] = "NINE";
+ CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A";
+ CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F";
+ CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X";
+ CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z";
+ CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A";
+ CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F";
+ CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z";
+})(CharCodes || (CharCodes = {}));
+/** Bit that needs to be set to convert an upper case ASCII character to lower case */
+const TO_LOWER_BIT = 0b100000;
+var BinTrieFlags;
+(function (BinTrieFlags) {
+ BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
+ BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
+ BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE";
+})(BinTrieFlags || (BinTrieFlags = {}));
+function isNumber(code) {
+ return code >= CharCodes.ZERO && code <= CharCodes.NINE;
+}
+function isHexadecimalCharacter(code) {
+ return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) ||
+ (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F));
+}
+function isAsciiAlphaNumeric(code) {
+ return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) ||
+ (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) ||
+ isNumber(code));
+}
+/**
+ * Checks if the given character is a valid end character for an entity in an attribute.
+ *
+ * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.
+ * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
+ */
+function isEntityInAttributeInvalidEnd(code) {
+ return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code);
+}
+var EntityDecoderState;
+(function (EntityDecoderState) {
+ EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart";
+ EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart";
+ EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal";
+ EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex";
+ EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity";
+})(EntityDecoderState || (EntityDecoderState = {}));
+var DecodingMode;
+(function (DecodingMode) {
+ /** Entities in text nodes that can end with any character. */
+ DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy";
+ /** Only allow entities terminated with a semicolon. */
+ DecodingMode[DecodingMode["Strict"] = 1] = "Strict";
+ /** Entities in attributes have limitations on ending characters. */
+ DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute";
+})(DecodingMode || (DecodingMode = {}));
+/**
+ * Token decoder with support of writing partial entities.
+ */
+class EntityDecoder {
+ constructor(
+ /** The tree used to decode entities. */
+ decodeTree,
+ /**
+ * The function that is called when a codepoint is decoded.
+ *
+ * For multi-byte named entities, this will be called multiple times,
+ * with the second codepoint, and the same `consumed` value.
+ *
+ * @param codepoint The decoded codepoint.
+ * @param consumed The number of bytes consumed by the decoder.
+ */
+ emitCodePoint,
+ /** An object that is used to produce errors. */
+ errors) {
+ this.decodeTree = decodeTree;
+ this.emitCodePoint = emitCodePoint;
+ this.errors = errors;
+ /** The current state of the decoder. */
+ this.state = EntityDecoderState.EntityStart;
+ /** Characters that were consumed while parsing an entity. */
+ this.consumed = 1;
+ /**
+ * The result of the entity.
+ *
+ * Either the result index of a numeric entity, or the codepoint of a
+ * numeric entity.
+ */
+ this.result = 0;
+ /** The current index in the decode tree. */
+ this.treeIndex = 0;
+ /** The number of characters that were consumed in excess. */
+ this.excess = 1;
+ /** The mode in which the decoder is operating. */
+ this.decodeMode = DecodingMode.Strict;
+ }
+ /** Resets the instance to make it reusable. */
+ startEntity(decodeMode) {
+ this.decodeMode = decodeMode;
+ this.state = EntityDecoderState.EntityStart;
+ this.result = 0;
+ this.treeIndex = 0;
+ this.excess = 1;
+ this.consumed = 1;
+ }
+ /**
+ * Write an entity to the decoder. This can be called multiple times with partial entities.
+ * If the entity is incomplete, the decoder will return -1.
+ *
+ * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
+ * entity is incomplete, and resume when the next string is written.
+ *
+ * @param string The string containing the entity (or a continuation of the entity).
+ * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ write(str, offset) {
+ switch (this.state) {
+ case EntityDecoderState.EntityStart: {
+ if (str.charCodeAt(offset) === CharCodes.NUM) {
+ this.state = EntityDecoderState.NumericStart;
+ this.consumed += 1;
+ return this.stateNumericStart(str, offset + 1);
+ }
+ this.state = EntityDecoderState.NamedEntity;
+ return this.stateNamedEntity(str, offset);
+ }
+ case EntityDecoderState.NumericStart: {
+ return this.stateNumericStart(str, offset);
+ }
+ case EntityDecoderState.NumericDecimal: {
+ return this.stateNumericDecimal(str, offset);
+ }
+ case EntityDecoderState.NumericHex: {
+ return this.stateNumericHex(str, offset);
+ }
+ case EntityDecoderState.NamedEntity: {
+ return this.stateNamedEntity(str, offset);
+ }
+ }
+ }
+ /**
+ * Switches between the numeric decimal and hexadecimal states.
+ *
+ * Equivalent to the `Numeric character reference state` in the HTML spec.
+ *
+ * @param str The string containing the entity (or a continuation of the entity).
+ * @param offset The current offset.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ stateNumericStart(str, offset) {
+ if (offset >= str.length) {
+ return -1;
+ }
+ if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
+ this.state = EntityDecoderState.NumericHex;
+ this.consumed += 1;
+ return this.stateNumericHex(str, offset + 1);
+ }
+ this.state = EntityDecoderState.NumericDecimal;
+ return this.stateNumericDecimal(str, offset);
+ }
+ addToNumericResult(str, start, end, base) {
+ if (start !== end) {
+ const digitCount = end - start;
+ this.result =
+ this.result * Math.pow(base, digitCount) +
+ parseInt(str.substr(start, digitCount), base);
+ this.consumed += digitCount;
+ }
+ }
+ /**
+ * Parses a hexadecimal numeric entity.
+ *
+ * Equivalent to the `Hexademical character reference state` in the HTML spec.
+ *
+ * @param str The string containing the entity (or a continuation of the entity).
+ * @param offset The current offset.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ stateNumericHex(str, offset) {
+ const startIdx = offset;
+ while (offset < str.length) {
+ const char = str.charCodeAt(offset);
+ if (isNumber(char) || isHexadecimalCharacter(char)) {
+ offset += 1;
+ }
+ else {
+ this.addToNumericResult(str, startIdx, offset, 16);
+ return this.emitNumericEntity(char, 3);
+ }
+ }
+ this.addToNumericResult(str, startIdx, offset, 16);
+ return -1;
+ }
+ /**
+ * Parses a decimal numeric entity.
+ *
+ * Equivalent to the `Decimal character reference state` in the HTML spec.
+ *
+ * @param str The string containing the entity (or a continuation of the entity).
+ * @param offset The current offset.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ stateNumericDecimal(str, offset) {
+ const startIdx = offset;
+ while (offset < str.length) {
+ const char = str.charCodeAt(offset);
+ if (isNumber(char)) {
+ offset += 1;
+ }
+ else {
+ this.addToNumericResult(str, startIdx, offset, 10);
+ return this.emitNumericEntity(char, 2);
+ }
+ }
+ this.addToNumericResult(str, startIdx, offset, 10);
+ return -1;
+ }
+ /**
+ * Validate and emit a numeric entity.
+ *
+ * Implements the logic from the `Hexademical character reference start
+ * state` and `Numeric character reference end state` in the HTML spec.
+ *
+ * @param lastCp The last code point of the entity. Used to see if the
+ * entity was terminated with a semicolon.
+ * @param expectedLength The minimum number of characters that should be
+ * consumed. Used to validate that at least one digit
+ * was consumed.
+ * @returns The number of characters that were consumed.
+ */
+ emitNumericEntity(lastCp, expectedLength) {
+ var _a;
+ // Ensure we consumed at least one digit.
+ if (this.consumed <= expectedLength) {
+ (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
+ return 0;
+ }
+ // Figure out if this is a legit end of the entity
+ if (lastCp === CharCodes.SEMI) {
+ this.consumed += 1;
+ }
+ else if (this.decodeMode === DecodingMode.Strict) {
+ return 0;
+ }
+ this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
+ if (this.errors) {
+ if (lastCp !== CharCodes.SEMI) {
+ this.errors.missingSemicolonAfterCharacterReference();
+ }
+ this.errors.validateNumericCharacterReference(this.result);
+ }
+ return this.consumed;
+ }
+ /**
+ * Parses a named entity.
+ *
+ * Equivalent to the `Named character reference state` in the HTML spec.
+ *
+ * @param str The string containing the entity (or a continuation of the entity).
+ * @param offset The current offset.
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
+ */
+ stateNamedEntity(str, offset) {
+ const { decodeTree } = this;
+ let current = decodeTree[this.treeIndex];
+ // The mask is the number of bytes of the value, including the current byte.
+ let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
+ for (; offset < str.length; offset++, this.excess++) {
+ const char = str.charCodeAt(offset);
+ this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
+ if (this.treeIndex < 0) {
+ return this.result === 0 ||
+ // If we are parsing an attribute
+ (this.decodeMode === DecodingMode.Attribute &&
+ // We shouldn't have consumed any characters after the entity,
+ (valueLength === 0 ||
+ // And there should be no invalid characters.
+ isEntityInAttributeInvalidEnd(char)))
+ ? 0
+ : this.emitNotTerminatedNamedEntity();
+ }
+ current = decodeTree[this.treeIndex];
+ valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
+ // If the branch is a value, store it and continue
+ if (valueLength !== 0) {
+ // If the entity is terminated by a semicolon, we are done.
+ if (char === CharCodes.SEMI) {
+ return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
+ }
+ // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it.
+ if (this.decodeMode !== DecodingMode.Strict) {
+ this.result = this.treeIndex;
+ this.consumed += this.excess;
+ this.excess = 0;
+ }
+ }
+ }
+ return -1;
+ }
+ /**
+ * Emit a named entity that was not terminated with a semicolon.
+ *
+ * @returns The number of characters consumed.
+ */
+ emitNotTerminatedNamedEntity() {
+ var _a;
+ const { result, decodeTree } = this;
+ const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
+ this.emitNamedEntityData(result, valueLength, this.consumed);
+ (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference();
+ return this.consumed;
+ }
+ /**
+ * Emit a named entity.
+ *
+ * @param result The index of the entity in the decode tree.
+ * @param valueLength The number of bytes in the entity.
+ * @param consumed The number of characters consumed.
+ *
+ * @returns The number of characters consumed.
+ */
+ emitNamedEntityData(result, valueLength, consumed) {
+ const { decodeTree } = this;
+ this.emitCodePoint(valueLength === 1
+ ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH
+ : decodeTree[result + 1], consumed);
+ if (valueLength === 3) {
+ // For multi-byte values, we need to emit the second byte.
+ this.emitCodePoint(decodeTree[result + 2], consumed);
+ }
+ return consumed;
+ }
+ /**
+ * Signal to the parser that the end of the input was reached.
+ *
+ * Remaining data will be emitted and relevant errors will be produced.
+ *
+ * @returns The number of characters consumed.
+ */
+ end() {
+ var _a;
+ switch (this.state) {
+ case EntityDecoderState.NamedEntity: {
+ // Emit a named entity if we have one.
+ return this.result !== 0 &&
+ (this.decodeMode !== DecodingMode.Attribute ||
+ this.result === this.treeIndex)
+ ? this.emitNotTerminatedNamedEntity()
+ : 0;
+ }
+ // Otherwise, emit a numeric entity if we have one.
+ case EntityDecoderState.NumericDecimal: {
+ return this.emitNumericEntity(0, 2);
+ }
+ case EntityDecoderState.NumericHex: {
+ return this.emitNumericEntity(0, 3);
+ }
+ case EntityDecoderState.NumericStart: {
+ (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
+ return 0;
+ }
+ case EntityDecoderState.EntityStart: {
+ // Return 0 if we have no entity.
+ return 0;
+ }
+ }
+ }
+}
+/**
+ * Creates a function that decodes entities in a string.
+ *
+ * @param decodeTree The decode tree.
+ * @returns A function that decodes entities in a string.
+ */
+function getDecoder(decodeTree) {
+ let ret = "";
+ const decoder = new EntityDecoder(decodeTree, (str) => (ret += fromCodePoint(str)));
+ return function decodeWithTrie(str, decodeMode) {
+ let lastIndex = 0;
+ let offset = 0;
+ while ((offset = str.indexOf("&", offset)) >= 0) {
+ ret += str.slice(lastIndex, offset);
+ decoder.startEntity(decodeMode);
+ const len = decoder.write(str,
+ // Skip the "&"
+ offset + 1);
+ if (len < 0) {
+ lastIndex = offset + decoder.end();
+ break;
+ }
+ lastIndex = offset + len;
+ // If `len` is 0, skip the current `&` and continue.
+ offset = len === 0 ? lastIndex + 1 : lastIndex;
+ }
+ const result = ret + str.slice(lastIndex);
+ // Make sure we don't keep a reference to the final string.
+ ret = "";
+ return result;
+ };
+}
+/**
+ * Determines the branch of the current node that is taken given the current
+ * character. This function is used to traverse the trie.
+ *
+ * @param decodeTree The trie.
+ * @param current The current node.
+ * @param nodeIdx The index right after the current node and its value.
+ * @param char The current character.
+ * @returns The index of the next node, or -1 if no branch is taken.
+ */
+function determineBranch(decodeTree, current, nodeIdx, char) {
+ const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
+ const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
+ // Case 1: Single branch encoded in jump offset
+ if (branchCount === 0) {
+ return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
+ }
+ // Case 2: Multiple branches encoded in jump table
+ if (jumpOffset) {
+ const value = char - jumpOffset;
+ return value < 0 || value >= branchCount
+ ? -1
+ : decodeTree[nodeIdx + value] - 1;
+ }
+ // Case 3: Multiple branches encoded in dictionary
+ // Binary search for the character.
+ let lo = nodeIdx;
+ let hi = lo + branchCount - 1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >>> 1;
+ const midVal = decodeTree[mid];
+ if (midVal < char) {
+ lo = mid + 1;
+ }
+ else if (midVal > char) {
+ hi = mid - 1;
+ }
+ else {
+ return decodeTree[mid + branchCount];
+ }
+ }
+ return -1;
+}
+const htmlDecoder = getDecoder(decode_data_html);
+const xmlDecoder = getDecoder(decode_data_xml);
+/**
+ * Decodes an HTML string.
+ *
+ * @param str The string to decode.
+ * @param mode The decoding mode.
+ * @returns The decoded string.
+ */
+function decodeHTML(str, mode = DecodingMode.Legacy) {
+ return htmlDecoder(str, mode);
+}
+/**
+ * Decodes an HTML string in an attribute.
+ *
+ * @param str The string to decode.
+ * @returns The decoded string.
+ */
+function decodeHTMLAttribute(str) {
+ return htmlDecoder(str, DecodingMode.Attribute);
+}
+/**
+ * Decodes an HTML string, requiring all entities to be terminated by a semicolon.
+ *
+ * @param str The string to decode.
+ * @returns The decoded string.
+ */
+function decodeHTMLStrict(str) {
+ return htmlDecoder(str, DecodingMode.Strict);
+}
+/**
+ * Decodes an XML string, requiring all entities to be terminated by a semicolon.
+ *
+ * @param str The string to decode.
+ * @returns The decoded string.
+ */
+function decodeXML(str) {
+ return xmlDecoder(str, DecodingMode.Strict);
+}
+//# sourceMappingURL=decode.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/common/html.js
+/** All valid namespaces in HTML. */
+var html_NS;
+(function (NS) {
+ NS["HTML"] = "http://www.w3.org/1999/xhtml";
+ NS["MATHML"] = "http://www.w3.org/1998/Math/MathML";
+ NS["SVG"] = "http://www.w3.org/2000/svg";
+ NS["XLINK"] = "http://www.w3.org/1999/xlink";
+ NS["XML"] = "http://www.w3.org/XML/1998/namespace";
+ NS["XMLNS"] = "http://www.w3.org/2000/xmlns/";
+})(html_NS = html_NS || (html_NS = {}));
+var html_ATTRS;
+(function (ATTRS) {
+ ATTRS["TYPE"] = "type";
+ ATTRS["ACTION"] = "action";
+ ATTRS["ENCODING"] = "encoding";
+ ATTRS["PROMPT"] = "prompt";
+ ATTRS["NAME"] = "name";
+ ATTRS["COLOR"] = "color";
+ ATTRS["FACE"] = "face";
+ ATTRS["SIZE"] = "size";
+})(html_ATTRS = html_ATTRS || (html_ATTRS = {}));
+/**
+ * The mode of the document.
+ *
+ * @see {@link https://dom.spec.whatwg.org/#concept-document-limited-quirks}
+ */
+var html_DOCUMENT_MODE;
+(function (DOCUMENT_MODE) {
+ DOCUMENT_MODE["NO_QUIRKS"] = "no-quirks";
+ DOCUMENT_MODE["QUIRKS"] = "quirks";
+ DOCUMENT_MODE["LIMITED_QUIRKS"] = "limited-quirks";
+})(html_DOCUMENT_MODE = html_DOCUMENT_MODE || (html_DOCUMENT_MODE = {}));
+var TAG_NAMES;
+(function (TAG_NAMES) {
+ TAG_NAMES["A"] = "a";
+ TAG_NAMES["ADDRESS"] = "address";
+ TAG_NAMES["ANNOTATION_XML"] = "annotation-xml";
+ TAG_NAMES["APPLET"] = "applet";
+ TAG_NAMES["AREA"] = "area";
+ TAG_NAMES["ARTICLE"] = "article";
+ TAG_NAMES["ASIDE"] = "aside";
+ TAG_NAMES["B"] = "b";
+ TAG_NAMES["BASE"] = "base";
+ TAG_NAMES["BASEFONT"] = "basefont";
+ TAG_NAMES["BGSOUND"] = "bgsound";
+ TAG_NAMES["BIG"] = "big";
+ TAG_NAMES["BLOCKQUOTE"] = "blockquote";
+ TAG_NAMES["BODY"] = "body";
+ TAG_NAMES["BR"] = "br";
+ TAG_NAMES["BUTTON"] = "button";
+ TAG_NAMES["CAPTION"] = "caption";
+ TAG_NAMES["CENTER"] = "center";
+ TAG_NAMES["CODE"] = "code";
+ TAG_NAMES["COL"] = "col";
+ TAG_NAMES["COLGROUP"] = "colgroup";
+ TAG_NAMES["DD"] = "dd";
+ TAG_NAMES["DESC"] = "desc";
+ TAG_NAMES["DETAILS"] = "details";
+ TAG_NAMES["DIALOG"] = "dialog";
+ TAG_NAMES["DIR"] = "dir";
+ TAG_NAMES["DIV"] = "div";
+ TAG_NAMES["DL"] = "dl";
+ TAG_NAMES["DT"] = "dt";
+ TAG_NAMES["EM"] = "em";
+ TAG_NAMES["EMBED"] = "embed";
+ TAG_NAMES["FIELDSET"] = "fieldset";
+ TAG_NAMES["FIGCAPTION"] = "figcaption";
+ TAG_NAMES["FIGURE"] = "figure";
+ TAG_NAMES["FONT"] = "font";
+ TAG_NAMES["FOOTER"] = "footer";
+ TAG_NAMES["FOREIGN_OBJECT"] = "foreignObject";
+ TAG_NAMES["FORM"] = "form";
+ TAG_NAMES["FRAME"] = "frame";
+ TAG_NAMES["FRAMESET"] = "frameset";
+ TAG_NAMES["H1"] = "h1";
+ TAG_NAMES["H2"] = "h2";
+ TAG_NAMES["H3"] = "h3";
+ TAG_NAMES["H4"] = "h4";
+ TAG_NAMES["H5"] = "h5";
+ TAG_NAMES["H6"] = "h6";
+ TAG_NAMES["HEAD"] = "head";
+ TAG_NAMES["HEADER"] = "header";
+ TAG_NAMES["HGROUP"] = "hgroup";
+ TAG_NAMES["HR"] = "hr";
+ TAG_NAMES["HTML"] = "html";
+ TAG_NAMES["I"] = "i";
+ TAG_NAMES["IMG"] = "img";
+ TAG_NAMES["IMAGE"] = "image";
+ TAG_NAMES["INPUT"] = "input";
+ TAG_NAMES["IFRAME"] = "iframe";
+ TAG_NAMES["KEYGEN"] = "keygen";
+ TAG_NAMES["LABEL"] = "label";
+ TAG_NAMES["LI"] = "li";
+ TAG_NAMES["LINK"] = "link";
+ TAG_NAMES["LISTING"] = "listing";
+ TAG_NAMES["MAIN"] = "main";
+ TAG_NAMES["MALIGNMARK"] = "malignmark";
+ TAG_NAMES["MARQUEE"] = "marquee";
+ TAG_NAMES["MATH"] = "math";
+ TAG_NAMES["MENU"] = "menu";
+ TAG_NAMES["META"] = "meta";
+ TAG_NAMES["MGLYPH"] = "mglyph";
+ TAG_NAMES["MI"] = "mi";
+ TAG_NAMES["MO"] = "mo";
+ TAG_NAMES["MN"] = "mn";
+ TAG_NAMES["MS"] = "ms";
+ TAG_NAMES["MTEXT"] = "mtext";
+ TAG_NAMES["NAV"] = "nav";
+ TAG_NAMES["NOBR"] = "nobr";
+ TAG_NAMES["NOFRAMES"] = "noframes";
+ TAG_NAMES["NOEMBED"] = "noembed";
+ TAG_NAMES["NOSCRIPT"] = "noscript";
+ TAG_NAMES["OBJECT"] = "object";
+ TAG_NAMES["OL"] = "ol";
+ TAG_NAMES["OPTGROUP"] = "optgroup";
+ TAG_NAMES["OPTION"] = "option";
+ TAG_NAMES["P"] = "p";
+ TAG_NAMES["PARAM"] = "param";
+ TAG_NAMES["PLAINTEXT"] = "plaintext";
+ TAG_NAMES["PRE"] = "pre";
+ TAG_NAMES["RB"] = "rb";
+ TAG_NAMES["RP"] = "rp";
+ TAG_NAMES["RT"] = "rt";
+ TAG_NAMES["RTC"] = "rtc";
+ TAG_NAMES["RUBY"] = "ruby";
+ TAG_NAMES["S"] = "s";
+ TAG_NAMES["SCRIPT"] = "script";
+ TAG_NAMES["SECTION"] = "section";
+ TAG_NAMES["SELECT"] = "select";
+ TAG_NAMES["SOURCE"] = "source";
+ TAG_NAMES["SMALL"] = "small";
+ TAG_NAMES["SPAN"] = "span";
+ TAG_NAMES["STRIKE"] = "strike";
+ TAG_NAMES["STRONG"] = "strong";
+ TAG_NAMES["STYLE"] = "style";
+ TAG_NAMES["SUB"] = "sub";
+ TAG_NAMES["SUMMARY"] = "summary";
+ TAG_NAMES["SUP"] = "sup";
+ TAG_NAMES["TABLE"] = "table";
+ TAG_NAMES["TBODY"] = "tbody";
+ TAG_NAMES["TEMPLATE"] = "template";
+ TAG_NAMES["TEXTAREA"] = "textarea";
+ TAG_NAMES["TFOOT"] = "tfoot";
+ TAG_NAMES["TD"] = "td";
+ TAG_NAMES["TH"] = "th";
+ TAG_NAMES["THEAD"] = "thead";
+ TAG_NAMES["TITLE"] = "title";
+ TAG_NAMES["TR"] = "tr";
+ TAG_NAMES["TRACK"] = "track";
+ TAG_NAMES["TT"] = "tt";
+ TAG_NAMES["U"] = "u";
+ TAG_NAMES["UL"] = "ul";
+ TAG_NAMES["SVG"] = "svg";
+ TAG_NAMES["VAR"] = "var";
+ TAG_NAMES["WBR"] = "wbr";
+ TAG_NAMES["XMP"] = "xmp";
+})(TAG_NAMES = TAG_NAMES || (TAG_NAMES = {}));
+/**
+ * Tag IDs are numeric IDs for known tag names.
+ *
+ * We use tag IDs to improve the performance of tag name comparisons.
+ */
+var TAG_ID;
+(function (TAG_ID) {
+ TAG_ID[TAG_ID["UNKNOWN"] = 0] = "UNKNOWN";
+ TAG_ID[TAG_ID["A"] = 1] = "A";
+ TAG_ID[TAG_ID["ADDRESS"] = 2] = "ADDRESS";
+ TAG_ID[TAG_ID["ANNOTATION_XML"] = 3] = "ANNOTATION_XML";
+ TAG_ID[TAG_ID["APPLET"] = 4] = "APPLET";
+ TAG_ID[TAG_ID["AREA"] = 5] = "AREA";
+ TAG_ID[TAG_ID["ARTICLE"] = 6] = "ARTICLE";
+ TAG_ID[TAG_ID["ASIDE"] = 7] = "ASIDE";
+ TAG_ID[TAG_ID["B"] = 8] = "B";
+ TAG_ID[TAG_ID["BASE"] = 9] = "BASE";
+ TAG_ID[TAG_ID["BASEFONT"] = 10] = "BASEFONT";
+ TAG_ID[TAG_ID["BGSOUND"] = 11] = "BGSOUND";
+ TAG_ID[TAG_ID["BIG"] = 12] = "BIG";
+ TAG_ID[TAG_ID["BLOCKQUOTE"] = 13] = "BLOCKQUOTE";
+ TAG_ID[TAG_ID["BODY"] = 14] = "BODY";
+ TAG_ID[TAG_ID["BR"] = 15] = "BR";
+ TAG_ID[TAG_ID["BUTTON"] = 16] = "BUTTON";
+ TAG_ID[TAG_ID["CAPTION"] = 17] = "CAPTION";
+ TAG_ID[TAG_ID["CENTER"] = 18] = "CENTER";
+ TAG_ID[TAG_ID["CODE"] = 19] = "CODE";
+ TAG_ID[TAG_ID["COL"] = 20] = "COL";
+ TAG_ID[TAG_ID["COLGROUP"] = 21] = "COLGROUP";
+ TAG_ID[TAG_ID["DD"] = 22] = "DD";
+ TAG_ID[TAG_ID["DESC"] = 23] = "DESC";
+ TAG_ID[TAG_ID["DETAILS"] = 24] = "DETAILS";
+ TAG_ID[TAG_ID["DIALOG"] = 25] = "DIALOG";
+ TAG_ID[TAG_ID["DIR"] = 26] = "DIR";
+ TAG_ID[TAG_ID["DIV"] = 27] = "DIV";
+ TAG_ID[TAG_ID["DL"] = 28] = "DL";
+ TAG_ID[TAG_ID["DT"] = 29] = "DT";
+ TAG_ID[TAG_ID["EM"] = 30] = "EM";
+ TAG_ID[TAG_ID["EMBED"] = 31] = "EMBED";
+ TAG_ID[TAG_ID["FIELDSET"] = 32] = "FIELDSET";
+ TAG_ID[TAG_ID["FIGCAPTION"] = 33] = "FIGCAPTION";
+ TAG_ID[TAG_ID["FIGURE"] = 34] = "FIGURE";
+ TAG_ID[TAG_ID["FONT"] = 35] = "FONT";
+ TAG_ID[TAG_ID["FOOTER"] = 36] = "FOOTER";
+ TAG_ID[TAG_ID["FOREIGN_OBJECT"] = 37] = "FOREIGN_OBJECT";
+ TAG_ID[TAG_ID["FORM"] = 38] = "FORM";
+ TAG_ID[TAG_ID["FRAME"] = 39] = "FRAME";
+ TAG_ID[TAG_ID["FRAMESET"] = 40] = "FRAMESET";
+ TAG_ID[TAG_ID["H1"] = 41] = "H1";
+ TAG_ID[TAG_ID["H2"] = 42] = "H2";
+ TAG_ID[TAG_ID["H3"] = 43] = "H3";
+ TAG_ID[TAG_ID["H4"] = 44] = "H4";
+ TAG_ID[TAG_ID["H5"] = 45] = "H5";
+ TAG_ID[TAG_ID["H6"] = 46] = "H6";
+ TAG_ID[TAG_ID["HEAD"] = 47] = "HEAD";
+ TAG_ID[TAG_ID["HEADER"] = 48] = "HEADER";
+ TAG_ID[TAG_ID["HGROUP"] = 49] = "HGROUP";
+ TAG_ID[TAG_ID["HR"] = 50] = "HR";
+ TAG_ID[TAG_ID["HTML"] = 51] = "HTML";
+ TAG_ID[TAG_ID["I"] = 52] = "I";
+ TAG_ID[TAG_ID["IMG"] = 53] = "IMG";
+ TAG_ID[TAG_ID["IMAGE"] = 54] = "IMAGE";
+ TAG_ID[TAG_ID["INPUT"] = 55] = "INPUT";
+ TAG_ID[TAG_ID["IFRAME"] = 56] = "IFRAME";
+ TAG_ID[TAG_ID["KEYGEN"] = 57] = "KEYGEN";
+ TAG_ID[TAG_ID["LABEL"] = 58] = "LABEL";
+ TAG_ID[TAG_ID["LI"] = 59] = "LI";
+ TAG_ID[TAG_ID["LINK"] = 60] = "LINK";
+ TAG_ID[TAG_ID["LISTING"] = 61] = "LISTING";
+ TAG_ID[TAG_ID["MAIN"] = 62] = "MAIN";
+ TAG_ID[TAG_ID["MALIGNMARK"] = 63] = "MALIGNMARK";
+ TAG_ID[TAG_ID["MARQUEE"] = 64] = "MARQUEE";
+ TAG_ID[TAG_ID["MATH"] = 65] = "MATH";
+ TAG_ID[TAG_ID["MENU"] = 66] = "MENU";
+ TAG_ID[TAG_ID["META"] = 67] = "META";
+ TAG_ID[TAG_ID["MGLYPH"] = 68] = "MGLYPH";
+ TAG_ID[TAG_ID["MI"] = 69] = "MI";
+ TAG_ID[TAG_ID["MO"] = 70] = "MO";
+ TAG_ID[TAG_ID["MN"] = 71] = "MN";
+ TAG_ID[TAG_ID["MS"] = 72] = "MS";
+ TAG_ID[TAG_ID["MTEXT"] = 73] = "MTEXT";
+ TAG_ID[TAG_ID["NAV"] = 74] = "NAV";
+ TAG_ID[TAG_ID["NOBR"] = 75] = "NOBR";
+ TAG_ID[TAG_ID["NOFRAMES"] = 76] = "NOFRAMES";
+ TAG_ID[TAG_ID["NOEMBED"] = 77] = "NOEMBED";
+ TAG_ID[TAG_ID["NOSCRIPT"] = 78] = "NOSCRIPT";
+ TAG_ID[TAG_ID["OBJECT"] = 79] = "OBJECT";
+ TAG_ID[TAG_ID["OL"] = 80] = "OL";
+ TAG_ID[TAG_ID["OPTGROUP"] = 81] = "OPTGROUP";
+ TAG_ID[TAG_ID["OPTION"] = 82] = "OPTION";
+ TAG_ID[TAG_ID["P"] = 83] = "P";
+ TAG_ID[TAG_ID["PARAM"] = 84] = "PARAM";
+ TAG_ID[TAG_ID["PLAINTEXT"] = 85] = "PLAINTEXT";
+ TAG_ID[TAG_ID["PRE"] = 86] = "PRE";
+ TAG_ID[TAG_ID["RB"] = 87] = "RB";
+ TAG_ID[TAG_ID["RP"] = 88] = "RP";
+ TAG_ID[TAG_ID["RT"] = 89] = "RT";
+ TAG_ID[TAG_ID["RTC"] = 90] = "RTC";
+ TAG_ID[TAG_ID["RUBY"] = 91] = "RUBY";
+ TAG_ID[TAG_ID["S"] = 92] = "S";
+ TAG_ID[TAG_ID["SCRIPT"] = 93] = "SCRIPT";
+ TAG_ID[TAG_ID["SECTION"] = 94] = "SECTION";
+ TAG_ID[TAG_ID["SELECT"] = 95] = "SELECT";
+ TAG_ID[TAG_ID["SOURCE"] = 96] = "SOURCE";
+ TAG_ID[TAG_ID["SMALL"] = 97] = "SMALL";
+ TAG_ID[TAG_ID["SPAN"] = 98] = "SPAN";
+ TAG_ID[TAG_ID["STRIKE"] = 99] = "STRIKE";
+ TAG_ID[TAG_ID["STRONG"] = 100] = "STRONG";
+ TAG_ID[TAG_ID["STYLE"] = 101] = "STYLE";
+ TAG_ID[TAG_ID["SUB"] = 102] = "SUB";
+ TAG_ID[TAG_ID["SUMMARY"] = 103] = "SUMMARY";
+ TAG_ID[TAG_ID["SUP"] = 104] = "SUP";
+ TAG_ID[TAG_ID["TABLE"] = 105] = "TABLE";
+ TAG_ID[TAG_ID["TBODY"] = 106] = "TBODY";
+ TAG_ID[TAG_ID["TEMPLATE"] = 107] = "TEMPLATE";
+ TAG_ID[TAG_ID["TEXTAREA"] = 108] = "TEXTAREA";
+ TAG_ID[TAG_ID["TFOOT"] = 109] = "TFOOT";
+ TAG_ID[TAG_ID["TD"] = 110] = "TD";
+ TAG_ID[TAG_ID["TH"] = 111] = "TH";
+ TAG_ID[TAG_ID["THEAD"] = 112] = "THEAD";
+ TAG_ID[TAG_ID["TITLE"] = 113] = "TITLE";
+ TAG_ID[TAG_ID["TR"] = 114] = "TR";
+ TAG_ID[TAG_ID["TRACK"] = 115] = "TRACK";
+ TAG_ID[TAG_ID["TT"] = 116] = "TT";
+ TAG_ID[TAG_ID["U"] = 117] = "U";
+ TAG_ID[TAG_ID["UL"] = 118] = "UL";
+ TAG_ID[TAG_ID["SVG"] = 119] = "SVG";
+ TAG_ID[TAG_ID["VAR"] = 120] = "VAR";
+ TAG_ID[TAG_ID["WBR"] = 121] = "WBR";
+ TAG_ID[TAG_ID["XMP"] = 122] = "XMP";
+})(TAG_ID = TAG_ID || (TAG_ID = {}));
+const TAG_NAME_TO_ID = new Map([
+ [TAG_NAMES.A, TAG_ID.A],
+ [TAG_NAMES.ADDRESS, TAG_ID.ADDRESS],
+ [TAG_NAMES.ANNOTATION_XML, TAG_ID.ANNOTATION_XML],
+ [TAG_NAMES.APPLET, TAG_ID.APPLET],
+ [TAG_NAMES.AREA, TAG_ID.AREA],
+ [TAG_NAMES.ARTICLE, TAG_ID.ARTICLE],
+ [TAG_NAMES.ASIDE, TAG_ID.ASIDE],
+ [TAG_NAMES.B, TAG_ID.B],
+ [TAG_NAMES.BASE, TAG_ID.BASE],
+ [TAG_NAMES.BASEFONT, TAG_ID.BASEFONT],
+ [TAG_NAMES.BGSOUND, TAG_ID.BGSOUND],
+ [TAG_NAMES.BIG, TAG_ID.BIG],
+ [TAG_NAMES.BLOCKQUOTE, TAG_ID.BLOCKQUOTE],
+ [TAG_NAMES.BODY, TAG_ID.BODY],
+ [TAG_NAMES.BR, TAG_ID.BR],
+ [TAG_NAMES.BUTTON, TAG_ID.BUTTON],
+ [TAG_NAMES.CAPTION, TAG_ID.CAPTION],
+ [TAG_NAMES.CENTER, TAG_ID.CENTER],
+ [TAG_NAMES.CODE, TAG_ID.CODE],
+ [TAG_NAMES.COL, TAG_ID.COL],
+ [TAG_NAMES.COLGROUP, TAG_ID.COLGROUP],
+ [TAG_NAMES.DD, TAG_ID.DD],
+ [TAG_NAMES.DESC, TAG_ID.DESC],
+ [TAG_NAMES.DETAILS, TAG_ID.DETAILS],
+ [TAG_NAMES.DIALOG, TAG_ID.DIALOG],
+ [TAG_NAMES.DIR, TAG_ID.DIR],
+ [TAG_NAMES.DIV, TAG_ID.DIV],
+ [TAG_NAMES.DL, TAG_ID.DL],
+ [TAG_NAMES.DT, TAG_ID.DT],
+ [TAG_NAMES.EM, TAG_ID.EM],
+ [TAG_NAMES.EMBED, TAG_ID.EMBED],
+ [TAG_NAMES.FIELDSET, TAG_ID.FIELDSET],
+ [TAG_NAMES.FIGCAPTION, TAG_ID.FIGCAPTION],
+ [TAG_NAMES.FIGURE, TAG_ID.FIGURE],
+ [TAG_NAMES.FONT, TAG_ID.FONT],
+ [TAG_NAMES.FOOTER, TAG_ID.FOOTER],
+ [TAG_NAMES.FOREIGN_OBJECT, TAG_ID.FOREIGN_OBJECT],
+ [TAG_NAMES.FORM, TAG_ID.FORM],
+ [TAG_NAMES.FRAME, TAG_ID.FRAME],
+ [TAG_NAMES.FRAMESET, TAG_ID.FRAMESET],
+ [TAG_NAMES.H1, TAG_ID.H1],
+ [TAG_NAMES.H2, TAG_ID.H2],
+ [TAG_NAMES.H3, TAG_ID.H3],
+ [TAG_NAMES.H4, TAG_ID.H4],
+ [TAG_NAMES.H5, TAG_ID.H5],
+ [TAG_NAMES.H6, TAG_ID.H6],
+ [TAG_NAMES.HEAD, TAG_ID.HEAD],
+ [TAG_NAMES.HEADER, TAG_ID.HEADER],
+ [TAG_NAMES.HGROUP, TAG_ID.HGROUP],
+ [TAG_NAMES.HR, TAG_ID.HR],
+ [TAG_NAMES.HTML, TAG_ID.HTML],
+ [TAG_NAMES.I, TAG_ID.I],
+ [TAG_NAMES.IMG, TAG_ID.IMG],
+ [TAG_NAMES.IMAGE, TAG_ID.IMAGE],
+ [TAG_NAMES.INPUT, TAG_ID.INPUT],
+ [TAG_NAMES.IFRAME, TAG_ID.IFRAME],
+ [TAG_NAMES.KEYGEN, TAG_ID.KEYGEN],
+ [TAG_NAMES.LABEL, TAG_ID.LABEL],
+ [TAG_NAMES.LI, TAG_ID.LI],
+ [TAG_NAMES.LINK, TAG_ID.LINK],
+ [TAG_NAMES.LISTING, TAG_ID.LISTING],
+ [TAG_NAMES.MAIN, TAG_ID.MAIN],
+ [TAG_NAMES.MALIGNMARK, TAG_ID.MALIGNMARK],
+ [TAG_NAMES.MARQUEE, TAG_ID.MARQUEE],
+ [TAG_NAMES.MATH, TAG_ID.MATH],
+ [TAG_NAMES.MENU, TAG_ID.MENU],
+ [TAG_NAMES.META, TAG_ID.META],
+ [TAG_NAMES.MGLYPH, TAG_ID.MGLYPH],
+ [TAG_NAMES.MI, TAG_ID.MI],
+ [TAG_NAMES.MO, TAG_ID.MO],
+ [TAG_NAMES.MN, TAG_ID.MN],
+ [TAG_NAMES.MS, TAG_ID.MS],
+ [TAG_NAMES.MTEXT, TAG_ID.MTEXT],
+ [TAG_NAMES.NAV, TAG_ID.NAV],
+ [TAG_NAMES.NOBR, TAG_ID.NOBR],
+ [TAG_NAMES.NOFRAMES, TAG_ID.NOFRAMES],
+ [TAG_NAMES.NOEMBED, TAG_ID.NOEMBED],
+ [TAG_NAMES.NOSCRIPT, TAG_ID.NOSCRIPT],
+ [TAG_NAMES.OBJECT, TAG_ID.OBJECT],
+ [TAG_NAMES.OL, TAG_ID.OL],
+ [TAG_NAMES.OPTGROUP, TAG_ID.OPTGROUP],
+ [TAG_NAMES.OPTION, TAG_ID.OPTION],
+ [TAG_NAMES.P, TAG_ID.P],
+ [TAG_NAMES.PARAM, TAG_ID.PARAM],
+ [TAG_NAMES.PLAINTEXT, TAG_ID.PLAINTEXT],
+ [TAG_NAMES.PRE, TAG_ID.PRE],
+ [TAG_NAMES.RB, TAG_ID.RB],
+ [TAG_NAMES.RP, TAG_ID.RP],
+ [TAG_NAMES.RT, TAG_ID.RT],
+ [TAG_NAMES.RTC, TAG_ID.RTC],
+ [TAG_NAMES.RUBY, TAG_ID.RUBY],
+ [TAG_NAMES.S, TAG_ID.S],
+ [TAG_NAMES.SCRIPT, TAG_ID.SCRIPT],
+ [TAG_NAMES.SECTION, TAG_ID.SECTION],
+ [TAG_NAMES.SELECT, TAG_ID.SELECT],
+ [TAG_NAMES.SOURCE, TAG_ID.SOURCE],
+ [TAG_NAMES.SMALL, TAG_ID.SMALL],
+ [TAG_NAMES.SPAN, TAG_ID.SPAN],
+ [TAG_NAMES.STRIKE, TAG_ID.STRIKE],
+ [TAG_NAMES.STRONG, TAG_ID.STRONG],
+ [TAG_NAMES.STYLE, TAG_ID.STYLE],
+ [TAG_NAMES.SUB, TAG_ID.SUB],
+ [TAG_NAMES.SUMMARY, TAG_ID.SUMMARY],
+ [TAG_NAMES.SUP, TAG_ID.SUP],
+ [TAG_NAMES.TABLE, TAG_ID.TABLE],
+ [TAG_NAMES.TBODY, TAG_ID.TBODY],
+ [TAG_NAMES.TEMPLATE, TAG_ID.TEMPLATE],
+ [TAG_NAMES.TEXTAREA, TAG_ID.TEXTAREA],
+ [TAG_NAMES.TFOOT, TAG_ID.TFOOT],
+ [TAG_NAMES.TD, TAG_ID.TD],
+ [TAG_NAMES.TH, TAG_ID.TH],
+ [TAG_NAMES.THEAD, TAG_ID.THEAD],
+ [TAG_NAMES.TITLE, TAG_ID.TITLE],
+ [TAG_NAMES.TR, TAG_ID.TR],
+ [TAG_NAMES.TRACK, TAG_ID.TRACK],
+ [TAG_NAMES.TT, TAG_ID.TT],
+ [TAG_NAMES.U, TAG_ID.U],
+ [TAG_NAMES.UL, TAG_ID.UL],
+ [TAG_NAMES.SVG, TAG_ID.SVG],
+ [TAG_NAMES.VAR, TAG_ID.VAR],
+ [TAG_NAMES.WBR, TAG_ID.WBR],
+ [TAG_NAMES.XMP, TAG_ID.XMP],
+]);
+function html_getTagID(tagName) {
+ var _a;
+ return (_a = TAG_NAME_TO_ID.get(tagName)) !== null && _a !== void 0 ? _a : TAG_ID.UNKNOWN;
+}
+const html_$ = TAG_ID;
+const html_SPECIAL_ELEMENTS = {
+ [html_NS.HTML]: new Set([
+ html_$.ADDRESS,
+ html_$.APPLET,
+ html_$.AREA,
+ html_$.ARTICLE,
+ html_$.ASIDE,
+ html_$.BASE,
+ html_$.BASEFONT,
+ html_$.BGSOUND,
+ html_$.BLOCKQUOTE,
+ html_$.BODY,
+ html_$.BR,
+ html_$.BUTTON,
+ html_$.CAPTION,
+ html_$.CENTER,
+ html_$.COL,
+ html_$.COLGROUP,
+ html_$.DD,
+ html_$.DETAILS,
+ html_$.DIR,
+ html_$.DIV,
+ html_$.DL,
+ html_$.DT,
+ html_$.EMBED,
+ html_$.FIELDSET,
+ html_$.FIGCAPTION,
+ html_$.FIGURE,
+ html_$.FOOTER,
+ html_$.FORM,
+ html_$.FRAME,
+ html_$.FRAMESET,
+ html_$.H1,
+ html_$.H2,
+ html_$.H3,
+ html_$.H4,
+ html_$.H5,
+ html_$.H6,
+ html_$.HEAD,
+ html_$.HEADER,
+ html_$.HGROUP,
+ html_$.HR,
+ html_$.HTML,
+ html_$.IFRAME,
+ html_$.IMG,
+ html_$.INPUT,
+ html_$.LI,
+ html_$.LINK,
+ html_$.LISTING,
+ html_$.MAIN,
+ html_$.MARQUEE,
+ html_$.MENU,
+ html_$.META,
+ html_$.NAV,
+ html_$.NOEMBED,
+ html_$.NOFRAMES,
+ html_$.NOSCRIPT,
+ html_$.OBJECT,
+ html_$.OL,
+ html_$.P,
+ html_$.PARAM,
+ html_$.PLAINTEXT,
+ html_$.PRE,
+ html_$.SCRIPT,
+ html_$.SECTION,
+ html_$.SELECT,
+ html_$.SOURCE,
+ html_$.STYLE,
+ html_$.SUMMARY,
+ html_$.TABLE,
+ html_$.TBODY,
+ html_$.TD,
+ html_$.TEMPLATE,
+ html_$.TEXTAREA,
+ html_$.TFOOT,
+ html_$.TH,
+ html_$.THEAD,
+ html_$.TITLE,
+ html_$.TR,
+ html_$.TRACK,
+ html_$.UL,
+ html_$.WBR,
+ html_$.XMP,
+ ]),
+ [html_NS.MATHML]: new Set([html_$.MI, html_$.MO, html_$.MN, html_$.MS, html_$.MTEXT, html_$.ANNOTATION_XML]),
+ [html_NS.SVG]: new Set([html_$.TITLE, html_$.FOREIGN_OBJECT, html_$.DESC]),
+ [html_NS.XLINK]: new Set(),
+ [html_NS.XML]: new Set(),
+ [html_NS.XMLNS]: new Set(),
+};
+function html_isNumberedHeader(tn) {
+ return tn === html_$.H1 || tn === html_$.H2 || tn === html_$.H3 || tn === html_$.H4 || tn === html_$.H5 || tn === html_$.H6;
+}
+const UNESCAPED_TEXT = new Set([
+ TAG_NAMES.STYLE,
+ TAG_NAMES.SCRIPT,
+ TAG_NAMES.XMP,
+ TAG_NAMES.IFRAME,
+ TAG_NAMES.NOEMBED,
+ TAG_NAMES.NOFRAMES,
+ TAG_NAMES.PLAINTEXT,
+]);
+function html_hasUnescapedText(tn, scriptingEnabled) {
+ return UNESCAPED_TEXT.has(tn) || (scriptingEnabled && tn === TAG_NAMES.NOSCRIPT);
+}
+//# sourceMappingURL=html.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/tokenizer/index.js
+
+
+
+
+
+
+//C1 Unicode control character reference replacements
+const C1_CONTROLS_REFERENCE_REPLACEMENTS = new Map([
+ [0x80, 8364],
+ [0x82, 8218],
+ [0x83, 402],
+ [0x84, 8222],
+ [0x85, 8230],
+ [0x86, 8224],
+ [0x87, 8225],
+ [0x88, 710],
+ [0x89, 8240],
+ [0x8a, 352],
+ [0x8b, 8249],
+ [0x8c, 338],
+ [0x8e, 381],
+ [0x91, 8216],
+ [0x92, 8217],
+ [0x93, 8220],
+ [0x94, 8221],
+ [0x95, 8226],
+ [0x96, 8211],
+ [0x97, 8212],
+ [0x98, 732],
+ [0x99, 8482],
+ [0x9a, 353],
+ [0x9b, 8250],
+ [0x9c, 339],
+ [0x9e, 382],
+ [0x9f, 376],
+]);
+//States
+var State;
+(function (State) {
+ State[State["DATA"] = 0] = "DATA";
+ State[State["RCDATA"] = 1] = "RCDATA";
+ State[State["RAWTEXT"] = 2] = "RAWTEXT";
+ State[State["SCRIPT_DATA"] = 3] = "SCRIPT_DATA";
+ State[State["PLAINTEXT"] = 4] = "PLAINTEXT";
+ State[State["TAG_OPEN"] = 5] = "TAG_OPEN";
+ State[State["END_TAG_OPEN"] = 6] = "END_TAG_OPEN";
+ State[State["TAG_NAME"] = 7] = "TAG_NAME";
+ State[State["RCDATA_LESS_THAN_SIGN"] = 8] = "RCDATA_LESS_THAN_SIGN";
+ State[State["RCDATA_END_TAG_OPEN"] = 9] = "RCDATA_END_TAG_OPEN";
+ State[State["RCDATA_END_TAG_NAME"] = 10] = "RCDATA_END_TAG_NAME";
+ State[State["RAWTEXT_LESS_THAN_SIGN"] = 11] = "RAWTEXT_LESS_THAN_SIGN";
+ State[State["RAWTEXT_END_TAG_OPEN"] = 12] = "RAWTEXT_END_TAG_OPEN";
+ State[State["RAWTEXT_END_TAG_NAME"] = 13] = "RAWTEXT_END_TAG_NAME";
+ State[State["SCRIPT_DATA_LESS_THAN_SIGN"] = 14] = "SCRIPT_DATA_LESS_THAN_SIGN";
+ State[State["SCRIPT_DATA_END_TAG_OPEN"] = 15] = "SCRIPT_DATA_END_TAG_OPEN";
+ State[State["SCRIPT_DATA_END_TAG_NAME"] = 16] = "SCRIPT_DATA_END_TAG_NAME";
+ State[State["SCRIPT_DATA_ESCAPE_START"] = 17] = "SCRIPT_DATA_ESCAPE_START";
+ State[State["SCRIPT_DATA_ESCAPE_START_DASH"] = 18] = "SCRIPT_DATA_ESCAPE_START_DASH";
+ State[State["SCRIPT_DATA_ESCAPED"] = 19] = "SCRIPT_DATA_ESCAPED";
+ State[State["SCRIPT_DATA_ESCAPED_DASH"] = 20] = "SCRIPT_DATA_ESCAPED_DASH";
+ State[State["SCRIPT_DATA_ESCAPED_DASH_DASH"] = 21] = "SCRIPT_DATA_ESCAPED_DASH_DASH";
+ State[State["SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN"] = 22] = "SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN";
+ State[State["SCRIPT_DATA_ESCAPED_END_TAG_OPEN"] = 23] = "SCRIPT_DATA_ESCAPED_END_TAG_OPEN";
+ State[State["SCRIPT_DATA_ESCAPED_END_TAG_NAME"] = 24] = "SCRIPT_DATA_ESCAPED_END_TAG_NAME";
+ State[State["SCRIPT_DATA_DOUBLE_ESCAPE_START"] = 25] = "SCRIPT_DATA_DOUBLE_ESCAPE_START";
+ State[State["SCRIPT_DATA_DOUBLE_ESCAPED"] = 26] = "SCRIPT_DATA_DOUBLE_ESCAPED";
+ State[State["SCRIPT_DATA_DOUBLE_ESCAPED_DASH"] = 27] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH";
+ State[State["SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH"] = 28] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH";
+ State[State["SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN"] = 29] = "SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN";
+ State[State["SCRIPT_DATA_DOUBLE_ESCAPE_END"] = 30] = "SCRIPT_DATA_DOUBLE_ESCAPE_END";
+ State[State["BEFORE_ATTRIBUTE_NAME"] = 31] = "BEFORE_ATTRIBUTE_NAME";
+ State[State["ATTRIBUTE_NAME"] = 32] = "ATTRIBUTE_NAME";
+ State[State["AFTER_ATTRIBUTE_NAME"] = 33] = "AFTER_ATTRIBUTE_NAME";
+ State[State["BEFORE_ATTRIBUTE_VALUE"] = 34] = "BEFORE_ATTRIBUTE_VALUE";
+ State[State["ATTRIBUTE_VALUE_DOUBLE_QUOTED"] = 35] = "ATTRIBUTE_VALUE_DOUBLE_QUOTED";
+ State[State["ATTRIBUTE_VALUE_SINGLE_QUOTED"] = 36] = "ATTRIBUTE_VALUE_SINGLE_QUOTED";
+ State[State["ATTRIBUTE_VALUE_UNQUOTED"] = 37] = "ATTRIBUTE_VALUE_UNQUOTED";
+ State[State["AFTER_ATTRIBUTE_VALUE_QUOTED"] = 38] = "AFTER_ATTRIBUTE_VALUE_QUOTED";
+ State[State["SELF_CLOSING_START_TAG"] = 39] = "SELF_CLOSING_START_TAG";
+ State[State["BOGUS_COMMENT"] = 40] = "BOGUS_COMMENT";
+ State[State["MARKUP_DECLARATION_OPEN"] = 41] = "MARKUP_DECLARATION_OPEN";
+ State[State["COMMENT_START"] = 42] = "COMMENT_START";
+ State[State["COMMENT_START_DASH"] = 43] = "COMMENT_START_DASH";
+ State[State["COMMENT"] = 44] = "COMMENT";
+ State[State["COMMENT_LESS_THAN_SIGN"] = 45] = "COMMENT_LESS_THAN_SIGN";
+ State[State["COMMENT_LESS_THAN_SIGN_BANG"] = 46] = "COMMENT_LESS_THAN_SIGN_BANG";
+ State[State["COMMENT_LESS_THAN_SIGN_BANG_DASH"] = 47] = "COMMENT_LESS_THAN_SIGN_BANG_DASH";
+ State[State["COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH"] = 48] = "COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH";
+ State[State["COMMENT_END_DASH"] = 49] = "COMMENT_END_DASH";
+ State[State["COMMENT_END"] = 50] = "COMMENT_END";
+ State[State["COMMENT_END_BANG"] = 51] = "COMMENT_END_BANG";
+ State[State["DOCTYPE"] = 52] = "DOCTYPE";
+ State[State["BEFORE_DOCTYPE_NAME"] = 53] = "BEFORE_DOCTYPE_NAME";
+ State[State["DOCTYPE_NAME"] = 54] = "DOCTYPE_NAME";
+ State[State["AFTER_DOCTYPE_NAME"] = 55] = "AFTER_DOCTYPE_NAME";
+ State[State["AFTER_DOCTYPE_PUBLIC_KEYWORD"] = 56] = "AFTER_DOCTYPE_PUBLIC_KEYWORD";
+ State[State["BEFORE_DOCTYPE_PUBLIC_IDENTIFIER"] = 57] = "BEFORE_DOCTYPE_PUBLIC_IDENTIFIER";
+ State[State["DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED"] = 58] = "DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED";
+ State[State["DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED"] = 59] = "DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED";
+ State[State["AFTER_DOCTYPE_PUBLIC_IDENTIFIER"] = 60] = "AFTER_DOCTYPE_PUBLIC_IDENTIFIER";
+ State[State["BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS"] = 61] = "BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS";
+ State[State["AFTER_DOCTYPE_SYSTEM_KEYWORD"] = 62] = "AFTER_DOCTYPE_SYSTEM_KEYWORD";
+ State[State["BEFORE_DOCTYPE_SYSTEM_IDENTIFIER"] = 63] = "BEFORE_DOCTYPE_SYSTEM_IDENTIFIER";
+ State[State["DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED"] = 64] = "DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED";
+ State[State["DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED"] = 65] = "DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED";
+ State[State["AFTER_DOCTYPE_SYSTEM_IDENTIFIER"] = 66] = "AFTER_DOCTYPE_SYSTEM_IDENTIFIER";
+ State[State["BOGUS_DOCTYPE"] = 67] = "BOGUS_DOCTYPE";
+ State[State["CDATA_SECTION"] = 68] = "CDATA_SECTION";
+ State[State["CDATA_SECTION_BRACKET"] = 69] = "CDATA_SECTION_BRACKET";
+ State[State["CDATA_SECTION_END"] = 70] = "CDATA_SECTION_END";
+ State[State["CHARACTER_REFERENCE"] = 71] = "CHARACTER_REFERENCE";
+ State[State["NAMED_CHARACTER_REFERENCE"] = 72] = "NAMED_CHARACTER_REFERENCE";
+ State[State["AMBIGUOUS_AMPERSAND"] = 73] = "AMBIGUOUS_AMPERSAND";
+ State[State["NUMERIC_CHARACTER_REFERENCE"] = 74] = "NUMERIC_CHARACTER_REFERENCE";
+ State[State["HEXADEMICAL_CHARACTER_REFERENCE_START"] = 75] = "HEXADEMICAL_CHARACTER_REFERENCE_START";
+ State[State["HEXADEMICAL_CHARACTER_REFERENCE"] = 76] = "HEXADEMICAL_CHARACTER_REFERENCE";
+ State[State["DECIMAL_CHARACTER_REFERENCE"] = 77] = "DECIMAL_CHARACTER_REFERENCE";
+ State[State["NUMERIC_CHARACTER_REFERENCE_END"] = 78] = "NUMERIC_CHARACTER_REFERENCE_END";
+})(State || (State = {}));
+//Tokenizer initial states for different modes
+const tokenizer_TokenizerMode = {
+ DATA: State.DATA,
+ RCDATA: State.RCDATA,
+ RAWTEXT: State.RAWTEXT,
+ SCRIPT_DATA: State.SCRIPT_DATA,
+ PLAINTEXT: State.PLAINTEXT,
+ CDATA_SECTION: State.CDATA_SECTION,
+};
+//Utils
+//OPTIMIZATION: these utility functions should not be moved out of this module. V8 Crankshaft will not inline
+//this functions if they will be situated in another module due to context switch.
+//Always perform inlining check before modifying this functions ('node --trace-inlining').
+function isAsciiDigit(cp) {
+ return cp >= CODE_POINTS.DIGIT_0 && cp <= CODE_POINTS.DIGIT_9;
+}
+function isAsciiUpper(cp) {
+ return cp >= CODE_POINTS.LATIN_CAPITAL_A && cp <= CODE_POINTS.LATIN_CAPITAL_Z;
+}
+function isAsciiLower(cp) {
+ return cp >= CODE_POINTS.LATIN_SMALL_A && cp <= CODE_POINTS.LATIN_SMALL_Z;
+}
+function isAsciiLetter(cp) {
+ return isAsciiLower(cp) || isAsciiUpper(cp);
+}
+function tokenizer_isAsciiAlphaNumeric(cp) {
+ return isAsciiLetter(cp) || isAsciiDigit(cp);
+}
+function isAsciiUpperHexDigit(cp) {
+ return cp >= CODE_POINTS.LATIN_CAPITAL_A && cp <= CODE_POINTS.LATIN_CAPITAL_F;
+}
+function isAsciiLowerHexDigit(cp) {
+ return cp >= CODE_POINTS.LATIN_SMALL_A && cp <= CODE_POINTS.LATIN_SMALL_F;
+}
+function isAsciiHexDigit(cp) {
+ return isAsciiDigit(cp) || isAsciiUpperHexDigit(cp) || isAsciiLowerHexDigit(cp);
+}
+function toAsciiLower(cp) {
+ return cp + 32;
+}
+function isWhitespace(cp) {
+ return cp === CODE_POINTS.SPACE || cp === CODE_POINTS.LINE_FEED || cp === CODE_POINTS.TABULATION || cp === CODE_POINTS.FORM_FEED;
+}
+function tokenizer_isEntityInAttributeInvalidEnd(nextCp) {
+ return nextCp === CODE_POINTS.EQUALS_SIGN || tokenizer_isAsciiAlphaNumeric(nextCp);
+}
+function isScriptDataDoubleEscapeSequenceEnd(cp) {
+ return isWhitespace(cp) || cp === CODE_POINTS.SOLIDUS || cp === CODE_POINTS.GREATER_THAN_SIGN;
+}
+//Tokenizer
+class tokenizer_Tokenizer {
+ constructor(options, handler) {
+ this.options = options;
+ this.handler = handler;
+ this.paused = false;
+ /** Ensures that the parsing loop isn't run multiple times at once. */
+ this.inLoop = false;
+ /**
+ * Indicates that the current adjusted node exists, is not an element in the HTML namespace,
+ * and that it is not an integration point for either MathML or HTML.
+ *
+ * @see {@link https://html.spec.whatwg.org/multipage/parsing.html#tree-construction}
+ */
+ this.inForeignNode = false;
+ this.lastStartTagName = '';
+ this.active = false;
+ this.state = State.DATA;
+ this.returnState = State.DATA;
+ this.charRefCode = -1;
+ this.consumedAfterSnapshot = -1;
+ this.currentCharacterToken = null;
+ this.currentToken = null;
+ this.currentAttr = { name: '', value: '' };
+ this.preprocessor = new Preprocessor(handler);
+ this.currentLocation = this.getCurrentLocation(-1);
+ }
+ //Errors
+ _err(code) {
+ var _a, _b;
+ (_b = (_a = this.handler).onParseError) === null || _b === void 0 ? void 0 : _b.call(_a, this.preprocessor.getError(code));
+ }
+ // NOTE: `offset` may never run across line boundaries.
+ getCurrentLocation(offset) {
+ if (!this.options.sourceCodeLocationInfo) {
+ return null;
+ }
+ return {
+ startLine: this.preprocessor.line,
+ startCol: this.preprocessor.col - offset,
+ startOffset: this.preprocessor.offset - offset,
+ endLine: -1,
+ endCol: -1,
+ endOffset: -1,
+ };
+ }
+ _runParsingLoop() {
+ if (this.inLoop)
+ return;
+ this.inLoop = true;
+ while (this.active && !this.paused) {
+ this.consumedAfterSnapshot = 0;
+ const cp = this._consume();
+ if (!this._ensureHibernation()) {
+ this._callState(cp);
+ }
+ }
+ this.inLoop = false;
+ }
+ //API
+ pause() {
+ this.paused = true;
+ }
+ resume(writeCallback) {
+ if (!this.paused) {
+ throw new Error('Parser was already resumed');
+ }
+ this.paused = false;
+ // Necessary for synchronous resume.
+ if (this.inLoop)
+ return;
+ this._runParsingLoop();
+ if (!this.paused) {
+ writeCallback === null || writeCallback === void 0 ? void 0 : writeCallback();
+ }
+ }
+ write(chunk, isLastChunk, writeCallback) {
+ this.active = true;
+ this.preprocessor.write(chunk, isLastChunk);
+ this._runParsingLoop();
+ if (!this.paused) {
+ writeCallback === null || writeCallback === void 0 ? void 0 : writeCallback();
+ }
+ }
+ insertHtmlAtCurrentPos(chunk) {
+ this.active = true;
+ this.preprocessor.insertHtmlAtCurrentPos(chunk);
+ this._runParsingLoop();
+ }
+ //Hibernation
+ _ensureHibernation() {
+ if (this.preprocessor.endOfChunkHit) {
+ this._unconsume(this.consumedAfterSnapshot);
+ this.active = false;
+ return true;
+ }
+ return false;
+ }
+ //Consumption
+ _consume() {
+ this.consumedAfterSnapshot++;
+ return this.preprocessor.advance();
+ }
+ _unconsume(count) {
+ this.consumedAfterSnapshot -= count;
+ this.preprocessor.retreat(count);
+ }
+ _reconsumeInState(state, cp) {
+ this.state = state;
+ this._callState(cp);
+ }
+ _advanceBy(count) {
+ this.consumedAfterSnapshot += count;
+ for (let i = 0; i < count; i++) {
+ this.preprocessor.advance();
+ }
+ }
+ _consumeSequenceIfMatch(pattern, caseSensitive) {
+ if (this.preprocessor.startsWith(pattern, caseSensitive)) {
+ // We will already have consumed one character before calling this method.
+ this._advanceBy(pattern.length - 1);
+ return true;
+ }
+ return false;
+ }
+ //Token creation
+ _createStartTagToken() {
+ this.currentToken = {
+ type: token_TokenType.START_TAG,
+ tagName: '',
+ tagID: TAG_ID.UNKNOWN,
+ selfClosing: false,
+ ackSelfClosing: false,
+ attrs: [],
+ location: this.getCurrentLocation(1),
+ };
+ }
+ _createEndTagToken() {
+ this.currentToken = {
+ type: token_TokenType.END_TAG,
+ tagName: '',
+ tagID: TAG_ID.UNKNOWN,
+ selfClosing: false,
+ ackSelfClosing: false,
+ attrs: [],
+ location: this.getCurrentLocation(2),
+ };
+ }
+ _createCommentToken(offset) {
+ this.currentToken = {
+ type: token_TokenType.COMMENT,
+ data: '',
+ location: this.getCurrentLocation(offset),
+ };
+ }
+ _createDoctypeToken(initialName) {
+ this.currentToken = {
+ type: token_TokenType.DOCTYPE,
+ name: initialName,
+ forceQuirks: false,
+ publicId: null,
+ systemId: null,
+ location: this.currentLocation,
+ };
+ }
+ _createCharacterToken(type, chars) {
+ this.currentCharacterToken = {
+ type,
+ chars,
+ location: this.currentLocation,
+ };
+ }
+ //Tag attributes
+ _createAttr(attrNameFirstCh) {
+ this.currentAttr = {
+ name: attrNameFirstCh,
+ value: '',
+ };
+ this.currentLocation = this.getCurrentLocation(0);
+ }
+ _leaveAttrName() {
+ var _a;
+ var _b;
+ const token = this.currentToken;
+ if (token_getTokenAttr(token, this.currentAttr.name) === null) {
+ token.attrs.push(this.currentAttr);
+ if (token.location && this.currentLocation) {
+ const attrLocations = ((_a = (_b = token.location).attrs) !== null && _a !== void 0 ? _a : (_b.attrs = Object.create(null)));
+ attrLocations[this.currentAttr.name] = this.currentLocation;
+ // Set end location
+ this._leaveAttrValue();
+ }
+ }
+ else {
+ this._err(error_codes_ERR.duplicateAttribute);
+ }
+ }
+ _leaveAttrValue() {
+ if (this.currentLocation) {
+ this.currentLocation.endLine = this.preprocessor.line;
+ this.currentLocation.endCol = this.preprocessor.col;
+ this.currentLocation.endOffset = this.preprocessor.offset;
+ }
+ }
+ //Token emission
+ prepareToken(ct) {
+ this._emitCurrentCharacterToken(ct.location);
+ this.currentToken = null;
+ if (ct.location) {
+ ct.location.endLine = this.preprocessor.line;
+ ct.location.endCol = this.preprocessor.col + 1;
+ ct.location.endOffset = this.preprocessor.offset + 1;
+ }
+ this.currentLocation = this.getCurrentLocation(-1);
+ }
+ emitCurrentTagToken() {
+ const ct = this.currentToken;
+ this.prepareToken(ct);
+ ct.tagID = html_getTagID(ct.tagName);
+ if (ct.type === token_TokenType.START_TAG) {
+ this.lastStartTagName = ct.tagName;
+ this.handler.onStartTag(ct);
+ }
+ else {
+ if (ct.attrs.length > 0) {
+ this._err(error_codes_ERR.endTagWithAttributes);
+ }
+ if (ct.selfClosing) {
+ this._err(error_codes_ERR.endTagWithTrailingSolidus);
+ }
+ this.handler.onEndTag(ct);
+ }
+ this.preprocessor.dropParsedChunk();
+ }
+ emitCurrentComment(ct) {
+ this.prepareToken(ct);
+ this.handler.onComment(ct);
+ this.preprocessor.dropParsedChunk();
+ }
+ emitCurrentDoctype(ct) {
+ this.prepareToken(ct);
+ this.handler.onDoctype(ct);
+ this.preprocessor.dropParsedChunk();
+ }
+ _emitCurrentCharacterToken(nextLocation) {
+ if (this.currentCharacterToken) {
+ //NOTE: if we have a pending character token, make it's end location equal to the
+ //current token's start location.
+ if (nextLocation && this.currentCharacterToken.location) {
+ this.currentCharacterToken.location.endLine = nextLocation.startLine;
+ this.currentCharacterToken.location.endCol = nextLocation.startCol;
+ this.currentCharacterToken.location.endOffset = nextLocation.startOffset;
+ }
+ switch (this.currentCharacterToken.type) {
+ case token_TokenType.CHARACTER: {
+ this.handler.onCharacter(this.currentCharacterToken);
+ break;
+ }
+ case token_TokenType.NULL_CHARACTER: {
+ this.handler.onNullCharacter(this.currentCharacterToken);
+ break;
+ }
+ case token_TokenType.WHITESPACE_CHARACTER: {
+ this.handler.onWhitespaceCharacter(this.currentCharacterToken);
+ break;
+ }
+ }
+ this.currentCharacterToken = null;
+ }
+ }
+ _emitEOFToken() {
+ const location = this.getCurrentLocation(0);
+ if (location) {
+ location.endLine = location.startLine;
+ location.endCol = location.startCol;
+ location.endOffset = location.startOffset;
+ }
+ this._emitCurrentCharacterToken(location);
+ this.handler.onEof({ type: token_TokenType.EOF, location });
+ this.active = false;
+ }
+ //Characters emission
+ //OPTIMIZATION: specification uses only one type of character tokens (one token per character).
+ //This causes a huge memory overhead and a lot of unnecessary parser loops. parse5 uses 3 groups of characters.
+ //If we have a sequence of characters that belong to the same group, the parser can process it
+ //as a single solid character token.
+ //So, there are 3 types of character tokens in parse5:
+ //1)TokenType.NULL_CHARACTER - \u0000-character sequences (e.g. '\u0000\u0000\u0000')
+ //2)TokenType.WHITESPACE_CHARACTER - any whitespace/new-line character sequences (e.g. '\n \r\t \f')
+ //3)TokenType.CHARACTER - any character sequence which don't belong to groups 1 and 2 (e.g. 'abcdef1234@@#$%^')
+ _appendCharToCurrentCharacterToken(type, ch) {
+ if (this.currentCharacterToken) {
+ if (this.currentCharacterToken.type !== type) {
+ this.currentLocation = this.getCurrentLocation(0);
+ this._emitCurrentCharacterToken(this.currentLocation);
+ this.preprocessor.dropParsedChunk();
+ }
+ else {
+ this.currentCharacterToken.chars += ch;
+ return;
+ }
+ }
+ this._createCharacterToken(type, ch);
+ }
+ _emitCodePoint(cp) {
+ const type = isWhitespace(cp)
+ ? token_TokenType.WHITESPACE_CHARACTER
+ : cp === CODE_POINTS.NULL
+ ? token_TokenType.NULL_CHARACTER
+ : token_TokenType.CHARACTER;
+ this._appendCharToCurrentCharacterToken(type, String.fromCodePoint(cp));
+ }
+ //NOTE: used when we emit characters explicitly.
+ //This is always for non-whitespace and non-null characters, which allows us to avoid additional checks.
+ _emitChars(ch) {
+ this._appendCharToCurrentCharacterToken(token_TokenType.CHARACTER, ch);
+ }
+ // Character reference helpers
+ _matchNamedCharacterReference(cp) {
+ let result = null;
+ let excess = 0;
+ let withoutSemicolon = false;
+ for (let i = 0, current = decode_data_html[0]; i >= 0; cp = this._consume()) {
+ i = determineBranch(decode_data_html, current, i + 1, cp);
+ if (i < 0)
+ break;
+ excess += 1;
+ current = decode_data_html[i];
+ const masked = current & BinTrieFlags.VALUE_LENGTH;
+ // If the branch is a value, store it and continue
+ if (masked) {
+ // The mask is the number of bytes of the value, including the current byte.
+ const valueLength = (masked >> 14) - 1;
+ // Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.
+ // See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
+ if (cp !== CODE_POINTS.SEMICOLON &&
+ this._isCharacterReferenceInAttribute() &&
+ tokenizer_isEntityInAttributeInvalidEnd(this.preprocessor.peek(1))) {
+ //NOTE: we don't flush all consumed code points here, and instead switch back to the original state after
+ //emitting an ampersand. This is fine, as alphanumeric characters won't be parsed differently in attributes.
+ result = [CODE_POINTS.AMPERSAND];
+ // Skip over the value.
+ i += valueLength;
+ }
+ else {
+ // If this is a surrogate pair, consume the next two bytes.
+ result =
+ valueLength === 0
+ ? [decode_data_html[i] & ~BinTrieFlags.VALUE_LENGTH]
+ : valueLength === 1
+ ? [decode_data_html[++i]]
+ : [decode_data_html[++i], decode_data_html[++i]];
+ excess = 0;
+ withoutSemicolon = cp !== CODE_POINTS.SEMICOLON;
+ }
+ if (valueLength === 0) {
+ // If the value is zero-length, we're done.
+ this._consume();
+ break;
+ }
+ }
+ }
+ this._unconsume(excess);
+ if (withoutSemicolon && !this.preprocessor.endOfChunkHit) {
+ this._err(error_codes_ERR.missingSemicolonAfterCharacterReference);
+ }
+ // We want to emit the error above on the code point after the entity.
+ // We always consume one code point too many in the loop, and we wait to
+ // unconsume it until after the error is emitted.
+ this._unconsume(1);
+ return result;
+ }
+ _isCharacterReferenceInAttribute() {
+ return (this.returnState === State.ATTRIBUTE_VALUE_DOUBLE_QUOTED ||
+ this.returnState === State.ATTRIBUTE_VALUE_SINGLE_QUOTED ||
+ this.returnState === State.ATTRIBUTE_VALUE_UNQUOTED);
+ }
+ _flushCodePointConsumedAsCharacterReference(cp) {
+ if (this._isCharacterReferenceInAttribute()) {
+ this.currentAttr.value += String.fromCodePoint(cp);
+ }
+ else {
+ this._emitCodePoint(cp);
+ }
+ }
+ // Calling states this way turns out to be much faster than any other approach.
+ _callState(cp) {
+ switch (this.state) {
+ case State.DATA: {
+ this._stateData(cp);
+ break;
+ }
+ case State.RCDATA: {
+ this._stateRcdata(cp);
+ break;
+ }
+ case State.RAWTEXT: {
+ this._stateRawtext(cp);
+ break;
+ }
+ case State.SCRIPT_DATA: {
+ this._stateScriptData(cp);
+ break;
+ }
+ case State.PLAINTEXT: {
+ this._statePlaintext(cp);
+ break;
+ }
+ case State.TAG_OPEN: {
+ this._stateTagOpen(cp);
+ break;
+ }
+ case State.END_TAG_OPEN: {
+ this._stateEndTagOpen(cp);
+ break;
+ }
+ case State.TAG_NAME: {
+ this._stateTagName(cp);
+ break;
+ }
+ case State.RCDATA_LESS_THAN_SIGN: {
+ this._stateRcdataLessThanSign(cp);
+ break;
+ }
+ case State.RCDATA_END_TAG_OPEN: {
+ this._stateRcdataEndTagOpen(cp);
+ break;
+ }
+ case State.RCDATA_END_TAG_NAME: {
+ this._stateRcdataEndTagName(cp);
+ break;
+ }
+ case State.RAWTEXT_LESS_THAN_SIGN: {
+ this._stateRawtextLessThanSign(cp);
+ break;
+ }
+ case State.RAWTEXT_END_TAG_OPEN: {
+ this._stateRawtextEndTagOpen(cp);
+ break;
+ }
+ case State.RAWTEXT_END_TAG_NAME: {
+ this._stateRawtextEndTagName(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_LESS_THAN_SIGN: {
+ this._stateScriptDataLessThanSign(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_END_TAG_OPEN: {
+ this._stateScriptDataEndTagOpen(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_END_TAG_NAME: {
+ this._stateScriptDataEndTagName(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_ESCAPE_START: {
+ this._stateScriptDataEscapeStart(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_ESCAPE_START_DASH: {
+ this._stateScriptDataEscapeStartDash(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_ESCAPED: {
+ this._stateScriptDataEscaped(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_ESCAPED_DASH: {
+ this._stateScriptDataEscapedDash(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_ESCAPED_DASH_DASH: {
+ this._stateScriptDataEscapedDashDash(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN: {
+ this._stateScriptDataEscapedLessThanSign(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN: {
+ this._stateScriptDataEscapedEndTagOpen(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_ESCAPED_END_TAG_NAME: {
+ this._stateScriptDataEscapedEndTagName(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_DOUBLE_ESCAPE_START: {
+ this._stateScriptDataDoubleEscapeStart(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_DOUBLE_ESCAPED: {
+ this._stateScriptDataDoubleEscaped(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH: {
+ this._stateScriptDataDoubleEscapedDash(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH: {
+ this._stateScriptDataDoubleEscapedDashDash(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN: {
+ this._stateScriptDataDoubleEscapedLessThanSign(cp);
+ break;
+ }
+ case State.SCRIPT_DATA_DOUBLE_ESCAPE_END: {
+ this._stateScriptDataDoubleEscapeEnd(cp);
+ break;
+ }
+ case State.BEFORE_ATTRIBUTE_NAME: {
+ this._stateBeforeAttributeName(cp);
+ break;
+ }
+ case State.ATTRIBUTE_NAME: {
+ this._stateAttributeName(cp);
+ break;
+ }
+ case State.AFTER_ATTRIBUTE_NAME: {
+ this._stateAfterAttributeName(cp);
+ break;
+ }
+ case State.BEFORE_ATTRIBUTE_VALUE: {
+ this._stateBeforeAttributeValue(cp);
+ break;
+ }
+ case State.ATTRIBUTE_VALUE_DOUBLE_QUOTED: {
+ this._stateAttributeValueDoubleQuoted(cp);
+ break;
+ }
+ case State.ATTRIBUTE_VALUE_SINGLE_QUOTED: {
+ this._stateAttributeValueSingleQuoted(cp);
+ break;
+ }
+ case State.ATTRIBUTE_VALUE_UNQUOTED: {
+ this._stateAttributeValueUnquoted(cp);
+ break;
+ }
+ case State.AFTER_ATTRIBUTE_VALUE_QUOTED: {
+ this._stateAfterAttributeValueQuoted(cp);
+ break;
+ }
+ case State.SELF_CLOSING_START_TAG: {
+ this._stateSelfClosingStartTag(cp);
+ break;
+ }
+ case State.BOGUS_COMMENT: {
+ this._stateBogusComment(cp);
+ break;
+ }
+ case State.MARKUP_DECLARATION_OPEN: {
+ this._stateMarkupDeclarationOpen(cp);
+ break;
+ }
+ case State.COMMENT_START: {
+ this._stateCommentStart(cp);
+ break;
+ }
+ case State.COMMENT_START_DASH: {
+ this._stateCommentStartDash(cp);
+ break;
+ }
+ case State.COMMENT: {
+ this._stateComment(cp);
+ break;
+ }
+ case State.COMMENT_LESS_THAN_SIGN: {
+ this._stateCommentLessThanSign(cp);
+ break;
+ }
+ case State.COMMENT_LESS_THAN_SIGN_BANG: {
+ this._stateCommentLessThanSignBang(cp);
+ break;
+ }
+ case State.COMMENT_LESS_THAN_SIGN_BANG_DASH: {
+ this._stateCommentLessThanSignBangDash(cp);
+ break;
+ }
+ case State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH: {
+ this._stateCommentLessThanSignBangDashDash(cp);
+ break;
+ }
+ case State.COMMENT_END_DASH: {
+ this._stateCommentEndDash(cp);
+ break;
+ }
+ case State.COMMENT_END: {
+ this._stateCommentEnd(cp);
+ break;
+ }
+ case State.COMMENT_END_BANG: {
+ this._stateCommentEndBang(cp);
+ break;
+ }
+ case State.DOCTYPE: {
+ this._stateDoctype(cp);
+ break;
+ }
+ case State.BEFORE_DOCTYPE_NAME: {
+ this._stateBeforeDoctypeName(cp);
+ break;
+ }
+ case State.DOCTYPE_NAME: {
+ this._stateDoctypeName(cp);
+ break;
+ }
+ case State.AFTER_DOCTYPE_NAME: {
+ this._stateAfterDoctypeName(cp);
+ break;
+ }
+ case State.AFTER_DOCTYPE_PUBLIC_KEYWORD: {
+ this._stateAfterDoctypePublicKeyword(cp);
+ break;
+ }
+ case State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: {
+ this._stateBeforeDoctypePublicIdentifier(cp);
+ break;
+ }
+ case State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: {
+ this._stateDoctypePublicIdentifierDoubleQuoted(cp);
+ break;
+ }
+ case State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: {
+ this._stateDoctypePublicIdentifierSingleQuoted(cp);
+ break;
+ }
+ case State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER: {
+ this._stateAfterDoctypePublicIdentifier(cp);
+ break;
+ }
+ case State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS: {
+ this._stateBetweenDoctypePublicAndSystemIdentifiers(cp);
+ break;
+ }
+ case State.AFTER_DOCTYPE_SYSTEM_KEYWORD: {
+ this._stateAfterDoctypeSystemKeyword(cp);
+ break;
+ }
+ case State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: {
+ this._stateBeforeDoctypeSystemIdentifier(cp);
+ break;
+ }
+ case State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: {
+ this._stateDoctypeSystemIdentifierDoubleQuoted(cp);
+ break;
+ }
+ case State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: {
+ this._stateDoctypeSystemIdentifierSingleQuoted(cp);
+ break;
+ }
+ case State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER: {
+ this._stateAfterDoctypeSystemIdentifier(cp);
+ break;
+ }
+ case State.BOGUS_DOCTYPE: {
+ this._stateBogusDoctype(cp);
+ break;
+ }
+ case State.CDATA_SECTION: {
+ this._stateCdataSection(cp);
+ break;
+ }
+ case State.CDATA_SECTION_BRACKET: {
+ this._stateCdataSectionBracket(cp);
+ break;
+ }
+ case State.CDATA_SECTION_END: {
+ this._stateCdataSectionEnd(cp);
+ break;
+ }
+ case State.CHARACTER_REFERENCE: {
+ this._stateCharacterReference(cp);
+ break;
+ }
+ case State.NAMED_CHARACTER_REFERENCE: {
+ this._stateNamedCharacterReference(cp);
+ break;
+ }
+ case State.AMBIGUOUS_AMPERSAND: {
+ this._stateAmbiguousAmpersand(cp);
+ break;
+ }
+ case State.NUMERIC_CHARACTER_REFERENCE: {
+ this._stateNumericCharacterReference(cp);
+ break;
+ }
+ case State.HEXADEMICAL_CHARACTER_REFERENCE_START: {
+ this._stateHexademicalCharacterReferenceStart(cp);
+ break;
+ }
+ case State.HEXADEMICAL_CHARACTER_REFERENCE: {
+ this._stateHexademicalCharacterReference(cp);
+ break;
+ }
+ case State.DECIMAL_CHARACTER_REFERENCE: {
+ this._stateDecimalCharacterReference(cp);
+ break;
+ }
+ case State.NUMERIC_CHARACTER_REFERENCE_END: {
+ this._stateNumericCharacterReferenceEnd(cp);
+ break;
+ }
+ default: {
+ throw new Error('Unknown state');
+ }
+ }
+ }
+ // State machine
+ // Data state
+ //------------------------------------------------------------------
+ _stateData(cp) {
+ switch (cp) {
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ this.state = State.TAG_OPEN;
+ break;
+ }
+ case CODE_POINTS.AMPERSAND: {
+ this.returnState = State.DATA;
+ this.state = State.CHARACTER_REFERENCE;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this._emitCodePoint(cp);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // RCDATA state
+ //------------------------------------------------------------------
+ _stateRcdata(cp) {
+ switch (cp) {
+ case CODE_POINTS.AMPERSAND: {
+ this.returnState = State.RCDATA;
+ this.state = State.CHARACTER_REFERENCE;
+ break;
+ }
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ this.state = State.RCDATA_LESS_THAN_SIGN;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this._emitChars(REPLACEMENT_CHARACTER);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // RAWTEXT state
+ //------------------------------------------------------------------
+ _stateRawtext(cp) {
+ switch (cp) {
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ this.state = State.RAWTEXT_LESS_THAN_SIGN;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this._emitChars(REPLACEMENT_CHARACTER);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // Script data state
+ //------------------------------------------------------------------
+ _stateScriptData(cp) {
+ switch (cp) {
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ this.state = State.SCRIPT_DATA_LESS_THAN_SIGN;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this._emitChars(REPLACEMENT_CHARACTER);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // PLAINTEXT state
+ //------------------------------------------------------------------
+ _statePlaintext(cp) {
+ switch (cp) {
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this._emitChars(REPLACEMENT_CHARACTER);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // Tag open state
+ //------------------------------------------------------------------
+ _stateTagOpen(cp) {
+ if (isAsciiLetter(cp)) {
+ this._createStartTagToken();
+ this.state = State.TAG_NAME;
+ this._stateTagName(cp);
+ }
+ else
+ switch (cp) {
+ case CODE_POINTS.EXCLAMATION_MARK: {
+ this.state = State.MARKUP_DECLARATION_OPEN;
+ break;
+ }
+ case CODE_POINTS.SOLIDUS: {
+ this.state = State.END_TAG_OPEN;
+ break;
+ }
+ case CODE_POINTS.QUESTION_MARK: {
+ this._err(error_codes_ERR.unexpectedQuestionMarkInsteadOfTagName);
+ this._createCommentToken(1);
+ this.state = State.BOGUS_COMMENT;
+ this._stateBogusComment(cp);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofBeforeTagName);
+ this._emitChars('<');
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.invalidFirstCharacterOfTagName);
+ this._emitChars('<');
+ this.state = State.DATA;
+ this._stateData(cp);
+ }
+ }
+ }
+ // End tag open state
+ //------------------------------------------------------------------
+ _stateEndTagOpen(cp) {
+ if (isAsciiLetter(cp)) {
+ this._createEndTagToken();
+ this.state = State.TAG_NAME;
+ this._stateTagName(cp);
+ }
+ else
+ switch (cp) {
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.missingEndTagName);
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofBeforeTagName);
+ this._emitChars('');
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.invalidFirstCharacterOfTagName);
+ this._createCommentToken(2);
+ this.state = State.BOGUS_COMMENT;
+ this._stateBogusComment(cp);
+ }
+ }
+ }
+ // Tag name state
+ //------------------------------------------------------------------
+ _stateTagName(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ this.state = State.BEFORE_ATTRIBUTE_NAME;
+ break;
+ }
+ case CODE_POINTS.SOLIDUS: {
+ this.state = State.SELF_CLOSING_START_TAG;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.DATA;
+ this.emitCurrentTagToken();
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ token.tagName += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInTag);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.tagName += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
+ }
+ }
+ }
+ // RCDATA less-than sign state
+ //------------------------------------------------------------------
+ _stateRcdataLessThanSign(cp) {
+ if (cp === CODE_POINTS.SOLIDUS) {
+ this.state = State.RCDATA_END_TAG_OPEN;
+ }
+ else {
+ this._emitChars('<');
+ this.state = State.RCDATA;
+ this._stateRcdata(cp);
+ }
+ }
+ // RCDATA end tag open state
+ //------------------------------------------------------------------
+ _stateRcdataEndTagOpen(cp) {
+ if (isAsciiLetter(cp)) {
+ this.state = State.RCDATA_END_TAG_NAME;
+ this._stateRcdataEndTagName(cp);
+ }
+ else {
+ this._emitChars('');
+ this.state = State.RCDATA;
+ this._stateRcdata(cp);
+ }
+ }
+ handleSpecialEndTag(_cp) {
+ if (!this.preprocessor.startsWith(this.lastStartTagName, false)) {
+ return !this._ensureHibernation();
+ }
+ this._createEndTagToken();
+ const token = this.currentToken;
+ token.tagName = this.lastStartTagName;
+ const cp = this.preprocessor.peek(this.lastStartTagName.length);
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ this._advanceBy(this.lastStartTagName.length);
+ this.state = State.BEFORE_ATTRIBUTE_NAME;
+ return false;
+ }
+ case CODE_POINTS.SOLIDUS: {
+ this._advanceBy(this.lastStartTagName.length);
+ this.state = State.SELF_CLOSING_START_TAG;
+ return false;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._advanceBy(this.lastStartTagName.length);
+ this.emitCurrentTagToken();
+ this.state = State.DATA;
+ return false;
+ }
+ default: {
+ return !this._ensureHibernation();
+ }
+ }
+ }
+ // RCDATA end tag name state
+ //------------------------------------------------------------------
+ _stateRcdataEndTagName(cp) {
+ if (this.handleSpecialEndTag(cp)) {
+ this._emitChars('');
+ this.state = State.RCDATA;
+ this._stateRcdata(cp);
+ }
+ }
+ // RAWTEXT less-than sign state
+ //------------------------------------------------------------------
+ _stateRawtextLessThanSign(cp) {
+ if (cp === CODE_POINTS.SOLIDUS) {
+ this.state = State.RAWTEXT_END_TAG_OPEN;
+ }
+ else {
+ this._emitChars('<');
+ this.state = State.RAWTEXT;
+ this._stateRawtext(cp);
+ }
+ }
+ // RAWTEXT end tag open state
+ //------------------------------------------------------------------
+ _stateRawtextEndTagOpen(cp) {
+ if (isAsciiLetter(cp)) {
+ this.state = State.RAWTEXT_END_TAG_NAME;
+ this._stateRawtextEndTagName(cp);
+ }
+ else {
+ this._emitChars('');
+ this.state = State.RAWTEXT;
+ this._stateRawtext(cp);
+ }
+ }
+ // RAWTEXT end tag name state
+ //------------------------------------------------------------------
+ _stateRawtextEndTagName(cp) {
+ if (this.handleSpecialEndTag(cp)) {
+ this._emitChars('');
+ this.state = State.RAWTEXT;
+ this._stateRawtext(cp);
+ }
+ }
+ // Script data less-than sign state
+ //------------------------------------------------------------------
+ _stateScriptDataLessThanSign(cp) {
+ switch (cp) {
+ case CODE_POINTS.SOLIDUS: {
+ this.state = State.SCRIPT_DATA_END_TAG_OPEN;
+ break;
+ }
+ case CODE_POINTS.EXCLAMATION_MARK: {
+ this.state = State.SCRIPT_DATA_ESCAPE_START;
+ this._emitChars('');
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this.state = State.SCRIPT_DATA_ESCAPED;
+ this._emitChars(REPLACEMENT_CHARACTER);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInScriptHtmlCommentLikeText);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this.state = State.SCRIPT_DATA_ESCAPED;
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // Script data escaped less-than sign state
+ //------------------------------------------------------------------
+ _stateScriptDataEscapedLessThanSign(cp) {
+ if (cp === CODE_POINTS.SOLIDUS) {
+ this.state = State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN;
+ }
+ else if (isAsciiLetter(cp)) {
+ this._emitChars('<');
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPE_START;
+ this._stateScriptDataDoubleEscapeStart(cp);
+ }
+ else {
+ this._emitChars('<');
+ this.state = State.SCRIPT_DATA_ESCAPED;
+ this._stateScriptDataEscaped(cp);
+ }
+ }
+ // Script data escaped end tag open state
+ //------------------------------------------------------------------
+ _stateScriptDataEscapedEndTagOpen(cp) {
+ if (isAsciiLetter(cp)) {
+ this.state = State.SCRIPT_DATA_ESCAPED_END_TAG_NAME;
+ this._stateScriptDataEscapedEndTagName(cp);
+ }
+ else {
+ this._emitChars('');
+ this.state = State.SCRIPT_DATA_ESCAPED;
+ this._stateScriptDataEscaped(cp);
+ }
+ }
+ // Script data escaped end tag name state
+ //------------------------------------------------------------------
+ _stateScriptDataEscapedEndTagName(cp) {
+ if (this.handleSpecialEndTag(cp)) {
+ this._emitChars('');
+ this.state = State.SCRIPT_DATA_ESCAPED;
+ this._stateScriptDataEscaped(cp);
+ }
+ }
+ // Script data double escape start state
+ //------------------------------------------------------------------
+ _stateScriptDataDoubleEscapeStart(cp) {
+ if (this.preprocessor.startsWith(SEQUENCES.SCRIPT, false) &&
+ isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))) {
+ this._emitCodePoint(cp);
+ for (let i = 0; i < SEQUENCES.SCRIPT.length; i++) {
+ this._emitCodePoint(this._consume());
+ }
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
+ }
+ else if (!this._ensureHibernation()) {
+ this.state = State.SCRIPT_DATA_ESCAPED;
+ this._stateScriptDataEscaped(cp);
+ }
+ }
+ // Script data double escaped state
+ //------------------------------------------------------------------
+ _stateScriptDataDoubleEscaped(cp) {
+ switch (cp) {
+ case CODE_POINTS.HYPHEN_MINUS: {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH;
+ this._emitChars('-');
+ break;
+ }
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
+ this._emitChars('<');
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this._emitChars(REPLACEMENT_CHARACTER);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInScriptHtmlCommentLikeText);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // Script data double escaped dash state
+ //------------------------------------------------------------------
+ _stateScriptDataDoubleEscapedDash(cp) {
+ switch (cp) {
+ case CODE_POINTS.HYPHEN_MINUS: {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH;
+ this._emitChars('-');
+ break;
+ }
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
+ this._emitChars('<');
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
+ this._emitChars(REPLACEMENT_CHARACTER);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInScriptHtmlCommentLikeText);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // Script data double escaped dash dash state
+ //------------------------------------------------------------------
+ _stateScriptDataDoubleEscapedDashDash(cp) {
+ switch (cp) {
+ case CODE_POINTS.HYPHEN_MINUS: {
+ this._emitChars('-');
+ break;
+ }
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
+ this._emitChars('<');
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.SCRIPT_DATA;
+ this._emitChars('>');
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
+ this._emitChars(REPLACEMENT_CHARACTER);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInScriptHtmlCommentLikeText);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // Script data double escaped less-than sign state
+ //------------------------------------------------------------------
+ _stateScriptDataDoubleEscapedLessThanSign(cp) {
+ if (cp === CODE_POINTS.SOLIDUS) {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPE_END;
+ this._emitChars('/');
+ }
+ else {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
+ this._stateScriptDataDoubleEscaped(cp);
+ }
+ }
+ // Script data double escape end state
+ //------------------------------------------------------------------
+ _stateScriptDataDoubleEscapeEnd(cp) {
+ if (this.preprocessor.startsWith(SEQUENCES.SCRIPT, false) &&
+ isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))) {
+ this._emitCodePoint(cp);
+ for (let i = 0; i < SEQUENCES.SCRIPT.length; i++) {
+ this._emitCodePoint(this._consume());
+ }
+ this.state = State.SCRIPT_DATA_ESCAPED;
+ }
+ else if (!this._ensureHibernation()) {
+ this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
+ this._stateScriptDataDoubleEscaped(cp);
+ }
+ }
+ // Before attribute name state
+ //------------------------------------------------------------------
+ _stateBeforeAttributeName(cp) {
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ // Ignore whitespace
+ break;
+ }
+ case CODE_POINTS.SOLIDUS:
+ case CODE_POINTS.GREATER_THAN_SIGN:
+ case CODE_POINTS.EOF: {
+ this.state = State.AFTER_ATTRIBUTE_NAME;
+ this._stateAfterAttributeName(cp);
+ break;
+ }
+ case CODE_POINTS.EQUALS_SIGN: {
+ this._err(error_codes_ERR.unexpectedEqualsSignBeforeAttributeName);
+ this._createAttr('=');
+ this.state = State.ATTRIBUTE_NAME;
+ break;
+ }
+ default: {
+ this._createAttr('');
+ this.state = State.ATTRIBUTE_NAME;
+ this._stateAttributeName(cp);
+ }
+ }
+ }
+ // Attribute name state
+ //------------------------------------------------------------------
+ _stateAttributeName(cp) {
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED:
+ case CODE_POINTS.SOLIDUS:
+ case CODE_POINTS.GREATER_THAN_SIGN:
+ case CODE_POINTS.EOF: {
+ this._leaveAttrName();
+ this.state = State.AFTER_ATTRIBUTE_NAME;
+ this._stateAfterAttributeName(cp);
+ break;
+ }
+ case CODE_POINTS.EQUALS_SIGN: {
+ this._leaveAttrName();
+ this.state = State.BEFORE_ATTRIBUTE_VALUE;
+ break;
+ }
+ case CODE_POINTS.QUOTATION_MARK:
+ case CODE_POINTS.APOSTROPHE:
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ this._err(error_codes_ERR.unexpectedCharacterInAttributeName);
+ this.currentAttr.name += String.fromCodePoint(cp);
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this.currentAttr.name += REPLACEMENT_CHARACTER;
+ break;
+ }
+ default: {
+ this.currentAttr.name += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
+ }
+ }
+ }
+ // After attribute name state
+ //------------------------------------------------------------------
+ _stateAfterAttributeName(cp) {
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ // Ignore whitespace
+ break;
+ }
+ case CODE_POINTS.SOLIDUS: {
+ this.state = State.SELF_CLOSING_START_TAG;
+ break;
+ }
+ case CODE_POINTS.EQUALS_SIGN: {
+ this.state = State.BEFORE_ATTRIBUTE_VALUE;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.DATA;
+ this.emitCurrentTagToken();
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInTag);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._createAttr('');
+ this.state = State.ATTRIBUTE_NAME;
+ this._stateAttributeName(cp);
+ }
+ }
+ }
+ // Before attribute value state
+ //------------------------------------------------------------------
+ _stateBeforeAttributeValue(cp) {
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ // Ignore whitespace
+ break;
+ }
+ case CODE_POINTS.QUOTATION_MARK: {
+ this.state = State.ATTRIBUTE_VALUE_DOUBLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.APOSTROPHE: {
+ this.state = State.ATTRIBUTE_VALUE_SINGLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.missingAttributeValue);
+ this.state = State.DATA;
+ this.emitCurrentTagToken();
+ break;
+ }
+ default: {
+ this.state = State.ATTRIBUTE_VALUE_UNQUOTED;
+ this._stateAttributeValueUnquoted(cp);
+ }
+ }
+ }
+ // Attribute value (double-quoted) state
+ //------------------------------------------------------------------
+ _stateAttributeValueDoubleQuoted(cp) {
+ switch (cp) {
+ case CODE_POINTS.QUOTATION_MARK: {
+ this.state = State.AFTER_ATTRIBUTE_VALUE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.AMPERSAND: {
+ this.returnState = State.ATTRIBUTE_VALUE_DOUBLE_QUOTED;
+ this.state = State.CHARACTER_REFERENCE;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this.currentAttr.value += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInTag);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this.currentAttr.value += String.fromCodePoint(cp);
+ }
+ }
+ }
+ // Attribute value (single-quoted) state
+ //------------------------------------------------------------------
+ _stateAttributeValueSingleQuoted(cp) {
+ switch (cp) {
+ case CODE_POINTS.APOSTROPHE: {
+ this.state = State.AFTER_ATTRIBUTE_VALUE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.AMPERSAND: {
+ this.returnState = State.ATTRIBUTE_VALUE_SINGLE_QUOTED;
+ this.state = State.CHARACTER_REFERENCE;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this.currentAttr.value += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInTag);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this.currentAttr.value += String.fromCodePoint(cp);
+ }
+ }
+ }
+ // Attribute value (unquoted) state
+ //------------------------------------------------------------------
+ _stateAttributeValueUnquoted(cp) {
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ this._leaveAttrValue();
+ this.state = State.BEFORE_ATTRIBUTE_NAME;
+ break;
+ }
+ case CODE_POINTS.AMPERSAND: {
+ this.returnState = State.ATTRIBUTE_VALUE_UNQUOTED;
+ this.state = State.CHARACTER_REFERENCE;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._leaveAttrValue();
+ this.state = State.DATA;
+ this.emitCurrentTagToken();
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this.currentAttr.value += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.QUOTATION_MARK:
+ case CODE_POINTS.APOSTROPHE:
+ case CODE_POINTS.LESS_THAN_SIGN:
+ case CODE_POINTS.EQUALS_SIGN:
+ case CODE_POINTS.GRAVE_ACCENT: {
+ this._err(error_codes_ERR.unexpectedCharacterInUnquotedAttributeValue);
+ this.currentAttr.value += String.fromCodePoint(cp);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInTag);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this.currentAttr.value += String.fromCodePoint(cp);
+ }
+ }
+ }
+ // After attribute value (quoted) state
+ //------------------------------------------------------------------
+ _stateAfterAttributeValueQuoted(cp) {
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ this._leaveAttrValue();
+ this.state = State.BEFORE_ATTRIBUTE_NAME;
+ break;
+ }
+ case CODE_POINTS.SOLIDUS: {
+ this._leaveAttrValue();
+ this.state = State.SELF_CLOSING_START_TAG;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._leaveAttrValue();
+ this.state = State.DATA;
+ this.emitCurrentTagToken();
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInTag);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.missingWhitespaceBetweenAttributes);
+ this.state = State.BEFORE_ATTRIBUTE_NAME;
+ this._stateBeforeAttributeName(cp);
+ }
+ }
+ }
+ // Self-closing start tag state
+ //------------------------------------------------------------------
+ _stateSelfClosingStartTag(cp) {
+ switch (cp) {
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ const token = this.currentToken;
+ token.selfClosing = true;
+ this.state = State.DATA;
+ this.emitCurrentTagToken();
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInTag);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.unexpectedSolidusInTag);
+ this.state = State.BEFORE_ATTRIBUTE_NAME;
+ this._stateBeforeAttributeName(cp);
+ }
+ }
+ }
+ // Bogus comment state
+ //------------------------------------------------------------------
+ _stateBogusComment(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.DATA;
+ this.emitCurrentComment(token);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this.emitCurrentComment(token);
+ this._emitEOFToken();
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ token.data += REPLACEMENT_CHARACTER;
+ break;
+ }
+ default: {
+ token.data += String.fromCodePoint(cp);
+ }
+ }
+ }
+ // Markup declaration open state
+ //------------------------------------------------------------------
+ _stateMarkupDeclarationOpen(cp) {
+ if (this._consumeSequenceIfMatch(SEQUENCES.DASH_DASH, true)) {
+ this._createCommentToken(SEQUENCES.DASH_DASH.length + 1);
+ this.state = State.COMMENT_START;
+ }
+ else if (this._consumeSequenceIfMatch(SEQUENCES.DOCTYPE, false)) {
+ // NOTE: Doctypes tokens are created without fixed offsets. We keep track of the moment a doctype *might* start here.
+ this.currentLocation = this.getCurrentLocation(SEQUENCES.DOCTYPE.length + 1);
+ this.state = State.DOCTYPE;
+ }
+ else if (this._consumeSequenceIfMatch(SEQUENCES.CDATA_START, true)) {
+ if (this.inForeignNode) {
+ this.state = State.CDATA_SECTION;
+ }
+ else {
+ this._err(error_codes_ERR.cdataInHtmlContent);
+ this._createCommentToken(SEQUENCES.CDATA_START.length + 1);
+ this.currentToken.data = '[CDATA[';
+ this.state = State.BOGUS_COMMENT;
+ }
+ }
+ //NOTE: Sequence lookups can be abrupted by hibernation. In that case, lookup
+ //results are no longer valid and we will need to start over.
+ else if (!this._ensureHibernation()) {
+ this._err(error_codes_ERR.incorrectlyOpenedComment);
+ this._createCommentToken(2);
+ this.state = State.BOGUS_COMMENT;
+ this._stateBogusComment(cp);
+ }
+ }
+ // Comment start state
+ //------------------------------------------------------------------
+ _stateCommentStart(cp) {
+ switch (cp) {
+ case CODE_POINTS.HYPHEN_MINUS: {
+ this.state = State.COMMENT_START_DASH;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.abruptClosingOfEmptyComment);
+ this.state = State.DATA;
+ const token = this.currentToken;
+ this.emitCurrentComment(token);
+ break;
+ }
+ default: {
+ this.state = State.COMMENT;
+ this._stateComment(cp);
+ }
+ }
+ }
+ // Comment start dash state
+ //------------------------------------------------------------------
+ _stateCommentStartDash(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.HYPHEN_MINUS: {
+ this.state = State.COMMENT_END;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.abruptClosingOfEmptyComment);
+ this.state = State.DATA;
+ this.emitCurrentComment(token);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInComment);
+ this.emitCurrentComment(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.data += '-';
+ this.state = State.COMMENT;
+ this._stateComment(cp);
+ }
+ }
+ }
+ // Comment state
+ //------------------------------------------------------------------
+ _stateComment(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.HYPHEN_MINUS: {
+ this.state = State.COMMENT_END_DASH;
+ break;
+ }
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ token.data += '<';
+ this.state = State.COMMENT_LESS_THAN_SIGN;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ token.data += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInComment);
+ this.emitCurrentComment(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.data += String.fromCodePoint(cp);
+ }
+ }
+ }
+ // Comment less-than sign state
+ //------------------------------------------------------------------
+ _stateCommentLessThanSign(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.EXCLAMATION_MARK: {
+ token.data += '!';
+ this.state = State.COMMENT_LESS_THAN_SIGN_BANG;
+ break;
+ }
+ case CODE_POINTS.LESS_THAN_SIGN: {
+ token.data += '<';
+ break;
+ }
+ default: {
+ this.state = State.COMMENT;
+ this._stateComment(cp);
+ }
+ }
+ }
+ // Comment less-than sign bang state
+ //------------------------------------------------------------------
+ _stateCommentLessThanSignBang(cp) {
+ if (cp === CODE_POINTS.HYPHEN_MINUS) {
+ this.state = State.COMMENT_LESS_THAN_SIGN_BANG_DASH;
+ }
+ else {
+ this.state = State.COMMENT;
+ this._stateComment(cp);
+ }
+ }
+ // Comment less-than sign bang dash state
+ //------------------------------------------------------------------
+ _stateCommentLessThanSignBangDash(cp) {
+ if (cp === CODE_POINTS.HYPHEN_MINUS) {
+ this.state = State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH;
+ }
+ else {
+ this.state = State.COMMENT_END_DASH;
+ this._stateCommentEndDash(cp);
+ }
+ }
+ // Comment less-than sign bang dash dash state
+ //------------------------------------------------------------------
+ _stateCommentLessThanSignBangDashDash(cp) {
+ if (cp !== CODE_POINTS.GREATER_THAN_SIGN && cp !== CODE_POINTS.EOF) {
+ this._err(error_codes_ERR.nestedComment);
+ }
+ this.state = State.COMMENT_END;
+ this._stateCommentEnd(cp);
+ }
+ // Comment end dash state
+ //------------------------------------------------------------------
+ _stateCommentEndDash(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.HYPHEN_MINUS: {
+ this.state = State.COMMENT_END;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInComment);
+ this.emitCurrentComment(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.data += '-';
+ this.state = State.COMMENT;
+ this._stateComment(cp);
+ }
+ }
+ }
+ // Comment end state
+ //------------------------------------------------------------------
+ _stateCommentEnd(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.DATA;
+ this.emitCurrentComment(token);
+ break;
+ }
+ case CODE_POINTS.EXCLAMATION_MARK: {
+ this.state = State.COMMENT_END_BANG;
+ break;
+ }
+ case CODE_POINTS.HYPHEN_MINUS: {
+ token.data += '-';
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInComment);
+ this.emitCurrentComment(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.data += '--';
+ this.state = State.COMMENT;
+ this._stateComment(cp);
+ }
+ }
+ }
+ // Comment end bang state
+ //------------------------------------------------------------------
+ _stateCommentEndBang(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.HYPHEN_MINUS: {
+ token.data += '--!';
+ this.state = State.COMMENT_END_DASH;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.incorrectlyClosedComment);
+ this.state = State.DATA;
+ this.emitCurrentComment(token);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInComment);
+ this.emitCurrentComment(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.data += '--!';
+ this.state = State.COMMENT;
+ this._stateComment(cp);
+ }
+ }
+ }
+ // DOCTYPE state
+ //------------------------------------------------------------------
+ _stateDoctype(cp) {
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ this.state = State.BEFORE_DOCTYPE_NAME;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.BEFORE_DOCTYPE_NAME;
+ this._stateBeforeDoctypeName(cp);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ this._createDoctypeToken(null);
+ const token = this.currentToken;
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.missingWhitespaceBeforeDoctypeName);
+ this.state = State.BEFORE_DOCTYPE_NAME;
+ this._stateBeforeDoctypeName(cp);
+ }
+ }
+ }
+ // Before DOCTYPE name state
+ //------------------------------------------------------------------
+ _stateBeforeDoctypeName(cp) {
+ if (isAsciiUpper(cp)) {
+ this._createDoctypeToken(String.fromCharCode(toAsciiLower(cp)));
+ this.state = State.DOCTYPE_NAME;
+ }
+ else
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ // Ignore whitespace
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ this._createDoctypeToken(REPLACEMENT_CHARACTER);
+ this.state = State.DOCTYPE_NAME;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.missingDoctypeName);
+ this._createDoctypeToken(null);
+ const token = this.currentToken;
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ this._createDoctypeToken(null);
+ const token = this.currentToken;
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._createDoctypeToken(String.fromCodePoint(cp));
+ this.state = State.DOCTYPE_NAME;
+ }
+ }
+ }
+ // DOCTYPE name state
+ //------------------------------------------------------------------
+ _stateDoctypeName(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ this.state = State.AFTER_DOCTYPE_NAME;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.DATA;
+ this.emitCurrentDoctype(token);
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ token.name += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.name += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
+ }
+ }
+ }
+ // After DOCTYPE name state
+ //------------------------------------------------------------------
+ _stateAfterDoctypeName(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ // Ignore whitespace
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.DATA;
+ this.emitCurrentDoctype(token);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ if (this._consumeSequenceIfMatch(SEQUENCES.PUBLIC, false)) {
+ this.state = State.AFTER_DOCTYPE_PUBLIC_KEYWORD;
+ }
+ else if (this._consumeSequenceIfMatch(SEQUENCES.SYSTEM, false)) {
+ this.state = State.AFTER_DOCTYPE_SYSTEM_KEYWORD;
+ }
+ //NOTE: sequence lookup can be abrupted by hibernation. In that case lookup
+ //results are no longer valid and we will need to start over.
+ else if (!this._ensureHibernation()) {
+ this._err(error_codes_ERR.invalidCharacterSequenceAfterDoctypeName);
+ token.forceQuirks = true;
+ this.state = State.BOGUS_DOCTYPE;
+ this._stateBogusDoctype(cp);
+ }
+ }
+ }
+ }
+ // After DOCTYPE public keyword state
+ //------------------------------------------------------------------
+ _stateAfterDoctypePublicKeyword(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ this.state = State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;
+ break;
+ }
+ case CODE_POINTS.QUOTATION_MARK: {
+ this._err(error_codes_ERR.missingWhitespaceAfterDoctypePublicKeyword);
+ token.publicId = '';
+ this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.APOSTROPHE: {
+ this._err(error_codes_ERR.missingWhitespaceAfterDoctypePublicKeyword);
+ token.publicId = '';
+ this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.missingDoctypePublicIdentifier);
+ token.forceQuirks = true;
+ this.state = State.DATA;
+ this.emitCurrentDoctype(token);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.missingQuoteBeforeDoctypePublicIdentifier);
+ token.forceQuirks = true;
+ this.state = State.BOGUS_DOCTYPE;
+ this._stateBogusDoctype(cp);
+ }
+ }
+ }
+ // Before DOCTYPE public identifier state
+ //------------------------------------------------------------------
+ _stateBeforeDoctypePublicIdentifier(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ // Ignore whitespace
+ break;
+ }
+ case CODE_POINTS.QUOTATION_MARK: {
+ token.publicId = '';
+ this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.APOSTROPHE: {
+ token.publicId = '';
+ this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.missingDoctypePublicIdentifier);
+ token.forceQuirks = true;
+ this.state = State.DATA;
+ this.emitCurrentDoctype(token);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.missingQuoteBeforeDoctypePublicIdentifier);
+ token.forceQuirks = true;
+ this.state = State.BOGUS_DOCTYPE;
+ this._stateBogusDoctype(cp);
+ }
+ }
+ }
+ // DOCTYPE public identifier (double-quoted) state
+ //------------------------------------------------------------------
+ _stateDoctypePublicIdentifierDoubleQuoted(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.QUOTATION_MARK: {
+ this.state = State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ token.publicId += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.abruptDoctypePublicIdentifier);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.publicId += String.fromCodePoint(cp);
+ }
+ }
+ }
+ // DOCTYPE public identifier (single-quoted) state
+ //------------------------------------------------------------------
+ _stateDoctypePublicIdentifierSingleQuoted(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.APOSTROPHE: {
+ this.state = State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ token.publicId += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.abruptDoctypePublicIdentifier);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.publicId += String.fromCodePoint(cp);
+ }
+ }
+ }
+ // After DOCTYPE public identifier state
+ //------------------------------------------------------------------
+ _stateAfterDoctypePublicIdentifier(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ this.state = State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.DATA;
+ this.emitCurrentDoctype(token);
+ break;
+ }
+ case CODE_POINTS.QUOTATION_MARK: {
+ this._err(error_codes_ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);
+ token.systemId = '';
+ this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.APOSTROPHE: {
+ this._err(error_codes_ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);
+ token.systemId = '';
+ this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.missingQuoteBeforeDoctypeSystemIdentifier);
+ token.forceQuirks = true;
+ this.state = State.BOGUS_DOCTYPE;
+ this._stateBogusDoctype(cp);
+ }
+ }
+ }
+ // Between DOCTYPE public and system identifiers state
+ //------------------------------------------------------------------
+ _stateBetweenDoctypePublicAndSystemIdentifiers(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ // Ignore whitespace
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.emitCurrentDoctype(token);
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.QUOTATION_MARK: {
+ token.systemId = '';
+ this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.APOSTROPHE: {
+ token.systemId = '';
+ this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.missingQuoteBeforeDoctypeSystemIdentifier);
+ token.forceQuirks = true;
+ this.state = State.BOGUS_DOCTYPE;
+ this._stateBogusDoctype(cp);
+ }
+ }
+ }
+ // After DOCTYPE system keyword state
+ //------------------------------------------------------------------
+ _stateAfterDoctypeSystemKeyword(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ this.state = State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;
+ break;
+ }
+ case CODE_POINTS.QUOTATION_MARK: {
+ this._err(error_codes_ERR.missingWhitespaceAfterDoctypeSystemKeyword);
+ token.systemId = '';
+ this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.APOSTROPHE: {
+ this._err(error_codes_ERR.missingWhitespaceAfterDoctypeSystemKeyword);
+ token.systemId = '';
+ this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.missingDoctypeSystemIdentifier);
+ token.forceQuirks = true;
+ this.state = State.DATA;
+ this.emitCurrentDoctype(token);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.missingQuoteBeforeDoctypeSystemIdentifier);
+ token.forceQuirks = true;
+ this.state = State.BOGUS_DOCTYPE;
+ this._stateBogusDoctype(cp);
+ }
+ }
+ }
+ // Before DOCTYPE system identifier state
+ //------------------------------------------------------------------
+ _stateBeforeDoctypeSystemIdentifier(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ // Ignore whitespace
+ break;
+ }
+ case CODE_POINTS.QUOTATION_MARK: {
+ token.systemId = '';
+ this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.APOSTROPHE: {
+ token.systemId = '';
+ this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.missingDoctypeSystemIdentifier);
+ token.forceQuirks = true;
+ this.state = State.DATA;
+ this.emitCurrentDoctype(token);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.missingQuoteBeforeDoctypeSystemIdentifier);
+ token.forceQuirks = true;
+ this.state = State.BOGUS_DOCTYPE;
+ this._stateBogusDoctype(cp);
+ }
+ }
+ }
+ // DOCTYPE system identifier (double-quoted) state
+ //------------------------------------------------------------------
+ _stateDoctypeSystemIdentifierDoubleQuoted(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.QUOTATION_MARK: {
+ this.state = State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ token.systemId += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.abruptDoctypeSystemIdentifier);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.systemId += String.fromCodePoint(cp);
+ }
+ }
+ }
+ // DOCTYPE system identifier (single-quoted) state
+ //------------------------------------------------------------------
+ _stateDoctypeSystemIdentifierSingleQuoted(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.APOSTROPHE: {
+ this.state = State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ token.systemId += REPLACEMENT_CHARACTER;
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this._err(error_codes_ERR.abruptDoctypeSystemIdentifier);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ token.systemId += String.fromCodePoint(cp);
+ }
+ }
+ }
+ // After DOCTYPE system identifier state
+ //------------------------------------------------------------------
+ _stateAfterDoctypeSystemIdentifier(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.SPACE:
+ case CODE_POINTS.LINE_FEED:
+ case CODE_POINTS.TABULATION:
+ case CODE_POINTS.FORM_FEED: {
+ // Ignore whitespace
+ break;
+ }
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.emitCurrentDoctype(token);
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInDoctype);
+ token.forceQuirks = true;
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._err(error_codes_ERR.unexpectedCharacterAfterDoctypeSystemIdentifier);
+ this.state = State.BOGUS_DOCTYPE;
+ this._stateBogusDoctype(cp);
+ }
+ }
+ }
+ // Bogus DOCTYPE state
+ //------------------------------------------------------------------
+ _stateBogusDoctype(cp) {
+ const token = this.currentToken;
+ switch (cp) {
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.emitCurrentDoctype(token);
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.NULL: {
+ this._err(error_codes_ERR.unexpectedNullCharacter);
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this.emitCurrentDoctype(token);
+ this._emitEOFToken();
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ // CDATA section state
+ //------------------------------------------------------------------
+ _stateCdataSection(cp) {
+ switch (cp) {
+ case CODE_POINTS.RIGHT_SQUARE_BRACKET: {
+ this.state = State.CDATA_SECTION_BRACKET;
+ break;
+ }
+ case CODE_POINTS.EOF: {
+ this._err(error_codes_ERR.eofInCdata);
+ this._emitEOFToken();
+ break;
+ }
+ default: {
+ this._emitCodePoint(cp);
+ }
+ }
+ }
+ // CDATA section bracket state
+ //------------------------------------------------------------------
+ _stateCdataSectionBracket(cp) {
+ if (cp === CODE_POINTS.RIGHT_SQUARE_BRACKET) {
+ this.state = State.CDATA_SECTION_END;
+ }
+ else {
+ this._emitChars(']');
+ this.state = State.CDATA_SECTION;
+ this._stateCdataSection(cp);
+ }
+ }
+ // CDATA section end state
+ //------------------------------------------------------------------
+ _stateCdataSectionEnd(cp) {
+ switch (cp) {
+ case CODE_POINTS.GREATER_THAN_SIGN: {
+ this.state = State.DATA;
+ break;
+ }
+ case CODE_POINTS.RIGHT_SQUARE_BRACKET: {
+ this._emitChars(']');
+ break;
+ }
+ default: {
+ this._emitChars(']]');
+ this.state = State.CDATA_SECTION;
+ this._stateCdataSection(cp);
+ }
+ }
+ }
+ // Character reference state
+ //------------------------------------------------------------------
+ _stateCharacterReference(cp) {
+ if (cp === CODE_POINTS.NUMBER_SIGN) {
+ this.state = State.NUMERIC_CHARACTER_REFERENCE;
+ }
+ else if (tokenizer_isAsciiAlphaNumeric(cp)) {
+ this.state = State.NAMED_CHARACTER_REFERENCE;
+ this._stateNamedCharacterReference(cp);
+ }
+ else {
+ this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
+ this._reconsumeInState(this.returnState, cp);
+ }
+ }
+ // Named character reference state
+ //------------------------------------------------------------------
+ _stateNamedCharacterReference(cp) {
+ const matchResult = this._matchNamedCharacterReference(cp);
+ //NOTE: Matching can be abrupted by hibernation. In that case, match
+ //results are no longer valid and we will need to start over.
+ if (this._ensureHibernation()) {
+ // Stay in the state, try again.
+ }
+ else if (matchResult) {
+ for (let i = 0; i < matchResult.length; i++) {
+ this._flushCodePointConsumedAsCharacterReference(matchResult[i]);
+ }
+ this.state = this.returnState;
+ }
+ else {
+ this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
+ this.state = State.AMBIGUOUS_AMPERSAND;
+ }
+ }
+ // Ambiguos ampersand state
+ //------------------------------------------------------------------
+ _stateAmbiguousAmpersand(cp) {
+ if (tokenizer_isAsciiAlphaNumeric(cp)) {
+ this._flushCodePointConsumedAsCharacterReference(cp);
+ }
+ else {
+ if (cp === CODE_POINTS.SEMICOLON) {
+ this._err(error_codes_ERR.unknownNamedCharacterReference);
+ }
+ this._reconsumeInState(this.returnState, cp);
+ }
+ }
+ // Numeric character reference state
+ //------------------------------------------------------------------
+ _stateNumericCharacterReference(cp) {
+ this.charRefCode = 0;
+ if (cp === CODE_POINTS.LATIN_SMALL_X || cp === CODE_POINTS.LATIN_CAPITAL_X) {
+ this.state = State.HEXADEMICAL_CHARACTER_REFERENCE_START;
+ }
+ // Inlined decimal character reference start state
+ else if (isAsciiDigit(cp)) {
+ this.state = State.DECIMAL_CHARACTER_REFERENCE;
+ this._stateDecimalCharacterReference(cp);
+ }
+ else {
+ this._err(error_codes_ERR.absenceOfDigitsInNumericCharacterReference);
+ this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
+ this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.NUMBER_SIGN);
+ this._reconsumeInState(this.returnState, cp);
+ }
+ }
+ // Hexademical character reference start state
+ //------------------------------------------------------------------
+ _stateHexademicalCharacterReferenceStart(cp) {
+ if (isAsciiHexDigit(cp)) {
+ this.state = State.HEXADEMICAL_CHARACTER_REFERENCE;
+ this._stateHexademicalCharacterReference(cp);
+ }
+ else {
+ this._err(error_codes_ERR.absenceOfDigitsInNumericCharacterReference);
+ this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
+ this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.NUMBER_SIGN);
+ this._unconsume(2);
+ this.state = this.returnState;
+ }
+ }
+ // Hexademical character reference state
+ //------------------------------------------------------------------
+ _stateHexademicalCharacterReference(cp) {
+ if (isAsciiUpperHexDigit(cp)) {
+ this.charRefCode = this.charRefCode * 16 + cp - 0x37;
+ }
+ else if (isAsciiLowerHexDigit(cp)) {
+ this.charRefCode = this.charRefCode * 16 + cp - 0x57;
+ }
+ else if (isAsciiDigit(cp)) {
+ this.charRefCode = this.charRefCode * 16 + cp - 0x30;
+ }
+ else if (cp === CODE_POINTS.SEMICOLON) {
+ this.state = State.NUMERIC_CHARACTER_REFERENCE_END;
+ }
+ else {
+ this._err(error_codes_ERR.missingSemicolonAfterCharacterReference);
+ this.state = State.NUMERIC_CHARACTER_REFERENCE_END;
+ this._stateNumericCharacterReferenceEnd(cp);
+ }
+ }
+ // Decimal character reference state
+ //------------------------------------------------------------------
+ _stateDecimalCharacterReference(cp) {
+ if (isAsciiDigit(cp)) {
+ this.charRefCode = this.charRefCode * 10 + cp - 0x30;
+ }
+ else if (cp === CODE_POINTS.SEMICOLON) {
+ this.state = State.NUMERIC_CHARACTER_REFERENCE_END;
+ }
+ else {
+ this._err(error_codes_ERR.missingSemicolonAfterCharacterReference);
+ this.state = State.NUMERIC_CHARACTER_REFERENCE_END;
+ this._stateNumericCharacterReferenceEnd(cp);
+ }
+ }
+ // Numeric character reference end state
+ //------------------------------------------------------------------
+ _stateNumericCharacterReferenceEnd(cp) {
+ if (this.charRefCode === CODE_POINTS.NULL) {
+ this._err(error_codes_ERR.nullCharacterReference);
+ this.charRefCode = CODE_POINTS.REPLACEMENT_CHARACTER;
+ }
+ else if (this.charRefCode > 1114111) {
+ this._err(error_codes_ERR.characterReferenceOutsideUnicodeRange);
+ this.charRefCode = CODE_POINTS.REPLACEMENT_CHARACTER;
+ }
+ else if (isSurrogate(this.charRefCode)) {
+ this._err(error_codes_ERR.surrogateCharacterReference);
+ this.charRefCode = CODE_POINTS.REPLACEMENT_CHARACTER;
+ }
+ else if (isUndefinedCodePoint(this.charRefCode)) {
+ this._err(error_codes_ERR.noncharacterCharacterReference);
+ }
+ else if (isControlCodePoint(this.charRefCode) || this.charRefCode === CODE_POINTS.CARRIAGE_RETURN) {
+ this._err(error_codes_ERR.controlCharacterReference);
+ const replacement = C1_CONTROLS_REFERENCE_REPLACEMENTS.get(this.charRefCode);
+ if (replacement !== undefined) {
+ this.charRefCode = replacement;
+ }
+ }
+ this._flushCodePointConsumedAsCharacterReference(this.charRefCode);
+ this._reconsumeInState(this.returnState, cp);
+ }
+}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/parser/open-element-stack.js
+
+//Element utils
+const IMPLICIT_END_TAG_REQUIRED = new Set([TAG_ID.DD, TAG_ID.DT, TAG_ID.LI, TAG_ID.OPTGROUP, TAG_ID.OPTION, TAG_ID.P, TAG_ID.RB, TAG_ID.RP, TAG_ID.RT, TAG_ID.RTC]);
+const IMPLICIT_END_TAG_REQUIRED_THOROUGHLY = new Set([
+ ...IMPLICIT_END_TAG_REQUIRED,
+ TAG_ID.CAPTION,
+ TAG_ID.COLGROUP,
+ TAG_ID.TBODY,
+ TAG_ID.TD,
+ TAG_ID.TFOOT,
+ TAG_ID.TH,
+ TAG_ID.THEAD,
+ TAG_ID.TR,
+]);
+const SCOPING_ELEMENT_NS = new Map([
+ [TAG_ID.APPLET, html_NS.HTML],
+ [TAG_ID.CAPTION, html_NS.HTML],
+ [TAG_ID.HTML, html_NS.HTML],
+ [TAG_ID.MARQUEE, html_NS.HTML],
+ [TAG_ID.OBJECT, html_NS.HTML],
+ [TAG_ID.TABLE, html_NS.HTML],
+ [TAG_ID.TD, html_NS.HTML],
+ [TAG_ID.TEMPLATE, html_NS.HTML],
+ [TAG_ID.TH, html_NS.HTML],
+ [TAG_ID.ANNOTATION_XML, html_NS.MATHML],
+ [TAG_ID.MI, html_NS.MATHML],
+ [TAG_ID.MN, html_NS.MATHML],
+ [TAG_ID.MO, html_NS.MATHML],
+ [TAG_ID.MS, html_NS.MATHML],
+ [TAG_ID.MTEXT, html_NS.MATHML],
+ [TAG_ID.DESC, html_NS.SVG],
+ [TAG_ID.FOREIGN_OBJECT, html_NS.SVG],
+ [TAG_ID.TITLE, html_NS.SVG],
+]);
+const NAMED_HEADERS = [TAG_ID.H1, TAG_ID.H2, TAG_ID.H3, TAG_ID.H4, TAG_ID.H5, TAG_ID.H6];
+const TABLE_ROW_CONTEXT = [TAG_ID.TR, TAG_ID.TEMPLATE, TAG_ID.HTML];
+const TABLE_BODY_CONTEXT = [TAG_ID.TBODY, TAG_ID.TFOOT, TAG_ID.THEAD, TAG_ID.TEMPLATE, TAG_ID.HTML];
+const TABLE_CONTEXT = [TAG_ID.TABLE, TAG_ID.TEMPLATE, TAG_ID.HTML];
+const TABLE_CELLS = [TAG_ID.TD, TAG_ID.TH];
+//Stack of open elements
+class open_element_stack_OpenElementStack {
+ get currentTmplContentOrNode() {
+ return this._isInTemplate() ? this.treeAdapter.getTemplateContent(this.current) : this.current;
+ }
+ constructor(document, treeAdapter, handler) {
+ this.treeAdapter = treeAdapter;
+ this.handler = handler;
+ this.items = [];
+ this.tagIDs = [];
+ this.stackTop = -1;
+ this.tmplCount = 0;
+ this.currentTagId = $.UNKNOWN;
+ this.current = document;
+ }
+ //Index of element
+ _indexOf(element) {
+ return this.items.lastIndexOf(element, this.stackTop);
+ }
+ //Update current element
+ _isInTemplate() {
+ return this.currentTagId === $.TEMPLATE && this.treeAdapter.getNamespaceURI(this.current) === NS.HTML;
+ }
+ _updateCurrentElement() {
+ this.current = this.items[this.stackTop];
+ this.currentTagId = this.tagIDs[this.stackTop];
+ }
+ //Mutations
+ push(element, tagID) {
+ this.stackTop++;
+ this.items[this.stackTop] = element;
+ this.current = element;
+ this.tagIDs[this.stackTop] = tagID;
+ this.currentTagId = tagID;
+ if (this._isInTemplate()) {
+ this.tmplCount++;
+ }
+ this.handler.onItemPush(element, tagID, true);
+ }
+ pop() {
+ const popped = this.current;
+ if (this.tmplCount > 0 && this._isInTemplate()) {
+ this.tmplCount--;
+ }
+ this.stackTop--;
+ this._updateCurrentElement();
+ this.handler.onItemPop(popped, true);
+ }
+ replace(oldElement, newElement) {
+ const idx = this._indexOf(oldElement);
+ this.items[idx] = newElement;
+ if (idx === this.stackTop) {
+ this.current = newElement;
+ }
+ }
+ insertAfter(referenceElement, newElement, newElementID) {
+ const insertionIdx = this._indexOf(referenceElement) + 1;
+ this.items.splice(insertionIdx, 0, newElement);
+ this.tagIDs.splice(insertionIdx, 0, newElementID);
+ this.stackTop++;
+ if (insertionIdx === this.stackTop) {
+ this._updateCurrentElement();
+ }
+ this.handler.onItemPush(this.current, this.currentTagId, insertionIdx === this.stackTop);
+ }
+ popUntilTagNamePopped(tagName) {
+ let targetIdx = this.stackTop + 1;
+ do {
+ targetIdx = this.tagIDs.lastIndexOf(tagName, targetIdx - 1);
+ } while (targetIdx > 0 && this.treeAdapter.getNamespaceURI(this.items[targetIdx]) !== NS.HTML);
+ this.shortenToLength(targetIdx < 0 ? 0 : targetIdx);
+ }
+ shortenToLength(idx) {
+ while (this.stackTop >= idx) {
+ const popped = this.current;
+ if (this.tmplCount > 0 && this._isInTemplate()) {
+ this.tmplCount -= 1;
+ }
+ this.stackTop--;
+ this._updateCurrentElement();
+ this.handler.onItemPop(popped, this.stackTop < idx);
+ }
+ }
+ popUntilElementPopped(element) {
+ const idx = this._indexOf(element);
+ this.shortenToLength(idx < 0 ? 0 : idx);
+ }
+ popUntilPopped(tagNames, targetNS) {
+ const idx = this._indexOfTagNames(tagNames, targetNS);
+ this.shortenToLength(idx < 0 ? 0 : idx);
+ }
+ popUntilNumberedHeaderPopped() {
+ this.popUntilPopped(NAMED_HEADERS, NS.HTML);
+ }
+ popUntilTableCellPopped() {
+ this.popUntilPopped(TABLE_CELLS, NS.HTML);
+ }
+ popAllUpToHtmlElement() {
+ //NOTE: here we assume that the root element is always first in the open element stack, so
+ //we perform this fast stack clean up.
+ this.tmplCount = 0;
+ this.shortenToLength(1);
+ }
+ _indexOfTagNames(tagNames, namespace) {
+ for (let i = this.stackTop; i >= 0; i--) {
+ if (tagNames.includes(this.tagIDs[i]) && this.treeAdapter.getNamespaceURI(this.items[i]) === namespace) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ clearBackTo(tagNames, targetNS) {
+ const idx = this._indexOfTagNames(tagNames, targetNS);
+ this.shortenToLength(idx + 1);
+ }
+ clearBackToTableContext() {
+ this.clearBackTo(TABLE_CONTEXT, NS.HTML);
+ }
+ clearBackToTableBodyContext() {
+ this.clearBackTo(TABLE_BODY_CONTEXT, NS.HTML);
+ }
+ clearBackToTableRowContext() {
+ this.clearBackTo(TABLE_ROW_CONTEXT, NS.HTML);
+ }
+ remove(element) {
+ const idx = this._indexOf(element);
+ if (idx >= 0) {
+ if (idx === this.stackTop) {
+ this.pop();
+ }
+ else {
+ this.items.splice(idx, 1);
+ this.tagIDs.splice(idx, 1);
+ this.stackTop--;
+ this._updateCurrentElement();
+ this.handler.onItemPop(element, false);
+ }
+ }
+ }
+ //Search
+ tryPeekProperlyNestedBodyElement() {
+ //Properly nested element (should be second element in stack).
+ return this.stackTop >= 1 && this.tagIDs[1] === $.BODY ? this.items[1] : null;
+ }
+ contains(element) {
+ return this._indexOf(element) > -1;
+ }
+ getCommonAncestor(element) {
+ const elementIdx = this._indexOf(element) - 1;
+ return elementIdx >= 0 ? this.items[elementIdx] : null;
+ }
+ isRootHtmlElementCurrent() {
+ return this.stackTop === 0 && this.tagIDs[0] === $.HTML;
+ }
+ //Element in scope
+ hasInScope(tagName) {
+ for (let i = this.stackTop; i >= 0; i--) {
+ const tn = this.tagIDs[i];
+ const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
+ if (tn === tagName && ns === NS.HTML) {
+ return true;
+ }
+ if (SCOPING_ELEMENT_NS.get(tn) === ns) {
+ return false;
+ }
+ }
+ return true;
+ }
+ hasNumberedHeaderInScope() {
+ for (let i = this.stackTop; i >= 0; i--) {
+ const tn = this.tagIDs[i];
+ const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
+ if (isNumberedHeader(tn) && ns === NS.HTML) {
+ return true;
+ }
+ if (SCOPING_ELEMENT_NS.get(tn) === ns) {
+ return false;
+ }
+ }
+ return true;
+ }
+ hasInListItemScope(tagName) {
+ for (let i = this.stackTop; i >= 0; i--) {
+ const tn = this.tagIDs[i];
+ const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
+ if (tn === tagName && ns === NS.HTML) {
+ return true;
+ }
+ if (((tn === $.UL || tn === $.OL) && ns === NS.HTML) || SCOPING_ELEMENT_NS.get(tn) === ns) {
+ return false;
+ }
+ }
+ return true;
+ }
+ hasInButtonScope(tagName) {
+ for (let i = this.stackTop; i >= 0; i--) {
+ const tn = this.tagIDs[i];
+ const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
+ if (tn === tagName && ns === NS.HTML) {
+ return true;
+ }
+ if ((tn === $.BUTTON && ns === NS.HTML) || SCOPING_ELEMENT_NS.get(tn) === ns) {
+ return false;
+ }
+ }
+ return true;
+ }
+ hasInTableScope(tagName) {
+ for (let i = this.stackTop; i >= 0; i--) {
+ const tn = this.tagIDs[i];
+ const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
+ if (ns !== NS.HTML) {
+ continue;
+ }
+ if (tn === tagName) {
+ return true;
+ }
+ if (tn === $.TABLE || tn === $.TEMPLATE || tn === $.HTML) {
+ return false;
+ }
+ }
+ return true;
+ }
+ hasTableBodyContextInTableScope() {
+ for (let i = this.stackTop; i >= 0; i--) {
+ const tn = this.tagIDs[i];
+ const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
+ if (ns !== NS.HTML) {
+ continue;
+ }
+ if (tn === $.TBODY || tn === $.THEAD || tn === $.TFOOT) {
+ return true;
+ }
+ if (tn === $.TABLE || tn === $.HTML) {
+ return false;
+ }
+ }
+ return true;
+ }
+ hasInSelectScope(tagName) {
+ for (let i = this.stackTop; i >= 0; i--) {
+ const tn = this.tagIDs[i];
+ const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
+ if (ns !== NS.HTML) {
+ continue;
+ }
+ if (tn === tagName) {
+ return true;
+ }
+ if (tn !== $.OPTION && tn !== $.OPTGROUP) {
+ return false;
+ }
+ }
+ return true;
+ }
+ //Implied end tags
+ generateImpliedEndTags() {
+ while (IMPLICIT_END_TAG_REQUIRED.has(this.currentTagId)) {
+ this.pop();
+ }
+ }
+ generateImpliedEndTagsThoroughly() {
+ while (IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) {
+ this.pop();
+ }
+ }
+ generateImpliedEndTagsWithExclusion(exclusionId) {
+ while (this.currentTagId !== exclusionId && IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) {
+ this.pop();
+ }
+ }
+}
+//# sourceMappingURL=open-element-stack.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/parser/formatting-element-list.js
+//Const
+const NOAH_ARK_CAPACITY = 3;
+var formatting_element_list_EntryType;
+(function (EntryType) {
+ EntryType[EntryType["Marker"] = 0] = "Marker";
+ EntryType[EntryType["Element"] = 1] = "Element";
+})(formatting_element_list_EntryType = formatting_element_list_EntryType || (formatting_element_list_EntryType = {}));
+const MARKER = { type: formatting_element_list_EntryType.Marker };
+//List of formatting elements
+class formatting_element_list_FormattingElementList {
+ constructor(treeAdapter) {
+ this.treeAdapter = treeAdapter;
+ this.entries = [];
+ this.bookmark = null;
+ }
+ //Noah Ark's condition
+ //OPTIMIZATION: at first we try to find possible candidates for exclusion using
+ //lightweight heuristics without thorough attributes check.
+ _getNoahArkConditionCandidates(newElement, neAttrs) {
+ const candidates = [];
+ const neAttrsLength = neAttrs.length;
+ const neTagName = this.treeAdapter.getTagName(newElement);
+ const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement);
+ for (let i = 0; i < this.entries.length; i++) {
+ const entry = this.entries[i];
+ if (entry.type === formatting_element_list_EntryType.Marker) {
+ break;
+ }
+ const { element } = entry;
+ if (this.treeAdapter.getTagName(element) === neTagName &&
+ this.treeAdapter.getNamespaceURI(element) === neNamespaceURI) {
+ const elementAttrs = this.treeAdapter.getAttrList(element);
+ if (elementAttrs.length === neAttrsLength) {
+ candidates.push({ idx: i, attrs: elementAttrs });
+ }
+ }
+ }
+ return candidates;
+ }
+ _ensureNoahArkCondition(newElement) {
+ if (this.entries.length < NOAH_ARK_CAPACITY)
+ return;
+ const neAttrs = this.treeAdapter.getAttrList(newElement);
+ const candidates = this._getNoahArkConditionCandidates(newElement, neAttrs);
+ if (candidates.length < NOAH_ARK_CAPACITY)
+ return;
+ //NOTE: build attrs map for the new element, so we can perform fast lookups
+ const neAttrsMap = new Map(neAttrs.map((neAttr) => [neAttr.name, neAttr.value]));
+ let validCandidates = 0;
+ //NOTE: remove bottommost candidates, until Noah's Ark condition will not be met
+ for (let i = 0; i < candidates.length; i++) {
+ const candidate = candidates[i];
+ // We know that `candidate.attrs.length === neAttrs.length`
+ if (candidate.attrs.every((cAttr) => neAttrsMap.get(cAttr.name) === cAttr.value)) {
+ validCandidates += 1;
+ if (validCandidates >= NOAH_ARK_CAPACITY) {
+ this.entries.splice(candidate.idx, 1);
+ }
+ }
+ }
+ }
+ //Mutations
+ insertMarker() {
+ this.entries.unshift(MARKER);
+ }
+ pushElement(element, token) {
+ this._ensureNoahArkCondition(element);
+ this.entries.unshift({
+ type: formatting_element_list_EntryType.Element,
+ element,
+ token,
+ });
+ }
+ insertElementAfterBookmark(element, token) {
+ const bookmarkIdx = this.entries.indexOf(this.bookmark);
+ this.entries.splice(bookmarkIdx, 0, {
+ type: formatting_element_list_EntryType.Element,
+ element,
+ token,
+ });
+ }
+ removeEntry(entry) {
+ const entryIndex = this.entries.indexOf(entry);
+ if (entryIndex >= 0) {
+ this.entries.splice(entryIndex, 1);
+ }
+ }
+ /**
+ * Clears the list of formatting elements up to the last marker.
+ *
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#clear-the-list-of-active-formatting-elements-up-to-the-last-marker
+ */
+ clearToLastMarker() {
+ const markerIdx = this.entries.indexOf(MARKER);
+ if (markerIdx >= 0) {
+ this.entries.splice(0, markerIdx + 1);
+ }
+ else {
+ this.entries.length = 0;
+ }
+ }
+ //Search
+ getElementEntryInScopeWithTagName(tagName) {
+ const entry = this.entries.find((entry) => entry.type === formatting_element_list_EntryType.Marker || this.treeAdapter.getTagName(entry.element) === tagName);
+ return entry && entry.type === formatting_element_list_EntryType.Element ? entry : null;
+ }
+ getElementEntry(element) {
+ return this.entries.find((entry) => entry.type === formatting_element_list_EntryType.Element && entry.element === element);
+ }
+}
+//# sourceMappingURL=formatting-element-list.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/tree-adapters/default.js
+
+function createTextNode(value) {
+ return {
+ nodeName: '#text',
+ value,
+ parentNode: null,
+ };
+}
+const defaultTreeAdapter = {
+ //Node construction
+ createDocument() {
+ return {
+ nodeName: '#document',
+ mode: html_DOCUMENT_MODE.NO_QUIRKS,
+ childNodes: [],
+ };
+ },
+ createDocumentFragment() {
+ return {
+ nodeName: '#document-fragment',
+ childNodes: [],
+ };
+ },
+ createElement(tagName, namespaceURI, attrs) {
+ return {
+ nodeName: tagName,
+ tagName,
+ attrs,
+ namespaceURI,
+ childNodes: [],
+ parentNode: null,
+ };
+ },
+ createCommentNode(data) {
+ return {
+ nodeName: '#comment',
+ data,
+ parentNode: null,
+ };
+ },
+ //Tree mutation
+ appendChild(parentNode, newNode) {
+ parentNode.childNodes.push(newNode);
+ newNode.parentNode = parentNode;
+ },
+ insertBefore(parentNode, newNode, referenceNode) {
+ const insertionIdx = parentNode.childNodes.indexOf(referenceNode);
+ parentNode.childNodes.splice(insertionIdx, 0, newNode);
+ newNode.parentNode = parentNode;
+ },
+ setTemplateContent(templateElement, contentElement) {
+ templateElement.content = contentElement;
+ },
+ getTemplateContent(templateElement) {
+ return templateElement.content;
+ },
+ setDocumentType(document, name, publicId, systemId) {
+ const doctypeNode = document.childNodes.find((node) => node.nodeName === '#documentType');
+ if (doctypeNode) {
+ doctypeNode.name = name;
+ doctypeNode.publicId = publicId;
+ doctypeNode.systemId = systemId;
+ }
+ else {
+ const node = {
+ nodeName: '#documentType',
+ name,
+ publicId,
+ systemId,
+ parentNode: null,
+ };
+ defaultTreeAdapter.appendChild(document, node);
+ }
+ },
+ setDocumentMode(document, mode) {
+ document.mode = mode;
+ },
+ getDocumentMode(document) {
+ return document.mode;
+ },
+ detachNode(node) {
+ if (node.parentNode) {
+ const idx = node.parentNode.childNodes.indexOf(node);
+ node.parentNode.childNodes.splice(idx, 1);
+ node.parentNode = null;
+ }
+ },
+ insertText(parentNode, text) {
+ if (parentNode.childNodes.length > 0) {
+ const prevNode = parentNode.childNodes[parentNode.childNodes.length - 1];
+ if (defaultTreeAdapter.isTextNode(prevNode)) {
+ prevNode.value += text;
+ return;
+ }
+ }
+ defaultTreeAdapter.appendChild(parentNode, createTextNode(text));
+ },
+ insertTextBefore(parentNode, text, referenceNode) {
+ const prevNode = parentNode.childNodes[parentNode.childNodes.indexOf(referenceNode) - 1];
+ if (prevNode && defaultTreeAdapter.isTextNode(prevNode)) {
+ prevNode.value += text;
+ }
+ else {
+ defaultTreeAdapter.insertBefore(parentNode, createTextNode(text), referenceNode);
+ }
+ },
+ adoptAttributes(recipient, attrs) {
+ const recipientAttrsMap = new Set(recipient.attrs.map((attr) => attr.name));
+ for (let j = 0; j < attrs.length; j++) {
+ if (!recipientAttrsMap.has(attrs[j].name)) {
+ recipient.attrs.push(attrs[j]);
+ }
+ }
+ },
+ //Tree traversing
+ getFirstChild(node) {
+ return node.childNodes[0];
+ },
+ getChildNodes(node) {
+ return node.childNodes;
+ },
+ getParentNode(node) {
+ return node.parentNode;
+ },
+ getAttrList(element) {
+ return element.attrs;
+ },
+ //Node data
+ getTagName(element) {
+ return element.tagName;
+ },
+ getNamespaceURI(element) {
+ return element.namespaceURI;
+ },
+ getTextNodeContent(textNode) {
+ return textNode.value;
+ },
+ getCommentNodeContent(commentNode) {
+ return commentNode.data;
+ },
+ getDocumentTypeNodeName(doctypeNode) {
+ return doctypeNode.name;
+ },
+ getDocumentTypeNodePublicId(doctypeNode) {
+ return doctypeNode.publicId;
+ },
+ getDocumentTypeNodeSystemId(doctypeNode) {
+ return doctypeNode.systemId;
+ },
+ //Node types
+ isTextNode(node) {
+ return node.nodeName === '#text';
+ },
+ isCommentNode(node) {
+ return node.nodeName === '#comment';
+ },
+ isDocumentTypeNode(node) {
+ return node.nodeName === '#documentType';
+ },
+ isElementNode(node) {
+ return Object.prototype.hasOwnProperty.call(node, 'tagName');
+ },
+ // Source code location
+ setNodeSourceCodeLocation(node, location) {
+ node.sourceCodeLocation = location;
+ },
+ getNodeSourceCodeLocation(node) {
+ return node.sourceCodeLocation;
+ },
+ updateNodeSourceCodeLocation(node, endLocation) {
+ node.sourceCodeLocation = { ...node.sourceCodeLocation, ...endLocation };
+ },
+};
+//# sourceMappingURL=default.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/common/doctype.js
+
+//Const
+const VALID_DOCTYPE_NAME = 'html';
+const VALID_SYSTEM_ID = 'about:legacy-compat';
+const QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd';
+const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [
+ '+//silmaril//dtd html pro v0r11 19970101//',
+ '-//as//dtd html 3.0 aswedit + extensions//',
+ '-//advasoft ltd//dtd html 3.0 aswedit + extensions//',
+ '-//ietf//dtd html 2.0 level 1//',
+ '-//ietf//dtd html 2.0 level 2//',
+ '-//ietf//dtd html 2.0 strict level 1//',
+ '-//ietf//dtd html 2.0 strict level 2//',
+ '-//ietf//dtd html 2.0 strict//',
+ '-//ietf//dtd html 2.0//',
+ '-//ietf//dtd html 2.1e//',
+ '-//ietf//dtd html 3.0//',
+ '-//ietf//dtd html 3.2 final//',
+ '-//ietf//dtd html 3.2//',
+ '-//ietf//dtd html 3//',
+ '-//ietf//dtd html level 0//',
+ '-//ietf//dtd html level 1//',
+ '-//ietf//dtd html level 2//',
+ '-//ietf//dtd html level 3//',
+ '-//ietf//dtd html strict level 0//',
+ '-//ietf//dtd html strict level 1//',
+ '-//ietf//dtd html strict level 2//',
+ '-//ietf//dtd html strict level 3//',
+ '-//ietf//dtd html strict//',
+ '-//ietf//dtd html//',
+ '-//metrius//dtd metrius presentational//',
+ '-//microsoft//dtd internet explorer 2.0 html strict//',
+ '-//microsoft//dtd internet explorer 2.0 html//',
+ '-//microsoft//dtd internet explorer 2.0 tables//',
+ '-//microsoft//dtd internet explorer 3.0 html strict//',
+ '-//microsoft//dtd internet explorer 3.0 html//',
+ '-//microsoft//dtd internet explorer 3.0 tables//',
+ '-//netscape comm. corp.//dtd html//',
+ '-//netscape comm. corp.//dtd strict html//',
+ "-//o'reilly and associates//dtd html 2.0//",
+ "-//o'reilly and associates//dtd html extended 1.0//",
+ "-//o'reilly and associates//dtd html extended relaxed 1.0//",
+ '-//sq//dtd html 2.0 hotmetal + extensions//',
+ '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//',
+ '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//',
+ '-//spyglass//dtd html 2.0 extended//',
+ '-//sun microsystems corp.//dtd hotjava html//',
+ '-//sun microsystems corp.//dtd hotjava strict html//',
+ '-//w3c//dtd html 3 1995-03-24//',
+ '-//w3c//dtd html 3.2 draft//',
+ '-//w3c//dtd html 3.2 final//',
+ '-//w3c//dtd html 3.2//',
+ '-//w3c//dtd html 3.2s draft//',
+ '-//w3c//dtd html 4.0 frameset//',
+ '-//w3c//dtd html 4.0 transitional//',
+ '-//w3c//dtd html experimental 19960712//',
+ '-//w3c//dtd html experimental 970421//',
+ '-//w3c//dtd w3 html//',
+ '-//w3o//dtd w3 html 3.0//',
+ '-//webtechs//dtd mozilla html 2.0//',
+ '-//webtechs//dtd mozilla html//',
+];
+const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = [
+ ...QUIRKS_MODE_PUBLIC_ID_PREFIXES,
+ '-//w3c//dtd html 4.01 frameset//',
+ '-//w3c//dtd html 4.01 transitional//',
+];
+const QUIRKS_MODE_PUBLIC_IDS = new Set([
+ '-//w3o//dtd w3 html strict 3.0//en//',
+ '-/w3c/dtd html 4.0 transitional/en',
+ 'html',
+]);
+const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//'];
+const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = [
+ ...LIMITED_QUIRKS_PUBLIC_ID_PREFIXES,
+ '-//w3c//dtd html 4.01 frameset//',
+ '-//w3c//dtd html 4.01 transitional//',
+];
+//Utils
+function hasPrefix(publicId, prefixes) {
+ return prefixes.some((prefix) => publicId.startsWith(prefix));
+}
+//API
+function isConforming(token) {
+ return (token.name === VALID_DOCTYPE_NAME &&
+ token.publicId === null &&
+ (token.systemId === null || token.systemId === VALID_SYSTEM_ID));
+}
+function getDocumentMode(token) {
+ if (token.name !== VALID_DOCTYPE_NAME) {
+ return DOCUMENT_MODE.QUIRKS;
+ }
+ const { systemId } = token;
+ if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) {
+ return DOCUMENT_MODE.QUIRKS;
+ }
+ let { publicId } = token;
+ if (publicId !== null) {
+ publicId = publicId.toLowerCase();
+ if (QUIRKS_MODE_PUBLIC_IDS.has(publicId)) {
+ return DOCUMENT_MODE.QUIRKS;
+ }
+ let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES;
+ if (hasPrefix(publicId, prefixes)) {
+ return DOCUMENT_MODE.QUIRKS;
+ }
+ prefixes =
+ systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES;
+ if (hasPrefix(publicId, prefixes)) {
+ return DOCUMENT_MODE.LIMITED_QUIRKS;
+ }
+ }
+ return DOCUMENT_MODE.NO_QUIRKS;
+}
+//# sourceMappingURL=doctype.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/common/foreign-content.js
+
+//MIME types
+const MIME_TYPES = {
+ TEXT_HTML: 'text/html',
+ APPLICATION_XML: 'application/xhtml+xml',
+};
+//Attributes
+const DEFINITION_URL_ATTR = 'definitionurl';
+const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL';
+const SVG_ATTRS_ADJUSTMENT_MAP = new Map([
+ 'attributeName',
+ 'attributeType',
+ 'baseFrequency',
+ 'baseProfile',
+ 'calcMode',
+ 'clipPathUnits',
+ 'diffuseConstant',
+ 'edgeMode',
+ 'filterUnits',
+ 'glyphRef',
+ 'gradientTransform',
+ 'gradientUnits',
+ 'kernelMatrix',
+ 'kernelUnitLength',
+ 'keyPoints',
+ 'keySplines',
+ 'keyTimes',
+ 'lengthAdjust',
+ 'limitingConeAngle',
+ 'markerHeight',
+ 'markerUnits',
+ 'markerWidth',
+ 'maskContentUnits',
+ 'maskUnits',
+ 'numOctaves',
+ 'pathLength',
+ 'patternContentUnits',
+ 'patternTransform',
+ 'patternUnits',
+ 'pointsAtX',
+ 'pointsAtY',
+ 'pointsAtZ',
+ 'preserveAlpha',
+ 'preserveAspectRatio',
+ 'primitiveUnits',
+ 'refX',
+ 'refY',
+ 'repeatCount',
+ 'repeatDur',
+ 'requiredExtensions',
+ 'requiredFeatures',
+ 'specularConstant',
+ 'specularExponent',
+ 'spreadMethod',
+ 'startOffset',
+ 'stdDeviation',
+ 'stitchTiles',
+ 'surfaceScale',
+ 'systemLanguage',
+ 'tableValues',
+ 'targetX',
+ 'targetY',
+ 'textLength',
+ 'viewBox',
+ 'viewTarget',
+ 'xChannelSelector',
+ 'yChannelSelector',
+ 'zoomAndPan',
+].map((attr) => [attr.toLowerCase(), attr]));
+const XML_ATTRS_ADJUSTMENT_MAP = new Map([
+ ['xlink:actuate', { prefix: 'xlink', name: 'actuate', namespace: html_NS.XLINK }],
+ ['xlink:arcrole', { prefix: 'xlink', name: 'arcrole', namespace: html_NS.XLINK }],
+ ['xlink:href', { prefix: 'xlink', name: 'href', namespace: html_NS.XLINK }],
+ ['xlink:role', { prefix: 'xlink', name: 'role', namespace: html_NS.XLINK }],
+ ['xlink:show', { prefix: 'xlink', name: 'show', namespace: html_NS.XLINK }],
+ ['xlink:title', { prefix: 'xlink', name: 'title', namespace: html_NS.XLINK }],
+ ['xlink:type', { prefix: 'xlink', name: 'type', namespace: html_NS.XLINK }],
+ ['xml:base', { prefix: 'xml', name: 'base', namespace: html_NS.XML }],
+ ['xml:lang', { prefix: 'xml', name: 'lang', namespace: html_NS.XML }],
+ ['xml:space', { prefix: 'xml', name: 'space', namespace: html_NS.XML }],
+ ['xmlns', { prefix: '', name: 'xmlns', namespace: html_NS.XMLNS }],
+ ['xmlns:xlink', { prefix: 'xmlns', name: 'xlink', namespace: html_NS.XMLNS }],
+]);
+//SVG tag names adjustment map
+const SVG_TAG_NAMES_ADJUSTMENT_MAP = new Map([
+ 'altGlyph',
+ 'altGlyphDef',
+ 'altGlyphItem',
+ 'animateColor',
+ 'animateMotion',
+ 'animateTransform',
+ 'clipPath',
+ 'feBlend',
+ 'feColorMatrix',
+ 'feComponentTransfer',
+ 'feComposite',
+ 'feConvolveMatrix',
+ 'feDiffuseLighting',
+ 'feDisplacementMap',
+ 'feDistantLight',
+ 'feFlood',
+ 'feFuncA',
+ 'feFuncB',
+ 'feFuncG',
+ 'feFuncR',
+ 'feGaussianBlur',
+ 'feImage',
+ 'feMerge',
+ 'feMergeNode',
+ 'feMorphology',
+ 'feOffset',
+ 'fePointLight',
+ 'feSpecularLighting',
+ 'feSpotLight',
+ 'feTile',
+ 'feTurbulence',
+ 'foreignObject',
+ 'glyphRef',
+ 'linearGradient',
+ 'radialGradient',
+ 'textPath',
+].map((tn) => [tn.toLowerCase(), tn]));
+//Tags that causes exit from foreign content
+const EXITS_FOREIGN_CONTENT = new Set([
+ TAG_ID.B,
+ TAG_ID.BIG,
+ TAG_ID.BLOCKQUOTE,
+ TAG_ID.BODY,
+ TAG_ID.BR,
+ TAG_ID.CENTER,
+ TAG_ID.CODE,
+ TAG_ID.DD,
+ TAG_ID.DIV,
+ TAG_ID.DL,
+ TAG_ID.DT,
+ TAG_ID.EM,
+ TAG_ID.EMBED,
+ TAG_ID.H1,
+ TAG_ID.H2,
+ TAG_ID.H3,
+ TAG_ID.H4,
+ TAG_ID.H5,
+ TAG_ID.H6,
+ TAG_ID.HEAD,
+ TAG_ID.HR,
+ TAG_ID.I,
+ TAG_ID.IMG,
+ TAG_ID.LI,
+ TAG_ID.LISTING,
+ TAG_ID.MENU,
+ TAG_ID.META,
+ TAG_ID.NOBR,
+ TAG_ID.OL,
+ TAG_ID.P,
+ TAG_ID.PRE,
+ TAG_ID.RUBY,
+ TAG_ID.S,
+ TAG_ID.SMALL,
+ TAG_ID.SPAN,
+ TAG_ID.STRONG,
+ TAG_ID.STRIKE,
+ TAG_ID.SUB,
+ TAG_ID.SUP,
+ TAG_ID.TABLE,
+ TAG_ID.TT,
+ TAG_ID.U,
+ TAG_ID.UL,
+ TAG_ID.VAR,
+]);
+//Check exit from foreign content
+function causesExit(startTagToken) {
+ const tn = startTagToken.tagID;
+ const isFontWithAttrs = tn === TAG_ID.FONT &&
+ startTagToken.attrs.some(({ name }) => name === html_ATTRS.COLOR || name === html_ATTRS.SIZE || name === html_ATTRS.FACE);
+ return isFontWithAttrs || EXITS_FOREIGN_CONTENT.has(tn);
+}
+//Token adjustments
+function adjustTokenMathMLAttrs(token) {
+ for (let i = 0; i < token.attrs.length; i++) {
+ if (token.attrs[i].name === DEFINITION_URL_ATTR) {
+ token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR;
+ break;
+ }
+ }
+}
+function adjustTokenSVGAttrs(token) {
+ for (let i = 0; i < token.attrs.length; i++) {
+ const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);
+ if (adjustedAttrName != null) {
+ token.attrs[i].name = adjustedAttrName;
+ }
+ }
+}
+function adjustTokenXMLAttrs(token) {
+ for (let i = 0; i < token.attrs.length; i++) {
+ const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);
+ if (adjustedAttrEntry) {
+ token.attrs[i].prefix = adjustedAttrEntry.prefix;
+ token.attrs[i].name = adjustedAttrEntry.name;
+ token.attrs[i].namespace = adjustedAttrEntry.namespace;
+ }
+ }
+}
+function adjustTokenSVGTagName(token) {
+ const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName);
+ if (adjustedTagName != null) {
+ token.tagName = adjustedTagName;
+ token.tagID = html_getTagID(token.tagName);
+ }
+}
+//Integration points
+function isMathMLTextIntegrationPoint(tn, ns) {
+ return ns === html_NS.MATHML && (tn === TAG_ID.MI || tn === TAG_ID.MO || tn === TAG_ID.MN || tn === TAG_ID.MS || tn === TAG_ID.MTEXT);
+}
+function isHtmlIntegrationPoint(tn, ns, attrs) {
+ if (ns === html_NS.MATHML && tn === TAG_ID.ANNOTATION_XML) {
+ for (let i = 0; i < attrs.length; i++) {
+ if (attrs[i].name === html_ATTRS.ENCODING) {
+ const value = attrs[i].value.toLowerCase();
+ return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML;
+ }
+ }
+ }
+ return ns === html_NS.SVG && (tn === TAG_ID.FOREIGN_OBJECT || tn === TAG_ID.DESC || tn === TAG_ID.TITLE);
+}
+function isIntegrationPoint(tn, ns, attrs, foreignNS) {
+ return (((!foreignNS || foreignNS === html_NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) ||
+ ((!foreignNS || foreignNS === html_NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns)));
+}
+//# sourceMappingURL=foreign-content.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/parser/index.js
+
+
+
+
+
+
+
+
+
+
+//Misc constants
+const HIDDEN_INPUT_TYPE = 'hidden';
+//Adoption agency loops iteration count
+const AA_OUTER_LOOP_ITER = 8;
+const AA_INNER_LOOP_ITER = 3;
+//Insertion modes
+var InsertionMode;
+(function (InsertionMode) {
+ InsertionMode[InsertionMode["INITIAL"] = 0] = "INITIAL";
+ InsertionMode[InsertionMode["BEFORE_HTML"] = 1] = "BEFORE_HTML";
+ InsertionMode[InsertionMode["BEFORE_HEAD"] = 2] = "BEFORE_HEAD";
+ InsertionMode[InsertionMode["IN_HEAD"] = 3] = "IN_HEAD";
+ InsertionMode[InsertionMode["IN_HEAD_NO_SCRIPT"] = 4] = "IN_HEAD_NO_SCRIPT";
+ InsertionMode[InsertionMode["AFTER_HEAD"] = 5] = "AFTER_HEAD";
+ InsertionMode[InsertionMode["IN_BODY"] = 6] = "IN_BODY";
+ InsertionMode[InsertionMode["TEXT"] = 7] = "TEXT";
+ InsertionMode[InsertionMode["IN_TABLE"] = 8] = "IN_TABLE";
+ InsertionMode[InsertionMode["IN_TABLE_TEXT"] = 9] = "IN_TABLE_TEXT";
+ InsertionMode[InsertionMode["IN_CAPTION"] = 10] = "IN_CAPTION";
+ InsertionMode[InsertionMode["IN_COLUMN_GROUP"] = 11] = "IN_COLUMN_GROUP";
+ InsertionMode[InsertionMode["IN_TABLE_BODY"] = 12] = "IN_TABLE_BODY";
+ InsertionMode[InsertionMode["IN_ROW"] = 13] = "IN_ROW";
+ InsertionMode[InsertionMode["IN_CELL"] = 14] = "IN_CELL";
+ InsertionMode[InsertionMode["IN_SELECT"] = 15] = "IN_SELECT";
+ InsertionMode[InsertionMode["IN_SELECT_IN_TABLE"] = 16] = "IN_SELECT_IN_TABLE";
+ InsertionMode[InsertionMode["IN_TEMPLATE"] = 17] = "IN_TEMPLATE";
+ InsertionMode[InsertionMode["AFTER_BODY"] = 18] = "AFTER_BODY";
+ InsertionMode[InsertionMode["IN_FRAMESET"] = 19] = "IN_FRAMESET";
+ InsertionMode[InsertionMode["AFTER_FRAMESET"] = 20] = "AFTER_FRAMESET";
+ InsertionMode[InsertionMode["AFTER_AFTER_BODY"] = 21] = "AFTER_AFTER_BODY";
+ InsertionMode[InsertionMode["AFTER_AFTER_FRAMESET"] = 22] = "AFTER_AFTER_FRAMESET";
+})(InsertionMode || (InsertionMode = {}));
+const BASE_LOC = {
+ startLine: -1,
+ startCol: -1,
+ startOffset: -1,
+ endLine: -1,
+ endCol: -1,
+ endOffset: -1,
+};
+const TABLE_STRUCTURE_TAGS = new Set([TAG_ID.TABLE, TAG_ID.TBODY, TAG_ID.TFOOT, TAG_ID.THEAD, TAG_ID.TR]);
+const defaultParserOptions = {
+ scriptingEnabled: true,
+ sourceCodeLocationInfo: false,
+ treeAdapter: defaultTreeAdapter,
+ onParseError: null,
+};
+//Parser
+class parser_Parser {
+ constructor(options, document, fragmentContext = null, scriptHandler = null) {
+ this.fragmentContext = fragmentContext;
+ this.scriptHandler = scriptHandler;
+ this.currentToken = null;
+ this.stopped = false;
+ this.insertionMode = InsertionMode.INITIAL;
+ this.originalInsertionMode = InsertionMode.INITIAL;
+ this.headElement = null;
+ this.formElement = null;
+ /** Indicates that the current node is not an element in the HTML namespace */
+ this.currentNotInHTML = false;
+ /**
+ * The template insertion mode stack is maintained from the left.
+ * Ie. the topmost element will always have index 0.
+ */
+ this.tmplInsertionModeStack = [];
+ this.pendingCharacterTokens = [];
+ this.hasNonWhitespacePendingCharacterToken = false;
+ this.framesetOk = true;
+ this.skipNextNewLine = false;
+ this.fosterParentingEnabled = false;
+ this.options = {
+ ...defaultParserOptions,
+ ...options,
+ };
+ this.treeAdapter = this.options.treeAdapter;
+ this.onParseError = this.options.onParseError;
+ // Always enable location info if we report parse errors.
+ if (this.onParseError) {
+ this.options.sourceCodeLocationInfo = true;
+ }
+ this.document = document !== null && document !== void 0 ? document : this.treeAdapter.createDocument();
+ this.tokenizer = new Tokenizer(this.options, this);
+ this.activeFormattingElements = new FormattingElementList(this.treeAdapter);
+ this.fragmentContextID = fragmentContext ? getTagID(this.treeAdapter.getTagName(fragmentContext)) : $.UNKNOWN;
+ this._setContextModes(fragmentContext !== null && fragmentContext !== void 0 ? fragmentContext : this.document, this.fragmentContextID);
+ this.openElements = new OpenElementStack(this.document, this.treeAdapter, this);
+ }
+ // API
+ static parse(html, options) {
+ const parser = new this(options);
+ parser.tokenizer.write(html, true);
+ return parser.document;
+ }
+ static getFragmentParser(fragmentContext, options) {
+ const opts = {
+ ...defaultParserOptions,
+ ...options,
+ };
+ //NOTE: use a element as the fragment context if no context element was provided,
+ //so we will parse in a "forgiving" manner
+ fragmentContext !== null && fragmentContext !== void 0 ? fragmentContext : (fragmentContext = opts.treeAdapter.createElement(TN.TEMPLATE, NS.HTML, []));
+ //NOTE: create a fake element which will be used as the `document` for fragment parsing.
+ //This is important for jsdom, where a new `document` cannot be created. This led to
+ //fragment parsing messing with the main `document`.
+ const documentMock = opts.treeAdapter.createElement('documentmock', NS.HTML, []);
+ const parser = new this(opts, documentMock, fragmentContext);
+ if (parser.fragmentContextID === $.TEMPLATE) {
+ parser.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE);
+ }
+ parser._initTokenizerForFragmentParsing();
+ parser._insertFakeRootElement();
+ parser._resetInsertionMode();
+ parser._findFormInFragmentContext();
+ return parser;
+ }
+ getFragment() {
+ const rootElement = this.treeAdapter.getFirstChild(this.document);
+ const fragment = this.treeAdapter.createDocumentFragment();
+ this._adoptNodes(rootElement, fragment);
+ return fragment;
+ }
+ //Errors
+ _err(token, code, beforeToken) {
+ var _a;
+ if (!this.onParseError)
+ return;
+ const loc = (_a = token.location) !== null && _a !== void 0 ? _a : BASE_LOC;
+ const err = {
+ code,
+ startLine: loc.startLine,
+ startCol: loc.startCol,
+ startOffset: loc.startOffset,
+ endLine: beforeToken ? loc.startLine : loc.endLine,
+ endCol: beforeToken ? loc.startCol : loc.endCol,
+ endOffset: beforeToken ? loc.startOffset : loc.endOffset,
+ };
+ this.onParseError(err);
+ }
+ //Stack events
+ onItemPush(node, tid, isTop) {
+ var _a, _b;
+ (_b = (_a = this.treeAdapter).onItemPush) === null || _b === void 0 ? void 0 : _b.call(_a, node);
+ if (isTop && this.openElements.stackTop > 0)
+ this._setContextModes(node, tid);
+ }
+ onItemPop(node, isTop) {
+ var _a, _b;
+ if (this.options.sourceCodeLocationInfo) {
+ this._setEndLocation(node, this.currentToken);
+ }
+ (_b = (_a = this.treeAdapter).onItemPop) === null || _b === void 0 ? void 0 : _b.call(_a, node, this.openElements.current);
+ if (isTop) {
+ let current;
+ let currentTagId;
+ if (this.openElements.stackTop === 0 && this.fragmentContext) {
+ current = this.fragmentContext;
+ currentTagId = this.fragmentContextID;
+ }
+ else {
+ ({ current, currentTagId } = this.openElements);
+ }
+ this._setContextModes(current, currentTagId);
+ }
+ }
+ _setContextModes(current, tid) {
+ const isHTML = current === this.document || this.treeAdapter.getNamespaceURI(current) === NS.HTML;
+ this.currentNotInHTML = !isHTML;
+ this.tokenizer.inForeignNode = !isHTML && !this._isIntegrationPoint(tid, current);
+ }
+ _switchToTextParsing(currentToken, nextTokenizerState) {
+ this._insertElement(currentToken, NS.HTML);
+ this.tokenizer.state = nextTokenizerState;
+ this.originalInsertionMode = this.insertionMode;
+ this.insertionMode = InsertionMode.TEXT;
+ }
+ switchToPlaintextParsing() {
+ this.insertionMode = InsertionMode.TEXT;
+ this.originalInsertionMode = InsertionMode.IN_BODY;
+ this.tokenizer.state = TokenizerMode.PLAINTEXT;
+ }
+ //Fragment parsing
+ _getAdjustedCurrentElement() {
+ return this.openElements.stackTop === 0 && this.fragmentContext
+ ? this.fragmentContext
+ : this.openElements.current;
+ }
+ _findFormInFragmentContext() {
+ let node = this.fragmentContext;
+ while (node) {
+ if (this.treeAdapter.getTagName(node) === TN.FORM) {
+ this.formElement = node;
+ break;
+ }
+ node = this.treeAdapter.getParentNode(node);
+ }
+ }
+ _initTokenizerForFragmentParsing() {
+ if (!this.fragmentContext || this.treeAdapter.getNamespaceURI(this.fragmentContext) !== NS.HTML) {
+ return;
+ }
+ switch (this.fragmentContextID) {
+ case $.TITLE:
+ case $.TEXTAREA: {
+ this.tokenizer.state = TokenizerMode.RCDATA;
+ break;
+ }
+ case $.STYLE:
+ case $.XMP:
+ case $.IFRAME:
+ case $.NOEMBED:
+ case $.NOFRAMES:
+ case $.NOSCRIPT: {
+ this.tokenizer.state = TokenizerMode.RAWTEXT;
+ break;
+ }
+ case $.SCRIPT: {
+ this.tokenizer.state = TokenizerMode.SCRIPT_DATA;
+ break;
+ }
+ case $.PLAINTEXT: {
+ this.tokenizer.state = TokenizerMode.PLAINTEXT;
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ //Tree mutation
+ _setDocumentType(token) {
+ const name = token.name || '';
+ const publicId = token.publicId || '';
+ const systemId = token.systemId || '';
+ this.treeAdapter.setDocumentType(this.document, name, publicId, systemId);
+ if (token.location) {
+ const documentChildren = this.treeAdapter.getChildNodes(this.document);
+ const docTypeNode = documentChildren.find((node) => this.treeAdapter.isDocumentTypeNode(node));
+ if (docTypeNode) {
+ this.treeAdapter.setNodeSourceCodeLocation(docTypeNode, token.location);
+ }
+ }
+ }
+ _attachElementToTree(element, location) {
+ if (this.options.sourceCodeLocationInfo) {
+ const loc = location && {
+ ...location,
+ startTag: location,
+ };
+ this.treeAdapter.setNodeSourceCodeLocation(element, loc);
+ }
+ if (this._shouldFosterParentOnInsertion()) {
+ this._fosterParentElement(element);
+ }
+ else {
+ const parent = this.openElements.currentTmplContentOrNode;
+ this.treeAdapter.appendChild(parent, element);
+ }
+ }
+ _appendElement(token, namespaceURI) {
+ const element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);
+ this._attachElementToTree(element, token.location);
+ }
+ _insertElement(token, namespaceURI) {
+ const element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);
+ this._attachElementToTree(element, token.location);
+ this.openElements.push(element, token.tagID);
+ }
+ _insertFakeElement(tagName, tagID) {
+ const element = this.treeAdapter.createElement(tagName, NS.HTML, []);
+ this._attachElementToTree(element, null);
+ this.openElements.push(element, tagID);
+ }
+ _insertTemplate(token) {
+ const tmpl = this.treeAdapter.createElement(token.tagName, NS.HTML, token.attrs);
+ const content = this.treeAdapter.createDocumentFragment();
+ this.treeAdapter.setTemplateContent(tmpl, content);
+ this._attachElementToTree(tmpl, token.location);
+ this.openElements.push(tmpl, token.tagID);
+ if (this.options.sourceCodeLocationInfo)
+ this.treeAdapter.setNodeSourceCodeLocation(content, null);
+ }
+ _insertFakeRootElement() {
+ const element = this.treeAdapter.createElement(TN.HTML, NS.HTML, []);
+ if (this.options.sourceCodeLocationInfo)
+ this.treeAdapter.setNodeSourceCodeLocation(element, null);
+ this.treeAdapter.appendChild(this.openElements.current, element);
+ this.openElements.push(element, $.HTML);
+ }
+ _appendCommentNode(token, parent) {
+ const commentNode = this.treeAdapter.createCommentNode(token.data);
+ this.treeAdapter.appendChild(parent, commentNode);
+ if (this.options.sourceCodeLocationInfo) {
+ this.treeAdapter.setNodeSourceCodeLocation(commentNode, token.location);
+ }
+ }
+ _insertCharacters(token) {
+ let parent;
+ let beforeElement;
+ if (this._shouldFosterParentOnInsertion()) {
+ ({ parent, beforeElement } = this._findFosterParentingLocation());
+ if (beforeElement) {
+ this.treeAdapter.insertTextBefore(parent, token.chars, beforeElement);
+ }
+ else {
+ this.treeAdapter.insertText(parent, token.chars);
+ }
+ }
+ else {
+ parent = this.openElements.currentTmplContentOrNode;
+ this.treeAdapter.insertText(parent, token.chars);
+ }
+ if (!token.location)
+ return;
+ const siblings = this.treeAdapter.getChildNodes(parent);
+ const textNodeIdx = beforeElement ? siblings.lastIndexOf(beforeElement) : siblings.length;
+ const textNode = siblings[textNodeIdx - 1];
+ //NOTE: if we have a location assigned by another token, then just update the end position
+ const tnLoc = this.treeAdapter.getNodeSourceCodeLocation(textNode);
+ if (tnLoc) {
+ const { endLine, endCol, endOffset } = token.location;
+ this.treeAdapter.updateNodeSourceCodeLocation(textNode, { endLine, endCol, endOffset });
+ }
+ else if (this.options.sourceCodeLocationInfo) {
+ this.treeAdapter.setNodeSourceCodeLocation(textNode, token.location);
+ }
+ }
+ _adoptNodes(donor, recipient) {
+ for (let child = this.treeAdapter.getFirstChild(donor); child; child = this.treeAdapter.getFirstChild(donor)) {
+ this.treeAdapter.detachNode(child);
+ this.treeAdapter.appendChild(recipient, child);
+ }
+ }
+ _setEndLocation(element, closingToken) {
+ if (this.treeAdapter.getNodeSourceCodeLocation(element) && closingToken.location) {
+ const ctLoc = closingToken.location;
+ const tn = this.treeAdapter.getTagName(element);
+ const endLoc =
+ // NOTE: For cases like
- First 'p' closes without a closing
+ // tag and for cases like
- 'p' closes without a closing tag.
+ closingToken.type === TokenType.END_TAG && tn === closingToken.tagName
+ ? {
+ endTag: { ...ctLoc },
+ endLine: ctLoc.endLine,
+ endCol: ctLoc.endCol,
+ endOffset: ctLoc.endOffset,
+ }
+ : {
+ endLine: ctLoc.startLine,
+ endCol: ctLoc.startCol,
+ endOffset: ctLoc.startOffset,
+ };
+ this.treeAdapter.updateNodeSourceCodeLocation(element, endLoc);
+ }
+ }
+ //Token processing
+ shouldProcessStartTagTokenInForeignContent(token) {
+ // Check that neither current === document, or ns === NS.HTML
+ if (!this.currentNotInHTML)
+ return false;
+ let current;
+ let currentTagId;
+ if (this.openElements.stackTop === 0 && this.fragmentContext) {
+ current = this.fragmentContext;
+ currentTagId = this.fragmentContextID;
+ }
+ else {
+ ({ current, currentTagId } = this.openElements);
+ }
+ if (token.tagID === $.SVG &&
+ this.treeAdapter.getTagName(current) === TN.ANNOTATION_XML &&
+ this.treeAdapter.getNamespaceURI(current) === NS.MATHML) {
+ return false;
+ }
+ return (
+ // Check that `current` is not an integration point for HTML or MathML elements.
+ this.tokenizer.inForeignNode ||
+ // If it _is_ an integration point, then we might have to check that it is not an HTML
+ // integration point.
+ ((token.tagID === $.MGLYPH || token.tagID === $.MALIGNMARK) &&
+ !this._isIntegrationPoint(currentTagId, current, NS.HTML)));
+ }
+ _processToken(token) {
+ switch (token.type) {
+ case TokenType.CHARACTER: {
+ this.onCharacter(token);
+ break;
+ }
+ case TokenType.NULL_CHARACTER: {
+ this.onNullCharacter(token);
+ break;
+ }
+ case TokenType.COMMENT: {
+ this.onComment(token);
+ break;
+ }
+ case TokenType.DOCTYPE: {
+ this.onDoctype(token);
+ break;
+ }
+ case TokenType.START_TAG: {
+ this._processStartTag(token);
+ break;
+ }
+ case TokenType.END_TAG: {
+ this.onEndTag(token);
+ break;
+ }
+ case TokenType.EOF: {
+ this.onEof(token);
+ break;
+ }
+ case TokenType.WHITESPACE_CHARACTER: {
+ this.onWhitespaceCharacter(token);
+ break;
+ }
+ }
+ }
+ //Integration points
+ _isIntegrationPoint(tid, element, foreignNS) {
+ const ns = this.treeAdapter.getNamespaceURI(element);
+ const attrs = this.treeAdapter.getAttrList(element);
+ return foreignContent.isIntegrationPoint(tid, ns, attrs, foreignNS);
+ }
+ //Active formatting elements reconstruction
+ _reconstructActiveFormattingElements() {
+ const listLength = this.activeFormattingElements.entries.length;
+ if (listLength) {
+ const endIndex = this.activeFormattingElements.entries.findIndex((entry) => entry.type === EntryType.Marker || this.openElements.contains(entry.element));
+ const unopenIdx = endIndex < 0 ? listLength - 1 : endIndex - 1;
+ for (let i = unopenIdx; i >= 0; i--) {
+ const entry = this.activeFormattingElements.entries[i];
+ this._insertElement(entry.token, this.treeAdapter.getNamespaceURI(entry.element));
+ entry.element = this.openElements.current;
+ }
+ }
+ }
+ //Close elements
+ _closeTableCell() {
+ this.openElements.generateImpliedEndTags();
+ this.openElements.popUntilTableCellPopped();
+ this.activeFormattingElements.clearToLastMarker();
+ this.insertionMode = InsertionMode.IN_ROW;
+ }
+ _closePElement() {
+ this.openElements.generateImpliedEndTagsWithExclusion($.P);
+ this.openElements.popUntilTagNamePopped($.P);
+ }
+ //Insertion modes
+ _resetInsertionMode() {
+ for (let i = this.openElements.stackTop; i >= 0; i--) {
+ //Insertion mode reset map
+ switch (i === 0 && this.fragmentContext ? this.fragmentContextID : this.openElements.tagIDs[i]) {
+ case $.TR: {
+ this.insertionMode = InsertionMode.IN_ROW;
+ return;
+ }
+ case $.TBODY:
+ case $.THEAD:
+ case $.TFOOT: {
+ this.insertionMode = InsertionMode.IN_TABLE_BODY;
+ return;
+ }
+ case $.CAPTION: {
+ this.insertionMode = InsertionMode.IN_CAPTION;
+ return;
+ }
+ case $.COLGROUP: {
+ this.insertionMode = InsertionMode.IN_COLUMN_GROUP;
+ return;
+ }
+ case $.TABLE: {
+ this.insertionMode = InsertionMode.IN_TABLE;
+ return;
+ }
+ case $.BODY: {
+ this.insertionMode = InsertionMode.IN_BODY;
+ return;
+ }
+ case $.FRAMESET: {
+ this.insertionMode = InsertionMode.IN_FRAMESET;
+ return;
+ }
+ case $.SELECT: {
+ this._resetInsertionModeForSelect(i);
+ return;
+ }
+ case $.TEMPLATE: {
+ this.insertionMode = this.tmplInsertionModeStack[0];
+ return;
+ }
+ case $.HTML: {
+ this.insertionMode = this.headElement ? InsertionMode.AFTER_HEAD : InsertionMode.BEFORE_HEAD;
+ return;
+ }
+ case $.TD:
+ case $.TH: {
+ if (i > 0) {
+ this.insertionMode = InsertionMode.IN_CELL;
+ return;
+ }
+ break;
+ }
+ case $.HEAD: {
+ if (i > 0) {
+ this.insertionMode = InsertionMode.IN_HEAD;
+ return;
+ }
+ break;
+ }
+ }
+ }
+ this.insertionMode = InsertionMode.IN_BODY;
+ }
+ _resetInsertionModeForSelect(selectIdx) {
+ if (selectIdx > 0) {
+ for (let i = selectIdx - 1; i > 0; i--) {
+ const tn = this.openElements.tagIDs[i];
+ if (tn === $.TEMPLATE) {
+ break;
+ }
+ else if (tn === $.TABLE) {
+ this.insertionMode = InsertionMode.IN_SELECT_IN_TABLE;
+ return;
+ }
+ }
+ }
+ this.insertionMode = InsertionMode.IN_SELECT;
+ }
+ //Foster parenting
+ _isElementCausesFosterParenting(tn) {
+ return TABLE_STRUCTURE_TAGS.has(tn);
+ }
+ _shouldFosterParentOnInsertion() {
+ return this.fosterParentingEnabled && this._isElementCausesFosterParenting(this.openElements.currentTagId);
+ }
+ _findFosterParentingLocation() {
+ for (let i = this.openElements.stackTop; i >= 0; i--) {
+ const openElement = this.openElements.items[i];
+ switch (this.openElements.tagIDs[i]) {
+ case $.TEMPLATE: {
+ if (this.treeAdapter.getNamespaceURI(openElement) === NS.HTML) {
+ return { parent: this.treeAdapter.getTemplateContent(openElement), beforeElement: null };
+ }
+ break;
+ }
+ case $.TABLE: {
+ const parent = this.treeAdapter.getParentNode(openElement);
+ if (parent) {
+ return { parent, beforeElement: openElement };
+ }
+ return { parent: this.openElements.items[i - 1], beforeElement: null };
+ }
+ default:
+ // Do nothing
+ }
+ }
+ return { parent: this.openElements.items[0], beforeElement: null };
+ }
+ _fosterParentElement(element) {
+ const location = this._findFosterParentingLocation();
+ if (location.beforeElement) {
+ this.treeAdapter.insertBefore(location.parent, element, location.beforeElement);
+ }
+ else {
+ this.treeAdapter.appendChild(location.parent, element);
+ }
+ }
+ //Special elements
+ _isSpecialElement(element, id) {
+ const ns = this.treeAdapter.getNamespaceURI(element);
+ return SPECIAL_ELEMENTS[ns].has(id);
+ }
+ onCharacter(token) {
+ this.skipNextNewLine = false;
+ if (this.tokenizer.inForeignNode) {
+ characterInForeignContent(this, token);
+ return;
+ }
+ switch (this.insertionMode) {
+ case InsertionMode.INITIAL: {
+ tokenInInitialMode(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HTML: {
+ tokenBeforeHtml(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HEAD: {
+ tokenBeforeHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD: {
+ tokenInHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD_NO_SCRIPT: {
+ tokenInHeadNoScript(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_HEAD: {
+ tokenAfterHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_BODY:
+ case InsertionMode.IN_CAPTION:
+ case InsertionMode.IN_CELL:
+ case InsertionMode.IN_TEMPLATE: {
+ characterInBody(this, token);
+ break;
+ }
+ case InsertionMode.TEXT:
+ case InsertionMode.IN_SELECT:
+ case InsertionMode.IN_SELECT_IN_TABLE: {
+ this._insertCharacters(token);
+ break;
+ }
+ case InsertionMode.IN_TABLE:
+ case InsertionMode.IN_TABLE_BODY:
+ case InsertionMode.IN_ROW: {
+ characterInTable(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE_TEXT: {
+ characterInTableText(this, token);
+ break;
+ }
+ case InsertionMode.IN_COLUMN_GROUP: {
+ tokenInColumnGroup(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_BODY: {
+ tokenAfterBody(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_AFTER_BODY: {
+ tokenAfterAfterBody(this, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ onNullCharacter(token) {
+ this.skipNextNewLine = false;
+ if (this.tokenizer.inForeignNode) {
+ nullCharacterInForeignContent(this, token);
+ return;
+ }
+ switch (this.insertionMode) {
+ case InsertionMode.INITIAL: {
+ tokenInInitialMode(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HTML: {
+ tokenBeforeHtml(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HEAD: {
+ tokenBeforeHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD: {
+ tokenInHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD_NO_SCRIPT: {
+ tokenInHeadNoScript(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_HEAD: {
+ tokenAfterHead(this, token);
+ break;
+ }
+ case InsertionMode.TEXT: {
+ this._insertCharacters(token);
+ break;
+ }
+ case InsertionMode.IN_TABLE:
+ case InsertionMode.IN_TABLE_BODY:
+ case InsertionMode.IN_ROW: {
+ characterInTable(this, token);
+ break;
+ }
+ case InsertionMode.IN_COLUMN_GROUP: {
+ tokenInColumnGroup(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_BODY: {
+ tokenAfterBody(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_AFTER_BODY: {
+ tokenAfterAfterBody(this, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ onComment(token) {
+ this.skipNextNewLine = false;
+ if (this.currentNotInHTML) {
+ appendComment(this, token);
+ return;
+ }
+ switch (this.insertionMode) {
+ case InsertionMode.INITIAL:
+ case InsertionMode.BEFORE_HTML:
+ case InsertionMode.BEFORE_HEAD:
+ case InsertionMode.IN_HEAD:
+ case InsertionMode.IN_HEAD_NO_SCRIPT:
+ case InsertionMode.AFTER_HEAD:
+ case InsertionMode.IN_BODY:
+ case InsertionMode.IN_TABLE:
+ case InsertionMode.IN_CAPTION:
+ case InsertionMode.IN_COLUMN_GROUP:
+ case InsertionMode.IN_TABLE_BODY:
+ case InsertionMode.IN_ROW:
+ case InsertionMode.IN_CELL:
+ case InsertionMode.IN_SELECT:
+ case InsertionMode.IN_SELECT_IN_TABLE:
+ case InsertionMode.IN_TEMPLATE:
+ case InsertionMode.IN_FRAMESET:
+ case InsertionMode.AFTER_FRAMESET: {
+ appendComment(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE_TEXT: {
+ tokenInTableText(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_BODY: {
+ appendCommentToRootHtmlElement(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_AFTER_BODY:
+ case InsertionMode.AFTER_AFTER_FRAMESET: {
+ appendCommentToDocument(this, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ onDoctype(token) {
+ this.skipNextNewLine = false;
+ switch (this.insertionMode) {
+ case InsertionMode.INITIAL: {
+ doctypeInInitialMode(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HEAD:
+ case InsertionMode.IN_HEAD:
+ case InsertionMode.IN_HEAD_NO_SCRIPT:
+ case InsertionMode.AFTER_HEAD: {
+ this._err(token, ERR.misplacedDoctype);
+ break;
+ }
+ case InsertionMode.IN_TABLE_TEXT: {
+ tokenInTableText(this, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ onStartTag(token) {
+ this.skipNextNewLine = false;
+ this.currentToken = token;
+ this._processStartTag(token);
+ if (token.selfClosing && !token.ackSelfClosing) {
+ this._err(token, ERR.nonVoidHtmlElementStartTagWithTrailingSolidus);
+ }
+ }
+ /**
+ * Processes a given start tag.
+ *
+ * `onStartTag` checks if a self-closing tag was recognized. When a token
+ * is moved inbetween multiple insertion modes, this check for self-closing
+ * could lead to false positives. To avoid this, `_processStartTag` is used
+ * for nested calls.
+ *
+ * @param token The token to process.
+ */
+ _processStartTag(token) {
+ if (this.shouldProcessStartTagTokenInForeignContent(token)) {
+ startTagInForeignContent(this, token);
+ }
+ else {
+ this._startTagOutsideForeignContent(token);
+ }
+ }
+ _startTagOutsideForeignContent(token) {
+ switch (this.insertionMode) {
+ case InsertionMode.INITIAL: {
+ tokenInInitialMode(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HTML: {
+ startTagBeforeHtml(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HEAD: {
+ startTagBeforeHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD: {
+ startTagInHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD_NO_SCRIPT: {
+ startTagInHeadNoScript(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_HEAD: {
+ startTagAfterHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_BODY: {
+ startTagInBody(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE: {
+ startTagInTable(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE_TEXT: {
+ tokenInTableText(this, token);
+ break;
+ }
+ case InsertionMode.IN_CAPTION: {
+ startTagInCaption(this, token);
+ break;
+ }
+ case InsertionMode.IN_COLUMN_GROUP: {
+ startTagInColumnGroup(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE_BODY: {
+ startTagInTableBody(this, token);
+ break;
+ }
+ case InsertionMode.IN_ROW: {
+ startTagInRow(this, token);
+ break;
+ }
+ case InsertionMode.IN_CELL: {
+ startTagInCell(this, token);
+ break;
+ }
+ case InsertionMode.IN_SELECT: {
+ startTagInSelect(this, token);
+ break;
+ }
+ case InsertionMode.IN_SELECT_IN_TABLE: {
+ startTagInSelectInTable(this, token);
+ break;
+ }
+ case InsertionMode.IN_TEMPLATE: {
+ startTagInTemplate(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_BODY: {
+ startTagAfterBody(this, token);
+ break;
+ }
+ case InsertionMode.IN_FRAMESET: {
+ startTagInFrameset(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_FRAMESET: {
+ startTagAfterFrameset(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_AFTER_BODY: {
+ startTagAfterAfterBody(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_AFTER_FRAMESET: {
+ startTagAfterAfterFrameset(this, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ onEndTag(token) {
+ this.skipNextNewLine = false;
+ this.currentToken = token;
+ if (this.currentNotInHTML) {
+ endTagInForeignContent(this, token);
+ }
+ else {
+ this._endTagOutsideForeignContent(token);
+ }
+ }
+ _endTagOutsideForeignContent(token) {
+ switch (this.insertionMode) {
+ case InsertionMode.INITIAL: {
+ tokenInInitialMode(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HTML: {
+ endTagBeforeHtml(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HEAD: {
+ endTagBeforeHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD: {
+ endTagInHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD_NO_SCRIPT: {
+ endTagInHeadNoScript(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_HEAD: {
+ endTagAfterHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_BODY: {
+ endTagInBody(this, token);
+ break;
+ }
+ case InsertionMode.TEXT: {
+ endTagInText(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE: {
+ endTagInTable(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE_TEXT: {
+ tokenInTableText(this, token);
+ break;
+ }
+ case InsertionMode.IN_CAPTION: {
+ endTagInCaption(this, token);
+ break;
+ }
+ case InsertionMode.IN_COLUMN_GROUP: {
+ endTagInColumnGroup(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE_BODY: {
+ endTagInTableBody(this, token);
+ break;
+ }
+ case InsertionMode.IN_ROW: {
+ endTagInRow(this, token);
+ break;
+ }
+ case InsertionMode.IN_CELL: {
+ endTagInCell(this, token);
+ break;
+ }
+ case InsertionMode.IN_SELECT: {
+ endTagInSelect(this, token);
+ break;
+ }
+ case InsertionMode.IN_SELECT_IN_TABLE: {
+ endTagInSelectInTable(this, token);
+ break;
+ }
+ case InsertionMode.IN_TEMPLATE: {
+ endTagInTemplate(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_BODY: {
+ endTagAfterBody(this, token);
+ break;
+ }
+ case InsertionMode.IN_FRAMESET: {
+ endTagInFrameset(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_FRAMESET: {
+ endTagAfterFrameset(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_AFTER_BODY: {
+ tokenAfterAfterBody(this, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ onEof(token) {
+ switch (this.insertionMode) {
+ case InsertionMode.INITIAL: {
+ tokenInInitialMode(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HTML: {
+ tokenBeforeHtml(this, token);
+ break;
+ }
+ case InsertionMode.BEFORE_HEAD: {
+ tokenBeforeHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD: {
+ tokenInHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_HEAD_NO_SCRIPT: {
+ tokenInHeadNoScript(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_HEAD: {
+ tokenAfterHead(this, token);
+ break;
+ }
+ case InsertionMode.IN_BODY:
+ case InsertionMode.IN_TABLE:
+ case InsertionMode.IN_CAPTION:
+ case InsertionMode.IN_COLUMN_GROUP:
+ case InsertionMode.IN_TABLE_BODY:
+ case InsertionMode.IN_ROW:
+ case InsertionMode.IN_CELL:
+ case InsertionMode.IN_SELECT:
+ case InsertionMode.IN_SELECT_IN_TABLE: {
+ eofInBody(this, token);
+ break;
+ }
+ case InsertionMode.TEXT: {
+ eofInText(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE_TEXT: {
+ tokenInTableText(this, token);
+ break;
+ }
+ case InsertionMode.IN_TEMPLATE: {
+ eofInTemplate(this, token);
+ break;
+ }
+ case InsertionMode.AFTER_BODY:
+ case InsertionMode.IN_FRAMESET:
+ case InsertionMode.AFTER_FRAMESET:
+ case InsertionMode.AFTER_AFTER_BODY:
+ case InsertionMode.AFTER_AFTER_FRAMESET: {
+ stopParsing(this, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ onWhitespaceCharacter(token) {
+ if (this.skipNextNewLine) {
+ this.skipNextNewLine = false;
+ if (token.chars.charCodeAt(0) === unicode.CODE_POINTS.LINE_FEED) {
+ if (token.chars.length === 1) {
+ return;
+ }
+ token.chars = token.chars.substr(1);
+ }
+ }
+ if (this.tokenizer.inForeignNode) {
+ this._insertCharacters(token);
+ return;
+ }
+ switch (this.insertionMode) {
+ case InsertionMode.IN_HEAD:
+ case InsertionMode.IN_HEAD_NO_SCRIPT:
+ case InsertionMode.AFTER_HEAD:
+ case InsertionMode.TEXT:
+ case InsertionMode.IN_COLUMN_GROUP:
+ case InsertionMode.IN_SELECT:
+ case InsertionMode.IN_SELECT_IN_TABLE:
+ case InsertionMode.IN_FRAMESET:
+ case InsertionMode.AFTER_FRAMESET: {
+ this._insertCharacters(token);
+ break;
+ }
+ case InsertionMode.IN_BODY:
+ case InsertionMode.IN_CAPTION:
+ case InsertionMode.IN_CELL:
+ case InsertionMode.IN_TEMPLATE:
+ case InsertionMode.AFTER_BODY:
+ case InsertionMode.AFTER_AFTER_BODY:
+ case InsertionMode.AFTER_AFTER_FRAMESET: {
+ whitespaceCharacterInBody(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE:
+ case InsertionMode.IN_TABLE_BODY:
+ case InsertionMode.IN_ROW: {
+ characterInTable(this, token);
+ break;
+ }
+ case InsertionMode.IN_TABLE_TEXT: {
+ whitespaceCharacterInTableText(this, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+}
+//Adoption agency algorithm
+//(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#adoptionAgency)
+//------------------------------------------------------------------
+//Steps 5-8 of the algorithm
+function aaObtainFormattingElementEntry(p, token) {
+ let formattingElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName(token.tagName);
+ if (formattingElementEntry) {
+ if (!p.openElements.contains(formattingElementEntry.element)) {
+ p.activeFormattingElements.removeEntry(formattingElementEntry);
+ formattingElementEntry = null;
+ }
+ else if (!p.openElements.hasInScope(token.tagID)) {
+ formattingElementEntry = null;
+ }
+ }
+ else {
+ genericEndTagInBody(p, token);
+ }
+ return formattingElementEntry;
+}
+//Steps 9 and 10 of the algorithm
+function aaObtainFurthestBlock(p, formattingElementEntry) {
+ let furthestBlock = null;
+ let idx = p.openElements.stackTop;
+ for (; idx >= 0; idx--) {
+ const element = p.openElements.items[idx];
+ if (element === formattingElementEntry.element) {
+ break;
+ }
+ if (p._isSpecialElement(element, p.openElements.tagIDs[idx])) {
+ furthestBlock = element;
+ }
+ }
+ if (!furthestBlock) {
+ p.openElements.shortenToLength(idx < 0 ? 0 : idx);
+ p.activeFormattingElements.removeEntry(formattingElementEntry);
+ }
+ return furthestBlock;
+}
+//Step 13 of the algorithm
+function aaInnerLoop(p, furthestBlock, formattingElement) {
+ let lastElement = furthestBlock;
+ let nextElement = p.openElements.getCommonAncestor(furthestBlock);
+ for (let i = 0, element = nextElement; element !== formattingElement; i++, element = nextElement) {
+ //NOTE: store the next element for the next loop iteration (it may be deleted from the stack by step 9.5)
+ nextElement = p.openElements.getCommonAncestor(element);
+ const elementEntry = p.activeFormattingElements.getElementEntry(element);
+ const counterOverflow = elementEntry && i >= AA_INNER_LOOP_ITER;
+ const shouldRemoveFromOpenElements = !elementEntry || counterOverflow;
+ if (shouldRemoveFromOpenElements) {
+ if (counterOverflow) {
+ p.activeFormattingElements.removeEntry(elementEntry);
+ }
+ p.openElements.remove(element);
+ }
+ else {
+ element = aaRecreateElementFromEntry(p, elementEntry);
+ if (lastElement === furthestBlock) {
+ p.activeFormattingElements.bookmark = elementEntry;
+ }
+ p.treeAdapter.detachNode(lastElement);
+ p.treeAdapter.appendChild(element, lastElement);
+ lastElement = element;
+ }
+ }
+ return lastElement;
+}
+//Step 13.7 of the algorithm
+function aaRecreateElementFromEntry(p, elementEntry) {
+ const ns = p.treeAdapter.getNamespaceURI(elementEntry.element);
+ const newElement = p.treeAdapter.createElement(elementEntry.token.tagName, ns, elementEntry.token.attrs);
+ p.openElements.replace(elementEntry.element, newElement);
+ elementEntry.element = newElement;
+ return newElement;
+}
+//Step 14 of the algorithm
+function aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement) {
+ const tn = p.treeAdapter.getTagName(commonAncestor);
+ const tid = getTagID(tn);
+ if (p._isElementCausesFosterParenting(tid)) {
+ p._fosterParentElement(lastElement);
+ }
+ else {
+ const ns = p.treeAdapter.getNamespaceURI(commonAncestor);
+ if (tid === $.TEMPLATE && ns === NS.HTML) {
+ commonAncestor = p.treeAdapter.getTemplateContent(commonAncestor);
+ }
+ p.treeAdapter.appendChild(commonAncestor, lastElement);
+ }
+}
+//Steps 15-19 of the algorithm
+function aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry) {
+ const ns = p.treeAdapter.getNamespaceURI(formattingElementEntry.element);
+ const { token } = formattingElementEntry;
+ const newElement = p.treeAdapter.createElement(token.tagName, ns, token.attrs);
+ p._adoptNodes(furthestBlock, newElement);
+ p.treeAdapter.appendChild(furthestBlock, newElement);
+ p.activeFormattingElements.insertElementAfterBookmark(newElement, token);
+ p.activeFormattingElements.removeEntry(formattingElementEntry);
+ p.openElements.remove(formattingElementEntry.element);
+ p.openElements.insertAfter(furthestBlock, newElement, token.tagID);
+}
+//Algorithm entry point
+function callAdoptionAgency(p, token) {
+ for (let i = 0; i < AA_OUTER_LOOP_ITER; i++) {
+ const formattingElementEntry = aaObtainFormattingElementEntry(p, token);
+ if (!formattingElementEntry) {
+ break;
+ }
+ const furthestBlock = aaObtainFurthestBlock(p, formattingElementEntry);
+ if (!furthestBlock) {
+ break;
+ }
+ p.activeFormattingElements.bookmark = formattingElementEntry;
+ const lastElement = aaInnerLoop(p, furthestBlock, formattingElementEntry.element);
+ const commonAncestor = p.openElements.getCommonAncestor(formattingElementEntry.element);
+ p.treeAdapter.detachNode(lastElement);
+ if (commonAncestor)
+ aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement);
+ aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry);
+ }
+}
+//Generic token handlers
+//------------------------------------------------------------------
+function appendComment(p, token) {
+ p._appendCommentNode(token, p.openElements.currentTmplContentOrNode);
+}
+function appendCommentToRootHtmlElement(p, token) {
+ p._appendCommentNode(token, p.openElements.items[0]);
+}
+function appendCommentToDocument(p, token) {
+ p._appendCommentNode(token, p.document);
+}
+function stopParsing(p, token) {
+ p.stopped = true;
+ // NOTE: Set end locations for elements that remain on the open element stack.
+ if (token.location) {
+ // NOTE: If we are not in a fragment, `html` and `body` will stay on the stack.
+ // This is a problem, as we might overwrite their end position here.
+ const target = p.fragmentContext ? 0 : 2;
+ for (let i = p.openElements.stackTop; i >= target; i--) {
+ p._setEndLocation(p.openElements.items[i], token);
+ }
+ // Handle `html` and `body`
+ if (!p.fragmentContext && p.openElements.stackTop >= 0) {
+ const htmlElement = p.openElements.items[0];
+ const htmlLocation = p.treeAdapter.getNodeSourceCodeLocation(htmlElement);
+ if (htmlLocation && !htmlLocation.endTag) {
+ p._setEndLocation(htmlElement, token);
+ if (p.openElements.stackTop >= 1) {
+ const bodyElement = p.openElements.items[1];
+ const bodyLocation = p.treeAdapter.getNodeSourceCodeLocation(bodyElement);
+ if (bodyLocation && !bodyLocation.endTag) {
+ p._setEndLocation(bodyElement, token);
+ }
+ }
+ }
+ }
+ }
+}
+// The "initial" insertion mode
+//------------------------------------------------------------------
+function doctypeInInitialMode(p, token) {
+ p._setDocumentType(token);
+ const mode = token.forceQuirks ? DOCUMENT_MODE.QUIRKS : doctype.getDocumentMode(token);
+ if (!doctype.isConforming(token)) {
+ p._err(token, ERR.nonConformingDoctype);
+ }
+ p.treeAdapter.setDocumentMode(p.document, mode);
+ p.insertionMode = InsertionMode.BEFORE_HTML;
+}
+function tokenInInitialMode(p, token) {
+ p._err(token, ERR.missingDoctype, true);
+ p.treeAdapter.setDocumentMode(p.document, DOCUMENT_MODE.QUIRKS);
+ p.insertionMode = InsertionMode.BEFORE_HTML;
+ p._processToken(token);
+}
+// The "before html" insertion mode
+//------------------------------------------------------------------
+function startTagBeforeHtml(p, token) {
+ if (token.tagID === $.HTML) {
+ p._insertElement(token, NS.HTML);
+ p.insertionMode = InsertionMode.BEFORE_HEAD;
+ }
+ else {
+ tokenBeforeHtml(p, token);
+ }
+}
+function endTagBeforeHtml(p, token) {
+ const tn = token.tagID;
+ if (tn === $.HTML || tn === $.HEAD || tn === $.BODY || tn === $.BR) {
+ tokenBeforeHtml(p, token);
+ }
+}
+function tokenBeforeHtml(p, token) {
+ p._insertFakeRootElement();
+ p.insertionMode = InsertionMode.BEFORE_HEAD;
+ p._processToken(token);
+}
+// The "before head" insertion mode
+//------------------------------------------------------------------
+function startTagBeforeHead(p, token) {
+ switch (token.tagID) {
+ case $.HTML: {
+ startTagInBody(p, token);
+ break;
+ }
+ case $.HEAD: {
+ p._insertElement(token, NS.HTML);
+ p.headElement = p.openElements.current;
+ p.insertionMode = InsertionMode.IN_HEAD;
+ break;
+ }
+ default: {
+ tokenBeforeHead(p, token);
+ }
+ }
+}
+function endTagBeforeHead(p, token) {
+ const tn = token.tagID;
+ if (tn === $.HEAD || tn === $.BODY || tn === $.HTML || tn === $.BR) {
+ tokenBeforeHead(p, token);
+ }
+ else {
+ p._err(token, ERR.endTagWithoutMatchingOpenElement);
+ }
+}
+function tokenBeforeHead(p, token) {
+ p._insertFakeElement(TN.HEAD, $.HEAD);
+ p.headElement = p.openElements.current;
+ p.insertionMode = InsertionMode.IN_HEAD;
+ p._processToken(token);
+}
+// The "in head" insertion mode
+//------------------------------------------------------------------
+function startTagInHead(p, token) {
+ switch (token.tagID) {
+ case $.HTML: {
+ startTagInBody(p, token);
+ break;
+ }
+ case $.BASE:
+ case $.BASEFONT:
+ case $.BGSOUND:
+ case $.LINK:
+ case $.META: {
+ p._appendElement(token, NS.HTML);
+ token.ackSelfClosing = true;
+ break;
+ }
+ case $.TITLE: {
+ p._switchToTextParsing(token, TokenizerMode.RCDATA);
+ break;
+ }
+ case $.NOSCRIPT: {
+ if (p.options.scriptingEnabled) {
+ p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
+ }
+ else {
+ p._insertElement(token, NS.HTML);
+ p.insertionMode = InsertionMode.IN_HEAD_NO_SCRIPT;
+ }
+ break;
+ }
+ case $.NOFRAMES:
+ case $.STYLE: {
+ p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
+ break;
+ }
+ case $.SCRIPT: {
+ p._switchToTextParsing(token, TokenizerMode.SCRIPT_DATA);
+ break;
+ }
+ case $.TEMPLATE: {
+ p._insertTemplate(token);
+ p.activeFormattingElements.insertMarker();
+ p.framesetOk = false;
+ p.insertionMode = InsertionMode.IN_TEMPLATE;
+ p.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE);
+ break;
+ }
+ case $.HEAD: {
+ p._err(token, ERR.misplacedStartTagForHeadElement);
+ break;
+ }
+ default: {
+ tokenInHead(p, token);
+ }
+ }
+}
+function endTagInHead(p, token) {
+ switch (token.tagID) {
+ case $.HEAD: {
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.AFTER_HEAD;
+ break;
+ }
+ case $.BODY:
+ case $.BR:
+ case $.HTML: {
+ tokenInHead(p, token);
+ break;
+ }
+ case $.TEMPLATE: {
+ templateEndTagInHead(p, token);
+ break;
+ }
+ default: {
+ p._err(token, ERR.endTagWithoutMatchingOpenElement);
+ }
+ }
+}
+function templateEndTagInHead(p, token) {
+ if (p.openElements.tmplCount > 0) {
+ p.openElements.generateImpliedEndTagsThoroughly();
+ if (p.openElements.currentTagId !== $.TEMPLATE) {
+ p._err(token, ERR.closingOfElementWithOpenChildElements);
+ }
+ p.openElements.popUntilTagNamePopped($.TEMPLATE);
+ p.activeFormattingElements.clearToLastMarker();
+ p.tmplInsertionModeStack.shift();
+ p._resetInsertionMode();
+ }
+ else {
+ p._err(token, ERR.endTagWithoutMatchingOpenElement);
+ }
+}
+function tokenInHead(p, token) {
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.AFTER_HEAD;
+ p._processToken(token);
+}
+// The "in head no script" insertion mode
+//------------------------------------------------------------------
+function startTagInHeadNoScript(p, token) {
+ switch (token.tagID) {
+ case $.HTML: {
+ startTagInBody(p, token);
+ break;
+ }
+ case $.BASEFONT:
+ case $.BGSOUND:
+ case $.HEAD:
+ case $.LINK:
+ case $.META:
+ case $.NOFRAMES:
+ case $.STYLE: {
+ startTagInHead(p, token);
+ break;
+ }
+ case $.NOSCRIPT: {
+ p._err(token, ERR.nestedNoscriptInHead);
+ break;
+ }
+ default: {
+ tokenInHeadNoScript(p, token);
+ }
+ }
+}
+function endTagInHeadNoScript(p, token) {
+ switch (token.tagID) {
+ case $.NOSCRIPT: {
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_HEAD;
+ break;
+ }
+ case $.BR: {
+ tokenInHeadNoScript(p, token);
+ break;
+ }
+ default: {
+ p._err(token, ERR.endTagWithoutMatchingOpenElement);
+ }
+ }
+}
+function tokenInHeadNoScript(p, token) {
+ const errCode = token.type === TokenType.EOF ? ERR.openElementsLeftAfterEof : ERR.disallowedContentInNoscriptInHead;
+ p._err(token, errCode);
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_HEAD;
+ p._processToken(token);
+}
+// The "after head" insertion mode
+//------------------------------------------------------------------
+function startTagAfterHead(p, token) {
+ switch (token.tagID) {
+ case $.HTML: {
+ startTagInBody(p, token);
+ break;
+ }
+ case $.BODY: {
+ p._insertElement(token, NS.HTML);
+ p.framesetOk = false;
+ p.insertionMode = InsertionMode.IN_BODY;
+ break;
+ }
+ case $.FRAMESET: {
+ p._insertElement(token, NS.HTML);
+ p.insertionMode = InsertionMode.IN_FRAMESET;
+ break;
+ }
+ case $.BASE:
+ case $.BASEFONT:
+ case $.BGSOUND:
+ case $.LINK:
+ case $.META:
+ case $.NOFRAMES:
+ case $.SCRIPT:
+ case $.STYLE:
+ case $.TEMPLATE:
+ case $.TITLE: {
+ p._err(token, ERR.abandonedHeadElementChild);
+ p.openElements.push(p.headElement, $.HEAD);
+ startTagInHead(p, token);
+ p.openElements.remove(p.headElement);
+ break;
+ }
+ case $.HEAD: {
+ p._err(token, ERR.misplacedStartTagForHeadElement);
+ break;
+ }
+ default: {
+ tokenAfterHead(p, token);
+ }
+ }
+}
+function endTagAfterHead(p, token) {
+ switch (token.tagID) {
+ case $.BODY:
+ case $.HTML:
+ case $.BR: {
+ tokenAfterHead(p, token);
+ break;
+ }
+ case $.TEMPLATE: {
+ templateEndTagInHead(p, token);
+ break;
+ }
+ default: {
+ p._err(token, ERR.endTagWithoutMatchingOpenElement);
+ }
+ }
+}
+function tokenAfterHead(p, token) {
+ p._insertFakeElement(TN.BODY, $.BODY);
+ p.insertionMode = InsertionMode.IN_BODY;
+ modeInBody(p, token);
+}
+// The "in body" insertion mode
+//------------------------------------------------------------------
+function modeInBody(p, token) {
+ switch (token.type) {
+ case TokenType.CHARACTER: {
+ characterInBody(p, token);
+ break;
+ }
+ case TokenType.WHITESPACE_CHARACTER: {
+ whitespaceCharacterInBody(p, token);
+ break;
+ }
+ case TokenType.COMMENT: {
+ appendComment(p, token);
+ break;
+ }
+ case TokenType.START_TAG: {
+ startTagInBody(p, token);
+ break;
+ }
+ case TokenType.END_TAG: {
+ endTagInBody(p, token);
+ break;
+ }
+ case TokenType.EOF: {
+ eofInBody(p, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+}
+function whitespaceCharacterInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ p._insertCharacters(token);
+}
+function characterInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ p._insertCharacters(token);
+ p.framesetOk = false;
+}
+function htmlStartTagInBody(p, token) {
+ if (p.openElements.tmplCount === 0) {
+ p.treeAdapter.adoptAttributes(p.openElements.items[0], token.attrs);
+ }
+}
+function bodyStartTagInBody(p, token) {
+ const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();
+ if (bodyElement && p.openElements.tmplCount === 0) {
+ p.framesetOk = false;
+ p.treeAdapter.adoptAttributes(bodyElement, token.attrs);
+ }
+}
+function framesetStartTagInBody(p, token) {
+ const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();
+ if (p.framesetOk && bodyElement) {
+ p.treeAdapter.detachNode(bodyElement);
+ p.openElements.popAllUpToHtmlElement();
+ p._insertElement(token, NS.HTML);
+ p.insertionMode = InsertionMode.IN_FRAMESET;
+ }
+}
+function addressStartTagInBody(p, token) {
+ if (p.openElements.hasInButtonScope($.P)) {
+ p._closePElement();
+ }
+ p._insertElement(token, NS.HTML);
+}
+function numberedHeaderStartTagInBody(p, token) {
+ if (p.openElements.hasInButtonScope($.P)) {
+ p._closePElement();
+ }
+ if (isNumberedHeader(p.openElements.currentTagId)) {
+ p.openElements.pop();
+ }
+ p._insertElement(token, NS.HTML);
+}
+function preStartTagInBody(p, token) {
+ if (p.openElements.hasInButtonScope($.P)) {
+ p._closePElement();
+ }
+ p._insertElement(token, NS.HTML);
+ //NOTE: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move
+ //on to the next one. (Newlines at the start of pre blocks are ignored as an authoring convenience.)
+ p.skipNextNewLine = true;
+ p.framesetOk = false;
+}
+function formStartTagInBody(p, token) {
+ const inTemplate = p.openElements.tmplCount > 0;
+ if (!p.formElement || inTemplate) {
+ if (p.openElements.hasInButtonScope($.P)) {
+ p._closePElement();
+ }
+ p._insertElement(token, NS.HTML);
+ if (!inTemplate) {
+ p.formElement = p.openElements.current;
+ }
+ }
+}
+function listItemStartTagInBody(p, token) {
+ p.framesetOk = false;
+ const tn = token.tagID;
+ for (let i = p.openElements.stackTop; i >= 0; i--) {
+ const elementId = p.openElements.tagIDs[i];
+ if ((tn === $.LI && elementId === $.LI) ||
+ ((tn === $.DD || tn === $.DT) && (elementId === $.DD || elementId === $.DT))) {
+ p.openElements.generateImpliedEndTagsWithExclusion(elementId);
+ p.openElements.popUntilTagNamePopped(elementId);
+ break;
+ }
+ if (elementId !== $.ADDRESS &&
+ elementId !== $.DIV &&
+ elementId !== $.P &&
+ p._isSpecialElement(p.openElements.items[i], elementId)) {
+ break;
+ }
+ }
+ if (p.openElements.hasInButtonScope($.P)) {
+ p._closePElement();
+ }
+ p._insertElement(token, NS.HTML);
+}
+function plaintextStartTagInBody(p, token) {
+ if (p.openElements.hasInButtonScope($.P)) {
+ p._closePElement();
+ }
+ p._insertElement(token, NS.HTML);
+ p.tokenizer.state = TokenizerMode.PLAINTEXT;
+}
+function buttonStartTagInBody(p, token) {
+ if (p.openElements.hasInScope($.BUTTON)) {
+ p.openElements.generateImpliedEndTags();
+ p.openElements.popUntilTagNamePopped($.BUTTON);
+ }
+ p._reconstructActiveFormattingElements();
+ p._insertElement(token, NS.HTML);
+ p.framesetOk = false;
+}
+function aStartTagInBody(p, token) {
+ const activeElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName(TN.A);
+ if (activeElementEntry) {
+ callAdoptionAgency(p, token);
+ p.openElements.remove(activeElementEntry.element);
+ p.activeFormattingElements.removeEntry(activeElementEntry);
+ }
+ p._reconstructActiveFormattingElements();
+ p._insertElement(token, NS.HTML);
+ p.activeFormattingElements.pushElement(p.openElements.current, token);
+}
+function bStartTagInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ p._insertElement(token, NS.HTML);
+ p.activeFormattingElements.pushElement(p.openElements.current, token);
+}
+function nobrStartTagInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ if (p.openElements.hasInScope($.NOBR)) {
+ callAdoptionAgency(p, token);
+ p._reconstructActiveFormattingElements();
+ }
+ p._insertElement(token, NS.HTML);
+ p.activeFormattingElements.pushElement(p.openElements.current, token);
+}
+function appletStartTagInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ p._insertElement(token, NS.HTML);
+ p.activeFormattingElements.insertMarker();
+ p.framesetOk = false;
+}
+function tableStartTagInBody(p, token) {
+ if (p.treeAdapter.getDocumentMode(p.document) !== DOCUMENT_MODE.QUIRKS && p.openElements.hasInButtonScope($.P)) {
+ p._closePElement();
+ }
+ p._insertElement(token, NS.HTML);
+ p.framesetOk = false;
+ p.insertionMode = InsertionMode.IN_TABLE;
+}
+function areaStartTagInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ p._appendElement(token, NS.HTML);
+ p.framesetOk = false;
+ token.ackSelfClosing = true;
+}
+function isHiddenInput(token) {
+ const inputType = getTokenAttr(token, ATTRS.TYPE);
+ return inputType != null && inputType.toLowerCase() === HIDDEN_INPUT_TYPE;
+}
+function inputStartTagInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ p._appendElement(token, NS.HTML);
+ if (!isHiddenInput(token)) {
+ p.framesetOk = false;
+ }
+ token.ackSelfClosing = true;
+}
+function paramStartTagInBody(p, token) {
+ p._appendElement(token, NS.HTML);
+ token.ackSelfClosing = true;
+}
+function hrStartTagInBody(p, token) {
+ if (p.openElements.hasInButtonScope($.P)) {
+ p._closePElement();
+ }
+ p._appendElement(token, NS.HTML);
+ p.framesetOk = false;
+ token.ackSelfClosing = true;
+}
+function imageStartTagInBody(p, token) {
+ token.tagName = TN.IMG;
+ token.tagID = $.IMG;
+ areaStartTagInBody(p, token);
+}
+function textareaStartTagInBody(p, token) {
+ p._insertElement(token, NS.HTML);
+ //NOTE: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move
+ //on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
+ p.skipNextNewLine = true;
+ p.tokenizer.state = TokenizerMode.RCDATA;
+ p.originalInsertionMode = p.insertionMode;
+ p.framesetOk = false;
+ p.insertionMode = InsertionMode.TEXT;
+}
+function xmpStartTagInBody(p, token) {
+ if (p.openElements.hasInButtonScope($.P)) {
+ p._closePElement();
+ }
+ p._reconstructActiveFormattingElements();
+ p.framesetOk = false;
+ p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
+}
+function iframeStartTagInBody(p, token) {
+ p.framesetOk = false;
+ p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
+}
+//NOTE: here we assume that we always act as an user agent with enabled plugins, so we parse
+// as rawtext.
+function noembedStartTagInBody(p, token) {
+ p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
+}
+function selectStartTagInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ p._insertElement(token, NS.HTML);
+ p.framesetOk = false;
+ p.insertionMode =
+ p.insertionMode === InsertionMode.IN_TABLE ||
+ p.insertionMode === InsertionMode.IN_CAPTION ||
+ p.insertionMode === InsertionMode.IN_TABLE_BODY ||
+ p.insertionMode === InsertionMode.IN_ROW ||
+ p.insertionMode === InsertionMode.IN_CELL
+ ? InsertionMode.IN_SELECT_IN_TABLE
+ : InsertionMode.IN_SELECT;
+}
+function optgroupStartTagInBody(p, token) {
+ if (p.openElements.currentTagId === $.OPTION) {
+ p.openElements.pop();
+ }
+ p._reconstructActiveFormattingElements();
+ p._insertElement(token, NS.HTML);
+}
+function rbStartTagInBody(p, token) {
+ if (p.openElements.hasInScope($.RUBY)) {
+ p.openElements.generateImpliedEndTags();
+ }
+ p._insertElement(token, NS.HTML);
+}
+function rtStartTagInBody(p, token) {
+ if (p.openElements.hasInScope($.RUBY)) {
+ p.openElements.generateImpliedEndTagsWithExclusion($.RTC);
+ }
+ p._insertElement(token, NS.HTML);
+}
+function mathStartTagInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ foreignContent.adjustTokenMathMLAttrs(token);
+ foreignContent.adjustTokenXMLAttrs(token);
+ if (token.selfClosing) {
+ p._appendElement(token, NS.MATHML);
+ }
+ else {
+ p._insertElement(token, NS.MATHML);
+ }
+ token.ackSelfClosing = true;
+}
+function svgStartTagInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ foreignContent.adjustTokenSVGAttrs(token);
+ foreignContent.adjustTokenXMLAttrs(token);
+ if (token.selfClosing) {
+ p._appendElement(token, NS.SVG);
+ }
+ else {
+ p._insertElement(token, NS.SVG);
+ }
+ token.ackSelfClosing = true;
+}
+function genericStartTagInBody(p, token) {
+ p._reconstructActiveFormattingElements();
+ p._insertElement(token, NS.HTML);
+}
+function startTagInBody(p, token) {
+ switch (token.tagID) {
+ case $.I:
+ case $.S:
+ case $.B:
+ case $.U:
+ case $.EM:
+ case $.TT:
+ case $.BIG:
+ case $.CODE:
+ case $.FONT:
+ case $.SMALL:
+ case $.STRIKE:
+ case $.STRONG: {
+ bStartTagInBody(p, token);
+ break;
+ }
+ case $.A: {
+ aStartTagInBody(p, token);
+ break;
+ }
+ case $.H1:
+ case $.H2:
+ case $.H3:
+ case $.H4:
+ case $.H5:
+ case $.H6: {
+ numberedHeaderStartTagInBody(p, token);
+ break;
+ }
+ case $.P:
+ case $.DL:
+ case $.OL:
+ case $.UL:
+ case $.DIV:
+ case $.DIR:
+ case $.NAV:
+ case $.MAIN:
+ case $.MENU:
+ case $.ASIDE:
+ case $.CENTER:
+ case $.FIGURE:
+ case $.FOOTER:
+ case $.HEADER:
+ case $.HGROUP:
+ case $.DIALOG:
+ case $.DETAILS:
+ case $.ADDRESS:
+ case $.ARTICLE:
+ case $.SECTION:
+ case $.SUMMARY:
+ case $.FIELDSET:
+ case $.BLOCKQUOTE:
+ case $.FIGCAPTION: {
+ addressStartTagInBody(p, token);
+ break;
+ }
+ case $.LI:
+ case $.DD:
+ case $.DT: {
+ listItemStartTagInBody(p, token);
+ break;
+ }
+ case $.BR:
+ case $.IMG:
+ case $.WBR:
+ case $.AREA:
+ case $.EMBED:
+ case $.KEYGEN: {
+ areaStartTagInBody(p, token);
+ break;
+ }
+ case $.HR: {
+ hrStartTagInBody(p, token);
+ break;
+ }
+ case $.RB:
+ case $.RTC: {
+ rbStartTagInBody(p, token);
+ break;
+ }
+ case $.RT:
+ case $.RP: {
+ rtStartTagInBody(p, token);
+ break;
+ }
+ case $.PRE:
+ case $.LISTING: {
+ preStartTagInBody(p, token);
+ break;
+ }
+ case $.XMP: {
+ xmpStartTagInBody(p, token);
+ break;
+ }
+ case $.SVG: {
+ svgStartTagInBody(p, token);
+ break;
+ }
+ case $.HTML: {
+ htmlStartTagInBody(p, token);
+ break;
+ }
+ case $.BASE:
+ case $.LINK:
+ case $.META:
+ case $.STYLE:
+ case $.TITLE:
+ case $.SCRIPT:
+ case $.BGSOUND:
+ case $.BASEFONT:
+ case $.TEMPLATE: {
+ startTagInHead(p, token);
+ break;
+ }
+ case $.BODY: {
+ bodyStartTagInBody(p, token);
+ break;
+ }
+ case $.FORM: {
+ formStartTagInBody(p, token);
+ break;
+ }
+ case $.NOBR: {
+ nobrStartTagInBody(p, token);
+ break;
+ }
+ case $.MATH: {
+ mathStartTagInBody(p, token);
+ break;
+ }
+ case $.TABLE: {
+ tableStartTagInBody(p, token);
+ break;
+ }
+ case $.INPUT: {
+ inputStartTagInBody(p, token);
+ break;
+ }
+ case $.PARAM:
+ case $.TRACK:
+ case $.SOURCE: {
+ paramStartTagInBody(p, token);
+ break;
+ }
+ case $.IMAGE: {
+ imageStartTagInBody(p, token);
+ break;
+ }
+ case $.BUTTON: {
+ buttonStartTagInBody(p, token);
+ break;
+ }
+ case $.APPLET:
+ case $.OBJECT:
+ case $.MARQUEE: {
+ appletStartTagInBody(p, token);
+ break;
+ }
+ case $.IFRAME: {
+ iframeStartTagInBody(p, token);
+ break;
+ }
+ case $.SELECT: {
+ selectStartTagInBody(p, token);
+ break;
+ }
+ case $.OPTION:
+ case $.OPTGROUP: {
+ optgroupStartTagInBody(p, token);
+ break;
+ }
+ case $.NOEMBED: {
+ noembedStartTagInBody(p, token);
+ break;
+ }
+ case $.FRAMESET: {
+ framesetStartTagInBody(p, token);
+ break;
+ }
+ case $.TEXTAREA: {
+ textareaStartTagInBody(p, token);
+ break;
+ }
+ case $.NOSCRIPT: {
+ if (p.options.scriptingEnabled) {
+ noembedStartTagInBody(p, token);
+ }
+ else {
+ genericStartTagInBody(p, token);
+ }
+ break;
+ }
+ case $.PLAINTEXT: {
+ plaintextStartTagInBody(p, token);
+ break;
+ }
+ case $.COL:
+ case $.TH:
+ case $.TD:
+ case $.TR:
+ case $.HEAD:
+ case $.FRAME:
+ case $.TBODY:
+ case $.TFOOT:
+ case $.THEAD:
+ case $.CAPTION:
+ case $.COLGROUP: {
+ // Ignore token
+ break;
+ }
+ default: {
+ genericStartTagInBody(p, token);
+ }
+ }
+}
+function bodyEndTagInBody(p, token) {
+ if (p.openElements.hasInScope($.BODY)) {
+ p.insertionMode = InsertionMode.AFTER_BODY;
+ //NOTE: is never popped from the stack, so we need to updated
+ //the end location explicitly.
+ if (p.options.sourceCodeLocationInfo) {
+ const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();
+ if (bodyElement) {
+ p._setEndLocation(bodyElement, token);
+ }
+ }
+ }
+}
+function htmlEndTagInBody(p, token) {
+ if (p.openElements.hasInScope($.BODY)) {
+ p.insertionMode = InsertionMode.AFTER_BODY;
+ endTagAfterBody(p, token);
+ }
+}
+function addressEndTagInBody(p, token) {
+ const tn = token.tagID;
+ if (p.openElements.hasInScope(tn)) {
+ p.openElements.generateImpliedEndTags();
+ p.openElements.popUntilTagNamePopped(tn);
+ }
+}
+function formEndTagInBody(p) {
+ const inTemplate = p.openElements.tmplCount > 0;
+ const { formElement } = p;
+ if (!inTemplate) {
+ p.formElement = null;
+ }
+ if ((formElement || inTemplate) && p.openElements.hasInScope($.FORM)) {
+ p.openElements.generateImpliedEndTags();
+ if (inTemplate) {
+ p.openElements.popUntilTagNamePopped($.FORM);
+ }
+ else if (formElement) {
+ p.openElements.remove(formElement);
+ }
+ }
+}
+function pEndTagInBody(p) {
+ if (!p.openElements.hasInButtonScope($.P)) {
+ p._insertFakeElement(TN.P, $.P);
+ }
+ p._closePElement();
+}
+function liEndTagInBody(p) {
+ if (p.openElements.hasInListItemScope($.LI)) {
+ p.openElements.generateImpliedEndTagsWithExclusion($.LI);
+ p.openElements.popUntilTagNamePopped($.LI);
+ }
+}
+function ddEndTagInBody(p, token) {
+ const tn = token.tagID;
+ if (p.openElements.hasInScope(tn)) {
+ p.openElements.generateImpliedEndTagsWithExclusion(tn);
+ p.openElements.popUntilTagNamePopped(tn);
+ }
+}
+function numberedHeaderEndTagInBody(p) {
+ if (p.openElements.hasNumberedHeaderInScope()) {
+ p.openElements.generateImpliedEndTags();
+ p.openElements.popUntilNumberedHeaderPopped();
+ }
+}
+function appletEndTagInBody(p, token) {
+ const tn = token.tagID;
+ if (p.openElements.hasInScope(tn)) {
+ p.openElements.generateImpliedEndTags();
+ p.openElements.popUntilTagNamePopped(tn);
+ p.activeFormattingElements.clearToLastMarker();
+ }
+}
+function brEndTagInBody(p) {
+ p._reconstructActiveFormattingElements();
+ p._insertFakeElement(TN.BR, $.BR);
+ p.openElements.pop();
+ p.framesetOk = false;
+}
+function genericEndTagInBody(p, token) {
+ const tn = token.tagName;
+ const tid = token.tagID;
+ for (let i = p.openElements.stackTop; i > 0; i--) {
+ const element = p.openElements.items[i];
+ const elementId = p.openElements.tagIDs[i];
+ // Compare the tag name here, as the tag might not be a known tag with an ID.
+ if (tid === elementId && (tid !== $.UNKNOWN || p.treeAdapter.getTagName(element) === tn)) {
+ p.openElements.generateImpliedEndTagsWithExclusion(tid);
+ if (p.openElements.stackTop >= i)
+ p.openElements.shortenToLength(i);
+ break;
+ }
+ if (p._isSpecialElement(element, elementId)) {
+ break;
+ }
+ }
+}
+function endTagInBody(p, token) {
+ switch (token.tagID) {
+ case $.A:
+ case $.B:
+ case $.I:
+ case $.S:
+ case $.U:
+ case $.EM:
+ case $.TT:
+ case $.BIG:
+ case $.CODE:
+ case $.FONT:
+ case $.NOBR:
+ case $.SMALL:
+ case $.STRIKE:
+ case $.STRONG: {
+ callAdoptionAgency(p, token);
+ break;
+ }
+ case $.P: {
+ pEndTagInBody(p);
+ break;
+ }
+ case $.DL:
+ case $.UL:
+ case $.OL:
+ case $.DIR:
+ case $.DIV:
+ case $.NAV:
+ case $.PRE:
+ case $.MAIN:
+ case $.MENU:
+ case $.ASIDE:
+ case $.BUTTON:
+ case $.CENTER:
+ case $.FIGURE:
+ case $.FOOTER:
+ case $.HEADER:
+ case $.HGROUP:
+ case $.DIALOG:
+ case $.ADDRESS:
+ case $.ARTICLE:
+ case $.DETAILS:
+ case $.SECTION:
+ case $.SUMMARY:
+ case $.LISTING:
+ case $.FIELDSET:
+ case $.BLOCKQUOTE:
+ case $.FIGCAPTION: {
+ addressEndTagInBody(p, token);
+ break;
+ }
+ case $.LI: {
+ liEndTagInBody(p);
+ break;
+ }
+ case $.DD:
+ case $.DT: {
+ ddEndTagInBody(p, token);
+ break;
+ }
+ case $.H1:
+ case $.H2:
+ case $.H3:
+ case $.H4:
+ case $.H5:
+ case $.H6: {
+ numberedHeaderEndTagInBody(p);
+ break;
+ }
+ case $.BR: {
+ brEndTagInBody(p);
+ break;
+ }
+ case $.BODY: {
+ bodyEndTagInBody(p, token);
+ break;
+ }
+ case $.HTML: {
+ htmlEndTagInBody(p, token);
+ break;
+ }
+ case $.FORM: {
+ formEndTagInBody(p);
+ break;
+ }
+ case $.APPLET:
+ case $.OBJECT:
+ case $.MARQUEE: {
+ appletEndTagInBody(p, token);
+ break;
+ }
+ case $.TEMPLATE: {
+ templateEndTagInHead(p, token);
+ break;
+ }
+ default: {
+ genericEndTagInBody(p, token);
+ }
+ }
+}
+function eofInBody(p, token) {
+ if (p.tmplInsertionModeStack.length > 0) {
+ eofInTemplate(p, token);
+ }
+ else {
+ stopParsing(p, token);
+ }
+}
+// The "text" insertion mode
+//------------------------------------------------------------------
+function endTagInText(p, token) {
+ var _a;
+ if (token.tagID === $.SCRIPT) {
+ (_a = p.scriptHandler) === null || _a === void 0 ? void 0 : _a.call(p, p.openElements.current);
+ }
+ p.openElements.pop();
+ p.insertionMode = p.originalInsertionMode;
+}
+function eofInText(p, token) {
+ p._err(token, ERR.eofInElementThatCanContainOnlyText);
+ p.openElements.pop();
+ p.insertionMode = p.originalInsertionMode;
+ p.onEof(token);
+}
+// The "in table" insertion mode
+//------------------------------------------------------------------
+function characterInTable(p, token) {
+ if (TABLE_STRUCTURE_TAGS.has(p.openElements.currentTagId)) {
+ p.pendingCharacterTokens.length = 0;
+ p.hasNonWhitespacePendingCharacterToken = false;
+ p.originalInsertionMode = p.insertionMode;
+ p.insertionMode = InsertionMode.IN_TABLE_TEXT;
+ switch (token.type) {
+ case TokenType.CHARACTER: {
+ characterInTableText(p, token);
+ break;
+ }
+ case TokenType.WHITESPACE_CHARACTER: {
+ whitespaceCharacterInTableText(p, token);
+ break;
+ }
+ // Ignore null
+ }
+ }
+ else {
+ tokenInTable(p, token);
+ }
+}
+function captionStartTagInTable(p, token) {
+ p.openElements.clearBackToTableContext();
+ p.activeFormattingElements.insertMarker();
+ p._insertElement(token, NS.HTML);
+ p.insertionMode = InsertionMode.IN_CAPTION;
+}
+function colgroupStartTagInTable(p, token) {
+ p.openElements.clearBackToTableContext();
+ p._insertElement(token, NS.HTML);
+ p.insertionMode = InsertionMode.IN_COLUMN_GROUP;
+}
+function colStartTagInTable(p, token) {
+ p.openElements.clearBackToTableContext();
+ p._insertFakeElement(TN.COLGROUP, $.COLGROUP);
+ p.insertionMode = InsertionMode.IN_COLUMN_GROUP;
+ startTagInColumnGroup(p, token);
+}
+function tbodyStartTagInTable(p, token) {
+ p.openElements.clearBackToTableContext();
+ p._insertElement(token, NS.HTML);
+ p.insertionMode = InsertionMode.IN_TABLE_BODY;
+}
+function tdStartTagInTable(p, token) {
+ p.openElements.clearBackToTableContext();
+ p._insertFakeElement(TN.TBODY, $.TBODY);
+ p.insertionMode = InsertionMode.IN_TABLE_BODY;
+ startTagInTableBody(p, token);
+}
+function tableStartTagInTable(p, token) {
+ if (p.openElements.hasInTableScope($.TABLE)) {
+ p.openElements.popUntilTagNamePopped($.TABLE);
+ p._resetInsertionMode();
+ p._processStartTag(token);
+ }
+}
+function inputStartTagInTable(p, token) {
+ if (isHiddenInput(token)) {
+ p._appendElement(token, NS.HTML);
+ }
+ else {
+ tokenInTable(p, token);
+ }
+ token.ackSelfClosing = true;
+}
+function formStartTagInTable(p, token) {
+ if (!p.formElement && p.openElements.tmplCount === 0) {
+ p._insertElement(token, NS.HTML);
+ p.formElement = p.openElements.current;
+ p.openElements.pop();
+ }
+}
+function startTagInTable(p, token) {
+ switch (token.tagID) {
+ case $.TD:
+ case $.TH:
+ case $.TR: {
+ tdStartTagInTable(p, token);
+ break;
+ }
+ case $.STYLE:
+ case $.SCRIPT:
+ case $.TEMPLATE: {
+ startTagInHead(p, token);
+ break;
+ }
+ case $.COL: {
+ colStartTagInTable(p, token);
+ break;
+ }
+ case $.FORM: {
+ formStartTagInTable(p, token);
+ break;
+ }
+ case $.TABLE: {
+ tableStartTagInTable(p, token);
+ break;
+ }
+ case $.TBODY:
+ case $.TFOOT:
+ case $.THEAD: {
+ tbodyStartTagInTable(p, token);
+ break;
+ }
+ case $.INPUT: {
+ inputStartTagInTable(p, token);
+ break;
+ }
+ case $.CAPTION: {
+ captionStartTagInTable(p, token);
+ break;
+ }
+ case $.COLGROUP: {
+ colgroupStartTagInTable(p, token);
+ break;
+ }
+ default: {
+ tokenInTable(p, token);
+ }
+ }
+}
+function endTagInTable(p, token) {
+ switch (token.tagID) {
+ case $.TABLE: {
+ if (p.openElements.hasInTableScope($.TABLE)) {
+ p.openElements.popUntilTagNamePopped($.TABLE);
+ p._resetInsertionMode();
+ }
+ break;
+ }
+ case $.TEMPLATE: {
+ templateEndTagInHead(p, token);
+ break;
+ }
+ case $.BODY:
+ case $.CAPTION:
+ case $.COL:
+ case $.COLGROUP:
+ case $.HTML:
+ case $.TBODY:
+ case $.TD:
+ case $.TFOOT:
+ case $.TH:
+ case $.THEAD:
+ case $.TR: {
+ // Ignore token
+ break;
+ }
+ default: {
+ tokenInTable(p, token);
+ }
+ }
+}
+function tokenInTable(p, token) {
+ const savedFosterParentingState = p.fosterParentingEnabled;
+ p.fosterParentingEnabled = true;
+ // Process token in `In Body` mode
+ modeInBody(p, token);
+ p.fosterParentingEnabled = savedFosterParentingState;
+}
+// The "in table text" insertion mode
+//------------------------------------------------------------------
+function whitespaceCharacterInTableText(p, token) {
+ p.pendingCharacterTokens.push(token);
+}
+function characterInTableText(p, token) {
+ p.pendingCharacterTokens.push(token);
+ p.hasNonWhitespacePendingCharacterToken = true;
+}
+function tokenInTableText(p, token) {
+ let i = 0;
+ if (p.hasNonWhitespacePendingCharacterToken) {
+ for (; i < p.pendingCharacterTokens.length; i++) {
+ tokenInTable(p, p.pendingCharacterTokens[i]);
+ }
+ }
+ else {
+ for (; i < p.pendingCharacterTokens.length; i++) {
+ p._insertCharacters(p.pendingCharacterTokens[i]);
+ }
+ }
+ p.insertionMode = p.originalInsertionMode;
+ p._processToken(token);
+}
+// The "in caption" insertion mode
+//------------------------------------------------------------------
+const TABLE_VOID_ELEMENTS = new Set([TAG_ID.CAPTION, TAG_ID.COL, TAG_ID.COLGROUP, TAG_ID.TBODY, TAG_ID.TD, TAG_ID.TFOOT, TAG_ID.TH, TAG_ID.THEAD, TAG_ID.TR]);
+function startTagInCaption(p, token) {
+ const tn = token.tagID;
+ if (TABLE_VOID_ELEMENTS.has(tn)) {
+ if (p.openElements.hasInTableScope($.CAPTION)) {
+ p.openElements.generateImpliedEndTags();
+ p.openElements.popUntilTagNamePopped($.CAPTION);
+ p.activeFormattingElements.clearToLastMarker();
+ p.insertionMode = InsertionMode.IN_TABLE;
+ startTagInTable(p, token);
+ }
+ }
+ else {
+ startTagInBody(p, token);
+ }
+}
+function endTagInCaption(p, token) {
+ const tn = token.tagID;
+ switch (tn) {
+ case $.CAPTION:
+ case $.TABLE: {
+ if (p.openElements.hasInTableScope($.CAPTION)) {
+ p.openElements.generateImpliedEndTags();
+ p.openElements.popUntilTagNamePopped($.CAPTION);
+ p.activeFormattingElements.clearToLastMarker();
+ p.insertionMode = InsertionMode.IN_TABLE;
+ if (tn === $.TABLE) {
+ endTagInTable(p, token);
+ }
+ }
+ break;
+ }
+ case $.BODY:
+ case $.COL:
+ case $.COLGROUP:
+ case $.HTML:
+ case $.TBODY:
+ case $.TD:
+ case $.TFOOT:
+ case $.TH:
+ case $.THEAD:
+ case $.TR: {
+ // Ignore token
+ break;
+ }
+ default: {
+ endTagInBody(p, token);
+ }
+ }
+}
+// The "in column group" insertion mode
+//------------------------------------------------------------------
+function startTagInColumnGroup(p, token) {
+ switch (token.tagID) {
+ case $.HTML: {
+ startTagInBody(p, token);
+ break;
+ }
+ case $.COL: {
+ p._appendElement(token, NS.HTML);
+ token.ackSelfClosing = true;
+ break;
+ }
+ case $.TEMPLATE: {
+ startTagInHead(p, token);
+ break;
+ }
+ default: {
+ tokenInColumnGroup(p, token);
+ }
+ }
+}
+function endTagInColumnGroup(p, token) {
+ switch (token.tagID) {
+ case $.COLGROUP: {
+ if (p.openElements.currentTagId === $.COLGROUP) {
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_TABLE;
+ }
+ break;
+ }
+ case $.TEMPLATE: {
+ templateEndTagInHead(p, token);
+ break;
+ }
+ case $.COL: {
+ // Ignore token
+ break;
+ }
+ default: {
+ tokenInColumnGroup(p, token);
+ }
+ }
+}
+function tokenInColumnGroup(p, token) {
+ if (p.openElements.currentTagId === $.COLGROUP) {
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_TABLE;
+ p._processToken(token);
+ }
+}
+// The "in table body" insertion mode
+//------------------------------------------------------------------
+function startTagInTableBody(p, token) {
+ switch (token.tagID) {
+ case $.TR: {
+ p.openElements.clearBackToTableBodyContext();
+ p._insertElement(token, NS.HTML);
+ p.insertionMode = InsertionMode.IN_ROW;
+ break;
+ }
+ case $.TH:
+ case $.TD: {
+ p.openElements.clearBackToTableBodyContext();
+ p._insertFakeElement(TN.TR, $.TR);
+ p.insertionMode = InsertionMode.IN_ROW;
+ startTagInRow(p, token);
+ break;
+ }
+ case $.CAPTION:
+ case $.COL:
+ case $.COLGROUP:
+ case $.TBODY:
+ case $.TFOOT:
+ case $.THEAD: {
+ if (p.openElements.hasTableBodyContextInTableScope()) {
+ p.openElements.clearBackToTableBodyContext();
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_TABLE;
+ startTagInTable(p, token);
+ }
+ break;
+ }
+ default: {
+ startTagInTable(p, token);
+ }
+ }
+}
+function endTagInTableBody(p, token) {
+ const tn = token.tagID;
+ switch (token.tagID) {
+ case $.TBODY:
+ case $.TFOOT:
+ case $.THEAD: {
+ if (p.openElements.hasInTableScope(tn)) {
+ p.openElements.clearBackToTableBodyContext();
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_TABLE;
+ }
+ break;
+ }
+ case $.TABLE: {
+ if (p.openElements.hasTableBodyContextInTableScope()) {
+ p.openElements.clearBackToTableBodyContext();
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_TABLE;
+ endTagInTable(p, token);
+ }
+ break;
+ }
+ case $.BODY:
+ case $.CAPTION:
+ case $.COL:
+ case $.COLGROUP:
+ case $.HTML:
+ case $.TD:
+ case $.TH:
+ case $.TR: {
+ // Ignore token
+ break;
+ }
+ default: {
+ endTagInTable(p, token);
+ }
+ }
+}
+// The "in row" insertion mode
+//------------------------------------------------------------------
+function startTagInRow(p, token) {
+ switch (token.tagID) {
+ case $.TH:
+ case $.TD: {
+ p.openElements.clearBackToTableRowContext();
+ p._insertElement(token, NS.HTML);
+ p.insertionMode = InsertionMode.IN_CELL;
+ p.activeFormattingElements.insertMarker();
+ break;
+ }
+ case $.CAPTION:
+ case $.COL:
+ case $.COLGROUP:
+ case $.TBODY:
+ case $.TFOOT:
+ case $.THEAD:
+ case $.TR: {
+ if (p.openElements.hasInTableScope($.TR)) {
+ p.openElements.clearBackToTableRowContext();
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_TABLE_BODY;
+ startTagInTableBody(p, token);
+ }
+ break;
+ }
+ default: {
+ startTagInTable(p, token);
+ }
+ }
+}
+function endTagInRow(p, token) {
+ switch (token.tagID) {
+ case $.TR: {
+ if (p.openElements.hasInTableScope($.TR)) {
+ p.openElements.clearBackToTableRowContext();
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_TABLE_BODY;
+ }
+ break;
+ }
+ case $.TABLE: {
+ if (p.openElements.hasInTableScope($.TR)) {
+ p.openElements.clearBackToTableRowContext();
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_TABLE_BODY;
+ endTagInTableBody(p, token);
+ }
+ break;
+ }
+ case $.TBODY:
+ case $.TFOOT:
+ case $.THEAD: {
+ if (p.openElements.hasInTableScope(token.tagID) || p.openElements.hasInTableScope($.TR)) {
+ p.openElements.clearBackToTableRowContext();
+ p.openElements.pop();
+ p.insertionMode = InsertionMode.IN_TABLE_BODY;
+ endTagInTableBody(p, token);
+ }
+ break;
+ }
+ case $.BODY:
+ case $.CAPTION:
+ case $.COL:
+ case $.COLGROUP:
+ case $.HTML:
+ case $.TD:
+ case $.TH: {
+ // Ignore end tag
+ break;
+ }
+ default: {
+ endTagInTable(p, token);
+ }
+ }
+}
+// The "in cell" insertion mode
+//------------------------------------------------------------------
+function startTagInCell(p, token) {
+ const tn = token.tagID;
+ if (TABLE_VOID_ELEMENTS.has(tn)) {
+ if (p.openElements.hasInTableScope($.TD) || p.openElements.hasInTableScope($.TH)) {
+ p._closeTableCell();
+ startTagInRow(p, token);
+ }
+ }
+ else {
+ startTagInBody(p, token);
+ }
+}
+function endTagInCell(p, token) {
+ const tn = token.tagID;
+ switch (tn) {
+ case $.TD:
+ case $.TH: {
+ if (p.openElements.hasInTableScope(tn)) {
+ p.openElements.generateImpliedEndTags();
+ p.openElements.popUntilTagNamePopped(tn);
+ p.activeFormattingElements.clearToLastMarker();
+ p.insertionMode = InsertionMode.IN_ROW;
+ }
+ break;
+ }
+ case $.TABLE:
+ case $.TBODY:
+ case $.TFOOT:
+ case $.THEAD:
+ case $.TR: {
+ if (p.openElements.hasInTableScope(tn)) {
+ p._closeTableCell();
+ endTagInRow(p, token);
+ }
+ break;
+ }
+ case $.BODY:
+ case $.CAPTION:
+ case $.COL:
+ case $.COLGROUP:
+ case $.HTML: {
+ // Ignore token
+ break;
+ }
+ default: {
+ endTagInBody(p, token);
+ }
+ }
+}
+// The "in select" insertion mode
+//------------------------------------------------------------------
+function startTagInSelect(p, token) {
+ switch (token.tagID) {
+ case $.HTML: {
+ startTagInBody(p, token);
+ break;
+ }
+ case $.OPTION: {
+ if (p.openElements.currentTagId === $.OPTION) {
+ p.openElements.pop();
+ }
+ p._insertElement(token, NS.HTML);
+ break;
+ }
+ case $.OPTGROUP: {
+ if (p.openElements.currentTagId === $.OPTION) {
+ p.openElements.pop();
+ }
+ if (p.openElements.currentTagId === $.OPTGROUP) {
+ p.openElements.pop();
+ }
+ p._insertElement(token, NS.HTML);
+ break;
+ }
+ case $.INPUT:
+ case $.KEYGEN:
+ case $.TEXTAREA:
+ case $.SELECT: {
+ if (p.openElements.hasInSelectScope($.SELECT)) {
+ p.openElements.popUntilTagNamePopped($.SELECT);
+ p._resetInsertionMode();
+ if (token.tagID !== $.SELECT) {
+ p._processStartTag(token);
+ }
+ }
+ break;
+ }
+ case $.SCRIPT:
+ case $.TEMPLATE: {
+ startTagInHead(p, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+}
+function endTagInSelect(p, token) {
+ switch (token.tagID) {
+ case $.OPTGROUP: {
+ if (p.openElements.stackTop > 0 &&
+ p.openElements.currentTagId === $.OPTION &&
+ p.openElements.tagIDs[p.openElements.stackTop - 1] === $.OPTGROUP) {
+ p.openElements.pop();
+ }
+ if (p.openElements.currentTagId === $.OPTGROUP) {
+ p.openElements.pop();
+ }
+ break;
+ }
+ case $.OPTION: {
+ if (p.openElements.currentTagId === $.OPTION) {
+ p.openElements.pop();
+ }
+ break;
+ }
+ case $.SELECT: {
+ if (p.openElements.hasInSelectScope($.SELECT)) {
+ p.openElements.popUntilTagNamePopped($.SELECT);
+ p._resetInsertionMode();
+ }
+ break;
+ }
+ case $.TEMPLATE: {
+ templateEndTagInHead(p, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+}
+// The "in select in table" insertion mode
+//------------------------------------------------------------------
+function startTagInSelectInTable(p, token) {
+ const tn = token.tagID;
+ if (tn === $.CAPTION ||
+ tn === $.TABLE ||
+ tn === $.TBODY ||
+ tn === $.TFOOT ||
+ tn === $.THEAD ||
+ tn === $.TR ||
+ tn === $.TD ||
+ tn === $.TH) {
+ p.openElements.popUntilTagNamePopped($.SELECT);
+ p._resetInsertionMode();
+ p._processStartTag(token);
+ }
+ else {
+ startTagInSelect(p, token);
+ }
+}
+function endTagInSelectInTable(p, token) {
+ const tn = token.tagID;
+ if (tn === $.CAPTION ||
+ tn === $.TABLE ||
+ tn === $.TBODY ||
+ tn === $.TFOOT ||
+ tn === $.THEAD ||
+ tn === $.TR ||
+ tn === $.TD ||
+ tn === $.TH) {
+ if (p.openElements.hasInTableScope(tn)) {
+ p.openElements.popUntilTagNamePopped($.SELECT);
+ p._resetInsertionMode();
+ p.onEndTag(token);
+ }
+ }
+ else {
+ endTagInSelect(p, token);
+ }
+}
+// The "in template" insertion mode
+//------------------------------------------------------------------
+function startTagInTemplate(p, token) {
+ switch (token.tagID) {
+ // First, handle tags that can start without a mode change
+ case $.BASE:
+ case $.BASEFONT:
+ case $.BGSOUND:
+ case $.LINK:
+ case $.META:
+ case $.NOFRAMES:
+ case $.SCRIPT:
+ case $.STYLE:
+ case $.TEMPLATE:
+ case $.TITLE: {
+ startTagInHead(p, token);
+ break;
+ }
+ // Re-process the token in the appropriate mode
+ case $.CAPTION:
+ case $.COLGROUP:
+ case $.TBODY:
+ case $.TFOOT:
+ case $.THEAD: {
+ p.tmplInsertionModeStack[0] = InsertionMode.IN_TABLE;
+ p.insertionMode = InsertionMode.IN_TABLE;
+ startTagInTable(p, token);
+ break;
+ }
+ case $.COL: {
+ p.tmplInsertionModeStack[0] = InsertionMode.IN_COLUMN_GROUP;
+ p.insertionMode = InsertionMode.IN_COLUMN_GROUP;
+ startTagInColumnGroup(p, token);
+ break;
+ }
+ case $.TR: {
+ p.tmplInsertionModeStack[0] = InsertionMode.IN_TABLE_BODY;
+ p.insertionMode = InsertionMode.IN_TABLE_BODY;
+ startTagInTableBody(p, token);
+ break;
+ }
+ case $.TD:
+ case $.TH: {
+ p.tmplInsertionModeStack[0] = InsertionMode.IN_ROW;
+ p.insertionMode = InsertionMode.IN_ROW;
+ startTagInRow(p, token);
+ break;
+ }
+ default: {
+ p.tmplInsertionModeStack[0] = InsertionMode.IN_BODY;
+ p.insertionMode = InsertionMode.IN_BODY;
+ startTagInBody(p, token);
+ }
+ }
+}
+function endTagInTemplate(p, token) {
+ if (token.tagID === $.TEMPLATE) {
+ templateEndTagInHead(p, token);
+ }
+}
+function eofInTemplate(p, token) {
+ if (p.openElements.tmplCount > 0) {
+ p.openElements.popUntilTagNamePopped($.TEMPLATE);
+ p.activeFormattingElements.clearToLastMarker();
+ p.tmplInsertionModeStack.shift();
+ p._resetInsertionMode();
+ p.onEof(token);
+ }
+ else {
+ stopParsing(p, token);
+ }
+}
+// The "after body" insertion mode
+//------------------------------------------------------------------
+function startTagAfterBody(p, token) {
+ if (token.tagID === $.HTML) {
+ startTagInBody(p, token);
+ }
+ else {
+ tokenAfterBody(p, token);
+ }
+}
+function endTagAfterBody(p, token) {
+ var _a;
+ if (token.tagID === $.HTML) {
+ if (!p.fragmentContext) {
+ p.insertionMode = InsertionMode.AFTER_AFTER_BODY;
+ }
+ //NOTE: is never popped from the stack, so we need to updated
+ //the end location explicitly.
+ if (p.options.sourceCodeLocationInfo && p.openElements.tagIDs[0] === $.HTML) {
+ p._setEndLocation(p.openElements.items[0], token);
+ // Update the body element, if it doesn't have an end tag
+ const bodyElement = p.openElements.items[1];
+ if (bodyElement && !((_a = p.treeAdapter.getNodeSourceCodeLocation(bodyElement)) === null || _a === void 0 ? void 0 : _a.endTag)) {
+ p._setEndLocation(bodyElement, token);
+ }
+ }
+ }
+ else {
+ tokenAfterBody(p, token);
+ }
+}
+function tokenAfterBody(p, token) {
+ p.insertionMode = InsertionMode.IN_BODY;
+ modeInBody(p, token);
+}
+// The "in frameset" insertion mode
+//------------------------------------------------------------------
+function startTagInFrameset(p, token) {
+ switch (token.tagID) {
+ case $.HTML: {
+ startTagInBody(p, token);
+ break;
+ }
+ case $.FRAMESET: {
+ p._insertElement(token, NS.HTML);
+ break;
+ }
+ case $.FRAME: {
+ p._appendElement(token, NS.HTML);
+ token.ackSelfClosing = true;
+ break;
+ }
+ case $.NOFRAMES: {
+ startTagInHead(p, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+}
+function endTagInFrameset(p, token) {
+ if (token.tagID === $.FRAMESET && !p.openElements.isRootHtmlElementCurrent()) {
+ p.openElements.pop();
+ if (!p.fragmentContext && p.openElements.currentTagId !== $.FRAMESET) {
+ p.insertionMode = InsertionMode.AFTER_FRAMESET;
+ }
+ }
+}
+// The "after frameset" insertion mode
+//------------------------------------------------------------------
+function startTagAfterFrameset(p, token) {
+ switch (token.tagID) {
+ case $.HTML: {
+ startTagInBody(p, token);
+ break;
+ }
+ case $.NOFRAMES: {
+ startTagInHead(p, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+}
+function endTagAfterFrameset(p, token) {
+ if (token.tagID === $.HTML) {
+ p.insertionMode = InsertionMode.AFTER_AFTER_FRAMESET;
+ }
+}
+// The "after after body" insertion mode
+//------------------------------------------------------------------
+function startTagAfterAfterBody(p, token) {
+ if (token.tagID === $.HTML) {
+ startTagInBody(p, token);
+ }
+ else {
+ tokenAfterAfterBody(p, token);
+ }
+}
+function tokenAfterAfterBody(p, token) {
+ p.insertionMode = InsertionMode.IN_BODY;
+ modeInBody(p, token);
+}
+// The "after after frameset" insertion mode
+//------------------------------------------------------------------
+function startTagAfterAfterFrameset(p, token) {
+ switch (token.tagID) {
+ case $.HTML: {
+ startTagInBody(p, token);
+ break;
+ }
+ case $.NOFRAMES: {
+ startTagInHead(p, token);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+}
+// The rules for parsing tokens in foreign content
+//------------------------------------------------------------------
+function nullCharacterInForeignContent(p, token) {
+ token.chars = unicode.REPLACEMENT_CHARACTER;
+ p._insertCharacters(token);
+}
+function characterInForeignContent(p, token) {
+ p._insertCharacters(token);
+ p.framesetOk = false;
+}
+function popUntilHtmlOrIntegrationPoint(p) {
+ while (p.treeAdapter.getNamespaceURI(p.openElements.current) !== NS.HTML &&
+ !p._isIntegrationPoint(p.openElements.currentTagId, p.openElements.current)) {
+ p.openElements.pop();
+ }
+}
+function startTagInForeignContent(p, token) {
+ if (foreignContent.causesExit(token)) {
+ popUntilHtmlOrIntegrationPoint(p);
+ p._startTagOutsideForeignContent(token);
+ }
+ else {
+ const current = p._getAdjustedCurrentElement();
+ const currentNs = p.treeAdapter.getNamespaceURI(current);
+ if (currentNs === NS.MATHML) {
+ foreignContent.adjustTokenMathMLAttrs(token);
+ }
+ else if (currentNs === NS.SVG) {
+ foreignContent.adjustTokenSVGTagName(token);
+ foreignContent.adjustTokenSVGAttrs(token);
+ }
+ foreignContent.adjustTokenXMLAttrs(token);
+ if (token.selfClosing) {
+ p._appendElement(token, currentNs);
+ }
+ else {
+ p._insertElement(token, currentNs);
+ }
+ token.ackSelfClosing = true;
+ }
+}
+function endTagInForeignContent(p, token) {
+ if (token.tagID === $.P || token.tagID === $.BR) {
+ popUntilHtmlOrIntegrationPoint(p);
+ p._endTagOutsideForeignContent(token);
+ return;
+ }
+ for (let i = p.openElements.stackTop; i > 0; i--) {
+ const element = p.openElements.items[i];
+ if (p.treeAdapter.getNamespaceURI(element) === NS.HTML) {
+ p._endTagOutsideForeignContent(token);
+ break;
+ }
+ const tagName = p.treeAdapter.getTagName(element);
+ if (tagName.toLowerCase() === token.tagName) {
+ //NOTE: update the token tag name for `_setEndLocation`.
+ token.tagName = tagName;
+ p.openElements.shortenToLength(i);
+ break;
+ }
+ }
+}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/entities/lib/esm/escape.js
+const xmlReplacer = /["&'<>$\x80-\uFFFF]/g;
+const xmlCodeMap = new Map([
+ [34, """],
+ [38, "&"],
+ [39, "'"],
+ [60, "<"],
+ [62, ">"],
+]);
+// For compatibility with node < 4, we wrap `codePointAt`
+const getCodePoint =
+// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+String.prototype.codePointAt != null
+ ? (str, index) => str.codePointAt(index)
+ : // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
+ (c, index) => (c.charCodeAt(index) & 0xfc00) === 0xd800
+ ? (c.charCodeAt(index) - 0xd800) * 0x400 +
+ c.charCodeAt(index + 1) -
+ 0xdc00 +
+ 0x10000
+ : c.charCodeAt(index);
+/**
+ * Encodes all non-ASCII characters, as well as characters not valid in XML
+ * documents using XML entities.
+ *
+ * If a character has no equivalent entity, a
+ * numeric hexadecimal reference (eg. `ü`) will be used.
+ */
+function encodeXML(str) {
+ let ret = "";
+ let lastIdx = 0;
+ let match;
+ while ((match = xmlReplacer.exec(str)) !== null) {
+ const i = match.index;
+ const char = str.charCodeAt(i);
+ const next = xmlCodeMap.get(char);
+ if (next !== undefined) {
+ ret += str.substring(lastIdx, i) + next;
+ lastIdx = i + 1;
+ }
+ else {
+ ret += `${str.substring(lastIdx, i)}${getCodePoint(str, i).toString(16)};`;
+ // Increase by 1 if we have a surrogate pair
+ lastIdx = xmlReplacer.lastIndex += Number((char & 0xfc00) === 0xd800);
+ }
+ }
+ return ret + str.substr(lastIdx);
+}
+/**
+ * Encodes all non-ASCII characters, as well as characters not valid in XML
+ * documents using numeric hexadecimal reference (eg. `ü`).
+ *
+ * Have a look at `escapeUTF8` if you want a more concise output at the expense
+ * of reduced transportability.
+ *
+ * @param data String to escape.
+ */
+const escape_escape = (/* unused pure expression or super */ null && (encodeXML));
+/**
+ * Creates a function that escapes all characters matched by the given regular
+ * expression using the given map of characters to escape to their entities.
+ *
+ * @param regex Regular expression to match characters to escape.
+ * @param map Map of characters to escape to their entities.
+ *
+ * @returns Function that escapes all characters matched by the given regular
+ * expression using the given map of characters to escape to their entities.
+ */
+function getEscaper(regex, map) {
+ return function escape(data) {
+ let match;
+ let lastIdx = 0;
+ let result = "";
+ while ((match = regex.exec(data))) {
+ if (lastIdx !== match.index) {
+ result += data.substring(lastIdx, match.index);
+ }
+ // We know that this character will be in the map.
+ result += map.get(match[0].charCodeAt(0));
+ // Every match will be of length 1
+ lastIdx = match.index + 1;
+ }
+ return result + data.substring(lastIdx);
+ };
+}
+/**
+ * Encodes all characters not valid in XML documents using XML entities.
+ *
+ * Note that the output will be character-set dependent.
+ *
+ * @param data String to escape.
+ */
+const escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap);
+/**
+ * Encodes all characters that have to be escaped in HTML attributes,
+ * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
+ *
+ * @param data String to escape.
+ */
+const escape_escapeAttribute = getEscaper(/["&\u00A0]/g, new Map([
+ [34, """],
+ [38, "&"],
+ [160, " "],
+]));
+/**
+ * Encodes all characters that have to be escaped in HTML text,
+ * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
+ *
+ * @param data String to escape.
+ */
+const escape_escapeText = getEscaper(/[&<>\u00A0]/g, new Map([
+ [38, "&"],
+ [60, "<"],
+ [62, ">"],
+ [160, " "],
+]));
+//# sourceMappingURL=escape.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/serializer/index.js
+
+
+
+// Sets
+const VOID_ELEMENTS = new Set([
+ TAG_NAMES.AREA,
+ TAG_NAMES.BASE,
+ TAG_NAMES.BASEFONT,
+ TAG_NAMES.BGSOUND,
+ TAG_NAMES.BR,
+ TAG_NAMES.COL,
+ TAG_NAMES.EMBED,
+ TAG_NAMES.FRAME,
+ TAG_NAMES.HR,
+ TAG_NAMES.IMG,
+ TAG_NAMES.INPUT,
+ TAG_NAMES.KEYGEN,
+ TAG_NAMES.LINK,
+ TAG_NAMES.META,
+ TAG_NAMES.PARAM,
+ TAG_NAMES.SOURCE,
+ TAG_NAMES.TRACK,
+ TAG_NAMES.WBR,
+]);
+function isVoidElement(node, options) {
+ return (options.treeAdapter.isElementNode(node) &&
+ options.treeAdapter.getNamespaceURI(node) === NS.HTML &&
+ VOID_ELEMENTS.has(options.treeAdapter.getTagName(node)));
+}
+const defaultOpts = { treeAdapter: defaultTreeAdapter, scriptingEnabled: true };
+/**
+ * Serializes an AST node to an HTML string.
+ *
+ * @example
+ *
+ * ```js
+ * const parse5 = require('parse5');
+ *
+ * const document = parse5.parse('Hi there!');
+ *
+ * // Serializes a document.
+ * const html = parse5.serialize(document);
+ *
+ * // Serializes the element content.
+ * const str = parse5.serialize(document.childNodes[1]);
+ *
+ * console.log(str); //> 'Hi there!'
+ * ```
+ *
+ * @param node Node to serialize.
+ * @param options Serialization options.
+ */
+function serialize(node, options) {
+ const opts = { ...defaultOpts, ...options };
+ if (isVoidElement(node, opts)) {
+ return '';
+ }
+ return serializeChildNodes(node, opts);
+}
+/**
+ * Serializes an AST element node to an HTML string, including the element node.
+ *
+ * @example
+ *
+ * ```js
+ * const parse5 = require('parse5');
+ *
+ * const document = parse5.parseFragment('Hello, world !
');
+ *
+ * // Serializes the element.
+ * const html = parse5.serializeOuter(document.childNodes[0]);
+ *
+ * console.log(str); //> '
Hello, world !
'
+ * ```
+ *
+ * @param node Node to serialize.
+ * @param options Serialization options.
+ */
+function serializeOuter(node, options) {
+ const opts = { ...defaultOpts, ...options };
+ return serializeNode(node, opts);
+}
+function serializeChildNodes(parentNode, options) {
+ let html = '';
+ // Get container of the child nodes
+ const container = options.treeAdapter.isElementNode(parentNode) &&
+ options.treeAdapter.getTagName(parentNode) === $.TEMPLATE &&
+ options.treeAdapter.getNamespaceURI(parentNode) === NS.HTML
+ ? options.treeAdapter.getTemplateContent(parentNode)
+ : parentNode;
+ const childNodes = options.treeAdapter.getChildNodes(container);
+ if (childNodes) {
+ for (const currentNode of childNodes) {
+ html += serializeNode(currentNode, options);
+ }
+ }
+ return html;
+}
+function serializeNode(node, options) {
+ if (options.treeAdapter.isElementNode(node)) {
+ return serializeElement(node, options);
+ }
+ if (options.treeAdapter.isTextNode(node)) {
+ return serializeTextNode(node, options);
+ }
+ if (options.treeAdapter.isCommentNode(node)) {
+ return serializeCommentNode(node, options);
+ }
+ if (options.treeAdapter.isDocumentTypeNode(node)) {
+ return serializeDocumentTypeNode(node, options);
+ }
+ // Return an empty string for unknown nodes
+ return '';
+}
+function serializeElement(node, options) {
+ const tn = options.treeAdapter.getTagName(node);
+ return `<${tn}${serializeAttributes(node, options)}>${isVoidElement(node, options) ? '' : `${serializeChildNodes(node, options)}${tn}>`}`;
+}
+function serializeAttributes(node, { treeAdapter }) {
+ let html = '';
+ for (const attr of treeAdapter.getAttrList(node)) {
+ html += ' ';
+ if (!attr.namespace) {
+ html += attr.name;
+ }
+ else
+ switch (attr.namespace) {
+ case NS.XML: {
+ html += `xml:${attr.name}`;
+ break;
+ }
+ case NS.XMLNS: {
+ if (attr.name !== 'xmlns') {
+ html += 'xmlns:';
+ }
+ html += attr.name;
+ break;
+ }
+ case NS.XLINK: {
+ html += `xlink:${attr.name}`;
+ break;
+ }
+ default: {
+ html += `${attr.prefix}:${attr.name}`;
+ }
+ }
+ html += `="${escapeAttribute(attr.value)}"`;
+ }
+ return html;
+}
+function serializeTextNode(node, options) {
+ const { treeAdapter } = options;
+ const content = treeAdapter.getTextNodeContent(node);
+ const parent = treeAdapter.getParentNode(node);
+ const parentTn = parent && treeAdapter.isElementNode(parent) && treeAdapter.getTagName(parent);
+ return parentTn &&
+ treeAdapter.getNamespaceURI(parent) === NS.HTML &&
+ hasUnescapedText(parentTn, options.scriptingEnabled)
+ ? content
+ : escapeText(content);
+}
+function serializeCommentNode(node, { treeAdapter }) {
+ return ``;
+}
+function serializeDocumentTypeNode(node, { treeAdapter }) {
+ return ``;
+}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5/dist/index.js
+
+
+
+
+
+/** @internal */
+
+/** @internal */
+
+/** @internal */
+
+/** @internal */
+
+// Shorthands
+/**
+ * Parses an HTML string.
+ *
+ * @param html Input HTML string.
+ * @param options Parsing options.
+ * @returns Document
+ *
+ * @example
+ *
+ * ```js
+ * const parse5 = require('parse5');
+ *
+ * const document = parse5.parse('Hi there!');
+ *
+ * console.log(document.childNodes[1].tagName); //> 'html'
+ *```
+ */
+function parse(html, options) {
+ return Parser.parse(html, options);
+}
+function parseFragment(fragmentContext, html, options) {
+ if (typeof fragmentContext === 'string') {
+ options = html;
+ html = fragmentContext;
+ fragmentContext = null;
+ }
+ const parser = Parser.getFragmentParser(fragmentContext, options);
+ parser.tokenizer.write(html, true);
+ return parser.getFragment();
+}
+//# sourceMappingURL=index.js.map
+// EXTERNAL MODULE: ./node_modules/stream-browserify/index.js
+var stream_browserify = __webpack_require__(2830);
+;// CONCATENATED MODULE: ./node_modules/parse5-sax-parser/dist/dev-null-stream.js
+
+class DevNullStream extends stream_browserify.Writable {
+ _write(_chunk, _encoding, cb) {
+ cb();
+ }
+}
+//# sourceMappingURL=dev-null-stream.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5-sax-parser/dist/parser-feedback-simulator.js
+
+const parser_feedback_simulator_$ = TAG_ID;
+const parser_feedback_simulator_REPLACEMENT_CHARACTER = '\uFFFD';
+const LINE_FEED_CODE_POINT = 0x0a;
+/**
+ * Simulates adjustments of the Tokenizer which are performed by the standard parser during tree construction.
+ */
+class ParserFeedbackSimulator {
+ constructor(options, handler) {
+ this.handler = handler;
+ this.namespaceStack = [];
+ this.inForeignContent = false;
+ this.skipNextNewLine = false;
+ this.tokenizer = new tokenizer_Tokenizer(options, this);
+ this._enterNamespace(html_NS.HTML);
+ }
+ /** @internal */
+ onNullCharacter(token) {
+ this.skipNextNewLine = false;
+ if (this.inForeignContent) {
+ this.handler.onCharacter({
+ type: token_TokenType.CHARACTER,
+ chars: parser_feedback_simulator_REPLACEMENT_CHARACTER,
+ location: token.location,
+ });
+ }
+ else {
+ this.handler.onNullCharacter(token);
+ }
+ }
+ /** @internal */
+ onWhitespaceCharacter(token) {
+ if (this.skipNextNewLine && token.chars.charCodeAt(0) === LINE_FEED_CODE_POINT) {
+ this.skipNextNewLine = false;
+ if (token.chars.length === 1) {
+ return;
+ }
+ token.chars = token.chars.substr(1);
+ }
+ this.handler.onWhitespaceCharacter(token);
+ }
+ /** @internal */
+ onCharacter(token) {
+ this.skipNextNewLine = false;
+ this.handler.onCharacter(token);
+ }
+ /** @internal */
+ onComment(token) {
+ this.skipNextNewLine = false;
+ this.handler.onComment(token);
+ }
+ /** @internal */
+ onDoctype(token) {
+ this.skipNextNewLine = false;
+ this.handler.onDoctype(token);
+ }
+ /** @internal */
+ onEof(token) {
+ this.skipNextNewLine = false;
+ this.handler.onEof(token);
+ }
+ //Namespace stack mutations
+ _enterNamespace(namespace) {
+ this.namespaceStack.unshift(namespace);
+ this.inForeignContent = namespace !== html_NS.HTML;
+ this.tokenizer.inForeignNode = this.inForeignContent;
+ }
+ _leaveCurrentNamespace() {
+ this.namespaceStack.shift();
+ this.inForeignContent = this.namespaceStack[0] !== html_NS.HTML;
+ this.tokenizer.inForeignNode = this.inForeignContent;
+ }
+ //Token handlers
+ _ensureTokenizerMode(tn) {
+ switch (tn) {
+ case parser_feedback_simulator_$.TEXTAREA:
+ case parser_feedback_simulator_$.TITLE: {
+ this.tokenizer.state = tokenizer_TokenizerMode.RCDATA;
+ break;
+ }
+ case parser_feedback_simulator_$.PLAINTEXT: {
+ this.tokenizer.state = tokenizer_TokenizerMode.PLAINTEXT;
+ break;
+ }
+ case parser_feedback_simulator_$.SCRIPT: {
+ this.tokenizer.state = tokenizer_TokenizerMode.SCRIPT_DATA;
+ break;
+ }
+ case parser_feedback_simulator_$.STYLE:
+ case parser_feedback_simulator_$.IFRAME:
+ case parser_feedback_simulator_$.XMP:
+ case parser_feedback_simulator_$.NOEMBED:
+ case parser_feedback_simulator_$.NOFRAMES:
+ case parser_feedback_simulator_$.NOSCRIPT: {
+ this.tokenizer.state = tokenizer_TokenizerMode.RAWTEXT;
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ }
+ /** @internal */
+ onStartTag(token) {
+ let tn = token.tagID;
+ switch (tn) {
+ case parser_feedback_simulator_$.SVG: {
+ this._enterNamespace(html_NS.SVG);
+ break;
+ }
+ case parser_feedback_simulator_$.MATH: {
+ this._enterNamespace(html_NS.MATHML);
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ if (this.inForeignContent) {
+ if (causesExit(token)) {
+ this._leaveCurrentNamespace();
+ }
+ else {
+ const currentNs = this.namespaceStack[0];
+ if (currentNs === html_NS.MATHML) {
+ adjustTokenMathMLAttrs(token);
+ }
+ else if (currentNs === html_NS.SVG) {
+ adjustTokenSVGTagName(token);
+ adjustTokenSVGAttrs(token);
+ }
+ adjustTokenXMLAttrs(token);
+ tn = token.tagID;
+ if (!token.selfClosing && isIntegrationPoint(tn, currentNs, token.attrs)) {
+ this._enterNamespace(html_NS.HTML);
+ }
+ }
+ }
+ else {
+ switch (tn) {
+ case parser_feedback_simulator_$.PRE:
+ case parser_feedback_simulator_$.TEXTAREA:
+ case parser_feedback_simulator_$.LISTING: {
+ this.skipNextNewLine = true;
+ break;
+ }
+ case parser_feedback_simulator_$.IMAGE: {
+ token.tagName = TAG_NAMES.IMG;
+ token.tagID = parser_feedback_simulator_$.IMG;
+ break;
+ }
+ default:
+ // Do nothing
+ }
+ this._ensureTokenizerMode(tn);
+ }
+ this.handler.onStartTag(token);
+ }
+ /** @internal */
+ onEndTag(token) {
+ let tn = token.tagID;
+ if (!this.inForeignContent) {
+ const previousNs = this.namespaceStack[1];
+ if (previousNs === html_NS.SVG) {
+ const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName);
+ if (adjustedTagName) {
+ tn = html_getTagID(adjustedTagName);
+ }
+ }
+ //NOTE: check for exit from integration point
+ if (isIntegrationPoint(tn, previousNs, token.attrs)) {
+ this._leaveCurrentNamespace();
+ }
+ }
+ else if ((tn === parser_feedback_simulator_$.SVG && this.namespaceStack[0] === html_NS.SVG) ||
+ (tn === parser_feedback_simulator_$.MATH && this.namespaceStack[0] === html_NS.MATHML)) {
+ this._leaveCurrentNamespace();
+ }
+ // NOTE: adjust end tag name as well for consistency
+ if (this.namespaceStack[0] === html_NS.SVG) {
+ adjustTokenSVGTagName(token);
+ }
+ this.handler.onEndTag(token);
+ }
+}
+//# sourceMappingURL=parser-feedback-simulator.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5-sax-parser/dist/index.js
+
+
+
+/**
+ * Streaming [SAX](https://en.wikipedia.org/wiki/Simple_API_for_XML)-style HTML parser.
+ * A [transform stream](https://nodejs.org/api/stream.html#stream_class_stream_transform) (which means you can pipe _through_ it, see example).
+ *
+ * @example
+ *
+ * ```js
+ * const SAXParser = require('parse5-sax-parser');
+ * const http = require('http');
+ * const fs = require('fs');
+ *
+ * const file = fs.createWriteStream('/home/google.com.html');
+ * const parser = new SAXParser();
+ *
+ * parser.on('text', text => {
+ * // Handle page text content
+ * ...
+ * });
+ *
+ * http.get('http://google.com', res => {
+ * // `SAXParser` is the `Transform` stream, which means you can pipe
+ * // through it. So, you can analyze the page content and, e.g., save it
+ * // to the file at the same time:
+ * res.pipe(parser).pipe(file);
+ * });
+ * ```
+ */
+class SAXParser extends stream_browserify.Transform {
+ /**
+ * @param options Parsing options.
+ */
+ constructor(options = {}) {
+ super({ encoding: 'utf8', decodeStrings: false });
+ this.pendingText = null;
+ this.lastChunkWritten = false;
+ this.stopped = false;
+ this.options = {
+ sourceCodeLocationInfo: false,
+ ...options,
+ };
+ this.parserFeedbackSimulator = new ParserFeedbackSimulator(this.options, this);
+ this.tokenizer = this.parserFeedbackSimulator.tokenizer;
+ // NOTE: always pipe the stream to the /dev/null stream to avoid
+ // the `highWaterMark` to be hit even if we don't have consumers.
+ // (see: https://github.com/inikulin/parse5/issues/97#issuecomment-171940774)
+ this.pipe(new DevNullStream());
+ }
+ //`Transform` implementation
+ _transform(chunk, _encoding, callback) {
+ if (typeof chunk !== 'string') {
+ throw new TypeError('Parser can work only with string streams.');
+ }
+ callback(null, this._transformChunk(chunk));
+ }
+ _final(callback) {
+ this.lastChunkWritten = true;
+ callback(null, this._transformChunk(''));
+ }
+ /**
+ * Stops parsing. Useful if you want the parser to stop consuming CPU time
+ * once you've obtained the desired info from the input stream. Doesn't
+ * prevent piping, so that data will flow through the parser as usual.
+ *
+ * @example
+ *
+ * ```js
+ * const SAXParser = require('parse5-sax-parser');
+ * const http = require('http');
+ * const fs = require('fs');
+ *
+ * const file = fs.createWriteStream('google.com.html');
+ * const parser = new SAXParser();
+ *
+ * parser.on('doctype', ({ name, publicId, systemId }) => {
+ * // Process doctype info and stop parsing
+ * ...
+ * parser.stop();
+ * });
+ *
+ * http.get('http://google.com', res => {
+ * // Despite the fact that parser.stop() was called whole
+ * // content of the page will be written to the file
+ * res.pipe(parser).pipe(file);
+ * });
+ * ```
+ */
+ stop() {
+ this.stopped = true;
+ this.tokenizer.pause();
+ }
+ //Internals
+ _transformChunk(chunk) {
+ if (!this.stopped) {
+ this.tokenizer.write(chunk, this.lastChunkWritten);
+ }
+ return chunk;
+ }
+ /** @internal */
+ onCharacter({ chars, location }) {
+ if (this.pendingText === null) {
+ this.pendingText = { text: chars, sourceCodeLocation: location };
+ }
+ else {
+ this.pendingText.text += chars;
+ if (location && this.pendingText.sourceCodeLocation) {
+ const { endLine, endCol, endOffset } = location;
+ this.pendingText.sourceCodeLocation = {
+ ...this.pendingText.sourceCodeLocation,
+ endLine,
+ endCol,
+ endOffset,
+ };
+ }
+ }
+ if (this.tokenizer.preprocessor.willDropParsedChunk()) {
+ this._emitPendingText();
+ }
+ }
+ /** @internal */
+ onWhitespaceCharacter(token) {
+ this.onCharacter(token);
+ }
+ /** @internal */
+ onNullCharacter(token) {
+ this.onCharacter(token);
+ }
+ /** @internal */
+ onEof() {
+ this._emitPendingText();
+ this.stopped = true;
+ }
+ /** @internal */
+ onStartTag(token) {
+ this._emitPendingText();
+ const startTag = {
+ tagName: token.tagName,
+ attrs: token.attrs,
+ selfClosing: token.selfClosing,
+ sourceCodeLocation: token.location,
+ };
+ this.emitIfListenerExists('startTag', startTag);
+ }
+ /** @internal */
+ onEndTag(token) {
+ this._emitPendingText();
+ const endTag = {
+ tagName: token.tagName,
+ sourceCodeLocation: token.location,
+ };
+ this.emitIfListenerExists('endTag', endTag);
+ }
+ /** @internal */
+ onDoctype(token) {
+ this._emitPendingText();
+ const doctype = {
+ name: token.name,
+ publicId: token.publicId,
+ systemId: token.systemId,
+ sourceCodeLocation: token.location,
+ };
+ this.emitIfListenerExists('doctype', doctype);
+ }
+ /** @internal */
+ onComment(token) {
+ this._emitPendingText();
+ const comment = {
+ text: token.data,
+ sourceCodeLocation: token.location,
+ };
+ this.emitIfListenerExists('comment', comment);
+ }
+ emitIfListenerExists(eventName, token) {
+ if (this.listenerCount(eventName) === 0) {
+ return false;
+ }
+ this._emitToken(eventName, token);
+ return true;
+ }
+ _emitToken(eventName, token) {
+ this.emit(eventName, token);
+ }
+ _emitPendingText() {
+ if (this.pendingText !== null) {
+ this.emitIfListenerExists('text', this.pendingText);
+ this.pendingText = null;
+ }
+ }
+}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/parse5-html-rewriting-stream/dist/index.js
+
+
+
+/**
+ * Streaming [SAX](https://en.wikipedia.org/wiki/Simple_API_for_XML)-style HTML rewriter.
+ * A [transform stream](https://nodejs.org/api/stream.html#stream_class_stream_transform) (which means you can pipe _through_ it, see example).
+ *
+ * The rewriter uses the raw source representation of tokens if they are not modified by the user. Therefore, the resulting
+ * HTML is not affected by parser error-recovery mechanisms as in a classical parsing-serialization roundtrip.
+ *
+ * @example
+ *
+ * ```js
+ * const RewritingStream = require('parse5-html-rewriting-stream');
+ * const http = require('http');
+ * const fs = require('fs');
+ *
+ * const file = fs.createWriteStream('/home/google.com.html');
+ * const rewriter = new RewritingStream();
+ *
+ * // Replace divs with spans
+ * rewriter.on('startTag', startTag => {
+ * if (startTag.tagName === 'span') {
+ * startTag.tagName = 'div';
+ * }
+ *
+ * rewriter.emitStartTag(startTag);
+ * });
+ *
+ * rewriter.on('endTag', endTag => {
+ * if (endTag.tagName === 'span') {
+ * endTag.tagName = 'div';
+ * }
+ *
+ * rewriter.emitEndTag(endTag);
+ * });
+ *
+ * // Wrap all text nodes with an
tag
+ * rewriter.on('text', (_, raw) => {
+ * // Use the raw representation of text without HTML entities decoding
+ * rewriter.emitRaw(`${raw} `);
+ * });
+ *
+ * http.get('http://google.com', res => {
+ * // Assumes response is UTF-8.
+ * res.setEncoding('utf8');
+ * // `RewritingStream` is a `Transform` stream, which means you can pipe
+ * // through it.
+ * res.pipe(rewriter).pipe(file);
+ * });
+ * ```
+ */
+class RewritingStream extends SAXParser {
+ /** Note: `sourceCodeLocationInfo` is always enabled. */
+ constructor() {
+ super({ sourceCodeLocationInfo: true });
+ }
+ _transformChunk(chunk) {
+ // NOTE: ignore upstream return values as we want to push to
+ // the `Writable` part of the `Transform` stream ourselves.
+ super._transformChunk(chunk);
+ return '';
+ }
+ _getRawHtml(location) {
+ const { droppedBufferSize, html } = this.tokenizer.preprocessor;
+ const start = location.startOffset - droppedBufferSize;
+ const end = location.endOffset - droppedBufferSize;
+ return html.slice(start, end);
+ }
+ // Events
+ emitIfListenerExists(eventName, token) {
+ if (!super.emitIfListenerExists(eventName, token)) {
+ this.emitRaw(this._getRawHtml(token.sourceCodeLocation));
+ }
+ // NOTE: don't skip new lines after `` and other tags,
+ // otherwise we'll have incorrect raw data.
+ this.parserFeedbackSimulator.skipNextNewLine = false;
+ return true;
+ }
+ // Emitter API
+ _emitToken(eventName, token) {
+ this.emit(eventName, token, this._getRawHtml(token.sourceCodeLocation));
+ }
+ /** Emits a serialized document type token into the output stream. */
+ emitDoctype(token) {
+ let res = `';
+ this.push(res);
+ }
+ /** Emits a serialized start tag token into the output stream. */
+ emitStartTag(token) {
+ let res = `<${token.tagName}`;
+ for (const attr of token.attrs) {
+ res += ` ${attr.name}="${escape_escapeAttribute(attr.value)}"`;
+ }
+ res += token.selfClosing ? '/>' : '>';
+ this.push(res);
+ }
+ /** Emits a serialized end tag token into the output stream. */
+ emitEndTag(token) {
+ this.push(`${token.tagName}>`);
+ }
+ /** Emits a serialized text token into the output stream. */
+ emitText({ text }) {
+ this.push(!this.parserFeedbackSimulator.inForeignContent &&
+ html_hasUnescapedText(this.tokenizer.lastStartTagName, true)
+ ? text
+ : escape_escapeText(text));
+ }
+ /** Emits a serialized comment token into the output stream. */
+ emitComment(token) {
+ this.push(``);
+ }
+ /** Emits a raw HTML string into the output stream. */
+ emitRaw(html) {
+ this.push(html);
+ }
+}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./src/rewrite/html.js
+
+
+
+
+const html_encoder = new TextEncoder();
+const html_decoder = new TextDecoder();
+
+
+// ===========================================================================
+const META_REFRESH_REGEX = /([\d.]+\s*;\s*url\s*=\s*)(.+)(\s*)/mi;
+
+const DATA_RW_PROTOCOLS = ["http://", "https://", "//"];
+
+const defmod = "mp_";
+
+const MAX_HTML_REWRITE_SIZE = 5000000;
+
+const rewriteTags = {
+ "a": { "href": defmod },
+ "applet": {
+ "codebase": "oe_",
+ "archive": "oe_"
+ },
+ "area": { "href": defmod },
+ "audio": { "src": "oe_" },
+ "base": { "href": defmod },
+ "blockquote": { "cite": defmod },
+ "body": { "background": "im_" },
+ "button": { "formaction": defmod },
+ "command": { "icon": "im_" },
+ "del": { "cite": defmod },
+ "embed": { "src": "oe_" },
+ "iframe": { "src": "if_" },
+ "image": { "src": "im_", "xlink:href": "im_", "href": "im_" },
+ "img": {
+ "src": "im_",
+ "srcset": "im_"
+ },
+ "ins": { "cite": defmod },
+ "input": {
+ "src": "im_",
+ "formaction": defmod
+ },
+ "form": { "action": defmod },
+ "frame": { "src": "fr_" },
+ "link": { "href": "oe_" },
+ "meta": { "content": defmod },
+ "object": {
+ "codebase": "oe_",
+ "data": "oe_"
+ },
+ "param": { "value": "oe_" },
+ "q": { "cite": defmod },
+ "ref": { "href": "oe_" },
+ "script": { "src": "js_", "xlink:href": "js_" },
+ "source": { "src": "oe_", "srcset": "oe_" },
+ "video": {
+ "src": "oe_",
+ "poster": "im_"
+ },
+};
+
+const OBJECT_FLASH_DATA_RX = [{
+ "match": /youtube.com\/v\/([^&]+)[&]/,
+ "replace": "youtube.com/embed/$1?"
+}];
+
+
+const TEXT_NODE_REWRITE_RULES = [
+ {
+ urlMatch: /[?&]:loadOrderID=([\d]+)/,
+ match: /(loadOrderID&(quot;&)?#x[^;]+?;)([\d]+)/gi,
+ replace: "$1$U1"
+ }
+];
+
+
+// ===========================================================================
+class HTMLRewriter
+{
+ constructor(rewriter, isCharsetUTF8 = false) {
+ this.rewriter = rewriter;
+ this.rule = null;
+
+ for (const rule of TEXT_NODE_REWRITE_RULES) {
+ const m = this.rewriter.url.match(rule.urlMatch);
+ if (m) {
+ this.ruleMatch = m;
+ this.rule = rule;
+ break;
+ }
+ }
+
+ this.isCharsetUTF8 = isCharsetUTF8;
+ }
+
+ rewriteMetaContent(attrs, attr, rewriter) {
+ let equiv = this.getAttr(attrs, "http-equiv");
+ if (equiv) {
+ equiv = equiv.toLowerCase();
+ }
+
+ if (equiv === "content-security-policy") {
+ attr.name = "_" + attr.name;
+ } else if (equiv === "refresh") {
+ return attr.value.replace(META_REFRESH_REGEX, (m, p1, p2, p3) => p1 + this.rewriteUrl(rewriter, p2) + p3);
+ } else if (this.getAttr(attrs, "name") === "referrer") {
+ return "no-referrer-when-downgrade";
+ } else if (startsWithAny(attr.value, DATA_RW_PROTOCOLS)) {
+ return this.rewriteUrl(rewriter, attr.value);
+ }
+
+ return attr.value;
+ }
+
+ rewriteSrcSet(value, rewriter) {
+ const SRCSET_REGEX = /\s*(\S*\s+[\d.]+[wx]),|(?:\s*,(?:\s+|(?=https?:)))/;
+
+ let rv = [];
+
+ for (let v of value.split(SRCSET_REGEX)) {
+ if (v) {
+ const parts = v.trim().split(" ");
+ parts[0] = this.rewriteUrl(rewriter, parts[0]);
+ rv.push(parts.join(" "));
+ }
+ }
+
+ return rv.join(", ");
+ }
+
+ rewriteTagAndAttrs(tag, attrRules, rewriter) {
+ const isUrl = (val) => { return startsWithAny(val, DATA_RW_PROTOCOLS); };
+ const tagName = tag.tagName;
+
+ for (let attr of tag.attrs) {
+ const name = attr.name;
+ const value = attr.value;
+
+ // js attrs
+ if (name.startsWith("on") && value.startsWith("javascript:") && name.slice(2, 3) != "-") {
+ attr.value = "javascript:" + rewriter.rewriteJS(value.slice("javascript:".length), {inline: true});
+ }
+ // css attrs
+ else if (name === "style") {
+ attr.value = rewriter.rewriteCSS(attr.value);
+ }
+
+ // background attr
+ else if (name === "background") {
+ attr.value = this.rewriteUrl(rewriter, value);
+ }
+
+ else if (name === "srcset" || (name === "imagesrcset" && tagName === "link")) {
+ attr.value = this.rewriteSrcSet(value, rewriter);
+ }
+
+ // for now, download attribute doesn't work in Chrome
+ // but disabling triggers default behavior which often does
+ else if (name === "crossorigin" || name === "integrity" || name === "download") {
+ attr.name = "_" + attr.name;
+ }
+
+ else if (tagName === "meta" && name === "content") {
+ attr.value = this.rewriteMetaContent(tag.attrs, attr, rewriter);
+ }
+
+ else if (tagName === "param" && isUrl(value)) {
+ attr.value = this.rewriteUrl(rewriter, attr.value);
+ }
+
+ else if (name.startsWith("data-") && isUrl(value)) {
+ attr.value = this.rewriteUrl(rewriter, attr.value);
+ }
+
+ else if (tagName === "base" && name === "href") {
+ try {
+ // rewrite url, keeping relativeness intact
+ attr.value = this.rewriter.updateBaseUrl(attr.value);
+ } catch (e) {
+ console.warn("Invalid : " + attr.value);
+ }
+ }
+
+ else if (tagName === "script" && name === "src") {
+ const rwType = this.getScriptRWType(tag);
+ const mod = (rwType === "module") ? "esm_" : null;
+ const newValue = this.rewriteUrl(rewriter, attr.value, false, mod);
+ if (newValue === attr.value) {// && this.isRewritableUrl(newValue)) {
+ tag.attrs.push({"name": "__wb_orig_src", "value": attr.value});
+ attr.value = this.rewriteUrl(rewriter, attr.value, true, mod);
+ } else {
+ attr.value = newValue;
+ }
+ }
+
+ else if (tagName === "object" && name === "data") {
+ const type = this.getAttr(tag.attrs, "type");
+
+ // convert object tag to iframe
+ if (type === "application/pdf") {
+ attr.name = "src";
+ tag.tagName = "iframe";
+ } else if (type === "application/x-shockwave-flash") {
+ for (const rule of OBJECT_FLASH_DATA_RX) {
+ const value = attr.value.replace(rule.match, rule.replace);
+ if (value !== attr.value) {
+ attr.name = "src";
+ attr.value = this.rewriteUrl(rewriter, value);
+ tag.tagName = "iframe";
+ break;
+ }
+ }
+ }
+ }
+
+ else if (name === "target") {
+ const target = attr.value;
+
+ if (target === "_blank" || target === "_parent" || target === "_top" || target === "new") {
+ attr.value = REPLAY_TOP_FRAME_NAME;
+ }
+ }
+
+ else if (name === "href" || name === "src") {
+ attr.value = this.rewriteUrl(rewriter, attr.value);
+ }
+
+ else {
+ if (attrRules[attr.name]) {
+ attr.value = this.rewriteUrl(rewriter, attr.value);
+ }
+ }
+ }
+ }
+
+ getAttr(attrs, name) {
+ for (let attr of attrs) {
+ if (attr.name === name) {
+ return attr.value;
+ }
+ }
+
+ return null;
+ }
+
+ getScriptRWType(tag) {
+ const scriptType = this.getAttr(tag.attrs, "type");
+
+ if (scriptType === "module") {
+ return "module";
+ } else if (scriptType === "application/json") {
+ return "json";
+ } else if (!scriptType || (scriptType.indexOf("javascript") >= 0 || scriptType.indexOf("ecmascript") >= 0)) {
+ return "js";
+ } else {
+ return "";
+ }
+ }
+
+ async rewrite(response) {
+ if (!response.buffer && !response.reader) {
+ //console.warn("Missing response body for: " + response.url);
+ return response;
+ }
+
+ if (response.expectedLength() > MAX_HTML_REWRITE_SIZE) {
+ console.warn("Skipping rewriting, HTML file too big: " + response.expectedLength());
+ return response;
+ }
+
+ const rewriter = this.rewriter;
+
+ const rwStream = new RewritingStream();
+ rwStream.tokenizer.preprocessor.bufferWaterline = Infinity;
+
+ let insertAdded = false;
+
+ let context = "";
+ let scriptRw = "";
+ let replaceTag = null;
+
+ const addInsert = () => {
+ if (!insertAdded && rewriter.headInsertFunc) {
+ const headInsert = rewriter.headInsertFunc(rewriter.url);
+ if (headInsert) {
+ rwStream.emitRaw(headInsert);
+ }
+ insertAdded = true;
+ }
+ };
+
+ rwStream.on("startTag", startTag => {
+
+ const tagRules = rewriteTags[startTag.tagName];
+
+ const original = startTag.tagName;
+
+ this.rewriteTagAndAttrs(startTag, tagRules || {}, rewriter);
+
+ if (!insertAdded && !["head", "html"].includes(startTag.tagName)) {
+ addInsert();
+ }
+
+ rwStream.emitStartTag(startTag);
+
+ switch (startTag.tagName) {
+ case "script": {
+ if (startTag.selfClosing) {
+ break;
+ }
+
+ context = startTag.tagName;
+ scriptRw = this.getScriptRWType(startTag);
+ break;
+ }
+
+ case "style":
+ if (!startTag.selfClosing) {
+ context = startTag.tagName;
+ }
+ break;
+
+ case "head":
+ addInsert();
+ break;
+ }
+
+ if (startTag.tagName !== original) {
+ context = original;
+ replaceTag = startTag.tagName;
+ }
+ });
+
+ rwStream.on("endTag", endTag => {
+ if (endTag.tagName === context) {
+ if (replaceTag) {
+ endTag.tagName = replaceTag;
+ replaceTag = null;
+ }
+ context = "";
+ }
+ rwStream.emitEndTag(endTag);
+ });
+
+ rwStream.on("text", (textToken, raw) => {
+ const text = (() => {
+ if (context === "script") {
+ const prefix = rewriter.prefix;
+ const isModule = scriptRw === "module";
+
+ if (scriptRw === "js" || isModule) {
+ return rewriter.rewriteJS(textToken.text, {isModule, prefix});
+ } else if (scriptRw === "json") {
+ return rewriter.rewriteJSON(textToken.text, {prefix});
+ } else {
+ return textToken.text;
+ }
+ } else if (context === "style") {
+ return rewriter.rewriteCSS(textToken.text);
+ } else {
+ return this.rewriteHTMLText(raw);
+ }
+ })();
+
+ for (let i = 0; i < text.length; i += MAX_STREAM_CHUNK_SIZE) {
+ rwStream.emitRaw(text.slice(i, i + MAX_STREAM_CHUNK_SIZE));
+ }
+ });
+
+ const sourceGen = response.createIter();
+ let hasData = false;
+
+ const isCharsetUTF8 = this.isCharsetUTF8;
+
+ response.setReader(new ReadableStream({
+ async start(controller) {
+ rwStream.on("data", (text) => {
+ controller.enqueue(isCharsetUTF8 ? html_encoder.encode(text) : encodeLatin1(text));
+ });
+
+ rwStream.on("end", () => {
+ controller.close();
+ });
+
+ for await (const chunk of sourceGen) {
+ if (isCharsetUTF8) {
+ rwStream.write(html_decoder.decode(chunk), "utf8");
+ } else {
+ rwStream.write(decodeLatin1(chunk), "latin1");
+ }
+ hasData = true;
+ }
+ if (hasData) {
+ addInsert();
+ }
+
+ rwStream.end();
+ },
+ }));
+
+ return response;
+ }
+
+ rewriteUrl(rewriter, text, forceAbs = false, mod = null) {
+ // if html charset not utf-8, just convert the url to utf-8 for rewriting
+ if (!this.isCharsetUTF8) {
+ text = html_decoder.decode(encodeLatin1(text));
+ }
+ const res = rewriter.rewriteUrl(text, forceAbs);
+ return mod ? res.replace("mp_/", mod + "/") : res;
+ }
+
+ rewriteHTMLText(text) {
+ if (this.rule) {
+ // todo: make more general if additional rules needed
+ // for now, just replace the first match
+ const replacer = this.rule.replace.replace("$U1", this.ruleMatch[1]);
+ const newText = text.replace(this.rule.match, replacer);
+ if (text !== newText) {
+ return newText;
+ }
+ }
+ return text;
+ }
+}
+
+
+
+
+;// CONCATENATED MODULE: ./src/rewrite/index.js
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+// ===========================================================================
+const STYLE_REGEX = /(url\s*\(\s*[\\"']*)([^)'"]+)([\\"']*\s*\))/gi;
+
+const IMPORT_REGEX = /(@import\s*[\\"']*)([^)'";]+)([\\"']*\s*;?)/gi;
+
+const NO_WOMBAT_REGEX = /WB_wombat_/g;
+
+//const JSONP_REGEX = /^(?:[ \t]*(?:(?:\/\*[^\*]*\*\/)|(?:\/\/[^\n]+[\n])))*[ \t]*(\w+)\(\{/m;
+const JSONP_REGEX = /^(?:\s*(?:(?:\/\*[^*]*\*\/)|(?:\/\/[^\n]+[\n])))*\s*([\w.]+)\([{[]/;
+
+const JSONP_CALLBACK_REGEX = /[?].*(?:callback|jsonp)=([^&]+)/i;
+
+// JS Rewriters
+const jsRules = new DomainSpecificRuleSet(JSRewriter);
+const baseRules = new DomainSpecificRuleSet(RxRewriter);
+
+
+// ===========================================================================
+class Rewriter {
+ constructor({baseUrl, prefix, responseUrl, workerInsertFunc, headInsertFunc = null,
+ urlRewrite = true, contentRewrite = true, decode = true, useBaseRules = false} = {}) {
+ this.urlRewrite = urlRewrite;
+ this.contentRewrite = contentRewrite;
+ this.dsRules = urlRewrite && !useBaseRules ? jsRules : baseRules;
+ this.decode = decode;
+
+ this.prefix = prefix || "";
+ if (this.prefix && urlRewrite) {
+ const parsed = new URL(this.prefix);
+ this.relPrefix = parsed.pathname;
+ this.schemeRelPrefix = this.prefix.slice(parsed.protocol.length);
+ }
+
+ // response url always has a scheme, should be specified if baseUrl may not..
+ const parsed = new URL(responseUrl || baseUrl);
+ this.scheme = parsed.protocol;
+
+ if (baseUrl.startsWith("//")) {
+ baseUrl = this.scheme + baseUrl;
+ }
+
+ this.url = this.baseUrl = baseUrl;
+
+ this.headInsertFunc = headInsertFunc;
+ this.workerInsertFunc = workerInsertFunc;
+ this.responseUrl = responseUrl;
+ this.isCharsetUTF8 = false;
+
+ this._jsonpCallback = null;
+ }
+
+ getRewriteMode(request, response, url = "", mime = null) {
+ if (!mime && response) {
+ mime = response.headers.get("Content-Type") || "";
+ const parts = mime.split(";");
+ mime = parts[0];
+ if (parts.length > 1) {
+ this.isCharsetUTF8 = parts[1].trim().toLowerCase().replace("charset=", "").replace("-", "") === "utf8";
+ }
+ }
+
+ if (request) {
+ switch (request.destination) {
+ case "style":
+ return "css";
+
+ case "script":
+ return this.getScriptRewriteMode(mime, url, "js");
+
+ case "worker":
+ return "js-worker";
+ }
+ }
+
+ switch (mime) {
+ case "text/html":
+ if (!request.destination && request.headers.get("Accept") === "application/json") {
+ return "json";
+ }
+ return "html";
+
+ case "text/css":
+ return "css";
+
+ case "application/x-mpegURL":
+ case "application/vnd.apple.mpegurl":
+ return "hls";
+
+ case "application/dash+xml":
+ return "dash";
+
+ default:
+ return this.getScriptRewriteMode(mime, url, null);
+ }
+ }
+
+ getScriptRewriteMode(mime, url, defaultType) {
+ switch (mime) {
+ case "text/javascript":
+ case "application/javascript":
+ case "application/x-javascript":
+ if (this.parseJSONPCallback(url)) {
+ return "jsonp";
+ }
+ return url.endsWith(".json") ? "json" : "js";
+
+ case "application/json":
+ return "json";
+
+ default:
+ return defaultType;
+ }
+ }
+
+ async rewrite(response, request) {
+ const rewriteMode = this.contentRewrite ? this.getRewriteMode(request, response, this.baseUrl) : null;
+
+ const isAjax = isAjaxRequest(request);
+
+ const urlRewrite = this.urlRewrite && !isAjax;
+
+ const headers = this.rewriteHeaders(response.headers, this.urlRewrite, !!rewriteMode, isAjax);
+
+ const encoding = response.headers.get("content-encoding");
+ const te = response.headers.get("transfer-encoding");
+
+ response.headers = headers;
+
+ // attempt to decode only if set
+ // eg. data may already be decoded for many stores
+ if (this.decode && (encoding || te)) {
+ response = await decodeResponse(response, encoding, te, rewriteMode === null);
+ }
+
+ const opts = {
+ response,
+ prefix: this.prefix,
+ baseUrl: this.baseUrl,
+ };
+
+ let rwFunc = null;
+
+ switch (rewriteMode) {
+ case "html":
+ if (urlRewrite) {
+ return await this.rewriteHtml(response);
+ }
+ break;
+
+ case "css":
+ if (this.urlRewrite) {
+ rwFunc = this.rewriteCSS;
+ }
+ break;
+
+ case "js":
+ rwFunc = this.rewriteJS;
+ if (request.mod === "esm_") {
+ opts.isModule = true;
+ }
+ break;
+
+ case "json":
+ rwFunc = this.rewriteJSON;
+ break;
+
+ case "js-worker":
+ rwFunc = this.workerInsertFunc;
+ break;
+
+ case "jsonp":
+ rwFunc = this.rewriteJSONP;
+ break;
+
+ case "hls":
+ rwFunc = rewriteHLS;
+ break;
+
+ case "dash":
+ rwFunc = rewriteDASH;
+ break;
+ }
+
+ if (urlRewrite) {
+ opts.rewriteUrl = url => this.rewriteUrl(url);
+ }
+
+ if (rwFunc) {
+ let text = await response.getText(this.isCharsetUTF8);
+ text = rwFunc.call(this, text, opts);
+ response.setText(text, this.isCharsetUTF8);
+ }
+
+ return response;
+ }
+
+ updateBaseUrl(url) {
+ // set internal base to full url
+ this.baseUrl = new URL(url, this.baseUrl).href;
+
+ // not an absolute url, ensure it has slash
+ if (url && this.baseUrl != url) {
+ try {
+ url = new URL(url).href;
+ } catch (e) {
+ if (url.startsWith("//")) {
+ url = new URL("https:" + url).href;
+ url = url.slice("https:".length);
+ }
+ }
+ }
+
+ // return rewritten base url, but keeping scheme-relativeness
+ return this.rewriteUrl(url);
+ }
+
+ isRewritableUrl(url) {
+ const NO_REWRITE_URI_PREFIX = ["#", "javascript:", "data:", "mailto:", "about:", "file:", "blob:", "{"];
+
+ for (let prefix of NO_REWRITE_URI_PREFIX) {
+ if (url.startsWith(prefix)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ rewriteUrl(url, forceAbs = false) {
+ if (!this.urlRewrite) {
+ return url;
+ }
+
+ var origUrl = url;
+
+ url = url.trim();
+
+ if (!url || !this.isRewritableUrl(url) || url.startsWith(this.prefix) || url.startsWith(this.relPrefix)) {
+ return origUrl;
+ }
+
+ if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("https\\3a/")) {
+ return this.prefix + url;
+ }
+
+ if (url.startsWith("//") || url.startsWith("\\/\\/")) {
+ return this.schemeRelPrefix + url;
+ }
+
+ if (url.startsWith("/")) {
+ url = new URL(url, this.baseUrl).href;
+ return this.relPrefix + url;
+ } else if (forceAbs || url.indexOf("../") >= 0) {
+ url = new URL(url, this.baseUrl).href;
+ return this.prefix + url;
+ } else {
+ return origUrl;
+ }
+ }
+
+ // HTML
+ rewriteHtml(response) {
+ const htmlRW = new HTMLRewriter(this, this.isCharsetUTF8);
+ return htmlRW.rewrite(response);
+ }
+
+ // CSS
+ rewriteCSS(text) {
+ const rewriter = this;
+
+ function cssStyleReplacer(match, n1, n2, n3) {
+ n2 = n2.trim();
+ return n1 + rewriter.rewriteUrl(n2) + n3;
+ }
+
+ return text
+ .replace(STYLE_REGEX, cssStyleReplacer)
+ .replace(IMPORT_REGEX, cssStyleReplacer)
+ .replace(NO_WOMBAT_REGEX, "");
+ }
+
+ // JS
+ rewriteJS(text, opts) {
+ const noUrlProxyRewrite = opts && !opts.rewriteUrl && opts.isModule === undefined;
+ const dsRules = noUrlProxyRewrite ? baseRules : this.dsRules;
+ const dsRewriter = dsRules.getRewriter(this.baseUrl);
+
+
+ // optimize: if default rewriter and not rewriting urls, skip
+ if (dsRewriter === dsRules.defaultRewriter && noUrlProxyRewrite) {
+ return text;
+ }
+
+ return dsRewriter.rewrite(text, opts);
+ }
+
+ // JSON
+ rewriteJSON(text, opts) {
+ text = this.rewriteJSONP(text);
+
+ const dsRewriter = baseRules.getRewriter(this.baseUrl);
+
+ if (dsRewriter !== baseRules.defaultRewriter) {
+ return dsRewriter.rewrite(text, opts);
+ }
+
+ return text;
+ }
+
+ parseJSONPCallback(url) {
+ const callback = url.match(JSONP_CALLBACK_REGEX);
+ if (!callback || callback[1] === "?") {
+ this._jsonpCallback = false;
+ return false;
+ }
+
+ this._jsonpCallback = callback[1];
+ return true;
+ }
+
+ // JSONP
+ rewriteJSONP(text) {
+ const jsonM = text.match(JSONP_REGEX);
+ if (!jsonM) {
+ return text;
+ }
+
+ // if null, hasn't been parsed yet
+ if (this._jsonpCallback === null) {
+ this.parseJSONPCallback(this.baseUrl);
+ }
+
+ if (this._jsonpCallback === false) {
+ return text;
+ }
+
+ return this._jsonpCallback + text.slice(text.indexOf(jsonM[1]) + jsonM[1].length);
+ }
+
+ //Headers
+ rewriteHeaders(headers, urlRewrite, contentRewrite, isAjax) {
+ const headerRules = {
+ "access-control-allow-origin": "prefix-if-url-rewrite",
+ "access-control-allow-credentials": "prefix-if-url-rewrite",
+ "access-control-expose-headers": "prefix-if-url-rewrite",
+ "access-control-max-age": "prefix-if-url-rewrite",
+ "access-control-allow-methods": "prefix-if-url-rewrite",
+ "access-control-allow-headers": "prefix-if-url-rewrite",
+
+ "accept-patch": "keep",
+ "accept-ranges": "keep",
+
+ "age": "prefix",
+
+ "allow": "keep",
+
+ "alt-svc": "prefix",
+ "cache-control": "prefix",
+
+ "connection": "prefix",
+
+ "content-base": "url-rewrite",
+ "content-disposition": "keep",
+ "content-encoding": "prefix-if-content-rewrite",
+ "content-language": "keep",
+ "content-length": "content-length",
+ "content-location": "url-rewrite",
+ "content-md5": "prefix",
+ "content-range": "keep",
+ "content-security-policy": "prefix",
+ "content-security-policy-report-only": "prefix",
+ "content-type": "keep",
+
+ "date": "keep",
+
+ "etag": "prefix",
+ "expires": "prefix",
+
+ "last-modified": "prefix",
+ "link": "link",
+ "location": "url-rewrite",
+
+ "p3p": "prefix",
+ "pragma": "prefix",
+
+ "proxy-authenticate": "keep",
+
+ "public-key-pins": "prefix",
+ "retry-after": "prefix",
+ "server": "prefix",
+
+ "set-cookie": "cookie",
+
+ "status": "prefix",
+
+ "strict-transport-security": "prefix",
+
+ "trailer": "prefix",
+ "transfer-encoding": "transfer-encoding",
+ "tk": "prefix",
+
+ "upgrade": "prefix",
+ "upgrade-insecure-requests": "prefix",
+
+ "vary": "prefix",
+
+ "via": "prefix",
+
+ "warning": "prefix",
+
+ "www-authenticate": "keep",
+
+ "x-frame-options": "prefix",
+ "x-xss-protection": "prefix",
+ };
+
+ const headerPrefix = "X-Archive-Orig-";
+
+ let new_headers = new Headers();
+
+ for (let header of headers.entries()) {
+ const rule = headerRules[header[0]];
+ switch (rule) {
+ case "keep":
+ new_headers.append(header[0], header[1]);
+ break;
+
+ case "url-rewrite":
+ if (urlRewrite) {
+
+ // if location and redirect just to change scheme of the responseUrl
+ if (header[0] === "location" && this.url !== this.responseUrl) {
+ const otherScheme = (this.scheme === "http:" ? "https:" : "http:");
+ const responseUrlOtherScheme = otherScheme + this.responseUrl.slice(this.scheme.length);
+ if (header[1] === responseUrlOtherScheme) {
+ header[1] = otherScheme + this.url.slice(this.url.indexOf("//"));
+ }
+ }
+
+ new_headers.append(header[0], this.rewriteUrl(header[1]));
+ } else {
+ new_headers.append(header[0], header[1]);
+ }
+ break;
+
+ case "prefix-if-content-rewrite":
+ if (contentRewrite) {
+ new_headers.append(headerPrefix + header[0], header[1]);
+ } else {
+ new_headers.append(header[0], header[1]);
+ }
+ break;
+
+ case "prefix-if-url-rewrite":
+ if (urlRewrite) {
+ new_headers.append(headerPrefix + header[0], header[1]);
+ } else {
+ new_headers.append(header[0], header[1]);
+ }
+ break;
+
+ case "content-length":
+ if (header[1] == "0") {
+ new_headers.append(header[0], header[1]);
+ continue;
+ }
+
+ if (contentRewrite) {
+ try {
+ if (parseInt(header[1]) >= 0) {
+ new_headers.append(header[0], header[1]);
+ continue;
+ }
+ } catch (e) {
+ // ignore if content-length is not parsable as number
+ }
+ }
+
+ new_headers.append(header[0], header[1]);
+ break;
+
+ case "transfer-encoding":
+ //todo: mark as needing decoding?
+ new_headers.append(headerPrefix + header[0], header[1]);
+ break;
+
+ case "prefix":
+ new_headers.append(headerPrefix + header[0], header[1]);
+ break;
+
+ case "cookie":
+ //todo
+ new_headers.append(header[0], header[1]);
+ break;
+
+ case "link":
+ if (urlRewrite && !isAjax) {
+ new_headers.append(header[0], this.rewriteLinkHeader(header[1]));
+ } else {
+ new_headers.append(header[0], header[1]);
+ }
+ break;
+
+ default:
+ new_headers.append(header[0], header[1]);
+ }
+ }
+
+ return new_headers;
+ }
+
+ rewriteLinkHeader(value) {
+ try {
+ const parsed = lib_link.parse(value);
+
+ for (const entry of parsed.refs) {
+ if (entry.uri) {
+ entry.uri = this.rewriteUrl(entry.uri);
+ }
+ }
+
+ return parsed.toString();
+ } catch (e) {
+ console.warn("Error parsing link header: " + value);
+ return value;
+ }
+ }
+}
+
+
+
+
+;// CONCATENATED MODULE: ./src/collection.js
+
+
+
+
+
+
+const DEFAULT_CSP = "default-src 'unsafe-eval' 'unsafe-inline' 'self' data: blob: mediastream: ws: wss: ; form-action 'self'";
+
+
+// ===========================================================================
+class Collection {
+ constructor(opts, prefixes, defaultConfig = {}) {
+ const { name, store, config } = opts;
+
+ this.name = name;
+ this.store = store;
+ this.config = config;
+ this.metadata = this.config.metadata ? this.config.metadata : {};
+
+ const extraConfig = {...defaultConfig, ...this.config.extraConfig};
+
+ this.injectScripts = extraConfig.injectScripts || [];
+ this.noRewritePrefixes = extraConfig.noRewritePrefixes || null;
+
+ this.noPostToGet = !!extraConfig.noPostToGet;
+
+ this.convertPostToGet = !!extraConfig.convertPostToGet;
+
+ this.coHeaders = extraConfig.coHeaders || false;
+
+ this.csp = extraConfig.csp || DEFAULT_CSP;
+
+ this.injectRelCanon = extraConfig.injectRelCanon || false;
+
+ this.baseFramePrefix = extraConfig.baseUrlSourcePrefix;
+ this.baseFrameUrl = extraConfig.baseUrl;
+ this.baseFrameHashReplay = extraConfig.baseUrlHashReplay || false;
+
+ this.liveRedirectOnNotFound = extraConfig.liveRedirectOnNotFound || false;
+
+ this.rootPrefix = prefixes.root || prefixes.main;
+
+ this.prefix = prefixes.main;
+
+ // support root collection hashtag nav
+ if (this.config.root) {
+ this.isRoot = true;
+ } else {
+ this.prefix += this.name + "/";
+ this.isRoot = false;
+ }
+
+ this.staticPrefix = prefixes.static;
+ }
+
+ async handleRequest(request, event) {
+ // force timestamp for root coll
+ //if (!requestTS && this.isRoot) {
+ //requestTS = "2";
+ //}
+ let requestURL = request.url;
+ let requestTS = request.timestamp;
+
+ if (!request.mod) {
+ return await this.makeTopFrame(requestURL, requestTS);
+ }
+
+ if (!this.noPostToGet) {
+ requestURL = await request.convertPostToGet();
+ }
+
+ // exact or fuzzy match
+ let response = null;
+
+ let baseUrl = requestURL;
+
+ try {
+ if (requestURL.startsWith("srcdoc:")) {
+ response = this.getSrcDocResponse(requestURL, requestURL.slice("srcdoc:".length));
+ } else if (requestURL.startsWith("blob:")) {
+ // the form of this url is now blob:/
+ // split on / to separate and
+ const inx = requestURL.indexOf("/");
+ // blob url = blob:/
+ // skip blob prefix also
+ const blobId = requestURL.slice(5, inx);
+ const blobUrl = `blob:${self.location.origin}/${blobId}`;
+ baseUrl = requestURL.slice(inx + 1);
+ response = await this.getBlobResponse(blobUrl);
+ } else if (requestURL === "about:blank") {
+ response = await this.getSrcDocResponse(requestURL);
+ } else if (requestURL === "__wb_module_decl.js") {
+ response = await this.getWrappedModuleDecl(requestURL);
+ } else {
+ response = await this.getReplayResponse(request, event);
+ requestURL = request.url;
+ if (response && response.updateTS) {
+ requestTS = response.updateTS;
+ }
+ }
+ } catch (e) {
+ if (await handleAuthNeeded(e, this.config)) {
+ return notFound(request, "Please wait, this page will reload after authentication...
", 401);
+ }
+ }
+
+ if (!response) {
+ try {
+ requestURL = decodeURIComponent(requestURL);
+ requestURL += request.hash;
+ } catch(e) {
+ // ignore invalid URL
+ }
+
+ const msg = `
+
+
+ Archived Page Not Found
+ Sorry, this page was not found in this archive:
+ ${requestURL}
+ ${this.liveRedirectOnNotFound && request.mode === "navigate" ? `
+ Redirecting to live page now... (If this URL is a file download, the download should have started).
+
+ ` : `
+ `}
+
+ Click Here to try to load the live page in a new tab (or to download the URL as a file).
+
+
+ `;
+ return notFound(request, msg);
+ } else if (response instanceof Response) {
+ // custom Response, not an ArchiveResponse, just return
+ return response;
+ }
+
+ if (!response.noRW) {
+ const basePrefix = this.prefix + (request.pageId ? `:${request.pageId}/` : "");
+ const basePrefixTS = basePrefix + requestTS;
+
+ const headInsertFunc = (url) => {
+ let presetCookie = response.headers.get("x-wabac-preset-cookie") || "";
+ const setCookie = response.headers.get("Set-Cookie");
+ const topUrl = basePrefixTS + (requestTS ? "/" : "") + url;
+ return this.makeHeadInsert(url, requestTS, response.date, topUrl, basePrefix, presetCookie, setCookie, response.isLive, request.referrer, response.extraOpts);
+ };
+
+ const workerInsertFunc = (text) => {
+ return `
+ (function() { self.importScripts('${this.staticPrefix}wombatWorkers.js');\
+ new WBWombat({'prefix': '${basePrefixTS}/', 'prefixMod': '${basePrefixTS}wkrf_/', 'originalURL': '${requestURL}'});\
+ })();` + text;
+ };
+
+ const mod = request.mod;
+
+ const noRewrite = mod === "id_" || mod === "wkrf_";
+
+ const prefix = basePrefixTS + mod + "/";
+
+ const rewriteOpts = {
+ baseUrl,
+ responseUrl: response.url,
+ prefix,
+ headInsertFunc,
+ workerInsertFunc,
+ urlRewrite: !noRewrite,
+ contentRewrite: !noRewrite,
+ decode: this.config.decode
+ };
+
+ const rewriter = new Rewriter(rewriteOpts);
+
+ response = await rewriter.rewrite(response, request);
+
+ if (mod !== "id_") {
+ response.headers.append("Content-Security-Policy", this.csp);
+ }
+ }
+
+ const range = request.headers.get("range");
+
+ if (range && (response.status === 200 || response.status === 206)) {
+ response.setRange(range);
+ }
+
+ return response.makeResponse(this.coHeaders);
+ }
+
+ getCanonRedirect(query) {
+ let {url, timestamp, mod, referrer} = query;
+ const schemeRel = url.startsWith("//");
+
+ if (schemeRel) {
+ let scheme = (referrer && referrer.indexOf("/http://") > 0) ? "http:" : "https:";
+ url = scheme + url;
+ }
+
+ try {
+ const parsed = new URL(url);
+ if (parsed.href !== url) {
+ if (parsed.pathname === "/") {
+ let redirectUrl = this.prefix + timestamp + mod;
+ if (timestamp || mod) {
+ redirectUrl += "/";
+ }
+ redirectUrl += parsed.href;
+ return Response.redirect(redirectUrl, 301);
+ // if different due to canonical URL included, just update the URL
+ } else if (!schemeRel && url.indexOf(":443") || url.indexOf(":80")) {
+ query.url = parsed.href;
+ }
+ }
+ } catch (e) {
+ // ignore invalid URLs, no redirect
+ }
+
+ return null;
+ }
+
+ getWrappedModuleDecl() {
+ const string = `
+ var wrapObj = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
+ if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
+
+ const window = wrapObj("window");
+ const document = wrapObj("document");
+ const location = wrapObj("location");
+ const top = wrapObj("top");
+ const parent = wrapObj("parent");
+ const frames = wrapObj("frames");
+ const opener = wrapObj("opener");
+ const __self = wrapObj("self");
+ const __globalThis = wrapObj("globalThis");
+
+ export { window, document, location, top, parent, frames, opener, __self as self, __globalThis as globalThis };
+ `;
+
+ const payload = new TextEncoder().encode(string);
+
+ const status = 200;
+ const statusText = "OK";
+ const headers = new Headers({"Content-Type": "application/javascript"});
+ return new Response(payload, {headers, status, statusText});
+ }
+
+ getSrcDocResponse(url, base64str) {
+ const string = base64str ? decodeURIComponent(atob(base64str)) : "";
+ const payload = new TextEncoder().encode(string);
+
+ const status = 200;
+ const statusText = "OK";
+ const headers = new Headers({"Content-Type": "text/html"});
+ const date = new Date();
+ return new ArchiveResponse({payload, status, statusText, headers, url, date});
+ }
+
+ async getBlobResponse(url) {
+ const resp = await fetch(url);
+
+ const status = resp.status;
+ const statusText = resp.statusText;
+ const headers = new Headers(resp.headers);
+ if (headers.get("content-type") === "application/xhtml+xml") {
+ headers.set("content-type", "text/html");
+ }
+ const date = new Date();
+ const payload = new Uint8Array(await resp.arrayBuffer());
+
+ return new ArchiveResponse({payload, status, statusText, headers, url, date});
+ }
+
+ async getReplayResponse(query, event) {
+ let response = this.getCanonRedirect(query);
+
+ if (response) {
+ return response;
+ }
+
+ const opts = {pageId: query.pageId};
+
+ response = await this.store.getResource(query, this.prefix, event, opts);
+
+ const {request, url} = query;
+
+ // necessary as service worker seem to not be allowed to return a redirect in some circumstances (eg. in extension)
+ if ((request.destination === "video" || request.destination === "audio") && request.mode !== "navigate") {
+ while (response && (response.status >= 301 && response.status < 400)) {
+ const newUrl = new URL(response.headers.get("location"), url);
+ query.url = newUrl.href;
+ console.log(`resolve redirect ${url} -> ${query.url}`);
+ response = await this.store.getResource(query, this.prefix, event, opts);
+ }
+ }
+
+ return response;
+ }
+
+ async makeTopFrame(url, requestTS) {
+ let baseUrl = null;
+
+ if (this.baseFrameUrl && !this.baseFramePrefix) {
+ baseUrl = this.baseFrameUrl;
+ } else if (!this.isRoot && this.config.sourceUrl) {
+ baseUrl = this.baseFramePrefix || "./";
+ baseUrl += `?source=${this.config.sourceUrl}`;
+ }
+
+ if (baseUrl) {
+ if (this.baseFrameHashReplay) {
+ baseUrl += `#${requestTS}/${url}`;
+ } else {
+ const locParams = new URLSearchParams({url, ts: requestTS, view: "replay"});
+ baseUrl += "#" + locParams.toString();
+ }
+
+ return Response.redirect(baseUrl);
+ }
+
+ let content = null;
+
+ if (this.config.topTemplateUrl) {
+ /* Modded for kiwix-js so the app can work fully offline (avoids a network Fetch request) */
+ // const resp = await fetch(this.config.topTemplateUrl);
+ const cache = await caches.open(APP_CACHE);
+ let resp = await cache.match(this.config.topTemplateUrl);
+ if (!resp) {
+ resp = await fetch(this.config.topTemplateUrl);
+ }
+ const topTemplate = await resp.text();
+ content = topTemplate.replace("$URL", url).replace("$TS", requestTS).replace("$PREFIX", this.prefix);
+ } else {
+ content = `
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+`;
+ }
+
+ let responseData = {
+ "status": 200,
+ "statusText": "OK",
+ "headers": { "Content-Type": "text/html", "Content-Security-Policy": this.csp }
+ };
+
+ return new Response(content, responseData);
+ }
+
+ makeHeadInsert(url, requestTS, date, topUrl, prefix, presetCookie, setCookie, isLive, referrer, extraOpts) {
+ const coll = this.name;
+
+ const seconds = getSecondsStr(date);
+
+ const timestamp = getTS(date.toISOString());
+
+ const urlParsed = new URL(url);
+
+ let scheme;
+
+ // protocol scheme (for relative urls): if not http/https, try to get actual protocol from referrer
+ if (urlParsed.protocol !== "https:" && urlParsed.protocol !== "http:") {
+ scheme = (referrer && referrer.indexOf("/http://") > 0) ? "http" : "https";
+ } else {
+ scheme = urlParsed.protocol.slice(0, -1);
+ }
+
+ if (setCookie) {
+ presetCookie = parseSetCookie(setCookie, scheme) + ";" + presetCookie;
+ }
+
+ const pixelRatio = extraOpts && Number(extraOpts.pixelRatio) ? extraOpts.pixelRatio : 1;
+ const storage = extraOpts && extraOpts.storage ? btoa(extraOpts.storage) : "";
+ const presetCookieStr = presetCookie ? JSON.stringify(presetCookie) : "\"\"";
+ return `
+
+
+${this.injectRelCanon ? ` ` : ""}
+
+
+
+${this.injectScripts.map((script) => ``).join("")}
+ `;
+ }
+}
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/idb/build/wrap-idb-value.js
+const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
+
+let idbProxyableTypes;
+let cursorAdvanceMethods;
+// This is a function to prevent it throwing up in node environments.
+function getIdbProxyableTypes() {
+ return (idbProxyableTypes ||
+ (idbProxyableTypes = [
+ IDBDatabase,
+ IDBObjectStore,
+ IDBIndex,
+ IDBCursor,
+ IDBTransaction,
+ ]));
+}
+// This is a function to prevent it throwing up in node environments.
+function getCursorAdvanceMethods() {
+ return (cursorAdvanceMethods ||
+ (cursorAdvanceMethods = [
+ IDBCursor.prototype.advance,
+ IDBCursor.prototype.continue,
+ IDBCursor.prototype.continuePrimaryKey,
+ ]));
+}
+const cursorRequestMap = new WeakMap();
+const transactionDoneMap = new WeakMap();
+const transactionStoreNamesMap = new WeakMap();
+const transformCache = new WeakMap();
+const reverseTransformCache = new WeakMap();
+function promisifyRequest(request) {
+ const promise = new Promise((resolve, reject) => {
+ const unlisten = () => {
+ request.removeEventListener('success', success);
+ request.removeEventListener('error', error);
+ };
+ const success = () => {
+ resolve(wrap(request.result));
+ unlisten();
+ };
+ const error = () => {
+ reject(request.error);
+ unlisten();
+ };
+ request.addEventListener('success', success);
+ request.addEventListener('error', error);
+ });
+ promise
+ .then((value) => {
+ // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
+ // (see wrapFunction).
+ if (value instanceof IDBCursor) {
+ cursorRequestMap.set(value, request);
+ }
+ // Catching to avoid "Uncaught Promise exceptions"
+ })
+ .catch(() => { });
+ // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
+ // is because we create many promises from a single IDBRequest.
+ reverseTransformCache.set(promise, request);
+ return promise;
+}
+function cacheDonePromiseForTransaction(tx) {
+ // Early bail if we've already created a done promise for this transaction.
+ if (transactionDoneMap.has(tx))
+ return;
+ const done = new Promise((resolve, reject) => {
+ const unlisten = () => {
+ tx.removeEventListener('complete', complete);
+ tx.removeEventListener('error', error);
+ tx.removeEventListener('abort', error);
+ };
+ const complete = () => {
+ resolve();
+ unlisten();
+ };
+ const error = () => {
+ reject(tx.error || new DOMException('AbortError', 'AbortError'));
+ unlisten();
+ };
+ tx.addEventListener('complete', complete);
+ tx.addEventListener('error', error);
+ tx.addEventListener('abort', error);
+ });
+ // Cache it for later retrieval.
+ transactionDoneMap.set(tx, done);
+}
+let idbProxyTraps = {
+ get(target, prop, receiver) {
+ if (target instanceof IDBTransaction) {
+ // Special handling for transaction.done.
+ if (prop === 'done')
+ return transactionDoneMap.get(target);
+ // Polyfill for objectStoreNames because of Edge.
+ if (prop === 'objectStoreNames') {
+ return target.objectStoreNames || transactionStoreNamesMap.get(target);
+ }
+ // Make tx.store return the only store in the transaction, or undefined if there are many.
+ if (prop === 'store') {
+ return receiver.objectStoreNames[1]
+ ? undefined
+ : receiver.objectStore(receiver.objectStoreNames[0]);
+ }
+ }
+ // Else transform whatever we get back.
+ return wrap(target[prop]);
+ },
+ set(target, prop, value) {
+ target[prop] = value;
+ return true;
+ },
+ has(target, prop) {
+ if (target instanceof IDBTransaction &&
+ (prop === 'done' || prop === 'store')) {
+ return true;
+ }
+ return prop in target;
+ },
+};
+function replaceTraps(callback) {
+ idbProxyTraps = callback(idbProxyTraps);
+}
+function wrapFunction(func) {
+ // Due to expected object equality (which is enforced by the caching in `wrap`), we
+ // only create one new func per func.
+ // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
+ if (func === IDBDatabase.prototype.transaction &&
+ !('objectStoreNames' in IDBTransaction.prototype)) {
+ return function (storeNames, ...args) {
+ const tx = func.call(unwrap(this), storeNames, ...args);
+ transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
+ return wrap(tx);
+ };
+ }
+ // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
+ // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
+ // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
+ // with real promises, so each advance methods returns a new promise for the cursor object, or
+ // undefined if the end of the cursor has been reached.
+ if (getCursorAdvanceMethods().includes(func)) {
+ return function (...args) {
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
+ // the original object.
+ func.apply(unwrap(this), args);
+ return wrap(cursorRequestMap.get(this));
+ };
+ }
+ return function (...args) {
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
+ // the original object.
+ return wrap(func.apply(unwrap(this), args));
+ };
+}
+function transformCachableValue(value) {
+ if (typeof value === 'function')
+ return wrapFunction(value);
+ // This doesn't return, it just creates a 'done' promise for the transaction,
+ // which is later returned for transaction.done (see idbObjectHandler).
+ if (value instanceof IDBTransaction)
+ cacheDonePromiseForTransaction(value);
+ if (instanceOfAny(value, getIdbProxyableTypes()))
+ return new Proxy(value, idbProxyTraps);
+ // Return the same value back if we're not going to transform it.
+ return value;
+}
+function wrap(value) {
+ // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
+ // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
+ if (value instanceof IDBRequest)
+ return promisifyRequest(value);
+ // If we've already transformed this value before, reuse the transformed value.
+ // This is faster, but it also provides object equality.
+ if (transformCache.has(value))
+ return transformCache.get(value);
+ const newValue = transformCachableValue(value);
+ // Not all types are transformed.
+ // These may be primitive types, so they can't be WeakMap keys.
+ if (newValue !== value) {
+ transformCache.set(value, newValue);
+ reverseTransformCache.set(newValue, value);
+ }
+ return newValue;
+}
+const unwrap = (value) => reverseTransformCache.get(value);
+
+
+
+;// CONCATENATED MODULE: ./node_modules/idb/build/index.js
+
+
+
+/**
+ * Open a database.
+ *
+ * @param name Name of the database.
+ * @param version Schema version.
+ * @param callbacks Additional callbacks.
+ */
+function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
+ const request = indexedDB.open(name, version);
+ const openPromise = wrap(request);
+ if (upgrade) {
+ request.addEventListener('upgradeneeded', (event) => {
+ upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
+ });
+ }
+ if (blocked) {
+ request.addEventListener('blocked', (event) => blocked(
+ // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
+ event.oldVersion, event.newVersion, event));
+ }
+ openPromise
+ .then((db) => {
+ if (terminated)
+ db.addEventListener('close', () => terminated());
+ if (blocking) {
+ db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
+ }
+ })
+ .catch(() => { });
+ return openPromise;
+}
+/**
+ * Delete a database.
+ *
+ * @param name Name of the database.
+ */
+function deleteDB(name, { blocked } = {}) {
+ const request = indexedDB.deleteDatabase(name);
+ if (blocked) {
+ request.addEventListener('blocked', (event) => blocked(
+ // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
+ event.oldVersion, event));
+ }
+ return wrap(request).then(() => undefined);
+}
+
+const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
+const writeMethods = ['put', 'add', 'delete', 'clear'];
+const cachedMethods = new Map();
+function getMethod(target, prop) {
+ if (!(target instanceof IDBDatabase &&
+ !(prop in target) &&
+ typeof prop === 'string')) {
+ return;
+ }
+ if (cachedMethods.get(prop))
+ return cachedMethods.get(prop);
+ const targetFuncName = prop.replace(/FromIndex$/, '');
+ const useIndex = prop !== targetFuncName;
+ const isWrite = writeMethods.includes(targetFuncName);
+ if (
+ // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
+ !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
+ !(isWrite || readMethods.includes(targetFuncName))) {
+ return;
+ }
+ const method = async function (storeName, ...args) {
+ // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
+ const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
+ let target = tx.store;
+ if (useIndex)
+ target = target.index(args.shift());
+ // Must reject if op rejects.
+ // If it's a write operation, must reject if tx.done rejects.
+ // Must reject with op rejection first.
+ // Must resolve with op value.
+ // Must handle both promises (no unhandled rejections)
+ return (await Promise.all([
+ target[targetFuncName](...args),
+ isWrite && tx.done,
+ ]))[0];
+ };
+ cachedMethods.set(prop, method);
+ return method;
+}
+replaceTraps((oldTraps) => ({
+ ...oldTraps,
+ get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
+ has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),
+}));
+
+
+
+;// CONCATENATED MODULE: ./node_modules/idb/build/async-iterators.js
+
+
+const advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];
+const methodMap = {};
+const advanceResults = new WeakMap();
+const ittrProxiedCursorToOriginalProxy = new WeakMap();
+const cursorIteratorTraps = {
+ get(target, prop) {
+ if (!advanceMethodProps.includes(prop))
+ return target[prop];
+ let cachedFunc = methodMap[prop];
+ if (!cachedFunc) {
+ cachedFunc = methodMap[prop] = function (...args) {
+ advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));
+ };
+ }
+ return cachedFunc;
+ },
+};
+async function* iterate(...args) {
+ // tslint:disable-next-line:no-this-assignment
+ let cursor = this;
+ if (!(cursor instanceof IDBCursor)) {
+ cursor = await cursor.openCursor(...args);
+ }
+ if (!cursor)
+ return;
+ cursor = cursor;
+ const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);
+ ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);
+ // Map this double-proxy back to the original, so other cursor methods work.
+ reverseTransformCache.set(proxiedCursor, unwrap(cursor));
+ while (cursor) {
+ yield proxiedCursor;
+ // If one of the advancing methods was not called, call continue().
+ cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());
+ advanceResults.delete(proxiedCursor);
+ }
+}
+function isIteratorProp(target, prop) {
+ return ((prop === Symbol.asyncIterator &&
+ instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor])) ||
+ (prop === 'iterate' && instanceOfAny(target, [IDBIndex, IDBObjectStore])));
+}
+replaceTraps((oldTraps) => ({
+ ...oldTraps,
+ get(target, prop, receiver) {
+ if (isIteratorProp(target, prop))
+ return iterate;
+ return oldTraps.get(target, prop, receiver);
+ },
+ has(target, prop) {
+ return isIteratorProp(target, prop) || oldTraps.has(target, prop);
+ },
+}));
+
+;// CONCATENATED MODULE: ./node_modules/idb/with-async-ittr.js
+
+
+
+// EXTERNAL MODULE: ./node_modules/js-levenshtein/index.js
+var js_levenshtein = __webpack_require__(9991);
+;// CONCATENATED MODULE: ./src/fuzzymatcher.js
+
+
+
+function joinRx(rxStr) {
+ return new RegExp("[?&]" + rxStr.map(x => "(" + x + ")").join("|"), "gi");
+}
+
+const MAX_ARG_LEN = 1024;
+
+const SPLIT_BASE_RX = /\[\d]+/;
+
+const fuzzymatcher_DEFAULT_RULES =
+[
+ {
+ "match": /\/\/.*(?:gcs-vimeo|vod|vod-progressive)\.akamaized\.net.*?\/([\d/]+\.mp4)/,
+ "fuzzyCanonReplace": "//vimeo-cdn.fuzzy.replayweb.page/$1",
+ "split": ".net",
+ },
+ {
+ "match": /\/\/.*player.vimeo.com\/(video\/[\d]+)\?.*/i,
+ "fuzzyCanonReplace": "//vimeo.fuzzy.replayweb.page/$1"
+ },
+ {
+ "match": /www.\washingtonpost\.com\/wp-apps\/imrs.php/,
+ "args": [["src"]],
+ },
+ {
+ "match": /(static.wixstatic.com\/.*\.[\w]+\/v1\/fill\/)(w_.*)/,
+ "replace": "$1?_args=$2",
+ "split": "/v1/fill"
+ },
+ {
+ "match": /(twimg.com\/profile_images\/[^/]+\/[^_]+)_([\w]+\.[\w]+)/,
+ "replace": "$1=_args=$2",
+ "split": "_",
+ "splitLast": true
+ },
+ // YouTube
+ {
+ "match": /^https?:\/\/(?:www\.)?(youtube\.com\/embed\/[^?]+)[?].*/i,
+ "replace": "$1"
+ },
+ {
+ "match": /^(https?:\/\/(?:www\.)?)(youtube\.com\/@[^?]+)[?].*/i,
+ "fuzzyCanonReplace": "$1$2"
+ },
+ {
+ "match": /\/\/(?:www\.)?youtube(?:-nocookie)?\.com\/(get_video_info)/i,
+ "fuzzyCanonReplace": "//youtube.fuzzy.replayweb.page/$1",
+ "args": [["video_id"]],
+ },
+ {
+ "match": /\/\/(?:www\.)?youtube(?:-nocookie)?\.com\/(youtubei\/v1\/[^?]+\?).*(videoId[^&]+).*/i,
+ "fuzzyCanonReplace": "//youtube.fuzzy.replayweb.page/$1$2",
+ "args": [["videoId"]]
+ },
+ {
+ "match": /\/\/.*googlevideo.com\/(videoplayback)/i,
+ "fuzzyCanonReplace": "//youtube.fuzzy.replayweb.page/$1",
+ "args": [
+ ["id", "itag"],
+ ["id"]
+ ],
+ "fuzzyArgs": true
+ },
+ {
+ "match": /facebook\.com\/ajax\/pagelet\/generic.php\/photoviewerinitpagelet/i,
+ "args": [[{"arg": "data",
+ "keys": ["query_type", "fbid", "v", "cursor", "data"]}]]
+ },
+ {
+ "match": /(twitter.com\/[^/]+\/status\/[^?]+)(\?.*)/,
+ "fuzzyCanonReplace": "$1"
+ },
+ // Facebook
+ {
+ "match": /facebook\.com\/ajax\//i,
+ "fuzzySet": true
+ },
+ // {
+ // "match": /facebook\.com\/api\/graphql/i,
+ // "args": [["fb_api_req_friendly_name"]],
+ // //"args": [["variables", "doc_id"]],
+ // //"fuzzyArgs": true
+ // },
+ // {
+ // "match": /facebook\.com\/api\/graphqlbatch/i,
+ // "args": [["batch_name", "queries"], ["batch_name"]]
+ // },
+ // {
+ // "match": /facebook\.com\/ajax\/navigation/i,
+ // "args": [["route_url", "__user"], ["route_url"]]
+ // },
+ // {
+ // "match": /facebook\.com\/ajax\/route-definition/i,
+ // "args": [["route_url", "__user"], ["route_url"]]
+ // },
+ // {
+ // "match": /facebook\.com\/ajax\/bulk-route-definitions/i,
+ // "args": [["route_urls[0]", "__user"], ["route_urls[0]"]]
+ // },
+ // {
+ // "match": /facebook\.com\/ajax\/relay-ef/i,
+ // "args": [["queries[0]", "__user"], ["queries[0]"]]
+ // },
+ // {
+ // "match": /facebook\.com\/videos\/vodcomments/i,
+ // "args": [["eft_id"]],
+ // },
+ // {
+ // "match": /facebook\.com\/ajax\.*/i,
+ // "replaceQuery": /([?&][^_]\w+=[^&]+)/g,
+ // },
+ // {"match": /plus\.googleapis\.com\/u\/\/0\/_\/widget\/render\/comments/i,
+ // "args": [["href", "stream_id", "substream_id"]]
+ // },
+
+ // Generic Rules -- should be last
+ {
+ "match": joinRx([
+ "(callback=jsonp)[^&]+(?=&|$)",
+ "((?:\\w+)=jquery)[\\d]+_[\\d]+",
+ "utm_[^=]+=[^&]+(?=&|$)",
+ "(_|cb|_ga|\\w*cache\\w*)=[\\d.-]+(?=$|&)"
+ ]),
+ "replace": ""
+ },
+ {
+ "match": /(\.(?:js|webm|mp4|gif|jpg|png|css|json|m3u8))\?.*/i,
+ "replace": "$1",
+ "maxResults": 2
+ }
+];
+
+// ===========================================================================
+class FuzzyMatcher {
+ constructor(rules) {
+ this.rules = rules || fuzzymatcher_DEFAULT_RULES;
+ }
+
+ getRuleFor(reqUrl) {
+ let rule;
+
+ const matchUrl = reqUrl.indexOf("?") === -1 ? reqUrl + "?" : reqUrl;
+
+ for (const testRule of this.rules) {
+ if (matchUrl.match(testRule.match)) {
+ rule = testRule;
+ break;
+ }
+ }
+
+ let fuzzyCanonUrl = reqUrl;
+
+ if (rule && rule.fuzzyCanonReplace) {
+ fuzzyCanonUrl = reqUrl.replace(rule.match, rule.fuzzyCanonReplace);
+ }
+
+ const split = rule && rule.split || "?";
+ const inx = rule && rule.splitLast ? reqUrl.lastIndexOf(split) : reqUrl.indexOf(split);
+ const prefix = inx > 0 ? reqUrl.slice(0, inx + split.length) : reqUrl;
+
+ return {prefix, rule, fuzzyCanonUrl};
+ }
+
+ getFuzzyCanonsWithArgs(reqUrl) {
+ let { fuzzyCanonUrl, prefix, rule } = this.getRuleFor(reqUrl);
+
+ if (fuzzyCanonUrl === reqUrl) {
+ fuzzyCanonUrl = prefix;
+ }
+
+ const urls = [];
+
+ if (rule && rule.args) {
+ const fuzzUrl = new URL(fuzzyCanonUrl);
+ const origUrl = new URL(reqUrl);
+
+ for (const args of rule.args) {
+ const query = new URLSearchParams();
+
+ for (const arg of args) {
+ query.set(arg, origUrl.searchParams.get(arg) || "");
+ }
+ fuzzUrl.search = query.toString();
+ urls.push(fuzzUrl.href);
+ }
+ return urls;
+ }
+
+ return [fuzzyCanonUrl];
+ }
+
+ fuzzyCompareUrls(reqUrl, results, matchedRule) {
+ if (!results || !results.length) {
+ return null;
+ }
+
+ if (matchedRule && matchedRule.replace !== undefined && matchedRule.match !== undefined &&
+ // if limit exists, only apply if < limit results
+ (!matchedRule.maxResults || results.length <= matchedRule.maxResults)) {
+ const match = matchedRule.match;
+ const replace = matchedRule.replace;
+ const fuzzyReqUrl = reqUrl.replace(match, replace);
+
+ const newResults = [];
+
+ // find best match by regex
+ for (const result of results) {
+ const url = (typeof result === "string" ? result : result.url);
+
+ const fuzzyMatchUrl = url.replace(match, replace);
+
+ if (fuzzyReqUrl === fuzzyMatchUrl) {
+ // exact match, return
+ return result;
+ }
+
+ result.fuzzyMatchUrl = fuzzyMatchUrl;
+ newResults.push(result);
+ }
+
+ results = newResults;
+ reqUrl = fuzzyReqUrl;
+ }
+
+ return this.fuzzyBestMatchQuery(reqUrl, results, matchedRule);
+ }
+
+ fuzzyBestMatchQuery(reqUrl, results, rule) {
+ try {
+ reqUrl = new URL(reqUrl);
+ } catch (e) {
+ return 0.0;
+ }
+
+ const reqArgs = rule && rule.args && !rule.fuzzyArgs ? new Set(rule.args[0]) : null;
+
+ let bestTotal = 0;
+ let bestResult = null;
+
+ const reqQuery = new URLSearchParams(reqUrl.search);
+
+ for (const result of results) {
+ // skip 204s and 304s from fuzzy matching (todo: reexamine)
+ if (result.status === 204 || result.status === 304) {
+ continue;
+ }
+
+ let url = (typeof result === "string" ? result : result.fuzzyMatchUrl || result.url);
+
+ try {
+ url = new URL(url);
+ } catch (e) {
+ continue;
+ }
+
+ const foundQuery = new URLSearchParams(url.search);
+ let total = this.getMatch(reqQuery, foundQuery, reqArgs, rule && rule.fuzzySet);
+ total += this.getMatch(foundQuery, reqQuery, reqArgs);
+ total /= 2.0;
+
+ // lower total score for status >200
+ if (result.status > 200) {
+ total *= 10 ** ((200 - result.status) * 0.0003);
+ }
+
+ //console.log('total: ' + total + ' ' + url.href + ' <=> ' + reqUrl);
+
+ if (total > bestTotal) {
+ bestTotal = total;
+ bestResult = result;
+ }
+ }
+
+ //console.log("best: " + bestResult.url);
+
+ //return {"score": bestTotal, "result": bestResult};
+ return bestResult;
+ }
+
+ getMatch(reqQuery, foundQuery, reqArgs = null, fuzzySet = false) {
+ let score = 1.0;
+ let total = 1.0;
+
+ const keySets = {};
+
+ for (let [key, value] of reqQuery) {
+ let foundValue = foundQuery.get(key);
+
+ // if key is required, return a large negative to skip this match
+ if (reqArgs && reqArgs.has(key) && foundValue !== value) {
+ return -1000;
+ }
+
+ let weight;
+
+ if (key[0] === "_") {
+ weight = 0.1;
+ } else {
+ weight = 10.0;
+ }
+
+ if (foundValue !== null) {
+ score += weight * 0.5;
+
+ if (foundValue.length > MAX_ARG_LEN) {
+ foundValue = foundValue.slice(0, MAX_ARG_LEN);
+ }
+ }
+
+ if (value && value.length > MAX_ARG_LEN) {
+ value = value.slice(0, MAX_ARG_LEN);
+ }
+
+ const numValue = Number(value);
+ const numFoundValue = Number(foundValue);
+
+ total += weight;
+
+ if (fuzzySet) {
+ this.addSetMatch(keySets, key, value, foundValue);
+ }
+
+ if (foundValue === value) {
+ score += weight * value.length;
+ } else if (foundValue === null || value === null) {
+ score += 0.0;
+ } else if (!isNaN(numValue) && !isNaN(numFoundValue)) {
+ score += 10.0 - Math.log(Math.abs(numValue - numFoundValue) + 1);
+ } else if (value.startsWith("{") && foundValue.startsWith("{")) {
+ try {
+ const rQ = E(value);
+ const fQ = E(foundValue);
+
+ score += this.getMatch(rQ, fQ) * weight * 2;
+
+ } catch (e) {
+ score += 0.5 * weight * this.levScore(value, foundValue);
+ }
+
+ } else {
+ // if (foundValue.length > value.length && foundValue.indexOf(",") >= 0 && foundValue.indexOf(value) >= 0) {
+ // score += weight * value.length * 0.5;
+ // }
+ if (!fuzzySet) {
+ score += weight * this.levScore(value, foundValue);
+ }
+ }
+ }
+
+ const result = (score / total) + (fuzzySet ? this.paramSetMatch(keySets, 100) : 0);
+ //console.log('score: ' + result + " " + reqQuery + " <-> " + foundQuery);
+ return result;
+ }
+
+ addSetMatch(keySets, key, value, foundValue) {
+ if (!value || !foundValue || value[0] !== "/" || foundValue[0] !== "/") {
+ return;
+ }
+
+ const keyParts = key.split(SPLIT_BASE_RX);
+
+ if (keyParts.length <= 1) {
+ return;
+ }
+
+ // compare set matches instead of by string
+ const valueQ = value.indexOf("?");
+ const foundQ = foundValue.indexOf("?");
+
+ const keyBase = keyParts[0];
+
+ const valueNoQ = valueQ > 0 ? value.slice(0, valueQ) : value;
+ const foundNoQ = foundQ > 0 ? foundValue.slice(0, foundQ) : foundValue;
+
+ if (!keySets[keyBase]) {
+ keySets[keyBase] = {value: [], found: new Set()};
+ }
+
+ keySets[keyBase].value.push(valueNoQ);
+ keySets[keyBase].found.add(foundNoQ);
+ }
+
+ paramSetMatch(keySets, weight) {
+ let score = 0;
+
+ for (const keySet of Object.values(keySets)) {
+ let currWeight = weight;
+
+ for (const obj of keySet.value) {
+ if (keySet.found.has(obj)) {
+ score += currWeight;
+ }
+ currWeight *= 0.33;
+ }
+ }
+
+ return score;
+ }
+
+ levScore(val1, val2) {
+ const minLen = Math.min(val1.length, val2.length);
+ const lev = js_levenshtein(val1, val2);
+ return lev < minLen ? minLen - lev : 0;
+ }
+}
+
+const fuzzyMatcher = new FuzzyMatcher();
+
+
+
+;// CONCATENATED MODULE: ./src/archivedb.js
+
+
+
+
+
+
+
+
+const MAX_FUZZY_MATCH = 128000;
+const MAX_RESULTS = 16;
+const MAX_DATE_TS = new Date("9999-01-01").getTime();
+
+const REVISIT = "warc/revisit";
+
+const EMPTY_PAYLOAD_SHA256 = "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+// sha-1 digests often base32 encoded
+const EMPTY_PAYLOAD_SHA1 = "sha1:3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ";
+
+const DB_VERSION = 4;
+
+// ===========================================================================
+class ArchiveDB {
+ constructor(name, opts = {}) {
+ this.name = name;
+ this.db = null;
+
+ const { minDedupSize, noRefCounts } = opts;
+ this.minDedupSize = Number.isInteger(minDedupSize) ? minDedupSize : 1024;
+
+ this.version = DB_VERSION;
+
+ this.autoHttpsCheck = true;
+ this.useRefCounts = !noRefCounts;
+
+ this.allowRepeats = true;
+ this.repeatTracker = this.allowRepeats ? new RepeatTracker() : null;
+ this.fuzzyPrefixSearch = true;
+
+ this.initing = this.init();
+ }
+
+ async init() {
+ let oldVersion = 0;
+
+ this.db = await openDB(this.name, this.version, {
+ upgrade: (db, oldV, newV, tx) => {
+ oldVersion = oldV;
+ this._initDB(db, oldV, newV, tx);
+ },
+ blocking: (_, oldV) => {
+ if (!oldV) {
+ this.close();
+ }
+ }
+ });
+
+ if (oldVersion === 1) {
+ await this.convertCuratedPagesToV2(this.db);
+ }
+ }
+
+ _initDB(db, oldV/*, newV, tx*/) {
+ if (!oldV) {
+ const pageStore = db.createObjectStore("pages", { keyPath: "id" });
+ pageStore.createIndex("url", "url");
+ pageStore.createIndex("ts", "ts");
+ pageStore.createIndex("state", "state");
+
+ db.createObjectStore("pageLists", { keyPath: "id", autoIncrement: true});
+
+ const curatedPages = db.createObjectStore("curatedPages", { keyPath: "id", autoIncrement: true});
+ curatedPages.createIndex("listPages", ["list", "pos"]);
+
+ const urlStore = db.createObjectStore("resources", { keyPath: ["url", "ts"] });
+ urlStore.createIndex("pageId", "pageId");
+ //urlStore.createIndex("pageUrlTs", ["pageId", "url", "ts"]);
+ //urlStore.createIndex("ts", "ts");
+ urlStore.createIndex("mimeStatusUrl", ["mime", "status", "url"]);
+
+ db.createObjectStore("payload", { keyPath: "digest", unique: true});
+ db.createObjectStore("digestRef", { keyPath: "digest", unique: true});
+ }
+ }
+
+ async clearAll() {
+ const stores = ["pages", "resources", "payload", "digestRef"];
+
+ for (const store of stores) {
+ await this.db.clear(store);
+ }
+ }
+
+ close() {
+ if (this.db) {
+ this.db.close();
+ this.db = null;
+ }
+ }
+
+ async delete() {
+ this.close();
+ await deleteDB(this.name, {
+ blocked(_, e) {
+ console.log("Unable to delete: " + e);
+ }
+ });
+ }
+
+ async addPage(page, tx) {
+ const url = page.url;
+ const title = page.title || page.url;
+ const id = page.id || this.newPageId();
+ const state = page.state || PAGE_STATE_SYNCED;
+ let ts = page.ts;
+
+
+ if (typeof(ts) !== "number") {
+ if (page.timestamp) {
+ ts = tsToDate(page.timestamp).getTime();
+ } else {
+ const date = page.ts || page.date || page.datetime;
+ if (date) {
+ ts = new Date(date).getTime();
+ }
+ }
+ }
+
+ const p = {...page, url, ts, title, id, state};
+
+ if (tx) {
+ tx.store.put(p);
+ return p.id;
+ } else {
+ return await this.db.put("pages", p);
+ }
+ }
+
+ async addPages(pages, pagesTable = "pages", update = false) {
+ const tx = this.db.transaction(pagesTable, "readwrite");
+
+ for (const page of pages) {
+ if (update) {
+ tx.store.put(page);
+ } else {
+ this.addPage(page, tx);
+ }
+ }
+
+ try {
+ await tx.done;
+ } catch(e) {
+ console.warn("addPages tx", e.toString());
+ }
+ }
+
+ async createPageList(data) {
+ const listData = {};
+ listData.title = data.title;
+ listData.desc = data.desc || data.description;
+ listData.slug = data.id || data.slug;
+
+ return await this.db.put("pageLists", listData);
+ }
+
+ async addCuratedPageList(listInfo, pages) {
+ const listId = await this.createPageList(listInfo);
+
+ let pos = 0;
+
+ for (const page of pages) {
+ page.pos = pos++;
+ page.list = listId;
+ }
+
+ await this.addPages(pages, "curatedPages");
+ }
+
+ async addCuratedPageLists(pageLists, pageKey = "pages", filter = "public") {
+ for (const list of pageLists) {
+ if (filter && !list[filter]) {
+ continue;
+ }
+
+ const pages = list[pageKey] || [];
+
+ await this.addCuratedPageList(list, pages);
+ }
+ }
+
+ async convertCuratedPagesToV2(db) {
+ const curatedPages = await db.getAll("curatedPages");
+
+ if (!curatedPages || !curatedPages.length) {
+ return;
+ }
+
+ const pages = await db.getAll("pages");
+ const pageMap = new Map();
+
+ for (const page of pages) {
+ pageMap.set(page.id, page);
+ }
+
+ for (const cpage of curatedPages) {
+ if (cpage.page) {
+ const page = pageMap.get(cpage.page);
+ if (page) {
+ cpage.id = this.newPageId();
+ cpage.url = page.url;
+ cpage.ts = page.ts;
+ if (!cpage.title && page.title) {
+ cpage.title = page.title;
+ }
+ }
+ delete cpage.page;
+ }
+ }
+
+ await db.clear("curatedPages");
+
+ const tx = db.transaction("curatedPages", "readwrite");
+
+ for (const cpage of curatedPages) {
+ tx.store.put(cpage);
+ }
+
+ try {
+ await tx.done;
+ } catch (e) {
+ console.warn("Conversion Failed", e);
+ }
+ }
+
+ async getCuratedPagesByList() {
+ const allLists = await this.db.getAll("pageLists");
+
+ const tx = this.db.transaction("curatedPages", "readonly");
+
+ for await (const cursor of tx.store.index("listPages").iterate()) {
+ const list = allLists[cursor.value.list - 1];
+ if (!list) {
+ continue;
+ }
+ list.show = true;
+ if (!list.pages) {
+ list.pages = [];
+ }
+ list.pages.push(cursor.value);
+ }
+
+ return allLists;
+ }
+
+ newPageId() {
+ return randomId();
+ }
+
+ async getAllPages() {
+ return await this.db.getAll("pages");
+ }
+
+ async getPages(pages) {
+ const results = [];
+ pages.sort();
+
+ for await (const result of this.matchAny("pages", null, pages)) {
+ results.push(result);
+ }
+
+ return results;
+ }
+
+ async getPagesWithState(state) {
+ return await this.db.getAllFromIndex("pages", "state", state);
+ }
+
+ async getVerifyInfo() {
+ return {};
+ }
+
+ async addVerifyData() {
+ return;
+ }
+
+ async addVerifyDataList() {
+ return;
+ }
+
+ async dedupResource(digest, payload, tx, count = 1) {
+ const digestRefStore = tx.objectStore("digestRef");
+ const ref = await digestRefStore.get(digest);
+
+ if (ref) {
+ ++ref.count;
+ return ref;
+ //digestRefStore.put(ref);
+ //return ref.count;
+
+ } else if (payload) {
+ try {
+ tx.objectStore("payload").put({digest, payload});
+ const size = payload.length;
+ //digestRefStore.put({digest, count, size});
+ return {digest, count, size};
+ } catch (e) {
+ console.log(e);
+ }
+ }
+
+ return null;
+ }
+
+ async addResources(datas) {
+ const revisits = [];
+ const regulars = [];
+
+ const digestRefCount = {};
+ const changedDigests = new Set();
+
+ const dtx = this.db.transaction(["digestRef", "payload"], "readwrite");
+
+ for (const data of datas) {
+ let refCount = 1;
+
+ const array = data.mime === REVISIT ? revisits : regulars;
+
+ array.push(data);
+
+ const fuzzyUrlData = this.getFuzzyUrl(data);
+
+ if (fuzzyUrlData) {
+ array.push(fuzzyUrlData);
+ refCount = 2;
+ }
+
+ if (this.useRefCounts && data.digest) {
+ if (!digestRefCount[data.digest]) {
+ digestRefCount[data.digest] = await this.dedupResource(data.digest, data.payload, dtx, refCount);
+ } else {
+ digestRefCount[data.digest].count += refCount;
+ changedDigests.add(data.digest);
+ }
+ delete data.payload;
+ }
+ }
+
+ if (this.useRefCounts) {
+ const digestRefStore = dtx.objectStore("digestRef");
+
+ for (const digest of changedDigests) {
+ digestRefStore.put(digestRefCount[digest]);
+ }
+ }
+
+ try {
+ await dtx.done;
+ } catch(e) {
+ console.error("Payload and Ref Count Bulk Add Failed: ", e);
+ }
+
+ // Add resources
+ const tx = this.db.transaction("resources", "readwrite");
+
+ // First, add revisits
+ for (const data of revisits) {
+ tx.store.put(data);
+ }
+
+ // Then, add non-revisits, overriding any revisits
+ for (const data of regulars) {
+ tx.store.put(data);
+ }
+
+ try {
+ await tx.done;
+ } catch (e) {
+ console.error("Resources Bulk Add Failed", e);
+ }
+ }
+
+ getFuzzyUrl(result) {
+ if (result.status >= 200 && result.status < 400 && result.status !== 304 && result.status !== 204) {
+ const {fuzzyCanonUrl} = fuzzyMatcher.getRuleFor(result.url);
+
+ if (!fuzzyCanonUrl || fuzzyCanonUrl === result.url) {
+ return null;
+ }
+
+ const fuzzyRes = {
+ url: fuzzyCanonUrl,
+ ts: result.ts,
+ origURL: result.url,
+ origTS: result.ts,
+ pageId: result.pageId,
+ digest: result.digest
+ };
+
+ return fuzzyRes;
+ }
+
+ return null;
+ }
+
+ async addResource(data) {
+ if (data.payload && data.payload.length > this.minDedupSize) {
+ if (!data.digest) {
+ data.digest = await digestMessage(data.payload, "sha-256");
+ }
+ }
+
+ let digestRefCount = null;
+ let isNew = false;
+
+ const tx = this.db.transaction(["resources", "digestRef", "payload"], "readwrite");
+
+ if (data.payload && data.payload.length > this.minDedupSize) {
+ digestRefCount = await this.dedupResource(data.digest, data.payload, tx);
+ isNew = (digestRefCount && digestRefCount.count === 1);
+ delete data.payload;
+ } else if (data.payload) {
+ isNew = true;
+ }
+
+ if (data.mime !== REVISIT) {
+ tx.objectStore("resources").put(data);
+
+ const fuzzyUrlData = this.getFuzzyUrl(data);
+
+ if (fuzzyUrlData) {
+ tx.objectStore("resources").put(fuzzyUrlData);
+ if (digestRefCount) {
+ digestRefCount.count++;
+ }
+ }
+ } else {
+ // using add() to allow failing if non-revisit already exists
+ tx.objectStore("resources").add(data);
+ }
+
+ if (digestRefCount) {
+ tx.objectStore("digestRef").put(digestRefCount);
+ }
+
+ try {
+ await tx.done;
+ } catch (e) {
+ if (data.mime === REVISIT) {
+ console.log("Skip Duplicate revisit for: " + data.url);
+ } else {
+ console.log("Add Error for " + data.url);
+ }
+ console.log(e);
+ }
+
+ return isNew;
+ }
+
+ async getResource(request, rwPrefix, event, opts = {}) {
+ const ts = tsToDate(request.timestamp).getTime();
+ let url = request.url;
+
+ let result = null;
+
+ const skip = this.repeatTracker ? this.repeatTracker.getSkipCount(event, url, request.request.method) : 0;
+ const newOpts = {...opts, skip};
+
+ if (url.startsWith("//")) {
+ let useHttp = false;
+ result = await this.lookupUrl("https:" + url, ts, newOpts);
+ if (!result) {
+ result = await this.lookupUrl("http:" + url, ts, newOpts);
+ // use http if found or if referrer contains an http replay path
+ // otherwise, default to https
+ if (result || request.request.referrer.indexOf("/http://", 2) > 0) {
+ useHttp = true;
+ }
+ }
+ url = (useHttp ? "http:" : "https:") + url;
+ } else {
+ result = await this.lookupUrl(url, ts, newOpts);
+ if (!result && this.autoHttpsCheck && url.startsWith("http://")) {
+ const httpsUrl = url.replace("http://", "https://");
+ result = await this.lookupUrl(httpsUrl, ts, newOpts);
+ if (result) {
+ url = httpsUrl;
+ }
+ }
+ }
+
+ if (!result && this.fuzzyPrefixSearch && !opts.noFuzzyCheck) {
+ result = await this.lookupQueryPrefix(url, opts);
+ }
+
+ // check if redirect
+ if (result && result.origURL) {
+ const origResult = await this.lookupUrl(result.origURL, result.origTS || result.ts, opts);
+ if (origResult) {
+ url = origResult.url;
+ result = origResult;
+ }
+ }
+
+ if (!result) {
+ return null;
+ }
+
+ const status = result.status;
+ const statusText = result.statusText || utils_getStatusText(status);
+
+ let payload = null;
+
+ if (!isNullBodyStatus()) {
+ payload = await this.loadPayload(result, opts);
+ if (!payload) {
+ return null;
+ }
+ }
+
+ const headers = makeHeaders(result.respHeaders);
+
+ const date = new Date(result.ts);
+
+ const extraOpts = result.extraOpts || null;
+
+ url = result.url;
+
+ if (url !== request.url) {
+ headers.set("Content-Location", url);
+ }
+
+ return new ArchiveResponse({url, payload, status, statusText, headers, date, extraOpts});
+ }
+
+ async loadPayload(result/*, opts*/) {
+ if (result.digest && !result.payload) {
+ if (result.digest === EMPTY_PAYLOAD_SHA256 || result.digest === EMPTY_PAYLOAD_SHA1) {
+ return new Uint8Array([]);
+ }
+ const payloadRes = await this.db.get("payload", result.digest);
+ if (!payloadRes) {
+ return null;
+ }
+ const { payload } = payloadRes;
+ return payload;
+ }
+
+ return result.payload;
+ }
+
+ async lookupUrl(url, ts, opts = {}) {
+ const tx = this.db.transaction("resources", "readonly");
+
+ if (ts) {
+ const range = IDBKeyRange.bound([url, ts], [url, MAX_DATE_TS]);
+
+ if (!opts.noRevisits && !opts.pageId) {
+ const result = await tx.store.get(range);
+ if (result) {
+ return result;
+ }
+ } else {
+ let results = await tx.store.getAll(range, MAX_RESULTS);
+ results = results || [];
+
+ for (const result of results) {
+ if (opts.pageId && result.pageId && (result.pageId !== opts.pageId)) {
+ continue;
+ }
+
+ if (opts.noRevisits && result.mime === REVISIT) {
+ continue;
+ }
+
+ return result;
+ }
+ }
+ }
+
+ // search reverse from ts (or from latest capture)
+ const range = IDBKeyRange.bound([url], [url, ts || MAX_DATE_TS]);
+
+ for await (const cursor of tx.store.iterate(range, "prev")) {
+ const result = cursor.value;
+
+ if (opts.pageId && result.pageId && (result.pageId !== opts.pageId)) {
+ continue;
+ }
+
+ if (opts.noRevisits && result.mime === REVISIT) {
+ continue;
+ }
+
+ return result;
+ }
+
+ return null;
+ }
+
+ async lookupQueryPrefix(url, opts) {
+ const {rule, prefix, fuzzyCanonUrl/*, fuzzyPrefix*/} = fuzzyMatcher.getRuleFor(url);
+
+ if (fuzzyCanonUrl !== url) {
+ const result = await this.lookupUrl(fuzzyCanonUrl, 0, opts);
+ if (result) {
+ return result;
+ }
+
+ //const results = await this.db.getAll("resources", this.getLookupRange(fuzzyPrefix, "prefix"));
+ //return fuzzyMatcher.fuzzyCompareUrls(url, results, rule);
+ }
+
+ // only do fuzzy prefix match for custom rules that have a query
+ if (!rule && prefix === url && prefix === fuzzyCanonUrl && !url.endsWith("?")) {
+ return null;
+ }
+
+ //todo: explore optimizing with incremental loading?
+ const results = await this.db.getAll("resources", this.getLookupRange(prefix, "prefix"), MAX_FUZZY_MATCH);
+
+ return fuzzyMatcher.fuzzyCompareUrls(url, results, rule);
+ }
+
+ resJson(res) {
+ const date = new Date(res.ts).toISOString();
+ return {
+ url: res.url,
+ date: date,
+ ts: getTS(date),
+ mime: res.mime,
+ status: res.status
+ };
+ }
+
+ async resourcesByPage(pageId) {
+ return this.db.getAllFromIndex("resources", "pageId", pageId);
+ }
+
+ async* resourcesByPages2(pageIds) {
+ pageIds.sort();
+
+ yield* this.matchAny("resources", "pageId", pageIds);
+ }
+
+ async* resourcesByPages(pageIds) {
+ const tx = this.db.transaction("resources", "readonly");
+
+ for await (const cursor of tx.store.iterate()) {
+ if (pageIds.includes(cursor.value.pageId)) {
+ yield cursor.value;
+ }
+ }
+ }
+
+ async* matchAny(storeName, indexName, sortedKeys, subKey, openBound = false) {
+ const tx = this.db.transaction(storeName, "readonly");
+
+ const range = IDBKeyRange.lowerBound(sortedKeys[0], openBound);
+
+ let cursor = indexName ? await tx.store.index(indexName).openCursor(range) : await tx.store.openCursor(range);
+
+ let i = 0;
+
+ while (cursor && i < sortedKeys.length) {
+ let currKey, matchKey, matches;
+
+ if (subKey !== undefined) {
+ currKey = cursor.key[subKey];
+ matchKey = sortedKeys[i][subKey];
+ matches = currKey.startsWith(matchKey);
+ } else {
+ currKey = cursor.key;
+ matchKey = sortedKeys[i];
+ matches = currKey === matchKey;
+ }
+
+ if (!matches && currKey > matchKey) {
+ ++i;
+ continue;
+ }
+
+ if (matches) {
+ yield cursor.value;
+ cursor = await cursor.continue();
+ } else {
+ cursor = await cursor.continue(sortedKeys[i]);
+ }
+ }
+ }
+
+ async resourcesByUrlAndMime(url, mimes, count = 1000, prefix = true, fromUrl = "", fromTs = "") {
+ // if doing local mime filtering, need to remove count
+ const queryCount = mimes ? null : count;
+
+ const fullResults = await this.db.getAll("resources",
+ this.getLookupRange(url, prefix ? "prefix" : "exact", fromUrl, fromTs), queryCount);
+
+ mimes = mimes.split(",");
+ const results = [];
+
+ for (const res of fullResults) {
+ for (const mime of mimes) {
+ if (!mime || (res.mime && res.mime.startsWith(mime))) {
+ results.push(this.resJson(res));
+ if (results.length === count) {
+ return results;
+ }
+ break;
+ }
+ }
+ }
+
+ return results;
+ }
+
+ async resourcesByMime(mimes, count = 100, fromMime = "", fromUrl = "", fromStatus = 0) {
+ mimes = mimes.split(",");
+ const results = [];
+
+ mimes.sort();
+
+ let startKey = [];
+
+ if (fromMime) {
+ startKey.push([fromMime, fromStatus, fromUrl]);
+ }
+
+ for (const mime of mimes) {
+ if (!fromMime || !mime || mime > fromMime) {
+ startKey.push([mime, 0, ""]);
+ }
+ }
+
+ for await (const result of this.matchAny("resources", "mimeStatusUrl", startKey, 0, true)) {
+ results.push(this.resJson(result));
+
+ if (results.length === count) {
+ break;
+ }
+ }
+
+ return results;
+ /*
+ let i = 0;
+ let cursor = await this.db.transaction("resources").store.index("mimeStatusUrl").openCursor();
+
+ while (cursor && i < startKey.length) {
+ const mime = cursor.key[0];
+
+ const matches = mime.startsWith(startKey[i][0]);
+
+ if (!matches && mime > startKey[i][0]) {
+ ++i;
+ continue;
+ }
+
+ if (matches) {
+ results.push(this.resJson(cursor.value));
+ cursor = await cursor.continue();
+ } else {
+ cursor = await cursor.continue(startKey[i]);
+ }
+ }
+*/
+ }
+
+ async deletePage(id) {
+ const tx = this.db.transaction("pages", "readwrite");
+ const page = await tx.store.get(id);
+ await tx.store.delete(id);
+
+ const size = await this.deletePageResources(id);
+ return {pageSize: page && page.size || 0,
+ dedupSize: size};
+ }
+
+ async deletePageResources(pageId) {
+ const digestSet = {};
+
+ const tx = this.db.transaction("resources", "readwrite");
+
+ let cursor = await tx.store.index("pageId").openCursor(pageId);
+
+ let size = 0;
+
+ while (cursor) {
+ const digest = cursor.value.digest;
+ if (digest) {
+ digestSet[digest] = (digestSet[digest] || 0) + 1;
+ } else if (cursor.value.payload) {
+ size += cursor.value.payload.length;
+ }
+
+ tx.store.delete(cursor.primaryKey);
+
+ cursor = await cursor.continue();
+ }
+
+ await tx.done;
+
+ // delete payloads
+ const tx2 = this.db.transaction(["payload", "digestRef"], "readwrite");
+ const digestRefStore = tx2.objectStore("digestRef");
+
+ for (const digest of Object.keys(digestSet)) {
+ const ref = await digestRefStore.get(digest);
+
+ if (ref) {
+ ref.count -= digestSet[digest];
+ }
+
+ if (ref && ref.count >= 1) {
+ digestRefStore.put(ref);
+ } else {
+ size += ref ? ref.size : 0;
+ digestRefStore.delete(digest);
+ tx2.objectStore("payload").delete(digest);
+ }
+ }
+
+ await tx2.done;
+ return size;
+ }
+
+ prefixUpperBound(url) {
+ return url.slice(0, -1) + String.fromCharCode(url.charCodeAt(url.length - 1) + 1);
+ }
+
+ getLookupRange(url, type, fromUrl, fromTs) {
+ let lower;
+ let upper;
+
+ switch (type) {
+ case "prefix":
+ lower = [url];
+ upper = [this.prefixUpperBound(url)];
+ break;
+
+ case "host": {
+ const origin = new URL(url).origin;
+ lower = [origin + "/"];
+ upper = [origin + "0"];
+ break;
+ }
+
+ case "exact":
+ default:
+ lower = [url];
+ //upper = [url + "!"];
+ upper = [url, Number.MAX_SAFE_INTEGER];
+ }
+
+ let exclusive;
+
+ if (fromUrl) {
+ lower = [fromUrl, fromTs || ""];
+ exclusive = true;
+ } else {
+ exclusive = false;
+ }
+
+ return IDBKeyRange.bound(lower, upper, exclusive, true);
+ }
+}
+
+// ===========================================================================
+class RepeatTracker {
+ constructor() {
+ this.repeats = {};
+ }
+
+ getSkipCount(event, url, method) {
+ if (method !== "POST" && !url.endsWith(".m3u8")) {
+ return 0;
+ }
+
+ if (event.replacesClientId) {
+ delete this.repeats[event.replacesClientId];
+ }
+
+ const id = event.resultingClientId || event.clientId;
+ if (!id) {
+ return 0;
+ }
+
+ if (this.repeats[id] === undefined) {
+ this.repeats[id] = {};
+ }
+
+ if (this.repeats[id][url] === undefined) {
+ this.repeats[id][url] = 0;
+ } else {
+ this.repeats[id][url]++;
+ }
+
+ return this.repeats[id][url];
+ }
+}
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./src/extract.js
+
+
+
+
+
+const SKIPPED_TAGS = ["script", "style", "header", "footer", "banner-div", "noscript"];
+
+
+// ===========================================================================
+async function extractText(url, buffer, ce, te) {
+ const parser = new SAXParser();
+ const textChunks = [];
+ let context = null;
+
+ parser.on("text", (data/*, raw*/) => {
+ if (context) {
+ return;
+ }
+ const text = data.text.trim();
+ if (text) {
+ textChunks.push(text);
+ }
+ });
+
+ parser.on("startTag", startTag => {
+ if (!startTag.selfClosing && SKIPPED_TAGS.includes(startTag.tagName)) {
+ context = startTag.tagName;
+ }
+ });
+
+ parser.on("endTag", endTag => {
+ if (endTag.tagName === context) {
+ context = null;
+ }
+ });
+
+ if (ce || te) {
+ buffer = await decodeContent(buffer, ce, te);
+ }
+
+ parser.end(new TextDecoder().decode(buffer));
+
+ const p = new Promise((resolve) => {
+ parser.on("end", () => {
+ resolve(textChunks.join(" "));
+ });
+ });
+
+ return await p;
+}
+
+
+
+;// CONCATENATED MODULE: ./src/baseparser.js
+const DEFAULT_BATCH_SIZE = 1000;
+
+
+// ===========================================================================
+class BaseParser
+{
+ constructor(batchSize = DEFAULT_BATCH_SIZE) {
+ this.batchSize = batchSize;
+
+ this.promises = [];
+
+ this.batch = [];
+ this.count = 0;
+
+ this.dupeSet = new Set();
+ }
+
+ addPage(page) {
+ this.promises.push(this.db.addPage(page));
+ }
+
+ isBatchFull() {
+ return this.batch.length >= this.batchSize;
+ }
+
+ addResource(res) {
+ if (this.isBatchFull()) {
+ this.flush();
+ }
+
+ if (Number.isNaN(res.ts)) {
+ console.warn("Skipping resource with missing/invalid ts: " + res.url);
+ return;
+ }
+
+ const key = res.url + " " + res.ts;
+
+ if (res.mime === "warc/revisit") {
+ if (this.dupeSet.has(key)) {
+ console.warn("Skipping duplicate revisit, prevent overriding non-revisit");
+ return;
+ }
+ } else {
+ this.dupeSet.add(key);
+ }
+
+ this.batch.push(res);
+ }
+
+ flush() {
+ if (this.batch.length > 0) {
+ this.promises.push(this.db.addResources(this.batch));
+ }
+ console.log(`Read ${this.count += this.batch.length} records`);
+ this.batch = [];
+ }
+
+ async finishIndexing() {
+ this.flush();
+
+ this._finishLoad();
+
+ try {
+ await Promise.all(this.promises);
+ } catch (e) {
+ console.warn(e);
+ }
+
+ this.promises = [];
+ }
+
+ _finishLoad() {
+
+ }
+}
+
+
+;// CONCATENATED MODULE: ./src/warcloader.js
+
+
+
+
+
+
+
+
+
+// ===========================================================================
+class WARCLoader extends BaseParser {
+ constructor(reader, abort = null, loadId = null, sourceExtra = null) {
+ super();
+
+ this.reader = reader;
+ this.abort = abort;
+ this.loadId = loadId;
+
+ this.anyPages = false;
+ this.detectPages = false;
+
+ this._lastRecord = null;
+
+ this.metadata = {};
+
+ this.pageMap = {};
+ this.pages = [];
+ this.lists = [];
+
+ this.source = sourceExtra;
+ }
+
+ parseWarcInfo(record) {
+ if (!record.payload) {
+ return;
+ }
+ var dec = new TextDecoder("utf-8");
+ const text = dec.decode(record.payload);
+
+ // Webrecorder-style metadata
+ for (const line of text.split("\n")) {
+ if (!line.startsWith("json-metadata:")) {
+ continue;
+ }
+
+ try {
+ const json = JSON.parse(line.slice("json-metadata:".length));
+
+ if (json.type === "collection") {
+ this.metadata.desc = json.desc;
+ this.metadata.title = json.title;
+ }
+
+ if (json.pages && json.pages.length) {
+ this.pages = this.pages.concat(json.pages);
+
+ for (const page of json.pages) {
+ page.ts = tsToDate(page.timestamp).getTime();
+ this.pageMap[page.ts + "/" + page.url] = {page};
+ }
+ //this.promises.push(this.db.addPages(pages));
+ this.anyPages = true;
+ }
+
+ if (json.lists && json.lists.length) {
+ this.lists = this.lists.concat(json.lists);
+ // this.promises.push(this.db.addCuratedPageLists(lists, "bookmarks", "public"));
+ }
+
+ } catch (e) {
+ console.log("Page Add Error", e.toString());
+ }
+ }
+ }
+
+ index(record, parser) {
+ if (record.warcType === "warcinfo") {
+ this.parseWarcInfo(record);
+ return;
+ }
+
+ //record.cdx = cdx;
+
+ if (!this._lastRecord) {
+ this._lastRecord = record;
+ return;
+ }
+
+ if (this._lastRecord.warcTargetURI != record.warcTargetURI) {
+ this.indexReqResponse(this._lastRecord, null, parser);
+ this._lastRecord = record;
+ return;
+ }
+
+ if (record.warcType === "request" && this._lastRecord.warcType === "response") {
+ this.indexReqResponse(this._lastRecord, record, parser);
+ this._lastRecord = null;
+ } else if (record.warcType === "response" && this._lastRecord.warcType === "request") {
+ this.indexReqResponse(record, this._lastRecord, parser);
+ this._lastRecord = null;
+ } else {
+ this.indexReqResponse(this._lastRecord, null, parser);
+ this._lastRecord = record;
+ }
+ }
+
+ indexDone(parser) {
+ if (this._lastRecord) {
+ this.indexReqResponse(this._lastRecord, null, parser);
+ this._lastRecord = null;
+ }
+ }
+
+ shouldIndexMetadataRecord(record) {
+ const targetURI = record.warcTargetURI;
+ if (targetURI && targetURI.startsWith("metadata://")) {
+ return true;
+ }
+
+ return false;
+ }
+
+ parseRevisitRecord(record, reqRecord) {
+ const url = record.warcTargetURI.split("#")[0];
+ const date = record.warcDate;
+ const ts = new Date(date).getTime();
+
+ let respHeaders = undefined;
+
+ if (record.httpHeaders) {
+ const parsed = this.parseResponseHttpHeaders(record, url, reqRecord);
+ respHeaders = parsed && Object.fromEntries(parsed.headers.entries());
+ }
+
+ const origURL = record.warcRefersToTargetURI;
+ const origTS = new Date(record.warcRefersToDate).getTime();
+
+ // self-revisit, skip
+ if (origURL === url && origTS === ts) {
+ return null;
+ }
+
+ const digest = record.warcPayloadDigest;
+
+ return {url, ts, origURL, origTS, digest, pageId: null, respHeaders};
+ }
+
+ parseResponseHttpHeaders(record, url, reqRecord) {
+ let status = 200;
+ let headers = null;
+ let mime = "";
+
+ const method = (reqRecord && reqRecord.httpHeaders.method);
+
+ if (record.httpHeaders) {
+ status = Number(record.httpHeaders.statusCode) || 200;
+
+ if (method === "OPTIONS" || method === "HEAD") {
+ return null;
+ }
+
+ //statusText = record.httpHeaders.statusText;
+
+ headers = makeHeaders(record.httpHeaders.headers);
+
+ //if (!reqRecord && !record.content.length &&
+ // (headers.get("access-control-allow-methods") || headers.get("access-control-allow-credentials"))) {
+ // return null;
+ //}
+
+ mime = (headers.get("content-type") || "").split(";")[0];
+
+ // skip partial responses (not starting from 0)
+ if (status === 206 && !this.isFullRangeRequest(headers)) {
+ return null;
+ }
+
+ // skip self-redirects
+ if (status > 300 && status < 400) {
+ const location = headers.get("location");
+ if (location) {
+ if (new URL(location, url).href === url) {
+ return null;
+ }
+ }
+ }
+ } else {
+ headers = new Headers();
+ headers.set("content-type", record.warcContentType);
+ headers.set("content-length", record.warcContentLength);
+ mime = record.warcContentType;
+
+ //cl = record.warcContentLength;
+ }
+
+ return {status, method, headers, mime};
+ }
+
+ indexReqResponse(record, reqRecord) {
+ const entry = this.parseRecords(record, reqRecord);
+
+ if (entry) {
+ this.addResource(entry);
+ }
+ }
+
+ parseRecords(record, reqRecord) {
+ switch (record.warcType) {
+ case "revisit":
+ return this.parseRevisitRecord(record, reqRecord);
+
+ case "resource":
+ reqRecord = null;
+ break;
+
+ case "response":
+ break;
+
+ case "metadata":
+ if (!this.shouldIndexMetadataRecord(record)) {
+ return null;
+ }
+ break;
+
+ default:
+ return null;
+ }
+
+ let url = record.warcTargetURI.split("#")[0];
+ const date = record.warcDate;
+
+ const parsed = this.parseResponseHttpHeaders(record, url, reqRecord);
+
+ if (!parsed) {
+ return null;
+ }
+
+ const {status, method, headers, mime} = parsed;
+
+ let referrer = null;
+ let requestBody = null;
+ let requestUrl;
+ let reqHeaders;
+
+ if (reqRecord && reqRecord.httpHeaders.headers) {
+ let requestHeaders = null;
+ try {
+ requestHeaders = new Headers(reqRecord.httpHeaders.headers);
+ const cookie = requestHeaders.get("cookie");
+ if (cookie) {
+ headers.set("x-wabac-preset-cookie", cookie);
+ }
+ referrer = reqRecord.httpHeaders.headers.get("Referer");
+ } catch(e) {
+ requestHeaders = new Headers();
+ console.warn(e);
+ }
+
+ reqHeaders = Object.fromEntries(requestHeaders.entries());
+
+ if (method !== "GET") {
+ const data = {
+ headers: requestHeaders,
+ method,
+ url,
+ postData: reqRecord.payload
+ };
+
+ if (L(data)) {
+ // original requestUrl
+ requestUrl = url;
+
+ // url with post data appended
+ url = data.url;
+
+ // raw request payload (for future serialization)
+ requestBody = reqRecord.payload;
+ }
+ }
+ }
+
+ // if no pages found, start detection if hasn't started already
+ if (this.detectPages === undefined) {
+ this.detectPages = !this.anyPages;
+ }
+
+ if (this.detectPages) {
+ if (isPage(url, status, mime)) {
+ const title = url;
+ this.addPage({url, date, title});
+ }
+ }
+
+ const ts = new Date(date).getTime();
+
+ const respHeaders = Object.fromEntries(headers.entries());
+
+ const digest = record.warcPayloadDigest;
+
+ const payload = record.payload;
+ const reader = payload ? null : record.reader;
+
+ const entry = {url, ts, status, mime, respHeaders, reqHeaders, digest, payload, reader, referrer};
+
+ if (this.pageMap[ts + "/" + url] && payload && mime.startsWith("text/")) {
+ this.pageMap[ts + "/" + url].textPromise = extractText(
+ url, payload,
+ headers.get("content-encoding"),
+ headers.get("transfer-encoding")
+ );
+ }
+
+ const extraMetadata = record.warcHeader("WARC-JSON-Metadata");
+
+ if (extraMetadata) {
+ try {
+ entry.extraOpts = JSON.parse(extraMetadata);
+ } catch (e) {
+ // ignore error on extraOpts
+ }
+ }
+
+ const pageId = record.warcHeader("WARC-Page-ID");
+
+ if (pageId) {
+ entry.pageId = pageId;
+ }
+
+ if (this.sourceExtra) {
+ entry.source = this.sourceExtra;
+ }
+
+ if (method !== "GET" && requestUrl && requestBody !== null) {
+ entry.requestUrl = requestUrl;
+ entry.method = method;
+ entry.requestBody = requestBody;
+ }
+
+ return entry;
+ }
+
+ isFullRangeRequest(headers) {
+ const range = headers.get("content-range");
+
+ const cl = parseInt(headers.get("content-length") || 0);
+
+ const fullRange = `bytes 0-${cl-1}/${cl}`;
+
+ // full range is range exists and matches expected full range
+ return range && range === fullRange;
+ }
+
+ filterRecord() {
+ return null;
+ }
+
+ async load(db, progressUpdate, totalSize) {
+ this.db = db;
+
+ const parser = new w(this.reader);
+
+ let lastUpdate = 0, updateTime = 0;
+ let count = 0;
+
+ try {
+ for await (const record of parser) {
+ count++;
+
+ if (!record.warcType) {
+ console.log("skip empty record");
+ continue;
+ }
+
+ if (self.interruptLoads && this.loadId && self.interruptLoads[this.loadId]) {
+ progressUpdate(Math.round((parser.offset / totalSize) * 95.0), "Loading Canceled", parser.offset, totalSize);
+ self.interruptLoads[this.loadId]();
+ if (this.abort) {
+ this.abort.abort();
+ }
+ throw new Canceled();
+ }
+
+ updateTime = new Date().getTime();
+ if ((updateTime - lastUpdate) > 500) {
+ const extraMsg = `Processed ${count} records`;
+ progressUpdate(Math.round((parser.offset / totalSize) * 95.0), null, parser.offset, totalSize, null, extraMsg);
+ lastUpdate = updateTime;
+ }
+
+ const skipMode = this.filterRecord(record);
+ if (skipMode === "done") {
+ if (this.abort) {
+ this.abort.abort();
+ }
+ break;
+ } else if (skipMode === "skip") {
+ continue;
+ }
+
+ if (skipMode === "skipContent") {
+ await record.skipFully();
+ } else {
+ await record.readFully();
+ }
+
+ count++;
+
+ this.index(record, parser);
+
+ if (this.promises.length > 0) {
+ try {
+ await Promise.all(this.promises);
+ } catch (e) {
+ console.warn(e.toString());
+ }
+ this.promises = [];
+ }
+ }
+ } catch(e) {
+ if (e instanceof Canceled) {
+ throw e;
+ }
+
+ progressUpdate(Math.round((parser.offset / totalSize) * 95.0),
+ `Sorry there was an error downloading. Please try again (${e})`,
+ parser.offset, totalSize);
+
+ console.warn(e);
+ }
+
+ this.indexDone(parser);
+
+ progressUpdate(95, null, parser.offset, totalSize);
+
+ await this.finishIndexing();
+
+ progressUpdate(100, null, totalSize, totalSize);
+
+ return this.metadata;
+ }
+
+ async _finishLoad() {
+ if (this.pages.length) {
+ for (const {page, textPromise} of Object.values(this.pageMap)) {
+ if (textPromise) {
+ try {
+ page.text = await textPromise;
+ } catch (e) {
+ console.warn("Error adding text: " + e.toString());
+ }
+ }
+ }
+ this.promises.push(this.db.addPages(this.pages));
+ }
+
+ if (this.lists.length) {
+ this.promises.push(this.db.addCuratedPageLists(this.lists, "bookmarks", "public"));
+ }
+ }
+}
+
+
+// ===========================================================================
+function isPage(url, status, mime) {
+ if (status != 200) {
+ return false;
+ }
+
+ if (!url.startsWith("http:") && !url.startsWith("https:") && !url.startsWith("blob:")) {
+ return false;
+ }
+
+ if (url.endsWith("/robots.txt")) {
+ return false;
+ }
+
+ // skip urls with long query
+ const parts = url.split("?", 2);
+
+ if (parts.length === 2 && parts[1].length > parts[0].length) {
+ return false;
+ }
+
+ // skip 'files' starting with '.' from being listed as pages
+ if (parts[0].substring(parts[0].lastIndexOf("/") + 1).startsWith(".")) {
+ return false;
+ }
+
+ if (mime && mime !== "text/html") {
+ return false;
+ }
+
+ return true;
+}
+
+
+// ===========================================================================
+class SingleRecordWARCLoader extends WARCLoader
+{
+ constructor(reader) {
+ super(reader);
+ this.detectPages = false;
+ }
+
+ addPage() {}
+
+ async load() {
+ const record = await new w(this.reader).parse();
+
+ if (!record) {
+ return null;
+ }
+
+ const entry = this.parseRecords(record, null);
+
+ if (!entry || record.warcType === "revisit") {
+ await record.readFully();
+ }
+
+ return entry;
+ }
+}
+
+
+// ===========================================================================
+class WARCInfoOnlyWARCLoader extends (/* unused pure expression or super */ null && (WARCLoader))
+{
+ filterRecord(record) {
+ if (record.warcType != "warcinfo") {
+ return "done";
+ }
+ }
+}
+
+
+
+;// CONCATENATED MODULE: ./node_modules/auto-js-ipfs/util.js
+/* global Response, ReadableStream, FormData, Headers, Blob */
+
+const BRAVE_PORTS = (/* unused pure expression or super */ null && ([45001, 45002, 45003, 45004, 45005]))
+const W3S_LINK_URL = 'https://w3s.link/'
+const DEFAULT_GATEWAY = W3S_LINK_URL
+
+function parseIPFSURL (url) {
+ const { hostname, protocol, pathname } = new URL(url)
+
+ const type = protocol.slice(0, -1)
+
+ if (!hostname) {
+ const [cid, ...segments] = pathname.slice(2).split('/')
+ const path = '/' + segments.join('/')
+ return { type, cid, path }
+ }
+ return { type, cid: hostname, path: pathname }
+}
+
+// Might not convert if it's a plain string
+// Used for appending to form data
+async function autoBlob (content) {
+ if (isStream(content)) {
+ const blob = await streamToBlob(content)
+ return blob
+ } else if (isIterator(content)) {
+ const stream = iteratorToStream(content)
+ const blob = await streamToBlob(stream)
+ return blob
+ } else if (content instanceof Blob) {
+ return content
+ } else {
+ return new Blob([content])
+ }
+}
+
+async function autoStream (content) {
+ if (isStream(content)) return content
+ if (isIterator(content)) return iteratorToStream(content)
+ /* if (typeof content.stream === 'function') {
+ // Probably a Blob or a File
+ return content.stream()
+ } */
+ // Probably a string or something
+ return content
+}
+
+async function streamToBlob (stream) {
+ const response = new Response(stream)
+ return response.blob()
+}
+
+async function * streamToIterator (stream) {
+ const reader = await stream.getReader()
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) return
+ yield value
+ }
+ } finally {
+ reader.releaseLock()
+ }
+}
+
+function iteratorToStream (iterable) {
+ let iterator = iterable
+ if (!iterator.next) {
+ iterator = iterable[Symbol.asyncIterator]()
+ }
+ const encoder = new TextEncoder()
+ return new ReadableStream({
+ async pull (controller) {
+ const { value, done } = await iterator.next()
+
+ if (done) {
+ await controller.close()
+ } else {
+ let toSend = value
+ if (typeof toSend === 'string') {
+ toSend = encoder.encode(toSend)
+ }
+ await controller.enqueue(toSend)
+ }
+ }
+ })
+}
+
+async function checkError (response) {
+ if (!response.ok) {
+ const error = await response.text()
+ const status = response.status
+ throw new Error(`HTTP Error ${status}: ${error}`)
+ }
+}
+
+async function postRawBody ({
+ url,
+ fileIterator,
+ signal
+}) {
+ const headers = new Headers()
+
+ headers.set('Content-Type', 'application/octet-stream')
+
+ addAuthorizationHeader(url, headers)
+
+ const body = await autoStream(fileIterator)
+
+ const duplex = 'half'
+
+ const response = await fetch(url, {
+ method: 'POST',
+ signal,
+ body,
+ headers,
+ duplex,
+ })
+
+ await checkError(response)
+
+ return response
+}
+
+async function postFormFile ({
+ url,
+ file,
+ fileName = '',
+ parameterName = 'file',
+ fetch = globalThis.fetch,
+ signal
+}) {
+ const body = new FormData()
+ const headers = new Headers()
+
+ addAuthorizationHeader(url, headers)
+
+ const content = await autoBlob(file)
+
+ if (fileName) {
+ body.append(parameterName, content, fileName)
+ } else {
+ body.append(parameterName, content)
+ }
+
+ const response = await fetch(url, {
+ method: 'POST',
+ body,
+ headers,
+ signal
+ })
+
+ await checkError(response)
+
+ return response
+}
+
+function isStream (content) {
+ return typeof content.getReader === 'function'
+}
+
+function isIterator (content) {
+ return content[Symbol.asyncIterator]
+ // || content[Symbol.iterator]
+}
+
+function addAuthorizationHeader (url, headers) {
+ if (url.password) {
+ if (url.username) {
+ const encoded = btoa(`${unescape(url.username)}:${unescape(url.password)}`)
+ const auth = `Basic ${encoded}`
+ headers.append('Authorization', unescape(auth))
+ url.username = ''
+ url.password = ''
+ } else {
+ // If we just have a password, it's for a bearer token
+ const token = url.password
+ const auth = `Bearer ${token}`
+ headers.append('Authorization', unescape(auth))
+ url.password = ''
+ }
+ }
+}
+
+async function getSizeFromURL ({
+ url,
+ fetch = globalThis.fetch,
+ signal
+}) {
+ const response = await fetch(url, {
+ method: 'HEAD',
+ signal
+ })
+
+ await checkError(response)
+
+ const lengthHeader = response.headers.get('x-ipfs-datasize') || response.headers.get('Content-Length')
+
+ return parseInt(lengthHeader, 10)
+}
+
+async function * getFromURL ({
+ url,
+ start,
+ end,
+ format,
+ signal,
+ fetch = globalThis.fetch
+}) {
+ const headers = new Headers()
+ if (Number.isInteger(start)) {
+ if (Number.isInteger(end)) {
+ headers.set('Range', `bytes=${start}-${end}`)
+ } else {
+ headers.set('Range', `bytes=${start}-`)
+ }
+ }
+
+ const toFetch = new URL(url)
+
+ if (format) {
+ headers.set('Accept', `application/vnd.ipld.${format}`)
+ headers.set('cache-control', 'no-cache')
+ }
+
+ const response = await fetch(toFetch.href, {
+ headers,
+ signal
+ })
+
+ await checkError(response)
+
+ yield * streamToIterator(response.body)
+}
+
+function toGatewayURL (url, gatewayBaseURL = detectDefaultGateway()) {
+ const { cid, path, type } = parseIPFSURL(url)
+
+ const relative = `/${type}/${cid}${path}`
+ const toFetch = new URL(relative, gatewayBaseURL)
+
+ return toFetch
+}
+
+async function * getFromGateway ({
+ url,
+ start,
+ end,
+ format,
+ signal,
+ gatewayURL = detectDefaultGateway()
+}) {
+ const toFetch = toGatewayURL(url, gatewayURL, format)
+
+ yield * getFromURL({
+ url: toFetch,
+ start,
+ end,
+ format,
+ signal
+ })
+}
+
+function detectDefaultGateway () {
+ if (!globalThis.location) return DEFAULT_GATEWAY
+ const { pathname, hostname, protocol } = globalThis.location
+ const isOnGatewayPath = pathname.startsWith('/ipfs/') || pathname.startsWith('/ipns/')
+
+ if (isOnGatewayPath) {
+ return `${protocol}//${hostname}/`
+ }
+
+ const [subdomain, ...segments] = hostname.split('.')
+
+ // If the first subdomain is about the length of a CID it's probably a gateway?
+ const isGatewaySubdomain = subdomain.length === 59 && segments.length >= 2
+
+ if (isGatewaySubdomain) {
+ return `${protocol}//${segments.join('.')}/`
+ }
+
+ return DEFAULT_GATEWAY
+}
+
+;// CONCATENATED MODULE: ./node_modules/auto-js-ipfs/index.js
+/* global fetch, Blob */
+
+
+
+
+let debug = false
+
+function setDebug (shouldDebug = true) {
+ debug = shouldDebug
+}
+
+const KNOWN_DAEMON_PORTS = [5001, 45001, 45002, 45003, 45004, 45005]
+const WEB3_STORAGE_URL = 'https://api.web3.storage/'
+const ESTUARY_URL = 'https://api.estuary.tech/'
+const DEFAULT_DAEMON_API_URL = 'http://localhost:5001/'
+const DEFAULT_TIMEOUT = 1000
+const AGREGORE_TYPE = 'agregore'
+const DAEMON_TYPE = 'daemon'
+const WEB3_STORAGE_TYPE = 'web3.storage'
+const ESTUARY_TYPE = 'estuary'
+const READONLY_TYPE = 'readonly'
+const INVALID_TYPE = 'invalid'
+const CHOOSE_ORDER = [
+ AGREGORE_TYPE,
+ DAEMON_TYPE,
+ WEB3_STORAGE_TYPE,
+ ESTUARY_TYPE,
+ READONLY_TYPE
+]
+
+class API {
+ get type () {
+ return INVALID_TYPE
+ }
+
+ async * get (url, { start, end, signal = null, format = null } = {}) {
+ throw new Error('Not Implemented')
+ }
+
+ async getSize (url, signal = null) {
+ throw new Error('Not Implemented')
+ }
+
+ async uploadCAR (carFileIterator, signal = null) {
+ throw new Error('Not Implemented')
+ }
+
+ async uploadFile (carFileIterator, fileName, signal = null) {
+ throw new Error('Not Implemented')
+ }
+
+ async clear (url, signal = null) {
+ throw new Error('Not Implemented')
+ }
+}
+
+async function detect ({
+ daemonURL,
+ web3StorageToken,
+ web3StorageURL = WEB3_STORAGE_URL,
+ estuaryToken,
+ estuaryURL = ESTUARY_URL,
+ publicGatewayURL = detectDefaultGateway(),
+ readonly = true,
+ timeout = DEFAULT_TIMEOUT,
+ fetch = globalThis.fetch
+} = {}) {
+ const options = []
+
+ const toAttempt = []
+
+ toAttempt.push(
+ detectAgregoreFetch(fetch)
+ .then(detected => detected && options.push({ type: AGREGORE_TYPE, fetch }))
+ )
+
+ toAttempt.push(
+ detectAllDaemons(fetch)
+ .then(detected => detected && options.push({ type: DAEMON_TYPE, url: detected, fetch }))
+ )
+
+ if (daemonURL) {
+ toAttempt.push(
+ detectDaemon(daemonURL, timeout, fetch)
+ .then(detected => detected && options.push({ type: DAEMON_TYPE, url: daemonURL, fetch }))
+ )
+ }
+
+ if (estuaryToken) {
+ const url = estuaryURL
+ const authorization = estuaryToken
+ options.push({ type: ESTUARY_TYPE, url, authorization, fetch, publicGatewayURL })
+ }
+
+ if (web3StorageToken) {
+ const url = web3StorageURL
+ const authorization = web3StorageToken
+ options.push({ type: WEB3_STORAGE_TYPE, url, authorization, fetch, publicGatewayURL })
+ }
+
+ if (readonly && publicGatewayURL) {
+ options.push({ type: READONLY_TYPE, fetch, publicGatewayURL })
+ }
+
+ await Promise.allSettled(toAttempt)
+
+ return options
+}
+
+async function create ({ chooseOrder = CHOOSE_ORDER, ...opts } = {}) {
+ const options = await detect(opts)
+
+ const chosen = defaultChoice(options, chooseOrder)
+
+ return choose(chosen)
+}
+
+function defaultChoice (options, chooseOrder = CHOOSE_ORDER) {
+ const sorted = options
+ .filter(({ type }) => chooseOrder.includes(type))
+ .sort(({ type: type1 }, { type: type2 }) => chooseOrder.indexOf(type1) - chooseOrder.indexOf(type2))
+
+ const chosen = sorted[0]
+ if (!chosen) throw new Error('Unable to find valid type')
+
+ return chosen
+}
+
+async function choose (option) {
+ const { type } = option
+ let api = null
+ if (type === AGREGORE_TYPE) {
+ api = new AgregoreAPI(option.fetch || globalThis.fetch)
+ } else if (type === DAEMON_TYPE) {
+ api = new DaemonAPI(option.url)
+ } else if (type === WEB3_STORAGE_TYPE) {
+ api = new Web3StorageAPI(option.authorization, option.url, option.publicGatewayURL)
+ } else if (type === ESTUARY_TYPE) {
+ api = new EstuaryAPI(option.authorization, option.url, option.publicGatewayURL)
+ } else if (type === READONLY_TYPE) {
+ api = new ReadonlyGatewayAPI(option.publicGatewayURL)
+ } else {
+ throw new TypeError(`Unknown API type: ${type}.`)
+ }
+
+ return api
+}
+
+class ReadonlyGatewayAPI extends API {
+ constructor (gatewayURL = detectDefaultGateway()) {
+ super()
+ this.gatewayURL = gatewayURL
+ }
+
+ get type () {
+ return READONLY_TYPE
+ }
+
+ async * get (url, { start, end, signal = null, format = null } = {}) {
+ yield * getFromGateway({
+ url,
+ start,
+ end,
+ format,
+ gatewayURL: this.gatewayURL,
+ signal
+ })
+ }
+
+ async getSize (url, signal = null) {
+ const { cid, path, type } = parseIPFSURL(url)
+
+ const relative = `/${type}/${cid}${path}`
+ const toFetch = new URL(relative, this.gatewayURL)
+
+ return getSizeFromURL({
+ url: toFetch,
+ signal
+ })
+ }
+}
+
+class EstuaryAPI extends ReadonlyGatewayAPI {
+ constructor (authorization, url = ESTUARY_URL, gatewayURL = detectDefaultGateway()) {
+ super(gatewayURL)
+ this.authorization = authorization
+ this.url = url
+ }
+
+ get type () {
+ return ESTUARY_TYPE
+ }
+
+ async uploadCAR (carFileIterator, signal = null) {
+ throw new Error('Not Implemented')
+ }
+
+ async uploadFile (fileIterator, fileName, signal = null) {
+ const toFetch = new URL('/content/add', this.url)
+ toFetch.password = this.authorization
+
+ const response = await postFormFile({
+ url: toFetch,
+ file: fileIterator,
+ fileName,
+ parameterName: 'data',
+ signal
+ })
+
+ const { cid } = await response.json()
+
+ return `ipfs://${cid}/`
+ }
+}
+
+class AgregoreAPI extends API {
+ constructor (fetch = globalThis.fetch) {
+ super()
+ this.fetch = fetch
+ }
+
+ get type () {
+ return AGREGORE_TYPE
+ }
+
+ async * get (url, { start, end, signal = null, format = null } = {}) {
+ const { fetch } = this
+ yield * getFromURL({
+ url,
+ start,
+ end,
+ format,
+ fetch,
+ signal
+ })
+ }
+
+ async getSize (url, signal = null) {
+ const { fetch } = this
+ return getSizeFromURL({
+ url,
+ fetch,
+ signal
+ })
+ }
+
+ async uploadCAR (carFileIterator, signal = null) {
+ // convert to stream if iterator
+ const body = await autoStream(carFileIterator)
+ const { fetch } = this
+ const response = await fetch('ipfs://localhost', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/vnd.ipld.car'
+ },
+ signal,
+ body
+ })
+
+ await checkError(response)
+
+ const results = await response.text()
+
+ return results.split('\n')
+ }
+
+ async uploadFile (fileIterator, signal = null) {
+ const body = await autoStream(fileIterator)
+ const { fetch } = this
+ const response = await fetch('ipfs://localhost', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/octet-stream'
+ },
+ signal,
+ body
+ })
+
+ await checkError(response)
+
+ return response.headers.get('Location')
+ }
+}
+
+class Web3StorageAPI extends ReadonlyGatewayAPI {
+ constructor (authorization, url = WEB3_STORAGE_URL, gatewayURL = detectDefaultGateway()) {
+ super(gatewayURL)
+ this.authorization = authorization
+ this.url = url
+ }
+
+ get type () {
+ return WEB3_STORAGE_TYPE
+ }
+
+ async uploadCAR (carFileIterator, signal = null) {
+ const toFetch = new URL('/car', this.url)
+ toFetch.password = this.authorization
+
+ const response = await postRawBody({
+ url: toFetch,
+ fileIterator: carFileIterator,
+ signal
+ })
+
+ const contents = await response.text()
+ const items = contents.split('\n')
+
+ return items.filter((line) => line).map((line) => {
+ const { cid } = JSON.parse(line)
+ return `ipfs://${cid}/`
+ })
+ }
+
+ async uploadFile (fileIterator, { fileName = '', signal = null } = {}) {
+ const toFetch = new URL('/upload', this.url)
+ toFetch.password = this.authorization
+
+ const response = await postFormFile({
+ url: toFetch,
+ file: fileIterator,
+ fileName,
+ signal
+ })
+
+ const { cid } = await response.json()
+
+ return `ipfs://${cid}/`
+ }
+}
+
+class DaemonAPI extends API {
+ constructor (url = DEFAULT_DAEMON_API_URL) {
+ super()
+ this.url = url
+ }
+
+ get type () {
+ return DAEMON_TYPE
+ }
+
+ async * get (url, { start, end, signal = null, format = null } = {}) {
+ const { cid, path, type } = parseIPFSURL(url)
+ const relative = `/api/v0/cat?arg=/${type}/${cid}${path}`
+ const toFetch = new URL(relative, this.url)
+
+ if (start) {
+ toFetch.searchParams.set('offset', start)
+ }
+ if (end) {
+ toFetch.searchParams.set('length', end - (start || 0) + 1)
+ }
+
+ if (format) {
+ throw new Error('Format is unsupported on Kubo Daemons for now')
+ }
+
+ const response = await fetch(toFetch, {
+ method: 'POST',
+ signal
+ })
+
+ await checkError(response)
+
+ yield * streamToIterator(response.body)
+ }
+
+ async getSize (url, signal = null) {
+ try {
+ const { cid, path, type } = parseIPFSURL(url)
+ const relative = `/api/v0/file/ls?arg=/${type}/${cid}${path}&size=true`
+ const toFetch = new URL(relative, this.url)
+
+ const response = await fetch(toFetch, {
+ method: 'POST',
+ signal
+ })
+
+ await checkError(response)
+
+ const { Objects } = await response.json()
+
+ const [{ Size }] = Object.values(Objects)
+
+ return Size
+ } catch (e) {
+ if (debug) console.warn(e)
+ return this._getSizeWithDag(url, signal)
+ }
+ }
+
+ async _getSizeWithDag (url, signal = null) {
+ const { cid, path, type } = parseIPFSURL(url)
+ const relative = `/api/v0/dag/stat?arg=/${type}/${cid}${path}`
+ const toFetch = new URL(relative, this.url)
+
+ const response = await fetch(toFetch, {
+ method: 'POST',
+ signal
+ })
+
+ await checkError(response)
+
+ const { Size } = await response.json()
+
+ return parseInt(Size, 10)
+ }
+
+ async _pin (url, signal = null) {
+ const { cid, path, type } = parseIPFSURL(url)
+ const relative = `/api/v0/pin/add?arg=/${type}/${cid}${path}`
+ const toFetch = new URL(relative, this.url)
+
+ const response = await fetch(toFetch, {
+ method: 'POST',
+ signal
+ })
+
+ await checkError(response)
+ }
+
+ async _unpin (url, signal = null) {
+ const { cid, path, type } = parseIPFSURL(url)
+ const relative = `/api/v0/pin/rm?arg=/${type}/${cid}${path}`
+ const toFetch = new URL(relative, this.url)
+
+ const response = await fetch(toFetch, {
+ method: 'POST',
+ signal
+ })
+
+ await checkError(response)
+ }
+
+ async clear(url, signal = null) {
+ return this._unpin(url, signal)
+ }
+
+ async uploadCAR (carFileIterator, signal = null) {
+ const relative = '/api/v0/dag/import?allow-big-block=true&pin-roots=true'
+ const toFetch = new URL(relative, this.url)
+
+ const response = await postFormFile({
+ url: toFetch,
+ file: carFileIterator,
+ signal
+ })
+
+ const contents = await response.text()
+ const items = contents.split('\n')
+
+ return items.filter((line) => line).map((line) => {
+ const { Root } = JSON.parse(line)
+ const cid = Root.Cid['/']
+ return `ipfs://${cid}/`
+ })
+ }
+
+ async uploadFile (fileIterator, fileName = '', signal = null) {
+ const relative = '/api/v0/add?pin=true&cid-version=1&inline=false&raw-leaves=true'
+ const toFetch = new URL(relative, this.url)
+
+ const isFile = fileIterator.name && fileIterator instanceof Blob
+ // We should just wrap files or things with a name with a directory
+ if (fileName || isFile) {
+ toFetch.searchParams.set('wrap-with-directory', 'true')
+ }
+
+ const response = await postFormFile({
+ url: toFetch,
+ file: fileIterator,
+ fileName,
+ signal
+ })
+
+ const contents = await response.text()
+ const [line] = contents.split('\n')
+
+ const { Hash: cid } = JSON.parse(line)
+
+ const url = `ipfs://${cid}/`
+
+ await this._pin(url, signal)
+
+ return url
+ }
+}
+
+let hasInterceptedWebRequests = false
+const shouldInterceptWebRequests = !!(
+ globalThis &&
+ globalThis.chrome &&
+ globalThis.chrome.webRequest &&
+ globalThis.chrome.webRequest.onBeforeSendHeaders &&
+ globalThis.chrome.webRequest.onBeforeSendHeaders.addListener
+)
+
+async function detectAllDaemons () {
+ const potentialGateways = KNOWN_DAEMON_PORTS.map((port) => `http://localhost:${port}`)
+ try {
+ // Search all the potential gateways in parallel and return the first valid one
+ const foundGateway = await Promise.any(potentialGateways.map(
+ (gateway) => detectDaemon(gateway).then((exists) => {
+ if (exists) return gateway
+ throw new Error('Not found')
+ })
+ ))
+
+ if (!foundGateway) return false
+
+ if (shouldInterceptWebRequests && !hasInterceptedWebRequests) {
+ interceptWebRequests(foundGateway)
+ }
+
+ return foundGateway
+ } catch {
+ return false
+ }
+}
+
+// This a funky thing that WebRecorder did to bypass cors
+function interceptWebRequests (apiURL) {
+ hasInterceptedWebRequests = true
+ globalThis.chrome.webRequest.onBeforeSendHeaders.addListener((details) => {
+ const { requestHeaders } = details
+
+ for (const header of requestHeaders) {
+ if (header.name.toLowerCase() === 'origin') {
+ header.value = apiURL
+ return { requestHeaders }
+ }
+ }
+
+ details.requestHeaders.push({ name: 'Origin', value: apiURL })
+ return { requestHeaders }
+ },
+ { urls: [apiURL + '/*'] },
+ ['blocking', 'requestHeaders', 'extraHeaders']
+ )
+}
+
+async function detectAgregoreFetch (fetch = globalThis.fetch) {
+ try {
+ // Should throw error if IPFS is not supported
+ // Also throws an error in brave even with IPFS support
+ await fetch('ipfs://localhost/')
+ return true
+ } catch (e) {
+ if (debug) console.warn('Unable to detect Agregore', e)
+ return false
+ }
+}
+
+async function detectDaemon (url = DEFAULT_DAEMON_API_URL, timeout = 1000, fetch = globalThis.fetch) {
+ try {
+ const controller = new AbortController()
+ const { signal } = controller
+ setTimeout(() => controller.abort(), timeout)
+ const response = await fetch(new URL('/api/v0/version', url), {
+ method: 'POST', signal
+ })
+ if (response.ok) return true
+ if (response.status === 405) return true
+ return false
+ } catch (e) {
+ if (debug) console.warn('Unable to detect Kubo Daemon', e, url)
+ return false
+ }
+}
+
+;// CONCATENATED MODULE: ./src/ipfs.js
+// ===========================================================================
+
+
+let autoipfsAPI = null;
+
+async function initAutoIPFS(opts) {
+ if (!autoipfsAPI) {
+ autoipfsAPI = await create(opts);
+ }
+
+ return autoipfsAPI;
+}
+
+;// CONCATENATED MODULE: ./src/blockloaders.js
+
+
+
+
+
+
+// todo: make configurable
+const HELPER_PROXY = "https://helper-proxy.webrecorder.workers.dev";
+
+
+// ===========================================================================
+async function createLoader(opts) {
+ const { url } = opts;
+
+ if (opts.extra && opts.extra.arrayBuffer) {
+ return new ArrayBufferLoader(opts.extra.arrayBuffer);
+ }
+
+ const scheme = url.split(":", 1)[0];
+
+ // built-in loaders
+ switch (scheme) {
+ case "blob":
+ return new BlobCacheLoader(opts);
+
+ case "http":
+ case "https":
+ return new FetchRangeLoader(opts);
+
+ case "file":
+ return new FileHandleLoader(opts);
+
+ case "googledrive":
+ return new GoogleDriveLoader(opts);
+
+ case "ipfs":
+ return new IPFSRangeLoader(opts);
+ }
+
+ // if URL has same scheme as current origin, use regular http fetch
+ try {
+ if (self.location && scheme === self.location.protocol.split(":")[0]) {
+ return new FetchRangeLoader(opts);
+ }
+ } catch (e) {
+ // likely no self and self.location, so ignore
+ }
+
+ // see if the specified scheme is generally fetchable
+ try {
+ await fetch(`${scheme}://localhost`, {method: "HEAD"});
+ // if reached here, scheme is supported, so use fetch loader
+ return new FetchRangeLoader(opts);
+ } catch (e) {
+ // if raised exception, scheme not supported, don't use fetch loader
+ }
+
+ // custom provided loaders
+ throw new Error("Invalid URL: " + url);
+}
+
+// ===========================================================================
+class FetchRangeLoader
+{
+ constructor({url, headers, length = null, canLoadOnDemand = false}) {
+ this.url = url;
+ this.headers = headers || {};
+ this.length = length;
+ this.canLoadOnDemand = canLoadOnDemand;
+ this.isValid = false;
+ this.ipfsAPI = null;
+ this.loadingIPFS = null;
+ }
+
+ async doInitialFetch(tryHead, skipRange = false) {
+ const headers = new Headers(this.headers);
+ if (!skipRange) {
+ headers.set("Range", "bytes=0-");
+ }
+
+ this.isValid = false;
+ let abort = null;
+ let response = null;
+
+ if (tryHead) {
+ try {
+ response = await this.retryFetch(this.url, {headers, method: "HEAD", cache: "no-store"});
+ if (response.status === 200 || response.status == 206) {
+ this.canLoadOnDemand = ((response.status === 206) || response.headers.get("Accept-Ranges") === "bytes");
+ this.isValid = true;
+ }
+ } catch (e) {
+ // ignore fetch failure, considered invalid
+ }
+ }
+
+ if (!this.isValid || !this.canLoadOnDemand) {
+ abort = new AbortController();
+ const signal = abort.signal;
+ response = await this.retryFetch(this.url, {headers, signal, cache: "no-store"});
+ this.canLoadOnDemand = ((response.status === 206) || response.headers.get("Accept-Ranges") === "bytes");
+ this.isValid = (response.status === 206 || response.status === 200);
+
+ // if emulating HEAD, abort here
+ if (tryHead) {
+ abort.abort();
+ abort = null;
+ }
+ }
+
+ if (this.length === null) {
+ this.length = Number(response.headers.get("Content-Length"));
+ if (!this.length && response.status === 206) {
+ let range = response.headers.get("Content-Range");
+ if (range) {
+ range = range.split("/");
+ if (range.length === 2){
+ this.length = range[1];
+ }
+ }
+ }
+ }
+
+ if (this.length === null) {
+ // attempt to get length via proxy
+ try {
+ const resp = await fetch(`${HELPER_PROXY}/c/${this.url}`);
+ const json = await resp.json();
+ if (json.size) {
+ this.length = json.size;
+ }
+ } catch (e) {
+ console.log("Error fetching from helper: " + e.toString());
+ }
+ }
+
+ this.length = Number(this.length || 0);
+
+ return {response, abort};
+ }
+
+ async getLength() {
+ if (this.length === null) {
+ const {abort} = await this.doInitialFetch(true);
+ if (abort) {
+ abort.abort();
+ }
+ }
+ return this.length;
+ }
+
+ async getRange(offset, length, streaming = false, signal = null) {
+ const headers = new Headers(this.headers);
+ headers.set("Range", `bytes=${offset}-${offset + length - 1}`);
+
+ const cache = "no-store";
+
+ const options = {signal, headers, cache};
+
+ let resp = null;
+
+ try {
+ resp = await this.retryFetch(this.url, options);
+ } catch(e) {
+ console.log(e);
+ throw new utils_RangeError(this.url);
+ }
+
+ if (resp.status != 206) {
+ const info = {url: this.url, status: resp.status, resp};
+
+ if (resp.status === 401) {
+ throw new AuthNeededError(info);
+ } else if (resp.status == 403) {
+ throw new AccessDeniedError(info);
+ } else {
+ throw new utils_RangeError(info);
+ }
+ }
+
+ if (streaming) {
+ return resp.body;
+ } else {
+ return new Uint8Array(await resp.arrayBuffer());
+ }
+ }
+
+ async retryFetch(url, options) {
+ let resp = null;
+ let backoff = 1000;
+ for (let count = 0; count < 20; count++) {
+ resp = await fetch(url, options);
+ if (resp.status !== 429) {
+ break;
+ }
+ await sleep(backoff);
+ backoff += 2000;
+ }
+ return resp;
+ }
+}
+
+// ===========================================================================
+class GoogleDriveLoader
+{
+ constructor({url, headers, size, extra}) {
+ this.fileId = url.slice("googledrive://".length);
+ this.apiUrl = `https://www.googleapis.com/drive/v3/files/${this.fileId}?alt=media`;
+ this.canLoadOnDemand = true;
+
+ this.headers = headers;
+ if (extra && extra.publicUrl) {
+ this.publicUrl = extra.publicUrl;
+ } else {
+ this.publicUrl = null;
+ }
+ this.length = size;
+ this.isValid = false;
+ }
+
+ async getLength() {
+ return this.length;
+ }
+
+ async doInitialFetch(tryHead) {
+ let loader = null;
+ let result = null;
+
+ if (this.publicUrl) {
+ loader = new FetchRangeLoader({url: this.publicUrl, length: this.length});
+ try {
+ result = await loader.doInitialFetch(tryHead);
+ } catch(e) {
+ // catch and ignore, considered invalid
+ }
+
+ if (!loader.isValid) {
+ if (result && result.abort) {
+ result.abort.abort();
+ }
+
+ if (await this.refreshPublicUrl()) {
+ loader = new FetchRangeLoader({url: this.publicUrl, length: this.length});
+ try {
+ result = await loader.doInitialFetch(tryHead);
+ } catch(e) {
+ // catch and ignore, considered invalid
+ }
+
+ if (!loader.isValid && result && result.abort) {
+ result.abort.abort();
+ }
+ }
+ }
+ }
+
+ if (!loader || !loader.isValid) {
+ this.publicUrl = null;
+ loader = new FetchRangeLoader({url: this.apiUrl, headers: this.headers, length: this.length});
+ result = await loader.doInitialFetch(tryHead);
+ }
+
+ this.isValid = loader.isValid;
+ if (!this.length) {
+ this.length = loader.length;
+ }
+ return result;
+ }
+
+ async getRange(offset, length, streaming = false, signal) {
+ let loader = null;
+
+ if (this.publicUrl) {
+ loader = new FetchRangeLoader({url: this.publicUrl, length: this.length});
+
+ try {
+ return await loader.getRange(offset, length, streaming, signal);
+ } catch (e) {
+ if (await this.refreshPublicUrl()) {
+ loader = new FetchRangeLoader({url: this.publicUrl, length: this.length});
+ try {
+ return await loader.getRange(offset, length, streaming, signal);
+ } catch (e) {
+ // ignore fetch failure, considered invalid
+ }
+ }
+ }
+
+ //disable public mode?
+ this.publicUrl = null;
+ }
+
+ loader = new FetchRangeLoader({url: this.apiUrl, headers: this.headers, length: this.length});
+
+ let backoff = 50;
+
+ while (backoff < 2000) {
+ try {
+ return await loader.getRange(offset, length, streaming, signal);
+ } catch(e) {
+ if ((e instanceof AccessDeniedError) &&
+ e.info && e.info.resp && e.info.resp.headers.get("content-type").
+ startsWith("application/json")) {
+ const err = await e.info.resp.json();
+ if (err.error && err.error.errors && err.error.errors[0].reason === "userRateLimitExceeded") {
+ console.log(`Exponential backoff, waiting for: ${backoff}`);
+ await sleep(backoff);
+ backoff *= 2;
+ continue;
+ }
+ }
+ throw e;
+ }
+ }
+ }
+
+ async refreshPublicUrl() {
+ try {
+ const resp = await fetch(`${HELPER_PROXY}/g/${this.fileId}`);
+ const json = await resp.json();
+ if (json.url) {
+ this.publicUrl = json.url;
+ return true;
+ }
+ } catch (e) {
+ // ignore, return false
+ }
+
+ return false;
+ }
+}
+
+// ===========================================================================
+class ArrayBufferLoader
+{
+ constructor(arrayBuffer) {
+ this.arrayBuffer = arrayBuffer;
+ this.size = arrayBuffer.length;
+
+ this.canLoadOnDemand = true;
+ }
+
+ get length() {
+ return this.size;
+ }
+
+ get isValid() {
+ return !!this.arrayBuffer;
+ }
+
+ async getLength() {
+ return this.size;
+ }
+
+ async doInitialFetch(tryHead = false) {
+ const stream = tryHead ? null : getReadableStreamFromArray(this.arrayBuffer);
+
+ const response = new Response(stream);
+
+ return {response};
+ }
+
+ async getRange(offset, length, streaming = false/*, signal*/) {
+ const range = this.arrayBuffer.slice(offset, offset + length);
+
+ return streaming ? getReadableStreamFromArray(range) : range;
+ }
+}
+
+
+// ===========================================================================
+class BlobCacheLoader
+{
+ constructor({url, blob = null, size = null}) {
+ this.url = url;
+ this.blob = blob;
+ this.size = this.blob ? this.blob.size : size;
+
+ this.canLoadOnDemand = true;
+ }
+
+ get length() {
+ return this.size;
+ }
+
+ get isValid() {
+ return !!this.blob;
+ }
+
+ async getLength() {
+ if (!this.blob || !this.blob.size) {
+ let response = await fetch(this.url);
+ this.blob = await response.blob();
+ this.size = this.blob.size;
+ }
+ return this.size;
+ }
+
+ async doInitialFetch(tryHead = false) {
+ if (!this.blob) {
+ try {
+ const response = await fetch(this.url);
+ this.blob = await response.blob();
+ this.size = this.blob.size;
+ } catch (e) {
+ console.warn(e);
+ throw e;
+ }
+ }
+
+ this.arrayBuffer = this.blob.arrayBuffer ? await this.blob.arrayBuffer() : await this._getArrayBuffer();
+ this.arrayBuffer = new Uint8Array(this.arrayBuffer);
+
+ const stream = tryHead ? null : getReadableStreamFromArray(this.arrayBuffer);
+
+ const response = new Response(stream);
+
+ return {response};
+ }
+
+ async getRange(offset, length, streaming = false/*, signal*/) {
+ if (!this.arrayBuffer) {
+ await this.doInitialFetch(true);
+ }
+
+ const range = this.arrayBuffer.slice(offset, offset + length);
+
+ return streaming ? getReadableStreamFromArray(range) : range;
+ }
+
+ _getArrayBuffer() {
+ return new Promise((resolve) => {
+ const fr = new FileReader();
+ fr.onloadend = () => {
+ resolve(fr.result);
+ };
+ fr.readAsArrayBuffer(this.blob);
+ });
+ }
+}
+
+// ===========================================================================
+class FileHandleLoader
+{
+ constructor({blob, size, extra, url})
+ {
+ this.url = url;
+ this.file = blob;
+ this.size = this.blob ? this.blob.size : size;
+
+ this.fileHandle = extra.fileHandle;
+
+ this.canLoadOnDemand = true;
+ }
+
+ get length() {
+ return this.size;
+ }
+
+ get isValid() {
+ return !!this.file;
+ }
+
+ async getLength() {
+ if (this.size === undefined) {
+ await this.initFileObject();
+ }
+ return this.size;
+ }
+
+ async initFileObject() {
+ const options = {mode: "read"};
+
+ const curr = await this.fileHandle.queryPermission(options);
+
+ if (curr !== "granted") {
+ const requested = await this.fileHandle.requestPermission(options);
+
+ if (requested !== "granted") {
+ throw new AuthNeededError({fileHandle: this.fileHandle});
+ }
+ }
+
+ this.file = await this.fileHandle.getFile();
+ this.size = this.file.size;
+ }
+
+ async doInitialFetch(tryHead = false) {
+ if (!this.file) {
+ await this.initFileObject();
+ }
+
+ const stream = tryHead ? null : this.file.stream();
+
+ const response = new Response(stream);
+
+ return {response};
+ }
+
+ async getRange(offset, length, streaming = false/*, signal*/) {
+ if (!this.file) {
+ await this.initFileObject();
+ }
+
+ const fileSlice = this.file.slice(offset, offset + length);
+
+ return streaming ? fileSlice.stream() : new Uint8Array(await fileSlice.arrayBuffer());
+ }
+}
+
+// ===========================================================================
+class IPFSRangeLoader
+{
+ constructor({url, headers, ...opts}) {
+ this.url = url;
+ this.opts = opts;
+
+ let inx = url.lastIndexOf("#");
+ if (inx < 0) {
+ inx = undefined;
+ }
+
+ this.headers = headers;
+ this.length = null;
+ this.canLoadOnDemand = true;
+ }
+
+ async getLength() {
+ if (this.length === null) {
+ await this.doInitialFetch(true);
+ }
+
+ return this.length;
+ }
+
+ async doInitialFetch(tryHead) {
+ const autoipfsClient = await initAutoIPFS(this.opts);
+
+ try {
+ this.length = await autoipfsClient.getSize(this.url);
+ this.isValid = (this.length !== null);
+ } catch (e) {
+ console.warn(e);
+ this.length = null;
+ this.isValid = false;
+ }
+
+ let status = 206;
+
+ if (!this.isValid) {
+ status = 404;
+ }
+
+ const abort = new AbortController();
+ const signal = abort.signal;
+ let body;
+
+ if (tryHead || !this.isValid) {
+ body = new Uint8Array([]);
+ } else {
+ const iter = autoipfsClient.get(this.url, {signal});
+ body = getReadableStreamFromIter(iter);
+ }
+
+ const response = new Response(body, {status});
+
+ return {response, abort};
+ }
+
+ async getRange(offset, length, streaming = false, signal = null) {
+ const autoipfsClient = await initAutoIPFS(this.opts);
+
+ const iter = autoipfsClient.get(this.url, {
+ start: offset,
+ end: offset + length - 1,
+ signal
+ });
+
+ if (streaming) {
+ return getReadableStreamFromIter(iter);
+ } else {
+ const chunks = [];
+ let size = 0;
+
+ for await (const chunk of iter) {
+ chunks.push(chunk);
+ size += chunk.byteLength;
+ }
+
+ return y(chunks, size);
+ }
+ }
+}
+
+function getReadableStreamFromIter(stream) {
+ return new ReadableStream({
+ start: async (controller) => {
+ try {
+ for await (const chunk of stream) {
+ controller.enqueue(chunk);
+ }
+ } catch (e) {
+ console.log(e);
+ }
+ controller.close();
+ }
+ });
+}
+
+function getReadableStreamFromArray(array) {
+ return new ReadableStream({
+ start(controller) {
+ controller.enqueue(array);
+ controller.close();
+ }
+ });
+}
+
+
+
+;// CONCATENATED MODULE: ./src/remotearchivedb.js
+
+
+
+
+
+
+
+// ===========================================================================
+class OnDemandPayloadArchiveDB extends ArchiveDB
+{
+ constructor(name, noCache = false) {
+ super(name);
+ this.noCache = noCache;
+
+ this.useRefCounts = !noCache;
+
+ this.streamMap = new Map();
+ }
+
+ async loadRecordFromSource(cdx) {
+ const responseStream = await this.loadSource(cdx.source);
+
+ const loader = new SingleRecordWARCLoader(responseStream);
+
+ const remote = await loader.load();
+ return {remote};
+ }
+
+ async loadPayload(cdx, opts) {
+ let payload = await super.loadPayload(cdx, opts);
+ if (payload) {
+ if (cdx.respHeaders && (cdx.mime !== "warc/revisit" || (cdx.status >= 300 && cdx.status < 400))) {
+ return payload;
+ }
+ }
+
+ const chunkstore = this.streamMap.get(cdx.url);
+ if (chunkstore) {
+ console.log(`Reuse stream for ${cdx.url}`);
+ return new PartialStreamReader(chunkstore);
+ }
+
+ const {remote, hasher} = await this.loadRecordFromSource(cdx);
+
+ if (!remote) {
+ console.log(`No WARC Record Loaded for: ${cdx.url}`);
+ return null;
+ }
+
+ if (remote.url !== cdx.url && !(cdx.method && cdx.url.startsWith(remote.url))) {
+ console.log(`Wrong url: expected ${cdx.url}, got ${remote.url}`);
+ return null;
+ }
+
+ if (remote.ts !== cdx.ts) {
+ const rounded = Math.floor(remote.ts / 1000) * 1000;
+ if (rounded !== cdx.ts) {
+ console.log(`Wrong timestamp: expected ${cdx.ts}, got ${remote.ts}`);
+ return null;
+ }
+ }
+
+ if (remote.digest !== cdx.digest && cdx.digest && remote.digest) {
+ const remoteDigestParts = remote.digest.split(":");
+ const cdxDigestParts = cdx.digest.split(":");
+ if (remoteDigestParts.length === 2 && cdxDigestParts.length === 2 &&
+ cdxDigestParts[1] === remoteDigestParts[1]) {
+ cdx.digest = remoteDigestParts[0] + ":" + cdxDigestParts[1];
+ } else {
+ console.log(`Wrong digest: expected ${cdx.digest}, got ${remote.digest}`);
+ }
+ //return null;
+ }
+
+ // Revisit
+ if (remote.origURL) {
+ // optimize: if revisit of redirect, just set the respHeaders and return empty payload
+ if (!payload && cdx.status >= 300 && cdx.status < 400 && remote.respHeaders) {
+ cdx.respHeaders = remote.respHeaders;
+ if (!this.noCache) {
+ try {
+ await this.db.put("resources", cdx);
+ } catch(e) {
+ console.log(e);
+ }
+ }
+ return new Uint8Array([]);
+ }
+
+ const origResult = await this.lookupUrl(remote.origURL, remote.origTS, {...opts, noRevisits: true});
+ if (!origResult) {
+ return null;
+ }
+
+ const depth = opts && opts.depth || 0;
+
+ if (!payload) {
+ if (depth < 2) {
+ payload = await this.loadPayload(origResult, {...opts, depth: depth + 1});
+ } else {
+ console.warn("Avoiding revisit lookup loop for: " + JSON.stringify(remote));
+ }
+ if (!payload) {
+ return null;
+ }
+ }
+
+ // if revisit record has header, use those, otherwise use headers from original
+ cdx.respHeaders = remote.respHeaders ? remote.respHeaders : origResult.respHeaders;
+ cdx.mime = origResult.mime;
+
+ if (origResult.extraOpts) {
+ cdx.extraOpts = origResult.extraOpts;
+ }
+
+ // update revisit data if cacheing
+ if (!this.noCache) {
+ // don't store in resources db
+ delete cdx.payload;
+
+ try {
+ await this.db.put("resources", cdx);
+ } catch(e) {
+ console.log(e);
+ }
+
+ // cache here only if somehow the digests don't match (wrong digest from previous versions?)
+ if (origResult.digest !== remote.digest && !payload[Symbol.asyncIterator]) {
+ await this.commitPayload(payload, remote.digest);
+ }
+ }
+
+ return payload;
+ }
+
+ const digest = remote.digest;
+
+ if (!this.noCache && remote.reader && digest) {
+ remote.reader = new PayloadBufferingReader(this, remote.reader, digest, cdx.url, this.streamMap, hasher, cdx.recordDigest, cdx.source);
+ }
+
+ payload = remote.payload;
+
+ if (!payload && !remote.reader) {
+ return null;
+ }
+
+ // Update payload if cacheing
+ try {
+ if (payload && !this.noCache) {
+ await this.commitPayload(payload, digest);
+ }
+ } catch(e) {
+ console.warn(`Payload Update Error: ${cdx.url}`);
+ console.warn(e);
+ }
+
+ // Update resources if headers or digest missing
+ if (!cdx.respHeaders || !cdx.digest) {
+ cdx.respHeaders = remote.respHeaders;
+ cdx.digest = digest;
+ if (remote.extraOpts) {
+ cdx.extraOpts = remote.extraOpts;
+ }
+
+ if (!this.noCache) {
+ try {
+ await this.db.put("resources", cdx);
+ } catch (e) {
+ console.warn(`Resource Update Error: ${cdx.url}`);
+ console.warn(e);
+ }
+ }
+ }
+
+ return payload ? payload : remote.reader;
+ }
+
+ async commitPayload(payload, digest) {
+ if (!payload || payload.length === 0) {
+ return;
+ }
+
+ const tx = this.db.transaction(["payload", "digestRef"], "readwrite");
+
+ try {
+ //const payloadEntry = await tx.objectStore("payload").get(digest);
+ //payloadEntry.payload = payload;
+ tx.objectStore("payload").put({payload, digest});
+
+ if (this.useRefCounts) {
+ const ref = await tx.objectStore("digestRef").get(digest);
+ if (ref) {
+ ref.size = payload.length;
+ tx.objectStore("digestRef").put(ref);
+ }
+ }
+
+ await tx.done;
+
+ } catch (e) {
+ console.warn("Payload Commit Error: " + e);
+ }
+ }
+}
+
+
+// ===========================================================================
+class RemoteSourceArchiveDB extends OnDemandPayloadArchiveDB
+{
+ constructor(name, loader, noCache = false) {
+ super(name, noCache);
+
+ this.loader = loader;
+ }
+
+ updateHeaders(headers) {
+ this.loader.headers = headers;
+ }
+
+ async loadSource(source) {
+ const { start, length } = source;
+
+ return await this.loader.getRange(start, length, true);
+ }
+}
+
+
+// ===========================================================================
+class RemotePrefixArchiveDB extends OnDemandPayloadArchiveDB
+{
+ constructor(name, remoteUrlPrefix, headers, noCache = false) {
+ super(name, noCache);
+
+ this.remoteUrlPrefix = remoteUrlPrefix;
+ this.headers = headers;
+ }
+
+ updateHeaders(headers) {
+ this.headers = headers;
+ }
+
+ async loadSource(source) {
+ const { start, length } = source;
+
+ const headers = new Headers(this.headers);
+ const url = new URL(source.path, this.remoteUrlPrefix).href;
+
+ const loader = await createLoader(url, headers);
+
+ return await loader.getRange(start, length, true);
+ }
+}
+
+
+// ===========================================================================
+class PartialStreamReader extends h
+{
+ constructor(chunkstore) {
+ super();
+ this.chunkstore = chunkstore;
+ this.offset = 0;
+ this.size = this.chunkstore.totalLength;
+ }
+
+ setLimitSkip(limit = -1, skip = 0) {
+ this.offset = skip;
+ if (limit > 0) {
+ this.size = limit;
+ }
+ }
+
+ setRangeAll(length) {
+ this.size = length;
+ }
+
+ getReadableStream() {
+ console.log(`Offset: ${this.offset}, Size: ${this.size}`);
+
+ const reader = this.chunkstore.getChunkIter();
+
+ const limitreader = new m(reader, this.size, this.offset);
+ return limitreader.getReadableStream();
+ }
+}
+
+// ===========================================================================
+class ChunkStore
+{
+ constructor(totalLength) {
+ this.chunks = [];
+ this.size = 0;
+ this.done = false;
+ this.totalLength = totalLength;
+
+ this.nextChunk = new Promise(resolve => this._nextResolve = resolve);
+ }
+
+ add(chunk) {
+ this.chunks.push(chunk);
+ this.size += chunk.byteLength;
+ this._nextResolve(true);
+ this.nextChunk = new Promise(resolve => this._nextResolve = resolve);
+ }
+
+ concatChunks() {
+ this._nextResolve(false);
+ this.done = true;
+
+ return y(this.chunks, this.size);
+ }
+
+ async* getChunkIter() {
+ for (const chunk of this.chunks) {
+ yield chunk;
+ }
+
+ let i = this.chunks.length;
+
+ while (!this.done) {
+ if (!await this.nextChunk) {
+ break;
+ }
+
+ for (i; i < this.chunks.length; i++) {
+ yield this.chunks[i];
+ }
+ }
+ }
+}
+
+
+// ===========================================================================
+class PayloadBufferingReader extends h
+{
+ constructor(db, reader, digest, url = "", streamMap, hasher, expectedHash, source) {
+ super();
+ this.db = db;
+ this.reader = reader;
+
+ this.digest = digest;
+ this.url = url;
+
+ this.commit = true;
+ this.fullbuff = null;
+
+ this.hasher = hasher;
+ this.expectedHash = expectedHash;
+ this.source = source;
+
+ this.isRange = false;
+ this.totalLength = -1;
+
+ this.streamMap = streamMap;
+ }
+
+ setRangeAll(length) {
+ this.isRange = true;
+ this.totalLength = length;
+ }
+
+ setLimitSkip(limit = -1, skip = 0) {
+ this.isRange = true;
+
+ if (limit === 2 && skip === 0) {
+ this.fixedSize = 2;
+ return;
+ }
+
+ if (limit != -1 || skip > 0) {
+ this.commit = false;
+ }
+ this.reader.setLimitSkip(limit, skip);
+ }
+
+ async* [Symbol.asyncIterator]() {
+ let chunkstore = null;
+
+ if (this.commit) {
+ chunkstore = new ChunkStore(this.totalLength);
+
+ if (this.isRange) {
+ console.log(`Store stream for ${this.url}, ${this.totalLength}`);
+ this.streamMap.set(this.url, chunkstore);
+ }
+ }
+
+ for await (const chunk of this.reader) {
+ if (chunkstore) {
+ chunkstore.add(chunk);
+ }
+
+ yield chunk;
+ }
+
+ if (this.reader.limit !== 0) {
+ console.warn(`Expected payload not consumed, ${this.reader.limit} bytes left`);
+ } else {
+
+ if (!this.isRange && this.hasher && this.expectedHash && this.source) {
+ const hash = this.hasher.getHash();
+ const {path, start, length} = this.source;
+ const id = `${path}:${start}-${length}`;
+ this.db.addVerifyData(id, this.expectedHash, hash);
+ }
+
+ if (this.commit) {
+ this.fullbuff = chunkstore.concatChunks();
+ await this.db.commitPayload(this.fullbuff, this.digest);
+ }
+ }
+
+ if (this.commit && this.isRange) {
+ this.streamMap.delete(this.url);
+ console.log(`Delete stream for ${this.url}`);
+ }
+ }
+
+ async _consumeIter(iter) {
+ // eslint-disable-next-line no-unused-vars
+ for await (const chunk of iter);
+ }
+
+ async readFully() {
+ if (!this.fullbuff) {
+ // should not set if already false
+ //this.commit = true;
+ await this._consumeIter(this);
+ }
+ return this.fullbuff;
+ }
+
+ getReadableStream() {
+ const stream = super.getReadableStream();
+
+ if (!this.commit) {
+ return stream;
+ }
+
+ // if committing, need to consume entire stream, so tee reader and consume async
+ const tees = stream.tee();
+
+ this._consumeIter(c.fromReadable(tees[1].getReader()));
+
+ // load a single, fixed chunk (only used for 0-1 safari range)
+ if (this.fixedSize) {
+ return this.getFixedSizeReader(tees[0].getReader(), this.fixedSize);
+ } else {
+ return tees[0];
+ }
+ }
+
+ getFixedSizeReader(reader, size) {
+ return new ReadableStream({
+ async start(controller) {
+ const {value, done} = await reader.read();
+ if (!done) {
+ controller.enqueue(value.slice(0, size));
+ }
+ controller.close();
+ reader.close();
+ }
+ });
+ }
+}
+
+
+
+
+
+;// CONCATENATED MODULE: ./src/harloader.js
+
+
+
+// ===========================================================================
+class HARLoader extends BaseParser {
+ constructor(string_or_har) {
+ super();
+ this.har = string_or_har;
+ this.pageRefs = {};
+ }
+
+ async load(db) {
+ this.db = db;
+ if (typeof this.har === "string") {
+ this.har = JSON.parse(this.har);
+ }
+
+ this.parseEntries(this.har);
+
+ this.parsePages(this.har);
+
+ await this.finishIndexing();
+
+ return {};
+ }
+
+ parsePages(har) {
+ for (const page of har.log.pages) {
+ if (!page.pageTimings || !page.pageTimings.onLoad) {
+ continue;
+ }
+
+ let url;
+ if (page.title && (page.title.startsWith("http:") || page.title.startsWith("https:"))) {
+ url = page.title;
+ } else {
+ url = this.pageRefs[page.id];
+ }
+
+ const title = page.title || url;
+
+ const date = page.startedDateTime;
+
+ //this.pageList.push({ "timestamp": getTS(page.startedDateTime), "title": title, "url": url });
+ this.addPage({url, date, title});
+ }
+ }
+
+ parseEntries(har) {
+ for (const entry of har.log.entries) {
+ const ts = new Date(entry.startedDateTime).getTime();
+
+ const respHeaders = {};
+
+ for (const {name, value} of entry.response.headers) {
+ respHeaders[name] = value;
+ }
+
+ let payload = null;
+
+ const encoder = new TextEncoder();
+
+ if (entry.response.content && entry.response.content.text) {
+ try {
+ payload = Uint8Array.from(atob(entry.response.content.text), c => c.charCodeAt(0));
+ } catch (e) {
+ payload = entry.response.content.text;
+ }
+ } else {
+ const cl = respHeaders["Content-Length"];
+ if (cl && cl !== "0") {
+ console.log(`Warning: Content-Length ${cl} but no content found for ${entry.request.url}`);
+ payload = encoder.encode("Sorry, the HAR file did not include the content for this resource.");
+ } else {
+ payload = Uint8Array.from([]);
+ }
+ }
+
+ this.addResource({url: entry.request.url,
+ ts,
+ status: entry.response.status,
+ //statusText: entry.response.statusText,
+ respHeaders,
+ //reqHeaders,
+ payload});
+
+ if (entry.pageref && !this.pageRefs[entry.pageref]) {
+ this.pageRefs[entry.pageref] = entry.request.url;
+ }
+ }
+ }
+}
+
+
+
+
+;// CONCATENATED MODULE: ./src/cdxloader.js
+
+
+
+
+
+
+const CDX_COOKIE = "req.http:cookie";
+
+
+// ===========================================================================
+class CDXFromWARCLoader extends WARCLoader
+{
+ constructor(reader, abort, id, sourceExtra = {}, shaPrefix = "sha256:") {
+ super(reader, abort, id);
+ this.cdxindexer = null;
+ this.sourceExtra = sourceExtra;
+ this.shaPrefix = shaPrefix;
+ }
+
+ filterRecord(record) {
+ switch (record.warcType) {
+ case "warcinfo":
+ case "revisit":
+ case "request":
+ return null;
+
+ case "metadata":
+ return this.shouldIndexMetadataRecord(record) ? null : "skip";
+ }
+
+ const url = record.warcTargetURI;
+ const ts = new Date(record.warcDate).getTime();
+
+ if (this.pageMap[ts + "/" + url]) {
+ record._isPage = true;
+ return null;
+ }
+ }
+
+ index(record, parser) {
+ if (record) {
+ record._offset = parser.offset;
+ record._length = parser.recordLength;
+ }
+ return super.index(record, parser);
+ }
+
+ indexReqResponse(record, reqRecord, parser) {
+ if (record._isPage) {
+ return super.indexReqResponse(record, reqRecord, parser);
+ }
+
+ if (record.warcType === "warcinfo") {
+ this.parseWarcInfo(record);
+ return;
+ }
+
+ if (!this.cdxindexer) {
+ this.cdxindexer = new W({noSurt: true}, null);
+ }
+
+ const cdx = this.cdxindexer.indexRecordPair(record, reqRecord, parser, "");
+
+ if (!cdx) {
+ return;
+ }
+
+ if (cdx.status === 206 && !this.isFullRangeRequest(record.httpHeaders.headers)) {
+ return;
+ }
+
+ if (reqRecord && reqRecord.httpHeaders) {
+ let cookie = reqRecord.httpHeaders.headers.get("cookie");
+ if (cookie) {
+ cdx[CDX_COOKIE] = cookie;
+ }
+ }
+
+ this.addCdx(cdx);
+ }
+
+ getSource(cdx) {
+ return {
+ ...this.sourceExtra,
+ path: cdx.filename,
+ start: Number(cdx.offset),
+ length: Number(cdx.length)
+ };
+ }
+
+ addCdx(cdx) {
+ const { url, mime } = cdx;
+
+ const status = Number(cdx.status) || 200;
+
+ const date = tsToDate(cdx.timestamp);
+ const ts = date.getTime();
+
+ //if (this.detectPages && isPage(url, status, mime)) {
+ // const title = url;
+ // promises.push(this.db.addPage({url, date: date.toISOString(), title}));
+ //}
+
+ const source = this.getSource(cdx);
+
+ let { digest, recordDigest } = cdx;
+ if (digest && digest.indexOf(":") === -1) {
+ digest = this.shaPrefix + digest;
+ }
+
+ const entry = {url, ts, status, digest, recordDigest, mime, loaded: false, source};
+
+ if (cdx.method) {
+ if (cdx.method === "HEAD" || cdx.method === "OPTIONS") {
+ return;
+ }
+ entry.method = cdx.method;
+ }
+
+ if (cdx[CDX_COOKIE]) {
+ entry[CDX_COOKIE] = cdx[CDX_COOKIE];
+ }
+
+ // url with post query appended
+ if (cdx.requestBody) {
+ entry.url = F(cdx.url, cdx.requestBody, cdx.method);
+ }
+
+ this.addResource(entry);
+ }
+}
+
+// ===========================================================================
+class CDXLoader extends CDXFromWARCLoader
+{
+ async load(db, progressUpdate, totalSize) {
+ this.db = db;
+
+ let reader = this.reader;
+
+ if (!reader.iterLines) {
+ reader = new c(this.reader);
+ }
+
+ let numRead = 0;
+
+ for await (const origLine of reader.iterLines()) {
+ let cdx;
+ let urlkey;
+ let timestamp;
+ numRead += origLine.length;
+ let line = origLine.trimEnd();
+
+ if (!line.startsWith("{")) {
+ const inx = line.indexOf(" {");
+ if (inx < 0) {
+ continue;
+ }
+ [urlkey, timestamp] = line.split(" ", 2);
+ line = line.slice(inx);
+ }
+
+ try {
+ cdx = JSON.parse(line);
+ } catch (e) {
+ console.log("JSON Parser error on: " + line);
+ continue;
+ }
+
+ cdx.timestamp = timestamp;
+ if (!cdx.url) {
+ cdx.url = urlkey;
+ console.warn(`URL missing, using urlkey ${urlkey}`);
+ }
+ if (progressUpdate && this.isBatchFull()) {
+ progressUpdate(Math.round((numRead / totalSize) * 100), null, numRead, totalSize);
+ }
+ this.addCdx(cdx);
+ }
+
+ await this.finishIndexing();
+
+ if (progressUpdate) {
+ progressUpdate(100, null, totalSize, totalSize);
+ }
+ }
+}
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/hash-wasm/dist/index.esm.js
+/*!
+ * hash-wasm (https://www.npmjs.com/package/hash-wasm)
+ * (c) Dani Biro
+ * @license MIT
+ */
+
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+
+function __awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+}
+
+class Mutex {
+ constructor() {
+ this.mutex = Promise.resolve();
+ }
+ lock() {
+ let begin = () => { };
+ this.mutex = this.mutex.then(() => new Promise(begin));
+ return new Promise((res) => {
+ begin = res;
+ });
+ }
+ dispatch(fn) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const unlock = yield this.lock();
+ try {
+ return yield Promise.resolve(fn());
+ }
+ finally {
+ unlock();
+ }
+ });
+ }
+}
+
+/* eslint-disable import/prefer-default-export */
+/* eslint-disable no-bitwise */
+var index_esm_a;
+function getGlobal() {
+ if (typeof globalThis !== 'undefined')
+ return globalThis;
+ // eslint-disable-next-line no-restricted-globals
+ if (typeof self !== 'undefined')
+ return self;
+ if (typeof window !== 'undefined')
+ return window;
+ return __webpack_require__.g;
+}
+const globalObject = getGlobal();
+const nodeBuffer = (index_esm_a = globalObject.Buffer) !== null && index_esm_a !== void 0 ? index_esm_a : null;
+const textEncoder = globalObject.TextEncoder ? new globalObject.TextEncoder() : null;
+function intArrayToString(arr, len) {
+ return String.fromCharCode(...arr.subarray(0, len));
+}
+function hexCharCodesToInt(a, b) {
+ return (((a & 0xF) + ((a >> 6) | ((a >> 3) & 0x8))) << 4) | ((b & 0xF) + ((b >> 6) | ((b >> 3) & 0x8)));
+}
+function writeHexToUInt8(buf, str) {
+ const size = str.length >> 1;
+ for (let i = 0; i < size; i++) {
+ const index = i << 1;
+ buf[i] = hexCharCodesToInt(str.charCodeAt(index), str.charCodeAt(index + 1));
+ }
+}
+function hexStringEqualsUInt8(str, buf) {
+ if (str.length !== buf.length * 2) {
+ return false;
+ }
+ for (let i = 0; i < buf.length; i++) {
+ const strIndex = i << 1;
+ if (buf[i] !== hexCharCodesToInt(str.charCodeAt(strIndex), str.charCodeAt(strIndex + 1))) {
+ return false;
+ }
+ }
+ return true;
+}
+const alpha = 'a'.charCodeAt(0) - 10;
+const digit = '0'.charCodeAt(0);
+function getDigestHex(tmpBuffer, input, hashLength) {
+ let p = 0;
+ /* eslint-disable no-plusplus */
+ for (let i = 0; i < hashLength; i++) {
+ let nibble = input[i] >>> 4;
+ tmpBuffer[p++] = nibble > 9 ? nibble + alpha : nibble + digit;
+ nibble = input[i] & 0xF;
+ tmpBuffer[p++] = nibble > 9 ? nibble + alpha : nibble + digit;
+ }
+ /* eslint-enable no-plusplus */
+ return String.fromCharCode.apply(null, tmpBuffer);
+}
+const getUInt8Buffer = nodeBuffer !== null
+ ? (data) => {
+ if (typeof data === 'string') {
+ const buf = nodeBuffer.from(data, 'utf8');
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
+ }
+ if (nodeBuffer.isBuffer(data)) {
+ return new Uint8Array(data.buffer, data.byteOffset, data.length);
+ }
+ if (ArrayBuffer.isView(data)) {
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
+ }
+ throw new Error('Invalid data type!');
+ }
+ : (data) => {
+ if (typeof data === 'string') {
+ return textEncoder.encode(data);
+ }
+ if (ArrayBuffer.isView(data)) {
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
+ }
+ throw new Error('Invalid data type!');
+ };
+const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+const base64Lookup = new Uint8Array(256);
+for (let i = 0; i < base64Chars.length; i++) {
+ base64Lookup[base64Chars.charCodeAt(i)] = i;
+}
+function encodeBase64(data, pad = true) {
+ const len = data.length;
+ const extraBytes = len % 3;
+ const parts = [];
+ const len2 = len - extraBytes;
+ for (let i = 0; i < len2; i += 3) {
+ const tmp = ((data[i] << 16) & 0xFF0000)
+ + ((data[i + 1] << 8) & 0xFF00)
+ + (data[i + 2] & 0xFF);
+ const triplet = base64Chars.charAt((tmp >> 18) & 0x3F)
+ + base64Chars.charAt((tmp >> 12) & 0x3F)
+ + base64Chars.charAt((tmp >> 6) & 0x3F)
+ + base64Chars.charAt(tmp & 0x3F);
+ parts.push(triplet);
+ }
+ if (extraBytes === 1) {
+ const tmp = data[len - 1];
+ const a = base64Chars.charAt(tmp >> 2);
+ const b = base64Chars.charAt((tmp << 4) & 0x3F);
+ parts.push(`${a}${b}`);
+ if (pad) {
+ parts.push('==');
+ }
+ }
+ else if (extraBytes === 2) {
+ const tmp = (data[len - 2] << 8) + data[len - 1];
+ const a = base64Chars.charAt(tmp >> 10);
+ const b = base64Chars.charAt((tmp >> 4) & 0x3F);
+ const c = base64Chars.charAt((tmp << 2) & 0x3F);
+ parts.push(`${a}${b}${c}`);
+ if (pad) {
+ parts.push('=');
+ }
+ }
+ return parts.join('');
+}
+function getDecodeBase64Length(data) {
+ let bufferLength = Math.floor(data.length * 0.75);
+ const len = data.length;
+ if (data[len - 1] === '=') {
+ bufferLength -= 1;
+ if (data[len - 2] === '=') {
+ bufferLength -= 1;
+ }
+ }
+ return bufferLength;
+}
+function decodeBase64(data) {
+ const bufferLength = getDecodeBase64Length(data);
+ const len = data.length;
+ const bytes = new Uint8Array(bufferLength);
+ let p = 0;
+ for (let i = 0; i < len; i += 4) {
+ const encoded1 = base64Lookup[data.charCodeAt(i)];
+ const encoded2 = base64Lookup[data.charCodeAt(i + 1)];
+ const encoded3 = base64Lookup[data.charCodeAt(i + 2)];
+ const encoded4 = base64Lookup[data.charCodeAt(i + 3)];
+ bytes[p] = (encoded1 << 2) | (encoded2 >> 4);
+ p += 1;
+ bytes[p] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
+ p += 1;
+ bytes[p] = ((encoded3 & 3) << 6) | (encoded4 & 63);
+ p += 1;
+ }
+ return bytes;
+}
+
+const MAX_HEAP = 16 * 1024;
+const WASM_FUNC_HASH_LENGTH = 4;
+const wasmMutex = new Mutex();
+const wasmModuleCache = new Map();
+function WASMInterface(binary, hashLength) {
+ return __awaiter(this, void 0, void 0, function* () {
+ let wasmInstance = null;
+ let memoryView = null;
+ let initialized = false;
+ if (typeof WebAssembly === 'undefined') {
+ throw new Error('WebAssembly is not supported in this environment!');
+ }
+ const writeMemory = (data, offset = 0) => {
+ memoryView.set(data, offset);
+ };
+ const getMemory = () => memoryView;
+ const getExports = () => wasmInstance.exports;
+ const setMemorySize = (totalSize) => {
+ wasmInstance.exports.Hash_SetMemorySize(totalSize);
+ const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
+ const memoryBuffer = wasmInstance.exports.memory.buffer;
+ memoryView = new Uint8Array(memoryBuffer, arrayOffset, totalSize);
+ };
+ const getStateSize = () => {
+ const view = new DataView(wasmInstance.exports.memory.buffer);
+ const stateSize = view.getUint32(wasmInstance.exports.STATE_SIZE, true);
+ return stateSize;
+ };
+ const loadWASMPromise = wasmMutex.dispatch(() => __awaiter(this, void 0, void 0, function* () {
+ if (!wasmModuleCache.has(binary.name)) {
+ const asm = decodeBase64(binary.data);
+ const promise = WebAssembly.compile(asm);
+ wasmModuleCache.set(binary.name, promise);
+ }
+ const module = yield wasmModuleCache.get(binary.name);
+ wasmInstance = yield WebAssembly.instantiate(module, {
+ // env: {
+ // emscripten_memcpy_big: (dest, src, num) => {
+ // const memoryBuffer = wasmInstance.exports.memory.buffer;
+ // const memView = new Uint8Array(memoryBuffer, 0);
+ // memView.set(memView.subarray(src, src + num), dest);
+ // },
+ // print_memory: (offset, len) => {
+ // const memoryBuffer = wasmInstance.exports.memory.buffer;
+ // const memView = new Uint8Array(memoryBuffer, 0);
+ // console.log('print_int32', memView.subarray(offset, offset + len));
+ // },
+ // },
+ });
+ // wasmInstance.exports._start();
+ }));
+ const setupInterface = () => __awaiter(this, void 0, void 0, function* () {
+ if (!wasmInstance) {
+ yield loadWASMPromise;
+ }
+ const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
+ const memoryBuffer = wasmInstance.exports.memory.buffer;
+ memoryView = new Uint8Array(memoryBuffer, arrayOffset, MAX_HEAP);
+ });
+ const init = (bits = null) => {
+ initialized = true;
+ wasmInstance.exports.Hash_Init(bits);
+ };
+ const updateUInt8Array = (data) => {
+ let read = 0;
+ while (read < data.length) {
+ const chunk = data.subarray(read, read + MAX_HEAP);
+ read += chunk.length;
+ memoryView.set(chunk);
+ wasmInstance.exports.Hash_Update(chunk.length);
+ }
+ };
+ const update = (data) => {
+ if (!initialized) {
+ throw new Error('update() called before init()');
+ }
+ const Uint8Buffer = getUInt8Buffer(data);
+ updateUInt8Array(Uint8Buffer);
+ };
+ const digestChars = new Uint8Array(hashLength * 2);
+ const digest = (outputType, padding = null) => {
+ if (!initialized) {
+ throw new Error('digest() called before init()');
+ }
+ initialized = false;
+ wasmInstance.exports.Hash_Final(padding);
+ if (outputType === 'binary') {
+ // the data is copied to allow GC of the original memory object
+ return memoryView.slice(0, hashLength);
+ }
+ return getDigestHex(digestChars, memoryView, hashLength);
+ };
+ const save = () => {
+ if (!initialized) {
+ throw new Error('save() can only be called after init() and before digest()');
+ }
+ const stateOffset = wasmInstance.exports.Hash_GetState();
+ const stateLength = getStateSize();
+ const memoryBuffer = wasmInstance.exports.memory.buffer;
+ const internalState = new Uint8Array(memoryBuffer, stateOffset, stateLength);
+ // prefix is 4 bytes from SHA1 hash of the WASM binary
+ // it is used to detect incompatible internal states between different versions of hash-wasm
+ const prefixedState = new Uint8Array(WASM_FUNC_HASH_LENGTH + stateLength);
+ writeHexToUInt8(prefixedState, binary.hash);
+ prefixedState.set(internalState, WASM_FUNC_HASH_LENGTH);
+ return prefixedState;
+ };
+ const load = (state) => {
+ if (!(state instanceof Uint8Array)) {
+ throw new Error('load() expects an Uint8Array generated by save()');
+ }
+ const stateOffset = wasmInstance.exports.Hash_GetState();
+ const stateLength = getStateSize();
+ const overallLength = WASM_FUNC_HASH_LENGTH + stateLength;
+ const memoryBuffer = wasmInstance.exports.memory.buffer;
+ if (state.length !== overallLength) {
+ throw new Error(`Bad state length (expected ${overallLength} bytes, got ${state.length})`);
+ }
+ if (!hexStringEqualsUInt8(binary.hash, state.subarray(0, WASM_FUNC_HASH_LENGTH))) {
+ throw new Error('This state was written by an incompatible hash implementation');
+ }
+ const internalState = state.subarray(WASM_FUNC_HASH_LENGTH);
+ new Uint8Array(memoryBuffer, stateOffset, stateLength).set(internalState);
+ initialized = true;
+ };
+ const isDataShort = (data) => {
+ if (typeof data === 'string') {
+ // worst case is 4 bytes / char
+ return data.length < MAX_HEAP / 4;
+ }
+ return data.byteLength < MAX_HEAP;
+ };
+ let canSimplify = isDataShort;
+ switch (binary.name) {
+ case 'argon2':
+ case 'scrypt':
+ canSimplify = () => true;
+ break;
+ case 'blake2b':
+ case 'blake2s':
+ // if there is a key at blake2 then cannot simplify
+ canSimplify = (data, initParam) => initParam <= 512 && isDataShort(data);
+ break;
+ case 'blake3':
+ // if there is a key at blake3 then cannot simplify
+ canSimplify = (data, initParam) => initParam === 0 && isDataShort(data);
+ break;
+ case 'xxhash64': // cannot simplify
+ case 'xxhash3':
+ case 'xxhash128':
+ canSimplify = () => false;
+ break;
+ }
+ // shorthand for (init + update + digest) for better performance
+ const calculate = (data, initParam = null, digestParam = null) => {
+ if (!canSimplify(data, initParam)) {
+ init(initParam);
+ update(data);
+ return digest('hex', digestParam);
+ }
+ const buffer = getUInt8Buffer(data);
+ memoryView.set(buffer);
+ wasmInstance.exports.Hash_Calculate(buffer.length, initParam, digestParam);
+ return getDigestHex(digestChars, memoryView, hashLength);
+ };
+ yield setupInterface();
+ return {
+ getMemory,
+ writeMemory,
+ getExports,
+ setMemorySize,
+ init,
+ update,
+ digest,
+ save,
+ load,
+ calculate,
+ hashLength,
+ };
+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FBGHZqIgRqIAQgBkEEaigCACIBQf8BcWoiBGogBCABQQh2Qf8BcWoiBGogBCABQRB2Qf8BcWoiBGogBCABQRh2aiIEaiAEIAZBCGooAgAiAUH/AXFqIgRqIAQgAUEIdkH/AXFqIgRqIAQgAUEQdkH/AXFqIgRqIAQgAUEYdmoiBGogBCAGQQxqKAIAIgFB/wFxaiIEaiAEIAFBCHZB/wFxaiIEaiAEIAFBEHZB/wFxaiIEaiAEIAFBGHZqIgJqIQMgBkEQaiEGIABBcGoiAEEPSw0ACyAARQ0BCwNAIAIgBi0AAGoiAiADaiEDIAZBAWohBiAAQX9qIgANAAsLIANB8f8DcCEDIAJB8f8DcCECCyACIANBEHRyIQELQQAgATYChAgLMgEBf0EAQQAoAoQIIgBBGHQgAEEIdEGAgPwHcXIgAEEIdkGA/gNxIABBGHZycjYCgAkLBQBBhAgLPABBAEEBNgKECCAAEAJBAEEAKAKECCIAQRh0IABBCHRBgID8B3FyIABBCHZBgP4DcSAAQRh2cnI2AoAJCwsVAgBBgAgLBAQAAAAAQYQICwQBAAAA";
+var hash$k = "321174b4";
+var wasmJson$k = {
+ name: name$k,
+ data: data$k,
+ hash: hash$k
+};
+
+function lockedCreate(mutex, binary, hashLength) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const unlock = yield mutex.lock();
+ const wasm = yield WASMInterface(binary, hashLength);
+ unlock();
+ return wasm;
+ });
+}
+
+const mutex$l = new Mutex();
+let wasmCache$l = null;
+/**
+ * Calculates Adler-32 hash. The resulting 32-bit hash is stored in
+ * network byte order (big-endian).
+ *
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function adler32(data) {
+ if (wasmCache$l === null) {
+ return lockedCreate(mutex$l, wasmJson$k, 4)
+ .then((wasm) => {
+ wasmCache$l = wasm;
+ return wasmCache$l.calculate(data);
+ });
+ }
+ try {
+ const hash = wasmCache$l.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new Adler-32 hash instance
+ */
+function createAdler32() {
+ return WASMInterface(wasmJson$k, 4).then((wasm) => {
+ wasm.init();
+ const obj = {
+ init: () => { wasm.init(); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 4,
+ digestSize: 4,
+ };
+ return obj;
+ });
+}
+
+var name$j = "blake2b";
+var data$j = "AGFzbQEAAAABEQRgAAF/YAJ/fwBgAX8AYAAAAwoJAAECAwECAgABBAUBcAEBAQUEAQECAgYOAn8BQbCLBQt/AEGACAsHcAgGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAApIYXNoX0ZpbmFsAAMJSGFzaF9Jbml0AAULSGFzaF9VcGRhdGUABg1IYXNoX0dldFN0YXRlAAcOSGFzaF9DYWxjdWxhdGUACApTVEFURV9TSVpFAwEKjzkJBQBBgAkL5QICBH8BfgJAIAFBAUgNAAJAAkACQEGAAUEAKALgigEiAmsiAyABSA0AIAEhAwwBC0EAQQA2AuCKAQJAIAJB/wBKDQBBACEEQQAhBQNAIAQgAmpB4IkBaiAAIARqLQAAOgAAIAMgBUEBaiIFQf8BcSIESg0ACwtBAEEAKQPAiQEiBkKAAXw3A8CJAUEAQQApA8iJASAGQv9+Vq18NwPIiQFB4IkBEAIgACADaiEAAkAgASADayIDQYEBSA0AIAIgAWohBANAQQBBACkDwIkBIgZCgAF8NwPAiQFBAEEAKQPIiQEgBkL/flatfDcDyIkBIAAQAiAAQYABaiEAIARBgH9qIgRBgAJKDQALIARBgH9qIQMLIANBAUgNAQtBACEEQQAhBQNAQQAoAuCKASAEakHgiQFqIAAgBGotAAA6AAAgAyAFQQFqIgVB/wFxIgRKDQALC0EAQQAoAuCKASADajYC4IoBCwu/LgEkfkEAIAApA2AiASAAKQNAIgIgACkDSCIDIAIgACkDGCIEIAApA1giBSAAKQMgIgYgAiAAKQMQI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ACAAOgDwigFBkH4hAANAIABB8IoBakEAOgAAIABBAWoiAyAATyEEIAMhACAEDQALQQAhAEEAQQApA/CKASIFQoiS853/zPmE6gCFNwOAiQFBAEEAKQP4igFCu86qptjQ67O7f4U3A4iJAUEAQQApA4CLAUKr8NP0r+68tzyFNwOQiQFBAEEAKQOIiwFC8e30+KWn/aelf4U3A5iJAUEAQQApA5CLAULRhZrv+s+Uh9EAhTcDoIkBQQBBACkDmIsBQp/Y+dnCkdqCm3+FNwOoiQFBAEEAKQOgiwFC6/qG2r+19sEfhTcDsIkBQQBBACkDqIsBQvnC+JuRo7Pw2wCFNwO4iQFBACAFp0H/AXE2AuSKAQJAIAFBAUgNACACQgA3A3ggAkIANwNwIAJCADcDaCACQgA3A2AgAkIANwNYIAJCADcDUCACQgA3A0ggAkIANwNAIAJCADcDOCACQgA3AzAgAkIANwMoIAJCADcDICACQgA3AxggAkIANwMQIAJCADcDCCACQgA3AwBBACEDA0AgAiAAaiAAQYAJai0AADoAACADQQFqIgNB/wFxIgAgAUgNAAsgAkGAARABCyACQYABaiQACxIAIABBA3ZB/z9xIABBEHYQBAsJAEGACSAAEAELBgBBgIkBCxsAIAFBA3ZB/z9xIAFBEHYQBEGACSAAEAEQAwsLCwEAQYAICwTwAAAA";
+var hash$j = "68afc9cf";
+var wasmJson$j = {
+ name: name$j,
+ data: data$j,
+ hash: hash$j
+};
+
+const mutex$k = new Mutex();
+let wasmCache$k = null;
+function validateBits$4(bits) {
+ if (!Number.isInteger(bits) || bits < 8 || bits > 512 || bits % 8 !== 0) {
+ return new Error('Invalid variant! Valid values: 8, 16, ..., 512');
+ }
+ return null;
+}
+function getInitParam$1(outputBits, keyBits) {
+ // eslint-disable-next-line no-bitwise
+ return outputBits | (keyBits << 16);
+}
+/**
+ * Calculates BLAKE2b hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param bits Number of output bits, which has to be a number
+ * divisible by 8, between 8 and 512. Defaults to 512.
+ * @param key Optional key (string, Buffer or TypedArray). Maximum length is 64 bytes.
+ * @returns Computed hash as a hexadecimal string
+ */
+function blake2b(data, bits = 512, key = null) {
+ if (validateBits$4(bits)) {
+ return Promise.reject(validateBits$4(bits));
+ }
+ let keyBuffer = null;
+ let initParam = bits;
+ if (key !== null) {
+ keyBuffer = getUInt8Buffer(key);
+ if (keyBuffer.length > 64) {
+ return Promise.reject(new Error('Max key length is 64 bytes'));
+ }
+ initParam = getInitParam$1(bits, keyBuffer.length);
+ }
+ const hashLength = bits / 8;
+ if (wasmCache$k === null || wasmCache$k.hashLength !== hashLength) {
+ return lockedCreate(mutex$k, wasmJson$j, hashLength)
+ .then((wasm) => {
+ wasmCache$k = wasm;
+ if (initParam > 512) {
+ wasmCache$k.writeMemory(keyBuffer);
+ }
+ return wasmCache$k.calculate(data, initParam);
+ });
+ }
+ try {
+ if (initParam > 512) {
+ wasmCache$k.writeMemory(keyBuffer);
+ }
+ const hash = wasmCache$k.calculate(data, initParam);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new BLAKE2b hash instance
+ * @param bits Number of output bits, which has to be a number
+ * divisible by 8, between 8 and 512. Defaults to 512.
+ * @param key Optional key (string, Buffer or TypedArray). Maximum length is 64 bytes.
+ */
+function createBLAKE2b(bits = 512, key = null) {
+ if (validateBits$4(bits)) {
+ return Promise.reject(validateBits$4(bits));
+ }
+ let keyBuffer = null;
+ let initParam = bits;
+ if (key !== null) {
+ keyBuffer = getUInt8Buffer(key);
+ if (keyBuffer.length > 64) {
+ return Promise.reject(new Error('Max key length is 64 bytes'));
+ }
+ initParam = getInitParam$1(bits, keyBuffer.length);
+ }
+ const outputSize = bits / 8;
+ return WASMInterface(wasmJson$j, outputSize).then((wasm) => {
+ if (initParam > 512) {
+ wasm.writeMemory(keyBuffer);
+ }
+ wasm.init(initParam);
+ const obj = {
+ init: initParam > 512
+ ? () => {
+ wasm.writeMemory(keyBuffer);
+ wasm.init(initParam);
+ return obj;
+ }
+ : () => {
+ wasm.init(initParam);
+ return obj;
+ },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 128,
+ digestSize: outputSize,
+ };
+ return obj;
+ });
+}
+
+var name$i = "argon2";
+var data$i = "AGFzbQEAAAABKQVgAX8Bf2AAAX9gEH9/f39/f39/f39/f39/f38AYAR/f39/AGACf38AAwYFAAECAwQEBQFwAQEBBQYBAQKAgAIGCAF/AUGQqAQLB0EEBm1lbW9yeQIAEkhhc2hfU2V0TWVtb3J5U2l6ZQAADkhhc2hfR2V0QnVmZmVyAAEOSGFzaF9DYWxjdWxhdGUABArXMwVbAQF/QQAhAQJAIABBACgCgAhrIgBFDQACQCAAQRB2IABBgIB8cSAASWoiAEAAQX9HDQBB/wEhAQwBC0EAIQFBAEEAKQOACCAAQRB0rXw3A4AICyABQRh0QRh1C2oBAn8CQEEAKAKICCIADQBBAD8AQRB0IgA2AogIQYCAIEEAKAKACGsiAUUNAAJAIAFBEHYgAUGAgHxxIAFJaiIAQABBf0cNAEEADwtBAEEAKQOACCAAQRB0rXw3A4AIQQAoAogIIQALIAALnA8BA34gACAEKQMAIhAgACkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDCAQIAwpAwCFIhBCIIkiETcDACAIIBEgCCkDACISfCASQgGGQv7///8fgyAQQiCIfnwiEDcDACAEIBAgBCkDAIUiEEIoiSIRNwMAIAAgESAAKQMAIhJ8IBBCGIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAMIBAgDCkDAIUiEEIwiSIRNwMAIAggESAIKQMAIhJ8IBBCEIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAEIBAgBCkDAIVCAYk3AwAgASAFKQMAIhAgASkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDSAQIA0pAwCFIhBCIIkiETcDACAJIBEgCSkDACISfCASQgGGQv7///8fgyAQQiCIfnwiEDcDACAFIBAgBSkDAIUiEEIoiSIRNwMAIAEgESABKQMAIhJ8IBBCGIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACANIBAgDSkDAIUiEEIwiSIRNwMAIAkgESAJKQMAIhJ8IBBCEIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAFIBAgBSkDAIVCAYk3AwAgAiAGKQMAIhAgAikDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDiAQIA4pAwCFIhBCIIkiETcDACAKIBEgCikDACISfCASQgGGQv7///8fgyAQQiCIfnwiEDcDACAGIBAgBikDAIUiEEIoiSIRNwMAIAIgESACKQMAIhJ8IBBCGIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAOIBAgDikDAIUiEEIwiSIRNwMAIAogESAKKQMAIhJ8IBBCEIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAGIBAgBikDAIVCAYk3AwAgAyAHKQMAIhAgAykDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDyAQIA8pAwCFIhBCIIkiETcDACALIBEgCykDACISfCASQgGGQv7///8fgyAQQiCIfnwiEDcDACAHIBAgBykDAIUiEEIoiSIRNwMAIAMgESADKQMAIhJ8IBBCGIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAPIBAgDykDAIUiEEIwiSIRNwMAIAsgESALKQMAIhJ8IBBCEIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAHIBAgBykDAIVCAYk3AwAgACAFKQMAIhAgACkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDyAQIA8pAwCFIhBCIIkiETcDACAKIBEgCikDACISfCASQgGGQv7///8fgyAQQiCIfnwiEDcDACAFIBAgBSkDAIUiEEIoiSIRNwMAIAAgESAAKQMAIhJ8IBBCGIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAPIBAgDykDAIUiEEIwiSIRNwMAIAogESAKKQMAIhJ8IBBCEIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAFIBAgBSkDAIVCAYk3AwAgASAGKQMAIhAgASkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDCAQIAwpAwCFIhBCIIkiETcDACALIBEgCykDACISfCASQgGGQv7///8fgyAQQiCIfnwiEDcDACAGIBAgBikDAIUiEEIoiSIRNwMAIAEgESABKQMAIhJ8IBBCGIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAMIBAgDCkDAIUiEEIwiSIRNwMAIAsgESALKQMAIhJ8IBBCEIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAGIBAgBikDAIVCAYk3AwAgAiAHKQMAIhAgAikDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDSAQIA0pAwCFIhBCIIkiETcDACAIIBEgCCkDACISfCASQgGGQv7///8fgyAQQiCIfnwiEDcDACAHIBAgBykDAIUiEEIoiSIRNwMAIAIgESACKQMAIhJ8IBBCGIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACANIBAgDSkDAIUiEEIwiSIRNwMAIAggESAIKQMAIhJ8IBBCEIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAHIBAgBykDAIVCAYk3AwAgAyAEKQMAIhAgAykDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDiAQIA4pAwCFIhBCIIkiETcDACAJIBEgCSkDACISfCASQgGGQv7///8fgyAQQiCIfnwiEDcDACAEIBAgBCkDAIUiEEIoiSIRNwMAIAMgESADKQMAIhJ8IBBCGIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAOIBAgDikDAIUiEEIwiSIRNwMAIAkgESAJKQMAIhJ8IBBCEIhC/////w+DIBJCAYZC/v///x+DfnwiEDcDACAEIBAgBCkDAIVCAYk3AwALhxoBAX9BACEEQQAgAikDACABKQMAhTcDkAhBACACKQMIIAEpAwiFNwOYCEEAIAIpAxAgASkDEIU3A6AIQQAgAikDGCABKQMYhTcDqAhBACACKQMgIAEpAyCFNwOwCEEAIAIpA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iIBIAhHDQALCyAUQgF8IhQgC1INAAsLIBNCAXwiE6chASATQgRSDQALIA9CAXwiDyAHUg0AC0EAKAKICCECCyAJQQx0QYB4aiEZAkAgBUF/aiIQRQ0AQQAhBQNAIAUgA2wgA2pBCnRBgHhqIRxBeCEEQQAhAQNAIAIgASAZamoiCCAIKQMAIAIgHCABamopAwCFNwMAIAFBCGohASAEQQhqIgRB+AdJDQALIAVBAWoiBSAQRw0ACwtBACEBA0AgAiABaiACIAEgGWpqKQMANwMAIAFB+AdJIQMgAUEIaiEBIAMNAAsLCw==";
+var hash$i = "59aa4fb4";
+var wasmJson$i = {
+ name: name$i,
+ data: data$i,
+ hash: hash$i
+};
+
+function encodeResult(salt, options, res) {
+ const parameters = [
+ `m=${options.memorySize}`,
+ `t=${options.iterations}`,
+ `p=${options.parallelism}`,
+ ].join(',');
+ return `$argon2${options.hashType}$v=19$${parameters}$${encodeBase64(salt, false)}$${encodeBase64(res, false)}`;
+}
+const uint32View = new DataView(new ArrayBuffer(4));
+function int32LE(x) {
+ uint32View.setInt32(0, x, true);
+ return new Uint8Array(uint32View.buffer);
+}
+function hashFunc(blake512, buf, len) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (len <= 64) {
+ const blake = yield createBLAKE2b(len * 8);
+ blake.update(int32LE(len));
+ blake.update(buf);
+ return blake.digest('binary');
+ }
+ const r = Math.ceil(len / 32) - 2;
+ const ret = new Uint8Array(len);
+ blake512.init();
+ blake512.update(int32LE(len));
+ blake512.update(buf);
+ let vp = blake512.digest('binary');
+ ret.set(vp.subarray(0, 32), 0);
+ for (let i = 1; i < r; i++) {
+ blake512.init();
+ blake512.update(vp);
+ vp = blake512.digest('binary');
+ ret.set(vp.subarray(0, 32), i * 32);
+ }
+ const partialBytesNeeded = len - 32 * r;
+ let blakeSmall;
+ if (partialBytesNeeded === 64) {
+ blakeSmall = blake512;
+ blakeSmall.init();
+ }
+ else {
+ blakeSmall = yield createBLAKE2b(partialBytesNeeded * 8);
+ }
+ blakeSmall.update(vp);
+ vp = blakeSmall.digest('binary');
+ ret.set(vp.subarray(0, partialBytesNeeded), r * 32);
+ return ret;
+ });
+}
+function getHashType(type) {
+ switch (type) {
+ case 'd':
+ return 0;
+ case 'i':
+ return 1;
+ default:
+ return 2;
+ }
+}
+function argon2Internal(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const { parallelism, iterations, hashLength } = options;
+ const password = getUInt8Buffer(options.password);
+ const salt = getUInt8Buffer(options.salt);
+ const version = 0x13;
+ const hashType = getHashType(options.hashType);
+ const { memorySize } = options; // in KB
+ const [argon2Interface, blake512] = yield Promise.all([
+ WASMInterface(wasmJson$i, 1024),
+ createBLAKE2b(512),
+ ]);
+ // last block is for storing the init vector
+ argon2Interface.setMemorySize(memorySize * 1024 + 1024);
+ const initVector = new Uint8Array(24);
+ const initVectorView = new DataView(initVector.buffer);
+ initVectorView.setInt32(0, parallelism, true);
+ initVectorView.setInt32(4, hashLength, true);
+ initVectorView.setInt32(8, memorySize, true);
+ initVectorView.setInt32(12, iterations, true);
+ initVectorView.setInt32(16, version, true);
+ initVectorView.setInt32(20, hashType, true);
+ argon2Interface.writeMemory(initVector, memorySize * 1024);
+ blake512.init();
+ blake512.update(initVector);
+ blake512.update(int32LE(password.length));
+ blake512.update(password);
+ blake512.update(int32LE(salt.length));
+ blake512.update(salt);
+ blake512.update(int32LE(0)); // key length + key
+ blake512.update(int32LE(0)); // associatedData length + associatedData
+ const segments = Math.floor(memorySize / (parallelism * 4)); // length of each lane
+ const lanes = segments * 4;
+ const param = new Uint8Array(72);
+ const H0 = blake512.digest('binary');
+ param.set(H0);
+ for (let lane = 0; lane < parallelism; lane++) {
+ param.set(int32LE(0), 64);
+ param.set(int32LE(lane), 68);
+ let position = lane * lanes;
+ let chunk = yield hashFunc(blake512, param, 1024);
+ argon2Interface.writeMemory(chunk, position * 1024);
+ position += 1;
+ param.set(int32LE(1), 64);
+ chunk = yield hashFunc(blake512, param, 1024);
+ argon2Interface.writeMemory(chunk, position * 1024);
+ }
+ const C = new Uint8Array(1024);
+ writeHexToUInt8(C, argon2Interface.calculate(new Uint8Array([]), memorySize));
+ const res = yield hashFunc(blake512, C, hashLength);
+ if (options.outputType === 'hex') {
+ const digestChars = new Uint8Array(hashLength * 2);
+ return getDigestHex(digestChars, res, hashLength);
+ }
+ if (options.outputType === 'encoded') {
+ return encodeResult(salt, options, res);
+ }
+ // return binary format
+ return res;
+ });
+}
+const validateOptions$3 = (options) => {
+ if (!options || typeof options !== 'object') {
+ throw new Error('Invalid options parameter. It requires an object.');
+ }
+ if (!options.password) {
+ throw new Error('Password must be specified');
+ }
+ options.password = getUInt8Buffer(options.password);
+ if (options.password.length < 1) {
+ throw new Error('Password must be specified');
+ }
+ if (!options.salt) {
+ throw new Error('Salt must be specified');
+ }
+ options.salt = getUInt8Buffer(options.salt);
+ if (options.salt.length < 8) {
+ throw new Error('Salt should be at least 8 bytes long');
+ }
+ if (!Number.isInteger(options.iterations) || options.iterations < 1) {
+ throw new Error('Iterations should be a positive number');
+ }
+ if (!Number.isInteger(options.parallelism) || options.parallelism < 1) {
+ throw new Error('Parallelism should be a positive number');
+ }
+ if (!Number.isInteger(options.hashLength) || options.hashLength < 4) {
+ throw new Error('Hash length should be at least 4 bytes.');
+ }
+ if (!Number.isInteger(options.memorySize)) {
+ throw new Error('Memory size should be specified.');
+ }
+ if (options.memorySize < 8 * options.parallelism) {
+ throw new Error('Memory size should be at least 8 * parallelism.');
+ }
+ if (options.outputType === undefined) {
+ options.outputType = 'hex';
+ }
+ if (!['hex', 'binary', 'encoded'].includes(options.outputType)) {
+ throw new Error(`Insupported output type ${options.outputType}. Valid values: ['hex', 'binary', 'encoded']`);
+ }
+};
+/**
+ * Calculates hash using the argon2i password-hashing function
+ * @returns Computed hash
+ */
+function argon2i(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ validateOptions$3(options);
+ return argon2Internal(Object.assign(Object.assign({}, options), { hashType: 'i' }));
+ });
+}
+/**
+ * Calculates hash using the argon2id password-hashing function
+ * @returns Computed hash
+ */
+function argon2id(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ validateOptions$3(options);
+ return argon2Internal(Object.assign(Object.assign({}, options), { hashType: 'id' }));
+ });
+}
+/**
+ * Calculates hash using the argon2d password-hashing function
+ * @returns Computed hash
+ */
+function argon2d(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ validateOptions$3(options);
+ return argon2Internal(Object.assign(Object.assign({}, options), { hashType: 'd' }));
+ });
+}
+const getHashParameters = (password, encoded) => {
+ const regex = /^\$argon2(id|i|d)\$v=([0-9]+)\$((?:[mtp]=[0-9]+,){2}[mtp]=[0-9]+)\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$/;
+ const match = encoded.match(regex);
+ if (!match) {
+ throw new Error('Invalid hash');
+ }
+ const [, hashType, version, parameters, salt, hash] = match;
+ if (version !== '19') {
+ throw new Error(`Unsupported version: ${version}`);
+ }
+ const parsedParameters = {};
+ const paramMap = { m: 'memorySize', p: 'parallelism', t: 'iterations' };
+ parameters.split(',').forEach((x) => {
+ const [n, v] = x.split('=');
+ parsedParameters[paramMap[n]] = parseInt(v, 10);
+ });
+ return Object.assign(Object.assign({}, parsedParameters), { password, hashType: hashType, salt: decodeBase64(salt), hashLength: getDecodeBase64Length(hash), outputType: 'encoded' });
+};
+const validateVerifyOptions$1 = (options) => {
+ if (!options || typeof options !== 'object') {
+ throw new Error('Invalid options parameter. It requires an object.');
+ }
+ if (options.hash === undefined || typeof options.hash !== 'string') {
+ throw new Error('Hash should be specified');
+ }
+};
+/**
+ * Verifies password using the argon2 password-hashing function
+ * @returns True if the encoded hash matches the password
+ */
+function argon2Verify(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ validateVerifyOptions$1(options);
+ const params = getHashParameters(options.password, options.hash);
+ validateOptions$3(params);
+ const hashStart = options.hash.lastIndexOf('$') + 1;
+ const result = yield argon2Internal(params);
+ return result.substring(hashStart) === options.hash.substring(hashStart);
+ });
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AkE/Sg0AQQAhAQNAIAIgAWpBsIkBakEAOgAAIAFBAWoiAUHAAEEAKALwiQEiAmtIDQALC0GwiQEQAiAAQQAoAoCJASIBNgIAIABBACgChIkBNgIEIABBACkDiIkBNwMIIABBACkDkIkBNwMQIABBACkDmIkBNwMYQQAoAvSJASIDQQBMDQBBACABOgCACSADQQFGDQBBASEBQQEhAgNAIAFBgAlqIAAgAWotAAA6AAAgAyACQQFqIgJB/wFxIgFKDQALCyAAQSBqJAALoAMBBH8jAEHAAGsiASQAQQBBgQI7AYKKAUEAIABBEHYiAjoAgYoBQQAgAEEDdjoAgIoBQYR/IQADQCAAQfyJAWpBADoAACAAQQFqIgMgAE8hBCADIQAgBA0AC0EAIQBBAEEAKAKAigEiA0HnzKfQBnM2AoCJAUEAQQAoAoSKAUGF3Z7be3M2AoSJAUEAQQAoAoiKAUHy5rvjA3M2AoiJAUEAQQAoAoyKAUG66r+qenM2AoyJAUEAQQAoApCKAUH/pLmIBXM2ApCJAUEAQQAoApSKAUGM0ZXYeXM2ApSJAUEAQQAoApiKAUGrs4/8AXM2ApiJAUEAIANB/wFxNgL0iQFBAEEAKAKcigFBmZqD3wVzNgKciQECQCACRQ0AIAFBOGpCADcDACABQTBqQgA3AwAgAUEoakIANwMAIAFBIGpCADcDACABQRhqQgA3AwAgAUEQakIANwMAIAFCADcDCCABQgA3AwBBACEDA0AgASAAaiAAQYAJai0AADoAACACIANBAWoiA0H/AXEiAEsNAAsgAUHAABABCyABQcAAaiQACwkAQYAJIAAQAQsGAEGAiQELDwAgARAEQYAJIAAQARADCwsLAQBBgAgLBHwAAAA=";
+var hash$h = "0f570f49";
+var wasmJson$h = {
+ name: name$h,
+ data: data$h,
+ hash: hash$h
+};
+
+const mutex$j = new Mutex();
+let wasmCache$j = null;
+function validateBits$3(bits) {
+ if (!Number.isInteger(bits) || bits < 8 || bits > 256 || bits % 8 !== 0) {
+ return new Error('Invalid variant! Valid values: 8, 16, ..., 256');
+ }
+ return null;
+}
+function getInitParam(outputBits, keyBits) {
+ // eslint-disable-next-line no-bitwise
+ return outputBits | (keyBits << 16);
+}
+/**
+ * Calculates BLAKE2s hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param bits Number of output bits, which has to be a number
+ * divisible by 8, between 8 and 256. Defaults to 256.
+ * @param key Optional key (string, Buffer or TypedArray). Maximum length is 32 bytes.
+ * @returns Computed hash as a hexadecimal string
+ */
+function blake2s(data, bits = 256, key = null) {
+ if (validateBits$3(bits)) {
+ return Promise.reject(validateBits$3(bits));
+ }
+ let keyBuffer = null;
+ let initParam = bits;
+ if (key !== null) {
+ keyBuffer = getUInt8Buffer(key);
+ if (keyBuffer.length > 32) {
+ return Promise.reject(new Error('Max key length is 32 bytes'));
+ }
+ initParam = getInitParam(bits, keyBuffer.length);
+ }
+ const hashLength = bits / 8;
+ if (wasmCache$j === null || wasmCache$j.hashLength !== hashLength) {
+ return lockedCreate(mutex$j, wasmJson$h, hashLength)
+ .then((wasm) => {
+ wasmCache$j = wasm;
+ if (initParam > 512) {
+ wasmCache$j.writeMemory(keyBuffer);
+ }
+ return wasmCache$j.calculate(data, initParam);
+ });
+ }
+ try {
+ if (initParam > 512) {
+ wasmCache$j.writeMemory(keyBuffer);
+ }
+ const hash = wasmCache$j.calculate(data, initParam);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new BLAKE2s hash instance
+ * @param bits Number of output bits, which has to be a number
+ * divisible by 8, between 8 and 256. Defaults to 256.
+ * @param key Optional key (string, Buffer or TypedArray). Maximum length is 32 bytes.
+ */
+function createBLAKE2s(bits = 256, key = null) {
+ if (validateBits$3(bits)) {
+ return Promise.reject(validateBits$3(bits));
+ }
+ let keyBuffer = null;
+ let initParam = bits;
+ if (key !== null) {
+ keyBuffer = getUInt8Buffer(key);
+ if (keyBuffer.length > 32) {
+ return Promise.reject(new Error('Max key length is 32 bytes'));
+ }
+ initParam = getInitParam(bits, keyBuffer.length);
+ }
+ const outputSize = bits / 8;
+ return WASMInterface(wasmJson$h, outputSize).then((wasm) => {
+ if (initParam > 512) {
+ wasm.writeMemory(keyBuffer);
+ }
+ wasm.init(initParam);
+ const obj = {
+ init: initParam > 512
+ ? () => {
+ wasm.writeMemory(keyBuffer);
+ wasm.init(initParam);
+ return obj;
+ }
+ : () => {
+ wasm.init(initParam);
+ return obj;
+ },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: outputSize,
+ };
+ return obj;
+ });
+}
+
+var name$g = "blake3";
+var data$g = "AGFzbQEAAAABJQZgAAF/YAF/AGADf39/AGAGf39/f35/AGABfgBgBX9/fn9/AX8DDQwAAQIDBAUBAQEBAAIEBQFwAQEBBQQBAQICBg4CfwFBgJgFC38AQYAICwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACUhhc2hfSW5pdAAHC0hhc2hfVXBkYXRlAAgKSGFzaF9GaW5hbAAJDUhhc2hfR2V0U3RhdGUACg5IYXNoX0NhbGN1bGF0ZQALClNUQVRFX1NJWkUDAQrAWAwFAEGACQubEQkDfwR+An8BfgF/A34CfwJ+BH8jAEHQAmsiASQAAkAgAEUNAAJAAkBBAC0AiYoBQQZ0QQAtAIiKAWoiAg0AQYAJIQMMAQtBoIkBQYAJIABBgAggAmsiAiACIABLGyICEAIgACACayIARQ0BIAFBoAFqQQApA9CJATcDACABQagBakEAKQPYiQE3AwAgAUEAKQOgiQEiBDcDcCABQQApA6iJASIFNwN4IAFBACkDsIkBIgY3A4ABIAFBACkDuIkBIgc3A4gBIAFBACkDyIkBNwOYAUEALQCKigEhCEEALQCJigEhCUEAKQPAiQEhCkEALQCIigEhCyABQbABakEAKQPgiQE3AwAgAUG4AWpBACkD6IkBNwMAIAFBwAFqQQApA/CJATcDACABQcgBakEAKQP4iQE3AwAgAUHQAWpBACkDgIoBNwMAIAEg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AtBAWo6AJCKASACQZGKAWogBjcDACACQamKAWogCjcDAEEAKQPAiQEgDUIBiHwQBEEAQQAtAJCKASICQQFqOgCQigEgAkEFdCICQamKAWogETcDACACQaGKAWogDjcDACACQZmKAWogDDcDACACQZGKAWogBzcDAAtBAEEAKQPAiQEgDXwiBDcDwIkBIAMgEGohAyAAIBBrIgBBgAhLDQALIABFDQELQaCJASADIAAQAkEAKQPAiQEQBAsgAUHQAmokAAvwBAEFfyMAQcAAayIDJAACQAJAIAAtAGgiBEUNAAJAIAJBwAAgBGsiBSAFIAJLGyIGRQ0AIAAgBGpBKGohBCABIQUgBiEHA0AgBCAFLQAAOgAAIAVBAWohBSAEQQFqIQQgB0F/aiIHDQALIAAtAGghBAsgACAEIAZqIgQ6AGggASAGaiEBAkAgAiAGayICDQBBACECDAILIAMgACAAQShqQcAAIAApAyAgAC0AaiAAQekAaiIELQAARXIQAyAAIAMpAyAgAykDAIU3AwAgACADKQMoIAMpAwiFNwMIIAAgAykDMCADKQMQhTcDECAAIAMpAzggAykDGIU3AxggAEEAOgBoIABB4ABqQgA3AwAgAEHYAGpCADcDACAAQdAAakIANwMAIABByABqQgA3AwAgAEHAAGpCADcDACAAQThqQgA3AwAgAEEwakIANwMAIABCADcDKCAEIAQtAABBAWo6AAALQQAhBCACQcEASQ0AIABB6QBqIgQtAAAhBQNAIAMgACABQcAAIAApAyAgAC0AaiAFQf8BcUVyEAMgACADKQMgIAMpAwCFNwMAIAAgAykDKCADKQMIhTcDCCAAIAMpAzAgAykDEIU3AxAgACADKQM4IAMpAxiFNwMYIAQgBC0AAEEBaiIFOgAAIAFBwABqIQEgAkFAaiICQcAASw0ACyAALQBoIQQLAkAgAkHAACAEQf8BcSIHayIFIAUgAksbIgJFDQAgACAHakEoaiEEIAIhBQNAIAQgAS0AADoAACABQQFqIQEgBEEBaiEEIAVBf2oiBQ0ACyAALQBoIQQLIAAgBCACajoAaCADQcAAaiQAC80cAgx+H38gAikDICEGIAIpAzghByACKQMwIQ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IdICBzQRR3Ih9qIiA2AgAgACAXICQgHHNBGHciHCAeaiIeIBtzQRl3IhtqIAFqIgEgFmogASAUc0EQdyIBICtqIhQgG3NBFHciFmoiFyABc0EYdyIBNgI4IAAgGCAVc0EZdyIVIC5qIANqIgMgE2ogAyAcc0EQdyIDIAIgImoiAmoiIiAVc0EUdyIVaiITNgIEIAAgASAUaiIBNgIkIAAgAiAFc0EZdyICIBlqICFqIgUgGmogBSAnc0EQdyIFIB5qIhQgAnNBFHciAmoiGjYCCCAAICAgEnNBGHciEiAdaiIhNgIoIAAgEyADc0EYdyIDNgIwIAAgASAWc0EZdzYCECAAIBogBXNBGHciATYCNCAAICEgH3NBGXc2AhQgACABIBRqIgE2AiAgACADICJqIgUgFXNBGXc2AhggACASNgI8IAAgASACc0EZdzYCHCAAIBc2AgwgACAFNgIsC7cDAwR/A34FfyMAQdABayIBJAACQCAAe6ciAkEALQCQigEiA08NACABQShqIQQDQCABQQApA4CJASIANwMAIAFBACkDiIkBIgU3AwggAUEAKQOQiQEiBjcDECABQQApA5iJASIHNwMYIAEgA0EFdCIDQdGJAWoiCCkDADcDKCABIANB2YkBaiIJKQMANwMwIAEgA0HhiQFqIgopAwA3AzggASADQemJAWoiCykDADcDQEEALQCKigEhDCABQcAAOgBoIAEgDEEEciIMOgBpIAFCADcDICABIANB8YkBaikDADcDSCABIANB+YkBaikDADcDUCABIANBgYoBaikDADcDWCABIANBiYoBaikDADcDYCABIAc3A4gBIAEgBjcDgAEgASAFNwN4IAEgADcDcCABQZABaiABQfAAaiAEQcAAQgAgDBADIAsgASkDyAEgASkDqAGFNwMAIAogASkDwAEgASkDoAGFNwMAIAkgASkDuAEgASkDmAGFNwMAIAggASkDsAEgASkDkAGFNwMAQQBBAC0AkIoBQX9qIgM6AJCKASACIANB/wFxIgNJDQALCyABQdABaiQAC/oLBAR/BH4GfwF+IwBB0AJrIgUkAAJAAkAgAUGACEsNAEEAIQYgASEHQQAhCAJAIAFBgAhHDQAgBUEAKQOA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AKQPoiQE3AwAgAUHQAGpBACkD8IkBNwMAIAFB2ABqQQApA/iJATcDACABQeAAakEAKQOAigE3AwAgASAJOgBoIAEgCDcDICABIAIgB0VyQQJyIgI6AGkgAUHwAGpBAXIhCiABQShqIQtCACEIQYAJIQwDQCABQbABaiABIAsgCUH/AXEgCCACQQhyQf8BcRADIAEgASkD2AEiDSABKQO4AYU3A3ggASABKQPgASIOIAEpA8ABhTcDgAEgASAGIAEpA+gBIg+FNwOoASABIAUgDoU3A6ABIAEgBCANhTcDmAEgASADIAEpA9ABIg2FNwOQASABIA8gASkDyAGFNwOIASAAQcAAIABBwABJGyIQQX9qIQkgASANIAEpA7ABhSINNwNwIA2nIREgCiEHIAwhAgJAA0AgAiAROgAAIAlFDQEgCUF/aiEJIAJBAWohAiAHLQAAIREgB0EBaiEHDAALCyAAIBBrIgBFDQIgDCAQaiEMIAhCAXwhCCABKQMIIQQgASkDACEDIAEpAxghBiABKQMQIQUgAS0AaSECIAEtAGghCQwACwsCQAJAAkBBAC0AiYoBIglBBnRBAEEALQCIigEiDGtGDQAgAUHgAGpBACkDgIoBNwMAIAFB2ABqQQApA/iJATcDACABQdAAakEAKQPwiQE3AwAgAUHIAGpBACkD6IkBNwMAIAFBwABqQQApA+CJATcDACABQThqQQApA9iJATcDACABQTBqQQApA9CJATcDACABQQApA8iJATcDKCABQQApA8CJASIINwMgIAFBACkDuIkBIg03AxggAUEAKQOwiQEiDjcDECABQQApA6iJASIPNwMIIAFBACkDoIkBIgM3AwBBAC0AiooBIQcgAUHuAGogAUG0AWovAQA7AQAgASABKAGwATYBaiABIAw6AGggASAHIAlFckECciIJOgBpDAELIAFB4ABqIAJBfmoiAkEFdCIJQcmKAWopAwA3AwAgAUHYAGogCUHBigFqKQMANwMAIAFB0ABqIAlBuYoBaikDADcDACABQcgAaiAJQbGKAWopAwA3AwBBwAAhDCABQcAAaiAJQamKAWopAwA3AwAgAUE4aiAJQaGKAWopAwA3AwAgAUEwaiAJQZmKAWopAwA3AwBCACEIIAFCADcDICABQQApA5iJASINNwMYIAFBACkDkIkBIg43AxAgAUEAKQOIiQEiDzcDCCABQQApA4CJASIDNwMAIAEgCUGRigFqKQMANwMoQQAtAIqKASEJIAFB7gBqIAFBsAFqQQRqLwEAOwEAIAEgASgBsAE2AWogASAJQQRyIgk6AGkgAUHAADoAaCACRQ0BCyACQX9qIgdBBXQiEUGRigFqKQMAIQQgEUGZigFqKQMAIQUgEUGhigFqKQMAIQYgEUGpigFqKQMAIRIgASANNwOIASABIA43A4ABIAEgDzcDeCABIAM3A3AgAUGwAWogAUHwAGogAUEoaiIQIAwgCCAJQf8BcRADIAFBwAA6AGggASASNwNAIAEgBjcDOCABIAU3AzAgASAENwMoIAFCADcDICABQQApA5iJASIINwMYIAFBACkDkIkBIg03AxAgAUEAKQOIiQEiDjcDCCABQQApA4CJASIPNwMAIAFBAC0AiooBQQRyIgk6AGkgASABKQPoASABKQPIAYU3A2AgASABKQPgASABKQPAAYU3A1ggASABKQPYASABKQO4AYU3A1AgASABKQPQASABKQOwAYU3A0ggAUHuAGogAUGwAWpBBGoiDC8BADsBACABIAEoAbABNgFqIAdFDQAgAUHqAGohESACQQV0QemJAWohAgNAIAJBaGopAwAhAyACQXBqKQMAIQQgAkF4aikDACEFIAIpAwAhBiABIAg3A4gBIAEgDTcDgAEgASAONwN4IAEgDzcDcCABQbABaiABQfAAaiAQQcAAQgAgCUH/AXEQAyABQcAAOgBoIAEgBjcDQCABIAU3AzggASAENwMwIAEgAzcDKCABQgA3AyAgAUEAKQOYiQEiCDcDGCABQQApA5CJASINNwMQIAFBACkDiIkBIg43AwggAUEAKQOAiQEiDzcDACABQQAtAIqKAUEEciIJOgBpIAEgASkD6AEgASkDyAGFNwNgIAEgASkD4AEgASkDwAGFNwNYIAEgASkD2AEgASkDuAGFNwNQIAEgASkD0AEgASkDsAGFNwNIIBFBBGogDC8BADsBACARIAEoAbABNgEAIAJBYGohAiAHQX9qIgcNAAsLIAFB8ABqQQFyIQogA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3A8CJAUEAIAM3A7iJAUEAIAQ3A7CJAUEAIAU3A6iJAUEAIAY3A6CJAUEAIAM3A5iJAUEAIAQ3A5CJAUEAIAU3A4iJAUEAIAY3A4CJAUEAQQA6AJCKAUEAQQA7AYiKASAAEAEgAhAGCwsLAQBBgAgLBHgHAAA=";
+var hash$g = "e8655383";
+var wasmJson$g = {
+ name: name$g,
+ data: data$g,
+ hash: hash$g
+};
+
+const mutex$i = new Mutex();
+let wasmCache$i = null;
+function validateBits$2(bits) {
+ if (!Number.isInteger(bits) || bits < 8 || bits % 8 !== 0) {
+ return new Error('Invalid variant! Valid values: 8, 16, ...');
+ }
+ return null;
+}
+/**
+ * Calculates BLAKE3 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param bits Number of output bits, which has to be a number
+ * divisible by 8. Defaults to 256.
+ * @param key Optional key (string, Buffer or TypedArray). Length should be 32 bytes.
+ * @returns Computed hash as a hexadecimal string
+ */
+function blake3(data, bits = 256, key = null) {
+ if (validateBits$2(bits)) {
+ return Promise.reject(validateBits$2(bits));
+ }
+ let keyBuffer = null;
+ let initParam = 0; // key is empty by default
+ if (key !== null) {
+ keyBuffer = getUInt8Buffer(key);
+ if (keyBuffer.length !== 32) {
+ return Promise.reject(new Error('Key length must be exactly 32 bytes'));
+ }
+ initParam = 32;
+ }
+ const hashLength = bits / 8;
+ const digestParam = hashLength;
+ if (wasmCache$i === null || wasmCache$i.hashLength !== hashLength) {
+ return lockedCreate(mutex$i, wasmJson$g, hashLength)
+ .then((wasm) => {
+ wasmCache$i = wasm;
+ if (initParam === 32) {
+ wasmCache$i.writeMemory(keyBuffer);
+ }
+ return wasmCache$i.calculate(data, initParam, digestParam);
+ });
+ }
+ try {
+ if (initParam === 32) {
+ wasmCache$i.writeMemory(keyBuffer);
+ }
+ const hash = wasmCache$i.calculate(data, initParam, digestParam);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new BLAKE3 hash instance
+ * @param bits Number of output bits, which has to be a number
+ * divisible by 8. Defaults to 256.
+ * @param key Optional key (string, Buffer or TypedArray). Length should be 32 bytes.
+ */
+function createBLAKE3(bits = 256, key = null) {
+ if (validateBits$2(bits)) {
+ return Promise.reject(validateBits$2(bits));
+ }
+ let keyBuffer = null;
+ let initParam = 0; // key is empty by default
+ if (key !== null) {
+ keyBuffer = getUInt8Buffer(key);
+ if (keyBuffer.length !== 32) {
+ return Promise.reject(new Error('Key length must be exactly 32 bytes'));
+ }
+ initParam = 32;
+ }
+ const outputSize = bits / 8;
+ const digestParam = outputSize;
+ return WASMInterface(wasmJson$g, outputSize).then((wasm) => {
+ if (initParam === 32) {
+ wasm.writeMemory(keyBuffer);
+ }
+ wasm.init(initParam);
+ const obj = {
+ init: initParam === 32
+ ? () => {
+ wasm.writeMemory(keyBuffer);
+ wasm.init(initParam);
+ return obj;
+ }
+ : () => {
+ wasm.init(initParam);
+ return obj;
+ },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType, digestParam),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: outputSize,
+ };
+ return obj;
+ });
+}
+
+var name$f = "crc32";
+var data$f = "AGFzbQEAAAABEQRgAAF/YAF/AGAAAGACf38AAwgHAAEBAQIAAwQFAXABAQEFBAEBAgIGDgJ/AUGQyQULfwBBgAgLB3AIBm1lbW9yeQIADkhhc2hfR2V0QnVmZmVyAAAJSGFzaF9Jbml0AAILSGFzaF9VcGRhdGUAAwpIYXNoX0ZpbmFsAAQNSGFzaF9HZXRTdGF0ZQAFDkhhc2hfQ2FsY3VsYXRlAAYKU1RBVEVfU0laRQMBCq0HBwUAQYAJC8MDAQN/QYCJASEBQQAhAgNAIAFBAEEAQQBBAEEAQQBBAEEAIAJBAXFrIABxIAJBAXZzIgNBAXFrIABxIANBAXZzIgNBAXFrIABxIANBAXZzIgNBAXFrIABxIANBAXZzIgNBAXFrIABxIANBA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LCwEAQYAICwQEAAAA";
+var hash$f = "749723dc";
+var wasmJson$f = {
+ name: name$f,
+ data: data$f,
+ hash: hash$f
+};
+
+const mutex$h = new Mutex();
+let wasmCache$h = null;
+/**
+ * Calculates CRC-32 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function crc32(data) {
+ if (wasmCache$h === null) {
+ return lockedCreate(mutex$h, wasmJson$f, 4)
+ .then((wasm) => {
+ wasmCache$h = wasm;
+ return wasmCache$h.calculate(data, 0xEDB88320);
+ });
+ }
+ try {
+ const hash = wasmCache$h.calculate(data, 0xEDB88320);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new CRC-32 hash instance
+ */
+function createCRC32() {
+ return WASMInterface(wasmJson$f, 4).then((wasm) => {
+ wasm.init(0xEDB88320);
+ const obj = {
+ init: () => { wasm.init(0xEDB88320); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 4,
+ digestSize: 4,
+ };
+ return obj;
+ });
+}
+
+const mutex$g = new Mutex();
+let wasmCache$g = null;
+/**
+ * Calculates CRC-32C hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function crc32c(data) {
+ if (wasmCache$g === null) {
+ return lockedCreate(mutex$g, wasmJson$f, 4)
+ .then((wasm) => {
+ wasmCache$g = wasm;
+ return wasmCache$g.calculate(data, 0x82F63B78);
+ });
+ }
+ try {
+ const hash = wasmCache$g.calculate(data, 0x82F63B78);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new CRC-32C hash instance
+ */
+function createCRC32C() {
+ return WASMInterface(wasmJson$f, 4).then((wasm) => {
+ wasm.init(0x82F63B78);
+ const obj = {
+ init: () => { wasm.init(0x82F63B78); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 4,
+ digestSize: 4,
+ };
+ return obj;
+ });
+}
+
+var name$e = "md4";
+var data$e = "AGFzbQEAAAABEgRgAAF/YAAAYAF/AGACf38BfwMIBwABAgMBAAIEBQFwAQEBBQQBAQICBg4CfwFBoIoFC38AQYAICwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACUhhc2hfSW5pdAABC0hhc2hfVXBkYXRlAAIKSGFzaF9GaW5hbAAEDUhhc2hfR2V0U3RhdGUABQ5IYXNoX0NhbGN1bGF0ZQAGClNUQVRFX1NJWkUDAQqXEQcFAEGACQstAEEAQv6568XpjpWZEDcCkIkBQQBCgcaUupbx6uZvNwKIiQFBAEIANwKAiQEL6AIBA39BAEEAKAKAiQEiASAAakH/////AXEiAjYCgIkBQQAoAoSJASEDAkAgAiABTw0AQQAgA0EBaiIDNgKEiQELQQAgAyAAQR12ajYChIkBAkACQAJAAkACQAJAIAFBP3EiAw0AQYAJIQIMAQtBwAAgA2siAiAASw0BIANBGGohA0EAIQEDQCADIAFqQYCJAWogAUGACWotAAA6AAAgAyABQQFqIgFqQdgARw0AC0GYiQFBwAAQAxogACACayEAIAJBgAlqIQILIABBwABPDQEgACEDDAILIABFDQJBACEBIANBmIkBakEALQCACToAACAAQQFGDQIgA0GZiQFqIQMgAEF/aiECA0AgAyABaiABQYEJai0AADoAACACIAFBAWoiAUcNAAwDCwsgAEE/cSEDIAIgAEFAcRADIQILIANFDQBBACEBA0AgAUGYiQFqIAIgAWotAAA6AAAgAyABQQFqIgFHDQALCwuYCwEXf0EAKAKUiQEhAkEAKAKQiQEhA0EAKAKMiQEhBEEAKAKIiQEhBQNAIABBHGooAgAiBiAAQRRqKAIAIgcgAEEYaigCACIIIABBEGooAgAiCSAAQSxqKAIAIgogAEEoaigCACILIABBJGooAgAiDCAAQSBqKAIAIg0gCyAIIABBCGooAgAiDiADaiAAQQRqKAIAIg8gAmogBCADIAJzcSACcyAFaiAAKAIAIhBqQQN3IhEgBCADc3EgA3NqQQd3IhIgESAEc3EgBHNqQQt3IhNqIBIgB2ogESAJaiAAQQxqKAIAIhQgBGogEyASIBFzcSARc2pBE3ciESATIBJzcSASc2pBA3ciEiARIBNzcSATc2pBB3ciEyASIBFzcSARc2pBC3ciFWogEyAMaiASIA1qIBEgBmogFSATIBJzcSASc2pBE3ciESAVIBNzcSATc2pBA3ciEiARIBVzcSAVc2pBB3ciEyASIBFzcSARc2pBC3ciFSAAQThqKAIAIhZqIBMgAEE0aigCACIXaiASIABBMGooAgAiGGogESAKaiAVIBMgEnNxIBJzakETdyISIBUgE3NxIBNzakEDdyITIBIgFXNxIBVzakEHdyIVIBMgEnNxIBJzakELdyIRaiAJIBVqIBAgE2ogEiAAQTxqKAIAIglqIBEgFSATc3EgE3NqQRN3IhIgESAVcnEgESAVcXJqQZnzidQFakEDdyITIBIgEXJxIBIgEXFyakGZ84nUBWpBBXciESATIBJycSATIBJxcmpBmfOJ1AVqQQl3IhVqIAcgEWogDyATaiAYIBJqIBUgESATcnEgESATcXJqQZnzidQFakENdyISIBUgEXJxIBUgEXFyakGZ84nUBWpBA3ciESASIBVycSASIBVxcmpBmfOJ1AVqQQV3IhMgESAScnEgESAScXJqQZnzidQFakEJdyIVaiAIIBNqIA4gEWogFyASaiAVIBMgEXJxIBMgEXFyakGZ84nUBWpBDXciESAVIBNycSAVIBNxcmpBmfOJ1AVqQQN3IhIgESAVcnEgESAVcXJqQZnzidQFakEFdyITIBIgEXJxIBIgEXFyakGZ84nUBWpBCXciFWogBiATaiAUIBJqIBYgEWogFSATIBJycSATIBJxcmpBmfOJ1AVqQQ13IhEgFSATcnEgFSATcXJqQZnzidQFakEDdyISIBEgFXJxIBEgFXFyakGZ84nUBWpBBXciEyASIBFycSASIBFxcmpBmfOJ1AVqQQl3IhVqIBAgEmogCSARaiAV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AgLBJgAAAA=";
+var hash$e = "1bf01052";
+var wasmJson$e = {
+ name: name$e,
+ data: data$e,
+ hash: hash$e
+};
+
+const mutex$f = new Mutex();
+let wasmCache$f = null;
+/**
+ * Calculates MD4 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function md4(data) {
+ if (wasmCache$f === null) {
+ return lockedCreate(mutex$f, wasmJson$e, 16)
+ .then((wasm) => {
+ wasmCache$f = wasm;
+ return wasmCache$f.calculate(data);
+ });
+ }
+ try {
+ const hash = wasmCache$f.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new MD4 hash instance
+ */
+function createMD4() {
+ return WASMInterface(wasmJson$e, 16).then((wasm) => {
+ wasm.init();
+ const obj = {
+ init: () => { wasm.init(); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: 16,
+ };
+ return obj;
+ });
+}
+
+var name$d = "md5";
+var data$d = "AGFzbQEAAAABEgRgAAF/YAAAYAF/AGACf38BfwMIBwABAgMBAAIEBQFwAQEBBQQBAQICBg4CfwFBoIoFC38AQYAICwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACUhhc2hfSW5pdAABC0hhc2hfVXBkYXRlAAIKSGFzaF9GaW5hbAAEDUhhc2hfR2V0U3RhdGUABQ5IYXNoX0NhbGN1bGF0ZQAGClNUQVRFX1NJWkUDAQqzFgcFAEGACQstAEEAQv6568XpjpWZEDcCkIkBQQBCgcaUupbx6uZvNwKIiQFBAEIANwKAiQEL6AIBA39BAEEAKAKAiQEiASAAakH/////AXEiAjYCgIkBQQAoAoSJASEDAkAgAiABTw0AQQAgA0EBaiIDNgKEiQELQQAgAyAAQR12ajYChIkBAkACQAJAAkACQAJAIAFBP3EiAw0AQYAJIQIMAQtBwAAgA2siAiAASw0BIANBGGohA0EAIQEDQCADIAFqQYCJAWogAUGACWotAAA6AAAgAyABQQFqIgFqQdgARw0AC0GYiQFBwAAQAxogACACayEAIAJBgAlqIQILIABBwABPDQEgACEDDAILIABFDQJBACEBIANBmIkBakEALQCACToAACAAQQFGDQIgA0GZiQFqIQMgAEF/aiECA0AgAyABaiABQYEJai0AADoAACACIAFBAWoiAUcNAAwDCwsgAEE/cSEDIAIgAEFAcRADIQILIANFDQBBACEBA0AgAUGYiQFqIAIgAWotAAA6AAAgAyABQQFqIgFHDQALCwu0EAEZf0EAKAKUiQEhAkEAKAKQiQEhA0EAKAKMiQEhBEEAKAKIiQEhBQNAIABBCGooAgAiBiAAQRhqKAIAIgcgAEEoaigCACIIIABBOGooAgAiCSAAQTxqKAIAIgogAEEMaigCACILIABBHGooAgAiDCAAQSxqKAIAIg0gDCALIAogDSAJIAggByADIAZqIAIgAEEEaigCACIOaiAFIAQgAiADc3EgAnNqIAAoAgAiD2pB+Miqu31qQQd3IARqIhAgBCADc3EgA3NqQdbunsZ+akEMdyAQaiIRIBAgBHNxIARzakHb4YGhAmpBEXcgEWoiEmogAEEUaigCACITIBFqIABBEGooAgAiFCAQaiAEIAtqIBIgESAQc3EgEHNqQe6d9418akEWdyASaiIQIBIgEXNxIBFzakGvn/Crf2pBB3cgEGoiESAQIBJzcSASc2pBqoyfvARqQQx3IBFqIhIgESAQc3EgEHNqQZOMwcF6akERdyASaiIVaiAAQSRqKAIAIhYgEmogAEEgaigCACIXIBFqIAwgEGogFSASIBFzcSARc2pBgaqaampBFncgFWoiECAVIBJzcSASc2pB2LGCzAZqQQd3IBBqIhEgECAVc3EgFXNqQa/vk9p4akEMdyARaiISIBEgEHNxIBBzakGxt31qQRF3IBJqIhVqIABBNGooAgAiGCASaiAAQTBqKAIAIhkgEWogDSAQaiAVIBIgEXNxIBFzakG+r/PKeGpBFncgFWoiECAVIBJzcSASc2pBoqLA3AZqQQd3IBBqIhEgECAVc3E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0AgASACakEAOgAAIAJBd2ohACACQX9qIQIgAEEASg0AC0EAKAKAiQEhAAtBACAAQRV2OgDTiQFBACAAQQ12OgDSiQFBACAAQQV2OgDRiQFBACAAQQN0IgI6ANCJAUEAIAI2AoCJAUEAQQAoAoSJATYC1IkBQZiJAUHAABADGkEAQQApAoiJATcDgAlBAEEAKQKQiQE3A4gJCwYAQYCJAQszAEEAQv6568XpjpWZEDcCkIkBQQBCgcaUupbx6uZvNwKIiQFBAEIANwKAiQEgABACEAQLCwsBAEGACAsEmAAAAA==";
+var hash$d = "9b0fac7d";
+var wasmJson$d = {
+ name: name$d,
+ data: data$d,
+ hash: hash$d
+};
+
+const mutex$e = new Mutex();
+let wasmCache$e = null;
+/**
+ * Calculates MD5 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function md5(data) {
+ if (wasmCache$e === null) {
+ return lockedCreate(mutex$e, wasmJson$d, 16)
+ .then((wasm) => {
+ wasmCache$e = wasm;
+ return wasmCache$e.calculate(data);
+ });
+ }
+ try {
+ const hash = wasmCache$e.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new MD5 hash instance
+ */
+function createMD5() {
+ return WASMInterface(wasmJson$d, 16).then((wasm) => {
+ wasm.init();
+ const obj = {
+ init: () => { wasm.init(); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: 16,
+ };
+ return obj;
+ });
+}
+
+var name$c = "sha1";
+var data$c = "AGFzbQEAAAABEQRgAAF/YAJ/fwBgAABgAX8AAwkIAAECAQMCAAMEBQFwAQEBBQQBAQICBg4CfwFB4IkFC38AQYAICwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACUhhc2hfSW5pdAACC0hhc2hfVXBkYXRlAAQKSGF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AUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycjYADCAAQQdqQQEQAwJAQQAoApSJAUH4A3FBwANGDQADQCAAQQA6AAcgAEEHakEBEANBACgClIkBQfgDcUHAA0cNAAsLIABBCGpBCBADQQBBACgCgIkBIgFBGHQgAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycjYCgAlBAEEAKAKEiQEiAUEYdCABQQh0QYCA/AdxciABQQh2QYD+A3EgAUEYdnJyNgKECUEAQQAoAoiJASIBQRh0IAFBCHRBgID8B3FyIAFBCHZBgP4DcSABQRh2cnI2AogJQQBBACgCjIkBIgFBGHQgAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycjYCjAlBAEEAKAKQiQEiAUEYdCABQQh0QYCA/AdxciABQQh2QYD+A3EgAUEYdnJyNgKQCSAAQRBqJAALBgBBgIkBC0MAQQBC/rnrxemOlZkQNwKIiQFBAEKBxpS6lvHq5m83AoCJAUEAQvDDy54MNwKQiQFBAEEANgKYiQFBgAkgABADEAULCwsBAEGACAsEXAAAAA==";
+var hash$c = "40d92e5d";
+var wasmJson$c = {
+ name: name$c,
+ data: data$c,
+ hash: hash$c
+};
+
+const mutex$d = new Mutex();
+let wasmCache$d = null;
+/**
+ * Calculates SHA-1 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function sha1(data) {
+ if (wasmCache$d === null) {
+ return lockedCreate(mutex$d, wasmJson$c, 20)
+ .then((wasm) => {
+ wasmCache$d = wasm;
+ return wasmCache$d.calculate(data);
+ });
+ }
+ try {
+ const hash = wasmCache$d.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new SHA-1 hash instance
+ */
+function createSHA1() {
+ return WASMInterface(wasmJson$c, 20).then((wasm) => {
+ wasm.init();
+ const obj = {
+ init: () => { wasm.init(); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: 20,
+ };
+ return obj;
+ });
+}
+
+var name$b = "sha3";
+var data$b = "AGFzbQEAAAABDwNgAAF/YAF/AGADf39/AAMIBwABAQIBAAIEBQFwAQEBBQQBAQICBg4CfwFBkI0FC38AQcAJCwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACUhhc2hfSW5pdAABC0hhc2hfVXBkYXRlAAIKSGFzaF9GaW5hbAAEDUhhc2hfR2V0U3RhdGUABQ5IYXNoX0NhbGN1bGF0ZQAGClNUQVRFX1NJWkUDAQrLFwcFAEGACgvXAwBBAEIANwOAjQFBAEIANwP4jAFBAEIANwPwjAFBAEIANwPojAFBAEIANwPgjAFBAEIANwPYjAFBAEIANwPQjAFBAEIANwPIjAFBAEIANwPAjAFBAEIANwO4jAFBAEIANwOwjAFBAEIANwOojAFBAEIANwOgjAFBAEIANwOYjAFBAEIANwOQjAFBAEIANwOIjAFBAEIANwOAjAFBAEIANwP4iwFBAEIANwPwiwFBAEIANwPoiwFBAEIANwPgiwFBAEIANwPYiwFBAEIANwPQiwFBAEIANwPIiwFBAEIANwPAiwFBAEIANwO4iwFBAEIANwOwiwFBAEIANwOoiwFBAEIANwOgiwFBAEIANwOYiwFBAEIANwOQiwFBAEIANwOIiwFBAEIANwOAiwFBAEIANwP4igFBAEIANwPwigFBAEIANwPoigFBAEIANwPgigFBAEIANwPYigFBAEIANwPQigFBAEIANwPIigFBAEIANwPAigFBAEIANwO4igFBAEIANwOwigFBAEIANwOoigFBAEIANwOgigFBAEIANwOYigFBAEIANwOQigFBAEIANwOIigFBAEIANwOAigFBAEHADCAAQQF0a0EDdjYCjI0BQQBBADYCiI0BC/8BAQZ/AkBBACgCiI0BIgFBAEgNAEEAIAEgAGpBACgCjI0BIgJwNgKIjQECQAJAIAENAEGACiEBDAELAkAgACACIAFrIgMgAyAASyIEGyIFRQ0AIAF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AAACKgAAAAAAAgACAAIAAAACAi4AAAAAAAAABAACAAAAAAIGAAIAAAACACYAAAAAAAICKAAAAAAAAAIgAAAAAAAAACYAAgAAAAAAKAACAAAAAAIuAAIAAAAAAiwAAAAAAAICJgAAAAAAAgAOAAAAAAACAAoAAAAAAAICAAAAAAAAAgAqAAAAAAAAACgAAgAAAAICBgACAAAAAgICAAAAAAACAAQAAgAAAAAAIgACAAAAAgJABAAA=";
+var hash$b = "ec266d91";
+var wasmJson$b = {
+ name: name$b,
+ data: data$b,
+ hash: hash$b
+};
+
+const mutex$c = new Mutex();
+let wasmCache$c = null;
+function validateBits$1(bits) {
+ if (![224, 256, 384, 512].includes(bits)) {
+ return new Error('Invalid variant! Valid values: 224, 256, 384, 512');
+ }
+ return null;
+}
+/**
+ * Calculates SHA-3 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param bits Number of output bits. Valid values: 224, 256, 384, 512
+ * @returns Computed hash as a hexadecimal string
+ */
+function sha3(data, bits = 512) {
+ if (validateBits$1(bits)) {
+ return Promise.reject(validateBits$1(bits));
+ }
+ const hashLength = bits / 8;
+ if (wasmCache$c === null || wasmCache$c.hashLength !== hashLength) {
+ return lockedCreate(mutex$c, wasmJson$b, hashLength)
+ .then((wasm) => {
+ wasmCache$c = wasm;
+ return wasmCache$c.calculate(data, bits, 0x06);
+ });
+ }
+ try {
+ const hash = wasmCache$c.calculate(data, bits, 0x06);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new SHA-3 hash instance
+ * @param bits Number of output bits. Valid values: 224, 256, 384, 512
+ */
+function createSHA3(bits = 512) {
+ if (validateBits$1(bits)) {
+ return Promise.reject(validateBits$1(bits));
+ }
+ const outputSize = bits / 8;
+ return WASMInterface(wasmJson$b, outputSize).then((wasm) => {
+ wasm.init(bits);
+ const obj = {
+ init: () => { wasm.init(bits); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType, 0x06),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 200 - 2 * outputSize,
+ digestSize: outputSize,
+ };
+ return obj;
+ });
+}
+
+const mutex$b = new Mutex();
+let wasmCache$b = null;
+function validateBits(bits) {
+ if (![224, 256, 384, 512].includes(bits)) {
+ return new Error('Invalid variant! Valid values: 224, 256, 384, 512');
+ }
+ return null;
+}
+/**
+ * Calculates Keccak hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param bits Number of output bits. Valid values: 224, 256, 384, 512
+ * @returns Computed hash as a hexadecimal string
+ */
+function keccak(data, bits = 512) {
+ if (validateBits(bits)) {
+ return Promise.reject(validateBits(bits));
+ }
+ const hashLength = bits / 8;
+ if (wasmCache$b === null || wasmCache$b.hashLength !== hashLength) {
+ return lockedCreate(mutex$b, wasmJson$b, hashLength)
+ .then((wasm) => {
+ wasmCache$b = wasm;
+ return wasmCache$b.calculate(data, bits, 0x01);
+ });
+ }
+ try {
+ const hash = wasmCache$b.calculate(data, bits, 0x01);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new Keccak hash instance
+ * @param bits Number of output bits. Valid values: 224, 256, 384, 512
+ */
+function createKeccak(bits = 512) {
+ if (validateBits(bits)) {
+ return Promise.reject(validateBits(bits));
+ }
+ const outputSize = bits / 8;
+ return WASMInterface(wasmJson$b, outputSize).then((wasm) => {
+ wasm.init(bits);
+ const obj = {
+ init: () => { wasm.init(bits); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType, 0x01),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 200 - 2 * outputSize,
+ digestSize: outputSize,
+ };
+ return obj;
+ });
+}
+
+var name$a = "sha256";
+var data$a = "AGFzbQEAAAABEQRgAAF/YAF/AGACf38AYAAAAwgHAAEBAgMAAgQFAXABAQEFBAEBAgIGDgJ/AUHwiQUL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gAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycjYC1IkBQQBBACgC0IkBIgFBGHQgAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycjYC0IkBQQBBACgCzIkBIgFBGHQgAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycjYCzIkBQQBBACgCyIkBIgFBGHQgAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZyciIBNgLIiQECQEEAKALoiQEiBEUNAEEAIAE6AIAJIARBAUYNACABQQh2IQNBASEBQQEhAgNAIAFBgAlqIAM6AAAgBCACQQFqIgJB/wFxIgFNDQEgAUHIiQFqLQAAIQMMAAsLCwYAQYCJAQujAQBBAEIANwPAiQFBAEEcQSAgAUHgAUYiARs2AuiJAUEAQqef5qfG9JP9vn9Cq7OP/JGjs/DbACABGzcD4IkBQQBCsZaA/p+ihazoAEL/pLmIxZHagpt/IAEbNwPYiQFBAEKXusODk6eWh3dC8ua746On/aelfyABGzcD0IkBQQBC2L2WiPygtb42QufMp9DW0Ouzu38gARs3A8iJASAAEAIQBAsLCwEAQYAICwRwAAAA";
+var hash$a = "817d957e";
+var wasmJson$a = {
+ name: name$a,
+ data: data$a,
+ hash: hash$a
+};
+
+const mutex$a = new Mutex();
+let wasmCache$a = null;
+/**
+ * Calculates SHA-2 (SHA-224) hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function sha224(data) {
+ if (wasmCache$a === null) {
+ return lockedCreate(mutex$a, wasmJson$a, 28)
+ .then((wasm) => {
+ wasmCache$a = wasm;
+ return wasmCache$a.calculate(data, 224);
+ });
+ }
+ try {
+ const hash = wasmCache$a.calculate(data, 224);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new SHA-2 (SHA-224) hash instance
+ */
+function createSHA224() {
+ return WASMInterface(wasmJson$a, 28).then((wasm) => {
+ wasm.init(224);
+ const obj = {
+ init: () => { wasm.init(224); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: 28,
+ };
+ return obj;
+ });
+}
+
+const mutex$9 = new Mutex();
+let wasmCache$9 = null;
+/**
+ * Calculates SHA-2 (SHA-256) hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function sha256(data) {
+ if (wasmCache$9 === null) {
+ return lockedCreate(mutex$9, wasmJson$a, 32)
+ .then((wasm) => {
+ wasmCache$9 = wasm;
+ return wasmCache$9.calculate(data, 256);
+ });
+ }
+ try {
+ const hash = wasmCache$9.calculate(data, 256);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new SHA-2 (SHA-256) hash instance
+ */
+function createSHA256() {
+ return WASMInterface(wasmJson$a, 32).then((wasm) => {
+ wasm.init(256);
+ const obj = {
+ init: () => { wasm.init(256); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: 32,
+ };
+ return obj;
+ });
+}
+
+var name$9 = "sha512";
+var data$9 = "AGFzbQEAAAABEQRgAAF/YAF/AGACf38AYAAAAwgHAAEBAgMAAgQFAXABAQEFBAEBAgIGDgJ/AUHQigULfwBBgAgLB3AIBm1lbW9yeQIADkhhc2hfR2V0QnVmZmVyAAAJSGFzaF9Jbml0AAELSGFzaF9VcGRhdGUAAgpIYXNoX0ZpbmFsAAQNSGFzaF9HZXRTdGF0ZQAFDkhhc2hfQ2FsY3VsYXRlAAYKU1RBVEVfU0laRQMBCvhnBwUAQYAJC5sCAEEAQgA3A4CKAUEAQTBBwAAgAEGAA0YiABs2AsiKAUEAQqSf6ffbg9LaxwBC+cL4m5Gjs/DbACAAG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4MgAEI4iISEhDcDkIoBQQBBACkDiIoBIgBCOIYgAEIohkKAgICAgIDA/wCDhCAAQhiGQoCAgICA4D+DIABCCIZCgICAgPAfg4SEIABCCIhCgICA+A+DIABCGIhCgID8B4OEIABCKIhCgP4DgyAAQjiIhISEIgA3A4iKAQJAQQAoAsiKASIDRQ0AQQAgADwAgAkgA0EBRg0AIABCCIinIQRBASEBQQEhAgNAIAFBgAlqIAQ6AAAgAyACQQFqIgJB/wFxIgFNDQEgAUGIigFqLQAAIQQMAAsLCwYAQYCJAQuhAgBBAEIANwOAigFBAEEwQcAAIAFBgANGIgEbNgLIigFBAEKkn+n324PS2scAQvnC+JuRo7Pw2wAgARs3A8CKAUEAQqef5qfWwYuGW0Lr+obav7X2wR8gARs3A7iKAUEAQpGq4ML20JLajn9Cn9j52cKR2oKbfyABGzcDsIoBQQBCsZaA/v/MyZnnAELRhZrv+s+Uh9EAIAEbNwOoigFBAEK5srm4j5v7lxVC8e30+KWn/aelfyABGzcDoIoBQQBCl7rDg6OrwKyRf0Kr8NP0r+68tzwgARs3A5iKAUEAQoeq87OjpYrN4gBCu86qptjQ67O7fyABGzcDkIoBQQBC2L2WiNyr591LQoiS853/zPmE6gAgARs3A4iKASAAEAIQBAsLCwEAQYAICwTQAAAA";
+var hash$9 = "a5d1ca7c";
+var wasmJson$9 = {
+ name: name$9,
+ data: data$9,
+ hash: hash$9
+};
+
+const mutex$8 = new Mutex();
+let wasmCache$8 = null;
+/**
+ * Calculates SHA-2 (SHA-384) hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function sha384(data) {
+ if (wasmCache$8 === null) {
+ return lockedCreate(mutex$8, wasmJson$9, 48)
+ .then((wasm) => {
+ wasmCache$8 = wasm;
+ return wasmCache$8.calculate(data, 384);
+ });
+ }
+ try {
+ const hash = wasmCache$8.calculate(data, 384);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new SHA-2 (SHA-384) hash instance
+ */
+function createSHA384() {
+ return WASMInterface(wasmJson$9, 48).then((wasm) => {
+ wasm.init(384);
+ const obj = {
+ init: () => { wasm.init(384); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 128,
+ digestSize: 48,
+ };
+ return obj;
+ });
+}
+
+const mutex$7 = new Mutex();
+let wasmCache$7 = null;
+/**
+ * Calculates SHA-2 (SHA-512) hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function sha512(data) {
+ if (wasmCache$7 === null) {
+ return lockedCreate(mutex$7, wasmJson$9, 64)
+ .then((wasm) => {
+ wasmCache$7 = wasm;
+ return wasmCache$7.calculate(data, 512);
+ });
+ }
+ try {
+ const hash = wasmCache$7.calculate(data, 512);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new SHA-2 (SHA-512) hash instance
+ */
+function createSHA512() {
+ return WASMInterface(wasmJson$9, 64).then((wasm) => {
+ wasm.init(512);
+ const obj = {
+ init: () => { wasm.init(512); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 128,
+ digestSize: 64,
+ };
+ return obj;
+ });
+}
+
+var name$8 = "xxhash32";
+var data$8 = "AGFzbQEAAAABEQRgAAF/YAF/AGAAAGACf38AAwcGAAEBAgADBAUBcAEBAQUEAQECAgYOAn8BQbCJBQt/AEGACAsHcAgGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAAlIYXNoX0luaXQAAQtIYXNoX1VwZGF0ZQACCkhhc2hfRmluYWwAAw1IYXNoX0dldFN0YXRlAAQOSGFzaF9DYWxjdWxhdGUABQpTVEFURV9TSVpFAwEKswkGBQB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jIkBQRJ3aiECDAELQQAoAoiJAUGxz9myAWohAgsgAiABaiECQZCJASEBQQAoAqCJASIDQZCJAWohBAJAIANBBEgNAEGQiQEhBQNAIAUoAgBBvdzKlXxsIAJqQRF3Qa/W074CbCECIAVBCGohBiAFQQRqIgEhBSAGIARNDQALCwJAIAEgBEYNACADQZCJAWohBQNAIAEtAABBsc/ZsgFsIAJqQQt3QbHz3fF5bCECIAUgAUEBaiIBRw0ACwtBACACQQ92IAJzQfeUr694bCIBQQ12IAFzQb3cypV8bCIBQRB2IAFzIgFBGHQgAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycq03A4AJCwYAQYCJAQtTAEEAQgA3A6iJAUEAIAE2AoiJAUEAIAFBz4yijgZqNgKMiQFBACABQfeUr694ajYChIkBQQAgAUGoiI2hAmo2AoCJAUEAQQA2AqCJASAAEAIQAwsLCwEAQYAICwQwAAAA";
+var hash$8 = "5b6a5062";
+var wasmJson$8 = {
+ name: name$8,
+ data: data$8,
+ hash: hash$8
+};
+
+const mutex$6 = new Mutex();
+let wasmCache$6 = null;
+function validateSeed$3(seed) {
+ if (!Number.isInteger(seed) || seed < 0 || seed > 0xFFFFFFFF) {
+ return new Error('Seed must be a valid 32-bit long unsigned integer.');
+ }
+ return null;
+}
+/**
+ * Calculates xxHash32 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param seed Number used to initialize the internal state of the algorithm (defaults to 0)
+ * @returns Computed hash as a hexadecimal string
+ */
+function xxhash32(data, seed = 0) {
+ if (validateSeed$3(seed)) {
+ return Promise.reject(validateSeed$3(seed));
+ }
+ if (wasmCache$6 === null) {
+ return lockedCreate(mutex$6, wasmJson$8, 4)
+ .then((wasm) => {
+ wasmCache$6 = wasm;
+ return wasmCache$6.calculate(data, seed);
+ });
+ }
+ try {
+ const hash = wasmCache$6.calculate(data, seed);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new xxHash32 hash instance
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param seed Number used to initialize the internal state of the algorithm (defaults to 0)
+ */
+function createXXHash32(seed = 0) {
+ if (validateSeed$3(seed)) {
+ return Promise.reject(validateSeed$3(seed));
+ }
+ return WASMInterface(wasmJson$8, 4).then((wasm) => {
+ wasm.init(seed);
+ const obj = {
+ init: () => { wasm.init(seed); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 16,
+ digestSize: 4,
+ };
+ return obj;
+ });
+}
+
+var name$7 = "xxhash64";
+var data$7 = "AGFzbQEAAAABDANgAAF/YAAAYAF/AAMHBgABAgEAAQQFAXABAQEFBAEBAgIGDgJ/AUHQiQULfwBBgAgLB3AIBm1lbW9yeQIADkhhc2hfR2V0QnVmZmVyAAAJSGFzaF9Jbml0AAELSGFzaF9VcGRhdGUAAgpIYXNoX0ZpbmFsAAMNSGFzaF9HZXRTdGF0ZQAEDkhhc2hfQ2FsY3VsYXRlAAUKU1RBVEVfU0laRQMBCqINBgUAQYAJC2MBAX5BAEIANwPIiQFBAEEAKQOACSIANwOQiQFBACAAQvnq0NDnyaHk4QB8NwOYiQFBACAAQs/W077Sx6vZQnw3A4iJAUEAIABC1uuC7ur9ifXgAHw3A4CJAUEAQQA2AsCJAQv/BQMDfwR+AX8CQCAARQ0AQQBBACkDyIkBIACtfDcDyIkBAkBBACgCwIkBIgEgAGpBH0sNAEEAIAFBAWo2AsCJASABQaCJAWpBAC0AgAk6AAAgAEEBRg0BQQEhAgNAQQBBACgCwIkBIgFBAWo2AsCJASABQaCJAWogAkGACWotAAA6AAAgACACQQFqIgJHDQAMAgsLIABB4AhqIQMCQAJAIAENAEEAKQOYiQEhBEEAKQOQiQEhBUEAKQOIiQEhBkEAKQOAiQEhB0GACSECDAELQYAJIQICQCABQR9LDQBBgAkhAgNAIAItAAAhCEEAIAFBAWo2AsCJASABQaCJAW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QoeVr6+Ytt6bnn9+QuPcypX8zvL1hX98IQEMAQtBACkDkIkBQsXP2bLx5brqJ3whAQsgASAAfCEAQaCJASEFQQAoAsCJASIGQaCJAWohBwJAIAZBCEgNAEGgiQEhCANAIAgpAwAiAULP1tO+0ser2UJ+QiGIIAFCgICAgPi0nfWTf36EQoeVr6+Ytt6bnn9+IACFQhuJQoeVr6+Ytt6bnn9+QuPcypX8zvL1hX98IQAgCEEQaiEJIAhBCGoiBSEIIAkgB00NAAsLAkACQCAFQQRqIgggB00NACAFIQgMAQsgBTUCAEKHla+vmLbem55/fiAAhUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAAsCQCAIIAdGDQAgBkGgiQFqIQkDQCAIMQAAQsXP2bLx5brqJ34gAIVCC4lCh5Wvr5i23puef34hACAJIAhBAWoiCEcNAAsLQQAgAEIhiCAAhULP1tO+0ser2UJ+IgBCHYggAIVC+fPd8Zn2masWfiIAQiCIIACFIgBCOIYgAEIohkKAgICAgIDA/wCDhCAAQhiGQoCAgICA4D+DIABCCIZCgICAgPAfg4SEIABCCIhCgICA+A+DIABCGIhCgID8B4OEIABCKIhCgP4DgyAAQjiIhISENwOACQsGAEGAiQELAgALCwsBAEGACAsEUAAAAA==";
+var hash$7 = "bc315b2a";
+var wasmJson$7 = {
+ name: name$7,
+ data: data$7,
+ hash: hash$7
+};
+
+const mutex$5 = new Mutex();
+let wasmCache$5 = null;
+const seedBuffer$2 = new ArrayBuffer(8);
+function validateSeed$2(seed) {
+ if (!Number.isInteger(seed) || seed < 0 || seed > 0xFFFFFFFF) {
+ return new Error('Seed must be given as two valid 32-bit long unsigned integers (lo + high).');
+ }
+ return null;
+}
+function writeSeed$2(arr, low, high) {
+ // write in little-endian format
+ const buffer = new DataView(arr);
+ buffer.setUint32(0, low, true);
+ buffer.setUint32(4, high, true);
+}
+/**
+ * Calculates xxHash64 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param seedLow Lower 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ * @param seedHigh Higher 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ * @returns Computed hash as a hexadecimal string
+ */
+function xxhash64(data, seedLow = 0, seedHigh = 0) {
+ if (validateSeed$2(seedLow)) {
+ return Promise.reject(validateSeed$2(seedLow));
+ }
+ if (validateSeed$2(seedHigh)) {
+ return Promise.reject(validateSeed$2(seedHigh));
+ }
+ if (wasmCache$5 === null) {
+ return lockedCreate(mutex$5, wasmJson$7, 8)
+ .then((wasm) => {
+ wasmCache$5 = wasm;
+ writeSeed$2(seedBuffer$2, seedLow, seedHigh);
+ wasmCache$5.writeMemory(new Uint8Array(seedBuffer$2));
+ return wasmCache$5.calculate(data);
+ });
+ }
+ try {
+ writeSeed$2(seedBuffer$2, seedLow, seedHigh);
+ wasmCache$5.writeMemory(new Uint8Array(seedBuffer$2));
+ const hash = wasmCache$5.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new xxHash64 hash instance
+ * @param seedLow Lower 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ * @param seedHigh Higher 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ */
+function createXXHash64(seedLow = 0, seedHigh = 0) {
+ if (validateSeed$2(seedLow)) {
+ return Promise.reject(validateSeed$2(seedLow));
+ }
+ if (validateSeed$2(seedHigh)) {
+ return Promise.reject(validateSeed$2(seedHigh));
+ }
+ return WASMInterface(wasmJson$7, 8).then((wasm) => {
+ const instanceBuffer = new ArrayBuffer(8);
+ writeSeed$2(instanceBuffer, seedLow, seedHigh);
+ wasm.writeMemory(new Uint8Array(instanceBuffer));
+ wasm.init();
+ const obj = {
+ init: () => {
+ wasm.writeMemory(new Uint8Array(instanceBuffer));
+ wasm.init();
+ return obj;
+ },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 32,
+ digestSize: 8,
+ };
+ return obj;
+ });
+}
+
+var name$6 = "xxhash3";
+var data$6 = "AGFzbQEAAAABJAZgAAF/YAR/f39/AGAHf39/f39/fwBgA39/fgF+YAAAYAF/AAMMCwABAgMDAwQFBAAEBAUBcAEBAQUEAQECAgYOAn8BQcCOBQt/AEHACQsHcAgGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAAlIYXNoX0luaXQABgtIYXNoX1VwZGF0ZQAHCkhhc2hfRmluYWwACA1IYXNoX0dldFN0YXRlAAkOSGFzaF9DYWxjdWxhdGUACgpTVEFURV9TSVpFAwEK+joLBQBBgAoL7wMBEH4CQCADRQ0AIAFBOGohASACQThqIQIgACkDMCEEIAApAzghBSAAKQMgIQYgACkDKCEHIAApAxAhCCAAKQMYIQkgACkDACEKIAApAwghCwNAIAcgAUFoaikDACIMfCACQXBqKQMAIAFBcGopAwAiDYUiB0IgiCAHQv////8Pg358IQcgCSABQVhqKQMAIg58IAJBYGopAwAgAUFgaikDACIPhSIJQiCIIAlC/////w+DfnwhCSALIAFBSGopAwAiEHwgAkFQaikDACABQVBqKQMAIhGFIgtCIIggC0L/////D4N+fCELIAJBeGopAwAgAUF4aikDACIShSITQiCIIBNC/////w+DfiAEfCABKQMAIhN8IQQgAkFoaikDACAMhSIMQiCIIAxC/////w+DfiAGfCANfCEGIAJBWGopAwAgDoUiDEIgiCAMQv////8Pg34gCHwgD3whCCACQUhqKQMAIBCFIgxCIIggDEL/////D4N+IAp8IBF8IQogBSASfCACKQMAIBOFIgVCIIggBUL/////D4N+fCEFIAFBwABqIQEgAkEIaiECIANBf2oiAw0ACyAAIAk3AxggACAKNwMAIAAgCzcDCCAAIAc3AyggACAINwMQIAAgBTcDOCAAIAY3AyAgACAENwMwCwveAgIBfwF+AkAgAiABKAIAIgdrIgIgBEsNACAAIAMgBSAHQQN0aiACEAEgACAAKQMAIgggBSAGaiIHKQMAhSAIQi+IhUKx893xC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gASkDQIUiA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC94IAQZ+IACtQoeVr6+Ytt6bnn9+IQMCQCAAQSFJDQACQCAAQcEASQ0AAkAgAEHhAEkNACABKQNoIAJ9QQApA7iMAYUiBEL/////D4MiBSABKQNgIAJ8QQApA7CMAYUiBkIgiCIHfiIIQv////8PgyAEQiCIIgQgBkL/////D4MiBn58IAUgBn4iBUIgiHwiBkIghiAFQv////8Pg4QgCEIgiCAEIAd+fCAGQiCIfIUgA3wgASkDeCACfSAAQciLAWopAwCFIgNC/////w+DIgQgASkDcCACfCAAQcCLAWopAwCFIgVCIIgiBn4iB0L/////D4MgA0IgiCIDIAVC/////w+DIgV+fCAEIAV+IgRCIIh8IgVCIIYgBEL/////D4OEIAdCIIggAyAGfnwgBUIgiHyFfCEDCyABKQNIIAJ9QQApA6iMAYUiBEL/////D4MiBSABKQNAIAJ8QQApA6CMAYUiBkIgiCIHfiIIQv////8PgyAEQiCIIgQgBkL/////D4MiBn58IAUgBn4iBUIgiHwiBkIghiAFQv////8Pg4QgCEIgiCAEIAd+fCAGQiCIfIUgA3wgASkDWCACfSAAQdiLAWopAwCFIgNC/////w+DIgQgASkDUCACfCAAQdCLAWopAwCFIgVCIIgiBn4iB0L/////D4MgA0IgiCIDIAVC/////w+DIgV+fCAEIAV+IgRCIIh8IgVCIIYgBEL/////D4OEIAdCIIggAyAGfnwgBUIgiHyFfCEDCyABKQMoIAJ9QQApA5iMAYUiBEL/////D4MiBSABKQMgIAJ8QQApA5CMAYUiBkIgiCIHfiIIQv////8PgyAEQiCIIgQgBkL/////D4MiBn58IAUgBn4iBUIgiHwiBkIghiAFQv////8Pg4QgCEIgiCAEIAd+fCAGQiCIfIUgA3wgASkDOCACfSAAQeiLAWopAwCFIgNC/////w+DIgQgASkDMCACfCAAQeCLAWopAwCFIgVCIIgiBn4iB0L/////D4MgA0IgiCIDIAVC/////w+DIgV+fCAEIAV+IgRCIIh8IgVCIIYgBEL/////D4OEIAdCIIggAyAGfnwgBUIgiHyFfCEDCyABKQMIIAJ9QQApA4iMAYUiBEL/////D4MiBSABKQMAIAJ8QQApA4CMAYUiBkIgiCIHfiIIQv////8PgyAEQiCIIgQgBkL/////D4MiBn58IAUgBn4iBUIgiHwiBkIghiAFQv////8Pg4QgCEIgiCAEIAd+fCAGQiCIfIUgA3wgASkDGCACfSAAQfiLAWopAwCFIgNC/////w+DIgQgASkDECACfCAAQfCLAWopAwCFIgJCIIgiBX4iBkL/////D4MgA0IgiCIDIAJC/////w+DIgJ+fCAEIAJ+IgJCIIh8IgRCIIYgAkL/////D4OEIAZCIIggAyAFfnwgBEIgiHyFfCICQiWIIAKFQvnz3fGZ8pmrFn4iAkIgiCAChQuICwQBfwV+An8BfkEAIQMgASkDeCACfUEAKQP4jAGFIgRC/////w+DIgUgASkDcCACfEEAKQPwjAGFIgZCIIgiB34iCEL/////D4MgBEIgiCIEIAZC/////w+DIgZ+fCAFIAZ+IgVCIIh8IgZCIIYgBUL/////D4OEIAhCIIggBCAHfnwgBkIgiHyFIAEpA2ggAn1BACkD6IwBhSIEQv////8PgyIFIAEpA2AgAnxBACkD4IwBhSIGQiCIIgd+IghC/////w+DIARCIIgiBCAGQv////8PgyIGfnwgBSAGfiIFQiCIfCIGQiCGIAVC/////w+DhCAIQiCIIAQgB358IAZCIIh8hSABKQNYIAJ9QQApA9iMAYUiBEL/////D4MiBSABKQNQIAJ8QQApA9CMAYUiBkIgiCIHfiIIQv////8PgyAEQiCIIgQgBkL/////D4MiBn58IAUgBn4iBUIgiHwiBkIghiAFQv////8Pg4QgCEIgiCAEIAd+fCAGQiCIfIUgASkDSCACfUEAKQPIjAGFIgRC/////w+DIgUgASkDQCACfEEAKQPAjAGFIgZCIIgiB34iCEL/////D4MgBEIgiCIEIAZC/////w+DIgZ+fCAFIAZ+IgVCIIh8IgZCIIYgBUL/////D4OEIAhCIIggBCAHfnwgBkIgiHyFIAEpAzggAn1BACkDuIwBhSIEQv////8PgyIFIAEpAzAgAnxBACkDsIwBhSIGQiCIIgd+IghC/////w+DIARCIIgiBCAGQv////8PgyIGfnwgBSAGfiIFQiCIfCIGQiCGIAVC/////w+DhCAIQiCIIAQgB358IAZCIIh8hSABKQMoIAJ9QQApA6iMAYUiBEL/////D4MiBSABKQMgIAJ8QQApA6CMAYUiBkIgiCIHfiIIQv////8PgyAEQiCIIgQgBkL/////D4MiBn58IAUgBn4iBUIgiHwiBkIghiAFQv////8Pg4QgCEIgiCAEIAd+fCAGQiCIfIUgASkDGCACfUEAKQOYjAGFIgRC/////w+DIgUgASkDECACfEEAKQOQjAGFIgZCIIgiB34iCEL/////D4MgBEIgiCIEIAZC/////w+DIgZ+fCAFIAZ+IgVCIIh8IgZCIIYgBUL/////D4OEIAhCIIggBCAHfnwgBkIgiHyFIAEpAwggAn1BACkDiIwBhSIEQv////8PgyIFIAEpAwAgAnxBACkDgIwBhSIGQiCIIgd+IghC/////w+DIARCIIgiBCAGQv////8PgyIGfnwgBSAGfiIFQiCIfCIGQiCGIAVC/////w+DhCAIQiCIIAQgB358IAZCIIh8hSAArUKHla+vmLbem55/fnx8fHx8fHx8IgRCJYggBIVC+fPd8ZnymasWfiIEQiCIIASFIQQgAEEQbSEJAkAgAEGQAUgNACAJQQkgCUEJShtBeGohCQNAIAEgA2oiCkELaikDACACfSADQYiNAWopAwCFIgVC/////w+DIgYgCkEDaikDACACfCADQYCNAWopAwCFIgdCIIgiCH4iC0L/////D4MgBUIgiCIFIAdC/////w+DIgd+fCAGIAd+IgZCIIh8IgdCIIYgBkL/////D4OEIAtCIIggBSAIfnwgB0IgiHyFIAR8IQQgA0EQaiEDIAlBf2oiCQ0ACwsgASkDfyACfSAAQfiLAWopAwCFIgVC/////w+DIgYgASkDdyACfCAAQfCLAWopAwCFIgJCIIgiB34iCEL/////D4MgBUIgiCIFIAJC/////w+DIgJ+fCAGIAJ+IgJCIIh8IgZCIIYgAkL/////D4OEIAhCIIggBSAHfnw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NBgAohBAJAAkAgAEEITw0AIAAhAQwBCyAAIQEDQCADIAQpAwA3AwAgA0EIaiEDIARBCGohBCABQXhqIgFBB0sNAAsLIAFFDQEDQCADIAQtAAA6AAAgA0EBaiEDIARBAWohBCABQX9qIgENAAtBACgCgI4BIABqIQIMAQtBgAohAyAAQYAKaiECQQAoArCOASIEQcCKASAEGyEAAkAgAUUNACABQYCMAWohA0GACiEEAkACQEGAAiABayIFQQhPDQAgBSEBDAELIAUhAQNAIAMgBCkDADcDACADQQhqIQMgBEEIaiEEIAFBeGoiAUEHSw0ACwsCQCABRQ0AA0AgAyAELQAAOgAAIANBAWohAyAEQQFqIQQgAUF/aiIBDQALC0GAigFBiI4BQQAoApiOAUGAjAFBBCAAQQAoApyOARACQQBBADYCgI4BIAVBgApqIQMLAkAgA0GAAmogAk8NACACQYB+aiEEA0BBgIoBQYiOAUEAKAKYjgEgA0EEIABBACgCnI4BEAIgA0GAAmoiAyAESQ0AC0EAIANBQGopAwA3A8CNAUEAIANBSGopAwA3A8iNAUEAIANBUGopAwA3A9CNAUEAIANBWGopAwA3A9iNAUEAIANBYGopAwA3A+CNAUEAIANBaGopAwA3A+iNAUEAIANBcGopAwA3A/CNAUEAIANBeGopAwA3A/iNAQtBgIwBIQQCQAJAIAIgA2siAkEITw0AIAIhAQwBCyACIQEDQCAEIAMpAwA3AwAgBEEIaiEEIANBCGohAyABQXhqIgFBB0sNAAsLIAFFDQADQCAEIAMtAAA6AAAgBEEBaiEEIANBAWohAyABQX9qIgENAAsLQQAgAjYCgI4BC6oQBQR/AX4Cfwp+An8jACIAIQEgAEGAAWtBQHEiAiQAQQAoArCOASIAQcCKASAAGyEDAkACQEEAKQOQjgEiBELxAVQNACACQQApA4CKATcDACACQQApA4iKATcDCCACQQApA5CKATcDECACQQApA5iKATcDGCACQQApA6CKATcDICACQQApA6iKATcDKCACQQApA7CKATcDMCACQQApA7iKATcDOAJAAkBBACgCgI4BIgVBwABJDQAgAkEAKAKIjgE2AkAgAiACQcAAakEAKAKYjgFBgIwBIAVBf2pBBnYgA0EAKAKcjgEQAiACIAIpAwhBACgCgI4BIgBBwIsBaikDACIEfCADQQAoApyOAWoiBkEBaikDACAAQciLAWopAwAiB4UiCEIgiCAIQv////8Pg358Igk3AwggAiACKQMYIABB0IsBaikDACIIfCAGQRFqKQMAIABB2IsBaikDACIKhSILQiCIIAtC/////w+DfnwiDDcDGCACIAcgBCAGQXlqKQMAhSIEQiCIIARC/////w+DfiACKQMAfHwiDTcDACACIAogCCAGQQlqKQMAhSIEQiCIIARC/////w+DfiACKQMQfHwiDjcDECAGQRlqKQMAIQQgAikDICEHIAIgAikDKCAAQeCLAWopAwAiCHwgBkEhaikDACAAQeiLAWopAwAiCoUiC0IgiCALQv////8Pg358Ig83AyggAiAKIAcgBCAIhSIEQiCIIARC/////w+Dfnx8IhA3AyAgAiACKQM4IABB8IsBaikDACIEfCAGQTFqKQMAIABB+IsBaikDACIHhSIIQiCIIAhC/////w+Dfnw3AzggByAEIAZBKWopAwCFIgRCIIggBEL/////D4N+IAIpAzB8fCEEDAELQcAAIAVrIRECQAJAAkAgBUE4TQ0AQYCOASARayEGIAJBwABqIQUgESEADAELQQAhEiARIQADQCACQcAAaiASaiAFIBJqQcCNAWopAwA3AwAgEkEIaiESIABBeGoiAEEHSw0ACyAFIBJqIgZBwABGDQEgBkHAjQFqIQYgAkHAAGogEmohBQsDQCAFIAYtAAA6AAAgBUEBaiEFIAZBAWohBiAAQX9qIgANAAtBACgCgI4BIQULIAJBwABqIBFqIQZBgIwBIQACQCAFQQhJDQBBgIwBIQADQCAGIAApAwA3AwAgBkEIaiEGIABBCGohACAFQXhqIgVBB0sNAAsLAkAgBUUNAANAIAYgAC0AADoAACAGQQFqIQYgAEEBaiEAIAVBf2oiBQ0ACwsgAiACKQMIIAIpA0AiBHwgA0EAKAKcjgFqIgBBAWopAwAgAikDSCIHhSIIQiCIIAhC/////w+DfnwiCTcDCCACIAIpAxggAikDUCIIfCAAQRFqKQMAIAIpA1giCoUiC0IgiCALQv////8Pg358Igw3AxggAiAHIAQgAEF5aikDAIUiBEIgiCAEQv////8Pg34gAikDAHx8Ig03AwAgAiAKIAggAEEJaikDAIUiBEIgiCAEQv////8Pg34gAikDEHx8Ig43AxAgAEEZaikDACEEIAIpAyAhByACIAIpAyggAikDYCIIfCAAQSFqKQMAIAIpA2giCoUiC0IgiCALQv////8Pg358Ig83AyggAiAKIAcgBCAIhSIEQiCIIARC/////w+Dfnx8IhA3AyAgAiACKQM4IAIpA3AiBHwgAEExaikDACACKQN4IgeFIghCIIggCEL/////D4N+fDcDOCAHIAQgAEEpaikDAIUiBEIgiCAEQv////8Pg34gAikDMHx8IQQLIAIgBDcDMCADKQNDIAIpAziFIgdC/////w+DIgggAykDOyAEhSIEQiCIIgp+IgtC/////w+DIAdCIIgiByAEQv////8PgyIEfnwgCCAEfiIEQiCIfCIIQiCGIARC/////w+DhCALQiCIIAcgCn58IAhCIIh8hSADKQMzIA+FIgRC/////w+DIgcgAykDKyAQhSIIQiCIIgp+IgtC/////w+DIARCIIgiBCAIQv////8PgyIIfnwgByAIfiIHQiCIfCIIQiCGIAdC/////w+DhCALQiCIIAQgCn58IAhCIIh8hSADKQMjIAyFIgRC/////w+DIgcgAykDGyAOhSIIQiCIIgp+IgtC/////w+DIARCIIgiBCAIQv////8PgyIIfnwgByAIfiIHQiCIfCIIQiCGIAdC/////w+DhCALQiCIIAQgCn58IAhCIIh8hSADKQMTIAmFIgRC/////w+DIgcgAykDCyANhSIIQiCIIgp+IgtC/////w+DIARCIIgiBCAIQv////8PgyIIfnwgByAIfiIHQiCIfCIIQiCGIAdC/////w+DhCALQiCIIAQgCn58IAhCIIh8hUEAKQOQjgFCh5Wvr5i23puef358fHx8IgRCJYggBIVC+fPd8ZnymasWfiIEQiCIIASFIQQMAQsgBKchAAJAQQApA6COASIEUA0AAkAgAEEQSw0AIABBgAggBBADIQQMAgsCQCAAQYABSw0AIABBgAggBBAEIQQMAgsgAEGACCAEEAUhBAwBCwJAIABBEEsNACAAIANCABADIQQMAQsCQCAAQYABSw0AIAAgA0IAEAQhBAwBCyAAIANCABAFIQQLQQAgBEI4hiAEQiiGQoCAgICAgMD/AIOEIARCGIZCgICAgIDgP4MgBEIIhkKAgICA8B+DhIQgBEIIiEKAgID4D4MgBEIYiEKAgPwHg4QgBEIoiEKA/gODIARCOIiEhIQ3A4AKIAEkAAsGAEGAigELAgALC8wBAQBBgAgLxAG4/mw5I6RLvnwBgSz3Ia0c3tRt6YOQl9tyQKSkt7NnH8t55k7MwOV4glrQfcz/ciG4CEZ090MkjuA1kOaBOiZMPChSu5HDAMuI0GWLG1Muo3FkSJeiDflOOBnvRqnerNio+nY/45w0P/ncu8fHC08dilHgS820WTHIn37J2XhzZOrFrIM00+vDxYGg//oTY+sXDd1Rt/DaSdMWVSYp1GieKxa+WH1HofyP+LjRetAxzkXLOo+VFgQor9f7yrtLQH5AAgAA";
+var hash$6 = "187bc2c6";
+var wasmJson$6 = {
+ name: name$6,
+ data: data$6,
+ hash: hash$6
+};
+
+const mutex$4 = new Mutex();
+let wasmCache$4 = null;
+const seedBuffer$1 = new ArrayBuffer(8);
+function validateSeed$1(seed) {
+ if (!Number.isInteger(seed) || seed < 0 || seed > 0xFFFFFFFF) {
+ return new Error('Seed must be given as two valid 32-bit long unsigned integers (lo + high).');
+ }
+ return null;
+}
+function writeSeed$1(arr, low, high) {
+ // write in little-endian format
+ const buffer = new DataView(arr);
+ buffer.setUint32(0, low, true);
+ buffer.setUint32(4, high, true);
+}
+/**
+ * Calculates xxHash3 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param seedLow Lower 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ * @param seedHigh Higher 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ * @returns Computed hash as a hexadecimal string
+ */
+function xxhash3(data, seedLow = 0, seedHigh = 0) {
+ if (validateSeed$1(seedLow)) {
+ return Promise.reject(validateSeed$1(seedLow));
+ }
+ if (validateSeed$1(seedHigh)) {
+ return Promise.reject(validateSeed$1(seedHigh));
+ }
+ if (wasmCache$4 === null) {
+ return lockedCreate(mutex$4, wasmJson$6, 8)
+ .then((wasm) => {
+ wasmCache$4 = wasm;
+ writeSeed$1(seedBuffer$1, seedLow, seedHigh);
+ wasmCache$4.writeMemory(new Uint8Array(seedBuffer$1));
+ return wasmCache$4.calculate(data);
+ });
+ }
+ try {
+ writeSeed$1(seedBuffer$1, seedLow, seedHigh);
+ wasmCache$4.writeMemory(new Uint8Array(seedBuffer$1));
+ const hash = wasmCache$4.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new xxHash3 hash instance
+ * @param seedLow Lower 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ * @param seedHigh Higher 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ */
+function createXXHash3(seedLow = 0, seedHigh = 0) {
+ if (validateSeed$1(seedLow)) {
+ return Promise.reject(validateSeed$1(seedLow));
+ }
+ if (validateSeed$1(seedHigh)) {
+ return Promise.reject(validateSeed$1(seedHigh));
+ }
+ return WASMInterface(wasmJson$6, 8).then((wasm) => {
+ const instanceBuffer = new ArrayBuffer(8);
+ writeSeed$1(instanceBuffer, seedLow, seedHigh);
+ wasm.writeMemory(new Uint8Array(instanceBuffer));
+ wasm.init();
+ const obj = {
+ init: () => {
+ wasm.writeMemory(new Uint8Array(instanceBuffer));
+ wasm.init();
+ return obj;
+ },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 512,
+ digestSize: 8,
+ };
+ return obj;
+ });
+}
+
+var name$5 = "xxhash128";
+var data$5 = "AGFzbQEAAAABKwdgAAF/YAR/f39/AGAHf39/f39/fwBgA39/fgF+YAR/f39+AGAAAGABfwADDQwAAQIDBAQEBQYFA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Qi+IhUKx893xCX43AyAgACAAKQMoIgggBykDKIUgCEIviIVCsfPd8Ql+NwMoIAAgACkDMCIIIAcpAzCFIAhCL4iFQrHz3fEJfjcDMCAAIAApAzgiCCAHKQM4hSAIQi+IhUKx893xCX43AzggACADIAJBBnRqIAUgBCACayIHEAEgASAHNgIADwsgACADIAUgB0EDdGogBBABIAEgByAEajYCAAvtAwEFfiABKQM4IAApAziFIgNC/////w+DIgQgASkDMCAAKQMwhSIFQiCIIgZ+IgdC/////w+DIANCIIgiAyAFQv////8PgyIFfnwgBCAFfiIEQiCIfCIFQiCGIARC/////w+DhCAHQiCIIAMgBn58IAVCIIh8hSABKQMoIAApAyiFIgNC/////w+DIgQgASkDICAAKQMghSIFQiCIIgZ+IgdC/////w+DIANCIIgiAyAFQv////8PgyIFfnwgBCAFfiIEQiCIfCIFQiCGIARC/////w+DhCAHQiCIIAMgBn58IAVCIIh8hSABKQMYIAApAxiFIgNC/////w+DIgQgASkDECAAKQMQhSIFQiCIIgZ+IgdC/////w+DIANCIIgiAyAFQv////8PgyIFfnwgBCAFfiIEQiCIfCIFQiCGIARC/////w+DhCAHQiCIIAMgBn58IAVCIIh8hSABKQMIIAApAwiFIgNC/////w+DIgQgASkDACAAKQMAhSIFQiCIIgZ+IgdC/////w+DIANCIIgiAyAFQv////8PgyIFfnwgBCAFfiIEQiCIfCIFQiCGIARC/////w+DhCAHQiCIIAMgBn58IAVCIIh8hSACfHx8fCICQiWIIAKFQvnz3fGZ8pmrFn4iAkIgiCAChQvCCAEFfgJAIAFBCUkNACAAQQApA4CMASACKQMoIAIpAyCFIAN9hSABQfiLAWopAwAiBIUiBUIgiCIGQoeVr68IfiIHQv////8PgyAFQv////8PgyIFQrHz3fEJfnwgBUKHla+vCH4iBUIgiHwiCEIghiAFQv////8Pg4QgAUF/aq1CNoZ8IAQgAikDOCACKQMwhSADfIUiA0L/////D4NC95Svrwh+IANCgICAgHCDfCAGQrHz3fEJfnwgB0IgiHwgCEIgiHwiA0I4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AIAOFIAIpA0iFIgNCIYggA4VCz9bTvtLHq9lCfiIDQh2IIAOFQvnz3fGZ9pmrFn4iA0IgiCADhTcDAAunCgEKfiABrSIEQoeVr6+Ytt6bnn9+IQUCQAJAIAFBIU8NAEIAIQYMAQtCACEHAkAgAUHBAEkNAEIAIQcCQCABQeEASQ0AIAIpA3ggA30gAUHIiwFqKQMAIgiFIgdC/////w+DIgkgAikDcCADfCABQcCLAWopAwAiCoUiC0IgiCIMfiINQiCIIAdCIIgiByAMfnwgDUL/////D4MgByALQv////8PgyILfnwgCSALfiIHQiCIfCIJQiCIfEEAKQO4jAEiC0EAKQOwjAEiDHyFIAlCIIYgB0L/////D4OEhSEHIAIpA2ggA30gC4UiCUL/////D4MiCyACKQNgIAN8IAyFIgxCIIgiDX4iBkL/////D4MgCUIgiCIJIAxC/////w+DIgx+fCALIAx+IgtCIIh8IgxCIIYgC0L/////D4OEIAZCIIggCSANfnwgDEIgiHyFIAV8IAggCnyFIQULIAIpA1ggA30gAUHYiwFqKQMAIgiFIglC/////w+DIgogAikDUCADfCABQdCLAWopAwAiC4UiDEIgiCINfiIGQv////8PgyAJQiCIIgkgDEL/////D4MiDH58IAogDH4iCkIgiHwiDEIghiAKQv////8Pg4QgBkIgiCAJIA1+fCAMQiCIfIUgB3xBACkDqIwBIglBACkDoIwBIgp8hSEHIAIpA0ggA30gCYUiCUL/////D4MiDCACKQNAIAN8IAqFIgpCIIgiDX4iBkL/////D4MgCUIgiCIJIApC/////w+DIgp+fCAMIAp+IgpCIIh8IgxCIIYgCkL/////D4OEIAZCIIggCSANfnwgDEIgiHyFIAV8IAggC3yFIQULIAIpAzggA30gAUHoiwFqKQMAIgiFIglC/////w+DIgogAikDMCADfCABQeCLAWopAwAiC4UiDEIgiCINfiIGQv////8PgyAJQiCIIgkgDEL/////D4MiDH58IAogDH4iCkIgiHwiDEIghiAKQv////8Pg4QgBkIgiCAJIA1+fCAMQiCIfIUgB3xBACkDmIwBIgdBACkDkIwBIgl8hSEGIAIpAyggA30gB4UiB0L/////D4MiCiACKQMgIAN8IAmFIglCIIgiDH4iDUL/////D4MgB0IgiCIHIAlC/////w+DIgl+fCAKIAl+IglCIIh8IgpCIIYgCUL/////D4OEIA1CIIggByAMfnwgCkIgiHyFIAV8IAggC3yFIQULIAAgAikDGCADfSABQfiLAWopAwAiB4UiCEL/////D4MiCSACKQMQIAN8IAFB8IsBaikDACIKhSILQiCIIgx+Ig1C/////w+DIAhCIIgiCCALQv////8PgyILfnwgCSALfiIJQiCIfCILQiCGIAlC/////w+DhCANQiCIIAggDH58IAtCIIh8hSAGfEEAKQOIjAEiCEEAKQOAjAEiCXyFIgsgAikDCCADfSAIhSIIQv////8PgyIMIAIpAwAgA3wgCYUiCUIgiCINfiIGQv////8PgyAIQiCIIgggCUL/////D4MiCX58IAwgCX4iCUIgiHwiDEIghiAJQv////8Pg4QgBkIgiCAIIA1+fCAMQiCIfIUgBXwgByAKfIUiBXwiB0IliCAHhUL5893xmfKZqxZ+IgdCIIggB4U3AwAgAEIAIAVCh5Wvr5i23puef34gBCADfULP1tO+0ser2UJ+fCALQuPcypX8zvL1hX9+fCIDQiWIIAOFQvnz3fGZ8pmrFn4iA0IgiCADhX03AwgLiQ8DAX8UfgJ/QQAhBCACKQN4IAN9QQApA/iMASIFhSIGQv////8PgyIHIAIpA3AgA3xBACkD8IwBIgiFIglCIIgiCn4iC0L/////D4MgBkIgiCIGIAlC/////w+DIgl+fCAHIAl+IgdCIIh8IglCIIYgB0L/////D4OEIAtCIIggBiAKfnwgCUIgiHyFIAIpA1ggA31BACkD2IwBIgeFIgZC/////w+DIgkgAikDUCADfEEAKQPQjAEiCoUiC0IgiCIMfiINQv////8PgyAGQiCIIgYgC0L/////D4MiC358IAkgC34iCUIgiHwiC0IghiAJQv////8Pg4QgDUIgiCAGIAx+fCALQiCIfIUgAikDOCADfUEAKQO4jAEiCYUiBkL/////D4MiCyACKQMwIAN8QQApA7CMASIMhSINQiCIIg5+Ig9C/////w+DIAZCIIgiBiANQv////8PgyINfnwgCyANfiILQiCIfCINQiCGIAtC/////w+DhCAPQiCIIAYgDn58IA1CIIh8hSACKQMYIAN9QQApA5iMASILhSIGQv////8PgyINIAIpAxAgA3xBACkDkIwBIg6FIg9CIIgiEH4iEUL/////D4MgBkIgiCIGIA9C/////w+DIg9+fCANIA9+Ig1CIIh8Ig9CIIYgDUL/////D4OEIBFCIIggBiAQfnwgD0IgiHyFQQApA4iMASINQQApA4CMASIPfIV8QQApA6iMASIQQQApA6CMASIRfIV8QQApA8iMASISQQApA8CMASITfIV8QQApA+iMASIUQQApA+CMASIVfIUiBkIliCAGhUL5893xmfKZqxZ+IgZCIIggBoUhBiACKQNoIAN9IBSFIhRC/////w+DIhYgAikDYCADfCAVhSIVQiCIIhd+IhhC/////w+DIBRCIIgiFCAVQv////8PgyIVfnwgFiAVfiIVQiCIfCIWQiCGIBVC/////w+DhCAYQiCIIBQgF358IBZCIIh8hSACKQNIIAN9IBKFIhJC/////w+DIhQgAikDQCADfCAThSITQiCIIhV+IhZC/////w+DIBJCIIgiEiATQv////8PgyITfnwgFCATfiITQiCIfCIUQiCGIBNC/////w+DhCAWQiCIIBIgFX58IBRCIIh8hSACKQMoIAN9IBCFIhBC/////w+DIhIgAikDICADfCARhSIRQiCIIhN+IhRC/////w+DIBBCIIgiECARQv////8PgyIRfnwgEiARfiIRQiCIfCISQiCGIBFC/////w+DhCAUQiCIIBAgE358IBJCIIh8hSACKQMIIAN9IA2FIg1C/////w+DIhAgAikDACADfCAPhSIPQiCIIhF+IhJC/////w+DIA1CIIgiDSAPQv////8PgyIPfnwgECAPfiIPQiCIfCIQQiCGIA9C/////w+DhCASQiCIIA0gEX58IBBCIIh8hSABrSIPQoeVr6+Ytt6bnn9+fCALIA58hXwgCSAMfIV8IAcgCnyFfCAFIAh8hSIFQiWIIAWFQvnz3fGZ8pmrFn4iBUIgiCAFhSEFIAFBIG0hGQJAIAFBoAFIDQAgGUEFIBlBBUobQXxqIRoDQCACIARq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WopAwAgAkHYiwFqKQMAIgmFIgpCIIggCkL/////D4N+fDcDGCAAIAcgBCAGQXlqKQMAhSIEQiCIIARC/////w+DfiAAKQMAfHw3AwAgACAJIAggBkEJaikDAIUiBEIgiCAEQv////8Pg34gACkDEHx8NwMQIAZBGWopAwAhBCAAKQMgIQcgACAAKQMoIAJB4IsBaikDACIIfCAGQSFqKQMAIAJB6IsBaikDACIJhSIKQiCIIApC/////w+Dfnw3AyggACAJIAcgBCAIhSIEQiCIIARC/////w+Dfnx8NwMgIAAgACkDOCACQfCLAWopAwAiBHwgBkExaikDACACQfiLAWopAwAiB4UiCEIgiCAIQv////8Pg358NwM4IAAgByAEIAZBKWopAwCFIgRCIIggBEL/////D4N+IAApAzB8fDcDMAwBC0HAACAFayELAkACQAJAIAVBOE0NAEGAjgEgC2shBiAAQcAAaiEFIAshAgwBC0EAIQwgCyECA0AgAEHAAGogDGogBSAMakHAjQFqKQMANwMAIAxBCGohDCACQXhqIgJBB0sNAAsgBSAMaiIGQcAARg0BIAZBwI0BaiEGIABBwABqIAxqIQULA0AgBSAGLQAAOgAAIAVBAWohBSAGQQFqIQYgAkF/aiICDQALQQAoAoCOASEFCyAAQcAAaiALaiEGQYCMASECAkAgBUEISQ0AQYCMASECA0AgBiACKQMANwMAIAZBCGohBiACQQhqIQIgBUF4aiIFQQdLDQALCwJAIAVFDQADQCAGIAItAAA6AAAgBkEBaiEGIAJBAWohAiAFQX9qIgUNAAsLIAAgACkDCCAAKQNAIgR8IANBACgCnI4BaiICQQFqKQMAIAApA0giB4UiCEIgiCAIQv////8Pg358NwMIIAAgACkDGCAAKQNQIgh8IAJBEWopAwAgACkDWCIJhSIKQiCIIApC/////w+Dfnw3AxggACAHIAQgAkF5aikDAIUiBEIgiCAEQv////8Pg34gACkDAHx8NwMAIAAgCSAIIAJBCWopAwCFIgRCIIggBEL/////D4N+IAApAxB8fDcDECACQRlqKQMAIQQgACkDICEHIAAgACkDKCAAKQNgIgh8IAJBIWopAwAgACkD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cLTx2KUeBLzbRZMciffsnZeHNk6sWsgzTT68PFgaD/+hNj6xcN3VG38NpJ0xZVJinUaJ4rFr5YfUeh/I/4uNF60DHORcs6j5UWBCiv1/vKu0tAfkACAAA=";
+var hash$5 = "e8e3fcf8";
+var wasmJson$5 = {
+ name: name$5,
+ data: data$5,
+ hash: hash$5
+};
+
+const mutex$3 = new Mutex();
+let wasmCache$3 = null;
+const seedBuffer = new ArrayBuffer(8);
+function validateSeed(seed) {
+ if (!Number.isInteger(seed) || seed < 0 || seed > 0xFFFFFFFF) {
+ return new Error('Seed must be given as two valid 32-bit long unsigned integers (lo + high).');
+ }
+ return null;
+}
+function writeSeed(arr, low, high) {
+ // write in little-endian format
+ const buffer = new DataView(arr);
+ buffer.setUint32(0, low, true);
+ buffer.setUint32(4, high, true);
+}
+/**
+ * Calculates xxHash128 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @param seedLow Lower 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ * @param seedHigh Higher 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ * @returns Computed hash as a hexadecimal string
+ */
+function xxhash128(data, seedLow = 0, seedHigh = 0) {
+ if (validateSeed(seedLow)) {
+ return Promise.reject(validateSeed(seedLow));
+ }
+ if (validateSeed(seedHigh)) {
+ return Promise.reject(validateSeed(seedHigh));
+ }
+ if (wasmCache$3 === null) {
+ return lockedCreate(mutex$3, wasmJson$5, 16)
+ .then((wasm) => {
+ wasmCache$3 = wasm;
+ writeSeed(seedBuffer, seedLow, seedHigh);
+ wasmCache$3.writeMemory(new Uint8Array(seedBuffer));
+ return wasmCache$3.calculate(data);
+ });
+ }
+ try {
+ writeSeed(seedBuffer, seedLow, seedHigh);
+ wasmCache$3.writeMemory(new Uint8Array(seedBuffer));
+ const hash = wasmCache$3.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new xxHash128 hash instance
+ * @param seedLow Lower 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ * @param seedHigh Higher 32 bits of the number used to
+ * initialize the internal state of the algorithm (defaults to 0)
+ */
+function createXXHash128(seedLow = 0, seedHigh = 0) {
+ if (validateSeed(seedLow)) {
+ return Promise.reject(validateSeed(seedLow));
+ }
+ if (validateSeed(seedHigh)) {
+ return Promise.reject(validateSeed(seedHigh));
+ }
+ return WASMInterface(wasmJson$5, 16).then((wasm) => {
+ const instanceBuffer = new ArrayBuffer(8);
+ writeSeed(instanceBuffer, seedLow, seedHigh);
+ wasm.writeMemory(new Uint8Array(instanceBuffer));
+ wasm.init();
+ const obj = {
+ init: () => {
+ wasm.writeMemory(new Uint8Array(instanceBuffer));
+ wasm.init();
+ return obj;
+ },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 512,
+ digestSize: 16,
+ };
+ return obj;
+ });
+}
+
+var name$4 = "ripemd160";
+var data$4 = "AGFzbQEAAAABEQRgAAF/YAAAYAF/AGACf38AAwkIAAECAwIBAAIEBQFwAQEBBQQBAQICBg4CfwFB4IkFC38AQcAICweDAQkGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAAlIYXNoX0luaXQAARByaXBlbWQxNjBfdXBkYXRlAAMLSGFzaF9VcGRhdGUABApIYXNoX0ZpbmFsAAUNSGFzaF9HZXRTdGF0ZQAGDkhhc2hfQ2FsY3VsYXRlAAcKU1RBVEVfU0laRQMBCtAxCAUAQYAJCzoAQQBB8MPLnnw2ApiJAUEAQv6568XpjpWZEDcCkIkBQQBCgcaUupbx6uZvNwKIiQFBAEIANwKAiQELpiwBHn9BACAAKAIkIgEgACgCACICIAAoAhAiAyACIAAoAiwiBCAAKAIMIgUgACgCBCIGIAAoAjwiByACIAAoAjAiCCAHIAAoAggiCUEAKAKIiQEiCkEAKAKQiQEiC0EAKAKUiQEiDEF/c3JB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EiA0sNAAtBnIkBEAIgASACayEBIAAgAmohAEEAIQILAkAgAUHAAEkNAANAIAAQAiAAQcAAaiEAIAFBQGoiAUE/Sw0ACwsgAUUNAEEAIQNBACEEA0AgAyACakGciQFqIAAgA2otAAA6AAAgASAEQQFqIgRB/wFxIgNLDQALCwsJAEGACSAAEAMLggEBAn8jAEEQayIAJAAgAEEAKAKAiQEiAUEDdDYCCCAAQQAoAoSJAUEDdCABQR12cjYCDEGACEE4QfgAIAFBP3EiAUE4SRsgAWsQAyAAQQhqQQgQA0EAQQAoAoiJATYCgAlBAEEAKQKMiQE3AoQJQQBBACkClIkBNwKMCSAAQRBqJAALBgBBgIkBC8EBAQF/IwBBEGsiASQAQQBB8MPLnnw2ApiJAUEAQv6568XpjpWZEDcCkIkBQQBCgcaUupbx6uZvNwKIiQFBAEIANwKAiQFBgAkgABADIAFBACgCgIkBIgBBA3Q2AgggAUEAKAKEiQFBA3QgAEEddnI2AgxBgAhBOEH4ACAAQT9xIgBBOEkbIABrEAMgAUEIakEIEANBAEEAKAKIiQE2AoAJQQBBACkCjIkBNwKECUEAQQApApSJATcCjAkgAUEQaiQACwtLAQBBgAgLRIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABcAAAA";
+var hash$4 = "42f1de39";
+var wasmJson$4 = {
+ name: name$4,
+ data: data$4,
+ hash: hash$4
+};
+
+const mutex$2 = new Mutex();
+let wasmCache$2 = null;
+/**
+ * Calculates RIPEMD-160 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function ripemd160(data) {
+ if (wasmCache$2 === null) {
+ return lockedCreate(mutex$2, wasmJson$4, 20)
+ .then((wasm) => {
+ wasmCache$2 = wasm;
+ return wasmCache$2.calculate(data);
+ });
+ }
+ try {
+ const hash = wasmCache$2.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new RIPEMD-160 hash instance
+ */
+function createRIPEMD160() {
+ return WASMInterface(wasmJson$4, 20).then((wasm) => {
+ wasm.init();
+ const obj = {
+ init: () => { wasm.init(); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: 20,
+ };
+ return obj;
+ });
+}
+
+function calculateKeyBuffer(hasher, key) {
+ const { blockSize } = hasher;
+ const buf = getUInt8Buffer(key);
+ if (buf.length > blockSize) {
+ hasher.update(buf);
+ const uintArr = hasher.digest('binary');
+ hasher.init();
+ return uintArr;
+ }
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
+}
+function calculateHmac(hasher, key) {
+ hasher.init();
+ const { blockSize } = hasher;
+ const keyBuf = calculateKeyBuffer(hasher, key);
+ const keyBuffer = new Uint8Array(blockSize);
+ keyBuffer.set(keyBuf);
+ const opad = new Uint8Array(blockSize);
+ for (let i = 0; i < blockSize; i++) {
+ const v = keyBuffer[i];
+ opad[i] = v ^ 0x5C;
+ keyBuffer[i] = v ^ 0x36;
+ }
+ hasher.update(keyBuffer);
+ const obj = {
+ init: () => {
+ hasher.init();
+ hasher.update(keyBuffer);
+ return obj;
+ },
+ update: (data) => {
+ hasher.update(data);
+ return obj;
+ },
+ digest: ((outputType) => {
+ const uintArr = hasher.digest('binary');
+ hasher.init();
+ hasher.update(opad);
+ hasher.update(uintArr);
+ return hasher.digest(outputType);
+ }),
+ save: () => {
+ throw new Error('save() not supported');
+ },
+ load: () => {
+ throw new Error('load() not supported');
+ },
+ blockSize: hasher.blockSize,
+ digestSize: hasher.digestSize,
+ };
+ return obj;
+}
+/**
+ * Calculates HMAC hash
+ * @param hash Hash algorithm to use. It has to be the return value of a function like createSHA1()
+ * @param key Key (string, Buffer or TypedArray)
+ */
+function createHMAC(hash, key) {
+ if (!hash || !hash.then) {
+ throw new Error('Invalid hash function is provided! Usage: createHMAC(createMD5(), "key").');
+ }
+ return hash.then((hasher) => calculateHmac(hasher, key));
+}
+
+function calculatePBKDF2(digest, salt, iterations, hashLength, outputType) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const DK = new Uint8Array(hashLength);
+ const block1 = new Uint8Array(salt.length + 4);
+ const block1View = new DataView(block1.buffer);
+ const saltBuffer = getUInt8Buffer(salt);
+ const saltUIntBuffer = new Uint8Array(saltBuffer.buffer, saltBuffer.byteOffset, saltBuffer.length);
+ block1.set(saltUIntBuffer);
+ let destPos = 0;
+ const hLen = digest.digestSize;
+ const l = Math.ceil(hashLength / hLen);
+ let T = null;
+ let U = null;
+ for (let i = 1; i <= l; i++) {
+ block1View.setUint32(salt.length, i);
+ digest.init();
+ digest.update(block1);
+ T = digest.digest('binary');
+ U = T.slice();
+ for (let j = 1; j < iterations; j++) {
+ digest.init();
+ digest.update(U);
+ U = digest.digest('binary');
+ for (let k = 0; k < hLen; k++) {
+ T[k] ^= U[k];
+ }
+ }
+ DK.set(T.subarray(0, hashLength - destPos), destPos);
+ destPos += hLen;
+ }
+ if (outputType === 'binary') {
+ return DK;
+ }
+ const digestChars = new Uint8Array(hashLength * 2);
+ return getDigestHex(digestChars, DK, hashLength);
+ });
+}
+const validateOptions$2 = (options) => {
+ if (!options || typeof options !== 'object') {
+ throw new Error('Invalid options parameter. It requires an object.');
+ }
+ if (!options.hashFunction || !options.hashFunction.then) {
+ throw new Error('Invalid hash function is provided! Usage: pbkdf2("password", "salt", 1000, 32, createSHA1()).');
+ }
+ if (!Number.isInteger(options.iterations) || options.iterations < 1) {
+ throw new Error('Iterations should be a positive number');
+ }
+ if (!Number.isInteger(options.hashLength) || options.hashLength < 1) {
+ throw new Error('Hash length should be a positive number');
+ }
+ if (options.outputType === undefined) {
+ options.outputType = 'hex';
+ }
+ if (!['hex', 'binary'].includes(options.outputType)) {
+ throw new Error(`Insupported output type ${options.outputType}. Valid values: ['hex', 'binary']`);
+ }
+};
+/**
+ * Generates a new PBKDF2 hash for the supplied password
+ */
+function pbkdf2(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ validateOptions$2(options);
+ const hmac = yield createHMAC(options.hashFunction, options.password);
+ return calculatePBKDF2(hmac, options.salt, options.iterations, options.hashLength, options.outputType);
+ });
+}
+
+var name$3 = "scrypt";
+var data$3 = "AGFzbQEAAAABIwZgAX8Bf2AAAX9gBX9/fn9/AGAEf39/fwBgAX8AYAN/f38AAwcGAAECAwQFBAUBcAEBAQUGAQECgIACBggBfwFBkIgECwc5BAZtZW1vcnkCABJIYXNoX1NldE1lbW9yeVNpemUAAA5IYXNoX0dldEJ1ZmZlcgABBnNjcnlwdAAFCpcmBlsBAX9BACEBAkAgAEEAKAKACGsiAEUNAAJAIABBEHYgAEGAgHxxIABJaiIAQABBf0cNAEH/ASEBDAELQQAhAUEAQQApA4AIIABBEHStfDcDgAgLIAFBGHRBGHULagECfwJAQQAoAogIIgANAEEAPwBBEHQiADYCiAhBgIAgQQAoAoAIayIBRQ0AAkAgAUEQdiABQYCAfHEgAUlqIgBAAEF/Rw0AQQAPC0EAQQApA4AIIABBEHStfDcDgAhBACgCiAghAAsgAAu5EAMMfwl+An8gAUEFdCEFIAQgAUEIdGohBiAEIAFBB3QiB2ohCAJAAkACQAJAIAFFDQBBACEJIAAhCiAEIQsDQCALIAooAgA2AgAgCkEEaiEKIAtBBGohCyAJQQFqIgkgBUkNAAsgAlANAiABQQh0IQxBACENIAMhDgNAQQAhCSABIQ8DQCAOIAlqIgogBCAJaiILKQMANwMAIApBCGogC0EIaikDADcDACAKQRBqIAtBEGopAwA3AwAgCkEYaiALQRhqKQMANwMAIApBIGogC0EgaikDADcDACAKQShqIAtBKGopAwA3AwAgCkEwaiALQTBqKQMANwMAIApBOGogC0E4aikDADcDACAKQcAAaiALQcAAaikDADcDACAKQcgAaiALQcgAaikDADcDACAKQdAAaiALQdAAaikDADcDACAKQdgAaiALQdgAaikDADcDACAKQeAAaiALQeAAaikDADcDACAKQegAaiALQegAaikDADcDACAKQfAAaiALQfAAaikDADcDACAKQfgAaiALQfgAaikDADcDACAJQYABaiEJIA9Bf2oiDw0ACyAEIAggBiABEAMgDiEJIAQhDyABIRADQCAJIAdqIgogDyAHaiILKQMANwMAIApBCGogC0EIaikDADcDACAKQRBqIAtBEGopAwA3AwAgCkEYaiALQRhqKQMANwMAIApBIGogC0EgaikDADcDACAKQShqIAtBKGopAwA3AwAgCkEwaiALQTBqKQMANwMAIApBOGogC0E4aikDADcDACAKQcAAaiALQcAAaikDADcDACAKQcgAaiALQcgAaikDADcDACAKQdAAaiALQdAAaikDADcDACAKQdgAaiALQdgAaikDADcDACAKQeAAaiALQeAAaikDADcDACAKQegAaiALQegAaikDADcDACAKQfAAaiALQfAAaikDADcDACAKQfgAaiALQfgAaikDADcDACAJQYABaiEJIA9BgAFqIQ8gEEF/aiIQDQALIAggBCAGIAEQAyAOIAxqIQ4gDUECaiINrSACVA0ADAILCyACUA0CIAhBQGoiCikDOCERIAopAzAhEiAKKQMoIRMgCikDICEUIAopAxghFSAKKQMQIRYgCikDCCEXIAopAwAhGEECIQoDQCAKrSEZIApBAmohCiAZIAJUDQALIAYgETcDOCAGIBI3AzAgBiATNwMoIAYgFDcDICAGIBU3AxggBiAWNwMQIAYgFzcDCCAGIBg3AwALAkAgAUUNACAHQUBqIgogCGohGiACp0F/aiEOIAogBGohGyABQQd0IQ1BACEMA0AgAyANIBsoAgAgDnFsaiEHQQAhCSABIQ8DQCAEIAlqIgogCikDACAHIAlqIgspAwCFNwMAIApBCGoiECAQKQMAIAtBCGopAwCFNwMAIApBEGoiECAQKQMAIAtBEGopAwCFNwMAIApBGGoiECAQKQMAIAtBGGopAwCFNwMAIApBIGoiECAQKQMAIAtBIGopAwCFNwMAIApBKGoiECAQKQMAIAtBKGopAwCFNwMAIApBMGoiECAQKQMAIAtBMGopAwCFNwMAIApBOGoiECAQKQMAIAtBOGopAwCFNwMAIApBwABqIhAgECkDACALQc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QRJ3IAZzajYCPAtyAwF/AX4CfwJAIAJFDQBBACgCiAgiAyAAIAGtIgQgAyAAQQd0IgUgAmxqIgMgAyAFIAFsaiIGEAIgAkEBRg0AIAJBf2ohASAFIQIDQEEAKAKICCACaiAAIAQgAyAGEAIgAiAFaiECIAFBf2oiAQ0ACwsL";
+var hash$3 = "d96fb75f";
+var wasmJson$3 = {
+ name: name$3,
+ data: data$3,
+ hash: hash$3
+};
+
+function scryptInternal(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const { costFactor, blockSize, parallelism, hashLength, } = options;
+ const SHA256Hasher = createSHA256();
+ const blockData = yield pbkdf2({
+ password: options.password,
+ salt: options.salt,
+ iterations: 1,
+ hashLength: 128 * blockSize * parallelism,
+ hashFunction: SHA256Hasher,
+ outputType: 'binary',
+ });
+ const scryptInterface = yield WASMInterface(wasmJson$3, 0);
+ // last block is for storing the temporary vectors
+ const VSize = 128 * blockSize * costFactor;
+ const XYSize = 256 * blockSize;
+ scryptInterface.setMemorySize(blockData.length + VSize + XYSize);
+ scryptInterface.writeMemory(blockData, 0);
+ // mix blocks
+ scryptInterface.getExports().scrypt(blockSize, costFactor, parallelism);
+ const expensiveSalt = scryptInterface
+ .getMemory()
+ .subarray(0, 128 * blockSize * parallelism);
+ const outputData = yield pbkdf2({
+ password: options.password,
+ salt: expensiveSalt,
+ iterations: 1,
+ hashLength,
+ hashFunction: SHA256Hasher,
+ outputType: 'binary',
+ });
+ if (options.outputType === 'hex') {
+ const digestChars = new Uint8Array(hashLength * 2);
+ return getDigestHex(digestChars, outputData, hashLength);
+ }
+ // return binary format
+ return outputData;
+ });
+}
+// eslint-disable-next-line no-bitwise
+const isPowerOfTwo = (v) => v && !(v & (v - 1));
+const validateOptions$1 = (options) => {
+ if (!options || typeof options !== 'object') {
+ throw new Error('Invalid options parameter. It requires an object.');
+ }
+ if (!Number.isInteger(options.blockSize) || options.blockSize < 1) {
+ throw new Error('Block size should be a positive number');
+ }
+ if (!Number.isInteger(options.costFactor)
+ || options.costFactor < 2
+ || !isPowerOfTwo(options.costFactor)) {
+ throw new Error('Cost factor should be a power of 2, greater than 1');
+ }
+ if (!Number.isInteger(options.parallelism) || options.parallelism < 1) {
+ throw new Error('Parallelism should be a positive number');
+ }
+ if (!Number.isInteger(options.hashLength) || options.hashLength < 1) {
+ throw new Error('Hash length should be a positive number.');
+ }
+ if (options.outputType === undefined) {
+ options.outputType = 'hex';
+ }
+ if (!['hex', 'binary'].includes(options.outputType)) {
+ throw new Error(`Insupported output type ${options.outputType}. Valid values: ['hex', 'binary']`);
+ }
+};
+/**
+ * Calculates hash using the scrypt password-based key derivation function
+ * @returns Computed hash as a hexadecimal string or as
+ * Uint8Array depending on the outputType option
+ */
+function scrypt(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ validateOptions$1(options);
+ return scryptInternal(options);
+ });
+}
+
+var name$2 = "bcrypt";
+var data$2 = "AGFzbQEAAAABFwRgAAF/YAR/f39/AGADf39/AGABfwF/AwUEAAECAwQFAXABAQEFBAEBAgIGCAF/AUGQqwULBzQEBm1lbW9yeQIADkhhc2hfR2V0QnVmZmVyAAAGYmNyeXB0AAINYmNyeXB0X3ZlcmlmeQADCuRbBAUAQYArC5FVAxJ/BX4HfyMAQfAAayEEIAJBADoAAiACQargADsAAAJAIAEtAABBKkcNACABLQABQTBHDQAgAkExOgABCwJAIAEsAAUgASwABEEKbGpB8HtqIgVBBEkNAEEBIAV0IQYgAUEHaiEFIARBGGohByAEQQhqIQgDQCAFLQAAQWBqIglB3wBLDQEgCUGACGotAAAiCkE/Sw0BIAVBAWotAABBYGoiCUHfAEsNASAJQYAIai0AACIJQT9LDQEgCCAJQQR2IApBAnRyOgAAAkAgCEEBaiIIIAdPDQAgBUECai0AAEFgaiIKQd8ASw0CIApBgAhqLQAAIgpBP0sNAiAIIApBAnYgCUEEdHI6AAAgCEEBaiIIIAdPDQAgBUEDai0AAEFgaiIJQd8ASw0CIAlBgAhqLQAAIglBP0sNAiAIIAkgCk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kA8sObuzgO9uYFr6gmExk6XgyMpUfn9+S0+ArNKDTHvJxiUF0ChuMNKNLIHG+xdgydsONnzXfLi+Zm0dvC+Yd8eMPVNpM5ZHY2h7PeWLOb34+zWaxGBYFHSz9xdKPhJki+/ZX8yP1I3YypjE1qJMCzcxWYoHwrLXrdVqXNhZuzHPSiJJilt7QSbmBG5BQTBRWxnG9x8bmChR6MgbQ4UWae/LD/VOqyQAPqGLivyW79tK9NQVpEnEiAgSyfM/Ltiucds3APhFT0+NAFmC9qzjwrUclnCA4unbORvfFoa93YGB1IE7+y4XYjeiKsPmqen6q+UxcwkgZjIr7AuRqwwH54evWafjUkKDeXKYtJQk/n+YIwjJhTrdb4nfO49+PV+ZywzqIaj8k0wijhS6KGRNEc3ADIjgJpNAxnymY+i4IiWxO7OYhKEV3E9A4z2ZUvmwM6TS3KazA3VB8ybXVhD8XCUe12dUWkhv7eYk=";
+var hash$2 = "9f4c7b9e";
+var wasmJson$2 = {
+ name: name$2,
+ data: data$2,
+ hash: hash$2
+};
+
+function bcryptInternal(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const { costFactor, password, salt } = options;
+ const bcryptInterface = yield WASMInterface(wasmJson$2, 0);
+ bcryptInterface.writeMemory(getUInt8Buffer(salt), 0);
+ const passwordBuffer = getUInt8Buffer(password);
+ bcryptInterface.writeMemory(passwordBuffer, 16);
+ const shouldEncode = options.outputType === 'encoded' ? 1 : 0;
+ bcryptInterface.getExports().bcrypt(passwordBuffer.length, costFactor, shouldEncode);
+ const memory = bcryptInterface.getMemory();
+ if (options.outputType === 'encoded') {
+ return intArrayToString(memory, 60);
+ }
+ if (options.outputType === 'hex') {
+ const digestChars = new Uint8Array(24 * 2);
+ return getDigestHex(digestChars, memory, 24);
+ }
+ // return binary format
+ // the data is copied to allow GC of the original memory buffer
+ return memory.slice(0, 24);
+ });
+}
+const validateOptions = (options) => {
+ if (!options || typeof options !== 'object') {
+ throw new Error('Invalid options parameter. It requires an object.');
+ }
+ if (!Number.isInteger(options.costFactor) || options.costFactor < 4 || options.costFactor > 31) {
+ throw new Error('Cost factor should be a number between 4 and 31');
+ }
+ options.password = getUInt8Buffer(options.password);
+ if (options.password.length < 1) {
+ throw new Error('Password should be at least 1 byte long');
+ }
+ if (options.password.length > 72) {
+ throw new Error('Password should be at most 72 bytes long');
+ }
+ options.salt = getUInt8Buffer(options.salt);
+ if (options.salt.length !== 16) {
+ throw new Error('Salt should be 16 bytes long');
+ }
+ if (options.outputType === undefined) {
+ options.outputType = 'encoded';
+ }
+ if (!['hex', 'binary', 'encoded'].includes(options.outputType)) {
+ throw new Error(`Insupported output type ${options.outputType}. Valid values: ['hex', 'binary', 'encoded']`);
+ }
+};
+/**
+ * Calculates hash using the bcrypt password-hashing function
+ * @returns Computed hash
+ */
+function bcrypt(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ validateOptions(options);
+ return bcryptInternal(options);
+ });
+}
+const validateHashCharacters = (hash) => {
+ if (!/^\$2[axyb]\$[0-3][0-9]\$[./A-Za-z0-9]{53}$/.test(hash)) {
+ return false;
+ }
+ if (hash[4] === '0' && parseInt(hash[5], 10) < 4) {
+ return false;
+ }
+ if (hash[4] === '3' && parseInt(hash[5], 10) > 1) {
+ return false;
+ }
+ return true;
+};
+const validateVerifyOptions = (options) => {
+ if (!options || typeof options !== 'object') {
+ throw new Error('Invalid options parameter. It requires an object.');
+ }
+ if (options.hash === undefined || typeof options.hash !== 'string') {
+ throw new Error('Hash should be specified');
+ }
+ if (options.hash.length !== 60) {
+ throw new Error('Hash should be 60 bytes long');
+ }
+ if (!validateHashCharacters(options.hash)) {
+ throw new Error('Invalid hash');
+ }
+ options.password = getUInt8Buffer(options.password);
+ if (options.password.length < 1) {
+ throw new Error('Password should be at least 1 byte long');
+ }
+ if (options.password.length > 72) {
+ throw new Error('Password should be at most 72 bytes long');
+ }
+};
+/**
+ * Verifies password using bcrypt password-hashing function
+ * @returns True if the encoded hash matches the password
+ */
+function bcryptVerify(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ validateVerifyOptions(options);
+ const { hash, password } = options;
+ const bcryptInterface = yield WASMInterface(wasmJson$2, 0);
+ bcryptInterface.writeMemory(getUInt8Buffer(hash), 0);
+ const passwordBuffer = getUInt8Buffer(password);
+ bcryptInterface.writeMemory(passwordBuffer, 60);
+ return !!bcryptInterface.getExports().bcrypt_verify(passwordBuffer.length);
+ });
+}
+
+var name$1 = "whirlpool";
+var data$1 = "AGFzbQEAAAABEQRgAAF/YAF/AGACf38AYAAAAwkIAAECAwEDAAEEBQFwAQEBBQQBAQICBg4CfwFB0JsFC38AQYAYCwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACUhhc2hfSW5pdAADC0hhc2hfVXBkYXRlAAQKSGFzaF9GaW5hbAAFDUhhc2hfR2V0U3RhdGUABg5IYXNoX0NhbGN1bGF0ZQAHClNUQVRFX1NJWkUDAQrgGggFAEGAGQv0BgEIfiAAKQMAIQFBAEEAKQOAmwEiAjcDgJkBIAApAxghAyAAKQMQIQQgACkDCCEFQQBBACkDmJsBIgY3A5iZAUEAQQApA5CbASIHNwOQmQFBAEEAKQOImwEiCDcDiJkBQQAgASAChTcDwJkBQQAgBSAIhTcDyJkBQQAgBCAHhTcD0JkBQQAgAyAGhTcD2JkBIAApAyAhAUEAQQApA6CbASICNwOgmQFBACABIAKFNwPgmQEgACkDKCEBQQBBACkDqJsBIgI3A6iZAUEAIAEgAoU3A+iZASAAKQMwIQFBAEEAKQOwmwEiAjcDsJkBQQAgASAChTcD8JkBIAApAzghAUEAQQApA7ibASICNwO4mQFBACABIAKFNwP4mQFBAEKYxpjG/pDugM8ANwOAmgFBgJkBQYCaARACQcCZAUGAmQEQAkEAQrbMyq6f79vI0gA3A4CaAUGAmQFBgJoBEAJBwJkBQYCZARACQQBC4Pju9LiUw701NwOAmgFBgJkBQYCaARACQcCZAUGAmQEQAkEAQp3A35bs5ZL/1wA3A4CaAUGAmQFBgJoBEAJBwJkBQYCZARACQQBC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SZFpYmJHok8lw+1FBRQFKBEKLTh4aPhW0LfuhYWWBawTiymOjroOs3SdPdpablpb9DSBgkJJAlILRJBcHDdcKet4Ne2tuK22VRxb9DQZ9DOt70e7e2T7Tt+x9bMzBfMLtuF4kJCFUIqV4RomJhamLTCLSykpKqkSQ5V7SgooChdiFB1XFxtXNoxuIb4+Mf4kz/ta4aGIoZEpBHCkAAAAA==";
+var hash$1 = "358808f8";
+var wasmJson$1 = {
+ name: name$1,
+ data: data$1,
+ hash: hash$1
+};
+
+const mutex$1 = new Mutex();
+let wasmCache$1 = null;
+/**
+ * Calculates Whirlpool hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function whirlpool(data) {
+ if (wasmCache$1 === null) {
+ return lockedCreate(mutex$1, wasmJson$1, 64)
+ .then((wasm) => {
+ wasmCache$1 = wasm;
+ return wasmCache$1.calculate(data);
+ });
+ }
+ try {
+ const hash = wasmCache$1.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new Whirlpool hash instance
+ */
+function createWhirlpool() {
+ return WASMInterface(wasmJson$1, 64).then((wasm) => {
+ wasm.init();
+ const obj = {
+ init: () => { wasm.init(); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: 64,
+ };
+ return obj;
+ });
+}
+
+var index_esm_name = "sm3";
+var data = "AGFzbQEAAAABDANgAAF/YAAAYAF/AAMIBwABAgIBAAIEBQFwAQEBBQQBAQICBg4CfwFB8IkFC38AQYAICwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACUhhc2hfSW5pdAABC0hhc2hfVXBkYXRlAAIKSGFzaF9GaW5hbAAEDUhhc2hfR2V0U3RhdGUABQ5IYXNoX0NhbGN1bGF0ZQAGClNUQVRFX1NJW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ALC0GoiQEQAyACQUhqIgVFDQEgAEEIakHAACACa2ohAQsgBkGoiQFqIQMDQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASAFQX9qIgUNAAsLQQBBACgCiIkBIgFBGHQgAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycjYCgAlBAEEAKAKMiQEiAUEYdCABQQh0QYCA/AdxciABQQh2QYD+A3EgAUEYdnJyNgKECUEAQQAoApCJASIBQRh0IAFBCHRBgID8B3FyIAFBCHZBgP4DcSABQRh2cnI2AogJQQBBACgClIkBIgFBGHQgAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycjYCjAlBAEEAKAKYiQEiAUEYdCABQQh0QYCA/AdxciABQQh2QYD+A3EgAUEYdnJyNgKQCUEAQQAoApyJASIBQRh0IAFBCHRBgID8B3FyIAFBCHZBgP4DcSABQRh2cnI2ApQJQQBBACgCoIkBIgFBGHQgAUEIdEGAgPwHcXIgAUEIdkGA/gNxIAFBGHZycjYCmAlBAEEAKAKkiQEiAUEYdCABQQh0QYCA/AdxciABQQh2QYD+A3EgAUEYdnJyNgKcCSAAQRBqJAALBgBBgIkBC8ABAQJ/QQBCzdy3nO7Jw/2wfzcCoIkBQQBCvOG8y6qVzpgWNwKYiQFBAELXhZG5gcCBxVo3ApCJAUEAQu+sgJyX16yKyQA3AoiJAUEAQgA3AoCJAQJAIABFDQBBACAANgKAiQFBgAkhAQJAIABBwABJDQBBgAkhAQNAIAEQAyABQcAAaiEBIABBQGoiAEE/Sw0ACyAARQ0BC0EAIQIDQCACQaiJAWogASACai0AADoAACAAIAJBAWoiAkcNAAsLEAQLC1ECAEGACAsEaAAAAABBkAgLQIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
+var hash = "6e6f46ad";
+var wasmJson = {
+ name: index_esm_name,
+ data: data,
+ hash: hash
+};
+
+const mutex = new Mutex();
+let wasmCache = null;
+/**
+ * Calculates SM3 hash
+ * @param data Input data (string, Buffer or TypedArray)
+ * @returns Computed hash as a hexadecimal string
+ */
+function sm3(data) {
+ if (wasmCache === null) {
+ return lockedCreate(mutex, wasmJson, 32)
+ .then((wasm) => {
+ wasmCache = wasm;
+ return wasmCache.calculate(data);
+ });
+ }
+ try {
+ const hash = wasmCache.calculate(data);
+ return Promise.resolve(hash);
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+/**
+ * Creates a new SM3 hash instance
+ */
+function createSM3() {
+ return WASMInterface(wasmJson, 32).then((wasm) => {
+ wasm.init();
+ const obj = {
+ init: () => { wasm.init(); return obj; },
+ update: (data) => { wasm.update(data); return obj; },
+ digest: (outputType) => wasm.digest(outputType),
+ save: () => wasm.save(),
+ load: (data) => { wasm.load(data); return obj; },
+ blockSize: 64,
+ digestSize: 32,
+ };
+ return obj;
+ });
+}
+
+
+
+;// CONCATENATED MODULE: ./src/wacz/ziprangereader.js
+
+
+
+
+// ===========================================================================
+const MAX_INT32 = 0xFFFFFFFF;
+const MAX_INT16 = 0xFFFF;
+
+
+// ===========================================================================
+class LoadMoreException
+{
+ constructor(start, length) {
+ this.start = start;
+ this.length = length;
+ }
+}
+
+// ===========================================================================
+class HashingAsyncIterReader extends c
+{
+ constructor(source, compressed = "gzip", dechunk = false) {
+ super(source, compressed, dechunk);
+ }
+
+ async initHasher() {
+ this.hasher = await createSHA256();
+ }
+
+ async _loadNext() {
+ const value = await super._loadNext();
+ if (value) {
+ this.hasher.update(value);
+ }
+ return value;
+ }
+
+ getHash() {
+ return "sha256:" + this.hasher.digest("hex");
+ }
+}
+
+// ===========================================================================
+class ZipRangeReader
+{
+ constructor(loader, entries = null) {
+ this.loader = loader;
+ this.entries = entries;
+ this.entriesUpdated = false;
+
+ // todo: make configurable
+ this.enableHashing = true;
+ }
+
+ async load(always = false) {
+ if (!this.entries || always) {
+ const totalLength = await this.loader.getLength();
+
+ const length = Math.min(MAX_INT16 + 23, totalLength);
+ const start = totalLength - length;
+ const endChunk = await this.loader.getRange(start, length);
+
+ try {
+ this.entries = this._loadEntries(endChunk, start);
+ } catch (e) {
+ if (e instanceof LoadMoreException) {
+ const extraChunk = await this.loader.getRange(e.start, e.length);
+ const combinedChunk = y([extraChunk, endChunk], e.length + length);
+ this.entries = this._loadEntries(combinedChunk, e.start);
+ }
+ }
+
+ this.entriesUpdated = true;
+ }
+ return this.entries;
+ }
+
+ _loadEntries(data, dataStartOffset) {
+ // Adapted from
+ // Copyright (c) 2016 Rob Wu (https://robwu.nl)
+ // * Published under a MIT license.
+ // * https://github.com/Rob--W/zipinfo.js
+ const length = data.byteLength;
+
+ if (!length) {
+ return null;
+ }
+
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
+
+ const utf8Decoder = new TextDecoder("utf8");
+ const asciiDecoder = new TextDecoder("ascii");
+ const entries = {};
+
+ let entriesLeft = 0;
+ let offset = 0;
+ let endoffset = length;
+ // Find EOCD (0xFFFF is the maximum size of an optional trailing comment).
+ for (let i = length - 22, ii = Math.max(0, i - MAX_INT16); i >= ii; --i) {
+ if (data[i] === 0x50 && data[i + 1] === 0x4b &&
+ data[i + 2] === 0x05 && data[i + 3] === 0x06) {
+ endoffset = i;
+ offset = view.getUint32(i + 16, true);
+ entriesLeft = view.getUint16(i + 8, true);
+ break;
+ }
+ }
+
+ //ZIP64 find offset
+ if (offset === MAX_INT32 || entriesLeft === MAX_INT16) {
+ if (view.getUint32(endoffset - 20, true) !== 0x07064b50) {
+ console.warn("invalid zip64 EOCD locator");
+ return;
+ }
+
+ const zip64Offset = this.getUint64(view, endoffset - 12, true);
+
+ const viewOffset = zip64Offset - dataStartOffset;
+
+ if (view.getUint32(viewOffset, true) !== 0x06064b50) {
+ console.warn("invalid zip64 EOCD record");
+ return;
+ }
+
+ entriesLeft = this.getUint64(view, viewOffset + 32, true);
+ offset = this.getUint64(view, viewOffset + 48, true);
+ //zip64 = true;
+ }
+
+ if (offset >= dataStartOffset) {
+ offset -= dataStartOffset;
+ } else if (offset < dataStartOffset && offset > 0) {
+ throw new LoadMoreException(offset, dataStartOffset - offset);
+ }
+
+ if (offset >= length || offset < 0) {
+ // EOCD not found or malformed. Try to recover if possible (the result is
+ // most likely going to be incomplete or bogus, but we can try...).
+ offset = -1;
+ entriesLeft = MAX_INT16;
+ while (++offset < length && data[offset] !== 0x50 &&
+ data[offset + 1] !== 0x4b && data[offset + 2] !== 0x01 &&
+ data[offset + 3] !== 0x02);
+ }
+
+ endoffset -= 46; // 46 = minimum size of an entry in the central directory.
+
+ while (--entriesLeft >= 0 && offset < endoffset) {
+ if (view.getUint32(offset) != 0x504b0102) {
+ break;
+ }
+
+ const bitFlag = view.getUint16(offset + 8, true);
+ let compressedSize = view.getUint32(offset + 20, true);
+ let uncompressedSize = view.getUint32(offset + 24, true);
+ const fileNameLength = view.getUint16(offset + 28, true);
+ const extraFieldLength = view.getUint16(offset + 30, true);
+ const fileCommentLength = view.getUint16(offset + 32, true);
+
+ const deflate = (view.getUint16(offset + 10, true) === 8);
+
+ let localEntryOffset = view.getUint32(offset + 42, true);
+
+ const decoder = (bitFlag & 0x800) ? utf8Decoder : asciiDecoder;
+ const filename = decoder.decode(data.subarray(offset + 46, offset + 46 + fileNameLength));
+
+ // ZIP64 support
+ if (compressedSize === MAX_INT32 ||
+ uncompressedSize === MAX_INT32 ||
+ localEntryOffset === MAX_INT32) {
+
+ let extraFieldOffset = offset + 46 + fileNameLength;
+ const efEnd = extraFieldOffset + extraFieldLength - 3;
+ while (extraFieldOffset < efEnd) {
+ const type = view.getUint16(extraFieldOffset, true);
+ let size = view.getUint16(extraFieldOffset + 2, true);
+ extraFieldOffset += 4;
+
+ // zip64 info
+ if (type === 1) {
+ if (uncompressedSize === MAX_INT32 && size >= 8) {
+ uncompressedSize = this.getUint64(view, extraFieldOffset, true);
+ extraFieldOffset += 8;
+ size -= 8;
+ }
+ if (compressedSize === MAX_INT32 && size >= 8) {
+ compressedSize = this.getUint64(view, extraFieldOffset, true);
+ extraFieldOffset += 8;
+ size -= 8;
+ }
+ if (localEntryOffset === MAX_INT32 && size >= 8) {
+ localEntryOffset = this.getUint64(view, extraFieldOffset, true);
+ extraFieldOffset += 8;
+ size -= 8;
+ }
+ }
+
+ extraFieldOffset += size;
+ }
+ }
+
+ const directory = filename.endsWith("/");
+
+ if (!directory) {
+ entries[filename] = {
+ filename,
+ deflate,
+ uncompressedSize,
+ compressedSize,
+ localEntryOffset,
+ };
+
+ // optimization if no extraFieldLength, can set offset and avoid extra lookup
+ if (!extraFieldLength) {
+ entries[filename].offset = 30 + fileNameLength + localEntryOffset;
+ }
+ }
+
+ offset += 46 + fileNameLength + extraFieldLength + fileCommentLength;
+ }
+ return entries;
+ }
+
+ getCompressedSize(name) {
+ if (this.entries === null) {
+ return 0;
+ }
+
+ const entry = this.entries[name];
+
+ if (!entry) {
+ return 0;
+ }
+
+ return isNaN(entry.compressedSize) ? 0 : entry.compressedSize;
+ }
+
+ async loadFile(name, {offset = 0, length = -1, signal = null, unzip = false, computeHash = null} = {}) {
+ if (this.entries === null) {
+ await this.load();
+ }
+
+ const entry = this.entries[name];
+
+ if (!entry) {
+ return {reader: null};
+ }
+
+ if (entry.offset === undefined) {
+ const header = await this.loader.getRange(entry.localEntryOffset, 30);
+ const view = new DataView(header.buffer, header.byteOffset, header.byteLength);
+
+ const fileNameLength = view.getUint16(26, true);
+ const extraFieldLength = view.getUint16(28, true);
+
+ entry.offset = 30 + fileNameLength + extraFieldLength + entry.localEntryOffset;
+ this.entriesUpdated = true;
+ }
+
+ length = length < 0 ? entry.compressedSize : Math.min(length, entry.compressedSize - offset);
+
+ offset += entry.offset;
+
+ const body = await this.loader.getRange(offset, length, true, signal);
+
+ let reader = body.getReader();
+ let hasher = null;
+
+ const wrapHasher = (reader) => {
+ if (computeHash && this.enableHashing) {
+ hasher = new HashingAsyncIterReader(reader);
+ return hasher;
+ }
+ return reader;
+ };
+
+ // if not unzip, deflate if needed only
+ if (!unzip) {
+ reader = new c(reader, entry.deflate ? "deflate" : null);
+ reader = wrapHasher(reader);
+ // if unzip and not deflated, reuse AsyncIterReader for auto unzipping
+ } else if (!entry.deflate) {
+ reader = wrapHasher(reader);
+ reader = new c(reader);
+ } else {
+ // need to deflate, than unzip again
+ reader = new c(new c(reader, "deflate"));
+ reader = wrapHasher(reader);
+ }
+
+ if (hasher) {
+ await hasher.initHasher();
+ }
+
+ return {reader, hasher};
+ }
+
+ // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
+ getUint64(dataview, byteOffset, littleEndian) {
+ // split 64-bit number into two 32-bit (4-byte) parts
+ const left = dataview.getUint32(byteOffset, littleEndian);
+ const right = dataview.getUint32(byteOffset+4, littleEndian);
+
+ // combine the two 32-bit values
+ const combined = littleEndian? left + 2**32*right : 2**32*left + right;
+
+ if (!Number.isSafeInteger(combined))
+ console.warn(combined, "exceeds MAX_SAFE_INTEGER. Precision may be lost");
+
+ return combined;
+ }
+}
+
+// ===========================================================================
+class ZipBlockLoader
+{
+ constructor(zipreader, filename) {
+ this.zipreader = zipreader;
+ this.filename = filename;
+ this.size = null;
+ }
+
+ async doInitialFetch(tryHead = false) {
+ await this.zipreader.load();
+
+ this.size = this.zipreader.getCompressedSize(this.filename);
+
+ let stream = null;
+
+ if (!tryHead) {
+ const { reader } = await this.zipreader.loadFile(this.filename, {unzip: true});
+ stream = getReadableStreamFromIter(reader);
+ }
+
+ const response = new Response(stream);
+
+ return {response};
+ }
+
+ async getLength() {
+ if (this.size === null) {
+ await this.doInitialFetch(true);
+ }
+
+ return this.size;
+ }
+
+ async getRange(offset, length, streaming = false, signal = null) {
+ const { reader } = await this.zipreader.loadFile(this.filename, {offset, length, signal, unzip: true});
+
+ if (streaming) {
+ return getReadableStreamFromIter(reader);
+ } else {
+ return await reader.readFully();
+ }
+ }
+}
+
+
+;// CONCATENATED MODULE: ./src/wacz/waczfile.js
+
+
+const NO_LOAD_WACZ = "local";
+const DEFAULT_WACZ = "default";
+
+const INDEX_NOT_LOADED = 0;
+const INDEX_CDX = 1;
+const INDEX_IDX = 2;
+
+const WACZ_LEAF = "wacz";
+const MULTI_WACZ = "multi-wacz";
+
+// ==========================================================================
+class WACZLoadSource
+{
+ getLoadPath(/*path*/) {
+ // not implemented;
+ }
+
+ getName(/*name*/) {
+ // not implemented;
+ }
+
+ async createLoader(/*opts*/) {
+ // not implemented;
+ }
+}
+
+// ==========================================================================
+class WACZFile extends WACZLoadSource
+{
+ constructor({waczname, hash, path, parent = null, entries = null, fileType = WACZ_LEAF, indexType = INDEX_NOT_LOADED, loader = null} = {}) {
+ super();
+ this.waczname = waczname;
+ this.hash = hash;
+ this.path = path;
+ this.loader = loader;
+ this.parent = parent;
+ this.zipreader = null;
+ this.entries = entries;
+ this.indexType = indexType;
+ this.fileType = fileType;
+ }
+
+ markAsMultiWACZ() {
+ this.fileType = MULTI_WACZ;
+ }
+
+ async init(path) {
+ if (path) {
+ this.path = path;
+ }
+ const loader = this.loader ? this.loader : await this.parent.createLoader({url: this.path});
+
+ return await this.initFromLoader(loader);
+ }
+
+ async initFromLoader(loader) {
+ this.zipreader = new ZipRangeReader(loader, this.entries);
+
+ if (!this.entries) {
+ this.entries = await this.zipreader.load();
+ }
+
+ return this.entries;
+ }
+
+ async loadFile(filename, opts) {
+ if (!this.zipreader) {
+ await this.init();
+ }
+
+ return await this.zipreader.loadFile(filename, opts);
+ }
+
+ containsFile(filename) {
+ return !!this.entries[filename];
+ }
+
+ getSizeOf(filename) {
+ return this.zipreader ? this.zipreader.getCompressedSize(filename) : 0 ;
+ }
+
+ serialize() {
+ return {
+ waczname: this.waczname,
+ hash: this.hash,
+ path: this.path,
+ entries: this.entries,
+ indexType: this.indexType
+ };
+ }
+
+ async save(db, always = false) {
+ const zipreader = this.zipreader;
+ if (always || (zipreader && zipreader.entriesUpdated)) {
+ await db.put("waczfiles", this.serialize());
+ if (zipreader) {
+ zipreader.entriesUpdated = false;
+ }
+ }
+ }
+
+ iterContainedFiles() {
+ return this.entries ? Object.keys(this.entries) : [];
+ }
+
+ getLoadPath(path) {
+ return this.waczname + "#!/" + path;
+ }
+
+ getName(name) {
+ return this.waczname + "#!/" + name;
+ }
+
+ async createLoader(opts) {
+ const { url } = opts;
+ const inx = url.lastIndexOf("#!/");
+
+ if (!this.zipreader) {
+ await this.init();
+ }
+
+ if (inx >= 0) {
+ return new ZipBlockLoader(this.zipreader, url.slice(inx + 3));
+ }
+ }
+}
+;// CONCATENATED MODULE: ./node_modules/js-yaml/dist/js-yaml.mjs
+
+/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */
+function isNothing(subject) {
+ return (typeof subject === 'undefined') || (subject === null);
+}
+
+
+function isObject(subject) {
+ return (typeof subject === 'object') && (subject !== null);
+}
+
+
+function toArray(sequence) {
+ if (Array.isArray(sequence)) return sequence;
+ else if (isNothing(sequence)) return [];
+
+ return [ sequence ];
+}
+
+
+function extend(target, source) {
+ var index, length, key, sourceKeys;
+
+ if (source) {
+ sourceKeys = Object.keys(source);
+
+ for (index = 0, length = sourceKeys.length; index < length; index += 1) {
+ key = sourceKeys[index];
+ target[key] = source[key];
+ }
+ }
+
+ return target;
+}
+
+
+function repeat(string, count) {
+ var result = '', cycle;
+
+ for (cycle = 0; cycle < count; cycle += 1) {
+ result += string;
+ }
+
+ return result;
+}
+
+
+function isNegativeZero(number) {
+ return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
+}
+
+
+var isNothing_1 = isNothing;
+var isObject_1 = isObject;
+var toArray_1 = toArray;
+var repeat_1 = repeat;
+var isNegativeZero_1 = isNegativeZero;
+var extend_1 = extend;
+
+var common = {
+ isNothing: isNothing_1,
+ isObject: isObject_1,
+ toArray: toArray_1,
+ repeat: repeat_1,
+ isNegativeZero: isNegativeZero_1,
+ extend: extend_1
+};
+
+// YAML error class. http://stackoverflow.com/questions/8458984
+
+
+function formatError(exception, compact) {
+ var where = '', message = exception.reason || '(unknown reason)';
+
+ if (!exception.mark) return message;
+
+ if (exception.mark.name) {
+ where += 'in "' + exception.mark.name + '" ';
+ }
+
+ where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')';
+
+ if (!compact && exception.mark.snippet) {
+ where += '\n\n' + exception.mark.snippet;
+ }
+
+ return message + ' ' + where;
+}
+
+
+function YAMLException$1(reason, mark) {
+ // Super constructor
+ Error.call(this);
+
+ this.name = 'YAMLException';
+ this.reason = reason;
+ this.mark = mark;
+ this.message = formatError(this, false);
+
+ // Include stack trace in error object
+ if (Error.captureStackTrace) {
+ // Chrome and NodeJS
+ Error.captureStackTrace(this, this.constructor);
+ } else {
+ // FF, IE 10+ and Safari 6+. Fallback for others
+ this.stack = (new Error()).stack || '';
+ }
+}
+
+
+// Inherit from Error
+YAMLException$1.prototype = Object.create(Error.prototype);
+YAMLException$1.prototype.constructor = YAMLException$1;
+
+
+YAMLException$1.prototype.toString = function toString(compact) {
+ return this.name + ': ' + formatError(this, compact);
+};
+
+
+var exception = YAMLException$1;
+
+// get snippet for a single line, respecting maxLength
+function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
+ var head = '';
+ var tail = '';
+ var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
+
+ if (position - lineStart > maxHalfLength) {
+ head = ' ... ';
+ lineStart = position - maxHalfLength + head.length;
+ }
+
+ if (lineEnd - position > maxHalfLength) {
+ tail = ' ...';
+ lineEnd = position + maxHalfLength - tail.length;
+ }
+
+ return {
+ str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail,
+ pos: position - lineStart + head.length // relative position
+ };
+}
+
+
+function padStart(string, max) {
+ return common.repeat(' ', max - string.length) + string;
+}
+
+
+function makeSnippet(mark, options) {
+ options = Object.create(options || null);
+
+ if (!mark.buffer) return null;
+
+ if (!options.maxLength) options.maxLength = 79;
+ if (typeof options.indent !== 'number') options.indent = 1;
+ if (typeof options.linesBefore !== 'number') options.linesBefore = 3;
+ if (typeof options.linesAfter !== 'number') options.linesAfter = 2;
+
+ var re = /\r?\n|\r|\0/g;
+ var lineStarts = [ 0 ];
+ var lineEnds = [];
+ var match;
+ var foundLineNo = -1;
+
+ while ((match = re.exec(mark.buffer))) {
+ lineEnds.push(match.index);
+ lineStarts.push(match.index + match[0].length);
+
+ if (mark.position <= match.index && foundLineNo < 0) {
+ foundLineNo = lineStarts.length - 2;
+ }
+ }
+
+ if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
+
+ var result = '', i, line;
+ var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
+ var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
+
+ for (i = 1; i <= options.linesBefore; i++) {
+ if (foundLineNo - i < 0) break;
+ line = getLine(
+ mark.buffer,
+ lineStarts[foundLineNo - i],
+ lineEnds[foundLineNo - i],
+ mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
+ maxLineLength
+ );
+ result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +
+ ' | ' + line.str + '\n' + result;
+ }
+
+ line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
+ result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +
+ ' | ' + line.str + '\n';
+ result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n';
+
+ for (i = 1; i <= options.linesAfter; i++) {
+ if (foundLineNo + i >= lineEnds.length) break;
+ line = getLine(
+ mark.buffer,
+ lineStarts[foundLineNo + i],
+ lineEnds[foundLineNo + i],
+ mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
+ maxLineLength
+ );
+ result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +
+ ' | ' + line.str + '\n';
+ }
+
+ return result.replace(/\n$/, '');
+}
+
+
+var snippet = makeSnippet;
+
+var TYPE_CONSTRUCTOR_OPTIONS = [
+ 'kind',
+ 'multi',
+ 'resolve',
+ 'construct',
+ 'instanceOf',
+ 'predicate',
+ 'represent',
+ 'representName',
+ 'defaultStyle',
+ 'styleAliases'
+];
+
+var YAML_NODE_KINDS = [
+ 'scalar',
+ 'sequence',
+ 'mapping'
+];
+
+function compileStyleAliases(map) {
+ var result = {};
+
+ if (map !== null) {
+ Object.keys(map).forEach(function (style) {
+ map[style].forEach(function (alias) {
+ result[String(alias)] = style;
+ });
+ });
+ }
+
+ return result;
+}
+
+function Type$1(tag, options) {
+ options = options || {};
+
+ Object.keys(options).forEach(function (name) {
+ if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
+ throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
+ }
+ });
+
+ // TODO: Add tag format check.
+ this.options = options; // keep original options in case user wants to extend this type later
+ this.tag = tag;
+ this.kind = options['kind'] || null;
+ this.resolve = options['resolve'] || function () { return true; };
+ this.construct = options['construct'] || function (data) { return data; };
+ this.instanceOf = options['instanceOf'] || null;
+ this.predicate = options['predicate'] || null;
+ this.represent = options['represent'] || null;
+ this.representName = options['representName'] || null;
+ this.defaultStyle = options['defaultStyle'] || null;
+ this.multi = options['multi'] || false;
+ this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
+
+ if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
+ throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
+ }
+}
+
+var type = Type$1;
+
+/*eslint-disable max-len*/
+
+
+
+
+
+function compileList(schema, name) {
+ var result = [];
+
+ schema[name].forEach(function (currentType) {
+ var newIndex = result.length;
+
+ result.forEach(function (previousType, previousIndex) {
+ if (previousType.tag === currentType.tag &&
+ previousType.kind === currentType.kind &&
+ previousType.multi === currentType.multi) {
+
+ newIndex = previousIndex;
+ }
+ });
+
+ result[newIndex] = currentType;
+ });
+
+ return result;
+}
+
+
+function compileMap(/* lists... */) {
+ var result = {
+ scalar: {},
+ sequence: {},
+ mapping: {},
+ fallback: {},
+ multi: {
+ scalar: [],
+ sequence: [],
+ mapping: [],
+ fallback: []
+ }
+ }, index, length;
+
+ function collectType(type) {
+ if (type.multi) {
+ result.multi[type.kind].push(type);
+ result.multi['fallback'].push(type);
+ } else {
+ result[type.kind][type.tag] = result['fallback'][type.tag] = type;
+ }
+ }
+
+ for (index = 0, length = arguments.length; index < length; index += 1) {
+ arguments[index].forEach(collectType);
+ }
+ return result;
+}
+
+
+function Schema$1(definition) {
+ return this.extend(definition);
+}
+
+
+Schema$1.prototype.extend = function extend(definition) {
+ var implicit = [];
+ var explicit = [];
+
+ if (definition instanceof type) {
+ // Schema.extend(type)
+ explicit.push(definition);
+
+ } else if (Array.isArray(definition)) {
+ // Schema.extend([ type1, type2, ... ])
+ explicit = explicit.concat(definition);
+
+ } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
+ // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })
+ if (definition.implicit) implicit = implicit.concat(definition.implicit);
+ if (definition.explicit) explicit = explicit.concat(definition.explicit);
+
+ } else {
+ throw new exception('Schema.extend argument should be a Type, [ Type ], ' +
+ 'or a schema definition ({ implicit: [...], explicit: [...] })');
+ }
+
+ implicit.forEach(function (type$1) {
+ if (!(type$1 instanceof type)) {
+ throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
+ }
+
+ if (type$1.loadKind && type$1.loadKind !== 'scalar') {
+ throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
+ }
+
+ if (type$1.multi) {
+ throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.');
+ }
+ });
+
+ explicit.forEach(function (type$1) {
+ if (!(type$1 instanceof type)) {
+ throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
+ }
+ });
+
+ var result = Object.create(Schema$1.prototype);
+
+ result.implicit = (this.implicit || []).concat(implicit);
+ result.explicit = (this.explicit || []).concat(explicit);
+
+ result.compiledImplicit = compileList(result, 'implicit');
+ result.compiledExplicit = compileList(result, 'explicit');
+ result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
+
+ return result;
+};
+
+
+var schema = Schema$1;
+
+var str = new type('tag:yaml.org,2002:str', {
+ kind: 'scalar',
+ construct: function (data) { return data !== null ? data : ''; }
+});
+
+var seq = new type('tag:yaml.org,2002:seq', {
+ kind: 'sequence',
+ construct: function (data) { return data !== null ? data : []; }
+});
+
+var map = new type('tag:yaml.org,2002:map', {
+ kind: 'mapping',
+ construct: function (data) { return data !== null ? data : {}; }
+});
+
+var failsafe = new schema({
+ explicit: [
+ str,
+ seq,
+ map
+ ]
+});
+
+function resolveYamlNull(data) {
+ if (data === null) return true;
+
+ var max = data.length;
+
+ return (max === 1 && data === '~') ||
+ (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
+}
+
+function constructYamlNull() {
+ return null;
+}
+
+function isNull(object) {
+ return object === null;
+}
+
+var _null = new type('tag:yaml.org,2002:null', {
+ kind: 'scalar',
+ resolve: resolveYamlNull,
+ construct: constructYamlNull,
+ predicate: isNull,
+ represent: {
+ canonical: function () { return '~'; },
+ lowercase: function () { return 'null'; },
+ uppercase: function () { return 'NULL'; },
+ camelcase: function () { return 'Null'; },
+ empty: function () { return ''; }
+ },
+ defaultStyle: 'lowercase'
+});
+
+function resolveYamlBoolean(data) {
+ if (data === null) return false;
+
+ var max = data.length;
+
+ return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
+ (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
+}
+
+function constructYamlBoolean(data) {
+ return data === 'true' ||
+ data === 'True' ||
+ data === 'TRUE';
+}
+
+function isBoolean(object) {
+ return Object.prototype.toString.call(object) === '[object Boolean]';
+}
+
+var bool = new type('tag:yaml.org,2002:bool', {
+ kind: 'scalar',
+ resolve: resolveYamlBoolean,
+ construct: constructYamlBoolean,
+ predicate: isBoolean,
+ represent: {
+ lowercase: function (object) { return object ? 'true' : 'false'; },
+ uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
+ camelcase: function (object) { return object ? 'True' : 'False'; }
+ },
+ defaultStyle: 'lowercase'
+});
+
+function isHexCode(c) {
+ return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
+ ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
+ ((0x61/* a */ <= c) && (c <= 0x66/* f */));
+}
+
+function isOctCode(c) {
+ return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
+}
+
+function isDecCode(c) {
+ return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
+}
+
+function resolveYamlInteger(data) {
+ if (data === null) return false;
+
+ var max = data.length,
+ index = 0,
+ hasDigits = false,
+ ch;
+
+ if (!max) return false;
+
+ ch = data[index];
+
+ // sign
+ if (ch === '-' || ch === '+') {
+ ch = data[++index];
+ }
+
+ if (ch === '0') {
+ // 0
+ if (index + 1 === max) return true;
+ ch = data[++index];
+
+ // base 2, base 8, base 16
+
+ if (ch === 'b') {
+ // base 2
+ index++;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (ch !== '0' && ch !== '1') return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== '_';
+ }
+
+
+ if (ch === 'x') {
+ // base 16
+ index++;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (!isHexCode(data.charCodeAt(index))) return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== '_';
+ }
+
+
+ if (ch === 'o') {
+ // base 8
+ index++;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (!isOctCode(data.charCodeAt(index))) return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== '_';
+ }
+ }
+
+ // base 10 (except 0)
+
+ // value should not start with `_`;
+ if (ch === '_') return false;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (!isDecCode(data.charCodeAt(index))) {
+ return false;
+ }
+ hasDigits = true;
+ }
+
+ // Should have digits and should not end with `_`
+ if (!hasDigits || ch === '_') return false;
+
+ return true;
+}
+
+function constructYamlInteger(data) {
+ var value = data, sign = 1, ch;
+
+ if (value.indexOf('_') !== -1) {
+ value = value.replace(/_/g, '');
+ }
+
+ ch = value[0];
+
+ if (ch === '-' || ch === '+') {
+ if (ch === '-') sign = -1;
+ value = value.slice(1);
+ ch = value[0];
+ }
+
+ if (value === '0') return 0;
+
+ if (ch === '0') {
+ if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
+ if (value[1] === 'x') return sign * parseInt(value.slice(2), 16);
+ if (value[1] === 'o') return sign * parseInt(value.slice(2), 8);
+ }
+
+ return sign * parseInt(value, 10);
+}
+
+function isInteger(object) {
+ return (Object.prototype.toString.call(object)) === '[object Number]' &&
+ (object % 1 === 0 && !common.isNegativeZero(object));
+}
+
+var js_yaml_int = new type('tag:yaml.org,2002:int', {
+ kind: 'scalar',
+ resolve: resolveYamlInteger,
+ construct: constructYamlInteger,
+ predicate: isInteger,
+ represent: {
+ binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
+ octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); },
+ decimal: function (obj) { return obj.toString(10); },
+ /* eslint-disable max-len */
+ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
+ },
+ defaultStyle: 'decimal',
+ styleAliases: {
+ binary: [ 2, 'bin' ],
+ octal: [ 8, 'oct' ],
+ decimal: [ 10, 'dec' ],
+ hexadecimal: [ 16, 'hex' ]
+ }
+});
+
+var YAML_FLOAT_PATTERN = new RegExp(
+ // 2.5e4, 2.5 and integers
+ '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
+ // .2e4, .2
+ // special case, seems not from spec
+ '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
+ // .inf
+ '|[-+]?\\.(?:inf|Inf|INF)' +
+ // .nan
+ '|\\.(?:nan|NaN|NAN))$');
+
+function resolveYamlFloat(data) {
+ if (data === null) return false;
+
+ if (!YAML_FLOAT_PATTERN.test(data) ||
+ // Quick hack to not allow integers end with `_`
+ // Probably should update regexp & check speed
+ data[data.length - 1] === '_') {
+ return false;
+ }
+
+ return true;
+}
+
+function constructYamlFloat(data) {
+ var value, sign;
+
+ value = data.replace(/_/g, '').toLowerCase();
+ sign = value[0] === '-' ? -1 : 1;
+
+ if ('+-'.indexOf(value[0]) >= 0) {
+ value = value.slice(1);
+ }
+
+ if (value === '.inf') {
+ return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
+
+ } else if (value === '.nan') {
+ return NaN;
+ }
+ return sign * parseFloat(value, 10);
+}
+
+
+var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
+
+function representYamlFloat(object, style) {
+ var res;
+
+ if (isNaN(object)) {
+ switch (style) {
+ case 'lowercase': return '.nan';
+ case 'uppercase': return '.NAN';
+ case 'camelcase': return '.NaN';
+ }
+ } else if (Number.POSITIVE_INFINITY === object) {
+ switch (style) {
+ case 'lowercase': return '.inf';
+ case 'uppercase': return '.INF';
+ case 'camelcase': return '.Inf';
+ }
+ } else if (Number.NEGATIVE_INFINITY === object) {
+ switch (style) {
+ case 'lowercase': return '-.inf';
+ case 'uppercase': return '-.INF';
+ case 'camelcase': return '-.Inf';
+ }
+ } else if (common.isNegativeZero(object)) {
+ return '-0.0';
+ }
+
+ res = object.toString(10);
+
+ // JS stringifier can build scientific format without dots: 5e-100,
+ // while YAML requres dot: 5.e-100. Fix it with simple hack
+
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
+}
+
+function isFloat(object) {
+ return (Object.prototype.toString.call(object) === '[object Number]') &&
+ (object % 1 !== 0 || common.isNegativeZero(object));
+}
+
+var js_yaml_float = new type('tag:yaml.org,2002:float', {
+ kind: 'scalar',
+ resolve: resolveYamlFloat,
+ construct: constructYamlFloat,
+ predicate: isFloat,
+ represent: representYamlFloat,
+ defaultStyle: 'lowercase'
+});
+
+var json = failsafe.extend({
+ implicit: [
+ _null,
+ bool,
+ js_yaml_int,
+ js_yaml_float
+ ]
+});
+
+var core = json;
+
+var YAML_DATE_REGEXP = new RegExp(
+ '^([0-9][0-9][0-9][0-9])' + // [1] year
+ '-([0-9][0-9])' + // [2] month
+ '-([0-9][0-9])$'); // [3] day
+
+var YAML_TIMESTAMP_REGEXP = new RegExp(
+ '^([0-9][0-9][0-9][0-9])' + // [1] year
+ '-([0-9][0-9]?)' + // [2] month
+ '-([0-9][0-9]?)' + // [3] day
+ '(?:[Tt]|[ \\t]+)' + // ...
+ '([0-9][0-9]?)' + // [4] hour
+ ':([0-9][0-9])' + // [5] minute
+ ':([0-9][0-9])' + // [6] second
+ '(?:\\.([0-9]*))?' + // [7] fraction
+ '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
+ '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
+
+function resolveYamlTimestamp(data) {
+ if (data === null) return false;
+ if (YAML_DATE_REGEXP.exec(data) !== null) return true;
+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
+ return false;
+}
+
+function constructYamlTimestamp(data) {
+ var match, year, month, day, hour, minute, second, fraction = 0,
+ delta = null, tz_hour, tz_minute, date;
+
+ match = YAML_DATE_REGEXP.exec(data);
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
+
+ if (match === null) throw new Error('Date resolve error');
+
+ // match: [1] year [2] month [3] day
+
+ year = +(match[1]);
+ month = +(match[2]) - 1; // JS month starts with 0
+ day = +(match[3]);
+
+ if (!match[4]) { // no hour
+ return new Date(Date.UTC(year, month, day));
+ }
+
+ // match: [4] hour [5] minute [6] second [7] fraction
+
+ hour = +(match[4]);
+ minute = +(match[5]);
+ second = +(match[6]);
+
+ if (match[7]) {
+ fraction = match[7].slice(0, 3);
+ while (fraction.length < 3) { // milli-seconds
+ fraction += '0';
+ }
+ fraction = +fraction;
+ }
+
+ // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
+
+ if (match[9]) {
+ tz_hour = +(match[10]);
+ tz_minute = +(match[11] || 0);
+ delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
+ if (match[9] === '-') delta = -delta;
+ }
+
+ date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
+
+ if (delta) date.setTime(date.getTime() - delta);
+
+ return date;
+}
+
+function representYamlTimestamp(object /*, style*/) {
+ return object.toISOString();
+}
+
+var timestamp = new type('tag:yaml.org,2002:timestamp', {
+ kind: 'scalar',
+ resolve: resolveYamlTimestamp,
+ construct: constructYamlTimestamp,
+ instanceOf: Date,
+ represent: representYamlTimestamp
+});
+
+function resolveYamlMerge(data) {
+ return data === '<<' || data === null;
+}
+
+var merge = new type('tag:yaml.org,2002:merge', {
+ kind: 'scalar',
+ resolve: resolveYamlMerge
+});
+
+/*eslint-disable no-bitwise*/
+
+
+
+
+
+// [ 64, 65, 66 ] -> [ padding, CR, LF ]
+var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
+
+
+function resolveYamlBinary(data) {
+ if (data === null) return false;
+
+ var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
+
+ // Convert one by one.
+ for (idx = 0; idx < max; idx++) {
+ code = map.indexOf(data.charAt(idx));
+
+ // Skip CR/LF
+ if (code > 64) continue;
+
+ // Fail on illegal characters
+ if (code < 0) return false;
+
+ bitlen += 6;
+ }
+
+ // If there are any bits left, source was corrupted
+ return (bitlen % 8) === 0;
+}
+
+function constructYamlBinary(data) {
+ var idx, tailbits,
+ input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
+ max = input.length,
+ map = BASE64_MAP,
+ bits = 0,
+ result = [];
+
+ // Collect by 6*4 bits (3 bytes)
+
+ for (idx = 0; idx < max; idx++) {
+ if ((idx % 4 === 0) && idx) {
+ result.push((bits >> 16) & 0xFF);
+ result.push((bits >> 8) & 0xFF);
+ result.push(bits & 0xFF);
+ }
+
+ bits = (bits << 6) | map.indexOf(input.charAt(idx));
+ }
+
+ // Dump tail
+
+ tailbits = (max % 4) * 6;
+
+ if (tailbits === 0) {
+ result.push((bits >> 16) & 0xFF);
+ result.push((bits >> 8) & 0xFF);
+ result.push(bits & 0xFF);
+ } else if (tailbits === 18) {
+ result.push((bits >> 10) & 0xFF);
+ result.push((bits >> 2) & 0xFF);
+ } else if (tailbits === 12) {
+ result.push((bits >> 4) & 0xFF);
+ }
+
+ return new Uint8Array(result);
+}
+
+function representYamlBinary(object /*, style*/) {
+ var result = '', bits = 0, idx, tail,
+ max = object.length,
+ map = BASE64_MAP;
+
+ // Convert every three bytes to 4 ASCII characters.
+
+ for (idx = 0; idx < max; idx++) {
+ if ((idx % 3 === 0) && idx) {
+ result += map[(bits >> 18) & 0x3F];
+ result += map[(bits >> 12) & 0x3F];
+ result += map[(bits >> 6) & 0x3F];
+ result += map[bits & 0x3F];
+ }
+
+ bits = (bits << 8) + object[idx];
+ }
+
+ // Dump tail
+
+ tail = max % 3;
+
+ if (tail === 0) {
+ result += map[(bits >> 18) & 0x3F];
+ result += map[(bits >> 12) & 0x3F];
+ result += map[(bits >> 6) & 0x3F];
+ result += map[bits & 0x3F];
+ } else if (tail === 2) {
+ result += map[(bits >> 10) & 0x3F];
+ result += map[(bits >> 4) & 0x3F];
+ result += map[(bits << 2) & 0x3F];
+ result += map[64];
+ } else if (tail === 1) {
+ result += map[(bits >> 2) & 0x3F];
+ result += map[(bits << 4) & 0x3F];
+ result += map[64];
+ result += map[64];
+ }
+
+ return result;
+}
+
+function isBinary(obj) {
+ return Object.prototype.toString.call(obj) === '[object Uint8Array]';
+}
+
+var binary = new type('tag:yaml.org,2002:binary', {
+ kind: 'scalar',
+ resolve: resolveYamlBinary,
+ construct: constructYamlBinary,
+ predicate: isBinary,
+ represent: representYamlBinary
+});
+
+var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
+var _toString$2 = Object.prototype.toString;
+
+function resolveYamlOmap(data) {
+ if (data === null) return true;
+
+ var objectKeys = [], index, length, pair, pairKey, pairHasKey,
+ object = data;
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ pair = object[index];
+ pairHasKey = false;
+
+ if (_toString$2.call(pair) !== '[object Object]') return false;
+
+ for (pairKey in pair) {
+ if (_hasOwnProperty$3.call(pair, pairKey)) {
+ if (!pairHasKey) pairHasKey = true;
+ else return false;
+ }
+ }
+
+ if (!pairHasKey) return false;
+
+ if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
+ else return false;
+ }
+
+ return true;
+}
+
+function constructYamlOmap(data) {
+ return data !== null ? data : [];
+}
+
+var omap = new type('tag:yaml.org,2002:omap', {
+ kind: 'sequence',
+ resolve: resolveYamlOmap,
+ construct: constructYamlOmap
+});
+
+var _toString$1 = Object.prototype.toString;
+
+function resolveYamlPairs(data) {
+ if (data === null) return true;
+
+ var index, length, pair, keys, result,
+ object = data;
+
+ result = new Array(object.length);
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ pair = object[index];
+
+ if (_toString$1.call(pair) !== '[object Object]') return false;
+
+ keys = Object.keys(pair);
+
+ if (keys.length !== 1) return false;
+
+ result[index] = [ keys[0], pair[keys[0]] ];
+ }
+
+ return true;
+}
+
+function constructYamlPairs(data) {
+ if (data === null) return [];
+
+ var index, length, pair, keys, result,
+ object = data;
+
+ result = new Array(object.length);
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ pair = object[index];
+
+ keys = Object.keys(pair);
+
+ result[index] = [ keys[0], pair[keys[0]] ];
+ }
+
+ return result;
+}
+
+var pairs = new type('tag:yaml.org,2002:pairs', {
+ kind: 'sequence',
+ resolve: resolveYamlPairs,
+ construct: constructYamlPairs
+});
+
+var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
+
+function resolveYamlSet(data) {
+ if (data === null) return true;
+
+ var key, object = data;
+
+ for (key in object) {
+ if (_hasOwnProperty$2.call(object, key)) {
+ if (object[key] !== null) return false;
+ }
+ }
+
+ return true;
+}
+
+function constructYamlSet(data) {
+ return data !== null ? data : {};
+}
+
+var set = new type('tag:yaml.org,2002:set', {
+ kind: 'mapping',
+ resolve: resolveYamlSet,
+ construct: constructYamlSet
+});
+
+var _default = core.extend({
+ implicit: [
+ timestamp,
+ merge
+ ],
+ explicit: [
+ binary,
+ omap,
+ pairs,
+ set
+ ]
+});
+
+/*eslint-disable max-len,no-use-before-define*/
+
+
+
+
+
+
+
+var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
+
+
+var CONTEXT_FLOW_IN = 1;
+var CONTEXT_FLOW_OUT = 2;
+var CONTEXT_BLOCK_IN = 3;
+var CONTEXT_BLOCK_OUT = 4;
+
+
+var CHOMPING_CLIP = 1;
+var CHOMPING_STRIP = 2;
+var CHOMPING_KEEP = 3;
+
+
+var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
+var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
+var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
+var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
+var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
+
+
+function _class(obj) { return Object.prototype.toString.call(obj); }
+
+function is_EOL(c) {
+ return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
+}
+
+function is_WHITE_SPACE(c) {
+ return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
+}
+
+function is_WS_OR_EOL(c) {
+ return (c === 0x09/* Tab */) ||
+ (c === 0x20/* Space */) ||
+ (c === 0x0A/* LF */) ||
+ (c === 0x0D/* CR */);
+}
+
+function is_FLOW_INDICATOR(c) {
+ return c === 0x2C/* , */ ||
+ c === 0x5B/* [ */ ||
+ c === 0x5D/* ] */ ||
+ c === 0x7B/* { */ ||
+ c === 0x7D/* } */;
+}
+
+function fromHexCode(c) {
+ var lc;
+
+ if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
+ return c - 0x30;
+ }
+
+ /*eslint-disable no-bitwise*/
+ lc = c | 0x20;
+
+ if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
+ return lc - 0x61 + 10;
+ }
+
+ return -1;
+}
+
+function escapedHexLen(c) {
+ if (c === 0x78/* x */) { return 2; }
+ if (c === 0x75/* u */) { return 4; }
+ if (c === 0x55/* U */) { return 8; }
+ return 0;
+}
+
+function fromDecimalCode(c) {
+ if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
+ return c - 0x30;
+ }
+
+ return -1;
+}
+
+function simpleEscapeSequence(c) {
+ /* eslint-disable indent */
+ return (c === 0x30/* 0 */) ? '\x00' :
+ (c === 0x61/* a */) ? '\x07' :
+ (c === 0x62/* b */) ? '\x08' :
+ (c === 0x74/* t */) ? '\x09' :
+ (c === 0x09/* Tab */) ? '\x09' :
+ (c === 0x6E/* n */) ? '\x0A' :
+ (c === 0x76/* v */) ? '\x0B' :
+ (c === 0x66/* f */) ? '\x0C' :
+ (c === 0x72/* r */) ? '\x0D' :
+ (c === 0x65/* e */) ? '\x1B' :
+ (c === 0x20/* Space */) ? ' ' :
+ (c === 0x22/* " */) ? '\x22' :
+ (c === 0x2F/* / */) ? '/' :
+ (c === 0x5C/* \ */) ? '\x5C' :
+ (c === 0x4E/* N */) ? '\x85' :
+ (c === 0x5F/* _ */) ? '\xA0' :
+ (c === 0x4C/* L */) ? '\u2028' :
+ (c === 0x50/* P */) ? '\u2029' : '';
+}
+
+function charFromCodepoint(c) {
+ if (c <= 0xFFFF) {
+ return String.fromCharCode(c);
+ }
+ // Encode UTF-16 surrogate pair
+ // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
+ return String.fromCharCode(
+ ((c - 0x010000) >> 10) + 0xD800,
+ ((c - 0x010000) & 0x03FF) + 0xDC00
+ );
+}
+
+var simpleEscapeCheck = new Array(256); // integer, for fast access
+var simpleEscapeMap = new Array(256);
+for (var i = 0; i < 256; i++) {
+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
+ simpleEscapeMap[i] = simpleEscapeSequence(i);
+}
+
+
+function State$1(input, options) {
+ this.input = input;
+
+ this.filename = options['filename'] || null;
+ this.schema = options['schema'] || _default;
+ this.onWarning = options['onWarning'] || null;
+ // (Hidden) Remove? makes the loader to expect YAML 1.1 documents
+ // if such documents have no explicit %YAML directive
+ this.legacy = options['legacy'] || false;
+
+ this.json = options['json'] || false;
+ this.listener = options['listener'] || null;
+
+ this.implicitTypes = this.schema.compiledImplicit;
+ this.typeMap = this.schema.compiledTypeMap;
+
+ this.length = input.length;
+ this.position = 0;
+ this.line = 0;
+ this.lineStart = 0;
+ this.lineIndent = 0;
+
+ // position of first leading tab in the current line,
+ // used to make sure there are no tabs in the indentation
+ this.firstTabInLine = -1;
+
+ this.documents = [];
+
+ /*
+ this.version;
+ this.checkLineBreaks;
+ this.tagMap;
+ this.anchorMap;
+ this.tag;
+ this.anchor;
+ this.kind;
+ this.result;*/
+
+}
+
+
+function generateError(state, message) {
+ var mark = {
+ name: state.filename,
+ buffer: state.input.slice(0, -1), // omit trailing \0
+ position: state.position,
+ line: state.line,
+ column: state.position - state.lineStart
+ };
+
+ mark.snippet = snippet(mark);
+
+ return new exception(message, mark);
+}
+
+function throwError(state, message) {
+ throw generateError(state, message);
+}
+
+function throwWarning(state, message) {
+ if (state.onWarning) {
+ state.onWarning.call(null, generateError(state, message));
+ }
+}
+
+
+var directiveHandlers = {
+
+ YAML: function handleYamlDirective(state, name, args) {
+
+ var match, major, minor;
+
+ if (state.version !== null) {
+ throwError(state, 'duplication of %YAML directive');
+ }
+
+ if (args.length !== 1) {
+ throwError(state, 'YAML directive accepts exactly one argument');
+ }
+
+ match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
+
+ if (match === null) {
+ throwError(state, 'ill-formed argument of the YAML directive');
+ }
+
+ major = parseInt(match[1], 10);
+ minor = parseInt(match[2], 10);
+
+ if (major !== 1) {
+ throwError(state, 'unacceptable YAML version of the document');
+ }
+
+ state.version = args[0];
+ state.checkLineBreaks = (minor < 2);
+
+ if (minor !== 1 && minor !== 2) {
+ throwWarning(state, 'unsupported YAML version of the document');
+ }
+ },
+
+ TAG: function handleTagDirective(state, name, args) {
+
+ var handle, prefix;
+
+ if (args.length !== 2) {
+ throwError(state, 'TAG directive accepts exactly two arguments');
+ }
+
+ handle = args[0];
+ prefix = args[1];
+
+ if (!PATTERN_TAG_HANDLE.test(handle)) {
+ throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
+ }
+
+ if (_hasOwnProperty$1.call(state.tagMap, handle)) {
+ throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
+ }
+
+ if (!PATTERN_TAG_URI.test(prefix)) {
+ throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
+ }
+
+ try {
+ prefix = decodeURIComponent(prefix);
+ } catch (err) {
+ throwError(state, 'tag prefix is malformed: ' + prefix);
+ }
+
+ state.tagMap[handle] = prefix;
+ }
+};
+
+
+function captureSegment(state, start, end, checkJson) {
+ var _position, _length, _character, _result;
+
+ if (start < end) {
+ _result = state.input.slice(start, end);
+
+ if (checkJson) {
+ for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
+ _character = _result.charCodeAt(_position);
+ if (!(_character === 0x09 ||
+ (0x20 <= _character && _character <= 0x10FFFF))) {
+ throwError(state, 'expected valid JSON character');
+ }
+ }
+ } else if (PATTERN_NON_PRINTABLE.test(_result)) {
+ throwError(state, 'the stream contains non-printable characters');
+ }
+
+ state.result += _result;
+ }
+}
+
+function mergeMappings(state, destination, source, overridableKeys) {
+ var sourceKeys, key, index, quantity;
+
+ if (!common.isObject(source)) {
+ throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
+ }
+
+ sourceKeys = Object.keys(source);
+
+ for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
+ key = sourceKeys[index];
+
+ if (!_hasOwnProperty$1.call(destination, key)) {
+ destination[key] = source[key];
+ overridableKeys[key] = true;
+ }
+ }
+}
+
+function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode,
+ startLine, startLineStart, startPos) {
+
+ var index, quantity;
+
+ // The output is a plain object here, so keys can only be strings.
+ // We need to convert keyNode to a string, but doing so can hang the process
+ // (deeply nested arrays that explode exponentially using aliases).
+ if (Array.isArray(keyNode)) {
+ keyNode = Array.prototype.slice.call(keyNode);
+
+ for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
+ if (Array.isArray(keyNode[index])) {
+ throwError(state, 'nested arrays are not supported inside keys');
+ }
+
+ if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
+ keyNode[index] = '[object Object]';
+ }
+ }
+ }
+
+ // Avoid code execution in load() via toString property
+ // (still use its own toString for arrays, timestamps,
+ // and whatever user schema extensions happen to have @@toStringTag)
+ if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
+ keyNode = '[object Object]';
+ }
+
+
+ keyNode = String(keyNode);
+
+ if (_result === null) {
+ _result = {};
+ }
+
+ if (keyTag === 'tag:yaml.org,2002:merge') {
+ if (Array.isArray(valueNode)) {
+ for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
+ mergeMappings(state, _result, valueNode[index], overridableKeys);
+ }
+ } else {
+ mergeMappings(state, _result, valueNode, overridableKeys);
+ }
+ } else {
+ if (!state.json &&
+ !_hasOwnProperty$1.call(overridableKeys, keyNode) &&
+ _hasOwnProperty$1.call(_result, keyNode)) {
+ state.line = startLine || state.line;
+ state.lineStart = startLineStart || state.lineStart;
+ state.position = startPos || state.position;
+ throwError(state, 'duplicated mapping key');
+ }
+
+ // used for this specific key only because Object.defineProperty is slow
+ if (keyNode === '__proto__') {
+ Object.defineProperty(_result, keyNode, {
+ configurable: true,
+ enumerable: true,
+ writable: true,
+ value: valueNode
+ });
+ } else {
+ _result[keyNode] = valueNode;
+ }
+ delete overridableKeys[keyNode];
+ }
+
+ return _result;
+}
+
+function readLineBreak(state) {
+ var ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x0A/* LF */) {
+ state.position++;
+ } else if (ch === 0x0D/* CR */) {
+ state.position++;
+ if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
+ state.position++;
+ }
+ } else {
+ throwError(state, 'a line break is expected');
+ }
+
+ state.line += 1;
+ state.lineStart = state.position;
+ state.firstTabInLine = -1;
+}
+
+function skipSeparationSpace(state, allowComments, checkIndent) {
+ var lineBreaks = 0,
+ ch = state.input.charCodeAt(state.position);
+
+ while (ch !== 0) {
+ while (is_WHITE_SPACE(ch)) {
+ if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {
+ state.firstTabInLine = state.position;
+ }
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (allowComments && ch === 0x23/* # */) {
+ do {
+ ch = state.input.charCodeAt(++state.position);
+ } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
+ }
+
+ if (is_EOL(ch)) {
+ readLineBreak(state);
+
+ ch = state.input.charCodeAt(state.position);
+ lineBreaks++;
+ state.lineIndent = 0;
+
+ while (ch === 0x20/* Space */) {
+ state.lineIndent++;
+ ch = state.input.charCodeAt(++state.position);
+ }
+ } else {
+ break;
+ }
+ }
+
+ if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
+ throwWarning(state, 'deficient indentation');
+ }
+
+ return lineBreaks;
+}
+
+function testDocumentSeparator(state) {
+ var _position = state.position,
+ ch;
+
+ ch = state.input.charCodeAt(_position);
+
+ // Condition state.position === state.lineStart is tested
+ // in parent on each call, for efficiency. No needs to test here again.
+ if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
+ ch === state.input.charCodeAt(_position + 1) &&
+ ch === state.input.charCodeAt(_position + 2)) {
+
+ _position += 3;
+
+ ch = state.input.charCodeAt(_position);
+
+ if (ch === 0 || is_WS_OR_EOL(ch)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function writeFoldedLines(state, count) {
+ if (count === 1) {
+ state.result += ' ';
+ } else if (count > 1) {
+ state.result += common.repeat('\n', count - 1);
+ }
+}
+
+
+function readPlainScalar(state, nodeIndent, withinFlowCollection) {
+ var preceding,
+ following,
+ captureStart,
+ captureEnd,
+ hasPendingContent,
+ _line,
+ _lineStart,
+ _lineIndent,
+ _kind = state.kind,
+ _result = state.result,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (is_WS_OR_EOL(ch) ||
+ is_FLOW_INDICATOR(ch) ||
+ ch === 0x23/* # */ ||
+ ch === 0x26/* & */ ||
+ ch === 0x2A/* * */ ||
+ ch === 0x21/* ! */ ||
+ ch === 0x7C/* | */ ||
+ ch === 0x3E/* > */ ||
+ ch === 0x27/* ' */ ||
+ ch === 0x22/* " */ ||
+ ch === 0x25/* % */ ||
+ ch === 0x40/* @ */ ||
+ ch === 0x60/* ` */) {
+ return false;
+ }
+
+ if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (is_WS_OR_EOL(following) ||
+ withinFlowCollection && is_FLOW_INDICATOR(following)) {
+ return false;
+ }
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+ captureStart = captureEnd = state.position;
+ hasPendingContent = false;
+
+ while (ch !== 0) {
+ if (ch === 0x3A/* : */) {
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (is_WS_OR_EOL(following) ||
+ withinFlowCollection && is_FLOW_INDICATOR(following)) {
+ break;
+ }
+
+ } else if (ch === 0x23/* # */) {
+ preceding = state.input.charCodeAt(state.position - 1);
+
+ if (is_WS_OR_EOL(preceding)) {
+ break;
+ }
+
+ } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
+ withinFlowCollection && is_FLOW_INDICATOR(ch)) {
+ break;
+
+ } else if (is_EOL(ch)) {
+ _line = state.line;
+ _lineStart = state.lineStart;
+ _lineIndent = state.lineIndent;
+ skipSeparationSpace(state, false, -1);
+
+ if (state.lineIndent >= nodeIndent) {
+ hasPendingContent = true;
+ ch = state.input.charCodeAt(state.position);
+ continue;
+ } else {
+ state.position = captureEnd;
+ state.line = _line;
+ state.lineStart = _lineStart;
+ state.lineIndent = _lineIndent;
+ break;
+ }
+ }
+
+ if (hasPendingContent) {
+ captureSegment(state, captureStart, captureEnd, false);
+ writeFoldedLines(state, state.line - _line);
+ captureStart = captureEnd = state.position;
+ hasPendingContent = false;
+ }
+
+ if (!is_WHITE_SPACE(ch)) {
+ captureEnd = state.position + 1;
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ captureSegment(state, captureStart, captureEnd, false);
+
+ if (state.result) {
+ return true;
+ }
+
+ state.kind = _kind;
+ state.result = _result;
+ return false;
+}
+
+function readSingleQuotedScalar(state, nodeIndent) {
+ var ch,
+ captureStart, captureEnd;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x27/* ' */) {
+ return false;
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+ state.position++;
+ captureStart = captureEnd = state.position;
+
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ if (ch === 0x27/* ' */) {
+ captureSegment(state, captureStart, state.position, true);
+ ch = state.input.charCodeAt(++state.position);
+
+ if (ch === 0x27/* ' */) {
+ captureStart = state.position;
+ state.position++;
+ captureEnd = state.position;
+ } else {
+ return true;
+ }
+
+ } else if (is_EOL(ch)) {
+ captureSegment(state, captureStart, captureEnd, true);
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
+ captureStart = captureEnd = state.position;
+
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
+ throwError(state, 'unexpected end of the document within a single quoted scalar');
+
+ } else {
+ state.position++;
+ captureEnd = state.position;
+ }
+ }
+
+ throwError(state, 'unexpected end of the stream within a single quoted scalar');
+}
+
+function readDoubleQuotedScalar(state, nodeIndent) {
+ var captureStart,
+ captureEnd,
+ hexLength,
+ hexResult,
+ tmp,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x22/* " */) {
+ return false;
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+ state.position++;
+ captureStart = captureEnd = state.position;
+
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ if (ch === 0x22/* " */) {
+ captureSegment(state, captureStart, state.position, true);
+ state.position++;
+ return true;
+
+ } else if (ch === 0x5C/* \ */) {
+ captureSegment(state, captureStart, state.position, true);
+ ch = state.input.charCodeAt(++state.position);
+
+ if (is_EOL(ch)) {
+ skipSeparationSpace(state, false, nodeIndent);
+
+ // TODO: rework to inline fn with no type cast?
+ } else if (ch < 256 && simpleEscapeCheck[ch]) {
+ state.result += simpleEscapeMap[ch];
+ state.position++;
+
+ } else if ((tmp = escapedHexLen(ch)) > 0) {
+ hexLength = tmp;
+ hexResult = 0;
+
+ for (; hexLength > 0; hexLength--) {
+ ch = state.input.charCodeAt(++state.position);
+
+ if ((tmp = fromHexCode(ch)) >= 0) {
+ hexResult = (hexResult << 4) + tmp;
+
+ } else {
+ throwError(state, 'expected hexadecimal character');
+ }
+ }
+
+ state.result += charFromCodepoint(hexResult);
+
+ state.position++;
+
+ } else {
+ throwError(state, 'unknown escape sequence');
+ }
+
+ captureStart = captureEnd = state.position;
+
+ } else if (is_EOL(ch)) {
+ captureSegment(state, captureStart, captureEnd, true);
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
+ captureStart = captureEnd = state.position;
+
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
+ throwError(state, 'unexpected end of the document within a double quoted scalar');
+
+ } else {
+ state.position++;
+ captureEnd = state.position;
+ }
+ }
+
+ throwError(state, 'unexpected end of the stream within a double quoted scalar');
+}
+
+function readFlowCollection(state, nodeIndent) {
+ var readNext = true,
+ _line,
+ _lineStart,
+ _pos,
+ _tag = state.tag,
+ _result,
+ _anchor = state.anchor,
+ following,
+ terminator,
+ isPair,
+ isExplicitPair,
+ isMapping,
+ overridableKeys = Object.create(null),
+ keyNode,
+ keyTag,
+ valueNode,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x5B/* [ */) {
+ terminator = 0x5D;/* ] */
+ isMapping = false;
+ _result = [];
+ } else if (ch === 0x7B/* { */) {
+ terminator = 0x7D;/* } */
+ isMapping = true;
+ _result = {};
+ } else {
+ return false;
+ }
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+
+ while (ch !== 0) {
+ skipSeparationSpace(state, true, nodeIndent);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === terminator) {
+ state.position++;
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = isMapping ? 'mapping' : 'sequence';
+ state.result = _result;
+ return true;
+ } else if (!readNext) {
+ throwError(state, 'missed comma between flow collection entries');
+ } else if (ch === 0x2C/* , */) {
+ // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4
+ throwError(state, "expected the node content, but found ','");
+ }
+
+ keyTag = keyNode = valueNode = null;
+ isPair = isExplicitPair = false;
+
+ if (ch === 0x3F/* ? */) {
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (is_WS_OR_EOL(following)) {
+ isPair = isExplicitPair = true;
+ state.position++;
+ skipSeparationSpace(state, true, nodeIndent);
+ }
+ }
+
+ _line = state.line; // Save the current line.
+ _lineStart = state.lineStart;
+ _pos = state.position;
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
+ keyTag = state.tag;
+ keyNode = state.result;
+ skipSeparationSpace(state, true, nodeIndent);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
+ isPair = true;
+ ch = state.input.charCodeAt(++state.position);
+ skipSeparationSpace(state, true, nodeIndent);
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
+ valueNode = state.result;
+ }
+
+ if (isMapping) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
+ } else if (isPair) {
+ _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
+ } else {
+ _result.push(keyNode);
+ }
+
+ skipSeparationSpace(state, true, nodeIndent);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x2C/* , */) {
+ readNext = true;
+ ch = state.input.charCodeAt(++state.position);
+ } else {
+ readNext = false;
+ }
+ }
+
+ throwError(state, 'unexpected end of the stream within a flow collection');
+}
+
+function readBlockScalar(state, nodeIndent) {
+ var captureStart,
+ folding,
+ chomping = CHOMPING_CLIP,
+ didReadContent = false,
+ detectedIndent = false,
+ textIndent = nodeIndent,
+ emptyLines = 0,
+ atMoreIndented = false,
+ tmp,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x7C/* | */) {
+ folding = false;
+ } else if (ch === 0x3E/* > */) {
+ folding = true;
+ } else {
+ return false;
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+
+ while (ch !== 0) {
+ ch = state.input.charCodeAt(++state.position);
+
+ if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
+ if (CHOMPING_CLIP === chomping) {
+ chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
+ } else {
+ throwError(state, 'repeat of a chomping mode identifier');
+ }
+
+ } else if ((tmp = fromDecimalCode(ch)) >= 0) {
+ if (tmp === 0) {
+ throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
+ } else if (!detectedIndent) {
+ textIndent = nodeIndent + tmp - 1;
+ detectedIndent = true;
+ } else {
+ throwError(state, 'repeat of an indentation width identifier');
+ }
+
+ } else {
+ break;
+ }
+ }
+
+ if (is_WHITE_SPACE(ch)) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (is_WHITE_SPACE(ch));
+
+ if (ch === 0x23/* # */) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (!is_EOL(ch) && (ch !== 0));
+ }
+ }
+
+ while (ch !== 0) {
+ readLineBreak(state);
+ state.lineIndent = 0;
+
+ ch = state.input.charCodeAt(state.position);
+
+ while ((!detectedIndent || state.lineIndent < textIndent) &&
+ (ch === 0x20/* Space */)) {
+ state.lineIndent++;
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (!detectedIndent && state.lineIndent > textIndent) {
+ textIndent = state.lineIndent;
+ }
+
+ if (is_EOL(ch)) {
+ emptyLines++;
+ continue;
+ }
+
+ // End of the scalar.
+ if (state.lineIndent < textIndent) {
+
+ // Perform the chomping.
+ if (chomping === CHOMPING_KEEP) {
+ state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
+ } else if (chomping === CHOMPING_CLIP) {
+ if (didReadContent) { // i.e. only if the scalar is not empty.
+ state.result += '\n';
+ }
+ }
+
+ // Break this `while` cycle and go to the funciton's epilogue.
+ break;
+ }
+
+ // Folded style: use fancy rules to handle line breaks.
+ if (folding) {
+
+ // Lines starting with white space characters (more-indented lines) are not folded.
+ if (is_WHITE_SPACE(ch)) {
+ atMoreIndented = true;
+ // except for the first content line (cf. Example 8.1)
+ state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
+
+ // End of more-indented block.
+ } else if (atMoreIndented) {
+ atMoreIndented = false;
+ state.result += common.repeat('\n', emptyLines + 1);
+
+ // Just one line break - perceive as the same line.
+ } else if (emptyLines === 0) {
+ if (didReadContent) { // i.e. only if we have already read some scalar content.
+ state.result += ' ';
+ }
+
+ // Several line breaks - perceive as different lines.
+ } else {
+ state.result += common.repeat('\n', emptyLines);
+ }
+
+ // Literal style: just add exact number of line breaks between content lines.
+ } else {
+ // Keep all line breaks except the header line break.
+ state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
+ }
+
+ didReadContent = true;
+ detectedIndent = true;
+ emptyLines = 0;
+ captureStart = state.position;
+
+ while (!is_EOL(ch) && (ch !== 0)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ captureSegment(state, captureStart, state.position, false);
+ }
+
+ return true;
+}
+
+function readBlockSequence(state, nodeIndent) {
+ var _line,
+ _tag = state.tag,
+ _anchor = state.anchor,
+ _result = [],
+ following,
+ detected = false,
+ ch;
+
+ // there is a leading tab before this token, so it can't be a block sequence/mapping;
+ // it can still be flow sequence/mapping or a scalar
+ if (state.firstTabInLine !== -1) return false;
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+
+ ch = state.input.charCodeAt(state.position);
+
+ while (ch !== 0) {
+ if (state.firstTabInLine !== -1) {
+ state.position = state.firstTabInLine;
+ throwError(state, 'tab characters must not be used in indentation');
+ }
+
+ if (ch !== 0x2D/* - */) {
+ break;
+ }
+
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (!is_WS_OR_EOL(following)) {
+ break;
+ }
+
+ detected = true;
+ state.position++;
+
+ if (skipSeparationSpace(state, true, -1)) {
+ if (state.lineIndent <= nodeIndent) {
+ _result.push(null);
+ ch = state.input.charCodeAt(state.position);
+ continue;
+ }
+ }
+
+ _line = state.line;
+ composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
+ _result.push(state.result);
+ skipSeparationSpace(state, true, -1);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
+ throwError(state, 'bad indentation of a sequence entry');
+ } else if (state.lineIndent < nodeIndent) {
+ break;
+ }
+ }
+
+ if (detected) {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = 'sequence';
+ state.result = _result;
+ return true;
+ }
+ return false;
+}
+
+function readBlockMapping(state, nodeIndent, flowIndent) {
+ var following,
+ allowCompact,
+ _line,
+ _keyLine,
+ _keyLineStart,
+ _keyPos,
+ _tag = state.tag,
+ _anchor = state.anchor,
+ _result = {},
+ overridableKeys = Object.create(null),
+ keyTag = null,
+ keyNode = null,
+ valueNode = null,
+ atExplicitKey = false,
+ detected = false,
+ ch;
+
+ // there is a leading tab before this token, so it can't be a block sequence/mapping;
+ // it can still be flow sequence/mapping or a scalar
+ if (state.firstTabInLine !== -1) return false;
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+
+ ch = state.input.charCodeAt(state.position);
+
+ while (ch !== 0) {
+ if (!atExplicitKey && state.firstTabInLine !== -1) {
+ state.position = state.firstTabInLine;
+ throwError(state, 'tab characters must not be used in indentation');
+ }
+
+ following = state.input.charCodeAt(state.position + 1);
+ _line = state.line; // Save the current line.
+
+ //
+ // Explicit notation case. There are two separate blocks:
+ // first for the key (denoted by "?") and second for the value (denoted by ":")
+ //
+ if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
+
+ if (ch === 0x3F/* ? */) {
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
+ keyTag = keyNode = valueNode = null;
+ }
+
+ detected = true;
+ atExplicitKey = true;
+ allowCompact = true;
+
+ } else if (atExplicitKey) {
+ // i.e. 0x3A/* : */ === character after the explicit key.
+ atExplicitKey = false;
+ allowCompact = true;
+
+ } else {
+ throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
+ }
+
+ state.position += 1;
+ ch = following;
+
+ //
+ // Implicit notation case. Flow-style node as the key first, then ":", and the value.
+ //
+ } else {
+ _keyLine = state.line;
+ _keyLineStart = state.lineStart;
+ _keyPos = state.position;
+
+ if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
+ // Neither implicit nor explicit notation.
+ // Reading is done. Go to the epilogue.
+ break;
+ }
+
+ if (state.line === _line) {
+ ch = state.input.charCodeAt(state.position);
+
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (ch === 0x3A/* : */) {
+ ch = state.input.charCodeAt(++state.position);
+
+ if (!is_WS_OR_EOL(ch)) {
+ throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
+ }
+
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
+ keyTag = keyNode = valueNode = null;
+ }
+
+ detected = true;
+ atExplicitKey = false;
+ allowCompact = false;
+ keyTag = state.tag;
+ keyNode = state.result;
+
+ } else if (detected) {
+ throwError(state, 'can not read an implicit mapping pair; a colon is missed');
+
+ } else {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ return true; // Keep the result of `composeNode`.
+ }
+
+ } else if (detected) {
+ throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
+
+ } else {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ return true; // Keep the result of `composeNode`.
+ }
+ }
+
+ //
+ // Common reading code for both explicit and implicit notations.
+ //
+ if (state.line === _line || state.lineIndent > nodeIndent) {
+ if (atExplicitKey) {
+ _keyLine = state.line;
+ _keyLineStart = state.lineStart;
+ _keyPos = state.position;
+ }
+
+ if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
+ if (atExplicitKey) {
+ keyNode = state.result;
+ } else {
+ valueNode = state.result;
+ }
+ }
+
+ if (!atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
+ keyTag = keyNode = valueNode = null;
+ }
+
+ skipSeparationSpace(state, true, -1);
+ ch = state.input.charCodeAt(state.position);
+ }
+
+ if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
+ throwError(state, 'bad indentation of a mapping entry');
+ } else if (state.lineIndent < nodeIndent) {
+ break;
+ }
+ }
+
+ //
+ // Epilogue.
+ //
+
+ // Special case: last mapping's node contains only the key in explicit notation.
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
+ }
+
+ // Expose the resulting mapping.
+ if (detected) {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = 'mapping';
+ state.result = _result;
+ }
+
+ return detected;
+}
+
+function readTagProperty(state) {
+ var _position,
+ isVerbatim = false,
+ isNamed = false,
+ tagHandle,
+ tagName,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x21/* ! */) return false;
+
+ if (state.tag !== null) {
+ throwError(state, 'duplication of a tag property');
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+
+ if (ch === 0x3C/* < */) {
+ isVerbatim = true;
+ ch = state.input.charCodeAt(++state.position);
+
+ } else if (ch === 0x21/* ! */) {
+ isNamed = true;
+ tagHandle = '!!';
+ ch = state.input.charCodeAt(++state.position);
+
+ } else {
+ tagHandle = '!';
+ }
+
+ _position = state.position;
+
+ if (isVerbatim) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (ch !== 0 && ch !== 0x3E/* > */);
+
+ if (state.position < state.length) {
+ tagName = state.input.slice(_position, state.position);
+ ch = state.input.charCodeAt(++state.position);
+ } else {
+ throwError(state, 'unexpected end of the stream within a verbatim tag');
+ }
+ } else {
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+
+ if (ch === 0x21/* ! */) {
+ if (!isNamed) {
+ tagHandle = state.input.slice(_position - 1, state.position + 1);
+
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
+ throwError(state, 'named tag handle cannot contain such characters');
+ }
+
+ isNamed = true;
+ _position = state.position + 1;
+ } else {
+ throwError(state, 'tag suffix cannot contain exclamation marks');
+ }
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ tagName = state.input.slice(_position, state.position);
+
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) {
+ throwError(state, 'tag suffix cannot contain flow indicator characters');
+ }
+ }
+
+ if (tagName && !PATTERN_TAG_URI.test(tagName)) {
+ throwError(state, 'tag name cannot contain such characters: ' + tagName);
+ }
+
+ try {
+ tagName = decodeURIComponent(tagName);
+ } catch (err) {
+ throwError(state, 'tag name is malformed: ' + tagName);
+ }
+
+ if (isVerbatim) {
+ state.tag = tagName;
+
+ } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
+ state.tag = state.tagMap[tagHandle] + tagName;
+
+ } else if (tagHandle === '!') {
+ state.tag = '!' + tagName;
+
+ } else if (tagHandle === '!!') {
+ state.tag = 'tag:yaml.org,2002:' + tagName;
+
+ } else {
+ throwError(state, 'undeclared tag handle "' + tagHandle + '"');
+ }
+
+ return true;
+}
+
+function readAnchorProperty(state) {
+ var _position,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x26/* & */) return false;
+
+ if (state.anchor !== null) {
+ throwError(state, 'duplication of an anchor property');
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (state.position === _position) {
+ throwError(state, 'name of an anchor node must contain at least one character');
+ }
+
+ state.anchor = state.input.slice(_position, state.position);
+ return true;
+}
+
+function readAlias(state) {
+ var _position, alias,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x2A/* * */) return false;
+
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (state.position === _position) {
+ throwError(state, 'name of an alias node must contain at least one character');
+ }
+
+ alias = state.input.slice(_position, state.position);
+
+ if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
+ throwError(state, 'unidentified alias "' + alias + '"');
+ }
+
+ state.result = state.anchorMap[alias];
+ skipSeparationSpace(state, true, -1);
+ return true;
+}
+
+function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
+ var allowBlockStyles,
+ allowBlockScalars,
+ allowBlockCollections,
+ indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) {
+ indentStatus = 1;
+ } else if (state.lineIndent === parentIndent) {
+ indentStatus = 0;
+ } else if (state.lineIndent < parentIndent) {
+ indentStatus = -1;
+ }
+ }
+ }
+
+ if (indentStatus === 1) {
+ while (readTagProperty(state) || readAnchorProperty(state)) {
+ if (skipSeparationSpace(state, true, -1)) {
+ atNewLine = true;
+ allowBlockCollections = allowBlockStyles;
+
+ if (state.lineIndent > parentIndent) {
+ indentStatus = 1;
+ } else if (state.lineIndent === parentIndent) {
+ indentStatus = 0;
+ } else if (state.lineIndent < parentIndent) {
+ indentStatus = -1;
+ }
+ } else {
+ allowBlockCollections = false;
+ }
+ }
+ }
+
+ if (allowBlockCollections) {
+ allowBlockCollections = atNewLine || allowCompact;
+ }
+
+ if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
+ if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
+ flowIndent = parentIndent;
+ } else {
+ flowIndent = parentIndent + 1;
+ }
+
+ blockIndent = state.position - state.lineStart;
+
+ if (indentStatus === 1) {
+ if (allowBlockCollections &&
+ (readBlockSequence(state, blockIndent) ||
+ readBlockMapping(state, blockIndent, flowIndent)) ||
+ readFlowCollection(state, flowIndent)) {
+ hasContent = true;
+ } else {
+ if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
+ readSingleQuotedScalar(state, flowIndent) ||
+ readDoubleQuotedScalar(state, flowIndent)) {
+ hasContent = true;
+
+ } else if (readAlias(state)) {
+ hasContent = true;
+
+ if (state.tag !== null || state.anchor !== null) {
+ throwError(state, 'alias node should not have any properties');
+ }
+
+ } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
+ hasContent = true;
+
+ if (state.tag === null) {
+ state.tag = '?';
+ }
+ }
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ }
+ } else if (indentStatus === 0) {
+ // Special case: block sequences are allowed to have same indentation level as the parent.
+ // http://www.yaml.org/spec/1.2/spec.html#id2799784
+ hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
+ }
+ }
+
+ if (state.tag === null) {
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+
+ } else if (state.tag === '?') {
+ // Implicit resolving is not allowed for non-scalar types, and '?'
+ // non-specific tag is only automatically assigned to plain scalars.
+ //
+ // We only need to check kind conformity in case user explicitly assigns '?'
+ // tag, for example like this: "!> [0]"
+ //
+ if (state.result !== null && state.kind !== 'scalar') {
+ throwError(state, 'unacceptable node kind for !> tag; it should be "scalar", not "' + state.kind + '"');
+ }
+
+ for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
+ type = state.implicitTypes[typeIndex];
+
+ if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
+ state.result = type.construct(state.result);
+ state.tag = type.tag;
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ break;
+ }
+ }
+ } else if (state.tag !== '!') {
+ if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
+ type = state.typeMap[state.kind || 'fallback'][state.tag];
+ } else {
+ // looking for multi type
+ type = null;
+ typeList = state.typeMap.multi[state.kind || 'fallback'];
+
+ for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
+ if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
+ type = typeList[typeIndex];
+ break;
+ }
+ }
+ }
+
+ if (!type) {
+ throwError(state, 'unknown tag !<' + state.tag + '>');
+ }
+
+ if (state.result !== null && type.kind !== state.kind) {
+ throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
+ }
+
+ if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched
+ throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
+ } else {
+ state.result = type.construct(state.result, state.tag);
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ }
+ }
+
+ if (state.listener !== null) {
+ state.listener('close', state);
+ }
+ return state.tag !== null || state.anchor !== null || hasContent;
+}
+
+function readDocument(state) {
+ var documentStart = state.position,
+ _position,
+ directiveName,
+ directiveArgs,
+ hasDirectives = false,
+ ch;
+
+ state.version = null;
+ state.checkLineBreaks = state.legacy;
+ state.tagMap = Object.create(null);
+ state.anchorMap = Object.create(null);
+
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ skipSeparationSpace(state, true, -1);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (state.lineIndent > 0 || ch !== 0x25/* % */) {
+ break;
+ }
+
+ hasDirectives = true;
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ directiveName = state.input.slice(_position, state.position);
+ directiveArgs = [];
+
+ if (directiveName.length < 1) {
+ throwError(state, 'directive name must not be less than one character in length');
+ }
+
+ while (ch !== 0) {
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (ch === 0x23/* # */) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (ch !== 0 && !is_EOL(ch));
+ break;
+ }
+
+ if (is_EOL(ch)) break;
+
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ directiveArgs.push(state.input.slice(_position, state.position));
+ }
+
+ if (ch !== 0) readLineBreak(state);
+
+ if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
+ directiveHandlers[directiveName](state, directiveName, directiveArgs);
+ } else {
+ throwWarning(state, 'unknown document directive "' + directiveName + '"');
+ }
+ }
+
+ skipSeparationSpace(state, true, -1);
+
+ if (state.lineIndent === 0 &&
+ state.input.charCodeAt(state.position) === 0x2D/* - */ &&
+ state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
+ state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
+ state.position += 3;
+ skipSeparationSpace(state, true, -1);
+
+ } else if (hasDirectives) {
+ throwError(state, 'directives end mark is expected');
+ }
+
+ composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
+ skipSeparationSpace(state, true, -1);
+
+ if (state.checkLineBreaks &&
+ PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
+ throwWarning(state, 'non-ASCII line breaks are interpreted as content');
+ }
+
+ state.documents.push(state.result);
+
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
+
+ if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
+ state.position += 3;
+ skipSeparationSpace(state, true, -1);
+ }
+ return;
+ }
+
+ if (state.position < (state.length - 1)) {
+ throwError(state, 'end of the stream or a document separator is expected');
+ } else {
+ return;
+ }
+}
+
+
+function loadDocuments(input, options) {
+ input = String(input);
+ options = options || {};
+
+ if (input.length !== 0) {
+
+ // Add tailing `\n` if not exists
+ if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
+ input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
+ input += '\n';
+ }
+
+ // Strip BOM
+ if (input.charCodeAt(0) === 0xFEFF) {
+ input = input.slice(1);
+ }
+ }
+
+ var state = new State$1(input, options);
+
+ var nullpos = input.indexOf('\0');
+
+ if (nullpos !== -1) {
+ state.position = nullpos;
+ throwError(state, 'null byte is not allowed in input');
+ }
+
+ // Use 0 as string terminator. That significantly simplifies bounds check.
+ state.input += '\0';
+
+ while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
+ state.lineIndent += 1;
+ state.position += 1;
+ }
+
+ while (state.position < (state.length - 1)) {
+ readDocument(state);
+ }
+
+ return state.documents;
+}
+
+
+function loadAll$1(input, iterator, options) {
+ if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
+ options = iterator;
+ iterator = null;
+ }
+
+ var documents = loadDocuments(input, options);
+
+ if (typeof iterator !== 'function') {
+ return documents;
+ }
+
+ for (var index = 0, length = documents.length; index < length; index += 1) {
+ iterator(documents[index]);
+ }
+}
+
+
+function load$1(input, options) {
+ var documents = loadDocuments(input, options);
+
+ if (documents.length === 0) {
+ /*eslint-disable no-undefined*/
+ return undefined;
+ } else if (documents.length === 1) {
+ return documents[0];
+ }
+ throw new exception('expected a single document in the stream, but found more');
+}
+
+
+var loadAll_1 = loadAll$1;
+var load_1 = load$1;
+
+var loader = {
+ loadAll: loadAll_1,
+ load: load_1
+};
+
+/*eslint-disable no-use-before-define*/
+
+
+
+
+
+var _toString = Object.prototype.toString;
+var _hasOwnProperty = Object.prototype.hasOwnProperty;
+
+var CHAR_BOM = 0xFEFF;
+var CHAR_TAB = 0x09; /* Tab */
+var CHAR_LINE_FEED = 0x0A; /* LF */
+var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
+var CHAR_SPACE = 0x20; /* Space */
+var CHAR_EXCLAMATION = 0x21; /* ! */
+var CHAR_DOUBLE_QUOTE = 0x22; /* " */
+var CHAR_SHARP = 0x23; /* # */
+var CHAR_PERCENT = 0x25; /* % */
+var CHAR_AMPERSAND = 0x26; /* & */
+var CHAR_SINGLE_QUOTE = 0x27; /* ' */
+var CHAR_ASTERISK = 0x2A; /* * */
+var CHAR_COMMA = 0x2C; /* , */
+var CHAR_MINUS = 0x2D; /* - */
+var CHAR_COLON = 0x3A; /* : */
+var CHAR_EQUALS = 0x3D; /* = */
+var CHAR_GREATER_THAN = 0x3E; /* > */
+var CHAR_QUESTION = 0x3F; /* ? */
+var CHAR_COMMERCIAL_AT = 0x40; /* @ */
+var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
+var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
+var CHAR_GRAVE_ACCENT = 0x60; /* ` */
+var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
+var CHAR_VERTICAL_LINE = 0x7C; /* | */
+var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
+
+var ESCAPE_SEQUENCES = {};
+
+ESCAPE_SEQUENCES[0x00] = '\\0';
+ESCAPE_SEQUENCES[0x07] = '\\a';
+ESCAPE_SEQUENCES[0x08] = '\\b';
+ESCAPE_SEQUENCES[0x09] = '\\t';
+ESCAPE_SEQUENCES[0x0A] = '\\n';
+ESCAPE_SEQUENCES[0x0B] = '\\v';
+ESCAPE_SEQUENCES[0x0C] = '\\f';
+ESCAPE_SEQUENCES[0x0D] = '\\r';
+ESCAPE_SEQUENCES[0x1B] = '\\e';
+ESCAPE_SEQUENCES[0x22] = '\\"';
+ESCAPE_SEQUENCES[0x5C] = '\\\\';
+ESCAPE_SEQUENCES[0x85] = '\\N';
+ESCAPE_SEQUENCES[0xA0] = '\\_';
+ESCAPE_SEQUENCES[0x2028] = '\\L';
+ESCAPE_SEQUENCES[0x2029] = '\\P';
+
+var DEPRECATED_BOOLEANS_SYNTAX = [
+ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
+ 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
+];
+
+var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
+
+function compileStyleMap(schema, map) {
+ var result, keys, index, length, tag, style, type;
+
+ if (map === null) return {};
+
+ result = {};
+ keys = Object.keys(map);
+
+ for (index = 0, length = keys.length; index < length; index += 1) {
+ tag = keys[index];
+ style = String(map[tag]);
+
+ if (tag.slice(0, 2) === '!!') {
+ tag = 'tag:yaml.org,2002:' + tag.slice(2);
+ }
+ type = schema.compiledTypeMap['fallback'][tag];
+
+ if (type && _hasOwnProperty.call(type.styleAliases, style)) {
+ style = type.styleAliases[style];
+ }
+
+ result[tag] = style;
+ }
+
+ return result;
+}
+
+function encodeHex(character) {
+ var string, handle, length;
+
+ string = character.toString(16).toUpperCase();
+
+ if (character <= 0xFF) {
+ handle = 'x';
+ length = 2;
+ } else if (character <= 0xFFFF) {
+ handle = 'u';
+ length = 4;
+ } else if (character <= 0xFFFFFFFF) {
+ handle = 'U';
+ length = 8;
+ } else {
+ throw new exception('code point within a string may not be greater than 0xFFFFFFFF');
+ }
+
+ return '\\' + handle + common.repeat('0', length - string.length) + string;
+}
+
+
+var QUOTING_TYPE_SINGLE = 1,
+ QUOTING_TYPE_DOUBLE = 2;
+
+function js_yaml_State(options) {
+ this.schema = options['schema'] || _default;
+ this.indent = Math.max(1, (options['indent'] || 2));
+ this.noArrayIndent = options['noArrayIndent'] || false;
+ this.skipInvalid = options['skipInvalid'] || false;
+ this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
+ this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
+ this.sortKeys = options['sortKeys'] || false;
+ this.lineWidth = options['lineWidth'] || 80;
+ this.noRefs = options['noRefs'] || false;
+ this.noCompatMode = options['noCompatMode'] || false;
+ this.condenseFlow = options['condenseFlow'] || false;
+ this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
+ this.forceQuotes = options['forceQuotes'] || false;
+ this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null;
+
+ this.implicitTypes = this.schema.compiledImplicit;
+ this.explicitTypes = this.schema.compiledExplicit;
+
+ this.tag = null;
+ this.result = '';
+
+ this.duplicates = [];
+ this.usedDuplicates = null;
+}
+
+// Indents every line in a string. Empty lines (\n only) are not indented.
+function indentString(string, spaces) {
+ var ind = common.repeat(' ', spaces),
+ position = 0,
+ next = -1,
+ result = '',
+ line,
+ length = string.length;
+
+ while (position < length) {
+ next = string.indexOf('\n', position);
+ if (next === -1) {
+ line = string.slice(position);
+ position = length;
+ } else {
+ line = string.slice(position, next + 1);
+ position = next + 1;
+ }
+
+ if (line.length && line !== '\n') result += ind;
+
+ result += line;
+ }
+
+ return result;
+}
+
+function generateNextLine(state, level) {
+ return '\n' + common.repeat(' ', state.indent * level);
+}
+
+function testImplicitResolving(state, str) {
+ var index, length, type;
+
+ for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
+ type = state.implicitTypes[index];
+
+ if (type.resolve(str)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// [33] s-white ::= s-space | s-tab
+function js_yaml_isWhitespace(c) {
+ return c === CHAR_SPACE || c === CHAR_TAB;
+}
+
+// Returns true if the character can be printed without escaping.
+// From YAML 1.2: "any allowed characters known to be non-printable
+// should also be escaped. [However,] This isn’t mandatory"
+// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
+function isPrintable(c) {
+ return (0x00020 <= c && c <= 0x00007E)
+ || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
+ || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM)
+ || (0x10000 <= c && c <= 0x10FFFF);
+}
+
+// [34] ns-char ::= nb-char - s-white
+// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
+// [26] b-char ::= b-line-feed | b-carriage-return
+// Including s-white (for some reason, examples doesn't match specs in this aspect)
+// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark
+function isNsCharOrWhitespace(c) {
+ return isPrintable(c)
+ && c !== CHAR_BOM
+ // - b-char
+ && c !== CHAR_CARRIAGE_RETURN
+ && c !== CHAR_LINE_FEED;
+}
+
+// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out
+// c = flow-in ⇒ ns-plain-safe-in
+// c = block-key ⇒ ns-plain-safe-out
+// c = flow-key ⇒ ns-plain-safe-in
+// [128] ns-plain-safe-out ::= ns-char
+// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator
+// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” )
+// | ( /* An ns-char preceding */ “#” )
+// | ( “:” /* Followed by an ns-plain-safe(c) */ )
+function isPlainSafe(c, prev, inblock) {
+ var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
+ var cIsNsChar = cIsNsCharOrWhitespace && !js_yaml_isWhitespace(c);
+ return (
+ // ns-plain-safe
+ inblock ? // c = flow-in
+ cIsNsCharOrWhitespace
+ : cIsNsCharOrWhitespace
+ // - c-flow-indicator
+ && c !== CHAR_COMMA
+ && c !== CHAR_LEFT_SQUARE_BRACKET
+ && c !== CHAR_RIGHT_SQUARE_BRACKET
+ && c !== CHAR_LEFT_CURLY_BRACKET
+ && c !== CHAR_RIGHT_CURLY_BRACKET
+ )
+ // ns-plain-char
+ && c !== CHAR_SHARP // false on '#'
+ && !(prev === CHAR_COLON && !cIsNsChar) // false on ': '
+ || (isNsCharOrWhitespace(prev) && !js_yaml_isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#'
+ || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]'
+}
+
+// Simplified test for values allowed as the first character in plain style.
+function isPlainSafeFirst(c) {
+ // Uses a subset of ns-char - c-indicator
+ // where ns-char = nb-char - s-white.
+ // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part
+ return isPrintable(c) && c !== CHAR_BOM
+ && !js_yaml_isWhitespace(c) // - s-white
+ // - (c-indicator ::=
+ // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
+ && c !== CHAR_MINUS
+ && c !== CHAR_QUESTION
+ && c !== CHAR_COLON
+ && c !== CHAR_COMMA
+ && c !== CHAR_LEFT_SQUARE_BRACKET
+ && c !== CHAR_RIGHT_SQUARE_BRACKET
+ && c !== CHAR_LEFT_CURLY_BRACKET
+ && c !== CHAR_RIGHT_CURLY_BRACKET
+ // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
+ && c !== CHAR_SHARP
+ && c !== CHAR_AMPERSAND
+ && c !== CHAR_ASTERISK
+ && c !== CHAR_EXCLAMATION
+ && c !== CHAR_VERTICAL_LINE
+ && c !== CHAR_EQUALS
+ && c !== CHAR_GREATER_THAN
+ && c !== CHAR_SINGLE_QUOTE
+ && c !== CHAR_DOUBLE_QUOTE
+ // | “%” | “@” | “`”)
+ && c !== CHAR_PERCENT
+ && c !== CHAR_COMMERCIAL_AT
+ && c !== CHAR_GRAVE_ACCENT;
+}
+
+// Simplified test for values allowed as the last character in plain style.
+function isPlainSafeLast(c) {
+ // just not whitespace or colon, it will be checked to be plain character later
+ return !js_yaml_isWhitespace(c) && c !== CHAR_COLON;
+}
+
+// Same as 'string'.codePointAt(pos), but works in older browsers.
+function codePointAt(string, pos) {
+ var first = string.charCodeAt(pos), second;
+ if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {
+ second = string.charCodeAt(pos + 1);
+ if (second >= 0xDC00 && second <= 0xDFFF) {
+ // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
+ return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+ }
+ }
+ return first;
+}
+
+// Determines whether block indentation indicator is required.
+function needIndentIndicator(string) {
+ var leadingSpaceRe = /^\n* /;
+ return leadingSpaceRe.test(string);
+}
+
+var STYLE_PLAIN = 1,
+ STYLE_SINGLE = 2,
+ STYLE_LITERAL = 3,
+ STYLE_FOLDED = 4,
+ STYLE_DOUBLE = 5;
+
+// Determines which scalar styles are possible and returns the preferred style.
+// lineWidth = -1 => no limit.
+// Pre-conditions: str.length > 0.
+// Post-conditions:
+// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
+// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
+// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
+function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth,
+ testAmbiguousType, quotingType, forceQuotes, inblock) {
+
+ var i;
+ var char = 0;
+ var prevChar = null;
+ var hasLineBreak = false;
+ var hasFoldableLine = false; // only checked if shouldTrackWidth
+ var shouldTrackWidth = lineWidth !== -1;
+ var previousLineBreak = -1; // count the first line correctly
+ var plain = isPlainSafeFirst(codePointAt(string, 0))
+ && isPlainSafeLast(codePointAt(string, string.length - 1));
+
+ if (singleLineOnly || forceQuotes) {
+ // Case: no block styles.
+ // Check for disallowed characters to rule out plain and single.
+ for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
+ char = codePointAt(string, i);
+ if (!isPrintable(char)) {
+ return STYLE_DOUBLE;
+ }
+ plain = plain && isPlainSafe(char, prevChar, inblock);
+ prevChar = char;
+ }
+ } else {
+ // Case: block styles permitted.
+ for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
+ char = codePointAt(string, i);
+ if (char === CHAR_LINE_FEED) {
+ hasLineBreak = true;
+ // Check if any line can be folded.
+ if (shouldTrackWidth) {
+ hasFoldableLine = hasFoldableLine ||
+ // Foldable line = too long, and not more-indented.
+ (i - previousLineBreak - 1 > lineWidth &&
+ string[previousLineBreak + 1] !== ' ');
+ previousLineBreak = i;
+ }
+ } else if (!isPrintable(char)) {
+ return STYLE_DOUBLE;
+ }
+ plain = plain && isPlainSafe(char, prevChar, inblock);
+ prevChar = char;
+ }
+ // in case the end is missing a \n
+ hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
+ (i - previousLineBreak - 1 > lineWidth &&
+ string[previousLineBreak + 1] !== ' '));
+ }
+ // Although every style can represent \n without escaping, prefer block styles
+ // for multiline, since they're more readable and they don't add empty lines.
+ // Also prefer folding a super-long line.
+ if (!hasLineBreak && !hasFoldableLine) {
+ // Strings interpretable as another type have to be quoted;
+ // e.g. the string 'true' vs. the boolean true.
+ if (plain && !forceQuotes && !testAmbiguousType(string)) {
+ return STYLE_PLAIN;
+ }
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
+ }
+ // Edge case: block indentation indicator can only have one digit.
+ if (indentPerLevel > 9 && needIndentIndicator(string)) {
+ return STYLE_DOUBLE;
+ }
+ // At this point we know block styles are valid.
+ // Prefer literal style unless we want to fold.
+ if (!forceQuotes) {
+ return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
+ }
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
+}
+
+// Note: line breaking/folding is implemented for only the folded style.
+// NB. We drop the last trailing newline (if any) of a returned block scalar
+// since the dumper adds its own newline. This always works:
+// • No ending newline => unaffected; already using strip "-" chomping.
+// • Ending newline => removed then restored.
+// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
+function writeScalar(state, string, level, iskey, inblock) {
+ state.dump = (function () {
+ if (string.length === 0) {
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
+ }
+ if (!state.noCompatMode) {
+ if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'");
+ }
+ }
+
+ var indent = state.indent * Math.max(1, level); // no 0-indent scalars
+ // As indentation gets deeper, let the width decrease monotonically
+ // to the lower bound min(state.lineWidth, 40).
+ // Note that this implies
+ // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
+ // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
+ // This behaves better than a constant minimum width which disallows narrower options,
+ // or an indent threshold which causes the width to suddenly increase.
+ var lineWidth = state.lineWidth === -1
+ ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
+
+ // Without knowing if keys are implicit/explicit, assume implicit for safety.
+ var singleLineOnly = iskey
+ // No block styles in flow mode.
+ || (state.flowLevel > -1 && level >= state.flowLevel);
+ function testAmbiguity(string) {
+ return testImplicitResolving(state, string);
+ }
+
+ switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,
+ testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
+
+ case STYLE_PLAIN:
+ return string;
+ case STYLE_SINGLE:
+ return "'" + string.replace(/'/g, "''") + "'";
+ case STYLE_LITERAL:
+ return '|' + blockHeader(string, state.indent)
+ + dropEndingNewline(indentString(string, indent));
+ case STYLE_FOLDED:
+ return '>' + blockHeader(string, state.indent)
+ + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
+ case STYLE_DOUBLE:
+ return '"' + escapeString(string) + '"';
+ default:
+ throw new exception('impossible error: invalid scalar style');
+ }
+ }());
+}
+
+// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
+function blockHeader(string, indentPerLevel) {
+ var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
+
+ // note the special case: the string '\n' counts as a "trailing" empty line.
+ var clip = string[string.length - 1] === '\n';
+ var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
+ var chomp = keep ? '+' : (clip ? '' : '-');
+
+ return indentIndicator + chomp + '\n';
+}
+
+// (See the note for writeScalar.)
+function dropEndingNewline(string) {
+ return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
+}
+
+// Note: a long line without a suitable break point will exceed the width limit.
+// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
+function foldString(string, width) {
+ // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
+ // unless they're before or after a more-indented line, or at the very
+ // beginning or end, in which case $k$ maps to $k$.
+ // Therefore, parse each chunk as newline(s) followed by a content line.
+ var lineRe = /(\n+)([^\n]*)/g;
+
+ // first line (possibly an empty line)
+ var result = (function () {
+ var nextLF = string.indexOf('\n');
+ nextLF = nextLF !== -1 ? nextLF : string.length;
+ lineRe.lastIndex = nextLF;
+ return foldLine(string.slice(0, nextLF), width);
+ }());
+ // If we haven't reached the first content line yet, don't add an extra \n.
+ var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
+ var moreIndented;
+
+ // rest of the lines
+ var match;
+ while ((match = lineRe.exec(string))) {
+ var prefix = match[1], line = match[2];
+ moreIndented = (line[0] === ' ');
+ result += prefix
+ + (!prevMoreIndented && !moreIndented && line !== ''
+ ? '\n' : '')
+ + foldLine(line, width);
+ prevMoreIndented = moreIndented;
+ }
+
+ return result;
+}
+
+// Greedy line breaking.
+// Picks the longest line under the limit each time,
+// otherwise settles for the shortest line over the limit.
+// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
+function foldLine(line, width) {
+ if (line === '' || line[0] === ' ') return line;
+
+ // Since a more-indented line adds a \n, breaks can't be followed by a space.
+ var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
+ var match;
+ // start is an inclusive index. end, curr, and next are exclusive.
+ var start = 0, end, curr = 0, next = 0;
+ var result = '';
+
+ // Invariants: 0 <= start <= length-1.
+ // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
+ // Inside the loop:
+ // A match implies length >= 2, so curr and next are <= length-2.
+ while ((match = breakRe.exec(line))) {
+ next = match.index;
+ // maintain invariant: curr - start <= width
+ if (next - start > width) {
+ end = (curr > start) ? curr : next; // derive end <= length-2
+ result += '\n' + line.slice(start, end);
+ // skip the space that was output as \n
+ start = end + 1; // derive start <= length-1
+ }
+ curr = next;
+ }
+
+ // By the invariants, start <= length-1, so there is something left over.
+ // It is either the whole string or a part starting from non-whitespace.
+ result += '\n';
+ // Insert a break if the remainder is too long and there is a break available.
+ if (line.length - start > width && curr > start) {
+ result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
+ } else {
+ result += line.slice(start);
+ }
+
+ return result.slice(1); // drop extra \n joiner
+}
+
+// Escapes a double-quoted string.
+function escapeString(string) {
+ var result = '';
+ var char = 0;
+ var escapeSeq;
+
+ for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
+ char = codePointAt(string, i);
+ escapeSeq = ESCAPE_SEQUENCES[char];
+
+ if (!escapeSeq && isPrintable(char)) {
+ result += string[i];
+ if (char >= 0x10000) result += string[i + 1];
+ } else {
+ result += escapeSeq || encodeHex(char);
+ }
+ }
+
+ return result;
+}
+
+function writeFlowSequence(state, level, object) {
+ var _result = '',
+ _tag = state.tag,
+ index,
+ length,
+ value;
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ value = object[index];
+
+ if (state.replacer) {
+ value = state.replacer.call(object, String(index), value);
+ }
+
+ // Write only valid elements, put null instead of invalid elements.
+ if (writeNode(state, level, value, false, false) ||
+ (typeof value === 'undefined' &&
+ writeNode(state, level, null, false, false))) {
+
+ if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '');
+ _result += state.dump;
+ }
+ }
+
+ state.tag = _tag;
+ state.dump = '[' + _result + ']';
+}
+
+function writeBlockSequence(state, level, object, compact) {
+ var _result = '',
+ _tag = state.tag,
+ index,
+ length,
+ value;
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ value = object[index];
+
+ if (state.replacer) {
+ value = state.replacer.call(object, String(index), value);
+ }
+
+ // Write only valid elements, put null instead of invalid elements.
+ if (writeNode(state, level + 1, value, true, true, false, true) ||
+ (typeof value === 'undefined' &&
+ writeNode(state, level + 1, null, true, true, false, true))) {
+
+ if (!compact || _result !== '') {
+ _result += generateNextLine(state, level);
+ }
+
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ _result += '-';
+ } else {
+ _result += '- ';
+ }
+
+ _result += state.dump;
+ }
+ }
+
+ state.tag = _tag;
+ state.dump = _result || '[]'; // Empty sequence if no valid values.
+}
+
+function writeFlowMapping(state, level, object) {
+ var _result = '',
+ _tag = state.tag,
+ objectKeyList = Object.keys(object),
+ index,
+ length,
+ objectKey,
+ objectValue,
+ pairBuffer;
+
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+
+ pairBuffer = '';
+ if (_result !== '') pairBuffer += ', ';
+
+ if (state.condenseFlow) pairBuffer += '"';
+
+ objectKey = objectKeyList[index];
+ objectValue = object[objectKey];
+
+ if (state.replacer) {
+ objectValue = state.replacer.call(object, objectKey, objectValue);
+ }
+
+ if (!writeNode(state, level, objectKey, false, false)) {
+ continue; // Skip this pair because of invalid key;
+ }
+
+ if (state.dump.length > 1024) pairBuffer += '? ';
+
+ pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
+
+ if (!writeNode(state, level, objectValue, false, false)) {
+ continue; // Skip this pair because of invalid value.
+ }
+
+ pairBuffer += state.dump;
+
+ // Both key and value are valid.
+ _result += pairBuffer;
+ }
+
+ state.tag = _tag;
+ state.dump = '{' + _result + '}';
+}
+
+function writeBlockMapping(state, level, object, compact) {
+ var _result = '',
+ _tag = state.tag,
+ objectKeyList = Object.keys(object),
+ index,
+ length,
+ objectKey,
+ objectValue,
+ explicitPair,
+ pairBuffer;
+
+ // Allow sorting keys so that the output file is deterministic
+ if (state.sortKeys === true) {
+ // Default sorting
+ objectKeyList.sort();
+ } else if (typeof state.sortKeys === 'function') {
+ // Custom sort function
+ objectKeyList.sort(state.sortKeys);
+ } else if (state.sortKeys) {
+ // Something is wrong
+ throw new exception('sortKeys must be a boolean or a function');
+ }
+
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+ pairBuffer = '';
+
+ if (!compact || _result !== '') {
+ pairBuffer += generateNextLine(state, level);
+ }
+
+ objectKey = objectKeyList[index];
+ objectValue = object[objectKey];
+
+ if (state.replacer) {
+ objectValue = state.replacer.call(object, objectKey, objectValue);
+ }
+
+ if (!writeNode(state, level + 1, objectKey, true, true, true)) {
+ continue; // Skip this pair because of invalid key.
+ }
+
+ explicitPair = (state.tag !== null && state.tag !== '?') ||
+ (state.dump && state.dump.length > 1024);
+
+ if (explicitPair) {
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ pairBuffer += '?';
+ } else {
+ pairBuffer += '? ';
+ }
+ }
+
+ pairBuffer += state.dump;
+
+ if (explicitPair) {
+ pairBuffer += generateNextLine(state, level);
+ }
+
+ if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
+ continue; // Skip this pair because of invalid value.
+ }
+
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ pairBuffer += ':';
+ } else {
+ pairBuffer += ': ';
+ }
+
+ pairBuffer += state.dump;
+
+ // Both key and value are valid.
+ _result += pairBuffer;
+ }
+
+ state.tag = _tag;
+ state.dump = _result || '{}'; // Empty mapping if no valid pairs.
+}
+
+function detectType(state, object, explicit) {
+ var _result, typeList, index, length, type, style;
+
+ typeList = explicit ? state.explicitTypes : state.implicitTypes;
+
+ for (index = 0, length = typeList.length; index < length; index += 1) {
+ type = typeList[index];
+
+ if ((type.instanceOf || type.predicate) &&
+ (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
+ (!type.predicate || type.predicate(object))) {
+
+ if (explicit) {
+ if (type.multi && type.representName) {
+ state.tag = type.representName(object);
+ } else {
+ state.tag = type.tag;
+ }
+ } else {
+ state.tag = '?';
+ }
+
+ if (type.represent) {
+ style = state.styleMap[type.tag] || type.defaultStyle;
+
+ if (_toString.call(type.represent) === '[object Function]') {
+ _result = type.represent(object, style);
+ } else if (_hasOwnProperty.call(type.represent, style)) {
+ _result = type.represent[style](object, style);
+ } else {
+ throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
+ }
+
+ state.dump = _result;
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// Serializes `object` and writes it to global `result`.
+// Returns true on success, or false on invalid object.
+//
+function writeNode(state, level, object, block, compact, iskey, isblockseq) {
+ state.tag = null;
+ state.dump = object;
+
+ if (!detectType(state, object, false)) {
+ detectType(state, object, true);
+ }
+
+ var type = _toString.call(state.dump);
+ var inblock = block;
+ var tagStr;
+
+ if (block) {
+ block = (state.flowLevel < 0 || state.flowLevel > level);
+ }
+
+ var objectOrArray = type === '[object Object]' || type === '[object Array]',
+ duplicateIndex,
+ duplicate;
+
+ if (objectOrArray) {
+ duplicateIndex = state.duplicates.indexOf(object);
+ duplicate = duplicateIndex !== -1;
+ }
+
+ if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
+ compact = false;
+ }
+
+ if (duplicate && state.usedDuplicates[duplicateIndex]) {
+ state.dump = '*ref_' + duplicateIndex;
+ } else {
+ if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
+ state.usedDuplicates[duplicateIndex] = true;
+ }
+ if (type === '[object Object]') {
+ if (block && (Object.keys(state.dump).length !== 0)) {
+ writeBlockMapping(state, level, state.dump, compact);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + state.dump;
+ }
+ } else {
+ writeFlowMapping(state, level, state.dump);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
+ }
+ }
+ } else if (type === '[object Array]') {
+ if (block && (state.dump.length !== 0)) {
+ if (state.noArrayIndent && !isblockseq && level > 0) {
+ writeBlockSequence(state, level - 1, state.dump, compact);
+ } else {
+ writeBlockSequence(state, level, state.dump, compact);
+ }
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + state.dump;
+ }
+ } else {
+ writeFlowSequence(state, level, state.dump);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
+ }
+ }
+ } else if (type === '[object String]') {
+ if (state.tag !== '?') {
+ writeScalar(state, state.dump, level, iskey, inblock);
+ }
+ } else if (type === '[object Undefined]') {
+ return false;
+ } else {
+ if (state.skipInvalid) return false;
+ throw new exception('unacceptable kind of an object to dump ' + type);
+ }
+
+ if (state.tag !== null && state.tag !== '?') {
+ // Need to encode all characters except those allowed by the spec:
+ //
+ // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */
+ // [36] ns-hex-digit ::= ns-dec-digit
+ // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */
+ // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */
+ // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-”
+ // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”
+ // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
+ // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”
+ //
+ // Also need to encode '!' because it has special meaning (end of tag prefix).
+ //
+ tagStr = encodeURI(
+ state.tag[0] === '!' ? state.tag.slice(1) : state.tag
+ ).replace(/!/g, '%21');
+
+ if (state.tag[0] === '!') {
+ tagStr = '!' + tagStr;
+ } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {
+ tagStr = '!!' + tagStr.slice(18);
+ } else {
+ tagStr = '!<' + tagStr + '>';
+ }
+
+ state.dump = tagStr + ' ' + state.dump;
+ }
+ }
+
+ return true;
+}
+
+function getDuplicateReferences(object, state) {
+ var objects = [],
+ duplicatesIndexes = [],
+ index,
+ length;
+
+ inspectNode(object, objects, duplicatesIndexes);
+
+ for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
+ state.duplicates.push(objects[duplicatesIndexes[index]]);
+ }
+ state.usedDuplicates = new Array(length);
+}
+
+function inspectNode(object, objects, duplicatesIndexes) {
+ var objectKeyList,
+ index,
+ length;
+
+ if (object !== null && typeof object === 'object') {
+ index = objects.indexOf(object);
+ if (index !== -1) {
+ if (duplicatesIndexes.indexOf(index) === -1) {
+ duplicatesIndexes.push(index);
+ }
+ } else {
+ objects.push(object);
+
+ if (Array.isArray(object)) {
+ for (index = 0, length = object.length; index < length; index += 1) {
+ inspectNode(object[index], objects, duplicatesIndexes);
+ }
+ } else {
+ objectKeyList = Object.keys(object);
+
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+ inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
+ }
+ }
+ }
+ }
+}
+
+function dump$1(input, options) {
+ options = options || {};
+
+ var state = new js_yaml_State(options);
+
+ if (!state.noRefs) getDuplicateReferences(input, state);
+
+ var value = input;
+
+ if (state.replacer) {
+ value = state.replacer.call({ '': value }, '', value);
+ }
+
+ if (writeNode(state, 0, value, true, true)) return state.dump + '\n';
+
+ return '';
+}
+
+var dump_1 = dump$1;
+
+var dumper = {
+ dump: dump_1
+};
+
+function renamed(from, to) {
+ return function () {
+ throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +
+ 'Use yaml.' + to + ' instead, which is now safe by default.');
+ };
+}
+
+
+var Type = type;
+var Schema = schema;
+var FAILSAFE_SCHEMA = failsafe;
+var JSON_SCHEMA = json;
+var CORE_SCHEMA = core;
+var DEFAULT_SCHEMA = _default;
+var load = loader.load;
+var loadAll = loader.loadAll;
+var dump = dumper.dump;
+var YAMLException = exception;
+
+// Re-export all types in case user wants to create custom schema
+var types = {
+ binary: binary,
+ float: js_yaml_float,
+ map: map,
+ null: _null,
+ pairs: pairs,
+ set: set,
+ timestamp: timestamp,
+ bool: bool,
+ int: js_yaml_int,
+ merge: merge,
+ omap: omap,
+ seq: seq,
+ str: str
+};
+
+// Removed functions from JS-YAML 3.0.x
+var safeLoad = renamed('safeLoad', 'load');
+var safeLoadAll = renamed('safeLoadAll', 'loadAll');
+var safeDump = renamed('safeDump', 'dump');
+
+var jsYaml = {
+ Type: Type,
+ Schema: Schema,
+ FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,
+ JSON_SCHEMA: JSON_SCHEMA,
+ CORE_SCHEMA: CORE_SCHEMA,
+ DEFAULT_SCHEMA: DEFAULT_SCHEMA,
+ load: load,
+ loadAll: loadAll,
+ dump: dump,
+ YAMLException: YAMLException,
+ types: types,
+ safeLoad: safeLoad,
+ safeLoadAll: safeLoadAll,
+ safeDump: safeDump
+};
+
+/* harmony default export */ const js_yaml = (jsYaml);
+
+
+// EXTERNAL MODULE: ./node_modules/base64-js/index.js
+var base64_js = __webpack_require__(9742);
+// EXTERNAL MODULE: ./node_modules/reflect-metadata/Reflect.js
+var reflect_metadata_Reflect = __webpack_require__(8660);
+// EXTERNAL MODULE: ./node_modules/pvtsutils/build/index.js
+var build = __webpack_require__(4585);
+;// CONCATENATED MODULE: ./node_modules/pvutils/build/utils.es.js
+/*!
+ Copyright (c) Peculiar Ventures, LLC
+*/
+
+function getUTCDate(date) {
+ return new Date(date.getTime() + (date.getTimezoneOffset() * 60000));
+}
+function getParametersValue(parameters, name, defaultValue) {
+ var _a;
+ if ((parameters instanceof Object) === false) {
+ return defaultValue;
+ }
+ return (_a = parameters[name]) !== null && _a !== void 0 ? _a : defaultValue;
+}
+function bufferToHexCodes(inputBuffer, inputOffset = 0, inputLength = (inputBuffer.byteLength - inputOffset), insertSpace = false) {
+ let result = "";
+ for (const item of (new Uint8Array(inputBuffer, inputOffset, inputLength))) {
+ const str = item.toString(16).toUpperCase();
+ if (str.length === 1) {
+ result += "0";
+ }
+ result += str;
+ if (insertSpace) {
+ result += " ";
+ }
+ }
+ return result.trim();
+}
+function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {
+ if (!(inputBuffer instanceof ArrayBuffer)) {
+ baseBlock.error = "Wrong parameter: inputBuffer must be \"ArrayBuffer\"";
+ return false;
+ }
+ if (!inputBuffer.byteLength) {
+ baseBlock.error = "Wrong parameter: inputBuffer has zero length";
+ return false;
+ }
+ if (inputOffset < 0) {
+ baseBlock.error = "Wrong parameter: inputOffset less than zero";
+ return false;
+ }
+ if (inputLength < 0) {
+ baseBlock.error = "Wrong parameter: inputLength less than zero";
+ return false;
+ }
+ if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {
+ baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
+ return false;
+ }
+ return true;
+}
+function utilFromBase(inputBuffer, inputBase) {
+ let result = 0;
+ if (inputBuffer.length === 1) {
+ return inputBuffer[0];
+ }
+ for (let i = (inputBuffer.length - 1); i >= 0; i--) {
+ result += inputBuffer[(inputBuffer.length - 1) - i] * Math.pow(2, inputBase * i);
+ }
+ return result;
+}
+function utilToBase(value, base, reserved = (-1)) {
+ const internalReserved = reserved;
+ let internalValue = value;
+ let result = 0;
+ let biggest = Math.pow(2, base);
+ for (let i = 1; i < 8; i++) {
+ if (value < biggest) {
+ let retBuf;
+ if (internalReserved < 0) {
+ retBuf = new ArrayBuffer(i);
+ result = i;
+ }
+ else {
+ if (internalReserved < i) {
+ return (new ArrayBuffer(0));
+ }
+ retBuf = new ArrayBuffer(internalReserved);
+ result = internalReserved;
+ }
+ const retView = new Uint8Array(retBuf);
+ for (let j = (i - 1); j >= 0; j--) {
+ const basis = Math.pow(2, j * base);
+ retView[result - j - 1] = Math.floor(internalValue / basis);
+ internalValue -= (retView[result - j - 1]) * basis;
+ }
+ return retBuf;
+ }
+ biggest *= Math.pow(2, base);
+ }
+ return new ArrayBuffer(0);
+}
+function utilConcatBuf(...buffers) {
+ let outputLength = 0;
+ let prevLength = 0;
+ for (const buffer of buffers) {
+ outputLength += buffer.byteLength;
+ }
+ const retBuf = new ArrayBuffer(outputLength);
+ const retView = new Uint8Array(retBuf);
+ for (const buffer of buffers) {
+ retView.set(new Uint8Array(buffer), prevLength);
+ prevLength += buffer.byteLength;
+ }
+ return retBuf;
+}
+function utilConcatView(...views) {
+ let outputLength = 0;
+ let prevLength = 0;
+ for (const view of views) {
+ outputLength += view.length;
+ }
+ const retBuf = new ArrayBuffer(outputLength);
+ const retView = new Uint8Array(retBuf);
+ for (const view of views) {
+ retView.set(view, prevLength);
+ prevLength += view.length;
+ }
+ return retView;
+}
+function utilDecodeTC() {
+ const buf = new Uint8Array(this.valueHex);
+ if (this.valueHex.byteLength >= 2) {
+ const condition1 = (buf[0] === 0xFF) && (buf[1] & 0x80);
+ const condition2 = (buf[0] === 0x00) && ((buf[1] & 0x80) === 0x00);
+ if (condition1 || condition2) {
+ this.warnings.push("Needlessly long format");
+ }
+ }
+ const bigIntBuffer = new ArrayBuffer(this.valueHex.byteLength);
+ const bigIntView = new Uint8Array(bigIntBuffer);
+ for (let i = 0; i < this.valueHex.byteLength; i++) {
+ bigIntView[i] = 0;
+ }
+ bigIntView[0] = (buf[0] & 0x80);
+ const bigInt = utilFromBase(bigIntView, 8);
+ const smallIntBuffer = new ArrayBuffer(this.valueHex.byteLength);
+ const smallIntView = new Uint8Array(smallIntBuffer);
+ for (let j = 0; j < this.valueHex.byteLength; j++) {
+ smallIntView[j] = buf[j];
+ }
+ smallIntView[0] &= 0x7F;
+ const smallInt = utilFromBase(smallIntView, 8);
+ return (smallInt - bigInt);
+}
+function utilEncodeTC(value) {
+ const modValue = (value < 0) ? (value * (-1)) : value;
+ let bigInt = 128;
+ for (let i = 1; i < 8; i++) {
+ if (modValue <= bigInt) {
+ if (value < 0) {
+ const smallInt = bigInt - modValue;
+ const retBuf = utilToBase(smallInt, 8, i);
+ const retView = new Uint8Array(retBuf);
+ retView[0] |= 0x80;
+ return retBuf;
+ }
+ let retBuf = utilToBase(modValue, 8, i);
+ let retView = new Uint8Array(retBuf);
+ if (retView[0] & 0x80) {
+ const tempBuf = retBuf.slice(0);
+ const tempView = new Uint8Array(tempBuf);
+ retBuf = new ArrayBuffer(retBuf.byteLength + 1);
+ retView = new Uint8Array(retBuf);
+ for (let k = 0; k < tempBuf.byteLength; k++) {
+ retView[k + 1] = tempView[k];
+ }
+ retView[0] = 0x00;
+ }
+ return retBuf;
+ }
+ bigInt *= Math.pow(2, 8);
+ }
+ return (new ArrayBuffer(0));
+}
+function isEqualBuffer(inputBuffer1, inputBuffer2) {
+ if (inputBuffer1.byteLength !== inputBuffer2.byteLength) {
+ return false;
+ }
+ const view1 = new Uint8Array(inputBuffer1);
+ const view2 = new Uint8Array(inputBuffer2);
+ for (let i = 0; i < view1.length; i++) {
+ if (view1[i] !== view2[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+function padNumber(inputNumber, fullLength) {
+ const str = inputNumber.toString(10);
+ if (fullLength < str.length) {
+ return "";
+ }
+ const dif = fullLength - str.length;
+ const padding = new Array(dif);
+ for (let i = 0; i < dif; i++) {
+ padding[i] = "0";
+ }
+ const paddingString = padding.join("");
+ return paddingString.concat(str);
+}
+const base64Template = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+const base64UrlTemplate = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";
+function toBase64(input, useUrlTemplate = false, skipPadding = false, skipLeadingZeros = false) {
+ let i = 0;
+ let flag1 = 0;
+ let flag2 = 0;
+ let output = "";
+ const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;
+ if (skipLeadingZeros) {
+ let nonZeroPosition = 0;
+ for (let i = 0; i < input.length; i++) {
+ if (input.charCodeAt(i) !== 0) {
+ nonZeroPosition = i;
+ break;
+ }
+ }
+ input = input.slice(nonZeroPosition);
+ }
+ while (i < input.length) {
+ const chr1 = input.charCodeAt(i++);
+ if (i >= input.length) {
+ flag1 = 1;
+ }
+ const chr2 = input.charCodeAt(i++);
+ if (i >= input.length) {
+ flag2 = 1;
+ }
+ const chr3 = input.charCodeAt(i++);
+ const enc1 = chr1 >> 2;
+ const enc2 = ((chr1 & 0x03) << 4) | (chr2 >> 4);
+ let enc3 = ((chr2 & 0x0F) << 2) | (chr3 >> 6);
+ let enc4 = chr3 & 0x3F;
+ if (flag1 === 1) {
+ enc3 = enc4 = 64;
+ }
+ else {
+ if (flag2 === 1) {
+ enc4 = 64;
+ }
+ }
+ if (skipPadding) {
+ if (enc3 === 64) {
+ output += `${template.charAt(enc1)}${template.charAt(enc2)}`;
+ }
+ else {
+ if (enc4 === 64) {
+ output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}`;
+ }
+ else {
+ output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;
+ }
+ }
+ }
+ else {
+ output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;
+ }
+ }
+ return output;
+}
+function fromBase64(input, useUrlTemplate = false, cutTailZeros = false) {
+ const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;
+ function indexOf(toSearch) {
+ for (let i = 0; i < 64; i++) {
+ if (template.charAt(i) === toSearch)
+ return i;
+ }
+ return 64;
+ }
+ function test(incoming) {
+ return ((incoming === 64) ? 0x00 : incoming);
+ }
+ let i = 0;
+ let output = "";
+ while (i < input.length) {
+ const enc1 = indexOf(input.charAt(i++));
+ const enc2 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));
+ const enc3 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));
+ const enc4 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));
+ const chr1 = (test(enc1) << 2) | (test(enc2) >> 4);
+ const chr2 = ((test(enc2) & 0x0F) << 4) | (test(enc3) >> 2);
+ const chr3 = ((test(enc3) & 0x03) << 6) | test(enc4);
+ output += String.fromCharCode(chr1);
+ if (enc3 !== 64) {
+ output += String.fromCharCode(chr2);
+ }
+ if (enc4 !== 64) {
+ output += String.fromCharCode(chr3);
+ }
+ }
+ if (cutTailZeros) {
+ const outputLength = output.length;
+ let nonZeroStart = (-1);
+ for (let i = (outputLength - 1); i >= 0; i--) {
+ if (output.charCodeAt(i) !== 0) {
+ nonZeroStart = i;
+ break;
+ }
+ }
+ if (nonZeroStart !== (-1)) {
+ output = output.slice(0, nonZeroStart + 1);
+ }
+ else {
+ output = "";
+ }
+ }
+ return output;
+}
+function arrayBufferToString(buffer) {
+ let resultString = "";
+ const view = new Uint8Array(buffer);
+ for (const element of view) {
+ resultString += String.fromCharCode(element);
+ }
+ return resultString;
+}
+function stringToArrayBuffer(str) {
+ const stringLength = str.length;
+ const resultBuffer = new ArrayBuffer(stringLength);
+ const resultView = new Uint8Array(resultBuffer);
+ for (let i = 0; i < stringLength; i++) {
+ resultView[i] = str.charCodeAt(i);
+ }
+ return resultBuffer;
+}
+const log2 = Math.log(2);
+function nearestPowerOf2(length) {
+ const base = (Math.log(length) / log2);
+ const floor = Math.floor(base);
+ const round = Math.round(base);
+ return ((floor === round) ? floor : round);
+}
+function clearProps(object, propsArray) {
+ for (const prop of propsArray) {
+ delete object[prop];
+ }
+}
+
+
+
+;// CONCATENATED MODULE: ./node_modules/asn1js/build/index.es.js
+/*!
+ * Copyright (c) 2014, GMO GlobalSign
+ * Copyright (c) 2015-2022, Peculiar Ventures
+ * All rights reserved.
+ *
+ * Author 2014-2019, Yury Strozhevsky
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright notice, this
+ * list of conditions and the following disclaimer in the documentation and/or
+ * other materials provided with the distribution.
+ *
+ * * Neither the name of the copyright holder nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+
+
+function assertBigInt() {
+ if (typeof BigInt === "undefined") {
+ throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.");
+ }
+}
+function concat(buffers) {
+ let outputLength = 0;
+ let prevLength = 0;
+ for (let i = 0; i < buffers.length; i++) {
+ const buffer = buffers[i];
+ outputLength += buffer.byteLength;
+ }
+ const retView = new Uint8Array(outputLength);
+ for (let i = 0; i < buffers.length; i++) {
+ const buffer = buffers[i];
+ retView.set(new Uint8Array(buffer), prevLength);
+ prevLength += buffer.byteLength;
+ }
+ return retView.buffer;
+}
+function index_es_checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {
+ if (!(inputBuffer instanceof Uint8Array)) {
+ baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'";
+ return false;
+ }
+ if (!inputBuffer.byteLength) {
+ baseBlock.error = "Wrong parameter: inputBuffer has zero length";
+ return false;
+ }
+ if (inputOffset < 0) {
+ baseBlock.error = "Wrong parameter: inputOffset less than zero";
+ return false;
+ }
+ if (inputLength < 0) {
+ baseBlock.error = "Wrong parameter: inputLength less than zero";
+ return false;
+ }
+ if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {
+ baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
+ return false;
+ }
+ return true;
+}
+
+class ViewWriter {
+ constructor() {
+ this.items = [];
+ }
+ write(buf) {
+ this.items.push(buf);
+ }
+ final() {
+ return concat(this.items);
+ }
+}
+
+const powers2 = [new Uint8Array([1])];
+const digitsString = "0123456789";
+const NAME = "name";
+const VALUE_HEX_VIEW = "valueHexView";
+const IS_HEX_ONLY = "isHexOnly";
+const ID_BLOCK = "idBlock";
+const TAG_CLASS = "tagClass";
+const TAG_NUMBER = "tagNumber";
+const IS_CONSTRUCTED = "isConstructed";
+const FROM_BER = "fromBER";
+const TO_BER = "toBER";
+const LOCAL = "local";
+const EMPTY_STRING = "";
+const EMPTY_BUFFER = new ArrayBuffer(0);
+const EMPTY_VIEW = new Uint8Array(0);
+const END_OF_CONTENT_NAME = "EndOfContent";
+const OCTET_STRING_NAME = "OCTET STRING";
+const BIT_STRING_NAME = "BIT STRING";
+
+function HexBlock(BaseClass) {
+ var _a;
+ return _a = class Some extends BaseClass {
+ constructor(...args) {
+ var _a;
+ super(...args);
+ const params = args[0] || {};
+ this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;
+ this.valueHexView = params.valueHex ? build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(params.valueHex) : EMPTY_VIEW;
+ }
+ get valueHex() {
+ return this.valueHexView.slice().buffer;
+ }
+ set valueHex(value) {
+ this.valueHexView = new Uint8Array(value);
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
+ if (!index_es_checkBufferParams(this, view, inputOffset, inputLength)) {
+ return -1;
+ }
+ const endLength = inputOffset + inputLength;
+ this.valueHexView = view.subarray(inputOffset, endLength);
+ if (!this.valueHexView.length) {
+ this.warnings.push("Zero buffer length");
+ return inputOffset;
+ }
+ this.blockLength = inputLength;
+ return endLength;
+ }
+ toBER(sizeOnly = false) {
+ if (!this.isHexOnly) {
+ this.error = "Flag 'isHexOnly' is not set, abort";
+ return EMPTY_BUFFER;
+ }
+ if (sizeOnly) {
+ return new ArrayBuffer(this.valueHexView.byteLength);
+ }
+ return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength)
+ ? this.valueHexView.buffer
+ : this.valueHexView.slice().buffer;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ isHexOnly: this.isHexOnly,
+ valueHex: build/* Convert.ToHex */.ep.ToHex(this.valueHexView),
+ };
+ }
+ },
+ _a.NAME = "hexBlock",
+ _a;
+}
+
+class LocalBaseBlock {
+ constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) {
+ this.blockLength = blockLength;
+ this.error = error;
+ this.warnings = warnings;
+ this.valueBeforeDecodeView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(valueBeforeDecode);
+ }
+ static blockName() {
+ return this.NAME;
+ }
+ get valueBeforeDecode() {
+ return this.valueBeforeDecodeView.slice().buffer;
+ }
+ set valueBeforeDecode(value) {
+ this.valueBeforeDecodeView = new Uint8Array(value);
+ }
+ toJSON() {
+ return {
+ blockName: this.constructor.NAME,
+ blockLength: this.blockLength,
+ error: this.error,
+ warnings: this.warnings,
+ valueBeforeDecode: build/* Convert.ToHex */.ep.ToHex(this.valueBeforeDecodeView),
+ };
+ }
+}
+LocalBaseBlock.NAME = "baseBlock";
+
+class ValueBlock extends LocalBaseBlock {
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
+ }
+ toBER(sizeOnly, writer) {
+ throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
+ }
+}
+ValueBlock.NAME = "valueBlock";
+
+class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {
+ constructor({ idBlock = {}, } = {}) {
+ var _a, _b, _c, _d;
+ super();
+ if (idBlock) {
+ this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;
+ this.valueHexView = idBlock.valueHex ? build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;
+ this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;
+ this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;
+ this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;
+ }
+ else {
+ this.tagClass = -1;
+ this.tagNumber = -1;
+ this.isConstructed = false;
+ }
+ }
+ toBER(sizeOnly = false) {
+ let firstOctet = 0;
+ switch (this.tagClass) {
+ case 1:
+ firstOctet |= 0x00;
+ break;
+ case 2:
+ firstOctet |= 0x40;
+ break;
+ case 3:
+ firstOctet |= 0x80;
+ break;
+ case 4:
+ firstOctet |= 0xC0;
+ break;
+ default:
+ this.error = "Unknown tag class";
+ return EMPTY_BUFFER;
+ }
+ if (this.isConstructed)
+ firstOctet |= 0x20;
+ if (this.tagNumber < 31 && !this.isHexOnly) {
+ const retView = new Uint8Array(1);
+ if (!sizeOnly) {
+ let number = this.tagNumber;
+ number &= 0x1F;
+ firstOctet |= number;
+ retView[0] = firstOctet;
+ }
+ return retView.buffer;
+ }
+ if (!this.isHexOnly) {
+ const encodedBuf = utilToBase(this.tagNumber, 7);
+ const encodedView = new Uint8Array(encodedBuf);
+ const size = encodedBuf.byteLength;
+ const retView = new Uint8Array(size + 1);
+ retView[0] = (firstOctet | 0x1F);
+ if (!sizeOnly) {
+ for (let i = 0; i < (size - 1); i++)
+ retView[i + 1] = encodedView[i] | 0x80;
+ retView[size] = encodedView[size - 1];
+ }
+ return retView.buffer;
+ }
+ const retView = new Uint8Array(this.valueHexView.byteLength + 1);
+ retView[0] = (firstOctet | 0x1F);
+ if (!sizeOnly) {
+ const curView = this.valueHexView;
+ for (let i = 0; i < (curView.length - 1); i++)
+ retView[i + 1] = curView[i] | 0x80;
+ retView[this.valueHexView.byteLength] = curView[curView.length - 1];
+ }
+ return retView.buffer;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ const inputView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer);
+ if (!index_es_checkBufferParams(this, inputView, inputOffset, inputLength)) {
+ return -1;
+ }
+ const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
+ if (intBuffer.length === 0) {
+ this.error = "Zero buffer length";
+ return -1;
+ }
+ const tagClassMask = intBuffer[0] & 0xC0;
+ switch (tagClassMask) {
+ case 0x00:
+ this.tagClass = (1);
+ break;
+ case 0x40:
+ this.tagClass = (2);
+ break;
+ case 0x80:
+ this.tagClass = (3);
+ break;
+ case 0xC0:
+ this.tagClass = (4);
+ break;
+ default:
+ this.error = "Unknown tag class";
+ return -1;
+ }
+ this.isConstructed = (intBuffer[0] & 0x20) === 0x20;
+ this.isHexOnly = false;
+ const tagNumberMask = intBuffer[0] & 0x1F;
+ if (tagNumberMask !== 0x1F) {
+ this.tagNumber = (tagNumberMask);
+ this.blockLength = 1;
+ }
+ else {
+ let count = 1;
+ let intTagNumberBuffer = this.valueHexView = new Uint8Array(255);
+ let tagNumberBufferMaxLength = 255;
+ while (intBuffer[count] & 0x80) {
+ intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;
+ count++;
+ if (count >= intBuffer.length) {
+ this.error = "End of input reached before message was fully decoded";
+ return -1;
+ }
+ if (count === tagNumberBufferMaxLength) {
+ tagNumberBufferMaxLength += 255;
+ const tempBufferView = new Uint8Array(tagNumberBufferMaxLength);
+ for (let i = 0; i < intTagNumberBuffer.length; i++)
+ tempBufferView[i] = intTagNumberBuffer[i];
+ intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength);
+ }
+ }
+ this.blockLength = (count + 1);
+ intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;
+ const tempBufferView = new Uint8Array(count);
+ for (let i = 0; i < count; i++)
+ tempBufferView[i] = intTagNumberBuffer[i];
+ intTagNumberBuffer = this.valueHexView = new Uint8Array(count);
+ intTagNumberBuffer.set(tempBufferView);
+ if (this.blockLength <= 9)
+ this.tagNumber = utilFromBase(intTagNumberBuffer, 7);
+ else {
+ this.isHexOnly = true;
+ this.warnings.push("Tag too long, represented as hex-coded");
+ }
+ }
+ if (((this.tagClass === 1)) &&
+ (this.isConstructed)) {
+ switch (this.tagNumber) {
+ case 1:
+ case 2:
+ case 5:
+ case 6:
+ case 9:
+ case 13:
+ case 14:
+ case 23:
+ case 24:
+ case 31:
+ case 32:
+ case 33:
+ case 34:
+ this.error = "Constructed encoding used for primitive type";
+ return -1;
+ }
+ }
+ return (inputOffset + this.blockLength);
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ tagClass: this.tagClass,
+ tagNumber: this.tagNumber,
+ isConstructed: this.isConstructed,
+ };
+ }
+}
+LocalIdentificationBlock.NAME = "identificationBlock";
+
+class LocalLengthBlock extends LocalBaseBlock {
+ constructor({ lenBlock = {}, } = {}) {
+ var _a, _b, _c;
+ super();
+ this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;
+ this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;
+ this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ const view = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer);
+ if (!index_es_checkBufferParams(this, view, inputOffset, inputLength)) {
+ return -1;
+ }
+ const intBuffer = view.subarray(inputOffset, inputOffset + inputLength);
+ if (intBuffer.length === 0) {
+ this.error = "Zero buffer length";
+ return -1;
+ }
+ if (intBuffer[0] === 0xFF) {
+ this.error = "Length block 0xFF is reserved by standard";
+ return -1;
+ }
+ this.isIndefiniteForm = intBuffer[0] === 0x80;
+ if (this.isIndefiniteForm) {
+ this.blockLength = 1;
+ return (inputOffset + this.blockLength);
+ }
+ this.longFormUsed = !!(intBuffer[0] & 0x80);
+ if (this.longFormUsed === false) {
+ this.length = (intBuffer[0]);
+ this.blockLength = 1;
+ return (inputOffset + this.blockLength);
+ }
+ const count = intBuffer[0] & 0x7F;
+ if (count > 8) {
+ this.error = "Too big integer";
+ return -1;
+ }
+ if ((count + 1) > intBuffer.length) {
+ this.error = "End of input reached before message was fully decoded";
+ return -1;
+ }
+ const lenOffset = inputOffset + 1;
+ const lengthBufferView = view.subarray(lenOffset, lenOffset + count);
+ if (lengthBufferView[count - 1] === 0x00)
+ this.warnings.push("Needlessly long encoded length");
+ this.length = utilFromBase(lengthBufferView, 8);
+ if (this.longFormUsed && (this.length <= 127))
+ this.warnings.push("Unnecessary usage of long length form");
+ this.blockLength = count + 1;
+ return (inputOffset + this.blockLength);
+ }
+ toBER(sizeOnly = false) {
+ let retBuf;
+ let retView;
+ if (this.length > 127)
+ this.longFormUsed = true;
+ if (this.isIndefiniteForm) {
+ retBuf = new ArrayBuffer(1);
+ if (sizeOnly === false) {
+ retView = new Uint8Array(retBuf);
+ retView[0] = 0x80;
+ }
+ return retBuf;
+ }
+ if (this.longFormUsed) {
+ const encodedBuf = utilToBase(this.length, 8);
+ if (encodedBuf.byteLength > 127) {
+ this.error = "Too big length";
+ return (EMPTY_BUFFER);
+ }
+ retBuf = new ArrayBuffer(encodedBuf.byteLength + 1);
+ if (sizeOnly)
+ return retBuf;
+ const encodedView = new Uint8Array(encodedBuf);
+ retView = new Uint8Array(retBuf);
+ retView[0] = encodedBuf.byteLength | 0x80;
+ for (let i = 0; i < encodedBuf.byteLength; i++)
+ retView[i + 1] = encodedView[i];
+ return retBuf;
+ }
+ retBuf = new ArrayBuffer(1);
+ if (sizeOnly === false) {
+ retView = new Uint8Array(retBuf);
+ retView[0] = this.length;
+ }
+ return retBuf;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ isIndefiniteForm: this.isIndefiniteForm,
+ longFormUsed: this.longFormUsed,
+ length: this.length,
+ };
+ }
+}
+LocalLengthBlock.NAME = "lengthBlock";
+
+const typeStore = {};
+
+class BaseBlock extends LocalBaseBlock {
+ constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) {
+ super(parameters);
+ this.name = name;
+ this.optional = optional;
+ if (primitiveSchema) {
+ this.primitiveSchema = primitiveSchema;
+ }
+ this.idBlock = new LocalIdentificationBlock(parameters);
+ this.lenBlock = new LocalLengthBlock(parameters);
+ this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters);
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);
+ if (resultOffset === -1) {
+ this.error = this.valueBlock.error;
+ return resultOffset;
+ }
+ if (!this.idBlock.error.length)
+ this.blockLength += this.idBlock.blockLength;
+ if (!this.lenBlock.error.length)
+ this.blockLength += this.lenBlock.blockLength;
+ if (!this.valueBlock.error.length)
+ this.blockLength += this.valueBlock.blockLength;
+ return resultOffset;
+ }
+ toBER(sizeOnly, writer) {
+ const _writer = writer || new ViewWriter();
+ if (!writer) {
+ prepareIndefiniteForm(this);
+ }
+ const idBlockBuf = this.idBlock.toBER(sizeOnly);
+ _writer.write(idBlockBuf);
+ if (this.lenBlock.isIndefiniteForm) {
+ _writer.write(new Uint8Array([0x80]).buffer);
+ this.valueBlock.toBER(sizeOnly, _writer);
+ _writer.write(new ArrayBuffer(2));
+ }
+ else {
+ const valueBlockBuf = this.valueBlock.toBER(sizeOnly);
+ this.lenBlock.length = valueBlockBuf.byteLength;
+ const lenBlockBuf = this.lenBlock.toBER(sizeOnly);
+ _writer.write(lenBlockBuf);
+ _writer.write(valueBlockBuf);
+ }
+ if (!writer) {
+ return _writer.final();
+ }
+ return EMPTY_BUFFER;
+ }
+ toJSON() {
+ const object = {
+ ...super.toJSON(),
+ idBlock: this.idBlock.toJSON(),
+ lenBlock: this.lenBlock.toJSON(),
+ valueBlock: this.valueBlock.toJSON(),
+ name: this.name,
+ optional: this.optional,
+ };
+ if (this.primitiveSchema)
+ object.primitiveSchema = this.primitiveSchema.toJSON();
+ return object;
+ }
+ toString(encoding = "ascii") {
+ if (encoding === "ascii") {
+ return this.onAsciiEncoding();
+ }
+ return build/* Convert.ToHex */.ep.ToHex(this.toBER());
+ }
+ onAsciiEncoding() {
+ return `${this.constructor.NAME} : ${build/* Convert.ToHex */.ep.ToHex(this.valueBlock.valueBeforeDecodeView)}`;
+ }
+ isEqual(other) {
+ if (this === other) {
+ return true;
+ }
+ if (!(other instanceof this.constructor)) {
+ return false;
+ }
+ const thisRaw = this.toBER();
+ const otherRaw = other.toBER();
+ return isEqualBuffer(thisRaw, otherRaw);
+ }
+}
+BaseBlock.NAME = "BaseBlock";
+function prepareIndefiniteForm(baseBlock) {
+ if (baseBlock instanceof typeStore.Constructed) {
+ for (const value of baseBlock.valueBlock.value) {
+ if (prepareIndefiniteForm(value)) {
+ baseBlock.lenBlock.isIndefiniteForm = true;
+ }
+ }
+ }
+ return !!baseBlock.lenBlock.isIndefiniteForm;
+}
+
+class BaseStringBlock extends BaseBlock {
+ constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
+ super(parameters, stringValueBlockType);
+ if (value) {
+ this.fromString(value);
+ }
+ }
+ getValue() {
+ return this.valueBlock.value;
+ }
+ setValue(value) {
+ this.valueBlock.value = value;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);
+ if (resultOffset === -1) {
+ this.error = this.valueBlock.error;
+ return resultOffset;
+ }
+ this.fromBuffer(this.valueBlock.valueHexView);
+ if (!this.idBlock.error.length)
+ this.blockLength += this.idBlock.blockLength;
+ if (!this.lenBlock.error.length)
+ this.blockLength += this.lenBlock.blockLength;
+ if (!this.valueBlock.error.length)
+ this.blockLength += this.valueBlock.blockLength;
+ return resultOffset;
+ }
+ onAsciiEncoding() {
+ return `${this.constructor.NAME} : '${this.valueBlock.value}'`;
+ }
+}
+BaseStringBlock.NAME = "BaseStringBlock";
+
+class LocalPrimitiveValueBlock extends HexBlock(ValueBlock) {
+ constructor({ isHexOnly = true, ...parameters } = {}) {
+ super(parameters);
+ this.isHexOnly = isHexOnly;
+ }
+}
+LocalPrimitiveValueBlock.NAME = "PrimitiveValueBlock";
+
+var _a$w;
+class Primitive extends BaseBlock {
+ constructor(parameters = {}) {
+ super(parameters, LocalPrimitiveValueBlock);
+ this.idBlock.isConstructed = false;
+ }
+}
+_a$w = Primitive;
+(() => {
+ typeStore.Primitive = _a$w;
+})();
+Primitive.NAME = "PRIMITIVE";
+
+function localChangeType(inputObject, newType) {
+ if (inputObject instanceof newType) {
+ return inputObject;
+ }
+ const newObject = new newType();
+ newObject.idBlock = inputObject.idBlock;
+ newObject.lenBlock = inputObject.lenBlock;
+ newObject.warnings = inputObject.warnings;
+ newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView;
+ return newObject;
+}
+function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) {
+ const incomingOffset = inputOffset;
+ let returnObject = new BaseBlock({}, ValueBlock);
+ const baseBlock = new LocalBaseBlock();
+ if (!index_es_checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) {
+ returnObject.error = baseBlock.error;
+ return {
+ offset: -1,
+ result: returnObject
+ };
+ }
+ const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength);
+ if (!intBuffer.length) {
+ returnObject.error = "Zero buffer length";
+ return {
+ offset: -1,
+ result: returnObject
+ };
+ }
+ let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength);
+ if (returnObject.idBlock.warnings.length) {
+ returnObject.warnings.concat(returnObject.idBlock.warnings);
+ }
+ if (resultOffset === -1) {
+ returnObject.error = returnObject.idBlock.error;
+ return {
+ offset: -1,
+ result: returnObject
+ };
+ }
+ inputOffset = resultOffset;
+ inputLength -= returnObject.idBlock.blockLength;
+ resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength);
+ if (returnObject.lenBlock.warnings.length) {
+ returnObject.warnings.concat(returnObject.lenBlock.warnings);
+ }
+ if (resultOffset === -1) {
+ returnObject.error = returnObject.lenBlock.error;
+ return {
+ offset: -1,
+ result: returnObject
+ };
+ }
+ inputOffset = resultOffset;
+ inputLength -= returnObject.lenBlock.blockLength;
+ if (!returnObject.idBlock.isConstructed &&
+ returnObject.lenBlock.isIndefiniteForm) {
+ returnObject.error = "Indefinite length form used for primitive encoding form";
+ return {
+ offset: -1,
+ result: returnObject
+ };
+ }
+ let newASN1Type = BaseBlock;
+ switch (returnObject.idBlock.tagClass) {
+ case 1:
+ if ((returnObject.idBlock.tagNumber >= 37) &&
+ (returnObject.idBlock.isHexOnly === false)) {
+ returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard";
+ return {
+ offset: -1,
+ result: returnObject
+ };
+ }
+ switch (returnObject.idBlock.tagNumber) {
+ case 0:
+ if ((returnObject.idBlock.isConstructed) &&
+ (returnObject.lenBlock.length > 0)) {
+ returnObject.error = "Type [UNIVERSAL 0] is reserved";
+ return {
+ offset: -1,
+ result: returnObject
+ };
+ }
+ newASN1Type = typeStore.EndOfContent;
+ break;
+ case 1:
+ newASN1Type = typeStore.Boolean;
+ break;
+ case 2:
+ newASN1Type = typeStore.Integer;
+ break;
+ case 3:
+ newASN1Type = typeStore.BitString;
+ break;
+ case 4:
+ newASN1Type = typeStore.OctetString;
+ break;
+ case 5:
+ newASN1Type = typeStore.Null;
+ break;
+ case 6:
+ newASN1Type = typeStore.ObjectIdentifier;
+ break;
+ case 10:
+ newASN1Type = typeStore.Enumerated;
+ break;
+ case 12:
+ newASN1Type = typeStore.Utf8String;
+ break;
+ case 13:
+ newASN1Type = typeStore.RelativeObjectIdentifier;
+ break;
+ case 14:
+ newASN1Type = typeStore.TIME;
+ break;
+ case 15:
+ returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard";
+ return {
+ offset: -1,
+ result: returnObject
+ };
+ case 16:
+ newASN1Type = typeStore.Sequence;
+ break;
+ case 17:
+ newASN1Type = typeStore.Set;
+ break;
+ case 18:
+ newASN1Type = typeStore.NumericString;
+ break;
+ case 19:
+ newASN1Type = typeStore.PrintableString;
+ break;
+ case 20:
+ newASN1Type = typeStore.TeletexString;
+ break;
+ case 21:
+ newASN1Type = typeStore.VideotexString;
+ break;
+ case 22:
+ newASN1Type = typeStore.IA5String;
+ break;
+ case 23:
+ newASN1Type = typeStore.UTCTime;
+ break;
+ case 24:
+ newASN1Type = typeStore.GeneralizedTime;
+ break;
+ case 25:
+ newASN1Type = typeStore.GraphicString;
+ break;
+ case 26:
+ newASN1Type = typeStore.VisibleString;
+ break;
+ case 27:
+ newASN1Type = typeStore.GeneralString;
+ break;
+ case 28:
+ newASN1Type = typeStore.UniversalString;
+ break;
+ case 29:
+ newASN1Type = typeStore.CharacterString;
+ break;
+ case 30:
+ newASN1Type = typeStore.BmpString;
+ break;
+ case 31:
+ newASN1Type = typeStore.DATE;
+ break;
+ case 32:
+ newASN1Type = typeStore.TimeOfDay;
+ break;
+ case 33:
+ newASN1Type = typeStore.DateTime;
+ break;
+ case 34:
+ newASN1Type = typeStore.Duration;
+ break;
+ default: {
+ const newObject = returnObject.idBlock.isConstructed
+ ? new typeStore.Constructed()
+ : new typeStore.Primitive();
+ newObject.idBlock = returnObject.idBlock;
+ newObject.lenBlock = returnObject.lenBlock;
+ newObject.warnings = returnObject.warnings;
+ returnObject = newObject;
+ }
+ }
+ break;
+ case 2:
+ case 3:
+ case 4:
+ default: {
+ newASN1Type = returnObject.idBlock.isConstructed
+ ? typeStore.Constructed
+ : typeStore.Primitive;
+ }
+ }
+ returnObject = localChangeType(returnObject, newASN1Type);
+ resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length);
+ returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength);
+ return {
+ offset: resultOffset,
+ result: returnObject
+ };
+}
+function fromBER(inputBuffer) {
+ if (!inputBuffer.byteLength) {
+ const result = new BaseBlock({}, ValueBlock);
+ result.error = "Input buffer has zero length";
+ return {
+ offset: -1,
+ result
+ };
+ }
+ return localFromBER(build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength);
+}
+
+function checkLen(indefiniteLength, length) {
+ if (indefiniteLength) {
+ return 1;
+ }
+ return length;
+}
+class LocalConstructedValueBlock extends ValueBlock {
+ constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) {
+ super(parameters);
+ this.value = value;
+ this.isIndefiniteForm = isIndefiniteForm;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ const view = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer);
+ if (!index_es_checkBufferParams(this, view, inputOffset, inputLength)) {
+ return -1;
+ }
+ this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength);
+ if (this.valueBeforeDecodeView.length === 0) {
+ this.warnings.push("Zero buffer length");
+ return inputOffset;
+ }
+ let currentOffset = inputOffset;
+ while (checkLen(this.isIndefiniteForm, inputLength) > 0) {
+ const returnObject = localFromBER(view, currentOffset, inputLength);
+ if (returnObject.offset === -1) {
+ this.error = returnObject.result.error;
+ this.warnings.concat(returnObject.result.warnings);
+ return -1;
+ }
+ currentOffset = returnObject.offset;
+ this.blockLength += returnObject.result.blockLength;
+ inputLength -= returnObject.result.blockLength;
+ this.value.push(returnObject.result);
+ if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) {
+ break;
+ }
+ }
+ if (this.isIndefiniteForm) {
+ if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) {
+ this.value.pop();
+ }
+ else {
+ this.warnings.push("No EndOfContent block encoded");
+ }
+ }
+ return currentOffset;
+ }
+ toBER(sizeOnly, writer) {
+ const _writer = writer || new ViewWriter();
+ for (let i = 0; i < this.value.length; i++) {
+ this.value[i].toBER(sizeOnly, _writer);
+ }
+ if (!writer) {
+ return _writer.final();
+ }
+ return EMPTY_BUFFER;
+ }
+ toJSON() {
+ const object = {
+ ...super.toJSON(),
+ isIndefiniteForm: this.isIndefiniteForm,
+ value: [],
+ };
+ for (const value of this.value) {
+ object.value.push(value.toJSON());
+ }
+ return object;
+ }
+}
+LocalConstructedValueBlock.NAME = "ConstructedValueBlock";
+
+var _a$v;
+class Constructed extends BaseBlock {
+ constructor(parameters = {}) {
+ super(parameters, LocalConstructedValueBlock);
+ this.idBlock.isConstructed = true;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
+ const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);
+ if (resultOffset === -1) {
+ this.error = this.valueBlock.error;
+ return resultOffset;
+ }
+ if (!this.idBlock.error.length)
+ this.blockLength += this.idBlock.blockLength;
+ if (!this.lenBlock.error.length)
+ this.blockLength += this.lenBlock.blockLength;
+ if (!this.valueBlock.error.length)
+ this.blockLength += this.valueBlock.blockLength;
+ return resultOffset;
+ }
+ onAsciiEncoding() {
+ const values = [];
+ for (const value of this.valueBlock.value) {
+ values.push(value.toString("ascii").split("\n").map(o => ` ${o}`).join("\n"));
+ }
+ const blockName = this.idBlock.tagClass === 3
+ ? `[${this.idBlock.tagNumber}]`
+ : this.constructor.NAME;
+ return values.length
+ ? `${blockName} :\n${values.join("\n")}`
+ : `${blockName} :`;
+ }
+}
+_a$v = Constructed;
+(() => {
+ typeStore.Constructed = _a$v;
+})();
+Constructed.NAME = "CONSTRUCTED";
+
+class LocalEndOfContentValueBlock extends ValueBlock {
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ return inputOffset;
+ }
+ toBER(sizeOnly) {
+ return EMPTY_BUFFER;
+ }
+}
+LocalEndOfContentValueBlock.override = "EndOfContentValueBlock";
+
+var _a$u;
+class EndOfContent extends BaseBlock {
+ constructor(parameters = {}) {
+ super(parameters, LocalEndOfContentValueBlock);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 0;
+ }
+}
+_a$u = EndOfContent;
+(() => {
+ typeStore.EndOfContent = _a$u;
+})();
+EndOfContent.NAME = END_OF_CONTENT_NAME;
+
+var _a$t;
+class Null extends BaseBlock {
+ constructor(parameters = {}) {
+ super(parameters, ValueBlock);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 5;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ if (this.lenBlock.length > 0)
+ this.warnings.push("Non-zero length of value block for Null type");
+ if (!this.idBlock.error.length)
+ this.blockLength += this.idBlock.blockLength;
+ if (!this.lenBlock.error.length)
+ this.blockLength += this.lenBlock.blockLength;
+ this.blockLength += inputLength;
+ if ((inputOffset + inputLength) > inputBuffer.byteLength) {
+ this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
+ return -1;
+ }
+ return (inputOffset + inputLength);
+ }
+ toBER(sizeOnly, writer) {
+ const retBuf = new ArrayBuffer(2);
+ if (!sizeOnly) {
+ const retView = new Uint8Array(retBuf);
+ retView[0] = 0x05;
+ retView[1] = 0x00;
+ }
+ if (writer) {
+ writer.write(retBuf);
+ }
+ return retBuf;
+ }
+ onAsciiEncoding() {
+ return `${this.constructor.NAME}`;
+ }
+}
+_a$t = Null;
+(() => {
+ typeStore.Null = _a$t;
+})();
+Null.NAME = "NULL";
+
+class LocalBooleanValueBlock extends HexBlock(ValueBlock) {
+ constructor({ value, ...parameters } = {}) {
+ super(parameters);
+ if (parameters.valueHex) {
+ this.valueHexView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(parameters.valueHex);
+ }
+ else {
+ this.valueHexView = new Uint8Array(1);
+ }
+ if (value) {
+ this.value = value;
+ }
+ }
+ get value() {
+ for (const octet of this.valueHexView) {
+ if (octet > 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+ set value(value) {
+ this.valueHexView[0] = value ? 0xFF : 0x00;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ const inputView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer);
+ if (!index_es_checkBufferParams(this, inputView, inputOffset, inputLength)) {
+ return -1;
+ }
+ this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength);
+ if (inputLength > 1)
+ this.warnings.push("Boolean value encoded in more then 1 octet");
+ this.isHexOnly = true;
+ utilDecodeTC.call(this);
+ this.blockLength = inputLength;
+ return (inputOffset + inputLength);
+ }
+ toBER() {
+ return this.valueHexView.slice();
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ value: this.value,
+ };
+ }
+}
+LocalBooleanValueBlock.NAME = "BooleanValueBlock";
+
+var _a$s;
+class index_es_Boolean extends BaseBlock {
+ constructor(parameters = {}) {
+ super(parameters, LocalBooleanValueBlock);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 1;
+ }
+ getValue() {
+ return this.valueBlock.value;
+ }
+ setValue(value) {
+ this.valueBlock.value = value;
+ }
+ onAsciiEncoding() {
+ return `${this.constructor.NAME} : ${this.getValue}`;
+ }
+}
+_a$s = index_es_Boolean;
+(() => {
+ typeStore.Boolean = _a$s;
+})();
+index_es_Boolean.NAME = "BOOLEAN";
+
+class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) {
+ constructor({ isConstructed = false, ...parameters } = {}) {
+ super(parameters);
+ this.isConstructed = isConstructed;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ let resultOffset = 0;
+ if (this.isConstructed) {
+ this.isHexOnly = false;
+ resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);
+ if (resultOffset === -1)
+ return resultOffset;
+ for (let i = 0; i < this.value.length; i++) {
+ const currentBlockName = this.value[i].constructor.NAME;
+ if (currentBlockName === END_OF_CONTENT_NAME) {
+ if (this.isIndefiniteForm)
+ break;
+ else {
+ this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only";
+ return -1;
+ }
+ }
+ if (currentBlockName !== OCTET_STRING_NAME) {
+ this.error = "OCTET STRING may consists of OCTET STRINGs only";
+ return -1;
+ }
+ }
+ }
+ else {
+ this.isHexOnly = true;
+ resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);
+ this.blockLength = inputLength;
+ }
+ return resultOffset;
+ }
+ toBER(sizeOnly, writer) {
+ if (this.isConstructed)
+ return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);
+ return sizeOnly
+ ? new ArrayBuffer(this.valueHexView.byteLength)
+ : this.valueHexView.slice().buffer;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ isConstructed: this.isConstructed,
+ };
+ }
+}
+LocalOctetStringValueBlock.NAME = "OctetStringValueBlock";
+
+var _a$r;
+class index_es_OctetString extends BaseBlock {
+ constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
+ var _b, _c;
+ (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
+ super({
+ idBlock: {
+ isConstructed: parameters.isConstructed,
+ ...idBlock,
+ },
+ lenBlock: {
+ ...lenBlock,
+ isIndefiniteForm: !!parameters.isIndefiniteForm,
+ },
+ ...parameters,
+ }, LocalOctetStringValueBlock);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 4;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ this.valueBlock.isConstructed = this.idBlock.isConstructed;
+ this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
+ if (inputLength === 0) {
+ if (this.idBlock.error.length === 0)
+ this.blockLength += this.idBlock.blockLength;
+ if (this.lenBlock.error.length === 0)
+ this.blockLength += this.lenBlock.blockLength;
+ return inputOffset;
+ }
+ if (!this.valueBlock.isConstructed) {
+ const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
+ const buf = view.subarray(inputOffset, inputOffset + inputLength);
+ try {
+ if (buf.byteLength) {
+ const asn = localFromBER(buf, 0, buf.byteLength);
+ if (asn.offset !== -1 && asn.offset === inputLength) {
+ this.valueBlock.value = [asn.result];
+ }
+ }
+ }
+ catch (e) {
+ }
+ }
+ return super.fromBER(inputBuffer, inputOffset, inputLength);
+ }
+ onAsciiEncoding() {
+ if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {
+ return Constructed.prototype.onAsciiEncoding.call(this);
+ }
+ return `${this.constructor.NAME} : ${build/* Convert.ToHex */.ep.ToHex(this.valueBlock.valueHexView)}`;
+ }
+ getValue() {
+ if (!this.idBlock.isConstructed) {
+ return this.valueBlock.valueHexView.slice().buffer;
+ }
+ const array = [];
+ for (const content of this.valueBlock.value) {
+ if (content instanceof index_es_OctetString) {
+ array.push(content.valueBlock.valueHexView);
+ }
+ }
+ return build/* BufferSourceConverter.concat */.vJ.concat(array);
+ }
+}
+_a$r = index_es_OctetString;
+(() => {
+ typeStore.OctetString = _a$r;
+})();
+index_es_OctetString.NAME = OCTET_STRING_NAME;
+
+class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) {
+ constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) {
+ super(parameters);
+ this.unusedBits = unusedBits;
+ this.isConstructed = isConstructed;
+ this.blockLength = this.valueHexView.byteLength;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ if (!inputLength) {
+ return inputOffset;
+ }
+ let resultOffset = -1;
+ if (this.isConstructed) {
+ resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);
+ if (resultOffset === -1)
+ return resultOffset;
+ for (const value of this.value) {
+ const currentBlockName = value.constructor.NAME;
+ if (currentBlockName === END_OF_CONTENT_NAME) {
+ if (this.isIndefiniteForm)
+ break;
+ else {
+ this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only";
+ return -1;
+ }
+ }
+ if (currentBlockName !== BIT_STRING_NAME) {
+ this.error = "BIT STRING may consists of BIT STRINGs only";
+ return -1;
+ }
+ const valueBlock = value.valueBlock;
+ if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) {
+ this.error = "Using of \"unused bits\" inside constructive BIT STRING allowed for least one only";
+ return -1;
+ }
+ this.unusedBits = valueBlock.unusedBits;
+ }
+ return resultOffset;
+ }
+ const inputView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer);
+ if (!index_es_checkBufferParams(this, inputView, inputOffset, inputLength)) {
+ return -1;
+ }
+ const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
+ this.unusedBits = intBuffer[0];
+ if (this.unusedBits > 7) {
+ this.error = "Unused bits for BitString must be in range 0-7";
+ return -1;
+ }
+ if (!this.unusedBits) {
+ const buf = intBuffer.subarray(1);
+ try {
+ if (buf.byteLength) {
+ const asn = localFromBER(buf, 0, buf.byteLength);
+ if (asn.offset !== -1 && asn.offset === (inputLength - 1)) {
+ this.value = [asn.result];
+ }
+ }
+ }
+ catch (e) {
+ }
+ }
+ this.valueHexView = intBuffer.subarray(1);
+ this.blockLength = intBuffer.length;
+ return (inputOffset + inputLength);
+ }
+ toBER(sizeOnly, writer) {
+ if (this.isConstructed) {
+ return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);
+ }
+ if (sizeOnly) {
+ return new ArrayBuffer(this.valueHexView.byteLength + 1);
+ }
+ if (!this.valueHexView.byteLength) {
+ return EMPTY_BUFFER;
+ }
+ const retView = new Uint8Array(this.valueHexView.length + 1);
+ retView[0] = this.unusedBits;
+ retView.set(this.valueHexView, 1);
+ return retView.buffer;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ unusedBits: this.unusedBits,
+ isConstructed: this.isConstructed,
+ };
+ }
+}
+LocalBitStringValueBlock.NAME = "BitStringValueBlock";
+
+var _a$q;
+class index_es_BitString extends BaseBlock {
+ constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
+ var _b, _c;
+ (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
+ super({
+ idBlock: {
+ isConstructed: parameters.isConstructed,
+ ...idBlock,
+ },
+ lenBlock: {
+ ...lenBlock,
+ isIndefiniteForm: !!parameters.isIndefiniteForm,
+ },
+ ...parameters,
+ }, LocalBitStringValueBlock);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 3;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ this.valueBlock.isConstructed = this.idBlock.isConstructed;
+ this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
+ return super.fromBER(inputBuffer, inputOffset, inputLength);
+ }
+ onAsciiEncoding() {
+ if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {
+ return Constructed.prototype.onAsciiEncoding.call(this);
+ }
+ else {
+ const bits = [];
+ const valueHex = this.valueBlock.valueHexView;
+ for (const byte of valueHex) {
+ bits.push(byte.toString(2).padStart(8, "0"));
+ }
+ const bitsStr = bits.join("");
+ return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;
+ }
+ }
+}
+_a$q = index_es_BitString;
+(() => {
+ typeStore.BitString = _a$q;
+})();
+index_es_BitString.NAME = BIT_STRING_NAME;
+
+var _a$p;
+function viewAdd(first, second) {
+ const c = new Uint8Array([0]);
+ const firstView = new Uint8Array(first);
+ const secondView = new Uint8Array(second);
+ let firstViewCopy = firstView.slice(0);
+ const firstViewCopyLength = firstViewCopy.length - 1;
+ const secondViewCopy = secondView.slice(0);
+ const secondViewCopyLength = secondViewCopy.length - 1;
+ let value = 0;
+ const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength;
+ let counter = 0;
+ for (let i = max; i >= 0; i--, counter++) {
+ switch (true) {
+ case (counter < secondViewCopy.length):
+ value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0];
+ break;
+ default:
+ value = firstViewCopy[firstViewCopyLength - counter] + c[0];
+ }
+ c[0] = value / 10;
+ switch (true) {
+ case (counter >= firstViewCopy.length):
+ firstViewCopy = utilConcatView(new Uint8Array([value % 10]), firstViewCopy);
+ break;
+ default:
+ firstViewCopy[firstViewCopyLength - counter] = value % 10;
+ }
+ }
+ if (c[0] > 0)
+ firstViewCopy = utilConcatView(c, firstViewCopy);
+ return firstViewCopy;
+}
+function power2(n) {
+ if (n >= powers2.length) {
+ for (let p = powers2.length; p <= n; p++) {
+ const c = new Uint8Array([0]);
+ let digits = (powers2[p - 1]).slice(0);
+ for (let i = (digits.length - 1); i >= 0; i--) {
+ const newValue = new Uint8Array([(digits[i] << 1) + c[0]]);
+ c[0] = newValue[0] / 10;
+ digits[i] = newValue[0] % 10;
+ }
+ if (c[0] > 0)
+ digits = utilConcatView(c, digits);
+ powers2.push(digits);
+ }
+ }
+ return powers2[n];
+}
+function viewSub(first, second) {
+ let b = 0;
+ const firstView = new Uint8Array(first);
+ const secondView = new Uint8Array(second);
+ const firstViewCopy = firstView.slice(0);
+ const firstViewCopyLength = firstViewCopy.length - 1;
+ const secondViewCopy = secondView.slice(0);
+ const secondViewCopyLength = secondViewCopy.length - 1;
+ let value;
+ let counter = 0;
+ for (let i = secondViewCopyLength; i >= 0; i--, counter++) {
+ value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b;
+ switch (true) {
+ case (value < 0):
+ b = 1;
+ firstViewCopy[firstViewCopyLength - counter] = value + 10;
+ break;
+ default:
+ b = 0;
+ firstViewCopy[firstViewCopyLength - counter] = value;
+ }
+ }
+ if (b > 0) {
+ for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) {
+ value = firstViewCopy[firstViewCopyLength - counter] - b;
+ if (value < 0) {
+ b = 1;
+ firstViewCopy[firstViewCopyLength - counter] = value + 10;
+ }
+ else {
+ b = 0;
+ firstViewCopy[firstViewCopyLength - counter] = value;
+ break;
+ }
+ }
+ }
+ return firstViewCopy.slice();
+}
+class LocalIntegerValueBlock extends HexBlock(ValueBlock) {
+ constructor({ value, ...parameters } = {}) {
+ super(parameters);
+ this._valueDec = 0;
+ if (parameters.valueHex) {
+ this.setValueHex();
+ }
+ if (value !== undefined) {
+ this.valueDec = value;
+ }
+ }
+ setValueHex() {
+ if (this.valueHexView.length >= 4) {
+ this.warnings.push("Too big Integer for decoding, hex only");
+ this.isHexOnly = true;
+ this._valueDec = 0;
+ }
+ else {
+ this.isHexOnly = false;
+ if (this.valueHexView.length > 0) {
+ this._valueDec = utilDecodeTC.call(this);
+ }
+ }
+ }
+ set valueDec(v) {
+ this._valueDec = v;
+ this.isHexOnly = false;
+ this.valueHexView = new Uint8Array(utilEncodeTC(v));
+ }
+ get valueDec() {
+ return this._valueDec;
+ }
+ fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) {
+ const offset = this.fromBER(inputBuffer, inputOffset, inputLength);
+ if (offset === -1)
+ return offset;
+ const view = this.valueHexView;
+ if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) {
+ this.valueHexView = view.subarray(1);
+ }
+ else {
+ if (expectedLength !== 0) {
+ if (view.length < expectedLength) {
+ if ((expectedLength - view.length) > 1)
+ expectedLength = view.length + 1;
+ this.valueHexView = view.subarray(expectedLength - view.length);
+ }
+ }
+ }
+ return offset;
+ }
+ toDER(sizeOnly = false) {
+ const view = this.valueHexView;
+ switch (true) {
+ case ((view[0] & 0x80) !== 0):
+ {
+ const updatedView = new Uint8Array(this.valueHexView.length + 1);
+ updatedView[0] = 0x00;
+ updatedView.set(view, 1);
+ this.valueHexView = updatedView;
+ }
+ break;
+ case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)):
+ {
+ this.valueHexView = this.valueHexView.subarray(1);
+ }
+ break;
+ }
+ return this.toBER(sizeOnly);
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);
+ if (resultOffset === -1) {
+ return resultOffset;
+ }
+ this.setValueHex();
+ return resultOffset;
+ }
+ toBER(sizeOnly) {
+ return sizeOnly
+ ? new ArrayBuffer(this.valueHexView.length)
+ : this.valueHexView.slice().buffer;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ valueDec: this.valueDec,
+ };
+ }
+ toString() {
+ const firstBit = (this.valueHexView.length * 8) - 1;
+ let digits = new Uint8Array((this.valueHexView.length * 8) / 3);
+ let bitNumber = 0;
+ let currentByte;
+ const asn1View = this.valueHexView;
+ let result = "";
+ let flag = false;
+ for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) {
+ currentByte = asn1View[byteNumber];
+ for (let i = 0; i < 8; i++) {
+ if ((currentByte & 1) === 1) {
+ switch (bitNumber) {
+ case firstBit:
+ digits = viewSub(power2(bitNumber), digits);
+ result = "-";
+ break;
+ default:
+ digits = viewAdd(digits, power2(bitNumber));
+ }
+ }
+ bitNumber++;
+ currentByte >>= 1;
+ }
+ }
+ for (let i = 0; i < digits.length; i++) {
+ if (digits[i])
+ flag = true;
+ if (flag)
+ result += digitsString.charAt(digits[i]);
+ }
+ if (flag === false)
+ result += digitsString.charAt(0);
+ return result;
+ }
+}
+_a$p = LocalIntegerValueBlock;
+LocalIntegerValueBlock.NAME = "IntegerValueBlock";
+(() => {
+ Object.defineProperty(_a$p.prototype, "valueHex", {
+ set: function (v) {
+ this.valueHexView = new Uint8Array(v);
+ this.setValueHex();
+ },
+ get: function () {
+ return this.valueHexView.slice().buffer;
+ },
+ });
+})();
+
+var _a$o;
+class Integer extends BaseBlock {
+ constructor(parameters = {}) {
+ super(parameters, LocalIntegerValueBlock);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 2;
+ }
+ toBigInt() {
+ assertBigInt();
+ return BigInt(this.valueBlock.toString());
+ }
+ static fromBigInt(value) {
+ assertBigInt();
+ const bigIntValue = BigInt(value);
+ const writer = new ViewWriter();
+ const hex = bigIntValue.toString(16).replace(/^-/, "");
+ const view = new Uint8Array(build/* Convert.FromHex */.ep.FromHex(hex));
+ if (bigIntValue < 0) {
+ const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0));
+ first[0] |= 0x80;
+ const firstInt = BigInt(`0x${build/* Convert.ToHex */.ep.ToHex(first)}`);
+ const secondInt = firstInt + bigIntValue;
+ const second = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(build/* Convert.FromHex */.ep.FromHex(secondInt.toString(16)));
+ second[0] |= 0x80;
+ writer.write(second);
+ }
+ else {
+ if (view[0] & 0x80) {
+ writer.write(new Uint8Array([0]));
+ }
+ writer.write(view);
+ }
+ const res = new Integer({
+ valueHex: writer.final(),
+ });
+ return res;
+ }
+ convertToDER() {
+ const integer = new Integer({ valueHex: this.valueBlock.valueHexView });
+ integer.valueBlock.toDER();
+ return integer;
+ }
+ convertFromDER() {
+ return new Integer({
+ valueHex: this.valueBlock.valueHexView[0] === 0
+ ? this.valueBlock.valueHexView.subarray(1)
+ : this.valueBlock.valueHexView,
+ });
+ }
+ onAsciiEncoding() {
+ return `${this.constructor.NAME} : ${this.valueBlock.toString()}`;
+ }
+}
+_a$o = Integer;
+(() => {
+ typeStore.Integer = _a$o;
+})();
+Integer.NAME = "INTEGER";
+
+var _a$n;
+class Enumerated extends Integer {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 10;
+ }
+}
+_a$n = Enumerated;
+(() => {
+ typeStore.Enumerated = _a$n;
+})();
+Enumerated.NAME = "ENUMERATED";
+
+class LocalSidValueBlock extends HexBlock(ValueBlock) {
+ constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) {
+ super(parameters);
+ this.valueDec = valueDec;
+ this.isFirstSid = isFirstSid;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ if (!inputLength) {
+ return inputOffset;
+ }
+ const inputView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer);
+ if (!index_es_checkBufferParams(this, inputView, inputOffset, inputLength)) {
+ return -1;
+ }
+ const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
+ this.valueHexView = new Uint8Array(inputLength);
+ for (let i = 0; i < inputLength; i++) {
+ this.valueHexView[i] = intBuffer[i] & 0x7F;
+ this.blockLength++;
+ if ((intBuffer[i] & 0x80) === 0x00)
+ break;
+ }
+ const tempView = new Uint8Array(this.blockLength);
+ for (let i = 0; i < this.blockLength; i++) {
+ tempView[i] = this.valueHexView[i];
+ }
+ this.valueHexView = tempView;
+ if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {
+ this.error = "End of input reached before message was fully decoded";
+ return -1;
+ }
+ if (this.valueHexView[0] === 0x00)
+ this.warnings.push("Needlessly long format of SID encoding");
+ if (this.blockLength <= 8)
+ this.valueDec = utilFromBase(this.valueHexView, 7);
+ else {
+ this.isHexOnly = true;
+ this.warnings.push("Too big SID for decoding, hex only");
+ }
+ return (inputOffset + this.blockLength);
+ }
+ set valueBigInt(value) {
+ assertBigInt();
+ let bits = BigInt(value).toString(2);
+ while (bits.length % 7) {
+ bits = "0" + bits;
+ }
+ const bytes = new Uint8Array(bits.length / 7);
+ for (let i = 0; i < bytes.length; i++) {
+ bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0);
+ }
+ this.fromBER(bytes.buffer, 0, bytes.length);
+ }
+ toBER(sizeOnly) {
+ if (this.isHexOnly) {
+ if (sizeOnly)
+ return (new ArrayBuffer(this.valueHexView.byteLength));
+ const curView = this.valueHexView;
+ const retView = new Uint8Array(this.blockLength);
+ for (let i = 0; i < (this.blockLength - 1); i++)
+ retView[i] = curView[i] | 0x80;
+ retView[this.blockLength - 1] = curView[this.blockLength - 1];
+ return retView.buffer;
+ }
+ const encodedBuf = utilToBase(this.valueDec, 7);
+ if (encodedBuf.byteLength === 0) {
+ this.error = "Error during encoding SID value";
+ return EMPTY_BUFFER;
+ }
+ const retView = new Uint8Array(encodedBuf.byteLength);
+ if (!sizeOnly) {
+ const encodedView = new Uint8Array(encodedBuf);
+ const len = encodedBuf.byteLength - 1;
+ for (let i = 0; i < len; i++)
+ retView[i] = encodedView[i] | 0x80;
+ retView[len] = encodedView[len];
+ }
+ return retView;
+ }
+ toString() {
+ let result = "";
+ if (this.isHexOnly)
+ result = build/* Convert.ToHex */.ep.ToHex(this.valueHexView);
+ else {
+ if (this.isFirstSid) {
+ let sidValue = this.valueDec;
+ if (this.valueDec <= 39)
+ result = "0.";
+ else {
+ if (this.valueDec <= 79) {
+ result = "1.";
+ sidValue -= 40;
+ }
+ else {
+ result = "2.";
+ sidValue -= 80;
+ }
+ }
+ result += sidValue.toString();
+ }
+ else
+ result = this.valueDec.toString();
+ }
+ return result;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ valueDec: this.valueDec,
+ isFirstSid: this.isFirstSid,
+ };
+ }
+}
+LocalSidValueBlock.NAME = "sidBlock";
+
+class LocalObjectIdentifierValueBlock extends ValueBlock {
+ constructor({ value = EMPTY_STRING, ...parameters } = {}) {
+ super(parameters);
+ this.value = [];
+ if (value) {
+ this.fromString(value);
+ }
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ let resultOffset = inputOffset;
+ while (inputLength > 0) {
+ const sidBlock = new LocalSidValueBlock();
+ resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);
+ if (resultOffset === -1) {
+ this.blockLength = 0;
+ this.error = sidBlock.error;
+ return resultOffset;
+ }
+ if (this.value.length === 0)
+ sidBlock.isFirstSid = true;
+ this.blockLength += sidBlock.blockLength;
+ inputLength -= sidBlock.blockLength;
+ this.value.push(sidBlock);
+ }
+ return resultOffset;
+ }
+ toBER(sizeOnly) {
+ const retBuffers = [];
+ for (let i = 0; i < this.value.length; i++) {
+ const valueBuf = this.value[i].toBER(sizeOnly);
+ if (valueBuf.byteLength === 0) {
+ this.error = this.value[i].error;
+ return EMPTY_BUFFER;
+ }
+ retBuffers.push(valueBuf);
+ }
+ return concat(retBuffers);
+ }
+ fromString(string) {
+ this.value = [];
+ let pos1 = 0;
+ let pos2 = 0;
+ let sid = "";
+ let flag = false;
+ do {
+ pos2 = string.indexOf(".", pos1);
+ if (pos2 === -1)
+ sid = string.substring(pos1);
+ else
+ sid = string.substring(pos1, pos2);
+ pos1 = pos2 + 1;
+ if (flag) {
+ const sidBlock = this.value[0];
+ let plus = 0;
+ switch (sidBlock.valueDec) {
+ case 0:
+ break;
+ case 1:
+ plus = 40;
+ break;
+ case 2:
+ plus = 80;
+ break;
+ default:
+ this.value = [];
+ return;
+ }
+ const parsedSID = parseInt(sid, 10);
+ if (isNaN(parsedSID))
+ return;
+ sidBlock.valueDec = parsedSID + plus;
+ flag = false;
+ }
+ else {
+ const sidBlock = new LocalSidValueBlock();
+ if (sid > Number.MAX_SAFE_INTEGER) {
+ assertBigInt();
+ const sidValue = BigInt(sid);
+ sidBlock.valueBigInt = sidValue;
+ }
+ else {
+ sidBlock.valueDec = parseInt(sid, 10);
+ if (isNaN(sidBlock.valueDec))
+ return;
+ }
+ if (!this.value.length) {
+ sidBlock.isFirstSid = true;
+ flag = true;
+ }
+ this.value.push(sidBlock);
+ }
+ } while (pos2 !== -1);
+ }
+ toString() {
+ let result = "";
+ let isHexOnly = false;
+ for (let i = 0; i < this.value.length; i++) {
+ isHexOnly = this.value[i].isHexOnly;
+ let sidStr = this.value[i].toString();
+ if (i !== 0)
+ result = `${result}.`;
+ if (isHexOnly) {
+ sidStr = `{${sidStr}}`;
+ if (this.value[i].isFirstSid)
+ result = `2.{${sidStr} - 80}`;
+ else
+ result += sidStr;
+ }
+ else
+ result += sidStr;
+ }
+ return result;
+ }
+ toJSON() {
+ const object = {
+ ...super.toJSON(),
+ value: this.toString(),
+ sidArray: [],
+ };
+ for (let i = 0; i < this.value.length; i++) {
+ object.sidArray.push(this.value[i].toJSON());
+ }
+ return object;
+ }
+}
+LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock";
+
+var _a$m;
+class ObjectIdentifier extends BaseBlock {
+ constructor(parameters = {}) {
+ super(parameters, LocalObjectIdentifierValueBlock);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 6;
+ }
+ getValue() {
+ return this.valueBlock.toString();
+ }
+ setValue(value) {
+ this.valueBlock.fromString(value);
+ }
+ onAsciiEncoding() {
+ return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ value: this.getValue(),
+ };
+ }
+}
+_a$m = ObjectIdentifier;
+(() => {
+ typeStore.ObjectIdentifier = _a$m;
+})();
+ObjectIdentifier.NAME = "OBJECT IDENTIFIER";
+
+class LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) {
+ constructor({ valueDec = 0, ...parameters } = {}) {
+ super(parameters);
+ this.valueDec = valueDec;
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ if (inputLength === 0)
+ return inputOffset;
+ const inputView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer);
+ if (!index_es_checkBufferParams(this, inputView, inputOffset, inputLength))
+ return -1;
+ const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
+ this.valueHexView = new Uint8Array(inputLength);
+ for (let i = 0; i < inputLength; i++) {
+ this.valueHexView[i] = intBuffer[i] & 0x7F;
+ this.blockLength++;
+ if ((intBuffer[i] & 0x80) === 0x00)
+ break;
+ }
+ const tempView = new Uint8Array(this.blockLength);
+ for (let i = 0; i < this.blockLength; i++)
+ tempView[i] = this.valueHexView[i];
+ this.valueHexView = tempView;
+ if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {
+ this.error = "End of input reached before message was fully decoded";
+ return -1;
+ }
+ if (this.valueHexView[0] === 0x00)
+ this.warnings.push("Needlessly long format of SID encoding");
+ if (this.blockLength <= 8)
+ this.valueDec = utilFromBase(this.valueHexView, 7);
+ else {
+ this.isHexOnly = true;
+ this.warnings.push("Too big SID for decoding, hex only");
+ }
+ return (inputOffset + this.blockLength);
+ }
+ toBER(sizeOnly) {
+ if (this.isHexOnly) {
+ if (sizeOnly)
+ return (new ArrayBuffer(this.valueHexView.byteLength));
+ const curView = this.valueHexView;
+ const retView = new Uint8Array(this.blockLength);
+ for (let i = 0; i < (this.blockLength - 1); i++)
+ retView[i] = curView[i] | 0x80;
+ retView[this.blockLength - 1] = curView[this.blockLength - 1];
+ return retView.buffer;
+ }
+ const encodedBuf = utilToBase(this.valueDec, 7);
+ if (encodedBuf.byteLength === 0) {
+ this.error = "Error during encoding SID value";
+ return EMPTY_BUFFER;
+ }
+ const retView = new Uint8Array(encodedBuf.byteLength);
+ if (!sizeOnly) {
+ const encodedView = new Uint8Array(encodedBuf);
+ const len = encodedBuf.byteLength - 1;
+ for (let i = 0; i < len; i++)
+ retView[i] = encodedView[i] | 0x80;
+ retView[len] = encodedView[len];
+ }
+ return retView.buffer;
+ }
+ toString() {
+ let result = "";
+ if (this.isHexOnly)
+ result = build/* Convert.ToHex */.ep.ToHex(this.valueHexView);
+ else {
+ result = this.valueDec.toString();
+ }
+ return result;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ valueDec: this.valueDec,
+ };
+ }
+}
+LocalRelativeSidValueBlock.NAME = "relativeSidBlock";
+
+class LocalRelativeObjectIdentifierValueBlock extends ValueBlock {
+ constructor({ value = EMPTY_STRING, ...parameters } = {}) {
+ super(parameters);
+ this.value = [];
+ if (value) {
+ this.fromString(value);
+ }
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ let resultOffset = inputOffset;
+ while (inputLength > 0) {
+ const sidBlock = new LocalRelativeSidValueBlock();
+ resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);
+ if (resultOffset === -1) {
+ this.blockLength = 0;
+ this.error = sidBlock.error;
+ return resultOffset;
+ }
+ this.blockLength += sidBlock.blockLength;
+ inputLength -= sidBlock.blockLength;
+ this.value.push(sidBlock);
+ }
+ return resultOffset;
+ }
+ toBER(sizeOnly, writer) {
+ const retBuffers = [];
+ for (let i = 0; i < this.value.length; i++) {
+ const valueBuf = this.value[i].toBER(sizeOnly);
+ if (valueBuf.byteLength === 0) {
+ this.error = this.value[i].error;
+ return EMPTY_BUFFER;
+ }
+ retBuffers.push(valueBuf);
+ }
+ return concat(retBuffers);
+ }
+ fromString(string) {
+ this.value = [];
+ let pos1 = 0;
+ let pos2 = 0;
+ let sid = "";
+ do {
+ pos2 = string.indexOf(".", pos1);
+ if (pos2 === -1)
+ sid = string.substring(pos1);
+ else
+ sid = string.substring(pos1, pos2);
+ pos1 = pos2 + 1;
+ const sidBlock = new LocalRelativeSidValueBlock();
+ sidBlock.valueDec = parseInt(sid, 10);
+ if (isNaN(sidBlock.valueDec))
+ return true;
+ this.value.push(sidBlock);
+ } while (pos2 !== -1);
+ return true;
+ }
+ toString() {
+ let result = "";
+ let isHexOnly = false;
+ for (let i = 0; i < this.value.length; i++) {
+ isHexOnly = this.value[i].isHexOnly;
+ let sidStr = this.value[i].toString();
+ if (i !== 0)
+ result = `${result}.`;
+ if (isHexOnly) {
+ sidStr = `{${sidStr}}`;
+ result += sidStr;
+ }
+ else
+ result += sidStr;
+ }
+ return result;
+ }
+ toJSON() {
+ const object = {
+ ...super.toJSON(),
+ value: this.toString(),
+ sidArray: [],
+ };
+ for (let i = 0; i < this.value.length; i++)
+ object.sidArray.push(this.value[i].toJSON());
+ return object;
+ }
+}
+LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock";
+
+var _a$l;
+class RelativeObjectIdentifier extends BaseBlock {
+ constructor(parameters = {}) {
+ super(parameters, LocalRelativeObjectIdentifierValueBlock);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 13;
+ }
+ getValue() {
+ return this.valueBlock.toString();
+ }
+ setValue(value) {
+ this.valueBlock.fromString(value);
+ }
+ onAsciiEncoding() {
+ return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ value: this.getValue(),
+ };
+ }
+}
+_a$l = RelativeObjectIdentifier;
+(() => {
+ typeStore.RelativeObjectIdentifier = _a$l;
+})();
+RelativeObjectIdentifier.NAME = "RelativeObjectIdentifier";
+
+var _a$k;
+class Sequence extends Constructed {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 16;
+ }
+}
+_a$k = Sequence;
+(() => {
+ typeStore.Sequence = _a$k;
+})();
+Sequence.NAME = "SEQUENCE";
+
+var _a$j;
+class index_es_Set extends Constructed {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 17;
+ }
+}
+_a$j = index_es_Set;
+(() => {
+ typeStore.Set = _a$j;
+})();
+index_es_Set.NAME = "SET";
+
+class LocalStringValueBlock extends HexBlock(ValueBlock) {
+ constructor({ ...parameters } = {}) {
+ super(parameters);
+ this.isHexOnly = true;
+ this.value = EMPTY_STRING;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ value: this.value,
+ };
+ }
+}
+LocalStringValueBlock.NAME = "StringValueBlock";
+
+class LocalSimpleStringValueBlock extends LocalStringValueBlock {
+}
+LocalSimpleStringValueBlock.NAME = "SimpleStringValueBlock";
+
+class LocalSimpleStringBlock extends BaseStringBlock {
+ constructor({ ...parameters } = {}) {
+ super(parameters, LocalSimpleStringValueBlock);
+ }
+ fromBuffer(inputBuffer) {
+ this.valueBlock.value = String.fromCharCode.apply(null, build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer));
+ }
+ fromString(inputString) {
+ const strLen = inputString.length;
+ const view = this.valueBlock.valueHexView = new Uint8Array(strLen);
+ for (let i = 0; i < strLen; i++)
+ view[i] = inputString.charCodeAt(i);
+ this.valueBlock.value = inputString;
+ }
+}
+LocalSimpleStringBlock.NAME = "SIMPLE STRING";
+
+class LocalUtf8StringValueBlock extends LocalSimpleStringBlock {
+ fromBuffer(inputBuffer) {
+ this.valueBlock.valueHexView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer);
+ try {
+ this.valueBlock.value = build/* Convert.ToUtf8String */.ep.ToUtf8String(inputBuffer);
+ }
+ catch (ex) {
+ this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`);
+ this.valueBlock.value = build/* Convert.ToBinary */.ep.ToBinary(inputBuffer);
+ }
+ }
+ fromString(inputString) {
+ this.valueBlock.valueHexView = new Uint8Array(build/* Convert.FromUtf8String */.ep.FromUtf8String(inputString));
+ this.valueBlock.value = inputString;
+ }
+}
+LocalUtf8StringValueBlock.NAME = "Utf8StringValueBlock";
+
+var _a$i;
+class Utf8String extends LocalUtf8StringValueBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 12;
+ }
+}
+_a$i = Utf8String;
+(() => {
+ typeStore.Utf8String = _a$i;
+})();
+Utf8String.NAME = "UTF8String";
+
+class LocalBmpStringValueBlock extends LocalSimpleStringBlock {
+ fromBuffer(inputBuffer) {
+ this.valueBlock.value = build/* Convert.ToUtf16String */.ep.ToUtf16String(inputBuffer);
+ this.valueBlock.valueHexView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer);
+ }
+ fromString(inputString) {
+ this.valueBlock.value = inputString;
+ this.valueBlock.valueHexView = new Uint8Array(build/* Convert.FromUtf16String */.ep.FromUtf16String(inputString));
+ }
+}
+LocalBmpStringValueBlock.NAME = "BmpStringValueBlock";
+
+var _a$h;
+class BmpString extends LocalBmpStringValueBlock {
+ constructor({ ...parameters } = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 30;
+ }
+}
+_a$h = BmpString;
+(() => {
+ typeStore.BmpString = _a$h;
+})();
+BmpString.NAME = "BMPString";
+
+class LocalUniversalStringValueBlock extends LocalSimpleStringBlock {
+ fromBuffer(inputBuffer) {
+ const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0);
+ const valueView = new Uint8Array(copyBuffer);
+ for (let i = 0; i < valueView.length; i += 4) {
+ valueView[i] = valueView[i + 3];
+ valueView[i + 1] = valueView[i + 2];
+ valueView[i + 2] = 0x00;
+ valueView[i + 3] = 0x00;
+ }
+ this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer));
+ }
+ fromString(inputString) {
+ const strLength = inputString.length;
+ const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4);
+ for (let i = 0; i < strLength; i++) {
+ const codeBuf = utilToBase(inputString.charCodeAt(i), 8);
+ const codeView = new Uint8Array(codeBuf);
+ if (codeView.length > 4)
+ continue;
+ const dif = 4 - codeView.length;
+ for (let j = (codeView.length - 1); j >= 0; j--)
+ valueHexView[i * 4 + j + dif] = codeView[j];
+ }
+ this.valueBlock.value = inputString;
+ }
+}
+LocalUniversalStringValueBlock.NAME = "UniversalStringValueBlock";
+
+var _a$g;
+class UniversalString extends LocalUniversalStringValueBlock {
+ constructor({ ...parameters } = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 28;
+ }
+}
+_a$g = UniversalString;
+(() => {
+ typeStore.UniversalString = _a$g;
+})();
+UniversalString.NAME = "UniversalString";
+
+var _a$f;
+class NumericString extends LocalSimpleStringBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 18;
+ }
+}
+_a$f = NumericString;
+(() => {
+ typeStore.NumericString = _a$f;
+})();
+NumericString.NAME = "NumericString";
+
+var _a$e;
+class PrintableString extends LocalSimpleStringBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 19;
+ }
+}
+_a$e = PrintableString;
+(() => {
+ typeStore.PrintableString = _a$e;
+})();
+PrintableString.NAME = "PrintableString";
+
+var _a$d;
+class TeletexString extends LocalSimpleStringBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 20;
+ }
+}
+_a$d = TeletexString;
+(() => {
+ typeStore.TeletexString = _a$d;
+})();
+TeletexString.NAME = "TeletexString";
+
+var _a$c;
+class VideotexString extends LocalSimpleStringBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 21;
+ }
+}
+_a$c = VideotexString;
+(() => {
+ typeStore.VideotexString = _a$c;
+})();
+VideotexString.NAME = "VideotexString";
+
+var _a$b;
+class IA5String extends LocalSimpleStringBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 22;
+ }
+}
+_a$b = IA5String;
+(() => {
+ typeStore.IA5String = _a$b;
+})();
+IA5String.NAME = "IA5String";
+
+var _a$a;
+class GraphicString extends LocalSimpleStringBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 25;
+ }
+}
+_a$a = GraphicString;
+(() => {
+ typeStore.GraphicString = _a$a;
+})();
+GraphicString.NAME = "GraphicString";
+
+var _a$9;
+class VisibleString extends LocalSimpleStringBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 26;
+ }
+}
+_a$9 = VisibleString;
+(() => {
+ typeStore.VisibleString = _a$9;
+})();
+VisibleString.NAME = "VisibleString";
+
+var _a$8;
+class GeneralString extends LocalSimpleStringBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 27;
+ }
+}
+_a$8 = GeneralString;
+(() => {
+ typeStore.GeneralString = _a$8;
+})();
+GeneralString.NAME = "GeneralString";
+
+var _a$7;
+class CharacterString extends LocalSimpleStringBlock {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 29;
+ }
+}
+_a$7 = CharacterString;
+(() => {
+ typeStore.CharacterString = _a$7;
+})();
+CharacterString.NAME = "CharacterString";
+
+var _a$6;
+class UTCTime extends VisibleString {
+ constructor({ value, valueDate, ...parameters } = {}) {
+ super(parameters);
+ this.year = 0;
+ this.month = 0;
+ this.day = 0;
+ this.hour = 0;
+ this.minute = 0;
+ this.second = 0;
+ if (value) {
+ this.fromString(value);
+ this.valueBlock.valueHexView = new Uint8Array(value.length);
+ for (let i = 0; i < value.length; i++)
+ this.valueBlock.valueHexView[i] = value.charCodeAt(i);
+ }
+ if (valueDate) {
+ this.fromDate(valueDate);
+ this.valueBlock.valueHexView = new Uint8Array(this.toBuffer());
+ }
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 23;
+ }
+ fromBuffer(inputBuffer) {
+ this.fromString(String.fromCharCode.apply(null, build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer)));
+ }
+ toBuffer() {
+ const str = this.toString();
+ const buffer = new ArrayBuffer(str.length);
+ const view = new Uint8Array(buffer);
+ for (let i = 0; i < str.length; i++)
+ view[i] = str.charCodeAt(i);
+ return buffer;
+ }
+ fromDate(inputDate) {
+ this.year = inputDate.getUTCFullYear();
+ this.month = inputDate.getUTCMonth() + 1;
+ this.day = inputDate.getUTCDate();
+ this.hour = inputDate.getUTCHours();
+ this.minute = inputDate.getUTCMinutes();
+ this.second = inputDate.getUTCSeconds();
+ }
+ toDate() {
+ return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second)));
+ }
+ fromString(inputString) {
+ const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig;
+ const parserArray = parser.exec(inputString);
+ if (parserArray === null) {
+ this.error = "Wrong input string for conversion";
+ return;
+ }
+ const year = parseInt(parserArray[1], 10);
+ if (year >= 50)
+ this.year = 1900 + year;
+ else
+ this.year = 2000 + year;
+ this.month = parseInt(parserArray[2], 10);
+ this.day = parseInt(parserArray[3], 10);
+ this.hour = parseInt(parserArray[4], 10);
+ this.minute = parseInt(parserArray[5], 10);
+ this.second = parseInt(parserArray[6], 10);
+ }
+ toString(encoding = "iso") {
+ if (encoding === "iso") {
+ const outputArray = new Array(7);
+ outputArray[0] = padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2);
+ outputArray[1] = padNumber(this.month, 2);
+ outputArray[2] = padNumber(this.day, 2);
+ outputArray[3] = padNumber(this.hour, 2);
+ outputArray[4] = padNumber(this.minute, 2);
+ outputArray[5] = padNumber(this.second, 2);
+ outputArray[6] = "Z";
+ return outputArray.join("");
+ }
+ return super.toString(encoding);
+ }
+ onAsciiEncoding() {
+ return `${this.constructor.NAME} : ${this.toDate().toISOString()}`;
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ year: this.year,
+ month: this.month,
+ day: this.day,
+ hour: this.hour,
+ minute: this.minute,
+ second: this.second,
+ };
+ }
+}
+_a$6 = UTCTime;
+(() => {
+ typeStore.UTCTime = _a$6;
+})();
+UTCTime.NAME = "UTCTime";
+
+var _a$5;
+class GeneralizedTime extends UTCTime {
+ constructor(parameters = {}) {
+ var _b;
+ super(parameters);
+ (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 24;
+ }
+ fromDate(inputDate) {
+ super.fromDate(inputDate);
+ this.millisecond = inputDate.getUTCMilliseconds();
+ }
+ toDate() {
+ return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)));
+ }
+ fromString(inputString) {
+ let isUTC = false;
+ let timeString = "";
+ let dateTimeString = "";
+ let fractionPart = 0;
+ let parser;
+ let hourDifference = 0;
+ let minuteDifference = 0;
+ if (inputString[inputString.length - 1] === "Z") {
+ timeString = inputString.substring(0, inputString.length - 1);
+ isUTC = true;
+ }
+ else {
+ const number = new Number(inputString[inputString.length - 1]);
+ if (isNaN(number.valueOf()))
+ throw new Error("Wrong input string for conversion");
+ timeString = inputString;
+ }
+ if (isUTC) {
+ if (timeString.indexOf("+") !== -1)
+ throw new Error("Wrong input string for conversion");
+ if (timeString.indexOf("-") !== -1)
+ throw new Error("Wrong input string for conversion");
+ }
+ else {
+ let multiplier = 1;
+ let differencePosition = timeString.indexOf("+");
+ let differenceString = "";
+ if (differencePosition === -1) {
+ differencePosition = timeString.indexOf("-");
+ multiplier = -1;
+ }
+ if (differencePosition !== -1) {
+ differenceString = timeString.substring(differencePosition + 1);
+ timeString = timeString.substring(0, differencePosition);
+ if ((differenceString.length !== 2) && (differenceString.length !== 4))
+ throw new Error("Wrong input string for conversion");
+ let number = parseInt(differenceString.substring(0, 2), 10);
+ if (isNaN(number.valueOf()))
+ throw new Error("Wrong input string for conversion");
+ hourDifference = multiplier * number;
+ if (differenceString.length === 4) {
+ number = parseInt(differenceString.substring(2, 4), 10);
+ if (isNaN(number.valueOf()))
+ throw new Error("Wrong input string for conversion");
+ minuteDifference = multiplier * number;
+ }
+ }
+ }
+ let fractionPointPosition = timeString.indexOf(".");
+ if (fractionPointPosition === -1)
+ fractionPointPosition = timeString.indexOf(",");
+ if (fractionPointPosition !== -1) {
+ const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`);
+ if (isNaN(fractionPartCheck.valueOf()))
+ throw new Error("Wrong input string for conversion");
+ fractionPart = fractionPartCheck.valueOf();
+ dateTimeString = timeString.substring(0, fractionPointPosition);
+ }
+ else
+ dateTimeString = timeString;
+ switch (true) {
+ case (dateTimeString.length === 8):
+ parser = /(\d{4})(\d{2})(\d{2})/ig;
+ if (fractionPointPosition !== -1)
+ throw new Error("Wrong input string for conversion");
+ break;
+ case (dateTimeString.length === 10):
+ parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig;
+ if (fractionPointPosition !== -1) {
+ let fractionResult = 60 * fractionPart;
+ this.minute = Math.floor(fractionResult);
+ fractionResult = 60 * (fractionResult - this.minute);
+ this.second = Math.floor(fractionResult);
+ fractionResult = 1000 * (fractionResult - this.second);
+ this.millisecond = Math.floor(fractionResult);
+ }
+ break;
+ case (dateTimeString.length === 12):
+ parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig;
+ if (fractionPointPosition !== -1) {
+ let fractionResult = 60 * fractionPart;
+ this.second = Math.floor(fractionResult);
+ fractionResult = 1000 * (fractionResult - this.second);
+ this.millisecond = Math.floor(fractionResult);
+ }
+ break;
+ case (dateTimeString.length === 14):
+ parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig;
+ if (fractionPointPosition !== -1) {
+ const fractionResult = 1000 * fractionPart;
+ this.millisecond = Math.floor(fractionResult);
+ }
+ break;
+ default:
+ throw new Error("Wrong input string for conversion");
+ }
+ const parserArray = parser.exec(dateTimeString);
+ if (parserArray === null)
+ throw new Error("Wrong input string for conversion");
+ for (let j = 1; j < parserArray.length; j++) {
+ switch (j) {
+ case 1:
+ this.year = parseInt(parserArray[j], 10);
+ break;
+ case 2:
+ this.month = parseInt(parserArray[j], 10);
+ break;
+ case 3:
+ this.day = parseInt(parserArray[j], 10);
+ break;
+ case 4:
+ this.hour = parseInt(parserArray[j], 10) + hourDifference;
+ break;
+ case 5:
+ this.minute = parseInt(parserArray[j], 10) + minuteDifference;
+ break;
+ case 6:
+ this.second = parseInt(parserArray[j], 10);
+ break;
+ default:
+ throw new Error("Wrong input string for conversion");
+ }
+ }
+ if (isUTC === false) {
+ const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);
+ this.year = tempDate.getUTCFullYear();
+ this.month = tempDate.getUTCMonth();
+ this.day = tempDate.getUTCDay();
+ this.hour = tempDate.getUTCHours();
+ this.minute = tempDate.getUTCMinutes();
+ this.second = tempDate.getUTCSeconds();
+ this.millisecond = tempDate.getUTCMilliseconds();
+ }
+ }
+ toString(encoding = "iso") {
+ if (encoding === "iso") {
+ const outputArray = [];
+ outputArray.push(padNumber(this.year, 4));
+ outputArray.push(padNumber(this.month, 2));
+ outputArray.push(padNumber(this.day, 2));
+ outputArray.push(padNumber(this.hour, 2));
+ outputArray.push(padNumber(this.minute, 2));
+ outputArray.push(padNumber(this.second, 2));
+ if (this.millisecond !== 0) {
+ outputArray.push(".");
+ outputArray.push(padNumber(this.millisecond, 3));
+ }
+ outputArray.push("Z");
+ return outputArray.join("");
+ }
+ return super.toString(encoding);
+ }
+ toJSON() {
+ return {
+ ...super.toJSON(),
+ millisecond: this.millisecond,
+ };
+ }
+}
+_a$5 = GeneralizedTime;
+(() => {
+ typeStore.GeneralizedTime = _a$5;
+})();
+GeneralizedTime.NAME = "GeneralizedTime";
+
+var _a$4;
+class DATE extends Utf8String {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 31;
+ }
+}
+_a$4 = DATE;
+(() => {
+ typeStore.DATE = _a$4;
+})();
+DATE.NAME = "DATE";
+
+var _a$3;
+class TimeOfDay extends Utf8String {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 32;
+ }
+}
+_a$3 = TimeOfDay;
+(() => {
+ typeStore.TimeOfDay = _a$3;
+})();
+TimeOfDay.NAME = "TimeOfDay";
+
+var _a$2;
+class DateTime extends Utf8String {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 33;
+ }
+}
+_a$2 = DateTime;
+(() => {
+ typeStore.DateTime = _a$2;
+})();
+DateTime.NAME = "DateTime";
+
+var _a$1;
+class Duration extends Utf8String {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 34;
+ }
+}
+_a$1 = Duration;
+(() => {
+ typeStore.Duration = _a$1;
+})();
+Duration.NAME = "Duration";
+
+var index_es_a;
+class TIME extends Utf8String {
+ constructor(parameters = {}) {
+ super(parameters);
+ this.idBlock.tagClass = 1;
+ this.idBlock.tagNumber = 14;
+ }
+}
+index_es_a = TIME;
+(() => {
+ typeStore.TIME = index_es_a;
+})();
+TIME.NAME = "TIME";
+
+class Any {
+ constructor({ name = EMPTY_STRING, optional = false, } = {}) {
+ this.name = name;
+ this.optional = optional;
+ }
+}
+
+class Choice extends Any {
+ constructor({ value = [], ...parameters } = {}) {
+ super(parameters);
+ this.value = value;
+ }
+}
+
+class Repeated extends Any {
+ constructor({ value = new Any(), local = false, ...parameters } = {}) {
+ super(parameters);
+ this.value = value;
+ this.local = local;
+ }
+}
+
+class RawData {
+ constructor({ data = EMPTY_VIEW } = {}) {
+ this.dataView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(data);
+ }
+ get data() {
+ return this.dataView.slice().buffer;
+ }
+ set data(value) {
+ this.dataView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(value);
+ }
+ fromBER(inputBuffer, inputOffset, inputLength) {
+ const endLength = inputOffset + inputLength;
+ this.dataView = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer).subarray(inputOffset, endLength);
+ return endLength;
+ }
+ toBER(sizeOnly) {
+ return this.dataView.slice().buffer;
+ }
+}
+
+function compareSchema(root, inputData, inputSchema) {
+ if (inputSchema instanceof Choice) {
+ for (let j = 0; j < inputSchema.value.length; j++) {
+ const result = compareSchema(root, inputData, inputSchema.value[j]);
+ if (result.verified) {
+ return {
+ verified: true,
+ result: root
+ };
+ }
+ }
+ {
+ const _result = {
+ verified: false,
+ result: {
+ error: "Wrong values for Choice type"
+ },
+ };
+ if (inputSchema.hasOwnProperty(NAME))
+ _result.name = inputSchema.name;
+ return _result;
+ }
+ }
+ if (inputSchema instanceof Any) {
+ if (inputSchema.hasOwnProperty(NAME))
+ root[inputSchema.name] = inputData;
+ return {
+ verified: true,
+ result: root
+ };
+ }
+ if ((root instanceof Object) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong root object" }
+ };
+ }
+ if ((inputData instanceof Object) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 data" }
+ };
+ }
+ if ((inputSchema instanceof Object) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema" }
+ };
+ }
+ if ((ID_BLOCK in inputSchema) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema" }
+ };
+ }
+ if ((FROM_BER in inputSchema.idBlock) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema" }
+ };
+ }
+ if ((TO_BER in inputSchema.idBlock) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema" }
+ };
+ }
+ const encodedId = inputSchema.idBlock.toBER(false);
+ if (encodedId.byteLength === 0) {
+ return {
+ verified: false,
+ result: { error: "Error encoding idBlock for ASN.1 schema" }
+ };
+ }
+ const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength);
+ if (decodedOffset === -1) {
+ return {
+ verified: false,
+ result: { error: "Error decoding idBlock for ASN.1 schema" }
+ };
+ }
+ if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema" }
+ };
+ }
+ if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) {
+ return {
+ verified: false,
+ result: root
+ };
+ }
+ if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema" }
+ };
+ }
+ if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) {
+ return {
+ verified: false,
+ result: root
+ };
+ }
+ if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema" }
+ };
+ }
+ if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) {
+ return {
+ verified: false,
+ result: root
+ };
+ }
+ if (!(IS_HEX_ONLY in inputSchema.idBlock)) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema" }
+ };
+ }
+ if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) {
+ return {
+ verified: false,
+ result: root
+ };
+ }
+ if (inputSchema.idBlock.isHexOnly) {
+ if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema" }
+ };
+ }
+ const schemaView = inputSchema.idBlock.valueHexView;
+ const asn1View = inputData.idBlock.valueHexView;
+ if (schemaView.length !== asn1View.length) {
+ return {
+ verified: false,
+ result: root
+ };
+ }
+ for (let i = 0; i < schemaView.length; i++) {
+ if (schemaView[i] !== asn1View[1]) {
+ return {
+ verified: false,
+ result: root
+ };
+ }
+ }
+ }
+ if (inputSchema.name) {
+ inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
+ if (inputSchema.name)
+ root[inputSchema.name] = inputData;
+ }
+ if (inputSchema instanceof typeStore.Constructed) {
+ let admission = 0;
+ let result = {
+ verified: false,
+ result: {
+ error: "Unknown error",
+ }
+ };
+ let maxLength = inputSchema.valueBlock.value.length;
+ if (maxLength > 0) {
+ if (inputSchema.valueBlock.value[0] instanceof Repeated) {
+ maxLength = inputData.valueBlock.value.length;
+ }
+ }
+ if (maxLength === 0) {
+ return {
+ verified: true,
+ result: root
+ };
+ }
+ if ((inputData.valueBlock.value.length === 0) &&
+ (inputSchema.valueBlock.value.length !== 0)) {
+ let _optional = true;
+ for (let i = 0; i < inputSchema.valueBlock.value.length; i++)
+ _optional = _optional && (inputSchema.valueBlock.value[i].optional || false);
+ if (_optional) {
+ return {
+ verified: true,
+ result: root
+ };
+ }
+ if (inputSchema.name) {
+ inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
+ if (inputSchema.name)
+ delete root[inputSchema.name];
+ }
+ root.error = "Inconsistent object length";
+ return {
+ verified: false,
+ result: root
+ };
+ }
+ for (let i = 0; i < maxLength; i++) {
+ if ((i - admission) >= inputData.valueBlock.value.length) {
+ if (inputSchema.valueBlock.value[i].optional === false) {
+ const _result = {
+ verified: false,
+ result: root
+ };
+ root.error = "Inconsistent length between ASN.1 data and schema";
+ if (inputSchema.name) {
+ inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
+ if (inputSchema.name) {
+ delete root[inputSchema.name];
+ _result.name = inputSchema.name;
+ }
+ }
+ return _result;
+ }
+ }
+ else {
+ if (inputSchema.valueBlock.value[0] instanceof Repeated) {
+ result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value);
+ if (result.verified === false) {
+ if (inputSchema.valueBlock.value[0].optional)
+ admission++;
+ else {
+ if (inputSchema.name) {
+ inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
+ if (inputSchema.name)
+ delete root[inputSchema.name];
+ }
+ return result;
+ }
+ }
+ if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) {
+ let arrayRoot = {};
+ if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local))
+ arrayRoot = inputData;
+ else
+ arrayRoot = root;
+ if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined")
+ arrayRoot[inputSchema.valueBlock.value[0].name] = [];
+ arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]);
+ }
+ }
+ else {
+ result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]);
+ if (result.verified === false) {
+ if (inputSchema.valueBlock.value[i].optional)
+ admission++;
+ else {
+ if (inputSchema.name) {
+ inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
+ if (inputSchema.name)
+ delete root[inputSchema.name];
+ }
+ return result;
+ }
+ }
+ }
+ }
+ }
+ if (result.verified === false) {
+ const _result = {
+ verified: false,
+ result: root
+ };
+ if (inputSchema.name) {
+ inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
+ if (inputSchema.name) {
+ delete root[inputSchema.name];
+ _result.name = inputSchema.name;
+ }
+ }
+ return _result;
+ }
+ return {
+ verified: true,
+ result: root
+ };
+ }
+ if (inputSchema.primitiveSchema &&
+ (VALUE_HEX_VIEW in inputData.valueBlock)) {
+ const asn1 = localFromBER(inputData.valueBlock.valueHexView);
+ if (asn1.offset === -1) {
+ const _result = {
+ verified: false,
+ result: asn1.result
+ };
+ if (inputSchema.name) {
+ inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
+ if (inputSchema.name) {
+ delete root[inputSchema.name];
+ _result.name = inputSchema.name;
+ }
+ }
+ return _result;
+ }
+ return compareSchema(root, asn1.result, inputSchema.primitiveSchema);
+ }
+ return {
+ verified: true,
+ result: root
+ };
+}
+function verifySchema(inputBuffer, inputSchema) {
+ if ((inputSchema instanceof Object) === false) {
+ return {
+ verified: false,
+ result: { error: "Wrong ASN.1 schema type" }
+ };
+ }
+ const asn1 = localFromBER(build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(inputBuffer));
+ if (asn1.offset === -1) {
+ return {
+ verified: false,
+ result: asn1.result
+ };
+ }
+ return compareSchema(asn1.result, asn1.result, inputSchema);
+}
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/enums.js
+var enums_AsnTypeTypes;
+(function (AsnTypeTypes) {
+ AsnTypeTypes[AsnTypeTypes["Sequence"] = 0] = "Sequence";
+ AsnTypeTypes[AsnTypeTypes["Set"] = 1] = "Set";
+ AsnTypeTypes[AsnTypeTypes["Choice"] = 2] = "Choice";
+})(enums_AsnTypeTypes || (enums_AsnTypeTypes = {}));
+var AsnPropTypes;
+(function (AsnPropTypes) {
+ AsnPropTypes[AsnPropTypes["Any"] = 1] = "Any";
+ AsnPropTypes[AsnPropTypes["Boolean"] = 2] = "Boolean";
+ AsnPropTypes[AsnPropTypes["OctetString"] = 3] = "OctetString";
+ AsnPropTypes[AsnPropTypes["BitString"] = 4] = "BitString";
+ AsnPropTypes[AsnPropTypes["Integer"] = 5] = "Integer";
+ AsnPropTypes[AsnPropTypes["Enumerated"] = 6] = "Enumerated";
+ AsnPropTypes[AsnPropTypes["ObjectIdentifier"] = 7] = "ObjectIdentifier";
+ AsnPropTypes[AsnPropTypes["Utf8String"] = 8] = "Utf8String";
+ AsnPropTypes[AsnPropTypes["BmpString"] = 9] = "BmpString";
+ AsnPropTypes[AsnPropTypes["UniversalString"] = 10] = "UniversalString";
+ AsnPropTypes[AsnPropTypes["NumericString"] = 11] = "NumericString";
+ AsnPropTypes[AsnPropTypes["PrintableString"] = 12] = "PrintableString";
+ AsnPropTypes[AsnPropTypes["TeletexString"] = 13] = "TeletexString";
+ AsnPropTypes[AsnPropTypes["VideotexString"] = 14] = "VideotexString";
+ AsnPropTypes[AsnPropTypes["IA5String"] = 15] = "IA5String";
+ AsnPropTypes[AsnPropTypes["GraphicString"] = 16] = "GraphicString";
+ AsnPropTypes[AsnPropTypes["VisibleString"] = 17] = "VisibleString";
+ AsnPropTypes[AsnPropTypes["GeneralString"] = 18] = "GeneralString";
+ AsnPropTypes[AsnPropTypes["CharacterString"] = 19] = "CharacterString";
+ AsnPropTypes[AsnPropTypes["UTCTime"] = 20] = "UTCTime";
+ AsnPropTypes[AsnPropTypes["GeneralizedTime"] = 21] = "GeneralizedTime";
+ AsnPropTypes[AsnPropTypes["DATE"] = 22] = "DATE";
+ AsnPropTypes[AsnPropTypes["TimeOfDay"] = 23] = "TimeOfDay";
+ AsnPropTypes[AsnPropTypes["DateTime"] = 24] = "DateTime";
+ AsnPropTypes[AsnPropTypes["Duration"] = 25] = "Duration";
+ AsnPropTypes[AsnPropTypes["TIME"] = 26] = "TIME";
+ AsnPropTypes[AsnPropTypes["Null"] = 27] = "Null";
+})(AsnPropTypes || (AsnPropTypes = {}));
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/types/bit_string.js
+
+
+class BitString {
+ constructor(params, unusedBits = 0) {
+ this.unusedBits = 0;
+ this.value = new ArrayBuffer(0);
+ if (params) {
+ if (typeof params === "number") {
+ this.fromNumber(params);
+ }
+ else if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(params)) {
+ this.unusedBits = unusedBits;
+ this.value = build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(params);
+ }
+ else {
+ throw TypeError("Unsupported type of 'params' argument for BitString");
+ }
+ }
+ }
+ fromASN(asn) {
+ if (!(asn instanceof index_es_BitString)) {
+ throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");
+ }
+ this.unusedBits = asn.valueBlock.unusedBits;
+ this.value = asn.valueBlock.valueHex;
+ return this;
+ }
+ toASN() {
+ return new index_es_BitString({ unusedBits: this.unusedBits, valueHex: this.value });
+ }
+ toSchema(name) {
+ return new index_es_BitString({ name });
+ }
+ toNumber() {
+ let res = "";
+ const uintArray = new Uint8Array(this.value);
+ for (const octet of uintArray) {
+ res += octet.toString(2).padStart(8, "0");
+ }
+ res = res.split("").reverse().join("");
+ if (this.unusedBits) {
+ res = res.slice(this.unusedBits).padStart(this.unusedBits, "0");
+ }
+ return parseInt(res, 2);
+ }
+ fromNumber(value) {
+ let bits = value.toString(2);
+ const octetSize = (bits.length + 7) >> 3;
+ this.unusedBits = (octetSize << 3) - bits.length;
+ const octets = new Uint8Array(octetSize);
+ bits = bits.padStart(octetSize << 3, "0").split("").reverse().join("");
+ let index = 0;
+ while (index < octetSize) {
+ octets[index] = parseInt(bits.slice(index << 3, (index << 3) + 8), 2);
+ index++;
+ }
+ this.value = octets.buffer;
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/types/octet_string.js
+
+
+class octet_string_OctetString {
+ constructor(param) {
+ if (typeof param === "number") {
+ this.buffer = new ArrayBuffer(param);
+ }
+ else {
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(param)) {
+ this.buffer = build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(param);
+ }
+ else if (Array.isArray(param)) {
+ this.buffer = new Uint8Array(param);
+ }
+ else {
+ this.buffer = new ArrayBuffer(0);
+ }
+ }
+ }
+ get byteLength() {
+ return this.buffer.byteLength;
+ }
+ get byteOffset() {
+ return 0;
+ }
+ fromASN(asn) {
+ if (!(asn instanceof index_es_OctetString)) {
+ throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");
+ }
+ this.buffer = asn.valueBlock.valueHex;
+ return this;
+ }
+ toASN() {
+ return new index_es_OctetString({ valueHex: this.buffer });
+ }
+ toSchema(name) {
+ return new index_es_OctetString({ name });
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/types/index.js
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/converters.js
+
+
+
+const AsnAnyConverter = {
+ fromASN: (value) => value instanceof Null ? null : value.valueBeforeDecodeView,
+ toASN: (value) => {
+ if (value === null) {
+ return new Null();
+ }
+ const schema = fromBER(value);
+ if (schema.result.error) {
+ throw new Error(schema.result.error);
+ }
+ return schema.result;
+ },
+};
+const AsnIntegerConverter = {
+ fromASN: (value) => value.valueBlock.valueHexView.byteLength >= 4
+ ? value.valueBlock.toString()
+ : value.valueBlock.valueDec,
+ toASN: (value) => new Integer({ value: +value }),
+};
+const AsnEnumeratedConverter = {
+ fromASN: (value) => value.valueBlock.valueDec,
+ toASN: (value) => new Enumerated({ value }),
+};
+const AsnIntegerArrayBufferConverter = {
+ fromASN: (value) => value.valueBlock.valueHexView,
+ toASN: (value) => new Integer({ valueHex: value }),
+};
+const AsnIntegerBigIntConverter = {
+ fromASN: (value) => value.toBigInt(),
+ toASN: (value) => Integer.fromBigInt(value),
+};
+const AsnBitStringConverter = {
+ fromASN: (value) => value.valueBlock.valueHexView,
+ toASN: (value) => new index_es_BitString({ valueHex: value }),
+};
+const AsnObjectIdentifierConverter = {
+ fromASN: (value) => value.valueBlock.toString(),
+ toASN: (value) => new ObjectIdentifier({ value }),
+};
+const AsnBooleanConverter = {
+ fromASN: (value) => value.valueBlock.value,
+ toASN: (value) => new index_es_Boolean({ value }),
+};
+const AsnOctetStringConverter = {
+ fromASN: (value) => value.valueBlock.valueHexView,
+ toASN: (value) => new index_es_OctetString({ valueHex: value }),
+};
+const AsnConstructedOctetStringConverter = {
+ fromASN: (value) => new octet_string_OctetString(value.getValue()),
+ toASN: (value) => value.toASN(),
+};
+function createStringConverter(Asn1Type) {
+ return {
+ fromASN: (value) => value.valueBlock.value,
+ toASN: (value) => new Asn1Type({ value }),
+ };
+}
+const AsnUtf8StringConverter = createStringConverter(Utf8String);
+const AsnBmpStringConverter = createStringConverter(BmpString);
+const AsnUniversalStringConverter = createStringConverter(UniversalString);
+const AsnNumericStringConverter = createStringConverter(NumericString);
+const AsnPrintableStringConverter = createStringConverter(PrintableString);
+const AsnTeletexStringConverter = createStringConverter(TeletexString);
+const AsnVideotexStringConverter = createStringConverter(VideotexString);
+const AsnIA5StringConverter = createStringConverter(IA5String);
+const AsnGraphicStringConverter = createStringConverter(GraphicString);
+const AsnVisibleStringConverter = createStringConverter(VisibleString);
+const AsnGeneralStringConverter = createStringConverter(GeneralString);
+const AsnCharacterStringConverter = createStringConverter(CharacterString);
+const AsnUTCTimeConverter = {
+ fromASN: (value) => value.toDate(),
+ toASN: (value) => new UTCTime({ valueDate: value }),
+};
+const AsnGeneralizedTimeConverter = {
+ fromASN: (value) => value.toDate(),
+ toASN: (value) => new GeneralizedTime({ valueDate: value }),
+};
+const AsnNullConverter = {
+ fromASN: () => null,
+ toASN: () => {
+ return new Null();
+ },
+};
+function converters_defaultConverter(type) {
+ switch (type) {
+ case AsnPropTypes.Any:
+ return AsnAnyConverter;
+ case AsnPropTypes.BitString:
+ return AsnBitStringConverter;
+ case AsnPropTypes.BmpString:
+ return AsnBmpStringConverter;
+ case AsnPropTypes.Boolean:
+ return AsnBooleanConverter;
+ case AsnPropTypes.CharacterString:
+ return AsnCharacterStringConverter;
+ case AsnPropTypes.Enumerated:
+ return AsnEnumeratedConverter;
+ case AsnPropTypes.GeneralString:
+ return AsnGeneralStringConverter;
+ case AsnPropTypes.GeneralizedTime:
+ return AsnGeneralizedTimeConverter;
+ case AsnPropTypes.GraphicString:
+ return AsnGraphicStringConverter;
+ case AsnPropTypes.IA5String:
+ return AsnIA5StringConverter;
+ case AsnPropTypes.Integer:
+ return AsnIntegerConverter;
+ case AsnPropTypes.Null:
+ return AsnNullConverter;
+ case AsnPropTypes.NumericString:
+ return AsnNumericStringConverter;
+ case AsnPropTypes.ObjectIdentifier:
+ return AsnObjectIdentifierConverter;
+ case AsnPropTypes.OctetString:
+ return AsnOctetStringConverter;
+ case AsnPropTypes.PrintableString:
+ return AsnPrintableStringConverter;
+ case AsnPropTypes.TeletexString:
+ return AsnTeletexStringConverter;
+ case AsnPropTypes.UTCTime:
+ return AsnUTCTimeConverter;
+ case AsnPropTypes.UniversalString:
+ return AsnUniversalStringConverter;
+ case AsnPropTypes.Utf8String:
+ return AsnUtf8StringConverter;
+ case AsnPropTypes.VideotexString:
+ return AsnVideotexStringConverter;
+ case AsnPropTypes.VisibleString:
+ return AsnVisibleStringConverter;
+ default:
+ return null;
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/helper.js
+function isConvertible(target) {
+ if (typeof target === "function" && target.prototype) {
+ if (target.prototype.toASN && target.prototype.fromASN) {
+ return true;
+ }
+ else {
+ return isConvertible(target.prototype);
+ }
+ }
+ else {
+ return !!(target && typeof target === "object" && "toASN" in target && "fromASN" in target);
+ }
+}
+function isTypeOfArray(target) {
+ var _a;
+ if (target) {
+ const proto = Object.getPrototypeOf(target);
+ if (((_a = proto === null || proto === void 0 ? void 0 : proto.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === Array) {
+ return true;
+ }
+ return isTypeOfArray(proto);
+ }
+ return false;
+}
+function isArrayEqual(bytes1, bytes2) {
+ if (!(bytes1 && bytes2)) {
+ return false;
+ }
+ if (bytes1.byteLength !== bytes2.byteLength) {
+ return false;
+ }
+ const b1 = new Uint8Array(bytes1);
+ const b2 = new Uint8Array(bytes2);
+ for (let i = 0; i < bytes1.byteLength; i++) {
+ if (b1[i] !== b2[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/schema.js
+
+
+
+class AsnSchemaStorage {
+ constructor() {
+ this.items = new WeakMap();
+ }
+ has(target) {
+ return this.items.has(target);
+ }
+ get(target, checkSchema = false) {
+ const schema = this.items.get(target);
+ if (!schema) {
+ throw new Error(`Cannot get schema for '${target.prototype.constructor.name}' target`);
+ }
+ if (checkSchema && !schema.schema) {
+ throw new Error(`Schema '${target.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);
+ }
+ return schema;
+ }
+ cache(target) {
+ const schema = this.get(target);
+ if (!schema.schema) {
+ schema.schema = this.create(target, true);
+ }
+ }
+ createDefault(target) {
+ const schema = {
+ type: enums_AsnTypeTypes.Sequence,
+ items: {},
+ };
+ const parentSchema = this.findParentSchema(target);
+ if (parentSchema) {
+ Object.assign(schema, parentSchema);
+ schema.items = Object.assign({}, schema.items, parentSchema.items);
+ }
+ return schema;
+ }
+ create(target, useNames) {
+ const schema = this.items.get(target) || this.createDefault(target);
+ const asn1Value = [];
+ for (const key in schema.items) {
+ const item = schema.items[key];
+ const name = useNames ? key : "";
+ let asn1Item;
+ if (typeof (item.type) === "number") {
+ const Asn1TypeName = AsnPropTypes[item.type];
+ const Asn1Type = index_es_namespaceObject[Asn1TypeName];
+ if (!Asn1Type) {
+ throw new Error(`Cannot get ASN1 class by name '${Asn1TypeName}'`);
+ }
+ asn1Item = new Asn1Type({ name });
+ }
+ else if (isConvertible(item.type)) {
+ const instance = new item.type();
+ asn1Item = instance.toSchema(name);
+ }
+ else if (item.optional) {
+ const itemSchema = this.get(item.type);
+ if (itemSchema.type === enums_AsnTypeTypes.Choice) {
+ asn1Item = new Any({ name });
+ }
+ else {
+ asn1Item = this.create(item.type, false);
+ asn1Item.name = name;
+ }
+ }
+ else {
+ asn1Item = new Any({ name });
+ }
+ const optional = !!item.optional || item.defaultValue !== undefined;
+ if (item.repeated) {
+ asn1Item.name = "";
+ const Container = item.repeated === "set"
+ ? index_es_Set
+ : Sequence;
+ asn1Item = new Container({
+ name: "",
+ value: [
+ new Repeated({
+ name,
+ value: asn1Item,
+ }),
+ ],
+ });
+ }
+ if (item.context !== null && item.context !== undefined) {
+ if (item.implicit) {
+ if (typeof item.type === "number" || isConvertible(item.type)) {
+ const Container = item.repeated
+ ? Constructed
+ : Primitive;
+ asn1Value.push(new Container({
+ name,
+ optional,
+ idBlock: {
+ tagClass: 3,
+ tagNumber: item.context,
+ },
+ }));
+ }
+ else {
+ this.cache(item.type);
+ const isRepeated = !!item.repeated;
+ let value = !isRepeated
+ ? this.get(item.type, true).schema
+ : asn1Item;
+ value = "valueBlock" in value ? value.valueBlock.value : value.value;
+ asn1Value.push(new Constructed({
+ name: !isRepeated ? name : "",
+ optional,
+ idBlock: {
+ tagClass: 3,
+ tagNumber: item.context,
+ },
+ value: value,
+ }));
+ }
+ }
+ else {
+ asn1Value.push(new Constructed({
+ optional,
+ idBlock: {
+ tagClass: 3,
+ tagNumber: item.context,
+ },
+ value: [asn1Item],
+ }));
+ }
+ }
+ else {
+ asn1Item.optional = optional;
+ asn1Value.push(asn1Item);
+ }
+ }
+ switch (schema.type) {
+ case enums_AsnTypeTypes.Sequence:
+ return new Sequence({ value: asn1Value, name: "" });
+ case enums_AsnTypeTypes.Set:
+ return new index_es_Set({ value: asn1Value, name: "" });
+ case enums_AsnTypeTypes.Choice:
+ return new Choice({ value: asn1Value, name: "" });
+ default:
+ throw new Error(`Unsupported ASN1 type in use`);
+ }
+ }
+ set(target, schema) {
+ this.items.set(target, schema);
+ return this;
+ }
+ findParentSchema(target) {
+ const parent = Object.getPrototypeOf(target);
+ if (parent) {
+ const schema = this.items.get(parent);
+ return schema || this.findParentSchema(parent);
+ }
+ return null;
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/storage.js
+
+const schemaStorage = new AsnSchemaStorage();
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/decorators.js
+
+
+
+const AsnType = (options) => (target) => {
+ let schema;
+ if (!schemaStorage.has(target)) {
+ schema = schemaStorage.createDefault(target);
+ schemaStorage.set(target, schema);
+ }
+ else {
+ schema = schemaStorage.get(target);
+ }
+ Object.assign(schema, options);
+};
+const AsnChoiceType = () => AsnType({ type: AsnTypeTypes.Choice });
+const AsnSetType = (options) => AsnType({ type: AsnTypeTypes.Set, ...options });
+const AsnSequenceType = (options) => AsnType({ type: AsnTypeTypes.Sequence, ...options });
+const AsnProp = (options) => (target, propertyKey) => {
+ let schema;
+ if (!schemaStorage.has(target.constructor)) {
+ schema = schemaStorage.createDefault(target.constructor);
+ schemaStorage.set(target.constructor, schema);
+ }
+ else {
+ schema = schemaStorage.get(target.constructor);
+ }
+ const copyOptions = Object.assign({}, options);
+ if (typeof copyOptions.type === "number" && !copyOptions.converter) {
+ const defaultConverter = converters_defaultConverter(options.type);
+ if (!defaultConverter) {
+ throw new Error(`Cannot get default converter for property '${propertyKey}' of ${target.constructor.name}`);
+ }
+ copyOptions.converter = defaultConverter;
+ }
+ schema.items[propertyKey] = copyOptions;
+};
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/errors/schema_validation.js
+class AsnSchemaValidationError extends Error {
+ constructor() {
+ super(...arguments);
+ this.schemas = [];
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/errors/index.js
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/parser.js
+
+
+
+
+
+
+class AsnParser {
+ static parse(data, target) {
+ const asn1Parsed = fromBER(data);
+ if (asn1Parsed.result.error) {
+ throw new Error(asn1Parsed.result.error);
+ }
+ const res = this.fromASN(asn1Parsed.result, target);
+ return res;
+ }
+ static fromASN(asn1Schema, target) {
+ var _a;
+ try {
+ if (isConvertible(target)) {
+ const value = new target();
+ return value.fromASN(asn1Schema);
+ }
+ const schema = schemaStorage.get(target);
+ schemaStorage.cache(target);
+ let targetSchema = schema.schema;
+ if (asn1Schema.constructor === Constructed && schema.type !== enums_AsnTypeTypes.Choice) {
+ targetSchema = new Constructed({
+ idBlock: {
+ tagClass: 3,
+ tagNumber: asn1Schema.idBlock.tagNumber,
+ },
+ value: schema.schema.valueBlock.value,
+ });
+ for (const key in schema.items) {
+ delete asn1Schema[key];
+ }
+ }
+ const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
+ if (!asn1ComparedSchema.verified) {
+ throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema. ${asn1ComparedSchema.result.error}`);
+ }
+ const res = new target();
+ if (isTypeOfArray(target)) {
+ if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
+ throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);
+ }
+ const itemType = schema.itemType;
+ if (typeof itemType === "number") {
+ const converter = converters_defaultConverter(itemType);
+ if (!converter) {
+ throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
+ }
+ return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
+ }
+ else {
+ return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType));
+ }
+ }
+ for (const key in schema.items) {
+ const asn1SchemaValue = asn1ComparedSchema.result[key];
+ if (!asn1SchemaValue) {
+ continue;
+ }
+ const schemaItem = schema.items[key];
+ const schemaItemType = schemaItem.type;
+ if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) {
+ const converter = (_a = schemaItem.converter) !== null && _a !== void 0 ? _a : (isConvertible(schemaItemType)
+ ? new schemaItemType()
+ : null);
+ if (!converter) {
+ throw new Error("Converter is empty");
+ }
+ if (schemaItem.repeated) {
+ if (schemaItem.implicit) {
+ const Container = schemaItem.repeated === "sequence"
+ ? Sequence
+ : index_es_Set;
+ const newItem = new Container();
+ newItem.valueBlock = asn1SchemaValue.valueBlock;
+ const newItemAsn = fromBER(newItem.toBER(false));
+ if (newItemAsn.offset === -1) {
+ throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
+ }
+ if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) {
+ throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
+ }
+ const value = newItemAsn.result.valueBlock.value;
+ res[key] = Array.from(value, (element) => converter.fromASN(element));
+ }
+ else {
+ res[key] = Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
+ }
+ }
+ else {
+ let value = asn1SchemaValue;
+ if (schemaItem.implicit) {
+ let newItem;
+ if (isConvertible(schemaItemType)) {
+ newItem = new schemaItemType().toSchema("");
+ }
+ else {
+ const Asn1TypeName = AsnPropTypes[schemaItemType];
+ const Asn1Type = index_es_namespaceObject[Asn1TypeName];
+ if (!Asn1Type) {
+ throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
+ }
+ newItem = new Asn1Type();
+ }
+ newItem.valueBlock = value.valueBlock;
+ value = fromBER(newItem.toBER(false)).result;
+ }
+ res[key] = converter.fromASN(value);
+ }
+ }
+ else {
+ if (schemaItem.repeated) {
+ if (!Array.isArray(asn1SchemaValue)) {
+ throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
+ }
+ res[key] = Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType));
+ }
+ else {
+ res[key] = this.fromASN(asn1SchemaValue, schemaItemType);
+ }
+ }
+ }
+ return res;
+ }
+ catch (error) {
+ if (error instanceof AsnSchemaValidationError) {
+ error.schemas.push(target.name);
+ }
+ throw error;
+ }
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/serializer.js
+
+
+
+
+
+class AsnSerializer {
+ static serialize(obj) {
+ if (obj instanceof BaseBlock) {
+ return obj.toBER(false);
+ }
+ return this.toASN(obj).toBER(false);
+ }
+ static toASN(obj) {
+ if (obj && typeof obj === "object" && isConvertible(obj)) {
+ return obj.toASN();
+ }
+ if (!(obj && typeof obj === "object")) {
+ throw new TypeError("Parameter 1 should be type of Object.");
+ }
+ const target = obj.constructor;
+ const schema = schemaStorage.get(target);
+ schemaStorage.cache(target);
+ let asn1Value = [];
+ if (schema.itemType) {
+ if (!Array.isArray(obj)) {
+ throw new TypeError("Parameter 1 should be type of Array.");
+ }
+ if (typeof schema.itemType === "number") {
+ const converter = converters_defaultConverter(schema.itemType);
+ if (!converter) {
+ throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
+ }
+ asn1Value = obj.map((o) => converter.toASN(o));
+ }
+ else {
+ asn1Value = obj.map((o) => this.toAsnItem({ type: schema.itemType }, "[]", target, o));
+ }
+ }
+ else {
+ for (const key in schema.items) {
+ const schemaItem = schema.items[key];
+ const objProp = obj[key];
+ if (objProp === undefined
+ || schemaItem.defaultValue === objProp
+ || (typeof schemaItem.defaultValue === "object" && typeof objProp === "object"
+ && isArrayEqual(this.serialize(schemaItem.defaultValue), this.serialize(objProp)))) {
+ continue;
+ }
+ const asn1Item = AsnSerializer.toAsnItem(schemaItem, key, target, objProp);
+ if (typeof schemaItem.context === "number") {
+ if (schemaItem.implicit) {
+ if (!schemaItem.repeated
+ && (typeof schemaItem.type === "number" || isConvertible(schemaItem.type))) {
+ const value = {};
+ value.valueHex = asn1Item instanceof Null ? asn1Item.valueBeforeDecodeView : asn1Item.valueBlock.toBER();
+ asn1Value.push(new Primitive({
+ optional: schemaItem.optional,
+ idBlock: {
+ tagClass: 3,
+ tagNumber: schemaItem.context,
+ },
+ ...value,
+ }));
+ }
+ else {
+ asn1Value.push(new Constructed({
+ optional: schemaItem.optional,
+ idBlock: {
+ tagClass: 3,
+ tagNumber: schemaItem.context,
+ },
+ value: asn1Item.valueBlock.value,
+ }));
+ }
+ }
+ else {
+ asn1Value.push(new Constructed({
+ optional: schemaItem.optional,
+ idBlock: {
+ tagClass: 3,
+ tagNumber: schemaItem.context,
+ },
+ value: [asn1Item],
+ }));
+ }
+ }
+ else if (schemaItem.repeated) {
+ asn1Value = asn1Value.concat(asn1Item);
+ }
+ else {
+ asn1Value.push(asn1Item);
+ }
+ }
+ }
+ let asnSchema;
+ switch (schema.type) {
+ case enums_AsnTypeTypes.Sequence:
+ asnSchema = new Sequence({ value: asn1Value });
+ break;
+ case enums_AsnTypeTypes.Set:
+ asnSchema = new index_es_Set({ value: asn1Value });
+ break;
+ case enums_AsnTypeTypes.Choice:
+ if (!asn1Value[0]) {
+ throw new Error(`Schema '${target.name}' has wrong data. Choice cannot be empty.`);
+ }
+ asnSchema = asn1Value[0];
+ break;
+ }
+ return asnSchema;
+ }
+ static toAsnItem(schemaItem, key, target, objProp) {
+ let asn1Item;
+ if (typeof (schemaItem.type) === "number") {
+ const converter = schemaItem.converter;
+ if (!converter) {
+ throw new Error(`Property '${key}' doesn't have converter for type ${AsnPropTypes[schemaItem.type]} in schema '${target.name}'`);
+ }
+ if (schemaItem.repeated) {
+ if (!Array.isArray(objProp)) {
+ throw new TypeError("Parameter 'objProp' should be type of Array.");
+ }
+ const items = Array.from(objProp, (element) => converter.toASN(element));
+ const Container = schemaItem.repeated === "sequence"
+ ? Sequence
+ : index_es_Set;
+ asn1Item = new Container({
+ value: items,
+ });
+ }
+ else {
+ asn1Item = converter.toASN(objProp);
+ }
+ }
+ else {
+ if (schemaItem.repeated) {
+ if (!Array.isArray(objProp)) {
+ throw new TypeError("Parameter 'objProp' should be type of Array.");
+ }
+ const items = Array.from(objProp, (element) => this.toASN(element));
+ const Container = schemaItem.repeated === "sequence"
+ ? Sequence
+ : index_es_Set;
+ asn1Item = new Container({
+ value: items,
+ });
+ }
+ else {
+ asn1Item = this.toASN(objProp);
+ }
+ }
+ return asn1Item;
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/objects.js
+class AsnArray extends Array {
+ constructor(items = []) {
+ if (typeof items === "number") {
+ super(items);
+ }
+ else {
+ super();
+ for (const item of items) {
+ this.push(item);
+ }
+ }
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/convert.js
+
+
+
+
+class convert_AsnConvert {
+ static serialize(obj) {
+ return AsnSerializer.serialize(obj);
+ }
+ static parse(data, target) {
+ return AsnParser.parse(data, target);
+ }
+ static toString(data) {
+ const buf = build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(data)
+ ? build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(data)
+ : convert_AsnConvert.serialize(data);
+ const asn = fromBER(buf);
+ if (asn.offset === -1) {
+ throw new Error(`Cannot decode ASN.1 data. ${asn.result.error}`);
+ }
+ return asn.result.toString();
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-schema/build/es2015/index.js
+
+
+
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
+/******************************************************************************
+Copyright (c) Microsoft Corporation.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global Reflect, Promise */
+
+var extendStatics = function(d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+};
+
+function tslib_es6_extends(d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+}
+
+var __assign = function() {
+ __assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ }
+ return __assign.apply(this, arguments);
+}
+
+function tslib_es6_rest(s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+}
+
+function __decorate(decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+}
+
+function __param(paramIndex, decorator) {
+ return function (target, key) { decorator(target, key, paramIndex); }
+}
+
+function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
+ var _, done = false;
+ for (var i = decorators.length - 1; i >= 0; i--) {
+ var context = {};
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
+ if (kind === "accessor") {
+ if (result === void 0) continue;
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
+ if (_ = accept(result.get)) descriptor.get = _;
+ if (_ = accept(result.set)) descriptor.set = _;
+ if (_ = accept(result.init)) initializers.unshift(_);
+ }
+ else if (_ = accept(result)) {
+ if (kind === "field") initializers.unshift(_);
+ else descriptor[key] = _;
+ }
+ }
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
+ done = true;
+};
+
+function __runInitializers(thisArg, initializers, value) {
+ var useValue = arguments.length > 2;
+ for (var i = 0; i < initializers.length; i++) {
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
+ }
+ return useValue ? value : void 0;
+};
+
+function __propKey(x) {
+ return typeof x === "symbol" ? x : "".concat(x);
+};
+
+function __setFunctionName(f, name, prefix) {
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
+};
+
+function __metadata(metadataKey, metadataValue) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+}
+
+function tslib_es6_awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+}
+
+function __generator(thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+}
+
+var __createBinding = Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+});
+
+function __exportStar(m, o) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
+}
+
+function __values(o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+}
+
+function __read(o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+}
+
+/** @deprecated */
+function tslib_es6_spread() {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(__read(arguments[i]));
+ return ar;
+}
+
+/** @deprecated */
+function __spreadArrays() {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
+}
+
+function __spreadArray(to, from, pack) {
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+ if (ar || !(i in from)) {
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+ ar[i] = from[i];
+ }
+ }
+ return to.concat(ar || Array.prototype.slice.call(from));
+}
+
+function __await(v) {
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
+}
+
+function __asyncGenerator(thisArg, _arguments, generator) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+}
+
+function __asyncDelegator(o) {
+ var i, p;
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
+}
+
+function __asyncValues(o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+}
+
+function __makeTemplateObject(cooked, raw) {
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
+ return cooked;
+};
+
+var __setModuleDefault = Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+};
+
+function __importStar(mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+}
+
+function __importDefault(mod) {
+ return (mod && mod.__esModule) ? mod : { default: mod };
+}
+
+function __classPrivateFieldGet(receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+}
+
+function __classPrivateFieldSet(receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+}
+
+function __classPrivateFieldIn(state, receiver) {
+ if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
+ return typeof state === "function" ? receiver === state : state.has(receiver);
+}
+
+/* harmony default export */ const tslib_es6 = ({
+ __extends: tslib_es6_extends,
+ __assign,
+ __rest: tslib_es6_rest,
+ __decorate,
+ __param,
+ __metadata,
+ __awaiter: tslib_es6_awaiter,
+ __generator,
+ __createBinding,
+ __exportStar,
+ __values,
+ __read,
+ __spread: tslib_es6_spread,
+ __spreadArrays,
+ __spreadArray,
+ __await,
+ __asyncGenerator,
+ __asyncDelegator,
+ __asyncValues,
+ __makeTemplateObject,
+ __importStar,
+ __importDefault,
+ __classPrivateFieldGet,
+ __classPrivateFieldSet,
+ __classPrivateFieldIn,
+});
+
+// EXTERNAL MODULE: ./node_modules/ipaddr.js/lib/ipaddr.js
+var ipaddr = __webpack_require__(6512);
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/ip_converter.js
+
+
+class IpConverter {
+ static decodeIP(value) {
+ if (value.length === 64 && parseInt(value, 16) === 0) {
+ return "::/0";
+ }
+ if (value.length !== 16) {
+ return value;
+ }
+ const mask = parseInt(value.slice(8), 16)
+ .toString(2)
+ .split('')
+ .reduce((a, k) => a + (+k), 0);
+ let ip = value.slice(0, 8)
+ .replace(/(.{2})/g, match => `${parseInt(match, 16)}.`);
+ ip = ip.slice(0, -1);
+ return `${ip}/${mask}`;
+ }
+ static toString(buf) {
+ if (buf.byteLength === 4 || buf.byteLength === 16) {
+ const uint8 = new Uint8Array(buf);
+ const addr = ipaddr.fromByteArray(Array.from(uint8));
+ return addr.toString();
+ }
+ return this.decodeIP(build/* Convert.ToHex */.ep.ToHex(buf));
+ }
+ static fromString(text) {
+ const addr = ipaddr.parse(text);
+ return new Uint8Array(addr.toByteArray()).buffer;
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/name.js
+var RelativeDistinguishedName_1, RDNSequence_1, Name_1;
+
+
+
+let DirectoryString = class DirectoryString {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+ toString() {
+ return this.bmpString || this.printableString || this.teletexString || this.universalString
+ || this.utf8String || "";
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.TeletexString })
+], DirectoryString.prototype, "teletexString", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.PrintableString })
+], DirectoryString.prototype, "printableString", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.UniversalString })
+], DirectoryString.prototype, "universalString", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Utf8String })
+], DirectoryString.prototype, "utf8String", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BmpString })
+], DirectoryString.prototype, "bmpString", void 0);
+DirectoryString = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], DirectoryString);
+
+let AttributeValue = class AttributeValue extends DirectoryString {
+ constructor(params = {}) {
+ super(params);
+ Object.assign(this, params);
+ }
+ toString() {
+ return this.ia5String || (this.anyValue ? build/* Convert.ToHex */.ep.ToHex(this.anyValue) : super.toString());
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.IA5String })
+], AttributeValue.prototype, "ia5String", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any })
+], AttributeValue.prototype, "anyValue", void 0);
+AttributeValue = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], AttributeValue);
+
+class AttributeTypeAndValue {
+ constructor(params = {}) {
+ this.type = "";
+ this.value = new AttributeValue();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], AttributeTypeAndValue.prototype, "type", void 0);
+__decorate([
+ AsnProp({ type: AttributeValue })
+], AttributeTypeAndValue.prototype, "value", void 0);
+let RelativeDistinguishedName = RelativeDistinguishedName_1 = class RelativeDistinguishedName extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, RelativeDistinguishedName_1.prototype);
+ }
+};
+RelativeDistinguishedName = RelativeDistinguishedName_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Set, itemType: AttributeTypeAndValue })
+], RelativeDistinguishedName);
+
+let RDNSequence = RDNSequence_1 = class RDNSequence extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, RDNSequence_1.prototype);
+ }
+};
+RDNSequence = RDNSequence_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: RelativeDistinguishedName })
+], RDNSequence);
+
+let name_Name = Name_1 = class Name extends RDNSequence {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, Name_1.prototype);
+ }
+};
+name_Name = Name_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], name_Name);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/general_name.js
+
+
+
+
+const AsnIpConverter = {
+ fromASN: (value) => IpConverter.toString(AsnOctetStringConverter.fromASN(value)),
+ toASN: (value) => AsnOctetStringConverter.toASN(IpConverter.fromString(value)),
+};
+class OtherName {
+ constructor(params = {}) {
+ this.typeId = "";
+ this.value = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], OtherName.prototype, "typeId", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, context: 0 })
+], OtherName.prototype, "value", void 0);
+class EDIPartyName {
+ constructor(params = {}) {
+ this.partyName = new DirectoryString();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: DirectoryString, optional: true, context: 0, implicit: true })
+], EDIPartyName.prototype, "nameAssigner", void 0);
+__decorate([
+ AsnProp({ type: DirectoryString, context: 1, implicit: true })
+], EDIPartyName.prototype, "partyName", void 0);
+let general_name_GeneralName = class GeneralName {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: OtherName, context: 0, implicit: true })
+], general_name_GeneralName.prototype, "otherName", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.IA5String, context: 1, implicit: true })
+], general_name_GeneralName.prototype, "rfc822Name", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.IA5String, context: 2, implicit: true })
+], general_name_GeneralName.prototype, "dNSName", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, context: 3, implicit: true })
+], general_name_GeneralName.prototype, "x400Address", void 0);
+__decorate([
+ AsnProp({ type: name_Name, context: 4, implicit: false })
+], general_name_GeneralName.prototype, "directoryName", void 0);
+__decorate([
+ AsnProp({ type: EDIPartyName, context: 5 })
+], general_name_GeneralName.prototype, "ediPartyName", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.IA5String, context: 6, implicit: true })
+], general_name_GeneralName.prototype, "uniformResourceIdentifier", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.OctetString, context: 7, implicit: true, converter: AsnIpConverter })
+], general_name_GeneralName.prototype, "iPAddress", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier, context: 8, implicit: true })
+], general_name_GeneralName.prototype, "registeredID", void 0);
+general_name_GeneralName = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], general_name_GeneralName);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/object_identifiers.js
+const id_pkix = "1.3.6.1.5.5.7";
+const id_pe = `${id_pkix}.1`;
+const id_qt = `${id_pkix}.2`;
+const id_kp = `${id_pkix}.3`;
+const id_ad = `${id_pkix}.48`;
+const id_qt_csp = `${id_qt}.1`;
+const id_qt_unotice = `${id_qt}.2`;
+const id_ad_ocsp = `${id_ad}.1`;
+const id_ad_caIssuers = `${id_ad}.2`;
+const id_ad_timeStamping = `${id_ad}.3`;
+const id_ad_caRepository = `${id_ad}.5`;
+const id_ce = "2.5.29";
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/authority_information_access.js
+var AuthorityInfoAccessSyntax_1;
+
+
+
+
+const id_pe_authorityInfoAccess = `${id_pe}.1`;
+class AccessDescription {
+ constructor(params = {}) {
+ this.accessMethod = "";
+ this.accessLocation = new general_name_GeneralName();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], AccessDescription.prototype, "accessMethod", void 0);
+__decorate([
+ AsnProp({ type: general_name_GeneralName })
+], AccessDescription.prototype, "accessLocation", void 0);
+let AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax_1 = class AuthorityInfoAccessSyntax extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, AuthorityInfoAccessSyntax_1.prototype);
+ }
+};
+AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: AccessDescription })
+], AuthorityInfoAccessSyntax);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/authority_key_identifier.js
+
+
+
+
+const id_ce_authorityKeyIdentifier = `${id_ce}.35`;
+class KeyIdentifier extends octet_string_OctetString {
+}
+class AuthorityKeyIdentifier {
+ constructor(params = {}) {
+ if (params) {
+ Object.assign(this, params);
+ }
+ }
+}
+__decorate([
+ AsnProp({ type: KeyIdentifier, context: 0, optional: true, implicit: true })
+], AuthorityKeyIdentifier.prototype, "keyIdentifier", void 0);
+__decorate([
+ AsnProp({ type: general_name_GeneralName, context: 1, optional: true, implicit: true, repeated: "sequence" })
+], AuthorityKeyIdentifier.prototype, "authorityCertIssuer", void 0);
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.Integer,
+ context: 2,
+ optional: true,
+ implicit: true,
+ converter: AsnIntegerArrayBufferConverter,
+ })
+], AuthorityKeyIdentifier.prototype, "authorityCertSerialNumber", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/basic_constraints.js
+
+
+
+const id_ce_basicConstraints = `${id_ce}.19`;
+class BasicConstraints {
+ constructor(params = {}) {
+ this.cA = false;
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Boolean, defaultValue: false })
+], BasicConstraints.prototype, "cA", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, optional: true })
+], BasicConstraints.prototype, "pathLenConstraint", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/general_names.js
+var GeneralNames_1;
+
+
+
+
+let general_names_GeneralNames = GeneralNames_1 = class GeneralNames extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, GeneralNames_1.prototype);
+ }
+};
+general_names_GeneralNames = GeneralNames_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: general_name_GeneralName })
+], general_names_GeneralNames);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/certificate_issuer.js
+var CertificateIssuer_1;
+
+
+
+
+const id_ce_certificateIssuer = `${id_ce}.29`;
+let CertificateIssuer = CertificateIssuer_1 = class CertificateIssuer extends general_names_GeneralNames {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, CertificateIssuer_1.prototype);
+ }
+};
+CertificateIssuer = CertificateIssuer_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], CertificateIssuer);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/certificate_policies.js
+var CertificatePolicies_1;
+
+
+
+const id_ce_certificatePolicies = `${id_ce}.32`;
+const id_ce_certificatePolicies_anyPolicy = `${id_ce_certificatePolicies}.0`;
+let DisplayText = class DisplayText {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+ toString() {
+ return this.ia5String || this.visibleString || this.bmpString || this.utf8String || "";
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.IA5String })
+], DisplayText.prototype, "ia5String", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.VisibleString })
+], DisplayText.prototype, "visibleString", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BmpString })
+], DisplayText.prototype, "bmpString", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Utf8String })
+], DisplayText.prototype, "utf8String", void 0);
+DisplayText = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], DisplayText);
+
+class NoticeReference {
+ constructor(params = {}) {
+ this.organization = new DisplayText();
+ this.noticeNumbers = [];
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: DisplayText })
+], NoticeReference.prototype, "organization", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, repeated: "sequence" })
+], NoticeReference.prototype, "noticeNumbers", void 0);
+class UserNotice {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: NoticeReference, optional: true })
+], UserNotice.prototype, "noticeRef", void 0);
+__decorate([
+ AsnProp({ type: DisplayText, optional: true })
+], UserNotice.prototype, "explicitText", void 0);
+let Qualifier = class Qualifier {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.IA5String })
+], Qualifier.prototype, "cPSuri", void 0);
+__decorate([
+ AsnProp({ type: UserNotice })
+], Qualifier.prototype, "userNotice", void 0);
+Qualifier = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], Qualifier);
+
+class PolicyQualifierInfo {
+ constructor(params = {}) {
+ this.policyQualifierId = "";
+ this.qualifier = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], PolicyQualifierInfo.prototype, "policyQualifierId", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any })
+], PolicyQualifierInfo.prototype, "qualifier", void 0);
+class PolicyInformation {
+ constructor(params = {}) {
+ this.policyIdentifier = "";
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], PolicyInformation.prototype, "policyIdentifier", void 0);
+__decorate([
+ AsnProp({ type: PolicyQualifierInfo, repeated: "sequence", optional: true })
+], PolicyInformation.prototype, "policyQualifiers", void 0);
+let CertificatePolicies = CertificatePolicies_1 = class CertificatePolicies extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, CertificatePolicies_1.prototype);
+ }
+};
+CertificatePolicies = CertificatePolicies_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: PolicyInformation })
+], CertificatePolicies);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/crl_number.js
+
+
+
+const id_ce_cRLNumber = `${id_ce}.20`;
+let CRLNumber = class CRLNumber {
+ constructor(value = 0) {
+ this.value = value;
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], CRLNumber.prototype, "value", void 0);
+CRLNumber = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], CRLNumber);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/crl_delta_indicator.js
+
+
+
+
+const id_ce_deltaCRLIndicator = `${id_ce}.27`;
+let BaseCRLNumber = class BaseCRLNumber extends CRLNumber {
+};
+BaseCRLNumber = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], BaseCRLNumber);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/crl_distribution_points.js
+var CRLDistributionPoints_1;
+
+
+
+
+
+const id_ce_cRLDistributionPoints = `${id_ce}.31`;
+var ReasonFlags;
+(function (ReasonFlags) {
+ ReasonFlags[ReasonFlags["unused"] = 1] = "unused";
+ ReasonFlags[ReasonFlags["keyCompromise"] = 2] = "keyCompromise";
+ ReasonFlags[ReasonFlags["cACompromise"] = 4] = "cACompromise";
+ ReasonFlags[ReasonFlags["affiliationChanged"] = 8] = "affiliationChanged";
+ ReasonFlags[ReasonFlags["superseded"] = 16] = "superseded";
+ ReasonFlags[ReasonFlags["cessationOfOperation"] = 32] = "cessationOfOperation";
+ ReasonFlags[ReasonFlags["certificateHold"] = 64] = "certificateHold";
+ ReasonFlags[ReasonFlags["privilegeWithdrawn"] = 128] = "privilegeWithdrawn";
+ ReasonFlags[ReasonFlags["aACompromise"] = 256] = "aACompromise";
+})(ReasonFlags || (ReasonFlags = {}));
+class Reason extends BitString {
+ toJSON() {
+ const res = [];
+ const flags = this.toNumber();
+ if (flags & ReasonFlags.aACompromise) {
+ res.push("aACompromise");
+ }
+ if (flags & ReasonFlags.affiliationChanged) {
+ res.push("affiliationChanged");
+ }
+ if (flags & ReasonFlags.cACompromise) {
+ res.push("cACompromise");
+ }
+ if (flags & ReasonFlags.certificateHold) {
+ res.push("certificateHold");
+ }
+ if (flags & ReasonFlags.cessationOfOperation) {
+ res.push("cessationOfOperation");
+ }
+ if (flags & ReasonFlags.keyCompromise) {
+ res.push("keyCompromise");
+ }
+ if (flags & ReasonFlags.privilegeWithdrawn) {
+ res.push("privilegeWithdrawn");
+ }
+ if (flags & ReasonFlags.superseded) {
+ res.push("superseded");
+ }
+ if (flags & ReasonFlags.unused) {
+ res.push("unused");
+ }
+ return res;
+ }
+ toString() {
+ return `[${this.toJSON().join(", ")}]`;
+ }
+}
+let DistributionPointName = class DistributionPointName {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: general_name_GeneralName, context: 0, repeated: "sequence", implicit: true })
+], DistributionPointName.prototype, "fullName", void 0);
+__decorate([
+ AsnProp({ type: RelativeDistinguishedName, context: 1, implicit: true })
+], DistributionPointName.prototype, "nameRelativeToCRLIssuer", void 0);
+DistributionPointName = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], DistributionPointName);
+
+class DistributionPoint {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: DistributionPointName, context: 0, optional: true })
+], DistributionPoint.prototype, "distributionPoint", void 0);
+__decorate([
+ AsnProp({ type: Reason, context: 1, optional: true, implicit: true })
+], DistributionPoint.prototype, "reasons", void 0);
+__decorate([
+ AsnProp({ type: general_name_GeneralName, context: 2, optional: true, repeated: "sequence", implicit: true })
+], DistributionPoint.prototype, "cRLIssuer", void 0);
+let CRLDistributionPoints = CRLDistributionPoints_1 = class CRLDistributionPoints extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, CRLDistributionPoints_1.prototype);
+ }
+};
+CRLDistributionPoints = CRLDistributionPoints_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: DistributionPoint })
+], CRLDistributionPoints);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/crl_freshest.js
+var FreshestCRL_1;
+
+
+
+
+const id_ce_freshestCRL = `${id_ce}.46`;
+let FreshestCRL = FreshestCRL_1 = class FreshestCRL extends CRLDistributionPoints {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, FreshestCRL_1.prototype);
+ }
+};
+FreshestCRL = FreshestCRL_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: DistributionPoint })
+], FreshestCRL);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/crl_issuing_distribution_point.js
+
+
+
+
+
+const id_ce_issuingDistributionPoint = `${id_ce}.28`;
+class IssuingDistributionPoint {
+ constructor(params = {}) {
+ this.onlyContainsUserCerts = IssuingDistributionPoint.ONLY;
+ this.onlyContainsCACerts = IssuingDistributionPoint.ONLY;
+ this.indirectCRL = IssuingDistributionPoint.ONLY;
+ this.onlyContainsAttributeCerts = IssuingDistributionPoint.ONLY;
+ Object.assign(this, params);
+ }
+}
+IssuingDistributionPoint.ONLY = false;
+__decorate([
+ AsnProp({ type: DistributionPointName, context: 0, optional: true })
+], IssuingDistributionPoint.prototype, "distributionPoint", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Boolean, context: 1, defaultValue: IssuingDistributionPoint.ONLY, implicit: true })
+], IssuingDistributionPoint.prototype, "onlyContainsUserCerts", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Boolean, context: 2, defaultValue: IssuingDistributionPoint.ONLY, implicit: true })
+], IssuingDistributionPoint.prototype, "onlyContainsCACerts", void 0);
+__decorate([
+ AsnProp({ type: Reason, context: 3, optional: true, implicit: true })
+], IssuingDistributionPoint.prototype, "onlySomeReasons", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Boolean, context: 4, defaultValue: IssuingDistributionPoint.ONLY, implicit: true })
+], IssuingDistributionPoint.prototype, "indirectCRL", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Boolean, context: 5, defaultValue: IssuingDistributionPoint.ONLY, implicit: true })
+], IssuingDistributionPoint.prototype, "onlyContainsAttributeCerts", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/crl_reason.js
+
+
+
+const crl_reason_id_ce_cRLReasons = `${id_ce}.21`;
+var CRLReasons;
+(function (CRLReasons) {
+ CRLReasons[CRLReasons["unspecified"] = 0] = "unspecified";
+ CRLReasons[CRLReasons["keyCompromise"] = 1] = "keyCompromise";
+ CRLReasons[CRLReasons["cACompromise"] = 2] = "cACompromise";
+ CRLReasons[CRLReasons["affiliationChanged"] = 3] = "affiliationChanged";
+ CRLReasons[CRLReasons["superseded"] = 4] = "superseded";
+ CRLReasons[CRLReasons["cessationOfOperation"] = 5] = "cessationOfOperation";
+ CRLReasons[CRLReasons["certificateHold"] = 6] = "certificateHold";
+ CRLReasons[CRLReasons["removeFromCRL"] = 8] = "removeFromCRL";
+ CRLReasons[CRLReasons["privilegeWithdrawn"] = 9] = "privilegeWithdrawn";
+ CRLReasons[CRLReasons["aACompromise"] = 10] = "aACompromise";
+})(CRLReasons || (CRLReasons = {}));
+let crl_reason_CRLReason = class CRLReason {
+ constructor(reason = CRLReasons.unspecified) {
+ this.reason = CRLReasons.unspecified;
+ this.reason = reason;
+ }
+ toJSON() {
+ return CRLReasons[this.reason];
+ }
+ toString() {
+ return this.toJSON();
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.Enumerated })
+], crl_reason_CRLReason.prototype, "reason", void 0);
+crl_reason_CRLReason = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], crl_reason_CRLReason);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/extended_key_usage.js
+var ExtendedKeyUsage_1;
+
+
+
+const id_ce_extKeyUsage = `${id_ce}.37`;
+let ExtendedKeyUsage = ExtendedKeyUsage_1 = class ExtendedKeyUsage extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, ExtendedKeyUsage_1.prototype);
+ }
+};
+ExtendedKeyUsage = ExtendedKeyUsage_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: AsnPropTypes.ObjectIdentifier })
+], ExtendedKeyUsage);
+
+const anyExtendedKeyUsage = `${id_ce_extKeyUsage}.0`;
+const id_kp_serverAuth = `${id_kp}.1`;
+const id_kp_clientAuth = `${id_kp}.2`;
+const id_kp_codeSigning = `${id_kp}.3`;
+const id_kp_emailProtection = `${id_kp}.4`;
+const id_kp_timeStamping = `${id_kp}.8`;
+const id_kp_OCSPSigning = `${id_kp}.9`;
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/inhibit_any_policy.js
+
+
+
+const id_ce_inhibitAnyPolicy = `${id_ce}.54`;
+let InhibitAnyPolicy = class InhibitAnyPolicy {
+ constructor(value = new ArrayBuffer(0)) {
+ this.value = value;
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], InhibitAnyPolicy.prototype, "value", void 0);
+InhibitAnyPolicy = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], InhibitAnyPolicy);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/invalidity_date.js
+
+
+
+const invalidity_date_id_ce_invalidityDate = `${id_ce}.24`;
+let invalidity_date_InvalidityDate = class InvalidityDate {
+ constructor(value) {
+ this.value = new Date();
+ if (value) {
+ this.value = value;
+ }
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.GeneralizedTime })
+], invalidity_date_InvalidityDate.prototype, "value", void 0);
+invalidity_date_InvalidityDate = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], invalidity_date_InvalidityDate);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/issuer_alternative_name.js
+var IssueAlternativeName_1;
+
+
+
+
+const id_ce_issuerAltName = `${id_ce}.18`;
+let IssueAlternativeName = IssueAlternativeName_1 = class IssueAlternativeName extends general_names_GeneralNames {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, IssueAlternativeName_1.prototype);
+ }
+};
+IssueAlternativeName = IssueAlternativeName_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], IssueAlternativeName);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/key_usage.js
+
+
+const id_ce_keyUsage = `${id_ce}.15`;
+var KeyUsageFlags;
+(function (KeyUsageFlags) {
+ KeyUsageFlags[KeyUsageFlags["digitalSignature"] = 1] = "digitalSignature";
+ KeyUsageFlags[KeyUsageFlags["nonRepudiation"] = 2] = "nonRepudiation";
+ KeyUsageFlags[KeyUsageFlags["keyEncipherment"] = 4] = "keyEncipherment";
+ KeyUsageFlags[KeyUsageFlags["dataEncipherment"] = 8] = "dataEncipherment";
+ KeyUsageFlags[KeyUsageFlags["keyAgreement"] = 16] = "keyAgreement";
+ KeyUsageFlags[KeyUsageFlags["keyCertSign"] = 32] = "keyCertSign";
+ KeyUsageFlags[KeyUsageFlags["cRLSign"] = 64] = "cRLSign";
+ KeyUsageFlags[KeyUsageFlags["encipherOnly"] = 128] = "encipherOnly";
+ KeyUsageFlags[KeyUsageFlags["decipherOnly"] = 256] = "decipherOnly";
+})(KeyUsageFlags || (KeyUsageFlags = {}));
+class KeyUsage extends BitString {
+ toJSON() {
+ const flag = this.toNumber();
+ const res = [];
+ if (flag & KeyUsageFlags.cRLSign) {
+ res.push("crlSign");
+ }
+ if (flag & KeyUsageFlags.dataEncipherment) {
+ res.push("dataEncipherment");
+ }
+ if (flag & KeyUsageFlags.decipherOnly) {
+ res.push("decipherOnly");
+ }
+ if (flag & KeyUsageFlags.digitalSignature) {
+ res.push("digitalSignature");
+ }
+ if (flag & KeyUsageFlags.encipherOnly) {
+ res.push("encipherOnly");
+ }
+ if (flag & KeyUsageFlags.keyAgreement) {
+ res.push("keyAgreement");
+ }
+ if (flag & KeyUsageFlags.keyCertSign) {
+ res.push("keyCertSign");
+ }
+ if (flag & KeyUsageFlags.keyEncipherment) {
+ res.push("keyEncipherment");
+ }
+ if (flag & KeyUsageFlags.nonRepudiation) {
+ res.push("nonRepudiation");
+ }
+ return res;
+ }
+ toString() {
+ return `[${this.toJSON().join(", ")}]`;
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/name_constraints.js
+var GeneralSubtrees_1;
+
+
+
+
+const id_ce_nameConstraints = `${id_ce}.30`;
+class GeneralSubtree {
+ constructor(params = {}) {
+ this.base = new general_name_GeneralName();
+ this.minimum = 0;
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: general_name_GeneralName })
+], GeneralSubtree.prototype, "base", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, context: 0, defaultValue: 0, implicit: true })
+], GeneralSubtree.prototype, "minimum", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, context: 1, optional: true, implicit: true })
+], GeneralSubtree.prototype, "maximum", void 0);
+let GeneralSubtrees = GeneralSubtrees_1 = class GeneralSubtrees extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, GeneralSubtrees_1.prototype);
+ }
+};
+GeneralSubtrees = GeneralSubtrees_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: GeneralSubtree })
+], GeneralSubtrees);
+
+class NameConstraints {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: GeneralSubtrees, context: 0, optional: true, implicit: true })
+], NameConstraints.prototype, "permittedSubtrees", void 0);
+__decorate([
+ AsnProp({ type: GeneralSubtrees, context: 1, optional: true, implicit: true })
+], NameConstraints.prototype, "excludedSubtrees", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/policy_constraints.js
+
+
+
+const id_ce_policyConstraints = `${id_ce}.36`;
+class PolicyConstraints {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.Integer, context: 0, implicit: true, optional: true,
+ converter: AsnIntegerArrayBufferConverter,
+ })
+], PolicyConstraints.prototype, "requireExplicitPolicy", void 0);
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.Integer, context: 1, implicit: true, optional: true,
+ converter: AsnIntegerArrayBufferConverter,
+ })
+], PolicyConstraints.prototype, "inhibitPolicyMapping", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/policy_mappings.js
+var PolicyMappings_1;
+
+
+
+const id_ce_policyMappings = `${id_ce}.33`;
+class PolicyMapping {
+ constructor(params = {}) {
+ this.issuerDomainPolicy = "";
+ this.subjectDomainPolicy = "";
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], PolicyMapping.prototype, "issuerDomainPolicy", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], PolicyMapping.prototype, "subjectDomainPolicy", void 0);
+let PolicyMappings = PolicyMappings_1 = class PolicyMappings extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, PolicyMappings_1.prototype);
+ }
+};
+PolicyMappings = PolicyMappings_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: PolicyMapping })
+], PolicyMappings);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/subject_alternative_name.js
+var SubjectAlternativeName_1;
+
+
+
+
+const id_ce_subjectAltName = `${id_ce}.17`;
+let SubjectAlternativeName = SubjectAlternativeName_1 = class SubjectAlternativeName extends general_names_GeneralNames {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, SubjectAlternativeName_1.prototype);
+ }
+};
+SubjectAlternativeName = SubjectAlternativeName_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], SubjectAlternativeName);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/attribute.js
+
+
+class attribute_Attribute {
+ constructor(params = {}) {
+ this.type = "";
+ this.values = [];
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], attribute_Attribute.prototype, "type", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, repeated: "set" })
+], attribute_Attribute.prototype, "values", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/subject_directory_attributes.js
+var SubjectDirectoryAttributes_1;
+
+
+
+
+const id_ce_subjectDirectoryAttributes = `${id_ce}.9`;
+let SubjectDirectoryAttributes = SubjectDirectoryAttributes_1 = class SubjectDirectoryAttributes extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, SubjectDirectoryAttributes_1.prototype);
+ }
+};
+SubjectDirectoryAttributes = SubjectDirectoryAttributes_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: attribute_Attribute })
+], SubjectDirectoryAttributes);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/subject_key_identifier.js
+
+
+const id_ce_subjectKeyIdentifier = `${id_ce}.14`;
+class SubjectKeyIdentifier extends KeyIdentifier {
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/private_key_usage_period.js
+
+
+
+const id_ce_privateKeyUsagePeriod = `${id_ce}.16`;
+class PrivateKeyUsagePeriod {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.GeneralizedTime, context: 0, implicit: true, optional: true })
+], PrivateKeyUsagePeriod.prototype, "notBefore", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.GeneralizedTime, context: 1, implicit: true, optional: true, })
+], PrivateKeyUsagePeriod.prototype, "notAfter", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/entrust_version_info.js
+
+
+const id_entrust_entrustVersInfo = "1.2.840.113533.7.65.0";
+var EntrustInfoFlags;
+(function (EntrustInfoFlags) {
+ EntrustInfoFlags[EntrustInfoFlags["keyUpdateAllowed"] = 1] = "keyUpdateAllowed";
+ EntrustInfoFlags[EntrustInfoFlags["newExtensions"] = 2] = "newExtensions";
+ EntrustInfoFlags[EntrustInfoFlags["pKIXCertificate"] = 4] = "pKIXCertificate";
+})(EntrustInfoFlags || (EntrustInfoFlags = {}));
+class EntrustInfo extends BitString {
+ toJSON() {
+ const res = [];
+ const flags = this.toNumber();
+ if (flags & EntrustInfoFlags.pKIXCertificate) {
+ res.push("pKIXCertificate");
+ }
+ if (flags & EntrustInfoFlags.newExtensions) {
+ res.push("newExtensions");
+ }
+ if (flags & EntrustInfoFlags.keyUpdateAllowed) {
+ res.push("keyUpdateAllowed");
+ }
+ return res;
+ }
+ toString() {
+ return `[${this.toJSON().join(", ")}]`;
+ }
+}
+class EntrustVersionInfo {
+ constructor(params = {}) {
+ this.entrustVers = '';
+ this.entrustInfoFlags = new EntrustInfo();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.GeneralString })
+], EntrustVersionInfo.prototype, "entrustVers", void 0);
+__decorate([
+ AsnProp({ type: EntrustInfo })
+], EntrustVersionInfo.prototype, "entrustInfoFlags", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/subject_info_access.js
+var SubjectInfoAccessSyntax_1;
+
+
+
+
+const id_pe_subjectInfoAccess = `${id_pe}.11`;
+let SubjectInfoAccessSyntax = SubjectInfoAccessSyntax_1 = class SubjectInfoAccessSyntax extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, SubjectInfoAccessSyntax_1.prototype);
+ }
+};
+SubjectInfoAccessSyntax = SubjectInfoAccessSyntax_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: AccessDescription })
+], SubjectInfoAccessSyntax);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extensions/index.js
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/algorithm_identifier.js
+
+
+
+class AlgorithmIdentifier {
+ constructor(params = {}) {
+ this.algorithm = "";
+ Object.assign(this, params);
+ }
+ isEqual(data) {
+ return data instanceof AlgorithmIdentifier
+ && data.algorithm == this.algorithm
+ && ((data.parameters && this.parameters
+ && build/* isEqual */.Xy(data.parameters, this.parameters))
+ ||
+ (data.parameters === this.parameters));
+ }
+}
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.ObjectIdentifier,
+ })
+], AlgorithmIdentifier.prototype, "algorithm", void 0);
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.Any,
+ optional: true,
+ })
+], AlgorithmIdentifier.prototype, "parameters", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/subject_public_key_info.js
+
+
+
+class subject_public_key_info_SubjectPublicKeyInfo {
+ constructor(params = {}) {
+ this.algorithm = new AlgorithmIdentifier();
+ this.subjectPublicKey = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], subject_public_key_info_SubjectPublicKeyInfo.prototype, "algorithm", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString })
+], subject_public_key_info_SubjectPublicKeyInfo.prototype, "subjectPublicKey", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/time.js
+
+
+let time_Time = class Time {
+ constructor(time) {
+ if (time) {
+ if (typeof time === "string" || typeof time === "number" || time instanceof Date) {
+ const date = new Date(time);
+ if (date.getUTCFullYear() > 2049) {
+ this.generalTime = date;
+ }
+ else {
+ this.utcTime = date;
+ }
+ }
+ else {
+ Object.assign(this, time);
+ }
+ }
+ }
+ getTime() {
+ const time = this.utcTime || this.generalTime;
+ if (!time) {
+ throw new Error("Cannot get time from CHOICE object");
+ }
+ return time;
+ }
+};
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.UTCTime,
+ })
+], time_Time.prototype, "utcTime", void 0);
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.GeneralizedTime,
+ })
+], time_Time.prototype, "generalTime", void 0);
+time_Time = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], time_Time);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/validity.js
+
+
+
+class Validity {
+ constructor(params) {
+ this.notBefore = new time_Time(new Date());
+ this.notAfter = new time_Time(new Date());
+ if (params) {
+ this.notBefore = new time_Time(params.notBefore);
+ this.notAfter = new time_Time(params.notAfter);
+ }
+ }
+}
+__decorate([
+ AsnProp({ type: time_Time })
+], Validity.prototype, "notBefore", void 0);
+__decorate([
+ AsnProp({ type: time_Time })
+], Validity.prototype, "notAfter", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/extension.js
+var Extensions_1;
+
+
+class extension_Extension {
+ constructor(params = {}) {
+ this.extnID = "";
+ this.critical = extension_Extension.CRITICAL;
+ this.extnValue = new octet_string_OctetString();
+ Object.assign(this, params);
+ }
+}
+extension_Extension.CRITICAL = false;
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], extension_Extension.prototype, "extnID", void 0);
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.Boolean,
+ defaultValue: extension_Extension.CRITICAL,
+ })
+], extension_Extension.prototype, "critical", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], extension_Extension.prototype, "extnValue", void 0);
+let extension_Extensions = Extensions_1 = class Extensions extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, Extensions_1.prototype);
+ }
+};
+extension_Extensions = Extensions_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: extension_Extension })
+], extension_Extensions);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/types.js
+var Version;
+(function (Version) {
+ Version[Version["v1"] = 0] = "v1";
+ Version[Version["v2"] = 1] = "v2";
+ Version[Version["v3"] = 2] = "v3";
+})(Version || (Version = {}));
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/tbs_certificate.js
+
+
+
+
+
+
+
+
+class TBSCertificate {
+ constructor(params = {}) {
+ this.version = Version.v1;
+ this.serialNumber = new ArrayBuffer(0);
+ this.signature = new AlgorithmIdentifier();
+ this.issuer = new name_Name();
+ this.validity = new Validity();
+ this.subject = new name_Name();
+ this.subjectPublicKeyInfo = new subject_public_key_info_SubjectPublicKeyInfo();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.Integer,
+ context: 0,
+ defaultValue: Version.v1,
+ })
+], TBSCertificate.prototype, "version", void 0);
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.Integer,
+ converter: AsnIntegerArrayBufferConverter,
+ })
+], TBSCertificate.prototype, "serialNumber", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], TBSCertificate.prototype, "signature", void 0);
+__decorate([
+ AsnProp({ type: name_Name })
+], TBSCertificate.prototype, "issuer", void 0);
+__decorate([
+ AsnProp({ type: Validity })
+], TBSCertificate.prototype, "validity", void 0);
+__decorate([
+ AsnProp({ type: name_Name })
+], TBSCertificate.prototype, "subject", void 0);
+__decorate([
+ AsnProp({ type: subject_public_key_info_SubjectPublicKeyInfo })
+], TBSCertificate.prototype, "subjectPublicKeyInfo", void 0);
+__decorate([
+ AsnProp({
+ type: AsnPropTypes.BitString,
+ context: 1,
+ implicit: true,
+ optional: true,
+ })
+], TBSCertificate.prototype, "issuerUniqueID", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString, context: 2, implicit: true, optional: true })
+], TBSCertificate.prototype, "subjectUniqueID", void 0);
+__decorate([
+ AsnProp({ type: extension_Extensions, context: 3, optional: true })
+], TBSCertificate.prototype, "extensions", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/certificate.js
+
+
+
+
+class certificate_Certificate {
+ constructor(params = {}) {
+ this.tbsCertificate = new TBSCertificate();
+ this.signatureAlgorithm = new AlgorithmIdentifier();
+ this.signatureValue = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: TBSCertificate })
+], certificate_Certificate.prototype, "tbsCertificate", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], certificate_Certificate.prototype, "signatureAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString })
+], certificate_Certificate.prototype, "signatureValue", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/tbs_cert_list.js
+
+
+
+
+
+
+class tbs_cert_list_RevokedCertificate {
+ constructor(params = {}) {
+ this.userCertificate = new ArrayBuffer(0);
+ this.revocationDate = new time_Time();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], tbs_cert_list_RevokedCertificate.prototype, "userCertificate", void 0);
+__decorate([
+ AsnProp({ type: time_Time })
+], tbs_cert_list_RevokedCertificate.prototype, "revocationDate", void 0);
+__decorate([
+ AsnProp({ type: extension_Extension, optional: true, repeated: "sequence" })
+], tbs_cert_list_RevokedCertificate.prototype, "crlEntryExtensions", void 0);
+class TBSCertList {
+ constructor(params = {}) {
+ this.signature = new AlgorithmIdentifier();
+ this.issuer = new name_Name();
+ this.thisUpdate = new time_Time();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, optional: true })
+], TBSCertList.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], TBSCertList.prototype, "signature", void 0);
+__decorate([
+ AsnProp({ type: name_Name })
+], TBSCertList.prototype, "issuer", void 0);
+__decorate([
+ AsnProp({ type: time_Time })
+], TBSCertList.prototype, "thisUpdate", void 0);
+__decorate([
+ AsnProp({ type: time_Time, optional: true })
+], TBSCertList.prototype, "nextUpdate", void 0);
+__decorate([
+ AsnProp({ type: tbs_cert_list_RevokedCertificate, repeated: "sequence", optional: true })
+], TBSCertList.prototype, "revokedCertificates", void 0);
+__decorate([
+ AsnProp({ type: extension_Extension, optional: true, context: 0, repeated: "sequence" })
+], TBSCertList.prototype, "crlExtensions", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/certificate_list.js
+
+
+
+
+class certificate_list_CertificateList {
+ constructor(params = {}) {
+ this.tbsCertList = new TBSCertList();
+ this.signatureAlgorithm = new AlgorithmIdentifier();
+ this.signature = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: TBSCertList })
+], certificate_list_CertificateList.prototype, "tbsCertList", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], certificate_list_CertificateList.prototype, "signatureAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString })
+], certificate_list_CertificateList.prototype, "signature", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509/build/es2015/index.js
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/attribute.js
+
+
+class Attribute {
+ constructor(params = {}) {
+ this.attrType = "";
+ this.attrValues = [];
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], Attribute.prototype, "attrType", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, repeated: "set" })
+], Attribute.prototype, "attrValues", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/aa_clear_attrs.js
+
+
+
+class ACClearAttrs {
+ constructor(params = {}) {
+ this.acIssuer = new general_name_GeneralName();
+ this.acSerial = 0;
+ this.attrs = [];
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: general_name_GeneralName })
+], ACClearAttrs.prototype, "acIssuer", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], ACClearAttrs.prototype, "acSerial", void 0);
+__decorate([
+ AsnProp({ type: attribute_Attribute, repeated: "sequence" })
+], ACClearAttrs.prototype, "attrs", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/attr_spec.js
+var AttrSpec_1;
+
+
+let AttrSpec = AttrSpec_1 = class AttrSpec extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, AttrSpec_1.prototype);
+ }
+};
+AttrSpec = AttrSpec_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: AsnPropTypes.ObjectIdentifier })
+], AttrSpec);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/aa_controls.js
+
+
+
+class AAControls {
+ constructor(params = {}) {
+ this.permitUnSpecified = true;
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, optional: true })
+], AAControls.prototype, "pathLenConstraint", void 0);
+__decorate([
+ AsnProp({ type: AttrSpec, implicit: true, context: 0, optional: true })
+], AAControls.prototype, "permittedAttrs", void 0);
+__decorate([
+ AsnProp({ type: AttrSpec, implicit: true, context: 1, optional: true })
+], AAControls.prototype, "excludedAttrs", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Boolean, defaultValue: true })
+], AAControls.prototype, "permitUnSpecified", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/issuer_serial.js
+
+
+
+class IssuerSerial {
+ constructor(params = {}) {
+ this.issuer = new general_names_GeneralNames();
+ this.serial = new ArrayBuffer(0);
+ this.issuerUID = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: general_names_GeneralNames })
+], IssuerSerial.prototype, "issuer", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], IssuerSerial.prototype, "serial", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString, optional: true })
+], IssuerSerial.prototype, "issuerUID", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/object_digest_info.js
+
+
+
+var DigestedObjectType;
+(function (DigestedObjectType) {
+ DigestedObjectType[DigestedObjectType["publicKey"] = 0] = "publicKey";
+ DigestedObjectType[DigestedObjectType["publicKeyCert"] = 1] = "publicKeyCert";
+ DigestedObjectType[DigestedObjectType["otherObjectTypes"] = 2] = "otherObjectTypes";
+})(DigestedObjectType || (DigestedObjectType = {}));
+class ObjectDigestInfo {
+ constructor(params = {}) {
+ this.digestedObjectType = DigestedObjectType.publicKey;
+ this.digestAlgorithm = new AlgorithmIdentifier();
+ this.objectDigest = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Enumerated })
+], ObjectDigestInfo.prototype, "digestedObjectType", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier, optional: true })
+], ObjectDigestInfo.prototype, "otherObjectTypeID", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], ObjectDigestInfo.prototype, "digestAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString })
+], ObjectDigestInfo.prototype, "objectDigest", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/v2_form.js
+
+
+
+
+
+class V2Form {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: general_names_GeneralNames, optional: true })
+], V2Form.prototype, "issuerName", void 0);
+__decorate([
+ AsnProp({ type: IssuerSerial, context: 0, implicit: true, optional: true })
+], V2Form.prototype, "baseCertificateID", void 0);
+__decorate([
+ AsnProp({ type: ObjectDigestInfo, context: 1, implicit: true, optional: true })
+], V2Form.prototype, "objectDigestInfo", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/attr_cert_issuer.js
+
+
+
+
+let AttCertIssuer = class AttCertIssuer {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: general_name_GeneralName, repeated: "sequence" })
+], AttCertIssuer.prototype, "v1Form", void 0);
+__decorate([
+ AsnProp({ type: V2Form, context: 0, implicit: true })
+], AttCertIssuer.prototype, "v2Form", void 0);
+AttCertIssuer = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], AttCertIssuer);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/attr_cert_validity_period.js
+
+
+class AttCertValidityPeriod {
+ constructor(params = {}) {
+ this.notBeforeTime = new Date();
+ this.notAfterTime = new Date();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.GeneralizedTime })
+], AttCertValidityPeriod.prototype, "notBeforeTime", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.GeneralizedTime })
+], AttCertValidityPeriod.prototype, "notAfterTime", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/holder.js
+
+
+
+
+
+class Holder {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: IssuerSerial, implicit: true, context: 0, optional: true })
+], Holder.prototype, "baseCertificateID", void 0);
+__decorate([
+ AsnProp({ type: general_names_GeneralNames, implicit: true, context: 1, optional: true })
+], Holder.prototype, "entityName", void 0);
+__decorate([
+ AsnProp({ type: ObjectDigestInfo, implicit: true, context: 2, optional: true })
+], Holder.prototype, "objectDigestInfo", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/attribute_certificate_info.js
+
+
+
+
+
+
+var AttCertVersion;
+(function (AttCertVersion) {
+ AttCertVersion[AttCertVersion["v2"] = 1] = "v2";
+})(AttCertVersion || (AttCertVersion = {}));
+class AttributeCertificateInfo {
+ constructor(params = {}) {
+ this.version = AttCertVersion.v2;
+ this.holder = new Holder();
+ this.issuer = new AttCertIssuer();
+ this.signature = new AlgorithmIdentifier();
+ this.serialNumber = new ArrayBuffer(0);
+ this.attrCertValidityPeriod = new AttCertValidityPeriod();
+ this.attributes = [];
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], AttributeCertificateInfo.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: Holder })
+], AttributeCertificateInfo.prototype, "holder", void 0);
+__decorate([
+ AsnProp({ type: AttCertIssuer })
+], AttributeCertificateInfo.prototype, "issuer", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], AttributeCertificateInfo.prototype, "signature", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], AttributeCertificateInfo.prototype, "serialNumber", void 0);
+__decorate([
+ AsnProp({ type: AttCertValidityPeriod })
+], AttributeCertificateInfo.prototype, "attrCertValidityPeriod", void 0);
+__decorate([
+ AsnProp({ type: attribute_Attribute, repeated: "sequence" })
+], AttributeCertificateInfo.prototype, "attributes", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString, optional: true })
+], AttributeCertificateInfo.prototype, "issuerUniqueID", void 0);
+__decorate([
+ AsnProp({ type: extension_Extensions, optional: true })
+], AttributeCertificateInfo.prototype, "extensions", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/attribute_certificate.js
+
+
+
+
+class AttributeCertificate {
+ constructor(params = {}) {
+ this.acinfo = new AttributeCertificateInfo();
+ this.signatureAlgorithm = new AlgorithmIdentifier();
+ this.signatureValue = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AttributeCertificateInfo })
+], AttributeCertificate.prototype, "acinfo", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], AttributeCertificate.prototype, "signatureAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString })
+], AttributeCertificate.prototype, "signatureValue", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/class_list.js
+
+var ClassListFlags;
+(function (ClassListFlags) {
+ ClassListFlags[ClassListFlags["unmarked"] = 1] = "unmarked";
+ ClassListFlags[ClassListFlags["unclassified"] = 2] = "unclassified";
+ ClassListFlags[ClassListFlags["restricted"] = 4] = "restricted";
+ ClassListFlags[ClassListFlags["confidential"] = 8] = "confidential";
+ ClassListFlags[ClassListFlags["secret"] = 16] = "secret";
+ ClassListFlags[ClassListFlags["topSecret"] = 32] = "topSecret";
+})(ClassListFlags || (ClassListFlags = {}));
+class ClassList extends BitString {
+}
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/security_category.js
+
+
+class SecurityCategory {
+ constructor(params = {}) {
+ this.type = "";
+ this.value = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier, implicit: true, context: 0 })
+], SecurityCategory.prototype, "type", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, implicit: true, context: 1 })
+], SecurityCategory.prototype, "value", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/clearance.js
+
+
+
+
+class Clearance {
+ constructor(params = {}) {
+ this.policyId = "";
+ this.classList = new ClassList(ClassListFlags.unclassified);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], Clearance.prototype, "policyId", void 0);
+__decorate([
+ AsnProp({ type: ClassList, defaultValue: new ClassList(ClassListFlags.unclassified) })
+], Clearance.prototype, "classList", void 0);
+__decorate([
+ AsnProp({ type: SecurityCategory, repeated: "set" })
+], Clearance.prototype, "securityCategories", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/ietf_attr_syntax.js
+
+
+
+class IetfAttrSyntaxValueChoices {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], IetfAttrSyntaxValueChoices.prototype, "cotets", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], IetfAttrSyntaxValueChoices.prototype, "oid", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Utf8String })
+], IetfAttrSyntaxValueChoices.prototype, "string", void 0);
+class IetfAttrSyntax {
+ constructor(params = {}) {
+ this.values = [];
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: general_names_GeneralNames, implicit: true, context: 0, optional: true })
+], IetfAttrSyntax.prototype, "policyAuthority", void 0);
+__decorate([
+ AsnProp({ type: IetfAttrSyntaxValueChoices, repeated: "sequence" })
+], IetfAttrSyntax.prototype, "values", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/object_identifiers.js
+
+const id_pe_ac_auditIdentity = `${id_pe}.4`;
+const id_pe_aaControls = `${id_pe}.6`;
+const id_pe_ac_proxying = `${id_pe}.10`;
+const id_ce_targetInformation = `${id_ce}.55`;
+const id_aca = `${id_pkix}.10`;
+const id_aca_authenticationInfo = `${id_aca}.1`;
+const id_aca_accessIdentity = `${id_aca}.2`;
+const id_aca_chargingIdentity = `${id_aca}.3`;
+const id_aca_group = `${id_aca}.4`;
+const id_aca_encAttrs = `${id_aca}.6`;
+const id_at = "2.5.4";
+const id_at_role = `${id_at}.72`;
+const id_at_clearance = "2.5.1.5.55";
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/target.js
+var Targets_1;
+
+
+
+
+
+class TargetCert {
+ constructor(params = {}) {
+ this.targetCertificate = new IssuerSerial();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: IssuerSerial })
+], TargetCert.prototype, "targetCertificate", void 0);
+__decorate([
+ AsnProp({ type: general_name_GeneralName, optional: true })
+], TargetCert.prototype, "targetName", void 0);
+__decorate([
+ AsnProp({ type: ObjectDigestInfo, optional: true })
+], TargetCert.prototype, "certDigestInfo", void 0);
+let Target = class Target {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: general_name_GeneralName, context: 0, implicit: true })
+], Target.prototype, "targetName", void 0);
+__decorate([
+ AsnProp({ type: general_name_GeneralName, context: 1, implicit: true })
+], Target.prototype, "targetGroup", void 0);
+__decorate([
+ AsnProp({ type: TargetCert, context: 2, implicit: true })
+], Target.prototype, "targetCert", void 0);
+Target = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], Target);
+
+let Targets = Targets_1 = class Targets extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, Targets_1.prototype);
+ }
+};
+Targets = Targets_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: Target })
+], Targets);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/proxy_info.js
+var ProxyInfo_1;
+
+
+
+let ProxyInfo = ProxyInfo_1 = class ProxyInfo extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, ProxyInfo_1.prototype);
+ }
+};
+ProxyInfo = ProxyInfo_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: Targets })
+], ProxyInfo);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/role_syntax.js
+
+
+
+class RoleSyntax {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: general_names_GeneralNames, implicit: true, context: 0, optional: true })
+], RoleSyntax.prototype, "roleAuthority", void 0);
+__decorate([
+ AsnProp({ type: general_name_GeneralName, implicit: true, context: 1 })
+], RoleSyntax.prototype, "roleName", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/svce_auth_info.js
+
+
+
+class SvceAuthInfo {
+ constructor(params = {}) {
+ this.service = new general_name_GeneralName();
+ this.ident = new general_name_GeneralName();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: general_name_GeneralName })
+], SvceAuthInfo.prototype, "service", void 0);
+__decorate([
+ AsnProp({ type: general_name_GeneralName })
+], SvceAuthInfo.prototype, "ident", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString, optional: true })
+], SvceAuthInfo.prototype, "authInfo", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-x509-attr/build/es2015/index.js
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/certificate_choices.js
+var CertificateSet_1;
+
+
+
+
+class OtherCertificateFormat {
+ constructor(params = {}) {
+ this.otherCertFormat = "";
+ this.otherCert = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], OtherCertificateFormat.prototype, "otherCertFormat", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any })
+], OtherCertificateFormat.prototype, "otherCert", void 0);
+let CertificateChoices = class CertificateChoices {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: certificate_Certificate })
+], CertificateChoices.prototype, "certificate", void 0);
+__decorate([
+ AsnProp({ type: AttributeCertificate, context: 2, implicit: true })
+], CertificateChoices.prototype, "v2AttrCert", void 0);
+__decorate([
+ AsnProp({ type: OtherCertificateFormat, context: 3, implicit: true })
+], CertificateChoices.prototype, "other", void 0);
+CertificateChoices = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], CertificateChoices);
+
+let CertificateSet = CertificateSet_1 = class CertificateSet extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, CertificateSet_1.prototype);
+ }
+};
+CertificateSet = CertificateSet_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Set, itemType: CertificateChoices })
+], CertificateSet);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/content_info.js
+
+
+class ContentInfo {
+ constructor(params = {}) {
+ this.contentType = "";
+ this.content = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], ContentInfo.prototype, "contentType", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, context: 0 })
+], ContentInfo.prototype, "content", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/encapsulated_content_info.js
+
+
+let EncapsulatedContent = class EncapsulatedContent {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], EncapsulatedContent.prototype, "single", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any })
+], EncapsulatedContent.prototype, "any", void 0);
+EncapsulatedContent = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], EncapsulatedContent);
+
+class EncapsulatedContentInfo {
+ constructor(params = {}) {
+ this.eContentType = "";
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], EncapsulatedContentInfo.prototype, "eContentType", void 0);
+__decorate([
+ AsnProp({ type: EncapsulatedContent, context: 0, optional: true })
+], EncapsulatedContentInfo.prototype, "eContent", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/types.js
+
+
+
+var CMSVersion;
+(function (CMSVersion) {
+ CMSVersion[CMSVersion["v0"] = 0] = "v0";
+ CMSVersion[CMSVersion["v1"] = 1] = "v1";
+ CMSVersion[CMSVersion["v2"] = 2] = "v2";
+ CMSVersion[CMSVersion["v3"] = 3] = "v3";
+ CMSVersion[CMSVersion["v4"] = 4] = "v4";
+ CMSVersion[CMSVersion["v5"] = 5] = "v5";
+})(CMSVersion || (CMSVersion = {}));
+let DigestAlgorithmIdentifier = class DigestAlgorithmIdentifier extends AlgorithmIdentifier {
+};
+DigestAlgorithmIdentifier = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], DigestAlgorithmIdentifier);
+
+let SignatureAlgorithmIdentifier = class SignatureAlgorithmIdentifier extends AlgorithmIdentifier {
+};
+SignatureAlgorithmIdentifier = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], SignatureAlgorithmIdentifier);
+
+let KeyEncryptionAlgorithmIdentifier = class KeyEncryptionAlgorithmIdentifier extends AlgorithmIdentifier {
+};
+KeyEncryptionAlgorithmIdentifier = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], KeyEncryptionAlgorithmIdentifier);
+
+let ContentEncryptionAlgorithmIdentifier = class ContentEncryptionAlgorithmIdentifier extends AlgorithmIdentifier {
+};
+ContentEncryptionAlgorithmIdentifier = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], ContentEncryptionAlgorithmIdentifier);
+
+let MessageAuthenticationCodeAlgorithm = class MessageAuthenticationCodeAlgorithm extends AlgorithmIdentifier {
+};
+MessageAuthenticationCodeAlgorithm = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], MessageAuthenticationCodeAlgorithm);
+
+let KeyDerivationAlgorithmIdentifier = class KeyDerivationAlgorithmIdentifier extends AlgorithmIdentifier {
+};
+KeyDerivationAlgorithmIdentifier = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], KeyDerivationAlgorithmIdentifier);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/encrypted_content_info.js
+
+
+
+let EncryptedContent = class EncryptedContent {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: octet_string_OctetString, context: 0, implicit: true, optional: true })
+], EncryptedContent.prototype, "value", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString, converter: AsnConstructedOctetStringConverter, context: 0, implicit: true, optional: true, repeated: "sequence" })
+], EncryptedContent.prototype, "constructedValue", void 0);
+EncryptedContent = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], EncryptedContent);
+
+class EncryptedContentInfo {
+ constructor(params = {}) {
+ this.contentType = "";
+ this.contentEncryptionAlgorithm = new ContentEncryptionAlgorithmIdentifier();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], EncryptedContentInfo.prototype, "contentType", void 0);
+__decorate([
+ AsnProp({ type: ContentEncryptionAlgorithmIdentifier })
+], EncryptedContentInfo.prototype, "contentEncryptionAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: EncryptedContent, optional: true })
+], EncryptedContentInfo.prototype, "encryptedContent", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/issuer_and_serial_number.js
+
+
+
+class IssuerAndSerialNumber {
+ constructor(params = {}) {
+ this.issuer = new name_Name;
+ this.serialNumber = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: name_Name })
+], IssuerAndSerialNumber.prototype, "issuer", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], IssuerAndSerialNumber.prototype, "serialNumber", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/other_key_attribute.js
+
+
+class OtherKeyAttribute {
+ constructor(params = {}) {
+ this.keyAttrId = "";
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], OtherKeyAttribute.prototype, "keyAttrId", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, optional: true })
+], OtherKeyAttribute.prototype, "keyAttr", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/key_agree_recipient_info.js
+var RecipientEncryptedKeys_1;
+
+
+
+
+
+
+class RecipientKeyIdentifier {
+ constructor(params = {}) {
+ this.subjectKeyIdentifier = new SubjectKeyIdentifier();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: SubjectKeyIdentifier })
+], RecipientKeyIdentifier.prototype, "subjectKeyIdentifier", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.GeneralizedTime, optional: true })
+], RecipientKeyIdentifier.prototype, "date", void 0);
+__decorate([
+ AsnProp({ type: OtherKeyAttribute, optional: true })
+], RecipientKeyIdentifier.prototype, "other", void 0);
+let KeyAgreeRecipientIdentifier = class KeyAgreeRecipientIdentifier {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: RecipientKeyIdentifier, context: 0, implicit: true, optional: true })
+], KeyAgreeRecipientIdentifier.prototype, "rKeyId", void 0);
+__decorate([
+ AsnProp({ type: IssuerAndSerialNumber, optional: true })
+], KeyAgreeRecipientIdentifier.prototype, "issuerAndSerialNumber", void 0);
+KeyAgreeRecipientIdentifier = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], KeyAgreeRecipientIdentifier);
+
+class RecipientEncryptedKey {
+ constructor(params = {}) {
+ this.rid = new KeyAgreeRecipientIdentifier();
+ this.encryptedKey = new octet_string_OctetString();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: KeyAgreeRecipientIdentifier })
+], RecipientEncryptedKey.prototype, "rid", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], RecipientEncryptedKey.prototype, "encryptedKey", void 0);
+let RecipientEncryptedKeys = RecipientEncryptedKeys_1 = class RecipientEncryptedKeys extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, RecipientEncryptedKeys_1.prototype);
+ }
+};
+RecipientEncryptedKeys = RecipientEncryptedKeys_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: RecipientEncryptedKey })
+], RecipientEncryptedKeys);
+
+class OriginatorPublicKey {
+ constructor(params = {}) {
+ this.algorithm = new AlgorithmIdentifier();
+ this.publicKey = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], OriginatorPublicKey.prototype, "algorithm", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString })
+], OriginatorPublicKey.prototype, "publicKey", void 0);
+let OriginatorIdentifierOrKey = class OriginatorIdentifierOrKey {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: SubjectKeyIdentifier, context: 0, implicit: true, optional: true })
+], OriginatorIdentifierOrKey.prototype, "subjectKeyIdentifier", void 0);
+__decorate([
+ AsnProp({ type: OriginatorPublicKey, context: 1, implicit: true, optional: true })
+], OriginatorIdentifierOrKey.prototype, "originatorKey", void 0);
+__decorate([
+ AsnProp({ type: IssuerAndSerialNumber, optional: true })
+], OriginatorIdentifierOrKey.prototype, "issuerAndSerialNumber", void 0);
+OriginatorIdentifierOrKey = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], OriginatorIdentifierOrKey);
+
+class KeyAgreeRecipientInfo {
+ constructor(params = {}) {
+ this.version = CMSVersion.v3;
+ this.originator = new OriginatorIdentifierOrKey();
+ this.keyEncryptionAlgorithm = new KeyEncryptionAlgorithmIdentifier();
+ this.recipientEncryptedKeys = new RecipientEncryptedKeys();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], KeyAgreeRecipientInfo.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: OriginatorIdentifierOrKey, context: 0 })
+], KeyAgreeRecipientInfo.prototype, "originator", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString, context: 1, optional: true })
+], KeyAgreeRecipientInfo.prototype, "ukm", void 0);
+__decorate([
+ AsnProp({ type: KeyEncryptionAlgorithmIdentifier })
+], KeyAgreeRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: RecipientEncryptedKeys })
+], KeyAgreeRecipientInfo.prototype, "recipientEncryptedKeys", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/key_trans_recipient_info.js
+
+
+
+
+
+let RecipientIdentifier = class RecipientIdentifier {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: SubjectKeyIdentifier, context: 0, implicit: true })
+], RecipientIdentifier.prototype, "subjectKeyIdentifier", void 0);
+__decorate([
+ AsnProp({ type: IssuerAndSerialNumber })
+], RecipientIdentifier.prototype, "issuerAndSerialNumber", void 0);
+RecipientIdentifier = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], RecipientIdentifier);
+
+class KeyTransRecipientInfo {
+ constructor(params = {}) {
+ this.version = CMSVersion.v0;
+ this.rid = new RecipientIdentifier();
+ this.keyEncryptionAlgorithm = new KeyEncryptionAlgorithmIdentifier();
+ this.encryptedKey = new octet_string_OctetString();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], KeyTransRecipientInfo.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: RecipientIdentifier })
+], KeyTransRecipientInfo.prototype, "rid", void 0);
+__decorate([
+ AsnProp({ type: KeyEncryptionAlgorithmIdentifier })
+], KeyTransRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], KeyTransRecipientInfo.prototype, "encryptedKey", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/kek_recipient_info.js
+
+
+
+
+class KEKIdentifier {
+ constructor(params = {}) {
+ this.keyIdentifier = new octet_string_OctetString();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], KEKIdentifier.prototype, "keyIdentifier", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.GeneralizedTime, optional: true })
+], KEKIdentifier.prototype, "date", void 0);
+__decorate([
+ AsnProp({ type: OtherKeyAttribute, optional: true })
+], KEKIdentifier.prototype, "other", void 0);
+class KEKRecipientInfo {
+ constructor(params = {}) {
+ this.version = CMSVersion.v4;
+ this.kekid = new KEKIdentifier();
+ this.keyEncryptionAlgorithm = new KeyEncryptionAlgorithmIdentifier();
+ this.encryptedKey = new octet_string_OctetString();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], KEKRecipientInfo.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: KEKIdentifier })
+], KEKRecipientInfo.prototype, "kekid", void 0);
+__decorate([
+ AsnProp({ type: KeyEncryptionAlgorithmIdentifier })
+], KEKRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], KEKRecipientInfo.prototype, "encryptedKey", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/password_recipient_info.js
+
+
+
+class PasswordRecipientInfo {
+ constructor(params = {}) {
+ this.version = CMSVersion.v0;
+ this.keyEncryptionAlgorithm = new KeyEncryptionAlgorithmIdentifier();
+ this.encryptedKey = new octet_string_OctetString();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], PasswordRecipientInfo.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: KeyDerivationAlgorithmIdentifier, context: 0, optional: true })
+], PasswordRecipientInfo.prototype, "keyDerivationAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: KeyEncryptionAlgorithmIdentifier })
+], PasswordRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], PasswordRecipientInfo.prototype, "encryptedKey", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/recipient_info.js
+
+
+
+
+
+
+class OtherRecipientInfo {
+ constructor(params = {}) {
+ this.oriType = "";
+ this.oriValue = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], OtherRecipientInfo.prototype, "oriType", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any })
+], OtherRecipientInfo.prototype, "oriValue", void 0);
+let RecipientInfo = class RecipientInfo {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: KeyTransRecipientInfo, optional: true })
+], RecipientInfo.prototype, "ktri", void 0);
+__decorate([
+ AsnProp({ type: KeyAgreeRecipientInfo, context: 1, implicit: true, optional: true })
+], RecipientInfo.prototype, "kari", void 0);
+__decorate([
+ AsnProp({ type: KEKRecipientInfo, context: 2, implicit: true, optional: true })
+], RecipientInfo.prototype, "kekri", void 0);
+__decorate([
+ AsnProp({ type: PasswordRecipientInfo, context: 3, implicit: true, optional: true })
+], RecipientInfo.prototype, "pwri", void 0);
+__decorate([
+ AsnProp({ type: OtherRecipientInfo, context: 4, implicit: true, optional: true })
+], RecipientInfo.prototype, "ori", void 0);
+RecipientInfo = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], RecipientInfo);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/recipient_infos.js
+var RecipientInfos_1;
+
+
+
+let RecipientInfos = RecipientInfos_1 = class RecipientInfos extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, RecipientInfos_1.prototype);
+ }
+};
+RecipientInfos = RecipientInfos_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Set, itemType: RecipientInfo })
+], RecipientInfos);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/revocation_info_choice.js
+var RevocationInfoChoices_1;
+
+
+
+const id_ri = `${id_pkix}.16`;
+const id_ri_ocsp_response = `${id_ri}.2`;
+const id_ri_scvp = `${id_ri}.4`;
+class OtherRevocationInfoFormat {
+ constructor(params = {}) {
+ this.otherRevInfoFormat = "";
+ this.otherRevInfo = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], OtherRevocationInfoFormat.prototype, "otherRevInfoFormat", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any })
+], OtherRevocationInfoFormat.prototype, "otherRevInfo", void 0);
+let RevocationInfoChoice = class RevocationInfoChoice {
+ constructor(params = {}) {
+ this.other = new OtherRevocationInfoFormat();
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: OtherRevocationInfoFormat, context: 1, implicit: true })
+], RevocationInfoChoice.prototype, "other", void 0);
+RevocationInfoChoice = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], RevocationInfoChoice);
+
+let RevocationInfoChoices = RevocationInfoChoices_1 = class RevocationInfoChoices extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, RevocationInfoChoices_1.prototype);
+ }
+};
+RevocationInfoChoices = RevocationInfoChoices_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Set, itemType: RevocationInfoChoice })
+], RevocationInfoChoices);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/originator_info.js
+
+
+
+
+class OriginatorInfo {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: CertificateSet, context: 0, implicit: true, optional: true })
+], OriginatorInfo.prototype, "certs", void 0);
+__decorate([
+ AsnProp({ type: RevocationInfoChoices, context: 1, implicit: true, optional: true })
+], OriginatorInfo.prototype, "crls", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/enveloped_data.js
+var UnprotectedAttributes_1;
+
+
+
+
+
+
+
+let UnprotectedAttributes = UnprotectedAttributes_1 = class UnprotectedAttributes extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, UnprotectedAttributes_1.prototype);
+ }
+};
+UnprotectedAttributes = UnprotectedAttributes_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Set, itemType: Attribute })
+], UnprotectedAttributes);
+
+class EnvelopedData {
+ constructor(params = {}) {
+ this.version = CMSVersion.v0;
+ this.recipientInfos = new RecipientInfos();
+ this.encryptedContentInfo = new EncryptedContentInfo();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], EnvelopedData.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: OriginatorInfo, context: 0, implicit: true, optional: true })
+], EnvelopedData.prototype, "originatorInfo", void 0);
+__decorate([
+ AsnProp({ type: RecipientInfos })
+], EnvelopedData.prototype, "recipientInfos", void 0);
+__decorate([
+ AsnProp({ type: EncryptedContentInfo })
+], EnvelopedData.prototype, "encryptedContentInfo", void 0);
+__decorate([
+ AsnProp({ type: UnprotectedAttributes, context: 1, implicit: true, optional: true })
+], EnvelopedData.prototype, "unprotectedAttrs", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/object_identifiers.js
+const id_ct_contentInfo = "1.2.840.113549.1.9.16.1.6";
+const id_data = "1.2.840.113549.1.7.1";
+const id_signedData = "1.2.840.113549.1.7.2";
+const id_envelopedData = "1.2.840.113549.1.7.3";
+const id_digestedData = "1.2.840.113549.1.7.5";
+const id_encryptedData = "1.2.840.113549.1.7.6";
+const id_authData = "1.2.840.113549.1.9.16.1.2";
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/signer_identifier.js
+
+
+
+
+let SignerIdentifier = class SignerIdentifier {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: SubjectKeyIdentifier, context: 0, implicit: true })
+], SignerIdentifier.prototype, "subjectKeyIdentifier", void 0);
+__decorate([
+ AsnProp({ type: IssuerAndSerialNumber })
+], SignerIdentifier.prototype, "issuerAndSerialNumber", void 0);
+SignerIdentifier = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], SignerIdentifier);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/signer_info.js
+var SignerInfos_1;
+
+
+
+
+
+class SignerInfo {
+ constructor(params = {}) {
+ this.version = CMSVersion.v0;
+ this.sid = new SignerIdentifier();
+ this.digestAlgorithm = new DigestAlgorithmIdentifier();
+ this.signatureAlgorithm = new SignatureAlgorithmIdentifier();
+ this.signature = new octet_string_OctetString();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], SignerInfo.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: SignerIdentifier })
+], SignerInfo.prototype, "sid", void 0);
+__decorate([
+ AsnProp({ type: DigestAlgorithmIdentifier })
+], SignerInfo.prototype, "digestAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: Attribute, repeated: "set", context: 0, implicit: true, optional: true })
+], SignerInfo.prototype, "signedAttrs", void 0);
+__decorate([
+ AsnProp({ type: SignatureAlgorithmIdentifier })
+], SignerInfo.prototype, "signatureAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], SignerInfo.prototype, "signature", void 0);
+__decorate([
+ AsnProp({ type: Attribute, repeated: "set", context: 1, implicit: true, optional: true })
+], SignerInfo.prototype, "unsignedAttrs", void 0);
+let SignerInfos = SignerInfos_1 = class SignerInfos extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, SignerInfos_1.prototype);
+ }
+};
+SignerInfos = SignerInfos_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Set, itemType: SignerInfo })
+], SignerInfos);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/signed_data.js
+var DigestAlgorithmIdentifiers_1;
+
+
+
+
+
+
+
+let DigestAlgorithmIdentifiers = DigestAlgorithmIdentifiers_1 = class DigestAlgorithmIdentifiers extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, DigestAlgorithmIdentifiers_1.prototype);
+ }
+};
+DigestAlgorithmIdentifiers = DigestAlgorithmIdentifiers_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Set, itemType: DigestAlgorithmIdentifier })
+], DigestAlgorithmIdentifiers);
+
+class SignedData {
+ constructor(params = {}) {
+ this.version = CMSVersion.v0;
+ this.digestAlgorithms = new DigestAlgorithmIdentifiers();
+ this.encapContentInfo = new EncapsulatedContentInfo();
+ this.signerInfos = new SignerInfos();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], SignedData.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: DigestAlgorithmIdentifiers })
+], SignedData.prototype, "digestAlgorithms", void 0);
+__decorate([
+ AsnProp({ type: EncapsulatedContentInfo })
+], SignedData.prototype, "encapContentInfo", void 0);
+__decorate([
+ AsnProp({ type: CertificateSet, context: 0, implicit: true, optional: true })
+], SignedData.prototype, "certificates", void 0);
+__decorate([
+ AsnProp({ type: RevocationInfoChoice, context: 1, implicit: true, optional: true })
+], SignedData.prototype, "crls", void 0);
+__decorate([
+ AsnProp({ type: SignerInfos })
+], SignedData.prototype, "signerInfos", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-cms/build/es2015/index.js
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-ecc/build/es2015/object_identifiers.js
+const id_ecPublicKey = "1.2.840.10045.2.1";
+const id_ecDH = "1.3.132.1.12";
+const id_ecMQV = "1.3.132.1.13";
+const id_ecdsaWithSHA1 = "1.2.840.10045.4.1";
+const id_ecdsaWithSHA224 = "1.2.840.10045.4.3.1";
+const id_ecdsaWithSHA256 = "1.2.840.10045.4.3.2";
+const id_ecdsaWithSHA384 = "1.2.840.10045.4.3.3";
+const id_ecdsaWithSHA512 = "1.2.840.10045.4.3.4";
+const id_secp192r1 = "1.2.840.10045.3.1.1";
+const id_sect163k1 = "1.3.132.0.1";
+const id_sect163r2 = "1.3.132.0.15";
+const id_secp224r1 = "1.3.132.0.33";
+const id_sect233k1 = "1.3.132.0.26";
+const id_sect233r1 = "1.3.132.0.27";
+const id_secp256r1 = "1.2.840.10045.3.1.7";
+const id_sect283k1 = "1.3.132.0.16";
+const id_sect283r1 = "1.3.132.0.17";
+const id_secp384r1 = "1.3.132.0.34";
+const id_sect409k1 = "1.3.132.0.36";
+const id_sect409r1 = "1.3.132.0.37";
+const id_secp521r1 = "1.3.132.0.35";
+const id_sect571k1 = "1.3.132.0.38";
+const id_sect571r1 = "1.3.132.0.39";
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-ecc/build/es2015/algorithms.js
+
+
+function algorithms_create(algorithm) {
+ return new AlgorithmIdentifier({ algorithm });
+}
+const ecdsaWithSHA1 = algorithms_create(id_ecdsaWithSHA1);
+const ecdsaWithSHA224 = algorithms_create(id_ecdsaWithSHA224);
+const ecdsaWithSHA256 = algorithms_create(id_ecdsaWithSHA256);
+const ecdsaWithSHA384 = algorithms_create(id_ecdsaWithSHA384);
+const ecdsaWithSHA512 = algorithms_create(id_ecdsaWithSHA512);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-ecc/build/es2015/ec_parameters.js
+
+
+let ECParameters = class ECParameters {
+ constructor(params = {}) {
+ Object.assign(this, params);
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], ECParameters.prototype, "namedCurve", void 0);
+ECParameters = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], ECParameters);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-ecc/build/es2015/ec_private_key.js
+
+
+
+class ECPrivateKey {
+ constructor(params = {}) {
+ this.version = 1;
+ this.privateKey = new octet_string_OctetString();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], ECPrivateKey.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], ECPrivateKey.prototype, "privateKey", void 0);
+__decorate([
+ AsnProp({ type: ECParameters, context: 0, optional: true })
+], ECPrivateKey.prototype, "parameters", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString, context: 1, optional: true })
+], ECPrivateKey.prototype, "publicKey", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-ecc/build/es2015/ec_signature_value.js
+
+
+class ECDSASigValue {
+ constructor(params = {}) {
+ this.r = new ArrayBuffer(0);
+ this.s = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], ECDSASigValue.prototype, "r", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], ECDSASigValue.prototype, "s", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-ecc/build/es2015/index.js
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/object_identifiers.js
+const id_pkcs_1 = "1.2.840.113549.1.1";
+const id_rsaEncryption = `${id_pkcs_1}.1`;
+const id_RSAES_OAEP = `${id_pkcs_1}.7`;
+const id_pSpecified = `${id_pkcs_1}.9`;
+const id_RSASSA_PSS = `${id_pkcs_1}.10`;
+const id_md2WithRSAEncryption = `${id_pkcs_1}.2`;
+const id_md5WithRSAEncryption = `${id_pkcs_1}.4`;
+const id_sha1WithRSAEncryption = `${id_pkcs_1}.5`;
+const id_sha224WithRSAEncryption = `${id_pkcs_1}.14`;
+const id_ssha224WithRSAEncryption = (/* unused pure expression or super */ null && (id_sha224WithRSAEncryption));
+const id_sha256WithRSAEncryption = `${id_pkcs_1}.11`;
+const id_sha384WithRSAEncryption = `${id_pkcs_1}.12`;
+const id_sha512WithRSAEncryption = `${id_pkcs_1}.13`;
+const id_sha512_224WithRSAEncryption = `${id_pkcs_1}.15`;
+const id_sha512_256WithRSAEncryption = `${id_pkcs_1}.16`;
+const id_sha1 = "1.3.14.3.2.26";
+const id_sha224 = "2.16.840.1.101.3.4.2.4";
+const id_sha256 = "2.16.840.1.101.3.4.2.1";
+const id_sha384 = "2.16.840.1.101.3.4.2.2";
+const id_sha512 = "2.16.840.1.101.3.4.2.3";
+const id_sha512_224 = "2.16.840.1.101.3.4.2.5";
+const id_sha512_256 = "2.16.840.1.101.3.4.2.6";
+const id_md2 = "1.2.840.113549.2.2";
+const id_md5 = "1.2.840.113549.2.5";
+const id_mgf1 = `${id_pkcs_1}.8`;
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/algorithms.js
+
+
+
+function es2015_algorithms_create(algorithm) {
+ return new AlgorithmIdentifier({ algorithm, parameters: null });
+}
+const md2 = es2015_algorithms_create(id_md2);
+const algorithms_md4 = es2015_algorithms_create(id_md5);
+const algorithms_sha1 = es2015_algorithms_create(id_sha1);
+const algorithms_sha224 = es2015_algorithms_create(id_sha224);
+const algorithms_sha256 = es2015_algorithms_create(id_sha256);
+const algorithms_sha384 = es2015_algorithms_create(id_sha384);
+const algorithms_sha512 = es2015_algorithms_create(id_sha512);
+const sha512_224 = es2015_algorithms_create(id_sha512_224);
+const sha512_256 = es2015_algorithms_create(id_sha512_256);
+const mgf1SHA1 = new AlgorithmIdentifier({
+ algorithm: id_mgf1,
+ parameters: convert_AsnConvert.serialize(algorithms_sha1),
+});
+const pSpecifiedEmpty = new AlgorithmIdentifier({
+ algorithm: id_pSpecified,
+ parameters: convert_AsnConvert.serialize(AsnOctetStringConverter.toASN(new Uint8Array([0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09]).buffer)),
+});
+const rsaEncryption = es2015_algorithms_create(id_rsaEncryption);
+const md2WithRSAEncryption = es2015_algorithms_create(id_md2WithRSAEncryption);
+const md5WithRSAEncryption = es2015_algorithms_create(id_md5WithRSAEncryption);
+const sha1WithRSAEncryption = es2015_algorithms_create(id_sha1WithRSAEncryption);
+const sha224WithRSAEncryption = es2015_algorithms_create(id_sha512_224WithRSAEncryption);
+const sha256WithRSAEncryption = es2015_algorithms_create(id_sha512_256WithRSAEncryption);
+const sha384WithRSAEncryption = es2015_algorithms_create(id_sha384WithRSAEncryption);
+const sha512WithRSAEncryption = es2015_algorithms_create(id_sha512WithRSAEncryption);
+const sha512_224WithRSAEncryption = es2015_algorithms_create(id_sha512_224WithRSAEncryption);
+const sha512_256WithRSAEncryption = es2015_algorithms_create(id_sha512_256WithRSAEncryption);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/parameters/rsaes_oaep.js
+
+
+
+
+
+class RsaEsOaepParams {
+ constructor(params = {}) {
+ this.hashAlgorithm = new AlgorithmIdentifier(algorithms_sha1);
+ this.maskGenAlgorithm = new AlgorithmIdentifier({
+ algorithm: id_mgf1,
+ parameters: convert_AsnConvert.serialize(algorithms_sha1),
+ });
+ this.pSourceAlgorithm = new AlgorithmIdentifier(pSpecifiedEmpty);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier, context: 0, defaultValue: algorithms_sha1 })
+], RsaEsOaepParams.prototype, "hashAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier, context: 1, defaultValue: mgf1SHA1 })
+], RsaEsOaepParams.prototype, "maskGenAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier, context: 2, defaultValue: pSpecifiedEmpty })
+], RsaEsOaepParams.prototype, "pSourceAlgorithm", void 0);
+const RSAES_OAEP = new AlgorithmIdentifier({
+ algorithm: id_RSAES_OAEP,
+ parameters: convert_AsnConvert.serialize(new RsaEsOaepParams()),
+});
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/parameters/rsassa_pss.js
+
+
+
+
+
+class RsaSaPssParams {
+ constructor(params = {}) {
+ this.hashAlgorithm = new AlgorithmIdentifier(algorithms_sha1);
+ this.maskGenAlgorithm = new AlgorithmIdentifier({
+ algorithm: id_mgf1,
+ parameters: convert_AsnConvert.serialize(algorithms_sha1),
+ });
+ this.saltLength = 20;
+ this.trailerField = 1;
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier, context: 0, defaultValue: algorithms_sha1 })
+], RsaSaPssParams.prototype, "hashAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier, context: 1, defaultValue: mgf1SHA1 })
+], RsaSaPssParams.prototype, "maskGenAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, context: 2, defaultValue: 20 })
+], RsaSaPssParams.prototype, "saltLength", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, context: 3, defaultValue: 1 })
+], RsaSaPssParams.prototype, "trailerField", void 0);
+const RSASSA_PSS = new AlgorithmIdentifier({
+ algorithm: id_RSASSA_PSS,
+ parameters: convert_AsnConvert.serialize(new RsaSaPssParams()),
+});
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/parameters/rsassa_pkcs1_v1_5.js
+
+
+
+class DigestInfo {
+ constructor(params = {}) {
+ this.digestAlgorithm = new AlgorithmIdentifier();
+ this.digest = new octet_string_OctetString();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], DigestInfo.prototype, "digestAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], DigestInfo.prototype, "digest", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/parameters/index.js
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/other_prime_info.js
+var OtherPrimeInfos_1;
+
+
+class OtherPrimeInfo {
+ constructor(params = {}) {
+ this.prime = new ArrayBuffer(0);
+ this.exponent = new ArrayBuffer(0);
+ this.coefficient = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], OtherPrimeInfo.prototype, "prime", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], OtherPrimeInfo.prototype, "exponent", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], OtherPrimeInfo.prototype, "coefficient", void 0);
+let OtherPrimeInfos = OtherPrimeInfos_1 = class OtherPrimeInfos extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, OtherPrimeInfos_1.prototype);
+ }
+};
+OtherPrimeInfos = OtherPrimeInfos_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: OtherPrimeInfo })
+], OtherPrimeInfos);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/rsa_private_key.js
+
+
+
+class RSAPrivateKey {
+ constructor(params = {}) {
+ this.version = 0;
+ this.modulus = new ArrayBuffer(0);
+ this.publicExponent = new ArrayBuffer(0);
+ this.privateExponent = new ArrayBuffer(0);
+ this.prime1 = new ArrayBuffer(0);
+ this.prime2 = new ArrayBuffer(0);
+ this.exponent1 = new ArrayBuffer(0);
+ this.exponent2 = new ArrayBuffer(0);
+ this.coefficient = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], RSAPrivateKey.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPrivateKey.prototype, "modulus", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPrivateKey.prototype, "publicExponent", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPrivateKey.prototype, "privateExponent", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPrivateKey.prototype, "prime1", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPrivateKey.prototype, "prime2", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPrivateKey.prototype, "exponent1", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPrivateKey.prototype, "exponent2", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPrivateKey.prototype, "coefficient", void 0);
+__decorate([
+ AsnProp({ type: OtherPrimeInfos, optional: true })
+], RSAPrivateKey.prototype, "otherPrimeInfos", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/rsa_public_key.js
+
+
+class RSAPublicKey {
+ constructor(params = {}) {
+ this.modulus = new ArrayBuffer(0);
+ this.publicExponent = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPublicKey.prototype, "modulus", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, converter: AsnIntegerArrayBufferConverter })
+], RSAPublicKey.prototype, "publicExponent", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-rsa/build/es2015/index.js
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/types/lifecycle.js
+var Lifecycle;
+(function (Lifecycle) {
+ Lifecycle[Lifecycle["Transient"] = 0] = "Transient";
+ Lifecycle[Lifecycle["Singleton"] = 1] = "Singleton";
+ Lifecycle[Lifecycle["ResolutionScoped"] = 2] = "ResolutionScoped";
+ Lifecycle[Lifecycle["ContainerScoped"] = 3] = "ContainerScoped";
+})(Lifecycle || (Lifecycle = {}));
+/* harmony default export */ const lifecycle = (Lifecycle);
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/types/index.js
+
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/node_modules/tslib/tslib.es6.js
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global Reflect, Promise */
+
+var tslib_es6_extendStatics = function(d, b) {
+ tslib_es6_extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return tslib_es6_extendStatics(d, b);
+};
+
+function tslib_tslib_es6_extends(d, b) {
+ tslib_es6_extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+}
+
+var tslib_es6_assign = function() {
+ tslib_es6_assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ }
+ return tslib_es6_assign.apply(this, arguments);
+}
+
+function tslib_tslib_es6_rest(s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+}
+
+function tslib_es6_decorate(decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+}
+
+function tslib_es6_param(paramIndex, decorator) {
+ return function (target, key) { decorator(target, key, paramIndex); }
+}
+
+function tslib_es6_metadata(metadataKey, metadataValue) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+}
+
+function tslib_tslib_es6_awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+}
+
+function tslib_es6_generator(thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (_) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+}
+
+function tslib_es6_createBinding(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}
+
+function tslib_es6_exportStar(m, exports) {
+ for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
+}
+
+function tslib_es6_values(o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+}
+
+function tslib_es6_read(o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+}
+
+function tslib_tslib_es6_spread() {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(tslib_es6_read(arguments[i]));
+ return ar;
+}
+
+function tslib_es6_spreadArrays() {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
+};
+
+function tslib_es6_await(v) {
+ return this instanceof tslib_es6_await ? (this.v = v, this) : new tslib_es6_await(v);
+}
+
+function tslib_es6_asyncGenerator(thisArg, _arguments, generator) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof tslib_es6_await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+}
+
+function tslib_es6_asyncDelegator(o) {
+ var i, p;
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: tslib_es6_await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
+}
+
+function tslib_es6_asyncValues(o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof tslib_es6_values === "function" ? tslib_es6_values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+}
+
+function tslib_es6_makeTemplateObject(cooked, raw) {
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
+ return cooked;
+};
+
+function tslib_es6_importStar(mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
+ result.default = mod;
+ return result;
+}
+
+function tslib_es6_importDefault(mod) {
+ return (mod && mod.__esModule) ? mod : { default: mod };
+}
+
+function tslib_es6_classPrivateFieldGet(receiver, privateMap) {
+ if (!privateMap.has(receiver)) {
+ throw new TypeError("attempted to get private field on non-instance");
+ }
+ return privateMap.get(receiver);
+}
+
+function tslib_es6_classPrivateFieldSet(receiver, privateMap, value) {
+ if (!privateMap.has(receiver)) {
+ throw new TypeError("attempted to set private field on non-instance");
+ }
+ privateMap.set(receiver, value);
+ return value;
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/providers/class-provider.js
+function isClassProvider(provider) {
+ return !!provider.useClass;
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/providers/factory-provider.js
+function isFactoryProvider(provider) {
+ return !!provider.useFactory;
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/lazy-helpers.js
+
+var DelayedConstructor = (function () {
+ function DelayedConstructor(wrap) {
+ this.wrap = wrap;
+ this.reflectMethods = [
+ "get",
+ "getPrototypeOf",
+ "setPrototypeOf",
+ "getOwnPropertyDescriptor",
+ "defineProperty",
+ "has",
+ "set",
+ "deleteProperty",
+ "apply",
+ "construct",
+ "ownKeys"
+ ];
+ }
+ DelayedConstructor.prototype.createProxy = function (createObject) {
+ var _this = this;
+ var target = {};
+ var init = false;
+ var value;
+ var delayedObject = function () {
+ if (!init) {
+ value = createObject(_this.wrap());
+ init = true;
+ }
+ return value;
+ };
+ return new Proxy(target, this.createHandler(delayedObject));
+ };
+ DelayedConstructor.prototype.createHandler = function (delayedObject) {
+ var handler = {};
+ var install = function (name) {
+ handler[name] = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ args[0] = delayedObject();
+ var method = Reflect[name];
+ return method.apply(void 0, tslib_tslib_es6_spread(args));
+ };
+ };
+ this.reflectMethods.forEach(install);
+ return handler;
+ };
+ return DelayedConstructor;
+}());
+
+function delay(wrappedConstructor) {
+ if (typeof wrappedConstructor === "undefined") {
+ throw new Error("Attempt to `delay` undefined. Constructor must be wrapped in a callback");
+ }
+ return new DelayedConstructor(wrappedConstructor);
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/providers/injection-token.js
+
+function isNormalToken(token) {
+ return typeof token === "string" || typeof token === "symbol";
+}
+function injection_token_isTokenDescriptor(descriptor) {
+ return (typeof descriptor === "object" &&
+ "token" in descriptor &&
+ "multiple" in descriptor);
+}
+function injection_token_isTransformDescriptor(descriptor) {
+ return (typeof descriptor === "object" &&
+ "token" in descriptor &&
+ "transform" in descriptor);
+}
+function isConstructorToken(token) {
+ return typeof token === "function" || token instanceof DelayedConstructor;
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/providers/token-provider.js
+function isTokenProvider(provider) {
+ return !!provider.useToken;
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/providers/value-provider.js
+function isValueProvider(provider) {
+ return provider.useValue != undefined;
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/providers/index.js
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/providers/provider.js
+
+
+
+
+function isProvider(provider) {
+ return (isClassProvider(provider) ||
+ isValueProvider(provider) ||
+ isTokenProvider(provider) ||
+ isFactoryProvider(provider));
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/registry-base.js
+var RegistryBase = (function () {
+ function RegistryBase() {
+ this._registryMap = new Map();
+ }
+ RegistryBase.prototype.entries = function () {
+ return this._registryMap.entries();
+ };
+ RegistryBase.prototype.getAll = function (key) {
+ this.ensure(key);
+ return this._registryMap.get(key);
+ };
+ RegistryBase.prototype.get = function (key) {
+ this.ensure(key);
+ var value = this._registryMap.get(key);
+ return value[value.length - 1] || null;
+ };
+ RegistryBase.prototype.set = function (key, value) {
+ this.ensure(key);
+ this._registryMap.get(key).push(value);
+ };
+ RegistryBase.prototype.setAll = function (key, value) {
+ this._registryMap.set(key, value);
+ };
+ RegistryBase.prototype.has = function (key) {
+ this.ensure(key);
+ return this._registryMap.get(key).length > 0;
+ };
+ RegistryBase.prototype.clear = function () {
+ this._registryMap.clear();
+ };
+ RegistryBase.prototype.ensure = function (key) {
+ if (!this._registryMap.has(key)) {
+ this._registryMap.set(key, []);
+ }
+ };
+ return RegistryBase;
+}());
+/* harmony default export */ const registry_base = (RegistryBase);
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/registry.js
+
+
+var Registry = (function (_super) {
+ tslib_tslib_es6_extends(Registry, _super);
+ function Registry() {
+ return _super !== null && _super.apply(this, arguments) || this;
+ }
+ return Registry;
+}(registry_base));
+/* harmony default export */ const registry = (Registry);
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/resolution-context.js
+var ResolutionContext = (function () {
+ function ResolutionContext() {
+ this.scopedResolutions = new Map();
+ }
+ return ResolutionContext;
+}());
+/* harmony default export */ const resolution_context = (ResolutionContext);
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/error-helpers.js
+
+function formatDependency(params, idx) {
+ if (params === null) {
+ return "at position #" + idx;
+ }
+ var argName = params.split(",")[idx].trim();
+ return "\"" + argName + "\" at position #" + idx;
+}
+function composeErrorMessage(msg, e, indent) {
+ if (indent === void 0) { indent = " "; }
+ return tslib_tslib_es6_spread([msg], e.message.split("\n").map(function (l) { return indent + l; })).join("\n");
+}
+function error_helpers_formatErrorCtor(ctor, paramIdx, error) {
+ var _a = tslib_es6_read(ctor.toString().match(/constructor\(([\w, ]+)\)/) || [], 2), _b = _a[1], params = _b === void 0 ? null : _b;
+ var dep = formatDependency(params, paramIdx);
+ return composeErrorMessage("Cannot inject the dependency " + dep + " of \"" + ctor.name + "\" constructor. Reason:", error);
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/types/disposable.js
+function isDisposable(value) {
+ if (typeof value.dispose !== "function")
+ return false;
+ var disposeFun = value.dispose;
+ if (disposeFun.length > 0) {
+ return false;
+ }
+ return true;
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/interceptors.js
+
+
+var PreResolutionInterceptors = (function (_super) {
+ tslib_tslib_es6_extends(PreResolutionInterceptors, _super);
+ function PreResolutionInterceptors() {
+ return _super !== null && _super.apply(this, arguments) || this;
+ }
+ return PreResolutionInterceptors;
+}(registry_base));
+
+var PostResolutionInterceptors = (function (_super) {
+ tslib_tslib_es6_extends(PostResolutionInterceptors, _super);
+ function PostResolutionInterceptors() {
+ return _super !== null && _super.apply(this, arguments) || this;
+ }
+ return PostResolutionInterceptors;
+}(registry_base));
+
+var Interceptors = (function () {
+ function Interceptors() {
+ this.preResolution = new PreResolutionInterceptors();
+ this.postResolution = new PostResolutionInterceptors();
+ }
+ return Interceptors;
+}());
+/* harmony default export */ const interceptors = (Interceptors);
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/dependency-container.js
+
+
+
+
+
+
+
+
+
+
+
+var typeInfo = new Map();
+var InternalDependencyContainer = (function () {
+ function InternalDependencyContainer(parent) {
+ this.parent = parent;
+ this._registry = new registry();
+ this.interceptors = new interceptors();
+ this.disposed = false;
+ this.disposables = new Set();
+ }
+ InternalDependencyContainer.prototype.register = function (token, providerOrConstructor, options) {
+ if (options === void 0) { options = { lifecycle: lifecycle.Transient }; }
+ this.ensureNotDisposed();
+ var provider;
+ if (!isProvider(providerOrConstructor)) {
+ provider = { useClass: providerOrConstructor };
+ }
+ else {
+ provider = providerOrConstructor;
+ }
+ if (isTokenProvider(provider)) {
+ var path = [token];
+ var tokenProvider = provider;
+ while (tokenProvider != null) {
+ var currentToken = tokenProvider.useToken;
+ if (path.includes(currentToken)) {
+ throw new Error("Token registration cycle detected! " + tslib_tslib_es6_spread(path, [currentToken]).join(" -> "));
+ }
+ path.push(currentToken);
+ var registration = this._registry.get(currentToken);
+ if (registration && isTokenProvider(registration.provider)) {
+ tokenProvider = registration.provider;
+ }
+ else {
+ tokenProvider = null;
+ }
+ }
+ }
+ if (options.lifecycle === lifecycle.Singleton ||
+ options.lifecycle == lifecycle.ContainerScoped ||
+ options.lifecycle == lifecycle.ResolutionScoped) {
+ if (isValueProvider(provider) || isFactoryProvider(provider)) {
+ throw new Error("Cannot use lifecycle \"" + lifecycle[options.lifecycle] + "\" with ValueProviders or FactoryProviders");
+ }
+ }
+ this._registry.set(token, { provider: provider, options: options });
+ return this;
+ };
+ InternalDependencyContainer.prototype.registerType = function (from, to) {
+ this.ensureNotDisposed();
+ if (isNormalToken(to)) {
+ return this.register(from, {
+ useToken: to
+ });
+ }
+ return this.register(from, {
+ useClass: to
+ });
+ };
+ InternalDependencyContainer.prototype.registerInstance = function (token, instance) {
+ this.ensureNotDisposed();
+ return this.register(token, {
+ useValue: instance
+ });
+ };
+ InternalDependencyContainer.prototype.registerSingleton = function (from, to) {
+ this.ensureNotDisposed();
+ if (isNormalToken(from)) {
+ if (isNormalToken(to)) {
+ return this.register(from, {
+ useToken: to
+ }, { lifecycle: lifecycle.Singleton });
+ }
+ else if (to) {
+ return this.register(from, {
+ useClass: to
+ }, { lifecycle: lifecycle.Singleton });
+ }
+ throw new Error('Cannot register a type name as a singleton without a "to" token');
+ }
+ var useClass = from;
+ if (to && !isNormalToken(to)) {
+ useClass = to;
+ }
+ return this.register(from, {
+ useClass: useClass
+ }, { lifecycle: lifecycle.Singleton });
+ };
+ InternalDependencyContainer.prototype.resolve = function (token, context) {
+ if (context === void 0) { context = new resolution_context(); }
+ this.ensureNotDisposed();
+ var registration = this.getRegistration(token);
+ if (!registration && isNormalToken(token)) {
+ throw new Error("Attempted to resolve unregistered dependency token: \"" + token.toString() + "\"");
+ }
+ this.executePreResolutionInterceptor(token, "Single");
+ if (registration) {
+ var result = this.resolveRegistration(registration, context);
+ this.executePostResolutionInterceptor(token, result, "Single");
+ return result;
+ }
+ if (isConstructorToken(token)) {
+ var result = this.construct(token, context);
+ this.executePostResolutionInterceptor(token, result, "Single");
+ return result;
+ }
+ throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.");
+ };
+ InternalDependencyContainer.prototype.executePreResolutionInterceptor = function (token, resolutionType) {
+ var e_1, _a;
+ if (this.interceptors.preResolution.has(token)) {
+ var remainingInterceptors = [];
+ try {
+ for (var _b = tslib_es6_values(this.interceptors.preResolution.getAll(token)), _c = _b.next(); !_c.done; _c = _b.next()) {
+ var interceptor = _c.value;
+ if (interceptor.options.frequency != "Once") {
+ remainingInterceptors.push(interceptor);
+ }
+ interceptor.callback(token, resolutionType);
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ this.interceptors.preResolution.setAll(token, remainingInterceptors);
+ }
+ };
+ InternalDependencyContainer.prototype.executePostResolutionInterceptor = function (token, result, resolutionType) {
+ var e_2, _a;
+ if (this.interceptors.postResolution.has(token)) {
+ var remainingInterceptors = [];
+ try {
+ for (var _b = tslib_es6_values(this.interceptors.postResolution.getAll(token)), _c = _b.next(); !_c.done; _c = _b.next()) {
+ var interceptor = _c.value;
+ if (interceptor.options.frequency != "Once") {
+ remainingInterceptors.push(interceptor);
+ }
+ interceptor.callback(token, result, resolutionType);
+ }
+ }
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
+ finally {
+ try {
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
+ }
+ finally { if (e_2) throw e_2.error; }
+ }
+ this.interceptors.postResolution.setAll(token, remainingInterceptors);
+ }
+ };
+ InternalDependencyContainer.prototype.resolveRegistration = function (registration, context) {
+ this.ensureNotDisposed();
+ if (registration.options.lifecycle === lifecycle.ResolutionScoped &&
+ context.scopedResolutions.has(registration)) {
+ return context.scopedResolutions.get(registration);
+ }
+ var isSingleton = registration.options.lifecycle === lifecycle.Singleton;
+ var isContainerScoped = registration.options.lifecycle === lifecycle.ContainerScoped;
+ var returnInstance = isSingleton || isContainerScoped;
+ var resolved;
+ if (isValueProvider(registration.provider)) {
+ resolved = registration.provider.useValue;
+ }
+ else if (isTokenProvider(registration.provider)) {
+ resolved = returnInstance
+ ? registration.instance ||
+ (registration.instance = this.resolve(registration.provider.useToken, context))
+ : this.resolve(registration.provider.useToken, context);
+ }
+ else if (isClassProvider(registration.provider)) {
+ resolved = returnInstance
+ ? registration.instance ||
+ (registration.instance = this.construct(registration.provider.useClass, context))
+ : this.construct(registration.provider.useClass, context);
+ }
+ else if (isFactoryProvider(registration.provider)) {
+ resolved = registration.provider.useFactory(this);
+ }
+ else {
+ resolved = this.construct(registration.provider, context);
+ }
+ if (registration.options.lifecycle === lifecycle.ResolutionScoped) {
+ context.scopedResolutions.set(registration, resolved);
+ }
+ return resolved;
+ };
+ InternalDependencyContainer.prototype.resolveAll = function (token, context) {
+ var _this = this;
+ if (context === void 0) { context = new resolution_context(); }
+ this.ensureNotDisposed();
+ var registrations = this.getAllRegistrations(token);
+ if (!registrations && isNormalToken(token)) {
+ throw new Error("Attempted to resolve unregistered dependency token: \"" + token.toString() + "\"");
+ }
+ this.executePreResolutionInterceptor(token, "All");
+ if (registrations) {
+ var result_1 = registrations.map(function (item) {
+ return _this.resolveRegistration(item, context);
+ });
+ this.executePostResolutionInterceptor(token, result_1, "All");
+ return result_1;
+ }
+ var result = [this.construct(token, context)];
+ this.executePostResolutionInterceptor(token, result, "All");
+ return result;
+ };
+ InternalDependencyContainer.prototype.isRegistered = function (token, recursive) {
+ if (recursive === void 0) { recursive = false; }
+ this.ensureNotDisposed();
+ return (this._registry.has(token) ||
+ (recursive &&
+ (this.parent || false) &&
+ this.parent.isRegistered(token, true)));
+ };
+ InternalDependencyContainer.prototype.reset = function () {
+ this.ensureNotDisposed();
+ this._registry.clear();
+ this.interceptors.preResolution.clear();
+ this.interceptors.postResolution.clear();
+ };
+ InternalDependencyContainer.prototype.clearInstances = function () {
+ var e_3, _a;
+ this.ensureNotDisposed();
+ try {
+ for (var _b = tslib_es6_values(this._registry.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
+ var _d = tslib_es6_read(_c.value, 2), token = _d[0], registrations = _d[1];
+ this._registry.setAll(token, registrations
+ .filter(function (registration) { return !isValueProvider(registration.provider); })
+ .map(function (registration) {
+ registration.instance = undefined;
+ return registration;
+ }));
+ }
+ }
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
+ finally {
+ try {
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
+ }
+ finally { if (e_3) throw e_3.error; }
+ }
+ };
+ InternalDependencyContainer.prototype.createChildContainer = function () {
+ var e_4, _a;
+ this.ensureNotDisposed();
+ var childContainer = new InternalDependencyContainer(this);
+ try {
+ for (var _b = tslib_es6_values(this._registry.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
+ var _d = tslib_es6_read(_c.value, 2), token = _d[0], registrations = _d[1];
+ if (registrations.some(function (_a) {
+ var options = _a.options;
+ return options.lifecycle === lifecycle.ContainerScoped;
+ })) {
+ childContainer._registry.setAll(token, registrations.map(function (registration) {
+ if (registration.options.lifecycle === lifecycle.ContainerScoped) {
+ return {
+ provider: registration.provider,
+ options: registration.options
+ };
+ }
+ return registration;
+ }));
+ }
+ }
+ }
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
+ finally {
+ try {
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
+ }
+ finally { if (e_4) throw e_4.error; }
+ }
+ return childContainer;
+ };
+ InternalDependencyContainer.prototype.beforeResolution = function (token, callback, options) {
+ if (options === void 0) { options = { frequency: "Always" }; }
+ this.interceptors.preResolution.set(token, {
+ callback: callback,
+ options: options
+ });
+ };
+ InternalDependencyContainer.prototype.afterResolution = function (token, callback, options) {
+ if (options === void 0) { options = { frequency: "Always" }; }
+ this.interceptors.postResolution.set(token, {
+ callback: callback,
+ options: options
+ });
+ };
+ InternalDependencyContainer.prototype.dispose = function () {
+ return tslib_tslib_es6_awaiter(this, void 0, void 0, function () {
+ var promises;
+ return tslib_es6_generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ this.disposed = true;
+ promises = [];
+ this.disposables.forEach(function (disposable) {
+ var maybePromise = disposable.dispose();
+ if (maybePromise) {
+ promises.push(maybePromise);
+ }
+ });
+ return [4, Promise.all(promises)];
+ case 1:
+ _a.sent();
+ return [2];
+ }
+ });
+ });
+ };
+ InternalDependencyContainer.prototype.getRegistration = function (token) {
+ if (this.isRegistered(token)) {
+ return this._registry.get(token);
+ }
+ if (this.parent) {
+ return this.parent.getRegistration(token);
+ }
+ return null;
+ };
+ InternalDependencyContainer.prototype.getAllRegistrations = function (token) {
+ if (this.isRegistered(token)) {
+ return this._registry.getAll(token);
+ }
+ if (this.parent) {
+ return this.parent.getAllRegistrations(token);
+ }
+ return null;
+ };
+ InternalDependencyContainer.prototype.construct = function (ctor, context) {
+ var _this = this;
+ if (ctor instanceof DelayedConstructor) {
+ return ctor.createProxy(function (target) {
+ return _this.resolve(target, context);
+ });
+ }
+ var instance = (function () {
+ var paramInfo = typeInfo.get(ctor);
+ if (!paramInfo || paramInfo.length === 0) {
+ if (ctor.length === 0) {
+ return new ctor();
+ }
+ else {
+ throw new Error("TypeInfo not known for \"" + ctor.name + "\"");
+ }
+ }
+ var params = paramInfo.map(_this.resolveParams(context, ctor));
+ return new (ctor.bind.apply(ctor, tslib_tslib_es6_spread([void 0], params)))();
+ })();
+ if (isDisposable(instance)) {
+ this.disposables.add(instance);
+ }
+ return instance;
+ };
+ InternalDependencyContainer.prototype.resolveParams = function (context, ctor) {
+ var _this = this;
+ return function (param, idx) {
+ var _a, _b, _c;
+ try {
+ if (injection_token_isTokenDescriptor(param)) {
+ if (injection_token_isTransformDescriptor(param)) {
+ return param.multiple
+ ? (_a = _this.resolve(param.transform)).transform.apply(_a, tslib_tslib_es6_spread([_this.resolveAll(param.token)], param.transformArgs)) : (_b = _this.resolve(param.transform)).transform.apply(_b, tslib_tslib_es6_spread([_this.resolve(param.token, context)], param.transformArgs));
+ }
+ else {
+ return param.multiple
+ ? _this.resolveAll(param.token)
+ : _this.resolve(param.token, context);
+ }
+ }
+ else if (injection_token_isTransformDescriptor(param)) {
+ return (_c = _this.resolve(param.transform, context)).transform.apply(_c, tslib_tslib_es6_spread([_this.resolve(param.token, context)], param.transformArgs));
+ }
+ return _this.resolve(param, context);
+ }
+ catch (e) {
+ throw new Error(error_helpers_formatErrorCtor(ctor, idx, e));
+ }
+ };
+ };
+ InternalDependencyContainer.prototype.ensureNotDisposed = function () {
+ if (this.disposed) {
+ throw new Error("This container has been disposed, you cannot interact with a disposed container");
+ }
+ };
+ return InternalDependencyContainer;
+}());
+var instance = new InternalDependencyContainer();
+/* harmony default export */ const dependency_container = ((/* unused pure expression or super */ null && (instance)));
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/decorators/auto-injectable.js
+
+
+
+
+
+function autoInjectable() {
+ return function (target) {
+ var paramInfo = getParamInfo(target);
+ return (function (_super) {
+ __extends(class_1, _super);
+ function class_1() {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ return _super.apply(this, __spread(args.concat(paramInfo.slice(args.length).map(function (type, index) {
+ var _a, _b, _c;
+ try {
+ if (isTokenDescriptor(type)) {
+ if (isTransformDescriptor(type)) {
+ return type.multiple
+ ? (_a = globalContainer
+ .resolve(type.transform)).transform.apply(_a, __spread([globalContainer.resolveAll(type.token)], type.transformArgs)) : (_b = globalContainer
+ .resolve(type.transform)).transform.apply(_b, __spread([globalContainer.resolve(type.token)], type.transformArgs));
+ }
+ else {
+ return type.multiple
+ ? globalContainer.resolveAll(type.token)
+ : globalContainer.resolve(type.token);
+ }
+ }
+ else if (isTransformDescriptor(type)) {
+ return (_c = globalContainer
+ .resolve(type.transform)).transform.apply(_c, __spread([globalContainer.resolve(type.token)], type.transformArgs));
+ }
+ return globalContainer.resolve(type);
+ }
+ catch (e) {
+ var argIndex = index + args.length;
+ throw new Error(formatErrorCtor(target, argIndex, e));
+ }
+ })))) || this;
+ }
+ return class_1;
+ }(target));
+ };
+}
+/* harmony default export */ const auto_injectable = ((/* unused pure expression or super */ null && (autoInjectable)));
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/reflection-helpers.js
+var INJECTION_TOKEN_METADATA_KEY = "injectionTokens";
+function reflection_helpers_getParamInfo(target) {
+ var params = Reflect.getMetadata("design:paramtypes", target) || [];
+ var injectionTokens = Reflect.getOwnMetadata(INJECTION_TOKEN_METADATA_KEY, target) || {};
+ Object.keys(injectionTokens).forEach(function (key) {
+ params[+key] = injectionTokens[key];
+ });
+ return params;
+}
+function defineInjectionTokenMetadata(data, transform) {
+ return function (target, _propertyKey, parameterIndex) {
+ var descriptors = Reflect.getOwnMetadata(INJECTION_TOKEN_METADATA_KEY, target) || {};
+ descriptors[parameterIndex] = transform
+ ? {
+ token: data,
+ transform: transform.transformToken,
+ transformArgs: transform.args || []
+ }
+ : data;
+ Reflect.defineMetadata(INJECTION_TOKEN_METADATA_KEY, descriptors, target);
+ };
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/decorators/injectable.js
+
+
+function injectable_injectable() {
+ return function (target) {
+ typeInfo.set(target, reflection_helpers_getParamInfo(target));
+ };
+}
+/* harmony default export */ const decorators_injectable = (injectable_injectable);
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/decorators/registry.js
+
+
+function registry_registry(registrations) {
+ if (registrations === void 0) { registrations = []; }
+ return function (target) {
+ registrations.forEach(function (_a) {
+ var token = _a.token, options = _a.options, provider = __rest(_a, ["token", "options"]);
+ return globalContainer.register(token, provider, options);
+ });
+ return target;
+ };
+}
+/* harmony default export */ const decorators_registry = ((/* unused pure expression or super */ null && (registry_registry)));
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/decorators/singleton.js
+
+
+function singleton() {
+ return function (target) {
+ injectable()(target);
+ globalContainer.registerSingleton(target);
+ };
+}
+/* harmony default export */ const decorators_singleton = ((/* unused pure expression or super */ null && (singleton)));
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/decorators/scoped.js
+
+
+function scoped(lifecycle, token) {
+ return function (target) {
+ injectable()(target);
+ globalContainer.register(token || target, target, {
+ lifecycle: lifecycle
+ });
+ };
+}
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/decorators/index.js
+
+
+
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/tsyringe/dist/esm5/index.js
+if (typeof Reflect === "undefined" || !Reflect.getMetadata) {
+ throw new Error("tsyringe requires a reflect polyfill. Please add 'import \"reflect-metadata\"' to the top of your entry point.");
+}
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/attribute.js
+var PKCS12AttrSet_1;
+
+
+class PKCS12Attribute {
+ constructor(params = {}) {
+ this.attrId = "";
+ this.attrValues = [];
+ Object.assign(params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], PKCS12Attribute.prototype, "attrId", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, repeated: "set" })
+], PKCS12Attribute.prototype, "attrValues", void 0);
+let PKCS12AttrSet = PKCS12AttrSet_1 = class PKCS12AttrSet extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, PKCS12AttrSet_1.prototype);
+ }
+};
+PKCS12AttrSet = PKCS12AttrSet_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: PKCS12Attribute })
+], PKCS12AttrSet);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/authenticated_safe.js
+var AuthenticatedSafe_1;
+
+
+
+let AuthenticatedSafe = AuthenticatedSafe_1 = class AuthenticatedSafe extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, AuthenticatedSafe_1.prototype);
+ }
+};
+AuthenticatedSafe = AuthenticatedSafe_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: ContentInfo })
+], AuthenticatedSafe);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/object_identifiers.js
+const id_rsadsi = "1.2.840.113549";
+const id_pkcs = `${id_rsadsi}.1`;
+const id_pkcs_12 = `${id_pkcs}.12`;
+const id_pkcs_12PbeIds = `${id_pkcs_12}.1`;
+const id_pbeWithSHAAnd128BitRC4 = `${id_pkcs_12PbeIds}.1`;
+const id_pbeWithSHAAnd40BitRC4 = `${id_pkcs_12PbeIds}.2`;
+const id_pbeWithSHAAnd3_KeyTripleDES_CBC = `${id_pkcs_12PbeIds}.3`;
+const id_pbeWithSHAAnd2_KeyTripleDES_CBC = `${id_pkcs_12PbeIds}.4`;
+const id_pbeWithSHAAnd128BitRC2_CBC = `${id_pkcs_12PbeIds}.5`;
+const id_pbewithSHAAnd40BitRC2_CBC = `${id_pkcs_12PbeIds}.6`;
+const id_bagtypes = `${id_pkcs_12}.10.1`;
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/bags/types.js
+
+const id_keyBag = `${id_bagtypes}.1`;
+const id_pkcs8ShroudedKeyBag = `${id_bagtypes}.2`;
+const id_certBag = `${id_bagtypes}.3`;
+const id_CRLBag = `${id_bagtypes}.4`;
+const id_SecretBag = `${id_bagtypes}.5`;
+const id_SafeContents = `${id_bagtypes}.6`;
+const id_pkcs_9 = "1.2.840.113549.1.9";
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/bags/cert_bag.js
+
+
+
+class CertBag {
+ constructor(params = {}) {
+ this.certId = "";
+ this.certValue = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], CertBag.prototype, "certId", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, context: 0 })
+], CertBag.prototype, "certValue", void 0);
+const id_certTypes = `${id_pkcs_9}.22`;
+const id_x509Certificate = `${id_certTypes}.1`;
+const id_sdsiCertificate = `${id_certTypes}.2`;
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/bags/crl_bag.js
+
+
+
+class CRLBag {
+ constructor(params = {}) {
+ this.crlId = "";
+ this.crltValue = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], CRLBag.prototype, "crlId", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, context: 0 })
+], CRLBag.prototype, "crltValue", void 0);
+const id_crlTypes = `${id_pkcs_9}.23`;
+const id_x509CRL = `${id_crlTypes}.1`;
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pkcs8/build/es2015/encrypted_private_key_info.js
+
+
+
+class EncryptedData extends octet_string_OctetString {
+}
+class encrypted_private_key_info_EncryptedPrivateKeyInfo {
+ constructor(params = {}) {
+ this.encryptionAlgorithm = new AlgorithmIdentifier();
+ this.encryptedData = new EncryptedData();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], encrypted_private_key_info_EncryptedPrivateKeyInfo.prototype, "encryptionAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: EncryptedData })
+], encrypted_private_key_info_EncryptedPrivateKeyInfo.prototype, "encryptedData", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pkcs8/build/es2015/private_key_info.js
+var Attributes_1;
+
+
+
+var private_key_info_Version;
+(function (Version) {
+ Version[Version["v1"] = 0] = "v1";
+})(private_key_info_Version || (private_key_info_Version = {}));
+class PrivateKey extends octet_string_OctetString {
+}
+let Attributes = Attributes_1 = class Attributes extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, Attributes_1.prototype);
+ }
+};
+Attributes = Attributes_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: attribute_Attribute })
+], Attributes);
+
+class PrivateKeyInfo {
+ constructor(params = {}) {
+ this.version = private_key_info_Version.v1;
+ this.privateKeyAlgorithm = new AlgorithmIdentifier();
+ this.privateKey = new PrivateKey();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], PrivateKeyInfo.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], PrivateKeyInfo.prototype, "privateKeyAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: PrivateKey })
+], PrivateKeyInfo.prototype, "privateKey", void 0);
+__decorate([
+ AsnProp({ type: Attributes, implicit: true, context: 0, optional: true })
+], PrivateKeyInfo.prototype, "attributes", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pkcs8/build/es2015/index.js
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/bags/key_bag.js
+
+
+
+let KeyBag = class KeyBag extends PrivateKeyInfo {
+};
+KeyBag = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], KeyBag);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/bags/pkcs8_shrouded_key_bag.js
+
+
+
+let PKCS8ShroudedKeyBag = class PKCS8ShroudedKeyBag extends encrypted_private_key_info_EncryptedPrivateKeyInfo {
+};
+PKCS8ShroudedKeyBag = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], PKCS8ShroudedKeyBag);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/bags/secret_bag.js
+
+
+class SecretBag {
+ constructor(params = {}) {
+ this.secretTypeId = "";
+ this.secretValue = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], SecretBag.prototype, "secretTypeId", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, context: 0 })
+], SecretBag.prototype, "secretValue", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/bags/index.js
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/mac_data.js
+
+
+
+class MacData {
+ constructor(params = {}) {
+ this.mac = new DigestInfo();
+ this.macSalt = new octet_string_OctetString();
+ this.iterations = 1;
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: DigestInfo })
+], MacData.prototype, "mac", void 0);
+__decorate([
+ AsnProp({ type: octet_string_OctetString })
+], MacData.prototype, "macSalt", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer, defaultValue: 1 })
+], MacData.prototype, "iterations", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/pfx.js
+
+
+
+
+class PFX {
+ constructor(params = {}) {
+ this.version = 3;
+ this.authSafe = new ContentInfo();
+ this.macData = new MacData();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], PFX.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: ContentInfo })
+], PFX.prototype, "authSafe", void 0);
+__decorate([
+ AsnProp({ type: MacData, optional: true })
+], PFX.prototype, "macData", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/safe_bag.js
+var SafeContents_1;
+
+
+
+class SafeBag {
+ constructor(params = {}) {
+ this.bagId = "";
+ this.bagValue = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], SafeBag.prototype, "bagId", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.Any, context: 0 })
+], SafeBag.prototype, "bagValue", void 0);
+__decorate([
+ AsnProp({ type: PKCS12Attribute, repeated: "set", optional: true })
+], SafeBag.prototype, "bagAttributes", void 0);
+let SafeContents = SafeContents_1 = class SafeContents extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, SafeContents_1.prototype);
+ }
+};
+SafeContents = SafeContents_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: SafeBag })
+], SafeContents);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pfx/build/es2015/index.js
+
+
+
+
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-pkcs9/build/es2015/index.js
+var ExtensionRequest_1, ExtendedCertificateAttributes_1, SMIMECapabilities_1;
+
+
+
+
+
+
+
+const id_pkcs9 = "1.2.840.113549.1.9";
+const id_pkcs9_mo = `${id_pkcs9}.0`;
+const id_pkcs9_oc = `${id_pkcs9}.24`;
+const id_pkcs9_at = `${id_pkcs9}.25`;
+const id_pkcs9_sx = `${id_pkcs9}.26`;
+const id_pkcs9_mr = `${id_pkcs9}.27`;
+const id_pkcs9_oc_pkcsEntity = `${id_pkcs9_oc}.1`;
+const id_pkcs9_oc_naturalPerson = `${id_pkcs9_oc}.2`;
+const id_pkcs9_at_emailAddress = `${id_pkcs9}.1`;
+const id_pkcs9_at_unstructuredName = `${id_pkcs9}.2`;
+const id_pkcs9_at_contentType = `${id_pkcs9}.3`;
+const id_pkcs9_at_messageDigest = `${id_pkcs9}.4`;
+const id_pkcs9_at_signingTime = `${id_pkcs9}.5`;
+const id_pkcs9_at_counterSignature = `${id_pkcs9}.6`;
+const id_pkcs9_at_challengePassword = `${id_pkcs9}.7`;
+const id_pkcs9_at_unstructuredAddress = `${id_pkcs9}.8`;
+const id_pkcs9_at_extendedCertificateAttributes = `${id_pkcs9}.9`;
+const id_pkcs9_at_signingDescription = `${id_pkcs9}.13`;
+const es2015_id_pkcs9_at_extensionRequest = `${id_pkcs9}.14`;
+const id_pkcs9_at_smimeCapabilities = `${id_pkcs9}.15`;
+const id_pkcs9_at_friendlyName = `${id_pkcs9}.20`;
+const id_pkcs9_at_localKeyId = `${id_pkcs9}.21`;
+const id_pkcs9_at_userPKCS12 = (/* unused pure expression or super */ null && (`2.16.840.1.113730.3.1.216`));
+const id_pkcs9_at_pkcs15Token = `${id_pkcs9_at}.1`;
+const id_pkcs9_at_encryptedPrivateKeyInfo = `${id_pkcs9_at}.2`;
+const id_pkcs9_at_randomNonce = `${id_pkcs9_at}.3`;
+const id_pkcs9_at_sequenceNumber = `${id_pkcs9_at}.4`;
+const id_pkcs9_at_pkcs7PDU = `${id_pkcs9_at}.5`;
+const id_ietf_at = `1.3.6.1.5.5.7.9`;
+const id_pkcs9_at_dateOfBirth = `${id_ietf_at}.1`;
+const id_pkcs9_at_placeOfBirth = `${id_ietf_at}.2`;
+const id_pkcs9_at_gender = `${id_ietf_at}.3`;
+const id_pkcs9_at_countryOfCitizenship = `${id_ietf_at}.4`;
+const id_pkcs9_at_countryOfResidence = `${id_ietf_at}.5`;
+const id_pkcs9_sx_pkcs9String = `${id_pkcs9_sx}.1`;
+const id_pkcs9_sx_signingTime = `${id_pkcs9_sx}.2`;
+const id_pkcs9_mr_caseIgnoreMatch = `${id_pkcs9_mr}.1`;
+const id_pkcs9_mr_signingTimeMatch = `${id_pkcs9_mr}.2`;
+const id_smime = `${id_pkcs9}.16`;
+const es2015_id_certTypes = `${id_pkcs9}.22`;
+const crlTypes = `${id_pkcs9}.23`;
+const id_at_pseudonym = `${id_at}.65`;
+let PKCS9String = class PKCS9String extends DirectoryString {
+ constructor(params = {}) {
+ super(params);
+ }
+ toString() {
+ const o = {};
+ o.toString();
+ return this.ia5String || super.toString();
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.IA5String })
+], PKCS9String.prototype, "ia5String", void 0);
+PKCS9String = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], PKCS9String);
+
+let Pkcs7PDU = class Pkcs7PDU extends ContentInfo {
+};
+Pkcs7PDU = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], Pkcs7PDU);
+
+let UserPKCS12 = class UserPKCS12 extends PFX {
+};
+UserPKCS12 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], UserPKCS12);
+
+let EncryptedPrivateKeyInfo = class EncryptedPrivateKeyInfo extends encrypted_private_key_info_EncryptedPrivateKeyInfo {
+};
+EncryptedPrivateKeyInfo = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], EncryptedPrivateKeyInfo);
+
+let EmailAddress = class EmailAddress {
+ constructor(value = "") {
+ this.value = value;
+ }
+ toString() {
+ return this.value;
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.IA5String })
+], EmailAddress.prototype, "value", void 0);
+EmailAddress = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], EmailAddress);
+
+let UnstructuredName = class UnstructuredName extends PKCS9String {
+};
+UnstructuredName = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], UnstructuredName);
+
+let UnstructuredAddress = class UnstructuredAddress extends DirectoryString {
+};
+UnstructuredAddress = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], UnstructuredAddress);
+
+let DateOfBirth = class DateOfBirth {
+ constructor(value = new Date()) {
+ this.value = value;
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.GeneralizedTime })
+], DateOfBirth.prototype, "value", void 0);
+DateOfBirth = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], DateOfBirth);
+
+let PlaceOfBirth = class PlaceOfBirth extends DirectoryString {
+};
+PlaceOfBirth = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], PlaceOfBirth);
+
+let Gender = class Gender {
+ constructor(value = "M") {
+ this.value = value;
+ }
+ toString() {
+ return this.value;
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.PrintableString })
+], Gender.prototype, "value", void 0);
+Gender = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], Gender);
+
+let CountryOfCitizenship = class CountryOfCitizenship {
+ constructor(value = "") {
+ this.value = value;
+ }
+ toString() {
+ return this.value;
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.PrintableString })
+], CountryOfCitizenship.prototype, "value", void 0);
+CountryOfCitizenship = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], CountryOfCitizenship);
+
+let CountryOfResidence = class CountryOfResidence extends CountryOfCitizenship {
+};
+CountryOfResidence = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], CountryOfResidence);
+
+let Pseudonym = class Pseudonym extends DirectoryString {
+};
+Pseudonym = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], Pseudonym);
+
+let ContentType = class ContentType {
+ constructor(value = "") {
+ this.value = value;
+ }
+ toString() {
+ return this.value;
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.ObjectIdentifier })
+], ContentType.prototype, "value", void 0);
+ContentType = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], ContentType);
+
+class MessageDigest extends (/* unused pure expression or super */ null && (OctetString)) {
+}
+let SigningTime = class SigningTime extends time_Time {
+};
+SigningTime = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], SigningTime);
+
+class RandomNonce extends (/* unused pure expression or super */ null && (OctetString)) {
+}
+let SequenceNumber = class SequenceNumber {
+ constructor(value = 0) {
+ this.value = value;
+ }
+ toString() {
+ return this.value.toString();
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], SequenceNumber.prototype, "value", void 0);
+SequenceNumber = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], SequenceNumber);
+
+let CounterSignature = class CounterSignature extends SignerInfo {
+};
+CounterSignature = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], CounterSignature);
+
+let ChallengePassword = class ChallengePassword extends DirectoryString {
+};
+ChallengePassword = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], ChallengePassword);
+
+let ExtensionRequest = ExtensionRequest_1 = class ExtensionRequest extends extension_Extensions {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, ExtensionRequest_1.prototype);
+ }
+};
+ExtensionRequest = ExtensionRequest_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], ExtensionRequest);
+
+let ExtendedCertificateAttributes = ExtendedCertificateAttributes_1 = class ExtendedCertificateAttributes extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, ExtendedCertificateAttributes_1.prototype);
+ }
+};
+ExtendedCertificateAttributes = ExtendedCertificateAttributes_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Set, itemType: Attribute })
+], ExtendedCertificateAttributes);
+
+let FriendlyName = class FriendlyName {
+ constructor(value = "") {
+ this.value = value;
+ }
+ toString() {
+ return this.value;
+ }
+};
+__decorate([
+ AsnProp({ type: AsnPropTypes.BmpString })
+], FriendlyName.prototype, "value", void 0);
+FriendlyName = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Choice })
+], FriendlyName);
+
+class LocalKeyId extends (/* unused pure expression or super */ null && (OctetString)) {
+}
+class SigningDescription extends DirectoryString {
+}
+let SMIMECapability = class SMIMECapability extends AlgorithmIdentifier {
+};
+SMIMECapability = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence })
+], SMIMECapability);
+
+let SMIMECapabilities = SMIMECapabilities_1 = class SMIMECapabilities extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, SMIMECapabilities_1.prototype);
+ }
+};
+SMIMECapabilities = SMIMECapabilities_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: SMIMECapability })
+], SMIMECapabilities);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-csr/build/es2015/attributes.js
+var attributes_Attributes_1;
+
+
+
+let attributes_Attributes = attributes_Attributes_1 = class Attributes extends AsnArray {
+ constructor(items) {
+ super(items);
+ Object.setPrototypeOf(this, attributes_Attributes_1.prototype);
+ }
+};
+attributes_Attributes = attributes_Attributes_1 = __decorate([
+ AsnType({ type: enums_AsnTypeTypes.Sequence, itemType: attribute_Attribute })
+], attributes_Attributes);
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-csr/build/es2015/certification_request_info.js
+
+
+
+
+class certification_request_info_CertificationRequestInfo {
+ constructor(params = {}) {
+ this.version = 0;
+ this.subject = new name_Name();
+ this.subjectPKInfo = new subject_public_key_info_SubjectPublicKeyInfo();
+ this.attributes = new attributes_Attributes();
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: AsnPropTypes.Integer })
+], certification_request_info_CertificationRequestInfo.prototype, "version", void 0);
+__decorate([
+ AsnProp({ type: name_Name })
+], certification_request_info_CertificationRequestInfo.prototype, "subject", void 0);
+__decorate([
+ AsnProp({ type: subject_public_key_info_SubjectPublicKeyInfo })
+], certification_request_info_CertificationRequestInfo.prototype, "subjectPKInfo", void 0);
+__decorate([
+ AsnProp({ type: attributes_Attributes, implicit: true, context: 0 })
+], certification_request_info_CertificationRequestInfo.prototype, "attributes", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-csr/build/es2015/certification_request.js
+
+
+
+
+class certification_request_CertificationRequest {
+ constructor(params = {}) {
+ this.certificationRequestInfo = new certification_request_info_CertificationRequestInfo();
+ this.signatureAlgorithm = new AlgorithmIdentifier();
+ this.signature = new ArrayBuffer(0);
+ Object.assign(this, params);
+ }
+}
+__decorate([
+ AsnProp({ type: certification_request_info_CertificationRequestInfo })
+], certification_request_CertificationRequest.prototype, "certificationRequestInfo", void 0);
+__decorate([
+ AsnProp({ type: AlgorithmIdentifier })
+], certification_request_CertificationRequest.prototype, "signatureAlgorithm", void 0);
+__decorate([
+ AsnProp({ type: AsnPropTypes.BitString })
+], certification_request_CertificationRequest.prototype, "signature", void 0);
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/asn1-csr/build/es2015/index.js
+
+
+
+
+;// CONCATENATED MODULE: ./node_modules/@peculiar/x509/build/x509.es.js
+/*!
+ * MIT License
+ *
+ * Copyright (c) Peculiar Ventures. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+const diAlgorithm = "crypto.algorithm";
+class AlgorithmProvider {
+ getAlgorithms() {
+ return instance.resolveAll(diAlgorithm);
+ }
+ toAsnAlgorithm(alg) {
+ ({ ...alg });
+ for (const algorithm of this.getAlgorithms()) {
+ const res = algorithm.toAsnAlgorithm(alg);
+ if (res) {
+ return res;
+ }
+ }
+ if (/[0-9.]+/.test(alg.name)) {
+ const res = new AlgorithmIdentifier({
+ algorithm: alg.name,
+ });
+ if ("parameters" in alg) {
+ const unknown = alg;
+ res.parameters = unknown.parameters;
+ }
+ return res;
+ }
+ throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm");
+ }
+ toWebAlgorithm(alg) {
+ for (const algorithm of this.getAlgorithms()) {
+ const res = algorithm.toWebAlgorithm(alg);
+ if (res) {
+ return res;
+ }
+ }
+ const unknown = {
+ name: alg.algorithm,
+ parameters: alg.parameters,
+ };
+ return unknown;
+ }
+}
+const diAlgorithmProvider = "crypto.algorithmProvider";
+instance.registerSingleton(diAlgorithmProvider, AlgorithmProvider);
+
+var EcAlgorithm_1;
+const idVersionOne = "1.3.36.3.3.2.8.1.1";
+const idBrainpoolP160r1 = `${idVersionOne}.1`;
+const idBrainpoolP160t1 = `${idVersionOne}.2`;
+const idBrainpoolP192r1 = `${idVersionOne}.3`;
+const idBrainpoolP192t1 = `${idVersionOne}.4`;
+const idBrainpoolP224r1 = `${idVersionOne}.5`;
+const idBrainpoolP224t1 = `${idVersionOne}.6`;
+const idBrainpoolP256r1 = `${idVersionOne}.7`;
+const idBrainpoolP256t1 = `${idVersionOne}.8`;
+const idBrainpoolP320r1 = `${idVersionOne}.9`;
+const idBrainpoolP320t1 = `${idVersionOne}.10`;
+const idBrainpoolP384r1 = `${idVersionOne}.11`;
+const idBrainpoolP384t1 = `${idVersionOne}.12`;
+const idBrainpoolP512r1 = `${idVersionOne}.13`;
+const idBrainpoolP512t1 = `${idVersionOne}.14`;
+const brainpoolP160r1 = "brainpoolP160r1";
+const brainpoolP160t1 = "brainpoolP160t1";
+const brainpoolP192r1 = "brainpoolP192r1";
+const brainpoolP192t1 = "brainpoolP192t1";
+const brainpoolP224r1 = "brainpoolP224r1";
+const brainpoolP224t1 = "brainpoolP224t1";
+const brainpoolP256r1 = "brainpoolP256r1";
+const brainpoolP256t1 = "brainpoolP256t1";
+const brainpoolP320r1 = "brainpoolP320r1";
+const brainpoolP320t1 = "brainpoolP320t1";
+const brainpoolP384r1 = "brainpoolP384r1";
+const brainpoolP384t1 = "brainpoolP384t1";
+const brainpoolP512r1 = "brainpoolP512r1";
+const brainpoolP512t1 = "brainpoolP512t1";
+const ECDSA = "ECDSA";
+let EcAlgorithm = EcAlgorithm_1 = class EcAlgorithm {
+ toAsnAlgorithm(alg) {
+ switch (alg.name.toLowerCase()) {
+ case ECDSA.toLowerCase():
+ if ("hash" in alg) {
+ const hash = typeof alg.hash === "string" ? alg.hash : alg.hash.name;
+ switch (hash.toLowerCase()) {
+ case "sha-1":
+ return ecdsaWithSHA1;
+ case "sha-256":
+ return ecdsaWithSHA256;
+ case "sha-384":
+ return ecdsaWithSHA384;
+ case "sha-512":
+ return ecdsaWithSHA512;
+ }
+ }
+ else if ("namedCurve" in alg) {
+ let parameters = "";
+ switch (alg.namedCurve) {
+ case "P-256":
+ parameters = id_secp256r1;
+ break;
+ case "K-256":
+ parameters = EcAlgorithm_1.SECP256K1;
+ break;
+ case "P-384":
+ parameters = id_secp384r1;
+ break;
+ case "P-521":
+ parameters = id_secp521r1;
+ break;
+ case brainpoolP160r1:
+ parameters = idBrainpoolP160r1;
+ break;
+ case brainpoolP160t1:
+ parameters = idBrainpoolP160t1;
+ break;
+ case brainpoolP192r1:
+ parameters = idBrainpoolP192r1;
+ break;
+ case brainpoolP192t1:
+ parameters = idBrainpoolP192t1;
+ break;
+ case brainpoolP224r1:
+ parameters = idBrainpoolP224r1;
+ break;
+ case brainpoolP224t1:
+ parameters = idBrainpoolP224t1;
+ break;
+ case brainpoolP256r1:
+ parameters = idBrainpoolP256r1;
+ break;
+ case brainpoolP256t1:
+ parameters = idBrainpoolP256t1;
+ break;
+ case brainpoolP320r1:
+ parameters = idBrainpoolP320r1;
+ break;
+ case brainpoolP320t1:
+ parameters = idBrainpoolP320t1;
+ break;
+ case brainpoolP384r1:
+ parameters = idBrainpoolP384r1;
+ break;
+ case brainpoolP384t1:
+ parameters = idBrainpoolP384t1;
+ break;
+ case brainpoolP512r1:
+ parameters = idBrainpoolP512r1;
+ break;
+ case brainpoolP512t1:
+ parameters = idBrainpoolP512t1;
+ break;
+ }
+ if (parameters) {
+ return new AlgorithmIdentifier({
+ algorithm: id_ecPublicKey,
+ parameters: convert_AsnConvert.serialize(new ECParameters({ namedCurve: parameters })),
+ });
+ }
+ }
+ }
+ return null;
+ }
+ toWebAlgorithm(alg) {
+ switch (alg.algorithm) {
+ case id_ecdsaWithSHA1:
+ return { name: ECDSA, hash: { name: "SHA-1" } };
+ case id_ecdsaWithSHA256:
+ return { name: ECDSA, hash: { name: "SHA-256" } };
+ case id_ecdsaWithSHA384:
+ return { name: ECDSA, hash: { name: "SHA-384" } };
+ case id_ecdsaWithSHA512:
+ return { name: ECDSA, hash: { name: "SHA-512" } };
+ case id_ecPublicKey: {
+ if (!alg.parameters) {
+ throw new TypeError("Cannot get required parameters from EC algorithm");
+ }
+ const parameters = convert_AsnConvert.parse(alg.parameters, ECParameters);
+ switch (parameters.namedCurve) {
+ case id_secp256r1:
+ return { name: ECDSA, namedCurve: "P-256" };
+ case EcAlgorithm_1.SECP256K1:
+ return { name: ECDSA, namedCurve: "K-256" };
+ case id_secp384r1:
+ return { name: ECDSA, namedCurve: "P-384" };
+ case id_secp521r1:
+ return { name: ECDSA, namedCurve: "P-521" };
+ case idBrainpoolP160r1:
+ return { name: ECDSA, namedCurve: brainpoolP160r1 };
+ case idBrainpoolP160t1:
+ return { name: ECDSA, namedCurve: brainpoolP160t1 };
+ case idBrainpoolP192r1:
+ return { name: ECDSA, namedCurve: brainpoolP192r1 };
+ case idBrainpoolP192t1:
+ return { name: ECDSA, namedCurve: brainpoolP192t1 };
+ case idBrainpoolP224r1:
+ return { name: ECDSA, namedCurve: brainpoolP224r1 };
+ case idBrainpoolP224t1:
+ return { name: ECDSA, namedCurve: brainpoolP224t1 };
+ case idBrainpoolP256r1:
+ return { name: ECDSA, namedCurve: brainpoolP256r1 };
+ case idBrainpoolP256t1:
+ return { name: ECDSA, namedCurve: brainpoolP256t1 };
+ case idBrainpoolP320r1:
+ return { name: ECDSA, namedCurve: brainpoolP320r1 };
+ case idBrainpoolP320t1:
+ return { name: ECDSA, namedCurve: brainpoolP320t1 };
+ case idBrainpoolP384r1:
+ return { name: ECDSA, namedCurve: brainpoolP384r1 };
+ case idBrainpoolP384t1:
+ return { name: ECDSA, namedCurve: brainpoolP384t1 };
+ case idBrainpoolP512r1:
+ return { name: ECDSA, namedCurve: brainpoolP512r1 };
+ case idBrainpoolP512t1:
+ return { name: ECDSA, namedCurve: brainpoolP512t1 };
+ }
+ }
+ }
+ return null;
+ }
+};
+EcAlgorithm.SECP256K1 = "1.3.132.0.10";
+EcAlgorithm = EcAlgorithm_1 = __decorate([
+ decorators_injectable()
+], EcAlgorithm);
+instance.registerSingleton(diAlgorithm, EcAlgorithm);
+
+const x509_es_NAME = Symbol("name");
+const VALUE = Symbol("value");
+class TextObject {
+ constructor(name, items = {}, value = "") {
+ this[x509_es_NAME] = name;
+ this[VALUE] = value;
+ for (const key in items) {
+ this[key] = items[key];
+ }
+ }
+}
+TextObject.NAME = x509_es_NAME;
+TextObject.VALUE = VALUE;
+class DefaultAlgorithmSerializer {
+ static toTextObject(alg) {
+ const obj = new TextObject("Algorithm Identifier", {}, OidSerializer.toString(alg.algorithm));
+ if (alg.parameters) {
+ switch (alg.algorithm) {
+ case id_ecPublicKey: {
+ const ecAlg = new EcAlgorithm().toWebAlgorithm(alg);
+ if (ecAlg && "namedCurve" in ecAlg) {
+ obj["Named Curve"] = ecAlg.namedCurve;
+ }
+ else {
+ obj["Parameters"] = alg.parameters;
+ }
+ break;
+ }
+ default:
+ obj["Parameters"] = alg.parameters;
+ }
+ }
+ return obj;
+ }
+}
+class OidSerializer {
+ static toString(oid) {
+ const name = this.items[oid];
+ if (name) {
+ return name;
+ }
+ return oid;
+ }
+}
+OidSerializer.items = {
+ [id_sha1]: "sha1",
+ [id_sha224]: "sha224",
+ [id_sha256]: "sha256",
+ [id_sha384]: "sha384",
+ [id_sha512]: "sha512",
+ [id_rsaEncryption]: "rsaEncryption",
+ [id_sha1WithRSAEncryption]: "sha1WithRSAEncryption",
+ [id_sha224WithRSAEncryption]: "sha224WithRSAEncryption",
+ [id_sha256WithRSAEncryption]: "sha256WithRSAEncryption",
+ [id_sha384WithRSAEncryption]: "sha384WithRSAEncryption",
+ [id_sha512WithRSAEncryption]: "sha512WithRSAEncryption",
+ [id_ecPublicKey]: "ecPublicKey",
+ [id_ecdsaWithSHA1]: "ecdsaWithSHA1",
+ [id_ecdsaWithSHA224]: "ecdsaWithSHA224",
+ [id_ecdsaWithSHA256]: "ecdsaWithSHA256",
+ [id_ecdsaWithSHA384]: "ecdsaWithSHA384",
+ [id_ecdsaWithSHA512]: "ecdsaWithSHA512",
+ [id_kp_serverAuth]: "TLS WWW server authentication",
+ [id_kp_clientAuth]: "TLS WWW client authentication",
+ [id_kp_codeSigning]: "Code Signing",
+ [id_kp_emailProtection]: "E-mail Protection",
+ [id_kp_timeStamping]: "Time Stamping",
+ [id_kp_OCSPSigning]: "OCSP Signing",
+ [id_signedData]: "Signed Data",
+};
+class TextConverter {
+ static serialize(obj) {
+ return this.serializeObj(obj).join("\n");
+ }
+ static pad(deep = 0) {
+ return "".padStart(2 * deep, " ");
+ }
+ static serializeObj(obj, deep = 0) {
+ const res = [];
+ let pad = this.pad(deep++);
+ let value = "";
+ const objValue = obj[TextObject.VALUE];
+ if (objValue) {
+ value = ` ${objValue}`;
+ }
+ res.push(`${pad}${obj[TextObject.NAME]}:${value}`);
+ pad = this.pad(deep);
+ for (const key in obj) {
+ if (typeof key === "symbol") {
+ continue;
+ }
+ const value = obj[key];
+ const keyValue = key ? `${key}: ` : "";
+ if (typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean") {
+ res.push(`${pad}${keyValue}${value}`);
+ }
+ else if (value instanceof Date) {
+ res.push(`${pad}${keyValue}${value.toUTCString()}`);
+ }
+ else if (Array.isArray(value)) {
+ for (const obj of value) {
+ obj[TextObject.NAME] = key;
+ res.push(...this.serializeObj(obj, deep));
+ }
+ }
+ else if (value instanceof TextObject) {
+ value[TextObject.NAME] = key;
+ res.push(...this.serializeObj(value, deep));
+ }
+ else if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(value)) {
+ if (key) {
+ res.push(`${pad}${keyValue}`);
+ res.push(...this.serializeBufferSource(value, deep + 1));
+ }
+ else {
+ res.push(...this.serializeBufferSource(value, deep));
+ }
+ }
+ else if ("toTextObject" in value) {
+ const obj = value.toTextObject();
+ obj[TextObject.NAME] = key;
+ res.push(...this.serializeObj(obj, deep));
+ }
+ else {
+ throw new TypeError("Cannot serialize data in text format. Unsupported type.");
+ }
+ }
+ return res;
+ }
+ static serializeBufferSource(buffer, deep = 0) {
+ const pad = this.pad(deep);
+ const view = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(buffer);
+ const res = [];
+ for (let i = 0; i < view.length;) {
+ const row = [];
+ for (let j = 0; j < 16 && i < view.length; j++) {
+ if (j === 8) {
+ row.push("");
+ }
+ const hex = view[i++].toString(16).padStart(2, "0");
+ row.push(hex);
+ }
+ res.push(`${pad}${row.join(" ")}`);
+ }
+ return res;
+ }
+ static serializeAlgorithm(alg) {
+ return this.algorithmSerializer.toTextObject(alg);
+ }
+}
+TextConverter.oidSerializer = OidSerializer;
+TextConverter.algorithmSerializer = DefaultAlgorithmSerializer;
+
+class AsnData {
+ constructor(...args) {
+ if (args.length === 1) {
+ const asn = args[0];
+ this.rawData = convert_AsnConvert.serialize(asn);
+ this.onInit(asn);
+ }
+ else {
+ const asn = convert_AsnConvert.parse(args[0], args[1]);
+ this.rawData = build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(args[0]);
+ this.onInit(asn);
+ }
+ }
+ equal(data) {
+ if (data instanceof AsnData) {
+ return (0,build/* isEqual */.Xy)(data.rawData, this.rawData);
+ }
+ return false;
+ }
+ toString(format = "text") {
+ switch (format) {
+ case "asn":
+ return convert_AsnConvert.toString(this.rawData);
+ case "text":
+ return TextConverter.serialize(this.toTextObject());
+ case "hex":
+ return build/* Convert.ToHex */.ep.ToHex(this.rawData);
+ case "base64":
+ return build/* Convert.ToBase64 */.ep.ToBase64(this.rawData);
+ case "base64url":
+ return build/* Convert.ToBase64Url */.ep.ToBase64Url(this.rawData);
+ default:
+ throw TypeError("Argument 'format' is unsupported value");
+ }
+ }
+ getTextName() {
+ const constructor = this.constructor;
+ return constructor.NAME;
+ }
+ toTextObject() {
+ const obj = this.toTextObjectEmpty();
+ obj[""] = this.rawData;
+ return obj;
+ }
+ toTextObjectEmpty(value) {
+ return new TextObject(this.getTextName(), {}, value);
+ }
+}
+AsnData.NAME = "ASN";
+
+class Extension extends AsnData {
+ constructor(...args) {
+ let raw;
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ raw = build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(args[0]);
+ }
+ else {
+ raw = convert_AsnConvert.serialize(new extension_Extension({
+ extnID: args[0],
+ critical: args[1],
+ extnValue: new octet_string_OctetString(build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(args[2])),
+ }));
+ }
+ super(raw, extension_Extension);
+ }
+ onInit(asn) {
+ this.type = asn.extnID;
+ this.critical = asn.critical;
+ this.value = asn.extnValue.buffer;
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ obj[""] = this.value;
+ return obj;
+ }
+ toTextObjectWithoutValue() {
+ const obj = this.toTextObjectEmpty(this.critical ? "critical" : undefined);
+ if (obj[TextObject.NAME] === Extension.NAME) {
+ obj[TextObject.NAME] = OidSerializer.toString(this.type);
+ }
+ return obj;
+ }
+}
+
+var x509_es_a;
+class CryptoProvider {
+ static isCryptoKeyPair(data) {
+ return data && data.privateKey && data.publicKey;
+ }
+ static isCryptoKey(data) {
+ return data && data.usages && data.type && data.algorithm && data.extractable !== undefined;
+ }
+ constructor() {
+ this.items = new Map();
+ this[x509_es_a] = "CryptoProvider";
+ if (typeof self !== "undefined" && typeof crypto !== "undefined") {
+ this.set(CryptoProvider.DEFAULT, crypto);
+ }
+ }
+ clear() {
+ this.items.clear();
+ }
+ delete(key) {
+ return this.items.delete(key);
+ }
+ forEach(callbackfn, thisArg) {
+ return this.items.forEach(callbackfn, thisArg);
+ }
+ has(key) {
+ return this.items.has(key);
+ }
+ get size() {
+ return this.items.size;
+ }
+ entries() {
+ return this.items.entries();
+ }
+ keys() {
+ return this.items.keys();
+ }
+ values() {
+ return this.items.values();
+ }
+ [Symbol.iterator]() {
+ return this.items[Symbol.iterator]();
+ }
+ get(key = CryptoProvider.DEFAULT) {
+ const crypto = this.items.get(key.toLowerCase());
+ if (!crypto) {
+ throw new Error(`Cannot get Crypto by name '${key}'`);
+ }
+ return crypto;
+ }
+ set(key, value) {
+ if (typeof key === "string") {
+ if (!value) {
+ throw new TypeError("Argument 'value' is required");
+ }
+ this.items.set(key.toLowerCase(), value);
+ }
+ else {
+ this.items.set(CryptoProvider.DEFAULT, key);
+ }
+ return this;
+ }
+}
+x509_es_a = Symbol.toStringTag;
+CryptoProvider.DEFAULT = "default";
+const cryptoProvider = new CryptoProvider();
+
+const OID_REGEX = /^[0-2](?:\.[1-9][0-9]*)+$/;
+function isOID(id) {
+ return new RegExp(OID_REGEX).test(id);
+}
+class NameIdentifier {
+ constructor(names = {}) {
+ this.items = {};
+ for (const id in names) {
+ this.register(id, names[id]);
+ }
+ }
+ get(idOrName) {
+ return this.items[idOrName] || null;
+ }
+ findId(idOrName) {
+ if (!isOID(idOrName)) {
+ return this.get(idOrName);
+ }
+ return idOrName;
+ }
+ register(id, name) {
+ this.items[id] = name;
+ this.items[name] = id;
+ }
+}
+const names = new NameIdentifier();
+names.register("CN", "2.5.4.3");
+names.register("L", "2.5.4.7");
+names.register("ST", "2.5.4.8");
+names.register("O", "2.5.4.10");
+names.register("OU", "2.5.4.11");
+names.register("C", "2.5.4.6");
+names.register("DC", "0.9.2342.19200300.100.1.25");
+names.register("E", "1.2.840.113549.1.9.1");
+names.register("G", "2.5.4.42");
+names.register("I", "2.5.4.43");
+names.register("SN", "2.5.4.4");
+names.register("T", "2.5.4.12");
+function replaceUnknownCharacter(text, char) {
+ return `\\${build/* Convert.ToHex */.ep.ToHex(build/* Convert.FromUtf8String */.ep.FromUtf8String(char)).toUpperCase()}`;
+}
+function x509_es_escape(data) {
+ return data
+ .replace(/([,+"\\<>;])/g, "\\$1")
+ .replace(/^([ #])/, "\\$1")
+ .replace(/([ ]$)/, "\\$1")
+ .replace(/([\r\n\t])/, replaceUnknownCharacter);
+}
+class Name {
+ static isASCII(text) {
+ for (let i = 0; i < text.length; i++) {
+ const code = text.charCodeAt(i);
+ if (code > 0xFF) {
+ return false;
+ }
+ }
+ return true;
+ }
+ constructor(data, extraNames = {}) {
+ this.extraNames = new NameIdentifier();
+ this.asn = new name_Name();
+ for (const key in extraNames) {
+ if (Object.prototype.hasOwnProperty.call(extraNames, key)) {
+ const value = extraNames[key];
+ this.extraNames.register(key, value);
+ }
+ }
+ if (typeof data === "string") {
+ this.asn = this.fromString(data);
+ }
+ else if (data instanceof name_Name) {
+ this.asn = data;
+ }
+ else if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(data)) {
+ this.asn = convert_AsnConvert.parse(data, name_Name);
+ }
+ else {
+ this.asn = this.fromJSON(data);
+ }
+ }
+ getField(idOrName) {
+ const id = this.extraNames.findId(idOrName) || names.findId(idOrName);
+ const res = [];
+ for (const name of this.asn) {
+ for (const rdn of name) {
+ if (rdn.type === id) {
+ res.push(rdn.value.toString());
+ }
+ }
+ }
+ return res;
+ }
+ getName(idOrName) {
+ return this.extraNames.get(idOrName) || names.get(idOrName);
+ }
+ toString() {
+ return this.asn.map(rdn => rdn.map(o => {
+ const type = this.getName(o.type) || o.type;
+ const value = o.value.anyValue
+ ? `#${build/* Convert.ToHex */.ep.ToHex(o.value.anyValue)}`
+ : x509_es_escape(o.value.toString());
+ return `${type}=${value}`;
+ })
+ .join("+"))
+ .join(", ");
+ }
+ toJSON() {
+ var _a;
+ const json = [];
+ for (const rdn of this.asn) {
+ const jsonItem = {};
+ for (const attr of rdn) {
+ const type = this.getName(attr.type) || attr.type;
+ (_a = jsonItem[type]) !== null && _a !== void 0 ? _a : (jsonItem[type] = []);
+ jsonItem[type].push(attr.value.anyValue ? `#${build/* Convert.ToHex */.ep.ToHex(attr.value.anyValue)}` : attr.value.toString());
+ }
+ json.push(jsonItem);
+ }
+ return json;
+ }
+ fromString(data) {
+ const asn = new name_Name();
+ const regex = /(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;
+ let matches = null;
+ let level = ",";
+ while (matches = regex.exec(`${data},`)) {
+ let [, type, value] = matches;
+ const lastChar = value[value.length - 1];
+ if (lastChar === "," || lastChar === "+") {
+ value = value.slice(0, value.length - 1);
+ matches[3] = lastChar;
+ }
+ const next = matches[3];
+ if (!/[\d.]+/.test(type)) {
+ type = this.getName(type) || "";
+ }
+ if (!type) {
+ throw new Error(`Cannot get OID for name type '${type}'`);
+ }
+ const attr = new AttributeTypeAndValue({ type });
+ if (value.charAt(0) === "#") {
+ attr.value.anyValue = build/* Convert.FromHex */.ep.FromHex(value.slice(1));
+ }
+ else {
+ const quotedMatches = /"(.*?[^\\])?"/.exec(value);
+ if (quotedMatches) {
+ value = quotedMatches[1];
+ }
+ value = value
+ .replace(/\\0a/ig, "\n")
+ .replace(/\\0d/ig, "\r")
+ .replace(/\\0g/ig, "\t")
+ .replace(/\\(.)/g, "$1");
+ if (type === this.getName("E") || type === this.getName("DC")) {
+ attr.value.ia5String = value;
+ }
+ else {
+ if (Name.isASCII(value)) {
+ attr.value.printableString = value;
+ }
+ else {
+ attr.value.utf8String = value;
+ }
+ }
+ }
+ if (level === "+") {
+ asn[asn.length - 1].push(attr);
+ }
+ else {
+ asn.push(new RelativeDistinguishedName([attr]));
+ }
+ level = next;
+ }
+ return asn;
+ }
+ fromJSON(data) {
+ const asn = new name_Name();
+ for (const item of data) {
+ const asnRdn = new RelativeDistinguishedName();
+ for (const type in item) {
+ let typeId = type;
+ if (!/[\d.]+/.test(type)) {
+ typeId = this.getName(type) || "";
+ }
+ if (!typeId) {
+ throw new Error(`Cannot get OID for name type '${type}'`);
+ }
+ const values = item[type];
+ for (const value of values) {
+ const asnAttr = new AttributeTypeAndValue({ type: typeId });
+ if (typeof value === "object") {
+ for (const key in value) {
+ switch (key) {
+ case "ia5String":
+ asnAttr.value.ia5String = value[key];
+ break;
+ case "utf8String":
+ asnAttr.value.utf8String = value[key];
+ break;
+ case "universalString":
+ asnAttr.value.universalString = value[key];
+ break;
+ case "bmpString":
+ asnAttr.value.bmpString = value[key];
+ break;
+ case "printableString":
+ asnAttr.value.printableString = value[key];
+ break;
+ }
+ }
+ }
+ else if (value[0] === "#") {
+ asnAttr.value.anyValue = build/* Convert.FromHex */.ep.FromHex(value.slice(1));
+ }
+ else {
+ if (typeId === this.getName("E") || typeId === this.getName("DC")) {
+ asnAttr.value.ia5String = value;
+ }
+ else {
+ asnAttr.value.printableString = value;
+ }
+ }
+ asnRdn.push(asnAttr);
+ }
+ }
+ asn.push(asnRdn);
+ }
+ return asn;
+ }
+ toArrayBuffer() {
+ return convert_AsnConvert.serialize(this.asn);
+ }
+ async getThumbprint(...args) {
+ var _a;
+ let crypto;
+ let algorithm = "SHA-1";
+ if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
+ algorithm = args[0] || algorithm;
+ crypto = args[1] || cryptoProvider.get();
+ }
+ else {
+ crypto = args[0] || cryptoProvider.get();
+ }
+ return await crypto.subtle.digest(algorithm, this.toArrayBuffer());
+ }
+}
+
+const ERR_GN_CONSTRUCTOR = "Cannot initialize GeneralName from ASN.1 data.";
+const ERR_GN_STRING_FORMAT = `${ERR_GN_CONSTRUCTOR} Unsupported string format in use.`;
+const ERR_GUID = `${ERR_GN_CONSTRUCTOR} Value doesn't match to GUID regular expression.`;
+const GUID_REGEX = /^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i;
+const id_GUID = "1.3.6.1.4.1.311.25.1";
+const id_UPN = "1.3.6.1.4.1.311.20.2.3";
+const DNS = "dns";
+const DN = "dn";
+const EMAIL = "email";
+const IP = "ip";
+const x509_es_URL = "url";
+const GUID = "guid";
+const UPN = "upn";
+const REGISTERED_ID = "id";
+class GeneralName extends AsnData {
+ constructor(...args) {
+ let name;
+ if (args.length === 2) {
+ switch (args[0]) {
+ case DN: {
+ const derName = new Name(args[1]).toArrayBuffer();
+ const asnName = convert_AsnConvert.parse(derName, name_Name);
+ name = new general_name_GeneralName({ directoryName: asnName });
+ break;
+ }
+ case DNS:
+ name = new general_name_GeneralName({ dNSName: args[1] });
+ break;
+ case EMAIL:
+ name = new general_name_GeneralName({ rfc822Name: args[1] });
+ break;
+ case GUID: {
+ const matches = new RegExp(GUID_REGEX, "i").exec(args[1]);
+ if (!matches) {
+ throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");
+ }
+ const hex = matches
+ .slice(1)
+ .map((o, i) => {
+ if (i < 3) {
+ return build/* Convert.ToHex */.ep.ToHex(new Uint8Array(build/* Convert.FromHex */.ep.FromHex(o)).reverse());
+ }
+ return o;
+ })
+ .join("");
+ name = new general_name_GeneralName({
+ otherName: new OtherName({
+ typeId: id_GUID,
+ value: convert_AsnConvert.serialize(new octet_string_OctetString(build/* Convert.FromHex */.ep.FromHex(hex))),
+ }),
+ });
+ break;
+ }
+ case IP:
+ name = new general_name_GeneralName({ iPAddress: args[1] });
+ break;
+ case REGISTERED_ID:
+ name = new general_name_GeneralName({ registeredID: args[1] });
+ break;
+ case UPN: {
+ name = new general_name_GeneralName({
+ otherName: new OtherName({
+ typeId: id_UPN,
+ value: convert_AsnConvert.serialize(AsnUtf8StringConverter.toASN(args[1])),
+ })
+ });
+ break;
+ }
+ case x509_es_URL:
+ name = new general_name_GeneralName({ uniformResourceIdentifier: args[1] });
+ break;
+ default:
+ throw new Error("Cannot create GeneralName. Unsupported type of the name");
+ }
+ }
+ else if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ name = convert_AsnConvert.parse(args[0], general_name_GeneralName);
+ }
+ else {
+ name = args[0];
+ }
+ super(name);
+ }
+ onInit(asn) {
+ if (asn.dNSName != undefined) {
+ this.type = DNS;
+ this.value = asn.dNSName;
+ }
+ else if (asn.rfc822Name != undefined) {
+ this.type = EMAIL;
+ this.value = asn.rfc822Name;
+ }
+ else if (asn.iPAddress != undefined) {
+ this.type = IP;
+ this.value = asn.iPAddress;
+ }
+ else if (asn.uniformResourceIdentifier != undefined) {
+ this.type = x509_es_URL;
+ this.value = asn.uniformResourceIdentifier;
+ }
+ else if (asn.registeredID != undefined) {
+ this.type = REGISTERED_ID;
+ this.value = asn.registeredID;
+ }
+ else if (asn.directoryName != undefined) {
+ this.type = DN;
+ this.value = new Name(asn.directoryName).toString();
+ }
+ else if (asn.otherName != undefined) {
+ if (asn.otherName.typeId === id_GUID) {
+ this.type = GUID;
+ const guid = convert_AsnConvert.parse(asn.otherName.value, octet_string_OctetString);
+ const matches = new RegExp(GUID_REGEX, "i").exec(build/* Convert.ToHex */.ep.ToHex(guid));
+ if (!matches) {
+ throw new Error(ERR_GUID);
+ }
+ this.value = matches
+ .slice(1)
+ .map((o, i) => {
+ if (i < 3) {
+ return build/* Convert.ToHex */.ep.ToHex(new Uint8Array(build/* Convert.FromHex */.ep.FromHex(o)).reverse());
+ }
+ return o;
+ })
+ .join("-");
+ }
+ else if (asn.otherName.typeId === id_UPN) {
+ this.type = UPN;
+ this.value = convert_AsnConvert.parse(asn.otherName.value, DirectoryString).toString();
+ }
+ else {
+ throw new Error(ERR_GN_STRING_FORMAT);
+ }
+ }
+ else {
+ throw new Error(ERR_GN_STRING_FORMAT);
+ }
+ }
+ toJSON() {
+ return {
+ type: this.type,
+ value: this.value,
+ };
+ }
+ toTextObject() {
+ let type;
+ switch (this.type) {
+ case DN:
+ case DNS:
+ case GUID:
+ case IP:
+ case REGISTERED_ID:
+ case UPN:
+ case x509_es_URL:
+ type = this.type.toUpperCase();
+ break;
+ case EMAIL:
+ type = "Email";
+ break;
+ default:
+ throw new Error("Unsupported GeneralName type");
+ }
+ let value = this.value;
+ if (this.type === REGISTERED_ID) {
+ value = OidSerializer.toString(value);
+ }
+ return new TextObject(type, undefined, value);
+ }
+}
+class GeneralNames extends AsnData {
+ constructor(params) {
+ let names;
+ if (params instanceof general_names_GeneralNames) {
+ names = params;
+ }
+ else if (Array.isArray(params)) {
+ const items = [];
+ for (const name of params) {
+ if (name instanceof general_name_GeneralName) {
+ items.push(name);
+ }
+ else {
+ const asnName = convert_AsnConvert.parse(new GeneralName(name.type, name.value).rawData, general_name_GeneralName);
+ items.push(asnName);
+ }
+ }
+ names = new general_names_GeneralNames(items);
+ }
+ else if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(params)) {
+ names = convert_AsnConvert.parse(params, general_names_GeneralNames);
+ }
+ else {
+ throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");
+ }
+ super(names);
+ }
+ onInit(asn) {
+ const items = [];
+ for (const asnName of asn) {
+ let name = null;
+ try {
+ name = new GeneralName(asnName);
+ }
+ catch {
+ continue;
+ }
+ items.push(name);
+ }
+ this.items = items;
+ }
+ toJSON() {
+ return this.items.map(o => o.toJSON());
+ }
+ toTextObject() {
+ const res = super.toTextObjectEmpty();
+ for (const name of this.items) {
+ const nameObj = name.toTextObject();
+ let field = res[nameObj[TextObject.NAME]];
+ if (!Array.isArray(field)) {
+ field = [];
+ res[nameObj[TextObject.NAME]] = field;
+ }
+ field.push(nameObj);
+ }
+ return res;
+ }
+}
+GeneralNames.NAME = "GeneralNames";
+
+const rPaddingTag = "-{5}";
+const rEolChars = "\\n";
+const rNameTag = `[^${rEolChars}]+`;
+const rBeginTag = `${rPaddingTag}BEGIN (${rNameTag}(?=${rPaddingTag}))${rPaddingTag}`;
+const rEndTag = `${rPaddingTag}END \\1${rPaddingTag}`;
+const rEolGroup = "\\n";
+const rHeaderKey = `[^:${rEolChars}]+`;
+const rHeaderValue = `(?:[^${rEolChars}]+${rEolGroup}(?: +[^${rEolChars}]+${rEolGroup})*)`;
+const rBase64Chars = "[a-zA-Z0-9=+/]+";
+const rBase64 = `(?:${rBase64Chars}${rEolGroup})+`;
+const rPem = `${rBeginTag}${rEolGroup}(?:((?:${rHeaderKey}: ${rHeaderValue})+))?${rEolGroup}?(${rBase64})${rEndTag}`;
+class PemConverter {
+ static isPem(data) {
+ return typeof data === "string"
+ && new RegExp(rPem, "g").test(data);
+ }
+ static decodeWithHeaders(pem) {
+ pem = pem.replace(/\r/g, "");
+ const pattern = new RegExp(rPem, "g");
+ const res = [];
+ let matches = null;
+ while (matches = pattern.exec(pem)) {
+ const base64 = matches[3]
+ .replace(new RegExp(`[${rEolChars}]+`, "g"), "");
+ const pemStruct = {
+ type: matches[1],
+ headers: [],
+ rawData: build/* Convert.FromBase64 */.ep.FromBase64(base64),
+ };
+ const headersString = matches[2];
+ if (headersString) {
+ const headers = headersString.split(new RegExp(rEolGroup, "g"));
+ let lastHeader = null;
+ for (const header of headers) {
+ const [key, value] = header.split(/:(.*)/);
+ if (value === undefined) {
+ if (!lastHeader) {
+ throw new Error("Cannot parse PEM string. Incorrect header value");
+ }
+ lastHeader.value += key.trim();
+ }
+ else {
+ if (lastHeader) {
+ pemStruct.headers.push(lastHeader);
+ }
+ lastHeader = { key, value: value.trim() };
+ }
+ }
+ if (lastHeader) {
+ pemStruct.headers.push(lastHeader);
+ }
+ }
+ res.push(pemStruct);
+ }
+ return res;
+ }
+ static decode(pem) {
+ const blocks = this.decodeWithHeaders(pem);
+ return blocks.map(o => o.rawData);
+ }
+ static decodeFirst(pem) {
+ const items = this.decode(pem);
+ if (!items.length) {
+ throw new RangeError("PEM string doesn't contain any objects");
+ }
+ return items[0];
+ }
+ static encode(rawData, tag) {
+ if (Array.isArray(rawData)) {
+ const raws = new Array();
+ if (tag) {
+ rawData.forEach(element => {
+ if (!build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(element)) {
+ throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");
+ }
+ raws.push(this.encodeStruct({
+ type: tag,
+ rawData: build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(element),
+ }));
+ });
+ }
+ else {
+ rawData.forEach(element => {
+ if (!("type" in element)) {
+ throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");
+ }
+ raws.push(this.encodeStruct(element));
+ });
+ }
+ return raws.join("\n");
+ }
+ else {
+ if (!tag) {
+ throw new Error("Required argument 'tag' is missed");
+ }
+ return this.encodeStruct({
+ type: tag,
+ rawData: build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(rawData),
+ });
+ }
+ }
+ static encodeStruct(pem) {
+ var _a;
+ const upperCaseType = pem.type.toLocaleUpperCase();
+ const res = [];
+ res.push(`-----BEGIN ${upperCaseType}-----`);
+ if ((_a = pem.headers) === null || _a === void 0 ? void 0 : _a.length) {
+ for (const header of pem.headers) {
+ res.push(`${header.key}: ${header.value}`);
+ }
+ res.push("");
+ }
+ const base64 = build/* Convert.ToBase64 */.ep.ToBase64(pem.rawData);
+ let sliced;
+ let offset = 0;
+ const rows = Array();
+ while (offset < base64.length) {
+ if (base64.length - offset < 64) {
+ sliced = base64.substring(offset);
+ }
+ else {
+ sliced = base64.substring(offset, offset + 64);
+ offset += 64;
+ }
+ if (sliced.length !== 0) {
+ rows.push(sliced);
+ if (sliced.length < 64) {
+ break;
+ }
+ }
+ else {
+ break;
+ }
+ }
+ res.push(...rows);
+ res.push(`-----END ${upperCaseType}-----`);
+ return res.join("\n");
+ }
+}
+PemConverter.CertificateTag = "CERTIFICATE";
+PemConverter.CrlTag = "CRL";
+PemConverter.CertificateRequestTag = "CERTIFICATE REQUEST";
+PemConverter.PublicKeyTag = "PUBLIC KEY";
+PemConverter.PrivateKeyTag = "PRIVATE KEY";
+
+class PemData extends AsnData {
+ static isAsnEncoded(data) {
+ return build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(data) || typeof data === "string";
+ }
+ static toArrayBuffer(raw) {
+ if (typeof raw === "string") {
+ if (PemConverter.isPem(raw)) {
+ return PemConverter.decode(raw)[0];
+ }
+ else if (build/* Convert.isHex */.ep.isHex(raw)) {
+ return build/* Convert.FromHex */.ep.FromHex(raw);
+ }
+ else if (build/* Convert.isBase64 */.ep.isBase64(raw)) {
+ return build/* Convert.FromBase64 */.ep.FromBase64(raw);
+ }
+ else if (build/* Convert.isBase64Url */.ep.isBase64Url(raw)) {
+ return build/* Convert.FromBase64Url */.ep.FromBase64Url(raw);
+ }
+ else {
+ throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");
+ }
+ }
+ else {
+ const stringRaw = build/* Convert.ToBinary */.ep.ToBinary(raw);
+ if (PemConverter.isPem(stringRaw)) {
+ return PemConverter.decode(stringRaw)[0];
+ }
+ else if (build/* Convert.isHex */.ep.isHex(stringRaw)) {
+ return build/* Convert.FromHex */.ep.FromHex(stringRaw);
+ }
+ else if (build/* Convert.isBase64 */.ep.isBase64(stringRaw)) {
+ return build/* Convert.FromBase64 */.ep.FromBase64(stringRaw);
+ }
+ else if (build/* Convert.isBase64Url */.ep.isBase64Url(stringRaw)) {
+ return build/* Convert.FromBase64Url */.ep.FromBase64Url(stringRaw);
+ }
+ return build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(raw);
+ }
+ }
+ constructor(...args) {
+ if (PemData.isAsnEncoded(args[0])) {
+ super(PemData.toArrayBuffer(args[0]), args[1]);
+ }
+ else {
+ super(args[0]);
+ }
+ }
+ toString(format = "pem") {
+ switch (format) {
+ case "pem":
+ return PemConverter.encode(this.rawData, this.tag);
+ default:
+ return super.toString(format);
+ }
+ }
+}
+
+class PublicKey extends PemData {
+ constructor(param) {
+ if (PemData.isAsnEncoded(param)) {
+ super(param, subject_public_key_info_SubjectPublicKeyInfo);
+ }
+ else {
+ super(param);
+ }
+ this.tag = PemConverter.PublicKeyTag;
+ }
+ async export(...args) {
+ let crypto;
+ let keyUsages = ["verify"];
+ let algorithm = { hash: "SHA-256", ...this.algorithm };
+ if (args.length > 1) {
+ algorithm = args[0] || algorithm;
+ keyUsages = args[1] || keyUsages;
+ crypto = args[2] || cryptoProvider.get();
+ }
+ else {
+ crypto = args[0] || cryptoProvider.get();
+ }
+ return crypto.subtle.importKey("spki", this.rawData, algorithm, true, keyUsages);
+ }
+ onInit(asn) {
+ const algProv = instance.resolve(diAlgorithmProvider);
+ const algorithm = this.algorithm = algProv.toWebAlgorithm(asn.algorithm);
+ switch (asn.algorithm.algorithm) {
+ case id_rsaEncryption:
+ {
+ const rsaPublicKey = convert_AsnConvert.parse(asn.subjectPublicKey, RSAPublicKey);
+ const modulus = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(rsaPublicKey.modulus);
+ algorithm.publicExponent = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(rsaPublicKey.publicExponent);
+ algorithm.modulusLength = (!modulus[0] ? modulus.slice(1) : modulus).byteLength << 3;
+ break;
+ }
+ }
+ }
+ async getThumbprint(...args) {
+ var _a;
+ let crypto;
+ let algorithm = "SHA-1";
+ if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
+ algorithm = args[0] || algorithm;
+ crypto = args[1] || cryptoProvider.get();
+ }
+ else {
+ crypto = args[0] || cryptoProvider.get();
+ }
+ return await crypto.subtle.digest(algorithm, this.rawData);
+ }
+ async getKeyIdentifier(crypto) {
+ if (!crypto) {
+ crypto = cryptoProvider.get();
+ }
+ const asn = convert_AsnConvert.parse(this.rawData, subject_public_key_info_SubjectPublicKeyInfo);
+ return await crypto.subtle.digest("SHA-1", asn.subjectPublicKey);
+ }
+ toTextObject() {
+ const obj = this.toTextObjectEmpty();
+ const asn = convert_AsnConvert.parse(this.rawData, subject_public_key_info_SubjectPublicKeyInfo);
+ obj["Algorithm"] = TextConverter.serializeAlgorithm(asn.algorithm);
+ switch (asn.algorithm.algorithm) {
+ case id_ecPublicKey:
+ obj["EC Point"] = asn.subjectPublicKey;
+ break;
+ case id_rsaEncryption:
+ default:
+ obj["Raw Data"] = asn.subjectPublicKey;
+ }
+ return obj;
+ }
+}
+
+class ExtensionFactory {
+ static register(id, type) {
+ this.items.set(id, type);
+ }
+ static create(data) {
+ const extension = new Extension(data);
+ const Type = this.items.get(extension.type);
+ if (Type) {
+ return new Type(data);
+ }
+ return extension;
+ }
+}
+ExtensionFactory.items = new Map();
+
+const diAsnSignatureFormatter = "crypto.signatureFormatter";
+class AsnDefaultSignatureFormatter {
+ toAsnSignature(algorithm, signature) {
+ return build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(signature);
+ }
+ toWebSignature(algorithm, signature) {
+ return build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(signature);
+ }
+}
+
+class X509Certificate extends PemData {
+ constructor(param) {
+ if (PemData.isAsnEncoded(param)) {
+ super(param, certificate_Certificate);
+ }
+ else {
+ super(param);
+ }
+ this.tag = PemConverter.CertificateTag;
+ }
+ onInit(asn) {
+ const tbs = asn.tbsCertificate;
+ this.tbs = convert_AsnConvert.serialize(tbs);
+ this.serialNumber = build/* Convert.ToHex */.ep.ToHex(tbs.serialNumber);
+ this.subjectName = new Name(tbs.subject);
+ this.subject = new Name(tbs.subject).toString();
+ this.issuerName = new Name(tbs.issuer);
+ this.issuer = this.issuerName.toString();
+ const algProv = instance.resolve(diAlgorithmProvider);
+ this.signatureAlgorithm = algProv.toWebAlgorithm(asn.signatureAlgorithm);
+ this.signature = asn.signatureValue;
+ const notBefore = tbs.validity.notBefore.utcTime || tbs.validity.notBefore.generalTime;
+ if (!notBefore) {
+ throw new Error("Cannot get 'notBefore' value");
+ }
+ this.notBefore = notBefore;
+ const notAfter = tbs.validity.notAfter.utcTime || tbs.validity.notAfter.generalTime;
+ if (!notAfter) {
+ throw new Error("Cannot get 'notAfter' value");
+ }
+ this.notAfter = notAfter;
+ this.extensions = [];
+ if (tbs.extensions) {
+ this.extensions = tbs.extensions.map(o => ExtensionFactory.create(convert_AsnConvert.serialize(o)));
+ }
+ this.publicKey = new PublicKey(tbs.subjectPublicKeyInfo);
+ }
+ getExtension(type) {
+ for (const ext of this.extensions) {
+ if (typeof type === "string") {
+ if (ext.type === type) {
+ return ext;
+ }
+ }
+ else {
+ if (ext instanceof type) {
+ return ext;
+ }
+ }
+ }
+ return null;
+ }
+ getExtensions(type) {
+ return this.extensions.filter(o => {
+ if (typeof type === "string") {
+ return o.type === type;
+ }
+ else {
+ return o instanceof type;
+ }
+ });
+ }
+ async verify(params = {}, crypto = cryptoProvider.get()) {
+ let keyAlgorithm;
+ let publicKey;
+ const paramsKey = params.publicKey;
+ try {
+ if (!paramsKey) {
+ keyAlgorithm = { ...this.publicKey.algorithm, ...this.signatureAlgorithm };
+ publicKey = await this.publicKey.export(keyAlgorithm, ["verify"], crypto);
+ }
+ else if ("publicKey" in paramsKey) {
+ keyAlgorithm = { ...paramsKey.publicKey.algorithm, ...this.signatureAlgorithm };
+ publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"], crypto);
+ }
+ else if (paramsKey instanceof PublicKey) {
+ keyAlgorithm = { ...paramsKey.algorithm, ...this.signatureAlgorithm };
+ publicKey = await paramsKey.export(keyAlgorithm, ["verify"], crypto);
+ }
+ else if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(paramsKey)) {
+ const key = new PublicKey(paramsKey);
+ keyAlgorithm = { ...key.algorithm, ...this.signatureAlgorithm };
+ publicKey = await key.export(keyAlgorithm, ["verify"], crypto);
+ }
+ else {
+ keyAlgorithm = { ...paramsKey.algorithm, ...this.signatureAlgorithm };
+ publicKey = paramsKey;
+ }
+ }
+ catch (e) {
+ return false;
+ }
+ const signatureFormatters = instance.resolveAll(diAsnSignatureFormatter).reverse();
+ let signature = null;
+ for (const signatureFormatter of signatureFormatters) {
+ signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
+ if (signature) {
+ break;
+ }
+ }
+ if (!signature) {
+ throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
+ }
+ const ok = await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
+ if (params.signatureOnly) {
+ return ok;
+ }
+ else {
+ const date = params.date || new Date();
+ const time = date.getTime();
+ return ok && this.notBefore.getTime() < time && time < this.notAfter.getTime();
+ }
+ }
+ async getThumbprint(...args) {
+ let crypto;
+ let algorithm = "SHA-1";
+ if (args[0]) {
+ if (!args[0].subtle) {
+ algorithm = args[0] || algorithm;
+ crypto = args[1];
+ }
+ else {
+ crypto = args[0];
+ }
+ }
+ crypto !== null && crypto !== void 0 ? crypto : (crypto = cryptoProvider.get());
+ return await crypto.subtle.digest(algorithm, this.rawData);
+ }
+ async isSelfSigned(crypto = cryptoProvider.get()) {
+ return this.subject === this.issuer && await this.verify({ signatureOnly: true }, crypto);
+ }
+ toTextObject() {
+ const obj = this.toTextObjectEmpty();
+ const cert = convert_AsnConvert.parse(this.rawData, certificate_Certificate);
+ const tbs = cert.tbsCertificate;
+ const data = new TextObject("", {
+ "Version": `${Version[tbs.version]} (${tbs.version})`,
+ "Serial Number": tbs.serialNumber,
+ "Signature Algorithm": TextConverter.serializeAlgorithm(tbs.signature),
+ "Issuer": this.issuer,
+ "Validity": new TextObject("", {
+ "Not Before": tbs.validity.notBefore.getTime(),
+ "Not After": tbs.validity.notAfter.getTime(),
+ }),
+ "Subject": this.subject,
+ "Subject Public Key Info": this.publicKey,
+ });
+ if (tbs.issuerUniqueID) {
+ data["Issuer Unique ID"] = tbs.issuerUniqueID;
+ }
+ if (tbs.subjectUniqueID) {
+ data["Subject Unique ID"] = tbs.subjectUniqueID;
+ }
+ if (this.extensions.length) {
+ const extensions = new TextObject("");
+ for (const ext of this.extensions) {
+ const extObj = ext.toTextObject();
+ extensions[extObj[TextObject.NAME]] = extObj;
+ }
+ data["Extensions"] = extensions;
+ }
+ obj["Data"] = data;
+ obj["Signature"] = new TextObject("", {
+ "Algorithm": TextConverter.serializeAlgorithm(cert.signatureAlgorithm),
+ "": cert.signatureValue,
+ });
+ return obj;
+ }
+}
+X509Certificate.NAME = "Certificate";
+
+class AuthorityKeyIdentifierExtension extends Extension {
+ static async create(param, critical = false, crypto = cryptoProvider.get()) {
+ if (param instanceof X509Certificate || CryptoProvider.isCryptoKey(param)) {
+ const publicKey = param instanceof X509Certificate ? await param.publicKey.export(crypto) : param;
+ const spki = await crypto.subtle.exportKey("spki", publicKey);
+ const key = new PublicKey(spki);
+ const id = await key.getKeyIdentifier(crypto);
+ return new AuthorityKeyIdentifierExtension(build/* Convert.ToHex */.ep.ToHex(id), critical);
+ }
+ else {
+ return new AuthorityKeyIdentifierExtension(param, critical);
+ }
+ }
+ constructor(...args) {
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ super(args[0]);
+ }
+ else if (typeof args[0] === "string") {
+ const value = new AuthorityKeyIdentifier({ keyIdentifier: new KeyIdentifier(build/* Convert.FromHex */.ep.FromHex(args[0])) });
+ super(id_ce_authorityKeyIdentifier, args[1], convert_AsnConvert.serialize(value));
+ }
+ else {
+ const certId = args[0];
+ const certIdName = certId.name instanceof GeneralNames
+ ? convert_AsnConvert.parse(certId.name.rawData, general_names_GeneralNames)
+ : certId.name;
+ const value = new AuthorityKeyIdentifier({
+ authorityCertIssuer: certIdName,
+ authorityCertSerialNumber: build/* Convert.FromHex */.ep.FromHex(certId.serialNumber),
+ });
+ super(id_ce_authorityKeyIdentifier, args[1], convert_AsnConvert.serialize(value));
+ }
+ }
+ onInit(asn) {
+ super.onInit(asn);
+ const aki = convert_AsnConvert.parse(asn.extnValue, AuthorityKeyIdentifier);
+ if (aki.keyIdentifier) {
+ this.keyId = build/* Convert.ToHex */.ep.ToHex(aki.keyIdentifier);
+ }
+ if (aki.authorityCertIssuer && aki.authorityCertSerialNumber) {
+ this.certId = {
+ name: aki.authorityCertIssuer,
+ serialNumber: build/* Convert.ToHex */.ep.ToHex(aki.authorityCertSerialNumber),
+ };
+ }
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ const asn = convert_AsnConvert.parse(this.value, AuthorityKeyIdentifier);
+ if (asn.authorityCertIssuer) {
+ obj["Authority Issuer"] = new GeneralNames(asn.authorityCertIssuer).toTextObject();
+ }
+ if (asn.authorityCertSerialNumber) {
+ obj["Authority Serial Number"] = asn.authorityCertSerialNumber;
+ }
+ if (asn.keyIdentifier) {
+ obj[""] = asn.keyIdentifier;
+ }
+ return obj;
+ }
+}
+AuthorityKeyIdentifierExtension.NAME = "Authority Key Identifier";
+
+class BasicConstraintsExtension extends Extension {
+ constructor(...args) {
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ super(args[0]);
+ const value = convert_AsnConvert.parse(this.value, BasicConstraints);
+ this.ca = value.cA;
+ this.pathLength = value.pathLenConstraint;
+ }
+ else {
+ const value = new BasicConstraints({
+ cA: args[0],
+ pathLenConstraint: args[1],
+ });
+ super(id_ce_basicConstraints, args[2], convert_AsnConvert.serialize(value));
+ this.ca = args[0];
+ this.pathLength = args[1];
+ }
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ if (this.ca) {
+ obj["CA"] = this.ca;
+ }
+ if (this.pathLength !== undefined) {
+ obj["Path Length"] = this.pathLength;
+ }
+ return obj;
+ }
+}
+BasicConstraintsExtension.NAME = "Basic Constraints";
+
+var x509_es_ExtendedKeyUsage;
+(function (ExtendedKeyUsage) {
+ ExtendedKeyUsage["serverAuth"] = "1.3.6.1.5.5.7.3.1";
+ ExtendedKeyUsage["clientAuth"] = "1.3.6.1.5.5.7.3.2";
+ ExtendedKeyUsage["codeSigning"] = "1.3.6.1.5.5.7.3.3";
+ ExtendedKeyUsage["emailProtection"] = "1.3.6.1.5.5.7.3.4";
+ ExtendedKeyUsage["timeStamping"] = "1.3.6.1.5.5.7.3.8";
+ ExtendedKeyUsage["ocspSigning"] = "1.3.6.1.5.5.7.3.9";
+})(x509_es_ExtendedKeyUsage || (x509_es_ExtendedKeyUsage = {}));
+class ExtendedKeyUsageExtension extends Extension {
+ constructor(...args) {
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ super(args[0]);
+ const value = convert_AsnConvert.parse(this.value, ExtendedKeyUsage);
+ this.usages = value.map(o => o);
+ }
+ else {
+ const value = new ExtendedKeyUsage(args[0]);
+ super(id_ce_extKeyUsage, args[1], convert_AsnConvert.serialize(value));
+ this.usages = args[0];
+ }
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ obj[""] = this.usages.map(o => OidSerializer.toString(o)).join(", ");
+ return obj;
+ }
+}
+ExtendedKeyUsageExtension.NAME = "Extended Key Usages";
+
+var x509_es_KeyUsageFlags;
+(function (KeyUsageFlags) {
+ KeyUsageFlags[KeyUsageFlags["digitalSignature"] = 1] = "digitalSignature";
+ KeyUsageFlags[KeyUsageFlags["nonRepudiation"] = 2] = "nonRepudiation";
+ KeyUsageFlags[KeyUsageFlags["keyEncipherment"] = 4] = "keyEncipherment";
+ KeyUsageFlags[KeyUsageFlags["dataEncipherment"] = 8] = "dataEncipherment";
+ KeyUsageFlags[KeyUsageFlags["keyAgreement"] = 16] = "keyAgreement";
+ KeyUsageFlags[KeyUsageFlags["keyCertSign"] = 32] = "keyCertSign";
+ KeyUsageFlags[KeyUsageFlags["cRLSign"] = 64] = "cRLSign";
+ KeyUsageFlags[KeyUsageFlags["encipherOnly"] = 128] = "encipherOnly";
+ KeyUsageFlags[KeyUsageFlags["decipherOnly"] = 256] = "decipherOnly";
+})(x509_es_KeyUsageFlags || (x509_es_KeyUsageFlags = {}));
+class KeyUsagesExtension extends Extension {
+ constructor(...args) {
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ super(args[0]);
+ const value = convert_AsnConvert.parse(this.value, KeyUsage);
+ this.usages = value.toNumber();
+ }
+ else {
+ const value = new KeyUsage(args[0]);
+ super(id_ce_keyUsage, args[1], convert_AsnConvert.serialize(value));
+ this.usages = args[0];
+ }
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ const asn = convert_AsnConvert.parse(this.value, KeyUsage);
+ obj[""] = asn.toJSON().join(", ");
+ return obj;
+ }
+}
+KeyUsagesExtension.NAME = "Key Usages";
+
+class SubjectKeyIdentifierExtension extends Extension {
+ static async create(publicKey, critical = false, crypto = cryptoProvider.get()) {
+ let spki;
+ if (publicKey instanceof PublicKey) {
+ spki = publicKey.rawData;
+ }
+ else if ("publicKey" in publicKey) {
+ spki = publicKey.publicKey.rawData;
+ }
+ else if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(publicKey)) {
+ spki = publicKey;
+ }
+ else {
+ spki = await crypto.subtle.exportKey("spki", publicKey);
+ }
+ const key = new PublicKey(spki);
+ const id = await key.getKeyIdentifier(crypto);
+ return new SubjectKeyIdentifierExtension(build/* Convert.ToHex */.ep.ToHex(id), critical);
+ }
+ constructor(...args) {
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ super(args[0]);
+ const value = convert_AsnConvert.parse(this.value, SubjectKeyIdentifier);
+ this.keyId = build/* Convert.ToHex */.ep.ToHex(value);
+ }
+ else {
+ const identifier = typeof args[0] === "string"
+ ? build/* Convert.FromHex */.ep.FromHex(args[0])
+ : args[0];
+ const value = new SubjectKeyIdentifier(identifier);
+ super(id_ce_subjectKeyIdentifier, args[1], convert_AsnConvert.serialize(value));
+ this.keyId = build/* Convert.ToHex */.ep.ToHex(identifier);
+ }
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ const asn = convert_AsnConvert.parse(this.value, SubjectKeyIdentifier);
+ obj[""] = asn;
+ return obj;
+ }
+}
+SubjectKeyIdentifierExtension.NAME = "Subject Key Identifier";
+
+class SubjectAlternativeNameExtension extends Extension {
+ constructor(...args) {
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ super(args[0]);
+ }
+ else {
+ super(id_ce_subjectAltName, args[1], new GeneralNames(args[0] || []).rawData);
+ }
+ }
+ onInit(asn) {
+ super.onInit(asn);
+ const value = convert_AsnConvert.parse(asn.extnValue, SubjectAlternativeName);
+ this.names = new GeneralNames(value);
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ const namesObj = this.names.toTextObject();
+ for (const key in namesObj) {
+ obj[key] = namesObj[key];
+ }
+ return obj;
+ }
+}
+SubjectAlternativeNameExtension.NAME = "Subject Alternative Name";
+
+class CertificatePolicyExtension extends Extension {
+ constructor(...args) {
+ var _a;
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ super(args[0]);
+ const asnPolicies = convert_AsnConvert.parse(this.value, CertificatePolicies);
+ this.policies = asnPolicies.map(o => o.policyIdentifier);
+ }
+ else {
+ const policies = args[0];
+ const critical = (_a = args[1]) !== null && _a !== void 0 ? _a : false;
+ const value = new CertificatePolicies(policies.map(o => (new PolicyInformation({
+ policyIdentifier: o,
+ }))));
+ super(id_ce_certificatePolicies, critical, convert_AsnConvert.serialize(value));
+ this.policies = policies;
+ }
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ obj["Policy"] = this.policies.map(o => new TextObject("", {}, OidSerializer.toString(o)));
+ return obj;
+ }
+}
+CertificatePolicyExtension.NAME = "Certificate Policies";
+ExtensionFactory.register(id_ce_certificatePolicies, CertificatePolicyExtension);
+
+class x509_es_Attribute extends AsnData {
+ constructor(...args) {
+ let raw;
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ raw = build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(args[0]);
+ }
+ else {
+ const type = args[0];
+ const values = Array.isArray(args[1]) ? args[1].map(o => build/* BufferSourceConverter.toArrayBuffer */.vJ.toArrayBuffer(o)) : [];
+ raw = convert_AsnConvert.serialize(new attribute_Attribute({ type, values }));
+ }
+ super(raw, attribute_Attribute);
+ }
+ onInit(asn) {
+ this.type = asn.type;
+ this.values = asn.values;
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ obj["Value"] = this.values.map(o => new TextObject("", { "": o }));
+ return obj;
+ }
+ toTextObjectWithoutValue() {
+ const obj = this.toTextObjectEmpty();
+ if (obj[TextObject.NAME] === x509_es_Attribute.NAME) {
+ obj[TextObject.NAME] = OidSerializer.toString(this.type);
+ }
+ return obj;
+ }
+}
+x509_es_Attribute.NAME = "Attribute";
+
+class ChallengePasswordAttribute extends x509_es_Attribute {
+ constructor(...args) {
+ var _a;
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ super(args[0]);
+ }
+ else {
+ const value = new ChallengePassword({
+ printableString: args[0],
+ });
+ super(id_pkcs9_at_challengePassword, [convert_AsnConvert.serialize(value)]);
+ }
+ (_a = this.password) !== null && _a !== void 0 ? _a : (this.password = "");
+ }
+ onInit(asn) {
+ super.onInit(asn);
+ if (this.values[0]) {
+ const value = convert_AsnConvert.parse(this.values[0], ChallengePassword);
+ this.password = value.toString();
+ }
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ obj[TextObject.VALUE] = this.password;
+ return obj;
+ }
+}
+ChallengePasswordAttribute.NAME = "Challenge Password";
+
+class ExtensionsAttribute extends x509_es_Attribute {
+ constructor(...args) {
+ var _a;
+ if (build/* BufferSourceConverter.isBufferSource */.vJ.isBufferSource(args[0])) {
+ super(args[0]);
+ }
+ else {
+ const extensions = args[0];
+ const value = new extension_Extensions();
+ for (const extension of extensions) {
+ value.push(convert_AsnConvert.parse(extension.rawData, extension_Extension));
+ }
+ super(es2015_id_pkcs9_at_extensionRequest, [convert_AsnConvert.serialize(value)]);
+ }
+ (_a = this.items) !== null && _a !== void 0 ? _a : (this.items = []);
+ }
+ onInit(asn) {
+ super.onInit(asn);
+ if (this.values[0]) {
+ const value = convert_AsnConvert.parse(this.values[0], extension_Extensions);
+ this.items = value.map(o => ExtensionFactory.create(convert_AsnConvert.serialize(o)));
+ }
+ }
+ toTextObject() {
+ const obj = this.toTextObjectWithoutValue();
+ const extensions = this.items.map(o => o.toTextObject());
+ for (const extension of extensions) {
+ obj[extension[TextObject.NAME]] = extension;
+ }
+ return obj;
+ }
+}
+ExtensionsAttribute.NAME = "Extensions";
+
+class AttributeFactory {
+ static register(id, type) {
+ this.items.set(id, type);
+ }
+ static create(data) {
+ const attribute = new x509_es_Attribute(data);
+ const Type = this.items.get(attribute.type);
+ if (Type) {
+ return new Type(data);
+ }
+ return attribute;
+ }
+}
+AttributeFactory.items = new Map();
+
+let RsaAlgorithm = class RsaAlgorithm {
+ toAsnAlgorithm(alg) {
+ switch (alg.name.toLowerCase()) {
+ case "rsassa-pkcs1-v1_5":
+ if (alg.hash) {
+ switch (alg.hash.name.toLowerCase()) {
+ case "sha-1":
+ return new AlgorithmIdentifier({ algorithm: id_sha1WithRSAEncryption, parameters: null });
+ case "sha-256":
+ return new AlgorithmIdentifier({ algorithm: id_sha256WithRSAEncryption, parameters: null });
+ case "sha-384":
+ return new AlgorithmIdentifier({ algorithm: id_sha384WithRSAEncryption, parameters: null });
+ case "sha-512":
+ return new AlgorithmIdentifier({ algorithm: id_sha512WithRSAEncryption, parameters: null });
+ }
+ }
+ else {
+ return new AlgorithmIdentifier({ algorithm: id_rsaEncryption, parameters: null });
+ }
+ }
+ return null;
+ }
+ toWebAlgorithm(alg) {
+ switch (alg.algorithm) {
+ case id_rsaEncryption:
+ return { name: "RSASSA-PKCS1-v1_5" };
+ case id_sha1WithRSAEncryption:
+ return { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-1" } };
+ case id_sha256WithRSAEncryption:
+ return { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } };
+ case id_sha384WithRSAEncryption:
+ return { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-384" } };
+ case id_sha512WithRSAEncryption:
+ return { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-512" } };
+ }
+ return null;
+ }
+};
+RsaAlgorithm = __decorate([
+ decorators_injectable()
+], RsaAlgorithm);
+instance.registerSingleton(diAlgorithm, RsaAlgorithm);
+
+class AsnEcSignatureFormatter {
+ addPadding(pointSize, data) {
+ const bytes = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(data);
+ const res = new Uint8Array(pointSize);
+ res.set(bytes, pointSize - bytes.length);
+ return res;
+ }
+ removePadding(data, positive = false) {
+ let bytes = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(data);
+ for (let i = 0; i < bytes.length; i++) {
+ if (!bytes[i]) {
+ continue;
+ }
+ bytes = bytes.slice(i);
+ break;
+ }
+ if (positive && bytes[0] > 127) {
+ const result = new Uint8Array(bytes.length + 1);
+ result.set(bytes, 1);
+ return result.buffer;
+ }
+ return bytes.buffer;
+ }
+ toAsnSignature(algorithm, signature) {
+ if (algorithm.name === "ECDSA") {
+ const namedCurve = algorithm.namedCurve;
+ const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve) || AsnEcSignatureFormatter.defaultNamedCurveSize;
+ const ecSignature = new ECDSASigValue();
+ const uint8Signature = build/* BufferSourceConverter.toUint8Array */.vJ.toUint8Array(signature);
+ ecSignature.r = this.removePadding(uint8Signature.slice(0, pointSize), true);
+ ecSignature.s = this.removePadding(uint8Signature.slice(pointSize, pointSize + pointSize), true);
+ return convert_AsnConvert.serialize(ecSignature);
+ }
+ return null;
+ }
+ toWebSignature(algorithm, signature) {
+ if (algorithm.name === "ECDSA") {
+ const ecSigValue = convert_AsnConvert.parse(signature, ECDSASigValue);
+ const namedCurve = algorithm.namedCurve;
+ const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve) || AsnEcSignatureFormatter.defaultNamedCurveSize;
+ const r = this.addPadding(pointSize, this.removePadding(ecSigValue.r));
+ const s = this.addPadding(pointSize, this.removePadding(ecSigValue.s));
+ return (0,build/* combine */.$e)(r, s);
+ }
+ return null;
+ }
+}
+AsnEcSignatureFormatter.namedCurveSize = new Map();
+AsnEcSignatureFormatter.defaultNamedCurveSize = 32;
+
+const idX25519 = "1.3.101.110";
+const idX448 = "1.3.101.111";
+const idEd25519 = "1.3.101.112";
+const idEd448 = "1.3.101.113";
+let EdAlgorithm = class EdAlgorithm {
+ toAsnAlgorithm(alg) {
+ let algorithm = null;
+ switch (alg.name.toLowerCase()) {
+ case "eddsa":
+ switch (alg.namedCurve.toLowerCase()) {
+ case "ed25519":
+ algorithm = idEd25519;
+ break;
+ case "ed448":
+ algorithm = idEd448;
+ break;
+ }
+ break;
+ case "ecdh-es":
+ switch (alg.namedCurve.toLowerCase()) {
+ case "x25519":
+ algorithm = idX25519;
+ break;
+ case "x448":
+ algorithm = idX448;
+ break;
+ }
+ }
+ if (algorithm) {
+ return new AlgorithmIdentifier({
+ algorithm,
+ });
+ }
+ return null;
+ }
+ toWebAlgorithm(alg) {
+ switch (alg.algorithm) {
+ case idEd25519:
+ return { name: "EdDSA", namedCurve: "Ed25519" };
+ case idEd448:
+ return { name: "EdDSA", namedCurve: "Ed448" };
+ case idX25519:
+ return { name: "ECDH-ES", namedCurve: "X25519" };
+ case idX448:
+ return { name: "ECDH-ES", namedCurve: "X448" };
+ }
+ return null;
+ }
+};
+EdAlgorithm = __decorate([
+ decorators_injectable()
+], EdAlgorithm);
+instance.registerSingleton(diAlgorithm, EdAlgorithm);
+
+class Pkcs10CertificateRequest extends PemData {
+ constructor(param) {
+ if (PemData.isAsnEncoded(param)) {
+ super(param, certification_request_CertificationRequest);
+ }
+ else {
+ super(param);
+ }
+ this.tag = PemConverter.CertificateRequestTag;
+ }
+ onInit(asn) {
+ this.tbs = convert_AsnConvert.serialize(asn.certificationRequestInfo);
+ this.publicKey = new PublicKey(asn.certificationRequestInfo.subjectPKInfo);
+ const algProv = instance.resolve(diAlgorithmProvider);
+ this.signatureAlgorithm = algProv.toWebAlgorithm(asn.signatureAlgorithm);
+ this.signature = asn.signature;
+ this.attributes = asn.certificationRequestInfo.attributes
+ .map(o => AttributeFactory.create(convert_AsnConvert.serialize(o)));
+ const extensions = this.getAttribute(es2015_id_pkcs9_at_extensionRequest);
+ this.extensions = [];
+ if (extensions instanceof ExtensionsAttribute) {
+ this.extensions = extensions.items;
+ }
+ this.subjectName = new Name(asn.certificationRequestInfo.subject);
+ this.subject = this.subjectName.toString();
+ }
+ getAttribute(type) {
+ for (const attr of this.attributes) {
+ if (attr.type === type) {
+ return attr;
+ }
+ }
+ return null;
+ }
+ getAttributes(type) {
+ return this.attributes.filter(o => o.type === type);
+ }
+ getExtension(type) {
+ for (const ext of this.extensions) {
+ if (ext.type === type) {
+ return ext;
+ }
+ }
+ return null;
+ }
+ getExtensions(type) {
+ return this.extensions.filter(o => o.type === type);
+ }
+ async verify(crypto = cryptoProvider.get()) {
+ const algorithm = { ...this.publicKey.algorithm, ...this.signatureAlgorithm };
+ const publicKey = await this.publicKey.export(algorithm, ["verify"], crypto);
+ const signatureFormatters = instance.resolveAll(diAsnSignatureFormatter).reverse();
+ let signature = null;
+ for (const signatureFormatter of signatureFormatters) {
+ signature = signatureFormatter.toWebSignature(algorithm, this.signature);
+ if (signature) {
+ break;
+ }
+ }
+ if (!signature) {
+ throw Error("Cannot convert WebCrypto signature value to ASN.1 format");
+ }
+ const ok = await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
+ return ok;
+ }
+ toTextObject() {
+ const obj = this.toTextObjectEmpty();
+ const req = convert_AsnConvert.parse(this.rawData, certification_request_CertificationRequest);
+ const tbs = req.certificationRequestInfo;
+ const data = new TextObject("", {
+ "Version": `${Version[tbs.version]} (${tbs.version})`,
+ "Subject": this.subject,
+ "Subject Public Key Info": this.publicKey,
+ });
+ if (this.attributes.length) {
+ const attrs = new TextObject("");
+ for (const ext of this.attributes) {
+ const attrObj = ext.toTextObject();
+ attrs[attrObj[TextObject.NAME]] = attrObj;
+ }
+ data["Attributes"] = attrs;
+ }
+ obj["Data"] = data;
+ obj["Signature"] = new TextObject("", {
+ "Algorithm": TextConverter.serializeAlgorithm(req.signatureAlgorithm),
+ "": req.signature,
+ });
+ return obj;
+ }
+}
+Pkcs10CertificateRequest.NAME = "PKCS#10 Certificate Request";
+
+class Pkcs10CertificateRequestGenerator {
+ static async create(params, crypto = cryptoProvider.get()) {
+ if (!params.keys.privateKey) {
+ throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");
+ }
+ if (!params.keys.publicKey) {
+ throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");
+ }
+ const spki = await crypto.subtle.exportKey("spki", params.keys.publicKey);
+ const asnReq = new CertificationRequest({
+ certificationRequestInfo: new CertificationRequestInfo({
+ subjectPKInfo: AsnConvert.parse(spki, SubjectPublicKeyInfo),
+ }),
+ });
+ if (params.name) {
+ const name = params.name instanceof Name
+ ? params.name
+ : new Name(params.name);
+ asnReq.certificationRequestInfo.subject = AsnConvert.parse(name.toArrayBuffer(), Name$1);
+ }
+ if (params.attributes) {
+ for (const o of params.attributes) {
+ asnReq.certificationRequestInfo.attributes.push(AsnConvert.parse(o.rawData, Attribute$1));
+ }
+ }
+ if (params.extensions && params.extensions.length) {
+ const attr = new Attribute$1({ type: id_pkcs9_at_extensionRequest });
+ const extensions = new Extensions();
+ for (const o of params.extensions) {
+ extensions.push(AsnConvert.parse(o.rawData, Extension$1));
+ }
+ attr.values.push(AsnConvert.serialize(extensions));
+ asnReq.certificationRequestInfo.attributes.push(attr);
+ }
+ const signingAlgorithm = { ...params.signingAlgorithm, ...params.keys.privateKey.algorithm };
+ const algProv = container.resolve(diAlgorithmProvider);
+ asnReq.signatureAlgorithm = algProv.toAsnAlgorithm(signingAlgorithm);
+ const tbs = AsnConvert.serialize(asnReq.certificationRequestInfo);
+ const signature = await crypto.subtle.sign(signingAlgorithm, params.keys.privateKey, tbs);
+ const signatureFormatters = container.resolveAll(diAsnSignatureFormatter).reverse();
+ let asnSignature = null;
+ for (const signatureFormatter of signatureFormatters) {
+ asnSignature = signatureFormatter.toAsnSignature(signingAlgorithm, signature);
+ if (asnSignature) {
+ break;
+ }
+ }
+ if (!asnSignature) {
+ throw Error("Cannot convert WebCrypto signature value to ASN.1 format");
+ }
+ asnReq.signature = asnSignature;
+ return new Pkcs10CertificateRequest(AsnConvert.serialize(asnReq));
+ }
+}
+
+class X509Certificates extends Array {
+ constructor(param) {
+ super();
+ if (PemData.isAsnEncoded(param)) {
+ this.import(param);
+ }
+ else if (param instanceof X509Certificate) {
+ this.push(param);
+ }
+ else if (Array.isArray(param)) {
+ for (const item of param) {
+ this.push(item);
+ }
+ }
+ }
+ export(format) {
+ const signedData = new asn1Cms.SignedData();
+ signedData.version = 1;
+ signedData.encapContentInfo.eContentType = asn1Cms.id_data;
+ signedData.encapContentInfo.eContent = new asn1Cms.EncapsulatedContent({
+ single: new OctetString(),
+ });
+ signedData.certificates = new asn1Cms.CertificateSet(this.map(o => new asn1Cms.CertificateChoices({
+ certificate: AsnConvert.parse(o.rawData, Certificate)
+ })));
+ const cms = new asn1Cms.ContentInfo({
+ contentType: asn1Cms.id_signedData,
+ content: AsnConvert.serialize(signedData),
+ });
+ const raw = AsnConvert.serialize(cms);
+ if (format === "raw") {
+ return raw;
+ }
+ return this.toString(format);
+ }
+ import(data) {
+ const raw = PemData.toArrayBuffer(data);
+ const cms = AsnConvert.parse(raw, asn1Cms.ContentInfo);
+ if (cms.contentType !== asn1Cms.id_signedData) {
+ throw new TypeError("Cannot parse CMS package. Incoming data is not a SignedData object.");
+ }
+ const signedData = AsnConvert.parse(cms.content, asn1Cms.SignedData);
+ this.clear();
+ for (const item of signedData.certificates || []) {
+ if (item.certificate) {
+ this.push(new X509Certificate(item.certificate));
+ }
+ }
+ }
+ clear() {
+ while (this.pop()) {
+ }
+ }
+ toString(format = "pem") {
+ const raw = this.export("raw");
+ switch (format) {
+ case "pem":
+ return PemConverter.encode(raw, "CMS");
+ case "pem-chain":
+ return this
+ .map(o => o.toString("pem"))
+ .join("\n");
+ case "asn":
+ return AsnConvert.toString(raw);
+ case "hex":
+ return Convert.ToHex(raw);
+ case "base64":
+ return Convert.ToBase64(raw);
+ case "base64url":
+ return Convert.ToBase64Url(raw);
+ case "text":
+ return TextConverter.serialize(this.toTextObject());
+ default:
+ throw TypeError("Argument 'format' is unsupported value");
+ }
+ }
+ toTextObject() {
+ const contentInfo = AsnConvert.parse(this.export("raw"), asn1Cms.ContentInfo);
+ const signedData = AsnConvert.parse(contentInfo.content, asn1Cms.SignedData);
+ const obj = new TextObject("X509Certificates", {
+ "Content Type": OidSerializer.toString(contentInfo.contentType),
+ "Content": new TextObject("", {
+ "Version": `${asn1Cms.CMSVersion[signedData.version]} (${signedData.version})`,
+ "Certificates": new TextObject("", { "Certificate": this.map(o => o.toTextObject()) }),
+ }),
+ });
+ return obj;
+ }
+}
+
+class X509ChainBuilder {
+ constructor(params = {}) {
+ this.certificates = [];
+ if (params.certificates) {
+ this.certificates = params.certificates;
+ }
+ }
+ async build(cert, crypto = cryptoProvider.get()) {
+ const chain = new X509Certificates(cert);
+ let current = cert;
+ while (current = await this.findIssuer(current, crypto)) {
+ const thumbprint = await current.getThumbprint(crypto);
+ for (const item of chain) {
+ const thumbprint2 = await item.getThumbprint(crypto);
+ if (isEqual(thumbprint, thumbprint2)) {
+ throw new Error("Cannot build a certificate chain. Circular dependency.");
+ }
+ }
+ chain.push(current);
+ }
+ return chain;
+ }
+ async findIssuer(cert, crypto = cryptoProvider.get()) {
+ if (!await cert.isSelfSigned(crypto)) {
+ const akiExt = cert.getExtension(asn1X509.id_ce_authorityKeyIdentifier);
+ for (const item of this.certificates) {
+ if (item.subject !== cert.issuer) {
+ continue;
+ }
+ if (akiExt) {
+ if (akiExt.keyId) {
+ const skiExt = item.getExtension(asn1X509.id_ce_subjectKeyIdentifier);
+ if (skiExt && skiExt.keyId !== akiExt.keyId) {
+ continue;
+ }
+ }
+ else if (akiExt.certId) {
+ const sanExt = item.getExtension(asn1X509.id_ce_subjectAltName);
+ if (sanExt &&
+ !(akiExt.certId.serialNumber === item.serialNumber && isEqual(AsnConvert.serialize(akiExt.certId.name), AsnConvert.serialize(sanExt)))) {
+ continue;
+ }
+ }
+ }
+ if (!await cert.verify({
+ publicKey: await item.publicKey.export(crypto),
+ signatureOnly: true,
+ }, crypto)) {
+ continue;
+ }
+ return item;
+ }
+ }
+ return null;
+ }
+}
+
+class X509CertificateGenerator {
+ static async createSelfSigned(params, crypto = cryptoProvider.get()) {
+ if (!params.keys.privateKey) {
+ throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");
+ }
+ if (!params.keys.publicKey) {
+ throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");
+ }
+ return this.create({
+ serialNumber: params.serialNumber,
+ subject: params.name,
+ issuer: params.name,
+ notBefore: params.notBefore,
+ notAfter: params.notAfter,
+ publicKey: params.keys.publicKey,
+ signingKey: params.keys.privateKey,
+ signingAlgorithm: params.signingAlgorithm,
+ extensions: params.extensions,
+ }, crypto);
+ }
+ static async create(params, crypto = cryptoProvider.get()) {
+ var _a;
+ let spki;
+ if (params.publicKey instanceof PublicKey) {
+ spki = params.publicKey.rawData;
+ }
+ else if ("publicKey" in params.publicKey) {
+ spki = params.publicKey.publicKey.rawData;
+ }
+ else if (BufferSourceConverter.isBufferSource(params.publicKey)) {
+ spki = params.publicKey;
+ }
+ else {
+ spki = await crypto.subtle.exportKey("spki", params.publicKey);
+ }
+ const asnX509 = new asn1X509.Certificate({
+ tbsCertificate: new asn1X509.TBSCertificate({
+ version: asn1X509.Version.v3,
+ serialNumber: Convert.FromHex(params.serialNumber),
+ validity: new asn1X509.Validity({
+ notBefore: params.notBefore,
+ notAfter: params.notAfter,
+ }),
+ extensions: new asn1X509.Extensions(((_a = params.extensions) === null || _a === void 0 ? void 0 : _a.map(o => AsnConvert.parse(o.rawData, asn1X509.Extension))) || []),
+ subjectPublicKeyInfo: AsnConvert.parse(spki, asn1X509.SubjectPublicKeyInfo),
+ }),
+ });
+ if (params.subject) {
+ const name = params.subject instanceof Name
+ ? params.subject
+ : new Name(params.subject);
+ asnX509.tbsCertificate.subject = AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name);
+ }
+ if (params.issuer) {
+ const name = params.issuer instanceof Name
+ ? params.issuer
+ : new Name(params.issuer);
+ asnX509.tbsCertificate.issuer = AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name);
+ }
+ const signatureAlgorithm = ("signingKey" in params)
+ ? { ...params.signingAlgorithm, ...params.signingKey.algorithm }
+ : params.publicKey.algorithm;
+ const algProv = container.resolve(diAlgorithmProvider);
+ asnX509.tbsCertificate.signature = asnX509.signatureAlgorithm = algProv.toAsnAlgorithm(signatureAlgorithm);
+ const tbs = AsnConvert.serialize(asnX509.tbsCertificate);
+ const signatureValue = ("signingKey" in params)
+ ? await crypto.subtle.sign(signatureAlgorithm, params.signingKey, tbs)
+ : params.signature;
+ const signatureFormatters = container.resolveAll(diAsnSignatureFormatter).reverse();
+ let asnSignature = null;
+ for (const signatureFormatter of signatureFormatters) {
+ asnSignature = signatureFormatter.toAsnSignature(signatureAlgorithm, signatureValue);
+ if (asnSignature) {
+ break;
+ }
+ }
+ if (!asnSignature) {
+ throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
+ }
+ asnX509.signatureValue = asnSignature;
+ return new X509Certificate(AsnConvert.serialize(asnX509));
+ }
+}
+
+var X509CrlReason;
+(function (X509CrlReason) {
+ X509CrlReason[X509CrlReason["unspecified"] = 0] = "unspecified";
+ X509CrlReason[X509CrlReason["keyCompromise"] = 1] = "keyCompromise";
+ X509CrlReason[X509CrlReason["cACompromise"] = 2] = "cACompromise";
+ X509CrlReason[X509CrlReason["affiliationChanged"] = 3] = "affiliationChanged";
+ X509CrlReason[X509CrlReason["superseded"] = 4] = "superseded";
+ X509CrlReason[X509CrlReason["cessationOfOperation"] = 5] = "cessationOfOperation";
+ X509CrlReason[X509CrlReason["certificateHold"] = 6] = "certificateHold";
+ X509CrlReason[X509CrlReason["removeFromCRL"] = 8] = "removeFromCRL";
+ X509CrlReason[X509CrlReason["privilegeWithdrawn"] = 9] = "privilegeWithdrawn";
+ X509CrlReason[X509CrlReason["aACompromise"] = 10] = "aACompromise";
+})(X509CrlReason || (X509CrlReason = {}));
+class X509CrlEntry extends (/* unused pure expression or super */ null && (AsnData)) {
+ constructor(...args) {
+ let raw;
+ if (BufferSourceConverter.isBufferSource(args[0])) {
+ raw = BufferSourceConverter.toArrayBuffer(args[0]);
+ }
+ else {
+ raw = AsnConvert.serialize(new RevokedCertificate({
+ userCertificate: args[0],
+ revocationDate: new Time(args[1]),
+ crlEntryExtensions: args[2],
+ }));
+ }
+ super(raw, RevokedCertificate);
+ }
+ onInit(asn) {
+ this.serialNumber = Convert.ToHex(asn.userCertificate);
+ this.revocationDate = asn.revocationDate.getTime();
+ this.extensions = [];
+ if (asn.crlEntryExtensions) {
+ this.extensions = asn.crlEntryExtensions.map((o) => {
+ const extension = ExtensionFactory.create(AsnConvert.serialize(o));
+ switch (extension.type) {
+ case id_ce_cRLReasons:
+ this.reason = AsnConvert.parse(extension.value, CRLReason).reason;
+ break;
+ case id_ce_invalidityDate:
+ this.invalidity = AsnConvert.parse(extension.value, InvalidityDate).value;
+ break;
+ }
+ return extension;
+ });
+ }
+ }
+}
+
+class X509Crl extends (/* unused pure expression or super */ null && (PemData)) {
+ constructor(param) {
+ if (PemData.isAsnEncoded(param)) {
+ super(param, CertificateList);
+ }
+ else {
+ super(param);
+ }
+ this.tag = PemConverter.CrlTag;
+ }
+ onInit(asn) {
+ var _a, _b;
+ const tbs = asn.tbsCertList;
+ this.tbs = AsnConvert.serialize(tbs);
+ this.version = tbs.version;
+ const algProv = container.resolve(diAlgorithmProvider);
+ this.signatureAlgorithm = algProv.toWebAlgorithm(asn.signatureAlgorithm);
+ this.tbsCertListSignatureAlgorithm = tbs.signature;
+ this.certListSignatureAlgorithm = asn.signatureAlgorithm;
+ this.signature = asn.signature;
+ this.issuerName = new Name(tbs.issuer);
+ this.issuer = this.issuerName.toString();
+ const thisUpdate = tbs.thisUpdate.getTime();
+ if (!thisUpdate) {
+ throw new Error("Cannot get 'thisUpdate' value");
+ }
+ this.thisUpdate = thisUpdate;
+ const nextUpdate = (_a = tbs.nextUpdate) === null || _a === void 0 ? void 0 : _a.getTime();
+ this.nextUpdate = nextUpdate;
+ this.entries = ((_b = tbs.revokedCertificates) === null || _b === void 0 ? void 0 : _b.map(o => new X509CrlEntry(AsnConvert.serialize(o)))) || [];
+ this.extensions = [];
+ if (tbs.crlExtensions) {
+ this.extensions = tbs.crlExtensions.map((o) => ExtensionFactory.create(AsnConvert.serialize(o)));
+ }
+ }
+ getExtension(type) {
+ for (const ext of this.extensions) {
+ if (typeof type === "string") {
+ if (ext.type === type) {
+ return ext;
+ }
+ }
+ else {
+ if (ext instanceof type) {
+ return ext;
+ }
+ }
+ }
+ return null;
+ }
+ getExtensions(type) {
+ return this.extensions.filter((o) => {
+ if (typeof type === "string") {
+ return o.type === type;
+ }
+ else {
+ return o instanceof type;
+ }
+ });
+ }
+ async verify(params, crypto = cryptoProvider.get()) {
+ if (!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm)) {
+ throw new Error("algorithm identifier in the sequence tbsCertList and CertificateList mismatch");
+ }
+ let keyAlgorithm;
+ let publicKey;
+ const paramsKey = params.publicKey;
+ try {
+ if (paramsKey instanceof X509Certificate) {
+ keyAlgorithm = {
+ ...paramsKey.publicKey.algorithm,
+ ...paramsKey.signatureAlgorithm,
+ };
+ publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"]);
+ }
+ else if (paramsKey instanceof PublicKey) {
+ keyAlgorithm = { ...paramsKey.algorithm, ...this.signature };
+ publicKey = await paramsKey.export(keyAlgorithm, ["verify"]);
+ }
+ else {
+ keyAlgorithm = { ...paramsKey.algorithm, ...this.signature };
+ publicKey = paramsKey;
+ }
+ }
+ catch (e) {
+ return false;
+ }
+ const signatureFormatters = container.resolveAll(diAsnSignatureFormatter).reverse();
+ let signature = null;
+ for (const signatureFormatter of signatureFormatters) {
+ signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
+ if (signature) {
+ break;
+ }
+ }
+ if (!signature) {
+ throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
+ }
+ return await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
+ }
+ async getThumbprint(...args) {
+ let crypto;
+ let algorithm = "SHA-1";
+ if (args[0]) {
+ if (!args[0].subtle) {
+ algorithm = args[0] || algorithm;
+ crypto = args[1];
+ }
+ else {
+ crypto = args[0];
+ }
+ }
+ crypto !== null && crypto !== void 0 ? crypto : (crypto = cryptoProvider.get());
+ return await crypto.subtle.digest(algorithm, this.rawData);
+ }
+ findRevoked(certOrSerialNumber) {
+ const serialNumber = typeof certOrSerialNumber === "string" ? certOrSerialNumber : certOrSerialNumber.serialNumber;
+ for (const entry of this.entries) {
+ if (entry.serialNumber === serialNumber) {
+ return entry;
+ }
+ }
+ return null;
+ }
+}
+
+class X509CrlGenerator {
+ static async create(params, crypto = cryptoProvider.get()) {
+ var _a;
+ const name = params.issuer instanceof Name
+ ? params.issuer
+ : new Name(params.issuer);
+ const asnX509Crl = new asn1X509.CertificateList({
+ tbsCertList: new asn1X509.TBSCertList({
+ version: asn1X509.Version.v2,
+ issuer: AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name),
+ thisUpdate: new Time(params.thisUpdate || new Date()),
+ }),
+ });
+ if (params.nextUpdate) {
+ asnX509Crl.tbsCertList.nextUpdate = new Time(params.nextUpdate);
+ }
+ if (params.extensions && params.extensions.length) {
+ asnX509Crl.tbsCertList.crlExtensions = new asn1X509.Extensions(params.extensions.map(o => AsnConvert.parse(o.rawData, asn1X509.Extension)) || []);
+ }
+ if (params.entries && params.entries.length) {
+ asnX509Crl.tbsCertList.revokedCertificates = [];
+ for (const entry of params.entries) {
+ const userCertificate = PemData.toArrayBuffer(entry.serialNumber);
+ const index = asnX509Crl.tbsCertList.revokedCertificates.findIndex(cert => isEqual(cert.userCertificate, userCertificate));
+ if (index > -1) {
+ throw new Error(`Certificate serial number ${entry.serialNumber} already exists in tbsCertList`);
+ }
+ const revokedCert = new RevokedCertificate({
+ userCertificate: userCertificate,
+ revocationDate: new Time(entry.revocationDate || new Date())
+ });
+ if ("extensions" in entry && ((_a = entry.extensions) === null || _a === void 0 ? void 0 : _a.length)) {
+ revokedCert.crlEntryExtensions = entry.extensions.map(o => AsnConvert.parse(o.rawData, asn1X509.Extension));
+ }
+ else {
+ revokedCert.crlEntryExtensions = [];
+ }
+ if (!(entry instanceof X509CrlEntry)) {
+ if (entry.reason) {
+ revokedCert.crlEntryExtensions.push(new asn1X509.Extension({
+ extnID: asn1X509.id_ce_cRLReasons,
+ critical: false,
+ extnValue: new OctetString(AsnConvert.serialize(new asn1X509.CRLReason(entry.reason))),
+ }));
+ }
+ if (entry.invalidity) {
+ revokedCert.crlEntryExtensions.push(new asn1X509.Extension({
+ extnID: asn1X509.id_ce_invalidityDate,
+ critical: false,
+ extnValue: new OctetString(AsnConvert.serialize(new asn1X509.InvalidityDate(entry.invalidity))),
+ }));
+ }
+ if (entry.issuer) {
+ const name = params.issuer instanceof Name
+ ? params.issuer
+ : new Name(params.issuer);
+ revokedCert.crlEntryExtensions.push(new asn1X509.Extension({
+ extnID: asn1X509.id_ce_certificateIssuer,
+ critical: false,
+ extnValue: new OctetString(AsnConvert.serialize(AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name))),
+ }));
+ }
+ }
+ asnX509Crl.tbsCertList.revokedCertificates.push(revokedCert);
+ }
+ }
+ const signingAlgorithm = { ...params.signingAlgorithm, ...params.signingKey.algorithm };
+ const algProv = container.resolve(diAlgorithmProvider);
+ asnX509Crl.tbsCertList.signature = asnX509Crl.signatureAlgorithm = algProv.toAsnAlgorithm(signingAlgorithm);
+ const tbs = AsnConvert.serialize(asnX509Crl.tbsCertList);
+ const signature = await crypto.subtle.sign(signingAlgorithm, params.signingKey, tbs);
+ const signatureFormatters = container.resolveAll(diAsnSignatureFormatter).reverse();
+ let asnSignature = null;
+ for (const signatureFormatter of signatureFormatters) {
+ asnSignature = signatureFormatter.toAsnSignature(signingAlgorithm, signature);
+ if (asnSignature) {
+ break;
+ }
+ }
+ if (!asnSignature) {
+ throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
+ }
+ asnX509Crl.signature = asnSignature;
+ return new X509Crl(AsnConvert.serialize(asnX509Crl));
+ }
+}
+
+ExtensionFactory.register(id_ce_basicConstraints, BasicConstraintsExtension);
+ExtensionFactory.register(id_ce_extKeyUsage, ExtendedKeyUsageExtension);
+ExtensionFactory.register(id_ce_keyUsage, KeyUsagesExtension);
+ExtensionFactory.register(id_ce_subjectKeyIdentifier, SubjectKeyIdentifierExtension);
+ExtensionFactory.register(id_ce_authorityKeyIdentifier, AuthorityKeyIdentifierExtension);
+ExtensionFactory.register(id_ce_subjectAltName, SubjectAlternativeNameExtension);
+AttributeFactory.register(id_pkcs9_at_challengePassword, ChallengePasswordAttribute);
+AttributeFactory.register(es2015_id_pkcs9_at_extensionRequest, ExtensionsAttribute);
+instance.registerSingleton(diAsnSignatureFormatter, AsnDefaultSignatureFormatter);
+instance.registerSingleton(diAsnSignatureFormatter, AsnEcSignatureFormatter);
+AsnEcSignatureFormatter.namedCurveSize.set("P-256", 32);
+AsnEcSignatureFormatter.namedCurveSize.set("K-256", 32);
+AsnEcSignatureFormatter.namedCurveSize.set("P-384", 48);
+AsnEcSignatureFormatter.namedCurveSize.set("P-521", 66);
+
+
+
+;// CONCATENATED MODULE: ./src/wacz/certutils.js
+
+
+
+
+
+
+//import { ASN1 } from "asn1-parser";
+
+
+
+const SPLIT_PEM = /-{5}(BEGIN|END) .*-{5}/gm;
+
+async function verifyWACZSignature({hash, signature, publicKey, domain, domainCert, created, software} = {}) {
+ let domainActual;
+ const results = [];
+
+ signature = (0,base64_js.toByteArray)(signature);
+
+ if (domainCert && domain && !publicKey) {
+ const certs = domainCert.split("\n\n");
+
+ const certBuffer = (0,base64_js.toByteArray)(certs[0].replace(SPLIT_PEM, "").replace(/\s/gm, ""));
+
+ const fingerprint = base16(await crypto.subtle.digest("SHA-256", certBuffer));
+ results.push({id: "certFingerprint", expected: fingerprint, matched: null});
+
+ const cert = new X509Certificate(certBuffer);
+
+ publicKey = await cert.publicKey.export();
+
+ const publicKeyEncoded = (0,base64_js.fromByteArray)(new Uint8Array(cert.publicKey.rawData));
+ results.push({id: "publicKey", expected: publicKeyEncoded, matched: null});
+
+ if (cert.subject && cert.subject.startsWith("CN=")) {
+ domainActual = cert.subject.split(3);
+ }
+
+ signature = parseASN1Signature(signature);
+
+ } else {
+ const ecdsaImportParams = {
+ name: "ECDSA",
+ namedCurve: "P-384"
+ };
+
+ results.push({id: "publicKey", expected: publicKey, matched: null});
+
+ publicKey = await crypto.subtle.importKey("spki", (0,base64_js.toByteArray)(publicKey), ecdsaImportParams, true, ["verify"]);
+ }
+
+ const ecdsaSignParams = {
+ name: "ECDSA",
+ hash: "SHA-256"
+ };
+
+ const encoder = new TextEncoder();
+
+ const sigValid = await crypto.subtle.verify(ecdsaSignParams, publicKey, signature, encoder.encode(hash));
+
+ results.push({id: "signature", expected: true, matched: sigValid});
+
+ if (created) {
+ results.push({id: "created", expected: created, matched: null});
+ }
+
+ if (software) {
+ results.push({id: "software", expected: software, matched: null});
+ }
+
+ if (domain) {
+ results.push({id: "domain", expected: domain, matched: domainActual});
+ }
+
+ return results;
+}
+
+function parseASN1Signature(signature) {
+ // extract r|s values from asn1
+ try {
+ const sig = AsnParser.parse(signature, ECDSASigValue);
+
+ const r = sig.r[0] === 0 ? sig.r.slice(1) : sig.r;
+ const s = sig.s[0] === 0 ? sig.s.slice(1) : sig.s;
+ signature = y([r, s], r.length + s.length);
+
+ } catch (se) {
+ console.log(se);
+ }
+
+ return signature;
+}
+
+
+// function parseSignature2(signature) {
+// // extract r|s values from asn1
+// try {
+// signature = decodeBase64(signature);
+
+// const result = ASN1.parse(signature);
+//
+// if (result && result.children && result.children.length == 2) {
+// const r = result.children[0].value;
+// const s = result.children[1].value;
+//
+// signature = concatChunks([r, s], r.length + s.length);
+// }
+//
+// } catch (se) {
+// console.log(se);
+// }
+//
+// return signature;
+// }
+
+;// CONCATENATED MODULE: ./src/wacz/waczimporter.js
+
+
+
+
+const MAIN_PAGES_JSON = "pages/pages.jsonl";
+const EXTRA_PAGES_JSON = "pages/extraPages.jsonl";
+
+const DATAPACKAGE_JSON = "datapackage.json";
+const DATAPACKAGE_DIGEST_JSON = "datapackage-digest.json";
+const WEBARCHIVE_YAML = "webarchive.yaml";
+
+const PAGE_BATCH_SIZE = 500;
+
+// ==========================================================================
+class WACZImporter
+{
+ constructor(store, file, isRoot = true) {
+ this.file = file;
+ this.waczname = file.waczname;
+ this.store = store;
+ this.isRoot = isRoot;
+ }
+
+ async loadFileFromWACZ(filename, opts) {
+ if (this.store.loadFileFromWACZ) {
+ return await this.store.loadFileFromWACZ(this.file, filename, opts);
+ } else {
+ return await this.file.loadFile(filename, opts);
+ }
+ }
+
+ async load() {
+ // process loading
+ let metadata;
+
+ let datapackageDigest = null;
+
+ if (this.file.containsFile(DATAPACKAGE_DIGEST_JSON)) {
+ datapackageDigest = await this.loadDigestData(DATAPACKAGE_DIGEST_JSON);
+ }
+
+ if (this.file.containsFile(DATAPACKAGE_JSON)) {
+ metadata = await this.loadPackage(DATAPACKAGE_JSON, datapackageDigest);
+ } else if (this.file.containsFile(WEBARCHIVE_YAML)) {
+ metadata = await this.loadOldPackageYAML(WEBARCHIVE_YAML);
+ }
+
+ return metadata || {};
+ }
+
+ async loadTextFileFromWACZ(filename, expectedHash = false) {
+ const { reader, hasher } = await this.loadFileFromWACZ(filename, {computeHash: !!expectedHash});
+ const text = new TextDecoder().decode(await reader.readFully());
+ if (expectedHash && hasher) {
+ await this.store.addVerifyData(this.waczname, filename, expectedHash, hasher.getHash());
+ }
+ return text;
+ }
+
+ async loadDigestData(filename) {
+ try {
+ const digestData = JSON.parse(await this.loadTextFileFromWACZ(filename));
+ let datapackageHash;
+
+ if (digestData.path === DATAPACKAGE_JSON && digestData.hash) {
+ datapackageHash = digestData.hash;
+ }
+
+ const store = this.store;
+ const sigPrefix = this.isRoot ? "" : this.waczname + ":";
+
+ if (!digestData.signedData || digestData.signedData.hash !== datapackageHash) {
+ await store.addVerifyData(sigPrefix, "signature");
+ return;
+ }
+
+ await store.addVerifyData(sigPrefix, "datapackageHash", datapackageHash);
+
+ const results = await verifyWACZSignature(digestData.signedData);
+
+ await store.addVerifyDataList(sigPrefix, results);
+
+ return datapackageHash;
+
+ } catch (e) {
+ console.warn(e);
+ }
+ }
+
+ async loadPackage(filename, expectedDigest) {
+ const text = await this.loadTextFileFromWACZ(filename, expectedDigest);
+
+ const root = JSON.parse(text);
+
+ //todo: check
+ if (this.isRoot && root.config !== undefined) {
+ this.store.initConfig(root.config);
+ }
+
+ switch (root.profile) {
+ case "data-package":
+ case "wacz-package":
+ return await this.loadLeafWACZPackage(root);
+
+ case "multi-wacz-package":
+ return await this.loadMultiWACZPackage(root);
+
+ default:
+ throw new Error(`Unknown package profile: ${root.profile}`);
+ }
+ }
+
+ async loadMultiWACZPackage(root) {
+ this.file.markAsMultiWACZ();
+ await this.store.loadWACZFiles(root, this.file);
+ return root;
+ }
+
+ async loadLeafWACZPackage(datapackage) {
+ const metadata = datapackage.metadata || {};
+
+ let pagesHash = null;
+
+ for (const res of datapackage.resources) {
+ if (res.path === MAIN_PAGES_JSON) {
+ pagesHash = res.hash;
+ await this.store.addVerifyData(this.waczname, res.path, res.hash);
+ } else if (res.path.endsWith(".idx") || res.path.endsWith(".cdx")) {
+ await this.store.addVerifyData(this.waczname, res.path, res.hash);
+ }
+ }
+
+ // All Pages
+ if (this.file.containsFile(MAIN_PAGES_JSON)) {
+ const pageInfo = await this.loadPages(MAIN_PAGES_JSON, pagesHash);
+
+ if (pageInfo.hasText) {
+ this.store.textIndex = metadata.textIndex = MAIN_PAGES_JSON;
+ }
+ }
+
+ if (this.file.containsFile(EXTRA_PAGES_JSON)) {
+ this.store.textIndex = metadata.textIndex = EXTRA_PAGES_JSON;
+ }
+
+ return metadata;
+ }
+
+ // Old WACZ 0.1.0 Format
+ async loadOldPackageYAML(filename) {
+ const text = await this.loadTextFileFromWACZ(filename);
+
+ const root = js_yaml.load(text);
+
+ const metadata = {
+ desc: root.desc,
+ title: root.title
+ };
+
+ if (root.textIndex) {
+ metadata.textIndex = root.textIndex;
+ if (!root.config) {
+ root.config = {};
+ }
+ root.config.textIndex = root.textIndex;
+ }
+
+ if (this.isRoot && root.config !== undefined) {
+ this.store.initConfig(root.config);
+ }
+
+ if (!metadata.title) {
+ metadata.title = this.store.config.sourceName;
+ }
+
+ // All pages
+ const pages = root.pages || [];
+
+ if (pages && pages.length) {
+ await this.store.addPages(pages);
+ }
+
+ // Curated Pages
+ const pageLists = root.pageLists || [];
+
+ if (pageLists && pageLists.length) {
+ await this.store.addCuratedPageLists(pageLists, "pages", "show");
+ }
+
+ return metadata;
+ }
+
+ async loadPages(filename = MAIN_PAGES_JSON, expectedHash = null) {
+ const {reader, hasher} = await this.loadFileFromWACZ(filename, {unzip: true, computeHash: true});
+
+ let pageListInfo = null;
+
+ let pages = [];
+
+ for await (const textLine of reader.iterLines()) {
+ const page = JSON.parse(textLine);
+
+ if (this.waczname) {
+ page.wacz = this.waczname;
+ }
+
+ if (!pageListInfo) {
+ pageListInfo = page;
+ continue;
+ }
+
+ pages.push(page);
+
+ if (pages.length === PAGE_BATCH_SIZE) {
+ await this.store.addPages(pages);
+ pages = [];
+ }
+ }
+
+ if (pages.length) {
+ await this.store.addPages(pages);
+ }
+
+ if (hasher && expectedHash) {
+ await this.store.addVerifyData(this.waczname, filename, expectedHash, hasher.getHash());
+ }
+
+ return pageListInfo;
+ }
+}
+;// CONCATENATED MODULE: ./src/wacz/waczloader.js
+
+
+
+
+
+
+
+
+// ============================================================================
+class SingleWACZLoader
+{
+ constructor(loader, config, loadId = null) {
+ this.loader = loader;
+ this.loadId = loadId;
+ this.loadUrl = config.loadUrl;
+ }
+
+ async load(db, /*progressUpdate, fullTotalSize*/) {
+ // if size less than MAX_FULL_DOWNLOAD_SIZE
+ if (db.fullConfig && this.loader.arrayBuffer &&
+ this.loader.arrayBuffer.byteLength <= MAX_FULL_DOWNLOAD_SIZE) {
+ if (!db.fullConfig.extra) {
+ db.fullConfig.extra = {};
+ }
+ db.fullConfig.extra.arrayBuffer = this.loader.arrayBuffer;
+ }
+
+ const name = DEFAULT_WACZ;
+ const path = this.loadUrl;
+ const loader = this.loader;
+ return await db.addNewWACZ({name, path, loader});
+ }
+}
+
+// ==========================================================================
+class SingleWACZFullImportLoader
+{
+ constructor(loader, config, loadId = null) {
+ this.config = config;
+ this.loadId = loadId;
+
+ this.loader = loader;
+ }
+
+ async load(db, progressUpdateCallback = null, fullTotalSize = 0) {
+
+ const file = new WACZFile({loader: this.loader});
+ await file.init();
+
+ const zipreader = file.zipreader;
+ const importer = new WACZImporter(db, file);
+
+ const metadata = await importer.load();
+
+ let offsetTotal = 0;
+
+ const progressUpdate = (percent, error, offset/*, total*/) => {
+ offset += offsetTotal;
+ if (progressUpdateCallback && fullTotalSize) {
+ progressUpdateCallback(Math.round(offset * 100.0 / fullTotalSize), null, offset, fullTotalSize);
+ }
+ };
+
+ // load CDX and IDX
+ for (const filename of file.iterContainedFiles()) {
+ const entryTotal = zipreader.getCompressedSize(filename);
+ if (filename.endsWith(".warc.gz") || filename.endsWith(".warc")) {
+ await this.loadWARC(db, zipreader, filename, progressUpdate, entryTotal);
+ }
+
+ offsetTotal += entryTotal;
+ }
+
+ return metadata || {};
+ }
+
+ async loadWARC(db, zipreader, filename, progressUpdate, total) {
+ const {reader} = await zipreader.loadFile(filename, {unzip: true});
+
+ const loader = new WARCLoader(reader, null, filename);
+ loader.detectPages = false;
+
+ return await loader.load(db, progressUpdate, total);
+ }
+}
+
+// ==========================================================================
+class JSONResponseMultiWACZLoader
+{
+ constructor(response) {
+ this.response = response;
+ }
+
+ async load(db) {
+ return await db.loadFromJSON(this.response);
+ }
+}
+
+;// CONCATENATED MODULE: ./src/liveproxy.js
+
+
+
+// ===========================================================================
+class LiveProxy {
+ constructor(extraConfig, {cloneResponse = false, allowBody = false, hostProxyOnly = false} = {}) {
+ extraConfig = extraConfig || {};
+
+ this.prefix = extraConfig.prefix || "";
+ this.proxyPathOnly = extraConfig.proxyPathOnly || false;
+ this.isLive = extraConfig.isLive !== undefined ? extraConfig.isLive : true;
+ this.archivePrefix = extraConfig.archivePrefix || "";
+ this.cloneResponse = cloneResponse;
+ this.allowBody = allowBody;
+
+ this.hostProxy = extraConfig.hostProxy;
+
+ if (this.hostProxy instanceof Array) {
+ const byHost = {};
+ for (const entry of this.hostProxy) {
+ byHost[entry.host] = entry;
+ }
+ this.hostProxy = byHost;
+ }
+
+ this.hostProxyOnly = hostProxyOnly;
+ }
+
+ async getAllPages() {
+ return [];
+ }
+
+ getFetchUrl(url, request, headers) {
+ let parsedUrl;
+
+ if (this.hostProxy) {
+ parsedUrl = new URL(url);
+ const hostdata = this.hostProxy[parsedUrl.host];
+ if (hostdata) {
+ // set X-Proxy-Host to matched host
+ headers.set("X-Proxy-Host", parsedUrl.host);
+ // Given https://example.com/path/somefile.html, and prefix "https://upstream-server/prefix/"
+ // with pathOnly, send to https://upstream-server/prefix/path/somefile.html
+ // without pathOnly, send to https://upstream-server/prefix/https://example.com/path/somefile.html
+ return hostdata.prefix + (hostdata.pathOnly ? parsedUrl.pathname + parsedUrl.search : url);
+ }
+ }
+
+ if (this.hostProxyOnly) {
+ return null;
+ }
+
+ if (this.proxyPathOnly) {
+ if (!parsedUrl) {
+ parsedUrl = new URL(url);
+ }
+ return this.prefix + parsedUrl.pathname + parsedUrl.search;
+ } else if (this.isLive || !request.timestamp) {
+ return this.prefix + url;
+ } else {
+ return this.prefix + this.archivePrefix + request.timestamp + "id_/" + url;
+ }
+ }
+
+
+ async getResource(request, prefix) {
+ const { headers, credentials, url} = request.prepareProxyRequest(prefix, true);
+
+ const fetchUrl = this.getFetchUrl(url, request, headers);
+
+ if (!fetchUrl) {
+ return null;
+ }
+
+ let body = null;
+
+ if (this.allowBody && (request.method === "POST" || request.method === "PUT")) {
+ body = await request.getBody();
+ }
+
+ const response = await fetch(fetchUrl, {
+ method: request.method,
+ body,
+ headers,
+ credentials,
+ mode: "cors",
+ redirect: "follow"
+ });
+
+ let clonedResponse = null;
+
+ if (this.cloneResponse) {
+ clonedResponse = response.clone();
+ }
+
+ const archiveResponse = ArchiveResponse.fromResponse({url,
+ response,
+ date: new Date(),
+ noRW: false,
+ isLive: this.isLive,
+ });
+
+ if (clonedResponse) {
+ archiveResponse.clonedResponse = clonedResponse;
+ }
+
+ return archiveResponse;
+ }
+}
+
+;// CONCATENATED MODULE: ./src/wacz/multiwacz.js
+
+
+
+
+
+
+
+
+
+
+
+const MAX_BLOCKS = 3;
+
+const IS_SURT = /^([\w-]+,)*[\w-]+(:\d+)?,?\)\//;
+
+
+// ==========================================================================
+class MultiWACZ extends OnDemandPayloadArchiveDB// implements WACZLoadSource
+{
+ constructor(config, sourceLoader, rootSourceType = "wacz") {
+ super(config.dbname, config.noCache);
+
+ this.config = config;
+
+ this.waczfiles = {};
+ this.waczNameForHash = {};
+ this.ziploadercache = {};
+
+ this.updating = null;
+
+ this.rootSourceType = rootSourceType;
+
+ this.sourceLoader = sourceLoader;
+
+ this.externalSource = null;
+ this.fuzzyUrlRules = [];
+ this.useSurt = false;
+
+ this.textIndex = config && config.metadata && config.metadata.textIndex;
+
+ if (config.extraConfig) {
+ this.initConfig(config.extraConfig);
+ }
+ }
+
+ initConfig(extraConfig) {
+ if (extraConfig.decodeResponses !== undefined) {
+ this.config.decode = extraConfig.decodeResponses;
+ }
+ if (extraConfig.useSurt !== undefined) {
+ this.useSurt = extraConfig.useSurt;
+ }
+ if (extraConfig.hostProxy) {
+ this.externalSource = new LiveProxy(extraConfig, {hostProxyOnly: true});
+ }
+ if (extraConfig.fuzzy) {
+ for (const [matchStr, replace] of extraConfig.fuzzy) {
+ const match = new RegExp(matchStr);
+ this.fuzzyUrlRules.push({match, replace});
+ }
+ }
+ if (extraConfig.textIndex) {
+ this.textIndex = extraConfig.textIndex;
+ }
+ }
+
+ updateHeaders(headers) {
+ if (this.sourceLoader) {
+ this.sourceLoader.headers = headers;
+ }
+ }
+
+ _initDB(db, oldV, newV, tx) {
+ super._initDB(db, oldV, newV, tx);
+
+ if (!oldV) {
+ db.createObjectStore("ziplines", { keyPath: ["waczname", "prefix"] });
+
+ db.createObjectStore("waczfiles", { keyPath: "waczname" } );
+
+ db.createObjectStore("verification", { keyPath: "id" });
+ }
+
+ if (oldV === 2) {
+ this.convertV2WACZDB(db, tx);
+ }
+
+ if (oldV === 3) {
+ db.createObjectStore("verification", { keyPath: "id" });
+ }
+ }
+
+ async convertV2WACZDB(db, tx) {
+ try {
+
+ const ziplines = await (tx.objectStore("ziplines")).getAll();
+ const entries = await (tx.objectStore("zipEntries")).getAll();
+
+ db.deleteObjectStore("ziplines");
+
+ db.deleteObjectStore("zipEntries");
+
+ db.createObjectStore("ziplines", { keyPath: ["waczname", "prefix"] });
+
+ db.createObjectStore("waczfiles", { keyPath: "waczname"} );
+
+ db.createObjectStore("verification", {keyPath: "id"});
+
+ const waczname = this.config.loadUrl;
+
+ for (const line of ziplines) {
+ line.waczname = waczname;
+ tx.objectStore("ziplines").put(line);
+ }
+
+ const indexType = ziplines.length > 0 ? INDEX_IDX : INDEX_CDX;
+ const hash = await this.computeHash(waczname);
+ const filedata = new WACZFile({waczname, hash, url: waczname, entries, indexType});
+
+ tx.objectStore("waczfiles").put(filedata.serialize());
+
+ await tx.done;
+ } catch (e) {
+ console.warn(e);
+ }
+ }
+
+ addWACZFile(file) {
+ this.waczfiles[file.waczname] = new WACZFile(file);
+ this.waczNameForHash[file.hash] = file.waczname;
+ return this.waczfiles[file.waczname];
+ }
+
+ async init() {
+ await super.init();
+
+ const fileDatas = await this.db.getAll("waczfiles") || [];
+
+ for (const file of fileDatas) {
+ this.addWACZFile({...file, parent: this});
+ }
+
+ for (const [key, value] of Object.entries(this.waczfiles)) {
+ value.path = value.path || key;
+
+ // nested wacz will contain '#!/'
+ const inx = value.path.lastIndexOf("#!/");
+ if (inx > 0) {
+ const parentName = value.path.slice(0, inx);
+ const parent = this.waczfiles[parentName];
+ value.parent = parent;
+ } else if (this.rootSourceType !== "json") {
+ value.loader = this.sourceLoader;
+ }
+ }
+
+ await this.checkUpdates();
+ }
+
+ async close() {
+ super.close();
+ caches.delete("cache:" + this.name.slice("db:".length));
+ }
+
+ async clearZipData() {
+ const stores = ["waczfiles", "ziplines"];
+
+ for (const store of stores) {
+ await this.db.clear(store);
+ }
+ }
+
+ async addVerifyData(prefix = "", id, expected, actual, log = false) {
+ let matched = null;
+
+ if (prefix) {
+ id = prefix + id;
+ }
+
+ if (actual) {
+ matched = expected === actual;
+ if (log) {
+ console.log(`verify ${id}: ${matched}`);
+ }
+ }
+ await this.db.put("verification", {id, expected, matched});
+ }
+
+ async addVerifyDataList(prefix, datalist) {
+ const tx = this.db.transaction("verification", "readwrite");
+
+ for (const data of datalist) {
+ if (prefix) {
+ data.id = prefix + data.id;
+ }
+ tx.store.put(data);
+ }
+
+ try {
+ await tx.done;
+ } catch (e) {
+ console.warn(e);
+ }
+ }
+
+ async getVerifyInfo() {
+ const results = await this.db.getAll("verification");
+
+ let numValid = 0;
+ let numInvalid = 0;
+
+ let info = {};
+
+ const includeProps = ["domain", "created", "certFingerprint", "software", "datapackageHash", "publicKey"];
+
+ for (const res of results) {
+ if (includeProps.includes(res.id)) {
+ info[res.id] = res.expected;
+ } else if (res.id === "signature") {
+ numValid++;
+ } else if (res.matched === true) {
+ numValid++;
+ } else if (res.matched === false) {
+ numInvalid++;
+ }
+ }
+
+ info.numInvalid = numInvalid;
+ info.numValid = numValid;
+
+ return info;
+ }
+
+ async getVerifyExpected(id) {
+ const res = await this.db.get("verification", id);
+ return res && res.expected;
+ }
+
+ async clearAll() {
+ await super.clearAll();
+
+ await this.clearZipData();
+ }
+
+ async loadRecordFromSource(cdx) {
+ const {start, length, path, wacz} = cdx.source;
+ const params = {offset: start, length, unzip: true, computeHash: true};
+ const waczname = wacz;
+
+ const {reader, hasher} = await this.loadFileFromNamedWACZ(waczname, "archive/" + path, params);
+
+ const loader = new SingleRecordWARCLoader(reader, hasher);
+
+ await this.waczfiles[waczname].save(this.db);
+
+ const remote = await loader.load();
+
+ if (cdx[CDX_COOKIE]) {
+ remote.respHeaders["x-wabac-preset-cookie"] = cdx[CDX_COOKIE];
+ }
+
+ return {remote, hasher};
+ }
+
+ async loadIndex(waczname) {
+ if (!this.waczfiles[waczname]) {
+ throw new Error("unknown waczfile: " + waczname);
+ }
+
+ if (this.waczfiles[waczname].indexType) {
+ return {indexType: this.waczfiles[waczname].indexType, isNew: false};
+ }
+
+ //const indexloaders = [];
+ let indexType = INDEX_NOT_LOADED;
+
+ // load CDX and IDX
+ for (const filename of this.waczfiles[waczname].iterContainedFiles()) {
+ if (filename.endsWith(".cdx") || filename.endsWith(".cdxj")) {
+
+ console.log(`Loading CDX for ${waczname}`);
+
+ await this.loadCDX(filename, waczname);
+
+ indexType = INDEX_CDX;
+
+ } else if (filename.endsWith(".idx")) {
+ // For compressed indices
+ console.log(`Loading IDX for ${waczname}`);
+
+ await this.loadIDX(filename, waczname);
+
+ indexType = INDEX_IDX;
+ }
+ }
+
+ this.waczfiles[waczname].indexType = indexType;
+
+ await this.waczfiles[waczname].save(this.db, true);
+
+ return {indexType, isNew: true};
+ }
+
+ async loadCDX(filename, waczname, progressUpdate, total) {
+ const { reader, hasher } = await this.loadFileFromNamedWACZ(waczname, filename, {computeHash: true});
+
+ const loader = new CDXLoader(reader, null, waczname, {wacz: waczname});
+
+ const res = await loader.load(this, progressUpdate, total);
+
+ if (hasher) {
+ const expected = await this.getVerifyExpected(filename);
+ if (expected) {
+ this.addVerifyData(waczname, filename, expected, hasher.getHash());
+ }
+ }
+
+ return res;
+ }
+
+ async loadIDX(filename, waczname, progressUpdate, total) {
+ const { reader, hasher } = await this.loadFileFromNamedWACZ(waczname, filename, {computeHash: true});
+
+ let batch = [];
+ let defaultFilename = "";
+ let useSurt = false;
+
+ let currOffset = 0;
+
+ for await (const line of reader.iterLines()) {
+ currOffset += line.length;
+
+ // first line
+ if (currOffset === line.length) {
+ if (line.startsWith("!meta")) {
+ const inx = line.indexOf(" {");
+ if (inx < 0) {
+ console.warn("Invalid Meta Line: " + line);
+ continue;
+ }
+
+ const indexMetadata = JSON.parse(line.slice(inx));
+
+ if (indexMetadata.filename) {
+ defaultFilename = indexMetadata.filename;
+ }
+ if (indexMetadata.format !== "cdxj-gzip-1.0") {
+ console.log(`Unknown CDXJ format "${indexMetadata.format}", archive may not parse correctly`);
+ }
+ continue;
+ }
+ }
+
+ let entry;
+
+ if (line.indexOf("\t") > 0) {
+ let [prefix, filename, offset, length] = line.split("\t");
+ offset = Number(offset);
+ length = Number(length);
+
+ entry = {waczname, prefix, filename, offset, length, loaded: false};
+
+ useSurt = true;
+ } else {
+ const inx = line.indexOf(" {");
+ if (inx < 0) {
+ console.log("Invalid Index Line: " + line);
+ continue;
+ }
+
+ const prefix = line.slice(0, inx);
+ let {offset, length, filename, digest} = JSON.parse(line.slice(inx));
+
+ useSurt = useSurt || prefix.match(IS_SURT);
+
+ filename = filename || defaultFilename;
+
+ entry = {waczname, prefix, filename, offset, length, digest, loaded: false};
+ }
+
+ if (progressUpdate) {
+ progressUpdate(currOffset / total, currOffset, total);
+ }
+
+ batch.push(entry);
+ }
+
+ if (hasher) {
+ const expected = await this.getVerifyExpected(filename);
+ if (expected) {
+ this.addVerifyData(waczname, filename, expected, hasher.getHash());
+ }
+ }
+
+ const tx = this.db.transaction("ziplines", "readwrite");
+
+ for (const entry of batch) {
+ tx.store.put(entry);
+ }
+
+ try {
+ await tx.done;
+ } catch (e) {
+ console.log("Error loading ziplines index: ", e);
+ }
+
+ if (useSurt && useSurt !== this.waczfiles[waczname].useSurt) {
+ // only store if defaults to true, false is default
+ this.waczfiles[waczname].useSurt = useSurt;
+ await this.waczfiles[waczname].save(this.db, true);
+ }
+ }
+
+ async loadCDXFromIDX(waczname, url, datetime = 0, isPrefix = false) {
+ //const timestamp = datetime ? getTS(new Date(datetime).toISOString()) : "";
+
+ const surt = this.waczfiles[waczname].useSurt ? decodeURIComponent(P(url)) : url;
+
+ const upperBound = isPrefix ? this.prefixUpperBound(surt) : surt + " 9999";
+
+ const key = IDBKeyRange.upperBound([waczname, upperBound], true);
+
+ const tx = this.db.transaction("ziplines", "readonly");
+
+ const values = [];
+
+ for await (const cursor of tx.store.iterate(key, "prev")) {
+ // restrict to specific waczname
+ if (cursor.value.waczname !== waczname) {
+ break;
+ }
+
+ // add to beginning as processing entries in reverse here
+ values.unshift(cursor.value);
+ if (!cursor.value.prefix.split(" ")[0].startsWith(surt)) {
+ break;
+ }
+ }
+
+ await tx.done;
+
+ const cdxloaders = [];
+
+ if (values.length > MAX_BLOCKS && datetime) {
+ values.sort((a, b) => {
+ const ts1 = a.prefix.split(" ")[1];
+ const ts2 = b.prefix.split(" ")[1];
+ if (!ts1 || !ts2) {
+ return 0;
+ }
+ const diff1 = Math.abs(tsToDate(ts1).getTime() - datetime);
+ const diff2 = Math.abs(tsToDate(ts2).getTime() - datetime);
+ if (diff1 === diff2) {
+ return 0;
+ }
+ return diff1 < diff2 ? -1 : 1;
+ });
+ }
+
+ let count = 0;
+
+ for (const zipblock of values) {
+ if (zipblock.loaded) {
+ continue;
+ }
+
+ const cacheKey = waczname + ":" + zipblock.filename + ":" + zipblock.offset;
+
+ let cachedLoad = this.ziploadercache[cacheKey];
+
+ if (!cachedLoad) {
+ cachedLoad = this.doCDXLoad(cacheKey, zipblock, waczname);
+ this.ziploadercache[cacheKey] = cachedLoad;
+ }
+ cdxloaders.push(cachedLoad);
+
+ if (++count > MAX_BLOCKS) {
+ break;
+ }
+ }
+
+ if (cdxloaders.length) {
+ await Promise.allSettled(cdxloaders);
+ }
+
+ await this.waczfiles[waczname].save(this.db);
+
+ return cdxloaders.length > 0;
+ }
+
+ async doCDXLoad(cacheKey, zipblock, waczname) {
+ try {
+ const filename = "indexes/" + zipblock.filename;
+ const params = {offset: zipblock.offset, length: zipblock.length, unzip: true, computeHash: !!zipblock.digest};
+ const { reader, hasher } = await this.loadFileFromNamedWACZ(waczname, filename, params);
+
+ const loader = new CDXLoader(reader, null, null, {wacz: waczname});
+ await loader.load(this);
+
+ if (hasher) {
+ const hash = hasher.getHash();
+ const id = `${filename}:${zipblock.offset}-${zipblock.length}`;
+ await this.addVerifyData(waczname, id, zipblock.digest, hash);
+ }
+
+ zipblock.loaded = true;
+ await this.db.put("ziplines", zipblock);
+
+ } catch (e) {
+ if (!await handleAuthNeeded(e, this.config)) {
+ console.warn(e);
+ }
+ } finally {
+ delete this.ziploadercache[cacheKey];
+ }
+ }
+
+ async findPageAtUrl(url, ts) {
+ const pages = await this.db.getAllFromIndex("pages", "url", url);
+ let currPage = null;
+ let minDiff = Number.MAX_SAFE_INTEGER;
+
+ for (const page of pages) {
+ const diff = Math.abs(page.ts - ts);
+ if (diff < 1000) {
+ return page;
+ }
+ if (diff < minDiff) {
+ currPage = page;
+ minDiff = diff;
+ }
+ }
+
+ return currPage;
+ }
+
+ async lookupUrl(url, datetime, opts = {}) {
+ try {
+ let result = await super.lookupUrl(url, datetime, opts);
+
+ if (result && (!opts.noRevisits || result.mime !== "warc/revisit")) {
+ return result;
+ }
+
+ const { waczname } = opts;
+
+ if (waczname && waczname !== NO_LOAD_WACZ) {
+ result = await this.lookupUrlForWACZ(waczname, url, datetime, opts);
+ }
+
+ return result;
+ } catch (e) {
+ console.warn(e);
+ return null;
+ }
+ }
+
+ async lookupUrlForWACZ(waczname, url, datetime, opts) {
+ const {indexType, isNew} = await this.loadIndex(waczname);
+
+ switch (indexType) {
+ case INDEX_IDX:
+ if (!await this.loadCDXFromIDX(waczname, url, datetime, false)) {
+ // no new idx lines loaded
+ return null;
+ }
+ break;
+
+ case INDEX_CDX:
+ if (!isNew) {
+ return null;
+ }
+ break;
+
+ default:
+ return null;
+ }
+
+ return await super.lookupUrl(url, datetime, opts);
+ }
+
+ async resourcesByUrlAndMime(url, ...args) {
+ let results = await super.resourcesByUrlAndMime(url, ...args);
+
+ if (results.length > 0) {
+ return results;
+ }
+
+ for (const waczname of Object.keys(this.waczfiles)) {
+ if (waczname && waczname !== "local") {
+ const {indexType, isNew} = await this.loadIndex(waczname);
+
+ switch (indexType) {
+ case INDEX_IDX:
+ if (!await this.loadCDXFromIDX(waczname, url, 0, true)) {
+ // no new idx lines loaded
+ continue;
+ }
+ break;
+
+ case INDEX_CDX:
+ if (!isNew) {
+ continue;
+ }
+ break;
+
+ default:
+ continue;
+ }
+
+ const newRes = await super.resourcesByUrlAndMime(url, ...args);
+ if (newRes && newRes.length) {
+ results = results.concat(newRes);
+ }
+ }
+ }
+
+ return results;
+ }
+
+ async loadFileFromWACZ(waczfile, filename, opts) {
+ try {
+ return await waczfile.loadFile(filename, opts);
+ } catch (e) {
+ if (await this.retryLoad(e)) {
+ return await waczfile.loadFile(filename, opts);
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ async loadFileFromNamedWACZ(waczname, filename, opts) {
+ const waczfile = this.waczfiles[waczname];
+
+ if (!waczfile) {
+ throw new Error("No WACZ Found for: " + waczname);
+ }
+
+ return await this.loadFileFromWACZ(waczfile, filename, opts);
+ }
+
+ async addNewWACZ({name, hash, path, parent = null, loader = null} = {}) {
+ const waczname = name || path;
+
+ if (!hash) {
+ hash = await digestMessage(waczname, "sha-256", "");
+ } else if (hash.indexOf(":") > 0) {
+ hash = hash.split(":")[1];
+ }
+
+ const file = this.addWACZFile({waczname, hash, path, parent, loader}, true);
+
+ await file.init();
+
+ await file.save(this.db, true);
+
+ const importer = new WACZImporter(this, file, !parent);
+
+ return await importer.load();
+ }
+
+ async loadWACZFiles(json, parent = this) {
+ const promises = [];
+
+ const update = async (name, path) => {
+ await this.waczfiles[name].init(path);
+ await this.waczfiles[name].save(this.db, true);
+ };
+
+ const files = json.resources.map((res) => {
+ const path = parent.getLoadPath(res.path);
+ const name = parent.getName(res.name);
+ const hash = res.hash;
+ return {name, hash, path};
+ });
+
+ for (const {name, hash, path} of files) {
+ if (!this.waczfiles[name]) {
+ promises.push(this.addNewWACZ({name, hash, path, parent}));
+ } else if (this.waczfiles[name].path !== path) {
+ promises.push(update(name, path));
+ }
+ }
+
+ if (promises.length) {
+ await Promise.allSettled(promises);
+ }
+ }
+
+ async getTextIndex() {
+ const headers = {"Content-Type": "application/ndjson"};
+
+ const keys = Object.keys(this.waczfiles);
+
+ if (!this.textIndex || !keys.length) {
+ return new Response("", {headers});
+ }
+
+ // just look at first wacz for now
+ const waczname = keys[0];
+
+ let result;
+
+ try {
+ result = await this.loadFileFromNamedWACZ(waczname, this.textIndex, {unzip: true});
+ } catch (e) {
+ return new Response("", {headers});
+ }
+
+ const {reader} = result;
+
+ const size = this.waczfiles[waczname].getSizeOf(this.textIndex);
+
+ if (size > 0) {
+ headers["Content-Length"] = "" + size;
+ }
+
+ return new Response(reader.getReadableStream(), {headers});
+ }
+
+ async getResource(request, prefix, event, {pageId} = {}) {
+ await this.initing;
+
+ if (this.externalSource) {
+ const res = await this.externalSource.getResource(request, prefix, event);
+ if (res) {
+ return res;
+ }
+ }
+
+ const isNavigate = event.request.mode === "navigate";
+
+ let hash = pageId;
+ let waczname = null;
+
+ let resp = null;
+
+ if (hash) {
+ waczname = this.waczNameForHash[hash];
+ if (!waczname) {
+ return null;
+ }
+ resp = await super.getResource(request, prefix, event, {waczname});
+ }
+
+ if (resp || !isNavigate) {
+ return resp;
+ }
+
+ for (const [name, file] of Object.entries(this.waczfiles)) {
+ if (file.fileType !== WACZ_LEAF) {
+ continue;
+ }
+
+ resp = await super.getResource(request, prefix, event, {waczname: name, noFuzzyCheck: true});
+ if (resp) {
+ waczname = name;
+ hash = file.hash;
+ break;
+ }
+ }
+
+ if (waczname) {
+ return Response.redirect(`${prefix}:${hash}/${request.timestamp}mp_/${request.url}`);
+ }
+
+ if (this.fuzzyUrlRules.length) {
+ for (const {match, replace} of this.fuzzyUrlRules) {
+ const newUrl = decodeURIComponent(request.url.replace(match, replace));
+ if (newUrl && newUrl !== request.url) {
+ request.url = newUrl;
+ const res = await super.getResource(request, prefix, event);
+ if (res) {
+ return res;
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+ async retryLoad(e) {
+ if (this.rootSourceType !== "json") {
+ return false;
+ }
+
+ if (e instanceof AccessDeniedError) {
+ if (!this.updating) {
+ this.updating = this.checkUpdates();
+ }
+ await this.updating;
+ this.updating = null;
+ return true;
+ } else {
+ return await handleAuthNeeded(e, this.config);
+ }
+ }
+
+ async checkUpdates() {
+ if (this.rootSourceType === "json") {
+ await this.loadFromJSON();
+ }
+ }
+
+ async loadFromJSON(response = null) {
+ if (!response) {
+ const result = await this.sourceLoader.doInitialFetch(false);
+ response = result.response;
+ }
+
+ if (response.status !== 206 && response.status !== 200) {
+ console.warn("WACZ update failed from: " + this.config.loadUrl);
+ return {};
+ }
+
+ const data = await response.json();
+
+ switch (data.profile) {
+ case "data-package":
+ case "wacz-package":
+ //eslint: disable=no-fallthrough
+ default:
+ await this.loadWACZFiles(data);
+ }
+
+ return data;
+ }
+
+ getLoadPath(path) {
+ return new URL(path, this.config.loadUrl).href;
+ }
+
+ getName(name) {
+ return name;
+ }
+
+ async createLoader(opts) {
+ return await createLoader(opts);
+ }
+}
+;// CONCATENATED MODULE: ./src/remotewarcproxy.js
+
+
+
+
+
+
+// ===========================================================================
+class RemoteWARCProxy {
+ constructor(rootConfig) {
+ const config = rootConfig.extraConfig || {};
+
+ this.sourceUrl = config.prefix;
+ this.type = config.sourceType || "kiwix";
+ this.notFoundPageUrl = config.notFoundPageUrl;
+ }
+
+ async getAllPages() {
+ return [];
+ }
+
+ async getResource(request, prefix) {
+ const { url, headers } = request.prepareProxyRequest(prefix);
+ let reqHeaders = headers;
+
+ if (this.type === "kiwix") {
+ // console.debug('Attempting to resolve canonical headers for url', url);
+ let headersData = await this.resolveHeaders(url);
+
+ if (!headersData) {
+ for (const newUrl of fuzzyMatcher.getFuzzyCanonsWithArgs(url)) {
+ if (newUrl !== url) {
+ console.debug('Attempting to resolve fuzzy headers for url', newUrl);
+ headersData = await this.resolveHeaders(newUrl);
+ if (headersData) {
+ break;
+ }
+ }
+ }
+ }
+
+ if (!headersData) {
+
+ // use custom error page for navigate events
+ if (this.notFoundPageUrl && request.mode === "navigate") {
+ const resp = await fetch(this.notFoundPageUrl);
+ // load 'not found' page template
+ if (resp.status === 200) {
+ const headers = {"Content-Type": "text/html"};
+ const text = await resp.text();
+ return new Response(text.replace("$URL", url), {status: 404, headers});
+ }
+ }
+
+ return null;
+ }
+
+ let { headers, encodedUrl, date, status, statusText, hasPayload } = headersData;
+
+ if (reqHeaders.has("Range")) {
+ const range = reqHeaders.get("Range");
+ // ensure uppercase range to avoid bug in kiwix-serve
+ reqHeaders = {"Range": range};
+ }
+
+ let payload = null;
+
+ let response = null;
+
+ if (hasPayload) {
+ // response = await fetch(this.sourceUrl + "A/" + encodedUrl, {headers: reqHeaders});
+ // DEV: modded for kiwix-js
+ // let kiwixJSUrl = new URL(sw.prefix + encodedUrl);
+ let kiwixJSUrl = sw.prefix + encodedUrl;
+ // DEV: For diagnostic purposes, you can send the expected headers as headers below. Although originally, or if used as a Worker,
+ // Replay will issue a Fetch with the requested (rather than expected) headers, we can't do that within a Service Worker, and in any
+ // case, headers are retrieved as a separate process in Kiwix ZIMs. So, only the expected headers could be meaningful in some cases.
+ // Note that range requests for video are responded to with a full uncompressed blob, so for most practical purposes, the expected headers are
+ // not needed. Support may need to be added in future versions of warc2zim.
+ response = await fetchUrlFromZIM(kiwixJSUrl, null/*, headers*/);
+ // DEV: End kiwix-js mod
+
+ if (response.body) {
+ payload = new c(response.body.getReader(), false);
+ }
+
+ if (response.status === 206) {
+ status = 206;
+ statusText = "Partial Content";
+ headers.set("Content-Length", response.headers.get("Content-Length"));
+ headers.set("Content-Range", response.headers.get("Content-Range"));
+ headers.set("Accept-Ranges", "bytes");
+ }
+ }
+
+ if (!payload) {
+ payload = new Uint8Array([]);
+ }
+
+ if (!date) {
+ date = new Date();
+ }
+
+ if (!headers) {
+ headers = new Headers();
+ }
+
+ const isLive = false;
+ const noRW = false;
+
+ return new ArchiveResponse({payload, status, statusText, headers, url, date, noRW, isLive});
+ }
+ }
+
+ async resolveHeaders(url) {
+ const urlNoScheme = url.slice(url.indexOf("//") + 2);
+
+ // need to escape utf-8, then % encode the entire string
+ let encodedUrl = encodeURI(urlNoScheme);
+ encodedUrl = encodeURIComponent(urlNoScheme);
+
+ // let headersResp = await fetch(this.sourceUrl + "H/" + encodedUrl);
+
+ // DEV: modded for kiwix-js
+ // let kiwixJSUrl = new URL(sw.prefix.replace(/\/A\/$/, '/H/') + encodedUrl);
+ let kiwixJSUrl = sw.prefix.replace(/\/A\/$/, '/H/') + encodedUrl;
+ let headersResp = await fetchUrlFromZIM(kiwixJSUrl);
+ // DEV: End kiwix-js mod
+
+ if (headersResp.status !== 200) {
+ return null;
+ }
+
+ let headers = null;
+ let date = null;
+ let status = null;
+ let statusText = null;
+ let hasPayload = false;
+
+ try {
+ const record = await w.parse(headersResp.body);
+
+ if (record.warcType === "revisit") {
+ const warcRevisitTarget = record.warcHeaders.headers.get("WARC-Refers-To-Target-URI");
+ if (warcRevisitTarget && warcRevisitTarget !== url) {
+ return await this.resolveHeaders(warcRevisitTarget);
+ }
+ }
+
+ date = new Date(record.warcDate);
+
+ if (record.httpHeaders) {
+ headers = record.httpHeaders.headers;
+ status = Number(record.httpHeaders.statusCode);
+ statusText = record.httpHeaders.statusText;
+ hasPayload = record.httpHeaders.headers.get("Content-Length") !== "0";
+ } else if (record.warcType === "resource") {
+ headers = new Headers();
+ headers.set("Content-Type", record.warcContentType);
+ headers.set("Content-Length", record.warcContentLength);
+ status = 200;
+ statusText = "OK";
+ hasPayload = record.warcContentLength > 0;
+ }
+
+ if (!status) {
+ status = 200;
+ }
+
+ } catch (e) {
+ console.warn(e);
+ console.warn("Ignoring headers, error parsing headers response for: " + url);
+ }
+
+ // console.debug('Header resolved:', {encodedUrl, headers, date, status, statusText, hasPayload});
+
+ return {encodedUrl, headers, date, status, statusText, hasPayload};
+ }
+}
+
+;// CONCATENATED MODULE: ./src/detectfiletype.js
+// https://en.wikipedia.org/wiki/List_of_file_signatures
+const zipMagicBytes = [0x50, 0x4B, 0x03, 0x04];
+const isZipFile = hasMagicBytes(zipMagicBytes);
+
+const gzMagicBytes = [0x1F, 0x8B, 0x08];
+const isGzFile = hasMagicBytes(gzMagicBytes);
+
+// starts with "WARC""
+const warcMagicBytes = [0x57, 0x41, 0x52, 0x43];
+const isWarcFile = hasMagicBytes(warcMagicBytes);
+
+const PEEK_BYTES = 4;
+
+// todo: improve this to do full detection of different text types
+function detectTextType(bytes) {
+ try {
+ const text = new TextDecoder().decode(bytes);
+ const lines = text.split("\n");
+
+ if (lines > 1 && lines.indexOf(" {")) {
+ return ".cdxj";
+ }
+ } catch (e) {
+ return "";
+ }
+}
+
+function hasMagicBytes(magicBytes) {
+ return fileBytes => {
+ for (const [index, value] of magicBytes.entries()) {
+ if (value !== fileBytes[index]) {
+ return false;
+ }
+ }
+ return true;
+ };
+}
+
+function getKnownFileExtension(name) {
+ const fileExtensions = [
+ ".warc",
+ ".warc.gz",
+ ".cdx",
+ ".cdxj",
+ ".har",
+ ".json",
+ ".wacz",
+ ".zip"
+ ];
+ for (const ext of fileExtensions) {
+ if (name.endsWith(ext)) {
+ return ext;
+ }
+ }
+ return "";
+}
+
+function checkMagicBytes(fileBytes) {
+ // todo: add additional detection for WACZ besides just zip
+ if (isZipFile(fileBytes)) {
+ return ".wacz";
+ }
+
+ if (isWarcFile(fileBytes)) {
+ return ".warc";
+ }
+
+ if (isGzFile(fileBytes)) {
+ return ".warc.gz";
+ }
+}
+
+async function detectFileType(response) {
+ const reader = response.body.getReader();
+ let fileType = "";
+ const { value, done } = await reader.read();
+ if (!done && value.length >= PEEK_BYTES) {
+ fileType = checkMagicBytes(value.slice(0, PEEK_BYTES));
+ if (!fileType) {
+ fileType = detectTextType(value);
+ }
+ }
+ if (!done) {
+ reader.cancel();
+ }
+ return fileType;
+}
+;// CONCATENATED MODULE: ./src/loaders.js
+
+
+//import { WACZRemoteArchiveDB } from "./waczarchive";
+
+
+//import { WBNLoader } from "./wbnloader";
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+if (!globalThis.self) {
+ globalThis.self = globalThis;
+}
+
+self.interruptLoads = {};
+
+
+// ===========================================================================
+class CollectionLoader
+{
+ constructor() {
+ this.colldb = null;
+ this.root = null;
+ this.checkIpfs = true;
+ this._init_db = this._initDB();
+ }
+
+ async _initDB() {
+ this.colldb = await openDB("collDB", 1, {
+ upgrade: (db/*, oldV, newV, tx*/) => {
+ const collstore = db.createObjectStore("colls", {keyPath: "name"});
+
+ collstore.createIndex("type", "type");
+ }
+ });
+ }
+
+ async loadAll(dbColls) {
+ await this._init_db;
+
+ if (dbColls) {
+ for (const extraColl of dbColls.split(",")) {
+ const parts = extraColl.split(":");
+ if (parts.length === 2) {
+ const config = {dbname: parts[1], sourceName: parts[1], decode: false};
+ const collData = {name: parts[0], type: "archive", config};
+ console.log("Adding Coll: " + JSON.stringify(collData));
+ await this.colldb.put("colls", collData);
+ }
+ }
+ }
+
+ try {
+ const allColls = await this.listAll();
+
+ const promises = allColls.map((data) => this._initColl(data));
+
+ await Promise.all(promises);
+ } catch (e) {
+ console.warn(e.toString());
+ }
+
+ return true;
+ }
+
+ async listAll() {
+ await this._init_db;
+ return await this.colldb.getAll("colls");
+ }
+
+ async loadColl(name) {
+ await this._init_db;
+ const data = await this.colldb.get("colls", name);
+ if (!data) {
+ return null;
+ }
+
+ return await this._initColl(data);
+ }
+
+ async reload(name) {
+ return this.loadColl(name);
+ }
+
+ async deleteColl(name) {
+ await this._init_db;
+ const data = await this.colldb.get("colls", name);
+ if (!data) {
+ return false;
+ }
+
+ if (data.config.dbname) {
+ try {
+ await deleteDB(data.config.dbname, {
+ blocked(_, e) {
+ console.log(`Unable to delete ${data.config.dbname}, blocked: ${e}`);
+ }
+ });
+ } catch(e) {
+ console.warn(e);
+ return false;
+ }
+ }
+
+ await this.colldb.delete("colls", name);
+
+ return true;
+ }
+
+ async updateAuth(name, newHeaders) {
+ await this._init_db;
+ const data = await this.colldb.get("colls", name);
+ if (!data) {
+ return false;
+ }
+ data.config.headers = newHeaders;
+ await this.colldb.put("colls", data);
+ return true;
+ }
+
+ async updateMetadata(name, newMetadata) {
+ await this._init_db;
+ const data = await this.colldb.get("colls", name);
+ if (!data) {
+ return false;
+ }
+ data.config.metadata = {...data.config.metadata, ...newMetadata};
+
+ await this.colldb.put("colls", data);
+ return data.config.metadata;
+ }
+
+ async updateSize(name, fullSize, dedupSize, decodeUpdate) {
+ await this._init_db;
+ const data = await this.colldb.get("colls", name);
+ if (!data) {
+ return false;
+ }
+
+ const metadata = data.config.metadata;
+ metadata.fullSize = (metadata.fullSize || 0) + fullSize;
+ metadata.size = (metadata.size || 0) + dedupSize;
+ metadata.mtime = new Date().getTime();
+
+ // if set, also update decode (a little hacky)
+ if (decodeUpdate !== undefined) {
+ data.config.decode = decodeUpdate;
+ }
+ await this.colldb.put("colls", data);
+ return metadata;
+ }
+
+ async initNewColl(metadata, extraConfig = {}, type = "archive") {
+ await this._init_db;
+ const id = randomId();
+ const dbname = "db:" + id;
+ const sourceUrl = "local://" + id;
+ const decode = false;
+ const ctime = new Date().getTime();
+
+ const data = {
+ name: id,
+ type,
+ config: {
+ dbname,
+ ctime,
+ decode,
+ metadata,
+ sourceUrl,
+ extraConfig,
+ }
+ };
+
+ const coll = await this._initColl(data);
+ await this.colldb.put("colls", data);
+ return coll;
+ }
+
+ async _initColl(data) {
+ const store = await this._initStore(data.type, data.config);
+
+ const name = data.name;
+ const config = data.config;
+
+ if (data.config.root && !this.root) {
+ this.root = name;
+ }
+
+ return this._createCollection({name, store, config});
+ }
+
+ async _initStore(type, config) {
+ let sourceLoader = null;
+ let store = null;
+
+ switch (type) {
+ case "archive":
+ store = new ArchiveDB(config.dbname);
+ break;
+
+ case "remotesource":
+ sourceLoader = await createLoader({
+ url: config.loadUrl,
+ headers: config.headers,
+ size: config.size,
+ extra: config.extra
+ });
+ store = new RemoteSourceArchiveDB(config.dbname, sourceLoader, config.noCache);
+ break;
+
+ case "remoteprefix":
+ store = new RemotePrefixArchiveDB(config.dbname, config.remotePrefix, config.headers, config.noCache);
+ break;
+
+ case "wacz":
+ case "remotezip":
+ case "multiwacz":
+ sourceLoader = await createLoader({
+ url: config.loadUrl || config.sourceUrl,
+ headers: config.headers,
+ extra: config.extra
+ });
+ store = new MultiWACZ(config, sourceLoader, type === "multiwacz" ? "json" : "wacz");
+ break;
+
+ case "remotewarcproxy":
+ store = new RemoteWARCProxy(config);
+ break;
+
+ case "live":
+ store = new LiveProxy(config.extraConfig);
+ break;
+ }
+
+ if (!store) {
+ console.log("no store found: " + type);
+ return null;
+ }
+
+ if (store.initing) {
+ await store.initing;
+ }
+
+ return store;
+ }
+
+ _createCollection(opts) {
+ return opts;
+ }
+}
+
+// ===========================================================================
+class WorkerLoader extends CollectionLoader
+{
+ constructor(worker) {
+ super();
+ // modded for kiwix-js
+ // this.registerListener(worker);
+ }
+
+ async hasCollection(name) {
+ await this._init_db;
+
+ return await this.colldb.getKey("colls", name) != null;
+ }
+
+ registerListener(worker) {
+ worker.addEventListener("message", event => {
+ if (event.waitUntil) {
+ event.waitUntil(this._handleMessage(event));
+ } else {
+ this._handleMessage(event);
+ }
+ });
+ }
+
+ async _handleMessage(event) {
+ await this._init_db;
+
+ const client = event.source || self;
+
+ switch (event.data.msg_type) {
+ case "addColl":
+ {
+ const name = event.data.name;
+
+ const progressUpdate = (percent, error, currentSize, totalSize, fileHandle = null, extraMsg = null) => {
+ client.postMessage({
+ "msg_type": "collProgress",
+ name,
+ percent,
+ error,
+ currentSize,
+ totalSize,
+ fileHandle,
+ extraMsg
+ });
+ };
+
+ let res;
+
+ try {
+ res = await this.colldb.get("colls", name);
+ if (res) {
+ if (!event.data.skipExisting) {
+ await this.deleteColl(name);
+ res = await this.addCollection(event.data, progressUpdate);
+ }
+ } else {
+ res = await this.addCollection(event.data, progressUpdate);
+ }
+
+ if (!res) {
+ if (event.data.name) {
+ try {
+ await deleteDB("db:" + event.data.name, {
+ blocked(_, e) {
+ console.log(`Load failed and unable to delete ${event.data.name}: ${e}`);
+ }
+ });
+ } catch (e) {
+ console.warn(e);
+ }
+ }
+ return;
+ }
+
+ } catch (e) {
+ if (e instanceof AuthNeededError) {
+ console.warn(e);
+ progressUpdate(0, "permission_needed", null, null, e.info && e.info.fileHandle);
+ return;
+ } else if (e.name === "ConstraintError") {
+ console.log("already being added, just continue...");
+ res = await this.colldb.get("colls", name);
+ } else {
+ console.warn(e);
+ progressUpdate(0, "An unexpected error occured: " + e.toString());
+ return;
+ }
+ }
+
+ client.postMessage({
+ msg_type: "collAdded",
+ name,
+ sourceUrl: res.config.sourceUrl
+ });
+
+ //this.doListAll(client);
+ break;
+ }
+
+ case "cancelLoad":
+ {
+ const name = event.data.name;
+
+ const p = new Promise((resolve) => self.interruptLoads[name] = resolve);
+
+ await p;
+
+ await this.deleteColl(name);
+
+ delete self.interruptLoads[name];
+
+ break;
+ }
+
+ case "removeColl":
+ {
+ const name = event.data.name;
+
+ if (await this.hasCollection(name)) {
+ await this.deleteColl(name);
+ this.doListAll(client);
+ }
+ break;
+ }
+
+ case "listAll":
+ this.doListAll(client);
+ break;
+
+ case "reload":
+ this.reload(event.data.name);
+ break;
+ }
+ }
+
+ async doListAll(client) {
+ const msgData = [];
+ const allColls = await this.listAll();
+
+ for (const coll of allColls) {
+
+ //const pageList = await coll.store.getAllPages();
+
+ msgData.push({
+ "name": coll.name,
+ "prefix": coll.name,
+ "pageList": [],
+ "sourceName": coll.config.sourceName
+ });
+ }
+ client.postMessage({ "msg_type": "listAll", "colls": msgData });
+ }
+
+ async addCollection(data, progressUpdate) {
+ let name = data.name;
+
+ let type = null;
+ let config = {root: data.root || false};
+ let db = null;
+
+ let updateExistingConfig = null;
+
+ const file = data.file;
+
+ if (!file || !file.sourceUrl) {
+ progressUpdate(0, "Invalid Load Request");
+ return false;
+ }
+
+ config.dbname = "db:" + name;
+
+ if (file.sourceUrl.startsWith("proxy:")) {
+ config.sourceUrl = file.sourceUrl.slice("proxy:".length);
+ config.extraConfig = data.extraConfig;
+ if (!config.extraConfig.prefix) {
+ config.extraConfig.prefix = config.sourceUrl;
+ }
+ config.topTemplateUrl = data.topTemplateUrl;
+ config.metadata = {};
+ type = data.type || config.extraConfig.type || "remotewarcproxy";
+
+ db = await this._initStore(type, config);
+
+ } else {
+ let loader = null;
+
+ if (file.newFullImport) {
+ name = randomId();
+ file.loadUrl = file.loadUrl || file.sourceUrl;
+ file.name = file.name || file.sourceUrl;
+ file.sourceUrl = "local://" + name;
+ }
+
+ type = "archive";
+
+ if (file.newFullImport && file.importCollId) {
+ const existing = await this.colldb.get("colls", file.importCollId);
+ if (!existing || existing.type !== "archive") {
+ progressUpdate(0, "Invalid Existing Collection: " + file.importCollId);
+ return;
+ }
+ config.dbname = existing.config.dbname;
+ updateExistingConfig = existing.config;
+ updateExistingConfig.decode = true;
+ }
+
+ let loadUrl = file.loadUrl || file.sourceUrl;
+
+ if (!loadUrl.match(/[\w]+:\/\//)) {
+ loadUrl = new URL(loadUrl, self.location.href).href;
+ }
+
+ config.decode = true;
+ config.onDemand = false;
+ config.loadUrl = loadUrl;
+ config.sourceUrl = file.sourceUrl;
+
+ config.sourceName = file.name || file.sourceUrl;
+
+ // parse to strip out query, keep hash/fragment (if any)
+ try {
+ if (config.sourceName.match(/https?:\/\//)) {
+ const sourceUrl = new URL(config.sourceName);
+ config.sourceName = sourceUrl.pathname + sourceUrl.hash;
+ }
+ } catch (e) {
+ // ignore, keep sourceName as is
+ }
+ config.sourceName = config.sourceName.slice(config.sourceName.lastIndexOf("/") + 1);
+
+ config.size = typeof(file.size) === "number" ? file.size : null;
+ config.extra = file.extra;
+
+ if (config.loadUrl.startsWith("file://") && !file.blob && !config.extra) {
+ if (this._fileHandles && this._fileHandles[config.sourceUrl]) {
+ config.extra = {fileHandle: this._fileHandles[config.sourceUrl]};
+ } else {
+ progressUpdate(0, "missing_local_file");
+ return;
+ }
+ }
+
+ config.extraConfig = data.extraConfig;
+ config.headers = file.headers || (config.extraConfig && config.extraConfig.headers);
+ config.noCache = file.noCache;
+
+ let sourceLoader = await createLoader({
+ url: loadUrl,
+ headers: config.headers,
+ size: file.size,
+ extra: config.extra,
+ blob: file.blob
+ });
+
+ if (file.loadEager) {
+ const {response} = await sourceLoader.doInitialFetch(false, true);
+ const arrayBuffer = new Uint8Array(await response.arrayBuffer());
+ const extra = {arrayBuffer};
+
+ //config.extra = extra;
+ file.newFullImport = true;
+
+ sourceLoader = await createLoader({
+ url: loadUrl,
+ headers: config.headers,
+ size: file.size,
+ extra,
+ });
+ }
+
+ let sourceExt = getKnownFileExtension(config.sourceName);
+
+ let { abort, response } = await sourceLoader.doInitialFetch(sourceExt === ".wacz");
+
+ if (!sourceExt) {
+ sourceExt = await detectFileType(await response.clone());
+ }
+
+ const stream = response.body;
+
+ config.onDemand = sourceLoader.canLoadOnDemand && !file.newFullImport;
+
+ if (!sourceLoader.isValid) {
+ const text = sourceLoader.length <= 1000 ? await response.text() : "";
+ progressUpdate(0, `\
+Sorry, this URL could not be loaded.
+Make sure this is a valid URL and you have access to this file.
+Status: ${response.status} ${response.statusText}
+Error Details:
+${text}`);
+ if (abort) {
+ abort.abort();
+ }
+ return false;
+ }
+
+ if (!sourceLoader.length) {
+ progressUpdate(0, `\
+Sorry, this URL could not be loaded because the size of the file is not accessible.
+Make sure this is a valid URL and you have access to this file.`);
+ if (abort) {
+ abort.abort();
+ }
+ return false;
+ }
+
+ const contentLength = sourceLoader.length;
+
+ if (sourceExt === ".wacz") {
+ if (config.onDemand) {
+ loader = new SingleWACZLoader(sourceLoader, config, name);
+ db = new MultiWACZ(config, sourceLoader, "wacz");
+ type = "wacz";
+
+ // can load on demand, but want a full import
+ } else if (sourceLoader.canLoadOnDemand && file.newFullImport) {
+ loader = new SingleWACZFullImportLoader(sourceLoader, config, name);
+ //use default db
+ db = null;
+ delete config.extra;
+
+ } else {
+ progressUpdate(0, "Sorry, can't load this WACZ file due to lack of range request support on the server");
+ if (abort) {
+ abort.abort();
+ }
+ return false;
+ }
+
+ } else if (sourceExt === ".warc" || sourceExt === ".warc.gz") {
+ if (!config.noCache && (contentLength < MAX_FULL_DOWNLOAD_SIZE || !config.onDemand)) {
+ loader = new WARCLoader(stream, abort, name);
+ } else {
+ loader = new CDXFromWARCLoader(stream, abort, name);
+ type = "remotesource";
+ db = new RemoteSourceArchiveDB(config.dbname, sourceLoader, config.noCache);
+ }
+
+ } else if (sourceExt === ".cdx" || sourceExt === ".cdxj") {
+ config.remotePrefix = data.remotePrefix || loadUrl.slice(0, loadUrl.lastIndexOf("/") + 1);
+ loader = new CDXLoader(stream, abort, name);
+ type = "remoteprefix";
+ db = new RemotePrefixArchiveDB(config.dbname, config.remotePrefix, config.headers, config.noCache);
+
+ // } else if (sourceExt === ".wbn") {
+ // //todo: fix
+ // loader = new WBNLoader(await response.arrayBuffer());
+ // config.decode = false;
+
+ } else if (sourceExt === ".har") {
+ loader = new HARLoader(await response.json());
+ config.decode = false;
+ } else if (sourceExt === ".json") {
+ db = new MultiWACZ(config, sourceLoader, "json");
+ loader = new JSONResponseMultiWACZLoader(response);
+ type = "multiwacz";
+ }
+
+ if (!loader) {
+ progressUpdate(0, `The ${config.sourceName} is not a known archive format that could be loaded.`);
+ if (abort) {
+ abort.abort();
+ }
+ return false;
+ }
+
+ if (!db) {
+ db = new ArchiveDB(config.dbname);
+ }
+ await db.initing;
+
+ try {
+ config.metadata = await loader.load(db, progressUpdate, contentLength);
+ } catch (e) {
+ if (!(e instanceof Canceled)) {
+ progressUpdate(0, `Unexpected Loading Error: ${e.toString()}`);
+ console.warn(e);
+ }
+ return false;
+ }
+
+ if (updateExistingConfig) {
+ await this.updateSize(file.importCollId, contentLength, contentLength, updateExistingConfig.decode);
+ return {config: updateExistingConfig};
+ }
+
+ if (!config.metadata.size) {
+ config.metadata.size = contentLength;
+ }
+
+ if (!config.metadata.title) {
+ config.metadata.title = config.sourceName;
+ }
+ }
+
+ config.ctime = new Date().getTime();
+
+ if (this._fileHandles && config.extra && config.extra.fileHandle) {
+ delete this._fileHandles[config.sourceUrl];
+ }
+
+ const collData = {name, type, config};
+ await this.colldb.add("colls", collData);
+ collData.store = db;
+ return collData;
+ }
+}
+
+
+
+
+;// CONCATENATED MODULE: ./src/statstracker.js
+class StatsTracker {
+ constructor() {
+ this.timeRanges = {};
+ }
+
+ updateStats(date, status, request, event) {
+ const id = event.clientId || event.resultingClientId;
+
+ if (!id || !date) {
+ return;
+ }
+
+ if (!request.url || request.url.indexOf("mp_/") < 0) {
+ return;
+ }
+
+ if (request.destination === "document" && (status > 300 && status < 400)) {
+ return;
+ }
+
+ let timeRange = null;
+
+ if (this.timeRanges[id] === undefined) {
+ timeRange = { "count": 0, "children": [] };
+ this.timeRanges[id] = timeRange;
+ if (request.referrer.indexOf("mp_/") > 0) {
+ self.clients.matchAll({ "type": "window" }).then(clients => this.updateStatsParent(id, request.referrer, clients));
+ }
+ } else {
+ timeRange = this.timeRanges[id];
+ }
+
+ const timestamp = date.getTime();
+
+ if (!timeRange.min || (timestamp < timeRange.min)) {
+ timeRange.min = timestamp;
+ }
+
+ if (!timeRange.max || (timestamp > timeRange.max)) {
+ timeRange.max = timestamp;
+ }
+
+ timeRange.count++;
+ }
+
+ updateStatsParent(id, referrer, clients) {
+ for (let client of clients) {
+ if (client.url === referrer) {
+ //self.timeRanges[id].parent = client.id;
+ if (!this.timeRanges[client.id]) {
+ this.timeRanges[client.id] = { "count": 0, "children": { id: 1 } };
+ } else {
+ this.timeRanges[client.id].children[id] = 1;
+ }
+ break;
+ }
+ }
+ }
+
+ async getStats(event) {
+ //const client = await self.clients.get(fe.clientId);
+
+ //const timeRange = self.timeRanges[client.url] || {};
+
+ const reqUrl = new URL(event.request.url);
+
+ const params = new URLSearchParams(reqUrl.search);
+
+ let id = 0;
+
+ const url = params.get("url");
+
+ const clients = await self.clients.matchAll({ "type": "window" });
+
+ const validIds = {};
+
+ for (let client of clients) {
+ if (client.url === url) {
+ id = client.id;
+ }
+ validIds[client.id] = 1;
+ }
+
+ const srcRange = this.timeRanges[id] || {};
+
+ const timeRange = {
+ "count": srcRange.count || 0,
+ "min": srcRange.min,
+ "max": srcRange.max
+ };
+
+ const children = (this.timeRanges[id] && Object.keys(this.timeRanges[id].children)) || [];
+
+ for (let child of children) {
+ const childRange = this.timeRanges[child];
+
+ if (!childRange) {
+ continue;
+ }
+
+
+ if (!timeRange.min || (childRange.min < timeRange.min)) {
+ timeRange.min = childRange.min;
+ }
+
+ if (!timeRange.max || (childRange.max > timeRange.max)) {
+ timeRange.max = childRange.max;
+ }
+
+ timeRange.count += childRange.count;
+ }
+
+ // remove invalid timeranges
+ for (let id of Object.keys(this.timeRanges)) {
+ if (!validIds[id]) {
+ delete this.timeRanges[id];
+ }
+ }
+
+ return new Response(JSON.stringify(timeRange), { "headers": { "Content-Type": "application/json" } });
+ }
+}
+
+
+
+;// CONCATENATED MODULE: ./node_modules/path-parser/node_modules/tslib/tslib.es6.js
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global Reflect, Promise */
+
+var tslib_tslib_es6_extendStatics = function(d, b) {
+ tslib_tslib_es6_extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return tslib_tslib_es6_extendStatics(d, b);
+};
+
+function node_modules_tslib_tslib_es6_extends(d, b) {
+ tslib_tslib_es6_extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+}
+
+var tslib_tslib_es6_assign = function() {
+ tslib_tslib_es6_assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ }
+ return tslib_tslib_es6_assign.apply(this, arguments);
+}
+
+function node_modules_tslib_tslib_es6_rest(s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+}
+
+function tslib_tslib_es6_decorate(decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+}
+
+function tslib_tslib_es6_param(paramIndex, decorator) {
+ return function (target, key) { decorator(target, key, paramIndex); }
+}
+
+function tslib_tslib_es6_metadata(metadataKey, metadataValue) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+}
+
+function node_modules_tslib_tslib_es6_awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+}
+
+function tslib_tslib_es6_generator(thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (_) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+}
+
+function tslib_tslib_es6_createBinding(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}
+
+function tslib_tslib_es6_exportStar(m, exports) {
+ for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
+}
+
+function tslib_tslib_es6_values(o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+}
+
+function tslib_tslib_es6_read(o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+}
+
+function node_modules_tslib_tslib_es6_spread() {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(tslib_tslib_es6_read(arguments[i]));
+ return ar;
+}
+
+function tslib_tslib_es6_spreadArrays() {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
+};
+
+function tslib_tslib_es6_await(v) {
+ return this instanceof tslib_tslib_es6_await ? (this.v = v, this) : new tslib_tslib_es6_await(v);
+}
+
+function tslib_tslib_es6_asyncGenerator(thisArg, _arguments, generator) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof tslib_tslib_es6_await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+}
+
+function tslib_tslib_es6_asyncDelegator(o) {
+ var i, p;
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: tslib_tslib_es6_await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
+}
+
+function tslib_tslib_es6_asyncValues(o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof tslib_tslib_es6_values === "function" ? tslib_tslib_es6_values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+}
+
+function tslib_tslib_es6_makeTemplateObject(cooked, raw) {
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
+ return cooked;
+};
+
+function tslib_tslib_es6_importStar(mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
+ result.default = mod;
+ return result;
+}
+
+function tslib_tslib_es6_importDefault(mod) {
+ return (mod && mod.__esModule) ? mod : { default: mod };
+}
+
+function tslib_tslib_es6_classPrivateFieldGet(receiver, privateMap) {
+ if (!privateMap.has(receiver)) {
+ throw new TypeError("attempted to get private field on non-instance");
+ }
+ return privateMap.get(receiver);
+}
+
+function tslib_tslib_es6_classPrivateFieldSet(receiver, privateMap, value) {
+ if (!privateMap.has(receiver)) {
+ throw new TypeError("attempted to set private field on non-instance");
+ }
+ privateMap.set(receiver, value);
+ return value;
+}
+
+;// CONCATENATED MODULE: ./node_modules/search-params/dist/search-params.esm.js
+var makeOptions = function makeOptions(opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ return {
+ arrayFormat: opts.arrayFormat || 'none',
+ booleanFormat: opts.booleanFormat || 'none',
+ nullFormat: opts.nullFormat || 'default'
+ };
+};
+
+var encodeValue = function encodeValue(value) {
+ return encodeURIComponent(value);
+};
+
+var decodeValue = function decodeValue(value) {
+ return decodeURIComponent(value);
+};
+
+var encodeBoolean = function encodeBoolean(name, value, opts) {
+ if (opts.booleanFormat === 'empty-true' && value) {
+ return name;
+ }
+
+ var encodedValue;
+
+ if (opts.booleanFormat === 'unicode') {
+ encodedValue = value ? '✓' : '✗';
+ } else {
+ encodedValue = value.toString();
+ }
+
+ return name + "=" + encodedValue;
+};
+
+var encodeNull = function encodeNull(name, opts) {
+ if (opts.nullFormat === 'hidden') {
+ return '';
+ }
+
+ if (opts.nullFormat === 'string') {
+ return name + "=null";
+ }
+
+ return name;
+};
+
+var getNameEncoder = function getNameEncoder(opts) {
+ if (opts.arrayFormat === 'index') {
+ return function (name, index) {
+ return name + "[" + index + "]";
+ };
+ }
+
+ if (opts.arrayFormat === 'brackets') {
+ return function (name) {
+ return name + "[]";
+ };
+ }
+
+ return function (name) {
+ return name;
+ };
+};
+
+var encodeArray = function encodeArray(name, arr, opts) {
+ var encodeName = getNameEncoder(opts);
+ return arr.map(function (val, index) {
+ return encodeName(name, index) + "=" + encodeValue(val);
+ }).join('&');
+};
+var encode = function encode(name, value, opts) {
+ if (value === null) {
+ return encodeNull(name, opts);
+ }
+
+ if (typeof value === 'boolean') {
+ return encodeBoolean(name, value, opts);
+ }
+
+ if (Array.isArray(value)) {
+ return encodeArray(name, value, opts);
+ }
+
+ return name + "=" + encodeValue(value);
+};
+var decode = function decode(value, opts) {
+ if (value === undefined) {
+ return opts.booleanFormat === 'empty-true' ? true : null;
+ }
+
+ if (opts.booleanFormat === 'string') {
+ if (value === 'true') {
+ return true;
+ }
+
+ if (value === 'false') {
+ return false;
+ }
+ }
+
+ if (opts.booleanFormat === 'unicode') {
+ if (decodeValue(value) === '✓') {
+ return true;
+ }
+
+ if (decodeValue(value) === '✗') {
+ return false;
+ }
+ }
+
+ if (opts.nullFormat === 'string') {
+ if (value === 'null') {
+ return null;
+ }
+ }
+
+ return decodeValue(value);
+};
+
+var getSearch = function getSearch(path) {
+ var pos = path.indexOf('?');
+
+ if (pos === -1) {
+ return path;
+ }
+
+ return path.slice(pos + 1);
+};
+var isSerialisable = function isSerialisable(val) {
+ return val !== undefined;
+};
+var parseName = function parseName(name) {
+ var bracketPosition = name.indexOf('[');
+ var hasBrackets = bracketPosition !== -1;
+ return {
+ hasBrackets: hasBrackets,
+ name: hasBrackets ? name.slice(0, bracketPosition) : name
+ };
+};
+
+/**
+ * Parse a querystring and return an object of parameters
+ */
+
+var search_params_esm_parse = function parse(path, opts) {
+ var options = makeOptions(opts);
+ return getSearch(path).split('&').reduce(function (params, param) {
+ var _a = param.split('='),
+ rawName = _a[0],
+ value = _a[1];
+
+ var _b = parseName(rawName),
+ hasBrackets = _b.hasBrackets,
+ name = _b.name;
+
+ var currentValue = params[name];
+ var decodedValue = decode(value, options);
+
+ if (currentValue === undefined) {
+ params[name] = hasBrackets ? [decodedValue] : decodedValue;
+ } else {
+ params[name] = (Array.isArray(currentValue) ? currentValue : [currentValue]).concat(decodedValue);
+ }
+
+ return params;
+ }, {});
+};
+/**
+ * Build a querystring from an object of parameters
+ */
+
+var search_params_esm_build = function build(params, opts) {
+ var options = makeOptions(opts);
+ return Object.keys(params).filter(function (paramName) {
+ return isSerialisable(params[paramName]);
+ }).map(function (paramName) {
+ return encode(paramName, params[paramName], options);
+ }).filter(Boolean).join('&');
+};
+/**
+ * Remove a list of parameters from a querystring
+ */
+
+var omit = function omit(path, paramsToOmit, opts) {
+ var options = makeOptions(opts);
+ var searchPart = getSearch(path);
+
+ if (searchPart === '') {
+ return {
+ querystring: '',
+ removedParams: {}
+ };
+ }
+
+ var _a = path.split('&').reduce(function (_a, chunk) {
+ var left = _a[0],
+ right = _a[1];
+ var rawName = chunk.split('=')[0];
+ var name = parseName(rawName).name;
+ return paramsToOmit.indexOf(name) === -1 ? [left.concat(chunk), right] : [left, right.concat(chunk)];
+ }, [[], []]),
+ kept = _a[0],
+ removed = _a[1];
+
+ return {
+ querystring: kept.join('&'),
+ removedParams: search_params_esm_parse(removed.join('&'), options)
+ };
+};
+/**
+ * Remove a list of parameters from a querystring
+ */
+
+var keep = function keep(path, paramsToKeep, opts) {
+ var options = makeOptions(opts);
+ var searchPart = getSearch(path);
+
+ if (searchPart === '') {
+ return {
+ keptParams: {},
+ querystring: ''
+ };
+ }
+
+ var kept = path.split('&').reduce(function (acc, chunk) {
+ var rawName = chunk.split('=')[0];
+ var name = parseName(rawName).name;
+
+ if (paramsToKeep.includes(name)) {
+ acc.push(chunk);
+ }
+
+ return acc;
+ }, []);
+ return {
+ keptParams: search_params_esm_parse(kept.join('&'), options),
+ querystring: kept.join('&')
+ };
+};
+
+
+//# sourceMappingURL=search-params.esm.js.map
+
+;// CONCATENATED MODULE: ./node_modules/path-parser/dist/path-parser.esm.js
+
+
+
+/**
+ * We encode using encodeURIComponent but we want to
+ * preserver certain characters which are commonly used
+ * (sub delimiters and ':')
+ *
+ * https://www.ietf.org/rfc/rfc3986.txt
+ *
+ * reserved = gen-delims / sub-delims
+ *
+ * gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
+ *
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ / "*" / "+" / "," / ";" / "="
+ */
+var excludeSubDelimiters = /[^!$'()*+,;|:]/g;
+var encodeURIComponentExcludingSubDelims = function encodeURIComponentExcludingSubDelims(segment) {
+ return segment.replace(excludeSubDelimiters, function (match) {
+ return encodeURIComponent(match);
+ });
+};
+var encodingMethods = {
+ "default": encodeURIComponentExcludingSubDelims,
+ uri: encodeURI,
+ uriComponent: encodeURIComponent,
+ none: function none(val) {
+ return val;
+ },
+ legacy: encodeURI
+};
+var decodingMethods = {
+ "default": decodeURIComponent,
+ uri: decodeURI,
+ uriComponent: decodeURIComponent,
+ none: function none(val) {
+ return val;
+ },
+ legacy: decodeURIComponent
+};
+var encodeParam = function encodeParam(param, encoding, isSpatParam) {
+ var encoder = encodingMethods[encoding] || encodeURIComponentExcludingSubDelims;
+
+ if (isSpatParam) {
+ return String(param).split('/').map(encoder).join('/');
+ }
+
+ return encoder(String(param));
+};
+var decodeParam = function decodeParam(param, encoding) {
+ return (decodingMethods[encoding] || decodeURIComponent)(param);
+};
+
+var defaultOrConstrained = function defaultOrConstrained(match) {
+ return '(' + (match ? match.replace(/(^<|>$)/g, '') : "[a-zA-Z0-9-_.~%':|=+\\*@$]+") + ')';
+};
+var rules = [{
+ name: 'url-parameter',
+ pattern: /^:([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})(<(.+?)>)?/,
+ regex: function regex(match) {
+ return new RegExp(defaultOrConstrained(match[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 regex(match) {
+ return new RegExp(';' + match[1] + '=' + defaultOrConstrained(match[2]));
+ }
+}, {
+ name: 'query-parameter',
+ pattern: /^(?:\?|&)(?::)?([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})/
+}, {
+ name: 'delimiter',
+ pattern: /^(\/|\?)/,
+ regex: function regex(match) {
+ return new RegExp('\\' + match[0]);
+ }
+}, {
+ name: 'sub-delimiter',
+ pattern: /^(!|&|-|_|\.|;)/,
+ regex: function regex(match) {
+ return new RegExp(match[0]);
+ }
+}, {
+ name: 'fragment',
+ pattern: /^([0-9a-zA-Z]+)/,
+ regex: function regex(match) {
+ return new RegExp(match[0]);
+ }
+}];
+
+var tokenise = function tokenise(str, tokens) {
+ if (tokens === void 0) {
+ tokens = [];
+ } // Look for a matching rule
+
+
+ var matched = rules.some(function (rule) {
+ var match = str.match(rule.pattern);
+
+ if (!match) {
+ return false;
+ }
+
+ tokens.push({
+ type: rule.name,
+ match: match[0],
+ val: match.slice(1, 2),
+ otherVal: match.slice(2),
+ regex: rule.regex instanceof Function ? rule.regex(match) : rule.regex
+ });
+
+ if (match[0].length < str.length) {
+ tokens = tokenise(str.substr(match[0].length), tokens);
+ }
+
+ return true;
+ }); // If no rules matched, throw an error (possible malformed path)
+
+ if (!matched) {
+ throw new Error("Could not parse path '" + str + "'");
+ }
+
+ return tokens;
+};
+
+var exists = function exists(val) {
+ return val !== undefined && val !== null;
+};
+
+var optTrailingSlash = function optTrailingSlash(source, strictTrailingSlash) {
+ if (strictTrailingSlash) {
+ return source;
+ }
+
+ if (source === '\\/') {
+ return source;
+ }
+
+ return source.replace(/\\\/$/, '') + '(?:\\/)?';
+};
+
+var upToDelimiter = function upToDelimiter(source, delimiter) {
+ if (!delimiter) {
+ return source;
+ }
+
+ return /(\/)$/.test(source) ? source : source + '(\\/|\\?|\\.|;|$)';
+};
+
+var appendQueryParam = function appendQueryParam(params, param, val) {
+ if (val === void 0) {
+ val = '';
+ }
+
+ var existingVal = params[param];
+
+ if (existingVal === undefined) {
+ params[param] = val;
+ } else {
+ params[param] = Array.isArray(existingVal) ? existingVal.concat(val) : [existingVal, val];
+ }
+
+ return params;
+};
+
+var defaultOptions = {
+ urlParamsEncoding: 'default'
+};
+
+var Path =
+/*#__PURE__*/
+
+/** @class */
+function () {
+ function Path(path, options) {
+ if (!path) {
+ throw new Error('Missing path in Path constructor');
+ }
+
+ this.path = path;
+ this.options = tslib_tslib_es6_assign(tslib_tslib_es6_assign({}, defaultOptions), options);
+ this.tokens = tokenise(path);
+ this.hasUrlParams = this.tokens.filter(function (t) {
+ return /^url-parameter/.test(t.type);
+ }).length > 0;
+ 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; // Extract named parameters from tokens
+
+ this.spatParams = this.getParams('url-parameter-splat');
+ this.urlParams = this.getParams(/^url-parameter/); // Query params
+
+ this.queryParams = this.getParams('query-parameter'); // All params
+
+ this.params = this.urlParams.concat(this.queryParams); // Check if hasQueryParams
+ // Regular expressions for url part only (full and partial match)
+
+ this.source = this.tokens.filter(function (t) {
+ return t.regex !== undefined;
+ }).map(function (t) {
+ return t.regex.source;
+ }).join('');
+ }
+
+ Path.createPath = function (path, options) {
+ return new Path(path, options);
+ };
+
+ Path.prototype.isQueryParam = function (name) {
+ return this.queryParams.indexOf(name) !== -1;
+ };
+
+ Path.prototype.isSpatParam = function (name) {
+ return this.spatParams.indexOf(name) !== -1;
+ };
+
+ Path.prototype.test = function (path, opts) {
+ var _this = this;
+
+ var options = tslib_tslib_es6_assign(tslib_tslib_es6_assign({
+ caseSensitive: false,
+ strictTrailingSlash: false
+ }, this.options), opts); // trailingSlash: falsy => non optional, truthy => optional
+
+
+ var source = optTrailingSlash(this.source, options.strictTrailingSlash); // Check if exact match
+
+ var match = this.urlTest(path, source + (this.hasQueryParams ? '(\\?.*$|$)' : '$'), options.caseSensitive, options.urlParamsEncoding); // If no match, or no query params, no need to go further
+
+ if (!match || !this.hasQueryParams) {
+ return match;
+ } // Extract query params
+
+
+ var queryParams = search_params_esm_parse(path, options.queryParams);
+ var unexpectedQueryParams = Object.keys(queryParams).filter(function (p) {
+ return !_this.isQueryParam(p);
+ });
+
+ if (unexpectedQueryParams.length === 0) {
+ // Extend url match
+ Object.keys(queryParams).forEach( // @ts-ignore
+ function (p) {
+ return match[p] = queryParams[p];
+ });
+ return match;
+ }
+
+ return null;
+ };
+
+ Path.prototype.partialTest = function (path, opts) {
+ var _this = this;
+
+ var options = tslib_tslib_es6_assign(tslib_tslib_es6_assign({
+ caseSensitive: false,
+ delimited: true
+ }, this.options), opts); // Check if partial match (start of given path matches regex)
+ // trailingSlash: falsy => non optional, truthy => optional
+
+
+ var source = upToDelimiter(this.source, options.delimited);
+ var match = this.urlTest(path, source, options.caseSensitive, options.urlParamsEncoding);
+
+ if (!match) {
+ return match;
+ }
+
+ if (!this.hasQueryParams) {
+ return match;
+ }
+
+ var queryParams = search_params_esm_parse(path, options.queryParams);
+ Object.keys(queryParams).filter(function (p) {
+ return _this.isQueryParam(p);
+ }).forEach(function (p) {
+ return appendQueryParam(match, p, queryParams[p]);
+ });
+ return match;
+ };
+
+ Path.prototype.build = function (params, opts) {
+ var _this = this;
+
+ if (params === void 0) {
+ params = {};
+ }
+
+ var options = tslib_tslib_es6_assign(tslib_tslib_es6_assign({
+ ignoreConstraints: false,
+ ignoreSearch: false,
+ queryParams: {}
+ }, this.options), opts);
+
+ var encodedUrlParams = Object.keys(params).filter(function (p) {
+ return !_this.isQueryParam(p);
+ }).reduce(function (acc, key) {
+ if (!exists(params[key])) {
+ return acc;
+ }
+
+ var val = params[key];
+
+ var isSpatParam = _this.isSpatParam(key);
+
+ if (typeof val === 'boolean') {
+ acc[key] = val;
+ } else if (Array.isArray(val)) {
+ acc[key] = val.map(function (v) {
+ return encodeParam(v, options.urlParamsEncoding, isSpatParam);
+ });
+ } else {
+ acc[key] = encodeParam(val, options.urlParamsEncoding, isSpatParam);
+ }
+
+ return acc;
+ }, {}); // Check all params are provided (not search parameters which are optional)
+
+ if (this.urlParams.some(function (p) {
+ return !exists(params[p]);
+ })) {
+ var missingParameters = this.urlParams.filter(function (p) {
+ return !exists(params[p]);
+ });
+ throw new Error("Cannot build path: '" + this.path + "' requires missing parameters { " + missingParameters.join(', ') + ' }');
+ } // Check constraints
+
+
+ if (!options.ignoreConstraints) {
+ var constraintsPassed = this.tokens.filter(function (t) {
+ return /^url-parameter/.test(t.type) && !/-splat$/.test(t.type);
+ }).every(function (t) {
+ return new RegExp('^' + defaultOrConstrained(t.otherVal[0]) + '$').test(encodedUrlParams[t.val]);
+ });
+
+ if (!constraintsPassed) {
+ throw new Error("Some parameters of '" + this.path + "' are of invalid format");
+ }
+ }
+
+ var base = this.tokens.filter(function (t) {
+ return /^query-parameter/.test(t.type) === false;
+ }).map(function (t) {
+ if (t.type === 'url-parameter-matrix') {
+ return ";" + t.val + "=" + encodedUrlParams[t.val[0]];
+ }
+
+ return /^url-parameter/.test(t.type) ? encodedUrlParams[t.val[0]] : t.match;
+ }).join('');
+
+ if (options.ignoreSearch) {
+ return base;
+ }
+
+ var searchParams = this.queryParams.filter(function (p) {
+ return Object.keys(params).indexOf(p) !== -1;
+ }).reduce(function (sparams, paramName) {
+ sparams[paramName] = params[paramName];
+ return sparams;
+ }, {});
+ var searchPart = search_params_esm_build(searchParams, options.queryParams);
+ return searchPart ? base + '?' + searchPart : base;
+ };
+
+ Path.prototype.getParams = function (type) {
+ var predicate = type instanceof RegExp ? function (t) {
+ return type.test(t.type);
+ } : function (t) {
+ return t.type === type;
+ };
+ return this.tokens.filter(predicate).map(function (t) {
+ return t.val[0];
+ });
+ };
+
+ Path.prototype.urlTest = function (path, source, caseSensitive, urlParamsEncoding) {
+ var _this = this;
+
+ var regex = new RegExp('^' + source, caseSensitive ? '' : 'i');
+ var match = path.match(regex);
+
+ if (!match) {
+ return null;
+ } else if (!this.urlParams.length) {
+ return {};
+ } // Reduce named params to key-value pairs
+
+
+ return match.slice(1, this.urlParams.length + 1).reduce(function (params, m, i) {
+ params[_this.urlParams[i]] = decodeParam(m, urlParamsEncoding);
+ return params;
+ }, {});
+ };
+
+ return Path;
+}();
+
+
+//# sourceMappingURL=path-parser.esm.js.map
+
+;// CONCATENATED MODULE: ./src/api.js
+
+
+
+// ===========================================================================
+class APIRouter {
+ constructor(paths) {
+ this.routes = {};
+
+ for (const [name, value] of Object.entries(paths)) {
+ let route, method;
+
+ if (value instanceof Array) {
+ route = value[0];
+ method = value[1] || "GET";
+ } else {
+ route = value;
+ method = "GET";
+ }
+
+ this.routes[method] = this.routes[method] || {};
+ this.routes[method][name] = new Path(route);
+ }
+ }
+
+ match(url, method = "GET") {
+ for (const [name, route] of Object.entries(this.routes[method] || [])) {
+ const parts = url.split("?", 2);
+ const matchUrl = parts[0];
+
+ const res = route.test(matchUrl);
+ if (res) {
+ res._route = name;
+ res._query = new URLSearchParams(parts.length === 2 ? parts[1] : "");
+ return res;
+ }
+ }
+
+ return {_route: null};
+ }
+}
+
+
+// ===========================================================================
+class api_API {
+ constructor(collections) {
+ this.router = new APIRouter(this.routes);
+
+ this.collections = collections;
+ }
+
+ 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(url, request, event) {
+ const params = this.router.match(url, request.method);
+ const response = await this.handleApi(request, params, event);
+ if (response instanceof Response) {
+ return response;
+ }
+ const status = response.error ? 404 : 200;
+ return this.makeResponse(response, status);
+ }
+
+ async handleApi(request, params/*, event*/) {
+ switch (params._route) {
+ case "index":
+ return await this.listAll(params._query.get("filter"));
+
+ case "createColl": {
+ const requestJSON = await request.json();
+ const coll = await this.collections.initNewColl(requestJSON.metadata || {}, requestJSON.extraConfig || {});
+ return getCollData(coll);
+ }
+
+ case "coll": {
+ const coll = await this.collections.getColl(params.coll);
+ if (!coll) {
+ return {error: "collection_not_found"};
+ }
+ const data = getCollData(coll);
+
+ if (params._query.get("all") === "1") {
+ if (coll.store.db) {
+ data.pages = await coll.store.getAllPages();
+ data.lists = await coll.store.db.getAll("pageLists");
+ data.curatedPages = await coll.store.db.getAll("curatedPages");
+ } else {
+ data.pages = [];
+ data.lists = [];
+ data.curatedPages = [];
+ }
+
+ data.verify = await coll.store.getVerifyInfo();
+
+ } else {
+ data.numLists = await coll.store.db.count("pageLists");
+ data.numPages = await coll.store.db.count("pages");
+ }
+
+ if (coll.config.metadata.ipfsPins) {
+ data.ipfsPins = coll.config.metadata.ipfsPins;
+ }
+
+ return data;
+ }
+
+ case "deleteColl": {
+ const keepFileHandle = params._query.get("reload") === "1";
+
+ if (!await this.collections.deleteColl(params.coll, keepFileHandle)) {
+ return {error: "collection_not_found"};
+ }
+ return await this.listAll();
+ }
+
+ case "updateAuth": {
+ const requestJSON = await request.json();
+ return {"success": await this.collections.updateAuth(params.coll, requestJSON.headers)};
+ }
+
+ case "updateMetadata": {
+ const requestJSON = await request.json();
+ const metadata = await this.collections.updateMetadata(params.coll, requestJSON);
+ return {metadata};
+ }
+
+ case "urls": {
+ const coll = await this.collections.getColl(params.coll);
+ if (!coll) {
+ return {error: "collection_not_found"};
+ }
+ const url = params._query.get("url");
+ const count = Number(params._query.get("count") || 100);
+ const mime = params._query.get("mime");
+ const prefix = (params._query.get("prefix") === "1");
+
+ const fromUrl = params._query.get("fromUrl");
+ const fromTs = params._query.get("fromTs");
+ const fromMime = params._query.get("fromMime");
+ const fromStatus = Number(params._query.get("fromStatus") || 0);
+
+ if (!coll.store.resourcesByMime) {
+ return {urls: []};
+ }
+
+ let urls;
+
+ if (url) {
+ urls = await coll.store.resourcesByUrlAndMime(url, mime, count, prefix, fromUrl, fromTs);
+ } else {
+ urls = await coll.store.resourcesByMime(mime, count, fromMime, fromUrl, fromStatus);
+ }
+
+ urls = urls || [];
+
+ return {urls};
+ }
+
+ case "pages": {
+ const coll = await this.collections.getColl(params.coll);
+ if (!coll) {
+ return {error: "collection_not_found"};
+ }
+ const pages = await coll.store.getAllPages();
+ return {pages};
+ }
+
+ case "textIndex": {
+ const coll = await this.collections.getColl(params.coll);
+ if (!coll) {
+ return {error: "collection_not_found"};
+ }
+ if (coll.store.getTextIndex) {
+ return await coll.store.getTextIndex();
+ } else {
+ return {};
+ }
+ }
+
+ case "curated": {
+ const coll = await this.collections.getColl(params.coll);
+ if (!coll) {
+ return {error: "collection_not_found"};
+ }
+ const list = Number(params.list);
+ const curated = await coll.store.db.getAllFromIndex("curatedPages", "listPages",
+ IDBKeyRange.bound([list], [list + 1]));
+ return {curated};
+ }
+
+ case "deletePage": {
+ const coll = await this.collections.getColl(params.coll);
+ if (!coll) {
+ return {error: "collection_not_found"};
+ }
+ const {pageSize, deleteSize} = coll.store.deletePage(params.page);
+
+ this.collections.updateSize(params.coll, pageSize, deleteSize);
+
+ return {pageSize, deleteSize};
+ }
+
+ default:
+ return {"error": "not_found"};
+ }
+ }
+
+ async listAll(filter) {
+ const response = await this.collections.listAll();
+ const collections = [];
+
+ response.forEach((coll) => {
+ if (coll.type === "live" || coll.type === "remoteproxy") {
+ return;
+ }
+
+ if (filter && coll.type.indexOf(filter) !== 0) {
+ return;
+ }
+
+ collections.push(getCollData(coll));
+ });
+
+ return {"colls": collections};
+ }
+
+ makeResponse(response, status = 200) {
+ return new Response(JSON.stringify(response), {status, headers: {"Content-Type": "application/json"}});
+ }
+}
+
+
+
+;// CONCATENATED MODULE: ./dist/wombat.js
+/* harmony default export */ const wombat = ("/*! wombat.js is part of Webrecorder project. Copyright (C) 2020-2023, Webrecorder Software. Licensed under the Affero General Public License v3. */\n/*\n * ATTENTION: The \"eval\" devtool has been used (maybe by default in mode: \"development\").\n * This devtool is neither made for production nor for readable output files.\n * It uses \"eval()\" calls to create a separate source file in the browser devtools.\n * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)\n * or disable the default devtool with \"devtool: false\".\n * If you are looking for production-ready output files, see mode: \"production\" (https://webpack.js.org/configuration/mode/).\n */\n/******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\n/******/ \tvar __webpack_modules__ = ({\n\n/***/ \"./vendor/wombat.js\":\n/*!**************************!*\\\n !*** ./vendor/wombat.js ***!\n \\**************************/\n/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {\n\neval(\"__webpack_require__.r(__webpack_exports__);\\n(function () {\\n \\n\\n /**\\n * A class that manages event listeners for the override applied to\\n * EventTarget.[addEventListener, removeEventListener]\\n */\\n function FuncMap() {\\n /**\\n * @type {Array}\\n * @private\\n */\\n this._map = [];\\n }\\n\\n /**\\n * Adds a mapping of original listener -> wrapped original listener\\n * @param {Function} fnKey - The original listener function\\n * @param {Function} fnValue - The wrapped original listener function\\n */\\n FuncMap.prototype.set = function(fnKey, fnValue) {\\n this._map.push([fnKey, fnValue]);\\n };\\n\\n /**\\n * Returns the wrapped original listener that is mapped to the supplied function\\n * if it exists in the FuncMap's mapping\\n * @param {Function} fnKey - The original listener function\\n * @return {?Function}\\n */\\n FuncMap.prototype.get = function(fnKey) {\\n for (var i = 0; i < this._map.length; i++) {\\n if (this._map[i][0] === fnKey) {\\n return this._map[i][1];\\n }\\n }\\n return null;\\n };\\n\\n /**\\n * Returns the index of the wrapper for the supplied original function\\n * if it exists in the FuncMap's mapping\\n * @param {Function} fnKey - The original listener function\\n * @return {number}\\n */\\n FuncMap.prototype.find = function(fnKey) {\\n for (var i = 0; i < this._map.length; i++) {\\n if (this._map[i][0] === fnKey) {\\n return i;\\n }\\n }\\n return -1;\\n };\\n\\n /**\\n * Returns the wrapped original listener function for the supplied original\\n * listener function. If the wrapped original listener does not exist in\\n * FuncMap's mapping it is added.\\n * @param {Function} func - The original listener function\\n * @param {Function} initter - The a function that returns a wrapped version\\n * of the original listener function\\n * @return {?Function}\\n */\\n FuncMap.prototype.add_or_get = function(func, initter) {\\n var fnValue = this.get(func);\\n if (!fnValue) {\\n fnValue = initter();\\n this.set(func, fnValue);\\n }\\n return fnValue;\\n };\\n\\n /**\\n * Removes the mapping of the original listener function to its wrapped counter part\\n * @param {Function} func - The original listener function\\n * @return {?Function}\\n */\\n FuncMap.prototype.remove = function(func) {\\n var idx = this.find(func);\\n if (idx >= 0) {\\n var fnMapping = this._map.splice(idx, 1);\\n return fnMapping[0][1];\\n }\\n return null;\\n };\\n\\n /**\\n * Calls all wrapped listener functions contained in the FuncMap's mapping\\n * with the supplied param\\n * @param {*} param\\n */\\n FuncMap.prototype.map = function(param) {\\n for (var i = 0; i < this._map.length; i++) {\\n this._map[i][1](param);\\n }\\n };\\n\\n /**\\n * Ensures the supplied argument is a number or if it is not (can not be coerced to a number)\\n * this function returns null.\\n * @param {*} maybeNumber\\n * @return {?number}\\n */\\n function ensureNumber(maybeNumber) {\\n try {\\n switch (typeof maybeNumber) {\\n case 'number':\\n case 'bigint':\\n return maybeNumber;\\n }\\n var converted = Number(maybeNumber);\\n return !isNaN(converted) ? converted : null;\\n } catch (e) {}\\n return null;\\n }\\n\\n /**\\n * Sets the supplied object's toStringTag IFF\\n * self.Symbol && self.Symbol.toStringTag are defined\\n * @param {Object} clazz\\n * @param {string} tag\\n */\\n function addToStringTagToClass(clazz, tag) {\\n if (\\n typeof self.Symbol !== 'undefined' &&\\n typeof self.Symbol.toStringTag !== 'undefined'\\n ) {\\n Object.defineProperty(clazz.prototype, self.Symbol.toStringTag, {\\n value: tag,\\n enumerable: false\\n });\\n }\\n }\\n\\n /**\\n * Binds every function this, except the constructor, of the supplied object\\n * to the instance of the supplied object\\n * @param {Object} clazz\\n */\\n function autobind(clazz) {\\n var proto = clazz.__proto__ || clazz.constructor.prototype || clazz.prototype;\\n var clazzProps = Object.getOwnPropertyNames(proto);\\n var len = clazzProps.length;\\n var prop;\\n var propValue;\\n for (var i = 0; i < len; i++) {\\n prop = clazzProps[i];\\n propValue = clazz[prop];\\n if (prop !== 'constructor' && typeof propValue === 'function') {\\n clazz[prop] = propValue.bind(clazz);\\n }\\n }\\n }\\n\\n /**\\n * Because we overriding specific interfaces (e.g. Storage) that do not expose\\n * an constructor only an interface object with our own we must have a way\\n * to indicate to our overrides when it is proper to throw exceptions\\n * @type {{yes: boolean}}\\n */\\n var ThrowExceptions = { yes: false };\\n\\n var WOMBAT = Symbol('__wb__storage_WOMBAT');\\n var TYPE = Symbol('__wb__storage_TYPE');\\n\\n /**\\n * A re-implementation of the Storage interface.\\n * This re-implementation is required for replay in order to ensure\\n * that web pages that require local or session storage work as expected as\\n * there is sometimes a limit on the amount of storage space that can be used.\\n * This re-implementation ensures that limit is unlimited as it would be in\\n * the live-web.\\n * @param {Wombat} wombat\\n * @param {string} type\\n * @param {object} initData\\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Storage\\n * @see https://html.spec.whatwg.org/multipage/webstorage.html#the-storage-interface\\n */\\n function Storage(wombat, type, initData) {\\n if (ThrowExceptions.yes) {\\n // there is no constructor exposed for this interface however there is an\\n // interface object exposed, thus we must throw an TypeError if userland\\n // attempts to create us\\n throw new TypeError('Illegal constructor');\\n }\\n\\n if (initData && initData.length) {\\n for (var i = 0; i < initData.length; i++) {\\n this[initData[i][0]] = initData[i][1].toString();\\n }\\n }\\n\\n Object.defineProperty(this, WOMBAT, {\\n value: wombat,\\n enumerable: false\\n });\\n\\n Object.defineProperty(this, TYPE, {\\n value: type,\\n enumerable: false\\n });\\n }\\n\\n function storageProxyHandler() {\\n return {\\n get: function(target, prop) {\\n var proto = target.__proto__;\\n\\n if (prop === '__proto__') {\\n return proto;\\n }\\n\\n if (proto.hasOwnProperty(prop) || (proto.__proto__ && proto.__proto__.hasOwnProperty(prop))) {\\n var res = target[prop];\\n\\n if (typeof(res) === 'function') {\\n res = res.bind(target);\\n }\\n\\n return res;\\n }\\n\\n return target.hasOwnProperty(prop) ? target.getItem(prop) : undefined;\\n },\\n\\n set: function(target, prop, value) {\\n if (target.__proto__.hasOwnProperty(prop)) {\\n target[prop] = value;\\n return true;\\n }\\n\\n target.setItem(prop, value);\\n return true;\\n }\\n };\\n }\\n function createStorage(wombat, type, initData) {\\n var storage = new Storage(wombat, type, initData);\\n\\n if (wombat.$wbwindow.Proxy) {\\n storage = new wombat.$wbwindow.Proxy(storage, storageProxyHandler());\\n }\\n\\n wombat.defGetterProp(wombat.$wbwindow, type, function() {\\n return storage;\\n });\\n\\n return storage;\\n }\\n\\n /**\\n * When passed a key name, will return that key's value\\n * @param {string} name\\n * @return {*}\\n */\\n Storage.prototype.getItem = function getItem(name) {\\n return this.hasOwnProperty(name) ? this[name] : null;\\n };\\n\\n /**\\n * When passed a key name and value, will add that key to the storage,\\n * or update that key's value if it already exists\\n * @param {string} name\\n * @param {*} value\\n * @return {*}\\n */\\n Storage.prototype.setItem = function setItem(name, value) {\\n var sname = String(name);\\n var svalue = String(value);\\n var old = this.getItem(sname);\\n this[sname] = value;\\n this.fireEvent(sname, old, svalue);\\n return undefined;\\n };\\n\\n Storage.prototype._deleteItem = function(item) {\\n delete this[item];\\n };\\n\\n /**\\n * When passed a key name, will remove that key from the storage\\n * @param {string} name\\n * @return {undefined}\\n */\\n Storage.prototype.removeItem = function removeItem(name) {\\n var old = this.getItem(name);\\n this._deleteItem(name);\\n this.fireEvent(name, old, null);\\n return undefined;\\n };\\n\\n\\n /**\\n * When invoked, will empty all keys out of the storage\\n * @return {undefined}\\n */\\n Storage.prototype.clear = function clear() {\\n for (var member in this) {\\n delete this[member];\\n }\\n\\n this.fireEvent(null, null, null);\\n return undefined;\\n };\\n\\n /**\\n * When passed a number n, this method will return the name of the nth key in the storage\\n * @param {number} index\\n * @return {*}\\n */\\n Storage.prototype.key = function key(index) {\\n var n = ensureNumber(index);\\n if (n == null || n < 0) return null;\\n var keys = Object.keys(this);\\n if (n < keys.length) return keys[n];\\n return null;\\n };\\n\\n /**\\n * Because we are re-implementing the storage interface we must fire StorageEvent\\n * ourselves, this function does just that.\\n * @param {?string} key\\n * @param {*} oldValue\\n * @param {*} newValue\\n * @see https://html.spec.whatwg.org/multipage/webstorage.html#send-a-storage-notification\\n */\\n Storage.prototype.fireEvent = function fireEvent(key, oldValue, newValue) {\\n var sevent = new StorageEvent('storage', {\\n key: key,\\n newValue: newValue,\\n oldValue: oldValue,\\n url: this[WOMBAT].$wbwindow.WB_wombat_location.href\\n });\\n // storage is a read only property of StorageEvent\\n // that must be on the fired instance of the event\\n Object.defineProperty(sevent, 'storageArea', {\\n value: this,\\n writable: false,\\n configurable: false\\n });\\n sevent._storageArea = this;\\n this[WOMBAT].storage_listeners.map(sevent);\\n };\\n\\n /**\\n * An override of the valueOf function that returns wombat's Proxy for the\\n * specific storage this class is for, either local or session storage.\\n * @return {Proxy}\\n */\\n Storage.prototype.valueOf = function valueOf() {\\n return this[WOMBAT].$wbwindow[this[TYPE]];\\n };\\n\\n\\n /**\\n * An override of toString to return '[object Storage]'\\n **/\\n Storage.prototype.toString = function() {\\n return '[object Storage]';\\n };\\n\\n\\n\\n // the length getter is on the prototype (__proto__ modern browsers)\\n Object.defineProperty(Storage.prototype, 'length', {\\n enumerable: false,\\n get: function length() {\\n return Object.keys(this).length;\\n }\\n });\\n\\n addToStringTagToClass(Storage, 'Storage');\\n\\n /* eslint-disable camelcase */\\n\\n /**\\n * A re-implementation of the Location interface that ensure that operations\\n * on the location interface behaves as expected during replay.\\n * @param {Location} orig_loc\\n * @param {Wombat} wombat\\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Location\\n * @see https://html.spec.whatwg.org/multipage/browsers.html#the-location-interface\\n */\\n function WombatLocation(orig_loc, wombat) {\\n // hide our values from enumeration, spreed, et al\\n Object.defineProperties(this, {\\n _orig_loc: {\\n configurable: true,\\n enumerable: false,\\n value: orig_loc\\n },\\n wombat: {\\n configurable: true,\\n enumerable: false,\\n value: wombat\\n },\\n orig_getter: {\\n enumerable: false,\\n value: function(prop) {\\n return this._orig_loc[prop];\\n }\\n },\\n orig_setter: {\\n enumerable: false,\\n value: function(prop, value) {\\n this._orig_loc[prop] = value;\\n }\\n }\\n });\\n\\n wombat.initLocOverride(this, this.orig_setter, this.orig_getter);\\n\\n wombat.setLoc(this, orig_loc.href);\\n\\n for (var prop in orig_loc) {\\n if (!this.hasOwnProperty(prop) && typeof orig_loc[prop] !== 'function') {\\n this[prop] = orig_loc[prop];\\n }\\n }\\n }\\n\\n /**\\n * Replaces the current resource with the one at the provided URL.\\n * The difference from the assign() method is that after using replace() the\\n * current page will not be saved in session History, meaning the user won't\\n * be able to use the back button to navigate to it.\\n * @param {string} url\\n * @return {*}\\n */\\n WombatLocation.prototype.replace = function replace(url) {\\n var new_url = this.wombat.rewriteUrl(url);\\n var orig = this.wombat.extractOriginalURL(new_url);\\n if (orig === this.href) {\\n return orig;\\n }\\n return this._orig_loc.replace(new_url);\\n };\\n\\n /**\\n * Loads the resource at the URL provided in parameter\\n * @param {string} url\\n * @return {*}\\n */\\n WombatLocation.prototype.assign = function assign(url) {\\n var new_url = this.wombat.rewriteUrl(url);\\n var orig = this.wombat.extractOriginalURL(new_url);\\n if (orig === this.href) {\\n return orig;\\n }\\n return this._orig_loc.assign(new_url);\\n };\\n\\n /**\\n * Reloads the resource from the current URL. Its optional unique parameter\\n * is a Boolean, which, when it is true, causes the page to always be reloaded\\n * from the server. If it is false or not specified, the browser may reload\\n * the page from its cache.\\n * @param {boolean} [forcedReload = false]\\n * @return {*}\\n */\\n WombatLocation.prototype.reload = function reload(forcedReload) {\\n //return this._orig_loc.reload(forcedReload || false);\\n return;\\n };\\n\\n /**\\n * @return {string}\\n */\\n WombatLocation.prototype.toString = function toString() {\\n return this.href;\\n };\\n\\n /**\\n * @return {WombatLocation}\\n */\\n WombatLocation.prototype.valueOf = function valueOf() {\\n return this;\\n };\\n\\n addToStringTagToClass(WombatLocation, 'Location');\\n\\n /* eslint-disable camelcase */\\n\\n /**\\n * Create a new instance of AutoFetcher\\n * @param {Wombat} wombat\\n * @param {{isTop: boolean, workerURL: string}} config\\n */\\n function AutoFetcher(wombat, config) {\\n if (!(this instanceof AutoFetcher)) {\\n return new AutoFetcher(wombat, config);\\n }\\n // specifically target the elements we desire\\n this.elemSelector =\\n 'img[srcset], img[data-srcset], img[data-src], video[srcset], video[data-srcset], video[data-src], audio[srcset], audio[data-srcset], audio[data-src], ' +\\n 'picture > source[srcset], picture > source[data-srcset], picture > source[data-src], ' +\\n 'video > source[srcset], video > source[data-srcset], video > source[data-src], ' +\\n 'audio > source[srcset], audio > source[data-srcset], audio > source[data-src]';\\n\\n /** @type {Wombat} */\\n this.wombat = wombat;\\n /** @type {Window} */\\n this.$wbwindow = wombat.$wbwindow;\\n\\n /** @type {?Worker|Object} */\\n this.worker = null;\\n autobind(this);\\n this._initWorker(config);\\n }\\n\\n /**\\n * Initializes the backing worker IFF the execution context we are in is\\n * the replay tops otherwise creates a dummy worker that simply bounces the\\n * message that would have been sent to the backing worker to replay top.\\n *\\n * If creation of the worker fails, likely due to the execution context we\\n * are currently in having an null origin, we fallback to dummy worker creation.\\n * @param {{isTop: boolean, workerURL: string}} config\\n * @private\\n */\\n AutoFetcher.prototype._initWorker = function(config) {\\n var wombat = this.wombat;\\n if (config.isTop) {\\n // we are top and can will own this worker\\n // setup URL for the kewl case\\n // Normal replay and preservation mode pworker setup, its all one origin so YAY!\\n try {\\n this.worker = new Worker(config.workerURL, {\\n type: 'classic',\\n credentials: 'include'\\n });\\n } catch (e) {\\n // it is likely we are in some kind of horrid iframe setup\\n // and the execution context we are currently in has a null origin\\n console.error('Failed to create auto fetch worker\\\\n', e);\\n }\\n return;\\n }\\n\\n // add only the portions of the worker interface we use since we are not top\\n // and if in proxy mode start check polling\\n this.worker = {\\n postMessage: function(msg) {\\n if (!msg.wb_type) {\\n msg = { wb_type: 'aaworker', msg: msg };\\n }\\n wombat.$wbwindow.__WB_replay_top.__orig_postMessage(msg, '*');\\n },\\n terminate: function() {}\\n };\\n };\\n\\n /**\\n * Extracts the media rules from the supplied CSSStyleSheet object if any\\n * are present and returns an array of the media cssText\\n * @param {CSSStyleSheet} sheet\\n * @return {Array}\\n */\\n AutoFetcher.prototype.extractMediaRulesFromSheet = function(sheet) {\\n var rules;\\n var media = [];\\n try {\\n rules = sheet.cssRules || sheet.rules;\\n } catch (e) {\\n return media;\\n }\\n\\n // loop through each rule of the stylesheet\\n for (var i = 0; i < rules.length; ++i) {\\n var rule = rules[i];\\n if (rule.type === CSSRule.MEDIA_RULE) {\\n // we are a media rule so get its text\\n media.push(rule.cssText);\\n }\\n }\\n return media;\\n };\\n\\n /**\\n * Extracts the media rules from the supplied CSSStyleSheet object if any\\n * are present after a tick of the event loop sending the results of the\\n * extraction to the backing worker\\n * @param {CSSStyleSheet|StyleSheet} sheet\\n */\\n AutoFetcher.prototype.deferredSheetExtraction = function(sheet) {\\n var afw = this;\\n // defer things until next time the Promise.resolve Qs are cleared\\n Promise.resolve().then(function() {\\n // loop through each rule of the stylesheet\\n var media = afw.extractMediaRulesFromSheet(sheet);\\n if (media.length > 0) {\\n // we have some media rules to preserve\\n afw.preserveMedia(media);\\n }\\n });\\n };\\n\\n /**\\n * Terminates the backing worker. This is a no op when we are not\\n * operating in the execution context of replay top\\n */\\n AutoFetcher.prototype.terminate = function() {\\n // terminate the worker, a no op when not replay top\\n this.worker.terminate();\\n };\\n\\n /**\\n * Sends the supplied array of URLs to the backing worker\\n * @param {Array} urls\\n */\\n AutoFetcher.prototype.justFetch = function(urls) {\\n this.worker.postMessage({ type: 'fetch-all', values: urls });\\n };\\n\\n /**\\n * Sends the supplied url with extra options to indicate\\n * that this is a page to backing worker\\n * @param {string} url\\n * @param {string} originalUrl\\n * @param {string} [title]\\n */\\n AutoFetcher.prototype.fetchAsPage = function(url, originalUrl, title) {\\n if (!url) {\\n return;\\n }\\n\\n var headers = { 'X-Wombat-History-Page': originalUrl };\\n if (title) {\\n var encodedTitle = encodeURIComponent(title.trim());\\n if (title) {\\n headers['X-Wombat-History-Title'] = encodedTitle;\\n }\\n }\\n\\n var fetchData = {\\n url: url,\\n options: { headers: headers, cache: 'no-store' }\\n };\\n\\n this.justFetch([fetchData]);\\n };\\n\\n /**\\n * Sends a message to backing worker. If deferred is true\\n * the message is sent after one tick of the event loop\\n * @param {Object} msg\\n * @param {boolean} [deferred]\\n */\\n AutoFetcher.prototype.postMessage = function(msg, deferred) {\\n if (deferred) {\\n var afWorker = this;\\n Promise.resolve().then(function() {\\n afWorker.worker.postMessage(msg);\\n });\\n return;\\n }\\n this.worker.postMessage(msg);\\n };\\n\\n /**\\n * Sends the supplied srcset value to the backing worker for preservation\\n * @param {string|Array} srcset\\n * @param {string} [mod]\\n */\\n AutoFetcher.prototype.preserveSrcset = function(srcset, mod) {\\n // send values from rewriteSrcset to the worker\\n this.postMessage(\\n {\\n type: 'values',\\n srcset: { value: srcset, mod: mod, presplit: true }\\n },\\n true\\n );\\n };\\n\\n /**\\n * Send the value of the supplied elements data-srcset attribute to the\\n * backing worker for preservation\\n * @param {Node} elem\\n */\\n AutoFetcher.prototype.preserveDataSrcset = function(elem) {\\n // send values from rewriteAttr srcset to the worker deferred\\n // to ensure the page viewer sees the images first\\n this.postMessage(\\n {\\n type: 'values',\\n srcset: {\\n value: elem.dataset.srcset,\\n mod: this.rwMod(elem),\\n presplit: false\\n }\\n },\\n true\\n );\\n };\\n\\n /**\\n * Sends the supplied array of cssText from media rules to the backing worker\\n * @param {Array} media\\n */\\n AutoFetcher.prototype.preserveMedia = function(media) {\\n // send CSSMediaRule values to the worker\\n this.postMessage({ type: 'values', media: media }, true);\\n };\\n\\n /**\\n * Extracts the value of the srcset property if it exists from the supplied\\n * element\\n * @param {Element} elem\\n * @return {?string}\\n */\\n AutoFetcher.prototype.getSrcset = function(elem) {\\n if (this.wombat.wb_getAttribute) {\\n return this.wombat.wb_getAttribute.call(elem, 'srcset');\\n }\\n return elem.getAttribute('srcset');\\n };\\n\\n /**\\n * Returns the correct rewrite modifier for the supplied element\\n * @param {Element} elem\\n * @return {string}\\n */\\n AutoFetcher.prototype.rwMod = function(elem) {\\n switch (elem.tagName) {\\n case 'SOURCE':\\n if (elem.parentElement && elem.parentElement.tagName === 'PICTURE') {\\n return 'im_';\\n }\\n return 'oe_';\\n case 'IMG':\\n return 'im_';\\n }\\n return 'oe_';\\n };\\n\\n /**\\n * Extracts the media rules from stylesheets and the (data-)srcset URLs from\\n * image elements the current context's document contains\\n */\\n AutoFetcher.prototype.extractFromLocalDoc = function() {\\n // get the values to be preserved from the documents stylesheets\\n // and all img, video, audio elements with (data-)?srcset or data-src\\n var afw = this;\\n Promise.resolve().then(function() {\\n var msg = {\\n type: 'values',\\n context: { docBaseURI: document.baseURI }\\n };\\n var media = [];\\n var i = 0;\\n var sheets = document.styleSheets;\\n for (; i < sheets.length; ++i) {\\n media = media.concat(afw.extractMediaRulesFromSheet(sheets[i]));\\n }\\n var elems = document.querySelectorAll(afw.elemSelector);\\n var srcset = { values: [], presplit: false };\\n var src = { values: [] };\\n var elem, srcv, mod;\\n for (i = 0; i < elems.length; ++i) {\\n elem = elems[i];\\n // we want the original src value in order to resolve URLs in the worker when needed\\n srcv = elem.src ? elem.src : null;\\n // a from value of 1 indicates images and a 2 indicates audio/video\\n mod = afw.rwMod(elem);\\n if (elem.srcset) {\\n srcset.values.push({\\n srcset: afw.getSrcset(elem),\\n mod: mod,\\n tagSrc: srcv\\n });\\n }\\n if (elem.dataset.srcset) {\\n srcset.values.push({\\n srcset: elem.dataset.srcset,\\n mod: mod,\\n tagSrc: srcv\\n });\\n }\\n if (elem.dataset.src) {\\n src.values.push({ src: elem.dataset.src, mod: mod });\\n }\\n if (elem.tagName === 'SOURCE' && srcv) {\\n src.values.push({ src: srcv, mod: mod });\\n }\\n }\\n if (media.length) {\\n msg.media = media;\\n }\\n if (srcset.values.length) {\\n msg.srcset = srcset;\\n }\\n if (src.values.length) {\\n msg.src = src;\\n }\\n if (msg.media || msg.srcset || msg.src) {\\n afw.postMessage(msg);\\n }\\n });\\n };\\n\\n /* eslint-disable camelcase */\\n\\n /**\\n *\\n * @param {Function} origListener\\n * @param {Window} win\\n * @return {Function}\\n */\\n function wrapSameOriginEventListener(origListener, win) {\\n return function wrappedSameOriginEventListener(event) {\\n if (window != win) {\\n return;\\n }\\n return origListener(event);\\n };\\n }\\n\\n /**\\n * @param {Function} origListener\\n * @param {Object} obj\\n * @param {Wombat} wombat\\n * @return {Function}\\n */\\n function wrapEventListener(origListener, obj, wombat) {\\n var origListenerFunc;\\n\\n // if a function, just use that\\n if (typeof(origListener) === 'function') {\\n origListenerFunc = origListener;\\n // if an EventHandler object, use its handleEvent() bound method\\n } else if (typeof(origListener) === 'object') {\\n origListenerFunc = origListener.handleEvent.bind(origListener);\\n // else do nothing!\\n } else {\\n origListenerFunc = function() {};\\n }\\n\\n return function wrappedEventListener(event) {\\n var ne;\\n\\n if (event.data && event.data.from && event.data.message) {\\n if (\\n event.data.to_origin !== '*' &&\\n obj.WB_wombat_location &&\\n !wombat.startsWith(event.data.to_origin, obj.WB_wombat_location.origin)\\n ) {\\n console.warn(\\n 'Skipping message event to ' +\\n event.data.to_origin +\\n ' doesn\\\\'t start with origin ' +\\n obj.WB_wombat_location.origin\\n );\\n return;\\n }\\n\\n var source = event.source;\\n\\n if (event.data.from_top) {\\n source = obj.__WB_top_frame;\\n } else if (\\n event.data.src_id &&\\n obj.__WB_win_id &&\\n obj.__WB_win_id[event.data.src_id]\\n ) {\\n source = obj.__WB_win_id[event.data.src_id];\\n }\\n\\n ne = new MessageEvent('message', {\\n bubbles: event.bubbles,\\n cancelable: event.cancelable,\\n data: event.data.message,\\n origin: event.data.from,\\n lastEventId: event.lastEventId,\\n source: wombat.proxyToObj(source),\\n ports: event.ports\\n });\\n\\n ne._target = event.target;\\n ne._srcElement = event.srcElement;\\n ne._currentTarget = event.currentTarget;\\n ne._eventPhase = event.eventPhase;\\n } else {\\n ne = event;\\n }\\n\\n return origListenerFunc(ne);\\n };\\n }\\n\\n function u(t){let e;typeof t==\\\"string\\\"?e=t:t&&t.length?e=t.reduce((r,n)=>(r+=String.fromCharCode(n),r),\\\"\\\"):t?e=t.toString():e=\\\"\\\";try{return \\\"__wb_post_data=\\\"+btoa(e)}catch{return \\\"__wb_post_data=\\\"}}function w(t){let{method:e,headers:r,postData:n}=t;if(e===\\\"GET\\\")return !1;let i=(r.get(\\\"content-type\\\")||\\\"\\\").split(\\\";\\\")[0];function o(a){return a instanceof Uint8Array&&(a=new TextDecoder().decode(a)),a}let s=\\\"\\\";switch(i){case\\\"application/x-www-form-urlencoded\\\":s=o(n);break;case\\\"application/json\\\":s=c(o(n));break;case\\\"text/plain\\\":try{s=c(o(n),!1);}catch{s=u(n);}break;case\\\"multipart/form-data\\\":{let a=r.get(\\\"content-type\\\");if(!a)throw new Error(\\\"utils cannot call postToGetURL when missing content-type header\\\");s=g(o(n),a);break}default:s=u(n);}return s!==null?(t.url=f(t.url,s,t.method),t.method=\\\"GET\\\",t.requestBody=s,!0):!1}function f(t,e,r){if(!r)return t;let n=t.indexOf(\\\"?\\\")>0?\\\"&\\\":\\\"?\\\";return `${t}${n}__wb_method=${r}&${e}`}function p(t,e=!0){if(typeof t==\\\"string\\\")try{t=JSON.parse(t);}catch{t={};}let r=new URLSearchParams,n={},i=o=>r.has(o)?(o in n||(n[o]=1),o+\\\".\\\"+ ++n[o]+\\\"_\\\"):o;try{JSON.stringify(t,(o,s)=>([\\\"object\\\",\\\"function\\\"].includes(typeof s)||r.set(i(o),s),s));}catch(o){if(!e)throw o}return r}function y(t,e){let r=new URLSearchParams;t instanceof Uint8Array&&(t=new TextDecoder().decode(t));try{let n=e.split(\\\"boundary=\\\")[1],i=t.split(new RegExp(\\\"-*\\\"+n+\\\"-*\\\",\\\"mi\\\"));for(let o of i){let s=o.trim().match(/name=\\\"([^\\\"]+)\\\"\\\\r\\\\n\\\\r\\\\n(.*)/im);s&&r.set(s[1],s[2]);}}catch{}return r}function c(t,e=!0){return p(t,e).toString()}function g(t,e){return y(t,e).toString()}\\n\\n /* eslint-disable camelcase */\\n\\n\\n /**\\n * @param {Window} $wbwindow\\n * @param {Object} wbinfo\\n */\\n function Wombat($wbwindow, wbinfo) {\\n if (!(this instanceof Wombat)) return new Wombat($wbwindow, wbinfo);\\n\\n /** @type {boolean} */\\n this.debug_rw = false;\\n\\n /** @type {Window} */\\n this.$wbwindow = $wbwindow;\\n this.WBWindow = Window;\\n\\n this.origHost = $wbwindow.location.host;\\n this.origHostname = $wbwindow.location.hostname;\\n this.origProtocol = $wbwindow.location.protocol;\\n\\n /** @type {string} */\\n this.HTTP_PREFIX = 'http://';\\n\\n /** @type {string} */\\n this.HTTPS_PREFIX = 'https://';\\n\\n /** @type {string} */\\n this.REL_PREFIX = '//';\\n\\n /** @type {Array} */\\n this.VALID_PREFIXES = [this.HTTP_PREFIX, this.HTTPS_PREFIX, this.REL_PREFIX];\\n\\n /** @type {Array} */\\n this.IGNORE_PREFIXES = [\\n '#',\\n 'about:',\\n 'data:',\\n 'blob:',\\n 'mailto:',\\n 'javascript:',\\n '{',\\n '*'\\n ];\\n if ('ignore_prefixes' in wbinfo) {\\n this.IGNORE_PREFIXES = this.IGNORE_PREFIXES.concat(wbinfo.ignore_prefixes);\\n }\\n\\n this.WB_CHECK_THIS_FUNC = '_____WB$wombat$check$this$function_____';\\n this.WB_ASSIGN_FUNC = '_____WB$wombat$assign$function_____';\\n\\n /** @type {function(qualifiedName: string, value: string): void} */\\n this.wb_setAttribute = $wbwindow.Element.prototype.setAttribute;\\n\\n /** @type {function(qualifiedName: string): ?string} */\\n this.wb_getAttribute = $wbwindow.Element.prototype.getAttribute;\\n\\n /** @type {function(): string} */\\n this.wb_funToString = Function.prototype.toString;\\n\\n /** @type {AutoFetcher} */\\n this.WBAutoFetchWorker = null;\\n\\n /** @type {boolean} */\\n this.wbUseAFWorker =\\n wbinfo.enable_auto_fetch && $wbwindow.Worker != null && wbinfo.is_live;\\n\\n /** @type {string} */\\n this.wb_rel_prefix = '';\\n\\n /** @type {boolean} */\\n this.wb_wombat_updating = false;\\n\\n /** @type {FuncMap} */\\n this.message_listeners = new FuncMap();\\n\\n /** @type {FuncMap} */\\n this.storage_listeners = new FuncMap();\\n\\n /**\\n * rewrite modifiers for \\n * expressed as as-value -> modifier\\n * @type {Object}\\n */\\n this.linkAsTypes = {\\n script: 'js_',\\n worker: 'js_',\\n style: 'cs_',\\n image: 'im_',\\n document: 'if_',\\n fetch: 'mp_',\\n font: 'oe_',\\n audio: 'oe_',\\n video: 'oe_',\\n embed: 'oe_',\\n object: 'oe_',\\n track: 'oe_',\\n // the following cover the default case\\n '': 'mp_',\\n null: 'mp_',\\n undefined: 'mp_'\\n };\\n\\n /**\\n * rewrite modifiers for and or\\n * expressed as a mapping of\\n * rel -> modifier or rel -> as -> modifier\\n * @type {Object}\\n */\\n this.linkTagMods = {\\n linkRelToAs: {\\n import: this.linkAsTypes,\\n preload: this.linkAsTypes\\n },\\n stylesheet: 'cs_',\\n // the following cover the default case\\n null: 'mp_',\\n undefined: 'mp_',\\n '': 'mp_'\\n };\\n\\n /**\\n * pre-computed modifiers for each tag\\n * @type {Object}\\n */\\n this.tagToMod = {\\n A: { href: 'mp_' },\\n AREA: { href: 'mp_' },\\n AUDIO: { src: 'oe_', poster: 'im_' },\\n BASE: { href: 'mp_' },\\n EMBED: { src: 'oe_' },\\n FORM: { action: 'mp_' },\\n FRAME: { src: 'fr_' },\\n IFRAME: { src: 'if_' },\\n IMAGE: { href: 'im_', 'xlink:href': 'im_' },\\n IMG: { src: 'im_', srcset: 'im_' },\\n INPUT: { src: 'oe_' },\\n INS: { cite: 'mp_' },\\n META: { content: 'mp_' },\\n OBJECT: { data: 'oe_', codebase: 'oe_' },\\n Q: { cite: 'mp_' },\\n // covers both HTML and SVG script element,\\n SCRIPT: { src: 'js_', 'xlink:href': 'js_' },\\n SOURCE: { src: 'oe_', srcset: 'oe_' },\\n TRACK: { src: 'oe_' },\\n VIDEO: { src: 'oe_', poster: 'im_' },\\n image: { href: 'im_', 'xlink:href': 'im_' }\\n };\\n\\n /** @type {Array} */\\n this.URL_PROPS = [\\n 'href',\\n 'hash',\\n 'pathname',\\n 'host',\\n 'hostname',\\n 'protocol',\\n 'origin',\\n 'search',\\n 'port'\\n ];\\n\\n /** @type {Object} */\\n this.wb_info = wbinfo;\\n\\n /**\\n * custom options\\n * @type {Object}\\n */\\n this.wb_opts = wbinfo.wombat_opts;\\n\\n /** @type {string} */\\n this.wb_replay_prefix = wbinfo.prefix;\\n\\n /** @type {boolean} */\\n this.wb_is_proxy = this.wb_info.proxy_magic || !this.wb_replay_prefix;\\n\\n /** @type {string} */\\n this.wb_info.top_host = this.wb_info.top_host || '*';\\n\\n /** @type {string} */\\n this.wb_curr_host =\\n $wbwindow.location.protocol + '//' + $wbwindow.location.host;\\n\\n /** @type {Object} */\\n this.wb_info.wombat_opts = this.wb_info.wombat_opts || {};\\n\\n /** @type {string} */\\n this.wb_orig_scheme = this.wb_info.wombat_scheme + '://';\\n /** @type {string} */\\n this.wb_orig_origin = this.wb_orig_scheme + this.wb_info.wombat_host;\\n\\n /** @type {string} */\\n this.wb_abs_prefix = this.wb_replay_prefix;\\n\\n /** @type {string} */\\n this.wb_capture_date_part = '';\\n if (!this.wb_info.is_live && this.wb_info.wombat_ts) {\\n this.wb_capture_date_part = '/' + this.wb_info.wombat_ts + '/';\\n }\\n\\n /** @type {Array} */\\n this.BAD_PREFIXES = [\\n 'http:' + this.wb_replay_prefix,\\n 'https:' + this.wb_replay_prefix,\\n 'http:/' + this.wb_replay_prefix,\\n 'https:/' + this.wb_replay_prefix\\n ];\\n\\n /** @type {RegExp} */\\n this.hostnamePortRe = /^[\\\\w-]+(\\\\.[\\\\w-_]+)+(:\\\\d+)(\\\\/|$)/;\\n\\n /** @type {RegExp} */\\n this.ipPortRe = /^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+(:\\\\d+)?(\\\\/|$)/;\\n\\n /** @type {RegExp} */\\n this.workerBlobRe = /__WB_pmw\\\\(.*?\\\\)\\\\.(?=postMessage\\\\()/g;\\n /** @type {RegExp} */\\n this.rmCheckThisInjectRe = /_____WB\\\\$wombat\\\\$check\\\\$this\\\\$function_____\\\\(.*?\\\\)/g;\\n\\n /** @type {RegExp} */\\n this.STYLE_REGEX = /(url\\\\s*\\\\(\\\\s*[\\\\\\\\\\\"']*)([^)'\\\"]+)([\\\\\\\\\\\"']*\\\\s*\\\\))/gi;\\n\\n /** @type {RegExp} */\\n this.IMPORT_REGEX = /(@import\\\\s*[\\\\\\\\\\\"']*)([^)'\\\";]+)([\\\\\\\\\\\"']*\\\\s*;?)/gi;\\n\\n /** @type {RegExp} */\\n this.IMPORT_JS_REGEX = /^(import\\\\s*\\\\(['\\\"]+)([^'\\\"]+)([\\\"'])/i;\\n\\n /** @type {RegExp} */\\n this.no_wombatRe = /WB_wombat_/g;\\n\\n /** @type {RegExp} */\\n this.srcsetRe = /\\\\s*(\\\\S*\\\\s+[\\\\d.]+[wx]),|(?:\\\\s*,(?:\\\\s+|(?=https?:)))/;\\n\\n /** @type {RegExp} */\\n this.cookie_path_regex = /\\\\bPath='?\\\"?([^;'\\\"\\\\s]+)/i;\\n\\n /** @type {RegExp} */\\n this.cookie_domain_regex = /\\\\bDomain=([^;'\\\"\\\\s]+)/i;\\n\\n /** @type {RegExp} */\\n this.cookie_expires_regex = /\\\\bExpires=([^;'\\\"]+)/gi;\\n\\n /** @type {RegExp} */\\n this.SetCookieRe = /,(?![|])/;\\n\\n /** @type {RegExp} */\\n this.IP_RX = /^(\\\\d)+\\\\.(\\\\d)+\\\\.(\\\\d)+\\\\.(\\\\d)+$/;\\n\\n /** @type {RegExp} */\\n this.FullHTMLRegex = /^\\\\s*<(?:html|head|body|!doctype html)/i;\\n\\n /** @type {RegExp} */\\n this.IsTagRegex = /^\\\\s*;\\n\\n /** @type {RegExp} */\\n this.DotPostMessageRe = /(\\\\.postMessage\\\\s*\\\\()/;\\n\\n /** @type {RegExp} */\\n this.extractPageUnderModifierRE = /\\\\/(?:[0-9]{14})?([a-z]{2, 3}_)\\\\//;\\n\\n /** @type {string} */\\n this.write_buff = '';\\n\\n var eTargetProto = ($wbwindow.EventTarget || {}).prototype;\\n /** @type {Object} */\\n this.utilFns = {\\n cspViolationListener: function(e) {\\n console.group('CSP Violation');\\n console.log('Replayed Page URL', window.WB_wombat_location.href);\\n console.log('The documentURI', e.documentURI);\\n console.log('The blocked URL', e.blockedURI);\\n console.log('The directive violated', e.violatedDirective);\\n console.log('Our policy', e.originalPolicy);\\n if (e.sourceFile) {\\n var fileInfo = 'File: ' + e.sourceFile;\\n if (e.lineNumber && e.columnNumber) {\\n fileInfo += ' @ ' + e.lineNumber + ':' + e.columnNumber;\\n } else if (e.lineNumber) {\\n fileInfo += ' @ ' + e.lineNumber;\\n }\\n console.log(fileInfo);\\n }\\n console.groupEnd();\\n },\\n addEventListener: eTargetProto.addEventListener,\\n removeEventListener: eTargetProto.removeEventListener,\\n // some sites do funky things with the toString function\\n // (e.g. if used throw error or deny operation) hence we\\n // need a surefire and safe way to tell us what an object\\n // or function is hence Objects native toString\\n objToString: Object.prototype.toString,\\n wbSheetMediaQChecker: null,\\n XHRopen: null,\\n XHRsend: null\\n };\\n /**\\n * @type {{yesNo: boolean, added: boolean}}\\n */\\n this.showCSPViolations = { yesNo: false, added: false };\\n autobind(this);\\n // this._addRemoveCSPViolationListener(true);\\n }\\n\\n /**\\n * Performs the initialization of wombat's internals:\\n * - {@link initTopFrame}\\n * - {@link initWombatLoc}\\n * - {@link initWombatTop}\\n * - {@link initAutoFetchWorker}\\n * - initializes the wb_rel_prefix property\\n * - initializes the wb_unrewrite_rx property\\n * - if we are in framed replay mode and the wb_info mod is not bn_\\n * {@link initTopFrameNotify} is called\\n * @private\\n */\\n Wombat.prototype._internalInit = function() {\\n this.initTopFrame(this.$wbwindow);\\n this.initWombatLoc(this.$wbwindow);\\n this.initWombatTop(this.$wbwindow);\\n // updated wb_unrewrite_rx for imgur.com\\n var wb_origin = this.$wbwindow.__WB_replay_top.location.origin;\\n var wb_host = this.$wbwindow.__WB_replay_top.location.host;\\n var wb_proto = this.$wbwindow.__WB_replay_top.location.protocol;\\n if (this.wb_replay_prefix && this.wb_replay_prefix.indexOf(wb_origin) === 0) {\\n this.wb_rel_prefix = this.wb_replay_prefix.substring(wb_origin.length);\\n } else {\\n this.wb_rel_prefix = this.wb_replay_prefix;\\n }\\n this.wb_prefixes = [this.wb_abs_prefix, this.wb_rel_prefix];\\n\\n // make the protocol and host optional now\\n var rx =\\n '((' + wb_proto + ')?//' + wb_host + ')?' + this.wb_rel_prefix + '[^/]+/';\\n this.wb_unrewrite_rx = new RegExp(rx, 'g');\\n\\n if (this.wb_info.is_framed && this.wb_info.mod !== 'bn_') {\\n this.initTopFrameNotify(this.wb_info);\\n }\\n this.initAutoFetchWorker();\\n };\\n\\n /**\\n * Internal function that adds a \\\"securitypolicyviolation\\\" event listener\\n * to the document that will log any CSP violations in a nicer way than\\n * is the default\\n *\\n * If the yesNo argument is true, the event listener is added, otherwise\\n * it is removed\\n * @param {boolean} yesNo\\n * @private\\n */\\n Wombat.prototype._addRemoveCSPViolationListener = function(yesNo) {\\n this.showCSPViolations.yesNo = yesNo;\\n if (this.showCSPViolations.yesNo && !this.showCSPViolations.added) {\\n this.showCSPViolations.added = true;\\n this._addEventListener(\\n document,\\n 'securitypolicyviolation',\\n this.utilFns.cspViolationListener\\n );\\n } else {\\n this.showCSPViolations.added = false;\\n this._removeEventListener(\\n document,\\n 'securitypolicyviolation',\\n this.utilFns.cspViolationListener\\n );\\n }\\n };\\n\\n /**\\n * Adds the supplied event listener on the supplied event target\\n * @param {Object} obj\\n * @param {string} event\\n * @param {Function} fun\\n * @return {*}\\n * @private\\n */\\n Wombat.prototype._addEventListener = function(obj, event, fun) {\\n if (this.utilFns.addEventListener) {\\n return this.utilFns.addEventListener.call(obj, event, fun);\\n }\\n obj.addEventListener(event, fun);\\n };\\n\\n /**\\n * Removes the supplied event listener on the supplied event target\\n * @param {Object} obj\\n * @param {string} event\\n * @param {Function} fun\\n * @return {*}\\n * @private\\n */\\n Wombat.prototype._removeEventListener = function(obj, event, fun) {\\n if (this.utilFns.removeEventListener) {\\n return this.utilFns.removeEventListener.call(obj, event, fun);\\n }\\n obj.removeEventListener(event, fun);\\n };\\n\\n /**\\n * Extracts the modifier (i.e. mp\\\\_, if\\\\_, ...) the page is under that wombat is\\n * operating in. If extracting the modifier fails for some reason mp\\\\_ is returned.\\n * Used to ensure the correct modifier is used for rewriting the service workers scope.\\n * @return {string}\\n */\\n Wombat.prototype.getPageUnderModifier = function() {\\n try {\\n var pageUnderModifier = this.extractPageUnderModifierRE.exec(\\n location.pathname\\n );\\n if (pageUnderModifier && pageUnderModifier[1]) {\\n var mod = pageUnderModifier[1].trim();\\n return mod || 'mp_';\\n }\\n } catch (e) {}\\n return 'mp_';\\n };\\n\\n /**\\n * Returns T/F indicating if the supplied function is a native function\\n * or not. The test checks for the presence of the substring `'[native code]'`\\n * in the result of calling `toString` on the function\\n * @param {Function} funToTest - The function to be tested\\n * @return {boolean}\\n */\\n Wombat.prototype.isNativeFunction = function(funToTest) {\\n if (!funToTest || typeof funToTest !== 'function') return false;\\n var str = this.wb_funToString.call(funToTest);\\n\\n if (str.indexOf('[native code]') == -1) {\\n return false;\\n }\\n if (funToTest.__WB_is_native_func__ !== undefined) {\\n return !!funToTest.__WB_is_native_func__;\\n }\\n return true;\\n };\\n\\n /**\\n * Returns T/F indicating if the supplied argument is a string or not\\n * @param {*} arg\\n * @return {boolean}\\n */\\n Wombat.prototype.isString = function(arg) {\\n return arg != null && Object.getPrototypeOf(arg) === String.prototype;\\n };\\n\\n\\n /**\\n * Create blob for content, convert to service-worker based blob URL\\n * set iframe to remove blob URL on unload\\n *\\n */\\n\\n Wombat.prototype.blobUrlForIframe = function(iframe, string) {\\n var blob = new Blob([string], {type: 'text/html'});\\n var url = URL.createObjectURL(blob);\\n\\n iframe.__wb_blobSrc = url;\\n iframe.addEventListener('load', function() {\\n if (iframe.__wb_blobSrc) {\\n URL.revokeObjectURL(iframe.__wb_blobSrc);\\n iframe.__wb_blobSrc = null;\\n }\\n }, {once: true});\\n\\n iframe.__wb_origSrc = iframe.src;\\n var blobIdUrl = url.slice(url.lastIndexOf('/') + 1) + '/' + this.wb_info.url;\\n iframe.src = this.wb_info.prefix + this.wb_info.request_ts + 'mp_/blob:' + blobIdUrl;\\n };\\n\\n /**\\n * Returns T/F indicating if the supplied element may have attributes that\\n * are auto-fetched\\n * @param {Element} elem\\n * @return {boolean}\\n */\\n Wombat.prototype.isSavedSrcSrcset = function(elem) {\\n switch (elem.tagName) {\\n case 'IMG':\\n case 'VIDEO':\\n case 'AUDIO':\\n return true;\\n case 'SOURCE':\\n if (!elem.parentElement) return false;\\n switch (elem.parentElement.tagName) {\\n case 'PICTURE':\\n case 'VIDEO':\\n case 'AUDIO':\\n return true;\\n default:\\n return false;\\n }\\n default:\\n return false;\\n }\\n };\\n\\n /**\\n * Returns T/F indicating if the supplied element is an Image element that\\n * may have srcset values to be sent to the backing auto-fetch worker\\n * @param {Element} elem\\n * @return {boolean}\\n */\\n Wombat.prototype.isSavedDataSrcSrcset = function(elem) {\\n if (elem.dataset && elem.dataset.srcset != null) {\\n return this.isSavedSrcSrcset(elem);\\n }\\n return false;\\n };\\n\\n /**\\n * Determines if the supplied string is an host URL\\n * @param {string} str\\n * @return {boolean}\\n */\\n Wombat.prototype.isHostUrl = function(str) {\\n // Good guess that's its a hostname\\n if (str.indexOf('www.') === 0) {\\n return true;\\n }\\n\\n // hostname:port (port required)\\n var matches = str.match(this.hostnamePortRe);\\n if (matches && matches[0].length < 64) {\\n return true;\\n }\\n\\n // ip:port\\n matches = str.match(this.ipPortRe);\\n if (matches) {\\n return matches[0].length < 64;\\n }\\n return false;\\n };\\n\\n /**\\n * Returns T/F indicating if the supplied object is the arguments object\\n * @param {*} maybeArgumentsObj\\n * @return {boolean}\\n */\\n Wombat.prototype.isArgumentsObj = function(maybeArgumentsObj) {\\n if (\\n !maybeArgumentsObj ||\\n !(typeof maybeArgumentsObj.toString === 'function')\\n ) {\\n return false;\\n }\\n try {\\n return (\\n this.utilFns.objToString.call(maybeArgumentsObj) === '[object Arguments]'\\n );\\n } catch (e) {\\n return false;\\n }\\n };\\n\\n /**\\n * Ensures that each element in the supplied arguments object or\\n * array is deproxied handling cases where we can not modify the\\n * supplied object returning a new or modified object with the\\n * exect elements/properties\\n * @param {*} maybeArgumentsObj\\n * @return {*}\\n */\\n Wombat.prototype.deproxyArrayHandlingArgumentsObj = function(\\n maybeArgumentsObj\\n ) {\\n if (\\n !maybeArgumentsObj ||\\n maybeArgumentsObj instanceof NodeList ||\\n !maybeArgumentsObj.length\\n ) {\\n return maybeArgumentsObj;\\n }\\n var args = this.isArgumentsObj(maybeArgumentsObj)\\n ? new Array(maybeArgumentsObj.length)\\n : maybeArgumentsObj;\\n for (var i = 0; i < maybeArgumentsObj.length; ++i) {\\n const res = this.proxyToObj(maybeArgumentsObj[i]);\\n if (res !== args[i]) {\\n args[i] = res;\\n }\\n }\\n return args;\\n };\\n\\n /**\\n * Determines if a string starts with the supplied prefix.\\n * If it does the matching prefix is returned otherwise undefined.\\n * @param {?string} string\\n * @param {string} prefix\\n * @return {?string}\\n */\\n Wombat.prototype.startsWith = function(string, prefix) {\\n if (!string) return undefined;\\n return string.indexOf(prefix) === 0 ? prefix : undefined;\\n };\\n\\n /**\\n * Determines if a string starts with the supplied array of prefixes.\\n * If it does the matching prefix is returned otherwise undefined.\\n * @param {?string} string\\n * @param {Array} prefixes\\n * @return {?string}\\n */\\n Wombat.prototype.startsWithOneOf = function(string, prefixes) {\\n if (!string) return undefined;\\n for (var i = 0; i < prefixes.length; i++) {\\n if (string.indexOf(prefixes[i]) === 0) {\\n return prefixes[i];\\n }\\n }\\n return undefined;\\n };\\n\\n /**\\n * Determines if a string ends with the supplied suffix.\\n * If it does the suffix is returned otherwise undefined.\\n * @param {?string} str\\n * @param {string} suffix\\n * @return {?string}\\n */\\n Wombat.prototype.endsWith = function(str, suffix) {\\n if (!str) return undefined;\\n if (str.indexOf(suffix, str.length - suffix.length) !== -1) {\\n return suffix;\\n }\\n return undefined;\\n };\\n\\n /**\\n * Returns T/F indicating if the supplied tag name and attribute name\\n * combination are to be rewritten\\n * @param {string} tagName\\n * @param {string} attr\\n * @return {boolean}\\n */\\n Wombat.prototype.shouldRewriteAttr = function(tagName, attr) {\\n switch (attr) {\\n case 'href':\\n case 'src':\\n case 'xlink:href':\\n return true;\\n }\\n if (\\n tagName &&\\n this.tagToMod[tagName] &&\\n this.tagToMod[tagName][attr] !== undefined\\n ) {\\n return true;\\n }\\n return (\\n (tagName === 'VIDEO' && attr === 'poster') ||\\n (tagName === 'META' && attr === 'content')\\n );\\n };\\n\\n /**\\n * Returns T/F indicating if the script tag being rewritten should not\\n * have its text contents wrapped based on the supplied script type.\\n * @param {?string} scriptType\\n * @return {boolean}\\n */\\n Wombat.prototype.skipWrapScriptBasedOnType = function(scriptType) {\\n if (!scriptType) return false;\\n if (scriptType.indexOf('javascript') >= 0 || scriptType.indexOf('ecmascript') >= 0) return false;\\n if (scriptType.indexOf('json') >= 0) return true;\\n if (scriptType.indexOf('text/') >= 0) return true;\\n return false;\\n };\\n\\n /**\\n * Returns T/F indicating if the script tag being rewritten should not\\n * have its text contents wrapped based on heuristic analysis of its\\n * text contents.\\n * @param {?string} text\\n * @return {boolean}\\n */\\n Wombat.prototype.skipWrapScriptTextBasedOnText = function(text) {\\n if (\\n !text ||\\n text.indexOf(this.WB_ASSIGN_FUNC) >= 0 ||\\n text.indexOf('<') === 0\\n ) {\\n return true;\\n }\\n var override_props = [\\n 'window',\\n 'self',\\n 'document',\\n 'location',\\n 'top',\\n 'parent',\\n 'frames',\\n 'opener'\\n ];\\n\\n for (var i = 0; i < override_props.length; i++) {\\n if (text.indexOf(override_props[i]) >= 0) {\\n return false;\\n }\\n }\\n\\n return true;\\n };\\n\\n /**\\n * Returns T/F indicating if the supplied DOM Node has child Elements/Nodes.\\n * Note this function should be used when the Node(s) being considered can\\n * be null/undefined.\\n * @param {Node} node\\n * @return {boolean}\\n */\\n Wombat.prototype.nodeHasChildren = function(node) {\\n if (!node) return false;\\n if (typeof node.hasChildNodes === 'function') return node.hasChildNodes();\\n var kids = node.children || node.childNodes;\\n if (kids) return kids.length > 0;\\n return false;\\n };\\n\\n /**\\n * Returns the correct rewrite modifier for the supplied element and\\n * attribute combination if one exists otherwise mp_.\\n * Used by\\n * - {@link performAttributeRewrite}\\n * - {@link rewriteFrameSrc}\\n * - {@link initElementGetSetAttributeOverride}\\n * - {@link overrideHrefAttr}\\n *\\n * @param {*} elem\\n * @param {string} attrName\\n * @return {?string}\\n */\\n Wombat.prototype.rwModForElement = function(elem, attrName) {\\n if (!elem) return undefined;\\n // the default modifier, if none is supplied to rewrite_url, is mp_\\n var mod = 'mp_';\\n if (elem.tagName === 'LINK' && attrName === 'href') {\\n // link types are always ASCII case-insensitive, and must be compared as such.\\n // https://html.spec.whatwg.org/multipage/links.html#linkTypes\\n if (elem.rel) {\\n var relV = elem.rel.trim().toLowerCase();\\n var asV = this.wb_getAttribute.call(elem, 'as');\\n if (asV && this.linkTagMods.linkRelToAs[relV] != null) {\\n var asMods = this.linkTagMods.linkRelToAs[relV];\\n mod = asMods[asV.toLowerCase()];\\n } else if (this.linkTagMods[relV] != null) {\\n mod = this.linkTagMods[relV];\\n }\\n }\\n } else {\\n // check if this element has an rewrite modifiers and set mod to it if it does\\n var maybeMod = this.tagToMod[elem.tagName];\\n if (maybeMod != null) {\\n mod = maybeMod[attrName];\\n }\\n }\\n return mod;\\n };\\n\\n /**\\n * If the supplied element is a script tag and has the server-side rewrite added\\n * property \\\"__wb_orig_src\\\" it is removed and the \\\"__$removedWBOSRC$__\\\" property\\n * is added to element as an internal flag indicating no further checks are to be\\n * made.\\n *\\n * See also {@link retrieveWBOSRC}\\n * @param {Element} elem\\n */\\n Wombat.prototype.removeWBOSRC = function(elem) {\\n if (elem.tagName === 'SCRIPT' && !elem.__$removedWBOSRC$__) {\\n if (elem.hasAttribute('__wb_orig_src')) {\\n elem.removeAttribute('__wb_orig_src');\\n }\\n elem.__$removedWBOSRC$__ = true;\\n }\\n };\\n\\n /**\\n * If the supplied element is a script tag and has the server-side rewrite added\\n * property \\\"__wb_orig_src\\\" its value is returned otherwise undefined is returned.\\n * If the element did not have the \\\"__wb_orig_src\\\" property the\\n * \\\"__$removedWBOSRC$__\\\" property is added to element as an internal flag\\n * indicating no further checks are to be made.\\n *\\n * See also {@link removeWBOSRC}\\n * @param {Element} elem\\n * @return {?string}\\n */\\n Wombat.prototype.retrieveWBOSRC = function(elem) {\\n if (elem.tagName === 'SCRIPT' && !elem.__$removedWBOSRC$__) {\\n var maybeWBOSRC;\\n if (this.wb_getAttribute) {\\n maybeWBOSRC = this.wb_getAttribute.call(elem, '__wb_orig_src');\\n } else {\\n maybeWBOSRC = elem.getAttribute('__wb_orig_src');\\n }\\n if (maybeWBOSRC == null) elem.__$removedWBOSRC$__ = true;\\n return maybeWBOSRC;\\n }\\n return undefined;\\n };\\n\\n /**\\n * Wraps the supplied text contents of a script tag with the required Wombat setup\\n * @param {?string} scriptText\\n * @return {string}\\n */\\n Wombat.prototype.wrapScriptTextJsProxy = function(scriptText) {\\n return (\\n 'var _____WB$wombat$assign$function_____ = function(name) {return ' +\\n '(self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };\\\\n' +\\n 'if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { ' +\\n 'this.__WB_source = obj; return this; } }\\\\n{\\\\n' +\\n 'let window = _____WB$wombat$assign$function_____(\\\"window\\\");\\\\n' +\\n 'let globalThis = _____WB$wombat$assign$function_____(\\\"globalThis\\\");\\\\n' +\\n 'let self = _____WB$wombat$assign$function_____(\\\"self\\\");\\\\n' +\\n 'let document = _____WB$wombat$assign$function_____(\\\"document\\\");\\\\n' +\\n 'let location = _____WB$wombat$assign$function_____(\\\"location\\\");\\\\n' +\\n 'let top = _____WB$wombat$assign$function_____(\\\"top\\\");\\\\n' +\\n 'let parent = _____WB$wombat$assign$function_____(\\\"parent\\\");\\\\n' +\\n 'let frames = _____WB$wombat$assign$function_____(\\\"frames\\\");\\\\n' +\\n 'let opener = _____WB$wombat$assign$function_____(\\\"opener\\\");\\\\n{\\\\n' +\\n scriptText.replace(this.DotPostMessageRe, '.__WB_pmw(self.window)$1') +\\n '\\\\n\\\\n}}'\\n );\\n };\\n\\n /**\\n * Calls the supplied function when the supplied element undergoes mutations\\n * @param elem\\n * @param func\\n * @return {boolean}\\n */\\n Wombat.prototype.watchElem = function(elem, func) {\\n if (!this.$wbwindow.MutationObserver) {\\n return false;\\n }\\n var m = new this.$wbwindow.MutationObserver(function(records, observer) {\\n for (var i = 0; i < records.length; i++) {\\n var r = records[i];\\n if (r.type === 'childList') {\\n for (var j = 0; j < r.addedNodes.length; j++) {\\n func(r.addedNodes[j]);\\n }\\n }\\n }\\n });\\n\\n m.observe(elem, {\\n childList: true,\\n subtree: true\\n });\\n };\\n\\n /**\\n * Reconstructs the doctype string if the supplied doctype object\\n * is non null/undefined. This function is used by {@link rewriteHtmlFull}\\n * in order to ensure correctness of rewriting full string of HTML that\\n * started with since the innerHTML and outerHTML properties\\n * do not include that.\\n * @param {DocumentType} doctype\\n * @return {string}\\n */\\n Wombat.prototype.reconstructDocType = function(doctype) {\\n if (doctype == null) return '';\\n return (\\n ''\\n );\\n };\\n\\n /**\\n * Constructs the final URL for the URL rewriting process\\n * @param {boolean} useRel\\n * @param {string} mod\\n * @param {string} url\\n * @return {string}\\n */\\n Wombat.prototype.getFinalUrl = function(useRel, mod, url) {\\n var prefix = useRel ? this.wb_rel_prefix : this.wb_abs_prefix;\\n\\n if (mod == null) {\\n mod = this.wb_info.mod;\\n }\\n\\n // if live, don't add the timestamp\\n if (!this.wb_info.is_live) {\\n prefix += this.wb_info.wombat_ts;\\n }\\n\\n prefix += mod;\\n\\n if (prefix[prefix.length - 1] !== '/') {\\n prefix += '/';\\n }\\n\\n return prefix + url;\\n };\\n\\n /**\\n * Converts the supplied relative URL to an absolute URL using an A tag\\n * @param {string} url\\n * @param {?Document} doc\\n * @return {string}\\n */\\n Wombat.prototype.resolveRelUrl = function(url, doc) {\\n var docObj = doc || this.$wbwindow.document;\\n var parser = this.makeParser(docObj.baseURI, docObj);\\n var hash = parser.href.lastIndexOf('#');\\n var href = hash >= 0 ? parser.href.substring(0, hash) : parser.href;\\n var lastslash = href.lastIndexOf('/');\\n\\n if (lastslash >= 0 && lastslash !== href.length - 1) {\\n parser.href = href.substring(0, lastslash + 1) + url;\\n } else {\\n parser.href = href + url;\\n }\\n return parser.href;\\n };\\n\\n /**\\n * Extracts the original URL from the supplied rewritten URL\\n * @param {?string} rewrittenUrl\\n * @return {string}\\n */\\n Wombat.prototype.extractOriginalURL = function(rewrittenUrl) {\\n if (!rewrittenUrl) {\\n return '';\\n } else if (this.wb_is_proxy) {\\n // proxy mode: no extraction needed\\n return rewrittenUrl;\\n }\\n\\n var rwURLString = rewrittenUrl.toString();\\n\\n var url = rwURLString;\\n\\n // ignore certain urls\\n if (this.startsWithOneOf(url, this.IGNORE_PREFIXES)) {\\n return url;\\n }\\n\\n if (url.startsWith(this.wb_info.static_prefix)) {\\n return url;\\n }\\n\\n var start;\\n\\n if (this.startsWith(url, this.wb_abs_prefix)) {\\n start = this.wb_abs_prefix.length;\\n } else if (this.wb_rel_prefix && this.startsWith(url, this.wb_rel_prefix)) {\\n start = this.wb_rel_prefix.length;\\n } else {\\n // if no coll, start from beginning, otherwise could be part of coll..\\n start = this.wb_rel_prefix ? 1 : 0;\\n }\\n\\n var index = url.indexOf('/http', start);\\n if (index < 0) {\\n index = url.indexOf('///', start);\\n }\\n if (index < 0) {\\n index = url.indexOf('/blob:', start);\\n }\\n if (index < 0) {\\n index = url.indexOf('/about:blank', start);\\n }\\n\\n // extract original url from wburl\\n if (index >= 0) {\\n url = url.substr(index + 1);\\n } else {\\n index = url.indexOf(this.wb_replay_prefix);\\n if (index >= 0) {\\n url = url.substr(index + this.wb_replay_prefix.length);\\n }\\n if (url.length > 4 && url.charAt(2) === '_' && url.charAt(3) === '/') {\\n url = url.substr(4);\\n }\\n\\n if (\\n url !== rwURLString &&\\n !this.startsWithOneOf(url, this.VALID_PREFIXES) && !this.startsWith(url, 'blob:')\\n ) {\\n url = this.wb_orig_scheme + url;\\n }\\n }\\n\\n if (\\n rwURLString.charAt(0) === '/' &&\\n rwURLString.charAt(1) !== '/' &&\\n this.startsWith(url, this.wb_orig_origin)\\n ) {\\n url = url.substr(this.wb_orig_origin.length);\\n }\\n\\n if (this.startsWith(url, this.REL_PREFIX)) {\\n return this.wb_info.wombat_scheme + ':' + url;\\n }\\n\\n return url;\\n };\\n\\n /**\\n * Creates and returns an A tag ready for parsing the original URL\\n * part of the supplied URL.\\n * @param {string} maybeRewrittenURL\\n * @param {?Document} doc\\n * @return {HTMLAnchorElement}\\n */\\n Wombat.prototype.makeParser = function(maybeRewrittenURL, doc) {\\n var originalURL = this.extractOriginalURL(maybeRewrittenURL);\\n var docElem = doc;\\n if (!doc) {\\n // special case: for newly opened blank windows, use the opener\\n // to create parser to have the proper baseURI\\n if (\\n this.$wbwindow.location.href === 'about:blank' &&\\n this.$wbwindow.opener\\n ) {\\n docElem = this.$wbwindow.opener.document;\\n } else {\\n docElem = this.$wbwindow.document;\\n }\\n }\\n\\n return this._makeURLParser(originalURL, docElem);\\n\\n };\\n\\n Wombat.prototype._makeURLParser = function(url, docElem) {\\n try {\\n return new this.$wbwindow.URL(url, docElem.baseURI);\\n } catch (e) {}\\n\\n var p = docElem.createElement('a');\\n p._no_rewrite = true;\\n p.href = url;\\n return p;\\n };\\n\\n /**\\n * Defines a new getter and optional setter for the property on the supplied\\n * object returning T/F to indicate if the new property was successfully defined\\n * @param {Object} obj\\n * @param {string} prop\\n * @param {?function(value: *): *} setFunc\\n * @param {function(): *} getFunc\\n * @param {?boolean} [enumerable]\\n * @return {boolean}\\n */\\n Wombat.prototype.defProp = function(obj, prop, setFunc, getFunc, enumerable) {\\n // if the property is marked as non-configurable in the current\\n // browser, skip the override\\n var existingDescriptor = Object.getOwnPropertyDescriptor(obj, prop);\\n if (existingDescriptor && !existingDescriptor.configurable) {\\n return false;\\n }\\n\\n // if no getter function was supplied, skip the override.\\n // See https://github.com/webrecorder/pywb/issues/147 for context\\n if (!getFunc) {\\n return false;\\n }\\n\\n var descriptor = {\\n configurable: true,\\n enumerable: enumerable || false,\\n get: getFunc\\n };\\n\\n if (setFunc) {\\n descriptor.set = setFunc;\\n }\\n\\n try {\\n Object.defineProperty(obj, prop, descriptor);\\n return true;\\n } catch (e) {\\n console.warn('Failed to redefine property %s', prop, e.message);\\n return false;\\n }\\n };\\n\\n /**\\n * Defines a new getter for the property on the supplied object returning\\n * T/F to indicate if the new property was successfully defined\\n * @param {Object} obj\\n * @param {string} prop\\n * @param {function(): *} getFunc\\n * @param {?boolean} [enumerable]\\n * @return {boolean}\\n */\\n Wombat.prototype.defGetterProp = function(obj, prop, getFunc, enumerable) {\\n var existingDescriptor = Object.getOwnPropertyDescriptor(obj, prop);\\n if (existingDescriptor && !existingDescriptor.configurable) {\\n return false;\\n }\\n // if no getter function was supplied, skip the override.\\n // See https://github.com/webrecorder/pywb/issues/147 for context\\n if (!getFunc) return false;\\n\\n try {\\n Object.defineProperty(obj, prop, {\\n configurable: true,\\n enumerable: enumerable || false,\\n get: getFunc\\n });\\n return true;\\n } catch (e) {\\n console.warn('Failed to redefine property %s', prop, e.message);\\n return false;\\n }\\n };\\n\\n /**\\n * Returns the original getter function for the supplied object's property\\n * @param {Object} obj\\n * @param {string} prop\\n * @return {function(): *}\\n */\\n Wombat.prototype.getOrigGetter = function(obj, prop) {\\n var orig_getter;\\n\\n if (obj.__lookupGetter__) {\\n orig_getter = obj.__lookupGetter__(prop);\\n }\\n\\n if (!orig_getter && Object.getOwnPropertyDescriptor) {\\n var props = Object.getOwnPropertyDescriptor(obj, prop);\\n if (props) {\\n orig_getter = props.get;\\n }\\n }\\n\\n return orig_getter;\\n };\\n\\n /**\\n * Returns the original setter function for the supplied object's property\\n * @param {Object} obj\\n * @param {string} prop\\n * @return {function(): *}\\n */\\n Wombat.prototype.getOrigSetter = function(obj, prop) {\\n var orig_setter;\\n\\n if (obj.__lookupSetter__) {\\n orig_setter = obj.__lookupSetter__(prop);\\n }\\n\\n if (!orig_setter && Object.getOwnPropertyDescriptor) {\\n var props = Object.getOwnPropertyDescriptor(obj, prop);\\n if (props) {\\n orig_setter = props.set;\\n }\\n }\\n\\n return orig_setter;\\n };\\n\\n /**\\n * Returns an array containing the names of all the properties\\n * that exist on the supplied object\\n * @param {Object} obj\\n * @return {Array}\\n */\\n Wombat.prototype.getAllOwnProps = function(obj) {\\n /** @type {Array} */\\n var ownProps = [];\\n\\n var props = Object.getOwnPropertyNames(obj);\\n var i = 0;\\n for (; i < props.length; i++) {\\n var prop = props[i];\\n\\n try {\\n if (obj[prop] && !obj[prop].prototype) {\\n ownProps.push(prop);\\n }\\n } catch (e) {}\\n }\\n\\n var traverseObj = Object.getPrototypeOf(obj);\\n\\n while (traverseObj) {\\n props = Object.getOwnPropertyNames(traverseObj);\\n for (i = 0; i < props.length; i++) {\\n ownProps.push(props[i]);\\n }\\n traverseObj = Object.getPrototypeOf(traverseObj);\\n }\\n\\n return ownProps;\\n };\\n\\n /**\\n * Sends the supplied message to __WB_top_frame\\n * @param {*} message\\n * @param {boolean} [skipTopCheck]\\n */\\n Wombat.prototype.sendTopMessage = function(message, skipTopCheck, win) {\\n win = win || this.$wbwindow;\\n if (!win.__WB_top_frame) return;\\n if (!skipTopCheck && win != win.__WB_replay_top) {\\n return;\\n }\\n win.__WB_top_frame.postMessage(message, this.wb_info.top_host);\\n };\\n\\n /**\\n * Notifies __WB_top_frame of an history update\\n * @param {?string} url\\n * @param {?string} title\\n */\\n Wombat.prototype.sendHistoryUpdate = function(url, title, win) {\\n this.sendTopMessage(\\n {\\n url: url,\\n ts: this.wb_info.timestamp,\\n request_ts: this.wb_info.request_ts,\\n is_live: this.wb_info.is_live,\\n title: title,\\n wb_type: 'replace-url'\\n },\\n false,\\n win\\n );\\n };\\n\\n /**\\n * Updates the real location object with the results of rewriting the supplied URL\\n * @param {?string} reqHref\\n * @param {string} origHref\\n * @param {Location} actualLocation\\n */\\n Wombat.prototype.updateLocation = function(reqHref, origHref, actualLocation) {\\n if (!reqHref || reqHref === origHref) return;\\n\\n var ext_orig = this.extractOriginalURL(origHref);\\n var ext_req = this.extractOriginalURL(reqHref);\\n\\n if (!ext_orig || ext_orig === ext_req) return;\\n\\n var final_href = this.rewriteUrl(reqHref);\\n\\n console.log(actualLocation.href + ' -> ' + final_href);\\n\\n actualLocation.href = final_href;\\n };\\n\\n /**\\n * Updates the real location with a change\\n * @param {*} wombatLoc\\n * @param {boolean} isTop\\n */\\n Wombat.prototype.checkLocationChange = function(wombatLoc, isTop) {\\n var locType = typeof wombatLoc;\\n\\n var actual_location = isTop\\n ? this.$wbwindow.__WB_replay_top.location\\n : this.$wbwindow.location;\\n\\n // String has been assigned to location, so assign it\\n if (locType === 'string') {\\n this.updateLocation(wombatLoc, actual_location.href, actual_location);\\n } else if (locType === 'object') {\\n this.updateLocation(wombatLoc.href, wombatLoc._orig_href, actual_location);\\n }\\n };\\n\\n /**\\n * Checks for a location change, either this browser context or top and updates\\n * accordingly\\n * @return {boolean}\\n */\\n Wombat.prototype.checkAllLocations = function() {\\n if (this.wb_wombat_updating) {\\n return false;\\n }\\n\\n this.wb_wombat_updating = true;\\n\\n this.checkLocationChange(this.$wbwindow.WB_wombat_location, false);\\n\\n // Only check top if its a different $wbwindow\\n if (\\n this.$wbwindow.WB_wombat_location !=\\n this.$wbwindow.__WB_replay_top.WB_wombat_location\\n ) {\\n this.checkLocationChange(\\n this.$wbwindow.__WB_replay_top.WB_wombat_location,\\n true\\n );\\n }\\n\\n this.wb_wombat_updating = false;\\n };\\n\\n /**\\n * Returns the Object the Proxy was proxying if it exists otherwise\\n * the original object\\n * @param {*} source\\n * @return {?Object}\\n */\\n Wombat.prototype.proxyToObj = function(source) {\\n if (source) {\\n try {\\n var proxyRealObj = source.__WBProxyRealObj__;\\n if (proxyRealObj) return proxyRealObj;\\n } catch (e) {}\\n }\\n return source;\\n };\\n\\n /**\\n * Returns the Proxy object for the supplied Object if it exists otherwise\\n * the original object\\n * @param {?Object} obj\\n * @return {Proxy|?Object}\\n */\\n Wombat.prototype.objToProxy = function(obj) {\\n if (obj) {\\n try {\\n var maybeWbProxy = obj._WB_wombat_obj_proxy;\\n if (maybeWbProxy) return maybeWbProxy;\\n } catch (e) {}\\n }\\n return obj;\\n };\\n\\n /**\\n * Returns the value of supplied object that is being Proxied\\n * @param {*} obj\\n * @param {*} prop\\n * @param {Array} ownProps\\n * @param {Object} fnCache\\n * @return {*}\\n */\\n Wombat.prototype.defaultProxyGet = function(obj, prop, ownProps, fnCache) {\\n switch (prop) {\\n case '__WBProxyRealObj__':\\n return obj;\\n case 'location':\\n case 'WB_wombat_location':\\n return obj.WB_wombat_location;\\n case '_WB_wombat_obj_proxy':\\n return obj._WB_wombat_obj_proxy;\\n case '__WB_pmw':\\n case this.WB_ASSIGN_FUNC:\\n case this.WB_CHECK_THIS_FUNC:\\n return obj[prop];\\n\\n case 'origin':\\n return obj.WB_wombat_location.origin;\\n\\n case 'constructor':\\n // allow tests that check constructor name/equality to work\\n // you can't create a new instance of window, document or location using the constructors\\n return obj.constructor;\\n }\\n var retVal = obj[prop];\\n\\n var type = typeof retVal;\\n\\n if (type === 'function' && ownProps.indexOf(prop) !== -1) {\\n // certain sites (e.g. facebook) are applying polyfills to native functions\\n // treating the polyfill as a native function [fn.bind(obj)] causes incorrect execution of the polyfill\\n // also depending on the site, the site can detect we \\\"tampered\\\" with the polyfill by binding it to obj\\n // to avoid these situations, we do not bind the returned fn if we detect they were polyfilled\\n switch (prop) {\\n case 'requestAnimationFrame':\\n case 'cancelAnimationFrame': {\\n if (!this.isNativeFunction(retVal)) {\\n return retVal;\\n }\\n break;\\n }\\n\\n case 'eval':\\n if (this.isNativeFunction(retVal)) {\\n return this.wrappedEval(retVal);\\n }\\n break;\\n }\\n // due to specific use cases involving native functions\\n // we must return the\\n var cachedFN = fnCache[prop];\\n if (!cachedFN || cachedFN.original !== retVal) {\\n cachedFN = {\\n original: retVal,\\n boundFn: retVal.bind(obj)\\n };\\n fnCache[prop] = cachedFN;\\n }\\n return cachedFN.boundFn;\\n } else if (type === 'object' && retVal && retVal._WB_wombat_obj_proxy) {\\n if (retVal instanceof this.WBWindow) {\\n this.initNewWindowWombat(retVal);\\n }\\n return retVal._WB_wombat_obj_proxy;\\n }\\n\\n return retVal;\\n };\\n\\n /**\\n * Set the location properties for either an instance of WombatLocation\\n * or an anchor tag\\n * @param {HTMLAnchorElement|WombatLocation} loc\\n * @param {string} originalURL\\n */\\n Wombat.prototype.setLoc = function(loc, originalURL) {\\n var parser = this.makeParser(originalURL, loc.ownerDocument);\\n\\n loc._orig_href = originalURL;\\n loc._parser = parser;\\n\\n var href = parser.href;\\n loc._hash = parser.hash;\\n\\n loc._href = href;\\n\\n loc._host = parser.host;\\n loc._hostname = parser.hostname;\\n\\n if (parser.origin) {\\n loc._origin = parser.host ? parser.origin : 'null';\\n } else {\\n loc._origin =\\n parser.protocol +\\n '//' +\\n parser.hostname +\\n (parser.port ? ':' + parser.port : '');\\n }\\n\\n loc._pathname = parser.pathname;\\n loc._port = parser.port;\\n // this.protocol = parser.protocol;\\n loc._protocol = parser.protocol;\\n loc._search = parser.search;\\n\\n if (!Object.defineProperty) {\\n loc.href = href;\\n loc.hash = parser.hash;\\n\\n loc.host = loc._host;\\n loc.hostname = loc._hostname;\\n loc.origin = loc._origin;\\n loc.pathname = loc._pathname;\\n loc.port = loc._port;\\n loc.protocol = loc._protocol;\\n loc.search = loc._search;\\n }\\n };\\n\\n /**\\n * Returns a function for retrieving some property on an instance of either\\n * WombatLocation or an anchor tag\\n * @param {string} prop\\n * @param {function(): string} origGetter\\n * @return {function(): string}\\n */\\n Wombat.prototype.makeGetLocProp = function(prop, origGetter) {\\n var wombat = this;\\n return function newGetLocProp() {\\n if (this._no_rewrite) return origGetter.call(this, prop);\\n\\n var curr_orig_href = origGetter.call(this, 'href');\\n\\n if (prop === 'href') {\\n return wombat.extractOriginalURL(curr_orig_href);\\n }\\n\\n if (prop === 'ancestorOrigins') {\\n return [];\\n }\\n\\n if (this._orig_href !== curr_orig_href) {\\n wombat.setLoc(this, curr_orig_href);\\n }\\n return this['_' + prop];\\n };\\n };\\n\\n /**\\n * Returns a function for setting some property on an instance of either\\n * WombatLocation or an anchor tag\\n * @param {string} prop\\n * @param {function (value: *): *} origSetter\\n * @param {function(): *} origGetter\\n * @return {function (value: *): *}\\n */\\n Wombat.prototype.makeSetLocProp = function(prop, origSetter, origGetter) {\\n var wombat = this;\\n return function newSetLocProp(value) {\\n if (this._no_rewrite) {\\n return origSetter.call(this, prop, value);\\n }\\n if (this['_' + prop] === value) return;\\n\\n this['_' + prop] = value;\\n\\n if (!this._parser) {\\n var href = origGetter.call(this);\\n this._parser = wombat.makeParser(href, this.ownerDocument);\\n }\\n\\n var rel = false;\\n\\n // Special case for assigning href to a relative path\\n if (prop === 'href' && typeof value === 'string') {\\n if (value && this._parser instanceof URL) {\\n try {\\n value = new URL(value, this._parser).href;\\n } catch (e) {\\n console.warn('Error resolving URL', e);\\n }\\n } else if (value) {\\n if (value[0] === '.' || value[0] === '#') {\\n value = wombat.resolveRelUrl(value, this.ownerDocument);\\n } else if (value[0] === '/') {\\n if (value.length > 1 && value[1] === '/') {\\n value = this._parser.protocol + value;\\n } else {\\n rel = true;\\n value = WB_wombat_location.origin + value;\\n }\\n }\\n }\\n }\\n\\n try {\\n this._parser[prop] = value;\\n } catch (e) {\\n console.log('Error setting ' + prop + ' = ' + value);\\n }\\n\\n if (prop === 'hash') {\\n value = this._parser[prop];\\n origSetter.call(this, 'hash', value);\\n } else {\\n rel = rel || value === this._parser.pathname;\\n value = wombat.rewriteUrl(this._parser.href, rel);\\n origSetter.call(this, 'href', value);\\n }\\n };\\n };\\n\\n /**\\n * Function used for rewriting URL's contained in CSS style definitions\\n * @param {Object} match\\n * @param {string} n1\\n * @param {string} n2\\n * @param {string} n3\\n * @param {number} offset\\n * @param {string} string\\n * @return {string}\\n */\\n Wombat.prototype.styleReplacer = function(match, n1, n2, n3, offset, string) {\\n return n1 + this.rewriteUrl(n2) + n3;\\n };\\n\\n\\n /**\\n * Due to the fact that we override specific DOM constructors, e.g. Worker,\\n * the normal TypeErrors are not thrown if the pre-conditions for those\\n * constructors are not met.\\n *\\n * Code that performs polyfills or browser feature detection based\\n * on those TypeErrors will not work as expected if we do not perform\\n * those checks ourselves (Note we use Chrome's error messages)\\n *\\n * This function checks for those pre-conditions and throws an TypeError\\n * with the appropriate message if a pre-condition is not met\\n * - `this` instanceof Window is false (requires new)\\n * - supplied required arguments\\n *\\n * @param {Object} thisObj\\n * @param {string} what\\n * @param {Object} [args]\\n * @param {number} [numRequiredArgs]\\n */\\n Wombat.prototype.domConstructorErrorChecker = function(\\n thisObj,\\n what,\\n args,\\n numRequiredArgs\\n ) {\\n var needArgs = typeof numRequiredArgs === 'number' ? numRequiredArgs : 1;\\n var errorMsg;\\n if (thisObj instanceof this.WBWindow) {\\n errorMsg =\\n 'Failed to construct \\\\'' +\\n what +\\n '\\\\': Please use the \\\\'new\\\\' operator, this DOM object constructor cannot be called as a function.';\\n } else if (args && args.length < needArgs) {\\n errorMsg =\\n 'Failed to construct \\\\'' +\\n what +\\n '\\\\': ' +\\n needArgs +\\n ' argument required, but only 0 present.';\\n }\\n if (errorMsg) {\\n throw new TypeError(errorMsg);\\n }\\n };\\n\\n /**\\n * Rewrites the arguments supplied to an function of the Node interface\\n * @param {Object} fnThis\\n * @param {function} originalFn\\n * @param {Node} newNode\\n * @param {Node} [oldNode]\\n */\\n Wombat.prototype.rewriteNodeFuncArgs = function(\\n fnThis,\\n originalFn,\\n newNode,\\n oldNode\\n ) {\\n if (newNode) {\\n switch (newNode.nodeType) {\\n case Node.ELEMENT_NODE:\\n this.rewriteElemComplete(newNode);\\n break;\\n case Node.TEXT_NODE:\\n // newNode is the new child of fnThis (the parent node)\\n if (\\n fnThis.tagName === 'STYLE' ||\\n (newNode.parentNode && newNode.parentNode.tagName === 'STYLE')\\n ) {\\n newNode.textContent = this.rewriteStyle(newNode.textContent);\\n }\\n break;\\n case Node.DOCUMENT_FRAGMENT_NODE:\\n this.recurseRewriteElem(newNode);\\n break;\\n }\\n }\\n var created = originalFn.call(fnThis, newNode, oldNode);\\n if (created && created.tagName === 'IFRAME') {\\n created.allow = 'autoplay \\\\'self\\\\'; fullscreen \\\\'self\\\\'';\\n this.initIframeWombat(created);\\n }\\n return created;\\n };\\n\\n /**\\n * Mini url rewriter specifically for rewriting web sockets\\n * @param {?string} originalURL\\n * @return {string}\\n */\\n Wombat.prototype.rewriteWSURL = function(originalURL) {\\n // If undefined, just return it\\n if (!originalURL) return originalURL;\\n\\n var urltype_ = typeof originalURL;\\n var url = originalURL;\\n\\n // If object, use toString\\n if (urltype_ === 'object') {\\n url = originalURL.toString();\\n } else if (urltype_ !== 'string') {\\n return originalURL;\\n }\\n\\n // empty string check\\n if (!url) return url;\\n\\n var wsScheme = 'ws://';\\n var wssScheme = 'wss://';\\n\\n // proxy mode: If no wb_replay_prefix, only rewrite scheme\\n // proxy mode: If no wb_replay_prefix, only rewrite scheme\\n if (this.wb_is_proxy) {\\n if (\\n this.wb_orig_scheme === this.HTTP_PREFIX &&\\n this.startsWith(url, wssScheme)\\n ) {\\n return wsScheme + url.substr(wssScheme.length);\\n } else if (\\n this.wb_orig_scheme === this.HTTPS_PREFIX &&\\n this.startsWith(url, wsScheme)\\n ) {\\n return wssScheme + url.substr(wsScheme.length);\\n } else {\\n return url;\\n }\\n }\\n\\n var wbSecure = this.wb_abs_prefix.indexOf(this.HTTPS_PREFIX) === 0;\\n var wbPrefix = this.wb_abs_prefix.replace(\\n wbSecure ? this.HTTPS_PREFIX : this.HTTP_PREFIX,\\n wbSecure ? wssScheme : wsScheme\\n );\\n wbPrefix += this.wb_info.wombat_ts + 'ws_';\\n if (url[url.length - 1] !== '/') {\\n wbPrefix += '/';\\n }\\n return wbPrefix + url.replace('WB_wombat_', '');\\n };\\n\\n /**\\n * Rewrites the supplied URL returning the rewritten URL\\n * @param {?string} originalURL\\n * @param {?boolean} [useRel]\\n * @param {?string} [mod]\\n * @param {?Document} [doc]\\n * @return {?string}\\n * @private\\n */\\n Wombat.prototype.rewriteUrl_ = function(originalURL, useRel, mod, doc) {\\n // If undefined, just return it\\n if (!originalURL) return originalURL;\\n\\n var urltype_ = typeof originalURL;\\n var url;\\n\\n // If object, use toString\\n if (urltype_ === 'object') {\\n url = originalURL.toString();\\n } else if (urltype_ !== 'string') {\\n return originalURL;\\n } else {\\n url = originalURL;\\n }\\n\\n // empty string check\\n if (!url) return url;\\n\\n // proxy mode: If no wb_replay_prefix, only rewrite scheme\\n if (this.wb_is_proxy) {\\n if (\\n this.wb_orig_scheme === this.HTTP_PREFIX &&\\n this.startsWith(url, this.HTTPS_PREFIX)\\n ) {\\n return this.HTTP_PREFIX + url.substr(this.HTTPS_PREFIX.length);\\n } else if (\\n this.wb_orig_scheme === this.HTTPS_PREFIX &&\\n this.startsWith(url, this.HTTP_PREFIX)\\n ) {\\n return this.HTTPS_PREFIX + url.substr(this.HTTP_PREFIX.length);\\n } else {\\n return url;\\n }\\n }\\n\\n // just in case _wombat reference made it into url!\\n url = url.replace('WB_wombat_', '');\\n\\n if (mod === 'if_' && this.wb_info.isSW && this.startsWith(url, 'blob:')) {\\n return this.wb_info.prefix + this.wb_info.request_ts + 'if_/' + url;\\n }\\n\\n // ignore anchors, about, data\\n if (this.startsWithOneOf(url.toLowerCase(), this.IGNORE_PREFIXES)) {\\n return url;\\n }\\n\\n // OPTS: additional ignore prefixes\\n if (\\n this.wb_opts.no_rewrite_prefixes &&\\n this.startsWithOneOf(url, this.wb_opts.no_rewrite_prefixes)\\n ) {\\n return url;\\n }\\n\\n // If starts with prefix, no rewriting needed\\n // Only check replay prefix (no date) as date may be different for each\\n // capture\\n\\n // if scheme relative, prepend current scheme\\n var check_url;\\n\\n if (url.indexOf('//') === 0) {\\n check_url = this.origProtocol + url;\\n } else {\\n check_url = url;\\n }\\n\\n //var originalLoc = this.$wbwindow.location;\\n if (\\n this.startsWith(check_url, this.wb_abs_prefix) ||\\n this.startsWith(check_url, this.wb_rel_prefix)\\n ) {\\n return url;\\n }\\n\\n // A special case where the port somehow gets dropped\\n // Check for this and add it back in, eg http://localhost/path/ -> http://localhost:8080/path/\\n if (\\n this.origHost !== this.origHostname &&\\n this.startsWith(\\n url,\\n this.origProtocol + '//' + this.origHostname + '/'\\n )\\n ) {\\n return url.replace(\\n '/' + this.origHostname + '/',\\n '/' + this.origHost + '/'\\n );\\n }\\n\\n // If server relative url, add prefix and original host\\n if (url.charAt(0) === '/' && !this.startsWith(url, this.REL_PREFIX)) {\\n // Already a relative url, don't make any changes!\\n if (\\n this.wb_capture_date_part &&\\n url.indexOf(this.wb_capture_date_part) >= 0\\n ) {\\n return url;\\n }\\n\\n // relative collection\\n if (url.indexOf(this.wb_rel_prefix) === 0 && url.indexOf('http') > 1) {\\n var scheme_sep = url.indexOf(':/');\\n if (scheme_sep > 0 && url[scheme_sep + 2] !== '/') {\\n return (\\n url.substring(0, scheme_sep + 2) + '/' + url.substring(scheme_sep + 2)\\n );\\n }\\n return url;\\n }\\n\\n return this.getFinalUrl(true, mod, this.wb_orig_origin + url);\\n }\\n\\n // Use a parser\\n if (url.charAt(0) === '.') {\\n url = this.resolveRelUrl(url, doc);\\n }\\n\\n // If full url starting with http://, https:// or //\\n // add rewrite prefix, we convert to lower case for this check\\n // due to the fact that the URL's scheme could be HTTP(S) LUL\\n var prefix = this.startsWithOneOf(url.toLowerCase(), this.VALID_PREFIXES);\\n\\n if (prefix) {\\n //var orig_host = this.$wbwindow.__WB_replay_top.location.host;\\n //var orig_protocol = this.$wbwindow.__WB_replay_top.location.protocol;\\n var orig_host = this.replayTopHost;\\n var orig_protocol = this.replayTopProtocol;\\n\\n var prefix_host = prefix + orig_host + '/';\\n\\n // if already rewritten url, must still check scheme\\n if (this.startsWith(url, prefix_host)) {\\n if (this.startsWith(url, this.wb_replay_prefix)) {\\n return url;\\n }\\n\\n var curr_scheme = orig_protocol + '//';\\n var path = url.substring(prefix_host.length);\\n var rebuild = false;\\n\\n if (path.indexOf(this.wb_rel_prefix) < 0 && url.indexOf('/static/') < 0) {\\n path = this.getFinalUrl(\\n true,\\n mod,\\n WB_wombat_location.origin + '/' + path\\n );\\n rebuild = true;\\n }\\n\\n // replace scheme to ensure using the correct server scheme\\n // if (starts_with(url, wb_orig_scheme) && (wb_orig_scheme != curr_scheme)) {\\n if (prefix !== curr_scheme && prefix !== this.REL_PREFIX) {\\n rebuild = true;\\n }\\n\\n if (rebuild) {\\n if (!useRel) {\\n url = curr_scheme + orig_host;\\n } else {\\n url = '';\\n }\\n if (path && path[0] !== '/') {\\n url += '/';\\n }\\n url += path;\\n }\\n\\n return url;\\n }\\n return this.getFinalUrl(useRel, mod, url);\\n }\\n // Check for common bad prefixes and remove them\\n prefix = this.startsWithOneOf(url, this.BAD_PREFIXES);\\n\\n if (prefix) {\\n return this.getFinalUrl(useRel, mod, this.extractOriginalURL(url));\\n }\\n\\n // May or may not be a hostname, call function to determine\\n // If it is, add the prefix and make sure port is removed\\n //if (this.isHostUrl(url) && !this.startsWith(url, originalLoc.host + '/')) {\\n // return this.getFinalUrl(useRel, mod, this.wb_orig_scheme + url);\\n //}\\n\\n return url;\\n };\\n\\n /**\\n * Rewrites the supplied URL returning the rewritten URL.\\n * If wombat is in debug mode the rewrite is logged to the console\\n * @param {*} url\\n * @param {?boolean} [useRel]\\n * @param {?string} [mod]\\n * @param {?Document} [doc]\\n * @return {?string}\\n */\\n Wombat.prototype.rewriteUrl = function(url, useRel, mod, doc) {\\n var rewritten = this.rewriteUrl_(url, useRel, mod, doc);\\n if (this.debug_rw) {\\n if (url !== rewritten) {\\n console.log('REWRITE: ' + url + ' -> ' + rewritten);\\n } else {\\n console.log('NOT REWRITTEN ' + url);\\n }\\n }\\n return rewritten;\\n };\\n\\n /**\\n * Rewrites the value of the supplied elements attribute returning its rewritten value.\\n * Used by {@link newAttrObjGetSet} and {@link rewriteAttr}\\n *\\n * @param {Element} elem\\n * @param {string} name\\n * @param {*} value\\n * @param {boolean} [absUrlOnly]\\n * @return {*}\\n */\\n Wombat.prototype.performAttributeRewrite = function(\\n elem,\\n name,\\n value,\\n absUrlOnly\\n ) {\\n switch (name) {\\n // inner and outer HTML are for the overrides applied by newAttrObjGetSet\\n case 'innerHTML':\\n case 'outerHTML':\\n return this.rewriteHtml(value);\\n case 'filter': // for svg filter attribute which is url(...)\\n return this.rewriteInlineStyle(value);\\n case 'style':\\n return this.rewriteStyle(value);\\n case 'srcset':\\n return this.rewriteSrcset(value, elem);\\n }\\n // Only rewrite if absolute url\\n if (absUrlOnly && !this.startsWithOneOf(value, this.VALID_PREFIXES)) {\\n return value;\\n }\\n var mod = this.rwModForElement(elem, name);\\n if (\\n this.wbUseAFWorker &&\\n this.WBAutoFetchWorker &&\\n this.isSavedDataSrcSrcset(elem)\\n ) {\\n this.WBAutoFetchWorker.preserveDataSrcset(elem);\\n }\\n return this.rewriteUrl(value, false, mod, elem.ownerDocument);\\n };\\n\\n /**\\n * Rewrites an element attribute's value\\n * @param {Element} elem\\n * @param {string} name\\n * @param {boolean} [absUrlOnly]\\n * @return {boolean}\\n */\\n Wombat.prototype.rewriteAttr = function(elem, name, absUrlOnly) {\\n var changed = false;\\n if (!elem || !elem.getAttribute || elem._no_rewrite || elem['_' + name]) {\\n return changed;\\n }\\n\\n var value = this.wb_getAttribute.call(elem, name);\\n\\n if (!value || this.startsWith(value, 'javascript:')) return changed;\\n\\n var new_value = this.performAttributeRewrite(elem, name, value, absUrlOnly);\\n\\n if (new_value !== value) {\\n this.removeWBOSRC(elem);\\n this.wb_setAttribute.call(elem, name, new_value);\\n changed = true;\\n }\\n\\n return changed;\\n };\\n\\n /**\\n * {@link rewriteStyle} wrapped in a try catch\\n * @param {string|Object} style\\n * @return {string|Object|null}\\n */\\n Wombat.prototype.noExceptRewriteStyle = function(style) {\\n try {\\n return this.rewriteStyle(style);\\n } catch (e) {\\n return style;\\n }\\n };\\n\\n /**\\n * Rewrites the supplied CSS style definitions\\n * @param {string|Object} style\\n * @return {string|Object|null}\\n */\\n Wombat.prototype.rewriteStyle = function(style) {\\n if (!style) return style;\\n\\n var value = style;\\n if (typeof style === 'object') {\\n value = style.toString();\\n }\\n\\n if (typeof value === 'string') {\\n return value\\n .replace(this.STYLE_REGEX, this.styleReplacer)\\n .replace(this.IMPORT_REGEX, this.styleReplacer)\\n .replace(this.no_wombatRe, '');\\n }\\n\\n return value;\\n };\\n\\n /**\\n * Rewrites the supplied srcset string returning the rewritten results.\\n * If the element is one the srcset values are auto-fetched they are sent\\n * to the backing auto-fetch worker\\n * @param {string} value\\n * @param {Element} elem\\n * @return {string}\\n */\\n Wombat.prototype.rewriteSrcset = function(value, elem) {\\n if (!value) return '';\\n\\n var split = value.split(this.srcsetRe);\\n var values = [];\\n var mod = this.rwModForElement(elem, 'srcset');\\n for (var i = 0; i < split.length; i++) {\\n // Filter removes non-truthy values like null, undefined, and \\\"\\\"\\n var v = split[i];\\n if (v) {\\n var parts = v.trim().split(' ');\\n parts[0] = this.rewriteUrl(parts[0], true, mod);\\n values.push(parts.join(' '));\\n }\\n }\\n\\n if (\\n this.wbUseAFWorker &&\\n this.WBAutoFetchWorker &&\\n this.isSavedSrcSrcset(elem)\\n ) {\\n // send post split values to preservation worker\\n this.WBAutoFetchWorker.preserveSrcset(\\n values,\\n this.WBAutoFetchWorker.rwMod(elem)\\n );\\n }\\n\\n return values.join(', ');\\n };\\n\\n /**\\n * Rewrites the URL supplied to the setter of an (i)frame's src attribute\\n * @param {Element} elem\\n * @param {string} attrName\\n * @return {boolean}\\n */\\n Wombat.prototype.rewriteFrameSrc = function(elem, attrName) {\\n var value = this.wb_getAttribute.call(elem, attrName);\\n var new_value;\\n\\n // special case for rewriting javascript: urls that contain WB_wombat_\\n // must insert _wombat init first!\\n if (this.startsWith(value, 'javascript:')) {\\n if (value.indexOf('WB_wombat_') >= 0) {\\n var JS = 'javascript:';\\n new_value =\\n JS +\\n 'window.parent._wb_wombat.initNewWindowWombat(window);' +\\n value.substr(JS.length);\\n }\\n }\\n\\n if (!new_value) {\\n new_value = this.rewriteUrl(\\n value,\\n false,\\n this.rwModForElement(elem, attrName)\\n );\\n }\\n\\n if (new_value !== value) {\\n this.wb_setAttribute.call(elem, attrName, new_value);\\n return true;\\n }\\n\\n return false;\\n };\\n\\n /**\\n * Rewrites either the URL contained in the src attribute or the text contents\\n * of the supplied script element. Returns T/F indicating if a rewrite occurred\\n * @param elem\\n * @return {boolean}\\n */\\n Wombat.prototype.rewriteScript = function(elem) {\\n if (elem.hasAttribute('src') || !elem.textContent || !this.$wbwindow.Proxy) {\\n return this.rewriteAttr(elem, 'src');\\n }\\n if (this.skipWrapScriptBasedOnType(elem.type)) return false;\\n var text = elem.textContent.trim();\\n if (this.skipWrapScriptTextBasedOnText(text)) return false;\\n elem.textContent = this.wrapScriptTextJsProxy(text);\\n return true;\\n };\\n\\n /**\\n * Rewrites the supplied SVG element returning T/F indicating if a rewrite occurred\\n * @param {SVGElement} elem\\n * @return {boolean}\\n */\\n Wombat.prototype.rewriteSVGElem = function(elem) {\\n var changed = this.rewriteAttr(elem, 'filter');\\n changed = this.rewriteAttr(elem, 'style') || changed;\\n // xlink:href is deprecated since SVG 2 in favor of href\\n // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href\\n changed = this.rewriteAttr(elem, 'xlink:href') || changed;\\n changed = this.rewriteAttr(elem, 'href') || changed;\\n changed = this.rewriteAttr(elem, 'src') || changed;\\n return changed;\\n };\\n\\n /**\\n * Rewrites the supplied element returning T/F indicating if a rewrite occurred\\n * @param {Element|Node} elem - The element to be rewritten\\n * @return {boolean}\\n */\\n Wombat.prototype.rewriteElem = function(elem) {\\n var changed = false;\\n if (!elem) return changed;\\n if (elem instanceof SVGElement) {\\n changed = this.rewriteSVGElem(elem);\\n } else {\\n switch (elem.tagName) {\\n case 'META':\\n var maybeCSP = this.wb_getAttribute.call(elem, 'http-equiv');\\n if (maybeCSP && maybeCSP.toLowerCase() === 'content-security-policy') {\\n this.wb_setAttribute.call(elem, 'http-equiv', '_' + maybeCSP);\\n changed = true;\\n }\\n break;\\n case 'STYLE':\\n var new_content = this.rewriteStyle(elem.textContent);\\n if (elem.textContent !== new_content) {\\n elem.textContent = new_content;\\n changed = true;\\n if (\\n this.wbUseAFWorker &&\\n this.WBAutoFetchWorker &&\\n elem.sheet != null\\n ) {\\n // we have a stylesheet so lets be nice to UI thread\\n // and defer extraction\\n this.WBAutoFetchWorker.deferredSheetExtraction(elem.sheet);\\n }\\n }\\n break;\\n case 'LINK':\\n changed = this.rewriteAttr(elem, 'href');\\n if (this.wbUseAFWorker && elem.rel === 'stylesheet') {\\n // we can only check link[rel='stylesheet'] when it loads\\n this._addEventListener(\\n elem,\\n 'load',\\n this.utilFns.wbSheetMediaQChecker\\n );\\n }\\n break;\\n case 'IMG':\\n changed = this.rewriteAttr(elem, 'src');\\n changed = this.rewriteAttr(elem, 'srcset') || changed;\\n changed = this.rewriteAttr(elem, 'style') || changed;\\n if (\\n this.wbUseAFWorker &&\\n this.WBAutoFetchWorker &&\\n elem.dataset.srcset\\n ) {\\n this.WBAutoFetchWorker.preserveDataSrcset(elem);\\n }\\n break;\\n case 'OBJECT':\\n if (this.wb_info.isSW && elem.parentElement && elem.getAttribute('type') === 'application/pdf') {\\n var iframe = this.$wbwindow.document.createElement('IFRAME');\\n for (var i = 0; i < elem.attributes.length; i++) {\\n var attr = elem.attributes[i];\\n var name = attr.name;\\n if (name === 'data') {\\n name = 'src';\\n }\\n this.wb_setAttribute.call(iframe, name, attr.value);\\n }\\n\\n elem.parentElement.replaceChild(iframe, elem);\\n changed = true;\\n break;\\n }\\n\\n changed = this.rewriteAttr(elem, 'data', true);\\n changed = this.rewriteAttr(elem, 'style') || changed;\\n break;\\n case 'FORM':\\n changed = this.rewriteAttr(elem, 'poster');\\n changed = this.rewriteAttr(elem, 'action') || changed;\\n changed = this.rewriteAttr(elem, 'style') || changed;\\n break;\\n case 'IFRAME':\\n changed = this.rewriteFrameSrc(elem, 'src');\\n if (this.wb_info.isSW && !changed) {\\n var srcdoc = elem.getAttribute('srcdoc');\\n if (elem.hasAttribute('srcdoc')) {\\n elem.removeAttribute('srcdoc');\\n }\\n if (srcdoc) {\\n this.blobUrlForIframe(elem, srcdoc);\\n } else {\\n var src = elem.getAttribute('src');\\n if (!src || src === 'about:blank') {\\n if (!src) {\\n elem.__WB_blank = true;\\n }\\n elem.src = this.wb_info.prefix + this.wb_info.request_ts + 'mp_/about:blank';\\n }\\n }\\n }\\n changed = this.rewriteAttr(elem, 'style') || changed;\\n break;\\n case 'FRAME':\\n changed = this.rewriteFrameSrc(elem, 'src');\\n changed = this.rewriteAttr(elem, 'style') || changed;\\n break;\\n case 'SCRIPT':\\n changed = this.rewriteScript(elem);\\n break;\\n case 'A':\\n changed = this.rewriteAttr(elem, 'href') || changed;\\n if (elem.hasAttribute('target')) {\\n var newTarget = this.rewriteAttrTarget(elem.target);\\n if (newTarget !== elem.target) {\\n elem.target = newTarget;\\n changed = true;\\n }\\n }\\n break;\\n\\n default: {\\n changed = this.rewriteAttr(elem, 'src');\\n changed = this.rewriteAttr(elem, 'srcset') || changed;\\n changed = this.rewriteAttr(elem, 'href') || changed;\\n changed = this.rewriteAttr(elem, 'style') || changed;\\n changed = this.rewriteAttr(elem, 'poster') || changed;\\n break;\\n }\\n }\\n }\\n\\n if (elem.hasAttribute && elem.removeAttribute) {\\n if (elem.hasAttribute('crossorigin')) {\\n elem.removeAttribute('crossorigin');\\n changed = true;\\n }\\n\\n if (elem.hasAttribute('integrity')) {\\n elem.removeAttribute('integrity');\\n changed = true;\\n }\\n }\\n return changed;\\n };\\n\\n /**\\n * Rewrites all the children and there descendants of the supplied Node\\n * returning T/F if a rewrite occurred\\n * @param {Node} curr\\n * @return {boolean}\\n */\\n Wombat.prototype.recurseRewriteElem = function(curr) {\\n if (!this.nodeHasChildren(curr)) return false;\\n var changed = false;\\n var rewriteQ = [curr.children || curr.childNodes];\\n\\n while (rewriteQ.length > 0) {\\n var children = rewriteQ.shift();\\n for (var i = 0; i < children.length; i++) {\\n var child = children[i];\\n if (child.nodeType === Node.ELEMENT_NODE) {\\n changed = this.rewriteElem(child) || changed;\\n if (this.nodeHasChildren(child)) {\\n rewriteQ.push(child.children || child.childNodes);\\n }\\n }\\n }\\n }\\n\\n return changed;\\n };\\n\\n /**\\n * Rewrites the supplied element and all its children if any.\\n * See {@link rewriteElem} and {@link recurseRewriteElem} for more details\\n * @param {Node} elem\\n * @return {boolean}\\n */\\n Wombat.prototype.rewriteElemComplete = function(elem) {\\n if (!elem) return false;\\n var changed = this.rewriteElem(elem);\\n var changedRecursively = this.recurseRewriteElem(elem);\\n return changed || changedRecursively;\\n };\\n\\n /**\\n * Rewrites any elements found in the supplied arguments object returning\\n * a new array containing the original contents of the supplied arguments\\n * object after rewriting.\\n * @param {Object} originalArguments\\n * @return {Array<*>}\\n */\\n Wombat.prototype.rewriteElementsInArguments = function(originalArguments) {\\n var argArr = new Array(originalArguments.length);\\n for (var i = 0; i < originalArguments.length; i++) {\\n var argElem = originalArguments[i];\\n if (argElem instanceof Node) {\\n this.rewriteElemComplete(argElem);\\n argArr[i] = argElem;\\n } else if (typeof argElem === 'string') {\\n argArr[i] = this.rewriteHtml(argElem);\\n } else {\\n argArr[i] = argElem;\\n }\\n }\\n return argArr;\\n };\\n\\n /**\\n * Rewrites the supplied string containing HTML, if the supplied string\\n * is full HTML (starts with ' + rwString + '',\\n 'text/html'\\n );\\n\\n if (\\n !inner_doc ||\\n !this.nodeHasChildren(inner_doc.head) ||\\n !inner_doc.head.children[0].content\\n ) {\\n return rwString;\\n }\\n\\n var template = inner_doc.head.children[0];\\n template._no_rewrite = true;\\n if (this.recurseRewriteElem(template.content)) {\\n var new_html = template.innerHTML;\\n if (checkEndTag) {\\n var first_elem =\\n template.content.children && template.content.children[0];\\n if (first_elem) {\\n var end_tag = '' + first_elem.tagName.toLowerCase() + '>';\\n if (\\n this.endsWith(new_html, end_tag) &&\\n !this.endsWith(rwString.toLowerCase(), end_tag)\\n ) {\\n new_html = new_html.substring(0, new_html.length - end_tag.length);\\n }\\n } else if (rwString[0] !== '<' || rwString[rwString.length - 1] !== '>') {\\n this.write_buff += rwString;\\n return undefined;\\n }\\n }\\n return new_html;\\n }\\n\\n return rwString;\\n };\\n\\n /**\\n * Rewrites the supplied string containing full HTML\\n * @param {string} string\\n * @param {boolean} [checkEndTag]\\n * @return {?string}\\n */\\n Wombat.prototype.rewriteHtmlFull = function(string, checkEndTag) {\\n var inner_doc = new DOMParser().parseFromString(string, 'text/html');\\n if (!inner_doc) return string;\\n\\n var changed = false;\\n\\n for (var i = 0; i < inner_doc.all.length; i++) {\\n changed = this.rewriteElem(inner_doc.all[i]) || changed;\\n }\\n\\n if (changed) {\\n var new_html;\\n // if original had tag, add full document HTML\\n if (string && string.indexOf('= 0) {\\n inner_doc.documentElement._no_rewrite = true;\\n new_html =\\n this.reconstructDocType(inner_doc.doctype) +\\n inner_doc.documentElement.outerHTML;\\n } else {\\n //\\n inner_doc.head._no_rewrite = true;\\n inner_doc.body._no_rewrite = true;\\n // hasChildNodes includes text nodes\\n var headHasKids = this.nodeHasChildren(inner_doc.head);\\n var bodyHasKids = this.nodeHasChildren(inner_doc.body);\\n new_html =\\n (headHasKids ? inner_doc.head.outerHTML : '') +\\n (bodyHasKids ? inner_doc.body.outerHTML : '');\\n if (checkEndTag) {\\n if (inner_doc.all.length > 3) {\\n var end_tag = '' + inner_doc.all[3].tagName.toLowerCase() + '>';\\n if (\\n this.endsWith(new_html, end_tag) &&\\n !this.endsWith(string.toLowerCase(), end_tag)\\n ) {\\n new_html = new_html.substring(0, new_html.length - end_tag.length);\\n }\\n } else if (string[0] !== '<' || string[string.length - 1] !== '>') {\\n this.write_buff += string;\\n return;\\n }\\n }\\n new_html = this.reconstructDocType(inner_doc.doctype) + new_html;\\n }\\n\\n return new_html;\\n }\\n\\n return string;\\n };\\n\\n /**\\n * Rewrites a CSS style string found in the style property of an element or\\n * FontFace\\n * @param {string} orig\\n * @return {string}\\n */\\n Wombat.prototype.rewriteInlineStyle = function(orig) {\\n var decoded;\\n\\n try {\\n decoded = decodeURIComponent(orig);\\n } catch (e) {\\n decoded = orig;\\n }\\n\\n if (decoded !== orig) {\\n var parts = this.rewriteStyle(decoded).split(',', 2);\\n return parts[0] + ',' + encodeURIComponent(parts[1]);\\n }\\n\\n return this.rewriteStyle(orig);\\n };\\n\\n /**\\n * Rewrites the supplied cookie\\n * @param {string} cookie\\n * @return {string}\\n */\\n Wombat.prototype.rewriteCookie = function(cookie) {\\n var wombat = this;\\n var rwCookie = cookie\\n .replace(this.wb_abs_prefix, '')\\n .replace(this.wb_rel_prefix, '');\\n rwCookie = rwCookie\\n .replace(this.cookie_domain_regex, function(m, m1) {\\n // rewrite domain\\n var message = {\\n domain: m1,\\n cookie: rwCookie,\\n wb_type: 'cookie'\\n };\\n\\n // notify of cookie setting to allow server-side tracking\\n wombat.sendTopMessage(message, true);\\n\\n // if no subdomain, eg. \\\"localhost\\\", just remove domain altogether\\n if (\\n wombat.$wbwindow.location.hostname.indexOf('.') >= 0 &&\\n !wombat.IP_RX.test(wombat.$wbwindow.location.hostname)\\n ) {\\n return 'Domain=.' + wombat.$wbwindow.location.hostname;\\n }\\n return '';\\n })\\n .replace(this.cookie_path_regex, function(m, m1) {\\n // rewrite path\\n var rewritten = wombat.rewriteUrl(m1);\\n\\n if (rewritten.indexOf(wombat.wb_curr_host) === 0) {\\n rewritten = rewritten.substring(wombat.wb_curr_host.length);\\n }\\n\\n return 'Path=' + rewritten;\\n });\\n\\n // rewrite secure, if needed\\n if (wombat.$wbwindow.location.protocol !== 'https:') {\\n rwCookie = rwCookie.replace('secure', '');\\n }\\n\\n return rwCookie.replace(',|', ',');\\n };\\n\\n /**\\n * Rewrites the supplied web worker URL\\n * @param {string} workerUrl\\n * @return {string}\\n */\\n Wombat.prototype.rewriteWorker = function(workerUrl) {\\n if (!workerUrl) return workerUrl;\\n workerUrl = workerUrl.toString();\\n var isBlob = workerUrl.indexOf('blob:') === 0;\\n var isJS = workerUrl.indexOf('javascript:') === 0;\\n if (!isBlob && !isJS) {\\n if (\\n !this.startsWithOneOf(workerUrl, this.VALID_PREFIXES) &&\\n !this.startsWith(workerUrl, '/') &&\\n !this.startsWithOneOf(workerUrl, this.BAD_PREFIXES)\\n ) {\\n // super relative url assets/js/xyz.js\\n var rurl = this.resolveRelUrl(workerUrl, this.$wbwindow.document);\\n return this.rewriteUrl(rurl, false, 'wkr_', this.$wbwindow.document);\\n }\\n return this.rewriteUrl(workerUrl, false, 'wkr_', this.$wbwindow.document);\\n }\\n\\n var workerCode = isJS ? workerUrl.replace('javascript:', '') : null;\\n if (isBlob) {\\n // fetching only skipped if it was JS url\\n var x = new XMLHttpRequest();\\n // use sync ajax request to get the contents, remove postMessage() rewriting\\n this.utilFns.XHRopen.call(x, 'GET', workerUrl, false);\\n this.utilFns.XHRsend.call(x);\\n workerCode = x.responseText\\n .replace(this.workerBlobRe, '')\\n // resolving blobs hit our sever side rewriting so we gotta\\n // ensure we good\\n .replace(this.rmCheckThisInjectRe, 'this');\\n }\\n\\n if (this.wb_info.static_prefix || this.wb_info.ww_rw_script) {\\n var originalURL = this.$wbwindow.document.baseURI;\\n // if we are here we can must return blob so set makeBlob to true\\n var ww_rw =\\n this.wb_info.ww_rw_script ||\\n this.wb_info.static_prefix + 'wombatWorkers.js';\\n var rw =\\n '(function() { self.importScripts(\\\\'' +\\n ww_rw +\\n '\\\\'); new WBWombat({\\\\'prefix\\\\': \\\\'' +\\n this.wb_abs_prefix +\\n '\\\\', \\\\'prefixMod\\\\': \\\\'' +\\n this.wb_abs_prefix +\\n 'wkrf_/\\\\', \\\\'originalURL\\\\': \\\\'' +\\n originalURL +\\n '\\\\'}); })();';\\n\\n workerCode = rw + workerCode;\\n }\\n var blob = new Blob([workerCode], { type: 'application/javascript' });\\n return URL.createObjectURL(blob);\\n };\\n\\n /**\\n * Rewrite the arguments supplied to a function of the Text interface in order\\n * to ensure CSS is rewritten when a text node is the child of the style tag\\n * @param {Object} fnThis\\n * @param {function} originalFn\\n * @param {Object} argsObj\\n */\\n Wombat.prototype.rewriteTextNodeFn = function(fnThis, originalFn, argsObj) {\\n var deproxiedThis = this.proxyToObj(fnThis);\\n var args;\\n if (\\n argsObj.length > 0 &&\\n deproxiedThis.parentElement &&\\n deproxiedThis.parentElement.tagName === 'STYLE'\\n ) {\\n // appendData(DOMString data); dataIndex = 0\\n // insertData(unsigned long offset, DOMString data); dataIndex = 1\\n // replaceData(unsigned long offset, unsigned long count, DOMString data); dataIndex = 2\\n args = new Array(argsObj.length);\\n var dataIndex = argsObj.length - 1;\\n if (dataIndex === 2) {\\n args[0] = argsObj[0];\\n args[1] = argsObj[1];\\n } else if (dataIndex === 1) {\\n args[0] = argsObj[0];\\n }\\n args[dataIndex] = this.rewriteStyle(argsObj[dataIndex]);\\n } else {\\n args = argsObj;\\n }\\n if (originalFn.__WB_orig_apply) {\\n return originalFn.__WB_orig_apply(deproxiedThis, args);\\n }\\n return originalFn.apply(deproxiedThis, args);\\n };\\n\\n /**\\n * Rewrite the arguments supplied to a function of the ChildNode interface\\n * in order to ensure that elements are rewritten\\n * @param {Object} fnThis\\n * @param {function} originalFn\\n * @param {Object} argsObj\\n */\\n Wombat.prototype.rewriteChildNodeFn = function(fnThis, originalFn, argsObj) {\\n var thisObj = this.proxyToObj(fnThis);\\n if (argsObj.length === 0) return originalFn.call(thisObj);\\n var newArgs = this.rewriteElementsInArguments(argsObj);\\n if (originalFn.__WB_orig_apply) {\\n return originalFn.__WB_orig_apply(thisObj, newArgs);\\n }\\n return originalFn.apply(thisObj, newArgs);\\n };\\n\\n /**\\n * Rewrites the arguments supplied to Element.[insertAdjacentElement, insertAdjacentHTML].\\n * If rwHTML is true the rewrite performed is done by {@link rewriteHtml} other wise\\n * {@link rewriteElemComplete}\\n * @param {Object} fnThis\\n * @param {function} originalFn\\n * @param {number} position\\n * @param {string|Node} textOrElem\\n * @param {boolean} rwHTML\\n * @return {*}\\n */\\n Wombat.prototype.rewriteInsertAdjHTMLOrElemArgs = function(\\n fnThis,\\n originalFn,\\n position,\\n textOrElem,\\n rwHTML\\n ) {\\n var fnThisObj = this.proxyToObj(fnThis);\\n if (fnThisObj._no_rewrite) {\\n return originalFn.call(fnThisObj, position, textOrElem);\\n }\\n if (rwHTML) {\\n return originalFn.call(fnThisObj, position, this.rewriteHtml(textOrElem));\\n }\\n this.rewriteElemComplete(textOrElem);\\n return originalFn.call(fnThisObj, position, textOrElem);\\n };\\n\\n /**\\n * Rewrites the arguments of either setTimeout or setInterval because\\n * [setTimeout|setInterval]('document.location.href = \\\"xyz.com\\\"', time)\\n * is legal and used\\n * @param {Object} fnThis\\n * @param {function} originalFn\\n * @param {Object} argsObj\\n * @return {*}\\n */\\n Wombat.prototype.rewriteSetTimeoutInterval = function(\\n fnThis,\\n originalFn,\\n argsObj\\n ) {\\n // strings are primitives with a prototype or __proto__ of String depending on the browser\\n var rw = this.isString(argsObj[0]);\\n // do not mess with the arguments object unless you want instant de-optimization\\n var args = rw ? new Array(argsObj.length) : argsObj;\\n if (rw) {\\n if (this.$wbwindow.Proxy) {\\n args[0] = this.wrapScriptTextJsProxy(argsObj[0]);\\n } else {\\n args[0] = argsObj[0].replace(/\\\\blocation\\\\b/g, 'WB_wombat_$&');\\n }\\n for (var i = 1; i < argsObj.length; ++i) {\\n args[i] = this.proxyToObj(argsObj[i]);\\n }\\n }\\n // setTimeout|setInterval does not require its this arg to be window so just in case\\n // someone got funky with it\\n var thisObj = this.proxyToObj(fnThis);\\n if (originalFn.__WB_orig_apply) {\\n return originalFn.__WB_orig_apply(thisObj, args);\\n }\\n return originalFn.apply(thisObj, args);\\n };\\n\\n /**\\n * Rewrites the value of used in to set SomeElement.[innerHTML|outerHTML]\\n * iframe.srcdoc, or style.textContent handling edge cases e.g. script tags.\\n *\\n * If the element is a style tag and it has a sheet after the new value is set\\n * it, the sheet, is checked for media rules.\\n *\\n * @param {Object} thisObj\\n * @param {Function} oSetter\\n * @param {?string} newValue\\n */\\n Wombat.prototype.rewriteHTMLAssign = function(thisObj, oSetter, newValue) {\\n var res = newValue;\\n var tagName = thisObj.tagName;\\n if (!thisObj._no_rewrite && !(thisObj instanceof this.$wbwindow.HTMLTemplateElement)) {\\n if (tagName === 'STYLE') {\\n res = this.rewriteStyle(newValue);\\n } else if (tagName === 'SCRIPT') {\\n // script tags are used to hold HTML for later use\\n // check if this contains tags or a script\\n\\n if (newValue && this.IsTagRegex.test(newValue)) {\\n res = this.rewriteHtml(newValue);\\n }\\n\\n // likely actual JS, not tags\\n if (res === newValue) {\\n if (\\n !this.skipWrapScriptBasedOnType(thisObj.type) &&\\n !this.skipWrapScriptTextBasedOnText(newValue)\\n ) {\\n res = this.wrapScriptTextJsProxy(res);\\n }\\n }\\n } else {\\n res = this.rewriteHtml(newValue);\\n }\\n }\\n oSetter.call(thisObj, res);\\n if (\\n this.wbUseAFWorker &&\\n this.WBAutoFetchWorker &&\\n tagName === 'STYLE' &&\\n thisObj.sheet != null\\n ) {\\n // got to preserve all the things\\n this.WBAutoFetchWorker.deferredSheetExtraction(thisObj.sheet);\\n }\\n };\\n\\n /**\\n * Rewrites the value to be supplied to eval or our injected wrapper\\n * @param {Function} rawEvalOrWrapper\\n * @param {*} evalArg\\n * @return {*}\\n */\\n Wombat.prototype.rewriteEvalArg = function(rawEvalOrWrapper, evalArg, extraArg) {\\n var toBeEvald =\\n this.isString(evalArg) && !this.skipWrapScriptTextBasedOnText(evalArg)\\n ? this.wrapScriptTextJsProxy(evalArg)\\n : this.otherEvalRewrite(evalArg);\\n return rawEvalOrWrapper(toBeEvald, extraArg);\\n };\\n\\n /**\\n * Apply other eval specific rewriting\\n * Currently just rewrite import('')\\n *\\n */\\n\\n Wombat.prototype.otherEvalRewrite = function(value) {\\n if (typeof(value) !== 'string') {\\n return value;\\n }\\n return value.replace(this.IMPORT_JS_REGEX, this.styleReplacer);\\n };\\n\\n /**\\n * Applies an Event property getter override for the supplied property\\n * @param {string} attr\\n * @param {Object} [eventProto]\\n */\\n Wombat.prototype.addEventOverride = function(attr, eventProto) {\\n var theProto = eventProto;\\n if (!eventProto) {\\n theProto = this.$wbwindow.MessageEvent.prototype;\\n }\\n var origGetter = this.getOrigGetter(theProto, attr);\\n if (!origGetter) return;\\n this.defGetterProp(theProto, attr, function() {\\n if (this['_' + attr] != null) {\\n return this['_' + attr];\\n }\\n return origGetter.call(this);\\n });\\n };\\n\\n /**\\n * Returns T/F indicating if the supplied attribute node is to be rewritten\\n * @param {Object} attr\\n * @return {boolean}\\n */\\n Wombat.prototype.isAttrObjRewrite = function(attr) {\\n if (!attr) return false;\\n var tagName = attr.ownerElement && attr.ownerElement.tagName;\\n return this.shouldRewriteAttr(tagName, attr.nodeName);\\n };\\n\\n /**\\n * Defines a new getter and setter function for the supplied\\n * property of the Attr interface\\n * @param {Object} attrProto\\n * @param {string} prop\\n */\\n Wombat.prototype.newAttrObjGetSet = function(attrProto, prop) {\\n var wombat = this;\\n var oGetter = this.getOrigGetter(attrProto, prop);\\n var oSetter = this.getOrigSetter(attrProto, prop);\\n this.defProp(\\n attrProto,\\n prop,\\n function newAttrObjSetter(newValue) {\\n var obj = wombat.proxyToObj(this);\\n var res = newValue;\\n if (wombat.isAttrObjRewrite(obj)) {\\n res = wombat.performAttributeRewrite(\\n obj.ownerElement,\\n obj.name,\\n newValue,\\n false\\n );\\n }\\n return oSetter.call(obj, res);\\n },\\n function newAttrObjGetter() {\\n var obj = wombat.proxyToObj(this);\\n var res = oGetter.call(obj);\\n if (wombat.isAttrObjRewrite(obj)) {\\n return wombat.extractOriginalURL(res);\\n }\\n return res;\\n }\\n );\\n };\\n\\n /**\\n * Overrides the nodeValue property of the Attr interface\\n */\\n Wombat.prototype.overrideAttrProps = function() {\\n var attrProto = this.$wbwindow.Attr.prototype;\\n this.newAttrObjGetSet(attrProto, 'value');\\n this.newAttrObjGetSet(attrProto, 'nodeValue');\\n this.newAttrObjGetSet(attrProto, 'textContent');\\n };\\n\\n /**\\n * Applies an override the attribute get/set override\\n * @param {Object} obj\\n * @param {string} attr\\n * @param {string} mod\\n */\\n Wombat.prototype.overrideAttr = function(obj, attr, mod) {\\n var orig_getter = this.getOrigGetter(obj, attr);\\n var orig_setter = this.getOrigSetter(obj, attr);\\n var wombat = this;\\n\\n var setter = function newAttrPropSetter(orig) {\\n if (mod === 'js_' && !this.__$removedWBOSRC$__) {\\n wombat.removeWBOSRC(this);\\n }\\n var val = wombat.rewriteUrl(orig, false, mod);\\n if (orig_setter) {\\n return orig_setter.call(this, val);\\n } else if (wombat.wb_setAttribute) {\\n return wombat.wb_setAttribute.call(this, attr, val);\\n }\\n };\\n\\n var getter = function newAttrPropGetter() {\\n var res;\\n if (orig_getter) {\\n res = orig_getter.call(this);\\n } else if (wombat.wb_getAttribute) {\\n res = wombat.wb_getAttribute.call(this, attr);\\n }\\n res = wombat.extractOriginalURL(res);\\n if (this.__WB_blank && res === 'about:blank') {\\n return '';\\n }\\n return res;\\n };\\n\\n this.defProp(obj, attr, setter, getter);\\n };\\n\\n /**\\n * Applies an attribute getter override IFF an original getter exists\\n * @param {Object} proto\\n * @param {string} prop\\n * @param {*} [cond]\\n */\\n Wombat.prototype.overridePropExtract = function(proto, prop) {\\n var orig_getter = this.getOrigGetter(proto, prop);\\n var wombat = this;\\n if (orig_getter) {\\n var new_getter = function () {\\n var obj = wombat.proxyToObj(this);\\n var res = orig_getter.call(obj);\\n return wombat.extractOriginalURL(res);\\n };\\n this.defGetterProp(proto, prop, new_getter);\\n }\\n };\\n\\n\\n /**\\n * Overrides referrer -- if top-replay frame, referrer should be \\\"\\\", otherwise extractOriginURL\\n * @param {Object} proto\\n * @param {string} prop\\n * @param {*} [cond]\\n */\\n Wombat.prototype.overrideReferrer = function($document) {\\n var orig_getter = this.getOrigGetter($document, 'referrer');\\n var wombat = this;\\n if (orig_getter) {\\n var new_getter = function() {\\n var obj = wombat.proxyToObj(this);\\n\\n var $win = this.defaultView;\\n\\n // if top replay-frame, referrer should always be \\\"\\\"\\n if ($win === $win.__WB_replay_top) {\\n return '';\\n }\\n\\n var res = orig_getter.call(obj);\\n\\n return wombat.extractOriginalURL(res);\\n };\\n this.defGetterProp($document, 'referrer', new_getter);\\n }\\n };\\n\\n\\n /**\\n * Applies an attribute getter override IFF an original getter exists that\\n * ensures that the results of retrieving the attributes value is not a\\n * wombat Proxy\\n * @param {Object} proto\\n * @param {string} prop\\n */\\n Wombat.prototype.overridePropToProxy = function(proto, prop) {\\n var orig_getter = this.getOrigGetter(proto, prop);\\n if (orig_getter) {\\n var wombat = this;\\n var new_getter = function overridePropToProxyNewGetter() {\\n return wombat.objToProxy(orig_getter.call(this));\\n };\\n this.defGetterProp(proto, prop, new_getter);\\n }\\n };\\n\\n /**\\n * Applies an override to supplied history function name IFF it exists\\n * @param {string} funcName\\n * @return {?function}\\n */\\n Wombat.prototype.overrideHistoryFunc = function(funcName) {\\n if (!this.$wbwindow.history) return undefined;\\n var orig_func = this.$wbwindow.history[funcName];\\n if (!orig_func) return undefined;\\n\\n this.$wbwindow.history['_orig_' + funcName] = orig_func;\\n\\n this.$wbwindow.history.___wb_ownWindow = this.$wbwindow;\\n\\n var wombat = this;\\n\\n var rewrittenFunc = function histNewFunc(stateObj, title, url) {\\n // in case functions rebound to different history obj!\\n var historyWin = this.___wb_ownWindow || wombat.$wbwindow;\\n\\n var wombatLocation = historyWin.WB_wombat_location;\\n var rewritten_url;\\n var resolvedURL;\\n if (url) {\\n var parser = wombat._makeURLParser(url, historyWin.document);\\n resolvedURL = parser.href;\\n\\n rewritten_url = wombat.rewriteUrl(resolvedURL);\\n\\n if (\\n resolvedURL !== wombatLocation.origin &&\\n wombatLocation.href !== 'about:blank' &&\\n !wombat.startsWith(resolvedURL, wombatLocation.origin + '/')\\n ) {\\n throw new DOMException('Invalid history change: ' + resolvedURL);\\n }\\n } else {\\n resolvedURL = wombatLocation.href;\\n }\\n\\n orig_func.call(this, stateObj, title, rewritten_url);\\n\\n var origTitle = historyWin.document.title;\\n\\n if (wombat.WBAutoFetchWorker) {\\n historyWin.setTimeout(function() {\\n if (!title && historyWin.document.title !== origTitle) {\\n title = historyWin.document.title;\\n }\\n\\n wombat.WBAutoFetchWorker.fetchAsPage(rewritten_url, resolvedURL, title);\\n }, 100);\\n }\\n\\n wombat.sendHistoryUpdate(resolvedURL, title, historyWin);\\n };\\n\\n this.$wbwindow.history[funcName] = rewrittenFunc;\\n if (this.$wbwindow.History && this.$wbwindow.History.prototype) {\\n this.$wbwindow.History.prototype[funcName] = rewrittenFunc;\\n }\\n\\n return rewrittenFunc;\\n };\\n\\n /**\\n * Applies an getter/setter override to the supplied style interface's attribute\\n * and prop name combination\\n * @param {Object} obj\\n * @param {string} attr\\n * @param {string} [propName]\\n */\\n Wombat.prototype.overrideStyleAttr = function(obj, attr, propName) {\\n var orig_getter = this.getOrigGetter(obj, attr);\\n var orig_setter = this.getOrigSetter(obj, attr);\\n\\n var wombat = this;\\n\\n var setter = function overrideStyleAttrSetter(orig) {\\n var val = wombat.rewriteStyle(orig);\\n if (orig_setter) {\\n orig_setter.call(this, val);\\n } else {\\n this.setProperty(propName, val);\\n }\\n return val;\\n };\\n\\n var getter = orig_getter;\\n\\n var extractUrl = function (_, p1, p2, p3, p4) {\\n return p1 + (p2 || '') + wombat.extractOriginalURL(p3) + p4;\\n };\\n\\n var EXTRACT_URL_RX = /(url\\\\()(['\\\"])?(.*?)(\\\\2\\\\))/;\\n\\n if (!orig_getter) {\\n getter = function overrideStyleAttrGetter() {\\n var res = this.getPropertyValue(propName);\\n if (res && res.startsWith('url(')) {\\n res = res.replace(EXTRACT_URL_RX, extractUrl);\\n }\\n return res;\\n };\\n }\\n\\n if ((orig_setter && orig_getter) || propName) {\\n this.defProp(obj, attr, setter, getter);\\n }\\n };\\n\\n /**\\n * Applies an override to the setProperty function\\n * @param style_proto\\n */\\n Wombat.prototype.overrideStyleSetProp = function(style_proto) {\\n var orig_setProp = style_proto.setProperty;\\n var wombat = this;\\n style_proto.setProperty = function rwSetProperty(name, value, priority) {\\n var rwvalue = wombat.rewriteStyle(value);\\n return orig_setProp.call(this, name, rwvalue, priority);\\n };\\n };\\n\\n /**\\n * Overrides the getter and setter functions for the properties listed in\\n * {@link Wombat#URL_PROPS} for the `a` and `area` tags\\n * @param {Object} whichObj\\n */\\n Wombat.prototype.overrideAnchorAreaElem = function(whichObj) {\\n if (!whichObj || !whichObj.prototype) return;\\n var originalGetSets = {};\\n var originalProto = whichObj.prototype;\\n\\n var anchorAreaSetter = function anchorAreaSetter(prop, value) {\\n var func = originalGetSets['set_' + prop];\\n if (func) return func.call(this, value);\\n return '';\\n };\\n\\n var anchorAreaGetter = function anchorAreaGetter(prop) {\\n var func = originalGetSets['get_' + prop];\\n if (func) return func.call(this);\\n return '';\\n };\\n\\n for (var i = 0; i < this.URL_PROPS.length; i++) {\\n var prop = this.URL_PROPS[i];\\n originalGetSets['get_' + prop] = this.getOrigGetter(originalProto, prop);\\n originalGetSets['set_' + prop] = this.getOrigSetter(originalProto, prop);\\n if (Object.defineProperty) {\\n this.defProp(\\n originalProto,\\n prop,\\n this.makeSetLocProp(prop, anchorAreaSetter, anchorAreaGetter),\\n this.makeGetLocProp(prop, anchorAreaGetter),\\n true\\n );\\n }\\n }\\n\\n originalProto.toString = function toString() {\\n return this.href;\\n };\\n };\\n\\n /**\\n * Overrides the getter and setter functions for the `innerHTML` and `outerHTML`\\n * properties of the supplied element\\n * @param {Object} elem\\n * @param {string} prop\\n * @param {boolean} [rewriteGetter]\\n */\\n Wombat.prototype.overrideHtmlAssign = function(elem, prop, rewriteGetter) {\\n if (!this.$wbwindow.DOMParser || !elem || !elem.prototype) {\\n return;\\n }\\n\\n var obj = elem.prototype;\\n\\n var orig_getter = this.getOrigGetter(obj, prop);\\n var orig_setter = this.getOrigSetter(obj, prop);\\n\\n if (!orig_setter) return;\\n\\n var rewriteFn = this.rewriteHTMLAssign;\\n\\n var setter = function overrideHTMLAssignSetter(orig) {\\n return rewriteFn(this, orig_setter, orig);\\n };\\n\\n var wb_unrewrite_rx = this.wb_unrewrite_rx;\\n\\n var getter = function overrideHTMLAssignGetter() {\\n var res = orig_getter.call(this);\\n if (!this._no_rewrite) {\\n return res.replace(wb_unrewrite_rx, '');\\n }\\n return res;\\n };\\n\\n this.defProp(obj, prop, setter, rewriteGetter ? getter : orig_getter);\\n };\\n\\n Wombat.prototype.overrideHtmlAssignSrcDoc = function(elem, prop) {\\n var obj = elem.prototype;\\n\\n this.getOrigGetter(obj, prop);\\n var orig_setter = this.getOrigSetter(obj, prop);\\n\\n var wombat = this;\\n\\n var setter = function overrideSetter(orig) {\\n this.__wb_srcdoc = orig;\\n\\n if (wombat.wb_info.isSW) {\\n wombat.blobUrlForIframe(this, orig);\\n return orig;\\n } else {\\n return wombat.rewriteHTMLAssign(this, orig_setter, orig);\\n }\\n };\\n\\n var getter = function overrideGetter() {\\n return this.__wb_srcdoc;\\n };\\n\\n this.defProp(obj, prop, setter, getter);\\n };\\n\\n\\n /**\\n * Override .dataset attribute on element and wraps in a proxy that unrewrites URLs\\n */\\n Wombat.prototype.overrideDataSet = function() {\\n var obj = this.$wbwindow.HTMLElement.prototype;\\n var orig_getter = this.getOrigGetter(obj, 'dataset');\\n\\n var wombat = this;\\n\\n var getter = function wrapDataSet() {\\n var dataset = orig_getter.call(this);\\n\\n var proxy = new Proxy(dataset, {\\n get(target, prop, receiver) {\\n\\n var result = target[prop];\\n\\n if (wombat.startsWithOneOf(result, wombat.wb_prefixes)) {\\n return wombat.extractOriginalURL(result);\\n }\\n\\n return result;\\n }\\n });\\n\\n return proxy;\\n };\\n\\n this.defProp(obj, 'dataset', null, getter);\\n };\\n\\n\\n /**\\n * Override .style attribute on element and wraps in a proxy that unrewrites URLs\\n */\\n Wombat.prototype.overrideStyleProxy = function(overrideProps) {\\n var obj = this.$wbwindow.HTMLElement.prototype;\\n var orig_setter = this.getOrigSetter(obj, 'style');\\n var orig_getter = this.getOrigGetter(obj, 'style');\\n\\n var wombat = this;\\n\\n var getter = function wrapStyle() {\\n var style = orig_getter.call(this);\\n\\n var fnCache = {};\\n\\n var proxy = new Proxy(style, {\\n set(target, prop, value) {\\n if (overrideProps.includes(prop)) {\\n value = wombat.rewriteStyle(value);\\n }\\n\\n target[prop] = value;\\n return true;\\n },\\n\\n get(target, prop, receiver) {\\n var value = target[prop];\\n\\n if (typeof value === 'function' && (prop === 'setProperty' || wombat.isNativeFunction(value))) {\\n if (!fnCache[prop]) {\\n fnCache[prop] = value.bind(style);\\n }\\n return fnCache[prop];\\n }\\n\\n return value;\\n },\\n });\\n\\n return proxy;\\n };\\n\\n this.defProp(obj, 'style', orig_setter, getter);\\n };\\n\\n\\n\\n /**\\n * Overrides the getter and setter functions for the supplied property\\n * on the HTMLIFrameElement\\n * @param {string} prop\\n */\\n Wombat.prototype.overrideIframeContentAccess = function(prop) {\\n if (\\n !this.$wbwindow.HTMLIFrameElement ||\\n !this.$wbwindow.HTMLIFrameElement.prototype\\n ) {\\n return;\\n }\\n\\n var obj = this.$wbwindow.HTMLIFrameElement.prototype;\\n var orig_getter = this.getOrigGetter(obj, prop);\\n\\n if (!orig_getter) return;\\n\\n var orig_setter = this.getOrigSetter(obj, prop);\\n var wombat = this;\\n var getter = function overrideIframeContentAccessGetter() {\\n wombat.initIframeWombat(this);\\n return wombat.objToProxy(orig_getter.call(this));\\n };\\n\\n this.defProp(obj, prop, orig_setter, getter);\\n obj['_get_' + prop] = orig_getter;\\n };\\n\\n /**\\n * Applies an override to the getter function for the frames property of\\n * the supplied window in order to ensure that wombat is initialized in\\n * all frames.\\n * * @param {Window} $wbwindow\\n */\\n Wombat.prototype.overrideFramesAccess = function($wbwindow) {\\n // If $wbwindow.frames is the window itself, nothing to override\\n // This can be handled in the Obj Proxy\\n if ($wbwindow.Proxy && $wbwindow === $wbwindow.frames) {\\n return;\\n }\\n $wbwindow.__wb_frames = $wbwindow.frames;\\n var wombat = this;\\n var getter = function overrideFramesAccessGetter() {\\n for (var i = 0; i < this.__wb_frames.length; i++) {\\n try {\\n wombat.initNewWindowWombat(this.__wb_frames[i]);\\n } catch (e) {}\\n }\\n return this.__wb_frames;\\n };\\n\\n this.defGetterProp($wbwindow, 'frames', getter);\\n this.defGetterProp($wbwindow.Window.prototype, 'frames', getter);\\n };\\n\\n\\n Wombat.prototype.overrideSWAccess = function($wbwindow) {\\n if (!$wbwindow.navigator.serviceWorker || !$wbwindow.navigator.serviceWorker.controller) {\\n return;\\n }\\n\\n $wbwindow._WB_wombat_sw = $wbwindow.navigator.serviceWorker;\\n\\n\\n var overrideSW = {\\n 'controller': null,\\n 'ready': Promise.resolve({'unregister': function() {} }),\\n 'register': function() { return Promise.reject(); },\\n 'addEventListener': function() {},\\n 'removeEventListener': function() {},\\n 'onmessage': null,\\n 'oncontrollerchange': null,\\n 'getRegistrations': function() { return Promise.resolve([]); },\\n 'getRegistration': function() { return Promise.resolve(undefined); },\\n 'startMessages': function() {}\\n };\\n\\n this.defGetterProp($wbwindow.navigator, 'serviceWorker', function() { return overrideSW; });\\n };\\n\\n\\n\\n /**\\n * Overrides the supplied method in order to ensure that the `this` argument\\n * of the function is not one of the JS Proxy objects used by wombat.\\n * @param {object} cls\\n * @param {string} method\\n * @param {Object} [obj]\\n */\\n Wombat.prototype.overrideFuncThisProxyToObj = function(cls, method, obj) {\\n if (!cls) return;\\n\\n var ovrObj = obj;\\n if (!obj && cls.prototype && cls.prototype[method]) {\\n ovrObj = cls.prototype;\\n } else if (!obj && cls[method]) {\\n ovrObj = cls;\\n }\\n\\n if (!ovrObj) return;\\n\\n var wombat = this;\\n var orig = ovrObj[method];\\n ovrObj[method] = function deproxyThis() {\\n return orig.apply(wombat.proxyToObj(this), arguments);\\n };\\n };\\n\\n /**\\n * Applies an function override that ensures that the argument the supplied index\\n * is not one of the JS Proxy objects used by wombat.\\n * @param {Object} cls\\n * @param {string} method\\n * @param {number} [argumentIdx]\\n */\\n Wombat.prototype.overrideFuncArgProxyToObj = function(\\n cls,\\n method,\\n argumentIdx\\n ) {\\n if (!cls || !cls.prototype) return;\\n var argIndex = argumentIdx || 0;\\n var orig = cls.prototype[method];\\n if (!orig) return;\\n var wombat = this;\\n cls.prototype[method] = function deproxyFnArg() {\\n var args = new Array(arguments.length);\\n for (var i = 0; i < args.length; i++) {\\n if (i === argIndex) {\\n args[i] = wombat.proxyToObj(arguments[i]);\\n } else {\\n args[i] = arguments[i];\\n }\\n }\\n var thisObj = wombat.proxyToObj(this);\\n if (orig.__WB_orig_apply) {\\n return orig.__WB_orig_apply(thisObj, args);\\n }\\n return orig.apply(thisObj, args);\\n };\\n };\\n\\n /**\\n * Overrides Function.prototype.apply in order to ensure that none of the\\n * arguments of `native` functions are one of the JS Proxy objects used by wombat.\\n * @param {Window} $wbwindow\\n */\\n Wombat.prototype.overrideFunctionApply = function($wbwindow) {\\n if ($wbwindow.Function.prototype.__WB_orig_apply) {\\n return;\\n }\\n var orig_apply = $wbwindow.Function.prototype.apply;\\n $wbwindow.Function.prototype.__WB_orig_apply = orig_apply;\\n var wombat = this;\\n $wbwindow.Function.prototype.apply = function apply(obj, args) {\\n // if native function, de-proxy\\n if (wombat.isNativeFunction(this)) {\\n obj = wombat.proxyToObj(obj);\\n args = wombat.deproxyArrayHandlingArgumentsObj(args);\\n }\\n\\n return this.__WB_orig_apply(obj, args);\\n };\\n\\n this.wb_funToString.apply = orig_apply;\\n };\\n\\n\\n /**\\n * Override Function.prototype.bind to deproxy the param target\\n * in case of native functions\\n *\\n */\\n Wombat.prototype.overrideFunctionBind = function($wbwindow) {\\n if ($wbwindow.Function.prototype.__WB_orig_bind) {\\n return;\\n }\\n var orig_bind = $wbwindow.Function.prototype.bind;\\n $wbwindow.Function.prototype.__WB_orig_bind = orig_bind;\\n var wombat = this;\\n $wbwindow.Function.prototype.bind = function bind(obj) {\\n var isNative = wombat.isNativeFunction(this);\\n var result = this.__WB_orig_bind.apply(this, arguments);\\n result.__WB_is_native_func__ = isNative;\\n return result;\\n };\\n };\\n\\n\\n\\n\\n /**\\n * Overrides the getter and setter functions for the `srcset` property\\n * of the supplied Object in order to rewrite accesses and retrievals\\n * @param {Object} obj\\n * @param {string} [mod]\\n */\\n Wombat.prototype.overrideSrcsetAttr = function(obj, mod) {\\n var prop = 'srcset';\\n var orig_getter = this.getOrigGetter(obj, prop);\\n var orig_setter = this.getOrigSetter(obj, prop);\\n var wombat = this;\\n\\n var setter = function srcset(orig) {\\n var val = wombat.rewriteSrcset(orig, this);\\n if (orig_setter) {\\n return orig_setter.call(this, val);\\n } else if (wombat.wb_setAttribute) {\\n return wombat.wb_setAttribute.call(this, prop, val);\\n }\\n };\\n\\n var getter = function srcset() {\\n var res;\\n if (orig_getter) {\\n res = orig_getter.call(this);\\n } else if (wombat.wb_getAttribute) {\\n res = wombat.wb_getAttribute.call(this, prop);\\n }\\n res = wombat.extractOriginalURL(res);\\n return res;\\n };\\n\\n this.defProp(obj, prop, setter, getter);\\n };\\n\\n /**\\n * Overrides the getter and setter functions for the `href` property\\n * of the supplied Object in order to rewrite accesses and retrievals\\n * @param {Object} obj\\n * @param {string} mod\\n */\\n Wombat.prototype.overrideHrefAttr = function(obj, mod) {\\n var orig_getter = this.getOrigGetter(obj, 'href');\\n var orig_setter = this.getOrigSetter(obj, 'href');\\n\\n var wombat = this;\\n\\n var setter = function href(orig) {\\n var val;\\n if (mod === 'cs_' && orig.indexOf('data:text/css') === 0) {\\n val = wombat.rewriteInlineStyle(orig);\\n } else if (this.tagName === 'LINK') {\\n val = wombat.rewriteUrl(\\n orig,\\n false,\\n wombat.rwModForElement(this, 'href')\\n );\\n } else {\\n val = wombat.rewriteUrl(orig, false, mod, this.ownerDocument);\\n }\\n if (orig_setter) {\\n return orig_setter.call(this, val);\\n } else if (wombat.wb_setAttribute) {\\n return wombat.wb_setAttribute.call(this, 'href', val);\\n }\\n };\\n\\n var getter = function href() {\\n var res;\\n if (orig_getter) {\\n res = orig_getter.call(this);\\n } else if (wombat.wb_getAttribute) {\\n res = wombat.wb_getAttribute.call(this, 'href');\\n }\\n if (!this._no_rewrite) return wombat.extractOriginalURL(res);\\n return res;\\n };\\n\\n this.defProp(obj, 'href', setter, getter);\\n };\\n\\n /**\\n * Overrides the getter and setter functions for a property of the Text\\n * interface in order to rewrite accesses and retrievals when a text node\\n * is the child of the style tag\\n * @param {Object} textProto\\n * @param {string} whichProp\\n */\\n Wombat.prototype.overrideTextProtoGetSet = function(textProto, whichProp) {\\n var orig_getter = this.getOrigGetter(textProto, whichProp);\\n var wombat = this;\\n var setter;\\n // data, from CharacterData, is both readable and writable whereas wholeText, from Text, is not\\n if (whichProp === 'data') {\\n var orig_setter = this.getOrigSetter(textProto, whichProp);\\n setter = function rwTextProtoSetter(orig) {\\n var res = orig;\\n if (\\n !this._no_rewrite &&\\n this.parentElement &&\\n this.parentElement.tagName === 'STYLE'\\n ) {\\n res = wombat.rewriteStyle(orig);\\n }\\n return orig_setter.call(this, res);\\n };\\n }\\n var getter = function rwTextProtoGetter() {\\n var res = orig_getter.call(this);\\n if (\\n !this._no_rewrite &&\\n this.parentElement &&\\n this.parentElement.tagName === 'STYLE'\\n ) {\\n return res.replace(wombat.wb_unrewrite_rx, '');\\n }\\n return res;\\n };\\n this.defProp(textProto, whichProp, setter, getter);\\n };\\n\\n /**\\n * Overrides the constructor of an UIEvent object in order to ensure\\n * that the `view`, `relatedTarget`, and `target` arguments of the\\n * constructor are not a JS Proxy used by wombat.\\n * @param {string} which\\n */\\n Wombat.prototype.overrideAnUIEvent = function(which) {\\n var didOverrideKey = '__wb_' + which + '_overridden';\\n var ConstructorFN = this.$wbwindow[which];\\n if (\\n !ConstructorFN ||\\n !ConstructorFN.prototype ||\\n ConstructorFN.prototype[didOverrideKey]\\n )\\n return;\\n // ensure if and when view is accessed it is proxied\\n var wombat = this;\\n this.overridePropToProxy(ConstructorFN.prototype, 'view');\\n var initFNKey = 'init' + which;\\n if (ConstructorFN.prototype[initFNKey]) {\\n var originalInitFn = ConstructorFN.prototype[initFNKey];\\n ConstructorFN.prototype[initFNKey] = function() {\\n var thisObj = wombat.proxyToObj(this);\\n if (arguments.length === 0 || arguments.length < 3) {\\n if (originalInitFn.__WB_orig_apply) {\\n return originalInitFn.__WB_orig_apply(thisObj, arguments);\\n }\\n return originalInitFn.apply(thisObj, arguments);\\n }\\n var newArgs = new Array(arguments.length);\\n for (var i = 0; i < arguments.length; i++) {\\n if (i === 3) {\\n newArgs[i] = wombat.proxyToObj(arguments[i]);\\n } else {\\n newArgs[i] = arguments[i];\\n }\\n }\\n if (originalInitFn.__WB_orig_apply) {\\n return originalInitFn.__WB_orig_apply(thisObj, newArgs);\\n }\\n return originalInitFn.apply(thisObj, newArgs);\\n };\\n }\\n this.$wbwindow[which] = (function(EventConstructor) {\\n return function NewEventConstructor(type, init) {\\n wombat.domConstructorErrorChecker(this, which, arguments);\\n if (init) {\\n if (init.view != null) {\\n init.view = wombat.proxyToObj(init.view);\\n }\\n if (init.relatedTarget != null) {\\n init.relatedTarget = wombat.proxyToObj(init.relatedTarget);\\n }\\n if (init.target != null) {\\n init.target = wombat.proxyToObj(init.target);\\n }\\n }\\n return new EventConstructor(type, init);\\n };\\n })(ConstructorFN);\\n this.$wbwindow[which].prototype = ConstructorFN.prototype;\\n Object.defineProperty(this.$wbwindow[which].prototype, 'constructor', {\\n value: this.$wbwindow[which]\\n });\\n this.$wbwindow[which].prototype[didOverrideKey] = true;\\n };\\n\\n /**\\n * Rewrites the arguments supplied to the functions of the ParentNode interface\\n * @param {Object} fnThis\\n * @param {function} originalFn\\n * @param {Object} argsObj\\n * @return {*}\\n */\\n Wombat.prototype.rewriteParentNodeFn = function(fnThis, originalFn, argsObj) {\\n var argArr = this._no_rewrite\\n ? argsObj\\n : this.rewriteElementsInArguments(argsObj);\\n var thisObj = this.proxyToObj(fnThis);\\n if (originalFn.__WB_orig_apply) {\\n return originalFn.__WB_orig_apply(thisObj, argArr);\\n }\\n return originalFn.apply(thisObj, argArr);\\n };\\n\\n /**\\n * Overrides the append and prepend functions on the supplied object in order\\n * to ensure that the elements or string of HTML supplied as arguments to these\\n * functions are rewritten\\n * @param {Object} obj\\n * @see https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append\\n * @see https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/prepend\\n */\\n Wombat.prototype.overrideParentNodeAppendPrepend = function(obj) {\\n var rewriteParentNodeFn = this.rewriteParentNodeFn;\\n if (obj.prototype.append) {\\n var originalAppend = obj.prototype.append;\\n obj.prototype.append = function append() {\\n return rewriteParentNodeFn(this, originalAppend, arguments);\\n };\\n }\\n if (obj.prototype.prepend) {\\n var originalPrepend = obj.prototype.prepend;\\n obj.prototype.prepend = function prepend() {\\n return rewriteParentNodeFn(this, originalPrepend, arguments);\\n };\\n }\\n };\\n\\n /**\\n * Overrides the `innerHTML` property and `append`, `prepend` functions\\n * on the ShadowRoot interface in order to ensure any HTML elements\\n * added via these methods are rewritten\\n * @see https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot\\n */\\n Wombat.prototype.overrideShadowDom = function() {\\n if (!this.$wbwindow.ShadowRoot || !this.$wbwindow.ShadowRoot.prototype) {\\n return;\\n }\\n // shadow root inherits from DocumentFragment, Node, and ParentNode not Element\\n this.overrideHtmlAssign(this.$wbwindow.ShadowRoot, 'innerHTML', true);\\n this.overrideParentNodeAppendPrepend(this.$wbwindow.ShadowRoot);\\n };\\n\\n /**\\n * Applies an override to the ChildNode interface that is inherited by\\n * the supplied Object. If the textIface argument is truthy the rewrite function\\n * used is {@link rewriteChildNodeFn} otherwise {@link rewriteTextNodeFn}\\n * @param {*} ifaceWithChildNode\\n * @param {boolean} [textIface]\\n */\\n Wombat.prototype.overrideChildNodeInterface = function(\\n ifaceWithChildNode,\\n textIface\\n ) {\\n if (!ifaceWithChildNode || !ifaceWithChildNode.prototype) return;\\n var rewriteFn = textIface ? this.rewriteTextNodeFn : this.rewriteChildNodeFn;\\n if (ifaceWithChildNode.prototype.before) {\\n var originalBefore = ifaceWithChildNode.prototype.before;\\n ifaceWithChildNode.prototype.before = function before() {\\n return rewriteFn(this, originalBefore, arguments);\\n };\\n }\\n if (ifaceWithChildNode.prototype.after) {\\n var originalAfter = ifaceWithChildNode.prototype.after;\\n ifaceWithChildNode.prototype.after = function after() {\\n return rewriteFn(this, originalAfter, arguments);\\n };\\n }\\n if (ifaceWithChildNode.prototype.replaceWith) {\\n var originalReplaceWith = ifaceWithChildNode.prototype.replaceWith;\\n ifaceWithChildNode.prototype.replaceWith = function replaceWith() {\\n return rewriteFn(this, originalReplaceWith, arguments);\\n };\\n }\\n };\\n\\n /**\\n * Applies overrides to the `appendData`, `insertData`, and `replaceData` functions\\n * and `data` and `wholeText` properties on the Text interface in order to ensure\\n * CSS strings are rewritten when Text nodes are children of the style tag\\n */\\n Wombat.prototype.initTextNodeOverrides = function() {\\n var Text = this.$wbwindow.Text;\\n if (!Text || !Text.prototype) return;\\n // https://dom.spec.whatwg.org/#characterdata and https://dom.spec.whatwg.org/#interface-text\\n // depending on the JS frameworks used some pages include JS that will append a single text node child\\n // to a style tag and then progressively modify that text nodes data for changing the css values that\\n // style tag contains\\n var textProto = Text.prototype;\\n // override inherited CharacterData functions\\n var rewriteTextProtoFunction = this.rewriteTextNodeFn;\\n if (textProto.appendData) {\\n var originalAppendData = textProto.appendData;\\n textProto.appendData = function appendData() {\\n return rewriteTextProtoFunction(this, originalAppendData, arguments);\\n };\\n }\\n if (textProto.insertData) {\\n var originalInsertData = textProto.insertData;\\n textProto.insertData = function insertData() {\\n return rewriteTextProtoFunction(this, originalInsertData, arguments);\\n };\\n }\\n if (textProto.replaceData) {\\n var originalReplaceData = textProto.replaceData;\\n textProto.replaceData = function replaceData() {\\n return rewriteTextProtoFunction(this, originalReplaceData, arguments);\\n };\\n }\\n this.overrideChildNodeInterface(Text, true);\\n // override property getters and setters\\n this.overrideTextProtoGetSet(textProto, 'data');\\n this.overrideTextProtoGetSet(textProto, 'wholeText');\\n };\\n\\n /**\\n * Applies attribute getter and setter function overrides to the HTML elements\\n * and CSS properties that are URLs are rewritten\\n */\\n Wombat.prototype.initAttrOverrides = function() {\\n // href attr overrides\\n this.overrideHrefAttr(this.$wbwindow.HTMLLinkElement.prototype, 'cs_');\\n this.overrideHrefAttr(this.$wbwindow.CSSStyleSheet.prototype, 'cs_');\\n this.overrideHrefAttr(this.$wbwindow.HTMLBaseElement.prototype, 'mp_');\\n // srcset attr overrides\\n this.overrideSrcsetAttr(this.$wbwindow.HTMLImageElement.prototype, 'im_');\\n this.overrideSrcsetAttr(this.$wbwindow.HTMLSourceElement.prototype, 'oe_');\\n // poster attr overrides\\n this.overrideAttr(this.$wbwindow.HTMLVideoElement.prototype, 'poster', 'im_');\\n this.overrideAttr(this.$wbwindow.HTMLAudioElement.prototype, 'poster', 'im_');\\n // src attr overrides\\n this.overrideAttr(this.$wbwindow.HTMLImageElement.prototype, 'src', 'im_');\\n this.overrideAttr(this.$wbwindow.HTMLInputElement.prototype, 'src', 'oe_');\\n this.overrideAttr(this.$wbwindow.HTMLEmbedElement.prototype, 'src', 'oe_');\\n this.overrideAttr(this.$wbwindow.HTMLMediaElement.prototype, 'src', 'oe_');\\n this.overrideAttr(this.$wbwindow.HTMLVideoElement.prototype, 'src', 'oe_');\\n this.overrideAttr(this.$wbwindow.HTMLAudioElement.prototype, 'src', 'oe_');\\n this.overrideAttr(this.$wbwindow.HTMLSourceElement.prototype, 'src', 'oe_');\\n if (window.HTMLTrackElement && window.HTMLTrackElement.prototype) {\\n this.overrideAttr(this.$wbwindow.HTMLTrackElement.prototype, 'src', 'oe_');\\n }\\n this.overrideAttr(this.$wbwindow.HTMLIFrameElement.prototype, 'src', 'if_');\\n if (\\n this.$wbwindow.HTMLFrameElement &&\\n this.$wbwindow.HTMLFrameElement.prototype\\n ) {\\n this.overrideAttr(this.$wbwindow.HTMLFrameElement.prototype, 'src', 'fr_');\\n }\\n this.overrideAttr(this.$wbwindow.HTMLScriptElement.prototype, 'src', 'js_');\\n // other attr overrides\\n this.overrideAttr(this.$wbwindow.HTMLObjectElement.prototype, 'data', 'oe_');\\n this.overrideAttr(\\n this.$wbwindow.HTMLObjectElement.prototype,\\n 'codebase',\\n 'oe_'\\n );\\n this.overrideAttr(this.$wbwindow.HTMLMetaElement.prototype, 'content', 'mp_');\\n this.overrideAttr(this.$wbwindow.HTMLFormElement.prototype, 'action', 'mp_');\\n this.overrideAttr(this.$wbwindow.HTMLQuoteElement.prototype, 'cite', 'mp_');\\n this.overrideAttr(this.$wbwindow.HTMLModElement.prototype, 'cite', 'mp_');\\n // a, area tag overrides\\n this.overrideAnchorAreaElem(this.$wbwindow.HTMLAnchorElement);\\n this.overrideAnchorAreaElem(this.$wbwindow.HTMLAreaElement);\\n\\n var style_proto = this.$wbwindow.CSSStyleDeclaration.prototype;\\n\\n var cssAttrToProps = {\\n 'background': 'background',\\n 'backgroundImage': 'background-image',\\n 'cursor': 'cursor',\\n 'listStyle': 'list-style',\\n 'listStyleImage': 'list-style-image',\\n 'border': 'border',\\n 'borderImage': 'border-image',\\n 'borderImageSource': 'border-image-source',\\n 'maskImage': 'mask-image'\\n };\\n\\n this.overrideStyleProxy(Object.values(cssAttrToProps));\\n\\n // For FF\\n if (this.$wbwindow.CSS2Properties) {\\n style_proto = this.$wbwindow.CSS2Properties.prototype;\\n }\\n\\n this.overrideStyleAttr(style_proto, 'cssText');\\n\\n for (var [attr, prop] of Object.entries(cssAttrToProps)) {\\n this.overrideStyleAttr(style_proto, attr, prop);\\n }\\n\\n this.overrideStyleSetProp(style_proto);\\n\\n if (this.$wbwindow.CSSStyleSheet && this.$wbwindow.CSSStyleSheet.prototype) {\\n // https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule\\n // ruleText is a string of raw css....\\n var wombat = this;\\n var oInsertRule = this.$wbwindow.CSSStyleSheet.prototype.insertRule;\\n this.$wbwindow.CSSStyleSheet.prototype.insertRule = function insertRule(\\n ruleText,\\n index\\n ) {\\n return oInsertRule.call(this, wombat.rewriteStyle(ruleText), index);\\n };\\n }\\n\\n if (this.$wbwindow.CSSRule && this.$wbwindow.CSSRule.prototype) {\\n this.overrideStyleAttr(this.$wbwindow.CSSRule.prototype, 'cssText');\\n }\\n };\\n\\n /**\\n * Applies overrides to CSSStyleValue.[parse,parseAll], CSSKeywordValue, and\\n * StylePropertyMap in order to ensure the URLs these interfaces operate on\\n * are rewritten. Gotta love Chrome.\\n * @see https://drafts.css-houdini.org/css-typed-om-1/\\n */\\n Wombat.prototype.initCSSOMOverrides = function() {\\n var wombat = this;\\n if (this.$wbwindow.CSSStyleValue) {\\n var cssStyleValueOverride = function(CSSSV, which) {\\n var oFN = CSSSV[which];\\n CSSSV[which] = function parseOrParseAllOverride(property, cssText) {\\n if (cssText == null) return oFN.call(this, property, cssText);\\n var rwCSSText = wombat.noExceptRewriteStyle(cssText);\\n return oFN.call(this, property, rwCSSText);\\n };\\n };\\n\\n if (\\n this.$wbwindow.CSSStyleValue.parse &&\\n this.$wbwindow.CSSStyleValue.parse.toString().indexOf('[native code]') > 0\\n ) {\\n cssStyleValueOverride(this.$wbwindow.CSSStyleValue, 'parse');\\n }\\n\\n if (\\n this.$wbwindow.CSSStyleValue.parseAll &&\\n this.$wbwindow.CSSStyleValue.parseAll\\n .toString()\\n .indexOf('[native code]') > 0\\n ) {\\n cssStyleValueOverride(this.$wbwindow.CSSStyleValue, 'parseAll');\\n }\\n }\\n\\n if (\\n this.$wbwindow.CSSKeywordValue &&\\n this.$wbwindow.CSSKeywordValue.prototype\\n ) {\\n var oCSSKV = this.$wbwindow.CSSKeywordValue;\\n this.$wbwindow.CSSKeywordValue = (function(CSSKeywordValue_) {\\n return function CSSKeywordValue(cssValue) {\\n wombat.domConstructorErrorChecker(this, 'CSSKeywordValue', arguments);\\n return new CSSKeywordValue_(wombat.rewriteStyle(cssValue));\\n };\\n })(this.$wbwindow.CSSKeywordValue);\\n this.$wbwindow.CSSKeywordValue.prototype = oCSSKV.prototype;\\n Object.defineProperty(\\n this.$wbwindow.CSSKeywordValue.prototype,\\n 'constructor',\\n {\\n value: this.$wbwindow.CSSKeywordValue\\n }\\n );\\n addToStringTagToClass(this.$wbwindow.CSSKeywordValue, 'CSSKeywordValue');\\n }\\n\\n if (\\n this.$wbwindow.StylePropertyMap &&\\n this.$wbwindow.StylePropertyMap.prototype\\n ) {\\n var originalSet = this.$wbwindow.StylePropertyMap.prototype.set;\\n this.$wbwindow.StylePropertyMap.prototype.set = function set() {\\n if (arguments.length <= 1) {\\n if (originalSet.__WB_orig_apply) {\\n return originalSet.__WB_orig_apply(this, arguments);\\n }\\n return originalSet.apply(this, arguments);\\n }\\n var newArgs = new Array(arguments.length);\\n newArgs[0] = arguments[0];\\n for (var i = 1; i < arguments.length; i++) {\\n newArgs[i] = wombat.noExceptRewriteStyle(arguments[i]);\\n }\\n if (originalSet.__WB_orig_apply) {\\n return originalSet.__WB_orig_apply(this, newArgs);\\n }\\n return originalSet.apply(this, newArgs);\\n };\\n\\n var originalAppend = this.$wbwindow.StylePropertyMap.prototype.append;\\n this.$wbwindow.StylePropertyMap.prototype.append = function append() {\\n if (arguments.length <= 1) {\\n if (originalSet.__WB_orig_apply) {\\n return originalAppend.__WB_orig_apply(this, arguments);\\n }\\n return originalAppend.apply(this, arguments);\\n }\\n var newArgs = new Array(arguments.length);\\n newArgs[0] = arguments[0];\\n for (var i = 1; i < arguments.length; i++) {\\n newArgs[i] = wombat.noExceptRewriteStyle(arguments[i]);\\n }\\n if (originalAppend.__WB_orig_apply) {\\n return originalAppend.__WB_orig_apply(this, newArgs);\\n }\\n return originalAppend.apply(this, newArgs);\\n };\\n }\\n };\\n\\n /**\\n * Applies an overrides to the Audio constructor in order to ensure its URL\\n * argument is rewritten\\n */\\n Wombat.prototype.initAudioOverride = function() {\\n if (!this.$wbwindow.Audio) return;\\n var orig_audio = this.$wbwindow.Audio;\\n var wombat = this;\\n this.$wbwindow.Audio = (function(Audio_) {\\n return function Audio(url) {\\n wombat.domConstructorErrorChecker(this, 'Audio');\\n return new Audio_(wombat.rewriteUrl(url, true, 'oe_'));\\n };\\n })(this.$wbwindow.Audio);\\n\\n this.$wbwindow.Audio.prototype = orig_audio.prototype;\\n Object.defineProperty(this.$wbwindow.Audio.prototype, 'constructor', {\\n value: this.$wbwindow.Audio\\n });\\n addToStringTagToClass(this.$wbwindow.Audio, 'HTMLAudioElement');\\n };\\n\\n /**\\n * Initializes the BAD_PREFIXES array using the supplied prefix\\n * @param {string} prefix\\n */\\n Wombat.prototype.initBadPrefixes = function(prefix) {\\n this.BAD_PREFIXES = [\\n 'http:' + prefix,\\n 'https:' + prefix,\\n 'http:/' + prefix,\\n 'https:/' + prefix\\n ];\\n };\\n\\n /**\\n * Applies an override to crypto.getRandomValues in order to make\\n * the values it returns are deterministic during replay\\n */\\n Wombat.prototype.initCryptoRandom = function() {\\n if (!this.$wbwindow.crypto || !this.$wbwindow.Crypto) return;\\n var wombat = this;\\n var new_getrandom = function getRandomValues(array) {\\n for (var i = 0; i < array.length; i++) {\\n array[i] = parseInt(wombat.$wbwindow.Math.random() * 4294967296);\\n }\\n return array;\\n };\\n this.$wbwindow.Crypto.prototype.getRandomValues = new_getrandom;\\n this.$wbwindow.crypto.getRandomValues = new_getrandom;\\n };\\n\\n /**\\n * Applies an override to the Date object in order to ensure that\\n * all Dates used during replay are in the datetime of replay\\n * @param {string} timestamp\\n */\\n Wombat.prototype.initDateOverride = function(timestamp) {\\n if (this.$wbwindow.__wb_Date_now) return;\\n var newTimestamp = parseInt(timestamp) * 1000;\\n // var timezone = new Date().getTimezoneOffset() * 60 * 1000;\\n // Already UTC!\\n var timezone = 0;\\n var start_now = this.$wbwindow.Date.now();\\n var timediff = start_now - (newTimestamp - timezone);\\n\\n var orig_date = this.$wbwindow.Date;\\n\\n var orig_utc = this.$wbwindow.Date.UTC;\\n var orig_parse = this.$wbwindow.Date.parse;\\n var orig_now = this.$wbwindow.Date.now;\\n\\n this.$wbwindow.__wb_Date_now = orig_now;\\n\\n this.$wbwindow.Date = (function(Date_) {\\n return function Date(A, B, C, D, E, F, G) {\\n // [native code]\\n // Apply doesn't work for constructors and Date doesn't\\n // seem to like undefined args, so must explicitly\\n // call constructor for each possible args 0..7\\n if (A === undefined) {\\n return new Date_(orig_now() - timediff);\\n } else if (B === undefined) {\\n return new Date_(A);\\n } else if (C === undefined) {\\n return new Date_(A, B);\\n } else if (D === undefined) {\\n return new Date_(A, B, C);\\n } else if (E === undefined) {\\n return new Date_(A, B, C, D);\\n } else if (F === undefined) {\\n return new Date_(A, B, C, D, E);\\n } else if (G === undefined) {\\n return new Date_(A, B, C, D, E, F);\\n } else {\\n return new Date_(A, B, C, D, E, F, G);\\n }\\n };\\n })(this.$wbwindow.Date);\\n\\n this.$wbwindow.Date.prototype = orig_date.prototype;\\n\\n this.$wbwindow.Date.now = function now() {\\n return orig_now() - timediff;\\n };\\n\\n this.$wbwindow.Date.UTC = orig_utc;\\n this.$wbwindow.Date.parse = orig_parse;\\n\\n this.$wbwindow.Date.__WB_timediff = timediff;\\n\\n this.$wbwindow.Date.prototype.getTimezoneOffset = function() {\\n return 0;\\n };\\n\\n var orig_toString = this.$wbwindow.Date.prototype.toString;\\n this.$wbwindow.Date.prototype.toString = function() {\\n var string = orig_toString.call(this).split(' GMT')[0];\\n return string + ' GMT+0000 (Coordinated Universal Time)';\\n };\\n\\n var orig_toTimeString = this.$wbwindow.Date.prototype.toTimeString;\\n this.$wbwindow.Date.prototype.toTimeString = function() {\\n var string = orig_toTimeString.call(this).split(' GMT')[0];\\n return string + ' GMT+0000 (Coordinated Universal Time)';\\n };\\n\\n Object.defineProperty(this.$wbwindow.Date.prototype, 'constructor', {\\n value: this.$wbwindow.Date\\n });\\n };\\n\\n\\n Wombat.prototype.initBlobOverride = function() {\\n // don't use for SW replay as blob: iframes won't have access to SW\\n if (!this.$wbwindow.Blob || this.wb_info.isSW) {\\n return;\\n }\\n\\n var orig_blob = this.$wbwindow.Blob;\\n\\n var wombat = this;\\n\\n this.$wbwindow.Blob = (function(Blob_) {\\n return function Blob(array, options) {\\n\\n if (options && (options.type === 'application/xhtml+xml' || options.type === 'text/html')) {\\n // for now, just handle single string case\\n if (array.length === 1 && typeof(array[0]) === 'string' && wombat.startsWith(array[0], '')) {\\n array[0] = wombat.rewriteHtml(array[0]);\\n options.type = 'text/html';\\n }\\n }\\n\\n return new Blob_(array, options);\\n };\\n })(this.$wbwindow.Blob);\\n\\n this.$wbwindow.Blob.prototype = orig_blob.prototype;\\n };\\n\\n Wombat.prototype.initWSOverride = function() {\\n if (!this.$wbwindow.WebSocket || !this.$wbwindow.WebSocket.prototype) {\\n return;\\n }\\n\\n this.$wbwindow.WebSocket = (function(WebSocket_) {\\n function WebSocket(url, protocols) {\\n this.addEventListener = function() {};\\n this.removeEventListener = function() {};\\n this.close = function() {};\\n this.send = function(data) {\\n console.log('ws send', data);\\n };\\n\\n this.protocol = protocols && protocols.length ? protocols[0] : '';\\n this.url = url;\\n this.readyState = 0;\\n }\\n\\n WebSocket.CONNECTING = 0;\\n WebSocket.OPEN = 1;\\n WebSocket.CLOSING = 2;\\n WebSocket.CLOSED = 3;\\n\\n return WebSocket;\\n })(this.$wbwindow.WebSocket);\\n\\n Object.defineProperty(this.$wbwindow.WebSocket.prototype, 'constructor', {\\n value: this.$wbwindow.WebSocket\\n });\\n\\n addToStringTagToClass(this.$wbwindow.WebSocket, 'WebSocket');\\n };\\n \\n /**\\n * Applies an override to the document.title property in order to ensure\\n * that actual top (archive top frame containing the replay iframe) receives\\n * document.title updates\\n */\\n Wombat.prototype.initDocTitleOverride = function() {\\n var orig_get_title = this.getOrigGetter(this.$wbwindow.document, 'title');\\n var orig_set_title = this.getOrigSetter(this.$wbwindow.document, 'title');\\n var wombat = this;\\n var set_title = function title(value) {\\n var res = orig_set_title.call(this, value);\\n var message = { wb_type: 'title', title: value };\\n wombat.sendTopMessage(message);\\n return res;\\n };\\n this.defProp(this.$wbwindow.document, 'title', set_title, orig_get_title);\\n };\\n\\n /**\\n * Applies an override to the FontFace constructor in order to ensure font URLs\\n * are rewritten\\n * @see https://drafts.csswg.org/css-font-loading/#FontFace-interface\\n */\\n Wombat.prototype.initFontFaceOverride = function() {\\n if (!this.$wbwindow.FontFace) {\\n return;\\n }\\n var wombat = this;\\n var origFontFace = this.$wbwindow.FontFace;\\n this.$wbwindow.FontFace = (function(FontFace_) {\\n return function FontFace(family, source, descriptors) {\\n wombat.domConstructorErrorChecker(this, 'FontFace', arguments, 2);\\n var rwSource = source;\\n if (source != null) {\\n if (typeof source !== 'string') {\\n // is CSSOMString or ArrayBuffer or ArrayBufferView\\n rwSource = wombat.rewriteInlineStyle(source.toString());\\n } else {\\n rwSource = wombat.rewriteInlineStyle(source);\\n }\\n }\\n return new FontFace_(family, rwSource, descriptors);\\n };\\n })(this.$wbwindow.FontFace);\\n this.$wbwindow.FontFace.prototype = origFontFace.prototype;\\n Object.defineProperty(this.$wbwindow.FontFace.prototype, 'constructor', {\\n value: this.$wbwindow.FontFace\\n });\\n addToStringTagToClass(this.$wbwindow.FontFace, 'FontFace');\\n };\\n\\n /**\\n * Forces, when possible, the devicePixelRatio property of window to 1\\n * in order to ensure deterministic replay\\n */\\n Wombat.prototype.initFixedRatio = function(value) {\\n try {\\n // otherwise, just set it\\n this.$wbwindow.devicePixelRatio = value;\\n } catch (e) {}\\n\\n // prevent changing, if possible\\n if (Object.defineProperty) {\\n try {\\n // fixed pix ratio\\n Object.defineProperty(this.$wbwindow, 'devicePixelRatio', {\\n value: value,\\n writable: false\\n });\\n } catch (e) {}\\n }\\n };\\n\\n /**\\n * Initializes wombats path information from the supplied wbinfo object\\n * @param {Object} wbinfo\\n */\\n Wombat.prototype.initPaths = function(wbinfo) {\\n wbinfo.wombat_opts = wbinfo.wombat_opts || {};\\n //this.wb_info = wbinfo;\\n Object.assign(this.wb_info, wbinfo);\\n this.wb_opts = wbinfo.wombat_opts;\\n this.wb_replay_prefix = wbinfo.prefix;\\n this.wb_is_proxy = wbinfo.proxy_magic || !this.wb_replay_prefix;\\n this.wb_info.top_host = this.wb_info.top_host || '*';\\n this.wb_curr_host =\\n this.$wbwindow.location.protocol + '//' + this.$wbwindow.location.host;\\n this.wb_info.wombat_opts = this.wb_info.wombat_opts || {};\\n this.wb_orig_scheme = wbinfo.wombat_scheme + '://';\\n this.wb_orig_origin = this.wb_orig_scheme + wbinfo.wombat_host;\\n this.wb_abs_prefix = this.wb_replay_prefix;\\n if (!wbinfo.is_live && wbinfo.wombat_ts) {\\n this.wb_capture_date_part = '/' + wbinfo.wombat_ts + '/';\\n } else {\\n this.wb_capture_date_part = '';\\n }\\n this.initBadPrefixes(this.wb_replay_prefix);\\n this.initCookiePreset();\\n };\\n\\n /**\\n * Applies an override to Math.seed and Math.random using the supplied\\n * seed in order to ensure that random numbers are deterministic during\\n * replay\\n * @param {string} seed\\n */\\n Wombat.prototype.initSeededRandom = function(seed) {\\n // Adapted from:\\n // http://indiegamr.com/generate-repeatable-random-numbers-in-js/\\n this.$wbwindow.Math.seed = parseInt(seed);\\n var wombat = this;\\n this.$wbwindow.Math.random = function random() {\\n wombat.$wbwindow.Math.seed =\\n (wombat.$wbwindow.Math.seed * 9301 + 49297) % 233280;\\n return wombat.$wbwindow.Math.seed / 233280;\\n };\\n };\\n\\n /**\\n * Applies overrides to history.pushState and history.replaceState in order\\n * to ensure that URLs used for browser history manipulation are rewritten.\\n * Also adds a `popstate` listener to window of the browser context wombat is in\\n * in order to ensure that actual top (archive top frame containing the replay iframe)\\n * browser history is updated IFF the history manipulation happens in the replay top\\n */\\n Wombat.prototype.initHistoryOverrides = function() {\\n this.overrideHistoryFunc('pushState');\\n this.overrideHistoryFunc('replaceState');\\n var wombat = this;\\n this.$wbwindow.addEventListener('popstate', function(event) {\\n wombat.sendHistoryUpdate(\\n wombat.$wbwindow.WB_wombat_location.href,\\n wombat.$wbwindow.document.title\\n );\\n });\\n };\\n\\n /**\\n * If cookie preset if passed in via wb_info, set parse and set cookies on the document\\n */\\n Wombat.prototype.initCookiePreset = function() {\\n if (this.wb_info.presetCookie) {\\n var splitCookies = this.wb_info.presetCookie.split(';');\\n for (var i = 0; i < splitCookies.length; i++) {\\n this.$wbwindow.document.cookie = splitCookies[i].trim() + '; Path=' + this.rewriteUrl('./', true);\\n }\\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 */\\n Wombat.prototype.initHTTPOverrides = function() {\\n var wombat = this;\\n\\n // responseURL override\\n this.overridePropExtract(this.$wbwindow.XMLHttpRequest.prototype, 'responseURL');\\n\\n if (!this.wb_info.isSW) {\\n if (this.$wbwindow.XMLHttpRequest.prototype.open) {\\n var origXMLHttpOpen = this.$wbwindow.XMLHttpRequest.prototype.open;\\n this.utilFns.XHRopen = origXMLHttpOpen;\\n this.utilFns.XHRsend = this.$wbwindow.XMLHttpRequest.prototype.send;\\n this.$wbwindow.XMLHttpRequest.prototype.open = function open(\\n method,\\n url,\\n async,\\n user,\\n password\\n ) {\\n var rwURL = !this._no_rewrite ? wombat.rewriteUrl(url) : url;\\n var openAsync = true;\\n if (async != null && !async) openAsync = false;\\n origXMLHttpOpen.call(this, method, rwURL, openAsync, user, password);\\n if (!wombat.startsWith(rwURL, 'data:')) {\\n this.setRequestHeader('X-Pywb-Requested-With', 'XMLHttpRequest');\\n }\\n };\\n }\\n } else {\\n var origOpen = this.$wbwindow.XMLHttpRequest.prototype.open;\\n var origSetRequestHeader = this.$wbwindow.XMLHttpRequest.prototype.setRequestHeader;\\n var origSend = this.$wbwindow.XMLHttpRequest.prototype.send;\\n this.utilFns.XHRopen = origOpen;\\n this.utilFns.XHRsend = origSend;\\n\\n this.$wbwindow.XMLHttpRequest.prototype.open = function() {\\n this.__WB_xhr_open_arguments = arguments;\\n this.__WB_xhr_headers = new Headers();\\n };\\n\\n this.$wbwindow.XMLHttpRequest.prototype.setRequestHeader = function(name, value) {\\n this.__WB_xhr_headers.set(name, value);\\n };\\n\\n var wombat = this;\\n var convertToGet = !!this.wb_info.convert_post_to_get;\\n\\n this.$wbwindow.XMLHttpRequest.prototype.send = async function(value) {\\n if (convertToGet && (this.__WB_xhr_open_arguments[0] === 'POST' || this.__WB_xhr_open_arguments[0] === 'PUT')) {\\n\\n var request = {\\n 'url': this.__WB_xhr_open_arguments[1],\\n 'method': this.__WB_xhr_open_arguments[0],\\n 'headers': this.__WB_xhr_headers,\\n 'postData': value\\n };\\n\\n if (w(request)) {\\n this.__WB_xhr_open_arguments[1] = request.url;\\n this.__WB_xhr_open_arguments[0] = 'GET';\\n value = null;\\n }\\n }\\n\\n // sync mode: disable unless Firefox\\n // sync xhr with service workers supported only in FF at the moment\\n // https://wpt.fyi/results/service-workers/service-worker/fetch-request-xhr-sync.https.html\\n if (this.__WB_xhr_open_arguments.length > 2 && !this.__WB_xhr_open_arguments[2] && navigator.userAgent.indexOf('Firefox') === -1) {\\n this.__WB_xhr_open_arguments[2] = true;\\n console.warn('wombat.js: Sync XHR not supported in SW-based replay in this browser, converted to async');\\n }\\n\\n if (!this._no_rewrite) {\\n this.__WB_xhr_open_arguments[1] = wombat.rewriteUrl(this.__WB_xhr_open_arguments[1]);\\n }\\n\\n origOpen.apply(this, this.__WB_xhr_open_arguments);\\n\\n if (!wombat.startsWith(this.__WB_xhr_open_arguments[1], 'data:')) {\\n for (const [name, value] of this.__WB_xhr_headers.entries()) {\\n origSetRequestHeader.call(this, name, value);\\n }\\n\\n origSetRequestHeader.call(this, 'X-Pywb-Requested-With', 'XMLHttpRequest');\\n }\\n\\n return origSend.call(this, value);\\n };\\n }\\n\\n if (this.$wbwindow.fetch) {\\n var orig_fetch = this.$wbwindow.fetch;\\n this.$wbwindow.fetch = function fetch(input, init_opts) {\\n var rwInput = input;\\n var inputType = typeof input;\\n if (inputType === 'string') {\\n rwInput = wombat.rewriteUrl(input);\\n } else if (inputType === 'object' && input.url) {\\n var new_url = wombat.rewriteUrl(input.url);\\n if (new_url !== input.url) {\\n rwInput = new Request(new_url, init_opts);\\n }\\n } else if (inputType === 'object' && input.href) {\\n // it is likely that input is either window.location or window.URL\\n rwInput = wombat.rewriteUrl(input.href);\\n }\\n\\n if (!init_opts) {\\n init_opts = {};\\n }\\n if (init_opts.credentials === undefined) {\\n try {\\n init_opts.credentials = 'include';\\n } catch(e) {}\\n }\\n\\n return orig_fetch.call(wombat.proxyToObj(this), rwInput, init_opts);\\n };\\n }\\n\\n if (this.$wbwindow.Request && this.$wbwindow.Request.prototype) {\\n var orig_request = this.$wbwindow.Request;\\n this.$wbwindow.Request = (function(Request_) {\\n return function Request(input, init_opts) {\\n wombat.domConstructorErrorChecker(this, 'Request', arguments);\\n var newInitOpts = init_opts || {};\\n var newInput = input;\\n var inputType = typeof input;\\n switch (inputType) {\\n case 'string':\\n newInput = wombat.rewriteUrl(input);\\n break;\\n case 'object':\\n newInput = input;\\n if (input.url) {\\n var new_url = wombat.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 newInput = new Request_(new_url, input);\\n }\\n } else if (input.href) {\\n // it is likely that input is either window.location or window.URL\\n newInput = wombat.rewriteUrl(input.toString(), true);\\n }\\n break;\\n }\\n newInitOpts['credentials'] = 'include';\\n if (newInitOpts.referrer) {\\n newInitOpts.referrer = wombat.rewriteUrl(newInitOpts.referrer);\\n }\\n\\n return new Request_(newInput, newInitOpts);\\n };\\n })(this.$wbwindow.Request);\\n\\n this.$wbwindow.Request.prototype = orig_request.prototype;\\n Object.defineProperty(this.$wbwindow.Request.prototype, 'constructor', {\\n value: this.$wbwindow.Request\\n });\\n\\n // override Request.url\\n this.overridePropExtract(this.$wbwindow.Request.prototype, 'url');\\n\\n // override Request.referrer\\n this.overridePropExtract(this.$wbwindow.Request.prototype, 'referrer');\\n }\\n\\n if (this.$wbwindow.Response && this.$wbwindow.Response.prototype) {\\n // https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect\\n var originalRedirect = this.$wbwindow.Response.prototype.redirect;\\n this.$wbwindow.Response.prototype.redirect = function redirect(\\n url,\\n status\\n ) {\\n var rwURL = wombat.rewriteUrl(url, true, null, wombat.$wbwindow.document);\\n return originalRedirect.call(this, rwURL, status);\\n };\\n\\n // override Response.url\\n this.overridePropExtract(this.$wbwindow.Response.prototype, 'url');\\n }\\n\\n if (this.$wbwindow.EventSource && this.$wbwindow.EventSource.prototype) {\\n var origEventSource = this.$wbwindow.EventSource;\\n this.$wbwindow.EventSource = (function(EventSource_) {\\n return function EventSource(url, configuration) {\\n wombat.domConstructorErrorChecker(this, 'EventSource', arguments);\\n var rwURL = url;\\n if (url != null) {\\n rwURL = wombat.rewriteUrl(url);\\n }\\n return new EventSource_(rwURL, configuration);\\n };\\n })(this.$wbwindow.EventSource);\\n this.$wbwindow.EventSource.prototype = origEventSource.prototype;\\n Object.defineProperty(this.$wbwindow.EventSource.prototype, 'constructor', {\\n value: this.$wbwindow.EventSource\\n });\\n addToStringTagToClass(this.$wbwindow.EventSource, 'EventSource');\\n }\\n };\\n\\n /**\\n * Applies an override to Element.[getAttribute, setAttribute] in order to\\n * ensure that operations on properties that contain URLs are rewritten\\n * @see https://www.w3.org/TR/dom/#interface-element\\n */\\n Wombat.prototype.initElementGetSetAttributeOverride = function() {\\n if (\\n this.wb_opts.skip_setAttribute ||\\n (!this.$wbwindow.Element || !this.$wbwindow.Element.prototype)\\n ) {\\n return;\\n }\\n\\n var wombat = this;\\n var ElementProto = this.$wbwindow.Element.prototype;\\n\\n if (ElementProto.setAttribute) {\\n var orig_setAttribute = ElementProto.setAttribute;\\n ElementProto._orig_setAttribute = orig_setAttribute;\\n ElementProto.setAttribute = function setAttribute(name, value) {\\n var rwValue = value;\\n if (name && typeof rwValue === 'string') {\\n var lowername = name.toLowerCase();\\n if (\\n this.tagName === 'LINK' &&\\n lowername === 'href' &&\\n rwValue.indexOf('data:text/css') === 0\\n ) {\\n rwValue = wombat.rewriteInlineStyle(value);\\n } else if (lowername === 'style') {\\n rwValue = wombat.rewriteStyle(value);\\n } else if (lowername === 'srcset' || (lowername === 'imagesrcset' && this.tagName === 'LINK')) {\\n rwValue = wombat.rewriteSrcset(value, this);\\n } else {\\n var shouldRW = wombat.shouldRewriteAttr(this.tagName, lowername);\\n if (shouldRW) {\\n wombat.removeWBOSRC(this);\\n if (!this._no_rewrite) {\\n rwValue = wombat.rewriteUrl(\\n value,\\n false,\\n wombat.rwModForElement(this, lowername)\\n );\\n }\\n }\\n }\\n }\\n return orig_setAttribute.call(this, name, rwValue);\\n };\\n }\\n\\n if (ElementProto.getAttribute) {\\n var orig_getAttribute = ElementProto.getAttribute;\\n this.wb_getAttribute = orig_getAttribute;\\n ElementProto.getAttribute = function getAttribute(name) {\\n var result = orig_getAttribute.call(this, name);\\n if (result === null) {\\n return result;\\n }\\n var lowerName = name;\\n if (name) {\\n lowerName = name.toLowerCase();\\n }\\n if (wombat.shouldRewriteAttr(this.tagName, lowerName)) {\\n var maybeWBOSRC = wombat.retrieveWBOSRC(this);\\n if (maybeWBOSRC) return maybeWBOSRC;\\n return wombat.extractOriginalURL(result);\\n } else if (\\n wombat.startsWith(lowerName, 'data-') &&\\n wombat.startsWithOneOf(result, wombat.wb_prefixes)\\n ) {\\n return wombat.extractOriginalURL(result);\\n }\\n\\n return result;\\n };\\n }\\n };\\n\\n /**\\n * Applies an override to the getAttribute[NS] and setAttribute[NS] functions\\n * of the SVGImageElement interface in order to ensure that the URLs of the\\n * href and xlink:href properties are rewritten\\n */\\n Wombat.prototype.initSvgImageOverrides = function() {\\n if (!this.$wbwindow.SVGImageElement) {\\n return;\\n }\\n var svgImgProto = this.$wbwindow.SVGImageElement.prototype;\\n\\n var orig_getAttr = svgImgProto.getAttribute;\\n var orig_getAttrNS = svgImgProto.getAttributeNS;\\n var orig_setAttr = svgImgProto.setAttribute;\\n var orig_setAttrNS = svgImgProto.setAttributeNS;\\n var wombat = this;\\n\\n svgImgProto.getAttribute = function getAttribute(name) {\\n var value = orig_getAttr.call(this, name);\\n if (name.indexOf('xlink:href') >= 0 || name === 'href') {\\n return wombat.extractOriginalURL(value);\\n }\\n return value;\\n };\\n\\n svgImgProto.getAttributeNS = function getAttributeNS(ns, name) {\\n var value = orig_getAttrNS.call(this, ns, name);\\n if (name.indexOf('xlink:href') >= 0 || name === 'href') {\\n return wombat.extractOriginalURL(value);\\n }\\n return value;\\n };\\n\\n svgImgProto.setAttribute = function setAttribute(name, value) {\\n var rwValue = value;\\n if (name.indexOf('xlink:href') >= 0 || name === 'href') {\\n rwValue = wombat.rewriteUrl(value);\\n }\\n return orig_setAttr.call(this, name, rwValue);\\n };\\n\\n svgImgProto.setAttributeNS = function setAttributeNS(ns, name, value) {\\n var rwValue = value;\\n if (name.indexOf('xlink:href') >= 0 || name === 'href') {\\n rwValue = wombat.rewriteUrl(value);\\n }\\n return orig_setAttrNS.call(this, ns, name, rwValue);\\n };\\n };\\n\\n /**\\n * Applies an override to document.createElementNS in order to ensure that the\\n * nameSpaceURI argument is un-rewritten\\n */\\n Wombat.prototype.initCreateElementNSFix = function() {\\n if (\\n !this.$wbwindow.document.createElementNS ||\\n !this.$wbwindow.Document.prototype.createElementNS\\n ) {\\n return;\\n }\\n var orig_createElementNS = this.$wbwindow.document.createElementNS;\\n var wombat = this;\\n\\n var createElementNS = function createElementNS(namespaceURI, qualifiedName) {\\n return orig_createElementNS.call(\\n wombat.proxyToObj(this),\\n wombat.extractOriginalURL(namespaceURI),\\n qualifiedName\\n );\\n };\\n\\n this.$wbwindow.Document.prototype.createElementNS = createElementNS;\\n this.$wbwindow.document.createElementNS = createElementNS;\\n };\\n\\n /**\\n * Applies an override to Element.insertAdjacentHTML in order to ensure\\n * that the strings of HTML to be inserted are rewritten and to\\n * Element.insertAdjacentElement in order to ensure that the Elements to\\n * be inserted are rewritten\\n */\\n Wombat.prototype.initInsertAdjacentElementHTMLOverrides = function() {\\n var Element = this.$wbwindow.Element;\\n if (!Element || !Element.prototype) return;\\n var elementProto = Element.prototype;\\n var rewriteFn = this.rewriteInsertAdjHTMLOrElemArgs;\\n if (elementProto.insertAdjacentHTML) {\\n var origInsertAdjacentHTML = elementProto.insertAdjacentHTML;\\n elementProto.insertAdjacentHTML = function insertAdjacentHTML(\\n position,\\n text\\n ) {\\n return rewriteFn(this, origInsertAdjacentHTML, position, text, true);\\n };\\n }\\n if (elementProto.insertAdjacentElement) {\\n var origIAdjElem = elementProto.insertAdjacentElement;\\n elementProto.insertAdjacentElement = function insertAdjacentElement(\\n position,\\n element\\n ) {\\n return rewriteFn(this, origIAdjElem, position, element, false);\\n };\\n }\\n };\\n\\n /**\\n * Applies overrides to Node.[appendChild, insertBefore, replaceChild] and\\n * [Element, DocumentFragment].[append, prepend) in order to ensure the that\\n * the elements added by these functions are rewritten.\\n * Also applies an override to the Node.ownerDocument, HTMLHtmlElement.parentNode,\\n * and Event.target getter functions do not return a JS Proxy object used by wombat\\n * @see https://www.w3.org/TR/dom/#node\\n */\\n Wombat.prototype.initDomOverride = function() {\\n var Node = this.$wbwindow.Node;\\n if (Node && Node.prototype) {\\n var rewriteFn = this.rewriteNodeFuncArgs;\\n if (Node.prototype.appendChild) {\\n var originalAppendChild = Node.prototype.appendChild;\\n Node.prototype.appendChild = function appendChild(newNode, oldNode) {\\n return rewriteFn(this, originalAppendChild, newNode, oldNode);\\n };\\n }\\n if (Node.prototype.insertBefore) {\\n var originalInsertBefore = Node.prototype.insertBefore;\\n Node.prototype.insertBefore = function insertBefore(newNode, oldNode) {\\n return rewriteFn(this, originalInsertBefore, newNode, oldNode);\\n };\\n }\\n if (Node.prototype.replaceChild) {\\n var originalReplaceChild = Node.prototype.replaceChild;\\n Node.prototype.replaceChild = function replaceChild(newNode, oldNode) {\\n return rewriteFn(this, originalReplaceChild, newNode, oldNode);\\n };\\n }\\n this.overridePropToProxy(Node.prototype, 'ownerDocument');\\n this.overridePropToProxy(\\n this.$wbwindow.HTMLHtmlElement.prototype,\\n 'parentNode'\\n );\\n this.overridePropToProxy(this.$wbwindow.Event.prototype, 'target');\\n }\\n\\n if (this.$wbwindow.Element && this.$wbwindow.Element.prototype) {\\n this.overrideParentNodeAppendPrepend(this.$wbwindow.Element);\\n this.overrideChildNodeInterface(this.$wbwindow.Element, false);\\n }\\n\\n if (\\n this.$wbwindow.DocumentFragment &&\\n this.$wbwindow.DocumentFragment.prototype\\n ) {\\n this.overrideParentNodeAppendPrepend(this.$wbwindow.DocumentFragment);\\n }\\n };\\n\\n /**\\n * Applies overrides to document.referrer, document.origin, document.domain, and\\n * window.origin in order to ensure their getters and setters behave as expected\\n * on the live web\\n * @param {Document} $document\\n */\\n Wombat.prototype.initDocOverrides = function($document) {\\n if (!Object.defineProperty) return;\\n\\n // referrer\\n this.overrideReferrer($document);\\n\\n // origin\\n this.defGetterProp($document, 'origin', function origin() {\\n return this.WB_wombat_location.origin;\\n });\\n // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/origin, chrome 59+ and ff 54+\\n this.defGetterProp(this.$wbwindow, 'origin', function origin() {\\n return this.WB_wombat_location.origin;\\n });\\n\\n var wombat = this;\\n // domain\\n var domain_setter = function domain(val) {\\n var loc = this.WB_wombat_location;\\n if (loc && wombat.endsWith(loc.hostname, val)) {\\n this.__wb_domain = val;\\n }\\n };\\n\\n var domain_getter = function domain() {\\n return this.__wb_domain || this.WB_wombat_location.hostname;\\n };\\n\\n this.defProp($document, 'domain', domain_setter, domain_getter);\\n };\\n\\n /**\\n * Apples overrides to document.[write, writeln, open, close] in order\\n * to ensure that the values they operate on or create are rewritten and\\n * wombat is initialized in the new documents/windows.\\n * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html\\n * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open-window\\n * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-close\\n * @see https://html.spec.whatwg.org/multipage/dom.html#dom-document-body\\n */\\n Wombat.prototype.initDocWriteOpenCloseOverride = function() {\\n if (!this.$wbwindow.DOMParser) {\\n return;\\n }\\n\\n // for both document.write and document.writeln, all arguments are treated as a string and concatenated together\\n // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html\\n\\n var DocumentProto = this.$wbwindow.Document.prototype;\\n var $wbDocument = this.$wbwindow.document;\\n\\n this._writeBuff = '';\\n\\n var wombat = this;\\n\\n function isSWLoad() {\\n return wombat.wb_info.isSW && wombat.$wbwindow.frameElement;\\n }\\n\\n function prepForWrite(args) {\\n var string;\\n\\n if (args.length === 0) {\\n return '';\\n }\\n\\n if (args.length === 1) {\\n string = args[0];\\n } else {\\n // use Array.join rather than Array.apply because join works with array like objects\\n string = Array.prototype.join.call(args, '');\\n }\\n\\n return string;\\n }\\n\\n /**\\n * Rewrite the arguments supplied to document.[write, writeln] in order\\n * to ensure that the string of HTML is rewritten\\n * @param {Object} fnThis\\n * @param {function} originalFn\\n * @param {Object} rewritten string\\n */\\n function docWrite(fnThis, originalFn, string) {\\n wombat.$wbwindow;\\n\\n if (isSWLoad()) {\\n wombat._writeBuff += string;\\n return;\\n }\\n\\n string = wombat.rewriteHtml(string, true);\\n var thisObj = wombat.proxyToObj(fnThis);\\n var res = originalFn.call(thisObj, string);\\n wombat.initNewWindowWombat(thisObj.defaultView);\\n return res;\\n }\\n // Write\\n var orig_doc_write = $wbDocument.write;\\n var new_write = function write() {\\n return docWrite(this, orig_doc_write, prepForWrite(arguments));\\n };\\n $wbDocument.write = new_write;\\n DocumentProto.write = new_write;\\n\\n // Writeln\\n var orig_doc_writeln = $wbDocument.writeln;\\n var new_writeln = function writeln() {\\n return docWrite(this, orig_doc_writeln, prepForWrite(arguments));\\n };\\n $wbDocument.writeln = new_writeln;\\n DocumentProto.writeln = new_writeln;\\n\\n // Open\\n var orig_doc_open = $wbDocument.open;\\n var new_open = function open() {\\n var thisObj = wombat.proxyToObj(this);\\n var res;\\n if (arguments.length === 3) {\\n // we have the case where a new window will be opened\\n // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open-window\\n var rwUrl = wombat.rewriteUrl(arguments[0], false, 'mp_');\\n res = orig_doc_open.call(thisObj, rwUrl, arguments[1], arguments[2]);\\n wombat.initNewWindowWombat(res, arguments[0]);\\n } else {\\n res = orig_doc_open.call(thisObj);\\n if (isSWLoad()) {\\n wombat._writeBuff = '';\\n } else {\\n wombat.initNewWindowWombat(thisObj.defaultView);\\n }\\n }\\n return res;\\n };\\n\\n $wbDocument.open = new_open;\\n DocumentProto.open = new_open;\\n\\n // we override close in order to ensure wombat is init'd\\n // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-close\\n var originalClose = $wbDocument.close;\\n var newClose = function close() {\\n if (wombat._writeBuff) {\\n wombat.blobUrlForIframe(wombat.$wbwindow.frameElement, wombat._writeBuff);\\n wombat._writeBuff = '';\\n return;\\n }\\n var thisObj = wombat.proxyToObj(this);\\n wombat.initNewWindowWombat(thisObj.defaultView);\\n if (originalClose.__WB_orig_apply) {\\n return originalClose.__WB_orig_apply(thisObj, arguments);\\n }\\n return originalClose.apply(thisObj, arguments);\\n };\\n\\n $wbDocument.close = newClose;\\n DocumentProto.close = newClose;\\n\\n // we override the setter for document.body because it is settable\\n // to either an instance of HTMLBodyElement or HTMLFrameSetElement and\\n // there are ways to get un-rewritten elements into replay we must allow\\n // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body\\n var oBodyGetter = this.getOrigGetter(DocumentProto, 'body');\\n var oBodySetter = this.getOrigSetter(DocumentProto, 'body');\\n if (oBodyGetter && oBodySetter) {\\n this.defProp(\\n DocumentProto,\\n 'body',\\n function body(newBody) {\\n if (\\n newBody &&\\n (newBody instanceof HTMLBodyElement ||\\n newBody instanceof HTMLFrameSetElement)\\n ) {\\n wombat.rewriteElemComplete(newBody);\\n }\\n return oBodySetter.call(wombat.proxyToObj(this), newBody);\\n },\\n oBodyGetter\\n );\\n }\\n };\\n\\n /**\\n * Inits wombat in the supplied iframe\\n * @param {HTMLIFrameElement} iframe\\n */\\n Wombat.prototype.initIframeWombat = function(iframe) {\\n var win;\\n\\n if (iframe._get_contentWindow) {\\n win = iframe._get_contentWindow.call(iframe); // eslint-disable-line no-useless-call\\n } else {\\n win = iframe.contentWindow;\\n }\\n\\n try {\\n if (!win || win === this.$wbwindow || win._skip_wombat || win._wb_wombat) {\\n return;\\n }\\n } catch (e) {\\n return;\\n }\\n\\n var src = iframe.src;\\n //var src = this.wb_getAttribute.call(iframe, 'src');\\n\\n this.initNewWindowWombat(win, src);\\n };\\n\\n /**\\n * Initializes wombat in the supplied window IFF the src URL of the window is\\n * not the empty string, about:blank, or a \\\"javascript:\\\" URL\\n * @param {Window} win\\n * @param {string} [src] unrewritten url\\n */\\n Wombat.prototype.initNewWindowWombat = function(win, src) {\\n var fullWombat = false;\\n\\n if (!win || win._wb_wombat) return;\\n\\n if (\\n !src ||\\n src === '' ||\\n this.startsWithOneOf(src, ['about:blank', 'javascript:'])\\n ) {\\n fullWombat = true;\\n }\\n\\n\\n if (!fullWombat && this.wb_info.isSW) {\\n var origURL = this.extractOriginalURL(src);\\n if (origURL === 'about:blank' || origURL.startsWith('srcdoc:') || origURL.startsWith('blob:')) {\\n fullWombat = true;\\n }\\n }\\n\\n if (fullWombat) {\\n // win._WBWombat = wombat_internal(win);\\n // win._wb_wombat = new win._WBWombat(wb_info);\\n var newInfo = {};\\n Object.assign(newInfo, this.wb_info);\\n var wombat = new Wombat(win, newInfo);\\n win._wb_wombat = wombat.wombatInit();\\n } else {\\n // These should get overridden when content is loaded, but just in case...\\n // win._WB_wombat_location = win.location;\\n // win.document.WB_wombat_location = win.document.location;\\n // win._WB_wombat_top = $wbwindow.WB_wombat_top;\\n\\n this.initProtoPmOrigin(win);\\n this.initPostMessageOverride(win);\\n this.initMessageEventOverride(win);\\n this.initCheckThisFunc(win);\\n this.initImportWrapperFunc(win);\\n }\\n };\\n\\n /**\\n * Applies an override to either window.[setTimeout, setInterval] functions\\n * in order to ensure that usage such as [setTimeout|setInterval]('document.location.href = \\\"xyz.com\\\"', time)\\n * behaves as expected during replay.\\n *\\n * In this case the supplied string is eval'd in the current context skipping\\n * the surrounding scope\\n */\\n Wombat.prototype.initTimeoutIntervalOverrides = function() {\\n var rewriteFn = this.rewriteSetTimeoutInterval;\\n if (this.$wbwindow.setTimeout && !this.$wbwindow.setTimeout.__$wbpatched$__) {\\n var originalSetTimeout = this.$wbwindow.setTimeout;\\n this.$wbwindow.setTimeout = function setTimeout() {\\n return rewriteFn(this, originalSetTimeout, arguments);\\n };\\n this.$wbwindow.setTimeout.__$wbpatched$__ = true;\\n }\\n\\n if (\\n this.$wbwindow.setInterval &&\\n !this.$wbwindow.setInterval.__$wbpatched$__\\n ) {\\n var originalSetInterval = this.$wbwindow.setInterval;\\n this.$wbwindow.setInterval = function setInterval() {\\n return rewriteFn(this, originalSetInterval, arguments);\\n };\\n this.$wbwindow.setInterval.__$wbpatched$__ = true;\\n }\\n };\\n\\n /**\\n * Applies an overrides to the constructor of window.[Worker, SharedWorker] in\\n * order to ensure that the URL argument is rewritten.\\n *\\n * Applies an override to ServiceWorkerContainer.register in order to ensure\\n * that the URLs used in ServiceWorker registration are rewritten.\\n *\\n * Applies an override to Worklet.addModule in order to ensure that URL\\n * to the worklet module is rewritten\\n * @see https://html.spec.whatwg.org/multipage/workers.html\\n * @see https://w3c.github.io/ServiceWorker/\\n * @see https://drafts.css-houdini.org/worklets/#worklet\\n */\\n Wombat.prototype.initWorkerOverrides = function() {\\n var wombat = this;\\n\\n if (this.$wbwindow.Worker && !this.$wbwindow.Worker._wb_worker_overridden) {\\n // Worker unrewrite postMessage\\n var orig_worker = this.$wbwindow.Worker;\\n this.$wbwindow.Worker = (function(Worker_) {\\n return function Worker(url, options) {\\n wombat.domConstructorErrorChecker(this, 'Worker', arguments);\\n return new Worker_(wombat.rewriteWorker(url), options);\\n };\\n })(orig_worker);\\n\\n this.$wbwindow.Worker.prototype = orig_worker.prototype;\\n Object.defineProperty(this.$wbwindow.Worker.prototype, 'constructor', {\\n value: this.$wbwindow.Worker\\n });\\n this.$wbwindow.Worker._wb_worker_overridden = true;\\n }\\n\\n if (\\n this.$wbwindow.SharedWorker &&\\n !this.$wbwindow.SharedWorker.__wb_sharedWorker_overridden\\n ) {\\n // per https://html.spec.whatwg.org/multipage/workers.html#sharedworker\\n var oSharedWorker = this.$wbwindow.SharedWorker;\\n this.$wbwindow.SharedWorker = (function(SharedWorker_) {\\n return function SharedWorker(url, options) {\\n wombat.domConstructorErrorChecker(this, 'SharedWorker', arguments);\\n return new SharedWorker_(wombat.rewriteWorker(url), options);\\n };\\n })(oSharedWorker);\\n\\n this.$wbwindow.SharedWorker.prototype = oSharedWorker.prototype;\\n Object.defineProperty(\\n this.$wbwindow.SharedWorker.prototype,\\n 'constructor',\\n {\\n value: this.$wbwindow.SharedWorker\\n }\\n );\\n this.$wbwindow.SharedWorker.__wb_sharedWorker_overridden = true;\\n }\\n\\n if (\\n this.$wbwindow.ServiceWorkerContainer &&\\n this.$wbwindow.ServiceWorkerContainer.prototype &&\\n this.$wbwindow.ServiceWorkerContainer.prototype.register\\n ) {\\n // https://w3c.github.io/ServiceWorker/\\n var orig_register = this.$wbwindow.ServiceWorkerContainer.prototype\\n .register;\\n this.$wbwindow.ServiceWorkerContainer.prototype.register = function register(\\n scriptURL,\\n options\\n ) {\\n var newScriptURL = new URL(scriptURL, wombat.$wbwindow.document.baseURI)\\n .href;\\n var mod = wombat.getPageUnderModifier();\\n if (options && options.scope) {\\n options.scope = wombat.rewriteUrl(options.scope, false, mod);\\n } else {\\n options = { scope: wombat.rewriteUrl('/', false, mod) };\\n }\\n return orig_register.call(\\n this,\\n wombat.rewriteUrl(newScriptURL, false, 'sw_'),\\n options\\n );\\n };\\n }\\n\\n if (\\n this.$wbwindow.Worklet &&\\n this.$wbwindow.Worklet.prototype &&\\n this.$wbwindow.Worklet.prototype.addModule &&\\n !this.$wbwindow.Worklet.__wb_workerlet_overridden\\n ) {\\n // https://developer.mozilla.org/en-US/docs/Web/API/Worklet/addModule\\n var oAddModule = this.$wbwindow.Worklet.prototype.addModule;\\n this.$wbwindow.Worklet.prototype.addModule = function addModule(\\n moduleURL,\\n options\\n ) {\\n var rwModuleURL = wombat.rewriteUrl(moduleURL, false, 'js_');\\n return oAddModule.call(this, rwModuleURL, options);\\n };\\n this.$wbwindow.Worklet.__wb_workerlet_overridden = true;\\n }\\n };\\n\\n /**\\n * Applies overrides to the getter setter functions of the supplied object\\n * for the properties defined in {@link Wombat#URL_PROPS} IFF\\n * Object.defineProperty is defined\\n * @param {Object} loc\\n * @param {function} oSetter\\n * @param {function} oGetter\\n */\\n Wombat.prototype.initLocOverride = function(loc, oSetter, oGetter) {\\n if (Object.defineProperty) {\\n for (var i = 0; i < this.URL_PROPS.length; i++) {\\n var prop = this.URL_PROPS[i];\\n this.defProp(\\n loc,\\n prop,\\n this.makeSetLocProp(prop, oSetter, oGetter),\\n this.makeGetLocProp(prop, oGetter),\\n true\\n );\\n }\\n }\\n };\\n\\n /**\\n * Initialized WombatLocation on the supplied window object and adds the\\n * __WB_pmw function on the window, as well as, defines WB_wombat_location\\n * as property on the prototype of Object and adds the _WB_wombat_location\\n * and __WB_check_loc properties to the supplied window\\n * @param {Window} win\\n */\\n Wombat.prototype.initWombatLoc = function(win) {\\n if (!win || (win.WB_wombat_location && win.document.WB_wombat_location)) {\\n return;\\n }\\n\\n // Location\\n var wombat_location = new WombatLocation(win.location, this);\\n\\n var wombat = this;\\n\\n if (Object.defineProperty) {\\n var setter = function(value) {\\n var loc =\\n this._WB_wombat_location ||\\n (this.defaultView && this.defaultView._WB_wombat_location);\\n\\n if (loc) {\\n loc.href = value;\\n }\\n win.location = wombat.rewriteUrl(value);\\n };\\n\\n var getter = function() {\\n return (\\n this._WB_wombat_location ||\\n (this.defaultView && this.defaultView._WB_wombat_location) ||\\n this.location\\n );\\n };\\n\\n this.defProp(win.Object.prototype, 'WB_wombat_location', setter, getter);\\n\\n this.initProtoPmOrigin(win);\\n\\n win._WB_wombat_location = wombat_location;\\n } else {\\n win.WB_wombat_location = wombat_location;\\n\\n // Check quickly after page load\\n setTimeout(this.checkAllLocations, 500);\\n\\n // Check periodically every few seconds\\n setInterval(this.checkAllLocations, 500);\\n }\\n };\\n\\n /**\\n * Adds the __WB_pmw property to prototype of Object and adds the\\n * __WB_check_loc property to window\\n * @param {Window} win\\n */\\n Wombat.prototype.initProtoPmOrigin = function(win) {\\n if (win.Object.prototype.__WB_pmw) return;\\n\\n var pm_origin = function pm_origin(origin_window) {\\n this.__WB_source = origin_window;\\n return this;\\n };\\n\\n try {\\n win.Object.defineProperty(win.Object.prototype, '__WB_pmw', {\\n get: function() {\\n return pm_origin;\\n },\\n set: function() {},\\n configurable: true,\\n enumerable: false\\n });\\n } catch (e) {}\\n\\n win.__WB_check_loc = function(loc, args) {\\n if (loc instanceof Location || loc instanceof WombatLocation) {\\n // args, if provided, should be the 'arguments' from calling function\\n // check if the location is actually a locally passed in argument,\\n // if so, don't assign to global location\\n if (args) {\\n for (var i = 0; i < args.length; i++) {\\n if (loc === args[i]) {\\n return {};\\n }\\n }\\n }\\n return this.WB_wombat_location;\\n } else {\\n return {};\\n }\\n };\\n };\\n\\n /**\\n * Add proxy object globals, assign func and 'this' wrapper, to global Object.prototype\\n *\\n */\\n\\n Wombat.prototype.initCheckThisFunc = function(win) {\\n try {\\n if (!win.Object.prototype[this.WB_CHECK_THIS_FUNC]) {\\n win.Object.defineProperty(win.Object.prototype, this.WB_CHECK_THIS_FUNC, {\\n configutable: false,\\n enumerable: false,\\n value: function(thisObj) {\\n return (thisObj && thisObj._WB_wombat_obj_proxy ? thisObj._WB_wombat_obj_proxy : thisObj);\\n },\\n });\\n }\\n } catch(e) {}\\n };\\n\\n\\n Wombat.prototype.initImportWrapperFunc = function(win) {\\n var wombat = this;\\n win.____wb_rewrite_import__ = function(base, url) {\\n // if base provided (set to import.meta.url), use that as base for imports\\n if (base) {\\n url = new URL(url, base).href;\\n }\\n return import(/*webpackIgnore: true*/ wombat.rewriteUrl(url, false, 'esm_'));\\n };\\n };\\n\\n /**\\n * Override Object.getOwnPropertyNames() to filter out special wombat-added properties\\n *\\n */\\n\\n Wombat.prototype.overrideGetOwnPropertyNames = function(win) {\\n var orig_getOwnPropertyNames = win.Object.getOwnPropertyNames;\\n\\n var removeProps = [\\n this.WB_CHECK_THIS_FUNC,\\n 'WB_wombat_location',\\n '__WB_pmw',\\n 'WB_wombat_top',\\n 'WB_wombat_eval',\\n 'WB_wombat_runEval'\\n ];\\n\\n try {\\n win.Object.defineProperty(win.Object, 'getOwnPropertyNames', {\\n value: function(object) {\\n var props = orig_getOwnPropertyNames(object);\\n\\n for (var i = 0; i < removeProps.length; i++) {\\n var foundInx = props.indexOf(removeProps[i]);\\n if (foundInx >= 0) {\\n props.splice(foundInx, 1);\\n }\\n }\\n\\n return props;\\n }\\n });\\n } catch (e) {\\n console.log(e);\\n }\\n };\\n\\n /**\\n * Adds listeners for `message` and `hashchange` to window of the browser context wombat is in\\n * in order to ensure that actual top (archive top frame containing the replay iframe)\\n * browser history is updated IFF the history manipulation happens in the replay top\\n */\\n Wombat.prototype.initHashChange = function() {\\n if (!this.$wbwindow.__WB_top_frame) return;\\n\\n var wombat = this;\\n\\n var receive_hash_change = function receive_hash_change(event) {\\n if (!event.data || !event.data.from_top) {\\n return;\\n }\\n\\n var message = event.data.message;\\n\\n if (!message.wb_type) return;\\n\\n if (message.wb_type === 'outer_hashchange') {\\n if (wombat.$wbwindow.location.hash != message.hash) {\\n wombat.$wbwindow.location.hash = message.hash;\\n }\\n }\\n };\\n\\n var send_hash_change = function send_hash_change() {\\n var message = {\\n wb_type: 'hashchange',\\n hash: wombat.$wbwindow.location.hash\\n };\\n\\n wombat.sendTopMessage(message);\\n };\\n\\n this.$wbwindow.addEventListener('message', receive_hash_change);\\n\\n this.$wbwindow.addEventListener('hashchange', send_hash_change);\\n };\\n\\n /**\\n * Overrides window.postMessage in order to ensure that messages sent\\n * via this function are routed to the correct window, especially that\\n * messages sent to the \\\"top frame\\\" do not go to archive top but replay top.\\n *\\n * This function also applies an override to EventTarget.[addEventListener, removeEventListener]\\n * to ensure that listening to events behaves correctly during replay.\\n *\\n * This function is the place where the `onmessage` and `onstorage` setter functions\\n * are overridden.\\n * @param {Window} $wbwindow\\n */\\n Wombat.prototype.initPostMessageOverride = function($wbwindow) {\\n if (!$wbwindow.postMessage || $wbwindow.__orig_postMessage) {\\n return;\\n }\\n\\n var orig = $wbwindow.postMessage;\\n var wombat = this;\\n\\n $wbwindow.__orig_postMessage = orig;\\n\\n // use this_obj.__WB_source not window to fix google calendar embeds, pm_origin sets this.__WB_source\\n var postmessage_rewritten = function postMessage(\\n message,\\n targetOrigin,\\n transfer,\\n from_top\\n ) {\\n var from;\\n var src_id;\\n var this_obj = wombat.proxyToObj(this);\\n if (!this_obj) {\\n this_obj = $wbwindow;\\n this_obj.__WB_source = $wbwindow;\\n }\\n if (this_obj.__WB_source && this_obj.__WB_source.WB_wombat_location) {\\n var source = this_obj.__WB_source;\\n\\n from = source.WB_wombat_location.origin;\\n if (!this_obj.__WB_win_id) {\\n this_obj.__WB_win_id = {};\\n this_obj.__WB_counter = 0;\\n }\\n\\n if (!source.__WB_id) {\\n var id = this_obj.__WB_counter;\\n source.__WB_id = id + source.WB_wombat_location.href;\\n this_obj.__WB_counter += 1;\\n }\\n this_obj.__WB_win_id[source.__WB_id] = source;\\n\\n src_id = source.__WB_id;\\n\\n this_obj.__WB_source = undefined;\\n } else {\\n from = window.WB_wombat_location.origin;\\n }\\n\\n var to_origin = targetOrigin;\\n\\n // if passed in origin is the replay (rewriting missed somewhere?)\\n // set origin to current 'from' origin\\n if (to_origin === this_obj.location.origin) {\\n to_origin = from;\\n }\\n\\n var new_message = {\\n from: from,\\n to_origin: to_origin,\\n src_id: src_id,\\n message: message,\\n from_top: from_top\\n };\\n\\n // set to 'real' origin if not '*'\\n if (targetOrigin !== '*') {\\n // if target origin is null (about:blank) or empty, don't pass event at all\\n // as it would never succeed\\n if (\\n this_obj.location.origin === 'null' ||\\n this_obj.location.origin === ''\\n ) {\\n return;\\n }\\n // set to actual (rewritten) origin\\n targetOrigin = this_obj.location.origin;\\n }\\n\\n // console.log(`Sending ${from} -> ${to_origin} (${targetOrigin}) ${message}`);\\n\\n return orig.call(this_obj, new_message, targetOrigin, transfer);\\n };\\n\\n $wbwindow.postMessage = postmessage_rewritten;\\n $wbwindow.Window.prototype.postMessage = postmessage_rewritten;\\n\\n var eventTarget = null;\\n if ($wbwindow.EventTarget && $wbwindow.EventTarget.prototype) {\\n eventTarget = $wbwindow.EventTarget.prototype;\\n } else {\\n eventTarget = $wbwindow;\\n }\\n\\n // ADD\\n var _oAddEventListener = eventTarget.addEventListener;\\n eventTarget.addEventListener = function addEventListener(\\n type,\\n listener,\\n useCapture\\n ) {\\n var obj = wombat.proxyToObj(this);\\n var rwListener;\\n if (type === 'message') {\\n rwListener = wombat.message_listeners.add_or_get(listener, function() {\\n return wrapEventListener(listener, obj, wombat);\\n });\\n } else if (type === 'storage') {\\n wombat.storage_listeners.add_or_get(listener, function() {\\n return wrapSameOriginEventListener(listener, obj);\\n });\\n } else {\\n rwListener = listener;\\n }\\n if (rwListener) {\\n return _oAddEventListener.call(obj, type, rwListener, useCapture);\\n }\\n };\\n\\n // REMOVE\\n var _oRemoveEventListener = eventTarget.removeEventListener;\\n eventTarget.removeEventListener = function removeEventListener(\\n type,\\n listener,\\n useCapture\\n ) {\\n var obj = wombat.proxyToObj(this);\\n var rwListener;\\n\\n if (type === 'message') {\\n rwListener = wombat.message_listeners.remove(listener);\\n } else if (type === 'storage') {\\n wombat.storage_listeners.remove(listener);\\n } else {\\n rwListener = listener;\\n }\\n\\n if (rwListener) {\\n return _oRemoveEventListener.call(obj, type, rwListener, useCapture);\\n }\\n };\\n\\n // ONMESSAGE & ONSTORAGE\\n var override_on_prop = function(onevent, wrapperFN) {\\n // var orig_getter = _wombat.getOrigGetter($wbwindow, onevent)\\n var orig_setter = wombat.getOrigSetter($wbwindow, onevent);\\n\\n var setter = function(value) {\\n this['__orig_' + onevent] = value;\\n var obj = wombat.proxyToObj(this);\\n var listener = value ? wrapperFN(value, obj, wombat) : value;\\n return orig_setter.call(obj, listener);\\n };\\n\\n var getter = function() {\\n return this['__orig_' + onevent];\\n };\\n\\n wombat.defProp($wbwindow, onevent, setter, getter);\\n };\\n override_on_prop('onmessage', wrapEventListener);\\n override_on_prop('onstorage', wrapSameOriginEventListener);\\n };\\n\\n /**\\n * Applies overrides to the MessageEvent.[target, srcElement, currentTarget, eventPhase, path, source]\\n * in order to ensure they are not a JS Proxy used by wombat\\n * @param {Window} $wbwindow\\n */\\n Wombat.prototype.initMessageEventOverride = function($wbwindow) {\\n if (!$wbwindow.MessageEvent || $wbwindow.MessageEvent.prototype.__extended) {\\n return;\\n }\\n this.addEventOverride('target');\\n this.addEventOverride('srcElement');\\n this.addEventOverride('currentTarget');\\n this.addEventOverride('eventPhase');\\n this.addEventOverride('path');\\n this.overridePropToProxy($wbwindow.MessageEvent.prototype, 'source');\\n $wbwindow.MessageEvent.prototype.__extended = true;\\n };\\n\\n /**\\n * Applies overrides to the constructors\\n * - UIEvent\\n * - MouseEvent\\n * - TouchEvent\\n * - KeyboardEvent\\n * - WheelEvent\\n * - InputEvent\\n * - CompositionEvent\\n *\\n * in order to ensure the proper behavior of the events when wombat is using\\n * an JS Proxy\\n */\\n Wombat.prototype.initUIEventsOverrides = function() {\\n this.overrideAnUIEvent('UIEvent');\\n this.overrideAnUIEvent('MouseEvent');\\n this.overrideAnUIEvent('TouchEvent');\\n this.overrideAnUIEvent('FocusEvent');\\n this.overrideAnUIEvent('KeyboardEvent');\\n this.overrideAnUIEvent('WheelEvent');\\n this.overrideAnUIEvent('InputEvent');\\n this.overrideAnUIEvent('CompositionEvent');\\n };\\n\\n /**\\n * Applies an override to window.open in order to ensure the URL argument is rewritten.\\n * Also applies the same override to the open function of all frames returned by\\n * window.frames\\n */\\n Wombat.prototype.initOpenOverride = function() {\\n var orig = this.$wbwindow.open;\\n\\n if (this.$wbwindow.Window.prototype.open) {\\n orig = this.$wbwindow.Window.prototype.open;\\n }\\n\\n var wombat = this;\\n\\n var open_rewritten = function open(strUrl, strWindowName, strWindowFeatures) {\\n if (strWindowName) {\\n strWindowName = wombat.rewriteAttrTarget(strWindowName);\\n }\\n var rwStrUrl = wombat.rewriteUrl(strUrl, false);\\n var res = orig.call(\\n wombat.proxyToObj(this),\\n rwStrUrl,\\n strWindowName,\\n strWindowFeatures\\n );\\n wombat.initNewWindowWombat(res, strUrl);\\n return res;\\n };\\n\\n this.$wbwindow.open = open_rewritten;\\n\\n if (this.$wbwindow.Window.prototype.open) {\\n this.$wbwindow.Window.prototype.open = open_rewritten;\\n }\\n\\n for (var i = 0; i < this.$wbwindow.frames.length; i++) {\\n try {\\n this.$wbwindow.frames[i].open = open_rewritten;\\n } catch (e) {\\n console.log(e);\\n }\\n }\\n };\\n\\n /**\\n * Rewrite 'target' for anchor tag or window.open\\n */\\n\\n Wombat.prototype.rewriteAttrTarget = function(target) {\\n if (!this.wb_info.target_frame) {\\n return target;\\n }\\n\\n if (target === '_blank' || target === '_parent' || target === '_top') {\\n return this.wb_info.target_frame;\\n }\\n\\n // if target is a different name, and we are the top frame, assume intent\\n // is to open a new window, and not some iframe\\n // (a further check could also be to check list of iframes to see if the target matches)\\n if (target && this.$wbwindow === this.$wbwindow.__WB_replay_top) {\\n return this.wb_info.target_frame;\\n }\\n\\n return target;\\n };\\n\\n /**\\n * Applies an override to the getter and setter functions of document.cookie\\n * in order to ensure that cookies are rewritten\\n */\\n Wombat.prototype.initCookiesOverride = function() {\\n var orig_get_cookie = this.getOrigGetter(this.$wbwindow.document, 'cookie');\\n var orig_set_cookie = this.getOrigSetter(this.$wbwindow.document, 'cookie');\\n\\n if (!orig_get_cookie) {\\n orig_get_cookie = this.getOrigGetter(\\n this.$wbwindow.Document.prototype,\\n 'cookie'\\n );\\n }\\n if (!orig_set_cookie) {\\n orig_set_cookie = this.getOrigSetter(\\n this.$wbwindow.Document.prototype,\\n 'cookie'\\n );\\n }\\n\\n var rwCookieReplacer = function(m, d1) {\\n var date = new Date(d1);\\n if (isNaN(date.getTime())) {\\n return 'Expires=Thu,| 01 Jan 1970 00:00:00 GMT';\\n }\\n var finalDate = new Date(date.getTime() + Date.__WB_timediff);\\n return 'Expires=' + finalDate.toUTCString().replace(',', ',|');\\n };\\n\\n var wombat = this;\\n var set_cookie = function cookie(value) {\\n if (!value) return;\\n var newValue = value.replace(wombat.cookie_expires_regex, rwCookieReplacer);\\n var cookies = newValue.split(wombat.SetCookieRe);\\n for (var i = 0; i < cookies.length; i++) {\\n cookies[i] = wombat.rewriteCookie(cookies[i]);\\n }\\n return orig_set_cookie.call(wombat.proxyToObj(this), cookies.join(','));\\n };\\n\\n var get_cookie = function cookie() {\\n return orig_get_cookie.call(wombat.proxyToObj(this));\\n };\\n\\n this.defProp(this.$wbwindow.document, 'cookie', set_cookie, get_cookie);\\n };\\n\\n /**\\n * Applies an override to navigator.[registerProtocolHandler, unregisterProtocolHandler] in order to\\n * ensure that the URI argument is rewritten\\n */\\n Wombat.prototype.initRegisterUnRegPHOverride = function() {\\n var wombat = this;\\n var winNavigator = this.$wbwindow.navigator;\\n if (winNavigator.registerProtocolHandler) {\\n var orig_registerPH = winNavigator.registerProtocolHandler;\\n winNavigator.registerProtocolHandler = function registerProtocolHandler(\\n protocol,\\n uri,\\n title\\n ) {\\n return orig_registerPH.call(\\n this,\\n protocol,\\n wombat.rewriteUrl(uri),\\n title\\n );\\n };\\n }\\n\\n if (winNavigator.unregisterProtocolHandler) {\\n var origUnregPH = winNavigator.unregisterProtocolHandler;\\n winNavigator.unregisterProtocolHandler = function unregisterProtocolHandler(\\n scheme,\\n url\\n ) {\\n return origUnregPH.call(this, scheme, wombat.rewriteUrl(url));\\n };\\n }\\n };\\n\\n /**\\n * Applies an override to navigator.sendBeacon in order to ensure that\\n * the URL argument is rewritten. This ensures that when a page is rewritten\\n * no information about who is viewing is leaked to the outside world\\n */\\n Wombat.prototype.initBeaconOverride = function() {\\n if (!this.$wbwindow.navigator.sendBeacon) return;\\n var orig_sendBeacon = this.$wbwindow.navigator.sendBeacon;\\n var wombat = this;\\n this.$wbwindow.navigator.sendBeacon = function sendBeacon(url, data) {\\n try {\\n return orig_sendBeacon.call(this, wombat.rewriteUrl(url), data);\\n } catch(e) {\\n return true;\\n }\\n };\\n };\\n\\n Wombat.prototype.initMiscNavigatorOverrides = function() {\\n if (this.$wbwindow.navigator.mediaDevices) {\\n this.$wbwindow.navigator.mediaDevices.setCaptureHandleConfig = function() {};\\n }\\n };\\n\\n\\n /**\\n * Applies an override to the constructor of the PresentationRequest interface object\\n * in order to rewrite its URL(s) arguments\\n * @see https://w3c.github.io/presentation-api/#constructing-a-presentationrequest\\n */\\n Wombat.prototype.initPresentationRequestOverride = function() {\\n if (\\n this.$wbwindow.PresentationRequest &&\\n this.$wbwindow.PresentationRequest.prototype\\n ) {\\n var wombat = this;\\n var origPresentationRequest = this.$wbwindow.PresentationRequest;\\n this.$wbwindow.PresentationRequest = (function(PresentationRequest_) {\\n return function PresentationRequest(url) {\\n wombat.domConstructorErrorChecker(\\n this,\\n 'PresentationRequest',\\n arguments\\n );\\n var rwURL = url;\\n if (url != null) {\\n if (Array.isArray(rwURL)) {\\n for (var i = 0; i < rwURL.length; i++) {\\n rwURL[i] = wombat.rewriteUrl(rwURL[i], true, 'mp_');\\n }\\n } else {\\n rwURL = wombat.rewriteUrl(url, true, 'mp_');\\n }\\n }\\n return new PresentationRequest_(rwURL);\\n };\\n })(this.$wbwindow.PresentationRequest);\\n this.$wbwindow.PresentationRequest.prototype =\\n origPresentationRequest.prototype;\\n Object.defineProperty(\\n this.$wbwindow.PresentationRequest.prototype,\\n 'constructor',\\n {\\n value: this.$wbwindow.PresentationRequest\\n }\\n );\\n }\\n };\\n\\n /**\\n * Applies an override that disables the pages ability to send OS native\\n * notifications. Also disables the ability of the replayed page to retrieve the geolocation\\n * of the view.\\n *\\n * This is done in order to ensure that no malicious abuse of these functions\\n * can happen during replay.\\n */\\n Wombat.prototype.initDisableNotificationsGeoLocation = function() {\\n if (window.Notification) {\\n window.Notification.requestPermission = function requestPermission(\\n callback\\n ) {\\n if (callback) {\\n callback('denied');\\n }\\n\\n return Promise.resolve('denied');\\n };\\n }\\n\\n var applyOverride = function(on) {\\n if (!on) return;\\n if (on.getCurrentPosition) {\\n on.getCurrentPosition = function getCurrentPosition(\\n success,\\n error,\\n options\\n ) {\\n if (error) {\\n error({ code: 2, message: 'not available' });\\n }\\n };\\n }\\n if (on.watchPosition) {\\n on.watchPosition = function watchPosition(success, error, options) {\\n if (error) {\\n error({ code: 2, message: 'not available' });\\n }\\n };\\n }\\n };\\n if (window.geolocation) {\\n applyOverride(window.geolocation);\\n }\\n if (window.navigator.geolocation) {\\n applyOverride(window.navigator.geolocation);\\n }\\n };\\n\\n /**\\n * Applies an override to window.[localStorage, sessionStorage] storage in order to ensure\\n * that the replayed page can use both interfaces as expected during replay.\\n */\\n Wombat.prototype.initStorageOverride = function() {\\n this.addEventOverride('storageArea', this.$wbwindow.StorageEvent.prototype);\\n\\n ThrowExceptions.yes = false;\\n\\n var initStorage = {};\\n\\n if (this.wb_info.storage) {\\n try {\\n initStorage = JSON.parse(atob(this.wb_info.storage));\\n } catch (e) {\\n console.warn('Error parsing storage, storages not loaded');\\n }\\n }\\n\\n createStorage(this, 'localStorage', initStorage.local);\\n createStorage(this, 'sessionStorage', initStorage.session);\\n\\n // ensure localStorage instanceof Storage works\\n this.$wbwindow.Storage = Storage;\\n ThrowExceptions.yes = true;\\n };\\n\\n\\n Wombat.prototype.initIndexedDBOverride = function() {\\n if (!this.$wbwindow.IDBFactory) {\\n return;\\n }\\n\\n var proto = this.$wbwindow.IDBFactory.prototype;\\n\\n var prefix = 'wb-' + this.wb_orig_origin + '-';\\n\\n var orig_open = proto.open;\\n proto.open = function(dbName, version) {\\n return orig_open.call(this, prefix + dbName, version);\\n };\\n\\n var orig_delete = proto.deleteDatabase;\\n proto.delete = function(dbName) {\\n return orig_delete.call(this, prefix + dbName, options);\\n };\\n\\n var orig_databases = proto.databases;\\n proto.databases = function() {\\n var func = this;\\n return new Promise(function (resolve, reject) {\\n orig_databases.call(func).then(function(dbList) {\\n var keys = [];\\n for (var i = 0; i < dbList.length; i++) {\\n if (dbList[i].name.indexOf(prefix) === 0) {\\n keys.push({name: dbList[i].name.substring(prefix.length), version: dbList[i].version});\\n }\\n }\\n resolve(keys);\\n }).catch(function(err) { reject(err); });\\n });\\n };\\n };\\n\\n Wombat.prototype.initCachesOverride = function() {\\n if (!this.$wbwindow.CacheStorage) {\\n return;\\n }\\n\\n // disable access to extension apis\\n if (this.$wbwindow.chrome) {\\n this.$wbwindow.chrome = {};\\n }\\n\\n var proto = this.$wbwindow.CacheStorage.prototype;\\n\\n var prefix = 'wb-' + this.wb_orig_origin + '-';\\n\\n var orig_open = proto.open;\\n proto.open = function(cacheName) {\\n return orig_open.call(this, prefix + cacheName);\\n };\\n\\n var orig_has = proto.has;\\n proto.has = function(cacheName) {\\n return orig_has.call(this, prefix + cacheName);\\n };\\n\\n var orig_delete = proto.delete;\\n proto.delete = function(cacheName) {\\n return orig_delete.call(this, prefix + cacheName);\\n };\\n\\n var orig_keys = proto.keys;\\n proto.keys = function() {\\n var func = this;\\n return new Promise(function (resolve, reject) {\\n orig_keys.call(func).then(function(keyList) {\\n var keys = [];\\n for (var i = 0; i < keyList.length; i++) {\\n if (keyList[i].indexOf(prefix) === 0) {\\n keys.push(keyList[i].substring(prefix.length));\\n }\\n }\\n resolve(keys);\\n }).catch(function(err) { reject(err); });\\n });\\n };\\n\\n proto.match;\\n proto.match = function match(request, opts) {\\n var caches = this;\\n\\n return this.keys().then(function(cacheNames) {\\n var match;\\n\\n return cacheNames.reduce(function(chain, cacheName) {\\n return chain.then(function() {\\n return match || caches.open(cacheName).then(function(cache) {\\n return cache.match(request, opts);\\n }).then(function(response) {\\n match = response;\\n return match;\\n });\\n });\\n }, Promise.resolve());\\n });\\n };\\n };\\n\\n /**\\n * Initializes the wombat window JS Proxy object IFF JS Proxies are available.\\n * @param {Window} $wbwindow\\n * @return {Proxy}\\n */\\n Wombat.prototype.initWindowObjProxy = function($wbwindow) {\\n if (!$wbwindow.Proxy) return undefined;\\n\\n var ownProps = this.getAllOwnProps($wbwindow);\\n var funCache = {};\\n var wombat = this;\\n var windowProxy = new $wbwindow.Proxy(\\n {},\\n {\\n get: function(target, prop) {\\n switch (prop) {\\n case 'top':\\n return wombat.$wbwindow.WB_wombat_top._WB_wombat_obj_proxy;\\n case 'parent':\\n // if at replay top, return the top object proxy\\n if (wombat.$wbwindow === wombat.$wbwindow.WB_wombat_top) {\\n return wombat.$wbwindow.WB_wombat_top._WB_wombat_obj_proxy;\\n }\\n // attempt to get the object proxy from parent, may throw if cross-origin\\n try {\\n var parentProxy = wombat.$wbwindow.parent._WB_wombat_obj_proxy;\\n if (parentProxy) return parentProxy;\\n } catch (e) {}\\n\\n // default to replay-top object proxy if all else fails\\n return wombat.$wbwindow.WB_wombat_top._WB_wombat_obj_proxy;\\n\\n }\\n return wombat.defaultProxyGet($wbwindow, prop, ownProps, funCache);\\n },\\n set: function(target, prop, value) {\\n switch (prop) {\\n case 'location':\\n $wbwindow.WB_wombat_location = value;\\n return true;\\n case 'postMessage':\\n case 'document':\\n return true;\\n }\\n try {\\n if (!Reflect.set(target, prop, value)) {\\n return false;\\n }\\n } catch (e) {}\\n return Reflect.set($wbwindow, prop, value);\\n },\\n has: function(target, prop) {\\n return prop in $wbwindow;\\n },\\n ownKeys: function(target) {\\n return Object.getOwnPropertyNames($wbwindow).concat(\\n Object.getOwnPropertySymbols($wbwindow)\\n );\\n },\\n getOwnPropertyDescriptor: function(target, key) {\\n // first try the underlying object's descriptor\\n // (to match defineProperty() behavior)\\n var descriptor = Object.getOwnPropertyDescriptor(target, key);\\n if (!descriptor) {\\n descriptor = Object.getOwnPropertyDescriptor($wbwindow, key);\\n // if using window's descriptor, must ensure it's configurable\\n if (descriptor) {\\n descriptor.configurable = true;\\n }\\n }\\n return descriptor;\\n },\\n getPrototypeOf: function(target) {\\n return Object.getPrototypeOf($wbwindow);\\n },\\n setPrototypeOf: function(target, newProto) {\\n return false;\\n },\\n isExtensible: function(target) {\\n return Object.isExtensible($wbwindow);\\n },\\n preventExtensions: function(target) {\\n Object.preventExtensions($wbwindow);\\n return true;\\n },\\n deleteProperty: function(target, prop) {\\n var propDescriptor = Object.getOwnPropertyDescriptor($wbwindow, prop);\\n if (propDescriptor === undefined) {\\n return true;\\n }\\n if (propDescriptor.configurable === false) {\\n return false;\\n }\\n delete target[prop];\\n delete $wbwindow[prop];\\n return true;\\n },\\n defineProperty: function(target, prop, desc) {\\n var ndesc = desc || {};\\n if (ndesc.value === undefined && ndesc.get === undefined) {\\n ndesc.value = $wbwindow[prop];\\n }\\n Reflect.defineProperty($wbwindow, prop, ndesc);\\n return Reflect.defineProperty(target, prop, ndesc);\\n }\\n }\\n );\\n $wbwindow._WB_wombat_obj_proxy = windowProxy;\\n return windowProxy;\\n };\\n\\n /**\\n * Initializes the wombat document JS Proxy object IFF JS Proxies are available.\\n * This function also applies the {@link initDocOverrides} overrides regardless\\n * if JS Proxies are available.\\n * @param {Document} $document\\n * @return {Proxy}\\n */\\n Wombat.prototype.initDocumentObjProxy = function($document) {\\n this.initDocOverrides($document);\\n if (!this.$wbwindow.Proxy) return undefined;\\n var funCache = {};\\n var ownProps = this.getAllOwnProps($document);\\n var wombat = this;\\n var documentProxy = new this.$wbwindow.Proxy($document, {\\n get: function(target, prop) {\\n return wombat.defaultProxyGet($document, prop, ownProps, funCache);\\n },\\n set: function(target, prop, value) {\\n if (prop === 'location') {\\n $document.WB_wombat_location = value;\\n } else {\\n target[prop] = value;\\n }\\n return true;\\n }\\n });\\n $document._WB_wombat_obj_proxy = documentProxy;\\n return documentProxy;\\n };\\n\\n /**\\n * Initializes and starts the auto-fetch worker IFF wbUseAFWorker is true\\n */\\n Wombat.prototype.initAutoFetchWorker = function() {\\n if (!this.wbUseAFWorker) return;\\n var af = new AutoFetcher(this, {\\n isTop: this.$wbwindow === this.$wbwindow.__WB_replay_top,\\n workerURL:\\n (this.wb_info.auto_fetch_worker_prefix || this.wb_info.static_prefix) +\\n 'autoFetchWorker.js?init=' +\\n encodeURIComponent(\\n JSON.stringify({\\n mod: this.wb_info.mod,\\n prefix: this.wb_abs_prefix,\\n rwRe: this.wb_unrewrite_rx.source\\n })\\n )\\n });\\n this.WBAutoFetchWorker = af;\\n this.$wbwindow.$WBAutoFetchWorker$ = af;\\n var wombat = this;\\n this.utilFns.wbSheetMediaQChecker = function checkStyle() {\\n // used only for link[rel='stylesheet'] so we remove our listener\\n wombat._removeEventListener(\\n this,\\n 'load',\\n wombat.utilFns.wbSheetMediaQChecker\\n );\\n // check no op condition\\n if (this.sheet == null) return;\\n // defer extraction to be nice :)\\n if (wombat.WBAutoFetchWorker) {\\n wombat.WBAutoFetchWorker.deferredSheetExtraction(this.sheet);\\n }\\n };\\n };\\n\\n /**\\n * Initializes the listener for when the document.readyState is \\\"complete\\\" in\\n * order to send archive top the information about the title of the page and\\n * have it add any favicons of the replayed page to its own markup.\\n *\\n * The wb_type=\\\"load\\\" message is sent to archive top IFF the page it originates\\n * is replay top\\n * @param {Object} wbinfo\\n */\\n Wombat.prototype.initTopFrameNotify = function(wbinfo) {\\n var wombat = this;\\n\\n var notify_top = function notify_top(event) {\\n if (!wombat.$wbwindow.__WB_top_frame) {\\n var hash = wombat.$wbwindow.location.hash;\\n wombat.$wbwindow.location.replace(wbinfo.top_url + hash);\\n return;\\n }\\n\\n if (!wombat.$wbwindow.WB_wombat_location) return;\\n\\n var url = wombat.$wbwindow.WB_wombat_location.href;\\n\\n if (\\n typeof url !== 'string' ||\\n url === 'about:blank' ||\\n url.indexOf('javascript:') === 0\\n ) {\\n return;\\n }\\n\\n if (\\n wombat.$wbwindow.document.readyState === 'complete' &&\\n wombat.wbUseAFWorker &&\\n wombat.WBAutoFetchWorker\\n ) {\\n wombat.WBAutoFetchWorker.extractFromLocalDoc();\\n }\\n\\n if (wombat.$wbwindow !== wombat.$wbwindow.__WB_replay_top) {\\n return;\\n }\\n\\n var icons = [];\\n var hicons = wombat.$wbwindow.document.querySelectorAll(\\n 'link[rel*=\\\\'icon\\\\']'\\n );\\n\\n for (var i = 0; i < hicons.length; i++) {\\n var hicon = hicons[i];\\n icons.push({\\n rel: hicon.rel,\\n href: wombat.wb_getAttribute.call(hicon, 'href')\\n });\\n }\\n\\n icons.push({\\n rel: 'icon',\\n href: wombat.rewriteUrl('/favicon.ico'),\\n });\\n\\n var message = {\\n icons: icons,\\n url: wombat.$wbwindow.WB_wombat_location.href,\\n ts: wombat.wb_info.timestamp,\\n request_ts: wombat.wb_info.request_ts,\\n is_live: wombat.wb_info.is_live,\\n title: wombat.$wbwindow.document ? wombat.$wbwindow.document.title : '',\\n readyState: wombat.$wbwindow.document.readyState,\\n wb_type: 'load'\\n };\\n\\n wombat.sendTopMessage(message);\\n };\\n\\n if (this.$wbwindow.document.readyState === 'complete') {\\n notify_top();\\n } else if (this.$wbwindow.addEventListener) {\\n this.$wbwindow.document.addEventListener('readystatechange', notify_top);\\n } else if (this.$wbwindow.attachEvent) {\\n this.$wbwindow.document.attachEvent('onreadystatechange', notify_top);\\n }\\n };\\n\\n /**\\n * Initialises the _WB_replay_top and _WB_top_frame properties on window\\n * @param {Window} $wbwindow\\n */\\n Wombat.prototype.initTopFrame = function($wbwindow) {\\n // proxy mode\\n if (this.wb_is_proxy) {\\n $wbwindow.__WB_replay_top = $wbwindow.top;\\n $wbwindow.__WB_top_frame = undefined;\\n this.replayTopHost = replay_top.location.host;\\n this.replayTopProtocol = replay_top.location.protocol;\\n return;\\n }\\n\\n var next_parent = function(win) {\\n try {\\n if (!win) return false;\\n // if no wbinfo, see if _wb_wombat was set (eg. if about:blank page)\\n if (!win.wbinfo) {\\n return win._wb_wombat != null;\\n } else {\\n // otherwise, ensure that it is not a top container frame\\n return win.wbinfo.is_framed;\\n }\\n } catch (e) {\\n return false;\\n }\\n };\\n\\n var replay_top = $wbwindow;\\n while (replay_top.parent != replay_top && next_parent(replay_top.parent)) {\\n replay_top = replay_top.parent;\\n }\\n\\n $wbwindow.__WB_replay_top = replay_top;\\n this.replayTopHost = replay_top.location.host;\\n this.replayTopProtocol = replay_top.location.protocol;\\n\\n var real_parent = replay_top.parent;\\n // Check to ensure top frame is different window and directly accessible (later refactor to support postMessage)\\n if (real_parent == $wbwindow || !this.wb_info.is_framed) {\\n real_parent = undefined;\\n }\\n\\n if (real_parent) {\\n $wbwindow.__WB_top_frame = real_parent;\\n this.initFrameElementOverride($wbwindow);\\n } else {\\n $wbwindow.__WB_top_frame = undefined;\\n }\\n\\n // if not top-replay frame and using auto-fetch workers, register listener\\n // messaging here\\n if (!this.wb_opts.embedded && replay_top == $wbwindow) {\\n if (this.wbUseAFWorker) {\\n var wombat = this;\\n this.$wbwindow.addEventListener(\\n 'message',\\n function(event) {\\n if (\\n event.data &&\\n event.data.wb_type === 'aaworker' &&\\n wombat.WBAutoFetchWorker\\n ) {\\n wombat.WBAutoFetchWorker.postMessage(event.data.msg);\\n }\\n },\\n false\\n );\\n }\\n //removed to rely on proxy object override to ensure 'parent' and 'top' overridden together\\n //$wbwindow.__WB_orig_parent = $wbwindow.parent;\\n //$wbwindow.parent = replay_top;\\n }\\n };\\n\\n /**\\n * Applies an override to window.frameElement IFF the supplied windows\\n * __WB_replay_top property is equal to the window object of the browser context\\n * wombat is currently operating in\\n * @param {Window} $wbwindow\\n */\\n Wombat.prototype.initFrameElementOverride = function($wbwindow) {\\n if (!Object.defineProperty) return;\\n // Also try disabling frameElement directly, though may no longer be supported in all browsers\\n if (\\n this.proxyToObj($wbwindow.__WB_replay_top) == this.proxyToObj($wbwindow)\\n ) {\\n try {\\n Object.defineProperty($wbwindow, 'frameElement', {\\n value: null,\\n configurable: false\\n });\\n } catch (e) {}\\n }\\n };\\n\\n /**\\n * Adds the WB_wombat_top property to the prototype of Object\\n * @param {Window} $wbwindow\\n */\\n Wombat.prototype.initWombatTop = function($wbwindow) {\\n if (!Object.defineProperty) return;\\n\\n // from http://stackoverflow.com/a/6229603\\n var isWindow = function isWindow(obj) {\\n if (typeof window.constructor === 'undefined') {\\n return obj instanceof window.constructor;\\n }\\n return obj.window == obj;\\n };\\n\\n var getter = function top() {\\n if (this.__WB_replay_top) {\\n return this.__WB_replay_top;\\n } else if (isWindow(this)) {\\n return this;\\n }\\n return this.top;\\n };\\n\\n var setter = function top(val) {\\n this.top = val;\\n };\\n\\n this.defProp($wbwindow.Object.prototype, 'WB_wombat_top', setter, getter);\\n };\\n\\n /**\\n * To quote the MDN: 'Do not ever use eval'\\n */\\n Wombat.prototype.initEvalOverride = function() {\\n var rewriteEvalArg = this.rewriteEvalArg;\\n var setNoop = function() {};\\n\\n this.wrappedEval = function (evalFunc) {\\n return function(arg) {\\n return rewriteEvalArg(evalFunc, arg);\\n };\\n };\\n\\n var wombat = this;\\n\\n var runEval = function runEval(func) {\\n var obj = this;\\n\\n if (obj && obj.eval && obj.eval !== eval) {\\n return {\\n eval: function() {\\n return obj.eval.__WB_orig_apply(obj, arguments);\\n }\\n };\\n } else {\\n return {\\n eval: function(arg) {\\n return rewriteEvalArg(func, arg);\\n }\\n };\\n }\\n };\\n\\n // with additional global opt\\n var runEval2 = function runEval(func) {\\n var obj = this;\\n\\n if (obj && obj.eval && obj.eval !== eval) {\\n return {\\n eval: function() {\\n // should have at least 2 arguments as 2 are injected\\n return obj.eval.__WB_orig_apply(obj, [].slice.call(arguments, 2));\\n }\\n };\\n } else {\\n return {\\n eval: function(thisObj, args, evalparam) {\\n // ensure this === window\\n var isGlobal = (thisObj === wombat.proxyToObj(wombat.$wbwindow));\\n // wrap in try/catch in the off chance case we're in strict mode, and then treat as non-global\\n try {\\n isGlobal = isGlobal && !args.callee.caller;\\n } catch (e) {\\n isGlobal = false;\\n }\\n return rewriteEvalArg(func, evalparam, isGlobal);\\n }\\n };\\n }\\n };\\n\\n this.defProp(\\n this.$wbwindow.Object.prototype,\\n 'WB_wombat_runEval',\\n setNoop,\\n function() {\\n return runEval;\\n }\\n );\\n\\n // for extra global eval option\\n this.defProp(\\n this.$wbwindow.Object.prototype,\\n 'WB_wombat_runEval2',\\n setNoop,\\n function() {\\n return runEval2;\\n }\\n );\\n };\\n\\n /**\\n * Initialize wombat's internal state and apply all overrides\\n * @return {Object}\\n */\\n Wombat.prototype.wombatInit = function() {\\n // wombat init\\n this._internalInit();\\n\\n this.initCookiePreset();\\n\\n // History\\n this.initHistoryOverrides();\\n\\n this.overrideFunctionApply(this.$wbwindow);\\n this.overrideFunctionBind(this.$wbwindow);\\n\\n // Doc Title\\n this.initDocTitleOverride();\\n this.initHashChange();\\n\\n // postMessage\\n // OPT skip\\n if (!this.wb_opts.skip_postmessage) {\\n this.initPostMessageOverride(this.$wbwindow);\\n this.initMessageEventOverride(this.$wbwindow);\\n }\\n\\n // proxy check this func\\n this.initCheckThisFunc(this.$wbwindow);\\n\\n\\n // add __wb_import__ for modules\\n this.initImportWrapperFunc(this.$wbwindow);\\n\\n // override getOwnPropertyNames\\n this.overrideGetOwnPropertyNames(this.$wbwindow);\\n\\n\\n this.initUIEventsOverrides();\\n\\n // write\\n this.initDocWriteOpenCloseOverride();\\n\\n // eval\\n this.initEvalOverride();\\n\\n // Ajax, Fetch, Request, Response, EventSource, WebSocket\\n this.initHTTPOverrides();\\n\\n // Audio\\n this.initAudioOverride();\\n\\n // FontFace\\n this.initFontFaceOverride(this.$wbwindow);\\n\\n // Worker override (experimental)\\n this.initWorkerOverrides();\\n\\n // text node overrides for js frameworks doing funky things with CSS\\n this.initTextNodeOverrides();\\n this.initCSSOMOverrides();\\n\\n // innerHTML & outerHTML can be overridden on prototype!\\n // we must override innerHTML & outerHTML on Element otherwise un-rewritten HTML\\n // can get into replay\\n this.overrideHtmlAssign(this.$wbwindow.Element, 'innerHTML', true);\\n this.overrideHtmlAssign(this.$wbwindow.Element, 'outerHTML', true);\\n this.overrideHtmlAssignSrcDoc(this.$wbwindow.HTMLIFrameElement, 'srcdoc', true);\\n this.overrideHtmlAssign(this.$wbwindow.HTMLStyleElement, 'textContent');\\n this.overrideShadowDom();\\n\\n // Document.URL override\\n this.overridePropExtract(this.$wbwindow.Document.prototype, 'URL');\\n this.overridePropExtract(this.$wbwindow.Document.prototype, 'documentURI');\\n\\n // Node.baseURI override\\n this.overridePropExtract(this.$wbwindow.Node.prototype, 'baseURI');\\n\\n // Attr nodeValue and value\\n this.overrideAttrProps();\\n\\n // Override dataset access and wrap in proxy\\n this.overrideDataSet();\\n\\n // init insertAdjacent[Element, HTML] override\\n this.initInsertAdjacentElementHTMLOverrides();\\n\\n // iframe.contentWindow and iframe.contentDocument overrides to\\n // ensure _wombat is inited on the iframe $wbwindow!\\n this.overrideIframeContentAccess('contentWindow');\\n this.overrideIframeContentAccess('contentDocument');\\n\\n // override funcs to convert first arg proxy->obj\\n this.overrideFuncArgProxyToObj(this.$wbwindow.MutationObserver, 'observe');\\n this.overrideFuncArgProxyToObj(\\n this.$wbwindow.Node,\\n 'compareDocumentPosition'\\n );\\n this.overrideFuncArgProxyToObj(this.$wbwindow.Node, 'contains');\\n this.overrideFuncArgProxyToObj(this.$wbwindow.Document, 'createTreeWalker');\\n this.overrideFuncArgProxyToObj(this.$wbwindow.Document, 'evaluate', 1);\\n this.overrideFuncArgProxyToObj(\\n this.$wbwindow.XSLTProcessor,\\n 'transformToFragment',\\n 1\\n );\\n\\n this.overrideFuncThisProxyToObj(\\n this.$wbwindow,\\n 'getComputedStyle',\\n this.$wbwindow\\n );\\n\\n this.overrideFuncThisProxyToObj(this.$wbwindow, 'clearTimeout');\\n this.overrideFuncThisProxyToObj(this.$wbwindow, 'clearInterval');\\n\\n this.overrideFuncThisProxyToObj(\\n this.$wbwindow.EventTarget.prototype,\\n 'dispatchEvent'\\n );\\n\\n this.initTimeoutIntervalOverrides();\\n\\n this.overrideFramesAccess(this.$wbwindow);\\n\\n this.overrideSWAccess(this.$wbwindow);\\n\\n // setAttribute\\n this.initElementGetSetAttributeOverride();\\n\\n this.initSvgImageOverrides();\\n\\n // override href and src attrs\\n this.initAttrOverrides();\\n\\n // Cookies\\n this.initCookiesOverride();\\n\\n // ensure namespace urls are NOT rewritten\\n this.initCreateElementNSFix();\\n\\n // DOM\\n // OPT skip\\n if (!this.wb_opts.skip_dom) {\\n this.initDomOverride();\\n }\\n\\n // registerProtocolHandler override\\n this.initRegisterUnRegPHOverride();\\n this.initPresentationRequestOverride();\\n\\n // sendBeacon override\\n this.initBeaconOverride();\\n\\n // additional navigator. overrides\\n this.initMiscNavigatorOverrides();\\n\\n // other overrides\\n // proxy mode: only using these overrides\\n\\n // Random\\n this.initSeededRandom(this.wb_info.wombat_sec);\\n\\n // Crypto Random\\n this.initCryptoRandom();\\n\\n // set fixed pixel ratio\\n this.initFixedRatio(this.wb_info.pixel_ratio || 1);\\n\\n // Date\\n this.initDateOverride(this.wb_info.wombat_sec);\\n\\n // Blob\\n this.initBlobOverride();\\n\\n // WebSocket\\n this.initWSOverride();\\n\\n // open\\n this.initOpenOverride();\\n\\n // disable notifications\\n this.initDisableNotificationsGeoLocation();\\n\\n // custom storage\\n this.initStorageOverride();\\n\\n // wrap caches to ensure only host sandboxed caches are available\\n this.initCachesOverride();\\n\\n // wraps indexeddb access to ensure only host sandboxed dbs are available\\n this.initIndexedDBOverride();\\n\\n // add window and document obj proxies, if available\\n this.initWindowObjProxy(this.$wbwindow);\\n this.initDocumentObjProxy(this.$wbwindow.document);\\n\\n var wombat = this;\\n return {\\n extract_orig: this.extractOriginalURL,\\n rewrite_url: this.rewriteUrl,\\n watch_elem: this.watchElem,\\n init_new_window_wombat: this.initNewWindowWombat,\\n init_paths: this.initPaths,\\n local_init: function(name) {\\n var res = wombat.$wbwindow._WB_wombat_obj_proxy[name];\\n if (name === 'document' && res && !res._WB_wombat_obj_proxy) {\\n return wombat.initDocumentObjProxy(res) || res;\\n }\\n return res;\\n },\\n showCSPViolations: function(yesNo) {\\n wombat._addRemoveCSPViolationListener(yesNo);\\n }\\n };\\n };\\n\\n window._WBWombat = Wombat;\\n window._WBWombatInit = function(wbinfo) {\\n if (!this._wb_wombat) {\\n var wombat = new Wombat(this, wbinfo);\\n this._wb_wombat = wombat.wombatInit();\\n } else {\\n this._wb_wombat.init_paths(wbinfo);\\n }\\n };\\n\\n})();\\n\\n\\n//# sourceURL=webpack://@webrecorder/wabac/./vendor/wombat.js?\");\n\n/***/ })\n\n/******/ \t});\n/************************************************************************/\n/******/ \t// The require scope\n/******/ \tvar __webpack_require__ = {};\n/******/ \t\n/************************************************************************/\n/******/ \t/* webpack/runtime/make namespace object */\n/******/ \t(() => {\n/******/ \t\t// define __esModule on exports\n/******/ \t\t__webpack_require__.r = (exports) => {\n/******/ \t\t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n/******/ \t\t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n/******/ \t\t\t}\n/******/ \t\t\tObject.defineProperty(exports, '__esModule', { value: true });\n/******/ \t\t};\n/******/ \t})();\n/******/ \t\n/************************************************************************/\n/******/ \t\n/******/ \t// startup\n/******/ \t// Load entry module and return exports\n/******/ \t// This entry module can't be inlined because the eval devtool is used.\n/******/ \tvar __webpack_exports__ = {};\n/******/ \t__webpack_modules__[\"./vendor/wombat.js\"](0, __webpack_exports__, __webpack_require__);\n/******/ \t\n/******/ })()\n;");
+;// CONCATENATED MODULE: ./node_modules/@webrecorder/wombat/src/wombatWorkers.js
+/* harmony default export */ const wombatWorkers = ("/**\n * Mini wombat for performing URL rewriting within the\n * Web/Shared/Service Worker context\n * @param {Object} info\n * @return {WBWombat}\n */\nfunction WBWombat(info) {\n if (!(this instanceof WBWombat)) return new WBWombat(info);\n /** @type {Object} */\n this.info = info;\n this.initImportScriptsRewrite();\n this.initHTTPOverrides();\n this.initClientApisOverride();\n this.initCacheApisOverride();\n}\n\n/**\n * Returns T/F indicating if the supplied URL is not to be rewritten\n * @param {string} url\n * @return {boolean}\n */\nWBWombat.prototype.noRewrite = function(url) {\n return (\n !url ||\n url.indexOf('blob:') === 0 ||\n url.indexOf('javascript:') === 0 ||\n url.indexOf('data:') === 0 ||\n url.indexOf(this.info.prefix) === 0\n );\n};\n\n/**\n * Returns T/F indicating if the supplied URL is an relative URL\n * @param {string} url\n * @return {boolean}\n */\nWBWombat.prototype.isRelURL = function(url) {\n return url.indexOf('/') === 0 || url.indexOf('http:') !== 0;\n};\n\n/**\n * Attempts to resolve the supplied relative URL against\n * the origin this worker was created on\n * @param {string} maybeRelURL\n * @param {string} against\n * @return {string}\n */\nWBWombat.prototype.maybeResolveURL = function(maybeRelURL, against) {\n if (!against) return maybeRelURL;\n try {\n var resolved = new URL(maybeRelURL, against);\n return resolved.href;\n } catch (e) {}\n return maybeRelURL;\n};\n\n/**\n * Returns null to indicate that the supplied URL is not to be rewritten.\n * Otherwise returns a URL that can be rewritten\n * @param {*} url\n * @param {string} resolveAgainst\n * @return {?string}\n */\nWBWombat.prototype.ensureURL = function(url, resolveAgainst) {\n if (!url) return url;\n var newURL;\n switch (typeof url) {\n case 'string':\n newURL = url;\n break;\n case 'object':\n newURL = url.toString();\n break;\n default:\n return null;\n }\n if (this.noRewrite(newURL)) return null;\n if (this.isRelURL(newURL)) {\n return this.maybeResolveURL(newURL, resolveAgainst);\n }\n\n // if url starts with current origin, but not properly rewritten, rewrite against current baseUr\n if (newURL.indexOf(self.location.origin) === 0) {\n return this.maybeResolveURL(newURL.slice(self.location.origin.length), resolveAgainst);\n }\n return newURL;\n};\n\n/**\n * Rewrites the supplied URL\n * @param {string} url\n * @return {string}\n */\nWBWombat.prototype.rewriteURL = function(url) {\n var rwURL = this.ensureURL(url, this.info.originalURL);\n if (!rwURL) return url;\n if (this.info.prefixMod) {\n return this.info.prefixMod + rwURL;\n }\n return rwURL;\n};\n\n/**\n * Rewrites the supplied URL of an controlled page using the mp\\_ modifier\n * @param {string} url\n * @param {WindowClient} [client]\n * @return {string}\n */\nWBWombat.prototype.rewriteClientWindowURL = function(url, client) {\n var rwURL = this.ensureURL(url, client ? client.url : this.info.originalURL);\n if (!rwURL) return url;\n if (this.info.prefix) {\n return this.info.prefix + 'mp_/' + rwURL;\n }\n return rwURL;\n};\n\n/**\n * Mini url rewriter specifically for rewriting web sockets\n * @param {?string} originalURL\n * @return {string}\n */\nWBWombat.prototype.rewriteWSURL = function(originalURL) {\n // If undefined, just return it\n if (!originalURL) return originalURL;\n\n var urltype_ = typeof originalURL;\n var url = originalURL;\n\n // If object, use toString\n if (urltype_ === 'object') {\n url = originalURL.toString();\n } else if (urltype_ !== 'string') {\n return originalURL;\n }\n\n // empty string check\n if (!url) return url;\n\n var wsScheme = 'ws://';\n var wssScheme = 'wss://';\n var https = 'https://';\n\n var wbSecure = this.info.prefix.indexOf(https) === 0;\n var wbPrefix =\n this.info.prefix.replace(\n wbSecure ? https : 'http://',\n wbSecure ? wssScheme : wsScheme\n ) + 'ws_/';\n return wbPrefix + url;\n};\n\n/**\n * Rewrites all URLs in the supplied arguments object\n * @param {Object} argsObj\n * @return {Array}\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");
+;// CONCATENATED MODULE: ./src/request.js
+
+
+const REPLAY_REGEX = /^(?::([\w-]+)\/)?(\d*)([a-z]+_|[$][a-z0-9:.-]+)?(?:\/|\||%7C|%7c)(.+)/;
+
+
+class ArchiveRequest
+{
+ constructor(wbUrlStr, request, {isRoot = false, mod = "", ts = "", proxyOrigin = null, localOrigin = null} = {})
+ {
+ const wbUrl = REPLAY_REGEX.exec(wbUrlStr);
+
+ this.url = "";
+ this.timestamp = ts;
+ this.mod = mod;
+ this.pageId = "";
+ this.hash = "";
+
+ if (!wbUrl && (wbUrlStr.startsWith("https:") || wbUrlStr.startsWith("http:") || wbUrlStr.startsWith("blob:"))) {
+ this.url = wbUrlStr;
+ } else if (!wbUrl && isRoot) {
+ this.url = "https://" + wbUrlStr;
+ } else if (!wbUrl) {
+ this.url = null;
+ return;
+ } else {
+ this.pageId = wbUrl[1] || "";
+ this.timestamp = wbUrl[2];
+ this.mod = wbUrl[3];
+ this.url = wbUrl[4];
+ }
+
+ if (proxyOrigin && localOrigin) {
+ const url = new URL(this.url);
+ if (url.origin === localOrigin) {
+ this.url = proxyOrigin + url.pathname + (url.search ? url.search : "");
+ }
+ }
+
+ const hashIndex = this.url.indexOf("#");
+ if (hashIndex > 0) {
+ this.hash = this.url.slice(hashIndex);
+ this.url = this.url.substring(0, hashIndex);
+ }
+
+ this.request = request;
+ this.method = request.method;
+ this.mode = request.mode;
+ this._postToGetConverted = false;
+ }
+
+ 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 request = this.request;
+
+ if (request.method !== "POST" && request.method !== "PUT") {
+ return this.url;
+ }
+
+ const data = {
+ method: request.method,
+ postData: await request.text(),
+ headers: request.headers,
+ url: this.url
+ };
+
+ if (L(data)) {
+ this.url = data.url;
+ this.method = "GET";
+ this.mode = this.request.mode === "navigate" ? "same-origin" : this.request.mode;
+ this._postToGetConverted = true;
+ }
+
+ return this.url;
+ }
+
+ prepareProxyRequest(prefix, isLive = true) {
+ let headers;
+ let referrer;
+ let credentials;
+
+ if (isLive) {
+ headers = new Headers(this.request.headers);
+ referrer = this.request.referrer;
+ const inx = referrer.indexOf("/http", prefix.length - 1);
+ if (inx > 0) {
+ referrer = referrer.slice(inx + 1);
+ headers.set("X-Proxy-Referer", referrer);
+ }
+ credentials = this.request.credentials;
+ if (this.cookie) {
+ headers.set("X-Proxy-Cookie", this.cookie);
+ }
+ } else {
+ headers = new Headers();
+ credentials = "omit";
+ }
+
+ let url = this.url;
+
+ if (url.startsWith("//")) {
+ try {
+ url = new URL(referrer).protocol + url;
+ } catch(e) {
+ url = "https:" + url;
+ }
+ }
+
+ return {referrer, headers, credentials, url};
+ }
+
+ async getBody() {
+ const request = this.request.clone();
+ return new Uint8Array(await request.arrayBuffer());
+ }
+}
+
+;// CONCATENATED MODULE: ./src/swmain.js
+
+
+
+
+
+
+
+
+
+
+
+
+
+const CACHE_PREFIX = "wabac-";
+const IS_AJAX_HEADER = "x-wabac-is-ajax-req";
+
+
+// ===========================================================================
+class SWCollections extends WorkerLoader
+{
+ constructor(prefixes, root = null, defaultConfig = {}) {
+ super(self);
+ this.prefixes = prefixes;
+ this.colls = {};
+ this.inited = null;
+ this.root = root;
+ this.defaultConfig = defaultConfig;
+
+ this._fileHandles = {};
+ }
+
+ _createCollection(opts) {
+ return new Collection(opts, this.prefixes, this.defaultConfig);
+ }
+
+ loadAll(dbColl) {
+ this.colls = {};
+ this.inited = super.loadAll(dbColl);
+ return this.inited;
+ }
+
+ async getColl(name) {
+ if (!this.colls[name]) {
+ this.colls[name] = await this.loadColl(name);
+ }
+ return this.colls[name];
+ }
+
+ async reload(name) {
+ delete this.colls[name];
+
+ await this.getColl(name);
+ }
+
+ async addCollection(data, progressUpdate) {
+ const opts = await super.addCollection(data, progressUpdate);
+
+ if (opts && opts.name) {
+ this.colls[opts.name] = this._createCollection(opts);
+ }
+
+ return opts;
+ }
+
+ async deleteColl(name, keepFileHandle = false) {
+ if (this.colls[name]) {
+ if (this.colls[name].store && this.colls[name].store.delete) {
+ await this.colls[name].store.delete();
+ }
+
+ if (keepFileHandle && this.colls[name].config && this.colls[name].config.extra &&
+ this.colls[name].config.extra.fileHandle) {
+ this._fileHandles[this.colls[name].config.sourceUrl] = this.colls[name].config.extra.fileHandle;
+ }
+ }
+
+ if (!await super.deleteColl(name)) {
+ return false;
+ }
+ delete this.colls[name];
+ return true;
+ }
+
+ async initNewColl(metadata, extraConfig = {}, type = "archive") {
+ const coll = await super.initNewColl(metadata, extraConfig, type);
+ if (coll) {
+ this.colls[coll.name] = coll;
+ }
+ return coll;
+ }
+
+ async updateAuth(name, headers) {
+ if (this.colls[name] && this.colls[name].store.updateHeaders) {
+ this.colls[name].store.updateHeaders(headers);
+ }
+
+ await super.updateAuth(name, headers);
+ }
+
+ async updateMetadata(name, newMetadata) {
+ const metadata = await super.updateMetadata(name, newMetadata);
+ if (this.colls[name] && metadata) {
+ this.colls[name].config.metadata = metadata;
+ this.colls[name].metadata = metadata;
+ }
+ return metadata;
+ }
+
+ async updateSize(name, fullSize, dedupSize, updateDecode) {
+ const metadata = await super.updateSize(name, fullSize, dedupSize, updateDecode);
+ if (this.colls[name] && metadata) {
+ this.colls[name].config.metadata = metadata;
+ this.colls[name].metadata = metadata;
+ }
+ if (updateDecode !== undefined && this.colls[name]) {
+ this.colls[name].config.decode = updateDecode;
+ }
+ return metadata;
+ }
+}
+
+
+// ===========================================================================
+class SWReplay {
+ constructor({staticData = null, ApiClass = api_API, defaultConfig = {}, CollectionsClass = SWCollections} = {}) {
+ if (!this.prefix) {
+ this.prefix = self.registration ? self.registration.scope : "";
+ }
+
+ this.replayPrefix = this.prefix;
+
+ const sp = new URLSearchParams(self.location.search);
+
+ let replayPrefixPath = "w";
+
+ if (sp.has("replayPrefix")) {
+ replayPrefixPath = sp.get("replayPrefix");
+ }
+
+ if (replayPrefixPath) {
+ this.replayPrefix += replayPrefixPath + "/";
+ }
+
+ this.staticPrefix = this.prefix + "static/";
+ this.distPrefix = this.prefix + "dist/";
+
+ const prefixes = {
+ static: this.staticPrefix,
+ root: this.prefix,
+ main: this.replayPrefix
+ };
+
+ this.staticData = staticData || new Map();
+ this.staticData.set(this.staticPrefix + "wombat.js", {type: "application/javascript", content: wombat});
+ this.staticData.set(this.staticPrefix + "wombatWorkers.js", {type: "application/javascript", content: wombatWorkers});
+
+ if (defaultConfig.injectScripts) {
+ defaultConfig.injectScripts = defaultConfig.injectScripts.map(url => this.staticPrefix + "proxy/" + url);
+ }
+
+ this.collections = new CollectionsClass(prefixes, sp.get("root"), defaultConfig);
+ this.collections.loadAll(sp.get("dbColl"));
+
+ this.proxyOriginMode = !!sp.get("proxyOriginMode");
+
+ this.api = new ApiClass(this.collections);
+ this.apiPrefix = this.replayPrefix + "api/";
+
+ this.allowRewrittenCache = sp.get("allowCache") ? true : false;
+
+ this.stats = sp.get("stats") ? new StatsTracker() : null;
+
+ /* modded for kiwix-js
+
+ // self.addEventListener("install", () => {
+ // self.skipWaiting();
+ // });
+
+ // self.addEventListener("activate", (event) => {
+ // event.waitUntil(self.clients.claim());
+ // console.log("Activate!");
+ // });
+
+ // self.addEventListener("fetch", (event) => {
+ // event.respondWith(this.handleFetch(event));
+ // });
+
+ // self.addEventListener("message", (event) => {
+ // if (event.data.msg_type === "reload_all") {
+ // event.waitUntil(this.collections.loadAll());
+ // }
+ // });
+
+ */
+ }
+
+ handleFetch(event) {
+ var that = this || sw;
+ const url = event.request.url;
+
+ if (that.proxyOriginMode) {
+ return that.getResponseFor(event.request, event);
+ }
+
+ // if not on our domain, just pass through (loading handled in local worker)
+ if (!url.startsWith(that.prefix)) {
+ if (url === "chrome-extension://invalid/") {
+ return notFound(event.request, "Invalid URL");
+ }
+ return that.defaultFetch(event.request);
+ }
+
+ // special handling when root collection set: pass through any root files, eg. /index.html
+ if (that.collections.root && url.slice(that.prefix.length).indexOf("/") < 0) {
+ return that.defaultFetch(event.request);
+ }
+
+ // JS rewrite on static/external files not from archive
+ if (url.startsWith(that.staticPrefix + "proxy/")) {
+ return that.staticPathProxy(url, event.request);
+ }
+
+ // handle replay / api
+ if (url.startsWith(that.replayPrefix) && !url.startsWith(that.staticPrefix)) {
+ return that.getResponseFor(event.request, event);
+ }
+
+ // current domain, but not replay, check if should cache ourselves or serve static data
+ const parsedUrl = new URL(url);
+ parsedUrl.search = "";
+ parsedUrl.hash = "";
+ const urlOnly = parsedUrl.href;
+
+ for (const staticPath of that.staticData.keys()) {
+ if (staticPath === urlOnly) {
+ const { content, type} = that.staticData.get(staticPath);
+ return new Response(content, {headers: {"Content-Type": type}});
+ }
+ }
+
+ // only cache: urls in the root directory (no more slashes)
+ if ((parsedUrl.protocol == "http:" || parsedUrl.protocol == "https:") && (parsedUrl.pathname.indexOf("/", 1) < 0)) {
+ return that.handleOffline(event.request);
+ } else {
+ return that.defaultFetch(event.request);
+ }
+ }
+
+ staticPathProxy(url, request) {
+ url = url.slice((this.staticPrefix + "proxy/").length);
+ url = new URL(url, self.location.href).href;
+ request = new Request(url);
+ return this.defaultFetch(request);
+ }
+
+ defaultFetch(request) {
+ const opts = {};
+ if (request.cache === "only-if-cached" && request.mode !== "same-origin") {
+ opts.cache = "default";
+ }
+ return Promise.resolve(request);
+ }
+
+ async ensureCached(urls) {
+ const cache = await caches.open("wabac-offline");
+
+ for (let url of urls) {
+ url = new URL(url, self.location.href).href;
+ let response = await cache.match(url, {ignoreSearch: true});
+ if (response) {
+ continue;
+ }
+
+ //console.log(`Auto Cacheing: ${url}`);
+ try {
+ response = await this.defaultFetch(url);
+ await cache.put(url, response);
+ } catch(e) {
+ console.warn(`Failed to Auto Cache: ${url}`, e);
+ }
+ }
+ }
+
+ async handleOffline(request) {
+ let response = null;
+
+ const cache = await caches.open("wabac-offline");
+
+ try {
+ response = await this.defaultFetch(request);
+
+ } catch(e) {
+ response = await cache.match(request, {ignoreSearch: true});
+ if (!response) {
+ response = notFound(request, "Sorry, this url was not cached for offline use");
+ }
+ return response;
+ }
+
+ if (request.url.startsWith(this.prefix + "?")) {
+ return response;
+ }
+
+ if (response.status === 200) {
+ const cacheResponse = response.clone();
+ await cache.put(request, cacheResponse);
+ //console.log(`Cached: ${request.method} ${request.url}`);
+ } else {
+ console.warn(`Not Cacheing ${request.url} - Status ${response.status}`);
+ }
+
+ return response;
+ }
+
+ async getResponseFor(request, event) {
+ // API
+ if (!this.proxyOriginMode && request.url.startsWith(this.apiPrefix)) {
+ if (this.stats && request.url.startsWith(this.apiPrefix + "stats.json")) {
+ return await this.stats.getStats(event);
+ }
+ return await this.api.apiResponse(request.url.slice(this.apiPrefix.length), request, event);
+ }
+
+ await this.collections.inited;
+
+ const isAjax = isAjaxRequest(request);
+ const range = request.headers.get("range");
+
+ try {
+ if (this.allowRewrittenCache && !range) {
+ const response = await self.caches.match(request);
+ if (response && !!response.headers.get(IS_AJAX_HEADER) === isAjax) {
+ return response;
+ }
+ }
+ } catch (e) {
+ // ignore, not cached
+ }
+
+ let collId = this.collections.root;
+
+ if (!collId) {
+ collId = request.url.slice(this.replayPrefix.length).split("/", 1)[0];
+ }
+
+ const coll = await this.collections.getColl(collId);
+
+ if (!coll || (!this.proxyOriginMode && !request.url.startsWith(coll.prefix))) {
+ return notFound(request);
+ }
+
+ const wbUrlStr = this.proxyOriginMode ? request.url : request.url.substring(coll.prefix.length);
+
+ const opts = {
+ isRoot: !!this.collections.root
+ };
+
+ if (this.proxyOriginMode) {
+ opts.mod = "id_";
+ opts.proxyOrigin = coll.config.extraConfig.proxyOrigin;
+ opts.localOrigin = self.location.origin;
+ }
+
+ const archiveRequest = new ArchiveRequest(wbUrlStr, request, opts);
+
+ if (!archiveRequest.url) {
+ return notFound(request, `Replay URL ${wbUrlStr} not found`);
+ }
+
+ const response = await coll.handleRequest(archiveRequest, event);
+
+ if (response) {
+ if (this.stats) {
+ this.stats.updateStats(response.date, response.status, request, event);
+ }
+
+ if (this.allowRewrittenCache && response.status === 200) {
+ try {
+ const cache = await self.caches.open(CACHE_PREFIX + coll.name);
+ if (isAjax) {
+ response.headers.set(IS_AJAX_HEADER, "true");
+ }
+ const cacheResp = response.clone();
+ await cache.put(request, cacheResp);
+ } catch (e) {
+ console.warn(e);
+ }
+ }
+
+ return response;
+ }
+
+ if (range) {
+ console.log("Not Found Range!: " + range);
+ }
+
+ return notFound(request);
+ }
+}
+
+
+
+
+;// CONCATENATED MODULE: ./src/sw.js
+
+
+
+if (self.registration) {
+// Service Worker Init
+ self.sw = new SWReplay();
+ console.log("sw init");
+} else if (self.postMessage) {
+// Inited as Web Worker
+ new WorkerLoader(self);
+ console.log("ww init");
+}
+
+
+
+})();
+
+/******/ })()
+;
\ No newline at end of file
diff --git a/rollup.config.js b/rollup.config.js
index 04dcd3a5..16e9bb99 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -1,10 +1,12 @@
// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
+import { transformAsync } from '@babel/core';
import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace';
import copy from 'rollup-plugin-copy';
import terser from '@rollup/plugin-terser';
+import { minify } from 'terser';
// import styles from "@ironkinoko/rollup-plugin-styles";
const config = {
@@ -69,20 +71,54 @@ if (process.env.BUILD === 'production') {
src: ['service-worker.js'],
dest: 'dist',
// Modify the Service Worker precache files
- transform: (contents, filename) => contents.toString()
- // Replace the entry point with the bundle
- .replace(/(www[\\/]js[\\/])app.js/, '$1bundle.min.js')
- // Remove all the lib files that will be included in the bundle
- .replace(/,\s+["']www[\\/]js[\\/]lib[\\/]abstractFilesystemAccess[\s\S]+zimfile.js["']\s*/, '')
- // Replace any references to node_modules
- .replace(/node_modules\/.*dist\/((?:js|css)\/)?/g, function (m, p1) {
- p1 = p1 || 'js/';
- return 'www/' + p1;
- })
- // Alter remaining lib references
- .replace(/([\\/])js[\\/]lib/g, '$1js')
- // Remove unneeded ASM/WASM binaries
- .replace(/["']www[\\/]js[\\/].*dec.*js["'],\s*/g, '')
+ transform: async (contents, filename) => {
+ const result = await minify(
+ contents.toString()
+ // Replace the entry point with the bundle
+ .replace(/(www[\\/]js[\\/])app.js/, '$1bundle.min.js')
+ // Remove all the lib files that will be included in the bundle
+ .replace(/,\s+["']www[\\/]js[\\/]lib[\\/]abstractFilesystemAccess[\s\S]+zimfile.js["']\s*/, '')
+ // Replace any references to node_modules
+ .replace(/node_modules\/.*dist\/((?:js|css)\/)?/g, function (m, p1) {
+ p1 = p1 || 'js/';
+ return 'www/' + p1;
+ })
+ // Alter remaining lib references
+ .replace(/([\\/])js[\\/]lib/g, '$1js')
+ // Remove unneeded ASM/WASM binaries
+ .replace(/["']www[\\/]js[\\/].*dec.*js["'],\s*/g, '')
+ );
+ return result.code;
+ }
+ },
+ {
+ src: ['replayWorker.js'],
+ dest: 'dist',
+ transform: async (contents, filename) => {
+ const code = contents.toString();
+ // Now minify the replayWorker
+ const minified = await minify(code);
+ // How to transform with babel (tested to make a difference with Firefox 68+)
+ const result = await transformAsync(minified.code, {
+ filename,
+ presets: [
+ [
+ '@babel/preset-env',
+ {
+ targets: {
+ edge: '18',
+ firefox: '60',
+ chrome: '67',
+ safari: '11.1'
+ },
+ modules: false,
+ spec: true
+ }
+ ]
+ ]
+ });
+ return result.code;
+ }
},
{
src: 'www/index.html',
@@ -134,6 +170,10 @@ if (process.env.BUILD === 'production') {
// Remove unneeded ASM/WASM binaries
.replace(/["']www[\\/]js[\\/].*dec.*js["'],\s*/g, '')
},
+ {
+ src: ['replayWorker.js'],
+ dest: 'dist'
+ },
{
src: 'www/index.html',
dest: 'dist/www',
diff --git a/service-worker.js b/service-worker.js
index 14439c0a..b3cd9a2a 100644
--- a/service-worker.js
+++ b/service-worker.js
@@ -25,13 +25,15 @@
/* global chrome */
+/* eslint-disable prefer-const */
+
/**
* App version number - ENSURE IT MATCHES VALUE IN init.js
* DEV: Changing this will cause the browser to recognize that the Service Worker has changed, and it will
* download and install a new copy; we have to hard code this here because it is needed before any other file
* is cached in APP_CACHE
*/
-const appVersion = '3.11.1';
+const appVersion = '3.11.2';
/**
* The name of the Cache API cache in which assets defined in regexpCachedContentTypes will be stored
@@ -64,6 +66,11 @@ var useAssetsCache = true;
*/
var useAppCache = true;
+/**
+ * A global Boolean that records whether the ReplayWorker is available
+ */
+var isReplayWorkerAvailable = false;
+
/**
* A regular expression that matches the Content-Types of assets that may be stored in ASSETS_CACHE
* Add any further Content-Types you wish to cache to the regexp, separated by '|'
@@ -103,6 +110,7 @@ const regexpByteRangeHeader = /^\s*bytes=(\d+)-/;
const precacheFiles = [
'.', // This caches the redirect to www/index.html, in case a user launches the app from its root directory
'manifest.json',
+ 'replayWorker.js',
'service-worker.js',
'i18n/en.jsonp.js',
'i18n/es.jsonp.js',
@@ -120,6 +128,7 @@ const precacheFiles = [
'www/article.html',
'www/library.html',
'www/main.html',
+ 'www/topFrame.html',
'www/js/app.js',
'www/js/init.js',
'www/js/lib/abstractFilesystemAccess.js',
@@ -223,6 +232,40 @@ self.addEventListener('activate', function (event) {
);
});
+// Wrapped in try-catch
+try {
+ // Import ReplayWorker
+ self.importScripts('./replayWorker.js');
+ isReplayWorkerAvailable = true;
+ console.log('[SW] ReplayWorker is available');
+} catch (err) {
+ console.warn('[SW ReplayWorker is NOT available', err);
+ isReplayWorkerAvailable = false;
+}
+
+let replayCollectionsReloaded;
+
+// Instruct the ReplayWorker to reload all collections, and adjust the root configuration (this is necessary after thw SW has stopped and restarted)
+if (isReplayWorkerAvailable) {
+ replayCollectionsReloaded = self.sw.collections.listAll().then(function (colls) {
+ if (colls) {
+ console.debug('[SW] Reloading ReplayWorker collections', colls);
+ return Promise.all(colls.map(function (coll) {
+ // console.debug('[SW] Reloading ReplayWorker collection ' + coll.name);
+ return self.sw.collections.reload(coll.name);
+ })).then(function () {
+ // Adjust the root configuration
+ if (self.sw.collections.root) {
+ console.debug('[SW] Adjusting ReplayWorker root configuration to ' + self.sw.collections.root);
+ return setReplayCollectionAsRoot(self.sw.collections.colls[self.sw.collections.root].config.sourceUrl, self.sw.collections.root);
+ }
+ });
+ } else {
+ console.debug('[SW] No ReplayWorker collections to reload');
+ }
+ });
+}
+
// For PWA functionality, this should be true unless explicitly disabled, and in fact currently it is never disabled
let fetchCaptureEnabled = true;
@@ -230,6 +273,7 @@ let fetchCaptureEnabled = true;
* Intercept selected Fetch requests from the browser window
*/
self.addEventListener('fetch', function (event) {
+ // console.debug('[SW] Fetch Event processing', event.request.url);
// Only handle GET or POST requests (POST is intended to handle video in Zimit ZIMs)
if (!/GET|POST/.test(event.request.method)) return;
var rqUrl = event.request.url;
@@ -252,32 +296,36 @@ self.addEventListener('fetch', function (event) {
}, function () {
// The response was not found in the cache so we look for it in the ZIM
// and add it to the cache if it is an asset type (css or js)
- // YouTube links from Zimit archives are dealt with specially
- if (/youtubei.*player/.test(strippedUrl) || cache === ASSETS_CACHE && regexpZIMUrlWithNamespace.test(strippedUrl)) {
- const range = event.request.headers.get('range');
- return fetchUrlFromZIM(urlObject, range).then(function (response) {
- // Add css or js assets to ASSETS_CACHE (or update their cache entries) unless the URL schema is not supported
- if (regexpCachedContentTypes.test(response.headers.get('Content-Type')) &&
- !regexpExcludedURLSchema.test(event.request.url)) {
- event.waitUntil(updateCache(ASSETS_CACHE, rqUrl, response.clone()));
- }
- return response;
- }).catch(function (msgPortData) {
- console.error('Invalid message received from app.js for ' + strippedUrl, msgPortData);
- return msgPortData;
- });
- } else {
- // It's not an asset, or it doesn't match a ZIM URL pattern, so we should fetch it with Fetch API
- return fetch(event.request).then(function (response) {
- // If request was successful, add or update it in the cache, but be careful not to cache the ZIM archive itself!
- if (!regexpExcludedURLSchema.test(event.request.url) && !/\.zim\w{0,2}$/i.test(strippedUrl)) {
- event.waitUntil(updateCache(APP_CACHE, rqUrl, response.clone()));
- }
- return response;
- }).catch(function (error) {
- console.debug('[SW] Network request failed and no cache.', error);
- });
- }
+ return zimitResolver(event).then(function (modRequestOrResponse) {
+ if (modRequestOrResponse instanceof Response) {
+ // The request was modified by the ReplayWorker and it returned a modified response, so we return it
+ // console.debug('[SW] Returning modified response from ReplayWorker', modRequest);
+ return cacheAndReturnResponseForAsset(event, modRequestOrResponse);
+ }
+ rqUrl = modRequestOrResponse.url;
+ urlObject = new URL(rqUrl);
+ strippedUrl = urlObject.pathname;
+ if (cache === ASSETS_CACHE && regexpZIMUrlWithNamespace.test(strippedUrl)) {
+ const range = modRequestOrResponse.headers.get('range');
+ return fetchUrlFromZIM(urlObject, range).then(function (response) {
+ return cacheAndReturnResponseForAsset(event, response);
+ }).catch(function (msgPortData) {
+ console.error('Invalid message received from app.js for ' + strippedUrl, msgPortData);
+ return msgPortData;
+ });
+ } else {
+ // It's not an asset, or it doesn't match a ZIM URL pattern, so we should fetch it with Fetch API
+ return fetch(modRequestOrResponse).then(function (response) {
+ // If request was successful, add or update it in the cache, but be careful not to cache the ZIM archive itself!
+ if (!regexpExcludedURLSchema.test(rqUrl) && !/\.zim\w{0,2}$/i.test(strippedUrl)) {
+ event.waitUntil(updateCache(APP_CACHE, rqUrl, response.clone()));
+ }
+ return response;
+ }).catch(function (error) {
+ console.debug('[SW] Network request failed and no cache.', error);
+ });
+ }
+ });
})
);
});
@@ -324,51 +372,218 @@ self.addEventListener('message', function (event) {
event.ports[0].postMessage({ type: cacheArr[0], name: cacheArr[1], description: cacheArr[2], count: cacheArr[3] });
});
}
+ } else if (event.data.msg_type) {
+ // Messages for the ReplayWorker
+ if (event.data.msg_type === 'addColl') {
+ console.debug('[SW] addColl message received from app.js');
+ if (!self.sw) {
+ console.error('[SW] Zimit ZIMs in ServiceWorker mode are not supported in this browser');
+ // Reply to the message port with an error
+ event.ports[0].postMessage({ error: 'ReplayWorker is unsupported!' });
+ } else {
+ event.waitUntil(
+ self.sw.collections._handleMessage(event).then(function () {
+ setReplayCollectionAsRoot(event.data.prefix, event.data.name);
+ // Reply to the message port with a success message
+ event.ports[0].postMessage({ success: 'ReplayWorker is supported!' });
+ })
+ );
+ }
+ }
}
});
/**
- * Handles URLs that need to be extracted from the ZIM archive
+ * Sets a Replay collection as the root configuration, so that the Replay Worker will deal correctly with requests to the collection
*
- * @param {URL} urlObject The URL object to be processed for extraction from the ZIM
- * @param {String} range Optional byte range string
+ * @param {String} prefix The URL prefix where assets are loaded, consisting of the local path to the ZIM file plus the namespace
+ * @param {String} name The name of the ZIM file (wihtout any extension), used as the Replay root
+ */
+function setReplayCollectionAsRoot (prefix, name) {
+ // Guard against prototype pollution attack
+ if (typeof prefix !== 'string' || typeof name !== 'string') {
+ console.error('Invalid prefix or name');
+ return;
+ }
+ const dangerousProps = ['__proto__', 'constructor', 'prototype'];
+ if (dangerousProps.includes(prefix) || dangerousProps.includes(name)) {
+ console.error('Potentially dangerous prefix or name');
+ return;
+ }
+ self.sw.prefix = prefix;
+ self.sw.replayPrefix = prefix;
+ self.sw.distPrefix = prefix + 'dist/';
+ self.sw.apiPrefix = prefix + 'api/';
+ self.sw.staticPrefix = prefix + 'static/';
+ self.sw.api.collections.prefixes = {
+ main: self.sw.prefix,
+ root: self.sw.prefix,
+ static: self.sw.staticPrefix
+ }
+ // If we want to be able to get the static data URL directly from the map, we need to replace the keyes, but as this is quite costly (moving a lot of static)
+ // data around, we're using another way to get the static data URL from the map in zimitResolver()
+ // let newMap = new Map();
+ // for (let [key, value] of self.sw.staticData.entries()) {
+ // const newKey = /wombat\.js/i.test(key) ? self.sw.staticPrefix + 'wombat.js' : /wombatWorkers\.js/i.test(key) ? self.sw.staticPrefix + 'wombatWorkers.js' : key;
+ // newMap.set(newKey, value);
+ // }
+ // self.sw.staticData = newMap;
+ if (self.sw.collections.colls[name]) {
+ self.sw.collections.colls[name].prefix = self.sw.prefix;
+ self.sw.collections.colls[name].rootPrefix = self.sw.prefix;
+ self.sw.collections.colls[name].staticPrefix = self.sw.staticPrefix;
+ self.sw.collections.root = name;
+ }
+}
+
+/**
+ * Handles resolving content for Zimit-style ZIM archives
+ *
+ * @param {FetchEvent} event The FetchEvent to be processed
* @returns {Promise} A Promise for the Response, or rejects with the invalid message port data
*/
-function fetchUrlFromZIM (urlObject, range) {
+function zimitResolver (event) {
+ var rqUrl = event.request.url;
+ var zimStem = rqUrl.replace(/^.*?\/([^/]+?)\.zim\w?\w?\/.*/, '$1');
+ if (/\/A\/load\.js$/.test(rqUrl)) {
+ // If the request is for load.js, we should filter its contents to load the mainUrl, as we don't need the other stuff
+ // concerning registration of the ServiceWorker and postMessage handling
+ console.debug('[SW] Filtering content of load.js', rqUrl);
+ // First we have to get the contents of load.js from the ZIM, because it is a common name, and there is no way to be sure
+ // that the request will be for the Zimit load.js
+ return fetchUrlFromZIM(new URL(rqUrl)).then(function (response) {
+ // The response was found in the ZIM so we respond with it
+ // Clone the response before reading its body
+ var clonedResponse = response.clone();
+ return response.text().then(function (contents) {
+ // We need to replace the entire contents with a single function that loads mainUrl
+ if (/\.register\([^;]+?sw\.js\?replayPrefix/.test(contents)) {
+ var newContents = "window.location.href = window.location.href.replace(/index\\.html/, window.mainUrl.replace('https://', ''));";
+ var responseLoadJS = contsructResponse(newContents, 'text/javascript');
+ return responseLoadJS;
+ } else {
+ // The contents of load.js are not as expected, so we should return the original response
+ return clonedResponse;
+ }
+ });
+ });
+ // Check that the requested URL is for a ZIM that we already have loaded
+ } else if (zimStem !== rqUrl && isReplayWorkerAvailable) {
+ // Wait for the ReplayWorker to initialize and reload all collections
+ return replayCollectionsReloaded.then(function () {
+ if (self.sw.collections.colls && self.sw.collections.colls[zimStem]) {
+ if (self.sw.collections.root !== zimStem) {
+ setReplayCollectionAsRoot(self.sw.collections.colls[zimStem].config.sourceUrl, zimStem);
+ }
+ if (/\/A\/static\//.test(rqUrl)) {
+ // If the request is for static data from the replayWorker, we should get them from the Worker's cache
+ // DEV: This extracts both wombat.js and wombatWorkers.js from the staticData Map
+ var staticDataUrl = rqUrl.replace(/^(.*?\/)[^/]+?\.zim\w?\w?\/[AC/]{2,4}(.*)/, '$1$2')
+ if (self.sw.staticData) {
+ var staticData = self.sw.staticData.get(staticDataUrl);
+ if (staticData) {
+ console.debug('[SW] Returning static data from ReplayWorker', rqUrl);
+ // Construct a new Response with headers to return the static data
+ var responseStaticData = contsructResponse(staticData.content, staticData.type);
+ return Promise.resolve(responseStaticData);
+ } else {
+ // Return a 404 response
+ return Promise.resolve(new Response('', { status: 404, statusText: 'Not Found' }));
+ }
+ }
+ } else {
+ // console.debug('[SW] Asking ReplayWorker to handleFetch', rqUrl);
+ return self.sw.handleFetch(event);
+ }
+ } else {
+ // The requested ZIM is not loaded, or it is a regular non-Zimit request
+ return event.request;
+ }
+ });
+ } else {
+ // The loaded ZIM archive is not a Zimit archive, or sw-Zimit is unsupported, so we should just return the request
+ return Promise.resolve(event.request);
+ }
+}
+
+function contsructResponse (content, contentType) {
+ var headers = new Headers();
+ headers.set('Content-Length', content.length);
+ headers.set('Content-Type', contentType);
+ var responseInit = {
+ status: 200,
+ statusText: 'OK',
+ headers: headers
+ };
+ return new Response(content, responseInit);
+}
+
+// Caches and returns the event and response pair for an asset. Do not use this for non-asset requests!
+function cacheAndReturnResponseForAsset (event, response) {
+ // Add css or js assets to ASSETS_CACHE (or update their cache entries) unless the URL schema is not supported
+ if (regexpCachedContentTypes.test(response.headers.get('Content-Type')) &&
+ !regexpExcludedURLSchema.test(event.request.url)) {
+ event.waitUntil(updateCache(ASSETS_CACHE, event.request.url, response.clone()));
+ }
+ return response;
+}
+
+/**
+ * Handles URLs that need to be extracted from the ZIM archive. They can be strings or URL objects, and should be URI encoded.
+ *
+ * @param {URL|String} urlObjectOrString The URL object, or a simple string representation, to be processed for extraction from the ZIM
+ * @param {String} range Optional byte range string (mostly used for video or audio streams)
+ * @param {String} expectedHeaders Optional comma-separated list of headers to be expected in the response (for error checking). Note that although
+ * Zimit requests may be for a range of bytes, in fact video (at least) is stored as a blob, so the appropriate response will just be a normal 200.
+ * @returns {Promise} A Promise for the Response, or rejects with the invalid message port data
+ */
+function fetchUrlFromZIM (urlObjectOrString, range, expectedHeaders) {
return new Promise(function (resolve, reject) {
+ var pathname = typeof urlObjectOrString === 'string' ? urlObjectOrString : urlObjectOrString.pathname;
// Note that titles may contain bare question marks or hashes, so we must use only the pathname without any URL parameters.
- // Be sure that you haven't encoded any querystring along with the URL.
- var barePathname = decodeURIComponent(urlObject.pathname);
+ // Be sure that you haven't encoded any querystring along with the URL (Zimit files, however, require encoding of the querystring)
+ var barePathname = decodeURIComponent(pathname);
var partsOfZIMUrl = regexpZIMUrlWithNamespace.exec(barePathname);
var prefix = partsOfZIMUrl ? partsOfZIMUrl[1] : '';
var nameSpace = partsOfZIMUrl ? partsOfZIMUrl[2] : '';
var title = partsOfZIMUrl ? partsOfZIMUrl[3] : barePathname;
- var anchorTarget = urlObject.hash.replace(/^#/, '');
- var uriComponent = urlObject.search.replace(/\?kiwix-display/, '');
+ var anchorTarget = '';
+ var uriComponent = '';
+ if (typeof urlObjectOrString === 'object') {
+ anchorTarget = urlObjectOrString.hash.replace(/^#/, '');
+ uriComponent = urlObjectOrString.search.replace(/\?kiwix-display/, '');
+ }
var titleWithNameSpace = nameSpace + '/' + title;
var zimName = prefix.replace(/\/$/, '');
+ // console.debug('[SW] Asking app.js for ' + titleWithNameSpace + ' from ' + zimName + '...');
+
var messageListener = function (msgPortEvent) {
if (msgPortEvent.data.action === 'giveContent') {
- // Content received from app.js
- var contentLength = msgPortEvent.data.content ? (msgPortEvent.data.content.byteLength || msgPortEvent.data.content.length) : null;
+ // Content received from app.js (note that null indicates that the content was not found in the ZIM)
+ var contentLength = msgPortEvent.data.content !== null ? (msgPortEvent.data.content.byteLength || msgPortEvent.data.content.length) : null;
var contentType = msgPortEvent.data.mimetype;
+ var zimType = msgPortEvent.data.zimType;
var headers = new Headers();
- if (contentLength) headers.set('Content-Length', contentLength);
+ if (contentLength !== null) headers.set('Content-Length', contentLength);
// Set Content-Security-Policy to sandbox the content (prevent XSS attacks from malicious ZIMs)
headers.set('Content-Security-Policy', "default-src 'self' data: blob: about: chrome-extension: moz-extension: https://browser-extension.kiwix.org https://kiwix.github.io 'unsafe-inline' 'unsafe-eval'; sandbox allow-scripts allow-same-origin allow-modals allow-popups allow-forms allow-downloads;");
headers.set('Referrer-Policy', 'no-referrer');
if (contentType) headers.set('Content-Type', contentType);
// Test if the content is a video or audio file. In this case, Chrome & Edge need us to support ranges.
+ // NB, the Replay Worker adds its own Accept-Ranges header, so we don't add it here for such requests.
// See kiwix-js #519 and openzim/zimwriterfs #113 for why we test for invalid types like "mp4" or "webm" (without "video/")
// The full list of types produced by zimwriterfs is in https://github.com/openzim/zimwriterfs/blob/master/src/tools.cpp
- if (contentLength >= 1 && /^(video|audio)|(^|\/)(mp4|webm|og[gmv]|mpeg)$/i.test(contentType)) {
+ if (zimType !== 'zimit' && contentLength >= 1 && /^(video|audio)|(^|\/)(mp4|webm|og[gmv]|mpeg)$/i.test(contentType)) {
headers.set('Accept-Ranges', 'bytes');
}
var slicedData = msgPortEvent.data.content;
- if (range) {
+
+ if (range && zimType === 'zimit') {
+ headers.set('Content-Range', range + '/*');
+ } else if (range && slicedData !== null) {
// The browser asks for a range of bytes (usually for a video or audio stream)
// In this case, we partially honor the request: if it asks for offsets x to y,
// we send partial contents starting at x offset, till the end of the data (ignoring y offset)
@@ -386,17 +601,30 @@ function fetchUrlFromZIM (urlObject, range) {
}
var responseInit = {
- // HTTP status is usually 200, but has to bee 206 when partial content (range) is sent
+ // HTTP status is usually 200, but has to be 206 when partial content (range) is sent
status: range ? 206 : 200,
statusText: 'OK',
headers: headers
};
+ // Deal with a not-found dirEntry
+ if (slicedData === null) {
+ responseInit.status = 404;
+ responseInit.statusText = 'Not Found';
+ }
+
+ if (slicedData === null) slicedData = '';
+
+ // if (expectedHeaders) {
+ // console.debug('[SW] Expected headers were', Object.fromEntries(expectedHeaders));
+ // console.debug('[SW] Constructed headers are', Object.fromEntries(headers));
+ // }
var httpResponse = new Response(slicedData, responseInit);
// Let's send the content back from the ServiceWorker
resolve(httpResponse);
} else if (msgPortEvent.data.action === 'sendRedirect') {
+ console.debug('[SW] Redirecting to ' + msgPortEvent.data.redirectUrl);
resolve(Response.redirect(prefix + msgPortEvent.data.redirectUrl));
} else {
reject(msgPortEvent.data, titleWithNameSpace);
diff --git a/tests/e2e/spec/gutenberg_ro.e2e.spec.js b/tests/e2e/spec/gutenberg_ro.e2e.spec.js
index d953dd34..dc272917 100644
--- a/tests/e2e/spec/gutenberg_ro.e2e.spec.js
+++ b/tests/e2e/spec/gutenberg_ro.e2e.spec.js
@@ -106,7 +106,7 @@ function runTests (driver, modes) {
this.slow(10000);
// Run tests twice, once in serviceworker mode and once in jquery mode
it('Load Kiwix JS and check title', async function () {
- await driver.get('http://localhost:' + port + '/dist/www/index.html');
+ await driver.get('http://localhost:' + port + '/dist/www/index.html?noPrompts=true');
const title = await driver.getTitle();
assert.equal('Kiwix', title);
});
@@ -137,7 +137,7 @@ function runTests (driver, modes) {
}
if (mode === 'jquery' || serviceWorkerAPI) {
// Wait until the mode has switched
- await driver.sleep(500);
+ await driver.sleep(2000);
let serviceWorkerStatus = await driver.findElement(By.id('serviceWorkerStatus')).getText();
try {
if (mode === 'serviceworker') {
@@ -152,7 +152,10 @@ function runTests (driver, modes) {
}
// We failed to switch modes, so let's try switching back and switching to this mode again
console.log('\x1b[33m%s\x1b[0m', ' Failed to switch to ' + mode + ' mode, trying again...');
- const otherModeSelector = await driver.findElement(By.id(mode === 'jquery' ? 'serviceworkerModeRadio' : 'jqueryModeRadio'));
+ let otherModeSelector;
+ await driver.wait(async function () {
+ otherModeSelector = await driver.findElement(By.id(mode === 'jquery' ? 'serviceworkerModeRadio' : 'jqueryModeRadio'));
+ }, 5000);
// Click the other mode selector
await otherModeSelector.click();
// Wait until the mode has switched
diff --git a/tests/e2e/spec/legacy-ray_charles.e2e.spec.js b/tests/e2e/spec/legacy-ray_charles.e2e.spec.js
index 028ae416..6b9fac9b 100644
--- a/tests/e2e/spec/legacy-ray_charles.e2e.spec.js
+++ b/tests/e2e/spec/legacy-ray_charles.e2e.spec.js
@@ -122,7 +122,13 @@ function runTests (driver, modes) {
this.slow(10000);
// Run tests twice, once in serviceworker mode and once in jquery mode
it('Load Kiwix JS and check title', async function () {
- await driver.get('http://localhost:' + port + '/dist/www/index.html');
+ await driver.get('http://localhost:' + port + '/dist/www/index.html?noPrompts=true');
+ // Pause for 1.3 seconds to allow the app to load
+ await driver.sleep(1300);
+ // Issue a reload to ensure that the app is in the correct mode
+ await driver.navigate().refresh();
+ // Pause for 800 milliseconds to allow the app to reload
+ await driver.sleep(800);
const title = await driver.getTitle();
assert.equal('Kiwix', title);
});
@@ -231,10 +237,11 @@ function runTests (driver, modes) {
await driver.wait(async function () {
const contentAvailable = await driver.executeScript('return document.getElementById("mw-content-text");');
return contentAvailable;
- }, 5000);
+ }, 6000);
const articleLink = await driver.wait(until.elementLocated(By.xpath('/html/body/div/div/ul/li[77]/a[2]')));
+ const text = await articleLink.getText();
// const articleLink = await driver.findElement(By.linkText('This Little Girl of Mine'));
- assert.equal('This Little Girl of Mine', await articleLink.getText());
+ assert.equal('This Little Girl of Mine', text);
// Scroll the element into view and navigate to it
await driver.wait(async function () {
const elementIsVisible = await driver.executeScript('var el=arguments[0]; el.scrollIntoView(true); setTimeout(function () {el.click();}, 50); return el.offsetParent;', articleLink);
diff --git a/ubuntu_touch/manifest.json b/ubuntu_touch/manifest.json
index 0d42ee7f..b789baa5 100644
--- a/ubuntu_touch/manifest.json
+++ b/ubuntu_touch/manifest.json
@@ -4,7 +4,7 @@
"architecture": "all",
"maintainer": "Kiwix team ",
"framework": "ubuntu-sdk-16.04",
- "version": "3.11.1",
+ "version": "3.11.2",
"title": "Kiwix",
"hooks": {
"kiwix": {
diff --git a/www/article.html b/www/article.html
index 73875a8a..e7324c95 100644
--- a/www/article.html
+++ b/www/article.html
@@ -2,7 +2,9 @@
- Placeholder for injecting an article into the iframe
+
+
+
\ No newline at end of file
diff --git a/www/index.html b/www/index.html
index fd4b1231..19be2269 100644
--- a/www/index.html
+++ b/www/index.html
@@ -187,9 +187,8 @@
Before downloading non-Wiki ZIM types, check if your browser supports ZIM archives with dynamic content : look at the bottom of the Configuration
- page, in the API panel, and if you see "ServiceWorker API available and registered" in green, then the app can read all ZIM types (except Zimit:
- see ZIM archive format for more details). Otherwise you should mostly stick to MediaWiki (Wikipedia, Wikivoyage, Wiktionary...)
- and Stack Exchange archives (see modes below for an explanation).
+ page, in the API panel, and if you see "ServiceWorker API available and registered" in green, then the app can read all ZIM types. Otherwise you should
+ mostly stick to MediaWiki (Wikipedia, Wikivoyage, Wiktionary...) and Stack Exchange archives (see modes below for an explanation).
Step 2: Download or copy the content onto your device
@@ -284,10 +283,10 @@
ServiceWorker Mode (see below ).
- This application is not currently compatible with archives that are created by Zimit (https://youzim.it )
- using the Web Archive (WARC) format. We have plans to enable this format, but there are considerable technical challenges to overcome in order to display
- these archives with the fidelity that you expect from Kiwix -- see issue #1009 .
- However, there is experimental support for Zimit archives in our Progressive Web App (PWA) available from https://pwa.kiwix.org .
+ This application is now fully compatible with archives that are created by Zimit (https://youzim.it )
+ using the Web Archive (WARC) format, so long as your browser supports ServiceWorker mode. If you can only use JQuery mode, we do our best to show you
+ the static content of the requested article (no JavaScript can run in this mode). This will work for some basic static sites, but many will look broken.
+ Search for content in the usual way.
Downloading and storing large archives
@@ -322,8 +321,7 @@
be capable of installing a Service Worker, which is usually the case in modern browsers. It works by intercepting
the browser or framework's Fetch calls (network requests) and supplying the requested content from the ZIM. In this
mode, the content is read and supplied as-is from the archive to the browser. Dynamic content (e.g. JavaScript) and
- proprietary UIs are fully supported in this mode. However, Zimit archives are not currently supported due to
- a conflict between the Kiwix JS Service Worker and the WARC Service Worker (but you can use the PWA for experimental support, see above). This mode can feel initially a little
+ proprietary UIs are fully supported in this mode. This mode can feel initially a little
slower than JQuery mode until commonly used assets are cached, but it soon equals JQuery mode in speed, at least in
modern browsers. However, older browsers such as IE11 are incompatible with this mode, and the app must be running
in a secure context (https:
, localhost
, or certain browser extensions). While this mode is
diff --git a/www/js/app.js b/www/js/app.js
index d0f28993..0ca2e715 100644
--- a/www/js/app.js
+++ b/www/js/app.js
@@ -157,19 +157,25 @@ function resizeIFrame () {
// IE cannot retrieve computed headerStyles till the next paint, so we wait a few ticks even if UI animations are disabled
}, params.showUIAnimations ? 400 : 100);
+ // Get the contentWindow of the iframe to operate on
+ var thisArticleWindow = articleWindow;
+ if (articleWindow.document && articleWindow.document.getElementById('replay_iframe')) {
+ thisArticleWindow = articleContainer.contentWindow.document.getElementById('replay_iframe').contentWindow;
+ }
+
// Remove and add the scroll event listener to the new article window
// Note that IE11 doesn't support wheel or touch events on the iframe, but it does support keydown and scroll
- articleWindow.removeEventListener('scroll', uiUtil.scroller);
- articleWindow.removeEventListener('touchstart', uiUtil.scroller);
- articleWindow.removeEventListener('touchend', uiUtil.scroller);
- articleWindow.removeEventListener('wheel', uiUtil.scroller);
- articleWindow.removeEventListener('keydown', uiUtil.scroller);
+ thisArticleWindow.removeEventListener('scroll', uiUtil.scroller);
+ thisArticleWindow.removeEventListener('touchstart', uiUtil.scroller);
+ thisArticleWindow.removeEventListener('touchend', uiUtil.scroller);
+ thisArticleWindow.removeEventListener('wheel', uiUtil.scroller);
+ thisArticleWindow.removeEventListener('keydown', uiUtil.scroller);
if (params.slideAway) {
- articleWindow.addEventListener('scroll', uiUtil.scroller);
- articleWindow.addEventListener('touchstart', uiUtil.scroller);
- articleWindow.addEventListener('touchend', uiUtil.scroller);
- articleWindow.addEventListener('wheel', uiUtil.scroller);
- articleWindow.addEventListener('keydown', uiUtil.scroller);
+ thisArticleWindow.addEventListener('scroll', uiUtil.scroller);
+ thisArticleWindow.addEventListener('touchstart', uiUtil.scroller);
+ thisArticleWindow.addEventListener('touchend', uiUtil.scroller);
+ thisArticleWindow.addEventListener('wheel', uiUtil.scroller);
+ thisArticleWindow.addEventListener('keydown', uiUtil.scroller);
}
}
@@ -338,7 +344,7 @@ prefixElement.addEventListener('blur', function () {
appstate.search.status = 'cancelled';
region.style.overflowY = 'hidden';
region.style.height = 'auto';
- document.getElementById('searchingArticles').style.display = 'none';
+ uiUtil.spinnerDisplay(false);
document.getElementById('articleListWithHeader').style.display = 'none';
}
});
@@ -391,8 +397,8 @@ document.getElementById('btnHome').addEventListener('click', function (event) {
var articleListHeaderMessage = document.getElementById('articleListHeaderMessage');
while (articleList.firstChild) articleList.removeChild(articleList.firstChild);
while (articleListHeaderMessage.firstChild) articleListHeaderMessage.removeChild(articleListHeaderMessage.firstChild);
- document.getElementById('searchingArticles').style.display = 'none';
- document.getElementById('articleContent').style.display = 'none';
+ uiUtil.spinnerDisplay(false);
+ // document.getElementById('articleContent').style.display = 'none';
// Empty and purge the article contents
var articleContent = document.getElementById('articleContent');
var articleContentDoc = articleContent ? articleContent.contentDocument : null;
@@ -728,8 +734,16 @@ function getAssetsCacheAttributes () {
// Handler for recieving message reply from service worker
channel.port1.onmessage = function (event) {
var cache = event.data;
- if (cache.error) reject(cache.error);
- else resolve(cache);
+ if (cache.error) {
+ reject(cache.error);
+ } else {
+ if (cache.type === 'cacheAPI' && selectedArchive && selectedArchive.zimType === 'zimit' && appstate.isReplayWorkerAvailable) {
+ cache.type = 'replayWorker';
+ cache.description = 'ReplayWorker';
+ cache.count = '-';
+ }
+ resolve(cache);
+ }
};
// Ask Service Worker for its cache status and asset count
navigator.serviceWorker.controller.postMessage({
@@ -829,6 +843,11 @@ function initServiceWorkerMessaging () {
}
handleMessageChannelMessage(event);
}
+ } else if (event.data.msg_type) {
+ // Messages received from the ReplayWorker
+ if (event.data.msg_type === 'colAdded') {
+ console.debug('ReplayWorker added a collection');
+ }
} else {
console.error('Invalid message received', event.data);
}
@@ -848,20 +867,22 @@ function initServiceWorkerMessaging () {
console.error('The Service Worker is not controlling the current page! We have to reload.');
// Turn off failsafe, as this is a controlled reboot
settingsStore.setItem('lastPageLoad', 'rebooting', Infinity);
- window.location.reload();
+ if (!appstate.preventAutoReboot) window.location.reload();
} else if (navigator && navigator.serviceWorker && !navigator.serviceWorker.controller) {
- uiUtil.systemAlert('No Service Worker is registered, meaning this app will not currently work offline!
Would you like to switch to ServiceWorker mode?
',
- 'Offline use is disabled!', true).then(function (response) {
- if (response) {
- setContentInjectionMode('serviceworker');
- if (selectedArchive) {
- setTimeout(function () {
- params.themeChanged = true;
- document.getElementById('btnHome').click();
- }, 750);
+ if (!params.noPrompts) {
+ uiUtil.systemAlert('No Service Worker is registered, meaning this app will not currently work offline!
Would you like to switch to ServiceWorker mode?
',
+ 'Offline use is disabled!', true).then(function (response) {
+ if (response) {
+ setContentInjectionMode('serviceworker');
+ if (selectedArchive) {
+ setTimeout(function () {
+ params.themeChanged = true;
+ document.getElementById('btnHome').click();
+ }, 750);
+ }
}
- }
- });
+ });
+ }
}
}
@@ -881,6 +902,7 @@ function setContentInjectionMode (value) {
params.serviceWorkerLocal = true;
}
params.contentInjectionMode = value;
+ params.originalContentInjectionMode = null;
var message = '';
if (value === 'jquery') {
if (!params.appCache) {
@@ -943,15 +965,19 @@ function setContentInjectionMode (value) {
'You can continue to use the app in the (now deprecated) JQuery mode, but note that this mode only works well with ' +
'ZIM archives that have static content, such as Wikipedia / Wikimedia ZIMs or Stackexchange.
' +
'If you can, we recommend that you update your browser to a version that supports ServiceWorker mode.
';
- uiUtil.systemAlert(message, (translateUI.t('dialog-launchpwa-unsupported-title') || 'ServiceWorker API not available'), true, null,
- (translateUI.t('dialog-serviceworker-unsupported-fallback') || 'Use JQuery mode')).then(function (response) {
- if (params.referrerExtensionURL && response) {
- var uriParams = '?allowInternetAccess=false&contentInjectionMode=jquery&defaultModeChangeAlertDisplayed=true';
- window.location.href = params.referrerExtensionURL + '/www/index.html' + uriParams;
- } else {
- setContentInjectionMode(params.oldInjectionMode || 'jquery');
- }
- });
+ if (!params.noPrompts) {
+ uiUtil.systemAlert(message, (translateUI.t('dialog-launchpwa-unsupported-title') || 'ServiceWorker API not available'), true, null,
+ (translateUI.t('dialog-serviceworker-unsupported-fallback') || 'Use JQuery mode')).then(function (response) {
+ if (params.referrerExtensionURL && response) {
+ var uriParams = '?allowInternetAccess=false&contentInjectionMode=jquery&defaultModeChangeAlertDisplayed=true';
+ window.location.href = params.referrerExtensionURL + '/www/index.html' + uriParams;
+ } else {
+ setContentInjectionMode(params.oldInjectionMode || 'jquery');
+ }
+ });
+ } else {
+ setContentInjectionMode(params.oldInjectionMode || 'jquery');
+ }
return;
}
if (!isMessageChannelAvailable()) {
@@ -1002,15 +1028,18 @@ function setContentInjectionMode (value) {
message += (translateUI.t('dialog-serviceworker-registration-failure-fileprotocol') ||
' You seem to be opening kiwix-js with the file:// protocol. You should open it through a web server: either through a local one (http://localhost/...) or through a remote one (but you need a secure connection: https://webserver.org/...)');
}
- uiUtil.systemAlert(message, (translateUI.t('dialog-serviceworker-registration-failure-title') || 'Failed to register Service Worker')).then(function () {
- setContentInjectionMode('jquery');
- // We need to wait for the previous dialogue box to unload fully before attempting to display another
- setTimeout(function () {
- params.defaultModeChangeAlertDisplayed = false;
- settingsStore.removeItem('defaultModeChangeAlertDisplayed');
- checkAndDisplayInjectionModeChangeAlert();
- }, 1200);
- });
+ appstate.preventAutoReboot = true;
+ if (!params.noPrompts) {
+ uiUtil.systemAlert(message, (translateUI.t('dialog-serviceworker-registration-failure-title') || 'Failed to register Service Worker')).then(function () {
+ setContentInjectionMode('jquery');
+ // We need to wait for the previous dialogue box to unload fully before attempting to display another
+ setTimeout(function () {
+ params.defaultModeChangeAlertDisplayed = false;
+ settingsStore.removeItem('defaultModeChangeAlertDisplayed');
+ checkAndDisplayInjectionModeChangeAlert();
+ }, 1200);
+ });
+ }
}
});
}
@@ -1200,7 +1229,7 @@ window.onpopstate = function (event) {
var titleSearch = event.state.titleSearch;
document.getElementById('prefix').value = '';
document.getElementById('welcomeText').style.display = 'none';
- document.getElementById('searchingArticles').style.display = 'none';
+ uiUtil.spinnerDisplay(false);
$('.navbar-collapse').collapse('hide');
document.getElementById('configuration').style.display = 'none';
document.getElementById('articleListWithHeader').style.display = 'none';
@@ -1561,6 +1590,13 @@ function archiveReadyCallback (archive) {
// A css cache significantly speeds up the loading of CSS files (used by default in jQuery mode)
selectedArchive.cssCache = new Map();
+ if (selectedArchive.zimType !== 'zimit') {
+ if (params.originalContentInjectionMode) {
+ params.contentInjectionMode = params.originalContentInjectionMode;
+ params.originalContentInjectionMode = null;
+ }
+ }
+
// Initialize the Service Worker
if (params.contentInjectionMode === 'serviceworker') {
initServiceWorkerMessaging();
@@ -1658,7 +1694,7 @@ function searchDirEntriesFromPrefix (prefix) {
if (activeContent) activeContent.style.display = 'none';
selectedArchive.findDirEntriesWithPrefix(appstate.search, populateListOfArticles);
} else {
- document.getElementById('searchingArticles').style.display = 'none';
+ uiUtil.spinnerDisplay(false);
// We have to remove the focus from the search field,
// so that the keyboard does not stay above the message
document.getElementById('searchArticles').focus();
@@ -1720,7 +1756,7 @@ function populateListOfArticles (dirEntryArray, reportingSearch) {
return false;
});
});
- if (!stillSearching) document.getElementById('searchingArticles').style.display = 'none';
+ if (!stillSearching) uiUtil.spinnerDisplay(false);
document.getElementById('articleListWithHeader').style.display = '';
}
@@ -1789,7 +1825,7 @@ function readArticle (dirEntry) {
expectedArticleURLToBeDisplayed = dirEntry.namespace + '/' + dirEntry.url;
// We must remove focus from UI elements in order to deselect whichever one was clicked (in both jQuery and SW modes),
// but we should not do this when opening the landing page (or else one of the Unit Tests fails, at least on Chrome 58)
- if (!params.isLandingPage) document.getElementById('articleContent').contentWindow.focus();
+ if (!params.isLandingPage) articleContainer.contentWindow.focus();
// Show the spinner with a loading message
var message = dirEntry.url.match(/(?:^|\/)([^/]{1,13})[^/]*?$/);
message = message ? message[1] + '...' : '...';
@@ -1804,84 +1840,55 @@ function readArticle (dirEntry) {
var encodedUrl = dirEntry.url.replace(/[^/]+/g, function (matchedSubstring) {
return encodeURIComponent(matchedSubstring);
});
- var iframeArticleContent = document.getElementById('articleContent');
- iframeArticleContent.onload = function () {
- // The content is fully loaded by the browser : we can hide the spinner
- document.getElementById('cachingAssets').textContent = translateUI.t('spinner-caching-assets') || 'Caching assets...';
- document.getElementById('cachingAssets').style.display = 'none';
- document.getElementById('searchingArticles').style.display = 'none';
- // Set the requested appTheme
- uiUtil.applyAppTheme(params.appTheme);
- // Display the iframe content
- document.getElementById('articleContent').style.display = '';
- // Deflect drag-and-drop of ZIM file on the iframe to Config
- if (!params.disableDragAndDrop) {
- var doc = iframeArticleContent.contentDocument ? iframeArticleContent.contentDocument.documentElement : null;
- var docBody = doc ? doc.getElementsByTagName('body') : null;
- docBody = docBody ? docBody[0] : null;
- if (docBody) {
- docBody.addEventListener('dragover', handleIframeDragover);
- docBody.addEventListener('drop', handleIframeDrop);
- }
- }
- resizeIFrame();
- if (iframeArticleContent.contentWindow) {
- // Configure home key press to focus #prefix only if the feature is in active state
- if (params.useHomeKeyToFocusSearchBar) { iframeArticleContent.contentWindow.addEventListener('keydown', focusPrefixOnHomeKey); }
- if (params.openExternalLinksInNewTabs) {
- // Add event listener to iframe window to check for links to external resources
- iframeArticleContent.contentWindow.addEventListener('click', function (event) {
- // Find the closest enclosing A tag (if any)
- var clickedAnchor = uiUtil.closestAnchorEnclosingElement(event.target);
- if (clickedAnchor) {
- var href = clickedAnchor.getAttribute('href');
- // We assume that, if an absolute http(s) link is hardcoded inside an HTML string,
- // it means it's a link to an external website.
- // We also do it for ftp even if it's not supported any more by recent browsers...
- if (/^(?:http|ftp)/i.test(href)) {
- uiUtil.warnAndOpenExternalLinkInNewTab(event, clickedAnchor);
- } else if (/\.pdf([?#]|$)/i.test(href)) {
- // Due to the iframe sandbox, we have to prevent the PDF viewer from opening in the iframe and instead open it in a new tab
- event.preventDefault();
- window.open(clickedAnchor.href, '_blank');
- } else if (/\/[-ABCIJMUVWX]\/.+$/.test(clickedAnchor.href)) {
- // Show the spinner if it's a ZIM link, but not an anchor
- if (!~href.indexOf('#')) {
- var message = href.match(/(?:^|\/)([^/]{1,13})[^/]*?$/);
- message = message ? message[1] + '...' : '...';
- uiUtil.spinnerDisplay(true, (translateUI.t('spinner-loading') || 'Loading') + ' ' + message);
- // In case of false positive, ensure spinner is eventually hidden
- setTimeout(function () {
- uiUtil.spinnerDisplay(false);
- }, 4000);
- uiUtil.showSlidingUIElements();
- }
- }
- }
- });
- }
- // Reset UI when the article is unloaded
- iframeArticleContent.contentWindow.onunload = function () {
- // remove eventListener to avoid memory leaks
- iframeArticleContent.contentWindow.removeEventListener('keydown', focusPrefixOnHomeKey);
- var articleList = document.getElementById('articleList');
- var articleListHeaderMessage = document.getElementById('articleListHeaderMessage');
- while (articleList.firstChild) articleList.removeChild(articleList.firstChild);
- while (articleListHeaderMessage.firstChild) articleListHeaderMessage.removeChild(articleListHeaderMessage.firstChild);
- document.getElementById('articleListWithHeader').style.display = 'none';
- document.getElementById('prefix').value = '';
- document.getElementById('searchingArticles').style.display = '';
- };
- }
- };
+ // Set up article onload handler
+ articleLoader();
if (!isDirEntryExpectedToBeDisplayed(dirEntry)) {
return;
}
- // We put the ZIM filename as a prefix in the URL, so that browser caches are separate for each ZIM file
- iframeArticleContent.src = '../' + selectedArchive.file.name + '/' + dirEntry.namespace + '/' + encodedUrl;
+ if (selectedArchive.zimType === 'zimit' && params.isLandingPage) {
+ var archiveName = selectedArchive.file.name.replace(/\.zim\w{0,2}$/i, '');
+ var cns = selectedArchive.getContentNamespace();
+ // Support type 0 and type 1 Zimit archives
+ var replayCns = cns === 'C' ? '/C/A/' : '/A/';
+ var base = window.location.href.replace(/^(.*?\/)www\/.*$/, '$1');
+ var prefix = base + selectedArchive.file.name + replayCns;
+ // Open a new message channel to the ServiceWorker
+ var zimitMessageChannel = new MessageChannel();
+ zimitMessageChannel.port1.onmessage = function (event) {
+ if (event.data.error) {
+ console.error('Reading Zimit archives in ServiceWorker mode is not supported in this browser', event.data.error);
+ handleUnsupportedReplayWorker(dirEntry);
+ } else if (event.data.success) {
+ // console.debug(event.data.success);
+ appstate.isReplayWorkerAvailable = true;
+ // We put the ZIM filename as a prefix in the URL, so that browser caches are separate for each ZIM file
+ articleContainer.src = '../' + selectedArchive.file.name + '/' + dirEntry.namespace + '/' + encodedUrl;
+ }
+ };
+ // If we are dealing with a Zimit ZIM, we need to instruct Replay to add the file as a new collection
+ navigator.serviceWorker.controller.postMessage({
+ msg_type: 'addColl',
+ name: archiveName,
+ prefix: prefix,
+ file: { sourceUrl: 'proxy:' + prefix },
+ root: true,
+ skipExisting: false,
+ extraConfig: {
+ // prefix: prefix, // If not set, Replay will use the proxy URL (without the 'proxy:' prefix)
+ sourceType: 'kiwix',
+ notFoundPageUrl: './404.html'/*,
+ baseUrl: base + selectedArchive.file.name + '/',
+ baseUrlHashReplay: false */
+ },
+ topTemplateUrl: './www/topFrame.html'
+ }, [zimitMessageChannel.port2]);
+ } else {
+ // We put the ZIM filename as a prefix in the URL, so that browser caches are separate for each ZIM file
+ articleContainer.src = '../' + selectedArchive.file.name + '/' + dirEntry.namespace + '/' + encodedUrl;
+ }
} else {
// In jQuery mode, we read the article content in the backend and manually insert it in the iframe
if (dirEntry.isRedirect()) {
@@ -1902,6 +1909,166 @@ function readArticle (dirEntry) {
}
}
+/**
+ * Selects the iframe to which to attach the onload event, and attaches it
+ */
+function articleLoader () {
+ if (selectedArchive.zimType === 'zimit') {
+ var doc = articleContainer.contentDocument || null;
+ if (doc) {
+ var replayIframe = doc.getElementById('replay_iframe');
+ if (replayIframe) {
+ replayIframe.onload = function () {
+ articleLoadedSW(replayIframe);
+ };
+ }
+ }
+ } else {
+ articleContainer.onload = function () {
+ articleLoadedSW(articleContainer);
+ };
+ }
+}
+
+/**
+ * Postprocessing required after the article contents are loaded
+ * @param {HTMLIFrameElement} iframeArticleContent The iframe containing the article content
+ */
+function articleLoadedSW (iframeArticleContent) {
+ // The content is fully loaded by the browser : we can hide the spinner
+ document.getElementById('cachingAssets').textContent = translateUI.t('spinner-caching-assets') || 'Caching assets...';
+ document.getElementById('cachingAssets').style.display = 'none';
+ uiUtil.spinnerDisplay(false);
+ // Set the requested appTheme
+ uiUtil.applyAppTheme(params.appTheme);
+ // Display the iframe content
+ iframeArticleContent.style.display = '';
+ articleContainer.style.display = '';
+ // Deflect drag-and-drop of ZIM file on the iframe to Config
+ if (!params.disableDragAndDrop) {
+ var doc = iframeArticleContent.contentDocument ? iframeArticleContent.contentDocument.documentElement : null;
+ var docBody = doc ? doc.getElementsByTagName('body') : null;
+ docBody = docBody ? docBody[0] : null;
+ if (docBody) {
+ docBody.ondragover = handleIframeDragover;
+ docBody.ondrop = handleIframeDrop;
+ }
+ }
+ resizeIFrame();
+
+ if (iframeArticleContent.contentWindow) {
+ // Configure home key press to focus #prefix only if the feature is in active state
+ if (params.useHomeKeyToFocusSearchBar) { iframeArticleContent.contentWindow.onkeydown = focusPrefixOnHomeKey; }
+ if (params.openExternalLinksInNewTabs) {
+ // Add event listener to iframe window to check for links to external resources
+ iframeArticleContent.contentWindow.onclick = function (event) {
+ // Find the closest enclosing A tag (if any)
+ var clickedAnchor = uiUtil.closestAnchorEnclosingElement(event.target);
+ // If the anchor has a passthrough property, then we have already checked it is safe, so we can return
+ if (clickedAnchor && clickedAnchor.passthrough) return;
+ if (clickedAnchor) {
+ // Check for Zimit links that would normally be handled by the Replay Worker
+ if (appstate.isReplayWorkerAvailable) {
+ handleClickOnReplayLink(event, clickedAnchor);
+ return;
+ }
+ // We assume that, if an absolute http(s) link is hardcoded inside an HTML string,
+ // it means it's a link to an external website.
+ // We also do it for ftp even if it's not supported any more by recent browsers...
+ var href = clickedAnchor.getAttribute('href');
+ if (/^(?:http|ftp)/i.test(href)) {
+ uiUtil.warnAndOpenExternalLinkInNewTab(event, clickedAnchor);
+ } else if (/\.pdf([?#]|$)/i.test(href) && selectedArchive.zimType !== 'zimit') {
+ // Due to the iframe sandbox, we have to prevent the PDF viewer from opening in the iframe and instead open it in a new tab
+ event.preventDefault();
+ window.open(clickedAnchor.href, '_blank');
+ } else if (/\/[-ABCIJMUVWX]\/.+$/.test(clickedAnchor.href)) {
+ // Show the spinner if it's a ZIM link, but not an anchor
+ if (!~href.indexOf('#')) {
+ var message = href.match(/(?:^|\/)([^/]{1,13})[^/]*?$/);
+ message = message ? message[1] + '...' : '...';
+ uiUtil.spinnerDisplay(true, (translateUI.t('spinner-loading') || 'Loading') + ' ' + message);
+ // In case of false positive, ensure spinner is eventually hidden
+ setTimeout(function () {
+ uiUtil.spinnerDisplay(false);
+ }, 4000);
+ uiUtil.showSlidingUIElements();
+ }
+ }
+ }
+ };
+ }
+ // Reset UI when the article is unloaded
+ iframeArticleContent.contentWindow.onunload = function () {
+ iframeArticleContent.loader = false;
+ // remove eventListener to avoid memory leaks
+ // iframeArticleContent.contentWindow.removeEventListener('keydown', focusPrefixOnHomeKey);
+ var articleList = document.getElementById('articleList');
+ var articleListHeaderMessage = document.getElementById('articleListHeaderMessage');
+ while (articleList.firstChild) articleList.removeChild(articleList.firstChild);
+ while (articleListHeaderMessage.firstChild) articleListHeaderMessage.removeChild(articleListHeaderMessage.firstChild);
+ document.getElementById('articleListWithHeader').style.display = 'none';
+ document.getElementById('prefix').value = '';
+ };
+ }
+};
+
+// Handles a click on a Zimit link that has been processed by Wombat
+function handleClickOnReplayLink (ev, anchor) {
+ var pseudoNamespace = selectedArchive.zimitPrefix.replace(/^(.*\/)[^/]{2,}\/$/, '$1');
+ var pseudoDomainPath = anchor.hostname + anchor.pathname;
+ var containingDocDomainPath = anchor.ownerDocument.location.hostname + anchor.ownerDocument.location.pathname;
+ // If the paths are identical, then we are dealing with a link to an anchor in the same document, so we can return
+ if (anchor.protocol !== document.location.protocol || pseudoDomainPath === containingDocDomainPath) return;
+ var zimUrl = pseudoNamespace + pseudoDomainPath + anchor.search;
+ // We are dealing with a ZIM link transformed by Wombat, so we need to reconstruct the ZIM link
+ if (zimUrl) {
+ ev.preventDefault();
+ ev.stopPropagation();
+ selectedArchive.getDirEntryByPath(zimUrl).then(function (dirEntry) {
+ if (dirEntry) {
+ var mimetype = dirEntry.getMimetype();
+ // Due to the iframe sandbox, we have to prevent the PDF viewer from opening in the iframe and instead open it in a new tab
+ // Note that some Replay PDFs have html mimetypes, or can be redirects to PDFs, we need to check the URL as well
+ if (/pdf/i.test(mimetype) || /\.pdf(?:[#?]|$)/i.test(anchor.href)) {
+ window.open(anchor.href, '_blank');
+ /*
+ } else if (/\bx?html\b/i.test(mimetype)) {
+ // If the SW has gone to sleep, loading this way gives it a chance to reload configuration
+ params.isLandingPage = false;
+ readArticle(dirEntry); */
+ } else {
+ // Fingers crossed, let Replay handle this link
+ anchor.passthrough = true;
+ // Handle middle-clicks and ctrl-clicks
+ if (ev.ctrlKey || ev.metaKey || ev.button === 1) {
+ window.open(anchor.href, '_blank');
+ } else {
+ anchor.click();
+ }
+ }
+ } else {
+ // If dirEntry was not-found, it's probably an external link, so warn user before opening a new tab/window
+ uiUtil.warnAndOpenExternalLinkInNewTab(null, anchor);
+ }
+ });
+ }
+}
+
+function handleUnsupportedReplayWorker (unhandledDirEntry) {
+ appstate.isReplayWorkerAvailable = false;
+ params.originalContentInjectionMode = params.contentInjectionMode;
+ params.contentInjectionMode = 'jquery';
+ readArticle(unhandledDirEntry);
+ // if (!params.hideActiveContentWarning) uiUtil.displayActiveContentWarning();
+ uiUtil.systemAlert(translateUI.t('dialog-unsupported-archivetype-message') || 'You are attempting to open a Zimit-style archive, ' +
+ 'which is not unsupported by your browser version in ServiceWorker mode.
We have temporarily switched you to JQuery mode ' +
+ 'so you can view static content, but a lot of content is non-functional. If you can upgrade your browser, you will ' +
+ 'be able to access dynamic content.
Alternatively, you can try the Kiwix JS PWA, which supports some dynamic Zimit content ' +
+ 'in older browsers. Go to: https://pwa.kiwix.org .
',
+ translateUI.t('dialog-unsupported-archivetype-title') || 'Unsupported archive type!');
+}
+
/**
* Function that handles a message of the messageChannel.
* It tries to read the content in the backend, and sends it back to the ServiceWorker
@@ -1912,11 +2079,16 @@ function handleMessageChannelMessage (event) {
// We received a message from the ServiceWorker
// The ServiceWorker asks for some content
var title = event.data.title;
+ if (selectedArchive.zimType === 'zimit') {
+ // Zimit ZIMs store assets with the querystring, so we need to add it!
+ title = title + event.data.search;
+ }
var messagePort = event.ports[0];
var readFile = function (dirEntry) {
if (dirEntry === null) {
- console.error('Title ' + title + ' not found in archive.');
- messagePort.postMessage({ action: 'giveContent', title: title, content: '' });
+ console.warn('Title ' + title.replace(/^(.{1,160}).*/, '$1...') + ' not found in archive.');
+ // DEV: We send null for the content, so that the ServiceWorker knows that the article was not found (as opposed to being merely empty)
+ messagePort.postMessage({ action: 'giveContent', title: title, content: null, zimType: selectedArchive.zimType });
} else if (dirEntry.isRedirect()) {
selectedArchive.resolveRedirect(dirEntry, function (resolvedDirEntry) {
var redirectURL = resolvedDirEntry.namespace + '/' + resolvedDirEntry.url;
@@ -1930,14 +2102,26 @@ function handleMessageChannelMessage (event) {
// Let's read the content in the ZIM file
selectedArchive.readBinaryFile(dirEntry, function (fileDirEntry, content) {
var mimetype = fileDirEntry.getMimetype();
+ // Show the spinner
+ var shortTitle = dirEntry.getTitleOrUrl().replace(/^.*?([^/]{3,18})[^/]*\/?$/, '$1 ...');
+ if (!/moved/i.test(shortTitle) && !/image|javascript|warc-headers|jsonp?/.test(mimetype)) {
+ uiUtil.spinnerDisplay(true, (translateUI.t('spinner-loading') || 'Loading') + ' ' + shortTitle);
+ clearTimeout(window.timeout);
+ window.timeout = setTimeout(function () {
+ uiUtil.spinnerDisplay(false);
+ }, 1000);
+ // Ensure the article onload event gets attached to the right iframe
+ articleLoader();
+ }
// Let's send the content to the ServiceWorker
- var message = { action: 'giveContent', title: title, content: content.buffer, mimetype: mimetype };
- messagePort.postMessage(message, [content.buffer]);
+ var buffer = content.buffer ? content.buffer : content;
+ var message = { action: 'giveContent', title: title, content: buffer, mimetype: mimetype, zimType: selectedArchive.zimType };
+ messagePort.postMessage(message);
});
}
};
selectedArchive.getDirEntryByPath(title).then(readFile).catch(function () {
- messagePort.postMessage({ action: 'giveContent', title: title, content: new Uint8Array() });
+ messagePort.postMessage({ action: 'giveContent', title: title, content: new Uint8Array(), zimType: selectedArchive.zimType });
});
}
@@ -1947,11 +2131,11 @@ var regexpZIMUrlWithNamespace = /^[./]*([-ABCIJMUVWX]\/.+)$/;
// The case-insensitive regex below finds images, scripts, stylesheets and tracks with ZIM-type metadata and image namespaces.
// It first searches for ]*?\s)(?:src|href)(\s*=\s*(["']))(?![a-z][a-z0-9+.-]+:)(.+?)(?=\3|\?|#)/ig;
+// absolute URIs with protocols that conform to RFC 3986 (e.g. 'http:', 'data:'). It then captures the whole of the URL up until any
+// querystring (? character) which (if it is exists) is captured with its contents in another gourp. The regex then tests for the end
+// of the URL with the opening delimiter (" or ', which is capture group \3) or a hash character (#). When the regex is used below, it
+// will be further processed to calculate the ZIM URL from the relative path. This regex can cope with legitimate single quote marks (') in the URL.
+var regexpTagsWithZimUrl = /(<(?:img|script|link|track)\b[^>]*?\s)(?:src|href)(\s*=\s*(["']))(?![a-z][a-z0-9+.-]+:)(.+?)(\?.*?)?(?=\3|#)/ig;
// Regex below tests the html of an article for active content [kiwix-js #466]
// It inspects every
+
+