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