package eu.friedcutlet.yokan.services.extensions.js import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbSourcePreference import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.blockingDispatcher import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.extensions.ExtensionLogger import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.runBlockingCompat import kotlinx.coroutines.Job import kotlinx.coroutines.ensureActive import kotlinx.coroutines.job import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlin.concurrent.Volatile import kotlin.coroutines.EmptyCoroutineContext import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull /** * Owns one extension's JavaScript engine and the host side of its `__bridge`. * * The engine boots lazily through [boot]. Every [call] is serialized by a per-host [Mutex] and runs * on [blockingDispatcher], so runtimes may be invoked from the main thread. A failed call closes the * engine so the next call boots a fresh one. Channels shared by every extension flavour (HTTP, log, * preferences, CSS selectors) are answered here, runtime-specific ones by [channels]; unknown * channels fail loudly. */ internal class JavaScriptHost( private val source: DbSource, private val http: HttpService, private val database: YokanDatabase?, private val engineFactory: (JavaScriptMessageBridge) -> JavaScriptEngine, private val boot: (JavaScriptEngine) -> Unit, private val channels: (channel: String, payload: String) -> String? = { _, _ -> null }, ) { private val mutex = Mutex() private var engine: JavaScriptEngine? = null // The job of the call holding [mutex]; QuickJS polls it from its own thread. @Volatile private var callerJob: Job? = null private val sourcePreferenceDefaults by lazy { buildMap { sourcePreferencesFromJson(source.preferenceList).forEach { getOrPut(it.key) { it.value } } } } // Values written while no database is attached; with a database, the settings are the source of truth. private val detachedPreferences = mutableMapOf() suspend fun call(block: (JavaScriptEngine) -> T): T = mutex.withLock { withContext(blockingDispatcher) { callerJob = coroutineContext.job try { val current = engine ?: bootEngine() try { block(current) } catch (error: Throwable) { close() throw error } } catch (error: Throwable) { // A cancelled call fails with the engine's interrupt error; report the cancellation instead. ensureActive() throw error } finally { callerJob = null } } } /** * Blocks a bridge callback on [block] as a child of the current [call], so cancelling the call * cancels it too. Failures are rethrown outside the child so they reach JavaScript without * cancelling the call. */ fun blockingBridgeCall(block: suspend () -> T): T = runBlockingCompat(callerJob ?: EmptyCoroutineContext) { catchingNonCancellation { block() } }.getOrThrow() /** Closes the engine. Must not race [call]; the runtime cache only disposes idle runtimes. */ fun close() { val current = engine ?: return engine = null runCatching { current.close() } } private fun bootEngine(): JavaScriptEngine { check(source.sourceCode.isNotBlank()) { "${source.name} does not contain JavaScript source code." } val created = engineFactory(JavaScriptMessageBridge(::sendMessage)).let { raw -> object : JavaScriptEngine by raw { override fun evaluate(script: String, isCancelled: () -> Boolean): String = raw.evaluate(script) { isCancelled() || callerJob?.isCancelled == true } } } try { boot(created) } catch (error: Throwable) { runCatching { created.close() } throw error } engine = created return created } private fun sendMessage(channel: String, payload: String): String = when (channel) { "http_head", "http_get", "http_post", "http_put", "http_delete", "http_patch" -> { val request = httpRequestFromMessage(channel, payload) // ponytail: QuickJS host functions are synchronous (zipline exposes no promise/job-queue API // to host bindings), so HTTP blocks the engine's background lane until the response arrives. // Non-blocking needs promise-returning host calls plus a job pump in the engine. On wasm // the engine itself is unsupported, so this is never reached there. blockingBridgeCall { http.request(request) }.toJson().toString() } "log" -> { val message = payloadArray(payload).joinToString(" ") { element -> element.primitiveOrNull()?.contentOrNull.orEmpty() } if (message.isNotBlank()) ExtensionLogger.log(source.name, message) "null" } "get", "getString" -> preferenceValue(payload) "setString" -> setPreferenceValue(payload) "querySelector", "querySelectorAll" -> querySelectorBridge(channel, payload) else -> channels(channel, payload) ?: throw UnsupportedOperationException("JavaScript bridge channel '$channel' is not ported yet.") } private fun preferenceValue(payload: String): String { val args = payloadArray(payload) val key = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty() val defaultValue = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty() return storedPreference(key) ?: sourcePreferenceDefaults[key] ?: defaultValue } private fun storedPreference(key: String): String? = if (database == null) { detachedPreferences[key] } else { database.settings().sourcePreferences.orEmpty() .lastOrNull { it.sourceId == source.id && it.key == key } ?.value } private fun setPreferenceValue(payload: String): String { val args = payloadArray(payload) val key = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty() val value = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty() if (key.isBlank()) return value if (database == null) { detachedPreferences[key] = value } else { val settings = database.settings() val others = settings.sourcePreferences.orEmpty().filterNot { it.sourceId == source.id && it.key == key } database.updateSettings( settings.copy(sourcePreferences = others + DbSourcePreference(sourceId = source.id, key = key, value = value)), ) } return value } private fun querySelectorBridge(channel: String, payload: String): String { val args = payloadArray(payload) val html = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty() val selector = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty() if (html.isBlank() || selector.isBlank()) return "[]" val matches = HtmlSelectorMatcher.match(html, selector) return if (channel == "querySelector") { matches.firstOrNull()?.let { JsonPrimitive(it).toString() } ?: "null" } else { buildJsonArray { matches.forEach { add(JsonPrimitive(it)) } }.toString() } } } /** Decodes the `[null, reqcopyWith, url, headers, body]` payload sent by the bootstraps' HTTP clients. */ private fun httpRequestFromMessage(channel: String, payload: String): HttpRequest { val args = payloadArray(payload) val url = args.getOrNull(2)?.primitiveOrNull()?.contentOrNull ?: throw IllegalArgumentException("Missing JavaScript HTTP url") val body = when (val bodyElement = args.getOrNull(4)) { null, JsonNull -> null is JsonPrimitive -> bodyElement.contentOrNull else -> bodyElement.toString() } return HttpRequest( url = url, method = channel.removePrefix("http_").uppercase(), headers = headersFromJsonElement(args.getOrNull(3)), body = body, ) } private fun HttpResponse.toJson(): JsonObject = buildJsonObject { put("body", JsonPrimitive(body)) put("statusCode", JsonPrimitive(statusCode)) put("headers", buildJsonObject { headers.forEach { (key, value) -> put(key, JsonPrimitive(value)) } }) put("isRedirect", JsonPrimitive(statusCode in 300..399)) put("persistentConnection", JsonPrimitive(false)) put("reasonPhrase", JsonPrimitive("")) put("request", buildJsonObject {}) }