bookclerk_plugin_sdk::workerd
Workerd guest bridge — same crate::PluginWorker contract as native.
Audience: authors of runtime = "workerd" plugins (JS modules and optional
Rust→Wasm). Dual-stack with native guests:
- Native:
use bookclerk_plugin_sdk::{PluginRoot, serve}; - Workerd: JS modules import the package; Rust implements ABI dispatch:
import { BookclerkEntrypoint, CliEntrypoint } from "@bookclerk/plugin-sdk/workerd";
import { initSync, cliInvoke } from "./pkg/….js";
import wasmModule from "./pkg/…_bg.wasm";
initSync({ module: wasmModule });
export class Cli extends CliEntrypoint { /* forwards to wasm */ }
export default class EchoPlugin extends BookclerkEntrypoint { /* event(batch) */ }
bookclerk-workerd injects @bookclerk/plugin-sdk/workerd (and the package
root) into the isolate — authors do not vendor a relative filepath. Optional
offline vendors can copy EMBED_BOOKCLERK_PLUGIN_JS_SRC via
bookclerk-plugin sync-embed (crate bookclerk-plugin-tools).
Layout (see examples/plugins-echo-workerd-rust/):
plugin.toml runtime = "workerd"
modules/index.js package import + wasm glue
modules/pkg/*.js + *.wasm wasm-bindgen output (`./build-wasm.sh`)
src/lib.rs ABI-typed `dispatch_json`
| Item | Kind | Summary |
|---|---|---|
DEFAULT_MAIN_MODULE |
constant | Suggested main module filename for JS+Wasm workerd guests. |
DEFAULT_MODULES_DIR |
constant | Suggested modules directory name relative to the plugin root. |
EMBED_BOOKCLERK_PLUGIN_JS |
constant | Filename historically used by optional sync-embed vendors. |
EMBED_BOOKCLERK_PLUGIN_JS_SRC |
constant | Source text of the embeddable workerd runtime helper. |
pub const DEFAULT_MAIN_MODULE: &str = "index.js";
Suggested main module filename for JS+Wasm workerd guests.
Matches the common plugin.toml [workerd] main_module = "index.js" default
and the layout under DEFAULT_MODULES_DIR.
pub const DEFAULT_MODULES_DIR: &str = "modules";
Suggested modules directory name relative to the plugin root.
Matches the plugin.toml [workerd] modules_dir default ("modules").
pub const EMBED_BOOKCLERK_PLUGIN_JS: &str = "bookclerk_plugin.js";
Filename historically used by optional sync-embed vendors.
Prefer importing @bookclerk/plugin-sdk/workerd (injected by
bookclerk-workerd) over shipping this file next to guest modules.
pub const EMBED_BOOKCLERK_PLUGIN_JS_SRC: &str = "/**\n * GENERATED FILE - do not edit. Bundled from `src/workerd.ts` by\n * `scripts/build-embed.mjs` (`npm run build` in packages/plugin-sdk).\n *\n * Workerd runtime for `@bookclerk/plugin-sdk` / `@bookclerk/plugin-sdk/workerd`\n * (@bookclerk/plugin-sdk@0.1.0). `bookclerk-workerd` injects this module into every\n * plugin isolate under those names; authors import the package, never a\n * relative embed path. Native guests use Rust `serve` / `PluginWorker` instead.\n */\n\n// dist/plugin.js\nimport { WorkerEntrypoint, RpcTarget } from \"cloudflare:workers\";\n\n// dist/abi.js\nvar PRODUCT_API_VERSION = 3;\nvar MAX_SCALAR_BYTES = 262144;\nvar MAX_STREAM_WINDOW_BYTES = 1048576;\nvar MAX_LIST_PAGE = 256;\nvar MAX_BATCH_KEYS = 256;\nvar MAX_CHANGES_PAGE = 256;\nvar MAX_CHANGES_CURSOR_BYTES = 4096;\nvar MAX_CHECKPOINT_BYTES = 65536;\nvar MAX_SCAN_PAGE_BOOKS = 500;\nvar MAX_SCAN_CURSOR_BYTES = 4096;\nvar MAX_EVENT_PAYLOAD_BYTES = 65536;\nvar MAX_KV_VALUE_BYTES = 1048576;\nvar MAX_KV_KEY_BYTES = 512;\nvar MAX_SOCKET_FRAME_BYTES = 262144;\nvar MAX_SOCKET_ATTACHMENT_BYTES = 2048;\nvar MAX_ORIGIN_HEADER_BYTES = 65536;\nvar MAX_ORIGIN_TARGET_BYTES = 8192;\nvar MAX_WEBHOOK_PULL_BATCH = 100;\nvar MAX_WEBHOOK_LEASE_ID_BYTES = 128;\nvar MAX_WEBHOOK_VISIBILITY_MS = 432e5;\nvar MAX_WEBHOOK_NAME_BYTES = 32;\nvar MAX_KV_METADATA_BYTES = 1024;\nvar MAX_PLUGIN_MIGRATION_OPS = 256;\nvar MAX_PLUGIN_MIGRATION_TOTAL_OPS = 2048;\nvar MAX_PLUGIN_MIGRATION_REGISTRATION_BYTES = 262144;\nvar FEATURE_SCALAR_LIMITS = \"rpc.scalarLimits\";\nvar FEATURE_STREAMS = \"rpc.streams\";\nvar FEATURE_STORAGE_COPY = \"storage.copy\";\nvar FEATURE_STORAGE_MOVE = \"storage.move\";\nvar FEATURE_STORAGE_MOVE_MANY = \"storage.moveMany\";\nvar FEATURE_STORAGE_DELETE_MANY = \"storage.deleteMany\";\nvar FEATURE_STORAGE_HEAD_MANY = \"storage.headMany\";\nvar FEATURE_STORAGE_CONDITIONAL_WRITE = \"storage.conditionalWrite\";\nvar FEATURE_STORAGE_CHANGES = \"storage.changes\";\nvar OBJECT_CHANGE_KINDS = [\"changed\", \"upserted\", \"removed\"];\nvar PLUGIN_ERROR_CODES = [\"invalid_params\", \"unauthorized\", \"forbidden\", \"not_found\", \"unavailable\", \"unsupported\", \"internal\", \"payload_too_large\", \"deadline_exceeded\", \"invalid_cursor\", \"cancelled\", \"conflict\", \"limit_exceeded\", \"rate_limited\", \"network_not_granted\"];\nvar CLI_ARG_KINDS = [\"string\", \"bool\", \"int\", \"path\"];\nvar WORK_KINDS = [\"unspecified\", \"book\", \"podcast\"];\nvar EXPRESSION_KINDS = [\"unspecified\", \"text\", \"narration\", \"dramatisation\", \"graphic\", \"originalAudio\"];\nvar MEDIA_KINDS = [\"unspecified\", \"audio\", \"ebook\", \"print\"];\nvar IDENTIFIER_SCHEMES = [\"isbn\", \"asin\", \"openLibraryEdition\", \"openLibraryWork\"];\nvar CREDIT_ROLES = [\"author\", \"narrator\", \"translator\", \"editor\", \"illustrator\", \"publisher\", \"host\", \"cast\", \"adaptor\"];\nvar CREDIT_LEVELS = [\"roleDefault\", \"work\", \"expression\", \"edition\"];\nvar FETCHED_FILE_ROLES = [\"unspecified\", \"part\", \"whole\", \"cover\"];\nvar CHAPTER_KINDS = [\"unknown\", \"chapters\", \"tracks\"];\nvar CATALOG_SORTS = [\"relevance\", \"popularity\", \"rating\", \"title\", \"author\"];\nvar CATALOG_FIELDS = [\"any\", \"author\", \"narrator\", \"series\", \"genre\"];\nvar PRICE_LOOKUPS = [\"unspecified\", \"product\", \"isbn\", \"asin\", \"title\"];\nvar ABRIDGEMENTS = [\"unknown\", \"unabridged\", \"abridged\"];\nvar EXPLICITNESSS = [\"unknown\", \"clean\", \"explicit\"];\nvar OFFERED_CODECS = [\"unknown\", \"aac\", \"alac\", \"flac\", \"mp3\", \"opus\", \"vorbis\", \"eac3\", \"ac4\"];\nvar OFFERED_AAC_PROFILES = [\"unknown\", \"lc\", \"he\", \"heV2\", \"xhe\"];\nvar METADATA_FIELDS = [\"title\", \"subtitle\", \"description\", \"publisher\", \"publishedAt\", \"language\", \"genres\", \"tags\", \"abridgement\", \"expressionKind\", \"identifiers\", \"credits\", \"series\", \"chapters\", \"duration\", \"explicitness\"];\nvar NOTIFICATION_SEVERITYS = [\"info\", \"warning\", \"critical\"];\nvar NOTIFICATION_ALERT_ACTIONS = [\"none\", \"trigger\", \"resolve\"];\nvar NOTIFY_DESTINATION_KINDS = [\"channel\", \"personal\"];\nvar AI_TASKS = [\"textEmbeddings\"];\nvar AI_TEXT_ROLES = [\"document\", \"query\"];\nvar DB_TYPES = [\"unspecified\", \"bool\", \"int64\", \"float64\", \"text\", \"bytes\"];\nvar DB_STATEMENT_KINDS = [\"execute\", \"select\", \"returning\"];\nvar DB_RESULT_SELECTIONS = [\"discard\", \"affectedRows\", \"rows\"];\nvar ISOLATION_REQS = [\"atomicBatch\", \"nestedSavepoint\", \"consistentSnapshot\"];\nvar RESOLVED_SQL_TYPES = [\"integer\", \"real\", \"text\", \"blob\", \"boolean\", \"null\"];\nvar INTEGER_ARITH_KINDS = [\"add\", \"sub\", \"mul\", \"abs\"];\n\n// dist/db-capnp.js\nvar WORD = 8;\nvar MAX_TRAVERSAL_WORDS = 64 * 1024;\nvar NO_CAPS = {\n exportCap() {\n throw new Error(\"message carries a capability but no CapTable was provided\");\n },\n importCap(index) {\n if (index === null) {\n return null;\n }\n throw new Error(\"message carries a capability but no CapTable was provided\");\n }\n};\nvar textEncoder = new TextEncoder();\nvar textDecoder = new TextDecoder();\nvar CapnpMessage = class {\n buf;\n view;\n /** Words used in the segment, including the root pointer at word 0. */\n usedWords = 1;\n constructor() {\n this.buf = new Uint8Array(256);\n this.view = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength);\n }\n alloc(nWords) {\n const off = this.usedWords;\n this.usedWords += nWords;\n this.ensure((this.usedWords + 1) * WORD);\n return off;\n }\n initRoot(dataWords, pointerWords) {\n const off = this.alloc(dataWords + pointerWords);\n this.writeStructPointer(0, off, dataWords, pointerWords);\n return new CapnpStruct(this, off, dataWords, pointerWords);\n }\n finish() {\n const segBytes = this.usedWords * WORD;\n const out = new Uint8Array(WORD + segBytes);\n const view = new DataView(out.buffer);\n view.setUint32(0, 0, true);\n view.setUint32(4, this.usedWords, true);\n out.set(this.buf.subarray(0, segBytes), WORD);\n return out;\n }\n writeStructPointer(ptrWord, targetWord, dataWords, pointerWords) {\n const offset = targetWord - (ptrWord + 1);\n const word = 0n | BigInt(offset & 1073741823) << 2n | BigInt(dataWords) << 32n | BigInt(pointerWords) << 48n;\n this.setWord(ptrWord, word);\n }\n writeListPointer(ptrWord, targetWord, elementSize, listLength) {\n const offset = targetWord - (ptrWord + 1);\n const word = 1n | BigInt(offset & 1073741823) << 2n | BigInt(elementSize) << 32n | BigInt(listLength) << 35n;\n this.setWord(ptrWord, word);\n }\n writeCapPointer(ptrWord, index) {\n this.setWord(ptrWord, 3n | BigInt(index) << 32n);\n }\n writeEmptyCompositeList(ptrWord, dataWords, pointerWords) {\n const tagWord = this.alloc(1);\n this.writeListPointer(ptrWord, tagWord, 7, 0);\n const tag = 0n | BigInt(dataWords) << 32n | BigInt(pointerWords) << 48n;\n this.setWord(tagWord, tag);\n }\n initStructList(ptrWord, count, dataWords, pointerWords) {\n if (count === 0) {\n this.writeEmptyCompositeList(ptrWord, dataWords, pointerWords);\n return [];\n }\n const elemWords = dataWords + pointerWords;\n const payloadWords = count * elemWords;\n const tagWord = this.alloc(1 + payloadWords);\n this.writeListPointer(ptrWord, tagWord, 7, payloadWords);\n const tag = 0n | BigInt(count) << 2n | BigInt(dataWords) << 32n | BigInt(pointerWords) << 48n;\n this.setWord(tagWord, tag);\n const out = [];\n for (let i = 0; i < count; i++) {\n out.push(new CapnpStruct(this, tagWord + 1 + i * elemWords, dataWords, pointerWords));\n }\n return out;\n }\n setText(ptrWord, value) {\n const encoded = textEncoder.encode(value);\n const withNul = new Uint8Array(encoded.length + 1);\n withNul.set(encoded, 0);\n this.setByteList(ptrWord, withNul);\n }\n setData(ptrWord, value) {\n this.setByteList(ptrWord, value);\n }\n setByteList(ptrWord, bytes) {\n if (bytes.length === 0) {\n this.writeListPointer(ptrWord, ptrWord + 1, 2, 0);\n return;\n }\n const nWords = Math.ceil(bytes.length / WORD);\n const target = this.alloc(nWords);\n this.buf.set(bytes, target * WORD);\n this.writeListPointer(ptrWord, target, 2, bytes.length);\n }\n /**\n * Allocates a list of `count` pointers.\n *\n * @param ptrWord - Word holding the list pointer.\n * @param count - Number of pointer elements.\n * @returns The word of each element, in order.\n */\n setPointerList(ptrWord, count) {\n if (count === 0) {\n this.writeListPointer(ptrWord, ptrWord + 1, 6, 0);\n return [];\n }\n const target = this.alloc(count);\n this.writeListPointer(ptrWord, target, 6, count);\n const out = [];\n for (let i = 0; i < count; i++) {\n out.push(target + i);\n }\n return out;\n }\n setTextList(ptrWord, values) {\n const words = this.setPointerList(ptrWord, values.length);\n for (let i = 0; i < values.length; i++) {\n this.setText(words[i], values[i]);\n }\n }\n setDataList(ptrWord, values) {\n const words = this.setPointerList(ptrWord, values.length);\n for (let i = 0; i < values.length; i++) {\n this.setData(words[i], values[i]);\n }\n }\n /**\n * Writes a `List(UInt16)` / `List(UInt32)` (element size codes 3 / 4).\n *\n * @param ptrWord - Word holding the list pointer.\n * @param values - Unsigned integers in range for `byteWidth`.\n * @param byteWidth - `2` for UInt16 (enums), `4` for UInt32.\n */\n setUintList(ptrWord, values, byteWidth) {\n const count = values.length;\n const sizeCode = byteWidth === 2 ? 3 : 4;\n if (count === 0) {\n this.writeListPointer(ptrWord, ptrWord + 1, sizeCode, 0);\n return;\n }\n const target = this.alloc(Math.ceil(count * byteWidth / WORD));\n const view = new DataView(this.buf.buffer, this.buf.byteOffset + target * WORD);\n for (let i = 0; i < count; i++) {\n if (byteWidth === 2) {\n view.setUint16(i * 2, values[i], true);\n } else {\n view.setUint32(i * 4, values[i], true);\n }\n }\n this.writeListPointer(ptrWord, target, sizeCode, count);\n }\n setBoolList(ptrWord, values) {\n const count = values.length;\n if (count === 0) {\n this.writeListPointer(ptrWord, ptrWord + 1, 1, 0);\n return;\n }\n const target = this.alloc(Math.ceil(count / 64));\n const base = target * WORD;\n for (let i = 0; i < count; i++) {\n if (values[i]) {\n this.buf[base + (i >> 3)] |= 1 << (i & 7);\n }\n }\n this.writeListPointer(ptrWord, target, 1, count);\n }\n setUint16(word, fieldIndex, value) {\n this.view.setUint16(word * WORD + fieldIndex * 2, value, true);\n }\n setInt32(word, fieldIndex, value) {\n this.view.setInt32(word * WORD + fieldIndex * 4, value | 0, true);\n }\n setUint32(word, fieldIndex, value) {\n this.view.setUint32(word * WORD + fieldIndex * 4, value >>> 0, true);\n }\n setInt64(word, fieldIndex, value) {\n this.view.setBigInt64(word * WORD + fieldIndex * 8, value, true);\n }\n setUint64(word, fieldIndex, value) {\n this.view.setBigUint64(word * WORD + fieldIndex * 8, value, true);\n }\n setFloat32(word, fieldIndex, value) {\n this.view.setFloat32(word * WORD + fieldIndex * 4, value, true);\n }\n setFloat64(word, fieldIndex, value) {\n this.view.setFloat64(word * WORD + fieldIndex * 8, value, true);\n }\n setBool(word, bitIndex, value) {\n const byteOff = word * WORD + (bitIndex >> 3);\n const mask = 1 << (bitIndex & 7);\n if (value) {\n this.buf[byteOff] |= mask;\n } else {\n this.buf[byteOff] &= ~mask;\n }\n }\n setWord(word, value) {\n this.view.setBigUint64(word * WORD, value, true);\n }\n ensure(bytes) {\n if (this.buf.byteLength >= bytes) {\n return;\n }\n let n = this.buf.byteLength;\n while (n < bytes) {\n n *= 2;\n }\n const next = new Uint8Array(n);\n next.set(this.buf);\n this.buf = next;\n this.view = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength);\n }\n};\nvar CapnpStruct = class _CapnpStruct {\n msg;\n word;\n dataWords;\n pointerWords;\n constructor(msg, word, dataWords, pointerWords) {\n this.msg = msg;\n this.word = word;\n this.dataWords = dataWords;\n this.pointerWords = pointerWords;\n }\n pointerWord(index) {\n if (index >= this.pointerWords) {\n throw new Error(\"pointer index outside struct pointer section\");\n }\n return this.word + this.dataWords + index;\n }\n setUint16(fieldIndex, value) {\n this.msg.setUint16(this.word, fieldIndex, value);\n }\n setInt32(fieldIndex, value) {\n this.msg.setInt32(this.word, fieldIndex, value);\n }\n setUint32(fieldIndex, value) {\n this.msg.setUint32(this.word, fieldIndex, value);\n }\n setInt64(fieldIndex, value) {\n this.msg.setInt64(this.word, fieldIndex, value);\n }\n setUint64(fieldIndex, value) {\n this.msg.setUint64(this.word, fieldIndex, value);\n }\n setFloat32(fieldIndex, value) {\n this.msg.setFloat32(this.word, fieldIndex, value);\n }\n setFloat64(fieldIndex, value) {\n this.msg.setFloat64(this.word, fieldIndex, value);\n }\n setBool(bitIndex, value) {\n this.msg.setBool(this.word, bitIndex, value);\n }\n setText(pointerIndex, value) {\n this.msg.setText(this.pointerWord(pointerIndex), value);\n }\n setData(pointerIndex, value) {\n this.msg.setData(this.pointerWord(pointerIndex), value);\n }\n setCap(pointerIndex, index) {\n this.msg.writeCapPointer(this.pointerWord(pointerIndex), index);\n }\n setTextList(pointerIndex, values) {\n this.msg.setTextList(this.pointerWord(pointerIndex), values);\n }\n setDataList(pointerIndex, values) {\n this.msg.setDataList(this.pointerWord(pointerIndex), values);\n }\n setBoolList(pointerIndex, values) {\n this.msg.setBoolList(this.pointerWord(pointerIndex), values);\n }\n setUint16List(pointerIndex, values) {\n this.msg.setUintList(this.pointerWord(pointerIndex), values, 2);\n }\n setUint32List(pointerIndex, values) {\n this.msg.setUintList(this.pointerWord(pointerIndex), values, 4);\n }\n initStructList(pointerIndex, count, dataWords, pointerWords) {\n return this.msg.initStructList(this.pointerWord(pointerIndex), count, dataWords, pointerWords);\n }\n initStruct(pointerIndex, dataWords, pointerWords) {\n const ptrWord = this.pointerWord(pointerIndex);\n const off = this.msg.alloc(dataWords + pointerWords);\n this.msg.writeStructPointer(ptrWord, off, dataWords, pointerWords);\n return new _CapnpStruct(this.msg, off, dataWords, pointerWords);\n }\n};\nvar CapnpReader = class {\n view;\n segOff;\n size0;\n /** Largest segment, pointer list or composite list, in words. */\n maxWords;\n /**\n * Words the reader may still visit. Every struct and list reached is\n * charged its size, so a message whose pointers alias one large value\n * many times over cannot materialize more than the budget, as the Cap\'n\n * Proto traversal limit does.\n */\n remaining;\n /**\n * @param bytes - Unpacked single-segment message.\n * @param maxWords - Traversal budget in words; the default suits control\n * messages, a streamed result frame passes the budget its stream\n * negotiated.\n */\n constructor(bytes, maxWords = MAX_TRAVERSAL_WORDS) {\n this.maxWords = maxWords;\n this.remaining = maxWords;\n if (bytes.byteLength < WORD) {\n throw new Error(\"truncated Cap\'n message\");\n }\n this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const nsegMinus = this.view.getUint32(0, true);\n if (nsegMinus + 1 !== 1) {\n throw new Error(\"multi-segment Cap\'n messages are not supported\");\n }\n const size0 = this.view.getUint32(4, true);\n this.segOff = WORD;\n this.size0 = size0;\n if (this.segOff + size0 * WORD > bytes.byteLength) {\n throw new Error(\"truncated Cap\'n segment\");\n }\n if (size0 > this.maxWords) {\n throw new Error(\"Cap\'n segment exceeds traversal budget\");\n }\n }\n root(dataWords, pointerWords) {\n return this.structAt(0, dataWords, pointerWords);\n }\n structAt(ptrWord, dataWords, pointerWords) {\n void dataWords;\n void pointerWords;\n const word = this.readWord(ptrWord);\n if (word === 0n) {\n return new StructReader(this, 0, 0, 0);\n }\n const a = Number(word & 3n);\n if (a === 2 || a === 3) {\n throw new Error(\"far pointers are not supported\");\n }\n if (a !== 0) {\n throw new Error(\"expected struct pointer\");\n }\n const offset = signExtend30(Number(word >> 2n & 0x3fffffffn));\n const dw = Number(word >> 32n & 0xffffn);\n const pw = Number(word >> 48n & 0xffffn);\n const target = ptrWord + 1 + offset;\n this.visit(target, dw + pw);\n return new StructReader(this, target, dw, pw);\n }\n readWord(word) {\n this.checkRange(word, 1);\n return this.view.getBigUint64(this.segOff + word * WORD, true);\n }\n checkRange(word, nWords) {\n if (word < 0 || nWords < 0 || word + nWords > this.size0) {\n throw new Error(\"Cap\'n pointer out of segment\");\n }\n }\n /**\n * Checks that `nWords` from `word` lie in the segment and charges them to\n * the traversal budget.\n *\n * @param word - First word of the struct or list reached.\n * @param nWords - Its size in words.\n * @throws When the range leaves the segment or exhausts the budget.\n */\n visit(word, nWords) {\n this.checkRange(word, nWords);\n this.charge(nWords);\n }\n /**\n * Charges `nWords` to the traversal budget without a range check, for\n * elements that occupy no words of their own.\n *\n * @param nWords - Words to charge.\n * @throws `Error` when the budget is exhausted.\n */\n charge(nWords) {\n this.remaining -= nWords;\n if (this.remaining < 0) {\n throw new Error(\"Cap\'n message exceeds traversal budget\");\n }\n }\n listPointer(ptrWord, expectSize) {\n const word = this.readWord(ptrWord);\n if (word === 0n) {\n return null;\n }\n const a = Number(word & 3n);\n if (a === 2 || a === 3) {\n throw new Error(\"far pointers are not supported\");\n }\n if (a !== 1) {\n throw new Error(\"expected list pointer\");\n }\n const offset = signExtend30(Number(word >> 2n & 0x3fffffffn));\n const c = Number(word >> 32n & 7n);\n const d = Number(word >> 35n);\n if (c !== expectSize) {\n throw new Error(`expected list element size ${expectSize}, found ${c}`);\n }\n return { target: ptrWord + 1 + offset, length: d };\n }\n getUint16(word, fieldIndex) {\n return this.view.getUint16(this.segOff + word * WORD + fieldIndex * 2, true);\n }\n getInt32(word, fieldIndex) {\n return this.view.getInt32(this.segOff + word * WORD + fieldIndex * 4, true);\n }\n getUint32(word, fieldIndex) {\n return this.view.getUint32(this.segOff + word * WORD + fieldIndex * 4, true);\n }\n getInt64(word, fieldIndex) {\n return this.view.getBigInt64(this.segOff + word * WORD + fieldIndex * 8, true);\n }\n getUint64(word, fieldIndex) {\n return this.view.getBigUint64(this.segOff + word * WORD + fieldIndex * 8, true);\n }\n getFloat32(word, fieldIndex) {\n return this.view.getFloat32(this.segOff + word * WORD + fieldIndex * 4, true);\n }\n getFloat64(word, fieldIndex) {\n return this.view.getFloat64(this.segOff + word * WORD + fieldIndex * 8, true);\n }\n getBool(word, bitIndex) {\n const byteOff = this.segOff + word * WORD + (bitIndex >> 3);\n return (this.view.getUint8(byteOff) & 1 << (bitIndex & 7)) !== 0;\n }\n readByteList(ptrWord) {\n const lp = this.listPointer(ptrWord, 2);\n if (lp === null) {\n return new Uint8Array(0);\n }\n const nWords = lp.length === 0 ? 0 : Math.ceil(lp.length / WORD);\n this.visit(lp.target, nWords);\n const start = this.segOff + lp.target * WORD;\n if (start + lp.length > this.view.byteLength) {\n throw new Error(\"truncated Cap\'n byte list\");\n }\n return new Uint8Array(this.view.buffer, this.view.byteOffset + start, lp.length);\n }\n readText(ptrWord) {\n const bytes = this.readByteList(ptrWord);\n const end = bytes.length > 0 && bytes[bytes.length - 1] === 0 ? bytes.length - 1 : bytes.length;\n return textDecoder.decode(bytes.subarray(0, end));\n }\n readCapIndex(ptrWord) {\n const word = this.readWord(ptrWord);\n if (word === 0n) {\n return null;\n }\n if ((word & 3n) !== 3n) {\n throw new Error(\"expected capability pointer\");\n }\n return Number(word >> 32n);\n }\n pointerList(ptrWord) {\n const lp = this.listPointer(ptrWord, 6);\n if (lp === null || lp.length === 0) {\n return [];\n }\n if (lp.length > this.maxWords) {\n throw new Error(\"pointer list exceeds traversal budget\");\n }\n this.visit(lp.target, lp.length);\n const out = [];\n for (let i = 0; i < lp.length; i++) {\n out.push(lp.target + i);\n }\n return out;\n }\n readTextList(ptrWord) {\n return this.pointerList(ptrWord).map((w) => this.readText(w));\n }\n readDataList(ptrWord) {\n return this.pointerList(ptrWord).map((w) => this.readByteList(w));\n }\n /**\n * Reads a `List(UInt16)` / `List(UInt32)`.\n *\n * @param ptrWord - Word holding the list pointer.\n * @param byteWidth - `2` for UInt16 (enums), `4` for UInt32.\n * @returns Decoded unsigned integers.\n */\n readUintList(ptrWord, byteWidth) {\n const lp = this.listPointer(ptrWord, byteWidth === 2 ? 3 : 4);\n if (lp === null || lp.length === 0) {\n return [];\n }\n this.visit(lp.target, Math.ceil(lp.length * byteWidth / WORD));\n const base = this.segOff + lp.target * WORD;\n const out = [];\n for (let i = 0; i < lp.length; i++) {\n out.push(byteWidth === 2 ? this.view.getUint16(base + i * 2, true) : this.view.getUint32(base + i * 4, true));\n }\n return out;\n }\n readBoolList(ptrWord) {\n const lp = this.listPointer(ptrWord, 1);\n if (lp === null || lp.length === 0) {\n return [];\n }\n this.visit(lp.target, Math.ceil(lp.length / 64));\n const base = this.segOff + lp.target * WORD;\n const out = [];\n for (let i = 0; i < lp.length; i++) {\n out.push((this.view.getUint8(base + (i >> 3)) >> (i & 7) & 1) === 1);\n }\n return out;\n }\n readStructList(ptrWord, dataWords, pointerWords) {\n void dataWords;\n void pointerWords;\n const lp = this.listPointer(ptrWord, 7);\n if (lp === null) {\n return [];\n }\n const { tagWord, count, dw, pw } = this.compositeTag(lp);\n const elemWords = dw + pw;\n this.checkRange(tagWord, 1 + count * elemWords);\n this.charge(1 + Math.max(count * elemWords, count));\n const out = [];\n for (let i = 0; i < count; i++) {\n out.push(new StructReader(this, tagWord + 1 + i * elemWords, dw, pw));\n }\n return out;\n }\n /**\n * Element count of a composite list without visiting its elements, so a\n * caller can refuse a list that is too long before any element decodes.\n *\n * @param ptrWord - Word holding the list pointer.\n * @returns The number of elements the list\'s tag announces, `0` for a\n * null or empty list.\n * @throws `Error` when the pointer is not a composite list pointer or the\n * count exceeds the list\'s payload.\n */\n readStructListLength(ptrWord) {\n const lp = this.listPointer(ptrWord, 7);\n if (lp === null) {\n return 0;\n }\n return this.compositeTag(lp).count;\n }\n /**\n * The tag word of a composite list: its element count and element shape.\n *\n * A composite list of zero words still carries its tag (zero-width\n * elements, or no elements), so the tag is read whenever the pointer is\n * not null.\n *\n * @param lp - A composite (element size 7) list pointer.\n * @returns The tag\'s word, element count, data words and pointer words.\n * @throws `Error` when the count exceeds the list\'s payload or the\n * traversal budget.\n */\n compositeTag(lp) {\n const tagWord = lp.target;\n this.checkRange(tagWord, 1);\n const tag = this.readWord(tagWord);\n const count = Number(tag >> 2n & 0x3fffffffn);\n const dw = Number(tag >> 32n & 0xffffn);\n const pw = Number(tag >> 48n & 0xffffn);\n const elemWords = dw + pw;\n if (elemWords > 0 && count > Math.floor(lp.length / elemWords)) {\n throw new Error(\"composite list count exceeds payload\");\n }\n if (count > this.maxWords) {\n throw new Error(\"composite list count exceeds traversal budget\");\n }\n return { tagWord, count, dw, pw };\n }\n};\nfunction signExtend30(n) {\n const v = n & 1073741823;\n return v & 536870912 ? v - 1073741824 : v;\n}\nvar StructReader = class _StructReader {\n reader;\n word;\n dataWords;\n pointerWords;\n constructor(reader, word, dataWords, pointerWords) {\n this.reader = reader;\n this.word = word;\n this.dataWords = dataWords;\n this.pointerWords = pointerWords;\n }\n hasData(fieldIndex, size) {\n return (fieldIndex + 1) * size <= this.dataWords * WORD;\n }\n pointerWord(index) {\n if (index >= this.pointerWords) {\n return null;\n }\n return this.word + this.dataWords + index;\n }\n getUint16(fieldIndex) {\n return this.hasData(fieldIndex, 2) ? this.reader.getUint16(this.word, fieldIndex) : 0;\n }\n getInt32(fieldIndex) {\n return this.hasData(fieldIndex, 4) ? this.reader.getInt32(this.word, fieldIndex) : 0;\n }\n getUint32(fieldIndex) {\n return this.hasData(fieldIndex, 4) ? this.reader.getUint32(this.word, fieldIndex) : 0;\n }\n getInt64(fieldIndex) {\n return this.hasData(fieldIndex, 8) ? this.reader.getInt64(this.word, fieldIndex) : 0n;\n }\n getUint64(fieldIndex) {\n return this.hasData(fieldIndex, 8) ? this.reader.getUint64(this.word, fieldIndex) : 0n;\n }\n getFloat32(fieldIndex) {\n return this.hasData(fieldIndex, 4) ? this.reader.getFloat32(this.word, fieldIndex) : 0;\n }\n getFloat64(fieldIndex) {\n return this.hasData(fieldIndex, 8) ? this.reader.getFloat64(this.word, fieldIndex) : 0;\n }\n getBool(bitIndex) {\n if (bitIndex >= this.dataWords * 64) {\n return false;\n }\n return this.reader.getBool(this.word, bitIndex);\n }\n getText(pointerIndex) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? \"\" : this.reader.readText(ptr);\n }\n getData(pointerIndex) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? new Uint8Array(0) : this.reader.readByteList(ptr);\n }\n getCapIndex(pointerIndex) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? null : this.reader.readCapIndex(ptr);\n }\n getTextList(pointerIndex) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? [] : this.reader.readTextList(ptr);\n }\n getDataList(pointerIndex) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? [] : this.reader.readDataList(ptr);\n }\n getBoolList(pointerIndex) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? [] : this.reader.readBoolList(ptr);\n }\n getUint16List(pointerIndex) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? [] : this.reader.readUintList(ptr, 2);\n }\n getUint32List(pointerIndex) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? [] : this.reader.readUintList(ptr, 4);\n }\n getStructList(pointerIndex, dataWords, pointerWords) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? [] : this.reader.readStructList(ptr, dataWords, pointerWords);\n }\n /**\n * Element count of the composite list at `pointerIndex`, read from its tag\n * alone (see {@link CapnpReader.readStructListLength}).\n *\n * @param pointerIndex - Pointer field index.\n * @returns The announced element count, `0` for a null or empty list.\n */\n getStructListLength(pointerIndex) {\n const ptr = this.pointerWord(pointerIndex);\n return ptr === null ? 0 : this.reader.readStructListLength(ptr);\n }\n getStruct(pointerIndex, dataWords, pointerWords) {\n const ptr = this.pointerWord(pointerIndex);\n if (ptr === null) {\n return new _StructReader(this.reader, 0, 0, 0);\n }\n return this.reader.structAt(ptr, dataWords, pointerWords);\n }\n};\n\n// dist/errors.js\nvar KNOWN_ERROR_CODES = new Set(PLUGIN_ERROR_CODES);\nvar MAX_DETAILS_BYTES = MAX_SCALAR_BYTES;\nvar LIMIT_NAME = /^[A-Za-z0-9_]+$/;\nvar UTF8 = new TextEncoder();\nfunction isCount(n) {\n return typeof n === \"number\" && Number.isSafeInteger(n) && n >= 0;\n}\nvar LIMIT_MESSAGE_PREFIX = \"limit exceeded: \";\nfunction limitExceededMessage(limit) {\n return `${LIMIT_MESSAGE_PREFIX}${limit.limit} is ${limit.cap}; used ${limit.used}`;\n}\nfunction parseLimitExceeded(message) {\n const start = message.indexOf(LIMIT_MESSAGE_PREFIX);\n if (start < 0)\n return void 0;\n const match = /^([A-Za-z0-9_]+) is (\\d+); used (\\d+)/.exec(message.slice(start + LIMIT_MESSAGE_PREFIX.length));\n if (!match)\n return void 0;\n const cap = Number(match[2]);\n const used = Number(match[3]);\n if (!Number.isSafeInteger(cap) || !Number.isSafeInteger(used))\n return void 0;\n return { limit: match[1] ?? \"\", cap, used };\n}\nfunction limitFromDetails(details) {\n const { limit, cap, used } = details;\n if (typeof limit !== \"string\" || !LIMIT_NAME.test(limit) || !isCount(cap) || !isCount(used)) {\n return void 0;\n }\n return { limit, cap, used };\n}\nfunction parseDetails(text) {\n if (text === \"\" || UTF8.encode(text).byteLength > MAX_DETAILS_BYTES)\n return void 0;\n try {\n const parsed = JSON.parse(text);\n if (parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return Object.freeze({ ...parsed });\n }\n } catch {\n }\n return void 0;\n}\nvar PluginError = class _PluginError extends Error {\n /** Known `PluginErrorCode` wire string, or `unknown`. */\n code;\n /** Raw wire code, including codes this SDK does not know. */\n wireCode;\n /** Structured detail object from the wire (`details` JSON), when the error carries one. */\n details;\n /**\n * @param code - Wire error code.\n * @param message - Operator-facing error text.\n * @param details - Detail object, or its JSON text as carried on the wire.\n */\n constructor(code, message, details) {\n super(message);\n this.name = \"PluginError\";\n this.wireCode = code;\n this.code = KNOWN_ERROR_CODES.has(code) ? code : \"unknown\";\n this.details = typeof details === \"string\" ? parseDetails(details) : details === void 0 ? void 0 : Object.freeze({ ...details });\n }\n /**\n * Construct a {@link PluginError} from a Cap\'n Proto / JSON wire code.\n *\n * Unknown codes become `unknown` on {@link PluginError.code} while\n * {@link PluginError.wireCode} keeps the raw value.\n *\n * @param code - Wire error code (known or unknown).\n * @param message - Operator-facing error text.\n * @param details - `details` JSON text from the wire (empty when none).\n * @returns Typed plugin error.\n */\n static fromWire(code, message, details = \"\") {\n return new _PluginError(code, message, details);\n }\n /**\n * Builds a `limit_exceeded` error whose message and `details` both carry\n * the exceeded cap.\n *\n * @param limit - Exceeded cap.\n * @returns Typed plugin error.\n */\n static limitExceeded(limit) {\n return new _PluginError(\"limit_exceeded\", limitExceededMessage(limit), { ...limit });\n }\n /**\n * The exceeded cap when this is a `limit_exceeded` error.\n *\n * @returns The cap from `details` first, then from the canonical message;\n * `undefined` for every other code.\n */\n get limit() {\n if (this.wireCode !== \"limit_exceeded\")\n return void 0;\n return (this.details && limitFromDetails(this.details)) ?? parseLimitExceeded(this.message);\n }\n /**\n * `details` as the JSON text the wire carries.\n *\n * @returns JSON object text, or an empty string when the error has none.\n */\n get detailsText() {\n if (this.details === void 0)\n return \"\";\n try {\n return JSON.stringify(this.details) ?? \"\";\n } catch {\n return \"\";\n }\n }\n};\n\n// dist/generated-wire.js\nfunction encodeMessage(codec, value, caps = NO_CAPS) {\n const msg = new CapnpMessage();\n codec.write(msg.initRoot(codec.dataWords, codec.pointerCount), value, caps);\n return msg.finish();\n}\nfunction decodeMessage(codec, bytes, caps = NO_CAPS) {\n return codec.read(new CapnpReader(bytes).root(codec.dataWords, codec.pointerCount), caps);\n}\nfunction ord(table, name, enumName) {\n const i = table.indexOf(name);\n if (i < 0) {\n throw new Error(`unknown ${enumName} value: ${name}`);\n }\n return i;\n}\nfunction fromOrd(table, ordinal, enumName) {\n const v = table[ordinal];\n if (v === void 0) {\n throw new Error(`unknown ${enumName} ordinal: ${ordinal}`);\n }\n return v;\n}\nfunction fromOrdOr(table, ordinal, fallback) {\n return table[ordinal] ?? fallback;\n}\nfunction unknownUnion(struct, member) {\n return new Error(`unknown ${struct} union member: ${String(member)}`);\n}\nvar EMPTY_BYTES = new Uint8Array(0);\nvar PluginErrorCodec = {\n dataWords: 0,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.code ?? \"\");\n s.setText(1, v.message ?? \"\");\n s.setText(2, v.details ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n code: s.getText(0),\n message: s.getText(1),\n details: s.getText(2)\n };\n }\n};\nvar ObjectMetadataCodec = {\n dataWords: 2,\n pointerCount: 6,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.key ?? \"\");\n s.setUint64(0, BigInt(v.size ?? 0));\n s.setText(1, v.contentType ?? \"\");\n s.setText(2, v.etag ?? \"\");\n s.setData(3, v.sha256 ?? EMPTY_BYTES);\n s.setUint64(1, BigInt(v.modifiedAtMs ?? 0));\n s.setText(4, v.versionId ?? \"\");\n s.setText(5, v.signature ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n key: s.getText(0),\n size: Number(s.getUint64(0)),\n contentType: s.getText(1),\n etag: s.getText(2),\n sha256: s.getData(3),\n modifiedAtMs: Number(s.getUint64(1)),\n versionId: s.getText(4),\n signature: s.getText(5)\n };\n }\n};\nvar ObjectInfoCodec = {\n dataWords: 2,\n pointerCount: 4,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.key ?? \"\");\n s.setUint64(0, BigInt(v.size ?? 0));\n s.setText(1, v.etag ?? \"\");\n s.setUint64(1, BigInt(v.modifiedAtMs ?? 0));\n s.setText(2, v.versionId ?? \"\");\n s.setText(3, v.signature ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n key: s.getText(0),\n size: Number(s.getUint64(0)),\n etag: s.getText(1),\n modifiedAtMs: Number(s.getUint64(1)),\n versionId: s.getText(2),\n signature: s.getText(3)\n };\n }\n};\nvar ListOptionsCodec = {\n dataWords: 2,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.prefix ?? \"\");\n s.setText(1, v.cursor ?? \"\");\n s.setUint32(0, v.limit ?? 0);\n s.setBool(32, v.withSignatures ?? false);\n s.setUint64(1, BigInt(v.modifiedSinceMs ?? 0));\n },\n read(s, caps) {\n void caps;\n return {\n prefix: s.getText(0),\n cursor: s.getText(1),\n limit: s.getUint32(0),\n withSignatures: s.getBool(32),\n modifiedSinceMs: Number(s.getUint64(1))\n };\n }\n};\nvar ListPageCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n {\n const list = v.objects ?? [];\n const items = s.initStructList(0, list.length, 2, 4);\n for (let i = 0; i < items.length; i++) {\n ObjectInfoCodec.write(items[i], list[i], caps);\n }\n }\n s.setText(1, v.nextCursor ?? \"\");\n s.setBool(0, v.signaturesIncluded ?? false);\n s.setBool(1, v.modifiedSinceApplied ?? false);\n },\n read(s, caps) {\n return {\n objects: s.getStructList(0, 2, 4).map((item) => ObjectInfoCodec.read(item, caps)),\n nextCursor: s.getText(1),\n signaturesIncluded: s.getBool(0),\n modifiedSinceApplied: s.getBool(1)\n };\n }\n};\nvar PutResultCodec = {\n dataWords: 2,\n pointerCount: 5,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.key ?? \"\");\n s.setUint64(0, BigInt(v.bytesWritten ?? 0));\n s.setText(1, v.etag ?? \"\");\n s.setData(2, v.sha256 ?? EMPTY_BYTES);\n s.setUint64(1, BigInt(v.modifiedAtMs ?? 0));\n s.setText(3, v.versionId ?? \"\");\n s.setText(4, v.signature ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n key: s.getText(0),\n bytesWritten: Number(s.getUint64(0)),\n etag: s.getText(1),\n sha256: s.getData(2),\n modifiedAtMs: Number(s.getUint64(1)),\n versionId: s.getText(3),\n signature: s.getText(4)\n };\n }\n};\nvar CopyResultCodec = {\n dataWords: 1,\n pointerCount: 0,\n write(s, v, caps) {\n void caps;\n s.setUint64(0, BigInt(v.bytesCopied ?? 0));\n },\n read(s, caps) {\n void caps;\n return {\n bytesCopied: Number(s.getUint64(0))\n };\n }\n};\nvar MoveOptionsCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setBool(0, v.noOverwrite ?? false);\n s.setText(0, v.ifSourceMatch ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n noOverwrite: s.getBool(0),\n ifSourceMatch: s.getText(0)\n };\n }\n};\nvar MoveResultCodec = {\n dataWords: 1,\n pointerCount: 0,\n write(s, v, caps) {\n void caps;\n s.setBool(0, v.atomic ?? false);\n s.setBool(1, v.alreadyMoved ?? false);\n },\n read(s, caps) {\n void caps;\n return {\n atomic: s.getBool(0),\n alreadyMoved: s.getBool(1)\n };\n }\n};\nvar KeyPairCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.from ?? \"\");\n s.setText(1, v.to ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n from: s.getText(0),\n to: s.getText(1)\n };\n }\n};\nvar MoveManyTargetCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"pairs\":\n s.setUint16(0, 0);\n {\n const list = v.value ?? [];\n const items = s.initStructList(0, list.length, 0, 2);\n for (let i = 0; i < items.length; i++) {\n KeyPairCodec.write(items[i], list[i], caps);\n }\n }\n break;\n case \"prefix\":\n s.setUint16(0, 1);\n if (v.value != null) {\n KeyPairCodec.write(s.initStruct(0, 0, 2), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"MoveManyTarget\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"pairs\", value: s.getStructList(0, 0, 2).map((item) => KeyPairCodec.read(item, caps)) };\n case 1:\n return { kind: \"prefix\", value: KeyPairCodec.read(s.getStruct(0, 0, 2), caps) };\n default:\n throw unknownUnion(\"MoveManyTarget\", disc);\n }\n }\n};\nvar MoveManyRequestCodec = {\n dataWords: 1,\n pointerCount: 3,\n write(s, v, caps) {\n if (v.target != null) {\n MoveManyTargetCodec.write(s.initStruct(0, 1, 1), v.target, caps);\n }\n s.setText(1, v.cursor ?? \"\");\n s.setUint32(0, v.limit ?? 0);\n if (v.options != null) {\n MoveOptionsCodec.write(s.initStruct(2, 1, 1), v.options, caps);\n }\n },\n read(s, caps) {\n return {\n target: MoveManyTargetCodec.read(s.getStruct(0, 1, 1), caps),\n cursor: s.getText(1),\n limit: s.getUint32(0),\n options: MoveOptionsCodec.read(s.getStruct(2, 1, 1), caps)\n };\n }\n};\nvar KeyOutcomeCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n s.setText(0, v.key ?? \"\");\n if (v.error != null) {\n PluginErrorCodec.write(s.initStruct(1, 0, 3), v.error, caps);\n }\n },\n read(s, caps) {\n return {\n key: s.getText(0),\n error: PluginErrorCodec.read(s.getStruct(1, 0, 3), caps)\n };\n }\n};\nvar MoveManyPageCodec = {\n dataWords: 2,\n pointerCount: 2,\n write(s, v, caps) {\n {\n const list = v.results ?? [];\n const items = s.initStructList(0, list.length, 0, 2);\n for (let i = 0; i < items.length; i++) {\n KeyOutcomeCodec.write(items[i], list[i], caps);\n }\n }\n s.setText(1, v.nextCursor ?? \"\");\n s.setBool(0, v.atomic ?? false);\n s.setUint64(1, BigInt(v.objectsMoved ?? 0));\n },\n read(s, caps) {\n return {\n results: s.getStructList(0, 0, 2).map((item) => KeyOutcomeCodec.read(item, caps)),\n nextCursor: s.getText(1),\n atomic: s.getBool(0),\n objectsMoved: Number(s.getUint64(1))\n };\n }\n};\nvar DeleteManyResultCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.results ?? [];\n const items = s.initStructList(0, list.length, 0, 2);\n for (let i = 0; i < items.length; i++) {\n KeyOutcomeCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n results: s.getStructList(0, 0, 2).map((item) => KeyOutcomeCodec.read(item, caps))\n };\n }\n};\nvar HeadManyResultCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.objects ?? [];\n const items = s.initStructList(0, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n HeadOkCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n objects: s.getStructList(0, 1, 1).map((item) => HeadOkCodec.read(item, caps))\n };\n }\n};\nvar TranslateKeysResultCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setTextList(0, v.keys ?? []);\n },\n read(s, caps) {\n void caps;\n return {\n keys: s.getTextList(0)\n };\n }\n};\nvar ChangesRequestCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.cursor ?? \"\");\n s.setUint32(0, v.limit ?? 0);\n },\n read(s, caps) {\n void caps;\n return {\n cursor: s.getText(0),\n limit: s.getUint32(0)\n };\n }\n};\nvar ObjectChangeCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n s.setText(0, v.key ?? \"\");\n s.setUint16(0, ord(OBJECT_CHANGE_KINDS, v.kind ?? OBJECT_CHANGE_KINDS[0], \"ObjectChangeKind\"));\n if (v.info != null) {\n ObjectInfoCodec.write(s.initStruct(1, 2, 4), v.info, caps);\n }\n },\n read(s, caps) {\n return {\n key: s.getText(0),\n kind: fromOrdOr(OBJECT_CHANGE_KINDS, s.getUint16(0), \"changed\"),\n info: ObjectInfoCodec.read(s.getStruct(1, 2, 4), caps)\n };\n }\n};\nvar ChangesPageCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n {\n const list = v.changes ?? [];\n const items = s.initStructList(0, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n ObjectChangeCodec.write(items[i], list[i], caps);\n }\n }\n s.setText(1, v.cursor ?? \"\");\n s.setBool(0, v.more ?? false);\n s.setBool(1, v.complete ?? false);\n s.setBool(2, v.liveWatch ?? false);\n },\n read(s, caps) {\n return {\n changes: s.getStructList(0, 1, 2).map((item) => ObjectChangeCodec.read(item, caps)),\n cursor: s.getText(1),\n more: s.getBool(0),\n complete: s.getBool(1),\n liveWatch: s.getBool(2)\n };\n }\n};\nvar OidcClientTemplateCodec = {\n dataWords: 1,\n pointerCount: 5,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.clientId ?? \"\");\n s.setText(1, v.displayName ?? \"\");\n s.setText(2, v.callbackPath ?? \"\");\n s.setBool(0, v.publicClient ?? false);\n s.setTextList(3, v.defaultScopes ?? []);\n s.setBool(1, v.issueRefreshToken ?? false);\n s.setText(4, v.originConfigKey ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n clientId: s.getText(0),\n displayName: s.getText(1),\n callbackPath: s.getText(2),\n publicClient: s.getBool(0),\n defaultScopes: s.getTextList(3),\n issueRefreshToken: s.getBool(1),\n originConfigKey: s.getText(4)\n };\n }\n};\nvar OidcClientsOkCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.clients ?? [];\n const items = s.initStructList(0, list.length, 1, 5);\n for (let i = 0; i < items.length; i++) {\n OidcClientTemplateCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n clients: s.getStructList(0, 1, 5).map((item) => OidcClientTemplateCodec.read(item, caps))\n };\n }\n};\nvar OidcClientsReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n OidcClientsOkCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"OidcClientsReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: OidcClientsOkCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"OidcClientsReply\", disc);\n }\n }\n};\nvar ExtensibleConfigCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setUint32(0, v.schemaVersion ?? 0);\n s.setText(0, v.mediaType ?? \"\");\n s.setData(1, v.payload ?? EMPTY_BYTES);\n },\n read(s, caps) {\n void caps;\n return {\n schemaVersion: s.getUint32(0),\n mediaType: s.getText(0),\n payload: s.getData(1)\n };\n }\n};\nvar JobInvocationCodec = {\n dataWords: 3,\n pointerCount: 8,\n write(s, v, caps) {\n void caps;\n s.setUint32(0, v.payloadSchemaVersion ?? 0);\n s.setText(0, v.invocationId ?? \"\");\n s.setText(1, v.commandType ?? \"\");\n s.setText(2, v.payloadJson ?? \"\");\n s.setText(3, v.idempotencyKey ?? \"\");\n s.setUint32(1, v.attempt ?? 0);\n s.setText(4, v.correlationId ?? \"\");\n s.setText(5, v.causationId ?? \"\");\n s.setUint64(1, BigInt(v.deadlineUnixMs ?? 0));\n s.setText(6, v.checkpointJson ?? \"\");\n s.setUint32(4, v.checkpointSchemaVersion ?? 0);\n s.setUint32(5, v.invocationSequence ?? 0);\n s.setText(7, v.stepId ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n payloadSchemaVersion: s.getUint32(0),\n invocationId: s.getText(0),\n commandType: s.getText(1),\n payloadJson: s.getText(2),\n idempotencyKey: s.getText(3),\n attempt: s.getUint32(1),\n correlationId: s.getText(4),\n causationId: s.getText(5),\n deadlineUnixMs: Number(s.getUint64(1)),\n checkpointJson: s.getText(6),\n checkpointSchemaVersion: s.getUint32(4),\n invocationSequence: s.getUint32(5),\n stepId: s.getText(7)\n };\n }\n};\nvar CompletedOutcomeCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.message ?? \"\");\n s.setUint64(0, BigInt(v.bytesCopied ?? 0));\n },\n read(s, caps) {\n void caps;\n return {\n message: s.getText(0),\n bytesCopied: Number(s.getUint64(0))\n };\n }\n};\nvar RetryableOutcomeCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.message ?? \"\");\n s.setUint64(0, BigInt(v.retryAfterUnixMs ?? 0));\n },\n read(s, caps) {\n void caps;\n return {\n message: s.getText(0),\n retryAfterUnixMs: Number(s.getUint64(0))\n };\n }\n};\nvar RejectedOutcomeCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.message ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n message: s.getText(0)\n };\n }\n};\nvar CancelledOutcomeCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.message ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n message: s.getText(0)\n };\n }\n};\nvar SuspendedOutcomeCodec = {\n dataWords: 2,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.checkpointJson ?? \"\");\n s.setUint32(0, v.checkpointSchemaVersion ?? 0);\n s.setUint64(1, BigInt(v.wakeAtUnixMs ?? 0));\n },\n read(s, caps) {\n void caps;\n return {\n checkpointJson: s.getText(0),\n checkpointSchemaVersion: s.getUint32(0),\n wakeAtUnixMs: Number(s.getUint64(1))\n };\n }\n};\nvar JobOutcomeCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"completed\":\n s.setUint16(0, 0);\n if (v.value != null) {\n CompletedOutcomeCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n case \"retryable\":\n s.setUint16(0, 1);\n if (v.value != null) {\n RetryableOutcomeCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n case \"rejected\":\n s.setUint16(0, 2);\n if (v.value != null) {\n RejectedOutcomeCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"cancelled\":\n s.setUint16(0, 3);\n if (v.value != null) {\n CancelledOutcomeCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"suspended\":\n s.setUint16(0, 4);\n if (v.value != null) {\n SuspendedOutcomeCodec.write(s.initStruct(0, 2, 1), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"JobOutcome\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"completed\", value: CompletedOutcomeCodec.read(s.getStruct(0, 1, 1), caps) };\n case 1:\n return { kind: \"retryable\", value: RetryableOutcomeCodec.read(s.getStruct(0, 1, 1), caps) };\n case 2:\n return { kind: \"rejected\", value: RejectedOutcomeCodec.read(s.getStruct(0, 0, 1), caps) };\n case 3:\n return { kind: \"cancelled\", value: CancelledOutcomeCodec.read(s.getStruct(0, 0, 1), caps) };\n case 4:\n return { kind: \"suspended\", value: SuspendedOutcomeCodec.read(s.getStruct(0, 2, 1), caps) };\n default:\n throw unknownUnion(\"JobOutcome\", disc);\n }\n }\n};\nvar DomainEventCodec = {\n dataWords: 4,\n pointerCount: 9,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.eventId ?? \"\");\n s.setText(1, v.eventType ?? \"\");\n s.setUint32(0, v.schemaVersion ?? 0);\n s.setUint64(1, BigInt(v.occurredAtUnixMs ?? 0));\n s.setText(2, v.accountId ?? \"\");\n s.setText(3, v.correlationId ?? \"\");\n s.setText(4, v.causationId ?? \"\");\n s.setText(5, v.deduplicationKey ?? \"\");\n s.setUint32(1, v.deliveryAttempt ?? 0);\n s.setData(6, v.payload ?? EMPTY_BYTES);\n s.setText(7, v.checkpointJson ?? \"\");\n s.setUint32(4, v.checkpointSchemaVersion ?? 0);\n s.setUint32(5, v.invocationSequence ?? 0);\n s.setBool(192, v.resumePending ?? false);\n s.setText(8, v.source ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n eventId: s.getText(0),\n eventType: s.getText(1),\n schemaVersion: s.getUint32(0),\n occurredAtUnixMs: Number(s.getUint64(1)),\n accountId: s.getText(2),\n correlationId: s.getText(3),\n causationId: s.getText(4),\n deduplicationKey: s.getText(5),\n deliveryAttempt: s.getUint32(1),\n payload: s.getData(6),\n checkpointJson: s.getText(7),\n checkpointSchemaVersion: s.getUint32(4),\n invocationSequence: s.getUint32(5),\n resumePending: s.getBool(192),\n source: s.getText(8)\n };\n }\n};\nvar EventAckCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n return {\n dummy: void 0\n };\n }\n};\nvar EventRetryCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setUint64(0, BigInt(v.retryAtUnixMs ?? 0));\n s.setText(0, v.reason ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n retryAtUnixMs: Number(s.getUint64(0)),\n reason: s.getText(0)\n };\n }\n};\nvar EventRejectCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.reason ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n reason: s.getText(0)\n };\n }\n};\nvar EventDeadLetterCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.reason ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n reason: s.getText(0)\n };\n }\n};\nvar EventSuspendedCodec = {\n dataWords: 2,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.checkpointJson ?? \"\");\n s.setUint32(0, v.checkpointSchemaVersion ?? 0);\n s.setUint64(1, BigInt(v.wakeAtUnixMs ?? 0));\n s.setText(1, v.wakeOnEventType ?? \"\");\n s.setText(2, v.wakeOnFilterJson ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n checkpointJson: s.getText(0),\n checkpointSchemaVersion: s.getUint32(0),\n wakeAtUnixMs: Number(s.getUint64(1)),\n wakeOnEventType: s.getText(1),\n wakeOnFilterJson: s.getText(2)\n };\n }\n};\nvar EventResultCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ack\":\n s.setUint16(0, 0);\n if (v.value != null) {\n EventAckCodec.write(s.initStruct(0, 0, 0), v.value, caps);\n }\n break;\n case \"retry\":\n s.setUint16(0, 1);\n if (v.value != null) {\n EventRetryCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n case \"reject\":\n s.setUint16(0, 2);\n if (v.value != null) {\n EventRejectCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"deadLetter\":\n s.setUint16(0, 3);\n if (v.value != null) {\n EventDeadLetterCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"suspended\":\n s.setUint16(0, 4);\n if (v.value != null) {\n EventSuspendedCodec.write(s.initStruct(0, 2, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"EventResult\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ack\", value: EventAckCodec.read(s.getStruct(0, 0, 0), caps) };\n case 1:\n return { kind: \"retry\", value: EventRetryCodec.read(s.getStruct(0, 1, 1), caps) };\n case 2:\n return { kind: \"reject\", value: EventRejectCodec.read(s.getStruct(0, 0, 1), caps) };\n case 3:\n return { kind: \"deadLetter\", value: EventDeadLetterCodec.read(s.getStruct(0, 0, 1), caps) };\n case 4:\n return { kind: \"suspended\", value: EventSuspendedCodec.read(s.getStruct(0, 2, 3), caps) };\n default:\n throw unknownUnion(\"EventResult\", disc);\n }\n }\n};\nvar EventBatchCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.events ?? [];\n const items = s.initStructList(0, list.length, 4, 9);\n for (let i = 0; i < items.length; i++) {\n DomainEventCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n events: s.getStructList(0, 4, 9).map((item) => DomainEventCodec.read(item, caps))\n };\n }\n};\nvar EventBatchReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n {\n const list = v.value ?? [];\n const items = s.initStructList(0, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n EventResultCodec.write(items[i], list[i], caps);\n }\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"EventBatchReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: s.getStructList(0, 1, 1).map((item) => EventResultCodec.read(item, caps)) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"EventBatchReply\", disc);\n }\n }\n};\nvar JobControllerCodec = {\n dataWords: 0,\n pointerCount: 5,\n write(s, v, caps) {\n if (v.invocation != null) {\n JobInvocationCodec.write(s.initStruct(0, 3, 8), v.invocation, caps);\n }\n if (v.input != null) {\n s.setCap(1, caps.exportCap(v.input));\n }\n if (v.output != null) {\n s.setCap(2, caps.exportCap(v.output));\n }\n if (v.progress != null) {\n s.setCap(3, caps.exportCap(v.progress));\n }\n if (v.cancel != null) {\n s.setCap(4, caps.exportCap(v.cancel));\n }\n },\n read(s, caps) {\n const out = {\n invocation: JobInvocationCodec.read(s.getStruct(0, 3, 8), caps)\n };\n const inputValue = caps.importCap(s.getCapIndex(1));\n if (!(inputValue == null)) {\n out.input = inputValue;\n }\n const outputValue = caps.importCap(s.getCapIndex(2));\n if (!(outputValue == null)) {\n out.output = outputValue;\n }\n const progressValue = caps.importCap(s.getCapIndex(3));\n if (!(progressValue == null)) {\n out.progress = progressValue;\n }\n const cancelValue = caps.importCap(s.getCapIndex(4));\n if (!(cancelValue == null)) {\n out.cancel = cancelValue;\n }\n return out;\n }\n};\nvar HeadOkCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n s.setBool(0, v.found ?? false);\n if (v.meta != null) {\n ObjectMetadataCodec.write(s.initStruct(0, 2, 6), v.meta, caps);\n }\n },\n read(s, caps) {\n return {\n found: s.getBool(0),\n meta: ObjectMetadataCodec.read(s.getStruct(0, 2, 6), caps)\n };\n }\n};\nvar HeadReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n HeadOkCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"HeadReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: HeadOkCodec.read(s.getStruct(0, 1, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"HeadReply\", disc);\n }\n }\n};\nvar ListReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n ListPageCodec.write(s.initStruct(0, 1, 2), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"ListReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: ListPageCodec.read(s.getStruct(0, 1, 2), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"ListReply\", disc);\n }\n }\n};\nvar PutReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n PutResultCodec.write(s.initStruct(0, 2, 5), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"PutReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: PutResultCodec.read(s.getStruct(0, 2, 5), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"PutReply\", disc);\n }\n }\n};\nvar CopyReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n CopyResultCodec.write(s.initStruct(0, 1, 0), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"CopyReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: CopyResultCodec.read(s.getStruct(0, 1, 0), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"CopyReply\", disc);\n }\n }\n};\nvar MoveReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n MoveResultCodec.write(s.initStruct(0, 1, 0), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"MoveReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: MoveResultCodec.read(s.getStruct(0, 1, 0), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"MoveReply\", disc);\n }\n }\n};\nvar MoveManyReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n MoveManyPageCodec.write(s.initStruct(0, 2, 2), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"MoveManyReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: MoveManyPageCodec.read(s.getStruct(0, 2, 2), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"MoveManyReply\", disc);\n }\n }\n};\nvar DeleteManyReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n DeleteManyResultCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"DeleteManyReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: DeleteManyResultCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"DeleteManyReply\", disc);\n }\n }\n};\nvar HeadManyReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n HeadManyResultCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"HeadManyReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: HeadManyResultCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"HeadManyReply\", disc);\n }\n }\n};\nvar TranslateKeysReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n TranslateKeysResultCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"TranslateKeysReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: TranslateKeysResultCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"TranslateKeysReply\", disc);\n }\n }\n};\nvar ChangesReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n ChangesPageCodec.write(s.initStruct(0, 1, 2), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"ChangesReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: ChangesPageCodec.read(s.getStruct(0, 1, 2), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"ChangesReply\", disc);\n }\n }\n};\nvar EmptyReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"EmptyReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\" };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"EmptyReply\", disc);\n }\n }\n};\nvar HandleReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n JobOutcomeCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"HandleReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: JobOutcomeCodec.read(s.getStruct(0, 1, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"HandleReply\", disc);\n }\n }\n};\nvar HealthOkCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setBool(0, v.ok ?? false);\n s.setText(0, v.detail ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n ok: s.getBool(0),\n detail: s.getText(0)\n };\n }\n};\nvar HealthReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n HealthOkCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"HealthReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: HealthOkCodec.read(s.getStruct(0, 1, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"HealthReply\", disc);\n }\n }\n};\nvar AdapterSessionReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n s.setCap(0, caps.exportCap(v.value));\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"AdapterSessionReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: caps.importCap(s.getCapIndex(0)) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"AdapterSessionReply\", disc);\n }\n }\n};\nvar CliSchemaCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.commands ?? [];\n const items = s.initStructList(0, list.length, 0, 3);\n for (let i = 0; i < items.length; i++) {\n CliCommandSpecCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n commands: s.getStructList(0, 0, 3).map((item) => CliCommandSpecCodec.read(item, caps))\n };\n }\n};\nvar CliCommandSpecCodec = {\n dataWords: 0,\n pointerCount: 3,\n write(s, v, caps) {\n s.setText(0, v.name ?? \"\");\n if (v.about !== void 0) {\n s.setText(1, v.about ?? \"\");\n }\n {\n const list = v.args ?? [];\n const items = s.initStructList(2, list.length, 1, 5);\n for (let i = 0; i < items.length; i++) {\n CliArgSpecCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n const out = {\n name: s.getText(0),\n args: s.getStructList(2, 1, 5).map((item) => CliArgSpecCodec.read(item, caps))\n };\n const aboutValue = s.getText(1);\n if (!(aboutValue === \"\")) {\n out.about = aboutValue;\n }\n return out;\n }\n};\nvar CliArgSpecCodec = {\n dataWords: 1,\n pointerCount: 5,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.name ?? \"\");\n if (v.long !== void 0) {\n s.setText(1, v.long ?? \"\");\n }\n if (v.short !== void 0) {\n s.setText(2, v.short ?? \"\");\n }\n s.setUint16(0, ord(CLI_ARG_KINDS, v.kind ?? CLI_ARG_KINDS[0], \"CliArgKind\"));\n s.setBool(16, v.required ?? false);\n if (v.default !== void 0) {\n s.setText(3, v.default ?? \"\");\n }\n if (v.about !== void 0) {\n s.setText(4, v.about ?? \"\");\n }\n s.setBool(17, v.positional ?? false);\n },\n read(s, caps) {\n void caps;\n const out = {\n name: s.getText(0),\n kind: fromOrd(CLI_ARG_KINDS, s.getUint16(0), \"CliArgKind\"),\n required: s.getBool(16),\n positional: s.getBool(17)\n };\n const longValue = s.getText(1);\n if (!(longValue === \"\")) {\n out.long = longValue;\n }\n const shortValue = s.getText(2);\n if (!(shortValue === \"\")) {\n out.short = shortValue;\n }\n const defaultValue = s.getText(3);\n if (!(defaultValue === \"\")) {\n out.default = defaultValue;\n }\n const aboutValue = s.getText(4);\n if (!(aboutValue === \"\")) {\n out.about = aboutValue;\n }\n return out;\n }\n};\nvar CliArgCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.name ?? \"\");\n s.setText(1, v.value ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n name: s.getText(0),\n value: s.getText(1)\n };\n }\n};\nvar CliInvokeParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n s.setText(0, v.command ?? \"\");\n {\n const list = v.args ?? [];\n const items = s.initStructList(1, list.length, 0, 2);\n for (let i = 0; i < items.length; i++) {\n CliArgCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n command: s.getText(0),\n args: s.getStructList(1, 0, 2).map((item) => CliArgCodec.read(item, caps))\n };\n }\n};\nvar CliInvokeResultCodec = {\n dataWords: 1,\n pointerCount: 3,\n write(s, v, caps) {\n s.setInt32(0, v.exitCode ?? 0);\n s.setText(0, v.stdout ?? \"\");\n s.setText(1, v.stderr ?? \"\");\n if (v.payload != null) {\n ExtensibleConfigCodec.write(s.initStruct(2, 1, 2), v.payload, caps);\n }\n },\n read(s, caps) {\n return {\n exitCode: s.getInt32(0),\n stdout: s.getText(0),\n stderr: s.getText(1),\n payload: ExtensibleConfigCodec.read(s.getStruct(2, 1, 2), caps)\n };\n }\n};\nvar CliSchemaReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n CliSchemaCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"CliSchemaReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: CliSchemaCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"CliSchemaReply\", disc);\n }\n }\n};\nvar CliInvokeReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n CliInvokeResultCodec.write(s.initStruct(0, 1, 3), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"CliInvokeReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: CliInvokeResultCodec.read(s.getStruct(0, 1, 3), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"CliInvokeReply\", disc);\n }\n }\n};\nvar DiagnoseResultCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setTextList(0, v.lines ?? []);\n },\n read(s, caps) {\n void caps;\n return {\n lines: s.getTextList(0)\n };\n }\n};\nvar DiagnoseReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n DiagnoseResultCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"DiagnoseReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: DiagnoseResultCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"DiagnoseReply\", disc);\n }\n }\n};\nvar SourceAccountCodec = {\n dataWords: 1,\n pointerCount: 4,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.accountId ?? \"\");\n s.setText(1, v.source ?? \"\");\n s.setText(2, v.marketplace ?? \"\");\n if (v.label !== void 0) {\n s.setText(3, v.label ?? \"\");\n }\n s.setBool(0, v.scanEnabled ?? false);\n },\n read(s, caps) {\n void caps;\n const out = {\n accountId: s.getText(0),\n source: s.getText(1),\n marketplace: s.getText(2),\n scanEnabled: s.getBool(0)\n };\n const labelValue = s.getText(3);\n if (!(labelValue === \"\")) {\n out.label = labelValue;\n }\n return out;\n }\n};\nvar LoginParamsCodec = {\n dataWords: 2,\n pointerCount: 10,\n write(s, v, caps) {\n s.setText(0, v.pluginDataDir ?? \"\");\n s.setText(1, v.marketplace ?? \"\");\n if (v.label !== void 0) {\n s.setText(2, v.label ?? \"\");\n }\n if (v.email !== void 0) {\n s.setText(3, v.email ?? \"\");\n }\n if (v.password !== void 0) {\n s.setText(4, v.password ?? \"\");\n }\n s.setBool(0, v.force ?? false);\n if (v.callbackBind !== void 0) {\n s.setText(5, v.callbackBind ?? \"\");\n }\n if (v.callbackIpc !== void 0) {\n s.setText(6, v.callbackIpc ?? \"\");\n }\n if (v.callbackPublicBase !== void 0) {\n s.setText(7, v.callbackPublicBase ?? \"\");\n }\n s.setBool(1, v.external ?? false);\n if (v.responseUrl !== void 0) {\n s.setText(8, v.responseUrl ?? \"\");\n }\n s.setBool(2, v.showQr ?? false);\n if (v.timeoutSecs !== void 0) {\n s.setUint64(1, BigInt(v.timeoutSecs ?? 0));\n }\n if (v.extra != null) {\n ExtensibleConfigCodec.write(s.initStruct(9, 1, 2), v.extra, caps);\n }\n },\n read(s, caps) {\n const out = {\n pluginDataDir: s.getText(0),\n marketplace: s.getText(1),\n force: s.getBool(0),\n external: s.getBool(1),\n showQr: s.getBool(2),\n extra: ExtensibleConfigCodec.read(s.getStruct(9, 1, 2), caps)\n };\n const labelValue = s.getText(2);\n if (!(labelValue === \"\")) {\n out.label = labelValue;\n }\n const emailValue = s.getText(3);\n if (!(emailValue === \"\")) {\n out.email = emailValue;\n }\n const passwordValue = s.getText(4);\n if (!(passwordValue === \"\")) {\n out.password = passwordValue;\n }\n const callbackBindValue = s.getText(5);\n if (!(callbackBindValue === \"\")) {\n out.callbackBind = callbackBindValue;\n }\n const callbackIpcValue = s.getText(6);\n if (!(callbackIpcValue === \"\")) {\n out.callbackIpc = callbackIpcValue;\n }\n const callbackPublicBaseValue = s.getText(7);\n if (!(callbackPublicBaseValue === \"\")) {\n out.callbackPublicBase = callbackPublicBaseValue;\n }\n const responseUrlValue = s.getText(8);\n if (!(responseUrlValue === \"\")) {\n out.responseUrl = responseUrlValue;\n }\n const timeoutSecsValue = Number(s.getUint64(1));\n if (!(timeoutSecsValue === 0)) {\n out.timeoutSecs = timeoutSecsValue;\n }\n return out;\n }\n};\nvar LoginResultCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n if (v.account != null) {\n SourceAccountCodec.write(s.initStruct(0, 1, 4), v.account, caps);\n }\n if (v.credentials !== void 0) {\n s.setData(1, v.credentials ?? EMPTY_BYTES);\n }\n },\n read(s, caps) {\n const out = {\n account: SourceAccountCodec.read(s.getStruct(0, 1, 4), caps)\n };\n const credentialsValue = s.getData(1);\n if (!(credentialsValue.length === 0)) {\n out.credentials = credentialsValue;\n }\n return out;\n }\n};\nvar LoginStartResultCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.sessionId ?? \"\");\n s.setText(1, v.url ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n sessionId: s.getText(0),\n url: s.getText(1)\n };\n }\n};\nvar LoginCompleteParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.sessionId ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n sessionId: s.getText(0)\n };\n }\n};\nvar LoginReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n LoginResultCodec.write(s.initStruct(0, 0, 2), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"LoginReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: LoginResultCodec.read(s.getStruct(0, 0, 2), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"LoginReply\", disc);\n }\n }\n};\nvar LoginStartReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n LoginStartResultCodec.write(s.initStruct(0, 0, 2), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"LoginStartReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: LoginStartResultCodec.read(s.getStruct(0, 0, 2), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"LoginStartReply\", disc);\n }\n }\n};\nvar AccountCredentialCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.accountId ?? \"\");\n s.setData(1, v.credentials ?? EMPTY_BYTES);\n },\n read(s, caps) {\n void caps;\n return {\n accountId: s.getText(0),\n credentials: s.getData(1)\n };\n }\n};\nvar ScanParamsCodec = {\n dataWords: 1,\n pointerCount: 5,\n write(s, v, caps) {\n s.setText(0, v.pluginDataDir ?? \"\");\n s.setText(1, v.accountId ?? \"\");\n s.setUint32(0, v.pageSize ?? 0);\n s.setBool(32, v.importEpisodes ?? false);\n s.setBool(33, v.importPlusTitles ?? false);\n if (v.credential != null) {\n AccountCredentialCodec.write(s.initStruct(2, 0, 2), v.credential, caps);\n }\n s.setText(3, v.cursor ?? \"\");\n s.setText(4, v.syncToken ?? \"\");\n },\n read(s, caps) {\n return {\n pluginDataDir: s.getText(0),\n accountId: s.getText(1),\n pageSize: s.getUint32(0),\n importEpisodes: s.getBool(32),\n importPlusTitles: s.getBool(33),\n credential: AccountCredentialCodec.read(s.getStruct(2, 0, 2), caps),\n cursor: s.getText(3),\n syncToken: s.getText(4)\n };\n }\n};\nvar IdentifierCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setUint16(0, ord(IDENTIFIER_SCHEMES, v.scheme ?? IDENTIFIER_SCHEMES[0], \"IdentifierScheme\"));\n s.setText(0, v.value ?? \"\");\n if (v.marketplace !== void 0) {\n s.setText(1, v.marketplace ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n scheme: fromOrd(IDENTIFIER_SCHEMES, s.getUint16(0), \"IdentifierScheme\"),\n value: s.getText(0)\n };\n const marketplaceValue = s.getText(1);\n if (!(marketplaceValue === \"\")) {\n out.marketplace = marketplaceValue;\n }\n return out;\n }\n};\nvar CreditCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.name ?? \"\");\n s.setUint16(0, ord(CREDIT_ROLES, v.role ?? CREDIT_ROLES[0], \"CreditRole\"));\n s.setUint16(1, ord(CREDIT_LEVELS, v.level ?? CREDIT_LEVELS[0], \"CreditLevel\"));\n },\n read(s, caps) {\n void caps;\n return {\n name: s.getText(0),\n role: fromOrd(CREDIT_ROLES, s.getUint16(0), \"CreditRole\"),\n level: fromOrd(CREDIT_LEVELS, s.getUint16(1), \"CreditLevel\")\n };\n }\n};\nvar SeriesEntryCodec = {\n dataWords: 0,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.name ?? \"\");\n if (v.position !== void 0) {\n s.setText(1, v.position ?? \"\");\n }\n if (v.storeSeriesId !== void 0) {\n s.setText(2, v.storeSeriesId ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n name: s.getText(0)\n };\n const positionValue = s.getText(1);\n if (!(positionValue === \"\")) {\n out.position = positionValue;\n }\n const storeSeriesIdValue = s.getText(2);\n if (!(storeSeriesIdValue === \"\")) {\n out.storeSeriesId = storeSeriesIdValue;\n }\n return out;\n }\n};\nvar ScanBookCodec = {\n dataWords: 3,\n pointerCount: 14,\n write(s, v, caps) {\n s.setText(0, v.accountId ?? \"\");\n s.setText(1, v.productId ?? \"\");\n s.setText(2, v.title ?? \"\");\n if (v.marketplace !== void 0) {\n s.setText(3, v.marketplace ?? \"\");\n }\n if (v.publisher !== void 0) {\n s.setText(4, v.publisher ?? \"\");\n }\n if (v.lengthMinutes !== void 0) {\n s.setInt64(0, v.lengthMinutes ?? 0);\n }\n if (v.subtitle !== void 0) {\n s.setText(5, v.subtitle ?? \"\");\n }\n s.setUint16(4, ord(WORK_KINDS, v.workKind ?? WORK_KINDS[0], \"WorkKind\"));\n s.setUint16(5, ord(EXPRESSION_KINDS, v.expressionKind ?? EXPRESSION_KINDS[0], \"ExpressionKind\"));\n s.setUint16(6, ord(MEDIA_KINDS, v.mediaKind ?? MEDIA_KINDS[0], \"MediaKind\"));\n {\n const list = v.identifiers ?? [];\n const items = s.initStructList(6, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n IdentifierCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.credits ?? [];\n const items = s.initStructList(7, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n CreditCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.seriesEntries ?? [];\n const items = s.initStructList(8, list.length, 0, 3);\n for (let i = 0; i < items.length; i++) {\n SeriesEntryCodec.write(items[i], list[i], caps);\n }\n }\n if (v.parentProductId !== void 0) {\n s.setText(9, v.parentProductId ?? \"\");\n }\n if (v.language !== void 0) {\n s.setText(10, v.language ?? \"\");\n }\n s.setUint16(7, ord(ABRIDGEMENTS, v.abridgement ?? ABRIDGEMENTS[0], \"Abridgement\"));\n if (v.publishedAt !== void 0) {\n s.setText(11, v.publishedAt ?? \"\");\n }\n if (v.purchasedAt !== void 0) {\n s.setText(12, v.purchasedAt ?? \"\");\n }\n if (v.categories !== void 0) {\n s.setText(13, v.categories ?? \"\");\n }\n s.setUint16(8, ord(EXPLICITNESSS, v.explicitness ?? EXPLICITNESSS[0], \"Explicitness\"));\n },\n read(s, caps) {\n const out = {\n accountId: s.getText(0),\n productId: s.getText(1),\n title: s.getText(2),\n workKind: fromOrd(WORK_KINDS, s.getUint16(4), \"WorkKind\"),\n expressionKind: fromOrd(EXPRESSION_KINDS, s.getUint16(5), \"ExpressionKind\"),\n mediaKind: fromOrd(MEDIA_KINDS, s.getUint16(6), \"MediaKind\"),\n identifiers: s.getStructList(6, 1, 2).map((item) => IdentifierCodec.read(item, caps)),\n credits: s.getStructList(7, 1, 1).map((item) => CreditCodec.read(item, caps)),\n seriesEntries: s.getStructList(8, 0, 3).map((item) => SeriesEntryCodec.read(item, caps)),\n abridgement: fromOrd(ABRIDGEMENTS, s.getUint16(7), \"Abridgement\"),\n explicitness: fromOrd(EXPLICITNESSS, s.getUint16(8), \"Explicitness\")\n };\n const marketplaceValue = s.getText(3);\n if (!(marketplaceValue === \"\")) {\n out.marketplace = marketplaceValue;\n }\n const publisherValue = s.getText(4);\n if (!(publisherValue === \"\")) {\n out.publisher = publisherValue;\n }\n const lengthMinutesValue = s.getInt64(0);\n if (!(lengthMinutesValue === 0n)) {\n out.lengthMinutes = lengthMinutesValue;\n }\n const subtitleValue = s.getText(5);\n if (!(subtitleValue === \"\")) {\n out.subtitle = subtitleValue;\n }\n const parentProductIdValue = s.getText(9);\n if (!(parentProductIdValue === \"\")) {\n out.parentProductId = parentProductIdValue;\n }\n const languageValue = s.getText(10);\n if (!(languageValue === \"\")) {\n out.language = languageValue;\n }\n const publishedAtValue = s.getText(11);\n if (!(publishedAtValue === \"\")) {\n out.publishedAt = publishedAtValue;\n }\n const purchasedAtValue = s.getText(12);\n if (!(purchasedAtValue === \"\")) {\n out.purchasedAt = purchasedAtValue;\n }\n const categoriesValue = s.getText(13);\n if (!(categoriesValue === \"\")) {\n out.categories = categoriesValue;\n }\n return out;\n }\n};\nvar ScanPageCodec = {\n dataWords: 1,\n pointerCount: 5,\n write(s, v, caps) {\n {\n const list = v.books ?? [];\n const items = s.initStructList(0, list.length, 3, 14);\n for (let i = 0; i < items.length; i++) {\n ScanBookCodec.write(items[i], list[i], caps);\n }\n }\n s.setTextList(1, v.removed ?? []);\n s.setText(2, v.nextCursor ?? \"\");\n s.setText(3, v.syncToken ?? \"\");\n s.setBool(0, v.complete ?? false);\n s.setUint32(1, v.storePages ?? 0);\n if (v.refreshedCredentials !== void 0) {\n s.setData(4, v.refreshedCredentials ?? EMPTY_BYTES);\n }\n },\n read(s, caps) {\n const out = {\n books: s.getStructList(0, 3, 14).map((item) => ScanBookCodec.read(item, caps)),\n removed: s.getTextList(1),\n nextCursor: s.getText(2),\n syncToken: s.getText(3),\n complete: s.getBool(0),\n storePages: s.getUint32(1)\n };\n const refreshedCredentialsValue = s.getData(4);\n if (!(refreshedCredentialsValue.length === 0)) {\n out.refreshedCredentials = refreshedCredentialsValue;\n }\n return out;\n }\n};\nvar ScanReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n ScanPageCodec.write(s.initStruct(0, 1, 5), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"ScanReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: ScanPageCodec.read(s.getStruct(0, 1, 5), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"ScanReply\", disc);\n }\n }\n};\nvar FetchOptionsCodec = {\n dataWords: 1,\n pointerCount: 4,\n write(s, v, caps) {\n void caps;\n s.setBool(0, v.widevine ?? false);\n s.setBool(1, v.xheAac ?? false);\n if (v.widevineCdmPath !== void 0) {\n s.setText(0, v.widevineCdmPath ?? \"\");\n }\n if (v.widevineCdmProvider !== void 0) {\n s.setText(1, v.widevineCdmProvider ?? \"\");\n }\n s.setBool(2, v.downloadCover ?? false);\n s.setBool(3, v.downloadPdf ?? false);\n s.setText(2, v.coverSize ?? \"\");\n s.setText(3, v.chapterLayout ?? \"\");\n s.setBool(4, v.stripAudibleBrandAudio ?? false);\n s.setBool(5, v.downloadClipsBookmarks ?? false);\n s.setBool(6, v.retainAaxFile ?? false);\n s.setUint32(1, v.downloadSpeedLimitKbps ?? 0);\n s.setBool(7, v.saveMetadataJson ?? false);\n },\n read(s, caps) {\n void caps;\n const out = {\n widevine: s.getBool(0),\n xheAac: s.getBool(1),\n downloadCover: s.getBool(2),\n downloadPdf: s.getBool(3),\n coverSize: s.getText(2),\n chapterLayout: s.getText(3),\n stripAudibleBrandAudio: s.getBool(4),\n downloadClipsBookmarks: s.getBool(5),\n retainAaxFile: s.getBool(6),\n downloadSpeedLimitKbps: s.getUint32(1),\n saveMetadataJson: s.getBool(7)\n };\n const widevineCdmPathValue = s.getText(0);\n if (!(widevineCdmPathValue === \"\")) {\n out.widevineCdmPath = widevineCdmPathValue;\n }\n const widevineCdmProviderValue = s.getText(1);\n if (!(widevineCdmProviderValue === \"\")) {\n out.widevineCdmProvider = widevineCdmProviderValue;\n }\n return out;\n }\n};\nvar FetchTitleParamsCodec = {\n dataWords: 0,\n pointerCount: 7,\n write(s, v, caps) {\n s.setText(0, v.pluginDataDir ?? \"\");\n s.setText(1, v.accountId ?? \"\");\n s.setText(2, v.titleId ?? \"\");\n s.setText(3, v.cacheDir ?? \"\");\n if (v.credentials !== void 0) {\n s.setData(4, v.credentials ?? EMPTY_BYTES);\n }\n if (v.sourceConfig != null) {\n ExtensibleConfigCodec.write(s.initStruct(5, 1, 2), v.sourceConfig, caps);\n }\n if (v.fetch != null) {\n FetchOptionsCodec.write(s.initStruct(6, 1, 4), v.fetch, caps);\n }\n },\n read(s, caps) {\n const out = {\n pluginDataDir: s.getText(0),\n accountId: s.getText(1),\n titleId: s.getText(2),\n cacheDir: s.getText(3),\n sourceConfig: ExtensibleConfigCodec.read(s.getStruct(5, 1, 2), caps),\n fetch: FetchOptionsCodec.read(s.getStruct(6, 1, 4), caps)\n };\n const credentialsValue = s.getData(4);\n if (!(credentialsValue.length === 0)) {\n out.credentials = credentialsValue;\n }\n return out;\n }\n};\nvar FetchedFileCodec = {\n dataWords: 2,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.path ?? \"\");\n s.setUint16(0, ord(FETCHED_FILE_ROLES, v.role ?? FETCHED_FILE_ROLES[0], \"FetchedFileRole\"));\n if (v.contentType !== void 0) {\n s.setText(1, v.contentType ?? \"\");\n }\n if (v.title !== void 0) {\n s.setText(2, v.title ?? \"\");\n }\n if (v.durationMs !== void 0) {\n s.setUint64(1, BigInt(v.durationMs ?? 0));\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n path: s.getText(0),\n role: fromOrd(FETCHED_FILE_ROLES, s.getUint16(0), \"FetchedFileRole\")\n };\n const contentTypeValue = s.getText(1);\n if (!(contentTypeValue === \"\")) {\n out.contentType = contentTypeValue;\n }\n const titleValue = s.getText(2);\n if (!(titleValue === \"\")) {\n out.title = titleValue;\n }\n const durationMsValue = Number(s.getUint64(1));\n if (!(durationMsValue === 0)) {\n out.durationMs = durationMsValue;\n }\n return out;\n }\n};\nvar ChapterMarkerCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.title ?? \"\");\n s.setUint64(0, BigInt(v.startMs ?? 0));\n },\n read(s, caps) {\n void caps;\n return {\n title: s.getText(0),\n startMs: Number(s.getUint64(0))\n };\n }\n};\nvar PlainFetchCodec = {\n dataWords: 1,\n pointerCount: 4,\n write(s, v, caps) {\n s.setUint16(0, ord(MEDIA_KINDS, v.mediaKind ?? MEDIA_KINDS[0], \"MediaKind\"));\n {\n const list = v.files ?? [];\n const items = s.initStructList(0, list.length, 2, 3);\n for (let i = 0; i < items.length; i++) {\n FetchedFileCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.chapters ?? [];\n const items = s.initStructList(1, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n ChapterMarkerCodec.write(items[i], list[i], caps);\n }\n }\n if (v.pdfUrl !== void 0) {\n s.setText(2, v.pdfUrl ?? \"\");\n }\n if (v.refreshedCredentials !== void 0) {\n s.setData(3, v.refreshedCredentials ?? EMPTY_BYTES);\n }\n s.setUint16(1, ord(CHAPTER_KINDS, v.chapterKind ?? CHAPTER_KINDS[0], \"ChapterKind\"));\n },\n read(s, caps) {\n const out = {\n mediaKind: fromOrd(MEDIA_KINDS, s.getUint16(0), \"MediaKind\"),\n files: s.getStructList(0, 2, 3).map((item) => FetchedFileCodec.read(item, caps)),\n chapters: s.getStructList(1, 1, 1).map((item) => ChapterMarkerCodec.read(item, caps)),\n chapterKind: fromOrd(CHAPTER_KINDS, s.getUint16(1), \"ChapterKind\")\n };\n const pdfUrlValue = s.getText(2);\n if (!(pdfUrlValue === \"\")) {\n out.pdfUrl = pdfUrlValue;\n }\n const refreshedCredentialsValue = s.getData(3);\n if (!(refreshedCredentialsValue.length === 0)) {\n out.refreshedCredentials = refreshedCredentialsValue;\n }\n return out;\n }\n};\nvar FetchTitleReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n PlainFetchCodec.write(s.initStruct(0, 1, 4), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"FetchTitleReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: PlainFetchCodec.read(s.getStruct(0, 1, 4), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"FetchTitleReply\", disc);\n }\n }\n};\nvar SourceAccountsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.accounts ?? [];\n const items = s.initStructList(0, list.length, 1, 4);\n for (let i = 0; i < items.length; i++) {\n SourceAccountCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n accounts: s.getStructList(0, 1, 4).map((item) => SourceAccountCodec.read(item, caps))\n };\n }\n};\nvar SourceAccountsReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n SourceAccountsCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"SourceAccountsReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: SourceAccountsCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"SourceAccountsReply\", disc);\n }\n }\n};\nvar SearchCatalogParamsCodec = {\n dataWords: 2,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.query ?? \"\");\n s.setText(1, v.region ?? \"\");\n s.setUint32(0, v.limit ?? 0);\n s.setUint32(1, v.page ?? 0);\n s.setUint16(4, ord(CATALOG_SORTS, v.sort ?? CATALOG_SORTS[0], \"CatalogSort\"));\n s.setUint16(5, ord(CATALOG_FIELDS, v.field ?? CATALOG_FIELDS[0], \"CatalogField\"));\n if (v.language !== void 0) {\n s.setText(2, v.language ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n query: s.getText(0),\n region: s.getText(1),\n limit: s.getUint32(0),\n page: s.getUint32(1),\n sort: fromOrd(CATALOG_SORTS, s.getUint16(4), \"CatalogSort\"),\n field: fromOrd(CATALOG_FIELDS, s.getUint16(5), \"CatalogField\")\n };\n const languageValue = s.getText(2);\n if (!(languageValue === \"\")) {\n out.language = languageValue;\n }\n return out;\n }\n};\nvar ExpandCandidatesParamsCodec = {\n dataWords: 1,\n pointerCount: 10,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.source ?? \"\");\n s.setText(1, v.productId ?? \"\");\n s.setText(2, v.title ?? \"\");\n if (v.authors !== void 0) {\n s.setText(3, v.authors ?? \"\");\n }\n if (v.narrators !== void 0) {\n s.setText(4, v.narrators ?? \"\");\n }\n if (v.series !== void 0) {\n s.setText(5, v.series ?? \"\");\n }\n if (v.seriesAsin !== void 0) {\n s.setText(6, v.seriesAsin ?? \"\");\n }\n if (v.asin !== void 0) {\n s.setText(7, v.asin ?? \"\");\n }\n if (v.isbn !== void 0) {\n s.setText(8, v.isbn ?? \"\");\n }\n s.setText(9, v.region ?? \"\");\n s.setUint32(0, v.limit ?? 0);\n },\n read(s, caps) {\n void caps;\n const out = {\n source: s.getText(0),\n productId: s.getText(1),\n title: s.getText(2),\n region: s.getText(9),\n limit: s.getUint32(0)\n };\n const authorsValue = s.getText(3);\n if (!(authorsValue === \"\")) {\n out.authors = authorsValue;\n }\n const narratorsValue = s.getText(4);\n if (!(narratorsValue === \"\")) {\n out.narrators = narratorsValue;\n }\n const seriesValue = s.getText(5);\n if (!(seriesValue === \"\")) {\n out.series = seriesValue;\n }\n const seriesAsinValue = s.getText(6);\n if (!(seriesAsinValue === \"\")) {\n out.seriesAsin = seriesAsinValue;\n }\n const asinValue = s.getText(7);\n if (!(asinValue === \"\")) {\n out.asin = asinValue;\n }\n const isbnValue = s.getText(8);\n if (!(isbnValue === \"\")) {\n out.isbn = isbnValue;\n }\n return out;\n }\n};\nvar PurchaseHintParamsCodec = {\n dataWords: 1,\n pointerCount: 6,\n write(s, v, caps) {\n void caps;\n if (v.productId !== void 0) {\n s.setText(0, v.productId ?? \"\");\n }\n if (v.title !== void 0) {\n s.setText(1, v.title ?? \"\");\n }\n if (v.authors !== void 0) {\n s.setText(2, v.authors ?? \"\");\n }\n if (v.asin !== void 0) {\n s.setText(3, v.asin ?? \"\");\n }\n if (v.isbn !== void 0) {\n s.setText(4, v.isbn ?? \"\");\n }\n s.setText(5, v.region ?? \"\");\n s.setBool(0, v.withPrice ?? false);\n s.setUint16(1, ord(PRICE_LOOKUPS, v.lookup ?? PRICE_LOOKUPS[0], \"PriceLookup\"));\n },\n read(s, caps) {\n void caps;\n const out = {\n region: s.getText(5),\n withPrice: s.getBool(0),\n lookup: fromOrd(PRICE_LOOKUPS, s.getUint16(1), \"PriceLookup\")\n };\n const productIdValue = s.getText(0);\n if (!(productIdValue === \"\")) {\n out.productId = productIdValue;\n }\n const titleValue = s.getText(1);\n if (!(titleValue === \"\")) {\n out.title = titleValue;\n }\n const authorsValue = s.getText(2);\n if (!(authorsValue === \"\")) {\n out.authors = authorsValue;\n }\n const asinValue = s.getText(3);\n if (!(asinValue === \"\")) {\n out.asin = asinValue;\n }\n const isbnValue = s.getText(4);\n if (!(isbnValue === \"\")) {\n out.isbn = isbnValue;\n }\n return out;\n }\n};\nvar ListDealsParamsCodec = {\n dataWords: 1,\n pointerCount: 0,\n write(s, v, caps) {\n void caps;\n if (v.limit !== void 0) {\n s.setUint32(0, v.limit ?? 0);\n }\n },\n read(s, caps) {\n void caps;\n const out = {};\n const limitValue = s.getUint32(0);\n if (!(limitValue === 0)) {\n out.limit = limitValue;\n }\n return out;\n }\n};\nvar CatalogDetailParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.productId ?? \"\");\n if (v.isbn !== void 0) {\n s.setText(1, v.isbn ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n productId: s.getText(0)\n };\n const isbnValue = s.getText(1);\n if (!(isbnValue === \"\")) {\n out.isbn = isbnValue;\n }\n return out;\n }\n};\nvar RevokeAccountParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.accountId ?? \"\");\n if (v.credentials !== void 0) {\n s.setData(1, v.credentials ?? EMPTY_BYTES);\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n accountId: s.getText(0)\n };\n const credentialsValue = s.getData(1);\n if (!(credentialsValue.length === 0)) {\n out.credentials = credentialsValue;\n }\n return out;\n }\n};\nvar CatalogHitCodec = {\n dataWords: 6,\n pointerCount: 17,\n write(s, v, caps) {\n s.setText(0, v.productId ?? \"\");\n s.setText(1, v.title ?? \"\");\n if (v.url !== void 0) {\n s.setText(2, v.url ?? \"\");\n }\n if (v.coverUrl !== void 0) {\n s.setText(3, v.coverUrl ?? \"\");\n }\n s.setText(4, v.origin ?? \"\");\n if (v.subtitle !== void 0) {\n s.setText(5, v.subtitle ?? \"\");\n }\n if (v.description !== void 0) {\n s.setText(6, v.description ?? \"\");\n }\n if (v.publisher !== void 0) {\n s.setText(7, v.publisher ?? \"\");\n }\n if (v.lengthMinutes !== void 0) {\n s.setInt64(0, v.lengthMinutes ?? 0);\n }\n if (v.publishedAt !== void 0) {\n s.setText(8, v.publishedAt ?? \"\");\n }\n if (v.categories !== void 0) {\n s.setText(9, v.categories ?? \"\");\n }\n if (v.language !== void 0) {\n s.setText(10, v.language ?? \"\");\n }\n if (v.priceCents !== void 0) {\n s.setInt64(1, v.priceCents ?? 0);\n }\n if (v.currency !== void 0) {\n s.setText(11, v.currency ?? \"\");\n }\n if (v.priceLabel !== void 0) {\n s.setText(12, v.priceLabel ?? \"\");\n }\n if (v.ratingOverall !== void 0) {\n s.setFloat64(2, v.ratingOverall ?? 0);\n }\n if (v.ratingCount !== void 0) {\n s.setInt64(3, v.ratingCount ?? 0);\n }\n s.setUint16(16, ord(ABRIDGEMENTS, v.abridgement ?? ABRIDGEMENTS[0], \"Abridgement\"));\n s.setUint16(17, ord(WORK_KINDS, v.workKind ?? WORK_KINDS[0], \"WorkKind\"));\n s.setUint16(18, ord(EXPRESSION_KINDS, v.expressionKind ?? EXPRESSION_KINDS[0], \"ExpressionKind\"));\n s.setUint16(19, ord(MEDIA_KINDS, v.mediaKind ?? MEDIA_KINDS[0], \"MediaKind\"));\n {\n const list = v.identifiers ?? [];\n const items = s.initStructList(13, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n IdentifierCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.credits ?? [];\n const items = s.initStructList(14, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n CreditCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.seriesEntries ?? [];\n const items = s.initStructList(15, list.length, 0, 3);\n for (let i = 0; i < items.length; i++) {\n SeriesEntryCodec.write(items[i], list[i], caps);\n }\n }\n if (v.parentProductId !== void 0) {\n s.setText(16, v.parentProductId ?? \"\");\n }\n if (v.rankHint !== void 0) {\n s.setUint32(10, v.rankHint ?? 0);\n }\n s.setUint16(22, ord(EXPLICITNESSS, v.explicitness ?? EXPLICITNESSS[0], \"Explicitness\"));\n },\n read(s, caps) {\n const out = {\n productId: s.getText(0),\n title: s.getText(1),\n origin: s.getText(4),\n abridgement: fromOrd(ABRIDGEMENTS, s.getUint16(16), \"Abridgement\"),\n workKind: fromOrd(WORK_KINDS, s.getUint16(17), \"WorkKind\"),\n expressionKind: fromOrd(EXPRESSION_KINDS, s.getUint16(18), \"ExpressionKind\"),\n mediaKind: fromOrd(MEDIA_KINDS, s.getUint16(19), \"MediaKind\"),\n identifiers: s.getStructList(13, 1, 2).map((item) => IdentifierCodec.read(item, caps)),\n credits: s.getStructList(14, 1, 1).map((item) => CreditCodec.read(item, caps)),\n seriesEntries: s.getStructList(15, 0, 3).map((item) => SeriesEntryCodec.read(item, caps)),\n explicitness: fromOrd(EXPLICITNESSS, s.getUint16(22), \"Explicitness\")\n };\n const urlValue = s.getText(2);\n if (!(urlValue === \"\")) {\n out.url = urlValue;\n }\n const coverUrlValue = s.getText(3);\n if (!(coverUrlValue === \"\")) {\n out.coverUrl = coverUrlValue;\n }\n const subtitleValue = s.getText(5);\n if (!(subtitleValue === \"\")) {\n out.subtitle = subtitleValue;\n }\n const descriptionValue = s.getText(6);\n if (!(descriptionValue === \"\")) {\n out.description = descriptionValue;\n }\n const publisherValue = s.getText(7);\n if (!(publisherValue === \"\")) {\n out.publisher = publisherValue;\n }\n const lengthMinutesValue = s.getInt64(0);\n if (!(lengthMinutesValue === 0n)) {\n out.lengthMinutes = lengthMinutesValue;\n }\n const publishedAtValue = s.getText(8);\n if (!(publishedAtValue === \"\")) {\n out.publishedAt = publishedAtValue;\n }\n const categoriesValue = s.getText(9);\n if (!(categoriesValue === \"\")) {\n out.categories = categoriesValue;\n }\n const languageValue = s.getText(10);\n if (!(languageValue === \"\")) {\n out.language = languageValue;\n }\n const priceCentsValue = s.getInt64(1);\n if (!(priceCentsValue === 0n)) {\n out.priceCents = priceCentsValue;\n }\n const currencyValue = s.getText(11);\n if (!(currencyValue === \"\")) {\n out.currency = currencyValue;\n }\n const priceLabelValue = s.getText(12);\n if (!(priceLabelValue === \"\")) {\n out.priceLabel = priceLabelValue;\n }\n const ratingOverallValue = s.getFloat64(2);\n if (!(ratingOverallValue === 0)) {\n out.ratingOverall = ratingOverallValue;\n }\n const ratingCountValue = s.getInt64(3);\n if (!(ratingCountValue === 0n)) {\n out.ratingCount = ratingCountValue;\n }\n const parentProductIdValue = s.getText(16);\n if (!(parentProductIdValue === \"\")) {\n out.parentProductId = parentProductIdValue;\n }\n const rankHintValue = s.getUint32(10);\n if (!(rankHintValue === 0)) {\n out.rankHint = rankHintValue;\n }\n return out;\n }\n};\nvar CatalogHitsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.hits ?? [];\n const items = s.initStructList(0, list.length, 6, 17);\n for (let i = 0; i < items.length; i++) {\n CatalogHitCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n hits: s.getStructList(0, 6, 17).map((item) => CatalogHitCodec.read(item, caps))\n };\n }\n};\nvar CatalogHitsReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n CatalogHitsCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"CatalogHitsReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: CatalogHitsCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"CatalogHitsReply\", disc);\n }\n }\n};\nvar CatalogDetailCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n s.setBool(0, v.found ?? false);\n if (v.hit != null) {\n CatalogHitCodec.write(s.initStruct(0, 6, 17), v.hit, caps);\n }\n },\n read(s, caps) {\n return {\n found: s.getBool(0),\n hit: CatalogHitCodec.read(s.getStruct(0, 6, 17), caps)\n };\n }\n};\nvar CatalogDetailReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n CatalogDetailCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"CatalogDetailReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: CatalogDetailCodec.read(s.getStruct(0, 1, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"CatalogDetailReply\", disc);\n }\n }\n};\nvar PurchaseHintCodec = {\n dataWords: 3,\n pointerCount: 7,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.productId ?? \"\");\n if (v.title !== void 0) {\n s.setText(1, v.title ?? \"\");\n }\n if (v.url !== void 0) {\n s.setText(2, v.url ?? \"\");\n }\n if (v.priceCents !== void 0) {\n s.setInt64(0, v.priceCents ?? 0);\n }\n if (v.currency !== void 0) {\n s.setText(3, v.currency ?? \"\");\n }\n if (v.priceLabel !== void 0) {\n s.setText(4, v.priceLabel ?? \"\");\n }\n if (v.listPriceCents !== void 0) {\n s.setInt64(1, v.listPriceCents ?? 0);\n }\n if (v.listPriceLabel !== void 0) {\n s.setText(5, v.listPriceLabel ?? \"\");\n }\n if (v.memberPriceCents !== void 0) {\n s.setInt64(2, v.memberPriceCents ?? 0);\n }\n if (v.memberPriceLabel !== void 0) {\n s.setText(6, v.memberPriceLabel ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n productId: s.getText(0)\n };\n const titleValue = s.getText(1);\n if (!(titleValue === \"\")) {\n out.title = titleValue;\n }\n const urlValue = s.getText(2);\n if (!(urlValue === \"\")) {\n out.url = urlValue;\n }\n const priceCentsValue = s.getInt64(0);\n if (!(priceCentsValue === 0n)) {\n out.priceCents = priceCentsValue;\n }\n const currencyValue = s.getText(3);\n if (!(currencyValue === \"\")) {\n out.currency = currencyValue;\n }\n const priceLabelValue = s.getText(4);\n if (!(priceLabelValue === \"\")) {\n out.priceLabel = priceLabelValue;\n }\n const listPriceCentsValue = s.getInt64(1);\n if (!(listPriceCentsValue === 0n)) {\n out.listPriceCents = listPriceCentsValue;\n }\n const listPriceLabelValue = s.getText(5);\n if (!(listPriceLabelValue === \"\")) {\n out.listPriceLabel = listPriceLabelValue;\n }\n const memberPriceCentsValue = s.getInt64(2);\n if (!(memberPriceCentsValue === 0n)) {\n out.memberPriceCents = memberPriceCentsValue;\n }\n const memberPriceLabelValue = s.getText(6);\n if (!(memberPriceLabelValue === \"\")) {\n out.memberPriceLabel = memberPriceLabelValue;\n }\n return out;\n }\n};\nvar PurchaseHintResultCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n s.setBool(0, v.found ?? false);\n if (v.hint != null) {\n PurchaseHintCodec.write(s.initStruct(0, 3, 7), v.hint, caps);\n }\n {\n const list = v.records ?? [];\n const items = s.initStructList(1, list.length, 0, 2);\n for (let i = 0; i < items.length; i++) {\n PricedRecordCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n found: s.getBool(0),\n hint: PurchaseHintCodec.read(s.getStruct(0, 3, 7), caps),\n records: s.getStructList(1, 0, 2).map((item) => PricedRecordCodec.read(item, caps))\n };\n }\n};\nvar PricedRecordCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n if (v.record != null) {\n CatalogHitCodec.write(s.initStruct(0, 6, 17), v.record, caps);\n }\n if (v.hint != null) {\n PurchaseHintCodec.write(s.initStruct(1, 3, 7), v.hint, caps);\n }\n },\n read(s, caps) {\n return {\n record: CatalogHitCodec.read(s.getStruct(0, 6, 17), caps),\n hint: PurchaseHintCodec.read(s.getStruct(1, 3, 7), caps)\n };\n }\n};\nvar PurchaseHintReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n PurchaseHintResultCodec.write(s.initStruct(0, 1, 2), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"PurchaseHintReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: PurchaseHintResultCodec.read(s.getStruct(0, 1, 2), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"PurchaseHintReply\", disc);\n }\n }\n};\nvar PurchaseHintsParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.queries ?? [];\n const items = s.initStructList(0, list.length, 1, 6);\n for (let i = 0; i < items.length; i++) {\n PurchaseHintParamsCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n queries: s.getStructList(0, 1, 6).map((item) => PurchaseHintParamsCodec.read(item, caps))\n };\n }\n};\nvar PurchaseHintsResultCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.results ?? [];\n const items = s.initStructList(0, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n PurchaseHintResultCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n results: s.getStructList(0, 1, 2).map((item) => PurchaseHintResultCodec.read(item, caps))\n };\n }\n};\nvar PurchaseHintsReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n PurchaseHintsResultCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"PurchaseHintsReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: PurchaseHintsResultCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"PurchaseHintsReply\", disc);\n }\n }\n};\nvar QualityOfferCodec = {\n dataWords: 2,\n pointerCount: 0,\n write(s, v, caps) {\n void caps;\n s.setUint16(0, ord(OFFERED_CODECS, v.codec ?? OFFERED_CODECS[0], \"OfferedCodec\"));\n s.setUint16(1, ord(OFFERED_AAC_PROFILES, v.aacProfile ?? OFFERED_AAC_PROFILES[0], \"OfferedAacProfile\"));\n if (v.bitrateKbps !== void 0) {\n s.setUint32(1, v.bitrateKbps ?? 0);\n }\n if (v.sampleRateHz !== void 0) {\n s.setUint32(2, v.sampleRateHz ?? 0);\n }\n if (v.channels !== void 0) {\n s.setUint32(3, v.channels ?? 0);\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n codec: fromOrd(OFFERED_CODECS, s.getUint16(0), \"OfferedCodec\"),\n aacProfile: fromOrd(OFFERED_AAC_PROFILES, s.getUint16(1), \"OfferedAacProfile\")\n };\n const bitrateKbpsValue = s.getUint32(1);\n if (!(bitrateKbpsValue === 0)) {\n out.bitrateKbps = bitrateKbpsValue;\n }\n const sampleRateHzValue = s.getUint32(2);\n if (!(sampleRateHzValue === 0)) {\n out.sampleRateHz = sampleRateHzValue;\n }\n const channelsValue = s.getUint32(3);\n if (!(channelsValue === 0)) {\n out.channels = channelsValue;\n }\n return out;\n }\n};\nvar QualityOffersParamsCodec = {\n dataWords: 0,\n pointerCount: 5,\n write(s, v, caps) {\n s.setText(0, v.accountId ?? \"\");\n if (v.credentials !== void 0) {\n s.setData(1, v.credentials ?? EMPTY_BYTES);\n }\n if (v.sourceConfig != null) {\n ExtensibleConfigCodec.write(s.initStruct(2, 1, 2), v.sourceConfig, caps);\n }\n s.setTextList(3, v.titleIds ?? []);\n if (v.fetch != null) {\n FetchOptionsCodec.write(s.initStruct(4, 1, 4), v.fetch, caps);\n }\n },\n read(s, caps) {\n const out = {\n accountId: s.getText(0),\n sourceConfig: ExtensibleConfigCodec.read(s.getStruct(2, 1, 2), caps),\n titleIds: s.getTextList(3),\n fetch: FetchOptionsCodec.read(s.getStruct(4, 1, 4), caps)\n };\n const credentialsValue = s.getData(1);\n if (!(credentialsValue.length === 0)) {\n out.credentials = credentialsValue;\n }\n return out;\n }\n};\nvar TitleQualityOfferCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n s.setBool(0, v.found ?? false);\n if (v.offer != null) {\n QualityOfferCodec.write(s.initStruct(0, 2, 0), v.offer, caps);\n }\n },\n read(s, caps) {\n return {\n found: s.getBool(0),\n offer: QualityOfferCodec.read(s.getStruct(0, 2, 0), caps)\n };\n }\n};\nvar QualityOffersResultCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n {\n const list = v.offers ?? [];\n const items = s.initStructList(0, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n TitleQualityOfferCodec.write(items[i], list[i], caps);\n }\n }\n if (v.refreshedCredentials !== void 0) {\n s.setData(1, v.refreshedCredentials ?? EMPTY_BYTES);\n }\n },\n read(s, caps) {\n const out = {\n offers: s.getStructList(0, 1, 1).map((item) => TitleQualityOfferCodec.read(item, caps))\n };\n const refreshedCredentialsValue = s.getData(1);\n if (!(refreshedCredentialsValue.length === 0)) {\n out.refreshedCredentials = refreshedCredentialsValue;\n }\n return out;\n }\n};\nvar QualityOffersReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n QualityOffersResultCodec.write(s.initStruct(0, 0, 2), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"QualityOffersReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: QualityOffersResultCodec.read(s.getStruct(0, 0, 2), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"QualityOffersReply\", disc);\n }\n }\n};\nvar ScanLibraryParamsCodec = {\n dataWords: 1,\n pointerCount: 0,\n write(s, v, caps) {\n void caps;\n s.setBool(0, v.force ?? false);\n },\n read(s, caps) {\n void caps;\n return {\n force: s.getBool(0)\n };\n }\n};\nvar AuthenticateUserParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.username ?? \"\");\n s.setText(1, v.password ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n username: s.getText(0),\n password: s.getText(1)\n };\n }\n};\nvar ExternalUserCodec = {\n dataWords: 0,\n pointerCount: 4,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.provider ?? \"\");\n s.setText(1, v.externalUserId ?? \"\");\n if (v.displayName !== void 0) {\n s.setText(2, v.displayName ?? \"\");\n }\n if (v.accessToken !== void 0) {\n s.setText(3, v.accessToken ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n provider: s.getText(0),\n externalUserId: s.getText(1)\n };\n const displayNameValue = s.getText(2);\n if (!(displayNameValue === \"\")) {\n out.displayName = displayNameValue;\n }\n const accessTokenValue = s.getText(3);\n if (!(accessTokenValue === \"\")) {\n out.accessToken = accessTokenValue;\n }\n return out;\n }\n};\nvar ExternalUserReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n ExternalUserCodec.write(s.initStruct(0, 0, 4), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"ExternalUserReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: ExternalUserCodec.read(s.getStruct(0, 0, 4), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"ExternalUserReply\", disc);\n }\n }\n};\nvar EventPollResultCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.users ?? [];\n const items = s.initStructList(0, list.length, 0, 4);\n for (let i = 0; i < items.length; i++) {\n ExternalUserCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n users: s.getStructList(0, 0, 4).map((item) => ExternalUserCodec.read(item, caps))\n };\n }\n};\nvar EventPollReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n EventPollResultCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"EventPollReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: EventPollResultCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"EventPollReply\", disc);\n }\n }\n};\nvar ListeningProgressCodec = {\n dataWords: 6,\n pointerCount: 6,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.externalUserId ?? \"\");\n s.setText(1, v.externalItemId ?? \"\");\n if (v.identityId !== void 0) {\n s.setInt64(0, v.identityId ?? 0);\n }\n if (v.title !== void 0) {\n s.setText(2, v.title ?? \"\");\n }\n if (v.authors !== void 0) {\n s.setText(3, v.authors ?? \"\");\n }\n if (v.asin !== void 0) {\n s.setText(4, v.asin ?? \"\");\n }\n if (v.isbn !== void 0) {\n s.setText(5, v.isbn ?? \"\");\n }\n if (v.progress !== void 0) {\n s.setFloat64(1, v.progress ?? 0);\n }\n if (v.currentTimeSeconds !== void 0) {\n s.setFloat64(2, v.currentTimeSeconds ?? 0);\n }\n if (v.durationSeconds !== void 0) {\n s.setFloat64(3, v.durationSeconds ?? 0);\n }\n s.setBool(256, v.isFinished ?? false);\n if (v.lastListenedAtUnixMs !== void 0) {\n s.setUint64(5, BigInt(v.lastListenedAtUnixMs ?? 0));\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n externalUserId: s.getText(0),\n externalItemId: s.getText(1),\n isFinished: s.getBool(256)\n };\n const identityIdValue = s.getInt64(0);\n if (!(identityIdValue === 0n)) {\n out.identityId = identityIdValue;\n }\n const titleValue = s.getText(2);\n if (!(titleValue === \"\")) {\n out.title = titleValue;\n }\n const authorsValue = s.getText(3);\n if (!(authorsValue === \"\")) {\n out.authors = authorsValue;\n }\n const asinValue = s.getText(4);\n if (!(asinValue === \"\")) {\n out.asin = asinValue;\n }\n const isbnValue = s.getText(5);\n if (!(isbnValue === \"\")) {\n out.isbn = isbnValue;\n }\n const progressValue = s.getFloat64(1);\n if (!(progressValue === 0)) {\n out.progress = progressValue;\n }\n const currentTimeSecondsValue = s.getFloat64(2);\n if (!(currentTimeSecondsValue === 0)) {\n out.currentTimeSeconds = currentTimeSecondsValue;\n }\n const durationSecondsValue = s.getFloat64(3);\n if (!(durationSecondsValue === 0)) {\n out.durationSeconds = durationSecondsValue;\n }\n const lastListenedAtUnixMsValue = Number(s.getUint64(5));\n if (!(lastListenedAtUnixMsValue === 0)) {\n out.lastListenedAtUnixMs = lastListenedAtUnixMsValue;\n }\n return out;\n }\n};\nvar SyncListeningResultCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.items ?? [];\n const items = s.initStructList(0, list.length, 6, 6);\n for (let i = 0; i < items.length; i++) {\n ListeningProgressCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n items: s.getStructList(0, 6, 6).map((item) => ListeningProgressCodec.read(item, caps))\n };\n }\n};\nvar SyncListeningReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n SyncListeningResultCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"SyncListeningReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: SyncListeningResultCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"SyncListeningReply\", disc);\n }\n }\n};\nvar QueueMessageCodec = {\n dataWords: 2,\n pointerCount: 4,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.id ?? \"\");\n s.setUint64(0, BigInt(v.timestampUnixMs ?? 0));\n s.setData(1, v.body ?? EMPTY_BYTES);\n s.setText(2, v.contentType ?? \"\");\n s.setUint32(2, v.attempts ?? 0);\n s.setText(3, v.source ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n id: s.getText(0),\n timestampUnixMs: Number(s.getUint64(0)),\n body: s.getData(1),\n contentType: s.getText(2),\n attempts: s.getUint32(2),\n source: s.getText(3)\n };\n }\n};\nvar QueueBatchCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n s.setText(0, v.queue ?? \"\");\n {\n const list = v.messages ?? [];\n const items = s.initStructList(1, list.length, 2, 4);\n for (let i = 0; i < items.length; i++) {\n QueueMessageCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n queue: s.getText(0),\n messages: s.getStructList(1, 2, 4).map((item) => QueueMessageCodec.read(item, caps))\n };\n }\n};\nvar QueueRetryCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setUint32(0, v.delaySeconds ?? 0);\n s.setText(0, v.reason ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n delaySeconds: s.getUint32(0),\n reason: s.getText(0)\n };\n }\n};\nvar QueueResultCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ack\":\n s.setUint16(0, 0);\n break;\n case \"retry\":\n s.setUint16(0, 1);\n if (v.value != null) {\n QueueRetryCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"QueueResult\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ack\" };\n case 1:\n return { kind: \"retry\", value: QueueRetryCodec.read(s.getStruct(0, 1, 1), caps) };\n default:\n throw unknownUnion(\"QueueResult\", disc);\n }\n }\n};\nvar QueueBatchOkCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.results ?? [];\n const items = s.initStructList(0, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n QueueResultCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n results: s.getStructList(0, 1, 1).map((item) => QueueResultCodec.read(item, caps))\n };\n }\n};\nvar QueueBatchReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n QueueBatchOkCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"QueueBatchReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: QueueBatchOkCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"QueueBatchReply\", disc);\n }\n }\n};\nvar ScheduledControllerCodec = {\n dataWords: 3,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.cron ?? \"\");\n s.setUint64(0, BigInt(v.scheduledTime ?? 0));\n s.setText(1, v.fireId ?? \"\");\n s.setUint32(2, v.attempt ?? 0);\n s.setUint64(2, BigInt(v.deadlineUnixMs ?? 0));\n },\n read(s, caps) {\n void caps;\n return {\n cron: s.getText(0),\n scheduledTime: Number(s.getUint64(0)),\n fireId: s.getText(1),\n attempt: s.getUint32(2),\n deadlineUnixMs: Number(s.getUint64(2))\n };\n }\n};\nvar MetadataLookupParamsCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n {\n const list = v.identifiers ?? [];\n const items = s.initStructList(0, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n IdentifierCodec.write(items[i], list[i], caps);\n }\n }\n if (v.marketplace !== void 0) {\n s.setText(1, v.marketplace ?? \"\");\n }\n if (v.limit !== void 0) {\n s.setUint32(0, v.limit ?? 0);\n }\n },\n read(s, caps) {\n const out = {\n identifiers: s.getStructList(0, 1, 2).map((item) => IdentifierCodec.read(item, caps))\n };\n const marketplaceValue = s.getText(1);\n if (!(marketplaceValue === \"\")) {\n out.marketplace = marketplaceValue;\n }\n const limitValue = s.getUint32(0);\n if (!(limitValue === 0)) {\n out.limit = limitValue;\n }\n return out;\n }\n};\nvar MetadataSearchParamsCodec = {\n dataWords: 1,\n pointerCount: 4,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.title ?? \"\");\n if (v.author !== void 0) {\n s.setText(1, v.author ?? \"\");\n }\n if (v.language !== void 0) {\n s.setText(2, v.language ?? \"\");\n }\n if (v.marketplace !== void 0) {\n s.setText(3, v.marketplace ?? \"\");\n }\n if (v.limit !== void 0) {\n s.setUint32(0, v.limit ?? 0);\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n title: s.getText(0)\n };\n const authorValue = s.getText(1);\n if (!(authorValue === \"\")) {\n out.author = authorValue;\n }\n const languageValue = s.getText(2);\n if (!(languageValue === \"\")) {\n out.language = languageValue;\n }\n const marketplaceValue = s.getText(3);\n if (!(marketplaceValue === \"\")) {\n out.marketplace = marketplaceValue;\n }\n const limitValue = s.getUint32(0);\n if (!(limitValue === 0)) {\n out.limit = limitValue;\n }\n return out;\n }\n};\nvar MetadataChaptersParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n {\n const list = v.identifiers ?? [];\n const items = s.initStructList(0, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n IdentifierCodec.write(items[i], list[i], caps);\n }\n }\n if (v.marketplace !== void 0) {\n s.setText(1, v.marketplace ?? \"\");\n }\n },\n read(s, caps) {\n const out = {\n identifiers: s.getStructList(0, 1, 2).map((item) => IdentifierCodec.read(item, caps))\n };\n const marketplaceValue = s.getText(1);\n if (!(marketplaceValue === \"\")) {\n out.marketplace = marketplaceValue;\n }\n return out;\n }\n};\nvar MetadataRecordCodec = {\n dataWords: 3,\n pointerCount: 12,\n write(s, v, caps) {\n s.setText(0, v.title ?? \"\");\n if (v.subtitle !== void 0) {\n s.setText(1, v.subtitle ?? \"\");\n }\n if (v.description !== void 0) {\n s.setText(2, v.description ?? \"\");\n }\n if (v.coverUrl !== void 0) {\n s.setText(3, v.coverUrl ?? \"\");\n }\n if (v.url !== void 0) {\n s.setText(4, v.url ?? \"\");\n }\n if (v.publisher !== void 0) {\n s.setText(5, v.publisher ?? \"\");\n }\n if (v.lengthMinutes !== void 0) {\n s.setUint32(0, v.lengthMinutes ?? 0);\n }\n if (v.publishedAt !== void 0) {\n s.setText(6, v.publishedAt ?? \"\");\n }\n if (v.categories !== void 0) {\n s.setText(7, v.categories ?? \"\");\n }\n if (v.language !== void 0) {\n s.setText(8, v.language ?? \"\");\n }\n s.setUint16(2, ord(ABRIDGEMENTS, v.abridgement ?? ABRIDGEMENTS[0], \"Abridgement\"));\n s.setUint16(3, ord(WORK_KINDS, v.workKind ?? WORK_KINDS[0], \"WorkKind\"));\n s.setUint16(4, ord(EXPRESSION_KINDS, v.expressionKind ?? EXPRESSION_KINDS[0], \"ExpressionKind\"));\n s.setUint16(5, ord(MEDIA_KINDS, v.mediaKind ?? MEDIA_KINDS[0], \"MediaKind\"));\n {\n const list = v.identifiers ?? [];\n const items = s.initStructList(9, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n IdentifierCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.credits ?? [];\n const items = s.initStructList(10, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n CreditCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.seriesEntries ?? [];\n const items = s.initStructList(11, list.length, 0, 3);\n for (let i = 0; i < items.length; i++) {\n SeriesEntryCodec.write(items[i], list[i], caps);\n }\n }\n if (v.ratingOverall !== void 0) {\n s.setFloat64(2, v.ratingOverall ?? 0);\n }\n if (v.ratingCount !== void 0) {\n s.setUint32(3, v.ratingCount ?? 0);\n }\n },\n read(s, caps) {\n const out = {\n title: s.getText(0),\n abridgement: fromOrd(ABRIDGEMENTS, s.getUint16(2), \"Abridgement\"),\n workKind: fromOrd(WORK_KINDS, s.getUint16(3), \"WorkKind\"),\n expressionKind: fromOrd(EXPRESSION_KINDS, s.getUint16(4), \"ExpressionKind\"),\n mediaKind: fromOrd(MEDIA_KINDS, s.getUint16(5), \"MediaKind\"),\n identifiers: s.getStructList(9, 1, 2).map((item) => IdentifierCodec.read(item, caps)),\n credits: s.getStructList(10, 1, 1).map((item) => CreditCodec.read(item, caps)),\n seriesEntries: s.getStructList(11, 0, 3).map((item) => SeriesEntryCodec.read(item, caps))\n };\n const subtitleValue = s.getText(1);\n if (!(subtitleValue === \"\")) {\n out.subtitle = subtitleValue;\n }\n const descriptionValue = s.getText(2);\n if (!(descriptionValue === \"\")) {\n out.description = descriptionValue;\n }\n const coverUrlValue = s.getText(3);\n if (!(coverUrlValue === \"\")) {\n out.coverUrl = coverUrlValue;\n }\n const urlValue = s.getText(4);\n if (!(urlValue === \"\")) {\n out.url = urlValue;\n }\n const publisherValue = s.getText(5);\n if (!(publisherValue === \"\")) {\n out.publisher = publisherValue;\n }\n const lengthMinutesValue = s.getUint32(0);\n if (!(lengthMinutesValue === 0)) {\n out.lengthMinutes = lengthMinutesValue;\n }\n const publishedAtValue = s.getText(6);\n if (!(publishedAtValue === \"\")) {\n out.publishedAt = publishedAtValue;\n }\n const categoriesValue = s.getText(7);\n if (!(categoriesValue === \"\")) {\n out.categories = categoriesValue;\n }\n const languageValue = s.getText(8);\n if (!(languageValue === \"\")) {\n out.language = languageValue;\n }\n const ratingOverallValue = s.getFloat64(2);\n if (!(ratingOverallValue === 0)) {\n out.ratingOverall = ratingOverallValue;\n }\n const ratingCountValue = s.getUint32(3);\n if (!(ratingCountValue === 0)) {\n out.ratingCount = ratingCountValue;\n }\n return out;\n }\n};\nvar MetadataRecordsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.records ?? [];\n const items = s.initStructList(0, list.length, 3, 12);\n for (let i = 0; i < items.length; i++) {\n MetadataRecordCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n records: s.getStructList(0, 3, 12).map((item) => MetadataRecordCodec.read(item, caps))\n };\n }\n};\nvar MetadataRecordsReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n MetadataRecordsCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"MetadataRecordsReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: MetadataRecordsCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"MetadataRecordsReply\", disc);\n }\n }\n};\nvar MetadataChapterCodec = {\n dataWords: 3,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.title ?? \"\");\n s.setUint64(0, BigInt(v.startMs ?? 0));\n if (v.lengthMs !== void 0) {\n s.setUint64(1, BigInt(v.lengthMs ?? 0));\n }\n s.setUint32(4, v.depth ?? 0);\n },\n read(s, caps) {\n void caps;\n const out = {\n title: s.getText(0),\n startMs: Number(s.getUint64(0)),\n depth: s.getUint32(4)\n };\n const lengthMsValue = Number(s.getUint64(1));\n if (!(lengthMsValue === 0)) {\n out.lengthMs = lengthMsValue;\n }\n return out;\n }\n};\nvar MetadataChaptersCodec = {\n dataWords: 4,\n pointerCount: 1,\n write(s, v, caps) {\n s.setBool(0, v.found ?? false);\n {\n const list = v.chapters ?? [];\n const items = s.initStructList(0, list.length, 3, 1);\n for (let i = 0; i < items.length; i++) {\n MetadataChapterCodec.write(items[i], list[i], caps);\n }\n }\n if (v.brandIntroMs !== void 0) {\n s.setUint64(1, BigInt(v.brandIntroMs ?? 0));\n }\n if (v.brandOutroMs !== void 0) {\n s.setUint64(2, BigInt(v.brandOutroMs ?? 0));\n }\n if (v.runtimeMs !== void 0) {\n s.setUint64(3, BigInt(v.runtimeMs ?? 0));\n }\n s.setBool(1, v.accurate ?? false);\n },\n read(s, caps) {\n const out = {\n found: s.getBool(0),\n chapters: s.getStructList(0, 3, 1).map((item) => MetadataChapterCodec.read(item, caps)),\n accurate: s.getBool(1)\n };\n const brandIntroMsValue = Number(s.getUint64(1));\n if (!(brandIntroMsValue === 0)) {\n out.brandIntroMs = brandIntroMsValue;\n }\n const brandOutroMsValue = Number(s.getUint64(2));\n if (!(brandOutroMsValue === 0)) {\n out.brandOutroMs = brandOutroMsValue;\n }\n const runtimeMsValue = Number(s.getUint64(3));\n if (!(runtimeMsValue === 0)) {\n out.runtimeMs = runtimeMsValue;\n }\n return out;\n }\n};\nvar MetadataChaptersReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n MetadataChaptersCodec.write(s.initStruct(0, 4, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"MetadataChaptersReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: MetadataChaptersCodec.read(s.getStruct(0, 4, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"MetadataChaptersReply\", disc);\n }\n }\n};\nvar CoverFetchParamsCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n s.setTextList(0, v.urls ?? []);\n s.setUint32(0, v.maxBytes ?? 0);\n {\n const list = v.conditions ?? [];\n const items = s.initStructList(1, list.length, 0, 2);\n for (let i = 0; i < items.length; i++) {\n CoverConditionCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n urls: s.getTextList(0),\n maxBytes: s.getUint32(0),\n conditions: s.getStructList(1, 0, 2).map((item) => CoverConditionCodec.read(item, caps))\n };\n }\n};\nvar CoverConditionCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n if (v.ifNoneMatch !== void 0) {\n s.setText(0, v.ifNoneMatch ?? \"\");\n }\n if (v.ifModifiedSince !== void 0) {\n s.setText(1, v.ifModifiedSince ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {};\n const ifNoneMatchValue = s.getText(0);\n if (!(ifNoneMatchValue === \"\")) {\n out.ifNoneMatch = ifNoneMatchValue;\n }\n const ifModifiedSinceValue = s.getText(1);\n if (!(ifModifiedSinceValue === \"\")) {\n out.ifModifiedSince = ifModifiedSinceValue;\n }\n return out;\n }\n};\nvar CoverImageCodec = {\n dataWords: 1,\n pointerCount: 9,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.url ?? \"\");\n s.setBool(0, v.stored ?? false);\n if (v.contentType !== void 0) {\n s.setText(1, v.contentType ?? \"\");\n }\n if (v.error !== void 0) {\n s.setText(2, v.error ?? \"\");\n }\n s.setBool(1, v.notModified ?? false);\n if (v.etag !== void 0) {\n s.setText(3, v.etag ?? \"\");\n }\n if (v.lastModified !== void 0) {\n s.setText(4, v.lastModified ?? \"\");\n }\n if (v.cacheControl !== void 0) {\n s.setText(5, v.cacheControl ?? \"\");\n }\n if (v.expires !== void 0) {\n s.setText(6, v.expires ?? \"\");\n }\n if (v.date !== void 0) {\n s.setText(7, v.date ?? \"\");\n }\n if (v.age !== void 0) {\n s.setText(8, v.age ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n url: s.getText(0),\n stored: s.getBool(0),\n notModified: s.getBool(1)\n };\n const contentTypeValue = s.getText(1);\n if (!(contentTypeValue === \"\")) {\n out.contentType = contentTypeValue;\n }\n const errorValue = s.getText(2);\n if (!(errorValue === \"\")) {\n out.error = errorValue;\n }\n const etagValue = s.getText(3);\n if (!(etagValue === \"\")) {\n out.etag = etagValue;\n }\n const lastModifiedValue = s.getText(4);\n if (!(lastModifiedValue === \"\")) {\n out.lastModified = lastModifiedValue;\n }\n const cacheControlValue = s.getText(5);\n if (!(cacheControlValue === \"\")) {\n out.cacheControl = cacheControlValue;\n }\n const expiresValue = s.getText(6);\n if (!(expiresValue === \"\")) {\n out.expires = expiresValue;\n }\n const dateValue = s.getText(7);\n if (!(dateValue === \"\")) {\n out.date = dateValue;\n }\n const ageValue = s.getText(8);\n if (!(ageValue === \"\")) {\n out.age = ageValue;\n }\n return out;\n }\n};\nvar CoverImagesCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.images ?? [];\n const items = s.initStructList(0, list.length, 1, 9);\n for (let i = 0; i < items.length; i++) {\n CoverImageCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n images: s.getStructList(0, 1, 9).map((item) => CoverImageCodec.read(item, caps))\n };\n }\n};\nvar CoverImagesReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n CoverImagesCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"CoverImagesReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: CoverImagesCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"CoverImagesReply\", disc);\n }\n }\n};\nvar MetadataFileRecordCodec = {\n dataWords: 2,\n pointerCount: 14,\n write(s, v, caps) {\n s.setUint16List(0, (v.present ?? []).map((v2) => ord(METADATA_FIELDS, v2, \"MetadataField\")));\n if (v.title !== void 0) {\n s.setText(1, v.title ?? \"\");\n }\n if (v.subtitle !== void 0) {\n s.setText(2, v.subtitle ?? \"\");\n }\n if (v.description !== void 0) {\n s.setText(3, v.description ?? \"\");\n }\n if (v.publisher !== void 0) {\n s.setText(4, v.publisher ?? \"\");\n }\n if (v.publishedAt !== void 0) {\n s.setText(5, v.publishedAt ?? \"\");\n }\n if (v.language !== void 0) {\n s.setText(6, v.language ?? \"\");\n }\n s.setTextList(7, v.genres ?? []);\n s.setTextList(8, v.tags ?? []);\n s.setUint16(0, ord(ABRIDGEMENTS, v.abridgement ?? ABRIDGEMENTS[0], \"Abridgement\"));\n s.setUint16(1, ord(EXPRESSION_KINDS, v.expressionKind ?? EXPRESSION_KINDS[0], \"ExpressionKind\"));\n {\n const list = v.identifiers ?? [];\n const items = s.initStructList(9, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n IdentifierCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.credits ?? [];\n const items = s.initStructList(10, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n CreditCodec.write(items[i], list[i], caps);\n }\n }\n s.setUint16List(11, (v.creditRoles ?? []).map((v2) => ord(CREDIT_ROLES, v2, \"CreditRole\")));\n {\n const list = v.seriesEntries ?? [];\n const items = s.initStructList(12, list.length, 0, 3);\n for (let i = 0; i < items.length; i++) {\n SeriesEntryCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.chapters ?? [];\n const items = s.initStructList(13, list.length, 3, 1);\n for (let i = 0; i < items.length; i++) {\n MetadataChapterCodec.write(items[i], list[i], caps);\n }\n }\n if (v.durationMs !== void 0) {\n s.setUint64(1, BigInt(v.durationMs ?? 0));\n }\n s.setUint16(2, ord(EXPLICITNESSS, v.explicitness ?? EXPLICITNESSS[0], \"Explicitness\"));\n },\n read(s, caps) {\n const out = {\n present: s.getUint16List(0).map((v) => fromOrd(METADATA_FIELDS, v, \"MetadataField\")),\n genres: s.getTextList(7),\n tags: s.getTextList(8),\n abridgement: fromOrd(ABRIDGEMENTS, s.getUint16(0), \"Abridgement\"),\n expressionKind: fromOrd(EXPRESSION_KINDS, s.getUint16(1), \"ExpressionKind\"),\n identifiers: s.getStructList(9, 1, 2).map((item) => IdentifierCodec.read(item, caps)),\n credits: s.getStructList(10, 1, 1).map((item) => CreditCodec.read(item, caps)),\n creditRoles: s.getUint16List(11).map((v) => fromOrd(CREDIT_ROLES, v, \"CreditRole\")),\n seriesEntries: s.getStructList(12, 0, 3).map((item) => SeriesEntryCodec.read(item, caps)),\n chapters: s.getStructList(13, 3, 1).map((item) => MetadataChapterCodec.read(item, caps)),\n explicitness: fromOrd(EXPLICITNESSS, s.getUint16(2), \"Explicitness\")\n };\n const titleValue = s.getText(1);\n if (!(titleValue === \"\")) {\n out.title = titleValue;\n }\n const subtitleValue = s.getText(2);\n if (!(subtitleValue === \"\")) {\n out.subtitle = subtitleValue;\n }\n const descriptionValue = s.getText(3);\n if (!(descriptionValue === \"\")) {\n out.description = descriptionValue;\n }\n const publisherValue = s.getText(4);\n if (!(publisherValue === \"\")) {\n out.publisher = publisherValue;\n }\n const publishedAtValue = s.getText(5);\n if (!(publishedAtValue === \"\")) {\n out.publishedAt = publishedAtValue;\n }\n const languageValue = s.getText(6);\n if (!(languageValue === \"\")) {\n out.language = languageValue;\n }\n const durationMsValue = Number(s.getUint64(1));\n if (!(durationMsValue === 0)) {\n out.durationMs = durationMsValue;\n }\n return out;\n }\n};\nvar MetadataFileParseParamsCodec = {\n dataWords: 0,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.dialect ?? \"\");\n s.setText(1, v.fileName ?? \"\");\n s.setData(2, v.bytes ?? EMPTY_BYTES);\n },\n read(s, caps) {\n void caps;\n return {\n dialect: s.getText(0),\n fileName: s.getText(1),\n bytes: s.getData(2)\n };\n }\n};\nvar MetadataFileParsedCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.record != null) {\n MetadataFileRecordCodec.write(s.initStruct(0, 2, 14), v.record, caps);\n }\n },\n read(s, caps) {\n return {\n record: MetadataFileRecordCodec.read(s.getStruct(0, 2, 14), caps)\n };\n }\n};\nvar MetadataFileParseReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n MetadataFileParsedCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"MetadataFileParseReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: MetadataFileParsedCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"MetadataFileParseReply\", disc);\n }\n }\n};\nvar MetadataAudioFileCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.name ?? \"\");\n s.setUint64(0, BigInt(v.durationMs ?? 0));\n },\n read(s, caps) {\n void caps;\n return {\n name: s.getText(0),\n durationMs: Number(s.getUint64(0))\n };\n }\n};\nvar MetadataFileRenderParamsCodec = {\n dataWords: 0,\n pointerCount: 5,\n write(s, v, caps) {\n s.setText(0, v.dialect ?? \"\");\n if (v.record != null) {\n MetadataFileRecordCodec.write(s.initStruct(1, 2, 14), v.record, caps);\n }\n s.setUint16List(2, (v.fields ?? []).map((v2) => ord(METADATA_FIELDS, v2, \"MetadataField\")));\n s.setData(3, v.existing ?? EMPTY_BYTES);\n {\n const list = v.audioFiles ?? [];\n const items = s.initStructList(4, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n MetadataAudioFileCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n dialect: s.getText(0),\n record: MetadataFileRecordCodec.read(s.getStruct(1, 2, 14), caps),\n fields: s.getUint16List(2).map((v) => fromOrd(METADATA_FIELDS, v, \"MetadataField\")),\n existing: s.getData(3),\n audioFiles: s.getStructList(4, 1, 1).map((item) => MetadataAudioFileCodec.read(item, caps))\n };\n }\n};\nvar MetadataFileRenderedCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setData(0, v.bytes ?? EMPTY_BYTES);\n },\n read(s, caps) {\n void caps;\n return {\n bytes: s.getData(0)\n };\n }\n};\nvar MetadataFileRenderReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n MetadataFileRenderedCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"MetadataFileRenderReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: MetadataFileRenderedCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"MetadataFileRenderReply\", disc);\n }\n }\n};\nvar NotificationFieldCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.name ?? \"\");\n s.setText(1, v.value ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n name: s.getText(0),\n value: s.getText(1)\n };\n }\n};\nvar NotificationMessageCodec = {\n dataWords: 1,\n pointerCount: 10,\n write(s, v, caps) {\n s.setText(0, v.notificationId ?? \"\");\n s.setText(1, v.notificationType ?? \"\");\n s.setUint16(0, ord(NOTIFICATION_SEVERITYS, v.severity ?? NOTIFICATION_SEVERITYS[0], \"NotificationSeverity\"));\n s.setText(2, v.title ?? \"\");\n s.setText(3, v.text ?? \"\");\n if (v.markdown !== void 0) {\n s.setText(4, v.markdown ?? \"\");\n }\n if (v.html !== void 0) {\n s.setText(5, v.html ?? \"\");\n }\n if (v.link !== void 0) {\n s.setText(6, v.link ?? \"\");\n }\n {\n const list = v.fields ?? [];\n const items = s.initStructList(7, list.length, 0, 2);\n for (let i = 0; i < items.length; i++) {\n NotificationFieldCodec.write(items[i], list[i], caps);\n }\n }\n if (v.groupKey !== void 0) {\n s.setText(8, v.groupKey ?? \"\");\n }\n s.setUint16(1, ord(NOTIFICATION_ALERT_ACTIONS, v.alertAction ?? NOTIFICATION_ALERT_ACTIONS[0], \"NotificationAlertAction\"));\n if (v.alertKey !== void 0) {\n s.setText(9, v.alertKey ?? \"\");\n }\n s.setBool(32, v.sensitive ?? false);\n },\n read(s, caps) {\n const out = {\n notificationId: s.getText(0),\n notificationType: s.getText(1),\n severity: fromOrd(NOTIFICATION_SEVERITYS, s.getUint16(0), \"NotificationSeverity\"),\n title: s.getText(2),\n text: s.getText(3),\n fields: s.getStructList(7, 0, 2).map((item) => NotificationFieldCodec.read(item, caps)),\n alertAction: fromOrd(NOTIFICATION_ALERT_ACTIONS, s.getUint16(1), \"NotificationAlertAction\"),\n sensitive: s.getBool(32)\n };\n const markdownValue = s.getText(4);\n if (!(markdownValue === \"\")) {\n out.markdown = markdownValue;\n }\n const htmlValue = s.getText(5);\n if (!(htmlValue === \"\")) {\n out.html = htmlValue;\n }\n const linkValue = s.getText(6);\n if (!(linkValue === \"\")) {\n out.link = linkValue;\n }\n const groupKeyValue = s.getText(8);\n if (!(groupKeyValue === \"\")) {\n out.groupKey = groupKeyValue;\n }\n const alertKeyValue = s.getText(9);\n if (!(alertKeyValue === \"\")) {\n out.alertKey = alertKeyValue;\n }\n return out;\n }\n};\nvar NotifyDestinationCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setUint16(0, ord(NOTIFY_DESTINATION_KINDS, v.kind ?? NOTIFY_DESTINATION_KINDS[0], \"NotifyDestinationKind\"));\n s.setText(0, v.destinationId ?? \"\");\n s.setText(1, v.addressJson ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n kind: fromOrd(NOTIFY_DESTINATION_KINDS, s.getUint16(0), \"NotifyDestinationKind\"),\n destinationId: s.getText(0),\n addressJson: s.getText(1)\n };\n }\n};\nvar NotifySendParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n if (v.message != null) {\n NotificationMessageCodec.write(s.initStruct(0, 1, 10), v.message, caps);\n }\n if (v.destination != null) {\n NotifyDestinationCodec.write(s.initStruct(1, 1, 2), v.destination, caps);\n }\n },\n read(s, caps) {\n return {\n message: NotificationMessageCodec.read(s.getStruct(0, 1, 10), caps),\n destination: NotifyDestinationCodec.read(s.getStruct(1, 1, 2), caps)\n };\n }\n};\nvar NotifySentCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n if (v.providerId !== void 0) {\n s.setText(0, v.providerId ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {};\n const providerIdValue = s.getText(0);\n if (!(providerIdValue === \"\")) {\n out.providerId = providerIdValue;\n }\n return out;\n }\n};\nvar NotifySendReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n NotifySentCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"NotifySendReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: NotifySentCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"NotifySendReply\", disc);\n }\n }\n};\nvar NotifyValidateParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.addressJson ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n addressJson: s.getText(0)\n };\n }\n};\nvar NotifyValidatedCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.addressJson ?? \"\");\n if (v.label !== void 0) {\n s.setText(1, v.label ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n addressJson: s.getText(0)\n };\n const labelValue = s.getText(1);\n if (!(labelValue === \"\")) {\n out.label = labelValue;\n }\n return out;\n }\n};\nvar NotifyValidateReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n NotifyValidatedCodec.write(s.initStruct(0, 0, 2), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"NotifyValidateReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: NotifyValidatedCodec.read(s.getStruct(0, 0, 2), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"NotifyValidateReply\", disc);\n }\n }\n};\nvar AiModelCodec = {\n dataWords: 2,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.modelId ?? \"\");\n s.setUint16(0, ord(AI_TASKS, v.task ?? AI_TASKS[0], \"AiTask\"));\n s.setText(1, v.revision ?? \"\");\n if (v.dimensions !== void 0) {\n s.setUint32(1, v.dimensions ?? 0);\n }\n if (v.maxTokens !== void 0) {\n s.setUint32(2, v.maxTokens ?? 0);\n }\n s.setTextList(2, v.languages ?? []);\n },\n read(s, caps) {\n void caps;\n const out = {\n modelId: s.getText(0),\n task: fromOrd(AI_TASKS, s.getUint16(0), \"AiTask\"),\n revision: s.getText(1),\n languages: s.getTextList(2)\n };\n const dimensionsValue = s.getUint32(1);\n if (!(dimensionsValue === 0)) {\n out.dimensions = dimensionsValue;\n }\n const maxTokensValue = s.getUint32(2);\n if (!(maxTokensValue === 0)) {\n out.maxTokens = maxTokensValue;\n }\n return out;\n }\n};\nvar AiModelListCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.models ?? [];\n const items = s.initStructList(0, list.length, 2, 3);\n for (let i = 0; i < items.length; i++) {\n AiModelCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n models: s.getStructList(0, 2, 3).map((item) => AiModelCodec.read(item, caps))\n };\n }\n};\nvar AiModelsReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n AiModelListCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"AiModelsReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: AiModelListCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"AiModelsReply\", disc);\n }\n }\n};\nvar AiEmbedTextCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.text ?? \"\");\n s.setUint16(0, ord(AI_TEXT_ROLES, v.role ?? AI_TEXT_ROLES[0], \"AiTextRole\"));\n },\n read(s, caps) {\n void caps;\n return {\n text: s.getText(0),\n role: fromOrd(AI_TEXT_ROLES, s.getUint16(0), \"AiTextRole\")\n };\n }\n};\nvar AiTextEmbeddingsInputCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.texts ?? [];\n const items = s.initStructList(0, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n AiEmbedTextCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n texts: s.getStructList(0, 1, 1).map((item) => AiEmbedTextCodec.read(item, caps))\n };\n }\n};\nvar AiTextEmbeddingsOutputCodec = {\n dataWords: 1,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setUint32(0, v.dimensions ?? 0);\n s.setData(0, v.vectors ?? EMPTY_BYTES);\n s.setText(1, v.revision ?? \"\");\n s.setUint32List(2, v.fallbacks ?? []);\n },\n read(s, caps) {\n void caps;\n return {\n dimensions: s.getUint32(0),\n vectors: s.getData(0),\n revision: s.getText(1),\n fallbacks: s.getUint32List(2)\n };\n }\n};\nvar AiInputCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.textEmbeddings != null) {\n AiTextEmbeddingsInputCodec.write(s.initStruct(0, 0, 1), v.textEmbeddings, caps);\n }\n },\n read(s, caps) {\n return {\n textEmbeddings: AiTextEmbeddingsInputCodec.read(s.getStruct(0, 0, 1), caps)\n };\n }\n};\nvar AiOutputCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.textEmbeddings != null) {\n AiTextEmbeddingsOutputCodec.write(s.initStruct(0, 1, 3), v.textEmbeddings, caps);\n }\n },\n read(s, caps) {\n return {\n textEmbeddings: AiTextEmbeddingsOutputCodec.read(s.getStruct(0, 1, 3), caps)\n };\n }\n};\nvar AiRunParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n s.setText(0, v.model ?? \"\");\n if (v.input != null) {\n AiInputCodec.write(s.initStruct(1, 0, 1), v.input, caps);\n }\n },\n read(s, caps) {\n return {\n model: s.getText(0),\n input: AiInputCodec.read(s.getStruct(1, 0, 1), caps)\n };\n }\n};\nvar AiRunOkCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n if (v.output != null) {\n AiOutputCodec.write(s.initStruct(0, 0, 1), v.output, caps);\n }\n if (v.model !== void 0) {\n s.setText(1, v.model ?? \"\");\n }\n },\n read(s, caps) {\n const out = {\n output: AiOutputCodec.read(s.getStruct(0, 0, 1), caps)\n };\n const modelValue = s.getText(1);\n if (!(modelValue === \"\")) {\n out.model = modelValue;\n }\n return out;\n }\n};\nvar AiRunReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n AiRunOkCodec.write(s.initStruct(0, 0, 2), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"AiRunReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: AiRunOkCodec.read(s.getStruct(0, 0, 2), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"AiRunReply\", disc);\n }\n }\n};\nvar SocketFrameCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n switch (v.kind) {\n case \"text\":\n s.setUint16(0, 0);\n s.setText(0, v.value ?? \"\");\n break;\n case \"binary\":\n s.setUint16(0, 1);\n s.setData(0, v.value ?? EMPTY_BYTES);\n break;\n default:\n throw unknownUnion(\"SocketFrame\", v.kind);\n }\n },\n read(s, caps) {\n void caps;\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"text\", value: s.getText(0) };\n case 1:\n return { kind: \"binary\", value: s.getData(0) };\n default:\n throw unknownUnion(\"SocketFrame\", disc);\n }\n }\n};\nvar SocketMessageReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n SocketMessageOkCodec.write(s.initStruct(0, 1, 0), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"SocketMessageReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: SocketMessageOkCodec.read(s.getStruct(0, 1, 0), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"SocketMessageReply\", disc);\n }\n }\n};\nvar SocketMessageOkCodec = {\n dataWords: 1,\n pointerCount: 0,\n write(s, v, caps) {\n void caps;\n s.setBool(0, v.pollEvents ?? false);\n },\n read(s, caps) {\n void caps;\n return {\n pollEvents: s.getBool(0)\n };\n }\n};\nvar SocketMessageCodec = {\n dataWords: 0,\n pointerCount: 3,\n write(s, v, caps) {\n s.setText(0, v.socket ?? \"\");\n if (v.frame != null) {\n SocketFrameCodec.write(s.initStruct(1, 1, 1), v.frame, caps);\n }\n s.setData(2, v.attachment ?? EMPTY_BYTES);\n },\n read(s, caps) {\n return {\n socket: s.getText(0),\n frame: SocketFrameCodec.read(s.getStruct(1, 1, 1), caps),\n attachment: s.getData(2)\n };\n }\n};\nvar SocketClosedCodec = {\n dataWords: 1,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.socket ?? \"\");\n s.setUint16(0, v.code ?? 0);\n if (v.reason !== void 0) {\n s.setText(1, v.reason ?? \"\");\n }\n s.setBool(16, v.clean ?? false);\n s.setData(2, v.attachment ?? EMPTY_BYTES);\n },\n read(s, caps) {\n void caps;\n const out = {\n socket: s.getText(0),\n code: s.getUint16(0),\n clean: s.getBool(16),\n attachment: s.getData(2)\n };\n const reasonValue = s.getText(1);\n if (!(reasonValue === \"\")) {\n out.reason = reasonValue;\n }\n return out;\n }\n};\nvar IngressStartedCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.origin ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n origin: s.getText(0)\n };\n }\n};\nvar IngressStartReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n IngressStartedCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"IngressStartReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: IngressStartedCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"IngressStartReply\", disc);\n }\n }\n};\nvar IngressHealthCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setBool(0, v.serving ?? false);\n if (v.detail !== void 0) {\n s.setText(0, v.detail ?? \"\");\n }\n },\n read(s, caps) {\n void caps;\n const out = {\n serving: s.getBool(0)\n };\n const detailValue = s.getText(0);\n if (!(detailValue === \"\")) {\n out.detail = detailValue;\n }\n return out;\n }\n};\nvar IngressHealthReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n IngressHealthCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"IngressHealthReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: IngressHealthCodec.read(s.getStruct(0, 1, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"IngressHealthReply\", disc);\n }\n }\n};\nvar WebhookDeliveredCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.name ?? \"\");\n s.setUint32(0, v.waiting ?? 0);\n },\n read(s, caps) {\n void caps;\n return {\n name: s.getText(0),\n waiting: s.getUint32(0)\n };\n }\n};\nvar DbValueCodec = {\n dataWords: 2,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n switch (v.kind) {\n case \"null\":\n s.setUint16(1, 0);\n s.setUint16(0, ord(DB_TYPES, v.value ?? DB_TYPES[0], \"DbType\"));\n break;\n case \"boolean\":\n s.setUint16(1, 1);\n s.setBool(0, v.value ?? false);\n break;\n case \"int64\":\n s.setUint16(1, 2);\n s.setInt64(1, v.value ?? 0);\n break;\n case \"float64\":\n s.setUint16(1, 3);\n s.setFloat64(1, v.value ?? 0);\n break;\n case \"text\":\n s.setUint16(1, 4);\n s.setText(0, v.value ?? \"\");\n break;\n case \"bytes\":\n s.setUint16(1, 5);\n s.setData(0, v.value ?? EMPTY_BYTES);\n break;\n default:\n throw unknownUnion(\"DbValue\", v.kind);\n }\n },\n read(s, caps) {\n void caps;\n const disc = s.getUint16(1);\n switch (disc) {\n case 0:\n return { kind: \"null\", value: fromOrd(DB_TYPES, s.getUint16(0), \"DbType\") };\n case 1:\n return { kind: \"boolean\", value: s.getBool(0) };\n case 2:\n return { kind: \"int64\", value: s.getInt64(1) };\n case 3:\n return { kind: \"float64\", value: s.getFloat64(1) };\n case 4:\n return { kind: \"text\", value: s.getText(0) };\n case 5:\n return { kind: \"bytes\", value: s.getData(0) };\n default:\n throw unknownUnion(\"DbValue\", disc);\n }\n }\n};\nvar DbColumnCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.name ?? \"\");\n s.setUint16(0, ord(DB_TYPES, v.dbType ?? DB_TYPES[0], \"DbType\"));\n },\n read(s, caps) {\n void caps;\n return {\n name: s.getText(0),\n dbType: fromOrd(DB_TYPES, s.getUint16(0), \"DbType\")\n };\n }\n};\nvar DbRowCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.values ?? [];\n const items = s.initStructList(0, list.length, 2, 1);\n for (let i = 0; i < items.length; i++) {\n DbValueCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n values: s.getStructList(0, 2, 1).map((item) => DbValueCodec.read(item, caps))\n };\n }\n};\nvar SqlSpanCodec = {\n dataWords: 1,\n pointerCount: 0,\n write(s, v, caps) {\n void caps;\n s.setUint32(0, v.start ?? 0);\n s.setUint32(1, v.end ?? 0);\n },\n read(s, caps) {\n void caps;\n return {\n start: s.getUint32(0),\n end: s.getUint32(1)\n };\n }\n};\nvar TextCollateSiteCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.span != null) {\n SqlSpanCodec.write(s.initStruct(0, 1, 0), v.span, caps);\n }\n },\n read(s, caps) {\n return {\n span: SqlSpanCodec.read(s.getStruct(0, 1, 0), caps)\n };\n }\n};\nvar IntegerArithSiteCodec = {\n dataWords: 1,\n pointerCount: 3,\n write(s, v, caps) {\n if (v.full != null) {\n SqlSpanCodec.write(s.initStruct(0, 1, 0), v.full, caps);\n }\n if (v.lhs != null) {\n SqlSpanCodec.write(s.initStruct(1, 1, 0), v.lhs, caps);\n }\n if (v.rhs != null) {\n SqlSpanCodec.write(s.initStruct(2, 1, 0), v.rhs, caps);\n }\n s.setUint16(0, ord(INTEGER_ARITH_KINDS, v.kind ?? INTEGER_ARITH_KINDS[0], \"IntegerArithKind\"));\n },\n read(s, caps) {\n return {\n full: SqlSpanCodec.read(s.getStruct(0, 1, 0), caps),\n lhs: SqlSpanCodec.read(s.getStruct(1, 1, 0), caps),\n rhs: SqlSpanCodec.read(s.getStruct(2, 1, 0), caps),\n kind: fromOrd(INTEGER_ARITH_KINDS, s.getUint16(0), \"IntegerArithKind\")\n };\n }\n};\nvar PhysicalAccessCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.table ?? \"\");\n s.setText(1, v.column ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n table: s.getText(0),\n column: s.getText(1)\n };\n }\n};\nvar ResolvedAssignmentCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.table ?? \"\");\n s.setText(1, v.column ?? \"\");\n s.setUint16(0, ord(RESOLVED_SQL_TYPES, v.dest ?? RESOLVED_SQL_TYPES[0], \"ResolvedSqlType\"));\n s.setUint16(1, ord(RESOLVED_SQL_TYPES, v.source ?? RESOLVED_SQL_TYPES[0], \"ResolvedSqlType\"));\n },\n read(s, caps) {\n void caps;\n return {\n table: s.getText(0),\n column: s.getText(1),\n dest: fromOrd(RESOLVED_SQL_TYPES, s.getUint16(0), \"ResolvedSqlType\"),\n source: fromOrd(RESOLVED_SQL_TYPES, s.getUint16(1), \"ResolvedSqlType\")\n };\n }\n};\nvar NamedSqlTypeCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.name ?? \"\");\n s.setUint16(0, ord(RESOLVED_SQL_TYPES, v.sqlType ?? RESOLVED_SQL_TYPES[0], \"ResolvedSqlType\"));\n },\n read(s, caps) {\n void caps;\n return {\n name: s.getText(0),\n sqlType: fromOrd(RESOLVED_SQL_TYPES, s.getUint16(0), \"ResolvedSqlType\")\n };\n }\n};\nvar ColumnReferenceCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.refTable ?? \"\");\n s.setTextList(1, v.refColumns ?? []);\n },\n read(s, caps) {\n void caps;\n return {\n refTable: s.getText(0),\n refColumns: s.getTextList(1)\n };\n }\n};\nvar OptionalColumnReferenceCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"none\":\n s.setUint16(0, 0);\n break;\n case \"some\":\n s.setUint16(0, 1);\n if (v.value != null) {\n ColumnReferenceCodec.write(s.initStruct(0, 0, 2), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"OptionalColumnReference\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"none\" };\n case 1:\n return { kind: \"some\", value: ColumnReferenceCodec.read(s.getStruct(0, 0, 2), caps) };\n default:\n throw unknownUnion(\"OptionalColumnReference\", disc);\n }\n }\n};\nvar ForeignKeyConstraintCodec = {\n dataWords: 0,\n pointerCount: 3,\n write(s, v, caps) {\n void caps;\n s.setTextList(0, v.columns ?? []);\n s.setText(1, v.refTable ?? \"\");\n s.setTextList(2, v.refColumns ?? []);\n },\n read(s, caps) {\n void caps;\n return {\n columns: s.getTextList(0),\n refTable: s.getText(1),\n refColumns: s.getTextList(2)\n };\n }\n};\nvar TableConstraintCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"primaryKey\":\n s.setUint16(0, 0);\n s.setTextList(0, v.value ?? []);\n break;\n case \"unique\":\n s.setUint16(0, 1);\n s.setTextList(0, v.value ?? []);\n break;\n case \"check\":\n s.setUint16(0, 2);\n s.setText(0, v.value ?? \"\");\n break;\n case \"foreignKey\":\n s.setUint16(0, 3);\n if (v.value != null) {\n ForeignKeyConstraintCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"TableConstraint\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"primaryKey\", value: s.getTextList(0) };\n case 1:\n return { kind: \"unique\", value: s.getTextList(0) };\n case 2:\n return { kind: \"check\", value: s.getText(0) };\n case 3:\n return { kind: \"foreignKey\", value: ForeignKeyConstraintCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"TableConstraint\", disc);\n }\n }\n};\nvar CreateTableSchemaCodec = {\n dataWords: 0,\n pointerCount: 10,\n write(s, v, caps) {\n s.setText(0, v.table ?? \"\");\n {\n const list = v.columns ?? [];\n const items = s.initStructList(1, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n NamedSqlTypeCodec.write(items[i], list[i], caps);\n }\n }\n s.setText(2, v.identityColumn ?? \"\");\n s.setBoolList(3, v.columnNotNull ?? []);\n s.setBoolList(4, v.columnUnique ?? []);\n s.setBoolList(5, v.columnPrimaryKey ?? []);\n s.setTextList(6, v.columnDefaults ?? []);\n s.setTextList(7, v.columnChecks ?? []);\n {\n const list = v.columnReferences ?? [];\n const items = s.initStructList(8, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n OptionalColumnReferenceCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.tableConstraints ?? [];\n const items = s.initStructList(9, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n TableConstraintCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n table: s.getText(0),\n columns: s.getStructList(1, 1, 1).map((item) => NamedSqlTypeCodec.read(item, caps)),\n identityColumn: s.getText(2),\n columnNotNull: s.getBoolList(3),\n columnUnique: s.getBoolList(4),\n columnPrimaryKey: s.getBoolList(5),\n columnDefaults: s.getTextList(6),\n columnChecks: s.getTextList(7),\n columnReferences: s.getStructList(8, 1, 1).map((item) => OptionalColumnReferenceCodec.read(item, caps)),\n tableConstraints: s.getStructList(9, 1, 1).map((item) => TableConstraintCodec.read(item, caps))\n };\n }\n};\nvar SchemaCreateCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n if (v.schema != null) {\n CreateTableSchemaCodec.write(s.initStruct(0, 0, 10), v.schema, caps);\n }\n s.setText(1, v.fingerprint ?? \"\");\n s.setBool(0, v.noop ?? false);\n },\n read(s, caps) {\n return {\n schema: CreateTableSchemaCodec.read(s.getStruct(0, 0, 10), caps),\n fingerprint: s.getText(1),\n noop: s.getBool(0)\n };\n }\n};\nvar SchemaActionCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"none\":\n s.setUint16(0, 0);\n break;\n case \"create\":\n s.setUint16(0, 1);\n if (v.value != null) {\n SchemaCreateCodec.write(s.initStruct(0, 1, 2), v.value, caps);\n }\n break;\n case \"drop\":\n s.setUint16(0, 2);\n s.setText(0, v.value ?? \"\");\n break;\n default:\n throw unknownUnion(\"SchemaAction\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"none\" };\n case 1:\n return { kind: \"create\", value: SchemaCreateCodec.read(s.getStruct(0, 1, 2), caps) };\n case 2:\n return { kind: \"drop\", value: s.getText(0) };\n default:\n throw unknownUnion(\"SchemaAction\", disc);\n }\n }\n};\nvar ResolvedStatementCodec = {\n dataWords: 0,\n pointerCount: 8,\n write(s, v, caps) {\n s.setText(0, v.statementHash ?? \"\");\n {\n const list = v.outputColumns ?? [];\n const items = s.initStructList(1, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n NamedSqlTypeCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.physicalAccesses ?? [];\n const items = s.initStructList(2, list.length, 0, 2);\n for (let i = 0; i < items.length; i++) {\n PhysicalAccessCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.assignments ?? [];\n const items = s.initStructList(3, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n ResolvedAssignmentCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.textCollateSites ?? [];\n const items = s.initStructList(4, list.length, 0, 1);\n for (let i = 0; i < items.length; i++) {\n TextCollateSiteCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.integerArithSites ?? [];\n const items = s.initStructList(5, list.length, 1, 3);\n for (let i = 0; i < items.length; i++) {\n IntegerArithSiteCodec.write(items[i], list[i], caps);\n }\n }\n s.setTextList(6, v.functions ?? []);\n if (v.schemaAction != null) {\n SchemaActionCodec.write(s.initStruct(7, 1, 1), v.schemaAction, caps);\n }\n },\n read(s, caps) {\n return {\n statementHash: s.getText(0),\n outputColumns: s.getStructList(1, 1, 1).map((item) => NamedSqlTypeCodec.read(item, caps)),\n physicalAccesses: s.getStructList(2, 0, 2).map((item) => PhysicalAccessCodec.read(item, caps)),\n assignments: s.getStructList(3, 1, 2).map((item) => ResolvedAssignmentCodec.read(item, caps)),\n textCollateSites: s.getStructList(4, 0, 1).map((item) => TextCollateSiteCodec.read(item, caps)),\n integerArithSites: s.getStructList(5, 1, 3).map((item) => IntegerArithSiteCodec.read(item, caps)),\n functions: s.getTextList(6),\n schemaAction: SchemaActionCodec.read(s.getStruct(7, 1, 1), caps)\n };\n }\n};\nvar AdapterReceiptCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setUint32(0, v.guestLen ?? 0);\n s.setText(0, v.guestHash ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n guestLen: s.getUint32(0),\n guestHash: s.getText(0)\n };\n }\n};\nvar AdapterStatementCodec = {\n dataWords: 1,\n pointerCount: 3,\n write(s, v, caps) {\n s.setText(0, v.sql ?? \"\");\n {\n const list = v.parameters ?? [];\n const items = s.initStructList(1, list.length, 2, 1);\n for (let i = 0; i < items.length; i++) {\n DbValueCodec.write(items[i], list[i], caps);\n }\n }\n s.setUint16(0, ord(DB_STATEMENT_KINDS, v.kind ?? DB_STATEMENT_KINDS[0], \"DbStatementKind\"));\n s.setUint32(1, v.maxRows ?? 0);\n s.setUint16(1, ord(DB_RESULT_SELECTIONS, v.resultSelection ?? DB_RESULT_SELECTIONS[0], \"DbResultSelection\"));\n if (v.proof != null) {\n ResolvedStatementCodec.write(s.initStruct(2, 0, 8), v.proof, caps);\n }\n },\n read(s, caps) {\n return {\n sql: s.getText(0),\n parameters: s.getStructList(1, 2, 1).map((item) => DbValueCodec.read(item, caps)),\n kind: fromOrd(DB_STATEMENT_KINDS, s.getUint16(0), \"DbStatementKind\"),\n maxRows: s.getUint32(1),\n resultSelection: fromOrd(DB_RESULT_SELECTIONS, s.getUint16(1), \"DbResultSelection\"),\n proof: ResolvedStatementCodec.read(s.getStruct(2, 0, 8), caps)\n };\n }\n};\nvar AdapterExecuteRequestCodec = {\n dataWords: 2,\n pointerCount: 4,\n write(s, v, caps) {\n s.setText(0, v.operationId ?? \"\");\n s.setText(1, v.requestHash ?? \"\");\n {\n const list = v.statements ?? [];\n const items = s.initStructList(2, list.length, 1, 3);\n for (let i = 0; i < items.length; i++) {\n AdapterStatementCodec.write(items[i], list[i], caps);\n }\n }\n s.setUint64(0, BigInt(v.deadlineUnixMs ?? 0));\n s.setUint16(4, ord(ISOLATION_REQS, v.isolation ?? ISOLATION_REQS[0], \"IsolationReq\"));\n if (v.receipt != null) {\n AdapterReceiptCodec.write(s.initStruct(3, 1, 1), v.receipt, caps);\n }\n },\n read(s, caps) {\n return {\n operationId: s.getText(0),\n requestHash: s.getText(1),\n statements: s.getStructList(2, 1, 3).map((item) => AdapterStatementCodec.read(item, caps)),\n deadlineUnixMs: Number(s.getUint64(0)),\n isolation: fromOrd(ISOLATION_REQS, s.getUint16(4), \"IsolationReq\"),\n receipt: AdapterReceiptCodec.read(s.getStruct(3, 1, 1), caps)\n };\n }\n};\nvar StatementResultCodec = {\n dataWords: 1,\n pointerCount: 2,\n write(s, v, caps) {\n {\n const list = v.rows ?? [];\n const items = s.initStructList(0, list.length, 0, 1);\n for (let i = 0; i < items.length; i++) {\n DbRowCodec.write(items[i], list[i], caps);\n }\n }\n {\n const list = v.columns ?? [];\n const items = s.initStructList(1, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n DbColumnCodec.write(items[i], list[i], caps);\n }\n }\n s.setUint64(0, BigInt(v.rowsAffected ?? 0));\n },\n read(s, caps) {\n return {\n rows: s.getStructList(0, 0, 1).map((item) => DbRowCodec.read(item, caps)),\n columns: s.getStructList(1, 1, 1).map((item) => DbColumnCodec.read(item, caps)),\n rowsAffected: Number(s.getUint64(0))\n };\n }\n};\nvar DbTimingCodec = {\n dataWords: 2,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setUint64(0, BigInt(v.attemptElapsedUs ?? 0));\n s.setUint64(1, BigInt(v.dbExecutionUs ?? 0));\n s.setText(0, v.dbTimingSource ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n attemptElapsedUs: Number(s.getUint64(0)),\n dbExecutionUs: Number(s.getUint64(1)),\n dbTimingSource: s.getText(0)\n };\n }\n};\nvar ExecuteReplyCodec = {\n dataWords: 0,\n pointerCount: 3,\n write(s, v, caps) {\n s.setText(0, v.operationId ?? \"\");\n {\n const list = v.statements ?? [];\n const items = s.initStructList(1, list.length, 1, 2);\n for (let i = 0; i < items.length; i++) {\n StatementResultCodec.write(items[i], list[i], caps);\n }\n }\n if (v.timing != null) {\n DbTimingCodec.write(s.initStruct(2, 2, 1), v.timing, caps);\n }\n },\n read(s, caps) {\n return {\n operationId: s.getText(0),\n statements: s.getStructList(1, 1, 2).map((item) => StatementResultCodec.read(item, caps)),\n timing: DbTimingCodec.read(s.getStruct(2, 2, 1), caps)\n };\n }\n};\nvar ExecuteResultReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n ExecuteReplyCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"ExecuteResultReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: ExecuteReplyCodec.read(s.getStruct(0, 0, 3), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"ExecuteResultReply\", disc);\n }\n }\n};\nvar ExecuteStreamHeadCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.operationId ?? \"\");\n s.setUint32(0, v.statementCount ?? 0);\n },\n read(s, caps) {\n void caps;\n return {\n operationId: s.getText(0),\n statementCount: s.getUint32(0)\n };\n }\n};\nvar ExecuteStreamStatementCodec = {\n dataWords: 2,\n pointerCount: 1,\n write(s, v, caps) {\n s.setUint32(0, v.index ?? 0);\n {\n const list = v.columns ?? [];\n const items = s.initStructList(0, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n DbColumnCodec.write(items[i], list[i], caps);\n }\n }\n s.setUint64(1, BigInt(v.rowsAffected ?? 0));\n },\n read(s, caps) {\n return {\n index: s.getUint32(0),\n columns: s.getStructList(0, 1, 1).map((item) => DbColumnCodec.read(item, caps)),\n rowsAffected: Number(s.getUint64(1))\n };\n }\n};\nvar ExecuteStreamFrameCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"head\":\n s.setUint16(0, 0);\n if (v.value != null) {\n ExecuteStreamHeadCodec.write(s.initStruct(0, 1, 1), v.value, caps);\n }\n break;\n case \"statement\":\n s.setUint16(0, 1);\n if (v.value != null) {\n ExecuteStreamStatementCodec.write(s.initStruct(0, 2, 1), v.value, caps);\n }\n break;\n case \"rows\":\n s.setUint16(0, 2);\n {\n const list = v.value ?? [];\n const items = s.initStructList(0, list.length, 0, 1);\n for (let i = 0; i < items.length; i++) {\n DbRowCodec.write(items[i], list[i], caps);\n }\n }\n break;\n case \"end\":\n s.setUint16(0, 3);\n if (v.value != null) {\n DbTimingCodec.write(s.initStruct(0, 2, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 4);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"ExecuteStreamFrame\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"head\", value: ExecuteStreamHeadCodec.read(s.getStruct(0, 1, 1), caps) };\n case 1:\n return { kind: \"statement\", value: ExecuteStreamStatementCodec.read(s.getStruct(0, 2, 1), caps) };\n case 2:\n return { kind: \"rows\", value: s.getStructList(0, 0, 1).map((item) => DbRowCodec.read(item, caps)) };\n case 3:\n return { kind: \"end\", value: DbTimingCodec.read(s.getStruct(0, 2, 1), caps) };\n case 4:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"ExecuteStreamFrame\", disc);\n }\n }\n};\nvar ExecuteStreamReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"inline\":\n s.setUint16(0, 0);\n s.setData(0, v.value ?? EMPTY_BYTES);\n break;\n case \"stream\":\n s.setUint16(0, 1);\n if (v.value != null) {\n s.setCap(0, caps.exportCap(v.value));\n }\n break;\n case \"err\":\n s.setUint16(0, 2);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"ExecuteStreamReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"inline\", value: s.getData(0) };\n case 1:\n return { kind: \"stream\", value: caps.importCap(s.getCapIndex(0)) };\n case 2:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"ExecuteStreamReply\", disc);\n }\n }\n};\nvar DbCapabilitiesCodec = {\n dataWords: 8,\n pointerCount: 0,\n write(s, v, caps) {\n void caps;\n s.setUint32(0, v.sqlContractVersion ?? 0);\n s.setBool(32, v.atomicBatch ?? false);\n s.setBool(33, v.returning ?? false);\n s.setBool(34, v.affectedRows ?? false);\n s.setBool(35, v.schemaMigrations ?? false);\n s.setBool(36, v.cancellation ?? false);\n s.setBool(37, v.timing ?? false);\n s.setUint32(2, v.maxBinds ?? 0);\n s.setUint32(3, v.maxStatements ?? 0);\n s.setUint32(4, v.maxResultRows ?? 0);\n s.setUint32(5, v.maxPayloadBytes ?? 0);\n s.setUint32(6, v.maxResultBytes ?? 0);\n s.setUint32(7, v.maxCellBytes ?? 0);\n s.setUint32(8, v.maxRequestBytes ?? 0);\n s.setUint32(9, v.maxAtomicResultBytes ?? 0);\n s.setBool(38, v.pluginDatabases ?? false);\n s.setUint32(10, v.maxFunctionArgs ?? 0);\n s.setUint32(11, v.maxSchemaColumns ?? 0);\n s.setUint32(12, v.maxPatternBytes ?? 0);\n s.setUint32(13, v.maxLoweredStatementBytes ?? 0);\n s.setBool(39, v.consistentBackupRead ?? false);\n s.setBool(40, v.atomicUnitRestore ?? false);\n s.setUint32(14, v.maxStreamedResultBytes ?? 0);\n s.setUint32(15, v.maxStreamedResultRows ?? 0);\n },\n read(s, caps) {\n void caps;\n return {\n sqlContractVersion: s.getUint32(0),\n atomicBatch: s.getBool(32),\n returning: s.getBool(33),\n affectedRows: s.getBool(34),\n schemaMigrations: s.getBool(35),\n cancellation: s.getBool(36),\n timing: s.getBool(37),\n maxBinds: s.getUint32(2),\n maxStatements: s.getUint32(3),\n maxResultRows: s.getUint32(4),\n maxPayloadBytes: s.getUint32(5),\n maxResultBytes: s.getUint32(6),\n maxCellBytes: s.getUint32(7),\n maxRequestBytes: s.getUint32(8),\n maxAtomicResultBytes: s.getUint32(9),\n pluginDatabases: s.getBool(38),\n maxFunctionArgs: s.getUint32(10),\n maxSchemaColumns: s.getUint32(11),\n maxPatternBytes: s.getUint32(12),\n maxLoweredStatementBytes: s.getUint32(13),\n consistentBackupRead: s.getBool(39),\n atomicUnitRestore: s.getBool(40),\n maxStreamedResultBytes: s.getUint32(14),\n maxStreamedResultRows: s.getUint32(15)\n };\n }\n};\nvar DbBootstrapReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n DbBootstrapCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"DbBootstrapReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: DbBootstrapCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"DbBootstrapReply\", disc);\n }\n }\n};\nvar DbBootstrapCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.engine ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n engine: s.getText(0)\n };\n }\n};\nvar DbCapabilitiesReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n DbCapabilitiesCodec.write(s.initStruct(0, 8, 0), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"DbCapabilitiesReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: DbCapabilitiesCodec.read(s.getStruct(0, 8, 0), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"DbCapabilitiesReply\", disc);\n }\n }\n};\nvar IdentityHighWaterCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.table ?? \"\");\n s.setInt64(0, v.last ?? 0);\n },\n read(s, caps) {\n void caps;\n return {\n table: s.getText(0),\n last: s.getInt64(0)\n };\n }\n};\nvar IdentityExportReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n {\n const list = v.value ?? [];\n const items = s.initStructList(0, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n IdentityHighWaterCodec.write(items[i], list[i], caps);\n }\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"IdentityExportReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: s.getStructList(0, 1, 1).map((item) => IdentityHighWaterCodec.read(item, caps)) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"IdentityExportReply\", disc);\n }\n }\n};\nvar UserRelationsReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n s.setTextList(0, v.value ?? []);\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"UserRelationsReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: s.getTextList(0) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"UserRelationsReply\", disc);\n }\n }\n};\nvar PluginMigrationOpCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n switch (v.kind) {\n case \"schema\":\n s.setUint16(0, 0);\n s.setText(0, v.value ?? \"\");\n break;\n case \"data\":\n s.setUint16(0, 1);\n s.setText(0, v.value ?? \"\");\n break;\n default:\n throw unknownUnion(\"PluginMigrationOp\", v.kind);\n }\n },\n read(s, caps) {\n void caps;\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"schema\", value: s.getText(0) };\n case 1:\n return { kind: \"data\", value: s.getText(0) };\n default:\n throw unknownUnion(\"PluginMigrationOp\", disc);\n }\n }\n};\nvar PluginMigrationCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n s.setText(0, v.id ?? \"\");\n {\n const list = v.operations ?? [];\n const items = s.initStructList(1, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n PluginMigrationOpCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n id: s.getText(0),\n operations: s.getStructList(1, 1, 1).map((item) => PluginMigrationOpCodec.read(item, caps))\n };\n }\n};\nvar PluginMigrationsOkCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.migrations ?? [];\n const items = s.initStructList(0, list.length, 0, 2);\n for (let i = 0; i < items.length; i++) {\n PluginMigrationCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n migrations: s.getStructList(0, 0, 2).map((item) => PluginMigrationCodec.read(item, caps))\n };\n }\n};\nvar PluginMigrationsReplyCodec = {\n dataWords: 1,\n pointerCount: 1,\n write(s, v, caps) {\n switch (v.kind) {\n case \"ok\":\n s.setUint16(0, 0);\n if (v.value != null) {\n PluginMigrationsOkCodec.write(s.initStruct(0, 0, 1), v.value, caps);\n }\n break;\n case \"err\":\n s.setUint16(0, 1);\n if (v.value != null) {\n PluginErrorCodec.write(s.initStruct(0, 0, 3), v.value, caps);\n }\n break;\n default:\n throw unknownUnion(\"PluginMigrationsReply\", v.kind);\n }\n },\n read(s, caps) {\n const disc = s.getUint16(0);\n switch (disc) {\n case 0:\n return { kind: \"ok\", value: PluginMigrationsOkCodec.read(s.getStruct(0, 0, 1), caps) };\n case 1:\n return { kind: \"err\", value: PluginErrorCodec.read(s.getStruct(0, 0, 3), caps) };\n default:\n throw unknownUnion(\"PluginMigrationsReply\", disc);\n }\n }\n};\nvar DestinationHeadParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.key ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n key: s.getText(0)\n };\n }\n};\nvar DestinationHeadResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HeadReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HeadReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationListParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.options != null) {\n ListOptionsCodec.write(s.initStruct(0, 2, 2), v.options, caps);\n }\n },\n read(s, caps) {\n return {\n options: ListOptionsCodec.read(s.getStruct(0, 2, 2), caps)\n };\n }\n};\nvar DestinationListResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n ListReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: ListReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationCopyParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.from ?? \"\");\n s.setText(1, v.to ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n from: s.getText(0),\n to: s.getText(1)\n };\n }\n};\nvar DestinationCopyResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n CopyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: CopyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationDeleteParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.key ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n key: s.getText(0)\n };\n }\n};\nvar DestinationDeleteResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationCommitParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.key ?? \"\");\n s.setText(1, v.commitToken ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n key: s.getText(0),\n commitToken: s.getText(1)\n };\n }\n};\nvar DestinationCommitResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n PutReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: PutReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationAbortStageParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.key ?? \"\");\n s.setText(1, v.commitToken ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n key: s.getText(0),\n commitToken: s.getText(1)\n };\n }\n};\nvar DestinationAbortStageResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationMoveParamsCodec = {\n dataWords: 0,\n pointerCount: 3,\n write(s, v, caps) {\n s.setText(0, v.from ?? \"\");\n s.setText(1, v.to ?? \"\");\n if (v.options != null) {\n MoveOptionsCodec.write(s.initStruct(2, 1, 1), v.options, caps);\n }\n },\n read(s, caps) {\n return {\n from: s.getText(0),\n to: s.getText(1),\n options: MoveOptionsCodec.read(s.getStruct(2, 1, 1), caps)\n };\n }\n};\nvar DestinationMoveResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n MoveReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: MoveReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationMoveManyParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.request != null) {\n MoveManyRequestCodec.write(s.initStruct(0, 1, 3), v.request, caps);\n }\n },\n read(s, caps) {\n return {\n request: MoveManyRequestCodec.read(s.getStruct(0, 1, 3), caps)\n };\n }\n};\nvar DestinationMoveManyResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n MoveManyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: MoveManyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationDeleteManyParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setTextList(0, v.keys ?? []);\n },\n read(s, caps) {\n void caps;\n return {\n keys: s.getTextList(0)\n };\n }\n};\nvar DestinationDeleteManyResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n DeleteManyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: DeleteManyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationHeadManyParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setTextList(0, v.keys ?? []);\n },\n read(s, caps) {\n void caps;\n return {\n keys: s.getTextList(0)\n };\n }\n};\nvar DestinationHeadManyResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HeadManyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HeadManyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationChangesParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.request != null) {\n ChangesRequestCodec.write(s.initStruct(0, 1, 1), v.request, caps);\n }\n },\n read(s, caps) {\n return {\n request: ChangesRequestCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationChangesResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n ChangesReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: ChangesReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DestinationTranslateKeysParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setTextList(0, v.keys ?? []);\n },\n read(s, caps) {\n void caps;\n return {\n keys: s.getTextList(0)\n };\n }\n};\nvar DestinationTranslateKeysResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n TranslateKeysReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: TranslateKeysReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar JobRunnerJobParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.controller != null) {\n JobControllerCodec.write(s.initStruct(0, 0, 5), v.controller, caps);\n }\n },\n read(s, caps) {\n return {\n controller: JobControllerCodec.read(s.getStruct(0, 0, 5), caps)\n };\n }\n};\nvar JobRunnerJobResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HandleReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HandleReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar EventConsumerEventParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.batch != null) {\n EventBatchCodec.write(s.initStruct(0, 0, 1), v.batch, caps);\n }\n },\n read(s, caps) {\n return {\n batch: EventBatchCodec.read(s.getStruct(0, 0, 1), caps)\n };\n }\n};\nvar EventConsumerEventResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EventBatchReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EventBatchReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ScheduledHandlerScheduledParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.controller != null) {\n ScheduledControllerCodec.write(s.initStruct(0, 3, 2), v.controller, caps);\n }\n },\n read(s, caps) {\n return {\n controller: ScheduledControllerCodec.read(s.getStruct(0, 3, 2), caps)\n };\n }\n};\nvar ScheduledHandlerScheduledResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar QueueConsumerQueueParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.batch != null) {\n QueueBatchCodec.write(s.initStruct(0, 0, 2), v.batch, caps);\n }\n },\n read(s, caps) {\n return {\n batch: QueueBatchCodec.read(s.getStruct(0, 0, 2), caps)\n };\n }\n};\nvar QueueConsumerQueueResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n QueueBatchReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: QueueBatchReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar SocketHandlerMessageParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.event != null) {\n SocketMessageCodec.write(s.initStruct(0, 0, 3), v.event, caps);\n }\n },\n read(s, caps) {\n return {\n event: SocketMessageCodec.read(s.getStruct(0, 0, 3), caps)\n };\n }\n};\nvar SocketHandlerMessageResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n SocketMessageReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: SocketMessageReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar SocketHandlerClosedParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.event != null) {\n SocketClosedCodec.write(s.initStruct(0, 1, 3), v.event, caps);\n }\n },\n read(s, caps) {\n return {\n event: SocketClosedCodec.read(s.getStruct(0, 1, 3), caps)\n };\n }\n};\nvar SocketHandlerClosedResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar IngressStartParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar IngressStartResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n IngressStartReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: IngressStartReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar IngressHealthParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar IngressHealthResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n IngressHealthReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: IngressHealthReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar IngressStopParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar IngressStopResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar WebhookHandlerDeliveredParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.event != null) {\n WebhookDeliveredCodec.write(s.initStruct(0, 1, 1), v.event, caps);\n }\n },\n read(s, caps) {\n return {\n event: WebhookDeliveredCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar WebhookHandlerDeliveredResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceLoginParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n LoginParamsCodec.write(s.initStruct(0, 2, 10), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: LoginParamsCodec.read(s.getStruct(0, 2, 10), caps)\n };\n }\n};\nvar ContentSourceLoginResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n LoginReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: LoginReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceScanParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n ScanParamsCodec.write(s.initStruct(0, 1, 5), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: ScanParamsCodec.read(s.getStruct(0, 1, 5), caps)\n };\n }\n};\nvar ContentSourceScanResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n ScanReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: ScanReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceFetchTitleParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n FetchTitleParamsCodec.write(s.initStruct(0, 0, 7), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: FetchTitleParamsCodec.read(s.getStruct(0, 0, 7), caps)\n };\n }\n};\nvar ContentSourceFetchTitleResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n FetchTitleReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: FetchTitleReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceListAccountsParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar ContentSourceListAccountsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n SourceAccountsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: SourceAccountsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceLoginStartParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n LoginParamsCodec.write(s.initStruct(0, 2, 10), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: LoginParamsCodec.read(s.getStruct(0, 2, 10), caps)\n };\n }\n};\nvar ContentSourceLoginStartResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n LoginStartReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: LoginStartReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceLoginCompleteParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n LoginCompleteParamsCodec.write(s.initStruct(0, 0, 1), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: LoginCompleteParamsCodec.read(s.getStruct(0, 0, 1), caps)\n };\n }\n};\nvar ContentSourceLoginCompleteResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n LoginReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: LoginReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceSearchCatalogParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n SearchCatalogParamsCodec.write(s.initStruct(0, 2, 3), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: SearchCatalogParamsCodec.read(s.getStruct(0, 2, 3), caps)\n };\n }\n};\nvar ContentSourceSearchCatalogResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n CatalogHitsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: CatalogHitsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceExpandCandidatesParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n ExpandCandidatesParamsCodec.write(s.initStruct(0, 1, 10), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: ExpandCandidatesParamsCodec.read(s.getStruct(0, 1, 10), caps)\n };\n }\n};\nvar ContentSourceExpandCandidatesResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n CatalogHitsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: CatalogHitsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourcePurchaseHintParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n PurchaseHintParamsCodec.write(s.initStruct(0, 1, 6), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: PurchaseHintParamsCodec.read(s.getStruct(0, 1, 6), caps)\n };\n }\n};\nvar ContentSourcePurchaseHintResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n PurchaseHintReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: PurchaseHintReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceListDealsParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n ListDealsParamsCodec.write(s.initStruct(0, 1, 0), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: ListDealsParamsCodec.read(s.getStruct(0, 1, 0), caps)\n };\n }\n};\nvar ContentSourceListDealsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n CatalogHitsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: CatalogHitsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceHealthParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar ContentSourceHealthResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HealthReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HealthReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceDiagnoseParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar ContentSourceDiagnoseResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n DiagnoseReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: DiagnoseReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceCatalogDetailParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n CatalogDetailParamsCodec.write(s.initStruct(0, 0, 2), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: CatalogDetailParamsCodec.read(s.getStruct(0, 0, 2), caps)\n };\n }\n};\nvar ContentSourceCatalogDetailResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n CatalogDetailReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: CatalogDetailReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceRevokeAccountParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n RevokeAccountParamsCodec.write(s.initStruct(0, 0, 2), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: RevokeAccountParamsCodec.read(s.getStruct(0, 0, 2), caps)\n };\n }\n};\nvar ContentSourceRevokeAccountResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourcePurchaseHintsParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n PurchaseHintsParamsCodec.write(s.initStruct(0, 0, 1), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: PurchaseHintsParamsCodec.read(s.getStruct(0, 0, 1), caps)\n };\n }\n};\nvar ContentSourcePurchaseHintsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n PurchaseHintsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: PurchaseHintsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar ContentSourceQualityOffersParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n QualityOffersParamsCodec.write(s.initStruct(0, 0, 5), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: QualityOffersParamsCodec.read(s.getStruct(0, 0, 5), caps)\n };\n }\n};\nvar ContentSourceQualityOffersResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n QualityOffersReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: QualityOffersReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar RemoteLibraryHealthParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar RemoteLibraryHealthResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HealthReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HealthReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar RemoteLibraryStartParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar RemoteLibraryStartResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar RemoteLibraryStopParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar RemoteLibraryStopResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar RemoteLibraryDiagnoseParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar RemoteLibraryDiagnoseResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n DiagnoseReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: DiagnoseReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar RemoteLibraryScanLibraryParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n ScanLibraryParamsCodec.write(s.initStruct(0, 1, 0), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: ScanLibraryParamsCodec.read(s.getStruct(0, 1, 0), caps)\n };\n }\n};\nvar RemoteLibraryScanLibraryResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar RemoteLibrarySyncListeningParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar RemoteLibrarySyncListeningResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n SyncListeningReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: SyncListeningReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar RemoteLibraryPollEventsParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar RemoteLibraryPollEventsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EventPollReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EventPollReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar PluginCliDescribeParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar PluginCliDescribeResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n CliSchemaReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: CliSchemaReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar PluginCliInvokeParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n CliInvokeParamsCodec.write(s.initStruct(0, 0, 2), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: CliInvokeParamsCodec.read(s.getStruct(0, 0, 2), caps)\n };\n }\n};\nvar PluginCliInvokeResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n CliInvokeReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: CliInvokeReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar OidcClientsParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar OidcClientsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n OidcClientsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: OidcClientsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar OidcAuthenticateUserParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n AuthenticateUserParamsCodec.write(s.initStruct(0, 0, 2), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: AuthenticateUserParamsCodec.read(s.getStruct(0, 0, 2), caps)\n };\n }\n};\nvar OidcAuthenticateUserResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n ExternalUserReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: ExternalUserReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar MetadataProviderHealthParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar MetadataProviderHealthResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HealthReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HealthReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar MetadataProviderLookupParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n MetadataLookupParamsCodec.write(s.initStruct(0, 1, 2), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: MetadataLookupParamsCodec.read(s.getStruct(0, 1, 2), caps)\n };\n }\n};\nvar MetadataProviderLookupResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n MetadataRecordsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: MetadataRecordsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar MetadataProviderSearchParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n MetadataSearchParamsCodec.write(s.initStruct(0, 1, 4), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: MetadataSearchParamsCodec.read(s.getStruct(0, 1, 4), caps)\n };\n }\n};\nvar MetadataProviderSearchResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n MetadataRecordsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: MetadataRecordsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar MetadataProviderChaptersParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n MetadataChaptersParamsCodec.write(s.initStruct(0, 0, 2), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: MetadataChaptersParamsCodec.read(s.getStruct(0, 0, 2), caps)\n };\n }\n};\nvar MetadataProviderChaptersResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n MetadataChaptersReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: MetadataChaptersReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar CoverFetcherHealthParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar CoverFetcherHealthResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HealthReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HealthReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar CoverFetcherFetchCoversParamsCodec = {\n dataWords: 0,\n pointerCount: 2,\n write(s, v, caps) {\n if (v.params != null) {\n CoverFetchParamsCodec.write(s.initStruct(0, 1, 2), v.params, caps);\n }\n if (v.sink != null) {\n s.setCap(1, caps.exportCap(v.sink));\n }\n },\n read(s, caps) {\n const out = {\n params: CoverFetchParamsCodec.read(s.getStruct(0, 1, 2), caps)\n };\n const sinkValue = caps.importCap(s.getCapIndex(1));\n if (!(sinkValue == null)) {\n out.sink = sinkValue;\n }\n return out;\n }\n};\nvar CoverFetcherFetchCoversResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n CoverImagesReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: CoverImagesReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar MetadataFilesHealthParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar MetadataFilesHealthResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HealthReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HealthReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar MetadataFilesParseParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n MetadataFileParseParamsCodec.write(s.initStruct(0, 0, 3), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: MetadataFileParseParamsCodec.read(s.getStruct(0, 0, 3), caps)\n };\n }\n};\nvar MetadataFilesParseResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n MetadataFileParseReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: MetadataFileParseReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar MetadataFilesRenderParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n MetadataFileRenderParamsCodec.write(s.initStruct(0, 0, 5), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: MetadataFileRenderParamsCodec.read(s.getStruct(0, 0, 5), caps)\n };\n }\n};\nvar MetadataFilesRenderResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n MetadataFileRenderReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: MetadataFileRenderReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar NotifierHealthParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar NotifierHealthResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HealthReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HealthReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar NotifierSendParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n NotifySendParamsCodec.write(s.initStruct(0, 0, 2), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: NotifySendParamsCodec.read(s.getStruct(0, 0, 2), caps)\n };\n }\n};\nvar NotifierSendResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n NotifySendReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: NotifySendReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar NotifierValidateDestinationParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n NotifyValidateParamsCodec.write(s.initStruct(0, 0, 1), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: NotifyValidateParamsCodec.read(s.getStruct(0, 0, 1), caps)\n };\n }\n};\nvar NotifierValidateDestinationResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n NotifyValidateReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: NotifyValidateReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AiModelsHealthParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar AiModelsHealthResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n HealthReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: HealthReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AiModelsModelsParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar AiModelsModelsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n AiModelsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: AiModelsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AiModelsRunParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.params != null) {\n AiRunParamsCodec.write(s.initStruct(0, 0, 2), v.params, caps);\n }\n },\n read(s, caps) {\n return {\n params: AiRunParamsCodec.read(s.getStruct(0, 0, 2), caps)\n };\n }\n};\nvar AiModelsRunResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n AiRunReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: AiRunReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DatabaseOpenSessionParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar DatabaseOpenSessionResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n AdapterSessionReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: AdapterSessionReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar DatabaseDropUnitParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.unitRef ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n unitRef: s.getText(0)\n };\n }\n};\nvar DatabaseDropUnitResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionCapabilitiesParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar AdapterDatabaseSessionCapabilitiesResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n DbCapabilitiesReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: DbCapabilitiesReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionExecuteParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.request != null) {\n AdapterExecuteRequestCodec.write(s.initStruct(0, 2, 4), v.request, caps);\n }\n },\n read(s, caps) {\n return {\n request: AdapterExecuteRequestCodec.read(s.getStruct(0, 2, 4), caps)\n };\n }\n};\nvar AdapterDatabaseSessionExecuteResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n ExecuteResultReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: ExecuteResultReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionCloseParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar AdapterDatabaseSessionCloseResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionBootstrapParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar AdapterDatabaseSessionBootstrapResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n DbBootstrapReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: DbBootstrapReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionExportIdentityParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar AdapterDatabaseSessionExportIdentityResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n IdentityExportReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: IdentityExportReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionImportIdentityParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n {\n const list = v.rows ?? [];\n const items = s.initStructList(0, list.length, 1, 1);\n for (let i = 0; i < items.length; i++) {\n IdentityHighWaterCodec.write(items[i], list[i], caps);\n }\n }\n },\n read(s, caps) {\n return {\n rows: s.getStructList(0, 1, 1).map((item) => IdentityHighWaterCodec.read(item, caps))\n };\n }\n};\nvar AdapterDatabaseSessionImportIdentityResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionListUserRelationsParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar AdapterDatabaseSessionListUserRelationsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n UserRelationsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: UserRelationsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionPrepareUnitRestoreParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar AdapterDatabaseSessionPrepareUnitRestoreResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionDropUserRelationsParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setTextList(0, v.names ?? []);\n },\n read(s, caps) {\n void caps;\n return {\n names: s.getTextList(0)\n };\n }\n};\nvar AdapterDatabaseSessionDropUserRelationsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionAssertRestoreConstraintsParamsCodec = {\n dataWords: 0,\n pointerCount: 0,\n write(s, v, caps) {\n void s;\n void v;\n void caps;\n },\n read(s, caps) {\n void caps;\n void s;\n return {};\n }\n};\nvar AdapterDatabaseSessionAssertRestoreConstraintsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n EmptyReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: EmptyReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar AdapterDatabaseSessionExecuteStreamedParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.request != null) {\n AdapterExecuteRequestCodec.write(s.initStruct(0, 2, 4), v.request, caps);\n }\n },\n read(s, caps) {\n return {\n request: AdapterExecuteRequestCodec.read(s.getStruct(0, 2, 4), caps)\n };\n }\n};\nvar AdapterDatabaseSessionExecuteStreamedResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n ExecuteStreamReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: ExecuteStreamReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\nvar PluginWorkerDatabaseMigrationsParamsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n void caps;\n s.setText(0, v.binding ?? \"\");\n },\n read(s, caps) {\n void caps;\n return {\n binding: s.getText(0)\n };\n }\n};\nvar PluginWorkerDatabaseMigrationsResultsCodec = {\n dataWords: 0,\n pointerCount: 1,\n write(s, v, caps) {\n if (v.result != null) {\n PluginMigrationsReplyCodec.write(s.initStruct(0, 1, 1), v.result, caps);\n }\n },\n read(s, caps) {\n return {\n result: PluginMigrationsReplyCodec.read(s.getStruct(0, 1, 1), caps)\n };\n }\n};\n\n// dist/db-value.js\nvar KINDS = /* @__PURE__ */ new Set([\"null\", \"boolean\", \"int64\", \"float64\", \"text\", \"bytes\"]);\nvar TYPES = new Set(DB_TYPES);\nfunction requirePortableText(text) {\n if (text.includes(\"\\0\")) {\n throw new Error(\"BookclerkSQL TEXT cannot contain U+0000 (use BYTES/BLOB for binary)\");\n }\n return text;\n}\nvar I64_MIN = -0x8000000000000000n;\nvar I64_MAX = 0x7fffffffffffffffn;\nvar DB_TYPE_FROM_ORD = DB_TYPES;\nvar DB_TYPE_ORD = Object.fromEntries(DB_TYPES.map((ty, ord2) => [ty, ord2]));\nfunction parseDbValue(raw) {\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(\"DbValue must be an object\");\n }\n const obj = raw;\n if (typeof obj.kind !== \"string\" || !KINDS.has(obj.kind)) {\n throw new Error(`unknown DbValue union member: ${String(obj.kind)}`);\n }\n switch (obj.kind) {\n case \"null\":\n if (typeof obj.value !== \"string\" || !TYPES.has(obj.value)) {\n throw new Error(\"typed null requires a DbType\");\n }\n return { kind: \"null\", value: obj.value };\n case \"boolean\":\n if (typeof obj.value !== \"boolean\") {\n throw new Error(\"boolean DbValue requires a boolean\");\n }\n return { kind: \"boolean\", value: obj.value };\n case \"int64\":\n return { kind: \"int64\", value: parseInt64(obj.value) };\n case \"float64\":\n if (typeof obj.value !== \"number\" || !Number.isFinite(obj.value)) {\n throw new Error(\"float64 value is not finite\");\n }\n return { kind: \"float64\", value: obj.value };\n case \"text\":\n if (typeof obj.value !== \"string\") {\n throw new Error(\"text DbValue requires a string\");\n }\n requirePortableText(obj.value);\n return { kind: \"text\", value: obj.value };\n case \"bytes\":\n return { kind: \"bytes\", value: parseBytes(obj.value) };\n default:\n throw new Error(`unknown DbValue union member: ${obj.kind}`);\n }\n}\nfunction encodeDbValue(value) {\n const msg = new CapnpMessage();\n const root = msg.initRoot(2, 1);\n writeDbValue(root, value);\n return msg.finish();\n}\nfunction decodeDbValue(bytes) {\n const reader = new CapnpReader(bytes);\n return readDbValue(reader.root(2, 1));\n}\nfunction writeDbValue(root, value) {\n switch (value.kind) {\n case \"null\":\n root.setUint16(0, DB_TYPE_ORD[value.value]);\n root.setUint16(1, 0);\n return;\n case \"boolean\":\n root.setBool(0, value.value);\n root.setUint16(1, 1);\n return;\n case \"int64\":\n if (value.value < I64_MIN || value.value > I64_MAX) {\n throw new Error(\"int64 DbValue is out of range\");\n }\n root.setInt64(1, value.value);\n root.setUint16(1, 2);\n return;\n case \"float64\":\n if (!Number.isFinite(value.value)) {\n throw new Error(\"float64 value is not finite\");\n }\n root.setFloat64(1, value.value);\n root.setUint16(1, 3);\n return;\n case \"text\":\n requirePortableText(value.value);\n root.setUint16(1, 4);\n root.setText(0, value.value);\n return;\n case \"bytes\":\n root.setUint16(1, 5);\n root.setData(0, value.value);\n return;\n default: {\n const _exhaustive = value;\n throw new Error(`unknown DbValue union member: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\nfunction readDbValue(root) {\n const disc = root.getUint16(1);\n switch (disc) {\n case 0: {\n const ty = DB_TYPE_FROM_ORD[root.getUint16(0)];\n if (ty === void 0) {\n throw new Error(\"unknown DbType\");\n }\n return { kind: \"null\", value: ty };\n }\n case 1:\n return { kind: \"boolean\", value: root.getBool(0) };\n case 2:\n return { kind: \"int64\", value: root.getInt64(1) };\n case 3: {\n const n = root.getFloat64(1);\n if (!Number.isFinite(n)) {\n throw new Error(\"float64 value is not finite\");\n }\n return { kind: \"float64\", value: n };\n }\n case 4:\n return { kind: \"text\", value: requirePortableText(root.getText(0)) };\n case 5:\n return { kind: \"bytes\", value: root.getData(0) };\n default:\n throw new Error(`unknown DbValue union member: ${disc}`);\n }\n}\nfunction parseInt64(raw) {\n let n;\n if (typeof raw === \"bigint\") {\n n = raw;\n } else if (typeof raw === \"number\") {\n if (!Number.isInteger(raw) || !Number.isFinite(raw)) {\n throw new Error(\"int64 DbValue requires an integer\");\n }\n n = BigInt(raw);\n } else if (typeof raw === \"string\") {\n if (!/^-?\\d+$/.test(raw)) {\n throw new Error(\"int64 DbValue requires an integer\");\n }\n n = BigInt(raw);\n } else {\n throw new Error(\"int64 DbValue requires an integer\");\n }\n if (n < I64_MIN || n > I64_MAX) {\n throw new Error(\"int64 DbValue is out of range\");\n }\n return n;\n}\nfunction parseBytes(raw) {\n if (raw instanceof Uint8Array) {\n return raw;\n }\n if (typeof raw !== \"string\") {\n throw new Error(\"bytes DbValue requires bytes\");\n }\n if (!raw.startsWith(\"b64:\")) {\n throw new Error(\"bytes DbValue requires bytes\");\n }\n return decodeBase64(raw.slice(4));\n}\nfunction decodeBase64(b64) {\n const bin = globalThis.atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) {\n out[i] = bin.charCodeAt(i);\n }\n return out;\n}\n\n// dist/db-stream.js\nvar ROWS_FRAME = 2;\nfunction streamsResults(caps) {\n return caps.maxStreamedResultBytes > 0 && caps.maxStreamedResultRows > 0;\n}\nfunction executeStreamLimits(caps) {\n if (streamsResults(caps)) {\n return {\n maxBytes: caps.maxStreamedResultBytes,\n bytesLimit: \"maxStreamedResultBytes\",\n maxRows: caps.maxStreamedResultRows,\n rowsLimit: \"maxStreamedResultRows\"\n };\n }\n return {\n maxBytes: caps.maxAtomicResultBytes,\n bytesLimit: \"maxAtomicResultBytes\",\n maxRows: caps.maxResultRows,\n rowsLimit: \"maxResultRows\"\n };\n}\nfunction rawStreamCeiling(limits) {\n return limits.maxBytes + Math.floor(limits.maxBytes / 8) + MAX_STREAM_WINDOW_BYTES;\n}\nvar ExecuteStreamDecoder = class {\n #limits;\n #retainRows;\n /** Bytes not yet consumed: `#buf[0, #len)`; the rest is spare capacity. */\n #buf = new Uint8Array(0);\n /** Bytes of `#buf` in use. */\n #len = 0;\n #seen = 0;\n #state = { kind: \"awaitingHead\" };\n #columns = [];\n /**\n * @param limits - Budget the stream is held to.\n * @param options - `retainRows: false` counts rows against the budget but\n * drops them from the collected reply (for `iterate()`).\n */\n constructor(limits, options = {}) {\n this.#limits = limits;\n this.#retainRows = options.retainRows ?? true;\n }\n /**\n * Whether the final frame (`end` or `err`) has been decoded.\n *\n * @returns True once the stream is complete.\n */\n get finished() {\n return this.#state.kind === \"finished\";\n }\n /**\n * Columns of the statement whose rows are arriving.\n *\n * @returns The open statement\'s columns, or an empty list between statements.\n */\n get columns() {\n return this.#columns;\n }\n /**\n * Feeds the next bytes of the stream.\n *\n * @param bytes - Any slice of the frame sequence.\n * @returns The frames completed by these bytes, in order.\n * @throws `PluginError` `limit_exceeded` when the stream exceeds the byte\n * or row budget, `invalid_params` when a frame is malformed or out of\n * sequence or bytes follow the final frame.\n */\n push(bytes) {\n try {\n return this.#push(bytes);\n } catch (err) {\n if (err instanceof PluginError) {\n this.#columns = [];\n this.#state = { kind: \"finished\", outcome: { err } };\n }\n throw err;\n }\n }\n /**\n * `push` before its failure is latched.\n *\n * @param bytes - Any slice of the frame sequence.\n * @returns The frames completed by these bytes, in order.\n * @throws See {@link ExecuteStreamDecoder.push}.\n */\n #push(bytes) {\n const frames = [];\n if (bytes.byteLength === 0) {\n return frames;\n }\n if (this.finished) {\n throw PluginError.fromWire(\"invalid_params\", \"streamed reply carries bytes after its final frame\");\n }\n this.#seen += bytes.byteLength;\n const ceiling = rawStreamCeiling(this.#limits);\n if (this.#seen > ceiling) {\n throw this.#bytesExceeded(this.#seen);\n }\n this.#append(bytes);\n let at = 0;\n while (this.#len - at >= 8) {\n const view = new DataView(this.#buf.buffer, this.#buf.byteOffset + at, 8);\n if (view.getUint32(0, true) !== 0) {\n throw PluginError.fromWire(\"invalid_params\", \"streamed reply frame is not a single-segment Cap\'n message\");\n }\n const frameLen = view.getUint32(4, true) * 8 + 8;\n if (frameLen > ceiling) {\n throw this.#bytesExceeded(frameLen);\n }\n if (this.#len - at < frameLen) {\n break;\n }\n const frame2 = decodeFrame(this.#buf.slice(at, at + frameLen), ceiling, (count) => this.#admitRows(count));\n at += frameLen;\n this.#apply(frame2);\n frames.push(frame2);\n if (this.finished) {\n if (this.#len > at) {\n throw PluginError.fromWire(\"invalid_params\", \"streamed reply carries bytes after its final frame\");\n }\n break;\n }\n }\n this.#consume(at);\n return frames;\n }\n /**\n * Appends `bytes` to the unconsumed remainder.\n *\n * The backing store grows geometrically, so a frame that arrives in many\n * small chunks is copied a bounded number of times rather than once per\n * chunk. A push onto an empty remainder is held as is, without a copy.\n *\n * @param bytes - The pushed bytes.\n */\n #append(bytes) {\n if (this.#len === 0) {\n this.#buf = bytes;\n this.#len = bytes.byteLength;\n return;\n }\n const need = this.#len + bytes.byteLength;\n if (need > this.#buf.byteLength) {\n const grown = new Uint8Array(Math.max(need, this.#buf.byteLength * 2));\n grown.set(this.#buf.subarray(0, this.#len), 0);\n this.#buf = grown;\n }\n this.#buf.set(bytes, this.#len);\n this.#len = need;\n }\n /**\n * Drops the first `at` bytes of the remainder.\n *\n * A remainder consumed whole releases its backing store, so a completed\n * decoder an author keeps does not pin the last chunk it was pushed.\n *\n * @param at - Bytes consumed from the front.\n */\n #consume(at) {\n if (at === 0) {\n return;\n }\n if (at === this.#len) {\n this.#buf = new Uint8Array(0);\n this.#len = 0;\n return;\n }\n const rest = this.#buf.slice(at, this.#len);\n this.#buf = rest;\n this.#len = rest.byteLength;\n }\n /**\n * Takes the reassembled reply once the stream has ended.\n *\n * @returns The reply the frames described.\n * @throws The adapter\'s `PluginError` when the stream ended with `err`, and\n * `unavailable` when it ended before its final frame.\n */\n finish() {\n if (this.#state.kind !== \"finished\") {\n throw PluginError.fromWire(\"unavailable\", \"streamed reply ended before its final frame\");\n }\n const outcome = this.#state.outcome;\n if (\"err\" in outcome) {\n throw outcome.err;\n }\n return outcome.ok;\n }\n /**\n * The typed error for a stream over its byte budget.\n *\n * @param used - Bytes seen or declared.\n * @returns `limit_exceeded` naming the budget\'s capability field.\n */\n #bytesExceeded(used) {\n return PluginError.limitExceeded({\n limit: this.#limits.bytesLimit,\n cap: this.#limits.maxBytes,\n used\n });\n }\n /**\n * The error for a frame out of sequence.\n *\n * @param message - What the stream did, completing \"streamed reply \u{2026}\".\n * @returns `invalid_params`.\n */\n #sequence(message) {\n return PluginError.fromWire(\"invalid_params\", `streamed reply ${message}`);\n }\n /**\n * Admits a rows frame by its row count before any of its cells decode, so\n * a frame past the row cap (or out of sequence) is refused without\n * materializing the rows it carries.\n *\n * @param count - Rows the frame announces.\n * @throws `PluginError` `invalid_params` when no statement is open,\n * `limit_exceeded` when the rows would pass the statement\'s row cap.\n */\n #admitRows(count) {\n const state = this.#state;\n if (state.kind !== \"inReply\" || !state.open) {\n throw this.#sequence(\"carries rows before a statement frame\");\n }\n const used = state.openRows + count;\n if (this.#limits.maxRows > 0 && used > this.#limits.maxRows) {\n throw PluginError.limitExceeded({\n limit: this.#limits.rowsLimit,\n cap: this.#limits.maxRows,\n used\n });\n }\n }\n /**\n * Advances the sequence by one decoded frame: opens the reply on `head`,\n * a statement on `statement`, counts (and keeps, when retained) `rows`,\n * and closes the reply on `end` or `err`.\n *\n * @param frame - The frame just decoded.\n * @throws `PluginError` `invalid_params` when the frame is out of sequence\n * or a cell is not a valid `DbValue`, `limit_exceeded` past the row cap.\n */\n #apply(frame2) {\n const state = this.#state;\n if (frame2.kind === \"err\") {\n this.#columns = [];\n this.#state = {\n kind: \"finished\",\n outcome: {\n err: PluginError.fromWire(frame2.value.code, frame2.value.message, frame2.value.details)\n }\n };\n return;\n }\n if (state.kind === \"awaitingHead\") {\n if (frame2.kind !== \"head\") {\n throw this.#sequence(`opens with a ${frame2.kind} frame instead of head`);\n }\n this.#state = {\n kind: \"inReply\",\n operationId: frame2.value.operationId,\n statementCount: frame2.value.statementCount,\n nextIndex: 0,\n statements: [],\n open: void 0,\n openRows: 0\n };\n return;\n }\n if (state.kind === \"finished\") {\n throw this.#sequence(\"carries a frame after its final frame\");\n }\n switch (frame2.kind) {\n case \"head\":\n throw this.#sequence(\"carries a second head frame\");\n case \"statement\": {\n if (frame2.value.index !== state.nextIndex) {\n throw this.#sequence(`statement frame ${frame2.value.index} arrived where ${state.nextIndex} was expected`);\n }\n if (state.nextIndex >= state.statementCount) {\n throw this.#sequence(`carries more statements than its head announced`);\n }\n if (state.open) {\n state.statements.push(state.open);\n }\n state.open = {\n rows: [],\n columns: frame2.value.columns,\n rowsAffected: frame2.value.rowsAffected\n };\n state.openRows = 0;\n state.nextIndex += 1;\n this.#columns = frame2.value.columns;\n return;\n }\n case \"rows\": {\n const open = state.open;\n if (!open) {\n throw this.#sequence(\"carries rows before a statement frame\");\n }\n for (const row of frame2.value) {\n if (row.values.length !== open.columns.length) {\n throw this.#sequence(`carries a row of ${row.values.length} cells for ${open.columns.length} columns`);\n }\n for (const cell of row.values) {\n validateCell(cell);\n }\n }\n state.openRows += frame2.value.length;\n if (this.#limits.maxRows > 0 && state.openRows > this.#limits.maxRows) {\n throw PluginError.limitExceeded({\n limit: this.#limits.rowsLimit,\n cap: this.#limits.maxRows,\n used: state.openRows\n });\n }\n if (this.#retainRows) {\n for (const row of frame2.value) {\n open.rows.push(row);\n }\n }\n return;\n }\n case \"end\": {\n if (state.open) {\n state.statements.push(state.open);\n state.open = void 0;\n }\n if (state.statements.length !== state.statementCount) {\n throw this.#sequence(`ended with ${state.statements.length} statements; its head announced ${state.statementCount}`);\n }\n this.#columns = [];\n this.#state = {\n kind: \"finished\",\n outcome: {\n ok: {\n operationId: state.operationId,\n statements: state.statements,\n timing: frame2.value\n }\n }\n };\n return;\n }\n }\n }\n};\nfunction decodeExecuteStream(bytes, limits) {\n const decoder = new ExecuteStreamDecoder(limits);\n decoder.push(bytes);\n return decoder.finish();\n}\nasync function collectExecuteStream(chunks, limits) {\n const decoder = new ExecuteStreamDecoder(limits);\n for await (const chunk of chunks) {\n decoder.push(chunk);\n }\n return decoder.finish();\n}\nasync function* streamChunks(body) {\n if (!body) {\n return;\n }\n const reader = body.getReader();\n let drained = false;\n try {\n for (; ; ) {\n const { done, value } = await reader.read();\n if (done) {\n drained = true;\n return;\n }\n if (value) {\n yield value;\n }\n }\n } finally {\n if (!drained) {\n await reader.cancel().catch(() => void 0);\n }\n reader.releaseLock();\n }\n}\nfunction validateCell(cell) {\n if (cell.kind === \"float64\" && !Number.isFinite(cell.value)) {\n throw PluginError.fromWire(\"invalid_params\", \"streamed reply float64 cell is not finite\");\n }\n if (cell.kind === \"text\" && cell.value.includes(\"\\0\")) {\n throw PluginError.fromWire(\"invalid_params\", \"streamed reply TEXT cell contains U+0000\");\n }\n}\nfunction decodeFrame(bytes, ceiling, admitRows) {\n const words = Math.min(Math.floor(bytes.byteLength / 8) + 16, Math.floor(Math.max(ceiling, MAX_SCALAR_BYTES) / 8));\n try {\n const reader = new CapnpReader(bytes, words);\n const root = reader.root(ExecuteStreamFrameCodec.dataWords, ExecuteStreamFrameCodec.pointerCount);\n if (root.getUint16(0) === ROWS_FRAME) {\n admitRows(root.getStructListLength(0));\n }\n return ExecuteStreamFrameCodec.read(root, NO_CAPS);\n } catch (err) {\n if (err instanceof PluginError) {\n throw err;\n }\n throw PluginError.fromWire(\"invalid_params\", `streamed reply frame does not decode: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n// dist/guest-sql.js\nfunction identStart(c) {\n const code = c.charCodeAt(0);\n return code >= 65 && code <= 90 || code >= 97 && code <= 122 || c === \"_\";\n}\nfunction identCont(c) {\n return identStart(c) || c >= \"0\" && c <= \"9\";\n}\nfunction skipWsComments(sql, start) {\n let i = start;\n while (i < sql.length) {\n while (i < sql.length && /\\s/.test(sql[i])) {\n i += 1;\n }\n if (sql[i] === \"-\" && sql[i + 1] === \"-\") {\n i += 2;\n while (i < sql.length && sql[i] !== \"\\n\") {\n i += 1;\n }\n continue;\n }\n if (sql[i] === \"/\" && sql[i + 1] === \"*\") {\n i += 2;\n while (i + 1 < sql.length && !(sql[i] === \"*\" && sql[i + 1] === \"/\")) {\n i += 1;\n }\n i = Math.min(i + 2, sql.length);\n continue;\n }\n break;\n }\n return i;\n}\nfunction keywordAt(sql, i, kw) {\n if (i + kw.length > sql.length) {\n return false;\n }\n if (sql.slice(i, i + kw.length).toLowerCase() !== kw.toLowerCase()) {\n return false;\n }\n const beforeOk = i === 0 || !identCont(sql[i - 1]);\n const after = sql[i + kw.length] ?? \" \";\n return beforeOk && !identCont(after);\n}\nfunction skipIdentOrQuoted(sql, i) {\n const c = sql[i];\n if (c === void 0) {\n return null;\n }\n if (c === \'\"\' || c === \"`\" || c === \"[\") {\n const end = c === \"[\" ? \"]\" : c;\n let j = i + 1;\n while (j < sql.length) {\n if (sql[j] === end) {\n if (end !== \"]\" && sql[j + 1] === end) {\n j += 2;\n continue;\n }\n return j + 1;\n }\n j += 1;\n }\n return null;\n }\n if (identStart(c)) {\n let j = i + 1;\n while (j < sql.length && identCont(sql[j])) {\n j += 1;\n }\n return j;\n }\n return null;\n}\nfunction skipBalancedParens(sql, start) {\n if (sql[start] !== \"(\") {\n return null;\n }\n let depth = 0;\n let end = null;\n forEachUnquoted(sql.slice(start), (slice, idx) => {\n if (end !== null) {\n return 1;\n }\n const c = slice[idx];\n if (c === \"(\") {\n depth += 1;\n } else if (c === \")\") {\n depth -= 1;\n if (depth === 0) {\n end = start + idx + 1;\n }\n }\n return 1;\n });\n return end;\n}\nfunction sqlAfterLeadingCtes(sql) {\n let i = skipWsComments(sql, 0);\n if (!keywordAt(sql, i, \"WITH\")) {\n return sql;\n }\n i += 4;\n i = skipWsComments(sql, i);\n if (keywordAt(sql, i, \"RECURSIVE\")) {\n i += 9;\n i = skipWsComments(sql, i);\n }\n for (; ; ) {\n const next = skipIdentOrQuoted(sql, i);\n if (next === null) {\n return sql;\n }\n i = skipWsComments(sql, next);\n if (sql[i] === \"(\") {\n const after = skipBalancedParens(sql, i);\n if (after === null) {\n return sql;\n }\n i = skipWsComments(sql, after);\n }\n if (!keywordAt(sql, i, \"AS\")) {\n return sql;\n }\n i = skipWsComments(sql, i + 2);\n if (keywordAt(sql, i, \"NOT\")) {\n const afterNot = skipWsComments(sql, i + 3);\n if (keywordAt(sql, afterNot, \"MATERIALIZED\")) {\n i = skipWsComments(sql, afterNot + 12);\n }\n } else if (keywordAt(sql, i, \"MATERIALIZED\")) {\n i = skipWsComments(sql, i + 12);\n }\n if (sql[i] !== \"(\") {\n return sql;\n }\n const afterBody = skipBalancedParens(sql, i);\n if (afterBody === null) {\n return sql;\n }\n i = skipWsComments(sql, afterBody);\n if (sql[i] === \",\") {\n i = skipWsComments(sql, i + 1);\n continue;\n }\n return sql.slice(i);\n }\n}\nfunction forEachUnquoted(sql, step) {\n let i = 0;\n let inS = false;\n let inD = false;\n let inLine = false;\n let inBlock = false;\n while (i < sql.length) {\n const c = sql[i];\n if (inLine) {\n if (c === \"\\n\") {\n inLine = false;\n }\n i += 1;\n continue;\n }\n if (inBlock) {\n if (c === \"*\" && sql[i + 1] === \"/\") {\n inBlock = false;\n i += 2;\n continue;\n }\n i += 1;\n continue;\n }\n if (inS) {\n if (c === \"\'\") {\n if (sql[i + 1] === \"\'\") {\n i += 2;\n continue;\n }\n inS = false;\n }\n i += 1;\n continue;\n }\n if (inD) {\n if (c === \'\"\') {\n if (sql[i + 1] === \'\"\') {\n i += 2;\n continue;\n }\n inD = false;\n }\n i += 1;\n continue;\n }\n if (c === \"-\" && sql[i + 1] === \"-\") {\n inLine = true;\n i += 2;\n continue;\n }\n if (c === \"/\" && sql[i + 1] === \"*\") {\n inBlock = true;\n i += 2;\n continue;\n }\n if (c === \"\'\") {\n inS = true;\n i += 1;\n continue;\n }\n if (c === \'\"\') {\n inD = true;\n i += 1;\n continue;\n }\n const n = Math.max(1, step(sql, i));\n i += n;\n }\n}\nfunction forEachTopLevelKeyword(sql, onKeyword) {\n let depth = 0;\n forEachUnquoted(sql, (slice, idx) => {\n const c = slice[idx];\n if (c === \"(\") {\n depth += 1;\n return 1;\n }\n if (c === \")\") {\n depth = Math.max(0, depth - 1);\n return 1;\n }\n if (depth === 0 && identStart(c)) {\n let j = idx + 1;\n while (j < slice.length && identCont(slice[j])) {\n j += 1;\n }\n onKeyword(idx, slice.slice(idx, j));\n return j - idx;\n }\n return 1;\n });\n}\nfunction hasTopLevelKeyword(sql, keyword) {\n const want = keyword.toUpperCase();\n let found = false;\n forEachTopLevelKeyword(sql, (_, kw) => {\n if (kw.toUpperCase() === want) {\n found = true;\n }\n });\n return found;\n}\nfunction firstTopLevelKeyword(sql) {\n let first;\n forEachTopLevelKeyword(sql, (_, kw) => {\n if (first === void 0) {\n first = kw.toUpperCase();\n }\n });\n return first;\n}\nfunction guestStatementKind(sql) {\n const main = sqlAfterLeadingCtes(sql);\n if (hasTopLevelKeyword(main, \"RETURNING\")) {\n return \"returning\";\n }\n const verb = firstTopLevelKeyword(main);\n if (verb === \"SELECT\" || verb === \"VALUES\") {\n return \"select\";\n }\n return \"execute\";\n}\nfunction splitExecQueries(query) {\n return query.split(\"\\n\").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => stripTrailingSemicolons(line).trim()).filter((line) => line.length > 0);\n}\nfunction stripTrailingSemicolons(line) {\n let end = line.length;\n while (end > 0 && line[end - 1] === \";\") {\n end -= 1;\n }\n return line.slice(0, end);\n}\n\n// dist/db-execute.js\nvar KIND_FROM = DB_STATEMENT_KINDS;\nvar KIND_ORD = Object.fromEntries(DB_STATEMENT_KINDS.map((kind, ord2) => [kind, ord2]));\nvar SELECT_FROM = DB_RESULT_SELECTIONS;\nvar SELECT_ORD = Object.fromEntries(DB_RESULT_SELECTIONS.map((sel, ord2) => [sel, ord2]));\nvar COL_TYPE_FROM = DB_TYPES;\nvar COL_TYPE_ORD = Object.fromEntries(DB_TYPES.map((ty, ord2) => [ty, ord2]));\nvar MAX_WRITE_KEY_BYTES = 256;\nvar WriteChunksError = class extends PluginError {\n /** Statements committed before the failure; resume with `from: next`. */\n next;\n /**\n * @param next - Statements committed before the failure.\n * @param cause - The failed batch\'s error, whose code, message and details\n * this error carries.\n */\n constructor(next, cause) {\n super(cause.wireCode, cause.message, cause.details);\n this.name = \"WriteChunksError\";\n this.next = next;\n }\n};\nasync function writeChunksOperationId(key, offset) {\n const bytes = new TextEncoder().encode(`bookclerk-write-chunks\\0${key}\\0${String(offset)}`);\n let hex;\n if (globalThis.crypto?.subtle) {\n hex = hexBytes(new Uint8Array(await globalThis.crypto.subtle.digest(\"SHA-256\", bytes)));\n } else {\n const { createHash } = await import(\"node:crypto\");\n hex = createHash(\"sha256\").update(bytes).digest(\"hex\");\n }\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;\n}\nfunction encodeExecuteRequest(request) {\n if (request.statements.length === 0) {\n throw new Error(\"execute statements must be non-empty\");\n }\n const msg = new CapnpMessage();\n const root = msg.initRoot(4, 3);\n root.setText(0, request.operationId);\n root.setText(1, request.requestHash);\n root.setUint64(3, BigInt(request.deadlineUnixMs));\n const stmts = root.initStructList(2, request.statements.length, 1, 2);\n for (let i = 0; i < request.statements.length; i++) {\n writeStatement(stmts[i], request.statements[i]);\n }\n return msg.finish();\n}\nfunction decodeExecuteRequest(bytes) {\n const reader = new CapnpReader(bytes);\n const root = reader.root(4, 3);\n const stmtStructs = root.getStructList(2, 1, 2);\n if (stmtStructs.length === 0) {\n throw new Error(\"execute statements must be non-empty\");\n }\n return {\n operationId: root.getText(0),\n requestHash: root.getText(1),\n statements: stmtStructs.map(readStatement),\n deadlineUnixMs: Number(root.getUint64(3))\n };\n}\nfunction encodeExecuteReply(reply) {\n const msg = new CapnpMessage();\n const root = msg.initRoot(0, 3);\n writeExecuteReply(root, reply);\n return msg.finish();\n}\nfunction encodeExecuteResultReply(outcome) {\n const msg = new CapnpMessage();\n const root = msg.initRoot(1, 1);\n if (\"ok\" in outcome) {\n root.setUint16(0, 0);\n writeExecuteReply(root.initStruct(0, 0, 3), outcome.ok);\n } else {\n root.setUint16(0, 1);\n const err = root.initStruct(0, 0, 3);\n err.setText(0, outcome.err.code);\n err.setText(1, outcome.err.message);\n err.setText(2, outcome.err.details ?? \"\");\n }\n return msg.finish();\n}\nfunction decodeExecuteResultReply(bytes) {\n const root = new CapnpReader(bytes).root(1, 1);\n const disc = root.getUint16(0);\n if (disc === 0) {\n return readExecuteReply(root.getStruct(0, 0, 3));\n }\n if (disc === 1) {\n const err = root.getStruct(0, 0, 3);\n throw PluginError.fromWire(err.getText(0), err.getText(1), err.getText(2));\n }\n throw new Error(\"unknown ExecuteResultReply union member\");\n}\nfunction encodeDbCapabilitiesReply(outcome) {\n return encodeMessage(DbCapabilitiesReplyCodec, \"ok\" in outcome ? { kind: \"ok\", value: outcome.ok } : {\n kind: \"err\",\n value: {\n code: outcome.err.code,\n message: outcome.err.message,\n details: outcome.err.details ?? \"\"\n }\n });\n}\nfunction decodeDbCapabilitiesReply(bytes) {\n const reply = decodeMessage(DbCapabilitiesReplyCodec, bytes);\n if (reply.kind === \"ok\") {\n return reply.value;\n }\n throw PluginError.fromWire(reply.value.code, reply.value.message, reply.value.details);\n}\nfunction statementResultToD1Result(stmt, timing) {\n const changes = stmt.rowsAffected;\n const durationMs = timing.dbExecutionUs / 1e3;\n const results = stmt.columns.length > 0 ? stmt.rows.map((row) => {\n const obj = {};\n for (let i = 0; i < stmt.columns.length; i++) {\n obj[stmt.columns[i].name] = row.values[i];\n }\n return obj;\n }) : null;\n return {\n success: true,\n results,\n meta: {\n duration: durationMs,\n changes,\n last_row_id: 0,\n changed_db: changes > 0,\n rows_read: stmt.rows.length,\n rows_written: changes\n }\n };\n}\nfunction executeReplyToD1Results(reply) {\n return reply.statements.map((stmt) => statementResultToD1Result(stmt, reply.timing));\n}\nfunction rowMapFromStatement(result) {\n if (result.rows.length === 0) {\n return null;\n }\n const row = {};\n for (let i = 0; i < result.columns.length; i++) {\n row[result.columns[i].name] = result.rows[0].values[i];\n }\n return row;\n}\nfunction columnValueFromRow(row, colName) {\n if (colName in row) {\n return row[colName];\n }\n const lower = colName.toLowerCase();\n for (const [name, value] of Object.entries(row)) {\n if (name.toLowerCase() === lower) {\n return value;\n }\n }\n throw new Error(`column ${colName} not found in first() result`);\n}\nfunction writeExecuteReply(root, reply) {\n root.setText(0, reply.operationId);\n const stmts = root.initStructList(1, reply.statements.length, 1, 2);\n for (let i = 0; i < reply.statements.length; i++) {\n writeStatementResult(stmts[i], reply.statements[i]);\n }\n const timing = root.initStruct(2, 2, 1);\n timing.setUint64(0, BigInt(reply.timing.attemptElapsedUs));\n timing.setUint64(1, BigInt(reply.timing.dbExecutionUs));\n timing.setText(0, reply.timing.dbTimingSource);\n}\nfunction readExecuteReply(root) {\n return {\n operationId: root.getText(0),\n statements: root.getStructList(1, 1, 2).map(readStatementResult),\n timing: (() => {\n const t = root.getStruct(2, 2, 1);\n return {\n attemptElapsedUs: Number(t.getUint64(0)),\n dbExecutionUs: Number(t.getUint64(1)),\n dbTimingSource: t.getText(0)\n };\n })()\n };\n}\nfunction writeStatementResult(s, stmt) {\n s.setUint64(0, BigInt(stmt.rowsAffected));\n const rows = s.initStructList(0, stmt.rows.length, 0, 1);\n for (let i = 0; i < stmt.rows.length; i++) {\n const cells = rows[i].initStructList(0, stmt.rows[i].values.length, 2, 1);\n for (let j = 0; j < stmt.rows[i].values.length; j++) {\n writeDbValue(cells[j], stmt.rows[i].values[j]);\n }\n }\n const cols = s.initStructList(1, stmt.columns.length, 1, 1);\n for (let i = 0; i < stmt.columns.length; i++) {\n cols[i].setText(0, stmt.columns[i].name);\n cols[i].setUint16(0, COL_TYPE_ORD[stmt.columns[i].dbType]);\n }\n}\nfunction readStatementResult(s) {\n const columns = s.getStructList(1, 1, 1).map((c) => {\n const ty = COL_TYPE_FROM[c.getUint16(0)];\n if (ty === void 0) {\n throw new Error(\"unknown DbType\");\n }\n return { name: c.getText(0), dbType: ty };\n });\n const rows = s.getStructList(0, 0, 1).map((row) => ({\n values: row.getStructList(0, 2, 1).map(readDbValue)\n }));\n return {\n rows,\n columns,\n rowsAffected: Number(s.getUint64(0))\n };\n}\nfunction createDatabaseBinding(transport, options = {}) {\n let cachedLimits;\n const sessionLimits = () => {\n if (cachedLimits === void 0) {\n try {\n cachedLimits = transport.limits === void 0 ? Promise.resolve(null) : transport.limits().catch(() => null);\n } catch {\n cachedLimits = Promise.resolve(null);\n }\n }\n return cachedLimits;\n };\n const requestFor = async (batch, retry) => {\n if (!Array.isArray(batch) || batch.length === 0) {\n throw new Error(\"execute statements must be non-empty\");\n }\n const request = await executeRequestFromBatch(batch, options, retry);\n const encoded = encodeExecuteRequest(request);\n const cap = tighterCap(options.maxRequestBytes ?? 0, (await sessionLimits())?.maxRequestBytes ?? 0);\n if (cap > 0 && encoded.byteLength > cap) {\n throw PluginError.limitExceeded({\n limit: \"maxRequestBytes\",\n cap,\n used: encoded.byteLength\n });\n }\n return request;\n };\n const openStreamed = async (request) => {\n if (transport.executeStreamed === void 0) {\n return void 0;\n }\n const caps = await sessionLimits();\n if (caps === null || !streamsResults(caps)) {\n return void 0;\n }\n let body;\n try {\n body = await transport.executeStreamed(request);\n } catch (err) {\n if (err instanceof PluginError && err.wireCode === \"unsupported\") {\n return void 0;\n }\n throw err;\n }\n const chunks = body instanceof Uint8Array ? (async function* one() {\n yield body;\n })() : streamChunks(body);\n return { chunks, caps };\n };\n const runExecute = async (batch, retry) => {\n const request = await requestFor(batch, retry);\n const streamed = await openStreamed(request);\n if (streamed === void 0) {\n return replyFor(request, await transport.execute(request));\n }\n const decoder = new ExecuteStreamDecoder(executeStreamLimits(streamed.caps));\n for await (const chunk of streamed.chunks) {\n decoder.push(chunk);\n }\n let reply;\n try {\n reply = decoder.finish();\n } catch (err) {\n if (err instanceof PluginError && err.wireCode === \"unsupported\") {\n return replyFor(request, await transport.execute(request));\n }\n throw err;\n }\n return replyFor(request, reply);\n };\n const inlineRows = async function* (request) {\n const reply = replyFor(request, await transport.execute(request));\n const result = reply.statements[0];\n if (result) {\n for (const row of result.rows) {\n yield rowMap(result.columns, row);\n }\n }\n };\n const iterateRows = async function* (batch, retry) {\n const request = await requestFor(batch, retry);\n const streamed = await openStreamed(request);\n if (streamed === void 0) {\n yield* inlineRows(request);\n return;\n }\n const decoder = new ExecuteStreamDecoder(executeStreamLimits(streamed.caps), {\n retainRows: false\n });\n const fallsBackInline = (err, yielded2) => !yielded2 && err instanceof PluginError && err.wireCode === \"unsupported\";\n let columns = [];\n let yielded = false;\n for await (const chunk of streamed.chunks) {\n let frames;\n try {\n frames = decoder.push(chunk);\n } catch (err) {\n if (fallsBackInline(err, yielded)) {\n yield* inlineRows(request);\n return;\n }\n throw err;\n }\n for (const frame2 of frames) {\n if (frame2.kind === \"head\") {\n checkReplyIdentity(request, frame2.value.operationId, frame2.value.statementCount);\n } else if (frame2.kind === \"statement\") {\n columns = frame2.value.columns;\n } else if (frame2.kind === \"rows\") {\n for (const row of frame2.value) {\n yielded = true;\n yield rowMap(columns, row);\n }\n }\n }\n }\n try {\n decoder.finish();\n } catch (err) {\n if (fallsBackInline(err, yielded)) {\n yield* inlineRows(request);\n return;\n }\n throw err;\n }\n };\n const binding = {\n prepare(sql) {\n return makePrepared(binding, sql, [], options.maxResultRows ?? 0, defaultIntent(options));\n },\n batch(statements, opts) {\n const typed = statements.map((s) => s._asTyped());\n return runExecute(typed, opts?.retry).then(executeReplyToD1Results);\n },\n exec(query, opts) {\n const queries = splitExecQueries(query);\n if (queries.length === 0) {\n return Promise.reject(new Error(\"exec query is empty\"));\n }\n const prepared = queries.map((sql) => binding.prepare(sql));\n return binding.batch(prepared, opts).then((results) => ({\n count: results.length,\n duration: results.reduce((sum, r) => sum + r.meta.duration, 0)\n }));\n },\n execute(batch, opts) {\n return runExecute(batch, opts?.retry);\n },\n limits() {\n if (transport.limits === void 0) {\n return Promise.reject(PluginError.fromWire(\"unsupported\", \"GuestDatabase.limits is not available on this host\"));\n }\n return sessionLimits().then(async (caps) => {\n if (caps !== null) {\n return caps;\n }\n const fetched = await transport.limits();\n cachedLimits = Promise.resolve(fetched);\n return fetched;\n });\n },\n async *chunk(statements, opts) {\n const explicit = opts?.maxStatements !== void 0 && opts.maxRequestBytes !== void 0;\n const caps = explicit ? null : await sessionLimits();\n const maxStatements = opts?.maxStatements ?? caps?.maxStatements ?? 0;\n const maxRequestBytes = opts?.maxRequestBytes ?? tighterCap(caps?.maxRequestBytes ?? 0, options.maxRequestBytes ?? 0);\n if (!explicit && maxStatements <= 0 && maxRequestBytes <= 0) {\n throw PluginError.fromWire(\"unsupported\", \"chunk needs the session limits (GuestDatabase.limits) or explicit maxStatements / maxRequestBytes\");\n }\n const typed = statements.map((stmt) => stmt._asTyped());\n for (const indexes of chunkIndexes(typed, maxStatements, maxRequestBytes)) {\n yield indexes.map((i) => statements[i]);\n }\n },\n async writeChunks(statements, opts) {\n const from = opts.from ?? 0;\n const fail = (next2, err) => new WriteChunksError(next2, err instanceof PluginError ? err : PluginError.fromWire(\"internal\", String(err)));\n const keyBytes = new TextEncoder().encode(opts.key).byteLength;\n if (keyBytes === 0 || keyBytes > MAX_WRITE_KEY_BYTES) {\n throw fail(from, PluginError.fromWire(\"invalid_params\", `writeChunks key must be 1 to ${String(MAX_WRITE_KEY_BYTES)} bytes`));\n }\n if (!Number.isInteger(from) || from < 0 || from > statements.length) {\n throw fail(from, PluginError.fromWire(\"invalid_params\", `writeChunks from ${String(from)} is not within the ${String(statements.length)} statements`));\n }\n const caps = {};\n if (opts.maxStatements !== void 0) {\n caps.maxStatements = opts.maxStatements;\n }\n if (opts.maxRequestBytes !== void 0) {\n caps.maxRequestBytes = opts.maxRequestBytes;\n }\n const batches = [];\n try {\n for await (const b of binding.chunk(statements.slice(from), caps)) {\n batches.push(b);\n }\n } catch (err) {\n throw fail(from, err);\n }\n let next = from;\n for (const b of batches) {\n try {\n if (opts.stop?.(next) === true) {\n return { next, done: false };\n }\n await binding.batch(b, {\n retry: { operationId: await writeChunksOperationId(opts.key, next), requestHash: \"\" }\n });\n } catch (err) {\n throw fail(next, err);\n }\n next += b.length;\n }\n return { next, done: true };\n }\n };\n binding._iterateRows = iterateRows;\n return binding;\n}\nfunction tighterCap(a, b) {\n if (a > 0 && b > 0) {\n return Math.min(a, b);\n }\n return a > 0 ? a : b;\n}\nfunction checkReplyIdentity(request, operationId, statementCount) {\n if (request.operationId !== \"\" && operationId !== request.operationId) {\n throw PluginError.fromWire(\"invalid_params\", `reply answers operation ${operationId}, not ${request.operationId}`);\n }\n if (statementCount !== request.statements.length) {\n throw PluginError.fromWire(\"invalid_params\", `reply carries ${statementCount} results for ${request.statements.length} statements`);\n }\n}\nfunction replyFor(request, reply) {\n checkReplyIdentity(request, reply.operationId, reply.statements.length);\n for (let i = 0; i < reply.statements.length; i++) {\n const maxRows = request.statements[i]?.maxRows ?? 0;\n const rows = reply.statements[i]?.rows.length ?? 0;\n if (maxRows > 0 && rows > maxRows) {\n throw PluginError.fromWire(\"invalid_params\", `reply carries ${rows} rows for statement ${i}, which asked for at most ${maxRows}`);\n }\n }\n return reply;\n}\nfunction rowMap(columns, row) {\n const out = {};\n for (let i = 0; i < columns.length; i++) {\n const value = row.values[i];\n if (value !== void 0) {\n out[columns[i].name] = value;\n }\n }\n return out;\n}\nfunction chunkIndexes(typed, maxStatements, maxRequestBytes) {\n if (typed.length === 0) {\n return [];\n }\n const base = encodeExecuteRequest({\n operationId: RETRY_ID_PLACEHOLDER,\n requestHash: RETRY_HASH_PLACEHOLDER,\n statements: [PROBE_STATEMENT],\n deadlineUnixMs: 0\n }).byteLength - PROBE_STATEMENT_BYTES;\n const sizes = typed.map((stmt) => encodeExecuteRequest({\n operationId: \"\",\n requestHash: \"\",\n statements: [PROBE_STATEMENT, stmt],\n deadlineUnixMs: 0\n }).byteLength - PROBE_REQUEST_BYTES);\n const fits = (run2) => maxRequestBytes <= 0 || encodeExecuteRequest({\n operationId: RETRY_ID_PLACEHOLDER,\n requestHash: RETRY_HASH_PLACEHOLDER,\n statements: run2.map((i) => typed[i]),\n deadlineUnixMs: 0\n }).byteLength <= maxRequestBytes;\n const out = [];\n const emit = (run2) => {\n if (run2.length <= 1 || fits(run2)) {\n out.push(run2);\n return;\n }\n const half = Math.ceil(run2.length / 2);\n emit(run2.slice(0, half));\n emit(run2.slice(half));\n };\n let run = [];\n let bytes = base;\n for (let i = 0; i < typed.length; i++) {\n const size = sizes[i];\n const overStatements = maxStatements > 0 && run.length >= maxStatements;\n const overBytes = maxRequestBytes > 0 && run.length > 0 && bytes + size > maxRequestBytes;\n if (overStatements || overBytes) {\n emit(run);\n run = [];\n bytes = base;\n }\n run.push(i);\n bytes += size;\n }\n if (run.length > 0) {\n emit(run);\n }\n return out;\n}\nvar RETRY_ID_PLACEHOLDER = \"00000000-0000-4000-8000-000000000000\";\nvar RETRY_HASH_PLACEHOLDER = \"0\".repeat(64);\nvar PROBE_STATEMENT = {\n sql: \"\",\n parameters: [],\n kind: \"select\",\n maxRows: 0,\n resultSelection: \"rows\"\n};\nvar PROBE_REQUEST_BYTES = encodeExecuteRequest({\n operationId: \"\",\n requestHash: \"\",\n statements: [PROBE_STATEMENT],\n deadlineUnixMs: 0\n}).byteLength;\nvar PROBE_STATEMENT_BYTES = encodeExecuteRequest({\n operationId: \"\",\n requestHash: \"\",\n statements: [PROBE_STATEMENT, PROBE_STATEMENT],\n deadlineUnixMs: 0\n}).byteLength - PROBE_REQUEST_BYTES;\nfunction defaultIntent(options) {\n return {\n resultSelection: \"rows\",\n maxRows: options.maxResultRows ?? 0\n };\n}\nfunction makePrepared(binding, sql, parameters, defaultAllRows, intent) {\n const stmt = {\n _intent: intent,\n bind(...values) {\n return makePrepared(binding, sql, values, defaultAllRows, intent);\n },\n asRun() {\n return makePrepared(binding, sql, parameters, defaultAllRows, {\n resultSelection: \"affectedRows\",\n maxRows: 0\n });\n },\n asFirst() {\n return makePrepared(binding, sql, parameters, defaultAllRows, {\n resultSelection: \"rows\",\n maxRows: 1\n });\n },\n asAll() {\n return makePrepared(binding, sql, parameters, defaultAllRows, {\n resultSelection: \"rows\",\n maxRows: defaultAllRows\n });\n },\n run(options) {\n return binding.execute([this.asAll()._asTyped()], options).then((reply) => statementResultToD1Result(reply.statements[0], reply.timing));\n },\n first(colName, options) {\n return binding.execute([this.asFirst()._asTyped()], options).then((reply) => {\n const result = reply.statements[0];\n if (!result) {\n return null;\n }\n const row = rowMapFromStatement(result);\n if (row === null) {\n return null;\n }\n if (colName !== void 0) {\n return columnValueFromRow(row, colName);\n }\n return row;\n });\n },\n raw(options) {\n return binding.execute([this.asAll()._asTyped()], options).then((reply) => {\n const result = reply.statements[0];\n if (!result) {\n return [];\n }\n return result.rows.map((row) => row.values);\n });\n },\n all(options) {\n return binding.execute([this.asAll()._asTyped()], options).then((reply) => statementResultToD1Result(reply.statements[0], reply.timing));\n },\n iterate(options) {\n const typed = [this.asAll()._asTyped()];\n const streamedRows = binding._iterateRows;\n if (streamedRows !== void 0) {\n return streamedRows(typed, options?.retry);\n }\n return (async function* inline() {\n const reply = await binding.execute(typed, options);\n const result = reply.statements[0];\n if (result) {\n for (const row of result.rows) {\n yield rowMap(result.columns, row);\n }\n }\n })();\n },\n _asTyped() {\n const used = intent ?? defaultIntent({ maxResultRows: defaultAllRows });\n return {\n sql,\n parameters,\n kind: used.resultSelection === \"affectedRows\" || used.resultSelection === \"discard\" ? \"execute\" : guestStatementKind(sql),\n maxRows: used.maxRows,\n resultSelection: used.resultSelection\n };\n }\n };\n return stmt;\n}\nasync function executeRequestFromBatch(batch, options, retry) {\n const token = retry ?? options.retry;\n return {\n operationId: token?.operationId ?? options.operationId ?? newOperationId(),\n requestHash: token?.requestHash ?? options.requestHash ?? \"\",\n statements: batch,\n deadlineUnixMs: options.deadlineUnixMs ?? 0\n };\n}\nasync function canonicalExecuteRequestHash(request) {\n const canonical = {\n ...request,\n operationId: \"\",\n requestHash: \"\",\n deadlineUnixMs: 0\n };\n const bytes = new Uint8Array(encodeExecuteRequest(canonical));\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return hexBytes(new Uint8Array(digest));\n }\n const { createHash } = await import(\"node:crypto\");\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\nfunction hexBytes(bytes) {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction newOperationId() {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `op-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n}\nfunction writeStatement(s, stmt) {\n s.setText(0, stmt.sql);\n s.setUint16(0, KIND_ORD[stmt.kind]);\n s.setUint16(1, SELECT_ORD[stmt.resultSelection]);\n s.setUint32(1, stmt.maxRows);\n const params = s.initStructList(1, stmt.parameters.length, 2, 1);\n for (let i = 0; i < stmt.parameters.length; i++) {\n writeDbValue(params[i], stmt.parameters[i]);\n }\n}\nfunction readStatement(s) {\n const kind = KIND_FROM[s.getUint16(0)];\n const selectionRaw = s.getUint16(1);\n const selection = SELECT_FROM[selectionRaw] ?? \"rows\";\n if (kind === void 0) {\n throw new Error(\"unknown DbStatementKind\");\n }\n return {\n sql: s.getText(0),\n parameters: s.getStructList(1, 2, 1).map(readDbValue),\n kind,\n maxRows: s.getUint32(1),\n resultSelection: selection\n };\n}\n\n// dist/invoke.js\nvar InvokeError = class extends PluginError {\n /** HTTP status the bridge answers with. */\n status;\n constructor(status, code, message) {\n super(code, message);\n this.name = \"InvokeError\";\n this.status = status;\n }\n};\nfunction okValue(value) {\n return { kind: \"ok\", value };\n}\nfunction okPass(value) {\n return { kind: \"ok\", value };\n}\nfunction okEmpty() {\n return { kind: \"ok\" };\n}\nfunction named(stub, ctx, method, args) {\n return stub.bookclerkInvoke(ctx, method, ...args);\n}\nfunction spec(entry) {\n return entry;\n}\nfunction withParams(stub, method, params, results, ok) {\n return spec({\n params,\n results,\n stub,\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), method, [p.params]),\n ok\n });\n}\nfunction withoutParams(stub, method, params, results, ok) {\n return spec({\n params,\n results,\n stub,\n call: (s, _p, cx) => named(s, cx.host.bindContext(cx.ctx), method, []),\n ok\n });\n}\nvar asList = (value) => Array.isArray(value) ? value : [];\nfunction hintResult(value) {\n if (value != null && typeof value === \"object\" && \"records\" in value) {\n const answer = value;\n return {\n found: answer.hint != null,\n // The wire leaves `hint` unset when not found.\n hint: answer.hint ?? void 0,\n records: Array.isArray(answer.records) ? answer.records : []\n };\n }\n return { found: value != null, hint: value ?? void 0, records: [] };\n}\nvar okHits = (value) => okValue({ hits: asList(value) });\nvar okRecords = (value) => {\n if (!Array.isArray(value)) {\n throw PluginError.fromWire(\"internal\", \"metadata provider must return a MetadataRecord[]\");\n }\n return okValue({ records: value });\n};\nvar okCoverImages = (value) => {\n if (!Array.isArray(value)) {\n throw PluginError.fromWire(\"internal\", \"cover fetcher must return a CoverImage[]\");\n }\n return okValue({ images: value });\n};\nvar okFileRecord = (value) => {\n if (value === null || typeof value !== \"object\" || !Array.isArray(value.present)) {\n throw PluginError.fromWire(\"internal\", \"metadata file dialect must return a MetadataFileRecord\");\n }\n return okValue({ record: value });\n};\nvar okFileBytes = (value) => {\n if (typeof value === \"string\") {\n return okValue({ bytes: new TextEncoder().encode(value) });\n }\n if (!(value instanceof Uint8Array)) {\n throw PluginError.fromWire(\"internal\", \"metadata file dialect must render a Uint8Array or string\");\n }\n return okValue({ bytes: value });\n};\nvar okAiModels = (value) => {\n const v = value ?? {};\n if (!Array.isArray(v.models)) {\n throw PluginError.fromWire(\"internal\", \"models must return an object with a models list\");\n }\n return okValue({ models: v.models });\n};\nvar okAiRun = (value) => {\n const out = (value ?? {}).output?.textEmbeddings;\n if (!out || !(out.vectors instanceof Uint8Array)) {\n throw PluginError.fromWire(\"internal\", \"run must return output.textEmbeddings with vectors as a Uint8Array\");\n }\n return okValue({\n output: {\n textEmbeddings: {\n dimensions: Number(out.dimensions),\n vectors: out.vectors,\n revision: String(out.revision ?? \"\"),\n fallbacks: Array.isArray(out.fallbacks) ? out.fallbacks.map(Number) : []\n }\n }\n });\n};\nvar okNotifySent = (value) => {\n const v = value ?? {};\n const providerId = v.providerId === void 0 || v.providerId === null ? \"\" : String(v.providerId);\n return okValue(providerId ? { providerId } : {});\n};\nvar okNotifyValidated = (value) => {\n const v = value ?? {};\n if (typeof v.addressJson !== \"string\") {\n throw PluginError.fromWire(\"internal\", \"validateDestination must return an object with an addressJson string\");\n }\n const label = typeof v.label === \"string\" ? v.label : \"\";\n return okValue(label ? { addressJson: v.addressJson, label } : { addressJson: v.addressJson });\n};\nvar okLines = (value) => okValue({ lines: asList(value).map((l) => String(l)) });\nvar okHealth = (value) => {\n const v = value ?? {};\n return okValue({ ok: Boolean(v.ok), detail: String(v.detail ?? \"\") });\n};\nfunction queueResult(outcome) {\n switch (outcome.kind) {\n case \"ack\":\n return { kind: \"ack\" };\n case \"retry\":\n return {\n kind: \"retry\",\n value: {\n delaySeconds: Number(outcome.delaySeconds) || 0,\n reason: String(outcome.reason ?? \"\")\n }\n };\n default:\n return { kind: \"retry\", value: { delaySeconds: 0, reason: \"unknown queue outcome\" } };\n }\n}\nfunction eventResult(outcome) {\n switch (outcome.kind) {\n case \"ack\":\n return { kind: \"ack\", value: { dummy: void 0 } };\n case \"retry\":\n return {\n kind: \"retry\",\n value: {\n retryAtUnixMs: Number(outcome.retryAtUnixMs) || 0,\n reason: String(outcome.reason ?? \"\")\n }\n };\n case \"reject\":\n return { kind: \"reject\", value: { reason: String(outcome.reason ?? \"\") } };\n case \"deadLetter\":\n return { kind: \"deadLetter\", value: { reason: String(outcome.reason ?? \"\") } };\n case \"suspended\":\n return {\n kind: \"suspended\",\n value: {\n checkpointJson: String(outcome.checkpointJson ?? \"\"),\n checkpointSchemaVersion: Number(outcome.checkpointSchemaVersion) || 0,\n wakeAtUnixMs: Number(outcome.wakeAtUnixMs) || 0,\n wakeOnEventType: String(outcome.wakeOnEventType ?? \"\"),\n wakeOnFilterJson: String(outcome.wakeOnFilterJson ?? \"\")\n }\n };\n default:\n throw PluginError.fromWire(\"internal\", `unknown event outcome ${String(outcome.kind)}`);\n }\n}\nfunction jobOutcome(record) {\n switch (record.kind) {\n case \"completed\":\n return {\n kind: \"completed\",\n value: {\n message: String(record.message ?? \"\"),\n bytesCopied: Number(record.bytesCopied) || 0\n }\n };\n case \"retryable\":\n return {\n kind: \"retryable\",\n value: {\n message: String(record.message ?? \"\"),\n retryAfterUnixMs: Number(record.retryAfterUnixMs) || 0\n }\n };\n case \"rejected\":\n return { kind: \"rejected\", value: { message: String(record.message ?? \"\") } };\n case \"cancelled\":\n return { kind: \"cancelled\", value: { message: String(record.message ?? \"\") } };\n case \"suspended\":\n return {\n kind: \"suspended\",\n value: {\n checkpointJson: String(record.checkpoint?.json ?? \"\"),\n checkpointSchemaVersion: Number(record.checkpoint?.schemaVersion) || 0,\n wakeAtUnixMs: Number(record.wakeAtUnixMs) || 0\n }\n };\n default:\n throw PluginError.fromWire(\"internal\", `unknown job outcome ${String(record.kind)}`);\n }\n}\nfunction wireMigration(migration) {\n const ops = Array.isArray(migration?.operations) ? migration.operations : [];\n return {\n id: String(migration?.id ?? \"\"),\n operations: ops.map((op) => {\n const o = op ?? {};\n if (typeof o.schema === \"string\")\n return { kind: \"schema\", value: o.schema };\n if (typeof o.data === \"string\")\n return { kind: \"data\", value: o.data };\n if (o.kind === \"schema\" || o.kind === \"data\")\n return { kind: o.kind, value: String(o.value ?? \"\") };\n throw PluginError.fromWire(\"invalid_params\", `migration \\`${String(migration?.id)}\\` has an op without schema/data`);\n })\n };\n}\nfunction listOptions(options) {\n return {\n prefix: options?.prefix || void 0,\n cursor: options?.cursor || void 0,\n limit: options?.limit || void 0,\n withSignatures: options?.withSignatures || void 0,\n modifiedSinceMs: options?.modifiedSinceMs || void 0\n };\n}\nfunction moveOptions(options) {\n return {\n noOverwrite: options?.noOverwrite || void 0,\n ifSourceMatch: options?.ifSourceMatch || void 0\n };\n}\nfunction moveManyRequest(request) {\n const target = request?.target ?? { kind: \"pairs\", value: [] };\n if (target.kind === \"pairs\" && target.value.length > MAX_BATCH_KEYS) {\n throw new PluginError(\"payload_too_large\", `moveMany of ${target.value.length} pairs`);\n }\n return {\n target,\n cursor: request?.cursor || void 0,\n limit: request?.limit || void 0,\n options: moveOptions(request?.options)\n };\n}\nfunction batchKeys(keys) {\n const list = keys ?? [];\n if (list.length === 0) {\n throw new PluginError(\"invalid_params\", \"a batch call needs at least one key\");\n }\n if (list.length > MAX_BATCH_KEYS) {\n throw new PluginError(\"payload_too_large\", `batch of ${list.length} keys`);\n }\n return list.map(String);\n}\nfunction wireOutcomes(outcomes) {\n return outcomes.map((o) => ({\n key: String(o.key ?? \"\"),\n error: {\n code: o.error ? String(o.error.code ?? \"\") || \"internal\" : \"\",\n message: o.error ? String(o.error.message ?? \"\") : \"\",\n details: \"\"\n }\n }));\n}\nfunction sessionCall(method) {\n return (s, p, cx) => {\n if (!cx.target) {\n throw new InvokeError(400, \"invalid_params\", `AdapterDatabaseSession.${method} requires X-Bookclerk-Target`);\n }\n const params = p;\n const args = method === \"execute\" || method === \"executeStreamed\" ? [params.request] : method === \"importIdentity\" ? [params.rows] : method === \"dropUserRelations\" ? [params.names] : [];\n return named(s, cx.host.bindContext(cx.ctx), \"session\", [cx.target, method, ...args]);\n };\n}\nfunction session(method, params, results, ok) {\n return spec({ params, results, stub: \"databaseAdapter\", call: sessionCall(method), ok });\n}\nvar METHODS = {\n PluginWorker: {\n databaseMigrations: spec({\n params: PluginWorkerDatabaseMigrationsParamsCodec,\n results: PluginWorkerDatabaseMigrationsResultsCodec,\n stub: \"author\",\n call: (s, p) => s.bookclerkDatabaseMigrations(String(p.binding ?? \"\")),\n ok: (value) => okValue({ migrations: asList(value).map(wireMigration) })\n })\n },\n ContentSource: {\n login: withParams(\"storefront\", \"login\", ContentSourceLoginParamsCodec, ContentSourceLoginResultsCodec, okPass),\n scan: withParams(\"storefront\", \"scan\", ContentSourceScanParamsCodec, ContentSourceScanResultsCodec, okPass),\n fetchTitle: withParams(\"storefront\", \"fetchTitle\", ContentSourceFetchTitleParamsCodec, ContentSourceFetchTitleResultsCodec, okPass),\n listAccounts: withoutParams(\"storefront\", \"listAccounts\", ContentSourceListAccountsParamsCodec, ContentSourceListAccountsResultsCodec, (value) => okValue({ accounts: asList(value) })),\n loginStart: withParams(\"storefront\", \"loginStart\", ContentSourceLoginStartParamsCodec, ContentSourceLoginStartResultsCodec, okPass),\n loginComplete: withParams(\"storefront\", \"loginComplete\", ContentSourceLoginCompleteParamsCodec, ContentSourceLoginCompleteResultsCodec, okPass),\n searchCatalog: withParams(\"storefront\", \"searchCatalog\", ContentSourceSearchCatalogParamsCodec, ContentSourceSearchCatalogResultsCodec, okHits),\n expandCandidates: withParams(\"storefront\", \"expandCandidates\", ContentSourceExpandCandidatesParamsCodec, ContentSourceExpandCandidatesResultsCodec, okHits),\n purchaseHint: withParams(\"storefront\", \"purchaseHint\", ContentSourcePurchaseHintParamsCodec, ContentSourcePurchaseHintResultsCodec, (value) => okValue(hintResult(value))),\n purchaseHints: withParams(\"storefront\", \"purchaseHints\", ContentSourcePurchaseHintsParamsCodec, ContentSourcePurchaseHintsResultsCodec, (value) => okValue({\n results: asList(value).map(hintResult)\n })),\n listDeals: withParams(\"storefront\", \"listDeals\", ContentSourceListDealsParamsCodec, ContentSourceListDealsResultsCodec, okHits),\n health: withoutParams(\"storefront\", \"health\", ContentSourceHealthParamsCodec, ContentSourceHealthResultsCodec, okHealth),\n diagnose: withoutParams(\"storefront\", \"diagnose\", ContentSourceDiagnoseParamsCodec, ContentSourceDiagnoseResultsCodec, okLines),\n catalogDetail: withParams(\"storefront\", \"catalogDetail\", ContentSourceCatalogDetailParamsCodec, ContentSourceCatalogDetailResultsCodec, (value) => okValue({ found: value != null, hit: value ?? void 0 })),\n revokeAccount: withParams(\"storefront\", \"revokeAccount\", ContentSourceRevokeAccountParamsCodec, ContentSourceRevokeAccountResultsCodec, okEmpty),\n qualityOffers: withParams(\"storefront\", \"qualityOffers\", ContentSourceQualityOffersParamsCodec, ContentSourceQualityOffersResultsCodec, okPass)\n },\n Destination: {\n head: spec({\n params: DestinationHeadParamsCodec,\n results: DestinationHeadResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"head\", [String(p.key ?? \"\")]),\n ok: (value) => {\n const meta = value ?? null;\n return okValue({\n found: meta != null,\n meta: meta ?? void 0\n });\n }\n }),\n list: spec({\n params: DestinationListParamsCodec,\n results: DestinationListResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"list\", [listOptions(p.options)]),\n ok: okPass\n }),\n copy: spec({\n params: DestinationCopyParamsCodec,\n results: DestinationCopyResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"copy\", [String(p.from ?? \"\"), String(p.to ?? \"\")]),\n ok: okPass\n }),\n delete: spec({\n params: DestinationDeleteParamsCodec,\n results: DestinationDeleteResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"delete\", [String(p.key ?? \"\")]),\n ok: okEmpty\n }),\n commit: spec({\n params: DestinationCommitParamsCodec,\n results: DestinationCommitResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"commit\", [\n String(p.key ?? \"\"),\n String(p.commitToken ?? \"\")\n ]),\n ok: okPass\n }),\n abortStage: spec({\n params: DestinationAbortStageParamsCodec,\n results: DestinationAbortStageResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"abortStage\", [\n String(p.key ?? \"\"),\n String(p.commitToken ?? \"\")\n ]),\n ok: okEmpty\n }),\n move: spec({\n params: DestinationMoveParamsCodec,\n results: DestinationMoveResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"move\", [\n String(p.from ?? \"\"),\n String(p.to ?? \"\"),\n moveOptions(p.options)\n ]),\n ok: okPass\n }),\n moveMany: spec({\n params: DestinationMoveManyParamsCodec,\n results: DestinationMoveManyResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"moveMany\", [moveManyRequest(p.request)]),\n ok: (value) => {\n const page = value ?? { results: [] };\n return okValue({\n results: wireOutcomes(asList(page.results)),\n nextCursor: page.nextCursor ?? \"\",\n atomic: page.atomic ?? false,\n objectsMoved: page.objectsMoved ?? 0\n });\n }\n }),\n deleteMany: spec({\n params: DestinationDeleteManyParamsCodec,\n results: DestinationDeleteManyResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"deleteMany\", [batchKeys(p.keys)]),\n ok: (value) => okValue({ results: wireOutcomes(asList(value)) })\n }),\n headMany: spec({\n params: DestinationHeadManyParamsCodec,\n results: DestinationHeadManyResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"headMany\", [batchKeys(p.keys)]),\n ok: (value) => okValue({\n objects: asList(value).map((meta) => ({\n found: meta != null,\n meta: meta ?? void 0\n }))\n })\n }),\n translateKeys: spec({\n params: DestinationTranslateKeysParamsCodec,\n results: DestinationTranslateKeysResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"translateKeys\", [batchKeys(p.keys)]),\n ok: (value) => okValue({ keys: asList(value).map(String) })\n }),\n changes: spec({\n params: DestinationChangesParamsCodec,\n results: DestinationChangesResultsCodec,\n stub: \"storage\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"changes\", [\n {\n cursor: p.request?.cursor || void 0,\n limit: p.request?.limit || void 0\n }\n ]),\n ok: okPass\n })\n },\n RemoteLibrary: {\n health: withoutParams(\"remoteLibrary\", \"health\", RemoteLibraryHealthParamsCodec, RemoteLibraryHealthResultsCodec, okHealth),\n start: withoutParams(\"remoteLibrary\", \"start\", RemoteLibraryStartParamsCodec, RemoteLibraryStartResultsCodec, okEmpty),\n stop: withoutParams(\"remoteLibrary\", \"stop\", RemoteLibraryStopParamsCodec, RemoteLibraryStopResultsCodec, okEmpty),\n diagnose: withoutParams(\"remoteLibrary\", \"diagnose\", RemoteLibraryDiagnoseParamsCodec, RemoteLibraryDiagnoseResultsCodec, okLines),\n scanLibrary: withParams(\"remoteLibrary\", \"scanLibrary\", RemoteLibraryScanLibraryParamsCodec, RemoteLibraryScanLibraryResultsCodec, okEmpty),\n syncListening: withoutParams(\"remoteLibrary\", \"syncListening\", RemoteLibrarySyncListeningParamsCodec, RemoteLibrarySyncListeningResultsCodec, (value) => okValue({ items: asList(value) })),\n pollEvents: withoutParams(\"remoteLibrary\", \"pollEvents\", RemoteLibraryPollEventsParamsCodec, RemoteLibraryPollEventsResultsCodec, (value) => okValue({ users: asList(value) }))\n },\n EventConsumer: {\n event: spec({\n params: EventConsumerEventParamsCodec,\n results: EventConsumerEventResultsCodec,\n stub: \"author\",\n call: (s, p, cx) => s.bookclerkEvent(cx.host.bindContext(cx.ctx), {\n events: Array.isArray(p.batch?.events) ? p.batch.events : []\n }),\n ok: (value) => okValue(asList(value).map(eventResult))\n })\n },\n QueueConsumer: {\n queue: spec({\n params: QueueConsumerQueueParamsCodec,\n results: QueueConsumerQueueResultsCodec,\n stub: \"author\",\n call: (s, p, cx) => s.bookclerkQueue(cx.host.bindContext(cx.ctx), {\n queue: String(p.batch?.queue ?? \"\"),\n messages: Array.isArray(p.batch?.messages) ? p.batch.messages : []\n }),\n ok: (value) => okValue({ results: asList(value).map(queueResult) })\n })\n },\n ScheduledHandler: {\n scheduled: spec({\n params: ScheduledHandlerScheduledParamsCodec,\n results: ScheduledHandlerScheduledResultsCodec,\n stub: \"author\",\n call: (s, p, cx) => s.bookclerkScheduled(cx.host.bindContext(cx.ctx), p.controller ?? {}),\n ok: okEmpty\n })\n },\n SocketHandler: {\n message: spec({\n params: SocketHandlerMessageParamsCodec,\n results: SocketHandlerMessageResultsCodec,\n stub: \"author\",\n call: (s, p, cx) => s.bookclerkSocketMessage(cx.host.bindContext(cx.ctx), p.event ?? {}),\n ok: (value) => okValue({\n pollEvents: value?.pollEvents === true\n })\n }),\n closed: spec({\n params: SocketHandlerClosedParamsCodec,\n results: SocketHandlerClosedResultsCodec,\n stub: \"author\",\n call: (s, p, cx) => s.bookclerkSocketClosed(cx.host.bindContext(cx.ctx), p.event ?? {}),\n ok: okEmpty\n })\n },\n WebhookHandler: {\n delivered: spec({\n params: WebhookHandlerDeliveredParamsCodec,\n results: WebhookHandlerDeliveredResultsCodec,\n stub: \"author\",\n call: (s, p, cx) => s.bookclerkWebhookDelivered(cx.host.bindContext(cx.ctx), p.event ?? {}),\n ok: okEmpty\n })\n },\n JobRunner: {\n job: spec({\n params: JobRunnerJobParamsCodec,\n results: JobRunnerJobResultsCodec,\n stub: \"author\",\n call: (s, p, cx) => {\n const controller = p.controller ?? {};\n const granted = {\n input: controller.input ?? null,\n output: controller.output ?? null,\n progress: controller.progress ?? null,\n cancel: controller.cancel ?? null\n };\n return s.bookclerkJob(cx.host.bindContext(cx.ctx), controller.invocation ?? {}, granted);\n },\n ok: (value) => okValue(jobOutcome(value))\n })\n },\n PluginCli: {\n describe: withoutParams(\"cli\", \"describe\", PluginCliDescribeParamsCodec, PluginCliDescribeResultsCodec, okPass),\n invoke: withParams(\"cli\", \"invoke\", PluginCliInvokeParamsCodec, PluginCliInvokeResultsCodec, okPass)\n },\n Oidc: {\n clients: withoutParams(\"oidc\", \"clients\", OidcClientsParamsCodec, OidcClientsResultsCodec, (value) => okValue({ clients: asList(value) })),\n authenticateUser: withParams(\"oidc\", \"authenticateUser\", OidcAuthenticateUserParamsCodec, OidcAuthenticateUserResultsCodec, okPass)\n },\n MetadataProvider: {\n health: withoutParams(\"metadata\", \"health\", MetadataProviderHealthParamsCodec, MetadataProviderHealthResultsCodec, okHealth),\n lookup: withParams(\"metadata\", \"lookup\", MetadataProviderLookupParamsCodec, MetadataProviderLookupResultsCodec, okRecords),\n search: withParams(\"metadata\", \"search\", MetadataProviderSearchParamsCodec, MetadataProviderSearchResultsCodec, okRecords),\n chapters: withParams(\"metadata\", \"chapters\", MetadataProviderChaptersParamsCodec, MetadataProviderChaptersResultsCodec, okPass)\n },\n CoverFetcher: {\n health: withoutParams(\"covers\", \"health\", CoverFetcherHealthParamsCodec, CoverFetcherHealthResultsCodec, okHealth),\n fetchCovers: spec({\n params: CoverFetcherFetchCoversParamsCodec,\n results: CoverFetcherFetchCoversResultsCodec,\n stub: \"covers\",\n call: (s, p, cx) => {\n if (!p.sink) {\n throw PluginError.fromWire(\"invalid_params\", \"fetchCovers needs a sink\");\n }\n return named(s, cx.host.bindContext(cx.ctx), \"fetchCovers\", [p.params, p.sink]);\n },\n ok: okCoverImages\n })\n },\n AiModels: {\n health: withoutParams(\"ai\", \"health\", AiModelsHealthParamsCodec, AiModelsHealthResultsCodec, okHealth),\n models: withoutParams(\"ai\", \"models\", AiModelsModelsParamsCodec, AiModelsModelsResultsCodec, okAiModels),\n run: withParams(\"ai\", \"run\", AiModelsRunParamsCodec, AiModelsRunResultsCodec, okAiRun)\n },\n Notifier: {\n health: withoutParams(\"notifier\", \"health\", NotifierHealthParamsCodec, NotifierHealthResultsCodec, okHealth),\n send: withParams(\"notifier\", \"send\", NotifierSendParamsCodec, NotifierSendResultsCodec, okNotifySent),\n validateDestination: withParams(\"notifier\", \"validateDestination\", NotifierValidateDestinationParamsCodec, NotifierValidateDestinationResultsCodec, okNotifyValidated)\n },\n MetadataFiles: {\n health: withoutParams(\"metadataFiles\", \"health\", MetadataFilesHealthParamsCodec, MetadataFilesHealthResultsCodec, okHealth),\n parse: withParams(\"metadataFiles\", \"parse\", MetadataFilesParseParamsCodec, MetadataFilesParseResultsCodec, okFileRecord),\n render: withParams(\"metadataFiles\", \"render\", MetadataFilesRenderParamsCodec, MetadataFilesRenderResultsCodec, okFileBytes)\n },\n Ingress: {\n start: withoutParams(\"ingress\", \"start\", IngressStartParamsCodec, IngressStartResultsCodec, okPass),\n health: withoutParams(\"ingress\", \"health\", IngressHealthParamsCodec, IngressHealthResultsCodec, okPass),\n stop: withoutParams(\"ingress\", \"stop\", IngressStopParamsCodec, IngressStopResultsCodec, okEmpty)\n },\n Database: {\n openSession: spec({\n params: DatabaseOpenSessionParamsCodec,\n results: DatabaseOpenSessionResultsCodec,\n stub: \"databaseAdapter\",\n call: async (s, _p, cx) => {\n const id = await named(s, cx.host.bindContext(cx.ctx), \"openSession\", []);\n if (typeof id !== \"string\" || !id) {\n throw PluginError.fromWire(\"internal\", \"openSession returned no session id\");\n }\n return id;\n },\n // The session id is exported through the reply CapTable as `adapterSession`.\n ok: (value) => okValue(value)\n }),\n dropUnit: spec({\n params: DatabaseDropUnitParamsCodec,\n results: DatabaseDropUnitResultsCodec,\n stub: \"databaseAdapter\",\n call: (s, p, cx) => named(s, cx.host.bindContext(cx.ctx), \"dropUnit\", [String(p.unitRef ?? \"\")]),\n ok: okEmpty\n })\n },\n AdapterDatabaseSession: {\n // An isolate adapter\'s streamed frames travel inside one invoke reply,\n // so a streamed budget above one scalar could not be delivered; the\n // advertisement is clamped so the host\'s budget is one the adapter can\n // honour before it commits.\n capabilities: session(\"capabilities\", AdapterDatabaseSessionCapabilitiesParamsCodec, AdapterDatabaseSessionCapabilitiesResultsCodec, (value) => okValue(clampIsolateStreamedCaps(value))),\n execute: session(\"execute\", AdapterDatabaseSessionExecuteParamsCodec, AdapterDatabaseSessionExecuteResultsCodec, (value) => okValue(value)),\n close: session(\"close\", AdapterDatabaseSessionCloseParamsCodec, AdapterDatabaseSessionCloseResultsCodec, okEmpty),\n bootstrap: session(\"bootstrap\", AdapterDatabaseSessionBootstrapParamsCodec, AdapterDatabaseSessionBootstrapResultsCodec, (value) => okValue(value)),\n exportIdentity: session(\"exportIdentity\", AdapterDatabaseSessionExportIdentityParamsCodec, AdapterDatabaseSessionExportIdentityResultsCodec, (value) => okValue(asList(value))),\n importIdentity: session(\"importIdentity\", AdapterDatabaseSessionImportIdentityParamsCodec, AdapterDatabaseSessionImportIdentityResultsCodec, okEmpty),\n listUserRelations: session(\"listUserRelations\", AdapterDatabaseSessionListUserRelationsParamsCodec, AdapterDatabaseSessionListUserRelationsResultsCodec, (value) => okValue(asList(value).map((n) => String(n)))),\n prepareUnitRestore: session(\"prepareUnitRestore\", AdapterDatabaseSessionPrepareUnitRestoreParamsCodec, AdapterDatabaseSessionPrepareUnitRestoreResultsCodec, okEmpty),\n dropUserRelations: session(\"dropUserRelations\", AdapterDatabaseSessionDropUserRelationsParamsCodec, AdapterDatabaseSessionDropUserRelationsResultsCodec, okEmpty),\n assertRestoreConstraints: session(\"assertRestoreConstraints\", AdapterDatabaseSessionAssertRestoreConstraintsParamsCodec, AdapterDatabaseSessionAssertRestoreConstraintsResultsCodec, okEmpty),\n // An isolate adapter answers with the frames in memory, which travel as\n // the `inline` member of the invoke reply; frames past one scalar cannot\n // cross that reply, so they become a typed limit error instead of a\n // transport failure.\n executeStreamed: session(\"executeStreamed\", AdapterDatabaseSessionExecuteStreamedParamsCodec, AdapterDatabaseSessionExecuteStreamedResultsCodec, (value) => inlineStreamReply(value))\n }\n};\nvar CAP_KINDS = /* @__PURE__ */ new Set([\n \"source\",\n \"destination\",\n \"progress\",\n \"cancellation\"\n]);\nfunction requestCapTable(caps, host, stop) {\n const resolved = /* @__PURE__ */ new Map();\n return {\n exportCap() {\n throw new InvokeError(400, \"invalid_params\", \"request message cannot export capabilities\");\n },\n importCap(index) {\n if (index === null)\n return null;\n if (resolved.has(index))\n return resolved.get(index);\n const descriptor = caps[index];\n if (!descriptor || typeof descriptor !== \"object\" || typeof descriptor.kind !== \"string\") {\n throw new InvokeError(400, \"invalid_params\", `capability index ${index} has no descriptor`);\n }\n if (!CAP_KINDS.has(descriptor.kind)) {\n throw new InvokeError(400, \"invalid_params\", `unsupported request capability kind ${descriptor.kind}`);\n }\n const value = host.importCap(descriptor, stop);\n if (value === void 0) {\n throw new InvokeError(400, \"invalid_params\", `unsupported request capability kind ${descriptor.kind}`);\n }\n resolved.set(index, value);\n return value;\n }\n };\n}\nfunction replyCapTable(caps) {\n return {\n exportCap(value) {\n if (typeof value !== \"string\" || !value) {\n throw PluginError.fromWire(\"internal\", \"reply capability is not an isolate object id\");\n }\n caps.push({ kind: \"adapterSession\", id: value });\n return caps.length - 1;\n },\n importCap() {\n throw new InvokeError(500, \"internal\", \"reply message cannot import capabilities\");\n }\n };\n}\nfunction clampIsolateStreamedCaps(caps) {\n const bytes = caps.maxStreamedResultBytes ?? 0;\n if (bytes <= MAX_SCALAR_BYTES) {\n return caps;\n }\n return { ...caps, maxStreamedResultBytes: MAX_SCALAR_BYTES };\n}\nfunction inlineStreamReply(frames) {\n if (!(frames instanceof Uint8Array)) {\n throw new InvokeError(500, \"internal\", \"executeStreamed must return a Uint8Array of frames\");\n }\n if (frames.byteLength > MAX_SCALAR_BYTES) {\n return {\n kind: \"err\",\n value: wireError(PluginError.limitExceeded({\n limit: \"maxScalarBytes\",\n cap: MAX_SCALAR_BYTES,\n used: frames.byteLength\n }))\n };\n }\n return { kind: \"inline\", value: frames };\n}\nfunction wireError(err) {\n const e = err;\n const code = e && typeof e === \"object\" ? typeof e.wireCode === \"string\" ? e.wireCode : typeof e.code === \"string\" ? e.code : \"internal\" : \"internal\";\n const message = err instanceof Error ? err.message : typeof err === \"string\" ? err : String(err);\n return { code, message, details: wireDetails(err) };\n}\nfunction wireDetails(err) {\n if (err instanceof PluginError)\n return err.detailsText;\n const details = err?.details;\n if (details === null || typeof details !== \"object\" || Array.isArray(details))\n return \"\";\n try {\n return JSON.stringify(details) ?? \"\";\n } catch {\n return \"\";\n }\n}\nfunction resolveStub(entry, host) {\n if (entry.stub === \"author\") {\n const author = host.author();\n if (!author)\n throw new InvokeError(500, \"unavailable\", \"PLUGIN binding missing\");\n return author;\n }\n const stub = host.named(entry.stub);\n if (!stub)\n throw new InvokeError(404, \"unsupported\", `${entry.stub} entrypoint not exported`);\n return stub;\n}\nasync function dispatchInvoke(iface, method, context, caps, target, body, host) {\n const table = Object.hasOwn(METHODS, iface) ? METHODS[iface] : void 0;\n const entry = table && Object.hasOwn(table, method) ? table[method] : void 0;\n if (!entry) {\n throw new InvokeError(400, \"invalid_params\", `unknown /invoke method ${iface}.${method}`);\n }\n const stop = new AbortController();\n let params;\n try {\n params = decodeMessage(entry.params, body, requestCapTable(caps, host, stop.signal));\n } catch (err) {\n stop.abort();\n if (err instanceof InvokeError)\n throw err;\n throw new InvokeError(400, \"invalid_params\", `malformed ${iface}.${method} params: ${wireError(err).message}`);\n }\n let reply;\n try {\n const stub = resolveStub(entry, host);\n const cx = { host, ctx: context, target, stop };\n try {\n reply = entry.ok(await entry.call(stub, params, cx));\n } catch (err) {\n if (err instanceof InvokeError)\n throw err;\n reply = { kind: \"err\", value: wireError(err) };\n }\n } finally {\n stop.abort();\n }\n const replyCaps = [];\n const bytes = encodeMessage(entry.results, { result: reply }, replyCapTable(replyCaps));\n return { body: bytes, caps: replyCaps };\n}\n\n// dist/plugin-migrations.js\nvar utf8 = new TextEncoder();\nfunction utf8Bytes(value) {\n return utf8.encode(value).byteLength;\n}\nfunction opSql(op) {\n if (op && typeof op === \"object\") {\n if (\"schema\" in op && typeof op.schema === \"string\") {\n return op.schema;\n }\n if (\"data\" in op && typeof op.data === \"string\") {\n return op.data;\n }\n if (\"value\" in op && typeof op.value === \"string\") {\n return op.value;\n }\n }\n return \"\";\n}\nfunction requirePluginMigrationRegistration(migrations) {\n if (!Array.isArray(migrations)) {\n return [];\n }\n if (migrations.length > MAX_LIST_PAGE) {\n throw migrationTooLarge(`plugin migration count ${migrations.length} exceeds maxListPage (${MAX_LIST_PAGE})`);\n }\n let total = 0;\n let totalOps = 0;\n for (const migration of migrations) {\n const ops = Array.isArray(migration.operations) ? migration.operations : [];\n if (ops.length > MAX_PLUGIN_MIGRATION_OPS) {\n throw migrationTooLarge(`plugin migration \\`${migration.id}\\` has ${ops.length} operations; exceeds maxPluginMigrationOps (${MAX_PLUGIN_MIGRATION_OPS})`);\n }\n totalOps += ops.length;\n if (totalOps > MAX_PLUGIN_MIGRATION_TOTAL_OPS) {\n throw migrationTooLarge(`plugin migration registration has ${totalOps} operations; exceeds maxPluginMigrationTotalOps (${MAX_PLUGIN_MIGRATION_TOTAL_OPS})`);\n }\n total += utf8Bytes(String(migration.id ?? \"\"));\n if (total > MAX_PLUGIN_MIGRATION_REGISTRATION_BYTES) {\n throw migrationTooLarge(`plugin migration registration is ${total} bytes; exceeds maxPluginMigrationRegistrationBytes (${MAX_PLUGIN_MIGRATION_REGISTRATION_BYTES})`);\n }\n for (const op of ops) {\n const n = utf8Bytes(opSql(op));\n if (n > MAX_SCALAR_BYTES) {\n throw migrationTooLarge(`plugin migration \\`${migration.id}\\` SQL is ${n} bytes; exceeds maxScalarBytes (${MAX_SCALAR_BYTES})`);\n }\n total += n;\n if (total > MAX_PLUGIN_MIGRATION_REGISTRATION_BYTES) {\n throw migrationTooLarge(`plugin migration registration is ${total} bytes; exceeds maxPluginMigrationRegistrationBytes (${MAX_PLUGIN_MIGRATION_REGISTRATION_BYTES})`);\n }\n }\n }\n return migrations;\n}\nfunction migrationTooLarge(message) {\n const err = new Error(message);\n err.code = \"payload_too_large\";\n err.wireCode = \"payload_too_large\";\n return err;\n}\n\n// dist/sockets.js\nfunction toBase64(bytes) {\n let bin = \"\";\n for (let i = 0; i < bytes.length; i++)\n bin += String.fromCharCode(bytes[i]);\n return btoa(bin);\n}\nfunction fromBase64(text) {\n if (typeof text !== \"string\" || text === \"\")\n return new Uint8Array();\n const bin = atob(text);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++)\n out[i] = bin.charCodeAt(i);\n return out;\n}\nfunction sendBytes(data) {\n if (typeof data === \"string\")\n return null;\n if (data instanceof ArrayBuffer)\n return new Uint8Array(data);\n if (ArrayBuffer.isView(data))\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n throw PluginError.fromWire(\"invalid_params\", \"a socket message must be a string or bytes\");\n}\nfunction routeFrame(data) {\n const bytes = sendBytes(data);\n const size = bytes ? bytes.byteLength : new TextEncoder().encode(data).byteLength;\n if (size > MAX_SOCKET_FRAME_BYTES) {\n throw PluginError.fromWire(\"payload_too_large\", `socket message of ${size} bytes exceeds ${MAX_SOCKET_FRAME_BYTES}`);\n }\n return bytes ? { binary: toBase64(bytes) } : { text: data };\n}\nfunction socketMessageData(frame2) {\n if (frame2 && frame2.kind === \"binary\") {\n const bytes = frame2.value instanceof Uint8Array ? frame2.value : new Uint8Array();\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n return frame2 && typeof frame2.value === \"string\" ? frame2.value : \"\";\n}\nfunction encodeAttachment(value) {\n if (value === null || value === void 0)\n return new Uint8Array();\n let text;\n try {\n text = JSON.stringify(value);\n } catch (err) {\n throw PluginError.fromWire(\"invalid_params\", `socket attachment is not JSON: ${String(err)}`);\n }\n if (text === void 0) {\n throw PluginError.fromWire(\"invalid_params\", \"socket attachment is not JSON\");\n }\n const bytes = new TextEncoder().encode(text);\n if (bytes.byteLength > MAX_SOCKET_ATTACHMENT_BYTES) {\n throw PluginError.fromWire(\"payload_too_large\", `socket attachment of ${bytes.byteLength} bytes exceeds ${MAX_SOCKET_ATTACHMENT_BYTES}`);\n }\n return bytes;\n}\nfunction decodeAttachment(bytes) {\n if (bytes.byteLength === 0)\n return null;\n const text = new TextDecoder().decode(bytes);\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\nasync function call(transport, op, body) {\n if (!transport) {\n throw PluginError.fromWire(\"unavailable\", \"SOCKETS is not granted to this invocation\");\n }\n const reply = await transport.call(op, body);\n if (\"err\" in reply) {\n throw PluginError.fromWire(reply.err.code || \"internal\", reply.err.message || \"\");\n }\n return reply.ok ?? {};\n}\nvar HostSocket = class {\n id;\n url;\n protocol;\n #transport;\n #attachment;\n /**\n * @param transport - The adapter\'s grant.\n * @param fields - Socket id, URL, subprotocol and attachment.\n */\n constructor(transport, fields) {\n this.id = String(fields.socket ?? \"\");\n this.url = typeof fields.url === \"string\" ? fields.url : \"\";\n this.protocol = typeof fields.protocol === \"string\" ? fields.protocol : \"\";\n this.#transport = transport;\n this.#attachment = fields.attachment instanceof Uint8Array ? fields.attachment : fromBase64(fields.attachment);\n }\n async send(message) {\n await call(this.#transport, \"send\", { socket: this.id, frame: routeFrame(message) });\n }\n async close(code, reason) {\n await call(this.#transport, \"close\", {\n socket: this.id,\n code: Math.max(0, Math.floor(Number(code ?? 0) || 0)),\n reason: String(reason ?? \"\")\n });\n }\n async serializeAttachment(value) {\n const bytes = encodeAttachment(value);\n await call(this.#transport, \"attachment\", { socket: this.id, attachment: toBase64(bytes) });\n this.#attachment = bytes;\n }\n deserializeAttachment() {\n return decodeAttachment(this.#attachment);\n }\n};\nfunction hostWebSocketOf(transport, fields) {\n return new HostSocket(transport, fields);\n}\nfunction connectBody(url, options) {\n const headers = options?.headers;\n const pairs = Array.isArray(headers) ? headers : Object.entries(headers ?? {});\n return {\n url: String(url ?? \"\"),\n protocols: (options?.protocols ?? []).map(String),\n headers: pairs.map(([name, value]) => ({ name: String(name), value: String(value) })),\n autoResponses: (options?.autoResponses ?? []).map((pair) => ({\n request: routeFrame(pair.request),\n response: routeFrame(pair.response)\n })),\n attachment: toBase64(encodeAttachment(options?.attachment))\n };\n}\nfunction socketsBinding(transport) {\n return Object.freeze({\n async connect(url, options) {\n const info = await call(transport, \"connect\", connectBody(url, options));\n return new HostSocket(transport, info);\n },\n async getWebSockets() {\n const reply = await call(transport, \"list\", {});\n const sockets = Array.isArray(reply.sockets) ? reply.sockets : [];\n return sockets.map((info) => new HostSocket(transport, info));\n }\n });\n}\n\n// dist/origin.js\nvar ORIGIN_FRAME_PREFIX_BYTES = 4;\nvar MAX_ORIGIN_FRAME_HEAD_BYTES = 2 * (MAX_ORIGIN_HEADER_BYTES + MAX_ORIGIN_TARGET_BYTES) + 16 * 1024;\nvar HOP_BY_HOP = /* @__PURE__ */ new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\"\n]);\nvar IGNORED = /* @__PURE__ */ new Set([\n \"host\",\n \"forwarded\",\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n \"x-real-ip\"\n]);\nfunction originTarget(url) {\n const parsed = new URL(url);\n return `${parsed.pathname}${parsed.search}`;\n}\nfunction requestHeaders(headers) {\n const out = [];\n headers.forEach((value, name) => {\n const lower = name.toLowerCase();\n if (HOP_BY_HOP.has(lower) || IGNORED.has(lower))\n return;\n out.push({ name: lower, value });\n });\n return out;\n}\nfunction originBinding(transport) {\n return Object.freeze({\n async fetch(request, options) {\n const head = {\n method: request.method,\n target: originTarget(request.url),\n headers: requestHeaders(request.headers),\n ...options?.clientAddress ? { clientAddress: options.clientAddress } : {}\n };\n const reply = await transport.fetch(head, request.body);\n if (\"err\" in reply)\n throw PluginError.fromWire(reply.err.code, reply.err.message);\n const headers = new Headers();\n for (const field of reply.ok.headers)\n headers.append(field.name, field.value);\n const nullBody = [101, 204, 205, 304].includes(reply.ok.status);\n return new Response(nullBody ? null : reply.ok.body, { status: reply.ok.status, headers });\n }\n });\n}\nfunction encodeOriginFrame(head) {\n const json = new TextEncoder().encode(JSON.stringify(head));\n if (json.length > MAX_ORIGIN_FRAME_HEAD_BYTES) {\n throw PluginError.fromWire(\"invalid_params\", \"origin request head is too large\");\n }\n const out = new Uint8Array(ORIGIN_FRAME_PREFIX_BYTES + json.length);\n new DataView(out.buffer).setUint32(0, json.length, false);\n out.set(json, ORIGIN_FRAME_PREFIX_BYTES);\n return out;\n}\nfunction framedBody(frame2, body) {\n const reader = body?.getReader();\n let sentHead = false;\n return new ReadableStream({\n async pull(controller) {\n if (!sentHead) {\n sentHead = true;\n controller.enqueue(frame2);\n return;\n }\n if (!reader) {\n controller.close();\n return;\n }\n const { done, value } = await reader.read();\n if (done)\n controller.close();\n else\n controller.enqueue(value);\n },\n async cancel(reason) {\n await reader?.cancel(reason);\n }\n });\n}\nasync function readOriginResponse(body) {\n const reader = body.getReader();\n let buffered = new Uint8Array(0);\n let need = -1;\n for (; ; ) {\n if (need < 0 && buffered.length >= ORIGIN_FRAME_PREFIX_BYTES) {\n need = new DataView(buffered.buffer, buffered.byteOffset, buffered.length).getUint32(0, false);\n if (need > MAX_ORIGIN_FRAME_HEAD_BYTES) {\n await reader.cancel();\n throw PluginError.fromWire(\"internal\", \"origin response head is too large\");\n }\n }\n if (need >= 0 && buffered.length >= ORIGIN_FRAME_PREFIX_BYTES + need)\n break;\n const { done, value } = await reader.read();\n if (done)\n throw PluginError.fromWire(\"internal\", \"origin response ended inside its head\");\n const next = new Uint8Array(buffered.length + value.length);\n next.set(buffered);\n next.set(value, buffered.length);\n buffered = next;\n }\n const end = ORIGIN_FRAME_PREFIX_BYTES + need;\n const head = parseResponseHead(new TextDecoder().decode(buffered.subarray(4, end)));\n const rest = buffered.slice(end);\n const out = new ReadableStream({\n start(controller) {\n if (rest.length > 0)\n controller.enqueue(rest);\n },\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done)\n controller.close();\n else\n controller.enqueue(value);\n },\n async cancel(reason) {\n await reader.cancel(reason);\n }\n });\n return { ...head, body: out };\n}\nfunction parseResponseHead(text) {\n let value;\n try {\n value = JSON.parse(text);\n } catch {\n throw PluginError.fromWire(\"internal\", \"origin response head is not JSON\");\n }\n const record = value ?? {};\n const status = record.status;\n if (typeof status !== \"number\" || !Number.isInteger(status) || status < 100 || status > 599) {\n throw PluginError.fromWire(\"internal\", \"origin response head has no valid status\");\n }\n const headers = [];\n for (const field of Array.isArray(record.headers) ? record.headers : []) {\n const f = field ?? {};\n if (typeof f.name !== \"string\" || typeof f.value !== \"string\") {\n throw PluginError.fromWire(\"internal\", \"origin response head has a malformed header\");\n }\n headers.push({ name: f.name, value: f.value });\n }\n return { status, headers };\n}\nasync function grantedOriginFetch(granted, auth, head, body) {\n let frame2;\n try {\n frame2 = encodeOriginFrame(head);\n } catch (err) {\n return { err: errorOf(err) };\n }\n let resp;\n try {\n resp = await granted.fetch(\"http://granted/origin/fetch\", {\n method: \"POST\",\n headers: { ...auth, \"content-type\": \"application/octet-stream\" },\n body: framedBody(frame2, body),\n // Node\'s fetch needs this for a streamed body; workerd ignores it.\n duplex: \"half\"\n });\n } catch (err) {\n return { err: { code: \"unavailable\", message: `origin fetch: ${messageOf(err)}` } };\n }\n if (resp.status !== 200 || !resp.body) {\n const value = await resp.json().catch(() => null);\n return {\n err: {\n code: value?.error?.code || \"internal\",\n message: value?.error?.message || `origin fetch HTTP ${resp.status}`\n }\n };\n }\n try {\n return { ok: await readOriginResponse(resp.body) };\n } catch (err) {\n return { err: errorOf(err) };\n }\n}\nfunction errorOf(err) {\n if (err instanceof PluginError)\n return { code: err.code, message: err.message };\n return { code: \"internal\", message: messageOf(err) };\n}\nfunction messageOf(err) {\n return err instanceof Error ? err.message : String(err);\n}\n\n// dist/webhooks.js\nvar DEFAULT_WEBHOOK_PULL_BATCH = 10;\nfunction checkWebhookName(name) {\n const text = String(name ?? \"\");\n if (text.length === 0 || text.length > MAX_WEBHOOK_NAME_BYTES || !/^[a-z0-9][a-z0-9-]*$/.test(text)) {\n throw PluginError.fromWire(\"invalid_params\", \"malformed webhook name\");\n }\n return text;\n}\nfunction checkLeases(leases) {\n const list = Array.isArray(leases) ? leases.map(String) : [];\n if (list.length > MAX_WEBHOOK_PULL_BATCH) {\n throw PluginError.fromWire(\"invalid_params\", `a webhook ack names at most ${MAX_WEBHOOK_PULL_BATCH} leases in each list`);\n }\n for (const lease of list) {\n if (lease.length === 0 || lease.length > MAX_WEBHOOK_LEASE_ID_BYTES || !/^[A-Za-z0-9_-]+$/.test(lease)) {\n throw PluginError.fromWire(\"invalid_params\", \"malformed webhook lease id\");\n }\n }\n return list;\n}\nfunction fromBase642(text) {\n if (typeof text !== \"string\" || text === \"\")\n return new Uint8Array();\n const bin = atob(text);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++)\n out[i] = bin.charCodeAt(i);\n return out;\n}\nasync function call2(transport, op, body) {\n const reply = await transport.call(op, body);\n if (\"err\" in reply) {\n throw PluginError.fromWire(reply.err.code || \"internal\", reply.err.message || \"\");\n }\n return reply.ok ?? {};\n}\nfunction messageOf2(wire) {\n const headers = {};\n if (Array.isArray(wire.headers)) {\n for (const header of wire.headers) {\n if (header && typeof header.name === \"string\") {\n headers[header.name] = String(header.value ?? \"\");\n }\n }\n }\n return Object.freeze({\n leaseId: String(wire.leaseId ?? \"\"),\n timestamp: new Date(Number(wire.receivedAtUnixMs ?? 0) || 0),\n attempts: Number(wire.attempt ?? 0) || 0,\n headers: Object.freeze(headers),\n body: fromBase642(wire.body)\n });\n}\nfunction webhooksBinding(transport) {\n return Object.freeze({\n async url(name) {\n const reply = await call2(transport, \"url\", { name: checkWebhookName(name) });\n return typeof reply.url === \"string\" && reply.url !== \"\" ? reply.url : null;\n },\n async pull(name, options) {\n const batchSize = Math.floor(Number(options?.batchSize ?? DEFAULT_WEBHOOK_PULL_BATCH));\n if (!(batchSize >= 1 && batchSize <= MAX_WEBHOOK_PULL_BATCH)) {\n throw PluginError.fromWire(\"invalid_params\", `webhook batch size must be 1..=${MAX_WEBHOOK_PULL_BATCH}`);\n }\n const visibilityTimeoutMs = Math.floor(Number(options?.visibilityTimeoutMs ?? 0));\n if (!(visibilityTimeoutMs >= 0 && visibilityTimeoutMs <= MAX_WEBHOOK_VISIBILITY_MS)) {\n throw PluginError.fromWire(\"invalid_params\", `webhook visibility timeout must be at most ${MAX_WEBHOOK_VISIBILITY_MS} ms`);\n }\n const reply = await call2(transport, \"pull\", {\n name: checkWebhookName(name),\n batchSize,\n visibilityTimeoutMs\n });\n const deliveries = Array.isArray(reply.deliveries) ? reply.deliveries : [];\n return { messages: deliveries.map(messageOf2), missed: reply.missed === true };\n },\n async ack(name, leases) {\n const acks = checkLeases(leases?.acks);\n const retries = checkLeases(leases?.retries);\n if (retries.some((lease) => acks.includes(lease))) {\n throw PluginError.fromWire(\"invalid_params\", \"a webhook lease is both acknowledged and retried\");\n }\n await call2(transport, \"ack\", { name: checkWebhookName(name), acks, retries });\n }\n });\n}\n\n// dist/plugin.js\nfunction unsupported(method) {\n return PluginError.fromWire(\"unsupported\", `${method} not implemented`);\n}\nfunction utf8Bytes2(value) {\n return new TextEncoder().encode(String(value ?? \"\")).byteLength;\n}\nfunction errorMessage(err) {\n return err instanceof Error ? err.message : String(err);\n}\nfunction schemaMigrationOp(sql) {\n return { schema: sql };\n}\nfunction dataMigrationOp(sql) {\n return { data: sql };\n}\nvar Destination = class extends RpcTarget {\n /**\n * Metadata without a body; `null` when the key is missing.\n *\n * @param _key - Object key.\n * @returns Metadata or `null` when the key is missing.\n */\n head(_key) {\n return Promise.reject(unsupported(\"head\"));\n }\n /**\n * One page of keys under `options.prefix`.\n *\n * @param _options - Prefix, cursor, and limit.\n * @returns One page of object keys.\n */\n list(_options) {\n return Promise.reject(unsupported(\"list\"));\n }\n /**\n * Streamed read. The body is a transferred stream, not a scalar.\n *\n * @param _key - Object key.\n * @param _options - Optional byte range.\n * @returns Metadata plus a transferred body stream.\n */\n get(_key, _options) {\n return Promise.reject(unsupported(\"get\"));\n }\n /**\n * Streamed write. `body` ownership is transferred to the destination.\n *\n * @param _key - Object key.\n * @param _body - Byte stream.\n * @param _options - Optional content type / length.\n * @returns Bytes written and optional etag / sha256.\n */\n put(_key, _body, _options) {\n return Promise.reject(unsupported(\"put\"));\n }\n /**\n * Server-side copy when the backend supports it.\n *\n * @param _from - Source key.\n * @param _to - Destination key.\n * @returns Bytes copied.\n */\n copy(_from, _to) {\n return Promise.reject(unsupported(\"copy\"));\n }\n /**\n * Delete a key (no-op if missing).\n *\n * @param _key - Object key.\n * @returns Resolves when the delete is complete.\n */\n delete(_key) {\n return Promise.reject(unsupported(\"delete\"));\n }\n /**\n * Finalize a destination-side staged object.\n *\n * @param _key - Object key.\n * @param _commitToken - Idempotency / commit token.\n * @returns Published object metadata.\n */\n commit(_key, _commitToken) {\n return Promise.reject(unsupported(\"commit\"));\n }\n /**\n * Abort a destination-side staged object.\n *\n * @param _key - Object key.\n * @param _commitToken - Staging token to discard.\n * @returns Rejects with typed `unsupported` unless overridden.\n */\n abortStage(_key, _commitToken) {\n return Promise.reject(unsupported(\"abortStage\"));\n }\n /**\n * Move one object (declare `storage.move`). Repeating a finished move\n * resolves with `alreadyMoved`.\n *\n * @param _from - Source key.\n * @param _to - Target key.\n * @param _options - Overwrite and source preconditions.\n * @returns How the move was done.\n */\n move(_from, _to, _options) {\n return Promise.reject(unsupported(\"move\"));\n }\n /**\n * Move a set of objects or a whole prefix, one page per call (declare\n * `storage.moveMany`). Safe to repeat.\n *\n * @param _request - Pairs or prefix, cursor, and options.\n * @returns Per-key outcomes and the continuation.\n */\n moveMany(_request) {\n return Promise.reject(unsupported(\"moveMany\"));\n }\n /**\n * Remove up to `MAX_BATCH_KEYS` objects (declare `storage.deleteMany`).\n *\n * @param _keys - Object keys.\n * @returns One outcome per key, in order; a missing key succeeds.\n */\n deleteMany(_keys) {\n return Promise.reject(unsupported(\"deleteMany\"));\n }\n /**\n * Probe up to `MAX_BATCH_KEYS` objects (declare `storage.headMany`).\n *\n * @param _keys - Object keys.\n * @returns One entry per key, in order; `null` when missing.\n */\n headMany(_keys) {\n return Promise.reject(unsupported(\"headMany\"));\n }\n /**\n * Keys changed since a cursor (declare `storage.changes`).\n *\n * @param _request - Cursor and page size.\n * @returns One page of changes.\n */\n changes(_request) {\n return Promise.reject(unsupported(\"changes\"));\n }\n /**\n * Translate up to `MAX_BATCH_KEYS` host keys into the keys this\n * destination stores them under (declare `storage.translateKeys`). A host\n * key is `/`-joined segments, none empty, `.`, `..` or holding `\\` or a\n * control character; return a relative key with the same properties. The\n * same host key must always translate to the same key. Without the\n * feature the host stores each host key as written.\n *\n * @param _keys - Host keys.\n * @returns One translated key per host key, in order.\n */\n translateKeys(_keys) {\n return Promise.reject(unsupported(\"translateKeys\"));\n }\n};\nvar Source = class extends RpcTarget {\n /**\n * Opens `key` for streamed reading.\n *\n * @param _key - Object key.\n * @returns Metadata plus a transferred body stream.\n */\n open(_key) {\n return Promise.reject(unsupported(\"open\"));\n }\n};\nvar ProgressSink = class extends RpcTarget {\n /**\n * Reports `percent` in `0..=100` and an operator-facing `message`.\n *\n * @param _percent - Completion percent.\n * @param _message - Operator-facing status.\n * @returns Resolves when the host records progress.\n */\n report(_percent, _message) {\n return Promise.reject(unsupported(\"report\"));\n }\n};\nvar AdapterDatabaseSession = class extends RpcTarget {\n /**\n * Typed SQL-contract advertisement.\n *\n * @returns Guest `DbCapabilities`.\n */\n capabilities() {\n return Promise.reject(unsupported(\"capabilities\"));\n }\n /**\n * Typed atomic batch (`ExecuteRequest` \u{2192} `ExecuteReply`).\n *\n * @param _request - Cap\'n `ExecuteRequest` (structured Workers RPC object).\n * @returns `ExecuteReply`.\n */\n execute(_request) {\n return Promise.reject(unsupported(\"execute\"));\n }\n /**\n * The same atomic batch as {@link AdapterDatabaseSession.execute}, answered\n * as concatenated `ExecuteStreamFrame` messages counted against the\n * advertised `maxStreamedResultBytes` / `maxStreamedResultRows`; optional.\n * Adapters that advertise `0` for both leave the default, which answers\n * `unsupported`. An isolate adapter\'s frames travel inside one invoke\n * reply, so its streamed budget is clamped to `MAX_SCALAR_BYTES` (256 KiB)\n * and larger frames are a `limit_exceeded` (`maxScalarBytes`) error.\n * `executeAdapterBatchStreamed` runs the batch, stores the replay receipt\n * and checks that bound before it commits.\n *\n * @param _request - Proven statements plus isolation and receipt.\n * @returns Every frame of the committed reply, concatenated.\n */\n executeStreamed(_request) {\n return Promise.reject(unsupported(\"executeStreamed\"));\n }\n /**\n * Close the adapter session.\n *\n * @returns Resolves when the session is closed.\n */\n close() {\n return Promise.resolve();\n }\n /**\n * Bootstrap-only diagnostic metadata (`DbBootstrap`); optional.\n *\n * @returns Engine identity for diagnostics.\n */\n bootstrap() {\n return Promise.reject(unsupported(\"bootstrap\"));\n }\n /**\n * Identity high-water marks for a logical export; optional.\n *\n * @returns One row per identity column.\n */\n exportIdentity() {\n return Promise.reject(unsupported(\"exportIdentity\"));\n }\n /**\n * Restore identity high-water marks after a logical import; optional.\n *\n * @param _rows - Rows from an earlier {@link AdapterDatabaseSession.exportIdentity}.\n * @returns Resolves when the marks are applied.\n */\n importIdentity(_rows) {\n return Promise.reject(unsupported(\"importIdentity\"));\n }\n /**\n * Names of user relations the host may drop before a restore; optional.\n *\n * @returns Relation names.\n */\n listUserRelations() {\n return Promise.reject(unsupported(\"listUserRelations\"));\n }\n /**\n * Prepare the engine for a unit restore (disable constraints, \u{2026}); optional.\n *\n * @returns Resolves when the engine is ready for the restore.\n */\n prepareUnitRestore() {\n return Promise.reject(unsupported(\"prepareUnitRestore\"));\n }\n /**\n * Drop the named user relations; optional.\n *\n * @param _names - Relation names from {@link AdapterDatabaseSession.listUserRelations}.\n * @returns Resolves when the relations are gone.\n */\n dropUserRelations(_names) {\n return Promise.reject(unsupported(\"dropUserRelations\"));\n }\n /**\n * Re-check constraints after a unit restore; optional.\n *\n * @returns Resolves when every constraint holds.\n */\n assertRestoreConstraints() {\n return Promise.reject(unsupported(\"assertRestoreConstraints\"));\n }\n};\nfunction decodeExtensibleConfig(cfg) {\n if (cfg == null)\n return {};\n if (typeof cfg !== \"object\")\n return {};\n const record = cfg;\n const payload = record.payload;\n let text = \"\";\n if (payload instanceof Uint8Array) {\n text = new TextDecoder().decode(payload);\n } else if (payload instanceof ArrayBuffer) {\n text = new TextDecoder().decode(new Uint8Array(payload));\n } else if (typeof payload === \"string\") {\n text = payload;\n } else if (payload && typeof payload === \"object\" && !(\"schemaVersion\" in record)) {\n return payload;\n }\n const mediaType = String(record.mediaType ?? \"\");\n if (!text.trim())\n return {};\n if (mediaType === \"\" || /json/i.test(mediaType)) {\n try {\n const parsed = JSON.parse(text);\n return parsed === null || typeof parsed !== \"object\" ? {} : parsed;\n } catch {\n return {};\n }\n }\n return { mediaType, text };\n}\nfunction jsonPayload(value) {\n return {\n schemaVersion: 1,\n mediaType: \"application/json\",\n payload: new TextEncoder().encode(JSON.stringify(value ?? null))\n };\n}\nfunction cliArgs(params) {\n const out = {};\n for (const arg of params?.args ?? []) {\n if (arg && typeof arg.name === \"string\")\n out[arg.name] = String(arg.value ?? \"\");\n }\n return out;\n}\nfunction invocationEnv(rawEnv, context) {\n const merged = { ...rawEnv ?? {} };\n if (context && typeof context === \"object\") {\n if (context.config !== void 0)\n merged.CONFIG = decodeExtensibleConfig(context.config);\n if (context.secrets !== void 0)\n merged.SECRETS = decodeExtensibleConfig(context.secrets);\n if (context.storage)\n merged.WORK_FS = context.storage;\n if (context.events)\n merged.EVENTS = context.events;\n if (context.notify)\n merged.NOTIFY = context.notify;\n if (context.ai)\n merged.AI = context.ai;\n if (Array.isArray(context.databases)) {\n for (const entry of context.databases) {\n if (!entry || typeof entry.name !== \"string\" || !entry.name)\n continue;\n if (entry.database) {\n merged[entry.name] = entry.database;\n } else if (entry.transport) {\n merged[entry.name] = transportDatabase(entry.transport);\n }\n }\n }\n if (Array.isArray(context.queues)) {\n for (const entry of context.queues) {\n if (!entry || typeof entry.name !== \"string\" || !entry.name || !entry.queue)\n continue;\n merged[entry.name] = entry.queue;\n }\n }\n if (Array.isArray(context.kv)) {\n for (const entry of context.kv) {\n if (!entry || typeof entry.name !== \"string\" || !entry.name || !entry.kv)\n continue;\n merged[entry.name] = entry.kv;\n }\n }\n const sockets = socketsTransportOf(context);\n if (sockets)\n merged[sockets.name] = socketsBinding(sockets.sockets);\n if (context.origin)\n merged.ORIGIN = originBinding(context.origin);\n if (context.webhooks)\n merged.WEBHOOKS = webhooksBinding(context.webhooks);\n if (context.network && typeof context.network === \"object\") {\n merged.NETWORK = Object.freeze(normalizeNetworkGrant(context.network));\n }\n }\n return Object.freeze(merged);\n}\nfunction normalizeNetworkGrant(grant) {\n return {\n outbound: grant.outbound === true,\n domains: Array.isArray(grant.domains) ? grant.domains : [],\n tcp: Array.isArray(grant.tcp) ? grant.tcp : [],\n settings: Array.isArray(grant.settings) ? grant.settings : []\n };\n}\nfunction transportDatabase(entry) {\n const transport = entry;\n const execute = typeof transport.executeBytes === \"function\" ? async (request) => decodeExecuteResultReply(await transport.executeBytes(encodeExecuteRequest(request))) : (request) => transport.execute(request);\n const readLimits = typeof transport.limitsBytes === \"function\" ? async () => decodeDbCapabilitiesReply(await transport.limitsBytes()) : typeof transport.limits === \"function\" ? () => transport.limits() : void 0;\n const streamed = typeof transport.openStreamedBytes === \"function\" ? (request) => transport.openStreamedBytes(encodeExecuteRequest(request)) : typeof transport.executeStreamed === \"function\" ? (request) => transport.executeStreamed(request) : void 0;\n return createDatabaseBinding({\n execute,\n ...readLimits ? { limits: readLimits } : {},\n ...streamed ? { executeStreamed: streamed } : {}\n });\n}\nfunction socketsTransportOf(context) {\n const list = context && Array.isArray(context.sockets) ? context.sockets : [];\n return list.find((entry) => entry && typeof entry.name === \"string\" && entry.name !== \"\" && entry.sockets);\n}\nfunction applyInvocationEnv(instance, context) {\n const target = instance;\n const merged = invocationEnv(target.env, context);\n try {\n target.env = merged;\n } catch {\n Object.defineProperty(instance, \"env\", { value: merged, configurable: true });\n }\n}\nfunction invocationOf(context) {\n const inv = context && typeof context === \"object\" ? context.invocation ?? {} : {};\n return Object.freeze({\n id: String(inv.id ?? \"\"),\n accountId: String(inv.accountId ?? \"\"),\n deadlineUnixMs: Number(inv.deadlineUnixMs ?? 0) || 0,\n correlationId: String(inv.correlationId ?? \"\"),\n causationId: String(inv.causationId ?? \"\")\n });\n}\nfunction unixMs(value) {\n if (value instanceof Date)\n return value.getTime();\n const n = Number(value ?? 0);\n return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;\n}\nfunction checkpointText(checkpoint) {\n if (checkpoint === void 0 || checkpoint === null)\n return \"\";\n const text = typeof checkpoint === \"string\" ? checkpoint : JSON.stringify(checkpoint);\n if (utf8Bytes2(text) > MAX_CHECKPOINT_BYTES) {\n throw PluginError.fromWire(\"payload_too_large\", `checkpoint is ${utf8Bytes2(text)} bytes; exceeds maxCheckpointBytes (${MAX_CHECKPOINT_BYTES})`);\n }\n return text;\n}\nvar EventMessage = class {\n #result = null;\n /** Outbox event id. */\n id;\n /** Event type (`book_acquired`, \u{2026}). */\n type;\n /** Schema version of {@link EventMessage.body}. */\n schemaVersion;\n /** When the producer observed the fact. */\n timestamp;\n /** Delivery counter, starting at 1. */\n attempts;\n /** Account scope; empty for host-wide events. */\n accountId;\n /** Producer plugin id; empty when unknown. */\n source;\n /** Trace correlation id. */\n correlationId;\n /** Id of the command or event that caused this one. */\n causationId;\n /** Consumer-side idempotency key; stable across redeliveries. */\n deduplicationKey;\n /** Encoded payload bytes. */\n body;\n /** Resume ordinal; distinct from `attempts`. */\n invocationSequence;\n /** True when this delivery resumes a prior `suspend()`. */\n resumePending;\n /** Checkpoint from the prior `suspend()`, or `null`. */\n checkpoint;\n /** Raw wire envelope. */\n raw;\n constructor(event) {\n const e = event && typeof event === \"object\" ? event : {};\n this.id = String(e.eventId ?? \"\");\n this.type = String(e.eventType ?? \"\");\n this.schemaVersion = Number(e.schemaVersion ?? 0) || 0;\n this.timestamp = new Date(Number(e.occurredAtUnixMs ?? 0) || 0);\n this.attempts = Number(e.deliveryAttempt ?? 1) || 1;\n this.accountId = String(e.accountId ?? \"\");\n this.source = String(e.source ?? \"\");\n this.correlationId = String(e.correlationId ?? \"\");\n this.causationId = String(e.causationId ?? \"\");\n this.deduplicationKey = String(e.deduplicationKey ?? \"\");\n const payload = e.payload;\n this.body = payload instanceof Uint8Array ? payload : payload instanceof ArrayBuffer ? new Uint8Array(payload) : new Uint8Array();\n this.invocationSequence = Number(e.invocationSequence ?? 0) || 0;\n this.resumePending = Boolean(e.resumePending);\n const checkpointJson = String(e.checkpointJson ?? \"\");\n this.checkpoint = checkpointJson ? Object.freeze({\n json: checkpointJson,\n schemaVersion: Number(e.checkpointSchemaVersion ?? 0) || 0\n }) : null;\n this.raw = e;\n }\n /**\n * Decode {@link EventMessage.body} as JSON.\n *\n * @returns Parsed payload (`{}` for an empty body).\n */\n json() {\n if (this.body.byteLength === 0)\n return {};\n return JSON.parse(new TextDecoder().decode(this.body));\n }\n /**\n * Recorded outcome.\n *\n * @returns The outcome, or `null` while undecided.\n */\n get result() {\n return this.#result;\n }\n #record(result) {\n if (this.#result === null)\n this.#result = Object.freeze(result);\n }\n /** Mark handled; the host marks the event delivered. */\n ack() {\n this.#record({ kind: \"ack\" });\n }\n /**\n * Redeliver later: at `retryAt`, after `delaySeconds`, or \u{2014} when both are\n * omitted \u{2014} whenever the host\'s backoff chooses.\n *\n * @param options - Redelivery timing and reason.\n */\n retry(options) {\n const explicit = unixMs(options?.retryAt);\n const delay = Number(options?.delaySeconds ?? 0) || 0;\n this.#record({\n kind: \"retry\",\n retryAtUnixMs: explicit || (delay > 0 ? Date.now() + Math.floor(delay * 1e3) : 0),\n reason: String(options?.reason ?? \"\")\n });\n }\n /**\n * Stop delivering; the host records `reason`.\n *\n * @param reason - Short operator-facing reason.\n */\n reject(reason) {\n this.#record({ kind: \"reject\", reason: String(reason ?? \"\") });\n }\n /**\n * Park for operator review.\n *\n * @param reason - Short operator-facing reason.\n */\n deadLetter(reason) {\n this.#record({ kind: \"deadLetter\", reason: String(reason ?? \"\") });\n }\n /**\n * Release with a bounded checkpoint; the host redelivers at `wakeAt` or\n * when a `wakeOnEventType` event arrives.\n *\n * @param options - Checkpoint and wake conditions.\n */\n suspend(options) {\n const opts = options ?? {};\n this.#record({\n kind: \"suspended\",\n checkpointJson: checkpointText(opts.checkpoint),\n checkpointSchemaVersion: Number(opts.checkpointSchemaVersion ?? 1) || 1,\n wakeAtUnixMs: unixMs(opts.wakeAt),\n wakeOnEventType: String(opts.wakeOnEventType ?? \"\"),\n wakeOnFilterJson: opts.wakeOnFilter === void 0 || opts.wakeOnFilter === null ? \"\" : typeof opts.wakeOnFilter === \"string\" ? opts.wakeOnFilter : JSON.stringify(opts.wakeOnFilter)\n });\n }\n};\nvar EventBatch = class {\n /** Messages in delivery order. */\n messages;\n /** Invocation identity of this delivery. */\n invocation;\n constructor(events, invocation) {\n this.messages = Object.freeze((Array.isArray(events) ? events : []).map((event) => new EventMessage(event)));\n this.invocation = invocation ?? invocationOf(void 0);\n }\n /**\n * Event type shared by the batch.\n *\n * @returns The shared type, or `\"\"` when mixed or empty.\n */\n get type() {\n const first = this.messages[0]?.type ?? \"\";\n return this.messages.every((m) => m.type === first) ? first : \"\";\n }\n /** Ack every message. */\n ackAll() {\n for (const m of this.messages)\n m.ack();\n }\n /**\n * Retry every message.\n *\n * @param options - Redelivery timing and reason.\n */\n retryAll(options) {\n for (const m of this.messages)\n m.retry(options);\n }\n};\nfunction eventBatchResults(batch, failed) {\n return batch.messages.map((m) => {\n if (m.result)\n return m.result;\n if (failed !== void 0) {\n return { kind: \"retry\", retryAtUnixMs: 0, reason: errorMessage(failed) };\n }\n return { kind: \"ack\" };\n });\n}\nvar QueueMessage = class {\n #result = null;\n /** Outbox row id; stable across redeliveries. */\n id;\n /** When the producer sent the message. */\n timestamp;\n /** Encoded body bytes. */\n body;\n /** Body encoding: `json`, `text`, or `bytes`. */\n contentType;\n /** Delivery counter, starting at 1. */\n attempts;\n /** Producer plugin id; empty when the host sent it. */\n source;\n /** Raw wire envelope. */\n raw;\n constructor(message) {\n const m = message && typeof message === \"object\" ? message : {};\n this.id = String(m.id ?? \"\");\n this.timestamp = new Date(Number(m.timestampUnixMs ?? 0) || 0);\n const body = m.body;\n this.body = body instanceof Uint8Array ? body : body instanceof ArrayBuffer ? new Uint8Array(body) : new Uint8Array();\n this.contentType = String(m.contentType ?? \"\") || \"json\";\n this.attempts = Number(m.attempts ?? 1) || 1;\n this.source = String(m.source ?? \"\");\n this.raw = m;\n }\n /**\n * Decode {@link QueueMessage.body} as JSON.\n *\n * @returns Parsed body (`null` for an empty body).\n */\n json() {\n if (this.body.byteLength === 0)\n return null;\n return JSON.parse(new TextDecoder().decode(this.body));\n }\n /**\n * Decode {@link QueueMessage.body} as UTF-8 text.\n *\n * @returns The body text.\n */\n text() {\n return new TextDecoder().decode(this.body);\n }\n /**\n * Recorded outcome.\n *\n * @returns The outcome, or `null` while undecided.\n */\n get result() {\n return this.#result;\n }\n #record(result) {\n if (this.#result === null)\n this.#result = Object.freeze(result);\n }\n /** Mark handled; the host marks the message delivered. */\n ack() {\n this.#record({ kind: \"ack\" });\n }\n /**\n * Redeliver later: after `delaySeconds`, or \u{2014} when omitted \u{2014} after the\n * consumer\'s `retry_delay`.\n *\n * @param options - Redelivery timing and reason.\n */\n retry(options) {\n this.#record({\n kind: \"retry\",\n delaySeconds: Math.max(0, Math.floor(Number(options?.delaySeconds ?? 0) || 0)),\n reason: String(options?.reason ?? \"\")\n });\n }\n};\nvar QueueBatch = class {\n /** Queue the messages were sent to. */\n queue;\n /** Messages in delivery order. */\n messages;\n /** Invocation identity of this delivery. */\n invocation;\n constructor(queue, messages, invocation) {\n this.queue = String(queue ?? \"\");\n this.messages = Object.freeze((Array.isArray(messages) ? messages : []).map((message) => new QueueMessage(message)));\n this.invocation = invocation ?? invocationOf(void 0);\n }\n /** Ack every message. */\n ackAll() {\n for (const m of this.messages)\n m.ack();\n }\n /**\n * Retry every message.\n *\n * @param options - Redelivery timing and reason.\n */\n retryAll(options) {\n for (const m of this.messages)\n m.retry(options);\n }\n};\nfunction queueBatchResults(batch, failed) {\n return batch.messages.map((m) => {\n if (m.result)\n return m.result;\n if (failed !== void 0) {\n return { kind: \"retry\", delaySeconds: 0, reason: errorMessage(failed) };\n }\n return { kind: \"ack\" };\n });\n}\nvar JobController = class {\n #result = null;\n #progress;\n #abort;\n /** Full durable envelope as delivered. */\n invocation;\n /** Unique id of this invocation attempt. */\n id;\n /** Command type the handler dispatches on. */\n type;\n /** Command payload JSON text. */\n payloadJson;\n /** Schema version of {@link JobController.payloadJson}. */\n payloadSchemaVersion;\n /** Caller idempotency key. */\n idempotencyKey;\n /** Failure retry counter, starting at 1. */\n attempt;\n /** Deadline hint (Unix ms); the host fence is authoritative. */\n deadlineUnixMs;\n /** Trace correlation id. */\n correlationId;\n /** Id of the event or command that caused this job. */\n causationId;\n /** Resume ordinal. */\n invocationSequence;\n /** Step id within a multi-step command; empty when single-step. */\n stepId;\n /** Checkpoint from the prior `suspend()`, or `null`. */\n checkpoint;\n /** Granted byte source, when the job has input. */\n input;\n /** Granted object store, when the job has output. */\n output;\n /** Aborts when the host cancels the invocation. */\n signal;\n constructor(invocation, granted) {\n const inv = invocation && typeof invocation === \"object\" ? invocation : {};\n this.invocation = Object.freeze({ ...inv });\n this.id = String(inv.invocationId ?? \"\");\n this.type = String(inv.commandType ?? \"\");\n this.payloadJson = String(inv.payloadJson ?? \"\");\n this.payloadSchemaVersion = Number(inv.payloadSchemaVersion ?? 0) || 0;\n this.idempotencyKey = String(inv.idempotencyKey ?? \"\");\n this.attempt = Number(inv.attempt ?? 1) || 1;\n this.deadlineUnixMs = Number(inv.deadlineUnixMs ?? 0) || 0;\n this.correlationId = String(inv.correlationId ?? \"\");\n this.causationId = String(inv.causationId ?? \"\");\n this.invocationSequence = Number(inv.invocationSequence ?? 0) || 0;\n this.stepId = String(inv.stepId ?? \"\");\n const checkpointJson = String(inv.checkpointJson ?? \"\");\n this.checkpoint = checkpointJson ? Object.freeze({\n json: checkpointJson,\n schemaVersion: Number(inv.checkpointSchemaVersion ?? 0) || 0\n }) : null;\n this.input = granted?.input ?? null;\n this.output = granted?.output ?? null;\n this.#progress = granted?.progress ?? null;\n this.#abort = new AbortController();\n this.signal = this.#abort.signal;\n const cancel = granted?.cancel;\n if (cancel && typeof cancel.wait === \"function\") {\n Promise.resolve().then(() => cancel.wait()).then(() => this.#abort.abort(PluginError.fromWire(\"cancelled\", \"job cancelled by host\")), () => {\n });\n }\n }\n /**\n * Decode {@link JobController.payloadJson}.\n *\n * @returns Parsed payload (`{}` when empty).\n */\n json() {\n return this.payloadJson ? JSON.parse(this.payloadJson) : {};\n }\n /**\n * Report `percent` in `0..=100` with an operator-facing `message`.\n *\n * @param percent - Completion percent.\n * @param message - Operator-facing status.\n * @returns Resolves when the host records progress.\n */\n async progress(percent, message) {\n if (!this.#progress)\n return;\n await this.#progress.report(Number(percent) || 0, String(message ?? \"\"));\n }\n /**\n * Recorded terminal outcome.\n *\n * @returns The outcome, or `null` while the job is still running.\n */\n get result() {\n return this.#result;\n }\n #record(result) {\n if (this.#result === null)\n this.#result = Object.freeze(result);\n }\n /**\n * Release with a bounded checkpoint; the host resumes at `wakeAt`.\n *\n * @param options - Checkpoint and wake time.\n */\n suspend(options) {\n const opts = options ?? {};\n this.#record({\n kind: \"suspended\",\n checkpoint: {\n schemaVersion: Number(opts.checkpointSchemaVersion ?? 1) || 1,\n json: checkpointText(opts.checkpoint)\n },\n wakeAtUnixMs: unixMs(opts.wakeAt)\n });\n }\n /**\n * Give up this attempt and let the host retry at `retryAt` (or its default).\n *\n * @param options - Retry time and reason.\n */\n retryLater(options) {\n const opts = options ?? {};\n this.#record({\n kind: \"retryable\",\n message: String(opts.reason ?? \"\"),\n retryAfterUnixMs: unixMs(opts.retryAt)\n });\n }\n /** Host-side cancellation observed (adapter-internal). */\n cancel() {\n this.#abort.abort(PluginError.fromWire(\"cancelled\", \"job cancelled by host\"));\n }\n};\nfunction jobOutcomeFor(job, returned, failed) {\n if (job.result)\n return job.result;\n if (failed !== void 0) {\n const code = failed && typeof failed === \"object\" ? failed.wireCode ?? failed.code : void 0;\n if (job.signal.aborted || code === \"cancelled\") {\n return { kind: \"cancelled\", message: errorMessage(failed) };\n }\n if (code === \"unavailable\" || code === \"deadline_exceeded\") {\n return { kind: \"retryable\", message: errorMessage(failed), retryAfterUnixMs: 0 };\n }\n return { kind: \"rejected\", message: errorMessage(failed) };\n }\n const extra = returned && typeof returned === \"object\" ? returned : {};\n return {\n kind: \"completed\",\n message: String(extra.message ?? \"\"),\n bytesCopied: Number(extra.bytesCopied ?? 0) || 0\n };\n}\nvar BookclerkEntrypoint = class extends WorkerEntrypoint {\n /**\n * Rejects HTTP fetch \u{2014} workerd guests are Workers-RPC only.\n *\n * @param _request - Incoming HTTP request when the entrypoint is fetch-facing.\n * @returns Always a 404 empty response.\n */\n async fetch(_request) {\n return new Response(null, { status: 404 });\n }\n /**\n * Adapter dispatch for `describe()`.\n *\n * @returns Author refinement or `null` when not implemented.\n * @internal\n */\n async bookclerkDescribe() {\n if (typeof this.describe !== \"function\")\n return null;\n return await this.describe();\n }\n /**\n * Adapter dispatch for the `event(batch)` trigger.\n *\n * @param context - Granted bindings for this invocation.\n * @param wireBatch - Wire `EventBatch`.\n * @returns One outcome per event, in order.\n * @internal\n */\n async bookclerkEvent(context, wireBatch) {\n if (typeof this.event !== \"function\") {\n throw unsupported(\"event\");\n }\n applyInvocationEnv(this, context);\n const events = Array.isArray(wireBatch?.events) ? wireBatch.events : [];\n const batch = new EventBatch(events, invocationOf(context));\n try {\n await this.event(batch);\n return eventBatchResults(batch, void 0);\n } catch (err) {\n return eventBatchResults(batch, err ?? new Error(\"event handler failed\"));\n }\n }\n /**\n * Adapter dispatch for the `queue(batch)` trigger.\n *\n * @param context - Granted bindings for this invocation.\n * @param wireBatch - Wire `QueueBatch`.\n * @returns One outcome per message, in order.\n * @internal\n */\n async bookclerkQueue(context, wireBatch) {\n if (typeof this.queue !== \"function\") {\n throw unsupported(\"queue\");\n }\n applyInvocationEnv(this, context);\n const messages = Array.isArray(wireBatch?.messages) ? wireBatch.messages : [];\n const batch = new QueueBatch(wireBatch?.queue, messages, invocationOf(context));\n try {\n await this.queue(batch);\n return queueBatchResults(batch, void 0);\n } catch (err) {\n return queueBatchResults(batch, err ?? new Error(\"queue handler failed\"));\n }\n }\n /**\n * Adapter dispatch for the `scheduled(controller)` trigger.\n *\n * @param context - Granted bindings for this invocation.\n * @param wire - Wire `ScheduledController`.\n * @returns Resolves when the author\'s handler completes.\n * @internal\n */\n async bookclerkScheduled(context, wire) {\n if (typeof this.scheduled !== \"function\") {\n throw unsupported(\"scheduled\");\n }\n applyInvocationEnv(this, context);\n await this.scheduled(scheduledControllerOf(wire));\n }\n /**\n * Adapter dispatch for `SocketHandler.message`.\n *\n * @param context - Granted bindings for this invocation.\n * @param wire - Wire `SocketMessage`.\n * @returns What the handler asks of the host (`pollEvents`).\n * @internal\n */\n async bookclerkSocketMessage(context, wire) {\n if (typeof this.webSocketMessage !== \"function\") {\n throw unsupported(\"webSocketMessage\");\n }\n applyInvocationEnv(this, context);\n const ws = hostWebSocketOf(socketsTransportOf(context)?.sockets, {\n socket: wire?.socket,\n attachment: wire?.attachment\n });\n const asked = await this.webSocketMessage(ws, socketMessageData(wire?.frame));\n return { pollEvents: asked?.pollEvents === true };\n }\n /**\n * Adapter dispatch for `SocketHandler.closed`. Without a\n * `webSocketClose` handler the close is acknowledged and ignored.\n *\n * @param context - Granted bindings for this invocation.\n * @param wire - Wire `SocketClosed`.\n * @returns Resolves when the author\'s handler completes.\n * @internal\n */\n async bookclerkSocketClosed(context, wire) {\n if (typeof this.webSocketClose !== \"function\")\n return;\n applyInvocationEnv(this, context);\n const ws = hostWebSocketOf(socketsTransportOf(context)?.sockets, {\n socket: wire?.socket,\n attachment: wire?.attachment\n });\n await this.webSocketClose(ws, Number(wire?.code ?? 0) || 0, String(wire?.reason ?? \"\"), wire?.clean === true);\n }\n /**\n * Adapter dispatch for `WebhookHandler.delivered`. Without a\n * `webhookDelivered` handler the call is acknowledged and ignored.\n *\n * @param context - Granted bindings for this invocation.\n * @param wire - Wire `WebhookDelivered`.\n * @returns Resolves when the author\'s handler completes.\n * @internal\n */\n async bookclerkWebhookDelivered(context, wire) {\n if (typeof this.webhookDelivered !== \"function\")\n return;\n applyInvocationEnv(this, context);\n await this.webhookDelivered(Object.freeze({\n name: String(wire?.name ?? \"\"),\n waiting: Number(wire?.waiting ?? 0) || 0\n }));\n }\n /**\n * Adapter dispatch for the `job(controller)` trigger.\n *\n * @param context - Granted bindings for this invocation.\n * @param invocation - Durable command envelope.\n * @param granted - Granted input / output / progress / cancel stubs.\n * @returns Wire job outcome.\n * @internal\n */\n async bookclerkJob(context, invocation, granted) {\n if (typeof this.job !== \"function\") {\n throw unsupported(\"job\");\n }\n applyInvocationEnv(this, context);\n const job = new JobController(invocation, granted);\n try {\n const returned = await this.job(job);\n return jobOutcomeFor(job, returned, void 0);\n } catch (err) {\n return jobOutcomeFor(job, void 0, err ?? new Error(\"job handler failed\"));\n }\n }\n /**\n * Adapter dispatch for `databaseMigrations(binding)`.\n *\n * @param binding - Binding name from `[[databases]]`.\n * @returns Bounded registration (`[]` when not implemented).\n * @internal\n */\n async bookclerkDatabaseMigrations(binding) {\n if (typeof this.databaseMigrations !== \"function\")\n return [];\n const migrations = await this.databaseMigrations(String(binding ?? \"\"));\n return requirePluginMigrationRegistration(Array.isArray(migrations) ? migrations : []);\n }\n /**\n * Adapter dispatch for `shutdown()`.\n *\n * @returns Resolves when the author hook has run.\n * @internal\n */\n async bookclerkShutdown() {\n if (typeof this.shutdown === \"function\")\n await this.shutdown();\n }\n};\nvar NamedEntrypoint = class extends WorkerEntrypoint {\n /** Methods the adapter may dispatch on this entrypoint. */\n static bookclerkMethods = [];\n /** Invocation identity of the current call (set by `bookclerkInvoke`). */\n invocation = invocationOf(void 0);\n /**\n * Rejects HTTP fetch \u{2014} workerd guests are Workers-RPC only.\n *\n * @param _request - Incoming HTTP request when the entrypoint is fetch-facing.\n * @returns Always a 404 empty response.\n */\n async fetch(_request) {\n return new Response(null, { status: 404 });\n }\n /**\n * Adapter dispatch: install granted bindings, then call `method`.\n *\n * @param context - Granted bindings for this invocation.\n * @param method - Method name from the static allowlist.\n * @param args - Method arguments.\n * @returns Method result.\n * @internal\n */\n async bookclerkInvoke(context, method, ...args) {\n const allowed = this.constructor.bookclerkMethods ?? [];\n const target = this[method];\n if (!allowed.includes(method) || typeof target !== \"function\") {\n throw unsupported(method);\n }\n applyInvocationEnv(this, context);\n this.invocation = invocationOf(context);\n return await target.apply(this, args);\n }\n};\nvar PURCHASE_HINTS_BUDGET_MS = 4e3;\nvar PURCHASE_HINTS_CONCURRENCY = 4;\nvar STOREFRONT_METHODS = Object.freeze([\n \"login\",\n \"scan\",\n \"fetchTitle\",\n \"listAccounts\",\n \"loginStart\",\n \"loginComplete\",\n \"searchCatalog\",\n \"expandCandidates\",\n \"purchaseHint\",\n \"purchaseHints\",\n \"listDeals\",\n \"catalogDetail\",\n \"revokeAccount\",\n \"qualityOffers\",\n \"diagnose\",\n \"health\"\n]);\nvar StorefrontEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = STOREFRONT_METHODS;\n /**\n * Password or one-shot OAuth login. The host seals\n * `LoginResult.credentials` into `encrypted_secrets`.\n *\n * @param _params - Login parameters.\n * @returns Account identity plus opaque credentials.\n */\n login(_params) {\n return Promise.reject(unsupported(\"login\"));\n }\n /**\n * One page of one account\'s library scan.\n *\n * The host calls this repeatedly, passing back `nextCursor` as\n * `params.cursor` until a page returns an empty `nextCursor`, which ends\n * the pass. An empty `params.syncToken` asks for a full pass; a non-empty\n * one asks only for changes since that token (list gone titles in\n * `removed`). Set `complete` only on the last page of a full pass that\n * listed the whole library. Only the last page\'s `syncToken` is stored. Reject a stale cursor or token with `invalid_cursor` and the\n * host restarts as a full pass.\n *\n * @param _params - The account, its credential, the cursor and the sync token.\n * @returns At most `MAX_SCAN_PAGE_BOOKS` books plus the paging fields.\n */\n scan(_params) {\n return Promise.reject(unsupported(\"scan\"));\n }\n /**\n * Fetches one title into `params.cacheDir` and returns plain media paths.\n *\n * @param _params - Title identifiers, credentials, fetch options.\n * @returns Plain media parts plus metadata.\n */\n fetchTitle(_params) {\n return Promise.reject(unsupported(\"fetchTitle\"));\n }\n /**\n * Accounts the guest knows about.\n *\n * @returns Account list.\n */\n listAccounts() {\n return Promise.reject(unsupported(\"listAccounts\"));\n }\n /**\n * Begins an interactive OAuth login.\n *\n * @param _params - Login parameters.\n * @returns Continuation for {@link StorefrontEntrypoint.loginComplete}.\n */\n loginStart(_params) {\n return Promise.reject(unsupported(\"loginStart\"));\n }\n /**\n * Finishes a login started by {@link StorefrontEntrypoint.loginStart}.\n *\n * @param _params - Continuation plus user input.\n * @returns Account identity plus opaque credentials.\n */\n loginComplete(_params) {\n return Promise.reject(unsupported(\"loginComplete\"));\n }\n /**\n * Free-text storefront catalog search.\n *\n * @param _params - Query parameters.\n * @returns Catalog hits.\n */\n searchCatalog(_params) {\n return Promise.reject(unsupported(\"searchCatalog\"));\n }\n /**\n * Related-title expansion from a seed title.\n *\n * @param _params - Seed title plus limits.\n * @returns Candidate hits.\n */\n expandCandidates(_params) {\n return Promise.reject(unsupported(\"expandCandidates\"));\n }\n /**\n * Purchase link / price hint; `null` when the title is unknown.\n *\n * `params.lookup` says how the host names the title: `\"isbn\"` or\n * `\"asin\"` (sent only when `describe().catalog` declares `priceByIsbn` /\n * `priceByAsin`) want that exact edition or `null`, never a title match;\n * `\"product\"` names the store\'s own product; `\"title\"` asks for a search\n * by title and authors, answered best with a {@link PurchaseHintAnswer}\n * listing every priced result; `\"unspecified\"` (older hosts) leaves the\n * choice to the store.\n *\n * @param _params - Title identifiers and how to look the title up.\n * @returns Hint, an answer with title-search records, or `null`.\n */\n purchaseHint(_params) {\n return Promise.reject(unsupported(\"purchaseHint\"));\n }\n /**\n * Purchase links / price hints for several titles in one call, one\n * answer per query in order. The default asks {@link purchaseHint} for\n * each query, {@link PURCHASE_HINTS_CONCURRENCY} at a time, those with a\n * product id first, and stops starting lookups after\n * {@link PURCHASE_HINTS_BUDGET_MS}; a store whose catalog prices\n * many products per request overrides this to make one request. Reject with a\n * `rate_limited` {@link PluginError} (its `details.retryAfterMs` says how\n * long) when the store asks to slow down, so the host leaves it alone.\n *\n * @param params - The titles to price, in order.\n * @returns One hint, answer with records, or `null` per query.\n */\n async purchaseHints(params) {\n const started = Date.now();\n const out = params.queries.map(() => null);\n const order = params.queries.map((query, i) => ({ i, direct: Boolean(query.productId?.trim()) })).sort((a, b) => Number(b.direct) - Number(a.direct)).map((entry) => entry.i);\n let next = 0;\n let failed = false;\n const lane = async () => {\n while (next < order.length && !failed) {\n if (Date.now() - started >= PURCHASE_HINTS_BUDGET_MS)\n return;\n const i = order[next++];\n try {\n out[i] = await this.purchaseHint(params.queries[i]);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n };\n const lanes = Math.min(PURCHASE_HINTS_CONCURRENCY, order.length);\n await Promise.all(Array.from({ length: lanes }, lane));\n return out;\n }\n /**\n * Current storefront deals.\n *\n * @param _params - Optional filters.\n * @returns Deal hits.\n */\n listDeals(_params) {\n return Promise.reject(unsupported(\"listDeals\"));\n }\n /**\n * Full catalog record for one product; `null` when unknown.\n *\n * @param _params - Product identifiers.\n * @returns Catalog hit or `null`.\n */\n catalogDetail(_params) {\n return Promise.reject(unsupported(\"catalogDetail\"));\n }\n /**\n * Undo store-side state for one account before the host deletes its\n * credentials, such as deregistering the device registered at login.\n * Best effort: the host revokes the account whatever this returns. The\n * default does nothing.\n *\n * @param _params - Account id and its stored credentials.\n * @returns Resolves when the store sign-out finished.\n */\n revokeAccount(_params) {\n return Promise.resolve();\n }\n /**\n * The audio quality one account would download for each title today, one\n * answer per title id in order (`found: false` when the store cannot\n * say). It must not license or download anything. The host asks only a\n * store that declares `catalog.qualityOffers` in `describe()`; the\n * default rejects as unsupported.\n *\n * @param _params - Account, its credentials, settings and title ids.\n * @returns One answer per title, plus any refreshed credentials.\n */\n qualityOffers(_params) {\n return Promise.reject(unsupported(\"qualityOffers\"));\n }\n /**\n * Operator-facing diagnostic lines.\n *\n * @returns Probe lines.\n */\n diagnose() {\n return Promise.resolve([]);\n }\n /**\n * Reports whether the storefront session is usable.\n *\n * @returns Health flag plus detail.\n */\n health() {\n return Promise.resolve({ ok: true, detail: \"\" });\n }\n};\nvar STORAGE_METHODS = Object.freeze([\n \"head\",\n \"list\",\n \"get\",\n \"put\",\n \"copy\",\n \"delete\",\n \"commit\",\n \"abortStage\",\n \"move\",\n \"moveMany\",\n \"deleteMany\",\n \"headMany\",\n \"changes\",\n \"translateKeys\"\n]);\nvar StorageEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = STORAGE_METHODS;\n /**\n * Metadata without a body; `null` when the key is missing.\n *\n * @param _key - Object key.\n * @returns Metadata or `null` when the key is missing.\n */\n head(_key) {\n return Promise.reject(unsupported(\"head\"));\n }\n /**\n * One page of keys under `options.prefix`.\n *\n * @param _options - Prefix, cursor, and limit.\n * @returns One page of object keys.\n */\n list(_options) {\n return Promise.reject(unsupported(\"list\"));\n }\n /**\n * Streamed read. The body is a transferred stream, not a scalar.\n *\n * @param _key - Object key.\n * @param _options - Optional byte range.\n * @returns Metadata plus a transferred body stream.\n */\n get(_key, _options) {\n return Promise.reject(unsupported(\"get\"));\n }\n /**\n * Streamed write. `body` ownership is transferred to the destination.\n *\n * @param _key - Object key.\n * @param _body - Byte stream.\n * @param _options - Optional content type / length.\n * @returns Bytes written and optional etag / sha256.\n */\n put(_key, _body, _options) {\n return Promise.reject(unsupported(\"put\"));\n }\n /**\n * Server-side copy when the backend supports it.\n *\n * @param _from - Source key.\n * @param _to - Destination key.\n * @returns Bytes copied.\n */\n copy(_from, _to) {\n return Promise.reject(unsupported(\"copy\"));\n }\n /**\n * Delete a key (no-op if missing).\n *\n * @param _key - Object key.\n * @returns Resolves when the delete is complete.\n */\n delete(_key) {\n return Promise.reject(unsupported(\"delete\"));\n }\n /**\n * Finalize a destination-side staged object.\n *\n * @param _key - Object key.\n * @param _commitToken - Idempotency / commit token.\n * @returns Published object metadata.\n */\n commit(_key, _commitToken) {\n return Promise.reject(unsupported(\"commit\"));\n }\n /**\n * Abort a destination-side staged object.\n *\n * @param _key - Object key.\n * @param _commitToken - Staging token to discard.\n * @returns Rejects with typed `unsupported` unless overridden.\n */\n abortStage(_key, _commitToken) {\n return Promise.reject(unsupported(\"abortStage\"));\n }\n /**\n * Move one object (declare `storage.move`). Repeating a finished move\n * resolves with `alreadyMoved`.\n *\n * @param _from - Source key.\n * @param _to - Target key.\n * @param _options - Overwrite and source preconditions.\n * @returns How the move was done.\n */\n move(_from, _to, _options) {\n return Promise.reject(unsupported(\"move\"));\n }\n /**\n * Move a set of objects or a whole prefix, one page per call (declare\n * `storage.moveMany`). Safe to repeat.\n *\n * @param _request - Pairs or prefix, cursor, and options.\n * @returns Per-key outcomes and the continuation.\n */\n moveMany(_request) {\n return Promise.reject(unsupported(\"moveMany\"));\n }\n /**\n * Remove up to `MAX_BATCH_KEYS` objects (declare `storage.deleteMany`).\n *\n * @param _keys - Object keys.\n * @returns One outcome per key, in order; a missing key succeeds.\n */\n deleteMany(_keys) {\n return Promise.reject(unsupported(\"deleteMany\"));\n }\n /**\n * Probe up to `MAX_BATCH_KEYS` objects (declare `storage.headMany`).\n *\n * @param _keys - Object keys.\n * @returns One entry per key, in order; `null` when missing.\n */\n headMany(_keys) {\n return Promise.reject(unsupported(\"headMany\"));\n }\n /**\n * Keys changed since a cursor (declare `storage.changes`).\n *\n * @param _request - Cursor and page size.\n * @returns One page of changes.\n */\n changes(_request) {\n return Promise.reject(unsupported(\"changes\"));\n }\n /**\n * Translate up to `MAX_BATCH_KEYS` host keys into the keys this\n * destination stores them under (declare `storage.translateKeys`). A host\n * key is `/`-joined segments, none empty, `.`, `..` or holding `\\` or a\n * control character; return a relative key with the same properties. The\n * same host key must always translate to the same key. Without the\n * feature the host stores each host key as written.\n *\n * @param _keys - Host keys.\n * @returns One translated key per host key, in order.\n */\n translateKeys(_keys) {\n return Promise.reject(unsupported(\"translateKeys\"));\n }\n};\nvar REMOTE_LIBRARY_METHODS = Object.freeze([\n \"health\",\n \"diagnose\",\n \"start\",\n \"stop\",\n \"scanLibrary\",\n \"syncListening\",\n \"pollEvents\"\n]);\nvar RemoteLibraryEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = REMOTE_LIBRARY_METHODS;\n /**\n * Reports whether the remote library session is usable.\n *\n * @returns Health flag plus detail.\n */\n health() {\n return Promise.resolve({ ok: true, detail: \"\" });\n }\n /**\n * Operator-facing diagnostic lines.\n *\n * @returns Probe lines.\n */\n diagnose() {\n return Promise.resolve([]);\n }\n /**\n * Starts long-running work for this invocation.\n *\n * @returns Resolves when running.\n */\n start() {\n return Promise.resolve();\n }\n /**\n * Stops long-running work for this invocation.\n *\n * @returns Resolves when stopped.\n */\n stop() {\n return Promise.resolve();\n }\n /**\n * Re-syncs the remote library.\n *\n * @param _params - Scan scope.\n * @returns Resolves when the scan has been accepted.\n */\n scanLibrary(_params) {\n return Promise.reject(unsupported(\"scanLibrary\"));\n }\n /**\n * Push / pull listening progress; the host upserts the rows.\n *\n * @returns Progress rows.\n */\n syncListening() {\n return Promise.reject(unsupported(\"syncListening\"));\n }\n /**\n * Drains external users observed since the last poll.\n *\n * @returns Newly observed users.\n */\n pollEvents() {\n return Promise.reject(unsupported(\"pollEvents\"));\n }\n};\nvar ADAPTER_SESSIONS = /* @__PURE__ */ new Map();\nvar ADAPTER_SESSION_METHODS = /* @__PURE__ */ new Set([\n \"capabilities\",\n \"execute\",\n \"close\",\n \"bootstrap\",\n \"exportIdentity\",\n \"importIdentity\",\n \"listUserRelations\",\n \"prepareUnitRestore\",\n \"dropUserRelations\",\n \"assertRestoreConstraints\",\n \"executeStreamed\"\n]);\nfunction freshSessionId() {\n const c = globalThis.crypto;\n if (c && typeof c.randomUUID === \"function\")\n return c.randomUUID();\n const bytes = new Uint8Array(16);\n if (c && typeof c.getRandomValues === \"function\")\n c.getRandomValues(bytes);\n else\n for (let i = 0; i < bytes.length; i++)\n bytes[i] = Math.floor(Math.random() * 256);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nvar DatabaseAdapterEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = Object.freeze([\"openSession\", \"dropUnit\"]);\n /**\n * Opens a session. Sessions cannot survive suspension.\n *\n * @returns Adapter session capability.\n */\n openSession() {\n return Promise.reject(unsupported(\"openSession\"));\n }\n /**\n * Physically drops one provisioned binding unit.\n *\n * @param _unitRef - Adapter-native unit identity.\n * @returns Resolves when the unit is dropped.\n */\n dropUnit(_unitRef) {\n return Promise.reject(unsupported(\"dropUnit\"));\n }\n /**\n * Adapter dispatch: `openSession` \u{2192} session id; `dropUnit`; `session` \u{2192} call\n * on a retained session (`args` = `[id, method, ...params]`).\n *\n * @param context - Granted bindings for this invocation.\n * @param method - `openSession`, `dropUnit`, or `session`.\n * @param args - Method arguments.\n * @returns Session id for `openSession`, else the session method result.\n * @internal\n */\n async bookclerkInvoke(context, method, ...args) {\n if (method === \"openSession\") {\n const session2 = await super.bookclerkInvoke(context, \"openSession\");\n if (!session2 || typeof session2 !== \"object\") {\n throw PluginError.fromWire(\"internal\", \"openSession returned no session\");\n }\n const id = freshSessionId();\n ADAPTER_SESSIONS.set(id, session2);\n return id;\n }\n if (method === \"dropUnit\") {\n applyInvocationEnv(this, context);\n this.invocation = invocationOf(context);\n await this.dropUnit(String(args[0] ?? \"\"));\n return void 0;\n }\n if (method === \"session\") {\n const [id, sessionMethod, ...params] = args;\n const session2 = typeof id === \"string\" ? ADAPTER_SESSIONS.get(id) : void 0;\n if (!session2) {\n throw PluginError.fromWire(\"invalid_params\", `unknown adapter session ${String(id)}`);\n }\n const name = String(sessionMethod ?? \"\");\n const target = session2[name];\n if (!ADAPTER_SESSION_METHODS.has(name) || typeof target !== \"function\") {\n throw unsupported(name);\n }\n applyInvocationEnv(this, context);\n this.invocation = invocationOf(context);\n try {\n return await target.apply(session2, params);\n } finally {\n if (name === \"close\")\n ADAPTER_SESSIONS.delete(id);\n }\n }\n return super.bookclerkInvoke(context, method, ...args);\n }\n};\nvar CliEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = Object.freeze([\"describe\", \"invoke\"]);\n /**\n * Guest CLI schema.\n *\n * @returns Declared commands (`{ commands: [] }` when the guest has no CLI).\n */\n describe() {\n return Promise.resolve({ commands: [] });\n }\n /**\n * Invokes a guest CLI command.\n *\n * @param _params - Command name plus named argument values.\n * @returns Exit code, captured output, optional structured payload.\n */\n invoke(_params) {\n return Promise.reject(unsupported(\"invoke\"));\n }\n};\nvar OidcEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = Object.freeze([\"clients\", \"authenticateUser\"]);\n /**\n * Plugin-provided OIDC authorization-server client templates. The host\n * materializes `oidc_clients` rows; plugins never mint tokens.\n *\n * @returns Templates (`[]` when unused).\n */\n clients() {\n return Promise.resolve([]);\n }\n /**\n * Verifies remote credentials on behalf of the host.\n *\n * @param _params - Username / password pair.\n * @returns External user identity.\n */\n authenticateUser(_params) {\n return Promise.reject(unsupported(\"authenticateUser\"));\n }\n};\nvar MetadataEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = Object.freeze([\"health\", \"lookup\", \"search\", \"chapters\"]);\n /**\n * Reports whether the provider can answer.\n *\n * @returns Health flag plus detail.\n */\n health() {\n return Promise.resolve({ ok: true, detail: \"\" });\n }\n /**\n * Records for the editions the identifiers name.\n *\n * @param _params - Identifiers, marketplace and result cap.\n * @returns Records in relevance order (`[]` when nothing matched).\n */\n lookup(_params) {\n return Promise.reject(unsupported(\"lookup\"));\n }\n /**\n * Records matching a title and, optionally, an author.\n *\n * @param _params - Title, author, language, marketplace and result cap.\n * @returns Records in relevance order (`[]` when nothing matched).\n */\n search(_params) {\n return Promise.reject(unsupported(\"search\"));\n }\n /**\n * Chapter layout of one edition.\n *\n * @param _params - Identifiers of the edition.\n * @returns The layout, or `{ found: false }` when the provider has none.\n */\n chapters(_params) {\n return Promise.reject(unsupported(\"chapters\"));\n }\n};\nvar CoverEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = Object.freeze([\"health\", \"fetchCovers\"]);\n /**\n * Reports whether the fetcher can answer.\n *\n * @returns Health flag plus detail.\n */\n health() {\n return Promise.resolve({ ok: true, detail: \"\" });\n }\n /**\n * Fetches each URL and streams its body into `sink` under its index.\n *\n * @param _params - URLs (absolute `https://`) and the per-body byte cap.\n * @param _sink - Host destination; accepts `put` for keys `0..urls.length`.\n * @returns One entry per URL, in request order.\n */\n fetchCovers(_params, _sink) {\n return Promise.reject(unsupported(\"fetchCovers\"));\n }\n};\nvar MetadataFilesEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = Object.freeze([\"health\", \"parse\", \"render\"]);\n /**\n * Reports whether the dialects can answer.\n *\n * @returns Health flag plus detail.\n */\n health() {\n return Promise.resolve({ ok: true, detail: \"\" });\n }\n /**\n * What one file says about its edition. List every field the file states\n * in `present`, including ones it states as empty; leave out fields it\n * does not mention. Throw `invalid_params` for a file the dialect cannot\n * read.\n *\n * @param _params - Dialect id, file name and the whole file.\n * @returns The parsed record.\n */\n parse(_params) {\n return Promise.reject(unsupported(\"parse\"));\n }\n /**\n * The new file: `params.existing` with each field in `params.fields` set to\n * the record\'s value (removed when the value is empty), everything else\n * kept as it was. `existing` is empty when the host creates the file.\n *\n * @param _params - Dialect id, values, fields to set and the current file.\n * @returns The new file\'s bytes; a string is written as UTF-8.\n */\n render(_params) {\n return Promise.reject(unsupported(\"render\"));\n }\n};\nvar AiEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = Object.freeze([\"health\", \"models\", \"run\"]);\n /**\n * Reports whether the models can be loaded with the current settings.\n *\n * @returns Health flag plus detail.\n */\n health() {\n return Promise.resolve({ ok: true, detail: \"\" });\n }\n /**\n * Lists the models served now. Must be cheap: do not load a model here.\n * Change a model\'s `revision` whenever its weights, tokenizer or loaded\n * language packs change, because outputs are comparable only within one\n * revision.\n *\n * @returns The served models, each `modelId` once.\n */\n models() {\n return Promise.resolve({ models: [] });\n }\n /**\n * Runs one model on one input. Throw `not_found` for a model this plugin\n * does not serve and `invalid_params` for an input of another task. For\n * text embeddings return one vector per text, in input order\n * ({@link packEmbeddingVectors}), with the model\'s listed `dimensions` and\n * `revision`.\n *\n * @param _params - The plugin\'s own model id and the input.\n * @returns The output; leave `model` unset.\n */\n run(_params) {\n return Promise.reject(unsupported(\"run\"));\n }\n};\nvar NotifierEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = Object.freeze([\"health\", \"send\", \"validateDestination\"]);\n /**\n * Reports whether the service can be reached with the current settings.\n *\n * @returns Health flag plus detail.\n */\n health() {\n return Promise.resolve({ ok: true, detail: \"\" });\n }\n /**\n * Delivers one message to one destination. Throw `rate_limited` (with\n * `details.retryAfterMs` when the service says when) or `unavailable` for\n * a failure worth retrying; any other error fails this destination. Never\n * log `params.message` when `sensitive` is set, nor `addressJson`.\n *\n * @param _params - The rendered message and its destination.\n * @returns The service\'s message id, when it gives one.\n */\n send(_params) {\n return Promise.reject(unsupported(\"send\"));\n }\n /**\n * Checks and normalises a personal address a patron entered. Throw\n * `invalid_params` for an address the service would refuse. The default\n * accepts the address as given.\n *\n * @param params - The address document as entered.\n * @returns The address to save and an optional label that is never a secret.\n */\n validateDestination(params) {\n return Promise.resolve({ addressJson: params.addressJson });\n }\n};\nvar IngressEntrypoint = class extends NamedEntrypoint {\n static bookclerkMethods = Object.freeze([\"start\", \"health\", \"stop\"]);\n /**\n * Brings the public address up and returns it once it serves.\n *\n * @returns The public origin: `https://` and a host name, no port, path\n * or trailing slash.\n */\n start() {\n return Promise.reject(unsupported(\"start\"));\n }\n /**\n * Reports whether the address is serving.\n *\n * @returns `serving`, plus a detail for the operator when it is not.\n */\n health() {\n return Promise.resolve({ serving: true });\n }\n /**\n * Takes the public address down. The host stops sending requests after\n * this returns.\n *\n * @returns Resolves once the address no longer serves.\n */\n stop() {\n return Promise.resolve();\n }\n};\nvar ENTRYPOINT_BINDINGS = Object.freeze({\n storefront: \"PLUGIN_STOREFRONT\",\n storage: \"PLUGIN_STORAGE\",\n databaseAdapter: \"PLUGIN_DATABASE_ADAPTER\",\n remoteLibrary: \"PLUGIN_REMOTE_LIBRARY\",\n cli: \"PLUGIN_CLI\",\n oidc: \"PLUGIN_OIDC\",\n metadata: \"PLUGIN_METADATA\",\n covers: \"PLUGIN_COVERS\",\n metadataFiles: \"PLUGIN_METADATA_FILES\",\n notifier: \"PLUGIN_NOTIFIER\",\n ingress: \"PLUGIN_INGRESS\",\n ai: \"PLUGIN_AI\"\n});\nvar ENTRYPOINT_CLASSES = Object.freeze({\n storefront: \"Storefront\",\n storage: \"Storage\",\n databaseAdapter: \"DatabaseAdapter\",\n remoteLibrary: \"RemoteLibrary\",\n cli: \"Cli\",\n oidc: \"Oidc\",\n metadata: \"Metadata\",\n covers: \"Covers\",\n metadataFiles: \"MetadataFiles\",\n notifier: \"Notifier\",\n ingress: \"Ingress\",\n ai: \"Ai\"\n});\nfunction exactLengthBody(body, expected) {\n if (body == null || expected == null || !Number.isFinite(expected)) {\n return body;\n }\n const reader = body.getReader();\n let n = 0;\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) {\n if (n !== expected) {\n controller.error(PluginError.fromWire(\"invalid_params\", `content-length ${expected} got ${n}`));\n return;\n }\n controller.close();\n return;\n }\n n += value.byteLength;\n if (n > expected) {\n controller.error(PluginError.fromWire(\"payload_too_large\", `body exceeded Content-Length ${expected}`));\n return;\n }\n controller.enqueue(value);\n },\n cancel(reason) {\n return reader.cancel(reason);\n }\n });\n}\nfunction streamedRead(resp, key) {\n return {\n meta: {\n key: resp.headers.get(\"x-bookclerk-key\") || key,\n size: Number(resp.headers.get(\"x-bookclerk-size\") || \"0\"),\n contentType: resp.headers.get(\"x-bookclerk-content-type\") || void 0,\n etag: resp.headers.get(\"x-bookclerk-etag\") || void 0\n },\n body: resp.body\n };\n}\nvar GrantedSource = class extends Source {\n #granted;\n #auth;\n #signal;\n constructor(granted, auth, signal) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n this.#signal = signal;\n }\n async open(key) {\n const resp = await this.#granted.fetch(`http://granted/open?key=${encodeURIComponent(key)}`, {\n headers: this.#auth,\n signal: this.#signal\n });\n if (!resp.ok) {\n throw PluginError.fromWire(\"internal\", await resp.text());\n }\n return streamedRead(resp, key);\n }\n};\nvar GrantedDestination = class extends Destination {\n #granted;\n #auth;\n #signal;\n constructor(granted, auth, signal) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n this.#signal = signal;\n }\n async put(key, body, options) {\n if (options?.ifMatch || options?.ifNoneMatch) {\n throw PluginError.fromWire(\"unsupported\", \"conditional writes are not supported on granted destinations\");\n }\n const headers = { ...this.#auth };\n if (options?.contentType)\n headers[\"content-type\"] = options.contentType;\n if (options?.contentLength != null) {\n headers[\"content-length\"] = String(options.contentLength);\n }\n const resp = await this.#granted.fetch(`http://granted/put?key=${encodeURIComponent(key)}`, {\n method: \"PUT\",\n headers,\n body,\n signal: this.#signal\n });\n if (!resp.ok) {\n throw PluginError.fromWire(\"internal\", await resp.text());\n }\n return await resp.json();\n }\n};\nvar GrantedProgress = class extends ProgressSink {\n #granted;\n #auth;\n #signal;\n constructor(granted, auth, signal) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n this.#signal = signal;\n }\n async report(percent, message) {\n await this.#granted.fetch(`http://granted/progress`, {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/json\" },\n body: JSON.stringify({ percent, message: message || \"\" }),\n signal: this.#signal\n });\n }\n};\nfunction publishPayloadBytes(payload) {\n if (payload === void 0 || payload === null)\n return new Uint8Array(0);\n if (payload instanceof Uint8Array)\n return payload;\n if (payload instanceof ArrayBuffer)\n return new Uint8Array(payload);\n if (typeof payload === \"string\")\n return new TextEncoder().encode(payload);\n return new TextEncoder().encode(JSON.stringify(payload));\n}\nfunction packEmbeddingVectors(vectors) {\n const width = vectors.length > 0 ? vectors[0].length : 0;\n const out = new Uint8Array(vectors.length * width * 4);\n const view = new DataView(out.buffer);\n vectors.forEach((vector, row) => {\n if (vector.length !== width) {\n throw PluginError.fromWire(\"internal\", \"embedding vectors differ in length\");\n }\n for (let i = 0; i < width; i++) {\n view.setFloat32((row * width + i) * 4, vector[i], true);\n }\n });\n return out;\n}\nfunction unpackEmbeddingVectors(bytes, dimensions) {\n const width = dimensions * 4;\n if (!Number.isInteger(dimensions) || dimensions < 1 || bytes.length % width !== 0) {\n throw PluginError.fromWire(\"internal\", \"embedding bytes are not whole vectors\");\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const out = [];\n for (let at = 0; at < bytes.length; at += width) {\n const vector = new Array(dimensions);\n for (let i = 0; i < dimensions; i++)\n vector[i] = view.getFloat32(at + i * 4, true);\n out.push(vector);\n }\n return out;\n}\nvar GrantedAi = class extends RpcTarget {\n #granted;\n #auth;\n /**\n * @param granted - Granted reverse channel.\n * @param auth - Bearer header for the ai grant.\n */\n constructor(granted, auth) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n }\n /**\n * Run one model on one input.\n *\n * @param model - Model name or task alias.\n * @param input - The input of the model\'s task.\n * @returns The model\'s output.\n */\n async run(model, input) {\n if (typeof model !== \"string\" || !model) {\n throw PluginError.fromWire(\"invalid_params\", \"run requires a model name\");\n }\n const text = input?.text;\n const list = typeof text === \"string\" ? [text] : text;\n if (!Array.isArray(list) || list.some((t) => typeof t !== \"string\")) {\n throw PluginError.fromWire(\"invalid_params\", \"run requires input.text as a string or strings\");\n }\n const role = input.role ?? \"document\";\n const wire = {\n model,\n input: { textEmbeddings: { texts: list.map((t) => ({ text: t, role })) } }\n };\n const resp = await this.#granted.fetch(\"http://granted/ai/run\", {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/json\" },\n body: JSON.stringify(wire)\n });\n const value = await resp.json().catch(() => ({}));\n if (value && value.error) {\n throw PluginError.fromWire(value.error.code || \"internal\", value.error.message || \"\");\n }\n if (!resp.ok) {\n throw PluginError.fromWire(\"internal\", `ai run HTTP ${resp.status}`);\n }\n const out = value.output?.textEmbeddings ?? {};\n const dimensions = Number(out.dimensions ?? 0);\n const bytes = typeof out.vectors === \"string\" ? base64ToBytes(out.vectors) : new Uint8Array();\n const data = unpackEmbeddingVectors(bytes, dimensions);\n return {\n shape: [data.length, dimensions],\n data,\n model: String(value.model ?? model),\n revision: String(out.revision ?? \"\"),\n fallbacks: Array.isArray(out.fallbacks) ? out.fallbacks.map(Number) : []\n };\n }\n};\nfunction notifyFields(fields) {\n if (fields === void 0)\n return [];\n if (Array.isArray(fields)) {\n return fields.map((f) => ({ name: String(f?.name ?? \"\"), value: String(f?.value ?? \"\") }));\n }\n if (fields === null || typeof fields !== \"object\") {\n throw PluginError.fromWire(\"invalid_params\", \"fields must be a list or an object\");\n }\n return Object.entries(fields).map(([name, value]) => ({ name, value: String(value) }));\n}\nvar GrantedNotify = class extends RpcTarget {\n #granted;\n #auth;\n /**\n * @param granted - Granted reverse channel.\n * @param auth - Bearer header for the notify grant.\n */\n constructor(granted, auth) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n }\n /**\n * Raise one declared notification type.\n *\n * @param raise - Type, fields, optional patron, link path and alert.\n * @returns The host\'s notification id.\n */\n async raise(raise) {\n if (!raise || typeof raise.notificationType !== \"string\" || !raise.notificationType) {\n throw PluginError.fromWire(\"invalid_params\", \"raise requires notificationType\");\n }\n const wire = {\n notificationType: raise.notificationType,\n fields: notifyFields(raise.fields),\n patronId: raise.patronId || void 0,\n linkPath: raise.linkPath || void 0,\n groupKey: raise.groupKey || void 0,\n alertAction: raise.alertAction ?? \"none\",\n alertKey: raise.alertKey || void 0\n };\n const resp = await this.#granted.fetch(\"http://granted/notify/raise\", {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/json\" },\n body: JSON.stringify(wire)\n });\n const value = await resp.json().catch(() => ({}));\n if (value && value.error) {\n throw PluginError.fromWire(value.error.code || \"internal\", value.error.message || \"\");\n }\n if (!resp.ok) {\n throw PluginError.fromWire(\"internal\", `notify raise HTTP ${resp.status}`);\n }\n return { notificationId: String(value.notificationId ?? \"\") };\n }\n};\nvar GrantedEvents = class extends RpcTarget {\n #granted;\n #auth;\n /**\n * @param granted - Granted reverse channel.\n * @param auth - Bearer header for the events grant.\n */\n constructor(granted, auth) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n }\n /**\n * Publish one domain event through the host outbox.\n *\n * @param event - Event type, schema version, payload, dedup key.\n * @returns Outbox row identity.\n */\n async publish(event) {\n if (!event || typeof event.eventType !== \"string\" || !event.eventType) {\n throw PluginError.fromWire(\"invalid_params\", \"publish requires eventType\");\n }\n const payload = publishPayloadBytes(event.payload);\n if (payload.byteLength > MAX_EVENT_PAYLOAD_BYTES) {\n throw PluginError.fromWire(\"payload_too_large\", `event payload of ${payload.byteLength} bytes exceeds ${MAX_EVENT_PAYLOAD_BYTES}`);\n }\n const wire = toBridgeJson({\n eventType: event.eventType,\n schemaVersion: Number(event.schemaVersion ?? 1) || 1,\n deduplicationKey: String(event.deduplicationKey ?? \"\"),\n payload,\n occurredAtUnixMs: Number(event.occurredAtUnixMs ?? 0) || 0,\n correlationId: String(event.correlationId ?? \"\"),\n causationId: String(event.causationId ?? \"\")\n });\n const resp = await this.#granted.fetch(\"http://granted/events/publish\", {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/json\" },\n body: JSON.stringify(wire)\n });\n const value = await resp.json().catch(() => ({}));\n if (value && value.error) {\n throw PluginError.fromWire(value.error.code || \"internal\", value.error.message || \"\");\n }\n if (!resp.ok) {\n throw PluginError.fromWire(\"internal\", `events publish HTTP ${resp.status}`);\n }\n return { eventId: String(value.eventId ?? \"\"), duplicate: Boolean(value.duplicate) };\n }\n /**\n * Read one page of past events the granted subscriptions match.\n *\n * @param options - Start position, types, and page size.\n * @returns One page of events and the cursor after it.\n */\n async read(options = {}) {\n const since = options.since instanceof Date ? options.since.getTime() : options.since ?? options.sinceUnixMs;\n if (since !== void 0 && (!Number.isSafeInteger(since) || since < 0)) {\n throw PluginError.fromWire(\"invalid_params\", \"since must be a non-negative instant\");\n }\n const limit = options.limit ?? 0;\n if (!Number.isSafeInteger(limit) || limit < 0) {\n throw PluginError.fromWire(\"invalid_params\", \"limit must be a non-negative integer\");\n }\n const resp = await this.#granted.fetch(\"http://granted/events/read\", {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/json\" },\n body: JSON.stringify({\n after: String(options.after ?? \"\"),\n sinceUnixMs: since ?? 0,\n types: (options.types ?? []).map(String),\n limit\n })\n });\n const value = await resp.json().catch((error) => {\n if (resp.ok) {\n throw PluginError.fromWire(\"internal\", `events read reply is not JSON: ${String(error)}`);\n }\n return {};\n });\n if (value && value.error) {\n throw PluginError.fromWire(value.error.code || \"internal\", value.error.message || \"\");\n }\n if (!resp.ok) {\n throw PluginError.fromWire(\"internal\", `events read HTTP ${resp.status}`);\n }\n const events = Array.isArray(value.events) ? value.events : [];\n return {\n events: events.map((event) => fromBridgeJson(event)),\n cursor: String(value.cursor ?? \"\"),\n more: Boolean(value.more),\n expiredEventIds: Array.isArray(value.expiredEventIds) ? value.expiredEventIds.map(String) : [],\n truncated: Boolean(value.truncated)\n };\n }\n};\nfunction queueBodyBytes(body, contentType) {\n const kind = contentType || \"json\";\n if (kind === \"bytes\") {\n if (body instanceof Uint8Array)\n return { body, contentType: kind };\n if (body instanceof ArrayBuffer)\n return { body: new Uint8Array(body), contentType: kind };\n throw PluginError.fromWire(\"invalid_params\", \"bytes queue message requires a Uint8Array body\");\n }\n if (kind === \"text\") {\n if (typeof body !== \"string\") {\n throw PluginError.fromWire(\"invalid_params\", \"text queue message requires a string body\");\n }\n return { body: new TextEncoder().encode(body), contentType: kind };\n }\n if (kind !== \"json\") {\n throw PluginError.fromWire(\"invalid_params\", `unknown queue content type \\`${kind}\\``);\n }\n return { body: new TextEncoder().encode(JSON.stringify(body ?? null)), contentType: kind };\n}\nvar GrantedQueue = class extends RpcTarget {\n #granted;\n #auth;\n /**\n * @param granted - Granted reverse channel.\n * @param auth - Bearer header for the queue grant.\n */\n constructor(granted, auth) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n }\n /**\n * Send one message.\n *\n * @param body - JSON value, string, or bytes per `options.contentType`.\n * @param options - Encoding and delay.\n * @returns The outbox id the host assigned.\n */\n async send(body, options) {\n return this.sendBatch([{ body, ...options ?? {} }]);\n }\n /**\n * Send up to `maxListPage` messages in order.\n *\n * @param messages - Bodies with per-message options.\n * @param options - Default delay for entries that carry none.\n * @returns The outbox ids in send order.\n */\n async sendBatch(messages, options) {\n if (!Array.isArray(messages) || messages.length === 0) {\n throw PluginError.fromWire(\"invalid_params\", \"sendBatch requires at least one message\");\n }\n if (messages.length > MAX_LIST_PAGE) {\n throw PluginError.fromWire(\"payload_too_large\", `queue batch of ${messages.length} exceeds ${MAX_LIST_PAGE}`);\n }\n const wireMessages = messages.map((entry) => {\n const encoded = queueBodyBytes(entry?.body, entry?.contentType);\n if (encoded.body.byteLength > MAX_EVENT_PAYLOAD_BYTES) {\n throw PluginError.fromWire(\"payload_too_large\", `queue message body of ${encoded.body.byteLength} bytes exceeds ${MAX_EVENT_PAYLOAD_BYTES}`);\n }\n return {\n body: encoded.body,\n contentType: encoded.contentType,\n delaySeconds: Math.max(0, Math.floor(Number(entry?.delaySeconds ?? 0) || 0))\n };\n });\n const wire = toBridgeJson({\n messages: wireMessages,\n delaySeconds: Math.max(0, Math.floor(Number(options?.delaySeconds ?? 0) || 0))\n });\n const resp = await this.#granted.fetch(\"http://granted/queues/send\", {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/json\" },\n body: JSON.stringify(wire)\n });\n const value = await resp.json().catch(() => ({}));\n if (value && value.error) {\n throw PluginError.fromWire(value.error.code || \"internal\", value.error.message || \"\");\n }\n if (!resp.ok) {\n throw PluginError.fromWire(\"internal\", `queue send HTTP ${resp.status}`);\n }\n return {\n messageIds: Array.isArray(value.messageIds) ? value.messageIds.map((id) => String(id)) : []\n };\n }\n};\nfunction checkKvKey(key) {\n if (typeof key !== \"string\" || key.length === 0) {\n throw PluginError.fromWire(\"invalid_params\", \"kv key must be a non-empty string\");\n }\n const bytes = new TextEncoder().encode(key).byteLength;\n if (bytes > MAX_KV_KEY_BYTES) {\n throw PluginError.fromWire(\"payload_too_large\", `kv key of ${bytes} bytes exceeds ${MAX_KV_KEY_BYTES}`);\n }\n return key;\n}\nfunction parseKvMetadata(text) {\n if (typeof text !== \"string\" || text === \"\")\n return null;\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\nfunction decodeKvValue(bytes, type) {\n if (type === \"arrayBuffer\") {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n const text = new TextDecoder().decode(bytes);\n if (type === \"json\")\n return JSON.parse(text);\n return text;\n}\nvar GrantedKv = class extends RpcTarget {\n #granted;\n #auth;\n /**\n * @param granted - Granted reverse channel.\n * @param auth - Bearer header for the kv grant.\n */\n constructor(granted, auth) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n }\n async #call(op, body) {\n const resp = await this.#granted.fetch(`http://granted/kv/${op}`, {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/json\" },\n body: JSON.stringify(toBridgeJson(body))\n });\n const value = await resp.json().catch(() => ({}));\n if (value && value.error) {\n throw PluginError.fromWire(value.error.code || \"internal\", value.error.message || \"\");\n }\n if (!resp.ok) {\n throw PluginError.fromWire(\"internal\", `kv ${op} HTTP ${resp.status}`);\n }\n return value ?? {};\n }\n async get(key, type = \"text\") {\n const found = await this.#read(key, type);\n return found.value;\n }\n async getWithMetadata(key, type = \"text\") {\n return this.#read(key, type);\n }\n async #read(key, type) {\n const reply = await this.#call(\"get\", { key: checkKvKey(key) });\n if (!reply.found)\n return { value: null, metadata: null };\n const bytes = typeof reply.value === \"string\" ? base64ToBytes(reply.value) : new Uint8Array();\n return { value: decodeKvValue(bytes, type), metadata: parseKvMetadata(reply.metadata) };\n }\n async put(key, value, options) {\n let bytes;\n if (typeof value === \"string\") {\n bytes = new TextEncoder().encode(value);\n } else if (value instanceof ArrayBuffer) {\n bytes = new Uint8Array(value);\n } else if (ArrayBuffer.isView(value)) {\n bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n } else {\n throw PluginError.fromWire(\"invalid_params\", \"kv value must be a string, ArrayBuffer, or view\");\n }\n if (bytes.byteLength > MAX_KV_VALUE_BYTES) {\n throw PluginError.fromWire(\"payload_too_large\", `kv value of ${bytes.byteLength} bytes exceeds ${MAX_KV_VALUE_BYTES}`);\n }\n const metadata = options?.metadata === void 0 ? \"\" : JSON.stringify(options.metadata);\n const metadataBytes = new TextEncoder().encode(metadata).byteLength;\n if (metadataBytes > MAX_KV_METADATA_BYTES) {\n throw PluginError.fromWire(\"payload_too_large\", `kv metadata of ${metadataBytes} bytes exceeds ${MAX_KV_METADATA_BYTES}`);\n }\n const expiration = Math.max(0, Math.floor(Number(options?.expiration ?? 0) || 0));\n const ttl = Math.max(0, Math.floor(Number(options?.expirationTtl ?? 0) || 0));\n await this.#call(\"put\", {\n key: checkKvKey(key),\n value: bytes,\n options: { expirationUnixMs: expiration * 1e3, expirationTtlSeconds: ttl, metadata }\n });\n }\n async delete(key) {\n await this.#call(\"delete\", { key: checkKvKey(key) });\n }\n async list(options) {\n const limit = Math.max(0, Math.floor(Number(options?.limit ?? 0) || 0));\n if (limit > MAX_LIST_PAGE) {\n throw PluginError.fromWire(\"invalid_params\", `kv list limit of ${limit} exceeds ${MAX_LIST_PAGE}`);\n }\n const reply = await this.#call(\"list\", {\n options: { prefix: options?.prefix ?? \"\", cursor: options?.cursor ?? \"\", limit }\n });\n const keys = Array.isArray(reply.keys) ? reply.keys : [];\n const cursor = typeof reply.cursor === \"string\" && reply.cursor ? reply.cursor : void 0;\n return {\n keys: keys.map((entry) => {\n const ms = Number(entry.expirationUnixMs ?? 0) || 0;\n const metadata = parseKvMetadata(entry.metadata);\n return {\n name: String(entry.key ?? \"\"),\n ...ms > 0 ? { expiration: Math.floor(ms / 1e3) } : {},\n ...metadata !== null ? { metadata } : {}\n };\n }),\n list_complete: Boolean(reply.listComplete),\n ...cursor ? { cursor } : {}\n };\n }\n};\nvar GrantedSockets = class extends RpcTarget {\n /** Granted reverse channel that serves `POST /sockets/<op>`. */\n #granted;\n /** `Authorization` header carrying the sockets-only grant token. */\n #auth;\n /**\n * @param granted - Granted reverse channel.\n * @param auth - Bearer header for the sockets grant.\n */\n constructor(granted, auth) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n }\n /**\n * Makes one `POST /sockets/<op>` call on the granted channel.\n *\n * @param op - Operation, the path segment after `/sockets/`.\n * @param body - That operation\'s JSON fields, bytes already base64.\n * @returns `{ ok }` with the route\'s reply body, or `{ err }` with the\n * host\'s code (`unavailable` when the channel cannot be reached,\n * `internal` for a reply that is not JSON); never throws.\n */\n async call(op, body) {\n let resp;\n try {\n resp = await this.#granted.fetch(`http://granted/sockets/${op}`, {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/json\" },\n body: JSON.stringify(body)\n });\n } catch (err) {\n return { err: { code: \"unavailable\", message: `sockets ${op}: ${errorMessage(err)}` } };\n }\n const value = await resp.json().catch(() => null);\n if (value && value.error) {\n return {\n err: { code: value.error.code || \"internal\", message: value.error.message || \"\" }\n };\n }\n if (!resp.ok || !value || typeof value !== \"object\") {\n return { err: { code: \"internal\", message: `sockets ${op} HTTP ${resp.status}` } };\n }\n return { ok: value };\n }\n};\nvar GrantedOrigin = class extends RpcTarget {\n /** Granted reverse channel that serves `POST /origin/fetch`. */\n #granted;\n /** `Authorization` header carrying the origin-only grant token. */\n #auth;\n /**\n * @param granted - Granted reverse channel.\n * @param auth - Bearer header for the origin grant.\n */\n constructor(granted, auth) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n }\n /**\n * Hands one request to the library.\n *\n * @param head - Method, target, header fields and client address.\n * @param body - Request body, or `null`.\n * @returns The library\'s response, or a typed failure; never throws.\n */\n fetch(head, body) {\n return grantedOriginFetch(this.#granted, this.#auth, head, body);\n }\n};\nvar GrantedWebhooks = class extends RpcTarget {\n /** Granted reverse channel that serves `POST /webhooks/<op>`. */\n #granted;\n /** `Authorization` header carrying the webhooks-only grant token. */\n #auth;\n /**\n * @param granted - Granted reverse channel.\n * @param auth - Bearer header for the webhooks grant.\n */\n constructor(granted, auth) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n }\n /**\n * Makes one `POST /webhooks/<op>` call on the granted channel.\n *\n * @param op - Operation, the path segment after `/webhooks/`.\n * @param body - That operation\'s JSON fields, bytes already base64.\n * @returns `{ ok }` with the route\'s reply body, or `{ err }` with the\n * host\'s code (`unavailable` when the channel cannot be reached,\n * `internal` for a reply that is not JSON); never throws.\n */\n async call(op, body) {\n let resp;\n try {\n resp = await this.#granted.fetch(`http://granted/webhooks/${op}`, {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/json\" },\n body: JSON.stringify(body)\n });\n } catch (err) {\n return { err: { code: \"unavailable\", message: `webhooks ${op}: ${errorMessage(err)}` } };\n }\n const value = await resp.json().catch(() => null);\n if (value && value.error) {\n return {\n err: { code: value.error.code || \"internal\", message: value.error.message || \"\" }\n };\n }\n if (!resp.ok || !value || typeof value !== \"object\") {\n return { err: { code: \"internal\", message: `webhooks ${op} HTTP ${resp.status}` } };\n }\n return { ok: value };\n }\n};\nvar GrantedDatabase = class extends RpcTarget {\n #granted;\n #auth;\n /**\n * @param granted - Granted reverse channel.\n * @param auth - Bearer header for the database grant.\n */\n constructor(granted, auth) {\n super();\n this.#granted = granted;\n this.#auth = auth;\n }\n /**\n * Run one typed atomic batch through the host broker.\n *\n * @param request - Structured `ExecuteRequest`.\n * @returns Structured `ExecuteReply`.\n */\n async execute(request) {\n return decodeExecuteResultReply(await this.executeBytes(encodeExecuteRequest(request)));\n }\n /**\n * Same batch as Cap\'n Proto bytes (Python authors encode locally).\n *\n * @param bytes - Unpacked `ExecuteRequest` message.\n * @returns Unpacked `ExecuteResultReply` message.\n */\n async executeBytes(bytes) {\n try {\n const resp = await this.#granted.fetch(\"http://granted/db/execute\", {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/octet-stream\" },\n body: bytes\n });\n return await grantedDatabaseBody(resp);\n } catch (err) {\n return encodeExecuteResultReply({ err: wirePluginError(err) });\n }\n }\n /**\n * Run one typed atomic batch answered as stream frames\n * (`POST /db/execute-streamed`). A non-2xx status is the channel\'s error;\n * an adapter or authorization failure travels inside the frames.\n *\n * @param request - Structured `ExecuteRequest`.\n * @returns The response body: the frame sequence.\n */\n async executeStreamed(request) {\n const resp = await this.#granted.fetch(\"http://granted/db/execute-streamed\", {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/octet-stream\" },\n body: encodeExecuteRequest(request)\n });\n if (!resp.ok) {\n await grantedDatabaseBody(resp, \"executeStreamed\");\n }\n return resp.body ?? new Uint8Array(0);\n }\n /**\n * Same frames, whole, from Cap\'n request bytes (Python authors decode\n * locally).\n *\n * @param bytes - Unpacked `ExecuteRequest` message.\n * @returns Every `ExecuteStreamFrame`, concatenated; a channel failure is\n * one `err` frame.\n */\n async executeStreamedBytes(bytes) {\n try {\n const resp = await this.#granted.fetch(\"http://granted/db/execute-streamed\", {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/octet-stream\" },\n body: bytes\n });\n return await grantedDatabaseBody(resp, \"executeStreamed\");\n } catch (err) {\n return errFrame(err);\n }\n }\n /**\n * Same frames, as the channel delivers them (a `ReadableStream` when it\n * streams), from Cap\'n request bytes, so a Python `iterate()` decodes\n * frames as they arrive.\n *\n * @param bytes - Unpacked `ExecuteRequest` message.\n * @returns The response body: the frame sequence; a channel failure is\n * one `err` frame.\n */\n async openStreamedBytes(bytes) {\n try {\n const resp = await this.#granted.fetch(\"http://granted/db/execute-streamed\", {\n method: \"POST\",\n headers: { ...this.#auth, \"content-type\": \"application/octet-stream\" },\n body: bytes\n });\n if (!resp.ok) {\n await grantedDatabaseBody(resp, \"executeStreamed\");\n }\n return resp.body ?? new Uint8Array(0);\n } catch (err) {\n return errFrame(err);\n }\n }\n /**\n * Negotiated limits of the granted session (`GET /db/limits`).\n *\n * @returns The adapter\'s `DbCapabilities` for this binding.\n */\n async limits() {\n return decodeDbCapabilitiesReply(await this.limitsBytes());\n }\n /**\n * Same answer as Cap\'n Proto bytes (Python authors decode locally).\n *\n * @returns Unpacked `DbCapabilitiesReply` message; a channel failure is\n * its `err` arm.\n */\n async limitsBytes() {\n try {\n const resp = await this.#granted.fetch(\"http://granted/db/limits\", {\n method: \"GET\",\n headers: { ...this.#auth }\n });\n return await grantedDatabaseBody(resp, \"limits\");\n } catch (err) {\n return encodeDbCapabilitiesReply({ err: wirePluginError(err) });\n }\n }\n};\nfunction wirePluginError(err) {\n if (err instanceof PluginError) {\n return { code: err.wireCode, message: err.message, details: err.detailsText };\n }\n const message = err instanceof Error ? err.message : String(err);\n return { code: \"unavailable\", message: `database grant: ${message}`, details: \"\" };\n}\nfunction errFrame(err) {\n return encodeMessage(ExecuteStreamFrameCodec, { kind: \"err\", value: wirePluginError(err) });\n}\nasync function grantedDatabaseBody(resp, method = \"execute\") {\n if (!resp.ok) {\n const text = await resp.text().catch(() => \"\");\n const message = `database grant: ${resp.status} ${text}`.trim();\n if (resp.status === 413) {\n const limit = parseLimitExceeded(text);\n throw limit === void 0 ? PluginError.fromWire(\"limit_exceeded\", message) : new PluginError(\"limit_exceeded\", message, { ...limit });\n }\n if (resp.status === 404 || resp.status === 405) {\n throw PluginError.fromWire(\"unsupported\", `GuestDatabase.${method} is not served by this host (${message})`);\n }\n throw PluginError.fromWire(resp.status === 401 ? \"unauthorized\" : \"unavailable\", message);\n }\n return new Uint8Array(await resp.arrayBuffer());\n}\nvar CancelWatch = class extends RpcTarget {\n #promise;\n constructor(granted, auth, stop) {\n super();\n this.#promise = new Promise((resolve) => {\n const poll = async () => {\n while (!stop.aborted) {\n const resp = await granted.fetch(\"http://granted/cancel\", {\n headers: auth,\n signal: stop\n });\n if (resp.status === 200) {\n resolve();\n return;\n }\n if (resp.status !== 204)\n return;\n }\n };\n poll().catch(() => {\n });\n });\n }\n wait() {\n return this.#promise;\n }\n};\nfunction bytesToBase64(bytes) {\n let bin = \"\";\n for (let i = 0; i < bytes.length; i++)\n bin += String.fromCharCode(bytes[i]);\n return btoa(bin);\n}\nfunction base64ToBytes(text) {\n const bin = atob(text);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++)\n out[i] = bin.charCodeAt(i);\n return out;\n}\nvar BRIDGE_BYTES_FIELDS = /* @__PURE__ */ new Set([\"payload\", \"sha256\", \"credentials\"]);\nfunction fromBridgeJson(value) {\n if (Array.isArray(value))\n return value.map(fromBridgeJson);\n if (value === null || typeof value !== \"object\")\n return value;\n const out = {};\n for (const [key, inner] of Object.entries(value)) {\n if (BRIDGE_BYTES_FIELDS.has(key) && typeof inner === \"string\") {\n out[key] = base64ToBytes(inner);\n } else if (BRIDGE_BYTES_FIELDS.has(key) && Array.isArray(inner) && inner.every((n) => typeof n === \"number\")) {\n out[key] = Uint8Array.from(inner);\n } else {\n out[key] = fromBridgeJson(inner);\n }\n }\n return out;\n}\nfunction toBridgeJson(value) {\n if (value instanceof Uint8Array)\n return bytesToBase64(value);\n if (value instanceof ArrayBuffer)\n return bytesToBase64(new Uint8Array(value));\n if (Array.isArray(value))\n return value.map(toBridgeJson);\n if (value === null || typeof value !== \"object\")\n return value;\n const out = {};\n for (const [key, inner] of Object.entries(value)) {\n if (inner === void 0)\n continue;\n out[key] = toBridgeJson(inner);\n }\n return out;\n}\nfunction parseHeaderJson(text, name) {\n if (text === null || text === void 0 || text === \"\")\n return void 0;\n try {\n return JSON.parse(String(text));\n } catch (err) {\n throw new InvokeError(400, \"invalid_params\", `${name} header is not JSON: ${errorMessage(err)}`);\n }\n}\nfunction parseJsonBinding(value) {\n if (value == null)\n return null;\n if (typeof value === \"string\") {\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n }\n return typeof value === \"object\" ? value : null;\n}\nfunction wrapPluginFromBinding() {\n return createInvocationAdapter();\n}\nfunction wrapPluginFromNative() {\n return createInvocationAdapter();\n}\nvar TRIGGER_FAMILIES = Object.freeze({\n eventConsumer: \"eventConsumer\",\n queueConsumer: \"queueConsumer\",\n scheduledHandler: \"scheduledHandler\",\n jobRunner: \"jobRunner\",\n socketHandler: \"socketHandler\",\n webhookHandler: \"webhookHandler\"\n});\nfunction scheduledControllerOf(wire) {\n const w = wire && typeof wire === \"object\" ? wire : {};\n return Object.freeze({\n cron: String(w.cron ?? \"\"),\n scheduledTime: Number(w.scheduledTime ?? 0) || 0,\n fireId: String(w.fireId ?? \"\"),\n attempt: Number(w.attempt ?? 0) || 0,\n deadlineUnixMs: Number(w.deadlineUnixMs ?? 0) || 0\n });\n}\nfunction allowedEntrypointFamilies(capabilities, requested) {\n if (!capabilities || typeof capabilities !== \"object\")\n return [];\n const entrypoints = Array.isArray(capabilities.entrypoints) ? capabilities.entrypoints : [];\n const consumes = Array.isArray(capabilities.consumes) ? capabilities.consumes : [];\n const queueConsumers = Array.isArray(capabilities.queueConsumers) ? capabilities.queueConsumers : [];\n const jobs = Array.isArray(capabilities.jobs) ? capabilities.jobs : [];\n const crons = Array.isArray(capabilities.crons) ? capabilities.crons : [];\n const exportsStorage = entrypoints.includes(\"storage\");\n const out = [];\n for (const name of requested) {\n if (typeof name !== \"string\" || out.includes(name))\n continue;\n if (name === TRIGGER_FAMILIES.eventConsumer) {\n if (consumes.length > 0)\n out.push(name);\n } else if (name === TRIGGER_FAMILIES.queueConsumer) {\n if (queueConsumers.length > 0)\n out.push(name);\n } else if (name === TRIGGER_FAMILIES.scheduledHandler) {\n if (crons.length > 0)\n out.push(name);\n } else if (name === TRIGGER_FAMILIES.jobRunner) {\n if (jobs.length > 0 || exportsStorage)\n out.push(name);\n } else if (name === TRIGGER_FAMILIES.socketHandler) {\n if (capabilities.sockets === true)\n out.push(name);\n } else if (name === TRIGGER_FAMILIES.webhookHandler) {\n if (capabilities.webhooks === true)\n out.push(name);\n } else if (name in ENTRYPOINT_BINDINGS && entrypoints.includes(name)) {\n out.push(name);\n }\n }\n return out;\n}\nfunction mergeDescribe(base, guest) {\n const guestCli = guest.cli;\n const cli = guestCli && Array.isArray(guestCli.commands) && guestCli.commands.length > 0 ? guestCli : base.cli ?? guestCli;\n const guestOptions = guest.configOptions;\n const configOptions = Array.isArray(guestOptions) && guestOptions.length > 0 ? guestOptions : base.configOptions ?? guestOptions;\n return {\n ...base,\n ...guest,\n apiVersion: base.apiVersion ?? guest.apiVersion ?? 3,\n id: base.id ?? guest.id,\n capabilities: base.capabilities ?? guest.capabilities,\n // `[media]` is the authority for the declared media, like capabilities.\n media: base.media ?? guest.media,\n ...cli === void 0 ? {} : { cli },\n ...configOptions === void 0 ? {} : { configOptions }\n };\n}\nfunction createInvocationAdapter() {\n return class InvocationAdapter extends WorkerEntrypoint {\n #manifest() {\n return parseJsonBinding(this.env.PLUGIN_DESCRIBE) ?? {};\n }\n #author() {\n if (this.env.PLUGIN)\n return this.env.PLUGIN;\n throw PluginError.fromWire(\"unavailable\", \"PLUGIN binding missing\");\n }\n #named(name) {\n const binding = ENTRYPOINT_BINDINGS[name];\n const stub = binding ? this.env[binding] : void 0;\n if (!stub) {\n throw PluginError.fromWire(\"unsupported\", `${name} entrypoint not exported`);\n }\n return stub;\n }\n /**\n * Turn the bridge context into the author-facing one: the host\'s events,\n * database, and queue grant tokens become `EVENTS` / `env.<BINDING>`\n * stubs and never reach the author.\n *\n * @param ctx - Bridge context from the launcher.\n * @returns Author-facing granted context.\n */\n #bindContext(ctx) {\n const source = ctx && typeof ctx === \"object\" ? ctx : {};\n const { eventsToken, notifyToken, aiToken, databases, queues, kv, sockets, originToken, webhooksToken, ...rest } = source;\n const bound = rest;\n const granted = this.env.GRANTED;\n if (typeof eventsToken === \"string\" && eventsToken && granted) {\n bound.events = new GrantedEvents(granted, {\n Authorization: `Bearer ${eventsToken}`\n });\n }\n if (typeof notifyToken === \"string\" && notifyToken && granted) {\n bound.notify = new GrantedNotify(granted, {\n Authorization: `Bearer ${notifyToken}`\n });\n }\n if (typeof aiToken === \"string\" && aiToken && granted) {\n bound.ai = new GrantedAi(granted, {\n Authorization: `Bearer ${aiToken}`\n });\n }\n if (databases && typeof databases === \"object\" && !Array.isArray(databases) && granted) {\n const named2 = [];\n for (const [name, token] of Object.entries(databases)) {\n if (!name || typeof token !== \"string\" || !token)\n continue;\n named2.push({\n name,\n transport: new GrantedDatabase(granted, { Authorization: `Bearer ${token}` })\n });\n }\n if (named2.length > 0)\n bound.databases = named2;\n }\n if (queues && typeof queues === \"object\" && !Array.isArray(queues) && granted) {\n const named2 = [];\n for (const [name, token] of Object.entries(queues)) {\n if (!name || typeof token !== \"string\" || !token)\n continue;\n named2.push({\n name,\n queue: new GrantedQueue(granted, { Authorization: `Bearer ${token}` })\n });\n }\n if (named2.length > 0)\n bound.queues = named2;\n }\n if (kv && typeof kv === \"object\" && !Array.isArray(kv) && granted) {\n const named2 = [];\n for (const [name, token] of Object.entries(kv)) {\n if (!name || typeof token !== \"string\" || !token)\n continue;\n named2.push({ name, kv: new GrantedKv(granted, { Authorization: `Bearer ${token}` }) });\n }\n if (named2.length > 0)\n bound.kv = named2;\n }\n if (sockets && typeof sockets === \"object\" && !Array.isArray(sockets) && granted) {\n const named2 = [];\n for (const [name, token] of Object.entries(sockets)) {\n if (!name || typeof token !== \"string\" || !token)\n continue;\n named2.push({\n name,\n sockets: new GrantedSockets(granted, { Authorization: `Bearer ${token}` })\n });\n }\n if (named2.length > 0)\n bound.sockets = named2.slice(0, 1);\n }\n if (typeof originToken === \"string\" && originToken && granted) {\n bound.origin = new GrantedOrigin(granted, { Authorization: `Bearer ${originToken}` });\n }\n if (typeof webhooksToken === \"string\" && webhooksToken && granted) {\n bound.webhooks = new GrantedWebhooks(granted, {\n Authorization: `Bearer ${webhooksToken}`\n });\n }\n return bound;\n }\n async fetch(_request) {\n return new Response(null, { status: 404 });\n }\n /**\n * `PluginDescribe`: the manifest projection the launcher binds as\n * `PLUGIN_DESCRIBE`, refined by the guest\'s describe. Author mode calls\n * the author\'s optional `describe()`; native-behind-workerd passes the\n * native guest\'s typed describe as `native`. Identity and capabilities\n * always come from the manifest.\n *\n * @param native - Native guest describe (native-behind-workerd only).\n * @returns Wire describe.\n */\n async describe(native) {\n const base = this.#manifest();\n if (native !== void 0) {\n if (native === null || typeof native !== \"object\") {\n throw PluginError.fromWire(\"invalid_params\", \"native describe must be an object\");\n }\n return mergeDescribe(base, native);\n }\n const author = await this.#author().bookclerkDescribe() ?? {};\n return mergeDescribe(base, author);\n }\n /**\n * `/open` policy for native-behind-workerd: validates the invocation\n * envelope and returns the requested entrypoint / trigger families the\n * manifest (`PLUGIN_DESCRIBE`) lets this plugin export. The launcher\n * nulls every family that is not returned.\n *\n * @param ctx - Open context (`invocation`, `config`, `secrets`).\n * @param requested - Family names the launcher wants to export.\n * @returns Authorized subset of `requested`.\n */\n async openInvocation(ctx, requested = []) {\n const invocation = ctx && typeof ctx === \"object\" ? ctx.invocation : void 0;\n if (!invocation || typeof invocation.id !== \"string\" || !invocation.id) {\n throw PluginError.fromWire(\"invalid_params\", \"open requires a non-empty invocation id\");\n }\n const list = Array.isArray(requested) ? requested : [];\n return allowedEntrypointFamilies(this.#manifest().capabilities, list);\n }\n /**\n * Call `method` on the named entrypoint `name` with the granted context.\n *\n * @param name - Entrypoint wire name.\n * @param ctx - Granted context.\n * @param method - Method name.\n * @param args - Method arguments.\n * @returns Method result.\n */\n async invokeEntrypoint(name, ctx, method, args = []) {\n const list = Array.isArray(args) ? args : [];\n return this.#named(name).bookclerkInvoke(this.#bindContext(ctx), method, ...list);\n }\n /**\n * Stream routes (`GET /destination/get`, `PUT /destination/put`) \u{2192}\n * `storage` entrypoint. Every other `Destination` method travels on\n * `POST /invoke` ({@link InvocationAdapter.invoke}).\n *\n * @param op - `get` or `put`.\n * @param ctx - Granted context.\n * @param args - Route arguments.\n * @param body - Stream body for `put`.\n * @returns Method result.\n */\n async invokeDestination(op, ctx, args = {}, body) {\n switch (op) {\n case \"get\":\n return this.invokeEntrypoint(\"storage\", ctx, \"get\", [\n String(args.key ?? \"\"),\n args.options\n ]);\n case \"put\": {\n if (!body) {\n throw PluginError.fromWire(\"invalid_params\", \"put missing body stream\");\n }\n const options = args.options;\n const bounded = exactLengthBody(body, options?.contentLength);\n return this.invokeEntrypoint(\"storage\", ctx, \"put\", [\n String(args.key ?? \"\"),\n bounded,\n options\n ]);\n }\n default:\n throw PluginError.fromWire(\"unsupported\", `destination.${op} is not a stream route`);\n }\n }\n /**\n * `/source/open` route \u{2192} `storage.get`.\n *\n * @param ctx - Granted context.\n * @param key - Object key.\n * @returns Opened byte source result.\n */\n async invokeSourceOpen(ctx, key) {\n return this.invokeEntrypoint(\"storage\", ctx, \"get\", [String(key ?? \"\")]);\n }\n /**\n * Resolve one request capability descriptor (`X-Bookclerk-Caps` entry)\n * into the granted-channel stub handed to the author.\n *\n * @param descriptor - Capability descriptor.\n * @param stop - Aborts when the call returns.\n * @returns Granted stub, or `undefined` for an unknown kind.\n */\n #importCap(descriptor, stop) {\n const granted = this.env.GRANTED;\n if (!granted) {\n throw new InvokeError(500, \"unavailable\", \"GRANTED reverse channel missing\");\n }\n const auth = { Authorization: `Bearer ${String(descriptor.token ?? \"\")}` };\n switch (descriptor.kind) {\n case \"source\":\n return new GrantedSource(granted, auth, stop);\n case \"destination\":\n return new GrantedDestination(granted, auth, stop);\n case \"progress\":\n return new GrantedProgress(granted, auth, stop);\n case \"cancellation\":\n return new CancelWatch(granted, auth, stop);\n default:\n return void 0;\n }\n }\n /**\n * `POST /invoke`: one ABI method call as Cap\'n Proto bytes. The bridge\n * passes the request headers through verbatim; the reply carries the\n * `$Results` bytes plus the descriptors of capabilities it exported.\n * Transport failures (unknown method, malformed message, missing\n * binding) come back as an {@link InvokeFailure} with the HTTP status the\n * bridge should answer with \u{2014} never as a thrown error, because Workers\n * RPC drops own properties of thrown errors.\n *\n * @param iface - `X-Bookclerk-Interface` (Cap\'n interface name).\n * @param method - `X-Bookclerk-Method`.\n * @param contextJson - `X-Bookclerk-Context` bridge JSON, or `null`.\n * @param capsJson - `X-Bookclerk-Caps` JSON descriptor array, or `null`.\n * @param target - `X-Bookclerk-Target` isolate object id, or `null`.\n * @param body - `$Params` message bytes.\n * @returns Reply bytes plus capability descriptors, or a transport failure.\n */\n async invoke(iface, method, contextJson, capsJson, target, body) {\n const host = {\n author: () => this.env.PLUGIN,\n named: (name) => {\n const binding = ENTRYPOINT_BINDINGS[name];\n return this.env[binding];\n },\n bindContext: (ctx) => this.#bindContext(ctx),\n importCap: (descriptor, stop) => this.#importCap(descriptor, stop)\n };\n try {\n const context = parseHeaderJson(contextJson, \"context\");\n if (context !== void 0 && (context === null || typeof context !== \"object\" || Array.isArray(context))) {\n throw new InvokeError(400, \"invalid_params\", \"context header must be a JSON object\");\n }\n const caps = parseHeaderJson(capsJson, \"caps\") ?? [];\n if (!Array.isArray(caps)) {\n throw new InvokeError(400, \"invalid_params\", \"caps header must be a JSON array\");\n }\n const ctx = context === void 0 ? void 0 : fromBridgeJson(context);\n return await dispatchInvoke(String(iface ?? \"\"), String(method ?? \"\"), ctx, caps, typeof target === \"string\" && target ? target : null, body instanceof Uint8Array ? body : new Uint8Array(body ?? []), host);\n } catch (err) {\n if (err instanceof InvokeError) {\n return { status: err.status, error: { code: err.wireCode, message: err.message } };\n }\n return { status: 500, error: { code: \"internal\", message: errorMessage(err) } };\n }\n }\n /**\n * `/shutdown` route \u{2192} default entrypoint `shutdown`. Without an author\n * `PLUGIN` binding (native-behind-workerd) there is nothing to run here:\n * the launcher shuts the native guest down over Cap\'n Proto.\n *\n * @returns Resolves when the author hook has run.\n */\n async shutdown() {\n if (!this.env.PLUGIN)\n return;\n await this.#author().bookclerkShutdown();\n }\n };\n}\n\n// dist/db-adapter.js\nvar GUEST_RECEIPT_WRAP_PREFIX = 2;\nvar GUEST_RECEIPT_STUB_SUFFIX = 1;\nvar GUEST_REPLAY_PAYLOAD_MAX_BYTES = 65536;\nvar GUEST_READ_ONLY_REPLAY_PAYLOAD = \'{\"readOnly\":true}\';\nvar GUEST_RECEIPT_RESULT_LOST = \"guest receipt committed without payload; original response lost\";\nvar GUEST_RECEIPT_CLAIM_LOST = \"guest receipt claimed by a concurrent attempt; retry to replay it\";\nvar STREAM_FRAME_TARGET_BYTES = 64 * 1024;\nvar STATUS_CLAIMED = \"claimed\";\nvar FINALIZE_SQL = \"UPDATE bookclerk_receipts SET payload = ?, status = \'ok\' WHERE operation_id = ? AND status IN (\'claimed\', \'applied\')\";\nasync function executeAdapterBatch(request, begin, options) {\n return inTransaction(begin, (txn) => runAdapterBatch(request, txn, options));\n}\nasync function executeAdapterBatchStreamed(request, begin, options) {\n return inTransaction(begin, async (txn) => {\n const reply = await runAdapterBatch(request, txn, options);\n const frames = encodeExecuteStream(reply, STREAM_FRAME_TARGET_BYTES, MAX_SCALAR_BYTES);\n decodeExecuteStream(frames, options.limits);\n requireReplyWithinBudget(reply, options.limits);\n return frames;\n });\n}\nfunction requireReplyWithinBudget(reply, limits) {\n if (limits.maxBytes === 0) {\n return;\n }\n const used = encodeExecuteReply(reply).length;\n if (used > limits.maxBytes) {\n throw PluginError.limitExceeded({ limit: limits.bytesLimit, cap: limits.maxBytes, used });\n }\n}\nasync function inTransaction(begin, body) {\n const txn = await begin();\n let result;\n try {\n result = await body(txn);\n await txn.commit();\n } catch (err) {\n try {\n await txn.rollback();\n } catch {\n }\n throw err;\n }\n return result;\n}\nasync function runAdapterBatch(request, txn, options) {\n const started = Date.now();\n const total = request.statements.length;\n const guestLen = request.receipt.guestLen;\n const guestHash = request.receipt.guestHash;\n const statements = [];\n for (const statement of request.statements) {\n statements.push(await txn.run(statement));\n if (guestLen > 0 && shouldSkipRemainingGuestWork(statements, total, guestHash)) {\n while (statements.length < total) {\n statements.push(affected(0));\n }\n break;\n }\n }\n const timing = () => {\n const elapsed = Math.max(0, Date.now() - started) * 1e3;\n return {\n attemptElapsedUs: elapsed,\n dbExecutionUs: elapsed,\n dbTimingSource: options.timingSource\n };\n };\n for (const result of statements) {\n for (const row of result.rows) {\n row.values.forEach(validateCell);\n }\n }\n if (guestLen > 0) {\n const prior = statements[1];\n const stub = statements[statements.length - 1];\n if (prior !== void 0 && prior.rows.length === 0 && stub?.rowsAffected === 0) {\n throw PluginError.fromWire(\"unavailable\", GUEST_RECEIPT_CLAIM_LOST);\n }\n const partial = {\n operationId: request.operationId,\n statements,\n timing: timing()\n };\n const readOnly = guestBatchIsReadOnly(request.statements, guestLen);\n for (const statement of guestReceiptFinalizeStatements(partial, guestLen, guestHash, readOnly)) {\n await txn.run(statement);\n }\n }\n return { operationId: request.operationId, statements, timing: timing() };\n}\nfunction guestBatchIsReadOnly(statements, guestLen) {\n const end = GUEST_RECEIPT_WRAP_PREFIX + guestLen;\n if (guestLen === 0 || end > statements.length) {\n return false;\n }\n return statements.slice(GUEST_RECEIPT_WRAP_PREFIX, end).every((s) => s.kind === \"select\");\n}\nfunction guestReceiptFinalizeStatements(partial, guestLen, guestHash, readOnly) {\n const expected = GUEST_RECEIPT_WRAP_PREFIX + guestLen + GUEST_RECEIPT_STUB_SUFFIX;\n if (partial.statements.length !== expected) {\n throw PluginError.fromWire(\"internal\", `guest atomic receipt wrap returned ${partial.statements.length} statements; expected ${expected}`);\n }\n const prior = partial.statements[1];\n const priorHash = prior ? receiptHash(prior) : void 0;\n if (prior && priorHash !== void 0) {\n if (priorHash !== guestHash) {\n return [];\n }\n if (receiptText(prior, \"payload\", 3) !== void 0) {\n return [];\n }\n const claimed = receiptText(prior, \"status\", 2) === STATUS_CLAIMED;\n const stubAffected = partial.statements[partial.statements.length - 1]?.rowsAffected ?? 0;\n if (!claimed && stubAffected === 0) {\n throw PluginError.fromWire(\"unavailable\", GUEST_RECEIPT_RESULT_LOST);\n }\n if (claimed && stubAffected === 0) {\n return [];\n }\n }\n const payload = readOnly ? GUEST_READ_ONLY_REPLAY_PAYLOAD : guestReplayPayload({\n operationId: partial.operationId,\n statements: partial.statements.slice(GUEST_RECEIPT_WRAP_PREFIX, GUEST_RECEIPT_WRAP_PREFIX + guestLen),\n timing: partial.timing\n });\n return [\n {\n sql: FINALIZE_SQL,\n parameters: [\n { kind: \"text\", value: payload },\n { kind: \"text\", value: partial.operationId }\n ],\n kind: \"execute\",\n maxRows: 0,\n resultSelection: \"affectedRows\"\n }\n ];\n}\nfunction shouldSkipRemainingGuestWork(results, total, guestHash) {\n if (results.length !== GUEST_RECEIPT_WRAP_PREFIX || total <= GUEST_RECEIPT_WRAP_PREFIX) {\n return false;\n }\n const prior = results[1];\n const priorHash = prior ? receiptHash(prior) : void 0;\n if (!prior || priorHash === void 0) {\n return false;\n }\n const sameHash = priorHash === guestHash;\n const resumesClaim = sameHash && receiptText(prior, \"status\", 2) === STATUS_CLAIMED;\n const readOnlyReplay = sameHash && receiptText(prior, \"payload\", 3) === GUEST_READ_ONLY_REPLAY_PAYLOAD;\n return !resumesClaim && !readOnlyReplay;\n}\nfunction guestReplayPayload(reply) {\n const statements = reply.statements.map(statementJson).join(\",\");\n const t = reply.timing;\n const text = `{\"operation_id\":${JSON.stringify(reply.operationId)},\"statements\":[${statements}],\"timing\":{\"attemptElapsedUs\":${uint(t.attemptElapsedUs)},\"dbExecutionUs\":${uint(t.dbExecutionUs)},\"dbTimingSource\":${JSON.stringify(t.dbTimingSource)}}}`;\n const bytes = new TextEncoder().encode(text).byteLength;\n if (bytes > GUEST_REPLAY_PAYLOAD_MAX_BYTES) {\n throw PluginError.fromWire(\"internal\", `guest replay payload is ${bytes} bytes; max is ${GUEST_REPLAY_PAYLOAD_MAX_BYTES}`);\n }\n return text;\n}\nfunction encodeExecuteStream(reply, frameTargetBytes = STREAM_FRAME_TARGET_BYTES, maxBytes = Number.POSITIVE_INFINITY) {\n const parts = [];\n let total = 0;\n const push = (part) => {\n total += part.byteLength;\n if (total > maxBytes) {\n throw PluginError.limitExceeded({ limit: \"maxScalarBytes\", cap: maxBytes, used: total });\n }\n parts.push(part);\n };\n push(frame({\n kind: \"head\",\n value: { operationId: reply.operationId, statementCount: reply.statements.length }\n }));\n reply.statements.forEach((stmt, index) => {\n push(frame({\n kind: \"statement\",\n value: { index, columns: stmt.columns, rowsAffected: stmt.rowsAffected }\n }));\n let start = 0;\n let size = 0;\n stmt.rows.forEach((row, i) => {\n const estimate = rowSizeEstimate(row);\n if (size > 0 && size + estimate > frameTargetBytes) {\n pushRowsFrames(push, stmt.rows.slice(start, i));\n start = i;\n size = 0;\n }\n size += estimate;\n });\n pushRowsFrames(push, stmt.rows.slice(start));\n });\n push(frame({ kind: \"end\", value: reply.timing }));\n const out = new Uint8Array(total);\n let at = 0;\n for (const part of parts) {\n out.set(part, at);\n at += part.byteLength;\n }\n return out;\n}\nfunction pushRowsFrames(push, rows) {\n if (rows.length === 0) {\n return;\n }\n const encoded = frame({ kind: \"rows\", value: rows });\n if (encoded.byteLength > MAX_SCALAR_BYTES && rows.length > 1) {\n const mid = Math.floor(rows.length / 2);\n pushRowsFrames(push, rows.slice(0, mid));\n pushRowsFrames(push, rows.slice(mid));\n return;\n }\n push(encoded);\n}\nfunction frame(value) {\n return encodeMessage(ExecuteStreamFrameCodec, value);\n}\nfunction rowSizeEstimate(row) {\n let size = 16;\n for (const value of row.values) {\n if (value.kind === \"text\") {\n size += new TextEncoder().encode(value.value).byteLength + 24;\n } else if (value.kind === \"bytes\") {\n size += value.value.byteLength + 24;\n } else {\n size += 24;\n }\n }\n return size;\n}\nfunction receiptHash(prior) {\n const cell = receiptCell(prior, \"request_hash\", 1);\n return cell?.kind === \"text\" ? cell.value : void 0;\n}\nfunction receiptText(prior, column, fallback) {\n const cell = receiptCell(prior, column, fallback);\n return cell?.kind === \"text\" && cell.value !== \"\" ? cell.value : void 0;\n}\nfunction receiptCell(prior, column, fallback) {\n const row = prior.rows[0];\n if (!row) {\n return void 0;\n }\n const named2 = prior.columns.findIndex((c) => c.name.toLowerCase() === column);\n return row.values[named2 >= 0 ? named2 : fallback];\n}\nfunction affected(n) {\n return { rows: [], columns: [], rowsAffected: n };\n}\nfunction statementJson(stmt) {\n const rows = stmt.rows.map((row) => `{\"values\":[${row.values.map(valueJson).join(\",\")}]}`);\n const columns = stmt.columns.map(columnJson);\n return `{\"rows\":[${rows.join(\",\")}],\"columns\":[${columns.join(\",\")}],\"rowsAffected\":${uint(stmt.rowsAffected)}}`;\n}\nfunction columnJson(column) {\n return `{\"name\":${JSON.stringify(column.name)},\"dbType\":${JSON.stringify(column.dbType)}}`;\n}\nfunction valueJson(value) {\n switch (value.kind) {\n case \"null\":\n return `{\"kind\":\"null\",\"value\":${JSON.stringify(value.value)}}`;\n case \"boolean\":\n return `{\"kind\":\"boolean\",\"value\":${value.value ? \"true\" : \"false\"}}`;\n case \"int64\":\n return `{\"kind\":\"int64\",\"value\":${BigInt(value.value).toString()}}`;\n case \"float64\":\n if (!Number.isFinite(value.value)) {\n throw PluginError.fromWire(\"internal\", \"guest replay payload has a non-finite float\");\n }\n return `{\"kind\":\"float64\",\"value\":${Object.is(value.value, -0) ? \"-0.0\" : JSON.stringify(value.value)}}`;\n case \"text\":\n return `{\"kind\":\"text\",\"value\":${JSON.stringify(value.value)}}`;\n case \"bytes\":\n return `{\"kind\":\"bytes\",\"value\":[${Array.from(value.value).join(\",\")}]}`;\n }\n}\nfunction uint(n) {\n if (!Number.isSafeInteger(n) || n < 0) {\n throw PluginError.fromWire(\"internal\", `guest replay payload counter ${n} is not a u64`);\n }\n return String(n);\n}\n\n// dist/scan-page.js\nvar CURSOR_PREFIX = \"sp1.\";\nvar UTF82 = new TextEncoder();\nfunction writeCursor(position) {\n const cursor = `${CURSOR_PREFIX}${position.offset}.${position.storeCursor}`;\n if (UTF82.encode(cursor).length > MAX_SCAN_CURSOR_BYTES) {\n throw new PluginError(\"internal\", `store cursor too long: a scan cursor is at most ${MAX_SCAN_CURSOR_BYTES} bytes`);\n }\n return cursor;\n}\nfunction readCursor(cursor) {\n if (cursor === \"\")\n return { storeCursor: \"\", offset: 0 };\n const stale = () => new PluginError(\"invalid_cursor\", \"scan cursor was not written by scanPage\");\n if (!cursor.startsWith(CURSOR_PREFIX))\n throw stale();\n const rest = cursor.slice(CURSOR_PREFIX.length);\n const dot = rest.indexOf(\".\");\n const digits = dot < 0 ? \"\" : rest.slice(0, dot);\n if (!/^(0|[1-9][0-9]{0,15})$/.test(digits))\n throw stale();\n const offset = Number(digits);\n if (!Number.isSafeInteger(offset) || offset % MAX_SCAN_PAGE_BOOKS !== 0)\n throw stale();\n return { storeCursor: rest.slice(dot + 1), offset };\n}\nasync function scanPage(params, fetchStorePage) {\n const { storeCursor, offset } = readCursor(params.cursor);\n const page = await fetchStorePage(storeCursor, params);\n const removed = page.removed ?? [];\n if (offset > 0 && offset >= page.books.length && offset >= removed.length) {\n throw new PluginError(\"invalid_cursor\", \"the store page shrank during the pass\");\n }\n const end = offset + MAX_SCAN_PAGE_BOOKS;\n const reply = {\n books: page.books.slice(offset, end),\n removed: removed.slice(offset, end),\n nextCursor: \"\",\n syncToken: \"\",\n complete: false,\n storePages: page.storePages ?? 1\n };\n if (page.books.length > end || removed.length > end) {\n reply.nextCursor = writeCursor({ storeCursor, offset: end });\n } else if (page.next) {\n reply.nextCursor = writeCursor({ storeCursor: page.next, offset: 0 });\n } else {\n reply.syncToken = page.syncToken ?? \"\";\n reply.complete = page.complete ?? false;\n }\n return reply;\n}\nexport {\n AdapterDatabaseSession,\n AiEntrypoint,\n BookclerkEntrypoint,\n CliEntrypoint,\n CoverEntrypoint,\n DatabaseAdapterEntrypoint,\n Destination,\n ENTRYPOINT_BINDINGS,\n ENTRYPOINT_CLASSES,\n EventBatch,\n EventMessage,\n ExecuteStreamDecoder,\n FEATURE_SCALAR_LIMITS,\n FEATURE_STORAGE_CHANGES,\n FEATURE_STORAGE_CONDITIONAL_WRITE,\n FEATURE_STORAGE_COPY,\n FEATURE_STORAGE_DELETE_MANY,\n FEATURE_STORAGE_HEAD_MANY,\n FEATURE_STORAGE_MOVE,\n FEATURE_STORAGE_MOVE_MANY,\n FEATURE_STREAMS,\n GUEST_READ_ONLY_REPLAY_PAYLOAD,\n GUEST_RECEIPT_CLAIM_LOST,\n GUEST_RECEIPT_RESULT_LOST,\n GUEST_RECEIPT_STUB_SUFFIX,\n GUEST_RECEIPT_WRAP_PREFIX,\n GUEST_REPLAY_PAYLOAD_MAX_BYTES,\n IngressEntrypoint,\n InvokeError,\n JobController,\n MAX_BATCH_KEYS,\n MAX_CHANGES_CURSOR_BYTES,\n MAX_CHANGES_PAGE,\n MAX_CHECKPOINT_BYTES,\n MAX_EVENT_PAYLOAD_BYTES,\n MAX_LIST_PAGE,\n MAX_PLUGIN_MIGRATION_OPS,\n MAX_PLUGIN_MIGRATION_REGISTRATION_BYTES,\n MAX_PLUGIN_MIGRATION_TOTAL_OPS,\n MAX_SCALAR_BYTES,\n MAX_STREAM_WINDOW_BYTES,\n MAX_WRITE_KEY_BYTES,\n MetadataEntrypoint,\n MetadataFilesEntrypoint,\n NamedEntrypoint,\n NotifierEntrypoint,\n OidcEntrypoint,\n PRODUCT_API_VERSION,\n PluginError,\n ProgressSink,\n QueueBatch,\n QueueMessage,\n RemoteLibraryEntrypoint,\n STREAM_FRAME_TARGET_BYTES,\n Source,\n StorageEntrypoint,\n StorefrontEntrypoint,\n TRIGGER_FAMILIES,\n WriteChunksError,\n allowedEntrypointFamilies,\n canonicalExecuteRequestHash,\n chunkIndexes,\n cliArgs,\n collectExecuteStream,\n createDatabaseBinding,\n dataMigrationOp,\n decodeDbValue,\n decodeExecuteRequest,\n decodeExecuteResultReply,\n decodeExecuteStream,\n decodeExtensibleConfig,\n dispatchInvoke,\n encodeDbValue,\n encodeExecuteRequest,\n encodeExecuteResultReply,\n encodeExecuteStream,\n eventBatchResults,\n executeAdapterBatch,\n executeAdapterBatchStreamed,\n executeReplyToD1Results,\n executeStreamLimits,\n fromBridgeJson,\n guestBatchIsReadOnly,\n guestReceiptFinalizeStatements,\n guestReplayPayload,\n invocationOf,\n jobOutcomeFor,\n jsonPayload,\n packEmbeddingVectors,\n parseDbValue,\n queueBatchResults,\n rawStreamCeiling,\n requirePluginMigrationRegistration,\n runAdapterBatch,\n scanPage,\n schemaMigrationOp,\n shouldSkipRemainingGuestWork,\n statementResultToD1Result,\n streamsResults,\n toBridgeJson,\n unpackEmbeddingVectors,\n wrapPluginFromBinding,\n wrapPluginFromNative,\n writeChunksOperationId\n};\n";
Source text of the embeddable workerd runtime helper.
Contains the BookclerkEntrypoint base class, the named *Entrypoint
bases, and the RpcTarget stream classes mirrored by the npm package. Written to
modules/@bookclerk/plugin-sdk/workerd.js by bookclerk-plugin sync-embed
(crate bookclerk-plugin-tools) when authors need an offline vendor.
Generated from crates/bookclerk-plugin-sdk at main · View as Markdown