@geonosis/document 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,4 +1,7 @@
1
- import { z } from 'zod';
1
+ import { StandardSchemaV1 } from '@standard-schema/spec';
2
+ export { StandardSchemaV1 } from '@standard-schema/spec';
3
+ import { EntityColumns, EntityName, SessionSettings, EntityMigration, Entity, Executor, Query, EntityUndo, SessionSeam } from '@geonosis/db';
4
+ export { ENTITY_PLACEHOLDERS as DOCUMENT_MIGRATION_PLACEHOLDERS } from '@geonosis/db';
2
5
 
3
6
  declare const BODY_VERSION_KEY = "_v";
4
7
  type StoredBody = Record<string, unknown>;
@@ -47,29 +50,33 @@ type DocumentStatusMachine<Status extends string> = {
47
50
  declare const canTransition: <Status extends string>(machine: DocumentStatusMachine<Status>, from: Status, to: Status) => boolean;
48
51
  declare const isTerminalStatus: <Status extends string>(machine: DocumentStatusMachine<Status>, status: Status) => boolean;
49
52
 
53
+ /** The five checks `Document.head` and `Document.record` are built from — never a sixth kind. */
54
+ type FieldKind = 'calendarDate' | 'decimal' | 'int' | 'positiveInt' | 'text';
55
+ /** The two `FieldKind`s a consumer's own schema library validates by pattern — `validatorOf`'s own regexes, on the door, so a fold names one pattern once (#409). */
56
+ declare const fieldPatterns: Record<'calendarDate' | 'decimal', RegExp>;
50
57
  /**
51
- * What every document has before anything knows what kind it is — the indexed facts a list sorts
52
- * and filters by. Every entity derives these from its own body (`headOf`).
58
+ * A `StandardSchemaV1` derived from a declarative field spec — one small checker per `FieldKind`,
59
+ * never a second listing of the fields `Document.head`/`Document.record` already carry.
53
60
  */
54
- declare const documentHeadSchema: z.ZodObject<{
55
- status: z.ZodNullable<z.ZodString>;
56
- issueDate: z.ZodNullable<z.ZodString>;
57
- dueDate: z.ZodNullable<z.ZodString>;
58
- counterparty: z.ZodNullable<z.ZodString>;
59
- externalRef: z.ZodNullable<z.ZodString>;
60
- revision: z.ZodNullable<z.ZodString>;
61
- total: z.ZodNullable<z.ZodString>;
62
- }, z.core.$strip>;
63
- type DocumentHead = z.infer<typeof documentHeadSchema>;
64
- /** What storage adds: the version a history counts, and the two clocks. */
65
- declare const documentRecordSchema: z.ZodObject<{
66
- version: z.ZodNumber;
67
- createdAt: z.ZodNumber;
68
- updatedAt: z.ZodNumber;
69
- }, z.core.$strip>;
70
- type DocumentRecord = z.infer<typeof documentRecordSchema>;
61
+ declare const validatorOf: <Output>(fields: Readonly<Record<string, FieldKind>>, options?: {
62
+ nullable?: boolean;
63
+ }) => StandardSchemaV1<unknown, Output>;
64
+ type DocumentHead = {
65
+ status: string | null;
66
+ issueDate: string | null;
67
+ dueDate: string | null;
68
+ counterparty: string | null;
69
+ externalRef: string | null;
70
+ revision: string | null;
71
+ total: string | null;
72
+ };
73
+ type DocumentRecord = {
74
+ version: number;
75
+ createdAt: number;
76
+ updatedAt: number;
77
+ };
71
78
  /** What an entity decides when it extends `Document`; every side effect is written once over these. */
72
- type DocumentDefinition<Name extends string, BodySchema extends z.ZodTypeAny, DraftSchema extends z.ZodTypeAny, IncomingSchema extends z.ZodTypeAny, Status extends string, Card, Path extends string> = {
79
+ type DocumentDefinition<Name extends string, BodySchema extends StandardSchemaV1, DraftSchema extends StandardSchemaV1, IncomingSchema extends StandardSchemaV1, Status extends string, CardSchema extends StandardSchemaV1, Path extends string> = {
73
80
  name: Name;
74
81
  noun: string;
75
82
  basePath: Path;
@@ -77,27 +84,30 @@ type DocumentDefinition<Name extends string, BodySchema extends z.ZodTypeAny, Dr
77
84
  draft: DraftSchema;
78
85
  incoming: IncomingSchema;
79
86
  statuses: DocumentStatusMachine<Status>;
80
- numbering: DocumentNumbering<z.output<DraftSchema>>;
87
+ numbering: DocumentNumbering<StandardSchemaV1.InferOutput<DraftSchema>>;
81
88
  /** The version this entity's stored body is at today — absent, it is 1. */
82
89
  bodyVersion?: number;
83
90
  /** Steps that bring an older stored body up to `bodyVersion`, keyed by the version they read. */
84
91
  migrations?: DocumentBodyMigrations<Record<string, unknown>>;
85
92
  /** `number` is the MINTED number — read off the numbering before the counter moves, never a series. */
86
- fromDraft: (draft: z.output<DraftSchema>, number: string) => z.output<BodySchema>;
87
- headOf: (body: z.output<BodySchema>) => DocumentHead;
88
- searchText: (body: z.output<BodySchema>) => {
93
+ fromDraft: (draft: StandardSchemaV1.InferOutput<DraftSchema>, number: string) => StandardSchemaV1.InferOutput<BodySchema>;
94
+ headOf: (body: StandardSchemaV1.InferOutput<BodySchema>) => DocumentHead;
95
+ searchText: (body: StandardSchemaV1.InferOutput<BodySchema>) => {
89
96
  body: string;
90
97
  };
91
- statusOf: (body: z.output<BodySchema>) => Status;
92
- withStatus: (body: z.output<BodySchema>, status: Status, at: string) => z.output<BodySchema>;
93
- prepare: (body: z.output<BodySchema>) => z.output<BodySchema>;
94
- merge: (stored: z.output<BodySchema>, incoming: z.output<IncomingSchema>, at: string) => z.output<BodySchema>;
95
- onSent: (body: z.output<BodySchema>) => z.output<BodySchema>;
96
- copy: (body: z.output<BodySchema>) => z.output<BodySchema>;
98
+ statusOf: (body: StandardSchemaV1.InferOutput<BodySchema>) => Status;
99
+ withStatus: (body: StandardSchemaV1.InferOutput<BodySchema>, status: Status, at: string) => StandardSchemaV1.InferOutput<BodySchema>;
100
+ prepare: (body: StandardSchemaV1.InferOutput<BodySchema>) => StandardSchemaV1.InferOutput<BodySchema>;
101
+ merge: (stored: StandardSchemaV1.InferOutput<BodySchema>, incoming: StandardSchemaV1.InferOutput<IncomingSchema>, at: string) => StandardSchemaV1.InferOutput<BodySchema>;
102
+ onSent: (body: StandardSchemaV1.InferOutput<BodySchema>) => StandardSchemaV1.InferOutput<BodySchema>;
103
+ copy: (body: StandardSchemaV1.InferOutput<BodySchema>) => StandardSchemaV1.InferOutput<BodySchema>;
97
104
  removable: boolean;
98
- card: (document: DocumentInstance<Name, z.output<BodySchema>>, names: {
99
- counterpartyName: string;
100
- }) => Card;
105
+ card: {
106
+ schema: CardSchema;
107
+ of: (document: DocumentInstance<Name, StandardSchemaV1.InferOutput<BodySchema>>, names: {
108
+ counterpartyName: string;
109
+ }) => StandardSchemaV1.InferOutput<CardSchema>;
110
+ };
101
111
  };
102
112
  /** A stored document of one entity: the head every document has, the record's clocks, its body. */
103
113
  type DocumentInstance<Name extends string, Body> = DocumentHead & DocumentRecord & {
@@ -105,39 +115,41 @@ type DocumentInstance<Name extends string, Body> = DocumentHead & DocumentRecord
105
115
  number: string;
106
116
  body: Body;
107
117
  };
108
- type DocumentEntity<Name extends string, BodySchema extends z.ZodTypeAny, DraftSchema extends z.ZodTypeAny, IncomingSchema extends z.ZodTypeAny, Status extends string, Card, Path extends string> = DocumentDefinition<Name, BodySchema, DraftSchema, IncomingSchema, Status, Card, Path> & {
118
+ type DocumentEntity<Name extends string, BodySchema extends StandardSchemaV1, DraftSchema extends StandardSchemaV1, IncomingSchema extends StandardSchemaV1, Status extends string, CardSchema extends StandardSchemaV1, Path extends string> = DocumentDefinition<Name, BodySchema, DraftSchema, IncomingSchema, Status, CardSchema, Path> & {
109
119
  is: (document: {
110
120
  entity: string;
111
- }) => document is DocumentInstance<Name, z.output<BodySchema>>;
121
+ }) => document is DocumentInstance<Name, StandardSchemaV1.InferOutput<BodySchema>>;
112
122
  };
113
123
  /**
114
124
  * The abstract Document. Never stored as itself — a consumer's entities extend it, and everything
115
125
  * written against `Document` runs for every one of them.
116
126
  */
117
127
  declare const Document: {
118
- head: z.ZodObject<{
119
- status: z.ZodNullable<z.ZodString>;
120
- issueDate: z.ZodNullable<z.ZodString>;
121
- dueDate: z.ZodNullable<z.ZodString>;
122
- counterparty: z.ZodNullable<z.ZodString>;
123
- externalRef: z.ZodNullable<z.ZodString>;
124
- revision: z.ZodNullable<z.ZodString>;
125
- total: z.ZodNullable<z.ZodString>;
126
- }, z.core.$strip>;
127
- record: z.ZodObject<{
128
- version: z.ZodNumber;
129
- createdAt: z.ZodNumber;
130
- updatedAt: z.ZodNumber;
131
- }, z.core.$strip>;
132
- extend: <Name extends string, BodySchema extends z.ZodTypeAny, DraftSchema extends z.ZodTypeAny, IncomingSchema extends z.ZodTypeAny, Status extends string, Card, Path extends string>(definition: DocumentDefinition<Name, BodySchema, DraftSchema, IncomingSchema, Status, Card, Path>) => DocumentEntity<Name, BodySchema, DraftSchema, IncomingSchema, Status, Card, Path>;
133
- };
134
- type Parts<Entity> = Entity extends DocumentDefinition<infer Name, infer BodySchema, infer DraftSchema, infer IncomingSchema, infer Status, infer Card, infer _Path> ? {
128
+ head: StandardSchemaV1<unknown, DocumentHead>;
129
+ headFields: {
130
+ readonly status: "text";
131
+ readonly issueDate: "calendarDate";
132
+ readonly dueDate: "calendarDate";
133
+ readonly counterparty: "text";
134
+ readonly externalRef: "text";
135
+ readonly revision: "text";
136
+ readonly total: "decimal";
137
+ };
138
+ record: StandardSchemaV1<unknown, DocumentRecord>;
139
+ recordFields: {
140
+ readonly version: "positiveInt";
141
+ readonly createdAt: "int";
142
+ readonly updatedAt: "int";
143
+ };
144
+ extend: <Name extends string, BodySchema extends StandardSchemaV1, DraftSchema extends StandardSchemaV1, IncomingSchema extends StandardSchemaV1, Status extends string, CardSchema extends StandardSchemaV1, Path extends string>(definition: DocumentDefinition<Name, BodySchema, DraftSchema, IncomingSchema, Status, CardSchema, Path>) => DocumentEntity<Name, BodySchema, DraftSchema, IncomingSchema, Status, CardSchema, Path>;
145
+ };
146
+ type Parts<Entity> = Entity extends DocumentDefinition<infer Name, infer BodySchema, infer DraftSchema, infer IncomingSchema, infer Status, infer CardSchema, infer _Path> ? {
135
147
  name: Name;
136
- body: z.output<BodySchema>;
137
- draft: z.output<DraftSchema>;
138
- incoming: z.output<IncomingSchema>;
148
+ body: StandardSchemaV1.InferOutput<BodySchema>;
149
+ draft: StandardSchemaV1.InferOutput<DraftSchema>;
150
+ incoming: StandardSchemaV1.InferOutput<IncomingSchema>;
139
151
  status: Status;
140
- card: Card;
152
+ card: StandardSchemaV1.InferOutput<CardSchema>;
141
153
  } : never;
142
154
  type NameOf<Entity> = Parts<Entity>['name'];
143
155
  type BodyOf<Entity> = Parts<Entity>['body'];
@@ -149,36 +161,54 @@ type InstanceOf<Entity> = DocumentInstance<NameOf<Entity>, BodyOf<Entity>>;
149
161
 
150
162
  /**
151
163
  * The least a map's value has to be for `documentEntities` to do its own work: a name to check
152
- * against the key, a body schema to union. The FULL entity type stays whatever the caller passed —
153
- * this is a constraint bound, not the type inference reads back — because a status machine typed
154
- * to its own narrow union is not assignable to one held at `string`, and widening it here would
155
- * break every entity's own `withStatus` the moment two of them met in one map.
164
+ * against the key, a body and a card schema to fold over. The FULL entity type stays whatever the
165
+ * caller passed — this is a constraint bound, not the type inference reads back — because a status
166
+ * machine typed to its own narrow union is not assignable to one held at `string`, and widening it
167
+ * here would break every entity's own `withStatus` the moment two of them met in one map.
168
+ *
169
+ * Exported for a layer that composes over the registry's OWN values generically (the store): the
170
+ * same minimal bound, never a second one.
156
171
  */
157
- type AnyEntity = {
158
- name: string;
159
- body: {
160
- parse: (input: unknown) => unknown;
172
+ type AnyDocumentEntity = {
173
+ body: StandardSchemaV1;
174
+ card: {
175
+ schema: StandardSchemaV1;
161
176
  };
177
+ name: string;
162
178
  };
163
179
  /**
164
180
  * `documentEntities(map)`: every entity that extends `Document`, by the name its rows carry.
165
181
  *
182
+ * A per-entity fact is never read off a map a caller fills in per entity — `fold` reads it off
183
+ * every entity the registry holds, in one place, typed over the union of the map's own values.
166
184
  * Adding an entity is one `Document.extend` call and one line in the map handed here; the returned
167
- * `names` union is DERIVED from the map's own keys, so a `satisfies Record<Names, T>` a consumer
168
- * writes elsewhere refuses to compile until it decides for the new one too.
185
+ * `names` union is DERIVED from the map's own keys.
169
186
  */
170
- declare const documentEntities: <Map extends Readonly<Record<string, AnyEntity>>>(map: Map) => {
187
+ declare const documentEntities: <Map extends Readonly<Record<string, AnyDocumentEntity>>>(map: Map) => {
188
+ bodies: StandardSchemaV1[];
189
+ cards: StandardSchemaV1[];
171
190
  entities: Map;
172
- names: readonly (keyof Map & string)[];
173
- nameSchema: z.ZodEnum<{ [K in keyof Map & string]: K; }>;
174
- bodySchema: z.ZodType<{ [K in keyof Map]: InstanceOf<Map[K]>["body"]; }[keyof Map]>;
175
- bodyDecoder: z.ZodType<{ [K in keyof Map]: InstanceOf<Map[K]>["body"]; }[keyof Map]>;
191
+ fold: <Result>(pick: (entity: Map[keyof Map]) => Result) => Result[];
176
192
  instance: <Name extends keyof Map & string>(name: Name, parts: Omit<InstanceOf<Map[Name]>, "entity" | "body"> & {
177
193
  body: unknown;
178
194
  }) => DocumentInstance<Name, InstanceOf<Map[Name]>["body"]>;
179
195
  named: <Name extends keyof Map & string>(name: Name) => Map[Name];
196
+ names: readonly (keyof Map & string)[];
180
197
  };
181
198
 
199
+ /** An unattended write's principal — `systemActor('recurring.generate')` — never a bare `'system'`. */
200
+ declare const systemActor: (name: string) => string;
201
+ declare const isSystemActor: (actor: string) => boolean;
202
+
203
+ /**
204
+ * Deep, key-order-independent: two payloads that hold the same facts hash the same. The ONE
205
+ * canonicaliser both sides use — a consumer's archive recomputes `hashOf` over the identical form,
206
+ * so a second implementation of this function is a second chain that silently stops agreeing.
207
+ */
208
+ declare const canonicalOf: (input: unknown) => unknown;
209
+ /** sha256 hex over the canonical JSON of `payload` — no whitespace, keys sorted recursively. */
210
+ declare const hashOf: (payload: unknown) => string;
211
+
182
212
  /** The identifiers a surface spells an entity with, all derived from its one hyphenated name. */
183
213
  declare const documentIdentifiers: (name: string) => {
184
214
  camel: string;
@@ -189,4 +219,288 @@ declare const documentIdentifiers: (name: string) => {
189
219
  path: string;
190
220
  };
191
221
 
192
- export { BODY_VERSION_KEY, type BodyOf, type CardOf, Document, type DocumentBodyMigrations, type DocumentBodyVersion, type DocumentDefinition, type DocumentEntity, type DocumentHead, type DocumentInstance, type DocumentNumbering, type DocumentRecord, type DocumentStatusMachine, type DraftOf, type IncomingOf, type InstanceOf, type NameOf, type StatusOf, canTransition, documentBodyVersioning, documentEntities, documentIdentifiers, isTerminalStatus, migrateBody, stampBody };
222
+ /**
223
+ * The archive's own key convention: `<tenant>/<entity>/<lineage>/<version>.json` — one object per
224
+ * revision, named so a lineage's own history sits together and a new lineage (`succeed`) never
225
+ * collides with the one it replaced.
226
+ */
227
+ type ArchivePort = {
228
+ head: (key: string) => Promise<{
229
+ hash: string;
230
+ } | null>;
231
+ put: (key: string, bytes: Uint8Array, meta: {
232
+ hash: string;
233
+ immutable: true;
234
+ }) => Promise<void>;
235
+ };
236
+ /** A trusted third party's timestamp over a hash — never implemented here, only declared. */
237
+ type TimestampPort = {
238
+ stamp: (hash: string) => Promise<{
239
+ at: number;
240
+ token: Uint8Array;
241
+ }>;
242
+ };
243
+
244
+ declare const DEFAULT_DOCUMENT_TABLE = "documents";
245
+ declare const DEFAULT_REVISIONS_TABLE = "document_revisions";
246
+ declare const DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
247
+ type DocumentColumns = EntityColumns & {
248
+ /** The discriminator column two entities on one table disagree on. `'entity'` when unnamed. */
249
+ entity?: string;
250
+ /**
251
+ * The log's own `committed | retired | reinstated` column. `'revision_kind'` when unnamed —
252
+ * never `'kind'`, the name the kit's own docs use for `entity`, and a consumer who follows that
253
+ * convention would otherwise declare one physical column twice (#407).
254
+ */
255
+ revisionKind?: string;
256
+ /** The physical column `heads`/`aggregate` read `total` off. `'total'` when unnamed. */
257
+ total?: EntityName;
258
+ };
259
+ /** The log — the append-only record of truth. `false` opts a consumer out of it entirely. */
260
+ type DocumentRevisionsOptions = {
261
+ table?: string;
262
+ };
263
+ type DocumentMigrationsOptions = {
264
+ /**
265
+ * The role a consumer's application connects as — the log's `revoke update, delete` and its
266
+ * trigger are rendered for THIS name, and nothing here can pick it: it belongs to whoever runs
267
+ * the database (`@geonosis/db`'s own `appRoleStatements`, the same law). Required whenever the
268
+ * log is on (the default); irrelevant when `revisions: false`.
269
+ */
270
+ appRole?: string;
271
+ columns?: DocumentColumns;
272
+ /** On by default (`document_revisions`); `false` renders none of it. */
273
+ revisions?: DocumentRevisionsOptions | false;
274
+ schema?: string;
275
+ settings: SessionSettings;
276
+ table?: string;
277
+ };
278
+ type AppendOnlyTablesOptions = {
279
+ /** Shorthand for `revisions.table` — ignored once `revisions` also names one. */
280
+ table?: string;
281
+ /** On by default (`document_revisions`); `false` names nothing — nothing here is append-only. */
282
+ revisions?: DocumentRevisionsOptions | false;
283
+ };
284
+ /**
285
+ * The tables this domain declares append-only — the names `@geonosis/db`'s `appRoleStatements`
286
+ * takes as `appendOnly` so its blanket grant excludes them, and `documentRoleStatements` below
287
+ * takes the same way for a consumer that provisions its role by hand.
288
+ */
289
+ declare const appendOnlyTables: (options?: AppendOnlyTablesOptions) => string[];
290
+ /**
291
+ * The log's own wall, standalone — for a consumer that provisions its application role outside
292
+ * `@geonosis/db`'s `appRoleStatements` (a hosted provider's own role, for instance). Run this AFTER
293
+ * the role exists; the revoke targets a table `documentMigrations` must already have created.
294
+ */
295
+ declare const documentRoleStatements: (appRole: string, options?: AppendOnlyTablesOptions & {
296
+ schema?: string;
297
+ }) => string[];
298
+ /**
299
+ * `documentMigrations` = `entityMigrations` over the seven head columns, the constants column that
300
+ * discriminates one document entity's rows from another's on the SAME table, and the version
301
+ * column `UpsertOutput.replaced` reads. One extra index this table needs that no per-column
302
+ * `sortable` index gives it: `(entity, issueDate)`, the predicate every read named in the brief
303
+ * narrows by — STATUS BREAKDOWN, TIME SERIES, COUNT BY ENTITY, RECENT, HEADS FOR MATCHING all
304
+ * start `kind = <entity> and issueDate between …`. The revisions table and its wall follow, unless
305
+ * a consumer opts out.
306
+ */
307
+ declare const documentMigrations: (options: DocumentMigrationsOptions) => EntityMigration[];
308
+
309
+ /**
310
+ * What `documentStore` needs off an entity beyond `documentEntities`'s own minimal bound: the head
311
+ * derivation, the write-time preparation, and the entity's own body versioning. The registry's
312
+ * `AnyDocumentEntity` stays as narrow as `documentEntities` itself needs — this is the store's own
313
+ * bound, never a widening of that one.
314
+ */
315
+ type StorableDocumentEntity = AnyDocumentEntity & {
316
+ bodyVersion?: number;
317
+ headOf: (body: never) => DocumentHead;
318
+ migrations?: DocumentBodyMigrations<Record<string, unknown>>;
319
+ prepare: (body: never) => unknown;
320
+ };
321
+ type Registry<Map extends Readonly<Record<string, StorableDocumentEntity>>> = ReturnType<typeof documentEntities<Map>>;
322
+ type DocumentStoreOptions<Map extends Readonly<Record<string, StorableDocumentEntity>>, Key extends string> = {
323
+ /**
324
+ * Copied after `commit`'s own transaction has already committed — never inside it, so a failed
325
+ * put is reported in the answer (`archived: false`) rather than rolling back a write the log
326
+ * already has durably. The mirror workflow (a later ticket) is what retries it.
327
+ */
328
+ archive?: ArchivePort;
329
+ columns?: DocumentColumns;
330
+ registry: Registry<Map>;
331
+ /** The append-only log. On by default (`document_revisions`); `false` opts out. */
332
+ revisions?: DocumentRevisionsOptions | false;
333
+ schema?: string;
334
+ seam: SessionSeam<Key, Executor>;
335
+ table?: string;
336
+ };
337
+ type HeadColumn = keyof DocumentHead | 'entity' | 'number';
338
+ type HeadsOrder = {
339
+ column: HeadColumn;
340
+ direction?: 'asc' | 'desc';
341
+ };
342
+ type HeadsWhere = {
343
+ createdAt?: readonly [number, number];
344
+ status?: string;
345
+ };
346
+ type HeadsArgs = {
347
+ columns: readonly HeadColumn[];
348
+ /** One entity, or a set — RECENT's own read narrows `kind IN ($kinds)`, never one kind alone. */
349
+ entity?: string | readonly string[];
350
+ /** Every column a page is ordered by, the tie-break included — HEADS FOR MATCHING orders by `kind, number`. */
351
+ order: readonly HeadsOrder[];
352
+ where?: HeadsWhere;
353
+ };
354
+ type AggregateMeasure = 'count' | 'sum:total';
355
+ type AggregateBy = 'entity' | 'status' | {
356
+ bucket: 'day' | 'month' | 'week';
357
+ of: 'issueDate';
358
+ };
359
+ type AggregateWhere = {
360
+ status?: string;
361
+ } & ({
362
+ createdAt: readonly [number, number];
363
+ } | {
364
+ issueDate: readonly [string, string];
365
+ } | Record<string, never>);
366
+ type AggregateRow = {
367
+ by?: string;
368
+ count?: number;
369
+ sum?: string;
370
+ };
371
+ type AggregateArgs = {
372
+ by?: AggregateBy;
373
+ entities?: readonly string[];
374
+ entity?: string;
375
+ measures: readonly AggregateMeasure[];
376
+ where?: AggregateWhere;
377
+ };
378
+ type SortableHeadColumn = keyof DocumentHead;
379
+ type Item = DocumentInstance<string, unknown>;
380
+ type DocumentKind = 'committed' | 'reinstated' | 'retired';
381
+ type CommitOutput = {
382
+ archived?: undefined;
383
+ committed: false;
384
+ hash?: undefined;
385
+ lineage: number;
386
+ previous?: undefined;
387
+ ref: string;
388
+ version: number;
389
+ } | {
390
+ /** Present only when `documentStore({ archive })` names a port — absent, nothing tried. */
391
+ archived?: boolean;
392
+ committed: true;
393
+ hash: string;
394
+ lineage: number;
395
+ previous: {
396
+ hash: string;
397
+ version: number;
398
+ } | null;
399
+ ref: string;
400
+ version: number;
401
+ };
402
+ type RetireOutput = {
403
+ hash: string;
404
+ lineage: number;
405
+ ref: string;
406
+ version: number;
407
+ };
408
+ type ReinstateOutput = {
409
+ hash: string;
410
+ lineage: number;
411
+ ref: string;
412
+ version: number;
413
+ };
414
+ type HistoryEntry = {
415
+ actor: string;
416
+ at: number;
417
+ body: unknown;
418
+ hash: string;
419
+ kind: DocumentKind;
420
+ reason: string | null;
421
+ version: number;
422
+ };
423
+ type VerifyResult = {
424
+ brokenAt: number;
425
+ expected: string;
426
+ found: string;
427
+ ok: false;
428
+ } | {
429
+ ok: true;
430
+ versions: number;
431
+ };
432
+ type DocumentEntityStore<Key extends string> = Pick<Entity<unknown, Item, Key, 'ref', Executor, SortableHeadColumn, SortableHeadColumn>, 'get' | 'list' | 'listAll'> & {
433
+ /** The latest revision whose `at` is at or before the instant — the current lineage only. */
434
+ asOf: Query<Readonly<Record<Key, string>> & {
435
+ at: number;
436
+ ref: string;
437
+ }, Item | null, Executor>;
438
+ /** `ref`'s revision at that exact version — the current lineage only. */
439
+ at: Query<Readonly<Record<Key, string>> & {
440
+ ref: string;
441
+ version: number;
442
+ }, Item | null, Executor>;
443
+ /** The ONE write verb: appends an immutable revision, updates the projection, one transaction. */
444
+ commit: Query<Readonly<Record<Key, string>> & {
445
+ actor: string;
446
+ body: unknown;
447
+ reason?: string;
448
+ ref: string;
449
+ }, CommitOutput, Executor>;
450
+ /** Every revision of one lineage, by version — the archive's own read. */
451
+ history: Query<Readonly<Record<Key, string>> & {
452
+ lineage?: number;
453
+ ref: string;
454
+ }, HistoryEntry[], Executor>;
455
+ /** Un-retires the SAME lineage — never a new one (`succeed` is that door). */
456
+ reinstate: Query<Readonly<Record<Key, string>> & {
457
+ actor: string;
458
+ reason?: string;
459
+ ref: string;
460
+ }, ReinstateOutput, Executor>;
461
+ /** `retire`: a commit of kind `retired` — refuses a document already retired. */
462
+ retire: Query<Readonly<Record<Key, string>> & {
463
+ actor: string;
464
+ reason?: string;
465
+ ref: string;
466
+ }, RetireOutput, Executor>;
467
+ /** Opens a NEW lineage for a `ref` whose document is dead — the old lineage stays in full. */
468
+ succeed: Query<Readonly<Record<Key, string>> & {
469
+ actor: string;
470
+ body: unknown;
471
+ reason?: string;
472
+ ref: string;
473
+ }, CommitOutput, Executor>;
474
+ undos: {
475
+ commit: EntityUndo<CommitOutput, Executor>;
476
+ retire: EntityUndo<RetireOutput, Executor>;
477
+ };
478
+ /** Recomputes every hash of one lineage from version 1 — tamper-evidence, on demand. */
479
+ verify: Query<Readonly<Record<Key, string>> & {
480
+ lineage?: number;
481
+ ref: string;
482
+ }, VerifyResult, Executor>;
483
+ };
484
+ type DocumentStore<Map extends Readonly<Record<string, StorableDocumentEntity>>, Key extends string> = {
485
+ [Name in keyof Map & string]: DocumentEntityStore<Key>;
486
+ } & {
487
+ aggregate: Query<Readonly<Record<Key, string>> & AggregateArgs, AggregateRow[], Executor>;
488
+ heads: Query<Readonly<Record<Key, string>> & HeadsArgs, Readonly<Record<string, unknown>>[], Executor>;
489
+ /** Rewrites the projection from the log — an exam's own rebuild, and a consumer's repair tool. */
490
+ rebuild: Query<Readonly<Record<Key, string>> & {
491
+ entity?: string;
492
+ }, {
493
+ rows: number;
494
+ }, Executor>;
495
+ };
496
+ /**
497
+ * `documentStore`: one physical table for every document entity, the log beside it, `heads` and
498
+ * `aggregate` beside that.
499
+ *
500
+ * Every per-entity fact is read off the registry by `fold`/`named` — never a map this function
501
+ * fills in itself. `heads`/`aggregate` are the only readers of the physical column names; a caller
502
+ * reaches them by the vocabulary `Document.headFields` already gave it, `entity` and `ref` beside.
503
+ */
504
+ declare const documentStore: <Map extends Readonly<Record<string, StorableDocumentEntity>>, Key extends string>(options: DocumentStoreOptions<Map, Key>) => DocumentStore<Map, Key>;
505
+
506
+ export { type AggregateArgs, type AggregateBy, type AggregateMeasure, type AggregateRow, type AggregateWhere, type AnyDocumentEntity, type AppendOnlyTablesOptions, type ArchivePort, BODY_VERSION_KEY, type BodyOf, type CardOf, type CommitOutput, DEFAULT_DOCUMENT_TABLE, DEFAULT_REVISIONS_TABLE, DEFAULT_REVISION_KIND_COLUMN, Document, type DocumentBodyMigrations, type DocumentBodyVersion, type DocumentColumns, type DocumentDefinition, type DocumentEntity, type DocumentHead, type DocumentInstance, type DocumentKind, type DocumentMigrationsOptions, type DocumentNumbering, type DocumentRecord, type DocumentRevisionsOptions, type DocumentStatusMachine, type DocumentStore, type DocumentStoreOptions, type DraftOf, type FieldKind, type HeadColumn, type HeadsArgs, type HeadsOrder, type HeadsWhere, type HistoryEntry, type IncomingOf, type InstanceOf, type NameOf, type ReinstateOutput, type RetireOutput, type StatusOf, type TimestampPort, type VerifyResult, appendOnlyTables, canTransition, canonicalOf, documentBodyVersioning, documentEntities, documentIdentifiers, documentMigrations, documentRoleStatements, documentStore, fieldPatterns, hashOf, isSystemActor, isTerminalStatus, migrateBody, stampBody, systemActor, validatorOf };