@kinloom/server 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.
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,668 @@
1
+ import { asRevisionId, compileArchive, computeEntityDiff, parseEntityPayload, patchCompiledBundle, resolveEffectiveLiving, } from '@kinloom/core';
2
+ import { bytesToStream, matchesIfNoneMatch, readStreamToBytes } from '../crypto.js';
3
+ import { KinloomHttpError } from '../errors.js';
4
+ import { FixedClock } from './systemClock.js';
5
+ function entityCompositeKey(entityType, entityId) {
6
+ return `${entityType}:${entityId}`;
7
+ }
8
+ function getRowPayload(row) {
9
+ if ('edge' in row) {
10
+ return structuredClone(row.edge);
11
+ }
12
+ return structuredClone(row.data);
13
+ }
14
+ /**
15
+ * Full reference in-memory ArchiveRepository with real atomic optimistic-lock rollback.
16
+ */
17
+ export class InMemoryArchiveRepository {
18
+ entities = new Map();
19
+ kinship = new Map();
20
+ revisions = [];
21
+ talkComments = [];
22
+ users = new Map();
23
+ invites = new Map();
24
+ magicLinks = new Map();
25
+ agentTokens = new Map();
26
+ nextCommentId = 1;
27
+ privacyConfig;
28
+ constructor(options) {
29
+ this.privacyConfig = options?.privacyConfig;
30
+ }
31
+ async getHeadRevisionId() {
32
+ const last = this.revisions[this.revisions.length - 1];
33
+ return asRevisionId(last ? last.revision_id : 0);
34
+ }
35
+ async getEntity(entityType, entityId) {
36
+ if (entityType === 'kinship_edge') {
37
+ const row = this.kinship.get(entityId);
38
+ return row ? structuredClone(row) : null;
39
+ }
40
+ const row = this.entities.get(entityCompositeKey(entityType, entityId));
41
+ return row ? structuredClone(row) : null;
42
+ }
43
+ async getLivingPersonIds() {
44
+ const living = new Set();
45
+ for (const row of this.entities.values()) {
46
+ if (row.entity_type !== 'person' || row.deleted_at !== null) {
47
+ continue;
48
+ }
49
+ const parsed = parseEntityPayload('person', row.data);
50
+ if (resolveEffectiveLiving(parsed, this.privacyConfig)) {
51
+ living.add(row.entity_id);
52
+ }
53
+ }
54
+ return living;
55
+ }
56
+ async loadActiveSnapshot() {
57
+ const activeEntities = [];
58
+ for (const row of this.entities.values()) {
59
+ if (row.deleted_at === null) {
60
+ activeEntities.push(structuredClone(row));
61
+ }
62
+ }
63
+ activeEntities.sort((a, b) => a.entity_type.localeCompare(b.entity_type) || a.entity_id.localeCompare(b.entity_id));
64
+ const activeKinship = [];
65
+ for (const row of this.kinship.values()) {
66
+ if (row.deleted_at === null) {
67
+ activeKinship.push(structuredClone(row));
68
+ }
69
+ }
70
+ activeKinship.sort((a, b) => a.edge_id.localeCompare(b.edge_id));
71
+ return {
72
+ head_revision_id: await this.getHeadRevisionId(),
73
+ entities: activeEntities,
74
+ kinship: activeKinship,
75
+ };
76
+ }
77
+ findLastRevisionForEntity(entityType, entityId, workingRevisions) {
78
+ for (let i = workingRevisions.length - 1; i >= 0; i -= 1) {
79
+ const rev = workingRevisions[i];
80
+ if (rev.entity_type === entityType && rev.entity_id === entityId) {
81
+ return rev;
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+ buildConflict(op, existing, workingRevisions) {
87
+ const lastRev = this.findLastRevisionForEntity(op.entity_type, op.entity_id, workingRevisions);
88
+ const serverEntity = existing.deleted_at === null ? getRowPayload(existing) : null;
89
+ return {
90
+ kind: 'conflict',
91
+ entity_type: op.entity_type,
92
+ entity_id: op.entity_id,
93
+ expected_parent_revision_id: op.expected_parent_revision_id,
94
+ server_revision_id: existing.current_revision_id,
95
+ server_entity: serverEntity,
96
+ server_deleted_at: existing.deleted_at,
97
+ last_author_name: lastRev?.author_name ?? 'Unknown editor',
98
+ last_updated_at: existing.updated_at,
99
+ diff: computeEntityDiff(serverEntity, op.after_json),
100
+ };
101
+ }
102
+ async commitAtomicMutations(params) {
103
+ // Stage all writes in isolated clones so any optimistic-lock failure rolls back atomically.
104
+ const workingEntities = new Map();
105
+ for (const [key, row] of this.entities.entries()) {
106
+ workingEntities.set(key, structuredClone(row));
107
+ }
108
+ const workingKinship = new Map();
109
+ for (const [key, row] of this.kinship.entries()) {
110
+ workingKinship.set(key, structuredClone(row));
111
+ }
112
+ const workingRevisions = [...this.revisions];
113
+ const stagedRevisions = [];
114
+ const mutatedInBatch = new Set();
115
+ let nextRevNum = (workingRevisions[workingRevisions.length - 1]?.revision_id ?? 0) + 1;
116
+ for (const op of params.operations) {
117
+ const key = entityCompositeKey(op.entity_type, op.entity_id);
118
+ const existing = op.entity_type === 'kinship_edge'
119
+ ? (workingKinship.get(op.entity_id) ?? null)
120
+ : (workingEntities.get(key) ?? null);
121
+ const alreadyMutatedInBatch = mutatedInBatch.has(key);
122
+ if (op.action === 'create') {
123
+ if (existing !== null) {
124
+ return this.buildConflict(op, existing, workingRevisions);
125
+ }
126
+ }
127
+ else {
128
+ if (existing === null) {
129
+ return {
130
+ kind: 'conflict',
131
+ entity_type: op.entity_type,
132
+ entity_id: op.entity_id,
133
+ expected_parent_revision_id: op.expected_parent_revision_id,
134
+ server_revision_id: asRevisionId(0),
135
+ server_entity: null,
136
+ server_deleted_at: null,
137
+ last_author_name: 'None',
138
+ last_updated_at: params.nowIso,
139
+ diff: computeEntityDiff(null, op.after_json),
140
+ };
141
+ }
142
+ if (op.expected_parent_revision_id !== null) {
143
+ if (existing.current_revision_id !== op.expected_parent_revision_id) {
144
+ return this.buildConflict(op, existing, workingRevisions);
145
+ }
146
+ }
147
+ else if (!alreadyMutatedInBatch) {
148
+ return this.buildConflict(op, existing, workingRevisions);
149
+ }
150
+ if (op.action === 'update' || op.action === 'delete') {
151
+ if (existing.deleted_at !== null) {
152
+ return this.buildConflict(op, existing, workingRevisions);
153
+ }
154
+ }
155
+ else if (op.action === 'restore') {
156
+ if (existing.deleted_at === null) {
157
+ return this.buildConflict(op, existing, workingRevisions);
158
+ }
159
+ }
160
+ }
161
+ const assignedRevId = asRevisionId(nextRevNum);
162
+ nextRevNum += 1;
163
+ const parentRevId = existing ? existing.current_revision_id : null;
164
+ const revRecord = {
165
+ revision_id: assignedRevId,
166
+ batch_id: params.batch_id,
167
+ entity_type: op.entity_type,
168
+ entity_id: op.entity_id,
169
+ parent_revision_id: parentRevId,
170
+ action: op.action,
171
+ reverted_revision_id: op.reverted_revision_id ?? null,
172
+ author_id: params.author.author_id,
173
+ author_name: params.author.author_name,
174
+ author_type: params.author.author_type,
175
+ summary: op.summary,
176
+ has_primary_source: op.has_primary_source,
177
+ before_json: op.before_json ? structuredClone(op.before_json) : null,
178
+ after_json: op.after_json ? structuredClone(op.after_json) : null,
179
+ created_at: params.nowIso,
180
+ };
181
+ const isSoftDelete = op.soft_delete === true || op.action === 'delete' || op.after_json === null;
182
+ if (op.entity_type === 'kinship_edge') {
183
+ const nextEdge = op.after_json
184
+ ? parseEntityPayload('kinship_edge', op.after_json)
185
+ : existing.edge;
186
+ const nextRow = {
187
+ edge_id: op.entity_id,
188
+ edge: structuredClone(nextEdge),
189
+ current_revision_id: assignedRevId,
190
+ deleted_at: isSoftDelete ? params.nowIso : null,
191
+ updated_at: params.nowIso,
192
+ };
193
+ workingKinship.set(op.entity_id, nextRow);
194
+ }
195
+ else {
196
+ const prevRow = existing;
197
+ const nextData = op.after_json
198
+ ? structuredClone(op.after_json)
199
+ : structuredClone(prevRow.data);
200
+ const nextSlug = op.slug !== undefined
201
+ ? op.slug
202
+ : typeof nextData.slug === 'string'
203
+ ? nextData.slug
204
+ : (prevRow?.slug ?? null);
205
+ const nextRow = {
206
+ entity_type: op.entity_type,
207
+ entity_id: op.entity_id,
208
+ slug: nextSlug,
209
+ data: nextData,
210
+ current_revision_id: assignedRevId,
211
+ has_primary_source: op.has_primary_source,
212
+ deleted_at: isSoftDelete ? params.nowIso : null,
213
+ updated_at: params.nowIso,
214
+ };
215
+ workingEntities.set(key, nextRow);
216
+ }
217
+ workingRevisions.push(revRecord);
218
+ stagedRevisions.push(revRecord);
219
+ mutatedInBatch.add(key);
220
+ }
221
+ // All operations succeeded: swap staged state atomically.
222
+ this.entities.clear();
223
+ for (const [key, row] of workingEntities.entries()) {
224
+ this.entities.set(key, row);
225
+ }
226
+ this.kinship.clear();
227
+ for (const [key, row] of workingKinship.entries()) {
228
+ this.kinship.set(key, row);
229
+ }
230
+ this.revisions.push(...stagedRevisions);
231
+ return {
232
+ kind: 'committed',
233
+ head_revision_id: await this.getHeadRevisionId(),
234
+ revisions: stagedRevisions.map((r) => structuredClone(r)),
235
+ };
236
+ }
237
+ async listRevisions(query) {
238
+ const limit = Math.min(200, Math.max(1, query.limit ?? 50));
239
+ const filtered = [];
240
+ for (let i = this.revisions.length - 1; i >= 0; i -= 1) {
241
+ const rev = this.revisions[i];
242
+ if (query.cursor !== undefined && rev.revision_id >= query.cursor) {
243
+ continue;
244
+ }
245
+ if (query.entity_type && rev.entity_type !== query.entity_type) {
246
+ continue;
247
+ }
248
+ if (query.entity_id && rev.entity_id !== query.entity_id) {
249
+ continue;
250
+ }
251
+ if (query.batch_id && rev.batch_id !== query.batch_id) {
252
+ continue;
253
+ }
254
+ if (query.author_type && rev.author_type !== query.author_type) {
255
+ continue;
256
+ }
257
+ filtered.push(structuredClone(rev));
258
+ if (filtered.length > limit) {
259
+ break;
260
+ }
261
+ }
262
+ const hasMore = filtered.length > limit;
263
+ const items = hasMore ? filtered.slice(0, limit) : filtered;
264
+ const lastItem = items[items.length - 1];
265
+ return {
266
+ items,
267
+ next_cursor: hasMore && lastItem ? asRevisionId(lastItem.revision_id) : null,
268
+ };
269
+ }
270
+ async getRevisionById(revisionId) {
271
+ const found = this.revisions.find((r) => r.revision_id === revisionId);
272
+ return found ? structuredClone(found) : null;
273
+ }
274
+ async getRevisionsByBatch(batchId) {
275
+ return this.revisions
276
+ .filter((r) => r.batch_id === batchId)
277
+ .toSorted((a, b) => a.revision_id - b.revision_id)
278
+ .map((r) => structuredClone(r));
279
+ }
280
+ async listTalkComments(entityType, entityId) {
281
+ return this.talkComments
282
+ .filter((c) => c.entity_type === entityType && c.entity_id === entityId && c.deleted_at === null)
283
+ .toSorted((a, b) => a.comment_id - b.comment_id)
284
+ .map((c) => structuredClone(c));
285
+ }
286
+ async insertTalkComment(input) {
287
+ const comment = {
288
+ comment_id: this.nextCommentId,
289
+ entity_type: input.entity_type,
290
+ entity_id: input.entity_id,
291
+ author_id: input.author_id,
292
+ author_name: input.author_name,
293
+ body_md: input.body_md,
294
+ created_at: input.created_at,
295
+ edited_at: null,
296
+ deleted_at: null,
297
+ };
298
+ this.nextCommentId += 1;
299
+ this.talkComments.push(comment);
300
+ return structuredClone(comment);
301
+ }
302
+ async softDeleteTalkComment(commentId, deletedAt) {
303
+ const comment = this.talkComments.find((c) => c.comment_id === commentId && c.deleted_at === null);
304
+ if (!comment) {
305
+ return false;
306
+ }
307
+ comment.deleted_at = deletedAt;
308
+ return true;
309
+ }
310
+ async getUser(email) {
311
+ const record = this.users.get(email.trim().toLowerCase());
312
+ return record ? structuredClone(record) : null;
313
+ }
314
+ async listUsers() {
315
+ return [...this.users.values()]
316
+ .toSorted((a, b) => a.email.localeCompare(b.email))
317
+ .map((u) => structuredClone(u));
318
+ }
319
+ async upsertUser(user) {
320
+ const normalized = {
321
+ ...structuredClone(user),
322
+ email: user.email.trim().toLowerCase(),
323
+ };
324
+ this.users.set(normalized.email, normalized);
325
+ return structuredClone(normalized);
326
+ }
327
+ async updateUserRole(email, role) {
328
+ const key = email.trim().toLowerCase();
329
+ const existing = this.users.get(key);
330
+ if (!existing) {
331
+ return null;
332
+ }
333
+ existing.role = role;
334
+ return structuredClone(existing);
335
+ }
336
+ async deleteUser(email) {
337
+ return this.users.delete(email.trim().toLowerCase());
338
+ }
339
+ async touchUserLogin(email, atIso) {
340
+ const existing = this.users.get(email.trim().toLowerCase());
341
+ if (existing) {
342
+ existing.last_login_at = atIso;
343
+ }
344
+ }
345
+ async getInvite(token) {
346
+ const invite = this.invites.get(token);
347
+ return invite ? structuredClone(invite) : null;
348
+ }
349
+ async listInvites() {
350
+ return [...this.invites.values()]
351
+ .toSorted((a, b) => b.created_at.localeCompare(a.created_at))
352
+ .map((i) => structuredClone(i));
353
+ }
354
+ async createInvite(invite) {
355
+ const clone = structuredClone(invite);
356
+ this.invites.set(clone.token, clone);
357
+ return structuredClone(clone);
358
+ }
359
+ async recordInviteUse(token, atIso) {
360
+ const invite = this.invites.get(token);
361
+ if (invite) {
362
+ invite.uses += 1;
363
+ invite.last_used_at = atIso;
364
+ }
365
+ }
366
+ async revokeInvite(token, atIso) {
367
+ const invite = this.invites.get(token);
368
+ if (!invite || invite.revoked_at !== null) {
369
+ return false;
370
+ }
371
+ invite.revoked_at = atIso;
372
+ return true;
373
+ }
374
+ async insertMagicLink(record) {
375
+ this.magicLinks.set(record.token_hash, structuredClone(record));
376
+ }
377
+ async consumeMagicLink(tokenHash, nowIso) {
378
+ const record = this.magicLinks.get(tokenHash);
379
+ if (!record || record.used_at !== null) {
380
+ return null;
381
+ }
382
+ const expiresMs = Date.parse(record.expires_at);
383
+ const nowMs = Date.parse(nowIso);
384
+ if (Number.isNaN(expiresMs) || Number.isNaN(nowMs) || expiresMs <= nowMs) {
385
+ return null;
386
+ }
387
+ record.used_at = nowIso;
388
+ return structuredClone(record);
389
+ }
390
+ async findActiveAgentTokenByHash(tokenHash) {
391
+ for (const token of this.agentTokens.values()) {
392
+ if (token.token_hash === tokenHash && token.revoked_at === null) {
393
+ return structuredClone(token);
394
+ }
395
+ }
396
+ return null;
397
+ }
398
+ async listAgentTokens() {
399
+ return [...this.agentTokens.values()]
400
+ .toSorted((a, b) => b.created_at.localeCompare(a.created_at))
401
+ .map((t) => structuredClone(t));
402
+ }
403
+ async createAgentToken(record) {
404
+ const clone = structuredClone(record);
405
+ this.agentTokens.set(clone.token_id, clone);
406
+ return structuredClone(clone);
407
+ }
408
+ async revokeAgentToken(tokenId, atIso) {
409
+ const token = this.agentTokens.get(tokenId);
410
+ if (!token || token.revoked_at !== null) {
411
+ return false;
412
+ }
413
+ token.revoked_at = atIso;
414
+ return true;
415
+ }
416
+ }
417
+ export function extractCollectionsFromSnapshot(snapshot) {
418
+ const people = [];
419
+ const events = [];
420
+ const places = [];
421
+ const sources = [];
422
+ const media = [];
423
+ const narratives = [];
424
+ for (const row of snapshot.entities) {
425
+ if (row.deleted_at !== null) {
426
+ continue;
427
+ }
428
+ switch (row.entity_type) {
429
+ case 'person': {
430
+ const parsed = parseEntityPayload('person', row.data);
431
+ if (!row.has_primary_source && parsed.has_primary_source === undefined) {
432
+ parsed.has_primary_source = false;
433
+ }
434
+ people.push(parsed);
435
+ break;
436
+ }
437
+ case 'event': {
438
+ const parsed = parseEntityPayload('event', row.data);
439
+ if (!row.has_primary_source && parsed.has_primary_source === undefined) {
440
+ parsed.has_primary_source = false;
441
+ }
442
+ events.push(parsed);
443
+ break;
444
+ }
445
+ case 'place': {
446
+ const parsed = parseEntityPayload('place', row.data);
447
+ if (!row.has_primary_source && parsed.has_primary_source === undefined) {
448
+ parsed.has_primary_source = false;
449
+ }
450
+ places.push(parsed);
451
+ break;
452
+ }
453
+ case 'source': {
454
+ const parsed = parseEntityPayload('source', row.data);
455
+ if (!row.has_primary_source && parsed.has_primary_source === undefined) {
456
+ parsed.has_primary_source = false;
457
+ }
458
+ sources.push(parsed);
459
+ break;
460
+ }
461
+ case 'media': {
462
+ const parsed = parseEntityPayload('media', row.data);
463
+ if (!row.has_primary_source && parsed.has_primary_source === undefined) {
464
+ parsed.has_primary_source = false;
465
+ }
466
+ media.push(parsed);
467
+ break;
468
+ }
469
+ case 'narrative': {
470
+ const parsed = parseEntityPayload('narrative', row.data);
471
+ if (!row.has_primary_source && parsed.has_primary_source === undefined) {
472
+ parsed.has_primary_source = false;
473
+ }
474
+ narratives.push(parsed);
475
+ break;
476
+ }
477
+ default: {
478
+ const _exhaustive = row.entity_type;
479
+ throw new Error(`Unhandled entity type: ${String(_exhaustive)}`);
480
+ }
481
+ }
482
+ }
483
+ const kinship = snapshot.kinship
484
+ .filter((row) => row.deleted_at === null)
485
+ .map((row) => structuredClone(row.edge));
486
+ return { people, events, places, sources, media, narratives, kinship };
487
+ }
488
+ /**
489
+ * In-memory incremental BundleCache using @kinloom/core patchCompiledBundle + compileArchive.
490
+ */
491
+ export class InMemoryIncrementalBundleCache {
492
+ siteConfig;
493
+ clock;
494
+ cached = null;
495
+ rebuildCount = 0;
496
+ incrementalPatchCount = 0;
497
+ constructor(siteConfig, clock) {
498
+ this.siteConfig = siteConfig;
499
+ this.clock = clock;
500
+ }
501
+ invalidate() {
502
+ this.cached = null;
503
+ }
504
+ async getCached(ifNoneMatch) {
505
+ if (!this.cached) {
506
+ return { status: 'miss' };
507
+ }
508
+ if (matchesIfNoneMatch(ifNoneMatch, this.cached.etag)) {
509
+ return { status: 'not_modified', etag: this.cached.etag };
510
+ }
511
+ return {
512
+ status: 'hit',
513
+ object: {
514
+ ...this.cached,
515
+ },
516
+ };
517
+ }
518
+ async rebuildAndStore(snapshot) {
519
+ const collections = extractCollectionsFromSnapshot(snapshot);
520
+ const generatedAt = this.clock.nowIso();
521
+ const { bundle } = compileArchive({
522
+ ...collections,
523
+ siteConfig: this.siteConfig,
524
+ mode: 'private',
525
+ generatedAt,
526
+ maxRevisionId: snapshot.head_revision_id,
527
+ });
528
+ this.rebuildCount += 1;
529
+ return this.storeBundle(bundle, snapshot.head_revision_id, generatedAt);
530
+ }
531
+ async applyMutationsAndStore(previous, mutations) {
532
+ const generatedAt = this.clock.nowIso();
533
+ const patched = patchCompiledBundle(previous, mutations, this.siteConfig, 'private', {
534
+ generatedAt,
535
+ });
536
+ let maxRev = previous.meta.max_revision_id ?? 0;
537
+ for (const m of mutations) {
538
+ if (m.revision_id > maxRev) {
539
+ maxRev = m.revision_id;
540
+ }
541
+ }
542
+ this.incrementalPatchCount += 1;
543
+ return this.storeBundle(patched, asRevisionId(maxRev), generatedAt);
544
+ }
545
+ storeBundle(bundle, revisionId, generatedAt) {
546
+ const serialized = JSON.stringify(bundle);
547
+ const byteLength = new TextEncoder().encode(serialized).byteLength;
548
+ const object = {
549
+ etag: `"r${revisionId}"`,
550
+ revision_id: revisionId,
551
+ body: serialized,
552
+ byteLength,
553
+ generated_at: generatedAt,
554
+ };
555
+ this.cached = object;
556
+ return object;
557
+ }
558
+ }
559
+ /**
560
+ * In-memory content-addressed MediaStore with HTTP 206 byte-range slice support.
561
+ */
562
+ export class InMemoryMediaStore {
563
+ blobs = new Map();
564
+ putCount = 0;
565
+ async head(key) {
566
+ const entry = this.blobs.get(key);
567
+ if (!entry) {
568
+ return { exists: false };
569
+ }
570
+ return {
571
+ exists: true,
572
+ sizeBytes: entry.bytes.byteLength,
573
+ contentType: entry.contentType,
574
+ };
575
+ }
576
+ async put(params) {
577
+ const bytes = params.body instanceof ArrayBuffer
578
+ ? new Uint8Array(params.body.slice(0))
579
+ : await readStreamToBytes(params.body);
580
+ this.blobs.set(params.key, {
581
+ bytes,
582
+ contentType: params.contentType,
583
+ sha256: params.sha256,
584
+ });
585
+ this.putCount += 1;
586
+ }
587
+ async get(key, options) {
588
+ const entry = this.blobs.get(key);
589
+ if (!entry) {
590
+ return null;
591
+ }
592
+ const total = entry.bytes.byteLength;
593
+ if (options?.range) {
594
+ const start = Math.max(0, options.range.offset);
595
+ const endExclusive = options.range.length !== undefined
596
+ ? Math.min(total, start + options.range.length)
597
+ : total;
598
+ const slice = entry.bytes.slice(start, endExclusive);
599
+ return {
600
+ key,
601
+ contentType: entry.contentType,
602
+ sizeBytes: slice.byteLength,
603
+ sha256: entry.sha256,
604
+ body: bytesToStream(slice),
605
+ range: {
606
+ start,
607
+ end: start + slice.byteLength - 1,
608
+ total,
609
+ },
610
+ };
611
+ }
612
+ return {
613
+ key,
614
+ contentType: entry.contentType,
615
+ sizeBytes: total,
616
+ sha256: entry.sha256,
617
+ body: bytesToStream(entry.bytes),
618
+ };
619
+ }
620
+ }
621
+ export class InMemoryEmailSender {
622
+ sentMessages = [];
623
+ async sendMagicLink(params) {
624
+ this.sentMessages.push({ ...params });
625
+ }
626
+ }
627
+ export class FakeAuthProvider {
628
+ id = 'fake-google';
629
+ profilesByCode = new Map();
630
+ lastAuthorizationParams = null;
631
+ lastExchangeParams = null;
632
+ registerCode(code, profile) {
633
+ this.profilesByCode.set(code, profile);
634
+ }
635
+ buildAuthorizationUrl(params) {
636
+ this.lastAuthorizationParams = { ...params };
637
+ const url = new URL('https://accounts.example.test/oauth/authorize');
638
+ url.searchParams.set('state', params.state);
639
+ url.searchParams.set('code_challenge', params.codeChallenge);
640
+ url.searchParams.set('redirect_uri', params.redirectUri);
641
+ return url.toString();
642
+ }
643
+ async exchangeCode(params) {
644
+ this.lastExchangeParams = { ...params };
645
+ const profile = this.profilesByCode.get(params.code);
646
+ if (!profile) {
647
+ throw new KinloomHttpError(400, 'INVALID_OAUTH_STATE', `Unknown OAuth code: ${params.code}`);
648
+ }
649
+ return { ...profile };
650
+ }
651
+ }
652
+ export function createInMemoryServerPorts(siteConfig, options) {
653
+ const clock = new FixedClock(options?.initialIso ?? '2026-06-01T12:00:00.000Z');
654
+ const repository = new InMemoryArchiveRepository({ privacyConfig: siteConfig.privacy });
655
+ const bundleCache = new InMemoryIncrementalBundleCache(siteConfig, clock);
656
+ const mediaStore = new InMemoryMediaStore();
657
+ const emailSender = new InMemoryEmailSender();
658
+ const authProvider = new FakeAuthProvider();
659
+ return {
660
+ repository,
661
+ bundleCache,
662
+ mediaStore,
663
+ emailSender,
664
+ authProvider,
665
+ clock,
666
+ };
667
+ }
668
+ //# sourceMappingURL=inMemory.js.map