/* 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); def("queueMicrotask", function (f) { Promise.resolve().then(f); }); 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() {} } class IntersectionObserver { constructor(cb, opts) { this._cb = cb; this.root = null; this.thresholds = [0]; } observe() {} unobserve() {} disconnect() {} takeRecords() { return []; } } def("MutationObserver", MutationObserver); def("ResizeObserver", ResizeObserver); def("IntersectionObserver", IntersectionObserver); /* ---- 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; }; } 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("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() {}); 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; 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; 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 = ""; doc.fonts = { ready: Promise.resolve(), add: function () {}, load: function () { return Promise.resolve([]); }, check: function () { return true; }, addEventListener: function () {} }; doc.implementation = { hasFeature: function () { return true; }, createHTMLDocument: function () { return doc; } }; Object.defineProperty(doc, "activeElement", { get: function () { return doc.body; }, configurable: true }); Object.defineProperty(doc, "currentScript", { get: function () { return null; }, 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; }; 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; }; g.dispatchEvent = g.dispatchEvent || function () { return true; }; })(globalThis);