@geonosis/document 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/store.js ADDED
@@ -0,0 +1,1127 @@
1
+ import {
2
+ Document,
3
+ canonicalOf,
4
+ headFields,
5
+ migrateBody,
6
+ stampBody
7
+ } from "./chunk-7P6FV2YX.js";
8
+ import {
9
+ arrayOf,
10
+ booleanSchema,
11
+ canTransition,
12
+ literalOf,
13
+ merge,
14
+ nullable,
15
+ numberSchema,
16
+ optional,
17
+ stringSchema,
18
+ systemActor,
19
+ unknownSchema
20
+ } from "./chunk-NA3DLROL.js";
21
+
22
+ // src/store/hash.ts
23
+ import { createHash } from "crypto";
24
+ var hashOf = (payload) => createHash("sha256").update(JSON.stringify(canonicalOf(payload))).digest("hex");
25
+
26
+ // src/surface/table.ts
27
+ var doorFor = (store, name) => {
28
+ const door = store[name];
29
+ if (door === void 0) {
30
+ throw new Error(
31
+ `"${name}" names no store this table's registry can find \u2014 the table and the store must share one registry`
32
+ );
33
+ }
34
+ return door;
35
+ };
36
+ var HEAD_COLUMNS = Object.keys(Document.headFields);
37
+ var SORT_COLUMNS = [...HEAD_COLUMNS, "number", "createdAt", "updatedAt"];
38
+ var rowsFor = (definition, store, schema) => {
39
+ const { name } = definition;
40
+ const door = doorFor(store, name);
41
+ const basePath = `/${definition.basePath}`;
42
+ const instanceSchema = merge([
43
+ Document.head,
44
+ Document.record,
45
+ schema.object({ body: definition.view, entity: schema.enum([name]), number: stringSchema })
46
+ ]);
47
+ const commitOutput = schema.union([
48
+ schema.object({
49
+ committed: literalOf(false),
50
+ lineage: numberSchema,
51
+ ref: stringSchema,
52
+ version: numberSchema
53
+ }),
54
+ schema.object({
55
+ archived: optional(booleanSchema),
56
+ committed: literalOf(true),
57
+ hash: stringSchema,
58
+ lineage: numberSchema,
59
+ previous: nullable(schema.object({ hash: stringSchema, version: numberSchema })),
60
+ ref: stringSchema,
61
+ version: numberSchema
62
+ })
63
+ ]);
64
+ const retireLikeOutput = schema.object({
65
+ hash: stringSchema,
66
+ lineage: numberSchema,
67
+ ref: stringSchema,
68
+ version: numberSchema
69
+ });
70
+ const verifyOutput = schema.union([
71
+ schema.object({ ok: literalOf(true), versions: numberSchema }),
72
+ schema.object({
73
+ brokenAt: numberSchema,
74
+ expected: stringSchema,
75
+ found: stringSchema,
76
+ ok: literalOf(false)
77
+ })
78
+ ]);
79
+ const historyOutput = arrayOf(
80
+ schema.object({
81
+ actor: stringSchema,
82
+ at: numberSchema,
83
+ body: unknownSchema,
84
+ hash: stringSchema,
85
+ kind: schema.enum(["committed", "retired", "reinstated"]),
86
+ reason: nullable(stringSchema),
87
+ version: numberSchema
88
+ })
89
+ );
90
+ const listInput = schema.object({
91
+ cursor: optional(nullable(stringSchema)),
92
+ filter: optional(
93
+ schema.object(
94
+ Object.fromEntries(HEAD_COLUMNS.map((column) => [column, optional(stringSchema)]))
95
+ )
96
+ ),
97
+ limit: optional(numberSchema),
98
+ order: optional(
99
+ schema.object({
100
+ column: schema.enum(SORT_COLUMNS),
101
+ direction: optional(schema.enum(["asc", "desc"]))
102
+ })
103
+ )
104
+ });
105
+ const listOutput = schema.object({
106
+ items: arrayOf(merge([instanceSchema, schema.object({ card: definition.card.schema })])),
107
+ nextCursor: nullable(stringSchema)
108
+ });
109
+ const ackOutput = schema.object({ ref: stringSchema });
110
+ return [
111
+ {
112
+ call: (handle, params) => door.get(handle, params),
113
+ input: schema.object({ ref: stringSchema }),
114
+ name: `${name}.get`,
115
+ output: nullable(instanceSchema),
116
+ path: `${basePath}/:ref`,
117
+ scope: "org",
118
+ verb: "query"
119
+ },
120
+ {
121
+ call: async (handle, params) => {
122
+ const page = await door.list(handle, params);
123
+ return {
124
+ items: page.items.map((item) => ({
125
+ ...item,
126
+ card: definition.card.of(item, { counterpartyName: "" })
127
+ })),
128
+ nextCursor: page.nextCursor
129
+ };
130
+ },
131
+ input: listInput,
132
+ name: `${name}.list`,
133
+ output: listOutput,
134
+ path: basePath,
135
+ scope: "org",
136
+ verb: "query"
137
+ },
138
+ {
139
+ call: (handle, params) => door.history(handle, params),
140
+ input: schema.object({ lineage: optional(numberSchema), ref: stringSchema }),
141
+ name: `${name}.history`,
142
+ output: historyOutput,
143
+ path: `${basePath}/:ref/history`,
144
+ scope: "org",
145
+ verb: "query"
146
+ },
147
+ {
148
+ call: (handle, params) => door.verify(handle, params),
149
+ input: schema.object({ lineage: optional(numberSchema), ref: stringSchema }),
150
+ name: `${name}.verify`,
151
+ output: verifyOutput,
152
+ path: `${basePath}/:ref/verify`,
153
+ scope: "org",
154
+ verb: "query"
155
+ },
156
+ {
157
+ call: (handle, params) => door.commit(handle, params),
158
+ input: schema.object({
159
+ actor: stringSchema,
160
+ body: definition.body,
161
+ reason: optional(stringSchema),
162
+ ref: stringSchema
163
+ }),
164
+ name: `${name}.commit`,
165
+ output: commitOutput,
166
+ path: basePath,
167
+ scope: "org",
168
+ verb: "mutation"
169
+ },
170
+ {
171
+ call: (handle, params) => door.retire(handle, params),
172
+ input: schema.object({
173
+ actor: stringSchema,
174
+ reason: optional(stringSchema),
175
+ ref: stringSchema
176
+ }),
177
+ name: `${name}.retire`,
178
+ output: retireLikeOutput,
179
+ path: `${basePath}/:ref/retire`,
180
+ scope: "org",
181
+ verb: "mutation"
182
+ },
183
+ {
184
+ call: (handle, params) => door.reinstate(handle, params),
185
+ input: schema.object({
186
+ actor: stringSchema,
187
+ reason: optional(stringSchema),
188
+ ref: stringSchema
189
+ }),
190
+ name: `${name}.reinstate`,
191
+ output: retireLikeOutput,
192
+ path: `${basePath}/:ref/reinstate`,
193
+ scope: "org",
194
+ verb: "mutation"
195
+ },
196
+ {
197
+ call: async (handle, params) => {
198
+ const asked = params;
199
+ const current = await door.get(handle, params);
200
+ if (current === null) {
201
+ throw new Error(`"${asked.ref}" (${name}) has no document to set a status on`);
202
+ }
203
+ const from = definition.statusOf(current.body);
204
+ if (!canTransition(definition.statuses, from, asked.status)) {
205
+ throw new Error(
206
+ `"${name}" cannot move "${asked.ref}" from "${from}" to "${asked.status}": the status machine declares no such transition`
207
+ );
208
+ }
209
+ const body = definition.withStatus(
210
+ current.body,
211
+ asked.status,
212
+ (/* @__PURE__ */ new Date()).toISOString()
213
+ );
214
+ return door.commit(handle, { ...asked, body });
215
+ },
216
+ input: schema.object({
217
+ actor: stringSchema,
218
+ reason: optional(stringSchema),
219
+ ref: stringSchema,
220
+ status: schema.enum(definition.statuses.statuses)
221
+ }),
222
+ name: `${name}.setStatus`,
223
+ output: commitOutput,
224
+ path: `${basePath}/:ref/status`,
225
+ scope: "org",
226
+ verb: "mutation"
227
+ },
228
+ {
229
+ call: { pending: "T3", workflow: `${name}.create` },
230
+ input: schema.object({ draft: definition.draft }),
231
+ name: `${name}.create`,
232
+ output: commitOutput,
233
+ path: basePath,
234
+ scope: "org",
235
+ verb: "mutation"
236
+ },
237
+ {
238
+ call: { pending: "T3", workflow: `${name}.send` },
239
+ input: schema.object({ ref: stringSchema }),
240
+ name: `${name}.send`,
241
+ output: ackOutput,
242
+ path: `${basePath}/:ref/send`,
243
+ scope: "org",
244
+ verb: "mutation"
245
+ },
246
+ {
247
+ call: { pending: "T3", workflow: `${name}.duplicate` },
248
+ input: schema.object({ ref: stringSchema }),
249
+ name: `${name}.duplicate`,
250
+ output: commitOutput,
251
+ path: `${basePath}/:ref/duplicate`,
252
+ scope: "org",
253
+ verb: "mutation"
254
+ },
255
+ {
256
+ call: { pending: "T3", workflow: `${name}.runStarted` },
257
+ input: schema.object({ ref: stringSchema }),
258
+ name: `${name}.runStarted`,
259
+ output: ackOutput,
260
+ path: `${basePath}/:ref/run-started`,
261
+ scope: "org",
262
+ verb: "mutation"
263
+ }
264
+ ];
265
+ };
266
+ var documentSurface = (options) => {
267
+ const { registry, schema, store } = options;
268
+ const headsColumns = [...HEAD_COLUMNS, "entity", "number"];
269
+ const headsInput = schema.object({
270
+ columns: arrayOf(schema.enum(headsColumns)),
271
+ entity: optional(schema.union([stringSchema, arrayOf(stringSchema)])),
272
+ order: arrayOf(
273
+ schema.object({
274
+ column: schema.enum([...SORT_COLUMNS, "entity"]),
275
+ direction: optional(schema.enum(["asc", "desc"]))
276
+ })
277
+ ),
278
+ where: optional(unknownSchema)
279
+ });
280
+ const aggregateInput = schema.object({
281
+ by: optional(unknownSchema),
282
+ entities: optional(arrayOf(stringSchema)),
283
+ entity: optional(stringSchema),
284
+ measures: arrayOf(schema.enum(["count", "sum:total"])),
285
+ where: optional(unknownSchema)
286
+ });
287
+ const aggregateOutput = arrayOf(
288
+ schema.object({
289
+ by: optional(stringSchema),
290
+ count: optional(numberSchema),
291
+ sum: optional(stringSchema)
292
+ })
293
+ );
294
+ const sharedOutput = schema.union(
295
+ registry.fold(
296
+ (entity) => schema.object({ entity: schema.enum([entity.name]), view: entity.view })
297
+ )
298
+ );
299
+ return [
300
+ ...registry.fold((entity) => rowsFor(entity, store, schema)).flat(),
301
+ {
302
+ call: (handle, params) => store.heads(handle, params),
303
+ input: headsInput,
304
+ name: "heads",
305
+ output: arrayOf(unknownSchema),
306
+ path: "/documents/heads",
307
+ scope: "org",
308
+ verb: "query"
309
+ },
310
+ {
311
+ call: (handle, params) => store.aggregate(handle, params),
312
+ input: aggregateInput,
313
+ name: "aggregate",
314
+ output: aggregateOutput,
315
+ path: "/documents/aggregate",
316
+ scope: "org",
317
+ verb: "query"
318
+ },
319
+ {
320
+ call: { pending: "T3", workflow: "document.shared" },
321
+ input: schema.object({ token: stringSchema }),
322
+ name: "shared",
323
+ output: sharedOutput,
324
+ path: "/documents/shared",
325
+ scope: "token",
326
+ verb: "query"
327
+ }
328
+ ];
329
+ };
330
+
331
+ // src/store/ddl.ts
332
+ import {
333
+ DbRefusal,
334
+ ENTITY_PLACEHOLDERS,
335
+ entityTable,
336
+ logMigrations,
337
+ projectionMigrations
338
+ } from "@geonosis/db";
339
+ var DEFAULT_DOCUMENT_TABLE = "documents";
340
+ var DEFAULT_ENTITY_COLUMN = "entity";
341
+ var DEFAULT_VERSION_COLUMN = "version";
342
+ var DEFAULT_TENANT_COLUMN = "tenant_id";
343
+ var DEFAULT_CREATED_AT_COLUMN = "created_at";
344
+ var DEFAULT_UPDATED_AT_COLUMN = "updated_at";
345
+ var DEFAULT_REVISIONS_TABLE = "document_revisions";
346
+ var DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
347
+ var REVISION_KINDS = ["committed", "retired", "reinstated"];
348
+ var HEAD_FIELDS = Object.keys(headFields);
349
+ var snakeOf = (field) => field.replaceAll(/[A-Z]/g, (upper) => `_${upper.toLowerCase()}`);
350
+ var nameOf = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
351
+ var physicalColumnsOf = (columns) => {
352
+ const heads = Object.fromEntries(
353
+ HEAD_FIELDS.map((field) => [
354
+ field,
355
+ nameOf(
356
+ columns?.heads?.[field] ?? (field === "total" ? columns?.total : void 0),
357
+ snakeOf(field)
358
+ )
359
+ ])
360
+ );
361
+ return {
362
+ ...heads,
363
+ createdAt: nameOf(columns?.createdAt, DEFAULT_CREATED_AT_COLUMN),
364
+ entity: columns?.entity ?? DEFAULT_ENTITY_COLUMN,
365
+ tenant: nameOf(columns?.tenant, DEFAULT_TENANT_COLUMN),
366
+ updatedAt: nameOf(columns?.updatedAt, DEFAULT_UPDATED_AT_COLUMN)
367
+ };
368
+ };
369
+ var appendOnlyTables = (options = {}) => {
370
+ if (options.revisions === false) return [];
371
+ return [options.revisions?.table ?? options.table ?? DEFAULT_REVISIONS_TABLE];
372
+ };
373
+ var quotedName = (name) => `"${name}"`;
374
+ var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
375
+ var documentRoleStatements = (appRole, options = {}) => {
376
+ if (typeof appRole !== "string" || appRole === "") {
377
+ throw new DbRefusal(
378
+ "documentRoleStatements needs an `appRole` \u2014 the name a consumer\u2019s application connects as belongs to whoever runs the database, and one baked in here would be another repo\u2019s"
379
+ );
380
+ }
381
+ const role = quotedName(appRole);
382
+ const on = (table) => options.schema === void 0 ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
383
+ return appendOnlyTables(options).flatMap((table) => [
384
+ `revoke update, delete on ${on(table)} from ${role}`,
385
+ `grant select, insert on ${on(table)} to ${role}`
386
+ ]);
387
+ };
388
+ var DDL_TYPE_OF = { decimal: "numeric" };
389
+ var headIndexedColumns = (physical) => HEAD_FIELDS.map((field) => {
390
+ const type = DDL_TYPE_OF[headFields[field]];
391
+ return {
392
+ column: physical[field],
393
+ nullable: field !== "status",
394
+ ...type === void 0 ? {} : { type }
395
+ };
396
+ });
397
+ var revisionKindType = (column) => `text check (${quotedName(column)} in (${REVISION_KINDS.map(literalName).join(", ")}))`;
398
+ var walls = (options) => ({
399
+ ...options.freeze === void 0 ? {} : { freeze: options.freeze },
400
+ ...options.names === void 0 ? {} : { names: options.names },
401
+ ...options.schema === void 0 ? {} : { schema: options.schema }
402
+ });
403
+ var revisionsMigrations = (options, physical) => {
404
+ if (options.revisions === false) return [];
405
+ if (typeof options.appRole !== "string" || options.appRole === "") {
406
+ throw new DbRefusal(
407
+ "documentMigrations needs an `appRole` to render the log\u2019s wall \u2014 the role a consumer\u2019s application connects as belongs to whoever runs the database, and one baked in here would be another repo\u2019s. Pass it, or opt out of the log entirely with `revisions: false`"
408
+ );
409
+ }
410
+ const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
411
+ const table = options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
412
+ const [tableMigration, policies] = logMigrations({
413
+ appRole: options.appRole,
414
+ columns: { tenant: physical.tenant },
415
+ extra: [{ column: revisionKindColumn, type: revisionKindType(revisionKindColumn) }],
416
+ key: [physical.entity, "ref", { column: "lineage", type: "integer" }],
417
+ ...walls(options),
418
+ settings: options.settings,
419
+ table
420
+ });
421
+ if (tableMigration === void 0 || policies === void 0) {
422
+ throw new Error("logMigrations answered with fewer than the two migrations a log renders");
423
+ }
424
+ return [
425
+ { ...tableMigration, name: `0003_${table}.sql` },
426
+ { ...policies, name: `0004_${table}_policies.sql` }
427
+ ];
428
+ };
429
+ var documentMigrations = (options) => {
430
+ const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
431
+ const physical = physicalColumnsOf(options.columns);
432
+ const {
433
+ entity: _entity,
434
+ heads: _heads,
435
+ revisionKind: _revisionKind,
436
+ total: _total,
437
+ version,
438
+ ...restColumns
439
+ } = options.columns ?? {};
440
+ const [tableMigration, ...rest] = projectionMigrations({
441
+ carried: [{ column: "lineage", type: "integer not null default 1" }],
442
+ columns: { ...restColumns, sequence: version ?? DEFAULT_VERSION_COLUMN },
443
+ constants: { [physical.entity]: "" },
444
+ indexed: headIndexedColumns(physical),
445
+ key: "number",
446
+ order: [{ column: "number" }],
447
+ ...walls(options),
448
+ settings: options.settings,
449
+ sortable: [
450
+ ...HEAD_FIELDS.map((field) => physical[field]),
451
+ physical.createdAt,
452
+ physical.updatedAt
453
+ ],
454
+ table
455
+ });
456
+ if (tableMigration === void 0) {
457
+ throw new Error(
458
+ "projectionMigrations answered with no table migration to append the listing index to"
459
+ );
460
+ }
461
+ const listingIndex = `create index if not exists ${quotedName(`${table}_${physical.entity}_${physical.issueDate}_idx`)} on ${quotedName(table)} (${quotedName(physical.entity)}, ${quotedName(physical.issueDate)})`;
462
+ return [
463
+ { ...tableMigration, statements: [...tableMigration.statements, listingIndex] },
464
+ ...rest,
465
+ ...revisionsMigrations(options, physical)
466
+ ];
467
+ };
468
+ var TABLE_TYPE_OF = { decimal: "numeric" };
469
+ var documentTable = (options = {}) => {
470
+ const physical = physicalColumnsOf(options.columns);
471
+ const {
472
+ entity: _entity,
473
+ heads: _heads,
474
+ id,
475
+ revisionKind: _revisionKind,
476
+ total: _total,
477
+ version,
478
+ ...restColumns
479
+ } = options.columns ?? {};
480
+ const named = Object.fromEntries(
481
+ Object.entries(restColumns).map(([column, held]) => [column, nameOf(held, column)])
482
+ );
483
+ return entityTable({
484
+ columns: { ...named, version: nameOf(version, DEFAULT_VERSION_COLUMN) },
485
+ constants: [physical.entity],
486
+ extra: {
487
+ ...Object.fromEntries(
488
+ HEAD_FIELDS.map((field) => [
489
+ physical[field],
490
+ {
491
+ nullable: field !== "status",
492
+ type: TABLE_TYPE_OF[headFields[field]] ?? "text"
493
+ }
494
+ ])
495
+ ),
496
+ hash: "text",
497
+ lineage: "integer"
498
+ },
499
+ key: "number",
500
+ ...options.schema === void 0 ? {} : { schema: options.schema },
501
+ ...options.settings === void 0 ? {} : { settings: options.settings },
502
+ ...id === void 0 ? {} : { surrogate: nameOf(id.column, "id") },
503
+ table: options.table ?? DEFAULT_DOCUMENT_TABLE
504
+ });
505
+ };
506
+
507
+ // src/store/store.ts
508
+ import {
509
+ DbRefusal as DbRefusal2,
510
+ defineEntity,
511
+ defineLog,
512
+ projectionOf
513
+ } from "@geonosis/db";
514
+ var DEFAULT_VERSION_COLUMN2 = "version";
515
+ var UNDO_ACTOR = systemActor("document.undo");
516
+ var nameOf2 = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
517
+ var readBody = (entity, entityName, ref, stored) => {
518
+ const migrated = migrateBody(entity, stored);
519
+ const result = entity.body["~standard"].validate(migrated);
520
+ if (result instanceof Promise) {
521
+ throw new Error(
522
+ `${entityName} ${ref}: this entity's body schema validates asynchronously, and a stored body can only be read synchronously here`
523
+ );
524
+ }
525
+ if (result.issues !== void 0) {
526
+ throw new Error(
527
+ `${entityName} ${ref}'s stored body no longer satisfies its own schema after migration: ${result.issues.map((issue) => issue.message).join("; ")}`
528
+ );
529
+ }
530
+ return result.value;
531
+ };
532
+ var headFrom = (found) => found === void 0 ? void 0 : {
533
+ body: found.body,
534
+ hash: found.hash,
535
+ lineage: Number(found.carried.lineage ?? 1),
536
+ retiredAt: found.retiredAt,
537
+ version: found.sequence
538
+ };
539
+ var documentStore = (options) => {
540
+ const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
541
+ const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
542
+ const physical = physicalColumnsOf(options.columns);
543
+ const {
544
+ entity: _entity,
545
+ heads: _heads,
546
+ revisionKind: _revisionKind,
547
+ total: _total,
548
+ version,
549
+ ...entityColumns
550
+ } = options.columns ?? {};
551
+ const versionColumn = nameOf2(version, DEFAULT_VERSION_COLUMN2);
552
+ const entityColumn = physical.entity;
553
+ const { archive, registry, schema, seam } = options;
554
+ const tenantKey = seam.tenantKey;
555
+ const placed = schema === void 0 ? {} : { schema };
556
+ const declared = documentTable({
557
+ ...options.columns === void 0 ? {} : { columns: options.columns },
558
+ ...placed,
559
+ table
560
+ });
561
+ const revisionsTable = options.revisions === false ? void 0 : options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
562
+ const tenanted = (tenantId) => ({ [tenantKey]: tenantId });
563
+ const columnOf = (column) => column === "number" ? "number" : physical[column];
564
+ const physicalHeads = HEAD_FIELDS.map(columnOf);
565
+ const narrowed = (where) => Object.fromEntries(
566
+ Object.entries(where ?? {}).map(([column, held]) => [
567
+ columnOf(column),
568
+ held
569
+ ])
570
+ );
571
+ const revisions = revisionsTable === void 0 ? void 0 : defineLog({
572
+ columns: { tenant: physical.tenant },
573
+ extra: [{ column: revisionKindColumn, param: "kind" }],
574
+ hash: (row) => hashOf({
575
+ actor: row.actor,
576
+ at: row.at,
577
+ body: row.body,
578
+ entity: row.entity,
579
+ kind: row.kind,
580
+ lineage: row.lineage,
581
+ prevHash: row.prevHash,
582
+ reason: row.reason,
583
+ ref: row.ref,
584
+ tenant: row.tenant,
585
+ version: row.sequence
586
+ }),
587
+ key: [
588
+ { column: entityColumn, param: "entity" },
589
+ { column: "ref", param: "ref" },
590
+ { column: "lineage", param: "lineage" }
591
+ ],
592
+ ...placed,
593
+ seam,
594
+ table: revisionsTable
595
+ });
596
+ const needsLog = () => {
597
+ if (revisions === void 0) {
598
+ throw new DbRefusal2(
599
+ "this store has no log \u2014 `documentStore({ revisions: false })` opted out of the append-only record entirely, and the write model has no other door"
600
+ );
601
+ }
602
+ return revisions;
603
+ };
604
+ const readers = defineEntity({
605
+ columns: { ...entityColumns, version: versionColumn },
606
+ filterable: [...physicalHeads, entityColumn, physical.createdAt, physical.updatedAt],
607
+ item: (row) => row,
608
+ key: { column: "number", param: "ref" },
609
+ order: [{ column: "number" }],
610
+ seam,
611
+ sortable: [...physicalHeads, entityColumn, "number", physical.createdAt, physical.updatedAt],
612
+ table: declared
613
+ });
614
+ const entityStoreFor = (name) => {
615
+ const definition = registry.named(name);
616
+ const item = (row) => {
617
+ const body = readBody(definition, name, row.key, row.body);
618
+ const head = definition.headOf(body);
619
+ return registry.instance(name, {
620
+ ...head,
621
+ body,
622
+ createdAt: row.createdAt,
623
+ number: row.key,
624
+ updatedAt: row.updatedAt,
625
+ version: row.version ?? 1
626
+ });
627
+ };
628
+ const instanceFromRevision = (ref, row) => {
629
+ const body = readBody(definition, name, ref, row.body);
630
+ const head = definition.headOf(body);
631
+ return registry.instance(name, {
632
+ ...head,
633
+ body,
634
+ createdAt: row.at,
635
+ number: ref,
636
+ updatedAt: row.at,
637
+ version: row.sequence
638
+ });
639
+ };
640
+ const projection = projectionOf({
641
+ carried: ["lineage"],
642
+ columns: { ...entityColumns, hash: "hash", sequence: versionColumn },
643
+ constants: { [entityColumn]: name },
644
+ filterable: physicalHeads,
645
+ item,
646
+ key: { column: "number", param: "ref" },
647
+ order: [{ column: "number" }],
648
+ ...placed,
649
+ seam,
650
+ sortable: [...physicalHeads, "number", physical.createdAt, physical.updatedAt],
651
+ table: declared
652
+ });
653
+ const list = (handle, params) => projection.list(handle, {
654
+ ...params,
655
+ ...params.filter === void 0 ? {} : { filter: narrowed(params.filter) },
656
+ ...params.order === void 0 ? {} : {
657
+ order: {
658
+ column: columnOf(params.order.column),
659
+ ...params.order.direction === void 0 ? {} : { direction: params.order.direction }
660
+ }
661
+ }
662
+ });
663
+ const locked = async (tx, params) => headFrom(await projection.lockLatest(tx, params));
664
+ const currentLineageOf = async (tx, params) => headFrom(await projection.head(tx, params))?.lineage ?? 1;
665
+ const stream = (params, lineage) => ({
666
+ ...tenanted(params[tenantKey]),
667
+ entity: name,
668
+ lineage,
669
+ ref: params.ref
670
+ });
671
+ const headColumnsOf = (body) => Object.fromEntries(
672
+ Object.entries(definition.headOf(body)).map(([key, held]) => [
673
+ columnOf(key),
674
+ held
675
+ ])
676
+ );
677
+ const storedHead = (ref, body) => headColumnsOf(readBody(definition, name, ref, body));
678
+ const append = async (tx, write) => {
679
+ const log = needsLog();
680
+ const params = {
681
+ ...tenanted(write.tenantId),
682
+ actor: write.actor,
683
+ body: write.body,
684
+ entity: name,
685
+ kind: write.kind,
686
+ lineage: write.lineage,
687
+ ref: write.ref,
688
+ ...write.reason === null ? {} : { reason: write.reason }
689
+ };
690
+ const out = write.compensationOf === null ? await log.append(tx, params) : await log.appendCompensation(tx, { ...params, compensationOf: write.compensationOf });
691
+ return { at: out.at, hash: out.hash, prevHash: out.prevHash, version: out.sequence };
692
+ };
693
+ const project = async (tx, write) => projection.write(tx, {
694
+ ...tenanted(write.tenantId),
695
+ at: write.at,
696
+ body: write.body,
697
+ carried: { lineage: write.lineage },
698
+ derived: write.head,
699
+ hash: write.hash,
700
+ ref: write.ref,
701
+ retiredAt: write.retiredAt,
702
+ sequence: write.version
703
+ });
704
+ const commitTx = seam.scoped(
705
+ async (tx, params) => {
706
+ const tenantId = params[tenantKey];
707
+ const prepared = definition.prepare(params.body);
708
+ const stamped = stampBody(definition, prepared);
709
+ const existing = await locked(tx, params);
710
+ if (existing !== void 0 && existing.retiredAt !== null) {
711
+ throw new DbRefusal2(
712
+ `"${params.ref}" (${name}) is retired: commit refuses a retired document \u2014 succeed opens a new lineage for it`
713
+ );
714
+ }
715
+ const changed = existing === void 0 || JSON.stringify(canonicalOf(existing.body)) !== JSON.stringify(canonicalOf(stamped));
716
+ if (existing !== void 0 && !changed) {
717
+ return {
718
+ committed: false,
719
+ lineage: existing.lineage,
720
+ ref: params.ref,
721
+ version: existing.version
722
+ };
723
+ }
724
+ const lineage = existing?.lineage ?? 1;
725
+ const reason = params.reason ?? null;
726
+ const appended = await append(tx, {
727
+ actor: params.actor,
728
+ body: stamped,
729
+ compensationOf: null,
730
+ kind: "committed",
731
+ lineage,
732
+ reason,
733
+ ref: params.ref,
734
+ tenantId
735
+ });
736
+ await project(tx, {
737
+ at: appended.at,
738
+ body: stamped,
739
+ hash: appended.hash,
740
+ head: headColumnsOf(prepared),
741
+ lineage,
742
+ ref: params.ref,
743
+ retiredAt: null,
744
+ tenantId,
745
+ version: appended.version
746
+ });
747
+ return {
748
+ archivable: {
749
+ actor: params.actor,
750
+ at: appended.at,
751
+ body: stamped,
752
+ prevHash: appended.prevHash,
753
+ reason
754
+ },
755
+ committed: true,
756
+ hash: appended.hash,
757
+ lineage,
758
+ previous: existing === void 0 ? null : { hash: existing.hash, version: existing.version },
759
+ ref: params.ref,
760
+ version: appended.version
761
+ };
762
+ }
763
+ );
764
+ const commit = async (handle, params) => {
765
+ const { archivable, ...answer } = await commitTx(handle, params);
766
+ if (archive === void 0 || !answer.committed || archivable === void 0) return answer;
767
+ const key = `${params[tenantKey]}/${name}/${answer.lineage}/${answer.version}.json`;
768
+ const payload = {
769
+ actor: archivable.actor,
770
+ at: archivable.at,
771
+ body: archivable.body,
772
+ entity: name,
773
+ hash: answer.hash,
774
+ kind: "committed",
775
+ lineage: answer.lineage,
776
+ prevHash: archivable.prevHash,
777
+ ref: params.ref,
778
+ reason: archivable.reason,
779
+ tenant: params[tenantKey],
780
+ version: answer.version
781
+ };
782
+ try {
783
+ await archive.put(key, new TextEncoder().encode(JSON.stringify(payload)), {
784
+ hash: answer.hash,
785
+ immutable: true
786
+ });
787
+ return { ...answer, archived: true };
788
+ } catch {
789
+ return { ...answer, archived: false };
790
+ }
791
+ };
792
+ const retire = seam.scoped(
793
+ async (tx, params) => {
794
+ const tenantId = params[tenantKey];
795
+ const existing = await locked(tx, params);
796
+ if (existing === void 0) {
797
+ throw new DbRefusal2(`"${params.ref}" (${name}) has no document to retire`);
798
+ }
799
+ if (existing.retiredAt !== null) {
800
+ throw new DbRefusal2(`"${params.ref}" (${name}) is already retired`);
801
+ }
802
+ const appended = await append(tx, {
803
+ actor: params.actor,
804
+ body: existing.body,
805
+ compensationOf: null,
806
+ kind: "retired",
807
+ lineage: existing.lineage,
808
+ reason: params.reason ?? null,
809
+ ref: params.ref,
810
+ tenantId
811
+ });
812
+ await project(tx, {
813
+ at: appended.at,
814
+ body: existing.body,
815
+ hash: appended.hash,
816
+ head: storedHead(params.ref, existing.body),
817
+ lineage: existing.lineage,
818
+ ref: params.ref,
819
+ retiredAt: appended.at,
820
+ tenantId,
821
+ version: appended.version
822
+ });
823
+ return {
824
+ hash: appended.hash,
825
+ lineage: existing.lineage,
826
+ ref: params.ref,
827
+ version: appended.version
828
+ };
829
+ }
830
+ );
831
+ const succeed = seam.scoped(
832
+ async (tx, params) => {
833
+ const tenantId = params[tenantKey];
834
+ const existing = await locked(tx, params);
835
+ if (existing === void 0 || existing.retiredAt === null) {
836
+ throw new DbRefusal2(
837
+ `"${params.ref}" (${name}) is not retired: succeed opens a new lineage only for a retired document \u2014 commit is the door for a live one`
838
+ );
839
+ }
840
+ const prepared = definition.prepare(params.body);
841
+ const stamped = stampBody(definition, prepared);
842
+ const lineage = existing.lineage + 1;
843
+ const appended = await append(tx, {
844
+ actor: params.actor,
845
+ body: stamped,
846
+ compensationOf: null,
847
+ kind: "committed",
848
+ lineage,
849
+ reason: params.reason ?? null,
850
+ ref: params.ref,
851
+ tenantId
852
+ });
853
+ await project(tx, {
854
+ at: appended.at,
855
+ body: stamped,
856
+ hash: appended.hash,
857
+ head: headColumnsOf(prepared),
858
+ lineage,
859
+ ref: params.ref,
860
+ retiredAt: null,
861
+ tenantId,
862
+ version: appended.version
863
+ });
864
+ return {
865
+ committed: true,
866
+ hash: appended.hash,
867
+ lineage,
868
+ previous: null,
869
+ ref: params.ref,
870
+ version: appended.version
871
+ };
872
+ }
873
+ );
874
+ const reinstate = seam.scoped(
875
+ async (tx, params) => {
876
+ const tenantId = params[tenantKey];
877
+ const existing = await locked(tx, params);
878
+ if (existing === void 0 || existing.retiredAt === null) {
879
+ throw new DbRefusal2(`"${params.ref}" (${name}) is not retired: nothing to reinstate`);
880
+ }
881
+ const appended = await append(tx, {
882
+ actor: params.actor,
883
+ body: existing.body,
884
+ compensationOf: null,
885
+ kind: "reinstated",
886
+ lineage: existing.lineage,
887
+ reason: params.reason ?? null,
888
+ ref: params.ref,
889
+ tenantId
890
+ });
891
+ await project(tx, {
892
+ at: appended.at,
893
+ body: existing.body,
894
+ hash: appended.hash,
895
+ head: storedHead(params.ref, existing.body),
896
+ lineage: existing.lineage,
897
+ ref: params.ref,
898
+ retiredAt: null,
899
+ tenantId,
900
+ version: appended.version
901
+ });
902
+ return {
903
+ hash: appended.hash,
904
+ lineage: existing.lineage,
905
+ ref: params.ref,
906
+ version: appended.version
907
+ };
908
+ }
909
+ );
910
+ const at = seam.scoped(
911
+ async (tx, params) => {
912
+ const lineage = await currentLineageOf(tx, params);
913
+ const row = await needsLog().at(tx, {
914
+ ...stream(params, lineage),
915
+ sequence: params.version
916
+ });
917
+ return row === null ? null : instanceFromRevision(params.ref, row);
918
+ }
919
+ );
920
+ const asOf = seam.scoped(
921
+ async (tx, params) => {
922
+ const lineage = await currentLineageOf(tx, params);
923
+ const row = await needsLog().asOf(tx, { ...stream(params, lineage), at: params.at });
924
+ return row === null ? null : instanceFromRevision(params.ref, row);
925
+ }
926
+ );
927
+ const history = seam.scoped(
928
+ async (tx, params) => {
929
+ const lineage = params.lineage ?? await currentLineageOf(tx, params);
930
+ const rows = await needsLog().history(tx, stream(params, lineage));
931
+ return rows.map((row) => ({
932
+ actor: row.actor,
933
+ at: row.at,
934
+ body: readBody(definition, name, `${params.ref} version ${row.sequence}`, row.body),
935
+ hash: row.hash,
936
+ kind: row.kind,
937
+ reason: row.reason,
938
+ version: row.sequence
939
+ }));
940
+ }
941
+ );
942
+ const verify = seam.scoped(
943
+ async (tx, params) => {
944
+ const lineage = params.lineage ?? await currentLineageOf(tx, params);
945
+ return needsLog().verify(tx, stream(params, lineage));
946
+ }
947
+ );
948
+ const compensate = async (scoped, tenantId, output, kind, body, retired) => {
949
+ const appended = await append(scoped, {
950
+ actor: UNDO_ACTOR,
951
+ body,
952
+ compensationOf: output.version,
953
+ kind,
954
+ lineage: output.lineage,
955
+ reason: `undo of v${output.version}`,
956
+ ref: output.ref,
957
+ tenantId
958
+ });
959
+ await project(scoped, {
960
+ at: appended.at,
961
+ body,
962
+ hash: appended.hash,
963
+ head: storedHead(output.ref, body),
964
+ lineage: output.lineage,
965
+ ref: output.ref,
966
+ retiredAt: retired ? appended.at : null,
967
+ tenantId,
968
+ version: appended.version
969
+ });
970
+ };
971
+ const lockedForUndo = async (scoped, tenantId, output) => {
972
+ const existing = await locked(scoped, { ...tenanted(tenantId), ref: output.ref });
973
+ if (existing === void 0) {
974
+ throw new DbRefusal2(
975
+ `"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
976
+ );
977
+ }
978
+ return existing;
979
+ };
980
+ const undos = {
981
+ commit: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
982
+ if (!output.committed) return;
983
+ const existing = await lockedForUndo(scoped, tenantId, output);
984
+ if (output.previous === null) {
985
+ await compensate(scoped, tenantId, output, "retired", existing.body, true);
986
+ return;
987
+ }
988
+ const prior = await needsLog().at(scoped, {
989
+ ...stream({ ...tenanted(tenantId), ref: output.ref }, output.lineage),
990
+ sequence: output.previous.version
991
+ });
992
+ if (prior === null) {
993
+ throw new DbRefusal2(
994
+ `"${output.ref}" (${name}) version ${output.previous.version} is gone \u2014 cannot undo v${output.version} without it`
995
+ );
996
+ }
997
+ await compensate(scoped, tenantId, output, "committed", prior.body, false);
998
+ }),
999
+ retire: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
1000
+ const existing = await lockedForUndo(scoped, tenantId, output);
1001
+ await compensate(scoped, tenantId, output, "reinstated", existing.body, false);
1002
+ })
1003
+ };
1004
+ const restore = async (tx, row, createdAt) => {
1005
+ const ref = String(row.ref);
1006
+ await project(tx, {
1007
+ at: createdAt,
1008
+ body: row.body,
1009
+ hash: row.hash,
1010
+ head: storedHead(ref, row.body),
1011
+ lineage: Number(row.lineage),
1012
+ ref,
1013
+ retiredAt: row.kind === "retired" ? row.at : null,
1014
+ tenantId: row.tenant,
1015
+ version: row.sequence
1016
+ });
1017
+ };
1018
+ return {
1019
+ door: {
1020
+ asOf,
1021
+ at,
1022
+ commit,
1023
+ get: projection.get,
1024
+ history,
1025
+ list,
1026
+ listAll: projection.listAll,
1027
+ reinstate,
1028
+ retire,
1029
+ succeed,
1030
+ undos,
1031
+ verify
1032
+ },
1033
+ restore
1034
+ };
1035
+ };
1036
+ const built = registry.names.map((name) => [name, entityStoreFor(name)]);
1037
+ const rawEntities = Object.fromEntries(built.map(([name, one]) => [name, one.door]));
1038
+ const restorers = Object.fromEntries(
1039
+ built.map(([name, one]) => [name, one.restore])
1040
+ );
1041
+ const heads = seam.scoped(
1042
+ async (tx, params) => {
1043
+ const { columns, entity, order, where } = params;
1044
+ const rows = await readers.project(tx, {
1045
+ ...tenanted(params[tenantKey]),
1046
+ columns: columns.filter((column) => column !== "number").map(columnOf),
1047
+ order: order.map((one) => ({
1048
+ column: columnOf(one.column),
1049
+ ...one.direction === void 0 ? {} : { direction: one.direction }
1050
+ })),
1051
+ where: {
1052
+ ...entity === void 0 ? {} : { [entityColumn]: entity },
1053
+ ...narrowed(where)
1054
+ }
1055
+ });
1056
+ return rows.map(
1057
+ (row) => Object.fromEntries(
1058
+ columns.map((column) => [column, column === "number" ? row.key : row[columnOf(column)]])
1059
+ )
1060
+ );
1061
+ }
1062
+ );
1063
+ const aggregate = seam.scoped(
1064
+ (tx, params) => {
1065
+ const { by, entities, entity, measures, where } = params;
1066
+ return readers.aggregate(tx, {
1067
+ ...tenanted(params[tenantKey]),
1068
+ ...by === void 0 ? {} : {
1069
+ by: typeof by === "string" ? columnOf(by) : { bucket: by.bucket, of: columnOf(by.of) }
1070
+ },
1071
+ measures: measures.map(
1072
+ (one) => one === "sum:total" ? `sum:${physical.total}` : one
1073
+ ),
1074
+ where: {
1075
+ ...entity === void 0 ? {} : { [entityColumn]: entity },
1076
+ ...entities === void 0 ? {} : { [entityColumn]: entities },
1077
+ ...narrowed(where)
1078
+ }
1079
+ });
1080
+ }
1081
+ );
1082
+ const rebuild = seam.scoped(
1083
+ async (tx, params) => {
1084
+ const log = needsLog();
1085
+ const tenant = tenanted(params[tenantKey]);
1086
+ const latest = /* @__PURE__ */ new Map();
1087
+ for (const row of await log.latestPerStream(tx, tenant)) {
1088
+ if (params.entity !== void 0 && row.entity !== params.entity) continue;
1089
+ const address = `${String(row.entity)} ${String(row.ref)}`;
1090
+ const held = latest.get(address);
1091
+ if (held === void 0 || Number(row.lineage) > Number(held.lineage)) {
1092
+ latest.set(address, row);
1093
+ }
1094
+ }
1095
+ let rows = 0;
1096
+ for (const row of latest.values()) {
1097
+ const restore = restorers[String(row.entity)];
1098
+ if (restore === void 0) continue;
1099
+ const first = await log.at(tx, {
1100
+ ...tenant,
1101
+ entity: row.entity,
1102
+ lineage: row.lineage,
1103
+ ref: row.ref,
1104
+ sequence: 1
1105
+ });
1106
+ await restore(tx, row, first?.at ?? row.at);
1107
+ rows += 1;
1108
+ }
1109
+ return { rows };
1110
+ }
1111
+ );
1112
+ return { ...rawEntities, aggregate, heads, rebuild };
1113
+ };
1114
+ export {
1115
+ DEFAULT_DOCUMENT_TABLE,
1116
+ DEFAULT_REVISIONS_TABLE,
1117
+ DEFAULT_REVISION_KIND_COLUMN,
1118
+ ENTITY_PLACEHOLDERS as DOCUMENT_MIGRATION_PLACEHOLDERS,
1119
+ HEAD_FIELDS,
1120
+ appendOnlyTables,
1121
+ documentMigrations,
1122
+ documentRoleStatements,
1123
+ documentStore,
1124
+ documentSurface,
1125
+ hashOf,
1126
+ physicalColumnsOf
1127
+ };