{"version":3,"file":"relation-DfWePtI7.mjs","names":[],"sources":["../src/database/repositories/relation.ts"],"sourcesContent":["import type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport type { Database, RelationTable, ContentReferenceTable } from \"../types.js\";\nimport { decodeCursor, encodeCursor, InvalidCursorError, type FindManyResult } from \"./types.js\";\n\nexport interface Relation {\n\tid: string;\n\tname: string;\n\tparentCollection: string;\n\tchildCollection: string;\n\tparentLabel: string;\n\tchildLabel: string;\n\tlocale: string;\n\ttranslationGroup: string;\n}\n\nexport interface CreateRelationInput {\n\tname: string;\n\t/** Required for a base relation; ignored (inherited from the source) when\n\t * `translationOf` is set. */\n\tparentCollection?: string;\n\t/** Required for a base relation; ignored (inherited from the source) when\n\t * `translationOf` is set. */\n\tchildCollection?: string;\n\tparentLabel: string;\n\tchildLabel: string;\n\t/** Omit to let the DB default (current value: 'en') apply. Higher layers\n\t * resolve locale from request context / i18n config. */\n\tlocale?: string;\n\t/** When set, joins the source relation's translation_group AND inherits its\n\t * structural fields (name, parentCollection, childCollection). Only locale +\n\t * labels may differ on a translation. */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateRelationInput {\n\t/** Only localized fields are mutable per row. Changing structural fields\n\t * (name/collections) is a cross-group operation deferred to a later slice. */\n\tparentLabel?: string;\n\tchildLabel?: string;\n}\n\nexport interface ContentReference {\n\tid: string;\n\trelationGroup: string;\n\tparentGroup: string;\n\tchildGroup: string;\n\tsortOrder: number;\n}\n\n/**\n * Content-references repository.\n *\n * Owns relation *definitions* (`_emdash_relations`, row-per-locale, mirroring\n * `_emdash_taxonomy_defs`) and the *edge* junction (`_emdash_content_references`,\n * keyed by `translation_group` so edges are locale-agnostic, mirroring\n * `content_taxonomies`).\n *\n * Like `TaxonomyRepository`, this is not the validation boundary: it trusts its\n * typed inputs. The API slice supplies Zod schemas at the route and enforces\n * collection-agreement / relation-existence invariants in the handler. The repo\n * does not resolve locale fallbacks — callers pass the locale they want.\n */\nexport class RelationRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a relation. Without `translationOf`, mints a fresh group\n\t * (`translation_group = id`, matching the migration backfill pattern). With\n\t * `translationOf`, the structural fields (name, parentCollection,\n\t * childCollection) and the translation_group are inherited from the source;\n\t * locale and the two labels are taken from `input`.\n\t */\n\tasync create(input: CreateRelationInput): Promise<Relation> {\n\t\tconst id = ulid();\n\t\tconst now = new Date().toISOString();\n\n\t\tlet translationGroup = id;\n\t\tlet name: string;\n\t\tlet parentCollection: string;\n\t\tlet childCollection: string;\n\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\t// translation_group is NOT NULL here, so we cannot fall back to a\n\t\t\t// fresh group like TaxonomyRepository does — a bad translationOf must\n\t\t\t// fail loudly rather than silently mint an unlinked relation.\n\t\t\tif (!source) throw new Error(\"Source relation for translation not found\");\n\t\t\ttranslationGroup = source.translationGroup;\n\t\t\tname = source.name;\n\t\t\tparentCollection = source.parentCollection;\n\t\t\tchildCollection = source.childCollection;\n\t\t} else {\n\t\t\t// A base relation carries its own structural fields. The API layer's Zod\n\t\t\t// schema enforces this; guard here too since the repo trusts its inputs\n\t\t\t// and the columns are NOT NULL.\n\t\t\tif (input.parentCollection === undefined || input.childCollection === undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"parentCollection and childCollection are required unless translationOf is set\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tname = input.name;\n\t\t\tparentCollection = input.parentCollection;\n\t\t\tchildCollection = input.childCollection;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_relations\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\tparent_collection: parentCollection,\n\t\t\t\tchild_collection: childCollection,\n\t\t\t\tparent_label: input.parentLabel,\n\t\t\t\tchild_label: input.childLabel,\n\t\t\t\tcreated_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t\t// Omit `locale` so the DB DEFAULT (configured defaultLocale)\n\t\t\t\t// applies — matches TaxonomyRepository.create.\n\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\ttranslation_group: translationGroup,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tconst relation = await this.findById(id);\n\t\tif (!relation) throw new Error(\"Failed to create relation\");\n\t\treturn relation;\n\t}\n\n\tasync findById(id: string): Promise<Relation | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? this.rowToRelation(row) : null;\n\t}\n\n\t/**\n\t * Find a relation by name. With `locale`, filter by it; without, return the\n\t * lowest-locale-code match deterministically. Mirrors\n\t * `TaxonomyRepository.findBySlug` — note this returns a single row, unlike\n\t * `TaxonomyRepository.findByName` which returns every term in a taxonomy.\n\t */\n\tasync findByName(name: string, locale?: string): Promise<Relation | null> {\n\t\tlet query = this.db.selectFrom(\"_emdash_relations\").selectAll().where(\"name\", \"=\", name);\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst row = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t\treturn row ? this.rowToRelation(row) : null;\n\t}\n\n\t/** Every translation sibling (including itself) sharing a translation_group. */\n\tasync findTranslations(translationGroup: string): Promise<Relation[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", translationGroup)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToRelation(row));\n\t}\n\n\t/**\n\t * All relations, ordered by name then id (id is a stable tiebreak for\n\t * relations sharing a name across locales). Optionally filtered by locale.\n\t */\n\tasync list(locale?: string): Promise<Relation[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"name\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToRelation(row));\n\t}\n\n\t/** Relations where `collection` is the parent OR the child side. */\n\tasync findForCollection(collection: string, locale?: string): Promise<Relation[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) =>\n\t\t\t\teb.or([eb(\"parent_collection\", \"=\", collection), eb(\"child_collection\", \"=\", collection)]),\n\t\t\t)\n\t\t\t.orderBy(\"name\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToRelation(row));\n\t}\n\n\t/**\n\t * Update the localized labels of one relation row. Structural fields are\n\t * immutable here (a cross-group concern). No-ops when nothing is supplied.\n\t */\n\tasync update(id: string, input: UpdateRelationInput): Promise<Relation | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst updates: Record<string, unknown> = {};\n\t\tif (input.parentLabel !== undefined) updates.parent_label = input.parentLabel;\n\t\tif (input.childLabel !== undefined) updates.child_label = input.childLabel;\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tupdates.updated_at = new Date().toISOString();\n\t\t\tawait this.db.updateTable(\"_emdash_relations\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Delete one relation row. When it is the *last* translation of its group,\n\t * purge edges referencing that group (application-layer cascade — group\n\t * linking precludes a SQL FK). Mirrors `TaxonomyRepository.delete`.\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst relation = await this.findById(id);\n\t\tif (!relation) return false;\n\n\t\tconst siblings = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"translation_group\", \"=\", relation.translationGroup)\n\t\t\t.where(\"id\", \"!=\", id)\n\t\t\t.execute();\n\t\tif (siblings.length === 0) {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t\t.where(\"relation_group\", \"=\", relation.translationGroup)\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_relations\")\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn (result.numDeletedRows ?? 0n) > 0n;\n\t}\n\n\t/** Normalize a relation id OR group to its translation_group. Returns null\n\t * for an unknown relation (edge methods then no-op, matching\n\t * `TaxonomyRepository.attachToEntry`). */\n\tprivate async resolveRelationGroup(idOrGroup: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.select([\"translation_group\"])\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\treturn row?.translation_group ?? null;\n\t}\n\n\tprivate rowToReference(row: Selectable<ContentReferenceTable>): ContentReference {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\trelationGroup: row.relation_group,\n\t\t\tparentGroup: row.parent_group,\n\t\t\tchildGroup: row.child_group,\n\t\t\tsortOrder: row.sort_order,\n\t\t};\n\t}\n\n\t/**\n\t * Link `parentGroup → childGroup` under a relation. `relation` is a relation\n\t * id or group. Idempotent (onConflict doNothing against the unique edge).\n\t * `sortOrder` defaults to append: max(sort_order)+1 within (relation, parent).\n\t *\n\t * The default-append MAX→INSERT is not atomic: concurrent appends without an\n\t * explicit `sortOrder` may both read the same max and collide on sort_order,\n\t * and onConflict silently drops the loser. Callers needing strict ordering\n\t * under concurrency should pass `sortOrder` explicitly (or serialize).\n\t */\n\tasync addReference(\n\t\trelation: string,\n\t\tparentGroup: string,\n\t\tchildGroup: string,\n\t\tsortOrder?: number,\n\t): Promise<void> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return;\n\n\t\tlet order = sortOrder;\n\t\tif (order === undefined) {\n\t\t\tconst max = await this.db\n\t\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t\t.select((eb) => eb.fn.max(\"sort_order\").as(\"max\"))\n\t\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t\t.executeTakeFirst();\n\t\t\torder = max?.max === null || max?.max === undefined ? 0 : Number(max.max) + 1;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_content_references\")\n\t\t\t.values({\n\t\t\t\tid: ulid(),\n\t\t\t\trelation_group: relationGroup,\n\t\t\t\tparent_group: parentGroup,\n\t\t\t\tchild_group: childGroup,\n\t\t\t\tsort_order: order,\n\t\t\t\tcreated_at: new Date().toISOString(),\n\t\t\t})\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t}\n\n\t/** Remove one `parentGroup → childGroup` edge under a relation. */\n\tasync removeReference(relation: string, parentGroup: string, childGroup: string): Promise<void> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup)\n\t\t\t.execute();\n\t}\n\n\t/** Forward traversal: a parent's children for a relation, ordered. */\n\tasync getChildren(relation: string, parentGroup: string): Promise<ContentReference[]> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return [];\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToReference(row));\n\t}\n\n\t/**\n\t * Forward traversal, paginated: one page of a parent's children for a\n\t * relation, ordered by `(sort_order, id)`. Use this on request paths — a\n\t * parent's children are capped but still up to 1000, and an unbounded read\n\t * scales poorly. Returns `{ items, nextCursor? }`; the cursor's order value is\n\t * the row's `sort_order`. Default limit 50, max 100.\n\t */\n\tasync getChildrenPage(\n\t\trelation: string,\n\t\tparentGroup: string,\n\t\toptions: { limit?: number; cursor?: string } = {},\n\t): Promise<FindManyResult<ContentReference>> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return { items: [] };\n\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup);\n\n\t\tif (options.cursor) {\n\t\t\tconst decoded = decodeCursor(options.cursor);\n\t\t\tconst sortOrder = Number(decoded.orderValue);\n\t\t\t// `decodeCursor` only guarantees `orderValue` is a string; a hand-crafted\n\t\t\t// cursor with a non-numeric order value would coerce to NaN and blow up at\n\t\t\t// the driver bind as a 500. A bad cursor is a client error — surface it as\n\t\t\t// INVALID_CURSOR (400). Server-issued cursors are always numeric here.\n\t\t\tif (!Number.isFinite(sortOrder)) throw new InvalidCursorError(options.cursor);\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"sort_order\", \">\", sortOrder),\n\t\t\t\t\teb.and([eb(\"sort_order\", \"=\", sortOrder), eb(\"id\", \">\", decoded.id)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst rows = await query\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.limit(limit + 1)\n\t\t\t.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToReference(row));\n\t\tconst result: FindManyResult<ContentReference> = { items };\n\t\tconst last = items.at(-1);\n\t\tif (hasMore && last) {\n\t\t\tresult.nextCursor = encodeCursor(String(last.sortOrder), last.id);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Backlink traversal: the parents that reference a child for a relation. */\n\tasync getParents(relation: string, childGroup: string): Promise<ContentReference[]> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return [];\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup)\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToReference(row));\n\t}\n\n\t/**\n\t * Replace all children of `parentGroup` under a relation with `childGroups`,\n\t * assigning positional sort_order (index in the deduped array). Deletes the\n\t * old set for this (relation, parent) and re-inserts — simple and correct;\n\t * the set is small (one parent's children). Mirrors the intent of\n\t * `TaxonomyRepository.setTermsForEntry`.\n\t *\n\t * A parent references a given child at most once (the unique edge), so\n\t * duplicate `childGroups` are collapsed first-occurrence-wins rather than\n\t * relying on the insert's onConflict to silently drop them. Not wrapped in a\n\t * transaction: a crash between the delete and insert leaves the parent with\n\t * no children — acceptable for a replace-all, since a retry restores state.\n\t *\n\t * Concurrency: two simultaneous replace-all calls for the same (relation,\n\t * parent) can interleave their deletes and inserts and merge into the union of\n\t * both sets (a lost update — neither \"replace\" wins). This is non-corrupting —\n\t * keyset pagination stays totally ordered via the `(sort_order, id)` tiebreak\n\t * even with duplicate sort_orders — and a single client editing one parent's\n\t * children serially never hits it. A D1-portable fix isn't available (no\n\t * multi-statement transactions), so concurrent replace-all on one parent is\n\t * unsupported by design rather than guarded here.\n\t */\n\tasync setChildren(relation: string, parentGroup: string, childGroups: string[]): Promise<void> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.execute();\n\n\t\t// Collapse duplicates so positional sort_order has no gaps.\n\t\tconst uniqueChildGroups = [...new Set(childGroups)];\n\t\tif (uniqueChildGroups.length === 0) return;\n\n\t\tconst now = new Date().toISOString();\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_content_references\")\n\t\t\t.values(\n\t\t\t\tuniqueChildGroups.map((childGroup, index) => ({\n\t\t\t\t\tid: ulid(),\n\t\t\t\t\trelation_group: relationGroup,\n\t\t\t\t\tparent_group: parentGroup,\n\t\t\t\t\tchild_group: childGroup,\n\t\t\t\t\tsort_order: index,\n\t\t\t\t\tcreated_at: now,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t// Belt-and-suspenders: the DELETE above already cleared this\n\t\t\t// (relation, parent), so no conflict is possible within one call.\n\t\t\t// This is NOT a concurrency guarantee — delete-then-insert is not atomic.\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Backlink traversal, paginated: one page of the parents that reference a\n\t * child for a relation, ordered by `id`. Unlike a parent's children, a\n\t * child's backlinks are *unbounded* — one popular entry can be referenced by\n\t * arbitrarily many parents — so this read must paginate. Returns\n\t * `{ items, nextCursor? }`; the cursor's order value is the row `id`. Default\n\t * limit 50, max 100.\n\t */\n\tasync getParentsPage(\n\t\trelation: string,\n\t\tchildGroup: string,\n\t\toptions: { limit?: number; cursor?: string } = {},\n\t): Promise<FindManyResult<ContentReference>> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return { items: [] };\n\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup);\n\n\t\tif (options.cursor) {\n\t\t\tconst decoded = decodeCursor(options.cursor);\n\t\t\tquery = query.where(\"id\", \">\", decoded.id);\n\t\t}\n\n\t\tconst rows = await query\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.limit(limit + 1)\n\t\t\t.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToReference(row));\n\t\tconst result: FindManyResult<ContentReference> = { items };\n\t\tconst last = items.at(-1);\n\t\tif (hasMore && last) {\n\t\t\tresult.nextCursor = encodeCursor(last.id, last.id);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Remove every edge where `group` is the parent OR the child — i.e. ensure no\n\t * orphaned reference edges survive when a content entry is deleted. The\n\t * application-layer cascade that group-linking precludes at the SQL level.\n\t * Wiring this into the content-delete path is a later (handler) slice.\n\t * Returns the number of edges removed.\n\t */\n\tasync clearReferencesForGroup(group: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t.where((eb) => eb.or([eb(\"parent_group\", \"=\", group), eb(\"child_group\", \"=\", group)]))\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\t/** Count a parent's children under a relation. */\n\tasync countChildren(relation: string, parentGroup: string): Promise<number> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return 0;\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.select((eb) => eb.fn.count(\"id\").as(\"count\"))\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/** Count a child's parents (backlinks) under a relation. */\n\tasync countParents(relation: string, childGroup: string): Promise<number> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return 0;\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.select((eb) => eb.fn.count(\"id\").as(\"count\"))\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Batch child-counts for many parents under a relation. Chunks at\n\t * SQL_BATCH_SIZE for D1's bind-parameter limit. Returns parent_group → count\n\t * (parents with no children are absent from the map). Mirrors\n\t * `TaxonomyRepository.countEntriesForTerms`.\n\t */\n\tasync countChildrenForParents(\n\t\trelation: string,\n\t\tparentGroups: string[],\n\t): Promise<Map<string, number>> {\n\t\tconst counts = new Map<string, number>();\n\t\tif (parentGroups.length === 0) return counts;\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return counts;\n\n\t\tfor (const chunk of chunks(parentGroups, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t\t.select([\"parent_group\", (eb) => eb.fn.count(\"id\").as(\"count\")])\n\t\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t\t.where(\"parent_group\", \"in\", chunk)\n\t\t\t\t.groupBy(\"parent_group\")\n\t\t\t\t.execute();\n\t\t\tfor (const row of rows) {\n\t\t\t\tcounts.set(row.parent_group, Number(row.count ?? 0));\n\t\t\t}\n\t\t}\n\t\treturn counts;\n\t}\n\n\tprivate rowToRelation(row: Selectable<RelationTable>): Relation {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tname: row.name,\n\t\t\tparentCollection: row.parent_collection,\n\t\t\tchildCollection: row.child_collection,\n\t\t\tparentLabel: row.parent_label,\n\t\t\tchildLabel: row.child_label,\n\t\t\tlocale: row.locale,\n\t\t\ttranslationGroup: row.translation_group,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiEA,IAAa,qBAAb,MAAgC;CAC/B,YAAY,AAAQ,IAAsB;EAAtB;;;;;;;;;CASpB,MAAM,OAAO,OAA+C;EAC3D,MAAM,KAAK,MAAM;EACjB,MAAM,uBAAM,IAAI,MAAM,EAAC,aAAa;EAEpC,IAAI,mBAAmB;EACvB,IAAI;EACJ,IAAI;EACJ,IAAI;AAEJ,MAAI,MAAM,eAAe;GACxB,MAAM,SAAS,MAAM,KAAK,SAAS,MAAM,cAAc;AAIvD,OAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,4CAA4C;AACzE,sBAAmB,OAAO;AAC1B,UAAO,OAAO;AACd,sBAAmB,OAAO;AAC1B,qBAAkB,OAAO;SACnB;AAIN,OAAI,MAAM,qBAAqB,UAAa,MAAM,oBAAoB,OACrE,OAAM,IAAI,MACT,gFACA;AAEF,UAAO,MAAM;AACb,sBAAmB,MAAM;AACzB,qBAAkB,MAAM;;AAGzB,QAAM,KAAK,GACT,WAAW,oBAAoB,CAC/B,OAAO;GACP;GACA;GACA,mBAAmB;GACnB,kBAAkB;GAClB,cAAc,MAAM;GACpB,aAAa,MAAM;GACnB,YAAY;GACZ,YAAY;GAGZ,GAAI,MAAM,WAAW,SAAY,EAAE,QAAQ,MAAM,QAAQ,GAAG,EAAE;GAC9D,mBAAmB;GACnB,CAAC,CACD,SAAS;EAEX,MAAM,WAAW,MAAM,KAAK,SAAS,GAAG;AACxC,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,4BAA4B;AAC3D,SAAO;;CAGR,MAAM,SAAS,IAAsC;EACpD,MAAM,MAAM,MAAM,KAAK,GACrB,WAAW,oBA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