@kinloom/server 0.0.0-stage → 0.1.1

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.
Files changed (66) hide show
  1. package/dist/adapters/googleOAuthProvider.d.ts +38 -0
  2. package/dist/adapters/googleOAuthProvider.d.ts.map +1 -0
  3. package/dist/adapters/googleOAuthProvider.js +99 -0
  4. package/dist/adapters/googleOAuthProvider.js.map +1 -0
  5. package/dist/adapters/inMemory.d.ts +171 -0
  6. package/dist/adapters/inMemory.d.ts.map +1 -0
  7. package/dist/adapters/inMemory.js +668 -0
  8. package/dist/adapters/inMemory.js.map +1 -0
  9. package/dist/adapters/systemClock.d.ts +16 -0
  10. package/dist/adapters/systemClock.d.ts.map +1 -0
  11. package/dist/adapters/systemClock.js +40 -0
  12. package/dist/adapters/systemClock.js.map +1 -0
  13. package/dist/crypto.d.ts +19 -0
  14. package/dist/crypto.d.ts.map +1 -0
  15. package/dist/crypto.js +159 -0
  16. package/dist/crypto.js.map +1 -0
  17. package/dist/errors.d.ts +13 -0
  18. package/dist/errors.d.ts.map +1 -0
  19. package/dist/errors.js +73 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/http/authMiddleware.d.ts +21 -0
  22. package/dist/http/authMiddleware.d.ts.map +1 -0
  23. package/dist/http/authMiddleware.js +155 -0
  24. package/dist/http/authMiddleware.js.map +1 -0
  25. package/dist/http/router.d.ts +20 -0
  26. package/dist/http/router.d.ts.map +1 -0
  27. package/dist/http/router.js +814 -0
  28. package/dist/http/router.js.map +1 -0
  29. package/dist/http/session.d.ts +71 -0
  30. package/dist/http/session.d.ts.map +1 -0
  31. package/dist/http/session.js +170 -0
  32. package/dist/http/session.js.map +1 -0
  33. package/dist/index.d.ts +17 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +20 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/services/adminService.d.ts +55 -0
  38. package/dist/services/adminService.d.ts.map +1 -0
  39. package/dist/services/adminService.js +168 -0
  40. package/dist/services/adminService.js.map +1 -0
  41. package/dist/services/authService.d.ts +71 -0
  42. package/dist/services/authService.d.ts.map +1 -0
  43. package/dist/services/authService.js +268 -0
  44. package/dist/services/authService.js.map +1 -0
  45. package/dist/services/bundleReadService.d.ts +69 -0
  46. package/dist/services/bundleReadService.d.ts.map +1 -0
  47. package/dist/services/bundleReadService.js +177 -0
  48. package/dist/services/bundleReadService.js.map +1 -0
  49. package/dist/services/mediaService.d.ts +44 -0
  50. package/dist/services/mediaService.d.ts.map +1 -0
  51. package/dist/services/mediaService.js +228 -0
  52. package/dist/services/mediaService.js.map +1 -0
  53. package/dist/services/talkService.d.ts +31 -0
  54. package/dist/services/talkService.d.ts.map +1 -0
  55. package/dist/services/talkService.js +59 -0
  56. package/dist/services/talkService.js.map +1 -0
  57. package/dist/services/wikiWriteService.d.ts +101 -0
  58. package/dist/services/wikiWriteService.d.ts.map +1 -0
  59. package/dist/services/wikiWriteService.js +809 -0
  60. package/dist/services/wikiWriteService.js.map +1 -0
  61. package/dist/testing/adapterContractSuite.d.ts +23 -0
  62. package/dist/testing/adapterContractSuite.d.ts.map +1 -0
  63. package/dist/testing/adapterContractSuite.js +765 -0
  64. package/dist/testing/adapterContractSuite.js.map +1 -0
  65. package/package.json +46 -4
  66. package/README.md +0 -3
