@kinloom/worker 0.0.0-stage → 0.1.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.
@@ -0,0 +1,769 @@
1
+ import { AgentTokenScopeSchema, asRevisionId, asSha256Hex, AuthorTypeSchema, computeEntityDiff, EntityTypeSchema, parseEntityPayload, resolveEffectiveLiving, RevisionActionSchema, UserRoleSchema, } from '@kinloom/core';
2
+ function parseJsonObject(raw) {
3
+ const parsed = JSON.parse(raw);
4
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
5
+ throw new Error('Stored entity JSON must be a plain object.');
6
+ }
7
+ return parsed;
8
+ }
9
+ function parseNonKinshipEntityType(raw) {
10
+ const parsed = EntityTypeSchema.parse(raw);
11
+ if (parsed === 'kinship_edge') {
12
+ throw new Error('Unexpected kinship_edge row inside entities table.');
13
+ }
14
+ return parsed;
15
+ }
16
+ function mapEntityRow(row) {
17
+ return {
18
+ entity_type: parseNonKinshipEntityType(row.entity_type),
19
+ entity_id: row.entity_id,
20
+ slug: row.slug,
21
+ data: parseJsonObject(row.data_json),
22
+ current_revision_id: asRevisionId(row.current_revision_id),
23
+ has_primary_source: row.has_primary_source !== 0,
24
+ deleted_at: row.deleted_at,
25
+ updated_at: row.updated_at,
26
+ };
27
+ }
28
+ function mapKinshipRow(row) {
29
+ const edge = parseEntityPayload('kinship_edge', {
30
+ from: row.from_person_id,
31
+ to: row.to_person_id,
32
+ relation: row.relation,
33
+ ...(row.family_xref !== null ? { family_xref: row.family_xref } : {}),
34
+ });
35
+ return {
36
+ edge_id: row.edge_id,
37
+ edge,
38
+ current_revision_id: asRevisionId(row.current_revision_id),
39
+ deleted_at: row.deleted_at,
40
+ updated_at: row.updated_at,
41
+ };
42
+ }
43
+ function mapRevisionRow(row) {
44
+ return {
45
+ revision_id: asRevisionId(row.revision_id),
46
+ batch_id: row.batch_id,
47
+ entity_type: EntityTypeSchema.parse(row.entity_type),
48
+ entity_id: row.entity_id,
49
+ parent_revision_id: row.parent_revision_id,
50
+ action: RevisionActionSchema.parse(row.action),
51
+ reverted_revision_id: row.reverted_revision_id,
52
+ author_id: row.author_id,
53
+ author_name: row.author_name,
54
+ author_type: AuthorTypeSchema.parse(row.author_type),
55
+ summary: row.summary,
56
+ has_primary_source: row.has_primary_source !== 0,
57
+ before_json: row.before_json !== null ? parseJsonObject(row.before_json) : null,
58
+ after_json: row.after_json !== null ? parseJsonObject(row.after_json) : null,
59
+ created_at: row.created_at,
60
+ };
61
+ }
62
+ function mapTalkRow(row) {
63
+ return {
64
+ comment_id: row.comment_id,
65
+ entity_type: EntityTypeSchema.parse(row.entity_type),
66
+ entity_id: row.entity_id,
67
+ author_id: row.author_id,
68
+ author_name: row.author_name,
69
+ body_md: row.body_md,
70
+ created_at: row.created_at,
71
+ edited_at: row.edited_at,
72
+ deleted_at: row.deleted_at,
73
+ };
74
+ }
75
+ function mapUserRow(row) {
76
+ return {
77
+ email: row.email,
78
+ display_name: row.display_name,
79
+ role: UserRoleSchema.parse(row.role),
80
+ added_by: row.added_by,
81
+ added_at: row.added_at,
82
+ last_login_at: row.last_login_at,
83
+ };
84
+ }
85
+ function mapInviteRow(row) {
86
+ return {
87
+ token: row.token,
88
+ label: row.label,
89
+ created_by: row.created_by,
90
+ created_at: row.created_at,
91
+ expires_at: row.expires_at,
92
+ revoked_at: row.revoked_at,
93
+ uses: row.uses,
94
+ last_used_at: row.last_used_at,
95
+ };
96
+ }
97
+ function mapMagicLinkRow(row) {
98
+ return {
99
+ token_hash: asSha256Hex(row.token_hash),
100
+ email: row.email,
101
+ invite_token: row.invite_token,
102
+ expires_at: row.expires_at,
103
+ used_at: row.used_at,
104
+ };
105
+ }
106
+ function mapAgentTokenRow(row) {
107
+ return {
108
+ token_id: row.token_id,
109
+ token_hash: asSha256Hex(row.token_hash),
110
+ label: row.label,
111
+ scope: AgentTokenScopeSchema.parse(row.scope),
112
+ created_by: row.created_by,
113
+ created_at: row.created_at,
114
+ revoked_at: row.revoked_at,
115
+ };
116
+ }
117
+ function entityCompositeKey(entityType, entityId) {
118
+ return `${entityType}:${entityId}`;
119
+ }
120
+ function rowToEntityPayload(row) {
121
+ if ('edge' in row) {
122
+ return structuredClone(row.edge);
123
+ }
124
+ return structuredClone(row.data);
125
+ }
126
+ function isSqliteConstraintError(error) {
127
+ const message = error instanceof Error ? error.message : String(error);
128
+ return (message.includes('SQLITE_CONSTRAINT') ||
129
+ message.includes('CHECK constraint failed') ||
130
+ message.includes('UNIQUE constraint failed') ||
131
+ message.includes('PRIMARY KEY constraint failed'));
132
+ }
133
+ function resolveSlugForOp(op) {
134
+ if (op.slug !== undefined) {
135
+ return { updateSlug: true, value: op.slug };
136
+ }
137
+ if (op.after_json && typeof op.after_json.slug === 'string') {
138
+ return { updateSlug: true, value: op.after_json.slug };
139
+ }
140
+ return { updateSlug: false, value: null };
141
+ }
142
+ /**
143
+ * Cloudflare D1 implementation of ArchiveRepository.
144
+ * Enforces zero-N+1 snapshot loading and mathematically atomic DB.batch() optimistic concurrency.
145
+ */
146
+ export class D1ArchiveRepository {
147
+ db;
148
+ privacyConfig;
149
+ constructor(db, options) {
150
+ this.db = db;
151
+ this.privacyConfig = options?.privacyConfig;
152
+ }
153
+ async getHeadRevisionId() {
154
+ const row = await this.db
155
+ .prepare('SELECT COALESCE(MAX(revision_id), 0) AS head_revision_id FROM revisions')
156
+ .first();
157
+ return asRevisionId(row?.head_revision_id ?? 0);
158
+ }
159
+ async getEntity(entityType, entityId) {
160
+ if (entityType === 'kinship_edge') {
161
+ const row = await this.db
162
+ .prepare(`SELECT edge_id, from_person_id, to_person_id, relation, family_xref,
163
+ current_revision_id, deleted_at, updated_at
164
+ FROM kinship_edges
165
+ WHERE edge_id = ?`)
166
+ .bind(entityId)
167
+ .first();
168
+ return row ? mapKinshipRow(row) : null;
169
+ }
170
+ const row = await this.db
171
+ .prepare(`SELECT entity_type, entity_id, slug, data_json, current_revision_id,
172
+ has_primary_source, deleted_at, updated_at
173
+ FROM entities
174
+ WHERE entity_type = ? AND entity_id = ?`)
175
+ .bind(entityType, entityId)
176
+ .first();
177
+ return row ? mapEntityRow(row) : null;
178
+ }
179
+ async getLivingPersonIds() {
180
+ const result = await this.db
181
+ .prepare(`SELECT entity_id, data_json
182
+ FROM entities
183
+ WHERE entity_type = 'person' AND deleted_at IS NULL`)
184
+ .all();
185
+ const living = new Set();
186
+ for (const row of result.results) {
187
+ const parsed = parseEntityPayload('person', parseJsonObject(row.data_json));
188
+ if (resolveEffectiveLiving(parsed, this.privacyConfig)) {
189
+ living.add(row.entity_id);
190
+ }
191
+ }
192
+ return living;
193
+ }
194
+ async loadActiveSnapshot() {
195
+ const [entitiesRes, kinshipRes, headRes] = await this.db.batch([
196
+ this.db.prepare(`SELECT entity_type, entity_id, slug, data_json, current_revision_id,
197
+ has_primary_source, deleted_at, updated_at
198
+ FROM entities
199
+ WHERE deleted_at IS NULL
200
+ ORDER BY entity_type, entity_id`),
201
+ this.db.prepare(`SELECT edge_id, from_person_id, to_person_id, relation, family_xref,
202
+ current_revision_id, deleted_at, updated_at
203
+ FROM kinship_edges
204
+ WHERE deleted_at IS NULL`),
205
+ this.db.prepare('SELECT COALESCE(MAX(revision_id), 0) AS head_revision_id FROM revisions'),
206
+ ]);
207
+ const entities = entitiesRes.results.map(mapEntityRow);
208
+ const kinship = kinshipRes.results
209
+ .map(mapKinshipRow)
210
+ .toSorted((a, b) => a.edge_id.localeCompare(b.edge_id));
211
+ const headRow = headRes.results[0];
212
+ return {
213
+ head_revision_id: asRevisionId(headRow?.head_revision_id ?? 0),
214
+ entities,
215
+ kinship,
216
+ };
217
+ }
218
+ async commitAtomicMutations(params) {
219
+ if (params.operations.length === 0) {
220
+ return {
221
+ kind: 'committed',
222
+ head_revision_id: await this.getHeadRevisionId(),
223
+ revisions: [],
224
+ };
225
+ }
226
+ const statements = [];
227
+ const revisionResultIndices = [];
228
+ const mutatedInBatch = new Set();
229
+ for (const op of params.operations) {
230
+ const key = entityCompositeKey(op.entity_type, op.entity_id);
231
+ const alreadyMutatedInBatch = mutatedInBatch.has(key);
232
+ if (op.action !== 'create' && op.expected_parent_revision_id === null && !alreadyMutatedInBatch) {
233
+ return this.buildConflictForOp(op, params.nowIso);
234
+ }
235
+ const revStmt = this.buildRevisionInsertStatement({
236
+ op,
237
+ batchId: params.batch_id,
238
+ author: params.author,
239
+ nowIso: params.nowIso,
240
+ alreadyMutatedInBatch,
241
+ });
242
+ revisionResultIndices.push(statements.length);
243
+ statements.push(revStmt);
244
+ const entityStmt = this.buildEntityMutationStatement(op, params.nowIso);
245
+ statements.push(entityStmt);
246
+ mutatedInBatch.add(key);
247
+ }
248
+ try {
249
+ const results = await this.db.batch(statements);
250
+ const committedRevisions = [];
251
+ for (const idx of revisionResultIndices) {
252
+ const revRows = results[idx]?.results;
253
+ const revRow = revRows?.[0];
254
+ if (!revRow) {
255
+ throw new Error('D1 revision insert did not return the inserted revision row.');
256
+ }
257
+ committedRevisions.push(mapRevisionRow(revRow));
258
+ }
259
+ const lastRevision = committedRevisions[committedRevisions.length - 1];
260
+ return {
261
+ kind: 'committed',
262
+ head_revision_id: asRevisionId(lastRevision.revision_id),
263
+ revisions: committedRevisions,
264
+ };
265
+ }
266
+ catch (error) {
267
+ if (!isSqliteConstraintError(error)) {
268
+ throw error;
269
+ }
270
+ return this.resolveConstraintConflict(params.operations, params.nowIso, error);
271
+ }
272
+ }
273
+ buildRevisionInsertStatement(params) {
274
+ const { op, batchId, author, nowIso, alreadyMutatedInBatch } = params;
275
+ const beforeJson = op.before_json !== null ? JSON.stringify(op.before_json) : null;
276
+ const afterJson = op.after_json !== null ? JSON.stringify(op.after_json) : null;
277
+ const hasPrimary = op.has_primary_source ? 1 : 0;
278
+ const revertedRevId = op.reverted_revision_id ?? null;
279
+ if (op.action === 'create') {
280
+ return this.db
281
+ .prepare(`INSERT INTO revisions (
282
+ batch_id, entity_type, entity_id, parent_revision_id, action,
283
+ reverted_revision_id, author_id, author_name, author_type,
284
+ summary, has_primary_source, before_json, after_json, created_at
285
+ ) VALUES (?, ?, ?, NULL, 'create', ?, ?, ?, ?, ?, ?, ?, ?, ?)
286
+ RETURNING revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
287
+ reverted_revision_id, author_id, author_name, author_type,
288
+ summary, has_primary_source, before_json, after_json, created_at`)
289
+ .bind(batchId, op.entity_type, op.entity_id, revertedRevId, author.author_id, author.author_name, author.author_type, op.summary, hasPrimary, beforeJson, afterJson, nowIso);
290
+ }
291
+ const lockWhere = this.buildLockWhereClause(op, alreadyMutatedInBatch);
292
+ if (op.action === 'restore') {
293
+ // Guard restore atomically through the action CHECK constraint so stale or active rows roll back DB.batch().
294
+ return this.db
295
+ .prepare(`INSERT INTO revisions (
296
+ batch_id, entity_type, entity_id, parent_revision_id, action,
297
+ reverted_revision_id, author_id, author_name, author_type,
298
+ summary, has_primary_source, before_json, after_json, created_at
299
+ ) VALUES (
300
+ ?, ?, ?,
301
+ (SELECT current_revision_id FROM ${lockWhere.table} WHERE ${lockWhere.sql}),
302
+ CASE
303
+ WHEN EXISTS (SELECT 1 FROM ${lockWhere.table} WHERE ${lockWhere.sql}) THEN 'restore'
304
+ ELSE 'invalid_restore_lock'
305
+ END,
306
+ ?, ?, ?, ?, ?, ?, ?, ?, ?
307
+ )
308
+ RETURNING revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
309
+ reverted_revision_id, author_id, author_name, author_type,
310
+ summary, has_primary_source, before_json, after_json, created_at`)
311
+ .bind(batchId, op.entity_type, op.entity_id, ...lockWhere.bindings, ...lockWhere.bindings, revertedRevId, author.author_id, author.author_name, author.author_type, op.summary, hasPrimary, beforeJson, afterJson, nowIso);
312
+ }
313
+ // update, delete, and revert rely on CHECK (action IN ('create', 'restore') OR parent_revision_id IS NOT NULL).
314
+ return this.db
315
+ .prepare(`INSERT INTO revisions (
316
+ batch_id, entity_type, entity_id, parent_revision_id, action,
317
+ reverted_revision_id, author_id, author_name, author_type,
318
+ summary, has_primary_source, before_json, after_json, created_at
319
+ ) VALUES (
320
+ ?, ?, ?,
321
+ (SELECT current_revision_id FROM ${lockWhere.table} WHERE ${lockWhere.sql}),
322
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
323
+ )
324
+ RETURNING revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
325
+ reverted_revision_id, author_id, author_name, author_type,
326
+ summary, has_primary_source, before_json, after_json, created_at`)
327
+ .bind(batchId, op.entity_type, op.entity_id, ...lockWhere.bindings, op.action, revertedRevId, author.author_id, author.author_name, author.author_type, op.summary, hasPrimary, beforeJson, afterJson, nowIso);
328
+ }
329
+ buildLockWhereClause(op, alreadyMutatedInBatch) {
330
+ const conditions = [];
331
+ const bindings = [];
332
+ if (op.entity_type === 'kinship_edge') {
333
+ conditions.push('edge_id = ?');
334
+ bindings.push(op.entity_id);
335
+ }
336
+ else {
337
+ conditions.push('entity_type = ?', 'entity_id = ?');
338
+ bindings.push(op.entity_type, op.entity_id);
339
+ }
340
+ if (op.expected_parent_revision_id !== null) {
341
+ conditions.push('current_revision_id = ?');
342
+ bindings.push(op.expected_parent_revision_id);
343
+ }
344
+ else if (!alreadyMutatedInBatch) {
345
+ conditions.push('1 = 0');
346
+ }
347
+ if (op.action === 'update' || op.action === 'delete') {
348
+ conditions.push('deleted_at IS NULL');
349
+ }
350
+ else if (op.action === 'restore') {
351
+ conditions.push('deleted_at IS NOT NULL');
352
+ }
353
+ return {
354
+ table: op.entity_type === 'kinship_edge' ? 'kinship_edges' : 'entities',
355
+ sql: conditions.join(' AND '),
356
+ bindings,
357
+ };
358
+ }
359
+ buildEntityMutationStatement(op, nowIso) {
360
+ const isSoftDelete = op.soft_delete === true || op.action === 'delete' || op.after_json === null;
361
+ const deletedAt = isSoftDelete ? nowIso : null;
362
+ if (op.entity_type === 'kinship_edge') {
363
+ if (op.action === 'create') {
364
+ if (!op.after_json) {
365
+ throw new Error('Create kinship_edge operation requires after_json.');
366
+ }
367
+ const edge = parseEntityPayload('kinship_edge', op.after_json);
368
+ return this.db
369
+ .prepare(`INSERT INTO kinship_edges (
370
+ edge_id, from_person_id, to_person_id, relation, family_xref,
371
+ current_revision_id, deleted_at, updated_at
372
+ ) VALUES (?, ?, ?, ?, ?, last_insert_rowid(), ?, ?)`)
373
+ .bind(op.entity_id, edge.from, edge.to, edge.relation, edge.family_xref ?? null, deletedAt, nowIso);
374
+ }
375
+ if (op.after_json !== null) {
376
+ const edge = parseEntityPayload('kinship_edge', op.after_json);
377
+ return this.db
378
+ .prepare(`UPDATE kinship_edges
379
+ SET from_person_id = ?, to_person_id = ?, relation = ?, family_xref = ?,
380
+ current_revision_id = last_insert_rowid(), deleted_at = ?, updated_at = ?
381
+ WHERE edge_id = ?`)
382
+ .bind(edge.from, edge.to, edge.relation, edge.family_xref ?? null, deletedAt, nowIso, op.entity_id);
383
+ }
384
+ return this.db
385
+ .prepare(`UPDATE kinship_edges
386
+ SET current_revision_id = last_insert_rowid(), deleted_at = ?, updated_at = ?
387
+ WHERE edge_id = ?`)
388
+ .bind(deletedAt, nowIso, op.entity_id);
389
+ }
390
+ const hasPrimary = op.has_primary_source ? 1 : 0;
391
+ if (op.action === 'create') {
392
+ if (!op.after_json) {
393
+ throw new Error(`Create ${op.entity_type} operation requires after_json.`);
394
+ }
395
+ const slugInfo = resolveSlugForOp(op);
396
+ return this.db
397
+ .prepare(`INSERT INTO entities (
398
+ entity_type, entity_id, slug, data_json, current_revision_id,
399
+ has_primary_source, deleted_at, updated_at
400
+ ) VALUES (?, ?, ?, ?, last_insert_rowid(), ?, ?, ?)`)
401
+ .bind(op.entity_type, op.entity_id, slugInfo.value, JSON.stringify(op.after_json), hasPrimary, deletedAt, nowIso);
402
+ }
403
+ if (op.after_json !== null) {
404
+ const slugInfo = resolveSlugForOp(op);
405
+ if (slugInfo.updateSlug) {
406
+ return this.db
407
+ .prepare(`UPDATE entities
408
+ SET slug = ?, data_json = ?, current_revision_id = last_insert_rowid(),
409
+ has_primary_source = ?, deleted_at = ?, updated_at = ?
410
+ WHERE entity_type = ? AND entity_id = ?`)
411
+ .bind(slugInfo.value, JSON.stringify(op.after_json), hasPrimary, deletedAt, nowIso, op.entity_type, op.entity_id);
412
+ }
413
+ return this.db
414
+ .prepare(`UPDATE entities
415
+ SET data_json = ?, current_revision_id = last_insert_rowid(),
416
+ has_primary_source = ?, deleted_at = ?, updated_at = ?
417
+ WHERE entity_type = ? AND entity_id = ?`)
418
+ .bind(JSON.stringify(op.after_json), hasPrimary, deletedAt, nowIso, op.entity_type, op.entity_id);
419
+ }
420
+ return this.db
421
+ .prepare(`UPDATE entities
422
+ SET current_revision_id = last_insert_rowid(),
423
+ has_primary_source = ?, deleted_at = ?, updated_at = ?
424
+ WHERE entity_type = ? AND entity_id = ?`)
425
+ .bind(hasPrimary, deletedAt, nowIso, op.entity_type, op.entity_id);
426
+ }
427
+ async resolveConstraintConflict(operations, nowIso, originalError) {
428
+ const seenInBatch = new Set();
429
+ for (const op of operations) {
430
+ const key = entityCompositeKey(op.entity_type, op.entity_id);
431
+ const alreadySeen = seenInBatch.has(key);
432
+ const existing = await this.getEntity(op.entity_type, op.entity_id);
433
+ if (op.action === 'create') {
434
+ if (existing !== null || alreadySeen) {
435
+ return this.buildConflictFromExisting(op, existing, nowIso);
436
+ }
437
+ seenInBatch.add(key);
438
+ continue;
439
+ }
440
+ if (alreadySeen && op.expected_parent_revision_id === null) {
441
+ continue;
442
+ }
443
+ if (existing === null) {
444
+ return this.buildConflictFromExisting(op, null, nowIso);
445
+ }
446
+ if (op.expected_parent_revision_id === null ||
447
+ existing.current_revision_id !== op.expected_parent_revision_id) {
448
+ return this.buildConflictFromExisting(op, existing, nowIso);
449
+ }
450
+ if ((op.action === 'update' || op.action === 'delete') && existing.deleted_at !== null) {
451
+ return this.buildConflictFromExisting(op, existing, nowIso);
452
+ }
453
+ if (op.action === 'restore' && existing.deleted_at === null) {
454
+ return this.buildConflictFromExisting(op, existing, nowIso);
455
+ }
456
+ seenInBatch.add(key);
457
+ }
458
+ // Fallback for unique secondary-index conflict (such as duplicate active slug or kinship edge)
459
+ const fallbackOp = operations[0];
460
+ if (fallbackOp) {
461
+ const existing = await this.getEntity(fallbackOp.entity_type, fallbackOp.entity_id);
462
+ return this.buildConflictFromExisting(fallbackOp, existing, nowIso);
463
+ }
464
+ throw originalError;
465
+ }
466
+ async buildConflictForOp(op, nowIso) {
467
+ const existing = await this.getEntity(op.entity_type, op.entity_id);
468
+ return this.buildConflictFromExisting(op, existing, nowIso);
469
+ }
470
+ async buildConflictFromExisting(op, existing, nowIso) {
471
+ if (existing === null) {
472
+ return {
473
+ kind: 'conflict',
474
+ entity_type: op.entity_type,
475
+ entity_id: op.entity_id,
476
+ expected_parent_revision_id: op.expected_parent_revision_id,
477
+ server_revision_id: asRevisionId(0),
478
+ server_entity: null,
479
+ server_deleted_at: null,
480
+ last_author_name: 'None',
481
+ last_updated_at: nowIso,
482
+ diff: computeEntityDiff(null, op.after_json),
483
+ };
484
+ }
485
+ const lastRev = await this.db
486
+ .prepare(`SELECT author_name
487
+ FROM revisions
488
+ WHERE entity_type = ? AND entity_id = ?
489
+ ORDER BY revision_id DESC
490
+ LIMIT 1`)
491
+ .bind(op.entity_type, op.entity_id)
492
+ .first();
493
+ const serverEntity = existing.deleted_at === null ? rowToEntityPayload(existing) : null;
494
+ return {
495
+ kind: 'conflict',
496
+ entity_type: op.entity_type,
497
+ entity_id: op.entity_id,
498
+ expected_parent_revision_id: op.expected_parent_revision_id,
499
+ server_revision_id: existing.current_revision_id,
500
+ server_entity: serverEntity,
501
+ server_deleted_at: existing.deleted_at,
502
+ last_author_name: lastRev?.author_name ?? 'Unknown editor',
503
+ last_updated_at: existing.updated_at,
504
+ diff: computeEntityDiff(serverEntity, op.after_json),
505
+ };
506
+ }
507
+ async listRevisions(query) {
508
+ const limit = Math.min(200, Math.max(1, query.limit ?? 50));
509
+ const conditions = [];
510
+ const bindings = [];
511
+ if (query.entity_type) {
512
+ conditions.push('entity_type = ?');
513
+ bindings.push(query.entity_type);
514
+ }
515
+ if (query.entity_id) {
516
+ conditions.push('entity_id = ?');
517
+ bindings.push(query.entity_id);
518
+ }
519
+ if (query.batch_id) {
520
+ conditions.push('batch_id = ? AND batch_id IS NOT NULL');
521
+ bindings.push(query.batch_id);
522
+ }
523
+ if (query.author_type) {
524
+ conditions.push('author_type = ?');
525
+ bindings.push(query.author_type);
526
+ }
527
+ if (query.cursor !== undefined) {
528
+ conditions.push('revision_id < ?');
529
+ bindings.push(query.cursor);
530
+ }
531
+ const whereSql = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
532
+ const res = await this.db
533
+ .prepare(`SELECT revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
534
+ reverted_revision_id, author_id, author_name, author_type,
535
+ summary, has_primary_source, before_json, after_json, created_at
536
+ FROM revisions
537
+ ${whereSql}
538
+ ORDER BY revision_id DESC
539
+ LIMIT ?`)
540
+ .bind(...bindings, limit + 1)
541
+ .all();
542
+ const hasMore = res.results.length > limit;
543
+ const sliced = hasMore ? res.results.slice(0, limit) : res.results;
544
+ const items = sliced.map(mapRevisionRow);
545
+ const lastItem = items[items.length - 1];
546
+ return {
547
+ items,
548
+ next_cursor: hasMore && lastItem ? asRevisionId(lastItem.revision_id) : null,
549
+ };
550
+ }
551
+ async getRevisionById(revisionId) {
552
+ const row = await this.db
553
+ .prepare(`SELECT revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
554
+ reverted_revision_id, author_id, author_name, author_type,
555
+ summary, has_primary_source, before_json, after_json, created_at
556
+ FROM revisions
557
+ WHERE revision_id = ?`)
558
+ .bind(revisionId)
559
+ .first();
560
+ return row ? mapRevisionRow(row) : null;
561
+ }
562
+ async getRevisionsByBatch(batchId) {
563
+ const res = await this.db
564
+ .prepare(`SELECT revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
565
+ reverted_revision_id, author_id, author_name, author_type,
566
+ summary, has_primary_source, before_json, after_json, created_at
567
+ FROM revisions
568
+ WHERE batch_id = ? AND batch_id IS NOT NULL
569
+ ORDER BY revision_id ASC`)
570
+ .bind(batchId)
571
+ .all();
572
+ return res.results.map(mapRevisionRow);
573
+ }
574
+ async listTalkComments(entityType, entityId) {
575
+ const res = await this.db
576
+ .prepare(`SELECT comment_id, entity_type, entity_id, author_id, author_name,
577
+ body_md, created_at, edited_at, deleted_at
578
+ FROM talk_comments
579
+ WHERE entity_type = ? AND entity_id = ? AND deleted_at IS NULL
580
+ ORDER BY comment_id ASC`)
581
+ .bind(entityType, entityId)
582
+ .all();
583
+ return res.results.map(mapTalkRow);
584
+ }
585
+ async insertTalkComment(input) {
586
+ const row = await this.db
587
+ .prepare(`INSERT INTO talk_comments (
588
+ entity_type, entity_id, author_id, author_name, body_md, created_at
589
+ ) VALUES (?, ?, ?, ?, ?, ?)
590
+ RETURNING comment_id, entity_type, entity_id, author_id, author_name,
591
+ body_md, created_at, edited_at, deleted_at`)
592
+ .bind(input.entity_type, input.entity_id, input.author_id, input.author_name, input.body_md, input.created_at)
593
+ .first();
594
+ if (!row) {
595
+ throw new Error('Failed to insert talk comment.');
596
+ }
597
+ return mapTalkRow(row);
598
+ }
599
+ async softDeleteTalkComment(commentId, deletedAt) {
600
+ const res = await this.db
601
+ .prepare(`UPDATE talk_comments
602
+ SET deleted_at = ?
603
+ WHERE comment_id = ? AND deleted_at IS NULL`)
604
+ .bind(deletedAt, commentId)
605
+ .run();
606
+ return (res.meta.changes ?? 0) > 0;
607
+ }
608
+ async getUser(email) {
609
+ const normalized = email.trim().toLowerCase();
610
+ const row = await this.db
611
+ .prepare(`SELECT email, display_name, role, added_by, added_at, last_login_at
612
+ FROM users
613
+ WHERE email = ?`)
614
+ .bind(normalized)
615
+ .first();
616
+ return row ? mapUserRow(row) : null;
617
+ }
618
+ async listUsers() {
619
+ const res = await this.db
620
+ .prepare(`SELECT email, display_name, role, added_by, added_at, last_login_at
621
+ FROM users
622
+ ORDER BY email ASC`)
623
+ .all();
624
+ return res.results.map(mapUserRow);
625
+ }
626
+ async upsertUser(user) {
627
+ const normalizedEmail = user.email.trim().toLowerCase();
628
+ const row = await this.db
629
+ .prepare(`INSERT INTO users (email, display_name, role, added_by, added_at, last_login_at)
630
+ VALUES (?, ?, ?, ?, ?, ?)
631
+ ON CONFLICT(email) DO UPDATE SET
632
+ display_name = excluded.display_name,
633
+ role = excluded.role,
634
+ added_by = excluded.added_by,
635
+ added_at = excluded.added_at,
636
+ last_login_at = excluded.last_login_at
637
+ RETURNING email, display_name, role, added_by, added_at, last_login_at`)
638
+ .bind(normalizedEmail, user.display_name, user.role, user.added_by, user.added_at, user.last_login_at)
639
+ .first();
640
+ if (!row) {
641
+ throw new Error(`Failed to upsert user '${normalizedEmail}'.`);
642
+ }
643
+ return mapUserRow(row);
644
+ }
645
+ async updateUserRole(email, role) {
646
+ const normalized = email.trim().toLowerCase();
647
+ const row = await this.db
648
+ .prepare(`UPDATE users
649
+ SET role = ?
650
+ WHERE email = ?
651
+ RETURNING email, display_name, role, added_by, added_at, last_login_at`)
652
+ .bind(role, normalized)
653
+ .first();
654
+ return row ? mapUserRow(row) : null;
655
+ }
656
+ async deleteUser(email) {
657
+ const normalized = email.trim().toLowerCase();
658
+ const res = await this.db.prepare('DELETE FROM users WHERE email = ?').bind(normalized).run();
659
+ return (res.meta.changes ?? 0) > 0;
660
+ }
661
+ async touchUserLogin(email, atIso) {
662
+ const normalized = email.trim().toLowerCase();
663
+ await this.db
664
+ .prepare('UPDATE users SET last_login_at = ? WHERE email = ?')
665
+ .bind(atIso, normalized)
666
+ .run();
667
+ }
668
+ async getInvite(token) {
669
+ const row = await this.db
670
+ .prepare(`SELECT token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at
671
+ FROM invites
672
+ WHERE token = ?`)
673
+ .bind(token)
674
+ .first();
675
+ return row ? mapInviteRow(row) : null;
676
+ }
677
+ async listInvites() {
678
+ const res = await this.db
679
+ .prepare(`SELECT token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at
680
+ FROM invites
681
+ ORDER BY created_at DESC`)
682
+ .all();
683
+ return res.results.map(mapInviteRow);
684
+ }
685
+ async createInvite(invite) {
686
+ const row = await this.db
687
+ .prepare(`INSERT INTO invites (
688
+ token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at
689
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
690
+ RETURNING token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at`)
691
+ .bind(invite.token, invite.label, invite.created_by, invite.created_at, invite.expires_at, invite.revoked_at, invite.uses, invite.last_used_at)
692
+ .first();
693
+ if (!row) {
694
+ throw new Error(`Failed to create invite '${invite.token}'.`);
695
+ }
696
+ return mapInviteRow(row);
697
+ }
698
+ async recordInviteUse(token, atIso) {
699
+ await this.db
700
+ .prepare('UPDATE invites SET uses = uses + 1, last_used_at = ? WHERE token = ?')
701
+ .bind(atIso, token)
702
+ .run();
703
+ }
704
+ async revokeInvite(token, atIso) {
705
+ const res = await this.db
706
+ .prepare('UPDATE invites SET revoked_at = ? WHERE token = ? AND revoked_at IS NULL')
707
+ .bind(atIso, token)
708
+ .run();
709
+ return (res.meta.changes ?? 0) > 0;
710
+ }
711
+ async insertMagicLink(record) {
712
+ await this.db
713
+ .prepare(`INSERT INTO magic_links (token_hash, email, invite_token, expires_at, used_at)
714
+ VALUES (?, ?, ?, ?, ?)`)
715
+ .bind(record.token_hash, record.email, record.invite_token, record.expires_at, record.used_at)
716
+ .run();
717
+ }
718
+ async consumeMagicLink(tokenHash, nowIso) {
719
+ // Single atomic UPDATE prevents replay races across concurrent verification requests.
720
+ const row = await this.db
721
+ .prepare(`UPDATE magic_links
722
+ SET used_at = ?
723
+ WHERE token_hash = ?
724
+ AND used_at IS NULL
725
+ AND expires_at > ?
726
+ RETURNING token_hash, email, invite_token, expires_at, used_at`)
727
+ .bind(nowIso, tokenHash, nowIso)
728
+ .first();
729
+ return row ? mapMagicLinkRow(row) : null;
730
+ }
731
+ async findActiveAgentTokenByHash(tokenHash) {
732
+ const row = await this.db
733
+ .prepare(`SELECT token_id, token_hash, label, scope, created_by, created_at, revoked_at
734
+ FROM agent_tokens
735
+ WHERE token_hash = ? AND revoked_at IS NULL`)
736
+ .bind(tokenHash)
737
+ .first();
738
+ return row ? mapAgentTokenRow(row) : null;
739
+ }
740
+ async listAgentTokens() {
741
+ const res = await this.db
742
+ .prepare(`SELECT token_id, token_hash, label, scope, created_by, created_at, revoked_at
743
+ FROM agent_tokens
744
+ ORDER BY created_at DESC`)
745
+ .all();
746
+ return res.results.map(mapAgentTokenRow);
747
+ }
748
+ async createAgentToken(record) {
749
+ const row = await this.db
750
+ .prepare(`INSERT INTO agent_tokens (
751
+ token_id, token_hash, label, scope, created_by, created_at, revoked_at
752
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
753
+ RETURNING token_id, token_hash, label, scope, created_by, created_at, revoked_at`)
754
+ .bind(record.token_id, record.token_hash, record.label, record.scope, record.created_by, record.created_at, record.revoked_at)
755
+ .first();
756
+ if (!row) {
757
+ throw new Error(`Failed to create agent token '${record.token_id}'.`);
758
+ }
759
+ return mapAgentTokenRow(row);
760
+ }
761
+ async revokeAgentToken(tokenId, atIso) {
762
+ const res = await this.db
763
+ .prepare('UPDATE agent_tokens SET revoked_at = ? WHERE token_id = ? AND revoked_at IS NULL')
764
+ .bind(atIso, tokenId)
765
+ .run();
766
+ return (res.meta.changes ?? 0) > 0;
767
+ }
768
+ }
769
+ //# sourceMappingURL=d1Repository.js.map