@geonosis/document 0.9.0 → 0.9.2

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