@@ -0,0 +1,809 @@
1
+ import { asBatchId, asRevisionId, assertMediaAllowedForPrivacy, BatchSubmissionSchema, computeEntityDiff, deriveKinshipEdgeId, isEditSummaryValid, parseEntityPayload, resolveEffectiveLiving, sanitizeEventForWrite, sanitizePersonForWrite, transitionBatchRevertLifecycle, transitionEntityLifecycle, } from '@kinloom/core';
2
+ import { generateEntityId, readBodyToString } from '../crypto.js';
3
+ import { KinloomHttpError } from '../errors.js';
4
+ const ENTITY_ID_PREFIX = {
5
+ person: 'per',
6
+ event: 'evt',
7
+ place: 'plc',
8
+ source: 'src',
9
+ media: 'med',
10
+ narrative: 'nar',
11
+ };
12
+ function rowToPayload(row) {
13
+ if ('edge' in row) {
14
+ return structuredClone(row.edge);
15
+ }
16
+ return structuredClone(row.data);
17
+ }
18
+ function rowToWorking(row) {
19
+ if (!row) {
20
+ return {
21
+ lifecycle: { kind: 'nonExistent' },
22
+ hasPrimarySource: true,
23
+ slug: null,
24
+ updatedAt: '',
25
+ };
26
+ }
27
+ const payload = rowToPayload(row);
28
+ if (row.deleted_at !== null) {
29
+ return {
30
+ lifecycle: {
31
+ kind: 'softDeleted',
32
+ currentRevisionId: row.current_revision_id,
33
+ lastData: payload,
34
+ deletedAt: row.deleted_at,
35
+ },
36
+ hasPrimarySource: 'edge' in row ? true : row.has_primary_source,
37
+ slug: 'edge' in row ? null : row.slug,
38
+ updatedAt: row.updated_at,
39
+ };
40
+ }
41
+ return {
42
+ lifecycle: {
43
+ kind: 'active',
44
+ currentRevisionId: row.current_revision_id,
45
+ data: payload,
46
+ },
47
+ hasPrimarySource: 'edge' in row ? true : row.has_primary_source,
48
+ slug: 'edge' in row ? null : row.slug,
49
+ updatedAt: row.updated_at,
50
+ };
51
+ }
52
+ function extractSlug(entityType, payload) {
53
+ if (!payload || entityType === 'kinship_edge') {
54
+ return null;
55
+ }
56
+ return typeof payload.slug === 'string' && payload.slug.trim().length > 0
57
+ ? payload.slug.trim()
58
+ : null;
59
+ }
60
+ function compositeKey(entityType, entityId) {
61
+ return `${entityType}:${entityId}`;
62
+ }
63
+ export class WikiWriteService {
64
+ repository;
65
+ bundleCache;
66
+ clock;
67
+ siteConfig;
68
+ plugins;
69
+ onPluginError;
70
+ constructor(deps) {
71
+ this.repository = deps.repository;
72
+ this.bundleCache = deps.bundleCache;
73
+ this.clock = deps.clock;
74
+ this.siteConfig = deps.siteConfig;
75
+ this.plugins = deps.plugins ?? [];
76
+ this.onPluginError = deps.onPluginError;
77
+ }
78
+ async createEntity(params) {
79
+ this.assertSummaryValid(params.summary);
80
+ const { entityId, sanitized } = await this.validateAndSanitizePayload({
81
+ entityType: params.entityType,
82
+ requestedEntityId: params.entityId,
83
+ rawPayload: params.data,
84
+ hasPrimarySource: params.hasPrimarySource,
85
+ });
86
+ const existing = await this.repository.getEntity(params.entityType, entityId);
87
+ if (existing !== null) {
88
+ throw new KinloomHttpError(409, 'ENTITY_EXISTS', existing.deleted_at !== null
89
+ ? `Entity ${params.entityType}/${entityId} is soft-deleted; use restore or revert instead.`
90
+ : `Entity ${params.entityType}/${entityId} already exists.`);
91
+ }
92
+ const op = {
93
+ entity_type: params.entityType,
94
+ entity_id: entityId,
95
+ slug: extractSlug(params.entityType, sanitized),
96
+ action: 'create',
97
+ expected_parent_revision_id: null,
98
+ summary: params.summary.trim(),
99
+ has_primary_source: params.hasPrimarySource,
100
+ before_json: null,
101
+ after_json: sanitized,
102
+ };
103
+ const committed = await this.commitOrThrowConflict({
104
+ batchId: null,
105
+ author: params.author,
106
+ operations: [op],
107
+ });
108
+ const etag = await this.refreshBundleCache(committed.revisions, committed.head_revision_id);
109
+ await this.notifyPlugins(committed.revisions, committed.head_revision_id);
110
+ return {
111
+ entity: sanitized,
112
+ revision: committed.revisions[0],
113
+ etag,
114
+ };
115
+ }
116
+ async updateEntity(params) {
117
+ this.assertSummaryValid(params.summary);
118
+ const existing = await this.repository.getEntity(params.entityType, params.entityId);
119
+ if (existing === null) {
120
+ throw new KinloomHttpError(404, 'NOT_FOUND', `Entity ${params.entityType}/${params.entityId} was not found.`);
121
+ }
122
+ const existingPayload = rowToPayload(existing);
123
+ const mergedRaw = params.merge
124
+ ? { ...existingPayload, ...structuredClone(params.data) }
125
+ : structuredClone(params.data);
126
+ const { sanitized } = await this.validateAndSanitizePayload({
127
+ entityType: params.entityType,
128
+ requestedEntityId: params.entityId,
129
+ rawPayload: mergedRaw,
130
+ hasPrimarySource: params.hasPrimarySource,
131
+ requireIdMatch: true,
132
+ });
133
+ if (existing.deleted_at !== null || existing.current_revision_id !== params.expectedParentRevisionId) {
134
+ throw await this.buildConflictHttpError({
135
+ entityType: params.entityType,
136
+ entityId: params.entityId,
137
+ expectedParentRevisionId: params.expectedParentRevisionId,
138
+ existing,
139
+ candidateAfter: sanitized,
140
+ });
141
+ }
142
+ const op = {
143
+ entity_type: params.entityType,
144
+ entity_id: params.entityId,
145
+ slug: extractSlug(params.entityType, sanitized),
146
+ action: 'update',
147
+ expected_parent_revision_id: params.expectedParentRevisionId,
148
+ summary: params.summary.trim(),
149
+ has_primary_source: params.hasPrimarySource,
150
+ before_json: existingPayload,
151
+ after_json: sanitized,
152
+ };
153
+ const committed = await this.commitOrThrowConflict({
154
+ batchId: null,
155
+ author: params.author,
156
+ operations: [op],
157
+ });
158
+ const etag = await this.refreshBundleCache(committed.revisions, committed.head_revision_id);
159
+ await this.notifyPlugins(committed.revisions, committed.head_revision_id);
160
+ return {
161
+ entity: sanitized,
162
+ revision: committed.revisions[0],
163
+ etag,
164
+ };
165
+ }
166
+ async deleteEntity(params) {
167
+ this.assertSummaryValid(params.summary);
168
+ const existing = await this.repository.getEntity(params.entityType, params.entityId);
169
+ if (existing === null) {
170
+ throw new KinloomHttpError(404, 'NOT_FOUND', `Entity ${params.entityType}/${params.entityId} was not found.`);
171
+ }
172
+ if (existing.deleted_at !== null || existing.current_revision_id !== params.expectedParentRevisionId) {
173
+ throw await this.buildConflictHttpError({
174
+ entityType: params.entityType,
175
+ entityId: params.entityId,
176
+ expectedParentRevisionId: params.expectedParentRevisionId,
177
+ existing,
178
+ candidateAfter: null,
179
+ });
180
+ }
181
+ const beforePayload = rowToPayload(existing);
182
+ const op = {
183
+ entity_type: params.entityType,
184
+ entity_id: params.entityId,
185
+ slug: 'edge' in existing ? null : existing.slug,
186
+ action: 'delete',
187
+ expected_parent_revision_id: params.expectedParentRevisionId,
188
+ summary: params.summary.trim(),
189
+ has_primary_source: 'edge' in existing ? true : existing.has_primary_source,
190
+ before_json: beforePayload,
191
+ after_json: null,
192
+ soft_delete: true,
193
+ };
194
+ const committed = await this.commitOrThrowConflict({
195
+ batchId: null,
196
+ author: params.author,
197
+ operations: [op],
198
+ });
199
+ const etag = await this.refreshBundleCache(committed.revisions, committed.head_revision_id);
200
+ await this.notifyPlugins(committed.revisions, committed.head_revision_id);
201
+ return {
202
+ revision: committed.revisions[0],
203
+ etag,
204
+ };
205
+ }
206
+ async restoreEntity(params) {
207
+ this.assertSummaryValid(params.summary);
208
+ const existing = await this.repository.getEntity(params.entityType, params.entityId);
209
+ if (existing === null) {
210
+ throw new KinloomHttpError(404, 'NOT_FOUND', `Entity ${params.entityType}/${params.entityId} was not found.`);
211
+ }
212
+ const existingPayload = rowToPayload(existing);
213
+ const candidateRaw = params.data
214
+ ? { ...existingPayload, ...structuredClone(params.data) }
215
+ : existingPayload;
216
+ const hasPrimary = 'edge' in existing ? true : existing.has_primary_source;
217
+ const { sanitized } = await this.validateAndSanitizePayload({
218
+ entityType: params.entityType,
219
+ requestedEntityId: params.entityId,
220
+ rawPayload: candidateRaw,
221
+ hasPrimarySource: hasPrimary,
222
+ requireIdMatch: true,
223
+ });
224
+ if (existing.deleted_at === null || existing.current_revision_id !== params.expectedParentRevisionId) {
225
+ throw await this.buildConflictHttpError({
226
+ entityType: params.entityType,
227
+ entityId: params.entityId,
228
+ expectedParentRevisionId: params.expectedParentRevisionId,
229
+ existing,
230
+ candidateAfter: sanitized,
231
+ });
232
+ }
233
+ const op = {
234
+ entity_type: params.entityType,
235
+ entity_id: params.entityId,
236
+ slug: extractSlug(params.entityType, sanitized),
237
+ action: 'restore',
238
+ expected_parent_revision_id: params.expectedParentRevisionId,
239
+ summary: params.summary.trim(),
240
+ has_primary_source: hasPrimary,
241
+ before_json: null,
242
+ after_json: sanitized,
243
+ restore_deleted: true,
244
+ };
245
+ const committed = await this.commitOrThrowConflict({
246
+ batchId: null,
247
+ author: params.author,
248
+ operations: [op],
249
+ });
250
+ const etag = await this.refreshBundleCache(committed.revisions, committed.head_revision_id);
251
+ await this.notifyPlugins(committed.revisions, committed.head_revision_id);
252
+ return {
253
+ entity: sanitized,
254
+ revision: committed.revisions[0],
255
+ etag,
256
+ };
257
+ }
258
+ async revertRevision(params) {
259
+ const targetRev = await this.repository.getRevisionById(params.revisionId);
260
+ if (!targetRev) {
261
+ throw new KinloomHttpError(404, 'REVISION_NOT_FOUND', `Revision r${params.revisionId} was not found.`);
262
+ }
263
+ const existing = await this.repository.getEntity(targetRev.entity_type, targetRev.entity_id);
264
+ const working = rowToWorking(existing);
265
+ const headRev = await this.repository.getHeadRevisionId();
266
+ const outcome = transitionEntityLifecycle(working.lifecycle, {
267
+ type: 'revert',
268
+ targetRevision: targetRev,
269
+ summary: params.summary,
270
+ nowIso: this.clock.nowIso(),
271
+ }, headRev + 1);
272
+ if (!outcome.ok) {
273
+ throw new KinloomHttpError(outcome.status, outcome.status === 409 ? 'OPTIMISTIC_CONFLICT' : 'NOT_FOUND', `Cannot revert revision r${params.revisionId}: ${outcome.code}.`);
274
+ }
275
+ let sanitizedAfter = null;
276
+ if (outcome.revisionInsert.afterJson !== null) {
277
+ const validated = await this.validateAndSanitizePayload({
278
+ entityType: targetRev.entity_type,
279
+ requestedEntityId: targetRev.entity_id,
280
+ rawPayload: outcome.revisionInsert.afterJson,
281
+ hasPrimarySource: targetRev.has_primary_source,
282
+ });
283
+ sanitizedAfter = validated.sanitized;
284
+ }
285
+ const op = {
286
+ entity_type: targetRev.entity_type,
287
+ entity_id: targetRev.entity_id,
288
+ slug: extractSlug(targetRev.entity_type, sanitizedAfter),
289
+ action: 'revert',
290
+ expected_parent_revision_id: existing ? existing.current_revision_id : null,
291
+ reverted_revision_id: asRevisionId(targetRev.revision_id),
292
+ summary: outcome.revisionInsert.summary,
293
+ has_primary_source: targetRev.has_primary_source,
294
+ before_json: outcome.revisionInsert.beforeJson,
295
+ after_json: sanitizedAfter,
296
+ soft_delete: sanitizedAfter === null,
297
+ restore_deleted: working.lifecycle.kind === 'softDeleted' && sanitizedAfter !== null,
298
+ };
299
+ const committed = await this.commitOrThrowConflict({
300
+ batchId: null,
301
+ author: params.author,
302
+ operations: [op],
303
+ });
304
+ const etag = await this.refreshBundleCache(committed.revisions, committed.head_revision_id);
305
+ await this.notifyPlugins(committed.revisions, committed.head_revision_id);
306
+ return {
307
+ revision: committed.revisions[0],
308
+ etag,
309
+ };
310
+ }
311
+ async submitBatch(params) {
312
+ const parsed = BatchSubmissionSchema.parse(params.submission);
313
+ const batchId = asBatchId(parsed.batch_id);
314
+ const nowIso = this.clock.nowIso();
315
+ const livingIds = new Set(await this.repository.getLivingPersonIds());
316
+ const workingEvents = new Map();
317
+ const workingByKey = new Map();
318
+ const lockedInitialByKey = new Set();
319
+ const operations = [];
320
+ let syntheticRev = (await this.repository.getHeadRevisionId()) + 1;
321
+ const getWorking = async (entityType, entityId) => {
322
+ const key = compositeKey(entityType, entityId);
323
+ const cached = workingByKey.get(key);
324
+ if (cached) {
325
+ return cached;
326
+ }
327
+ const row = await this.repository.getEntity(entityType, entityId);
328
+ const loaded = rowToWorking(row);
329
+ workingByKey.set(key, loaded);
330
+ return loaded;
331
+ };
332
+ for (const patch of parsed.patches) {
333
+ const entityType = patch.entity_type;
334
+ const entityId = patch.entity_id;
335
+ const key = compositeKey(entityType, entityId);
336
+ const current = await getWorking(entityType, entityId);
337
+ const alreadyMutatedInBatch = lockedInitialByKey.has(key);
338
+ const summary = (patch.summary ?? parsed.summary).trim();
339
+ this.assertSummaryValid(summary);
340
+ const hasPrimarySource = ('has_primary_source' in patch && patch.has_primary_source !== undefined
341
+ ? patch.has_primary_source
342
+ : parsed.has_primary_source);
343
+ switch (patch.action) {
344
+ case 'create': {
345
+ if (current.lifecycle.kind !== 'nonExistent') {
346
+ throw new KinloomHttpError(409, 'OPTIMISTIC_CONFLICT', `Cannot create ${entityType}/${entityId}: entity already exists or is soft-deleted.`);
347
+ }
348
+ const validated = await this.validateAndSanitizePayload({
349
+ entityType,
350
+ requestedEntityId: entityId,
351
+ rawPayload: patch.data,
352
+ hasPrimarySource,
353
+ livingPersonIdsOverride: livingIds,
354
+ extraEventsById: workingEvents,
355
+ });
356
+ this.updateWorkingPrivacyContext(entityType, validated.entityId, validated.sanitized, livingIds, workingEvents);
357
+ operations.push({
358
+ entity_type: entityType,
359
+ entity_id: validated.entityId,
360
+ slug: extractSlug(entityType, validated.sanitized),
361
+ action: 'create',
362
+ expected_parent_revision_id: null,
363
+ summary,
364
+ has_primary_source: hasPrimarySource,
365
+ before_json: null,
366
+ after_json: validated.sanitized,
367
+ });
368
+ workingByKey.set(compositeKey(entityType, validated.entityId), {
369
+ lifecycle: { kind: 'active', currentRevisionId: syntheticRev, data: validated.sanitized },
370
+ hasPrimarySource,
371
+ slug: extractSlug(entityType, validated.sanitized),
372
+ updatedAt: nowIso,
373
+ });
374
+ lockedInitialByKey.add(compositeKey(entityType, validated.entityId));
375
+ syntheticRev += 1;
376
+ break;
377
+ }
378
+ case 'update': {
379
+ if (current.lifecycle.kind === 'nonExistent') {
380
+ throw new KinloomHttpError(404, 'NOT_FOUND', `Entity ${entityType}/${entityId} was not found.`);
381
+ }
382
+ if (current.lifecycle.kind === 'softDeleted') {
383
+ throw new KinloomHttpError(409, 'OPTIMISTIC_CONFLICT', `Entity ${entityType}/${entityId} is soft-deleted; restore before updating.`);
384
+ }
385
+ const mergedRaw = patch.merge
386
+ ? { ...structuredClone(current.lifecycle.data), ...structuredClone(patch.data) }
387
+ : structuredClone(patch.data);
388
+ const validated = await this.validateAndSanitizePayload({
389
+ entityType,
390
+ requestedEntityId: entityId,
391
+ rawPayload: mergedRaw,
392
+ hasPrimarySource,
393
+ requireIdMatch: true,
394
+ livingPersonIdsOverride: livingIds,
395
+ extraEventsById: workingEvents,
396
+ });
397
+ const expectedParent = alreadyMutatedInBatch
398
+ ? null
399
+ : asRevisionId(patch.parent_revision_id ?? current.lifecycle.currentRevisionId);
400
+ if (!alreadyMutatedInBatch &&
401
+ patch.parent_revision_id !== undefined &&
402
+ patch.parent_revision_id !== current.lifecycle.currentRevisionId) {
403
+ const existingRow = await this.repository.getEntity(entityType, entityId);
404
+ if (existingRow) {
405
+ throw await this.buildConflictHttpError({
406
+ entityType,
407
+ entityId,
408
+ expectedParentRevisionId: asRevisionId(patch.parent_revision_id),
409
+ existing: existingRow,
410
+ candidateAfter: validated.sanitized,
411
+ });
412
+ }
413
+ }
414
+ this.updateWorkingPrivacyContext(entityType, entityId, validated.sanitized, livingIds, workingEvents);
415
+ operations.push({
416
+ entity_type: entityType,
417
+ entity_id: entityId,
418
+ slug: extractSlug(entityType, validated.sanitized),
419
+ action: 'update',
420
+ expected_parent_revision_id: expectedParent,
421
+ summary,
422
+ has_primary_source: hasPrimarySource,
423
+ before_json: structuredClone(current.lifecycle.data),
424
+ after_json: validated.sanitized,
425
+ });
426
+ workingByKey.set(key, {
427
+ lifecycle: { kind: 'active', currentRevisionId: syntheticRev, data: validated.sanitized },
428
+ hasPrimarySource,
429
+ slug: extractSlug(entityType, validated.sanitized),
430
+ updatedAt: nowIso,
431
+ });
432
+ lockedInitialByKey.add(key);
433
+ syntheticRev += 1;
434
+ break;
435
+ }
436
+ case 'delete': {
437
+ if (current.lifecycle.kind === 'nonExistent') {
438
+ throw new KinloomHttpError(404, 'NOT_FOUND', `Entity ${entityType}/${entityId} was not found.`);
439
+ }
440
+ if (current.lifecycle.kind === 'softDeleted') {
441
+ throw new KinloomHttpError(409, 'OPTIMISTIC_CONFLICT', `Entity ${entityType}/${entityId} is already soft-deleted.`);
442
+ }
443
+ const expectedParent = alreadyMutatedInBatch
444
+ ? null
445
+ : asRevisionId(patch.parent_revision_id ?? current.lifecycle.currentRevisionId);
446
+ if (!alreadyMutatedInBatch &&
447
+ patch.parent_revision_id !== undefined &&
448
+ patch.parent_revision_id !== current.lifecycle.currentRevisionId) {
449
+ const existingRow = await this.repository.getEntity(entityType, entityId);
450
+ if (existingRow) {
451
+ throw await this.buildConflictHttpError({
452
+ entityType,
453
+ entityId,
454
+ expectedParentRevisionId: asRevisionId(patch.parent_revision_id),
455
+ existing: existingRow,
456
+ candidateAfter: null,
457
+ });
458
+ }
459
+ }
460
+ if (entityType === 'person') {
461
+ livingIds.delete(entityId);
462
+ }
463
+ operations.push({
464
+ entity_type: entityType,
465
+ entity_id: entityId,
466
+ slug: current.slug,
467
+ action: 'delete',
468
+ expected_parent_revision_id: expectedParent,
469
+ summary,
470
+ has_primary_source: current.hasPrimarySource,
471
+ before_json: structuredClone(current.lifecycle.data),
472
+ after_json: null,
473
+ soft_delete: true,
474
+ });
475
+ workingByKey.set(key, {
476
+ lifecycle: {
477
+ kind: 'softDeleted',
478
+ currentRevisionId: syntheticRev,
479
+ lastData: structuredClone(current.lifecycle.data),
480
+ deletedAt: nowIso,
481
+ },
482
+ hasPrimarySource: current.hasPrimarySource,
483
+ slug: current.slug,
484
+ updatedAt: nowIso,
485
+ });
486
+ lockedInitialByKey.add(key);
487
+ syntheticRev += 1;
488
+ break;
489
+ }
490
+ case 'restore': {
491
+ if (current.lifecycle.kind === 'nonExistent') {
492
+ throw new KinloomHttpError(404, 'NOT_FOUND', `Entity ${entityType}/${entityId} was not found.`);
493
+ }
494
+ if (current.lifecycle.kind !== 'softDeleted') {
495
+ throw new KinloomHttpError(409, 'OPTIMISTIC_CONFLICT', `Entity ${entityType}/${entityId} is not soft-deleted.`);
496
+ }
497
+ const candidateRaw = patch.data
498
+ ? { ...structuredClone(current.lifecycle.lastData), ...structuredClone(patch.data) }
499
+ : structuredClone(current.lifecycle.lastData);
500
+ const validated = await this.validateAndSanitizePayload({
501
+ entityType,
502
+ requestedEntityId: entityId,
503
+ rawPayload: candidateRaw,
504
+ hasPrimarySource: current.hasPrimarySource,
505
+ requireIdMatch: true,
506
+ livingPersonIdsOverride: livingIds,
507
+ extraEventsById: workingEvents,
508
+ });
509
+ const expectedParent = alreadyMutatedInBatch
510
+ ? null
511
+ : asRevisionId(patch.parent_revision_id ?? current.lifecycle.currentRevisionId);
512
+ if (!alreadyMutatedInBatch &&
513
+ patch.parent_revision_id !== undefined &&
514
+ patch.parent_revision_id !== current.lifecycle.currentRevisionId) {
515
+ const existingRow = await this.repository.getEntity(entityType, entityId);
516
+ if (existingRow) {
517
+ throw await this.buildConflictHttpError({
518
+ entityType,
519
+ entityId,
520
+ expectedParentRevisionId: asRevisionId(patch.parent_revision_id),
521
+ existing: existingRow,
522
+ candidateAfter: validated.sanitized,
523
+ });
524
+ }
525
+ }
526
+ this.updateWorkingPrivacyContext(entityType, entityId, validated.sanitized, livingIds, workingEvents);
527
+ operations.push({
528
+ entity_type: entityType,
529
+ entity_id: entityId,
530
+ slug: extractSlug(entityType, validated.sanitized),
531
+ action: 'restore',
532
+ expected_parent_revision_id: expectedParent,
533
+ summary,
534
+ has_primary_source: current.hasPrimarySource,
535
+ before_json: null,
536
+ after_json: validated.sanitized,
537
+ restore_deleted: true,
538
+ });
539
+ workingByKey.set(key, {
540
+ lifecycle: { kind: 'active', currentRevisionId: syntheticRev, data: validated.sanitized },
541
+ hasPrimarySource: current.hasPrimarySource,
542
+ slug: extractSlug(entityType, validated.sanitized),
543
+ updatedAt: nowIso,
544
+ });
545
+ lockedInitialByKey.add(key);
546
+ syntheticRev += 1;
547
+ break;
548
+ }
549
+ default: {
550
+ const _exhaustive = patch;
551
+ throw new Error(`Unhandled patch action: ${String(_exhaustive)}`);
552
+ }
553
+ }
554
+ }
555
+ const committed = await this.commitOrThrowConflict({
556
+ batchId,
557
+ author: params.author,
558
+ operations,
559
+ });
560
+ const etag = await this.refreshBundleCache(committed.revisions, committed.head_revision_id);
561
+ await this.notifyPlugins(committed.revisions, committed.head_revision_id);
562
+ return {
563
+ batch_id: batchId,
564
+ revisions: committed.revisions,
565
+ head_revision_id: committed.head_revision_id,
566
+ etag,
567
+ };
568
+ }
569
+ async revertBatch(params) {
570
+ const batchRevisions = await this.repository.getRevisionsByBatch(params.batchId);
571
+ if (batchRevisions.length === 0) {
572
+ throw new KinloomHttpError(404, 'BATCH_NOT_FOUND', `Batch ${params.batchId} was not found.`);
573
+ }
574
+ const currentStatesByKey = new Map();
575
+ const initialRevisionByKey = new Map();
576
+ const revById = new Map();
577
+ for (const rev of batchRevisions) {
578
+ revById.set(rev.revision_id, rev);
579
+ const key = compositeKey(rev.entity_type, rev.entity_id);
580
+ if (!currentStatesByKey.has(key)) {
581
+ const row = await this.repository.getEntity(rev.entity_type, rev.entity_id);
582
+ const working = rowToWorking(row);
583
+ currentStatesByKey.set(key, working.lifecycle);
584
+ if (row) {
585
+ initialRevisionByKey.set(key, row.current_revision_id);
586
+ }
587
+ }
588
+ }
589
+ const headRev = await this.repository.getHeadRevisionId();
590
+ const outcome = transitionBatchRevertLifecycle(currentStatesByKey, batchRevisions, headRev + 1, {
591
+ nowIso: this.clock.nowIso(),
592
+ summaryPrefix: params.summary?.trim() || `Revert batch ${params.batchId}`,
593
+ });
594
+ if (!outcome.ok) {
595
+ throw new KinloomHttpError(outcome.status, outcome.status === 409 ? 'OPTIMISTIC_CONFLICT' : 'NOT_FOUND', `Cannot revert batch ${params.batchId} at revision r${outcome.failedRevisionId}: ${outcome.code}.`);
596
+ }
597
+ const livingIds = new Set(await this.repository.getLivingPersonIds());
598
+ const workingEvents = new Map();
599
+ const lockedInitialByKey = new Set();
600
+ const operations = [];
601
+ for (const step of outcome.steps) {
602
+ const targetRev = revById.get(step.revisionInsert.revertedRevisionId ?? -1);
603
+ const hasPrimarySource = targetRev?.has_primary_source ?? true;
604
+ let sanitizedAfter = null;
605
+ if (step.revisionInsert.afterJson !== null) {
606
+ const validated = await this.validateAndSanitizePayload({
607
+ entityType: step.entityType,
608
+ requestedEntityId: step.entityId,
609
+ rawPayload: step.revisionInsert.afterJson,
610
+ hasPrimarySource,
611
+ livingPersonIdsOverride: livingIds,
612
+ extraEventsById: workingEvents,
613
+ });
614
+ sanitizedAfter = validated.sanitized;
615
+ this.updateWorkingPrivacyContext(step.entityType, step.entityId, sanitizedAfter, livingIds, workingEvents);
616
+ }
617
+ else if (step.entityType === 'person') {
618
+ livingIds.delete(step.entityId);
619
+ }
620
+ const alreadyLocked = lockedInitialByKey.has(step.entityKey);
621
+ const expectedParent = alreadyLocked
622
+ ? null
623
+ : (initialRevisionByKey.get(step.entityKey) ?? null);
624
+ lockedInitialByKey.add(step.entityKey);
625
+ operations.push({
626
+ entity_type: step.entityType,
627
+ entity_id: step.entityId,
628
+ slug: extractSlug(step.entityType, sanitizedAfter),
629
+ action: 'revert',
630
+ expected_parent_revision_id: expectedParent,
631
+ reverted_revision_id: step.revisionInsert.revertedRevisionId !== null
632
+ ? asRevisionId(step.revisionInsert.revertedRevisionId)
633
+ : null,
634
+ summary: step.revisionInsert.summary,
635
+ has_primary_source: hasPrimarySource,
636
+ before_json: step.revisionInsert.beforeJson,
637
+ after_json: sanitizedAfter,
638
+ soft_delete: sanitizedAfter === null,
639
+ restore_deleted: step.revisionInsert.beforeJson === null && sanitizedAfter !== null,
640
+ });
641
+ }
642
+ const committed = await this.commitOrThrowConflict({
643
+ batchId: null,
644
+ author: params.author,
645
+ operations,
646
+ });
647
+ const etag = await this.refreshBundleCache(committed.revisions, committed.head_revision_id);
648
+ await this.notifyPlugins(committed.revisions, committed.head_revision_id);
649
+ return {
650
+ reverted_batch_id: params.batchId,
651
+ revisions: committed.revisions,
652
+ head_revision_id: committed.head_revision_id,
653
+ etag,
654
+ };
655
+ }
656
+ assertSummaryValid(summary) {
657
+ if (!isEditSummaryValid(summary)) {
658
+ throw new KinloomHttpError(400, 'VALIDATION_ERROR', 'Edit summary must be at least 3 characters.');
659
+ }
660
+ }
661
+ updateWorkingPrivacyContext(entityType, entityId, sanitized, livingIds, workingEvents) {
662
+ if (entityType === 'person') {
663
+ const parsed = parseEntityPayload('person', sanitized);
664
+ if (resolveEffectiveLiving(parsed, this.siteConfig.privacy)) {
665
+ livingIds.add(entityId);
666
+ }
667
+ else {
668
+ livingIds.delete(entityId);
669
+ }
670
+ }
671
+ else if (entityType === 'event') {
672
+ const parsed = parseEntityPayload('event', sanitized);
673
+ workingEvents.set(entityId, { id: parsed.id, participants: parsed.participants });
674
+ }
675
+ }
676
+ async validateAndSanitizePayload(params) {
677
+ const candidate = structuredClone(params.rawPayload);
678
+ if (params.entityType === 'kinship_edge') {
679
+ const parsedEdge = parseEntityPayload('kinship_edge', candidate);
680
+ const derivedId = deriveKinshipEdgeId(parsedEdge);
681
+ if (params.requireIdMatch && params.requestedEntityId && params.requestedEntityId !== derivedId) {
682
+ throw new KinloomHttpError(400, 'VALIDATION_ERROR', `Kinship edge ID mismatch: expected '${params.requestedEntityId}', derived '${derivedId}'.`);
683
+ }
684
+ return {
685
+ entityId: params.requestedEntityId ?? derivedId,
686
+ sanitized: parsedEdge,
687
+ };
688
+ }
689
+ const prefix = ENTITY_ID_PREFIX[params.entityType];
690
+ const bodyId = typeof candidate.id === 'string' && candidate.id.trim().length > 0
691
+ ? candidate.id.trim()
692
+ : undefined;
693
+ if (params.requireIdMatch && params.requestedEntityId && bodyId && bodyId !== params.requestedEntityId) {
694
+ throw new KinloomHttpError(400, 'VALIDATION_ERROR', `Payload id '${bodyId}' does not match path id '${params.requestedEntityId}'.`);
695
+ }
696
+ const entityId = params.requestedEntityId ?? bodyId ?? generateEntityId(prefix);
697
+ candidate.id = entityId;
698
+ candidate.has_primary_source = params.hasPrimarySource;
699
+ switch (params.entityType) {
700
+ case 'person': {
701
+ const parsed = parseEntityPayload('person', candidate);
702
+ const sanitized = sanitizePersonForWrite(parsed, this.siteConfig.privacy);
703
+ return { entityId, sanitized: sanitized };
704
+ }
705
+ case 'event': {
706
+ const parsed = parseEntityPayload('event', candidate);
707
+ const livingIds = params.livingPersonIdsOverride ?? (await this.repository.getLivingPersonIds());
708
+ const sanitized = sanitizeEventForWrite(parsed, livingIds, this.siteConfig.privacy);
709
+ return { entityId, sanitized: sanitized };
710
+ }
711
+ case 'media': {
712
+ const parsed = parseEntityPayload('media', candidate);
713
+ const livingIds = params.livingPersonIdsOverride ?? (await this.repository.getLivingPersonIds());
714
+ const eventsMap = new Map(params.extraEventsById ?? []);
715
+ if (parsed.event_id && !eventsMap.has(parsed.event_id)) {
716
+ const evRow = await this.repository.getEntity('event', parsed.event_id);
717
+ if (evRow && !('edge' in evRow) && evRow.deleted_at === null) {
718
+ const parsedEv = parseEntityPayload('event', evRow.data);
719
+ eventsMap.set(parsedEv.id, parsedEv);
720
+ }
721
+ }
722
+ assertMediaAllowedForPrivacy(parsed, livingIds, eventsMap);
723
+ return { entityId, sanitized: parsed };
724
+ }
725
+ case 'place': {
726
+ const parsed = parseEntityPayload('place', candidate);
727
+ return { entityId, sanitized: parsed };
728
+ }
729
+ case 'source': {
730
+ const parsed = parseEntityPayload('source', candidate);
731
+ return { entityId, sanitized: parsed };
732
+ }
733
+ case 'narrative': {
734
+ const parsed = parseEntityPayload('narrative', candidate);
735
+ return { entityId, sanitized: parsed };
736
+ }
737
+ default: {
738
+ const _exhaustive = params.entityType;
739
+ throw new Error(`Unhandled entity type: ${String(_exhaustive)}`);
740
+ }
741
+ }
742
+ }
743
+ async buildConflictHttpError(params) {
744
+ const history = await this.repository.listRevisions({
745
+ entity_type: params.entityType,
746
+ entity_id: params.entityId,
747
+ limit: 1,
748
+ });
749
+ const lastAuthorName = history.items[0]?.author_name ?? 'Unknown editor';
750
+ const serverEntity = params.existing.deleted_at === null ? rowToPayload(params.existing) : null;
751
+ const conflict = {
752
+ kind: 'conflict',
753
+ entity_type: params.entityType,
754
+ entity_id: params.entityId,
755
+ expected_parent_revision_id: params.expectedParentRevisionId,
756
+ server_revision_id: params.existing.current_revision_id,
757
+ server_entity: serverEntity,
758
+ server_deleted_at: params.existing.deleted_at,
759
+ last_author_name: lastAuthorName,
760
+ last_updated_at: params.existing.updated_at,
761
+ diff: computeEntityDiff(serverEntity, params.candidateAfter),
762
+ };
763
+ return new KinloomHttpError(409, 'OPTIMISTIC_CONFLICT', `Entity ${params.entityType}/${params.entityId} was modified by another editor.`, conflict);
764
+ }
765
+ async commitOrThrowConflict(params) {
766
+ const result = await this.repository.commitAtomicMutations({
767
+ batch_id: params.batchId,
768
+ author: params.author,
769
+ nowIso: this.clock.nowIso(),
770
+ operations: params.operations,
771
+ });
772
+ if (result.kind === 'conflict') {
773
+ throw new KinloomHttpError(409, 'OPTIMISTIC_CONFLICT', `Entity ${result.entity_type}/${result.entity_id} was modified by another editor.`, result);
774
+ }
775
+ return {
776
+ head_revision_id: result.head_revision_id,
777
+ revisions: result.revisions,
778
+ };
779
+ }
780
+ async refreshBundleCache(committedRevisions, headRevisionId) {
781
+ if (this.bundleCache.applyMutationsAndStore && committedRevisions.length > 0) {
782
+ const cached = await this.bundleCache.getCached(null);
783
+ const firstNewRevId = committedRevisions[0].revision_id;
784
+ if (cached.status === 'hit' && cached.object.revision_id === firstNewRevId - 1) {
785
+ const rawJson = await readBodyToString(cached.object.body);
786
+ const previousBundle = JSON.parse(rawJson);
787
+ const patched = await this.bundleCache.applyMutationsAndStore(previousBundle, committedRevisions);
788
+ return patched.etag;
789
+ }
790
+ }
791
+ const snapshot = await this.repository.loadActiveSnapshot();
792
+ const rebuilt = await this.bundleCache.rebuildAndStore(snapshot);
793
+ return rebuilt.etag || `"r${headRevisionId}"`;
794
+ }
795
+ async notifyPlugins(revisions, headRevisionId) {
796
+ for (const plugin of this.plugins) {
797
+ if (!plugin.onRevisionCommitted) {
798
+ continue;
799
+ }
800
+ try {
801
+ await plugin.onRevisionCommitted({ revisions, headRevisionId });
802
+ }
803
+ catch (err) {
804
+ this.onPluginError?.(plugin.id, err);
805
+ }
806
+ }
807
+ }
808
+ }
809
+ //# sourceMappingURL=wikiWriteService.js.map