LnReaderBootstrap.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/lnreader/LnReaderBootstrap.kt
1package eu.friedcutlet.yokan.services.extensions.lnreader23import eu.friedcutlet.yokan.services.extensions.js.HTML_DOM_JS45/** LNReader's CommonJS modules run with synchronous HTTP, DOM and Promise adapters. */6internal val lnReaderBootstrap = HTML_DOM_JS + """7 function LnPromise(executor) {8 var self = this;9 self.state = 0; self.value = undefined; self.handlers = [];10 function settle(state, value) {11 if (self.state) return;12 if (state === 1 && value && typeof value.then === 'function') {13 if (value === self) return settle(2, new TypeError('Promise resolved to itself'));14 return value.then(function(v) { settle(1, v); }, function(e) { settle(2, e); });15 }16 self.state = state; self.value = value;17 self.handlers.splice(0).forEach(function(handler) { handler(); });18 }19 try { executor(function(v) { settle(1, v); }, function(e) { settle(2, e); }); }20 catch (e) { settle(2, e); }21 }22 LnPromise.prototype.then = function(success, failure) {23 var self = this;24 return new LnPromise(function(resolve, reject) {25 function run() {26 var callback = self.state === 1 ? success : failure;27 if (typeof callback !== 'function') return (self.state === 1 ? resolve : reject)(self.value);28 try { resolve(callback(self.value)); } catch (e) { reject(e); }29 }30 if (self.state) run(); else self.handlers.push(run);31 });32 };33 LnPromise.prototype.catch = function(failure) { return this.then(undefined, failure); };34 LnPromise.prototype.finally = function(callback) {35 return this.then(function(value) { return LnPromise.resolve(callback()).then(function() { return value; }); },36 function(error) { return LnPromise.resolve(callback()).then(function() { throw error; }); });37 };38 LnPromise.resolve = function(value) { return value instanceof LnPromise ? value : new LnPromise(function(resolve) { resolve(value); }); };39 LnPromise.reject = function(error) { return new LnPromise(function(resolve, reject) { reject(error); }); };40 LnPromise.all = function(values) {41 return new LnPromise(function(resolve, reject) {42 var result = [], remaining = values.length;43 if (!remaining) return resolve(result);44 values.forEach(function(value, index) { LnPromise.resolve(value).then(function(v) {45 result[index] = v; if (!--remaining) resolve(result);46 }, reject); });47 });48 };49 function lnReaderResult(value) {50 if (value && typeof value.then === 'function') {51 var complete = false, failure = false, result;52 value.then(function(v) { complete = true; result = v; }, function(e) { complete = true; failure = true; result = e; });53 if (!complete) throw new Error('LNReader plugin returned an unsupported asynchronous operation');54 if (failure) throw result;55 value = result;56 }57 return JSON.stringify(value === undefined ? null : value);58 }59 function LnFormData() { this.fields = []; }60 LnFormData.prototype.append = function(name, value) { this.fields.push([String(name), String(value)]); };61 LnFormData.prototype.toString = function() { return this.fields.map(function(pair) {62 return encodeURIComponent(pair[0]) + '=' + encodeURIComponent(pair[1]);63 }).join('&'); };64 function lnFetch(url, options) {65 options = options || {};66 var method = (options.method || 'GET').toLowerCase();67 if (options.body instanceof LnFormData) {68 options.headers = Object.assign({'Content-Type': 'application/x-www-form-urlencoded'}, options.headers || {});69 options.body = options.body.toString();70 }71 var response = JSON.parse(__bridge.sendMessage('http_' + method,72 JSON.stringify([null, null, String(url), options.headers || {}, options.body == null ? null : options.body])));73 var value = {74 text: function() { return response.body; },75 json: function() { return JSON.parse(response.body); },76 status: response.statusCode, statusText: response.reasonPhrase || '',77 ok: response.statusCode >= 200 && response.statusCode < 300,78 url: response.request && response.request.url || String(url),79 headers: response.headers || {}80 };81 return Object.assign(LnPromise.resolve(value), value);82 }83 function lnLoad(html) {84 var document = new Document(html);85 function wrap(elements) { return new Selection(elements); }86 function select(selector, context) {87 if (selector instanceof Selection) return selector;88 if (selector instanceof Element) return wrap([selector]);89 if (Array.isArray(selector)) return wrap(selector);90 if (typeof selector !== 'string') return wrap([]);91 if (selector.trim().charAt(0) === '<') return wrap(new Document(selector).children().toArray());92 return context ? select(context).find(selector) : wrap(document.select(selector).toArray());93 }94 function Selection(elements) {95 this.elements = elements; this.length = elements.length;96 elements.forEach(function(element, index) { this[index] = element; }, this);97 }98 Selection.prototype.each = function(callback) {99 for (var i = 0; i < this.length; i++) if (callback.call(this[i], i, this[i]) === false) break;100 return this;101 };102 Selection.prototype.toArray = function() { return this.elements.slice(); };103 Selection.prototype.get = function(index) { return index == null ? this.toArray() : this.elements[index < 0 ? this.length + index : index]; };104 Selection.prototype.eq = function(index) { var element = this.get(index); return wrap(element ? [element] : []); };105 Selection.prototype.first = function() { return this.eq(0); };106 Selection.prototype.last = function() { return this.eq(-1); };107 Selection.prototype.find = function(selector) {108 var found = [];109 this.each(function(i, element) { element.select(selector).toArray().forEach(function(child) { if (found.indexOf(child) < 0) found.push(child); }); });110 return wrap(found);111 };112 Selection.prototype.children = function(selector) {113 var children = [];114 this.each(function(i, element) { children = children.concat(element.children().toArray()); });115 var result = wrap(children);116 return selector ? result.filter(selector) : result;117 };118 Selection.prototype.next = function() {119 return wrap(this.elements.map(function(element) { return element.nextElementSibling(); }).filter(Boolean));120 };121 Selection.prototype.text = function() { return this.elements.map(function(element) { return String(element.wholeText); }).join(''); };122 Selection.prototype.html = function() { return this.length ? String(this[0].html) : null; };123 Selection.prototype.attr = function(name, value) {124 if (arguments.length === 1) return this.length && this[0].hasAttr(name) ? this[0].attr(name) : undefined;125 return this.each(function(i, element) { element._node.attrs[name] = String(value); });126 };127 Selection.prototype.hasClass = function(name) { return this.elements.some(function(element) { return element.hasClass(name); }); };128 Selection.prototype.removeClass = function(name) {129 return this.each(function(i, element) { element._node.attrs['class'] = element.attr('class').split(/\s+/).filter(function(c) { return c !== name; }).join(' '); });130 };131 Selection.prototype.remove = function() {132 return this.each(function(i, element) { var node = element._node, parent = node.parent; if (parent) parent.children = parent.children.filter(function(child) { return child !== node; }); });133 };134 Selection.prototype.map = function(callback) {135 var result = [];136 this.each(function(i, element) { var value = callback.call(element, i, element); if (value != null) result = result.concat(value); });137 return { get: function() { return result; }, toArray: function() { return result; } };138 };139 Selection.prototype.filter = function(callback) {140 return wrap(this.elements.filter(function(element, index) {141 return typeof callback === 'function' ? callback.call(element, index, element) : document.select(callback).toArray().some(function(other) { return other._node === element._node; });142 }));143 };144 select.html = function() { return String(document.html); };145 select.root = function() { return wrap([document]); };146 return select;147 }148 function lnRequire(name) {149 switch (name) {150 case 'cheerio': return { load: lnLoad };151 case '@libs/fetch': return { fetchApi: lnFetch, fetch: lnFetch, default: lnFetch };152 case '@libs/filterInputs': return { FilterTypes: {153 Picker: 'Picker', TextInput: 'TextInput', Checkbox: 'Checkbox',154 CheckboxGroup: 'CheckboxGroup', ExcludableCheckboxGroup: 'ExcludableCheckboxGroup', Switch: 'Switch'155 }};156 case '@libs/novelStatus': return { NovelStatus: { Ongoing: 'Ongoing', Completed: 'Completed', Hiatus: 'Hiatus', Cancelled: 'Cancelled', Unknown: 'Unknown' } };157 default: throw new Error('Unsupported LNReader module: ' + name);158 }159 }160 var plugin;161""".trimIndent()162