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