JavaScriptBootstrap.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptBootstrap.kt
1package eu.friedcutlet.yokan.services.extensions.js23import eu.friedcutlet.yokan.database.DbSource4import kotlinx.serialization.json.JsonObject5import kotlinx.serialization.json.JsonPrimitive6import kotlinx.serialization.json.buildJsonObject78/**9 * Mangayomi-compatible globals (`Client`, `SharedPreferences`, `MProvider`, DOM, crypto, ...)10 * evaluated before the extension source; every host call goes through `sendMessage`.11 */12internal fun javaScriptBootstrap(source: DbSource): String =13 """14 function sendMessage(channel, payload) {15 return __bridge.sendMessage(String(channel), String(payload));16 }1718 function Client(reqcopyWith) { this.reqcopyWith = reqcopyWith || null; }19 // The bootstrap intentionally stays ES5 so loading it is cheap. User extensions run directly20 // on QuickJS and can use modern ECMAScript syntax without a transpilation pass.21 Client.prototype.head = function(url, headers) { return JSON.parse(sendMessage("http_head", JSON.stringify([null, this.reqcopyWith, url, headers || {}]))); };22 Client.prototype.get = function(url, headers) { return JSON.parse(sendMessage("http_get", JSON.stringify([null, this.reqcopyWith, url, headers || {}]))); };23 Client.prototype.post = function(url, headers, body) { return JSON.parse(sendMessage("http_post", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); };24 Client.prototype.put = function(url, headers, body) { return JSON.parse(sendMessage("http_put", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); };25 Client.prototype.delete = function(url, headers, body) { return JSON.parse(sendMessage("http_delete", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); };26 Client.prototype.patch = function(url, headers, body) { return JSON.parse(sendMessage("http_patch", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); };2728 function SharedPreferences() {}29 SharedPreferences.prototype.get = function(key) { return sendMessage("get", JSON.stringify([key])); };30 SharedPreferences.prototype.getString = function(key, defaultValue) { return sendMessage("getString", JSON.stringify([key, defaultValue == null ? "" : defaultValue])); };31 SharedPreferences.prototype.setString = function(key, value) { return sendMessage("setString", JSON.stringify([key, value == null ? "" : String(value)])); };32 SharedPreferences.prototype.getBoolean = function(key, defaultValue) {33 var raw = sendMessage("getString", JSON.stringify([key, ""]));34 if (raw === "true") return true;35 if (raw === "false") return false;36 return !!defaultValue;37 };38 SharedPreferences.prototype.getInt = function(key, defaultValue) {39 var raw = sendMessage("getString", JSON.stringify([key, ""]));40 var n = parseInt(raw, 10);41 return isNaN(n) ? (defaultValue | 0) : n;42 };43 SharedPreferences.prototype.getLong = function(key, defaultValue) {44 var raw = sendMessage("getString", JSON.stringify([key, ""]));45 var n = Number(raw);46 return isFinite(n) && raw !== "" ? n : (defaultValue || 0);47 };48 SharedPreferences.prototype.getFloat = function(key, defaultValue) {49 var raw = sendMessage("getString", JSON.stringify([key, ""]));50 var n = parseFloat(raw);51 return isNaN(n) ? (defaultValue || 0) : n;52 };53 SharedPreferences.prototype.getStringSet = function(key, defaultValue) {54 var raw = sendMessage("getString", JSON.stringify([key, ""]));55 if (!raw) return defaultValue || [];56 try { var parsed = JSON.parse(raw); if (Array.isArray(parsed)) return parsed; } catch (e) {}57 return String(raw).split(",").map(function(s) { return s.trim(); }).filter(Boolean);58 };59 SharedPreferences.prototype.setBoolean = function(key, value) { return sendMessage("setString", JSON.stringify([key, value ? "true" : "false"])); };60 SharedPreferences.prototype.setInt = function(key, value) { return sendMessage("setString", JSON.stringify([key, String(value | 0)])); };61 SharedPreferences.prototype.setLong = function(key, value) { return sendMessage("setString", JSON.stringify([key, String(value)])); };62 SharedPreferences.prototype.setFloat = function(key, value) { return sendMessage("setString", JSON.stringify([key, String(value)])); };63 SharedPreferences.prototype.setStringSet = function(key, value) { return sendMessage("setString", JSON.stringify([key, JSON.stringify(value || [])])); };6465 // QuickJS lacks a few newer builtins the extensions rely on; polyfill defensively.66 if (typeof Array.prototype.at !== "function") {67 Array.prototype.at = function(index) { index = Math.trunc(index) || 0; if (index < 0) index += this.length; return (index < 0 || index >= this.length) ? undefined : this[index]; };68 }69 if (typeof String.prototype.at !== "function") {70 String.prototype.at = function(index) { index = Math.trunc(index) || 0; if (index < 0) index += this.length; return (index < 0 || index >= this.length) ? undefined : this.charAt(index); };71 }72 if (typeof Array.prototype.findLast !== "function") {73 Array.prototype.findLast = function(predicate, thisArg) { for (var i = this.length - 1; i >= 0; i--) { if (predicate.call(thisArg, this[i], i, this)) return this[i]; } return undefined; };74 }75 if (typeof Array.prototype.findLastIndex !== "function") {76 Array.prototype.findLastIndex = function(predicate, thisArg) { for (var i = this.length - 1; i >= 0; i--) { if (predicate.call(thisArg, this[i], i, this)) return i; } return -1; };77 }7879 var console = typeof console === "undefined" ? {} : console;80 console.log = console.warn = console.error = function(message) {81 if (typeof message === "object") message = JSON.stringify(message);82 sendMessage("log", JSON.stringify([String(message)]));83 };8485 String.prototype.substringAfter = function(pattern) {86 const index = this.indexOf(pattern);87 return index === -1 ? this.substring(0) : this.substring(index + pattern.length);88 };89 String.prototype.substringAfterLast = function(pattern) { return this.split(pattern).pop(); };90 String.prototype.substringBefore = function(pattern) {91 const index = this.indexOf(pattern);92 return index === -1 ? this.substring(0) : this.substring(0, index);93 };94 String.prototype.substringBeforeLast = function(pattern) {95 const index = this.lastIndexOf(pattern);96 return index === -1 ? this.substring(0) : this.substring(0, index);97 };98 String.prototype.substringBetween = function(left, right) {99 const start = this.indexOf(left);100 if (start === -1) return "";101 const contentStart = start + left.length;102 const end = this.indexOf(right, contentStart);103 return end === -1 ? "" : this.substring(contentStart, end);104 };105106 function parseDates(value, dateFormat, dateFormatLocale) {107 return JSON.parse(sendMessage("parseDates", JSON.stringify([Array.isArray(value) ? value : [value], dateFormat || "", dateFormatLocale || ""])));108 }109110 $HTML_DOM_JS111 function xpathFirst(html, expression) {112 return JSON.parse(sendMessage("xpathFirst", JSON.stringify([String(html || ""), String(expression || "")])));113 }114 function xpathAll(html, expression) {115 return JSON.parse(sendMessage("xpathAll", JSON.stringify([String(html || ""), String(expression || "")])));116 }117118 function parseEpub(path) {119 return JSON.parse(sendMessage("parseEpub", JSON.stringify([String(path || "")])));120 }121 function parseEpubChapter(path, index) {122 return sendMessage("parseEpubChapter", JSON.stringify([String(path || ""), index | 0]));123 }124 function cryptoBytesToHex(value) {125 if (typeof value === "string") return value;126 if (!Array.isArray(value)) return "";127 var out = "";128 for (var i = 0; i < value.length; i++) {129 var part = (Number(value[i]) & 255).toString(16);130 out += part.length < 2 ? "0" + part : part;131 }132 return out;133 }134 var Crypto = {135 aesEncrypt: function(keyHexOrBase64, ivHexOrBase64, plaintext) {136 return JSON.parse(sendMessage("cryptoAes", JSON.stringify(["encrypt", keyHexOrBase64, ivHexOrBase64, plaintext])));137 },138 aesDecrypt: function(keyHexOrBase64, ivHexOrBase64, ciphertext) {139 return JSON.parse(sendMessage("cryptoAes", JSON.stringify(["decrypt", keyHexOrBase64, ivHexOrBase64, ciphertext])));140 },141 aesGcmEncrypt: function(keyHexOrBase64, ivHexOrBase64, plaintextHexOrBase64, additionalDataHexOrBase64) {142 return JSON.parse(sendMessage("cryptoAesGcm", JSON.stringify(["encrypt", keyHexOrBase64, ivHexOrBase64, plaintextHexOrBase64, additionalDataHexOrBase64 || ""])));143 },144 aesGcmDecrypt: function(options, ivHexOrBase64, ciphertextHexOrBase64) {145 var key = options;146 var iv = ivHexOrBase64;147 var data = ciphertextHexOrBase64;148 var returnText = false;149 if (options && typeof options === "object") {150 key = options.key || (options.keyFromSha256 ? this.sha256Hex(options.keyFromSha256) : "");151 iv = cryptoBytesToHex(options.iv);152 data = cryptoBytesToHex(options.data);153 returnText = true;154 }155 var result = JSON.parse(sendMessage("cryptoAesGcm", JSON.stringify(["decrypt", key, iv, data, options && options.additionalData ? options.additionalData : ""])));156 return returnText ? (result ? result.utf8 : null) : result;157 },158 sha256: function(data) { return JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-256", data]))); },159 sha1: function(data) { return JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-1", data]))); },160 md5: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["md5", String(data == null ? "" : data)]))); return r ? r.hex : ""; },161 sha256Hex: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-256", String(data == null ? "" : data)]))); return r ? r.hex : ""; },162 sha1Hex: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-1", String(data == null ? "" : data)]))); return r ? r.hex : ""; },163 sha256Bytes: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-256", String(data == null ? "" : data)]))); return r ? r.hex : ""; },164 hmac: function(algorithm, key, message) { var r = JSON.parse(sendMessage("cryptoHmac", JSON.stringify([String(algorithm || "sha-256"), String(key == null ? "" : key), String(message == null ? "" : message)]))); return r ? r.hex : ""; },165 hmacSHA256: function(key, message) { return this.hmac("sha-256", key, message); },166 hmacSha256: function(key, message) { return this.hmac("sha-256", key, message); },167 hmacSha256Truncated: function(key, message, bytes) { return this.hmac("sha-256", key, message).substring(0, (bytes | 0) * 2); },168 hmacSHA1: function(key, message) { return this.hmac("sha-1", key, message); },169 base64Encode: function(text) { return JSON.parse(sendMessage("cryptoBase64", JSON.stringify(["encode", String(text || "")]))); },170 base64Decode: function(text) { return JSON.parse(sendMessage("cryptoBase64", JSON.stringify(["decode", String(text || "")]))); },171 fromBase64: function(text) { return JSON.parse(sendMessage("cryptoBase64", JSON.stringify(["decode", String(text || "")]))); },172 base64ToHex: function(b64) { var s = atob(String(b64 || "")); var out = ""; for (var i = 0; i < s.length; i++) { var h = s.charCodeAt(i).toString(16); out += h.length < 2 ? "0" + h : h; } return out; },173 tripleDESEncrypt: function(dataBase64, keyBase64, ivBase64) { var r = JSON.parse(sendMessage("cryptoDes", JSON.stringify(["encrypt", String(keyBase64 || ""), String(ivBase64 || ""), String(dataBase64 || "")]))); return r ? r.base64 : ""; },174 encrypt3DESCBC: function(dataBase64, keyBase64, ivBase64) { return this.tripleDESEncrypt(dataBase64, keyBase64, ivBase64); }175 };176 var Extractors = {177 extract: function(host, url, headers) {178 return JSON.parse(sendMessage("extractVideo", JSON.stringify([String(host || ""), String(url || ""), headers || {}])));179 }180 };181182 // Promise-aware JSON.stringify helper. Extensions can pass either synchronous or asynchronous183 // producer functions; QuickJS drains the resulting promise jobs before evaluation returns.184 function jsonStringify(fn) {185 var result = fn();186 if (result && typeof result.then === "function") {187 return result.then(function(v) { return JSON.stringify(v); });188 }189 return JSON.stringify(result);190 }191192 function MProvider() {}193 Object.defineProperty(MProvider.prototype, "source", { get: function() { return ${source.toMSourceJson()}; }, configurable: true });194 Object.defineProperty(MProvider.prototype, "supportsLatest", { get: function() { throw new Error("supportsLatest not implemented"); }, configurable: true });195 // Default methods stay synchronous; subclasses may freely override them with async methods.196 MProvider.prototype.getHeaders = function(url) { throw new Error("getHeaders not implemented"); };197 MProvider.prototype.getPopular = function(page) { throw new Error("getPopular not implemented"); };198 MProvider.prototype.getLatestUpdates = function(page) { throw new Error("getLatestUpdates not implemented"); };199 MProvider.prototype.search = function(query, page, filters) { throw new Error("search not implemented"); };200 MProvider.prototype.getDetail = function(url) { throw new Error("getDetail not implemented"); };201 MProvider.prototype.getPageList = function(url) { throw new Error("getPageList not implemented"); };202 MProvider.prototype.getVideoList = function(url) { throw new Error("getVideoList not implemented"); };203 MProvider.prototype.getHtmlContent = function(name, url) { throw new Error("getHtmlContent not implemented"); };204 MProvider.prototype.cleanHtmlContent = function(html) { throw new Error("cleanHtmlContent not implemented"); };205 MProvider.prototype.getFilterList = function() { return []; };206 MProvider.prototype.getSourcePreferences = function() { return []; };207 """.trimIndent()208209private fun DbSource.toMSourceJson(): JsonObject = buildJsonObject {210 put("apiUrl", JsonPrimitive(apiUrl))211 put("baseUrl", JsonPrimitive(baseUrl))212 put("dateFormat", JsonPrimitive(dateFormat))213 put("dateFormatLocale", JsonPrimitive(dateFormatLocale))214 put("hasCloudflare", JsonPrimitive(hasCloudflare))215 put("id", JsonPrimitive(id))216 put("isFullData", JsonPrimitive(isFullData))217 put("lang", JsonPrimitive(lang))218 put("name", JsonPrimitive(name))219 put("additionalParams", JsonPrimitive(additionalParams))220 put("notes", JsonPrimitive(notes))221}222