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