| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709 |
- /* Web platform APIs for the NebOS browser, written in JavaScript on top of a
- * few C primitives (js_browser.c):
- * __nb_http(method, url, contentType, body) -> [status, ctype, finalUrl, text]
- * __nb_storage(kind[, text]) kind 0 = localStorage, 1 = sessionStorage
- * __nb_resolve(base, relative) -> absolute URL
- * __nb_nodeproto prototype shared by every DOM node wrapper
- * It runs once per page state, before the page's scripts; the primitives are
- * removed from the global object afterwards. Embedded by js_prelude.S. */
- (function (g) {
- "use strict";
- var http = g.__nb_http, storage = g.__nb_storage, resolve = g.__nb_resolve;
- var nodeproto = g.__nb_nodeproto;
- delete g.__nb_http; delete g.__nb_storage; delete g.__nb_resolve;
- delete g.__nb_nodeproto;
- var hasOwn = Object.prototype.hasOwnProperty;
- function def(name, value) {
- Object.defineProperty(g, name, { value: value, writable: true,
- configurable: true, enumerable: false });
- }
- /* ---- console, timers, misc globals ---- */
- var con = g.console, rawlog = con.log;
- /* Errors print with their stack (Vue reports caught errors this way). */
- function fmt(a) {
- if (a instanceof Error)
- return a.name + ": " + a.message + (a.stack ? "\n" + a.stack : "");
- if (a !== null && typeof a === "object" && !(typeof a.nodeType === "number")) {
- try { return JSON.stringify(a); } catch (e) { return String(a); }
- }
- return a;
- }
- function logger(prefix) {
- return function () {
- var args = Array.prototype.map.call(arguments, fmt);
- if (prefix) args.unshift(prefix);
- rawlog.apply(con, args);
- };
- }
- con.log = logger("");
- con.info = logger("");
- con.debug = logger("");
- con.dir = logger("");
- con.warn = logger("[warn]");
- con.error = logger("[error]");
- con.trace = logger("[trace]");
- ["group", "groupCollapsed", "groupEnd", "time", "timeEnd", "timeLog",
- "table", "count", "countReset", "clear"].forEach(function (k) {
- if (!con[k]) con[k] = function () {};
- });
- con.assert = function (c) {
- if (!c) con.log.apply(con, ["Assertion failed:"].concat(
- Array.prototype.slice.call(arguments, 1)));
- };
- def("self", g); def("top", g); def("parent", g); def("frames", g);
- def("isSecureContext", true);
- def("origin", g.location.origin);
- /* The engine's own Promise, captured before any page script runs: core-js
- * (heise's consent script) installs a Promise polyfill that schedules its
- * reactions through queueMicrotask, and a queueMicrotask built on the
- * replaced global Promise would call back into the polyfill forever. */
- var NativePromise = Promise;
- def("queueMicrotask", function (f) { NativePromise.resolve().then(f); });
- /* Present so core-js keeps the native Promise (it polyfills browsers that
- * lack unhandled-rejection events). */
- class PromiseRejectionEvent {
- constructor(type, init) {
- this.type = type;
- this.promise = init && init.promise;
- this.reason = init && init.reason;
- }
- }
- def("PromiseRejectionEvent", PromiseRejectionEvent);
- def("requestIdleCallback", function (f) {
- return setTimeout(function () {
- f({ didTimeout: false, timeRemaining: function () { return 10; } });
- }, 1);
- });
- def("cancelIdleCallback", function (id) { clearTimeout(id); });
- def("structuredClone", function (v) {
- return v === undefined ? v : JSON.parse(JSON.stringify(v));
- });
- class DOMException extends Error {
- constructor(message, name) {
- super(message === undefined ? "" : message);
- this.name = name === undefined ? "Error" : name;
- }
- }
- def("DOMException", DOMException);
- /* ---- base64 ---- */
- var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- def("btoa", function (s) {
- s = String(s);
- var out = "", i;
- for (i = 0; i < s.length; i += 3) {
- var a = s.charCodeAt(i), b = s.charCodeAt(i + 1),
- c = s.charCodeAt(i + 2);
- if (a > 255 || b > 255 || c > 255)
- throw new DOMException("Invalid character",
- "InvalidCharacterError");
- var n = (a << 16) | ((b || 0) << 8) | (c || 0);
- out += B64[n >> 18 & 63] + B64[n >> 12 & 63] +
- (i + 1 < s.length ? B64[n >> 6 & 63] : "=") +
- (i + 2 < s.length ? B64[n & 63] : "=");
- }
- return out;
- });
- def("atob", function (s) {
- s = String(s).replace(/[\s=]/g, "");
- var out = "", bits = 0, acc = 0, i;
- for (i = 0; i < s.length; i++) {
- var v = B64.indexOf(s[i]);
- if (v < 0)
- throw new DOMException("Invalid character",
- "InvalidCharacterError");
- acc = (acc << 6) | v;
- bits += 6;
- if (bits >= 8) {
- bits -= 8;
- out += String.fromCharCode((acc >> bits) & 255);
- }
- }
- return out;
- });
- /* ---- text encoding ---- */
- function utf8(s) {
- var out = [], i;
- s = String(s);
- for (i = 0; i < s.length; i++) {
- var c = s.charCodeAt(i);
- if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) {
- var d = s.charCodeAt(i + 1);
- if (d >= 0xdc00 && d < 0xe000) {
- c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00);
- i++;
- }
- }
- if (c < 0x80) out.push(c);
- else if (c < 0x800) out.push(0xc0 | c >> 6, 0x80 | c & 63);
- else if (c < 0x10000)
- out.push(0xe0 | c >> 12, 0x80 | c >> 6 & 63, 0x80 | c & 63);
- else
- out.push(0xf0 | c >> 18, 0x80 | c >> 12 & 63,
- 0x80 | c >> 6 & 63, 0x80 | c & 63);
- }
- return new Uint8Array(out);
- }
- function bytesOf(b) {
- if (b instanceof ArrayBuffer) return new Uint8Array(b);
- if (ArrayBuffer.isView(b))
- return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
- return utf8(b);
- }
- function unutf8(u) {
- var s = "", i = 0;
- while (i < u.length) {
- var c = u[i++];
- if (c >= 0xf0 && i + 2 < u.length + 0) {
- c = ((c & 7) << 18) | ((u[i++] & 63) << 12) |
- ((u[i++] & 63) << 6) | (u[i++] & 63);
- } else if (c >= 0xe0) {
- c = ((c & 15) << 12) | ((u[i++] & 63) << 6) | (u[i++] & 63);
- } else if (c >= 0xc0) {
- c = ((c & 31) << 6) | (u[i++] & 63);
- }
- s += String.fromCodePoint(c);
- }
- return s;
- }
- class TextEncoder {
- get encoding() { return "utf-8"; }
- encode(s) { return utf8(s === undefined ? "" : s); }
- }
- class TextDecoder {
- constructor(label) { this.encoding = "utf-8"; }
- decode(b) { return b ? unutf8(bytesOf(b)) : ""; }
- }
- def("TextEncoder", TextEncoder);
- def("TextDecoder", TextDecoder);
- /* ---- URLSearchParams / URL ---- */
- function qenc(s) {
- return encodeURIComponent(s).replace(/%20/g, "+").replace(/[!'()~]/g,
- function (c) {
- return "%" + c.charCodeAt(0).toString(16).toUpperCase();
- });
- }
- function qdec(s) {
- s = s.replace(/\+/g, " ");
- try { return decodeURIComponent(s); } catch (e) { return s; }
- }
- class URLSearchParams {
- constructor(init) {
- this._l = [];
- this._url = null;
- if (init == null) return;
- if (init instanceof URLSearchParams) {
- this._l = init._l.map(function (p) { return [p[0], p[1]]; });
- return;
- }
- if (typeof init === "object" || typeof init === "function") {
- if (typeof init[Symbol.iterator] === "function") {
- for (var p of init)
- this._l.push([String(p[0]), String(p[1])]);
- } else {
- for (var k of Object.keys(init))
- this._l.push([k, String(init[k])]);
- }
- return;
- }
- this._parse(String(init));
- }
- _parse(s) {
- this._l = [];
- if (s[0] === "?") s = s.slice(1);
- for (var part of s.split("&")) {
- if (!part) continue;
- var i = part.indexOf("=");
- this._l.push(i < 0 ? [qdec(part), ""] :
- [qdec(part.slice(0, i)), qdec(part.slice(i + 1))]);
- }
- }
- _upd() {
- if (this._url) {
- var s = this.toString();
- this._url._search = s ? "?" + s : "";
- }
- }
- append(k, v) { this._l.push([String(k), String(v)]); this._upd(); }
- delete(k) {
- k = String(k);
- this._l = this._l.filter(function (p) { return p[0] !== k; });
- this._upd();
- }
- get(k) {
- k = String(k);
- for (var p of this._l) if (p[0] === k) return p[1];
- return null;
- }
- getAll(k) {
- k = String(k);
- return this._l.filter(function (p) { return p[0] === k; })
- .map(function (p) { return p[1]; });
- }
- has(k) { return this.get(k) !== null; }
- set(k, v) {
- k = String(k); v = String(v);
- var found = false;
- this._l = this._l.filter(function (p) {
- if (p[0] !== k) return true;
- if (found) return false;
- found = true;
- p[1] = v;
- return true;
- });
- if (!found) this._l.push([k, v]);
- this._upd();
- }
- sort() {
- this._l.sort(function (a, b) {
- return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
- });
- this._upd();
- }
- forEach(f, t) { for (var p of this._l.slice()) f.call(t, p[1], p[0], this); }
- keys() { return this._l.map(function (p) { return p[0]; })[Symbol.iterator](); }
- values() { return this._l.map(function (p) { return p[1]; })[Symbol.iterator](); }
- entries() { return this._l.map(function (p) { return [p[0], p[1]]; })[Symbol.iterator](); }
- [Symbol.iterator]() { return this.entries(); }
- get size() { return this._l.length; }
- toString() {
- return this._l.map(function (p) {
- return qenc(p[0]) + "=" + qenc(p[1]);
- }).join("&");
- }
- }
- def("URLSearchParams", URLSearchParams);
- var URL_RE = /^([a-zA-Z][a-zA-Z0-9+.\-]*:)(\/\/([^\/?#]*))?([^?#]*)(\?[^#]*)?(#.*)?$/;
- class URL {
- constructor(url, base) {
- url = String(url).trim();
- if (!/^[a-zA-Z][a-zA-Z0-9+.\-]*:/.test(url)) {
- if (base === undefined)
- throw new TypeError("Invalid URL: " + url);
- base = new URL(String(base)).href;
- url = resolve(base, url);
- }
- this._parse(url);
- }
- _parse(u) {
- var m = URL_RE.exec(u);
- if (!m) throw new TypeError("Invalid URL: " + u);
- this._protocol = m[1].toLowerCase();
- var auth = m[3] || "", at = auth.lastIndexOf("@");
- this._user = "";
- this._pass = "";
- if (at >= 0) {
- var ui = auth.slice(0, at), c = ui.indexOf(":");
- auth = auth.slice(at + 1);
- this._user = c < 0 ? ui : ui.slice(0, c);
- this._pass = c < 0 ? "" : ui.slice(c + 1);
- }
- var pm = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(auth);
- this._hostname = (pm ? pm[1] : auth).toLowerCase();
- this._port = (pm && pm[2]) || "";
- if ((this._protocol === "https:" && this._port === "443") ||
- (this._protocol === "http:" && this._port === "80"))
- this._port = "";
- this._special = m[2] !== undefined;
- this._pathname = m[4] || (this._special ? "/" : "");
- this._search = m[5] && m[5].length > 1 ? m[5] : "";
- this._hash = m[6] && m[6].length > 1 ? m[6] : "";
- if (this._sp) this._sp._parse(this._search);
- }
- get protocol() { return this._protocol; }
- set protocol(v) {
- v = String(v);
- this._protocol = (v.endsWith(":") ? v : v + ":").toLowerCase();
- }
- get username() { return this._user; }
- set username(v) { this._user = String(v); }
- get password() { return this._pass; }
- set password(v) { this._pass = String(v); }
- get hostname() { return this._hostname; }
- set hostname(v) { this._hostname = String(v).toLowerCase(); }
- get port() { return this._port; }
- set port(v) { this._port = String(v); }
- get host() { return this._hostname + (this._port ? ":" + this._port : ""); }
- set host(v) {
- var m = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(String(v));
- if (m) { this._hostname = m[1].toLowerCase(); this._port = m[2] || ""; }
- }
- get pathname() { return this._pathname; }
- set pathname(v) {
- v = String(v);
- this._pathname = this._special && v[0] !== "/" ? "/" + v : v;
- }
- get search() { return this._search; }
- set search(v) {
- v = String(v);
- if (v && v[0] !== "?") v = "?" + v;
- this._search = v === "?" ? "" : v;
- if (this._sp) this._sp._parse(this._search);
- }
- get hash() { return this._hash; }
- set hash(v) {
- v = String(v);
- if (v && v[0] !== "#") v = "#" + v;
- this._hash = v === "#" ? "" : v;
- }
- get origin() {
- return this._special && this._protocol !== "file:" ?
- this._protocol + "//" + this.host : "null";
- }
- get href() {
- var a = this._user ? this._user +
- (this._pass ? ":" + this._pass : "") + "@" : "";
- return this._protocol + (this._special ? "//" + a + this.host : "") +
- this._pathname + this._search + this._hash;
- }
- set href(v) { this._parse(String(v)); }
- get searchParams() {
- if (!this._sp) {
- this._sp = new URLSearchParams(this._search);
- this._sp._url = this;
- }
- return this._sp;
- }
- toString() { return this.href; }
- toJSON() { return this.href; }
- static canParse(u, b) {
- try { new URL(u, b); return true; } catch (e) { return false; }
- }
- static parse(u, b) {
- try { return new URL(u, b); } catch (e) { return null; }
- }
- static createObjectURL() { return "blob:nebos/" + Date.now(); }
- static revokeObjectURL() {}
- }
- def("URL", URL);
- def("webkitURL", URL);
- /* ---- Headers / Blob / FormData / Request / Response ---- */
- class Headers {
- constructor(init) {
- this._m = new Map();
- if (!init) return;
- if (init instanceof Headers)
- init.forEach((v, k) => this.append(k, v));
- else if (typeof init[Symbol.iterator] === "function")
- for (var p of init) this.append(p[0], p[1]);
- else
- for (var k of Object.keys(init)) this.append(k, init[k]);
- }
- append(k, v) {
- k = String(k).toLowerCase();
- var o = this._m.get(k);
- this._m.set(k, o !== undefined ? o + ", " + v : String(v));
- }
- set(k, v) { this._m.set(String(k).toLowerCase(), String(v)); }
- get(k) {
- var v = this._m.get(String(k).toLowerCase());
- return v === undefined ? null : v;
- }
- has(k) { return this._m.has(String(k).toLowerCase()); }
- delete(k) { this._m.delete(String(k).toLowerCase()); }
- forEach(f, t) { for (var [k, v] of this._m) f.call(t, v, k, this); }
- keys() { return this._m.keys(); }
- values() { return this._m.values(); }
- entries() { return this._m.entries(); }
- [Symbol.iterator]() { return this._m.entries(); }
- }
- def("Headers", Headers);
- function partText(p) {
- if (typeof p === "string") return p;
- if (p instanceof Blob) return p._s;
- if (p instanceof ArrayBuffer || ArrayBuffer.isView(p))
- return unutf8(bytesOf(p));
- return String(p);
- }
- class Blob {
- constructor(parts, opts) {
- this._s = (parts || []).map(partText).join("");
- this.type = (opts && opts.type) || "";
- }
- get size() { return utf8(this._s).length; }
- text() { return Promise.resolve(this._s); }
- arrayBuffer() { return Promise.resolve(utf8(this._s).buffer); }
- slice(a, b, t) { return new Blob([this._s.slice(a, b)], { type: t }); }
- }
- class File extends Blob {
- constructor(parts, name, opts) {
- super(parts, opts);
- this.name = String(name);
- this.lastModified = (opts && opts.lastModified) || Date.now();
- }
- }
- def("Blob", Blob);
- def("File", File);
- class FormData {
- constructor() { this._l = []; }
- append(k, v) { this._l.push([String(k), v]); }
- set(k, v) { this.delete(k); this.append(k, v); }
- get(k) {
- for (var p of this._l) if (p[0] === k) return p[1];
- return null;
- }
- getAll(k) {
- return this._l.filter(function (p) { return p[0] === k; })
- .map(function (p) { return p[1]; });
- }
- has(k) { return this.get(k) !== null; }
- delete(k) { this._l = this._l.filter(function (p) { return p[0] !== k; }); }
- forEach(f, t) { for (var p of this._l) f.call(t, p[1], p[0], this); }
- entries() { return this._l.map(function (p) { return [p[0], p[1]]; })[Symbol.iterator](); }
- keys() { return this._l.map(function (p) { return p[0]; })[Symbol.iterator](); }
- values() { return this._l.map(function (p) { return p[1]; })[Symbol.iterator](); }
- [Symbol.iterator]() { return this.entries(); }
- }
- def("FormData", FormData);
- class AbortSignal {
- constructor() {
- this.aborted = false;
- this.reason = undefined;
- this.onabort = null;
- this._l = [];
- }
- addEventListener(t, f) { if (t === "abort") this._l.push(f); }
- removeEventListener(t, f) { this._l = this._l.filter(function (x) { return x !== f; }); }
- throwIfAborted() { if (this.aborted) throw this.reason; }
- static abort(r) { var c = new AbortController(); c.abort(r); return c.signal; }
- static timeout(ms) {
- var c = new AbortController();
- setTimeout(function () {
- c.abort(new DOMException("signal timed out", "TimeoutError"));
- }, ms);
- return c.signal;
- }
- }
- class AbortController {
- constructor() { this.signal = new AbortSignal(); }
- abort(r) {
- var s = this.signal, ev;
- if (s.aborted) return;
- s.aborted = true;
- s.reason = r === undefined ?
- new DOMException("signal is aborted without reason",
- "AbortError") : r;
- ev = { type: "abort", target: s };
- if (typeof s.onabort === "function") s.onabort(ev);
- s._l.forEach(function (f) { f(ev); });
- }
- }
- def("AbortSignal", AbortSignal);
- def("AbortController", AbortController);
- class Request {
- constructor(input, init) {
- init = init || {};
- if (input instanceof Request) {
- this.url = input.url;
- this.method = input.method;
- this.headers = new Headers(input.headers);
- this.body = input.body;
- this.signal = input.signal;
- } else {
- this.url = new URL(String(input), g.location.href).href;
- this.method = "GET";
- this.headers = new Headers();
- this.body = null;
- this.signal = null;
- }
- if (init.method) this.method = String(init.method).toUpperCase();
- if (init.headers) this.headers = new Headers(init.headers);
- if (init.body !== undefined) this.body = init.body;
- if (init.signal) this.signal = init.signal;
- this.credentials = init.credentials || "same-origin";
- this.mode = init.mode || "cors";
- }
- clone() { return new Request(this); }
- }
- def("Request", Request);
- class Response {
- constructor(body, init) {
- init = init || {};
- this._b = body == null ? "" : partText(body);
- this.status = init.status === undefined ? 200 : init.status;
- this.statusText = init.statusText || "";
- this.headers = init.headers instanceof Headers ? init.headers :
- new Headers(init.headers);
- this.ok = this.status >= 200 && this.status < 300;
- this.url = init.url || "";
- this.redirected = !!init.redirected;
- this.type = "basic";
- this.bodyUsed = false;
- this.body = null;
- }
- text() { this.bodyUsed = true; return Promise.resolve(this._b); }
- json() {
- this.bodyUsed = true;
- try { return Promise.resolve(JSON.parse(this._b)); }
- catch (e) { return Promise.reject(e); }
- }
- blob() {
- this.bodyUsed = true;
- return Promise.resolve(new Blob([this._b],
- { type: this.headers.get("content-type") || "" }));
- }
- arrayBuffer() { this.bodyUsed = true; return Promise.resolve(utf8(this._b).buffer); }
- formData() { return Promise.reject(new TypeError("formData() is not supported")); }
- clone() {
- return new Response(this._b, { status: this.status,
- statusText: this.statusText, url: this.url,
- headers: new Headers(this.headers) });
- }
- static json(data, init) {
- var h = new Headers(init && init.headers);
- h.set("content-type", "application/json");
- return new Response(JSON.stringify(data),
- Object.assign({}, init, { headers: h }));
- }
- static error() { return new Response(null, { status: 0 }); }
- static redirect(url, status) {
- return new Response(null, { status: status || 302,
- headers: { location: String(url) } });
- }
- }
- def("Response", Response);
- var STATUS_TEXT = { 200: "OK", 201: "Created", 204: "No Content",
- 301: "Moved Permanently", 302: "Found", 303: "See Other",
- 304: "Not Modified", 400: "Bad Request", 401: "Unauthorized",
- 403: "Forbidden", 404: "Not Found", 409: "Conflict", 410: "Gone",
- 500: "Internal Server Error", 502: "Bad Gateway",
- 503: "Service Unavailable" };
- /* One synchronous request through the browser's fetch helpers. */
- function send(method, url, headers, body) {
- var ct = headers.get("content-type");
- if (body instanceof URLSearchParams) {
- if (!ct) ct = "application/x-www-form-urlencoded;charset=UTF-8";
- body = body.toString();
- } else if (body instanceof FormData) {
- var sp = new URLSearchParams();
- body.forEach(function (v, k) {
- sp.append(k, typeof v === "string" ? v : "");
- });
- body = sp.toString();
- ct = "application/x-www-form-urlencoded;charset=UTF-8";
- } else if (body instanceof Blob) {
- if (!ct) ct = body.type;
- body = body._s;
- } else if (body != null && typeof body !== "string") {
- body = partText(body);
- } else if (typeof body === "string" && !ct) {
- ct = "text/plain;charset=UTF-8";
- }
- if (method === "GET" || method === "HEAD") body = null;
- var r = http(method, url, ct || "", body == null ? "" : body);
- var h = new Headers();
- if (r[1]) h.set("content-type", r[1]);
- return { status: r[0], headers: h, url: r[2] || url, text: r[3] };
- }
- def("fetch", function (input, init) {
- return new Promise(function (res, rej) {
- var req, out;
- try {
- req = new Request(input, init);
- } catch (e) {
- rej(e);
- return;
- }
- if (req.signal && req.signal.aborted) {
- rej(req.signal.reason);
- return;
- }
- try {
- out = send(req.method, req.url, req.headers, req.body);
- } catch (e) {
- rej(new TypeError("Failed to fetch"));
- return;
- }
- res(new Response(out.text, { status: out.status,
- statusText: STATUS_TEXT[out.status] || "",
- headers: out.headers, url: out.url,
- redirected: out.url !== req.url }));
- });
- });
- /* XMLHttpRequest on the same synchronous path; events fire asynchronously
- * (from a timer) so the caller can finish wiring its handlers. */
- class XMLHttpRequest {
- constructor() {
- this.readyState = 0;
- this.status = 0;
- this.statusText = "";
- this.responseText = "";
- this.response = "";
- this.responseType = "";
- this.responseURL = "";
- this.timeout = 0;
- this.withCredentials = false;
- this._h = new Headers();
- this._rh = new Headers();
- this._l = {};
- this.upload = { addEventListener: function () {} };
- }
- open(method, url) {
- this._m = String(method).toUpperCase();
- this._u = new URL(String(url), g.location.href).href;
- this.readyState = 1;
- }
- setRequestHeader(k, v) { this._h.append(k, v); }
- getResponseHeader(k) { return this._rh.get(k); }
- getAllResponseHeaders() {
- var s = "";
- this._rh.forEach(function (v, k) { s += k + ": " + v + "\r\n"; });
- return s;
- }
- overrideMimeType() {}
- addEventListener(t, f) { (this._l[t] = this._l[t] || []).push(f); }
- removeEventListener(t, f) {
- if (this._l[t]) this._l[t] = this._l[t].filter(function (x) { return x !== f; });
- }
- _fire(t) {
- var ev = { type: t, target: this, currentTarget: this,
- lengthComputable: false, loaded: 0, total: 0 };
- if (typeof this["on" + t] === "function") this["on" + t](ev);
- (this._l[t] || []).slice().forEach((f) => f.call(this, ev));
- }
- abort() { this._aborted = true; }
- send(body) {
- var self = this, out, err = false;
- try {
- out = send(this._m, this._u, this._h, body);
- } catch (e) {
- err = true;
- }
- setTimeout(function () {
- if (self._aborted) return;
- if (err) {
- self.readyState = 4;
- self._fire("readystatechange");
- self._fire("error");
- self._fire("loadend");
- return;
- }
- self.status = out.status;
- self.statusText = STATUS_TEXT[out.status] || "";
- self._rh = out.headers;
- self.responseURL = out.url;
- self.responseText = out.text;
- if (self.responseType === "json") {
- try { self.response = JSON.parse(out.text); }
- catch (e) { self.response = null; }
- } else {
- self.response = out.text;
- }
- self.readyState = 4;
- self._fire("readystatechange");
- self._fire("load");
- self._fire("loadend");
- }, 0);
- }
- }
- XMLHttpRequest.UNSENT = 0;
- XMLHttpRequest.OPENED = 1;
- XMLHttpRequest.HEADERS_RECEIVED = 2;
- XMLHttpRequest.LOADING = 3;
- XMLHttpRequest.DONE = 4;
- def("XMLHttpRequest", XMLHttpRequest);
- /* ---- Web Storage, persisted by the host per origin ---- */
- function makeStorage(kind) {
- var data = {};
- try {
- var t = storage(kind);
- if (t) data = JSON.parse(t) || {};
- } catch (e) {
- data = {};
- }
- function save() { storage(kind, JSON.stringify(data)); }
- var api = {
- getItem: function (k) {
- k = String(k);
- return hasOwn.call(data, k) ? data[k] : null;
- },
- setItem: function (k, v) { data[String(k)] = String(v); save(); },
- removeItem: function (k) { delete data[String(k)]; save(); },
- clear: function () { data = {}; save(); },
- key: function (i) {
- var k = Object.keys(data);
- return i < k.length ? k[i] : null;
- }
- };
- return new Proxy({}, {
- get: function (t, k) {
- if (typeof k === "symbol") return undefined;
- if (k === "length") return Object.keys(data).length;
- if (hasOwn.call(api, k)) return api[k];
- return hasOwn.call(data, k) ? data[k] : undefined;
- },
- set: function (t, k, v) {
- if (typeof k === "symbol") return true;
- data[k] = String(v);
- save();
- return true;
- },
- has: function (t, k) {
- return typeof k === "string" &&
- (k === "length" || hasOwn.call(api, k) || hasOwn.call(data, k));
- },
- deleteProperty: function (t, k) {
- if (typeof k === "string" && hasOwn.call(data, k)) {
- delete data[k];
- save();
- }
- return true;
- },
- ownKeys: function () { return Object.keys(data); },
- getOwnPropertyDescriptor: function (t, k) {
- if (typeof k === "string" && hasOwn.call(data, k))
- return { value: data[k], writable: true,
- enumerable: true, configurable: true };
- return undefined;
- }
- });
- }
- def("localStorage", makeStorage(0));
- def("sessionStorage", makeStorage(1));
- /* ---- crypto ---- */
- var K256 = [
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
- 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
- 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
- 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
- 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
- 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
- 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
- 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
- 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
- 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
- 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
- function sha256(msg) {
- var h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
- 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
- var len = msg.length, n = ((len + 9 + 63) >> 6) << 6;
- var b = new Uint8Array(n), w = new Array(64), i, j;
- b.set(msg);
- b[len] = 0x80;
- b[n - 4] = (len * 8) >>> 24;
- b[n - 3] = (len * 8) >>> 16 & 255;
- b[n - 2] = (len * 8) >>> 8 & 255;
- b[n - 1] = (len * 8) & 255;
- b[n - 5] = Math.floor(len / 0x20000000) & 255;
- function rotr(x, r) { return (x >>> r) | (x << (32 - r)); }
- for (i = 0; i < n; i += 64) {
- for (j = 0; j < 16; j++)
- w[j] = (b[i + 4 * j] << 24) | (b[i + 4 * j + 1] << 16) |
- (b[i + 4 * j + 2] << 8) | b[i + 4 * j + 3];
- for (j = 16; j < 64; j++) {
- var s0 = rotr(w[j - 15], 7) ^ rotr(w[j - 15], 18) ^ (w[j - 15] >>> 3);
- var s1 = rotr(w[j - 2], 17) ^ rotr(w[j - 2], 19) ^ (w[j - 2] >>> 10);
- w[j] = (w[j - 16] + s0 + w[j - 7] + s1) | 0;
- }
- var a = h[0], bb = h[1], c = h[2], d = h[3], e = h[4], f = h[5],
- gg = h[6], hh = h[7];
- for (j = 0; j < 64; j++) {
- var S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
- var ch = (e & f) ^ (~e & gg);
- var t1 = (hh + S1 + ch + K256[j] + w[j]) | 0;
- var S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
- var mj = (a & bb) ^ (a & c) ^ (bb & c);
- var t2 = (S0 + mj) | 0;
- hh = gg; gg = f; f = e; e = (d + t1) | 0;
- d = c; c = bb; bb = a; a = (t1 + t2) | 0;
- }
- h[0] = (h[0] + a) | 0; h[1] = (h[1] + bb) | 0;
- h[2] = (h[2] + c) | 0; h[3] = (h[3] + d) | 0;
- h[4] = (h[4] + e) | 0; h[5] = (h[5] + f) | 0;
- h[6] = (h[6] + gg) | 0; h[7] = (h[7] + hh) | 0;
- }
- var out = new Uint8Array(32);
- for (i = 0; i < 8; i++) {
- out[4 * i] = h[i] >>> 24;
- out[4 * i + 1] = h[i] >>> 16 & 255;
- out[4 * i + 2] = h[i] >>> 8 & 255;
- out[4 * i + 3] = h[i] & 255;
- }
- return out;
- }
- /* The entropy is weak (Math.random seeded from the clock, stirred with the
- * millisecond timer), like the TLS DRBG; fine for PKCE nonces on a hobby
- * OS, not for long-term keys. */
- var rngState = sha256(utf8(String(Date.now()) + ":" + Math.random() + ":" +
- g.performance.now()));
- var rngPos = 0;
- function randomByte() {
- if (rngPos >= 32) {
- var seed = new Uint8Array(40);
- seed.set(rngState);
- var t = g.performance.now() * 1000 + Math.random() * 4294967296;
- for (var i = 0; i < 8; i++)
- seed[32 + i] = Math.floor(t / Math.pow(256, i)) & 255;
- rngState = sha256(seed);
- rngPos = 0;
- }
- return rngState[rngPos++];
- }
- var subtle = {
- digest: function (alg, data) {
- var name = typeof alg === "string" ? alg : alg && alg.name;
- if (String(name).toUpperCase().replace("-", "") !== "SHA256")
- return Promise.reject(new DOMException(
- "Unsupported algorithm " + name, "NotSupportedError"));
- return Promise.resolve(sha256(bytesOf(data)).buffer);
- }
- };
- def("crypto", {
- subtle: subtle,
- getRandomValues: function (a) {
- var u = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
- for (var i = 0; i < u.length; i++) u[i] = randomByte();
- return a;
- },
- randomUUID: function () {
- var b = new Uint8Array(16), i, s = "";
- this.getRandomValues(b);
- b[6] = (b[6] & 0x0f) | 0x40;
- b[8] = (b[8] & 0x3f) | 0x80;
- for (i = 0; i < 16; i++) {
- s += (b[i] + 0x100).toString(16).slice(1);
- if (i === 3 || i === 5 || i === 7 || i === 9) s += "-";
- }
- return s;
- }
- });
- /* ---- observers (no layout notifications yet: inert) ---- */
- class MutationObserver {
- constructor(cb) { this._cb = cb; }
- observe() {}
- disconnect() {}
- takeRecords() { return []; }
- }
- class ResizeObserver {
- constructor(cb) { this._cb = cb; }
- observe() {}
- unobserve() {}
- disconnect() {}
- }
- /* Without scroll geometry every observed target is reported visible, once
- * per observe(): lazy loaders and "becomes visible" components (heise's
- * a-img) then load their content. Capped per page against infinite-scroll
- * sentinels that re-observe forever. */
- var ioBudget = 400;
- /* One timer drains every deferred callback: a page with hundreds of lazy
- * images would otherwise overflow the browser's timer table. */
- var laterQ = [], laterArmed = false;
- function later(f) {
- laterQ.push(f);
- if (laterArmed) return;
- laterArmed = true;
- setTimeout(function () {
- var q = laterQ, i;
- laterQ = [];
- laterArmed = false;
- for (i = 0; i < q.length; i++)
- try { q[i](); } catch (e) { con.error(e); }
- }, 0);
- }
- class IntersectionObserver {
- constructor(cb, opts) {
- this._cb = cb;
- this._t = [];
- this.root = (opts && opts.root) || null;
- this.rootMargin = (opts && opts.rootMargin) || "0px";
- this.thresholds = [0];
- }
- observe(t) {
- var self = this;
- if (!t || this._t.indexOf(t) >= 0 || ioBudget <= 0) return;
- ioBudget--;
- this._t.push(t);
- later(function () {
- if (self._t.indexOf(t) < 0) return;
- var r = t.getBoundingClientRect();
- self._cb([{ target: t, isIntersecting: true,
- intersectionRatio: 1, boundingClientRect: r,
- intersectionRect: r, rootBounds: null,
- time: g.performance.now() }], self);
- });
- }
- unobserve(t) { this._t = this._t.filter(function (x) { return x !== t; }); }
- disconnect() { this._t = []; }
- takeRecords() { return []; }
- }
- def("MutationObserver", MutationObserver);
- def("ResizeObserver", ResizeObserver);
- def("IntersectionObserver", IntersectionObserver);
- /* Present with isIntersecting/intersectionRatio on the prototype so the
- * common IntersectionObserver polyfill (bundled by heise) keeps ours. */
- class IntersectionObserverEntry {
- constructor(init) { Object.assign(this, init); }
- get isIntersecting() { return !!this._i; }
- get intersectionRatio() { return this._r || 0; }
- }
- def("IntersectionObserverEntry", IntersectionObserverEntry);
- /* ---- DOM classes: instanceof works on the node wrappers ---- */
- function domClass(name, test) {
- var C = function () { throw new TypeError("Illegal constructor"); };
- Object.defineProperty(C, "name", { value: name });
- Object.defineProperty(C, Symbol.hasInstance, {
- value: function (o) {
- return o != null && typeof o === "object" &&
- typeof o.nodeType === "number" && test(o);
- }
- });
- C.prototype = nodeproto;
- def(name, C);
- return C;
- }
- function tag(t) { return function (o) { return o.nodeType === 1 && o.tagName === t; }; }
- /* Real accessors and methods on the shared prototype for the members the
- * C hook answers. A wrapper's own lookup reaches the hook first, so these
- * only serve code that takes them from the prototype, like DOMPurify's
- * clobbering-safe `getOwnPropertyDescriptor(Node.prototype, "nodeName")
- * .get.call(node)`; without them it read every node as null and treated
- * the whole tree as detached. `busy` stops the recursion when the hook
- * does not know the name (or `this` is not a wrapper). */
- (function () {
- var busy = false;
- function own(name) {
- return Object.getOwnPropertyDescriptor(nodeproto, name);
- }
- ["nodeName", "nodeType", "parentNode", "nextSibling", "childNodes",
- "attributes"].forEach(function (name) {
- if (own(name)) return;
- Object.defineProperty(nodeproto, name, {
- configurable: true, enumerable: false,
- get: function () {
- if (busy) return undefined;
- busy = true;
- try { return this[name]; } finally { busy = false; }
- },
- set: function (v) {
- if (busy) return;
- busy = true;
- try { this[name] = v; } finally { busy = false; }
- }
- });
- });
- ["cloneNode", "remove", "removeAttributeNode"].forEach(function (name) {
- if (own(name)) return;
- Object.defineProperty(nodeproto, name, {
- configurable: true, enumerable: false, writable: true,
- value: function () {
- var f;
- if (busy) return undefined;
- busy = true;
- try { f = this[name]; } finally { busy = false; }
- if (typeof f !== "function" || f === nodeproto[name])
- return undefined;
- return f.apply(this, arguments);
- }
- });
- });
- })();
- domClass("EventTarget", function (o) { return true; });
- domClass("Node", function (o) { return true; });
- domClass("Element", function (o) { return o.nodeType === 1; });
- domClass("HTMLElement", function (o) { return o.nodeType === 1; });
- domClass("SVGElement", function (o) { return o.nodeType === 1 && o.namespaceURI === "http://www.w3.org/2000/svg"; });
- domClass("CharacterData", function (o) { return o.nodeType === 3 || o.nodeType === 8; });
- domClass("Text", function (o) { return o.nodeType === 3; });
- domClass("Comment", function (o) { return o.nodeType === 8; });
- domClass("DocumentFragment", function (o) { return o.nodeType === 11; });
- domClass("Document", function (o) { return o.nodeType === 9; });
- domClass("DocumentType", function (o) { return o.nodeType === 10; });
- domClass("Attr", function (o) { return o.nodeType === 2; });
- domClass("HTMLDocument", function (o) { return o.nodeType === 9; });
- domClass("HTMLInputElement", tag("INPUT"));
- domClass("HTMLTextAreaElement", tag("TEXTAREA"));
- domClass("HTMLSelectElement", tag("SELECT"));
- domClass("HTMLOptionElement", tag("OPTION"));
- domClass("HTMLButtonElement", tag("BUTTON"));
- domClass("HTMLFormElement", tag("FORM"));
- domClass("HTMLAnchorElement", tag("A"));
- domClass("HTMLImageElement", tag("IMG"));
- domClass("HTMLTemplateElement", tag("TEMPLATE"));
- domClass("HTMLIFrameElement", tag("IFRAME"));
- domClass("HTMLLinkElement", tag("LINK"));
- domClass("HTMLScriptElement", tag("SCRIPT"));
- domClass("HTMLStyleElement", tag("STYLE"));
- domClass("HTMLCanvasElement", tag("CANVAS"));
- def("Window", function Window() {});
- /* ---- Custom Elements ----
- * A registered class adopts an existing element: HTMLElement, used as the
- * base constructor, returns the element being upgraded (or a fresh one for
- * `new MyElement()`) with its prototype switched to the subclass, the way
- * the custom-elements polyfills do it. New elements are upgraded when
- * created by script and by a scan after DOM changes (js_browser.c calls
- * __nb_ce_scan from its tick); connectedCallback runs once the element is
- * in the document. attributeChangedCallback fires for the observed
- * attributes present at upgrade, not for later changes. */
- var ceRegistry = new Map(), ceNames = new Map(), ceWaiters = new Map();
- var cePending = [];
- var createEl = g.document.createElement;
- function HTMLElementCtor() {
- var el = cePending.length ? cePending[cePending.length - 1] : null;
- if (!el) {
- var name = ceNames.get(new.target);
- if (!name) throw new TypeError("Illegal constructor");
- el = createEl.call(g.document, name);
- }
- Object.setPrototypeOf(el, new.target.prototype);
- return el;
- }
- HTMLElementCtor.prototype = nodeproto;
- Object.defineProperty(HTMLElementCtor, "name", { value: "HTMLElement" });
- Object.defineProperty(HTMLElementCtor, Symbol.hasInstance, {
- value: function (o) {
- if (this !== HTMLElementCtor)
- return Function.prototype[Symbol.hasInstance].call(this, o);
- return o != null && typeof o === "object" && o.nodeType === 1;
- }
- });
- def("HTMLElement", HTMLElementCtor);
- function ceUpgrade(el) {
- var C, obs, i;
- if (!el || el.nodeType !== 1 || el.__nbce) return;
- C = ceRegistry.get(el.localName);
- if (!C) return;
- el.__nbce = 1;
- cePending.push(el);
- try { new C(); } catch (e) { con.error(e); }
- cePending.pop();
- obs = C.observedAttributes;
- if (obs && typeof el.attributeChangedCallback === "function")
- for (i = 0; i < obs.length; i++)
- if (el.hasAttribute(obs[i]))
- try { el.attributeChangedCallback(obs[i], null, el.getAttribute(obs[i])); }
- catch (e) { con.error(e); }
- ceConnect(el);
- }
- function ceConnect(el) {
- if (el.__nbceConn || !el.isConnected) return;
- el.__nbceConn = 1;
- if (typeof el.connectedCallback === "function") {
- try {
- var r = el.connectedCallback();
- if (r && typeof r.then === "function")
- r.then(null, function (e) { con.error(e); });
- } catch (e) { con.error(e); }
- }
- }
- function ceScan() {
- ceRegistry.forEach(function (C, name) {
- var list = g.document.querySelectorAll(name), i;
- for (i = 0; i < list.length; i++) {
- if (!list[i].__nbce) ceUpgrade(list[i]);
- else ceConnect(list[i]);
- }
- });
- }
- def("__nb_ce_scan", function () { if (ceRegistry.size) ceScan(); });
- def("customElements", {
- define: function (name, C) {
- name = String(name).toLowerCase();
- if (ceRegistry.has(name))
- throw new DOMException("'" + name + "' is already defined", "NotSupportedError");
- ceRegistry.set(name, C);
- ceNames.set(C, name);
- ceScan();
- var w = ceWaiters.get(name);
- if (w) { w.forEach(function (f) { f(C); }); ceWaiters.delete(name); }
- },
- get: function (name) { return ceRegistry.get(String(name).toLowerCase()); },
- getName: function (C) { return ceNames.get(C) || null; },
- whenDefined: function (name) {
- name = String(name).toLowerCase();
- if (ceRegistry.has(name)) return Promise.resolve(ceRegistry.get(name));
- return new Promise(function (res) {
- if (!ceWaiters.has(name)) ceWaiters.set(name, []);
- ceWaiters.get(name).push(res);
- });
- },
- upgrade: function (root) {
- ceUpgrade(root);
- if (root && root.querySelectorAll) ceScan();
- }
- });
- g.document.createElement = function (name, opts) {
- var el = createEl.call(g.document, name);
- var n = String(name).toLowerCase();
- if (ceRegistry.has(n)) ceUpgrade(el);
- if (n === "img") imgLoadShim(el);
- return el;
- };
- /* Document collections (live: recomputed on every access). */
- [["scripts", "script"], ["images", "img"], ["forms", "form"],
- ["embeds", "embed"], ["links", "a[href],area[href]"]].forEach(function (p) {
- Object.defineProperty(g.document, p[0], {
- configurable: true,
- get: function () {
- return p[1].indexOf("[") >= 0 ?
- g.document.querySelectorAll(p[1]) :
- g.document.getElementsByTagName(p[1]);
- }
- });
- });
- /* Script-created images never really load in the page's DOM; fire "load"
- * once a src is set so preload-then-swap code (load a detached <img>, then
- * copy its URL) proceeds. The visible <img> is loaded by the browser. */
- function imgLoadShim(el) {
- later(function () {
- if (el.getAttribute("src"))
- el.dispatchEvent(new Event("load"));
- });
- }
- def("Image", function Image(w, h) {
- var el = g.document.createElement("img");
- if (w !== undefined) el.setAttribute("width", String(w));
- if (h !== undefined) el.setAttribute("height", String(h));
- return el;
- });
- def("ShadowRoot", function ShadowRoot() {});
- var NodeConst = g.Node;
- [["ELEMENT_NODE", 1], ["ATTRIBUTE_NODE", 2], ["TEXT_NODE", 3],
- ["CDATA_SECTION_NODE", 4], ["COMMENT_NODE", 8], ["DOCUMENT_NODE", 9],
- ["DOCUMENT_TYPE_NODE", 10], ["DOCUMENT_FRAGMENT_NODE", 11]]
- .forEach(function (p) { NodeConst[p[0]] = p[1]; });
- /* Methods every node wrapper inherits (the C has-hook answers the rest). */
- var doc = g.document;
- /* <template>.content: the parser keeps a template's children in the tree
- * (hidden); the first access moves them into a fragment, which Alpine's
- * x-for/x-if/x-teleport clone. */
- Object.defineProperty(nodeproto, "content", { configurable: true,
- get: function () {
- if (this.nodeType !== 1 || this.tagName !== "TEMPLATE")
- return undefined;
- if (!this.__nb_tc) {
- var f = doc.createDocumentFragment();
- while (this.firstChild)
- f.appendChild(this.firstChild);
- this.__nb_tc = f;
- }
- return this.__nb_tc;
- } });
- function toNode(n) {
- return typeof n === "object" && n !== null ? n : doc.createTextNode(String(n));
- }
- Object.assign(nodeproto, {
- setAttributeNS: function (ns, n, v) {
- this.setAttribute(String(n).replace(/^[^:]*:/, ""), v);
- },
- getAttributeNS: function (ns, n) { return this.getAttribute(n); },
- removeAttributeNS: function (ns, n) { this.removeAttribute(n); },
- hasAttributeNS: function (ns, n) { return this.hasAttribute(n); },
- toggleAttribute: function (n, force) {
- var on = force === undefined ? !this.hasAttribute(n) : !!force;
- if (on) this.setAttribute(n, "");
- else this.removeAttribute(n);
- return on;
- },
- getAttributeNames: function () {
- var a = this.attributes, out = [], i;
- for (i = 0; a && i < a.length; i++) out.push(a[i].name);
- return out;
- },
- closest: function (sel) {
- var e = this;
- while (e && e.nodeType === 1) {
- if (e.matches(sel)) return e;
- e = e.parentNode;
- }
- return null;
- },
- append: function () {
- for (var i = 0; i < arguments.length; i++)
- this.appendChild(toNode(arguments[i]));
- },
- prepend: function () {
- var first = this.firstChild;
- for (var i = 0; i < arguments.length; i++)
- this.insertBefore(toNode(arguments[i]), first);
- },
- before: function () {
- var p = this.parentNode;
- if (!p) return;
- for (var i = 0; i < arguments.length; i++)
- p.insertBefore(toNode(arguments[i]), this);
- },
- after: function () {
- var p = this.parentNode, next = this.nextSibling;
- if (!p) return;
- for (var i = 0; i < arguments.length; i++)
- p.insertBefore(toNode(arguments[i]), next);
- },
- replaceWith: function () {
- var p = this.parentNode;
- if (!p) return;
- this.before.apply(this, arguments);
- p.removeChild(this);
- },
- replaceChildren: function () {
- while (this.firstChild) this.removeChild(this.firstChild);
- this.append.apply(this, arguments);
- },
- insertAdjacentElement: function (pos, el) {
- pos = String(pos).toLowerCase();
- if (pos === "beforebegin") this.before(el);
- else if (pos === "afterbegin") this.prepend(el);
- else if (pos === "beforeend") this.appendChild(el);
- else if (pos === "afterend") this.after(el);
- return el;
- },
- insertAdjacentText: function (pos, text) {
- this.insertAdjacentElement(pos, doc.createTextNode(String(text)));
- },
- insertAdjacentHTML: function (pos, html) {
- var tmp = doc.createElement("div"), nodes = [], c;
- tmp.innerHTML = html;
- for (c = tmp.firstChild; c; c = c.nextSibling) nodes.push(c);
- pos = String(pos).toLowerCase();
- if (pos === "afterbegin") nodes.reverse();
- for (c of nodes) {
- tmp.removeChild(c);
- this.insertAdjacentElement(pos, c);
- }
- },
- getRootNode: function () { return doc; },
- scrollIntoView: function () {},
- scrollTo: function () {},
- scrollBy: function () {},
- animate: function () {
- return { finished: Promise.resolve(), cancel: function () {},
- play: function () {}, pause: function () {},
- onfinish: null };
- },
- attachShadow: function () { return this; },
- compareDocumentPosition: function (other) {
- if (this === other) return 0;
- if (this.contains(other)) return 20;
- if (other.contains && other.contains(this)) return 10;
- return 4;
- },
- isSameNode: function (o) { return this === o; },
- normalize: function () {}
- });
- /* ---- document extras ---- */
- doc.createElementNS = function (ns, name) {
- var el = doc.createElement(String(name).replace(/^[^:]*:/, ""));
- if (ns === "http://www.w3.org/2000/svg")
- el.setAttribute("xmlns", ns);
- return el;
- };
- doc.createRange = function () {
- return {
- createContextualFragment: function (html) {
- var tmp = doc.createElement("div"),
- frag = doc.createDocumentFragment();
- tmp.innerHTML = html;
- while (tmp.firstChild) frag.appendChild(tmp.firstChild);
- return frag;
- },
- selectNodeContents: function () {},
- setStart: function () {}, setEnd: function () {},
- getBoundingClientRect: function () {
- return { x: 0, y: 0, top: 0, left: 0, right: 0, bottom: 0,
- width: 0, height: 0 };
- }
- };
- };
- doc.createTreeWalker = undefined;
- /* NodeIterator over a snapshot of the subtree in document order. A node
- * removed from the root meanwhile is skipped, and the children a sanitizer
- * hoists out of a removed element are still visited, which is what
- * DOMPurify (the Cloudron dashboard's markdown) relies on. */
- def("NodeFilter", {
- FILTER_ACCEPT: 1, FILTER_REJECT: 2, FILTER_SKIP: 3,
- SHOW_ALL: 0xFFFFFFFF, SHOW_ELEMENT: 0x1, SHOW_ATTRIBUTE: 0x2,
- SHOW_TEXT: 0x4, SHOW_CDATA_SECTION: 0x8,
- SHOW_PROCESSING_INSTRUCTION: 0x40, SHOW_COMMENT: 0x80,
- SHOW_DOCUMENT: 0x100, SHOW_DOCUMENT_TYPE: 0x200,
- SHOW_DOCUMENT_FRAGMENT: 0x400
- });
- doc.createNodeIterator = function (root, what, filter) {
- var list = [], stack = [root], i = -1, n, c, kids;
- what = what === undefined ? 0xFFFFFFFF : what >>> 0;
- while (stack.length) {
- n = stack.pop();
- list.push(n);
- kids = [];
- for (c = n.firstChild; c; c = c.nextSibling) kids.push(c);
- while (kids.length) stack.push(kids.pop());
- }
- function shown(x) {
- var t = x.nodeType || 1, r;
- if (t > 32 || !(what & (1 << (t - 1)))) return false;
- if (!filter) return true;
- r = typeof filter === "function" ? filter(x) : filter.acceptNode(x);
- return r === 1;
- }
- function inside(x) { return x === root || root.contains(x); }
- return {
- root: root, whatToShow: what, filter: filter || null,
- referenceNode: root, pointerBeforeReferenceNode: true,
- nextNode: function () {
- while (++i < list.length)
- if (inside(list[i]) && shown(list[i]))
- return (this.referenceNode = list[i]);
- i = list.length;
- return null;
- },
- previousNode: function () {
- while (--i >= 0)
- if (inside(list[i]) && shown(list[i]))
- return (this.referenceNode = list[i]);
- i = -1;
- return null;
- },
- detach: function () {}
- };
- };
- doc.hasFocus = function () { return true; };
- doc.getElementsByName = function (n) {
- return doc.querySelectorAll("[name=\"" + String(n).replace(/"/g, "\\\"") + "\"]");
- };
- doc.hidden = false;
- doc.visibilityState = "visible";
- doc.characterSet = "UTF-8";
- doc.charset = "UTF-8";
- doc.contentType = "text/html";
- doc.referrer = "";
- doc.dir = "";
- /* CSS Font Loading API surface. Faces come from the stylesheets'
- * @font-face rules, loaded before layout; a script-built FontFace resolves
- * at once but is not rendered (the cascade resolves families at parse). */
- g.FontFace = function (family, source, desc) {
- this.family = String(family);
- this.source = source;
- desc = desc || {};
- this.style = desc.style || "normal";
- this.weight = String(desc.weight || "normal");
- this.display = desc.display || "auto";
- this.unicodeRange = desc.unicodeRange || "U+0-10FFFF";
- this.status = "loaded";
- this.loaded = Promise.resolve(this);
- };
- g.FontFace.prototype.load = function () { return this.loaded; };
- (function () {
- var faces = [];
- var fonts = {
- status: "loaded", ready: null, onloading: null,
- onloadingdone: null, onloadingerror: null,
- add: function (f) { if (faces.indexOf(f) < 0) faces.push(f); return fonts; },
- delete: function (f) { var i = faces.indexOf(f); if (i < 0) return false; faces.splice(i, 1); return true; },
- has: function (f) { return faces.indexOf(f) >= 0; },
- clear: function () { faces.length = 0; },
- forEach: function (cb, t) { faces.slice().forEach(function (f) { cb.call(t, f, f, fonts); }); },
- values: function () { return faces.slice()[Symbol.iterator](); },
- load: function () { return Promise.resolve([]); },
- check: function () { return true; },
- addEventListener: function () {},
- removeEventListener: function () {}
- };
- fonts.ready = Promise.resolve(fonts);
- fonts.keys = fonts.values;
- fonts[Symbol.iterator] = fonts.values;
- Object.defineProperty(fonts, "size", { get: function () { return faces.length; } });
- doc.fonts = fonts;
- })();
- /* A separate inert document (jQuery's parseHTML context, DOMPurify): its
- * nodes live in the page's node arena but are detached, so writing to its
- * body never touches the page. Returning the page document here made
- * jQuery's support probe replace the whole page body with two <form>s. */
- function nbInertDocument(title) {
- var html = doc.createElement("html"), head = doc.createElement("head");
- var body = doc.createElement("body"), d;
- html.appendChild(head);
- html.appendChild(body);
- if (title !== undefined) {
- var t = doc.createElement("title");
- t.textContent = String(title);
- head.appendChild(t);
- }
- d = {
- __nbInert: true,
- nodeType: 9, nodeName: "#document", documentElement: html,
- head: head, body: body, readyState: "complete",
- compatMode: "CSS1Compat", characterSet: "UTF-8",
- contentType: "text/html", defaultView: null, location: null,
- cookie: "", URL: "about:blank", baseURI: doc.URL,
- addEventListener: function () {},
- removeEventListener: function () {},
- querySelector: function (s) { return html.querySelector(s); },
- querySelectorAll: function (s) { return html.querySelectorAll(s); },
- getElementsByTagName: function (s) {
- return html.getElementsByTagName(s);
- },
- getElementsByClassName: function (s) {
- return html.getElementsByClassName(s);
- },
- getElementById: function (id) {
- return html.querySelector("[id=\"" +
- String(id).replace(/"/g, "\\\"") + "\"]");
- }
- };
- ["createElement", "createTextNode", "createComment",
- "createDocumentFragment", "createAttribute", "createEvent"].forEach(
- function (m) {
- d[m] = function () { return doc[m].apply(doc, arguments); };
- });
- d.createElementNS = function (ns, n) { return doc.createElement(n); };
- d.implementation = doc.implementation;
- Object.defineProperty(d, "title", { configurable: true,
- get: function () {
- var t = head.querySelector("title");
- return t ? t.textContent : "";
- } });
- return d;
- }
- /* The page document's lookups called on an inert document
- * (`document.getElementsByTagName.call(parsed, "body")`, as DOMPurify does)
- * answer for that document: searching the page instead handed DOMPurify the
- * real <body> to sanitize, and it emptied the page. */
- ["getElementsByTagName", "getElementsByClassName", "querySelector",
- "querySelectorAll", "getElementById"].forEach(function (m) {
- var f = doc[m];
- if (typeof f !== "function") return;
- doc[m] = function () {
- if (this && this !== doc && this.__nbInert)
- return this[m].apply(this, arguments);
- return f.apply(doc, arguments);
- };
- });
- doc.implementation = {
- hasFeature: function () { return true; },
- createHTMLDocument: function (title) { return nbInertDocument(title); }
- };
- /* DOMParser on the same inert document: the markup goes through the
- * innerHTML fragment parser. A whole document is split at its <head> and
- * <body>, so the parsed body holds the body's children and not a nested
- * copy of the <html>/<head>/<body> elements. */
- if (!g.DOMParser) {
- g.DOMParser = function DOMParser() {};
- g.DOMParser.prototype.parseFromString = function (str) {
- var d = nbInertDocument(), s = String(str), m;
- s = s.replace(/<!doctype[^>]*>/i, "");
- m = /<head(\s[^>]*)?>([\s\S]*?)<\/head>/i.exec(s);
- if (m) {
- d.head.innerHTML = m[2];
- s = s.slice(0, m.index) + s.slice(m.index + m[0].length);
- }
- m = /<body(\s[^>]*)?>([\s\S]*?)(<\/body>|$)/i.exec(s);
- s = m ? m[2] : s.replace(/<\/?html(\s[^>]*)?>/gi, "");
- d.body.innerHTML = s;
- return d;
- };
- }
- Object.defineProperty(doc, "activeElement", {
- get: function () { return doc.body; }, configurable: true });
- Object.defineProperty(doc, "defaultView", {
- get: function () { return g; }, configurable: true });
- var nav = g.navigator;
- nav.languages = [nav.language];
- nav.onLine = true;
- nav.cookieEnabled = true;
- nav.maxTouchPoints = 0;
- nav.hardwareConcurrency = 1;
- nav.vendor = "";
- nav.clipboard = {
- writeText: function () { return Promise.resolve(); },
- readText: function () { return Promise.resolve(""); }
- };
- nav.sendBeacon = function () { return true; };
- /* ---- performance: a page-relative clock, User Timing, no resources ----
- * The C side's now() counts from boot; pages expect milliseconds since the
- * navigation (google.com adds it to timing.navigationStart). mark()/
- * measure() keep a small timeline that getEntries*() search; resource and
- * navigation entries are never recorded, so those lists are empty.
- * google.com's results script calls performance.mark/measure/clearMarks
- * around every render and getEntriesByType("resource") in its CSI ping;
- * both threw "not a function" before. */
- (function () {
- var perf = g.performance, rawNow = perf.now, base = rawNow.call(perf);
- var origin = Date.now(), timeline = [];
- function now() { return rawNow.call(perf) - base; }
- function at(v) {
- if (typeof v === "number") return v;
- if (typeof v === "string") {
- for (var i = timeline.length - 1; i >= 0; i--)
- if (timeline[i].entryType === "mark" &&
- timeline[i].name === v)
- return timeline[i].startTime;
- throw new SyntaxError("The mark '" + v + "' does not exist.");
- }
- return undefined;
- }
- function entry(name, type, start, duration, detail) {
- var e = { name: String(name), entryType: type, startTime: start,
- duration: duration, detail: detail === undefined ?
- null : detail };
- e.toJSON = function () { return Object.assign({}, this); };
- timeline.push(e);
- if (timeline.length > 1000) timeline.shift();
- return e;
- }
- function clear(type, name) {
- timeline = timeline.filter(function (e) {
- return e.entryType !== type ||
- (name !== undefined && e.name !== name);
- });
- }
- perf.now = now;
- perf.timeOrigin = origin;
- perf.timing = {
- navigationStart: origin, fetchStart: origin,
- requestStart: origin, responseStart: origin,
- responseEnd: origin, domLoading: origin,
- domInteractive: origin, domContentLoadedEventStart: origin,
- domContentLoadedEventEnd: origin, domComplete: origin,
- loadEventStart: origin, loadEventEnd: origin,
- toJSON: function () { return Object.assign({}, this); }
- };
- perf.navigation = { type: 0, redirectCount: 0 };
- perf.mark = function (name, opts) {
- opts = opts || {};
- return entry(name, "mark", opts.startTime !== undefined ?
- opts.startTime : now(), 0, opts.detail);
- };
- perf.measure = function (name, start, end) {
- var s = 0, e = now(), detail;
- if (start && typeof start === "object") {
- detail = start.detail;
- if (start.start !== undefined) s = at(start.start);
- if (start.end !== undefined) e = at(start.end);
- if (start.duration !== undefined) {
- if (start.start !== undefined) e = s + start.duration;
- else s = e - start.duration;
- }
- } else {
- if (start !== undefined) s = at(start);
- if (end !== undefined) e = at(end);
- }
- return entry(name, "measure", s, e - s, detail);
- };
- perf.clearMarks = function (name) { clear("mark", name); };
- perf.clearMeasures = function (name) { clear("measure", name); };
- perf.clearResourceTimings = function () {};
- perf.setResourceTimingBufferSize = function () {};
- perf.getEntries = function () { return timeline.slice(); };
- perf.getEntriesByType = function (type) {
- return timeline.filter(function (e) { return e.entryType === type; });
- };
- perf.getEntriesByName = function (name, type) {
- return timeline.filter(function (e) {
- return e.name === name &&
- (type === undefined || e.entryType === type);
- });
- };
- perf.toJSON = function () {
- return { timeOrigin: origin, timing: perf.timing.toJSON() };
- };
- })();
- class PerformanceObserver {
- constructor(cb) { this._cb = cb; }
- observe() {}
- disconnect() {}
- takeRecords() { return []; }
- }
- PerformanceObserver.supportedEntryTypes = [];
- def("PerformanceObserver", PerformanceObserver);
- /* ---- CSS namespace ----
- * escape() is the CSSOM serialization of an identifier; supports() gives
- * the cascade's own @supports answer (true unless it asks for selector()),
- * so scripts and stylesheets agree. */
- def("CSS", {
- escape: function (value) {
- var s = String(value), out = "", i, c, first = s.charCodeAt(0);
- if (s.length === 1 && first === 0x2D) return "\\-";
- for (i = 0; i < s.length; i++) {
- c = s.charCodeAt(i);
- if (c === 0) out += "�";
- else if ((c >= 0x01 && c <= 0x1F) || c === 0x7F ||
- (i === 0 && c >= 0x30 && c <= 0x39) ||
- (i === 1 && c >= 0x30 && c <= 0x39 &&
- first === 0x2D))
- out += "\\" + c.toString(16) + " ";
- else if (c >= 0x80 || c === 0x2D || c === 0x5F ||
- (c >= 0x30 && c <= 0x39) ||
- (c >= 0x41 && c <= 0x5A) ||
- (c >= 0x61 && c <= 0x7A))
- out += s.charAt(i);
- else
- out += "\\" + s.charAt(i);
- }
- return out;
- },
- supports: function (prop, value) {
- var q = arguments.length > 1 ? String(prop) + ":" + String(value) :
- String(prop);
- return !/selector\s*\(/i.test(q) && !/^\s*not\s/i.test(q);
- }
- });
- g.history.state = null;
- g.screen = { width: g.innerWidth, height: g.innerHeight,
- availWidth: g.innerWidth, availHeight: g.innerHeight,
- colorDepth: 16, pixelDepth: 16 };
- g.outerWidth = g.innerWidth;
- g.outerHeight = g.innerHeight;
- g.name = "";
- g.closed = false;
- g.open = function () { return null; };
- g.close = function () {};
- g.focus = function () {};
- g.blur = function () {};
- g.print = function () {};
- g.postMessage = function () {};
- g.confirm = function () { return true; };
- g.prompt = function () { return null; };
- /* Parsed <template> children are inert in a browser: move them into each
- * template's content fragment before the page's scripts walk the tree
- * (Alpine would otherwise initialise them in place, in the wrong scope). */
- (function () {
- var tl = doc.getElementsByTagName("template"), a = [], i;
- for (i = 0; i < tl.length; i++)
- a.push(tl[i]);
- for (i = 0; i < a.length; i++)
- void a[i].content;
- })();
- })(globalThis);
|