@murumets-ee/yhikas-sync 0.40.0 → 0.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +518 -59
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/jobs-CYy8AaKK.mjs +2 -0
- package/dist/jobs-CYy8AaKK.mjs.map +1 -0
- package/dist/plugin.d.mts.map +1 -1
- package/dist/plugin.mjs +1 -1
- package/dist/plugin.mjs.map +1 -1
- package/dist/sync-state-table-CM6eL5W9.mjs +2 -0
- package/dist/sync-state-table-CM6eL5W9.mjs.map +1 -0
- package/dist/watchdog-dfFi-7re.mjs +2 -0
- package/dist/watchdog-dfFi-7re.mjs.map +1 -0
- package/package.json +7 -7
- package/dist/jobs-D2perJoW.mjs +0 -2
- package/dist/jobs-D2perJoW.mjs.map +0 -1
- package/dist/sync-state-table-CYl_DVX9.mjs +0 -2
- package/dist/sync-state-table-CYl_DVX9.mjs.map +0 -1
- package/dist/watchdog-CNsiJMUR.mjs +0 -2
- package/dist/watchdog-CNsiJMUR.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"watchdog-CNsiJMUR.mjs","names":["#baseUrl","#apiKey","#timeoutMs","#fetch","#get"],"sources":["../src/apply.ts","../src/upstream/errors.ts","../src/diff.ts","../src/entity-client.ts","../src/projection.ts","../src/run-sync.ts","../src/sync-state.ts","../src/upstream/wire.ts","../src/upstream/client.ts","../src/watchdog.ts"],"sourcesContent":["/**\n * Applying a diff plan through `AdminClient`.\n *\n * Writes go through the normal entity path — hooks, validation, audit logging\n * — so the sync's own writes are attributable, which is worth having precisely\n * because the UPSTREAM writes are not (F006: `addRoomType`/`updateRoomType`/\n * `deleteRoomType` skip `requireAdmin()`, with no audit log and no timestamp\n * to reconstruct from).\n *\n * ## Bounded, and bounded at one\n *\n * Rows are written sequentially. CLAUDE.md's fan-out rule wants a concurrency\n * bound and a total cap, and \"it's only N today\" is explicitly not a defence\n * — so rather than a semaphore the shape is simply serial, which is the\n * tightest bound available. At ~25 rows every six hours that costs nothing,\n * keeps the run from adding a burst to a connection pool shared with the whole\n * app, and makes the audit log read in a deterministic order. The total cap\n * lives in the differ, which REFUSES an oversized snapshot rather than\n * truncating it.\n *\n * ## Partial application is tolerated, silent partial application is not\n *\n * A per-row failure is caught, logged and counted, and the remaining rows are\n * still applied — one malformed document should not hold back 24 correct price\n * updates. But the run then THROWS at the end, so `lastSuccessAt` is not\n * advanced and the staleness watchdog stays armed. Retries re-run the whole\n * handler from scratch (the queue has no checkpointing primitive), which is\n * safe here because every write is an upsert against a business key.\n */\n\nimport type { SyncResource } from './constants.js'\nimport type { DiffPlan, LocalRow } from './diff.js'\nimport type { ProjectedRow } from './projection.js'\n\n/**\n * The `AdminClient` surface the sync uses, structurally.\n *\n * Declared rather than imported so the apply logic is unit-testable with a\n * fake — CI runs unit tests only, with no database, so a design that could\n * only be exercised by an integration test would in practice be exercised by\n * nothing.\n */\nexport interface SyncEntityClient {\n findMany(options: { limit: number }): Promise<Record<string, unknown>[]>\n create(data: Record<string, unknown>): Promise<Record<string, unknown>>\n update(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>\n updateForLocale(\n id: string,\n data: Record<string, unknown>,\n locale: string,\n ): Promise<Record<string, unknown>>\n deleteTranslation(id: string, locale: string): Promise<void>\n}\n\nexport interface SyncLogger {\n info(obj: Record<string, unknown>, msg: string): void\n warn(obj: Record<string, unknown>, msg: string): void\n error(obj: Record<string, unknown>, msg: string): void\n}\n\nexport interface ApplyCounts {\n created: number\n updated: number\n retired: number\n unchanged: number\n failed: number\n}\n\n/** Thrown when at least one row failed; carries the counts that were achieved. */\nexport class YhikasApplyPartialError extends Error {\n readonly counts: ApplyCounts\n constructor(resource: SyncResource, counts: ApplyCounts) {\n super(\n `${counts.failed} of ${counts.created + counts.updated + counts.retired + counts.failed} ` +\n `${resource} writes failed. The run is NOT recorded as successful, so the staleness ` +\n `watchdog stays armed and the next run retries from scratch.`,\n )\n this.name = 'YhikasApplyPartialError'\n this.counts = counts\n }\n}\n\n/**\n * Read every local row of one synced entity, reduced to what the differ needs.\n *\n * `limit` is the same ceiling the differ refuses above, so a local set that\n * has somehow outgrown it is truncated HERE — which would present the missing\n * tail as absent-locally and re-create it, hitting the unique index rather\n * than silently duplicating. Not silent, but not pretty either; the ceiling is\n * three orders of magnitude above the real row count.\n */\n/**\n * Normalize a timestamp that may arrive as a `Date` or as an ISO string.\n *\n * Coercing an unrecognised shape to `null` is not neutral here: `commitRow`\n * back-fills `publishedAt` when it is absent, so a string that read as `null`\n * would silently replace the original first-publish date on every single\n * update, turning the column into \"last touched by the sync\".\n */\nfunction toDate(value: unknown): Date | null {\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value\n if (typeof value === 'string') {\n const parsed = new Date(value)\n return Number.isNaN(parsed.getTime()) ? null : parsed\n }\n return null\n}\n\nexport async function readLocalRows(\n client: SyncEntityClient,\n keyField: string,\n limit: number,\n): Promise<LocalRow[]> {\n const rows = await client.findMany({ limit })\n return rows.map((row) => ({\n id: String(row.id),\n key: String(row[keyField]),\n status: String(row.status),\n sourceHash: typeof row.sourceHash === 'string' ? row.sourceHash : null,\n publishedAt: toDate(row.publishedAt),\n }))\n}\n\nexport interface ApplyPlanInput {\n readonly resource: SyncResource\n readonly plan: DiffPlan<ProjectedRow>\n readonly client: SyncEntityClient\n /** The locale that is NOT on the base row — the one whose publish state is toggled. */\n readonly secondaryLocale: string\n readonly logger: SyncLogger\n}\n\nexport async function applyPlan(input: ApplyPlanInput): Promise<ApplyCounts> {\n const { resource, plan, client, secondaryLocale, logger } = input\n const counts: ApplyCounts = {\n created: 0,\n updated: 0,\n retired: 0,\n unchanged: plan.unchanged.length,\n failed: 0,\n }\n\n for (const row of plan.create) {\n try {\n // Created as a DRAFT, deliberately. Publishing before the secondary\n // locale is written would expose a window — and, if that write then\n // failed, a permanent state — in which the English URL is live and\n // falls back to the Estonian text, because the public read predicate is\n // `COALESCE(locale_status.status, main.status)` and an absent locale row\n // inherits the base row's `published`. Invisible beats wrong.\n const created = await client.create({ ...row.base, status: 'draft' })\n await writeSecondaryLocale(client, String(created.id), row, secondaryLocale)\n await commitRow(client, String(created.id), row.hash, null)\n counts.created += 1\n } catch (err) {\n counts.failed += 1\n logger.error({ err, resource, key: row.key }, 'yhikas-sync: failed to create a synced row')\n }\n }\n\n for (const { local, row } of plan.update) {\n try {\n // NOTE the absence of `sourceHash` here — see `commitRow`.\n await client.update(local.id, { ...row.base })\n await writeSecondaryLocale(client, local.id, row, secondaryLocale)\n await commitRow(client, local.id, row.hash, local.publishedAt)\n counts.updated += 1\n } catch (err) {\n counts.failed += 1\n logger.error({ err, resource, key: row.key }, 'yhikas-sync: failed to update a synced row')\n }\n }\n\n for (const local of plan.retire) {\n try {\n // Unpublished, NEVER deleted (D016). The row and its audit trail stay,\n // and a wrongly-retired row heals automatically on the next successful\n // run — the differ treats a drafted row with a matching hash as an\n // update precisely so that re-publishing happens without operator action.\n // The LOCALE goes first, for the same reason `writeSecondaryLocale`\n // orders its writes the way it does — and here the cost of getting it\n // wrong is permanent rather than transient. Drafting the base row first\n // and then failing to draft the locale leaves the locale `published`\n // with the base row already `draft`; `planDiff` only ever selects\n // retirement candidates whose `status === 'published'`, so that row\n // never enters `plan.retire` again and the secondary locale serves\n // retired content indefinitely. This order fails safe: an error after\n // the locale unpublish leaves the base row published, so the row is\n // still a candidate on the next run.\n await client.updateForLocale(local.id, { status: 'draft' }, secondaryLocale)\n await client.update(local.id, { status: 'draft' })\n counts.retired += 1\n logger.warn(\n { resource, key: local.key },\n // Not \"no longer present upstream\": a row also lands here when it IS\n // present but was skipped as unpublishable (an empty default-locale\n // name). Naming only the first cause would send an operator looking\n // for a deletion that never happened.\n 'yhikas-sync: retiring a row that upstream no longer offers as publishable content',\n )\n } catch (err) {\n counts.failed += 1\n logger.error({ err, resource, key: local.key }, 'yhikas-sync: failed to retire a synced row')\n }\n }\n\n if (counts.failed > 0) throw new YhikasApplyPartialError(resource, counts)\n return counts\n}\n\n/**\n * Publish the row and stamp its `sourceHash` — the LAST write for a row, and\n * the only one that records \"this row now matches upstream\".\n *\n * Committing the hash alongside the base fields would be a durable lie the\n * moment any later write for the row failed: the hash covers the whole\n * projected payload including the secondary locale, so the differ would\n * classify the row `unchanged` on every subsequent run, the run would report\n * success, and the incomplete row would never be retried. Writing it last\n * makes a partial failure self-healing — the stored hash still describes the\n * previous state, so the next run sees a difference and redoes the row.\n *\n * `publishedAt` is preserved when the row already had one. `publishable()`\n * back-fills it whenever a payload sets `status: 'published'` without it,\n * which would otherwise turn \"first published\" into \"last touched by the\n * sync\" — a value that moves every time a price changes.\n */\nasync function commitRow(\n client: SyncEntityClient,\n id: string,\n hash: string,\n publishedAt: Date | null,\n): Promise<void> {\n await client.update(id, {\n status: 'published',\n publishedAt: publishedAt ?? new Date(),\n sourceHash: hash,\n })\n}\n\n/**\n * Write — or suppress — the non-default locale.\n *\n * When the upstream text is present, its translation row is written and the\n * locale is published in one call: `updateForLocale` splits the payload,\n * routing `status` to `<entity>_locale_status` and the translatable fields to\n * `<entity>_translations`.\n *\n * When it is absent, the locale is set to `draft` FIRST and only then is the\n * previous translation deleted. The order is load-bearing and was originally\n * the other way round: `deleteTranslation` does not touch\n * `<entity>_locale_status`, so deleting first and then failing to unpublish\n * leaves a locale marked `published` with no translation row — and the merged\n * read falls back to the base row, i.e. the English URL serves Estonian text,\n * live. Unpublishing first degrades to stale-but-hidden instead.\n *\n * Deleting at all still matters: leaving stale English text in the\n * translations table, merely unpublished, keeps a copy that any future read\n * path forgetting the publish filter could serve. The unpublish is the\n * control; the delete removes the thing the control is protecting — so the\n * control goes on first.\n */\nasync function writeSecondaryLocale(\n client: SyncEntityClient,\n id: string,\n row: ProjectedRow,\n secondaryLocale: string,\n): Promise<void> {\n if (row.secondary) {\n // Two calls, not one, and in this order for the same reason the branch\n // below is ordered the way it is. `updateForLocale` writes the locale\n // STATUS before the translation when handed both in one payload, so a\n // combined call that failed halfway would mark the locale published with\n // no translation row behind it — and the merged read then falls back to\n // the base row, i.e. the English URL serving Estonian text, live.\n //\n // Writing the translation first and the status second means a failure\n // between them leaves the locale unpublished with correct content waiting\n // — invisible, and healed by the next run.\n await client.updateForLocale(id, { ...row.secondary }, secondaryLocale)\n await client.updateForLocale(id, { status: 'published' }, secondaryLocale)\n return\n }\n await client.updateForLocale(id, { status: 'draft' }, secondaryLocale)\n await client.deleteTranslation(id, secondaryLocale)\n}\n","/**\n * Every way a snapshot fetch can fail to be authoritative.\n *\n * The distinction this file exists to preserve: a refusal, a timeout and a\n * malformed body are all \"we do not know what is upstream\", and none of them\n * is \"upstream is empty\". Collapsing them is how a partial response becomes a\n * wiped price sheet, so they are typed and they all abort the run.\n */\n\nimport type { SyncResource } from '../constants.js'\n\nexport type UpstreamFailureKind =\n /** DNS failure, connection refused, TLS error — the request never completed. */\n | 'network'\n /** The per-request deadline elapsed. The queue has no per-job timeout (R012 §3). */\n | 'timeout'\n /** A completed response the sync will not act on: 401, 429, 5xx, or any non-2xx. */\n | 'http'\n /** A 2xx whose body failed the wire schema — including `success: false`. */\n | 'shape'\n\nexport class YhikasUpstreamError extends Error {\n readonly resource: SyncResource\n readonly kind: UpstreamFailureKind\n readonly status: number | undefined\n\n constructor(\n resource: SyncResource,\n kind: UpstreamFailureKind,\n message: string,\n options?: { status?: number; cause?: unknown },\n ) {\n super(message, options?.cause === undefined ? undefined : { cause: options.cause })\n this.name = 'YhikasUpstreamError'\n this.resource = resource\n this.kind = kind\n this.status = options?.status\n }\n}\n\n/**\n * Thrown when a snapshot IS authoritative but applying it would be reckless —\n * the D016 guards. Separate from {@link YhikasUpstreamError} because the\n * remedies differ: an upstream failure usually resolves itself on the next\n * run, whereas this one wants a human to look at why the source shrank.\n */\nexport class YhikasSyncRefusedError extends Error {\n readonly resource: SyncResource\n readonly reason: 'empty-snapshot' | 'retire-fraction' | 'oversized-snapshot' | 'duplicate-key'\n\n constructor(resource: SyncResource, reason: YhikasSyncRefusedError['reason'], message: string) {\n super(message)\n this.name = 'YhikasSyncRefusedError'\n this.resource = resource\n this.reason = reason\n }\n}\n","/**\n * The full-snapshot differ — a pure function, so every guard in it is testable\n * without a database, an HTTP server or a queue.\n *\n * Full-snapshot rather than incremental is FORCED, not chosen: `room_type`\n * carries no timestamp of any kind, and `legal_document`'s `updated_at` is not\n * in the API response. There is no cursor, no high-water mark and no change\n * feed, so the only available shape is fetch-everything-and-compare. At ~25\n * room types and a handful of documents that is trivially cheap.\n *\n * Identity is the business key — `room_type.code`, `legal_document.type` —\n * never the serial `id`, which is an implementation detail of the other system\n * and would make this system's content depend on the other's insert order.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { SyncResource } from './constants.js'\nimport { YhikasSyncRefusedError } from './upstream/errors.js'\n\n/** One local row, reduced to what the diff needs. */\nexport interface LocalRow {\n readonly id: string\n /** The business key this row was synced under. */\n readonly key: string\n readonly status: string\n /**\n * `null` on a row whose last sync did not complete — the hash is written\n * LAST, after every other write for the row succeeded, so a null (or stale)\n * hash is exactly the signal that the row needs redoing.\n */\n readonly sourceHash: string | null\n /** Preserved across updates so it keeps meaning \"first published\". */\n readonly publishedAt: Date | null\n}\n\nexport interface DiffPlan<T> {\n /** Upstream rows with no local counterpart. */\n readonly create: readonly T[]\n /** Local rows whose hash differs, OR whose status drifted from `published`. */\n readonly update: readonly { readonly local: LocalRow; readonly row: T }[]\n /** Local rows already identical and already published — no write at all. */\n readonly unchanged: readonly LocalRow[]\n /** Published locally, absent upstream. Unpublished, never deleted (D016). */\n readonly retire: readonly LocalRow[]\n}\n\nexport interface SanityFloor {\n /** Refuse a snapshot larger than this rather than truncating it. */\n readonly maxRows: number\n /** Refuse a run retiring more than this fraction of published rows. */\n readonly maxRetireFraction: number\n /** The fraction rule applies only once at least this many rows are published. */\n readonly minRowsForFraction: number\n}\n\nexport interface PlanDiffInput<T> {\n readonly resource: SyncResource\n readonly upstream: readonly T[]\n readonly local: readonly LocalRow[]\n readonly keyOf: (row: T) => string\n readonly hashOf: (row: T) => string\n readonly floor: SanityFloor\n}\n\n/**\n * Stable content hash of an upstream row.\n *\n * Keys are sorted so the hash does not depend on JSON property order, which no\n * part of the HTTP stack guarantees. `undefined` and `null` are distinguished\n * because a null price is meaningful data here, not an absence.\n */\nexport function stableHash(value: unknown): string {\n return createHash('sha256').update(canonicalize(value)).digest('hex')\n}\n\nfunction canonicalize(value: unknown): string {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`)\n return `{${entries.join(',')}}`\n }\n return JSON.stringify(value)\n}\n\n/**\n * Compare an authoritative upstream snapshot against local state.\n *\n * **The caller must not invoke this with a snapshot that did not fully\n * succeed.** That guard lives one level up, in the client: a non-2xx, a\n * timeout or a body failing the wire schema throws before the differ is ever\n * reached, so a partial response can never present as an absence here. This\n * function's own guards are for a snapshot that IS authoritative but whose\n * shape makes acting on it reckless.\n *\n * @throws {YhikasSyncRefusedError} for any of the D016 refusals. Every one of\n * them aborts before a single write, so a refused run leaves local content\n * exactly as it was — which is the first of PR 05's three obligatory\n * negative tests.\n */\nexport function planDiff<T>(input: PlanDiffInput<T>): DiffPlan<T> {\n const { resource, upstream, local, keyOf, hashOf, floor } = input\n\n // An oversized snapshot is REFUSED, not truncated. Capping at N and\n // processing the first N would turn the dropped tail into apparent absences\n // and therefore into mass retirement — the bound CLAUDE.md requires, applied\n // the one way that is not itself a bug.\n if (upstream.length > floor.maxRows) {\n throw new YhikasSyncRefusedError(\n resource,\n 'oversized-snapshot',\n `yhikas-admin returned ${upstream.length} ${resource} rows, above the ${floor.maxRows} ceiling. ` +\n `Refusing the run rather than processing a prefix — a truncated snapshot would read as ` +\n `${upstream.length - floor.maxRows} deletions.`,\n )\n }\n\n const upstreamByKey = new Map<string, T>()\n for (const row of upstream) {\n const key = keyOf(row)\n if (upstreamByKey.has(key)) {\n throw new YhikasSyncRefusedError(\n resource,\n 'duplicate-key',\n `yhikas-admin returned two ${resource} rows with the same business key '${key}'. ` +\n `That key is unique upstream, so the response is not a faithful snapshot.`,\n )\n }\n upstreamByKey.set(key, row)\n }\n\n const localByKey = new Map<string, LocalRow>()\n for (const row of local) {\n if (localByKey.has(row.key)) {\n // A unique index makes this unreachable; if it happens the local state is\n // corrupt and picking one arbitrarily would quietly entrench the damage.\n throw new YhikasSyncRefusedError(\n resource,\n 'duplicate-key',\n `Local ${resource} content holds two rows keyed '${row.key}'. Refusing to guess which is ` +\n `authoritative.`,\n )\n }\n localByKey.set(row.key, row)\n }\n\n const create: T[] = []\n const update: { local: LocalRow; row: T }[] = []\n const unchanged: LocalRow[] = []\n\n for (const [key, row] of upstreamByKey) {\n const existing = localByKey.get(key)\n if (!existing) {\n create.push(row)\n continue\n }\n // Re-publishing a row that drifted to draft is an update even when the\n // content is byte-identical: that is how a wrongly-retired row heals on the\n // next successful run, with no operator action.\n if (existing.sourceHash === hashOf(row) && existing.status === 'published') {\n unchanged.push(existing)\n } else {\n update.push({ local: existing, row })\n }\n }\n\n const retire = local.filter((row) => row.status === 'published' && !upstreamByKey.has(row.key))\n\n assertRetirementIsPlausible(resource, upstream.length, local, retire, floor)\n\n return { create, update, unchanged, retire }\n}\n\n/**\n * The two refusal triggers of D016. They are independent because neither can\n * see the other's case:\n *\n * - The fraction rule is blind at small N — two published rows against an\n * empty snapshot is 100% retirement but never reaches `minRowsForFraction`,\n * and a freshly seeded install lives at exactly that size.\n * - The empty-snapshot rule is blind to a HALF-truncated response, which is\n * the shape a partial upstream failure actually produces.\n */\nfunction assertRetirementIsPlausible(\n resource: SyncResource,\n upstreamCount: number,\n local: readonly LocalRow[],\n retire: readonly LocalRow[],\n floor: SanityFloor,\n): void {\n if (retire.length === 0) return\n\n if (upstreamCount === 0) {\n throw new YhikasSyncRefusedError(\n resource,\n 'empty-snapshot',\n `yhikas-admin returned zero ${resource} rows while ${retire.length} are published locally. ` +\n `Refusing to retire content on the strength of an empty snapshot — that is how a partial ` +\n `upstream response becomes a wiped price sheet.`,\n )\n }\n\n const publishedCount = local.filter((row) => row.status === 'published').length\n if (publishedCount < floor.minRowsForFraction) return\n\n const fraction = retire.length / publishedCount\n if (fraction > floor.maxRetireFraction) {\n throw new YhikasSyncRefusedError(\n resource,\n 'retire-fraction',\n `This run would retire ${retire.length} of ${publishedCount} published ${resource} rows ` +\n `(${Math.round(fraction * 100)}%), above the ${Math.round(floor.maxRetireFraction * 100)}% floor. ` +\n `At this change rate a run proposing to retire most of the set is far likelier to be a bug ` +\n `than a business event.`,\n )\n }\n}\n","/**\n * Adapting a framework `AdminClient` to the structural {@link SyncEntityClient}\n * the sync logic is written against.\n *\n * Its own module, importing nothing at runtime (`import type` only), for one\n * reason: this is the seam where the sync meets the framework, and it is where\n * the worst defect in this package's history lived — `updateForLocale` was\n * called without `options.defaultLocale`, so every secondary-locale write threw\n * while the base write succeeded. The run failed once, the next run saw a\n * matching hash and reported success, and the English site served Estonian\n * text indefinitely. No test could see it because the seam sat inside a module\n * that pulls in `@murumets-ee/core`.\n *\n * Keeping it here makes the seam directly unit-testable with a plain object,\n * with no database and no app.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport type { SyncEntityClient } from './apply.js'\n\n/** The `AdminClient` methods the adapter forwards, structurally. */\nexport type AdminClientLike = ReturnType<ToolkitApp['getClient']>\n\n/**\n * @param defaultLocale The app's REAL default locale — resolved from\n * `@murumets-ee/content`, never configured. It is passed explicitly on every\n * `updateForLocale` call and is not optional, because\n * `elevateRequestContext` deliberately strips `locale`/`defaultLocale` from\n * the context it builds, and `updateForLocale` THROWS when it can resolve\n * the default locale from neither the options nor the context.\n */\nexport function toSyncEntityClient(\n client: AdminClientLike,\n defaultLocale: string,\n): SyncEntityClient {\n if (defaultLocale.trim().length === 0) {\n // `updateForLocale` resolves `options?.defaultLocale ?? context…`, and `??`\n // treats `''` — and `' '` — as present, so either sails past the throw\n // this module exists to avoid and reaches the write as a locale nobody\n // serves. Trimmed, so whitespace is not a way around the guard.\n throw new TypeError('yhikas-sync: defaultLocale must be a non-empty locale code')\n }\n return {\n findMany: (options) => client.findMany(options) as Promise<Record<string, unknown>[]>,\n // The payload casts are the established in-repo idiom at this exact seam —\n // `packages/blocks/src/server/routes/op-commit.ts` writes\n // `client.updateForLocale(id, data as never, locale, { tx })` for the same\n // reason: `InferUpdateInput<F>` is keyed on one entity's field map, which a\n // caller holding a plain record cannot be proven to satisfy. Threading the\n // entity's field generics through every sync module instead would make the\n // logic untestable without a live client.\n create: (data) => client.create(data as never) as Promise<Record<string, unknown>>,\n update: (id, data) => client.update(id, data as never) as Promise<Record<string, unknown>>,\n updateForLocale: (id, data, locale) =>\n client.updateForLocale(id, data as never, locale, { defaultLocale }) as Promise<\n Record<string, unknown>\n >,\n deleteTranslation: (id, locale) => client.deleteTranslation(id, locale),\n }\n}\n","/**\n * Upstream wire row → local entity payload. Pure, so every semantic decision\n * in here is testable without a database.\n *\n * Three things happen at this boundary and nowhere else:\n *\n * 1. **HTML is sanitized**, via an injected sanitizer. Injected rather than\n * imported so this module stays free of `@murumets-ee/blocks` — whose root\n * export evaluates React's `createContext` at module scope — and so a test\n * can assert that the sanitizer was actually applied rather than trusting\n * that it was.\n * 2. **Semantics the source does not carry are stamped on**: currency and VAT\n * treatment (see `constants.ts` for why the period is not one of them).\n * 3. **An empty locale is decided.** D015: no empty string is ever written as\n * a translation value, and a row whose DEFAULT-locale text is empty is\n * skipped entirely rather than published with a blank title.\n *\n * The hash is computed over the PROJECTED payload, not the raw upstream row.\n * That is deliberate: it means a change in our own sanitizer's allowlist, or\n * in a declared constant, also produces a different hash and therefore a\n * rewrite — so stored content cannot silently diverge from what today's code\n * would produce.\n */\n\nimport { DECLARED_CURRENCY, DECLARED_VAT_TREATMENT, EN_LOCALE, ET_LOCALE } from './constants.js'\nimport { stableHash } from './diff.js'\nimport type { LegalDocumentRow, MultilingualText, RoomTypeRow } from './upstream/wire.js'\n\n/** Injected at the seam; see the module docblock for why it is not imported. */\nexport type HtmlSanitizer = (html: string) => string\n\nexport interface ProjectionOptions {\n /** The locale whose values live on the base entity row. `et` or `en`. */\n readonly defaultLocale: string\n}\n\nexport interface ProjectedRow {\n /** The business key — `room_type.code` or `legal_document.type`. */\n readonly key: string\n /** Base-row fields, including the default locale's values for translatable fields. */\n readonly base: Record<string, unknown>\n /**\n * Translatable values for the non-default locale, or `null` when that\n * locale's text is empty upstream. `null` means \"unpublish that locale\",\n * never \"write an empty string\".\n */\n readonly secondary: Record<string, unknown> | null\n readonly hash: string\n}\n\nexport interface SkippedRow {\n readonly key: string\n readonly reason: string\n}\n\nexport interface ProjectionResult {\n readonly projected: readonly ProjectedRow[]\n readonly skipped: readonly SkippedRow[]\n}\n\n/** The only locales this projection can express — upstream carries exactly these two. */\nexport const SUPPORTED_LOCALES: readonly string[] = [ET_LOCALE, EN_LOCALE]\n\n/**\n * Refuse a locale this projection cannot express.\n *\n * Both helpers below are implicit-else: `pickLocale` returns `text.en` for\n * every locale that is not `et`, and `secondaryLocaleOf` returns `et` for every\n * locale that is not `et`. So a site reporting `fi` as its default would get\n * the ENGLISH text on the base row under the `fi` locale, Estonian as the\n * secondary, and per-locale publish status wrong for both — silently, with\n * every write succeeding. That is the same publish-the-wrong-language failure\n * the entity docblocks call worse than an absent document.\n *\n * `jobs.ts` already screens the value it reads from the app, but this module is\n * a public export and its functions can be called directly. The check belongs\n * where the assumption lives.\n */\nexport function assertSupportedLocale(locale: string): void {\n if (!SUPPORTED_LOCALES.includes(locale)) {\n throw new TypeError(\n `yhikas-sync: unsupported locale '${locale}' — upstream carries only '${ET_LOCALE}' and ` +\n `'${EN_LOCALE}', and projecting one language's text under another locale would publish ` +\n `the wrong language while every write succeeded.`,\n )\n }\n}\n\n/** The locale that is NOT the base row's. */\nexport function secondaryLocaleOf(defaultLocale: string): string {\n assertSupportedLocale(defaultLocale)\n return defaultLocale === ET_LOCALE ? EN_LOCALE : ET_LOCALE\n}\n\nfunction pickLocale(text: MultilingualText, locale: string): string {\n return locale === ET_LOCALE ? text.et : text.en\n}\n\n/**\n * Non-empty after trimming.\n *\n * Trimming matters: both upstream columns are `notNull`, but nothing validates\n * that either string is non-empty — the form has no schema and no required\n * check — so `\"\"` and `\" \"` are both expected states of a half-filled row,\n * and only one of them looks empty.\n */\nfunction present(value: string): boolean {\n return value.trim().length > 0\n}\n\n/**\n * Characters that make a slug unusable — or unsafe — as an anchor fragment.\n *\n * A DENY-list rather than an allow-list, deliberately, and this is the one\n * place in the package where that is the right way round. Upstream derives the\n * slug from an unvalidated free-text field, so an Estonian dormitory produces\n * Estonian slugs (`üldtingimused`); a character-class allow-list would reject\n * legitimate content and — since the slug is not the identity — buy nothing for\n * it. What actually needs excluding is the small set that turns a fragment into\n * a scheme, a path, or markup.\n */\nconst UNSAFE_SLUG_CHARS = /[\\s:/\\\\<>\"'`?#&%]/\n\n/**\n * The `maxLength` both entities declare for their key and slug columns.\n *\n * Checked here rather than left to the write: an overlong value that reaches\n * `client.create` fails at the database, `applyPlan` counts the row failed, and\n * the run throws — so one overlong free-text value upstream would keep the\n * whole resource failing every six hours with the watchdog armed. Skipping the\n * row keeps the blast radius at one document, matching the policy already\n * stated for an unsafe slug.\n */\nconst MAX_COLUMN_LENGTH = 190\n\nfunction isSafeAnchorSlug(slug: string): boolean {\n // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are exactly what is being excluded from a URL fragment\n return !UNSAFE_SLUG_CHARS.test(slug) && !/[\\u0000-\\u001f\\u007f]/.test(slug)\n}\n\nexport function projectRoomTypes(\n rows: readonly RoomTypeRow[],\n options: ProjectionOptions,\n): ProjectionResult {\n assertSupportedLocale(options.defaultLocale)\n const secondaryLocale = secondaryLocaleOf(options.defaultLocale)\n const projected: ProjectedRow[] = []\n const skipped: SkippedRow[] = []\n\n for (const row of rows) {\n if (row.code.length > MAX_COLUMN_LENGTH) {\n skipped.push({\n key: row.code.slice(0, 80),\n reason: `upstream code exceeds the ${MAX_COLUMN_LENGTH}-character column`,\n })\n continue\n }\n\n const primaryName = pickLocale(row.name, options.defaultLocale)\n if (!present(primaryName)) {\n skipped.push({\n key: row.code,\n reason:\n `no '${options.defaultLocale}' name upstream — a room type with no name in the ` +\n `site's primary language has nothing publishable to render`,\n })\n continue\n }\n\n const secondaryName = pickLocale(row.name, secondaryLocale)\n const base: Record<string, unknown> = {\n code: row.code,\n name: primaryName,\n // Decimals stay STRINGS end to end — see the entity docblock.\n totalArea: row.totalArea,\n livingArea: row.livingArea,\n commonArea: row.commonArea,\n capacity: row.capacity,\n placesOccupied: row.placesOccupied,\n monthlyRent: row.monthlyRent,\n discountedMonthlyRent: row.discountedRent,\n dailyRent: row.dailyRent,\n currency: DECLARED_CURRENCY,\n vatTreatment: DECLARED_VAT_TREATMENT,\n hasEnglish: present(row.name.en),\n }\n const secondary = present(secondaryName) ? { name: secondaryName } : null\n\n projected.push({ key: row.code, base, secondary, hash: hashOf(base, secondary) })\n }\n\n return { projected, skipped }\n}\n\nexport function projectLegalDocuments(\n rows: readonly LegalDocumentRow[],\n options: ProjectionOptions,\n sanitize: HtmlSanitizer,\n): ProjectionResult {\n assertSupportedLocale(options.defaultLocale)\n const secondaryLocale = secondaryLocaleOf(options.defaultLocale)\n const projected: ProjectedRow[] = []\n const skipped: SkippedRow[] = []\n\n for (const row of rows) {\n const primaryTitle = pickLocale(row.title, options.defaultLocale)\n // Sanitize BEFORE the emptiness test: markup that reduces to nothing under\n // the allowlist (a lone `<script>`, say) is empty content, and publishing a\n // legal document whose body sanitizes away would be worse than omitting it.\n const primaryBody = sanitize(pickLocale(htmlOf(row), options.defaultLocale))\n\n if (!present(primaryTitle) || !present(primaryBody)) {\n skipped.push({\n key: row.type,\n reason: `no publishable '${options.defaultLocale}' title or body upstream`,\n })\n continue\n }\n\n if (row.type.length > MAX_COLUMN_LENGTH || row.slug.length > MAX_COLUMN_LENGTH) {\n skipped.push({\n key: row.type.slice(0, 80),\n reason:\n `upstream type or slug exceeds the ${MAX_COLUMN_LENGTH}-character column — refusing ` +\n `this row rather than letting the write fail and hold the whole resource in failure`,\n })\n continue\n }\n\n if (!isSafeAnchorSlug(row.slug)) {\n skipped.push({\n key: row.type,\n reason:\n `upstream slug ${JSON.stringify(row.slug)} is not usable as an anchor fragment — it ` +\n `carries a scheme, a path separator, whitespace or markup. Refusing this row rather ` +\n `than the whole response: upstream derives the slug from an unvalidated free-text ` +\n `field, so one bad value must not take the resource offline`,\n })\n continue\n }\n\n const secondaryTitle = pickLocale(row.title, secondaryLocale)\n const secondaryBody = sanitize(pickLocale(htmlOf(row), secondaryLocale))\n const englishBody = sanitize(row.htmlContentEn)\n\n const base: Record<string, unknown> = {\n type: row.type,\n title: primaryTitle,\n sourceSlug: row.slug,\n body: primaryBody,\n order: row.order,\n hasEnglish: present(row.title.en) && present(englishBody),\n }\n // BOTH halves must be present. A title with no body renders an empty page;\n // a body with no title renders an untitled one. Either is the \"empty page\"\n // D015 exists to prevent, so the locale is suppressed unless both survive.\n const secondary =\n present(secondaryTitle) && present(secondaryBody)\n ? { title: secondaryTitle, body: secondaryBody }\n : null\n\n projected.push({ key: row.type, base, secondary, hash: hashOf(base, secondary) })\n }\n\n return { projected, skipped }\n}\n\n/** The two parallel HTML columns, re-shaped as a `MultilingualText` so locale picking is uniform. */\nfunction htmlOf(row: LegalDocumentRow): MultilingualText {\n return { et: row.htmlContentEt, en: row.htmlContentEn }\n}\n\nfunction hashOf(base: Record<string, unknown>, secondary: Record<string, unknown> | null): string {\n return stableHash({ base, secondary })\n}\n","/**\n * One sync run: fetch, diff, apply, record — per resource, in that order.\n *\n * Every collaborator is injected, so a run is fully exercisable in a unit test\n * with no Postgres, no HTTP server and no queue worker. That is not a stylistic\n * preference: CI runs unit tests only, so logic reachable only through\n * integration tests is in practice covered by nothing, and PR 05's three\n * obligatory negative tests all live at this level.\n *\n * ## Ordering: fetch BEFORE reading local state, and abort before either write\n *\n * The upstream fetch happens first and its failure aborts the resource\n * immediately — before the differ, and therefore before any write. That is the\n * mechanical form of \"never act on an absence from a response that did not\n * fully succeed\": an unreachable endpoint cannot retire anything, because\n * nothing downstream of the fetch runs.\n *\n * ## Resources are independent\n *\n * A failure syncing room types does not prevent legal documents from syncing,\n * and each records its own success separately, so the watchdog reports per\n * resource. Whichever failed still fails the JOB at the end, so the queue's\n * retry and dead-letter path engages.\n */\n\nimport {\n type ApplyCounts,\n applyPlan,\n readLocalRows,\n type SyncEntityClient,\n type SyncLogger,\n} from './apply.js'\nimport { LEGAL_DOCUMENTS_RESOURCE, ROOM_TYPES_RESOURCE, type SyncResource } from './constants.js'\nimport { planDiff, type SanityFloor } from './diff.js'\nimport {\n type HtmlSanitizer,\n type ProjectedRow,\n type ProjectionResult,\n projectLegalDocuments,\n projectRoomTypes,\n secondaryLocaleOf,\n} from './projection.js'\nimport type { SyncStateStore } from './sync-state.js'\nimport type { YhikasUpstreamClient } from './upstream/client.js'\n\n/** Per-run ceiling on individual skip warnings; the remainder is reported as a count. */\nconst MAX_LOGGED_SKIPS = 20\n\nexport interface SyncRunDeps {\n readonly upstream: YhikasUpstreamClient\n readonly roomTypeClient: SyncEntityClient\n readonly legalDocumentClient: SyncEntityClient\n readonly state: SyncStateStore\n readonly sanitizeHtml: HtmlSanitizer\n readonly logger: SyncLogger\n readonly defaultLocale: string\n readonly floor: SanityFloor\n /** Injectable so tests are not order-dependent on the wall clock. */\n readonly now?: () => Date\n}\n\nexport interface ResourceOutcome {\n readonly resource: SyncResource\n readonly ok: boolean\n readonly counts: ApplyCounts | null\n readonly skipped: number\n readonly error: string | null\n}\n\nexport interface SyncRunSummary {\n readonly outcomes: readonly ResourceOutcome[]\n readonly ok: boolean\n}\n\n/** Thrown when at least one resource failed, so the queue retries and eventually alerts. */\nexport class YhikasSyncRunError extends Error {\n readonly summary: SyncRunSummary\n constructor(summary: SyncRunSummary) {\n const failed = summary.outcomes.filter((outcome) => !outcome.ok)\n super(\n `yhikas-admin sync failed for ${failed.map((o) => o.resource).join(', ')}: ` +\n failed.map((o) => o.error).join(' | '),\n )\n this.name = 'YhikasSyncRunError'\n this.summary = summary\n }\n}\n\nexport async function runYhikasSync(deps: SyncRunDeps): Promise<SyncRunSummary> {\n const now = deps.now ?? (() => new Date())\n const secondaryLocale = secondaryLocaleOf(deps.defaultLocale)\n\n const outcomes: ResourceOutcome[] = []\n\n outcomes.push(\n await syncOne({\n resource: ROOM_TYPES_RESOURCE,\n keyField: 'code',\n client: deps.roomTypeClient,\n fetchAndProject: async () =>\n projectRoomTypes(await deps.upstream.fetchRoomTypes(), {\n defaultLocale: deps.defaultLocale,\n }),\n deps,\n secondaryLocale,\n now,\n }),\n )\n\n outcomes.push(\n await syncOne({\n resource: LEGAL_DOCUMENTS_RESOURCE,\n keyField: 'type',\n client: deps.legalDocumentClient,\n fetchAndProject: async () =>\n projectLegalDocuments(\n await deps.upstream.fetchLegalDocuments(),\n { defaultLocale: deps.defaultLocale },\n deps.sanitizeHtml,\n ),\n deps,\n secondaryLocale,\n now,\n }),\n )\n\n const summary: SyncRunSummary = { outcomes, ok: outcomes.every((outcome) => outcome.ok) }\n if (!summary.ok) throw new YhikasSyncRunError(summary)\n return summary\n}\n\ninterface SyncOneInput {\n readonly resource: SyncResource\n readonly keyField: string\n readonly client: SyncEntityClient\n readonly fetchAndProject: () => Promise<ProjectionResult>\n readonly deps: SyncRunDeps\n readonly secondaryLocale: string\n readonly now: () => Date\n}\n\nasync function syncOne(input: SyncOneInput): Promise<ResourceOutcome> {\n const { resource, keyField, client, fetchAndProject, deps, secondaryLocale, now } = input\n const { logger, state, floor } = deps\n\n try {\n // Inside the try, deliberately. Outside it, a store failure — Postgres\n // unreachable, table not yet migrated — would reject `syncOne` rather than\n // returning a `ResourceOutcome`, which breaks two stated guarantees at\n // once: the second resource is never attempted (so much for \"resources are\n // independent\"), and the caller gets a raw store error instead of a\n // `YhikasSyncRunError` carrying the per-resource summary the watchdog\n // reports on. The catch below already treats a state write as non-fatal;\n // these two get the same treatment.\n await state.ensure(resource, now())\n await state.recordAttempt(resource, now())\n\n // 1. Fetch + project. Any refusal, timeout or shape failure throws HERE,\n // before local state is even read — so a failed fetch cannot influence\n // what is retired.\n const projection = await fetchAndProject()\n\n // Logged, never silent: a dropped row nobody hears about reads as \"covered\n // everything\". Capped all the same — the snapshot ceiling is in the\n // hundreds, and a systematically malformed upstream would otherwise bury\n // every other line in the run. The suppressed COUNT is reported, so the\n // cap can never itself become a silent truncation.\n for (const skip of projection.skipped.slice(0, MAX_LOGGED_SKIPS)) {\n logger.warn(\n { resource, key: skip.key, reason: skip.reason },\n 'yhikas-sync: skipping an upstream row that cannot be published',\n )\n }\n if (projection.skipped.length > MAX_LOGGED_SKIPS) {\n logger.warn(\n {\n resource,\n suppressed: projection.skipped.length - MAX_LOGGED_SKIPS,\n total: projection.skipped.length,\n },\n 'yhikas-sync: further skipped rows not logged individually',\n )\n }\n\n // 2. Read local state and plan. The differ raises the D016 refusals.\n const local = await readLocalRows(client, keyField, floor.maxRows)\n const plan = planDiff<ProjectedRow>({\n resource,\n upstream: projection.projected,\n local,\n keyOf: (row) => row.key,\n hashOf: (row) => row.hash,\n floor,\n })\n\n // 3. Apply.\n const counts = await applyPlan({ resource, plan, client, secondaryLocale, logger })\n\n await state.recordSuccess(resource, now(), counts)\n logger.info(\n { resource, ...counts, skipped: projection.skipped.length },\n 'yhikas-sync: resource synced',\n )\n return { resource, ok: true, counts, skipped: projection.skipped.length, error: null }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n logger.error({ err, resource }, 'yhikas-sync: resource sync failed — local content unchanged')\n try {\n // `lastSuccessAt` is untouched, so the staleness watchdog stays armed.\n await state.recordFailure(resource, now(), message)\n } catch (stateErr) {\n // Recording the failure must never REPLACE it. If the database is the\n // thing that is broken, this write fails too, and letting it throw here\n // would report a bookkeeping error while hiding the real cause.\n logger.error(\n { err: stateErr, resource },\n 'yhikas-sync: could not record the failure in yhikas_sync_state',\n )\n }\n return { resource, ok: false, counts: null, skipped: 0, error: message }\n }\n}\n","/**\n * Reading and writing `yhikas_sync_state`.\n *\n * Behind an interface so the run orchestrator and the watchdog are both\n * testable against an in-memory fake — CI runs no integration tests, so\n * anything reachable only through a real Postgres is in practice covered by\n * nothing.\n */\n\nimport type { ApplyCounts } from './apply.js'\nimport type { SyncResource } from './constants.js'\nimport { SYNC_RESOURCES } from './constants.js'\nimport type { yhikasSyncStateTable } from './sync-state-table.js'\n\nexport interface SyncStateRecord {\n readonly resource: string\n readonly firstSeenAt: Date\n readonly lastAttemptAt: Date | null\n readonly lastSuccessAt: Date | null\n readonly lastError: string | null\n}\n\nexport interface SyncStateStore {\n /** Create the row if absent, so the watchdog can measure a never-ran sync from somewhere. */\n ensure(resource: SyncResource, now: Date): Promise<void>\n recordAttempt(resource: SyncResource, now: Date): Promise<void>\n recordSuccess(resource: SyncResource, now: Date, counts: ApplyCounts): Promise<void>\n recordFailure(resource: SyncResource, now: Date, error: string): Promise<void>\n readAll(): Promise<SyncStateRecord[]>\n}\n\ntype SyncStateClient = ReturnType<typeof yhikasSyncStateTable.makeClient>\n\n/** Keep the stored message inside the column and free of anything unbounded. */\nconst MAX_ERROR_LENGTH = 1024\n\nexport function truncateError(message: string): string {\n return message.length <= MAX_ERROR_LENGTH ? message : `${message.slice(0, MAX_ERROR_LENGTH - 1)}…`\n}\n\nexport function createSyncStateStore(client: SyncStateClient): SyncStateStore {\n return {\n async ensure(resource, now) {\n // `set: {}` would be an empty conflict update, so the no-op path re-states\n // `resource`: the point is only to guarantee the row exists, never to\n // move `firstSeenAt` — moving it would reset the never-ran clock on every\n // boot and the staleness alert could then never fire.\n await client.upsert({ resource, firstSeenAt: now }, { target: 'resource', set: { resource } })\n },\n\n async recordAttempt(resource, now) {\n await client.upsert(\n { resource, firstSeenAt: now, lastAttemptAt: now },\n { target: 'resource', set: { lastAttemptAt: now } },\n )\n },\n\n async recordSuccess(resource, now, counts) {\n await client.upsert(\n {\n resource,\n firstSeenAt: now,\n lastAttemptAt: now,\n lastSuccessAt: now,\n lastError: null,\n lastCreated: counts.created,\n lastUpdated: counts.updated,\n lastRetired: counts.retired,\n lastUnchanged: counts.unchanged,\n },\n {\n target: 'resource',\n set: {\n lastAttemptAt: now,\n lastSuccessAt: now,\n // Cleared, so a stale message from a resolved failure cannot read\n // as a current one.\n lastError: null,\n lastCreated: counts.created,\n lastUpdated: counts.updated,\n lastRetired: counts.retired,\n lastUnchanged: counts.unchanged,\n },\n },\n )\n },\n\n async recordFailure(resource, now, error) {\n const lastError = truncateError(error)\n // `lastSuccessAt` is deliberately NOT touched. It is the watchdog's only\n // input, and advancing it on a failed run would silence the alert for\n // exactly the runs that should raise it.\n await client.upsert(\n { resource, firstSeenAt: now, lastAttemptAt: now, lastError },\n { target: 'resource', set: { lastAttemptAt: now, lastError } },\n )\n },\n\n async readAll() {\n // Filtered by resource rather than capped at \"however many resources\n // there are\": an unrelated leftover row — a resource added and later\n // removed, e.g. the Q1 `site_info` — would otherwise be able to fill the\n // limit and push an in-scope resource out of the result, which the\n // watchdog reads as \"no tracking row at all\" and reports as a total\n // outage. A false alarm on the one channel that has to stay trustworthy.\n const rows = await client.findMany({\n where: { resource: { in: [...SYNC_RESOURCES] } },\n limit: SYNC_RESOURCES.length,\n })\n return rows.map((row) => ({\n resource: String(row.resource),\n firstSeenAt: row.firstSeenAt as Date,\n lastAttemptAt: (row.lastAttemptAt as Date | null) ?? null,\n lastSuccessAt: (row.lastSuccessAt as Date | null) ?? null,\n lastError: (row.lastError as string | null) ?? null,\n }))\n },\n }\n}\n","/**\n * The yhikas-admin `/api/public/*` wire contract, as Zod schemas.\n *\n * Measured from that repository's route handlers on 2026-08-06 (R013), not\n * inferred from its `src/db/schema.ts` — a sync is written against the\n * envelope, and the envelope is named (`{ success, roomTypes }`,\n * `{ success, documents }`) rather than bare or `data`-keyed.\n *\n * Two properties of the upstream response are deliberate on that side and must\n * survive the hop:\n *\n * - **Decimals arrive as strings.** `pg` returns `numeric` as a string and the\n * route passes it through. Parsing to a float would introduce rounding into\n * a price, so every money/area field is validated AS a string and stored as\n * one. `z.coerce` is banned in this file for that reason.\n * - **Nulls pass through untouched.** The route's own comment: \"no `?? 0`, no\n * `?? ''` … so the site can decide how to render a missing price rather than\n * displaying a fabricated zero.\" A missing price is data; the sync\n * substitutes no defaults either.\n */\n\nimport { z } from 'zod'\n\n/**\n * A memory bound on a key-ish string, NOT the column width.\n *\n * The entities declare `maxLength: 190`, but enforcing that HERE would fail\n * `legalDocumentsResponseSchema` for the whole payload over one overlong\n * free-text value — the same blast-radius mistake the slug charset check made.\n * The column-width check lives in the projection, per row.\n */\nconst MAX_KEY_LENGTH = 2000\n/** Upper bound on a human-facing label (a room-type name, a document title). */\nconst MAX_LABEL_LENGTH = 500\n/** Upper bound on one document's HTML. Refusing beats storing an unbounded blob. */\nconst MAX_HTML_LENGTH = 512 * 1024\n\n/**\n * A Postgres `numeric` as `pg` serializes it. Anything that is not a plain\n * decimal literal is a shape violation and aborts the run — validating at the\n * boundary, per CLAUDE.md, rather than storing whatever arrived.\n */\nconst decimalString = z\n .string()\n .max(32)\n .regex(/^-?\\d+(\\.\\d+)?$/, 'expected a decimal literal, e.g. \"180.00\"')\n\n/**\n * `MultilingualText` — a Postgres `json` column, so it arrives as a nested\n * object and is never stringified.\n *\n * NOT `.strict()`: unknown keys are stripped rather than rejected, so adding a\n * third language upstream degrades to \"the sync ignores it\" instead of \"every\n * run fails\".\n */\nexport const multilingualTextSchema = z.object({\n et: z.string().max(MAX_LABEL_LENGTH),\n en: z.string().max(MAX_LABEL_LENGTH),\n})\n\nexport type MultilingualText = z.infer<typeof multilingualTextSchema>\n\n/**\n * One `room_type` row.\n *\n * `depositAmount` / `discountedDepositAmount` are absent by design. Upstream\n * ships them as hardcoded `null` with no backing column; validating them as\n * `z.null()` would turn the day someone adds the column into a hard sync\n * failure. Deposits are unbuilt admin-side work, not something the sync can\n * surface.\n */\nexport const roomTypeRowSchema = z.object({\n code: z.string().min(1).max(MAX_KEY_LENGTH),\n name: multilingualTextSchema,\n totalArea: decimalString.nullable(),\n livingArea: decimalString.nullable(),\n commonArea: decimalString.nullable(),\n capacity: z.number().int().nullable(),\n monthlyRent: decimalString.nullable(),\n discountedRent: decimalString.nullable(),\n dailyRent: decimalString.nullable(),\n placesOccupied: z.number().int().nullable(),\n})\n\nexport type RoomTypeRow = z.infer<typeof roomTypeRowSchema>\n\n/**\n * One active `legal_document` row.\n *\n * `type` is `text().notNull().unique()` upstream — NOT a pgEnum, and there is\n * no TS union anywhere. The five values seeded today are closed by convention\n * only and the admin UI can mint a sixth, so this validates the SHAPE of the\n * business key and never its membership in a list. A whitelist here would turn\n * a new upstream document into a hard sync failure.\n */\nexport const legalDocumentRowSchema = z.object({\n type: z.string().min(1).max(MAX_KEY_LENGTH),\n title: multilingualTextSchema,\n /**\n * Accepted as free text HERE, and screened per-row in the projection.\n *\n * Upstream derives it from an unvalidated free-text form field\n * (`type.toLowerCase().replace(/_/g, '-')`), so an Estonian title yields an\n * Estonian slug — `üldtingimused` — and a title with a space yields a slug\n * with a space. A character-class regex on the RESPONSE schema would fail\n * `legalDocumentsResponseSchema` for the whole payload, so one newly\n * authored document would take the entire resource offline every six hours\n * until someone edited it upstream. The blast radius belongs at one row.\n */\n slug: z.string().min(1).max(MAX_KEY_LENGTH),\n htmlContentEt: z.string().max(MAX_HTML_LENGTH),\n htmlContentEn: z.string().max(MAX_HTML_LENGTH),\n order: z.number().int(),\n})\n\nexport type LegalDocumentRow = z.infer<typeof legalDocumentRowSchema>\n\n/**\n * `success: z.literal(true)` is the load-bearing clause, not decoration.\n *\n * Every upstream failure path sets `success: false` — 401 (missing header,\n * wrong scheme, wrong key, AND an unset server-side key: all four\n * indistinguishable, deny-by-default through one branch), 429, and 500. No\n * route returns 200 with a degraded body. So the discriminator is `success`,\n * never array length, and a snapshot that fails this schema can never be\n * mistaken for an authoritative empty one.\n */\nexport const roomTypesResponseSchema = z.object({\n success: z.literal(true),\n roomTypes: z.array(roomTypeRowSchema),\n})\n\nexport const legalDocumentsResponseSchema = z.object({\n success: z.literal(true),\n documents: z.array(legalDocumentRowSchema),\n})\n","/**\n * The read-only yhikas-admin client.\n *\n * **One-directional by construction, not by convention.** This class exposes\n * two methods and both are GETs. There is no `post`, no `put`, no generic\n * `request(method, …)` — so there is no code path anywhere in the sync that\n * could write upstream, which is a property of the type rather than a rule\n * someone has to keep remembering.\n *\n * It also never touches a database. D014 rules out a direct connection even\n * though the credentials would technically permit one: upstream keeps public\n * and private tables in one database behind one pool, with no read replica and\n * no schema separation, and the isolation that exists is query-level (explicit\n * column lists, no joins). The three narrow endpoints are the boundary, and\n * they are the boundary precisely because someone already drew it.\n */\n\nimport type { z } from 'zod'\nimport {\n LEGAL_DOCUMENTS_PATH,\n LEGAL_DOCUMENTS_RESOURCE,\n ROOM_TYPES_PATH,\n ROOM_TYPES_RESOURCE,\n type SyncResource,\n} from '../constants.js'\nimport { YhikasUpstreamError } from './errors.js'\nimport {\n type LegalDocumentRow,\n legalDocumentsResponseSchema,\n type RoomTypeRow,\n roomTypesResponseSchema,\n} from './wire.js'\n\n/**\n * Ceiling on one response, in BYTES, enforced WHILE reading the stream.\n *\n * An earlier version measured after `response.text()` had already buffered the\n * whole body, and said so — which made the bound honest but inert against\n * exactly the case it exists for: a chunked response declares no\n * `content-length`, so nothing stopped an unbounded body being read into\n * memory before the check could run. Availability is a security property\n * (CLAUDE.md), and a bound that cannot act until after the damage is a comment,\n * not a control. Now the read aborts mid-stream.\n */\nconst MAX_RESPONSE_BYTES = 8 * 1024 * 1024\n\nexport interface YhikasUpstreamClientOptions {\n /** Origin of the yhikas-admin deployment. Must be http or https. */\n baseUrl: string\n /** The sync's OWN bearer credential — never the site's (see `API_KEY_ENV_VAR`). */\n apiKey: string\n /** Per-request deadline in milliseconds. */\n timeoutMs: number\n /** Injectable for tests. Defaults to the global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\n/**\n * Release an unread body before throwing, so the connection is not pinned\n * waiting for a consumer that will never arrive. Cancellation failures are\n * swallowed on purpose: the caller is already throwing something more\n * informative, and replacing it with a teardown error would hide the cause.\n */\n/**\n * Read a response body as text, aborting once it exceeds the byte ceiling.\n *\n * Throws a `shape` {@link YhikasUpstreamError} on overrun — which the caller\n * re-raises untouched, so an oversized body is refused rather than\n * misclassified as unreadable.\n */\nasync function readBounded(\n response: Response,\n resource: SyncResource,\n path: string,\n): Promise<string> {\n const stream = response.body\n if (!stream) return ''\n // Annotated, not cast: `Response.body` is typed `ReadableStream<any>` under\n // the Node type definitions, but the Fetch spec guarantees its chunks are\n // `Uint8Array`. Stating that here keeps `value.byteLength` honestly typed\n // instead of letting three `any`s leak into the byte accounting.\n const reader: ReadableStreamDefaultReader<Uint8Array> = stream.getReader()\n const decoder = new TextDecoder()\n let seen = 0\n let text = ''\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n seen += value.byteLength\n if (seen > MAX_RESPONSE_BYTES) {\n await reader.cancel()\n throw new YhikasUpstreamError(\n resource,\n 'shape',\n `yhikas-admin sent more than ${MAX_RESPONSE_BYTES} bytes for ${path}, above the ` +\n `ceiling — the read was aborted mid-stream rather than buffered and measured after`,\n { status: response.status },\n )\n }\n // `stream: true` so a multi-byte character split across chunk boundaries\n // is not mangled — Estonian text is full of them.\n text += decoder.decode(value, { stream: true })\n }\n return text + decoder.decode()\n } finally {\n reader.releaseLock()\n }\n}\n\nasync function discardBody(response: Response): Promise<void> {\n try {\n await response.body?.cancel()\n } catch {\n // Nothing useful to do — the original refusal is the interesting error.\n }\n}\n\nexport class YhikasUpstreamClient {\n readonly #baseUrl: URL\n readonly #apiKey: string\n readonly #timeoutMs: number\n readonly #fetch: typeof fetch\n\n constructor(options: YhikasUpstreamClientOptions) {\n let parsed: URL\n try {\n parsed = new URL(options.baseUrl)\n } catch (cause) {\n throw new TypeError(`yhikas-sync: baseUrl is not a valid URL: ${options.baseUrl}`, { cause })\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new TypeError(\n `yhikas-sync: baseUrl must be http or https, got '${parsed.protocol}'. ` +\n `A file: or data: origin here would be a way to feed the sync a local snapshot.`,\n )\n }\n if (parsed.pathname !== '/') {\n // `new URL('/api/public/room-types', 'http://host/yhikas-admin/')` resolves\n // to `http://host/api/public/room-types` — the base path is silently\n // dropped and the sync calls the host root. Refusing beats joining:\n // upstream mounts these routes at the origin root, so a base path here is\n // a misconfiguration rather than a shape to support.\n throw new TypeError(\n `yhikas-sync: baseUrl must be an origin with no path, got '${parsed.pathname}'. ` +\n `The upstream routes are absolute, so a base path would be silently discarded.`,\n )\n }\n if (options.apiKey.length === 0) {\n throw new TypeError('yhikas-sync: apiKey must not be empty')\n }\n this.#baseUrl = parsed\n this.#apiKey = options.apiKey\n this.#timeoutMs = options.timeoutMs\n this.#fetch = options.fetchImpl ?? globalThis.fetch\n }\n\n /** `GET /api/public/room-types`. Ordered by `code` upstream; unpaginated. */\n async fetchRoomTypes(): Promise<RoomTypeRow[]> {\n const body = await this.#get(ROOM_TYPES_RESOURCE, ROOM_TYPES_PATH, roomTypesResponseSchema)\n return body.roomTypes\n }\n\n /** `GET /api/public/legal-documents`. Active only, ordered by `order`; unpaginated. */\n async fetchLegalDocuments(): Promise<LegalDocumentRow[]> {\n const body = await this.#get(\n LEGAL_DOCUMENTS_RESOURCE,\n LEGAL_DOCUMENTS_PATH,\n legalDocumentsResponseSchema,\n )\n return body.documents\n }\n\n // Generic over the PARSED type rather than over the schema: a bare\n // `S extends z.ZodType` defaults its type parameters to `any`, so\n // `safeParse(...).data` would come back `any` and every caller would silently\n // lose the contract this method exists to enforce. `z.ZodType<T>` is the\n // CLAUDE.md-sanctioned form — the defaults handle the internal parameters.\n async #get<T>(resource: SyncResource, path: string, schema: z.ZodType<T>): Promise<T> {\n // Resolved against the configured origin so a path can never escape it.\n const url = new URL(path, this.#baseUrl)\n\n // The queue has NO per-job timeout (R012 §3): a hung fetch would hold a\n // concurrency slot until `jobLockTimeout` (30 min) let lease recovery\n // re-claim the job, at which point the handler body would run TWICE,\n // concurrently. The deadline is what keeps that from being routine.\n const signal = AbortSignal.timeout(this.#timeoutMs)\n\n let response: Response\n try {\n response = await this.#fetch(url, {\n method: 'GET',\n headers: {\n authorization: `Bearer ${this.#apiKey}`,\n accept: 'application/json',\n },\n redirect: 'error',\n signal,\n })\n } catch (cause) {\n const timedOut = signal.aborted\n throw new YhikasUpstreamError(\n resource,\n timedOut ? 'timeout' : 'network',\n timedOut\n ? `yhikas-admin did not answer ${path} within ${this.#timeoutMs}ms`\n : `yhikas-admin was unreachable at ${path}`,\n { cause },\n )\n }\n\n if (!response.ok) {\n // Never log or echo the body: a refusal envelope is uninteresting and the\n // request carried a credential. Status alone distinguishes the cases that\n // matter — 401 (wrong or unset key), 429 (limiter), 5xx (upstream fault).\n await discardBody(response)\n throw new YhikasUpstreamError(\n resource,\n 'http',\n `yhikas-admin refused ${path} with HTTP ${response.status}`,\n { status: response.status },\n )\n }\n\n const declaredLength = Number(response.headers.get('content-length') ?? Number.NaN)\n if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {\n await discardBody(response)\n throw new YhikasUpstreamError(\n resource,\n 'shape',\n `yhikas-admin returned ${declaredLength} bytes for ${path}, above the ${MAX_RESPONSE_BYTES}-byte ceiling`,\n { status: response.status },\n )\n }\n\n // Read through the stream, counting bytes as they arrive, rather than\n // `response.text()`/`.json()`. The `content-length` check above is inert on\n // a chunked response — which is precisely the shape an unbounded body\n // arrives in — so buffering first and measuring after would apply the\n // ceiling to every case except the one it exists for.\n let body: string\n try {\n body = await readBounded(response, resource, path)\n } catch (cause) {\n if (cause instanceof YhikasUpstreamError) throw cause\n // `AbortSignal.timeout` aborts the body stream too, so a deadline that\n // elapses mid-read surfaces here rather than at the request. Reporting\n // it as a malformed body would point an operator at the wrong system.\n const timedOut = signal.aborted\n throw new YhikasUpstreamError(\n resource,\n timedOut ? 'timeout' : 'shape',\n timedOut\n ? `yhikas-admin did not finish sending ${path} within ${this.#timeoutMs}ms`\n : `${path} returned a body that could not be read`,\n { status: response.status, cause },\n )\n }\n\n let json: unknown\n try {\n json = JSON.parse(body)\n } catch (cause) {\n throw new YhikasUpstreamError(resource, 'shape', `${path} returned a body that is not JSON`, {\n status: response.status,\n cause,\n })\n }\n\n const parsed = schema.safeParse(json)\n if (!parsed.success) {\n // The issue paths are field names from OUR schema, never response values,\n // so this cannot leak content into a log line.\n const where = parsed.error.issues\n .slice(0, 5)\n .map((issue) => `${issue.path.join('.') || '<root>'}: ${issue.message}`)\n .join('; ')\n throw new YhikasUpstreamError(\n resource,\n 'shape',\n `${path} returned a body that does not match the expected contract — ${where}`,\n { status: response.status },\n )\n }\n return parsed.data\n }\n}\n","/**\n * The staleness watchdog — S7's \"and the staleness is OBSERVABLE\" half.\n *\n * ## Why this is new code\n *\n * The failure being defended against is not a crash. It is a job that silently\n * stops running while the site keeps serving last month's prices, indefinitely\n * and confidently — nothing about the rendered page would look wrong. The\n * queue cannot see that (R012 §1): its heartbeat is per worker PROCESS and\n * answers \"is any worker alive\", and its alerter fires only from `failJob`'s\n * dead-letter branch, i.e. only on a job that RAN and THREW. A job that never\n * starts produces no error at all.\n *\n * So detection is new. Delivery is not: this check runs as its own scheduled\n * job and THROWS, and the throw reaches `failJob` → `QueueAlerter.recordFailure`\n * → the shipped dedupe window, digest and email path. No alert channel is\n * invented.\n *\n * ## The limitation, stated rather than papered over\n *\n * The watchdog is itself a scheduled job, so a worker that is entirely dead\n * runs neither the sync nor the watchdog. That case is exactly what the queue's\n * worker heartbeat DOES see. The two are complementary: the heartbeat covers\n * \"no worker\", this covers \"worker alive, this schedule not firing\" — and\n * neither covers the other.\n */\n\nimport { SYNC_RESOURCES, type SyncResource } from './constants.js'\nimport type { SyncStateRecord } from './sync-state.js'\n\nexport interface ResourceStaleness {\n readonly resource: SyncResource\n /** `null` when this resource has never once synced successfully. */\n readonly lastSuccessAt: Date | null\n /** Age of the last success, or of the tracking row when there has never been one. */\n readonly ageMs: number\n readonly stale: boolean\n readonly lastError: string | null\n}\n\n/** Thrown to reach the queue's dead-letter alerting. */\nexport class YhikasSyncStaleError extends Error {\n readonly stale: readonly ResourceStaleness[]\n constructor(stale: readonly ResourceStaleness[], staleAfterMs: number) {\n const detail = stale.map(describeOne).join('; ')\n super(\n `yhikas-admin sync is stale beyond the ${formatAge(staleAfterMs)} window. ${detail}. ` +\n `The public site is serving content that old — this alert fires on ABSENCE of success, ` +\n `so there may be no failing job to look at.`,\n )\n this.name = 'YhikasSyncStaleError'\n this.stale = stale\n }\n}\n\nfunction describeOne(entry: ResourceStaleness): string {\n const suffix = entry.lastError ? ` — last error: ${entry.lastError}` : ''\n if (entry.lastSuccessAt) {\n return `${entry.resource}: last succeeded ${formatAge(entry.ageMs)} ago${suffix}`\n }\n // An infinite age is the no-tracking-row-at-all case. Rendering it through\n // `formatAge` would print \"Infinityd\", which reads as a bug in the alert\n // rather than as the loudest thing the alert has to say.\n if (!Number.isFinite(entry.ageMs)) {\n return `${entry.resource}: has NEVER synced — no tracking row exists at all${suffix}`\n }\n return `${entry.resource}: has NEVER succeeded (tracked for ${formatAge(entry.ageMs)})${suffix}`\n}\n\nfunction formatAge(ms: number): string {\n if (!Number.isFinite(ms)) return 'an unknown time'\n const hours = ms / 3_600_000\n if (hours < 1) return `${Math.round(ms / 60_000)}m`\n if (hours < 48) return `${Math.round(hours)}h`\n return `${Math.round(hours / 24)}d`\n}\n\n/**\n * Assess every in-scope resource.\n *\n * A resource with no state row at all counts as stale with an age of\n * `Infinity`: \"nothing has ever written this row\" is the loudest possible\n * version of \"this sync has never run\", and treating a missing row as\n * not-yet-stale would make an install that never once synced look healthy\n * forever — the exact unobserved-bound failure S7 names.\n *\n * A resource that HAS a row but no success is measured from `firstSeenAt`, so\n * a freshly installed sync gets one full window to succeed before it alerts.\n */\nexport function assessStaleness(\n records: readonly SyncStateRecord[],\n now: Date,\n staleAfterMs: number,\n): ResourceStaleness[] {\n const byResource = new Map(records.map((record) => [record.resource, record]))\n\n return SYNC_RESOURCES.map((resource) => {\n const record = byResource.get(resource)\n if (!record) {\n return {\n resource,\n lastSuccessAt: null,\n ageMs: Number.POSITIVE_INFINITY,\n stale: true,\n lastError: null,\n }\n }\n const since = record.lastSuccessAt ?? record.firstSeenAt\n const ageMs = now.getTime() - since.getTime()\n return {\n resource,\n lastSuccessAt: record.lastSuccessAt,\n ageMs,\n stale: ageMs > staleAfterMs,\n lastError: record.lastError,\n }\n })\n}\n\n/**\n * Assess, and throw if anything is stale.\n *\n * @throws {YhikasSyncStaleError} which the queue turns into a dead-lettered\n * job and therefore into the shipped alert.\n */\nexport function assertNotStale(\n records: readonly SyncStateRecord[],\n now: Date,\n staleAfterMs: number,\n): ResourceStaleness[] {\n const assessed = assessStaleness(records, now, staleAfterMs)\n const stale = assessed.filter((entry) => entry.stale)\n if (stale.length > 0) throw new YhikasSyncStaleError(stale, staleAfterMs)\n return assessed\n}\n"],"mappings":"iJAqEA,IAAa,EAAb,cAA6C,KAAM,CACjD,OACA,YAAY,EAAwB,EAAqB,CACvD,MACE,GAAG,EAAO,OAAO,MAAM,EAAO,QAAU,EAAO,QAAU,EAAO,QAAU,EAAO,OAAO,GACnF,EAAS,oIAEhB,EACA,KAAK,KAAO,0BACZ,KAAK,OAAS,CAChB,CACF,EAmBA,SAAS,EAAO,EAA6B,CAC3C,GAAI,aAAiB,KAAM,OAAO,OAAO,MAAM,EAAM,QAAQ,CAAC,EAAI,KAAO,EACzE,GAAI,OAAO,GAAU,SAAU,CAC7B,IAAM,EAAS,IAAI,KAAK,CAAK,EAC7B,OAAO,OAAO,MAAM,EAAO,QAAQ,CAAC,EAAI,KAAO,CACjD,CACA,OAAO,IACT,CAEA,eAAsB,EACpB,EACA,EACA,EACqB,CAErB,OAAO,MADY,E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