@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class) package eu.friedcutlet.yokan.services.extensions import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import kotlin.js.JsAny import kotlin.js.Promise import kotlin.js.js @OptIn(ExperimentalEncodingApi::class) internal actual suspend fun gzipDecompress(bytes: ByteArray): ByteArray = suspendCancellableCoroutine { continuation -> gzipDecompressJs(Base64.encode(bytes), MaxProtobufDecompressedBytes).then( onFulfilled = { value -> runCatching { Base64.decode(jsString(value)) } .fold(continuation::resume, continuation::resumeWithException) null }, onRejected = { error -> continuation.resumeWithException(IllegalStateException(jsString(error))) null }, ) } private fun gzipDecompressJs(base64: String, maxOutputBytes: Int): Promise = js( """ (async () => { const binary = atob(base64); const input = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) input[i] = binary.charCodeAt(i); const stream = new Blob([input]).stream().pipeThrough(new DecompressionStream('gzip')); const reader = stream.getReader(); const chunks = []; let outputLength = 0; while (true) { const result = await reader.read(); if (result.done) break; outputLength += result.value.byteLength; if (outputLength > maxOutputBytes) { await reader.cancel(); throw new Error('decompressed protobuf exceeds the 64 MiB limit'); } chunks.push(result.value); } const bytes = new Uint8Array(outputLength); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } let result = ''; for (let i = 0; i < bytes.length; i += 0x8000) { result += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); } return btoa(result); })() """, ) private fun jsString(value: JsAny): String = js("String(value)")