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