/** * BOOKS IN THE OBJECT (owner, 4 Nov 2026: Cotton Books, a Kindle and * Goodreads app over the one object). The `book` table is the books kit's * (crates/cotton-core/kits/personal/tables/book.json); these are its acts: * * - `start_book { book }` and `finish_book { book }`: the day stamped in the * object's own zone, never the phone's guess. Starting a finished book is a * re-read: its finished day is cleared; finishing counts the reading * (`read_count`). * - `find_book { query | isbn, book? }`: Open Library, asked by the * object (identified as `artwork.ts` identifies itself; the phone never looks * anything up). A query takes the first match and makes a Want to read book * from it, or fills the one already holding that Open Library work; an ISBN * makes one. Either fills the book named (a book's Find details: the phone * asks by its ISBN where it has one, else by its title and author). Only EMPTY columns are filled, and * the cover is fetched by cover id and kept as the object's media, as the * artwork engine keeps one. Open Library answering 403 or 429 is a refusal, * `lookup_failed`: asked too often, try again later. NOT ANSWERING (7 Nov * 2026: Open Library's Cloudflare answered the Worker 521 for minutes) — * no answer at all, a 5xx, or a 200 that is no search answer — is asked * once more after LOOKUP_WAIT_MS, then refused `lookup_failed` in the * honest line NOT_ANSWERING, and the book keeps what it has: a lookup that * was not answered is never read as nothing found. The cover is asked the * same way; one still not answered leaves the details written, the answer * saying so (`cover_unanswered`), and the artwork engine asks again. * - A book's KIND FOLLOWS ITS FILE (5 Nov 2026): every write of a `book` * row that leaves `file` set and `format` empty, whoever writes it (an * act, the phone's post, MCP, an import), sets `format` from the file key's * extension, one of the kinds media keeps under `books/` (bookTypes); a * file of any other extension is refused. The reader opens only an `epub` * or a `pdf`, and `format` is readonly, so no writer can be trusted to say * it (`withBookFormat`, folded by the engine on create and update). * - `import_goodreads { file }`: a Goodreads library export (My Books › * Import and export › Export Library), its CSV TEXT, read by HEADER NAME — * the 24 columns of today's export, or the 31 of an older one. Each book is * found again by its Goodreads id, so a second import updates, never * moving a book backwards or over what the owner set in Cotton; other * shelves become lists (record groups of `book`), one per shelf name. * - WHERE A BOOK'S FACTS CAME FROM (7 Nov 2026): a * fill says, in the book's `filled_from` (film's shape, a JSON object of * column to source), the source of each column it wrote: `open_library` * for find_book, `goodreads` for import_goodreads, `opf` for the book_file * pass (book_file.ts) and the phone's EPUB add. BOOK_SOURCES is the one * closed list, held to cotton_core::books::SOURCES by the shared fixture * crates/cotton-core/tests/fixtures/book_filled_from.json. */import { derivedId } from"./import/ids.ts";import { filling, typeEngine, typeOutcome } from"./engine.ts";import { isSealedRow } from"./seal.ts";import { kept, USER_AGENT as ARTWORK_AGENT, typeArtworkHost, typeFetcher } from"./artwork.ts";import { refuse } from"./http.ts";import { bookTypes } from"./media.ts";import { equalSql } from"./mcp/tools/records/where.ts";import { filledFrom } from"./filled_from.ts";importtype { StoredRow } from"./store.ts";importtype { Data } from"./mcp/context.ts";exportconst BOOK = "book";exportconst GROUP = "record_group";exportconst MEMBER = "group_member";exportconst OPEN_LIBRARY = "https://openlibrary.org/search.json";/** Who asks, as Open Library asks a client to say (3 requests a second, not 1): the artwork engine's own name, so the cover it fetches says the same. */exportconst USER_AGENT = ARTWORK_AGENT;/** The fields a search answers with: one request, no second call for the edition. */const FIELDS = "key,title,author_name,first_publish_year,number_of_pages_median,cover_i,language,isbn";// ── where its facts came from ────────────────────────────────────────────/** Every source a book's `filled_from` names, and no other (cotton_core::books::SOURCES). */exportconst BOOK_SOURCES = ["opf", "goodreads", "open_library"] asconst;exporttypeBookSource = (typeof BOOK_SOURCES)[number];exportconst FILLED_FROM = "filled_from";/** * The `filled_from` a fill of `columns` from `from` writes on a book holding * `held`: each column said beside what was said already. Nothing when it * filled nothing, or the object's book table holds no `filled_from` yet. */exportfunction stampFilled(engine: Engine, held: unknown, columns: readonly string[], from: BookSource): Data {const said = columns.filter((k) => k !== FILLED_FROM);if (!said.length || !engine.defs.table(BOOK)?.columns.some((c) => c.key === FILLED_FROM)) return {};return { [FILLED_FROM]: filledFrom(held, Object.fromEntries(said.map((k) => [k, from]))) };}// ── a book's kind ────────────────────────────────────────────────────────const empty = (value: unknown): boolean => value === null || value === undefined || value === "";/** * A book write with its `format` filled from its file: where the row as it * will stand (`held` under `data`) has a `file` and no `format`, `format` is * the file key's extension, a kind bookTypes names, or the write is * refused. A row with no file, or one that names its format, is left as it is. */exportfunction withBookFormat(data: Data, held: Data = {}): Data {const file = data.file !== undefined ? data.file : held.file;const format = data.format !== undefined ? data.format : held.format;if (empty(file) || !empty(format)) return data;const ext = typeof file === "string" ? /\.([^./]+)$/.exec(file)?.[1] : undefined;if (!ext || !Object.hasOwn(bookTypes(), ext)) { refuse(400, "bad_book_file", `a book's file is ${Object.keys(bookTypes()).map((k) => `.${k}`).join(" or ")}, not ${JSON.stringify(file)}`); }return { ...data, format: ext };}// ── the reading acts ─────────────────────────────────────────────────────function liveBook(engine: Engine, args: Record<string, unknown>): StoredRow {const id = args.book;if (typeof id !== "string" || !id.trim()) refuse(400, "bad_args", "name the book: { book: <id> }");const row = engine.store.get(BOOK, id.trim());if (!row || row.deleted) refuse(404, "no_such_book", `no book with id ${id}`);return row;}/** `start_book { book }`: reading, started today; a finished book started again is a re-read, its finished day cleared. */exportfunction startBook(engine: Engine, args: Record<string, unknown>, today: string, version: number, outcome: Outcome): StoredRow {const row = liveBook(engine, args);if (row.data.status === "reading") refuse(409, "already_reading", "that book is being read already");const patch: Data = { status: "reading", started_on: today };if (row.data.status === "finished") patch.finished_on = null;return engine.update(row, patch, version, outcome);}/** `finish_book { book }`: finished today, one more reading counted. */exportfunction finishBook(engine: Engine, args: Record<string, unknown>, today: string, version: number, outcome: Outcome): StoredRow {const row = liveBook(engine, args);if (row.data.status === "finished") refuse(409, "already_finished", "that book is finished already; start it again to read it again");const count = typeof row.data.read_count === "number" ? row.data.read_count : 0;return engine.update(row, { status: "finished", finished_on: today, read_count: count + 1 }, version, outcome);}// ── find_book ────────────────────────────────────────────────────────────/** What Open Library said of a book, in the table's columns; `cover` is the media key it was kept under. */exportinterfaceFoundBook { title: string; author: string | null; year: string | null; pages: number | null; isbn: string | null; ol_work: string | null; language: string | null; cover: string | null;}exportinterfacePreparedFind { found: FoundBook;/** The book to fill, when the act named one. */ book: string | null;/** NOT_ANSWERING when Open Library did not answer for the cover, asked twice: the details are written and the answer says so. */ coverUnanswered: string | null;}/** Open Library's three-letter MARC codes as the two-letter ones an EPUB says (`dc:language`), for the languages a person most likely reads. */const LANGUAGES: Record<string, string> = { eng: "en", fre: "fr", fra: "fr", ger: "de", deu: "de", spa: "es", ita: "it", por: "pt", rus: "ru", jpn: "ja", chi: "zh", zho: "zh", hin: "hi", tel: "te", tam: "ta", ben: "bn", mar: "mr", kan: "kn", mal: "ml", guj: "gu", pan: "pa", urd: "ur", ara: "ar", dut: "nl", nld: "nl", swe: "sv", nor: "no", dan: "da", fin: "fi", pol: "pl", tur: "tr", gre: "el", ell: "el", heb: "he", kor: "ko", lat: "la",};function digits(isbn: string): string {return isbn.replace(/[^0-9Xx]/g, "").toUpperCase();}/** The line a lookup Open Library did not answer is refused with, asked twice. */exportconst NOT_ANSWERING = "Open Library is not answering; try again later";/** How long the second ask waits after the first went unanswered. */exportconst LOOKUP_WAIT_MS = 1500;/** How a lookup waits before it asks again: a timer, or a test's own. */exporttypeWait = (ms: number) => Promise<void>;exportconst timer: Wait = (ms) => newPromise((resolve) => setTimeout(resolve, ms));/** Not answered: nothing came back, or a server error (Cloudflare's 521 among them). */const unanswered = (res: Response | null): boolean => res === null || res.status >= 500;/** `url` asked once: its answer, or null when nothing came back. */asyncfunction asked(url: string, init: RequestInit, fetcher: Fetcher): Promise<Response | null> {try {returnawait fetcher(url, init); } catch (error) { console.error(`cottondb: ${new URL(url).host} did not answer (${error instanceof Error ? error.message : String(error)})`);returnnull; }}/** The search's first match, or a refusal: nothing found, Open Library asked too often (403 and 429), or not answering even when asked again. */asyncfunction search(query: URLSearchParams, fetcher: Fetcher, wait: Wait): Promise<Record<string, unknown>> { query.set("fields", FIELDS); query.set("limit", "5");const url = `${OPEN_LIBRARY}?${query}`;// The matches, or null when Open Library did not answer: nothing came// back, a server error, or a 200 that is no search answer (an error page,// a body cut short) — never read as nothing found.const read = async (): Promise<Record<string, unknown>[] | null> => {const res = await asked(url, { headers: { "user-agent": USER_AGENT, accept: "application/json" } }, fetcher);if (res && (res.status === 403 || res.status === 429)) refuse(503, "lookup_failed", `Open Library refused the lookup (${res.status}): asked too often; try again later`);if (unanswered(res)) {await res?.body?.cancel(); console.error(`cottondb: find_book: Open Library answered ${res ? res.status : "nothing"}`);returnnull; }if (!res!.ok) refuse(502, "lookup_failed", `Open Library answered ${res!.status}; try again later`);const answer = (await res!.json().catch(() => null)) as { docs?: unknown } | null;return answer && Array.isArray(answer.docs) ? (answer.docs asRecord<string, unknown>[]) : null; };let docs = await read();if (docs === null) {await wait(LOOKUP_WAIT_MS); docs = await read(); }if (docs === null) refuse(503, "lookup_failed", NOT_ANSWERING);const doc = docs.find((d) => typeof d.title === "string" && d.title.trim() !== "");if (!doc) refuse(404, "no_book_found", `Open Library knows no book for “${query.get("q") ?? query.get("isbn")}”`);return doc;}/** * `find_book`'s lookup, before its write (looking up is asynchronous, the * write is not): the first match, its cover kept by cover id. A cover that * could not be fetched is left empty, and the artwork engine asks for it * again (src/artwork.ts). */exportasyncfunction prepareFind(host: Pick<ArtworkHost, "store" | "databaseId" | "keep">, args: Record<string, unknown>, fetcher: Fetcher, wait: Wait = timer): Promise<PreparedFind> {const query = typeof args.query === "string" ? args.query.trim() : "";const isbn = typeof args.isbn === "string" ? digits(args.isbn) : "";const book = typeof args.book === "string" && args.book.trim() ? args.book.trim() : null;if (!!query === !!isbn) refuse(400, "bad_args", "find_book takes a query (the book's name, its author too if you like) or an isbn, not both");if (isbn && isbn.length !== 10 && isbn.length !== 13) refuse(400, "bad_args", `${args.isbn as string} is not an ISBN: ten or thirteen digits`);if (book) {const row = host.store.get(BOOK, book);if (!row || row.deleted) refuse(404, "no_such_book", `no book with id ${book}`); }const doc = await search(new URLSearchParams(isbn ? { isbn } : { q: query }), fetcher, wait);const authors = Array.isArray(doc.author_name) ? (doc.author_name as unknown[]).filter((a): a is string => typeof a === "string") : [];const languages = Array.isArray(doc.language) ? (doc.language as unknown[]).filter((l): l is string => typeof l === "string") : [];const work = typeof doc.key === "string" ? doc.key.replace(/^\/works\//, "") : null;let cover: string | null = null;let coverUnanswered: string | null = null;if (typeof doc.cover_i === "number" && doc.cover_i > 0) {const url = `https://covers.openlibrary.org/b/id/${doc.cover_i}-L.jpg?default=false`;const init = { headers: { "user-agent": USER_AGENT, accept: "image/*" } };let res = await asked(url, init, fetcher);if (unanswered(res)) {await res?.body?.cancel();await wait(LOOKUP_WAIT_MS); res = await asked(url, init, fetcher); }try {if (unanswered(res)) {await res?.body?.cancel(); coverUnanswered = NOT_ANSWERING;thrownewError(`covers.openlibrary.org answered ${res ? res.status : "nothing"}, asked twice`); } cover = await kept(host, res!, url); } catch (error) { console.error(`cottondb: find_book: the cover of ${work ?? "a book"} could not be kept (${error instanceof Error ? error.message : String(error)}); the artwork engine asks again`); } }return { book, coverUnanswered, found: { title: String(doc.title).trim(), author: authors.length ? authors.join(", ") : null, year: typeof doc.first_publish_year === "number" ? String(doc.first_publish_year) : null, pages: typeof doc.number_of_pages_median === "number" && doc.number_of_pages_median > 0 ? doc.number_of_pages_median : null, isbn: isbn || null, ol_work: work, language: languages.length === 1 ? (LANGUAGES[languages[0]!] ?? languages[0]!) : null, cover, }, };}const blank = (v: unknown): boolean => v === undefined || v === null || v === "";/** The found columns a row holds none of. */function gaps(row: StoredRow, found: FoundBook): Data {const patch: Data = {};for (const [key, value] ofObject.entries(found)) if (value !== null && blank(row.data[key])) patch[key] = value;return patch;}/** `find_book`'s write: the named book (or the one holding the same work) filled where empty, else a new Want to read book. */exportfunction applyFind(engine: Engine, prepared: PreparedFind, today: string, version: number, outcome: Outcome): FindAnswer {const { found } = prepared;// A book found by its Open Library work: by the id that work derives (a sealed book's ol_work is not the object's to read), else by the column.const derived = found.ol_work ? derivedId(BOOK, ["open_library", found.ol_work]) : null;const held = prepared.book ? engine.store.get(BOOK, prepared.book) : found.ol_work ? (engine.store.get(BOOK, derived!) ?? engine.store.select(BOOK, [equalSql("ol_work", found.ol_work)], "created_at, id", 1)[0] ?? null) : null;if (prepared.book && (!held || held.deleted)) refuse(404, "no_such_book", `no book with id ${prepared.book}`);if (held) {// A sealed book's words are not the object's to read: its details go as a fill patch, which the phone lays only where the book is empty (src/arrival_seam.ts).const patch = gaps(held, found);const write = () => engine.update(held, { ...patch, ...stampFilled(engine, held.data.filled_from, Object.keys(patch), "open_library") }, version, outcome);if (Object.keys(patch).length) {if (isSealedRow(held.data)) filling(engine, write);else write(); }return said({ book: held.id, made: false, filled: Object.keys(patch) }, prepared); }const data: Data = { status: "want_to_read", source: "lookup", added_on: today };const filled: string[] = [];for (const [key, value] ofObject.entries(found)) {if (value === null) continue; data[key] = value; filled.push(key); }const made = engine.create(BOOK, { ...data, ...stampFilled(engine, null, filled, "open_library") }, version, outcome, 0, derived ? { id: derived } : {}); outcome.made = made;return said({ book: made.id, made: true, filled: Object.keys(data) }, prepared);}/** What `find_book` answers: the book, whether it was made, the columns filled, and the cover's line when Open Library did not answer for it. */exportinterfaceFindAnswer { book: string; made: boolean; filled: string[]; cover_unanswered?: string;}function said(answer: FindAnswer, prepared: PreparedFind): FindAnswer {return prepared.coverUnanswered ? { ...answer, cover_unanswered: prepared.coverUnanswered } : answer;}// ── import_goodreads ─────────────────────────────────────────────────────/** The headers an export must carry to be read as one. */const NEEDED = ["Book Id", "Title", "Author", "Exclusive Shelf"];/** The three shelves every Goodreads library has, each a status rather than a list. */const EXCLUSIVE: Record<string, string> = { "to-read": "want_to_read", "currently-reading": "reading", read: "finished" };/** RFC 4180 rows: quoted fields may hold commas, quotes ("") and line breaks; a CRLF or an LF ends a row; a blank line is no row. */exportfunction csvRows(text: string): string[][] {const rows: string[][] = [];let row: string[] = [];let field = "";let quoted = false;let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;for (; i < text.length; i++) {const ch = text[i]!;if (quoted) {if (ch === '"' && text[i + 1] === '"') { field += '"'; i++; } elseif (ch === '"') quoted = false;else field += ch; } elseif (ch === '"' && field === "") quoted = true;elseif (ch === ",") { row.push(field); field = ""; } elseif (ch === "\n" || ch === "\r") {if (ch === "\r" && text[i + 1] === "\n") i++; row.push(field); field = "";if (row.some((f) => f !== "")) rows.push(row); row = []; } else field += ch; } row.push(field);if (row.some((f) => f !== "")) rows.push(row);return rows;}/** A Goodreads ISBN as written (`="0141439513"`), as its digits; empty when it holds none. */exportfunction isbnOf(cell: string): string {return digits(cell.replace(/^="?/, "").replace(/"$/, ""));}/** `yyyy/mm/dd` as `yyyy-mm-dd`; anything else is no date. */function dayOf(cell: string): string | null {const m = /^(\d{4})\/(\d{2})\/(\d{2})$/.exec(cell.trim());return m ? `${m[1]}-${m[2]}-${m[3]}` : null;}/** A count or a rating, with Goodreads' 0 meaning none. */function numberOf(cell: string): number | null {const n = Number(cell.trim());return cell.trim() !== "" && Number.isFinite(n) && n > 0 ? n : null;}function textOf(cell: string | undefined): string | null {const t = (cell ?? "").trim();return t ? t : null;}/** A review as Goodreads keeps it (HTML with `<br/>`), as plain text. */function reviewOf(cell: string): string | null {return textOf(cell.replace(/<br\s*\/?>/gi, "\n").replace(/<[^>]+>/g, "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'"));}/** One export row as the book's columns, its status and the shelves that are lists. */exportinterfaceGoodreadsBook { goodreads_id: string; data: Data; lists: string[];}/** The export's books, read by header name; a file that is not an export is refused. */exportfunction readExport(text: string): GoodreadsBook[] {const rows = csvRows(text);const header = rows[0]?.map((h) => h.trim()) ?? [];const missing = NEEDED.filter((h) => !header.includes(h));if (missing.length) refuse(400, "not_goodreads", `this is not a Goodreads library export: its first line names no ${missing.join(", ")}`);const at = (name: string): number => header.indexOf(name);return rows.slice(1).flatMap((cells) => {const cell = (name: string): string => (at(name) >= 0 ? (cells[at(name)] ?? "") : "");const id = cell("Book Id").trim();const title = textOf(cell("Title"));if (!id || !title) return [];const exclusive = cell("Exclusive Shelf").trim().toLowerCase();const shelves = cell("Bookshelves") .split(",") .map((s) => s.trim()) .filter((s) => s !== "" && !(s.toLowerCase() in EXCLUSIVE) && s.toLowerCase() !== exclusive);const stopped = exclusive.includes("dnf") || shelves.some((s) => s.toLowerCase().includes("dnf"));const status = stopped ? "stopped" : (EXCLUSIVE[exclusive] ?? "want_to_read");// A custom exclusive shelf that is not a did-not-finish is a list too.const lists = [...(exclusive && !(exclusive in EXCLUSIVE) && !exclusive.includes("dnf") ? [cell("Exclusive Shelf").trim()] : []), ...shelves.filter((s) => !s.toLowerCase().includes("dnf"))];const isbn = isbnOf(cell("ISBN13")) || isbnOf(cell("ISBN"));const year = [cell("Original Publication Year"), cell("Year Published")].map((y) => y.trim()).find((y) => /^-?\d+$/.test(y) && y !== "0") ?? null;const data: Data = { title, author: textOf(cell("Author")), isbn: isbn || null, rating: numberOf(cell("My Rating")), review: reviewOf(cell("My Review")), added_on: dayOf(cell("Date Added")), finished_on: dayOf(cell("Date Read")), read_count: numberOf(cell("Read Count")), pages: numberOf(cell("Number of Pages")), year, status, goodreads_id: id, source: "goodreads", };return [{ goodreads_id: id, data, lists: [...newSet(lists)] }]; });}/** What an import did. */exportinterfaceImported { books: number; made: number; updated: number; lists: number;/** * The book the phone lands on: the first this import made, in the export's * order, else the first it found again; absent for an export of no books. */ first?: string;}/** * How far along a book is; a status moves only up this order on a re-import. * Stopped sits above reading and below finished: a book stopped in Cotton is * never put back to want to read or reading by a file, the file's dnf stops a * book not yet finished, and only finished moves a stopped book on. */const STATUS_RANK: Record<string, number> = { want_to_read: 0, reading: 1, stopped: 2, finished: 3 };/** Columns the owner keeps in Cotton (the reader, Start reading, their own rating and review): a re-import fills them only when empty. */const OWNER_HELD = ["started_on", "finished_on", "position", "progress", "position_at", "rating", "review"];/** * A re-import's patch for a book it made before: Goodreads columns written over * with what the export says (a column it leaves empty kept), the status moved * only forward, and the owner's columns filled only where empty. */function reimportPatch(held: Data, file: Data): Data {const heldRank = STATUS_RANK[String(held.status)] ?? -1;const fileRank = STATUS_RANK[String(file.status)] ?? -1;// A finish the file dates before the row's started_on is an earlier reading, not the one under way.const earlierReading = file.status === "finished" && typeof held.started_on === "string" && typeof file.finished_on === "string" && file.finished_on < held.started_on;const status = fileRank > heldRank && !earlierReading ? file.status : held.status;const patch: Data = {};for (const [key, value] ofObject.entries(file)) {if (value === null || key === "status") continue;if (OWNER_HELD.includes(key) && !empty(held[key])) continue;// The file's finished day belongs only to a book that ends finished.if (key === "finished_on" && status !== "finished") continue;if (JSON.stringify(held[key] ?? null) !== JSON.stringify(value)) patch[key] = value; }if (status !== held.status) patch.status = status;return patch;}/** The columns an import wrote that are the export's facts: all but `source`, which says the row's door. */const fromFile = (data: Data): string[] => Object.keys(data).filter((k) => k !== "source");/** * `import_goodreads`'s write: each book found again by its Goodreads id and * patched by `reimportPatch`, or made from the export as it stands; each list * found by its name on `book`, or made, and the book put on it once. */exportfunction importGoodreads(engine: Engine, args: Record<string, unknown>, version: number, outcome: Outcome): Imported {const file = args.file;if (typeof file !== "string" || !file.trim()) refuse(400, "bad_args", "import_goodreads takes the export's CSV text as file");const books = readExport(file);const answer: Imported = { books: books.length, made: 0, updated: 0, lists: 0 };const groups = newMap<string, string>();const groupOf = (name: string): string => {const known = groups.get(name);if (known) return known;// A shelf is found by its name while lists are open, else by the id its name derives: a sealed list's name is not the object's to read (R1).const derived = derivedId(GROUP, [BOOK, name]);const held = engine.store.get(GROUP, derived) ?? engine.store.select(GROUP, [equalSql("table_id", BOOK), equalSql("name", name)], "created_at, id", 1)[0];const id = held ? held.id : engine.create(GROUP, { table_id: BOOK, name }, version, outcome, 0, { id: derived }).id;if (!held) answer.lists++; groups.set(name, id);return id; };let foundFirst: string | undefined;for (const book of books) {// Found again by the id its Goodreads id derives (a sealed book's goodreads_id is not the object's to read), else by the column.const derived = derivedId(BOOK, ["goodreads", String(book.goodreads_id)]);const held = engine.store.get(BOOK, derived) ?? engine.store.select(BOOK, [equalSql("goodreads_id", book.goodreads_id)], "created_at, id", 1)[0];let row: StoredRow;if (held) {const patch = reimportPatch(held.data, book.data);const stamp = stampFilled(engine, held.data.filled_from, fromFile(patch), "goodreads");if (isSealedRow(held.data)) {// The export's facts go as they are; what the owner holds (their rating, review, dates) only where the book is empty.const owner = Object.fromEntries(Object.entries(patch).filter(([k]) => OWNER_HELD.includes(k)));const facts = Object.fromEntries(Object.entries(patch).filter(([k]) => !OWNER_HELD.includes(k))); row = held;if (Object.keys(facts).length) row = engine.update(row, { ...facts, ...stamp }, version, outcome);if (Object.keys(owner).length) row = filling(engine, () => engine.update(row, owner, version, outcome)); } else row = Object.keys(patch).length ? engine.update(held, { ...patch, ...stamp }, version, outcome) : held;if (Object.keys(patch).length) answer.updated++; } else {const data: Data = {};for (const [key, value] ofObject.entries(book.data)) if (value !== null) data[key] = value; row = engine.create(BOOK, { ...data, ...stampFilled(engine, null, fromFile(data), "goodreads") }, version, outcome, 0, { id: derived });if (!answer.made) answer.first = row.id; answer.made++; } foundFirst ??= row.id;for (const name of book.lists) {const group = groupOf(name);if (engine.store.select(MEMBER, [equalSql("group", group), equalSql("record_id", row.id)], "id", 1).length) continue;const place = engine.store.count(MEMBER, [equalSql("group", group)]) + 1; engine.create(MEMBER, { group, record_id: row.id, place }, version, outcome); } } answer.first ??= foundFirst;return answer;}