@molecule/api-resource-version-history 1.0.4 → 1.0.6

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/README.md CHANGED
@@ -3,15 +3,11 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-08-04T01:49:24.369Z
6
+ Generated: 2026-10-16T23:31:39.608Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-resource-version-history
10
10
 
11
- > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
12
- > It is written to be read by coding agents as much as by people, and is generated from this
13
- > package's source — edit `src/index.ts` JSDoc, not this file.
14
-
15
11
  Append-only version history resource for molecule.dev.
16
12
 
17
13
  Polymorphic, append-only `versions` table that captures full snapshots of
@@ -21,6 +17,10 @@ DELETE for individual versions, by design. Restoring a prior version
21
17
  appends a new version whose snapshot equals the target's; the existing
22
18
  rows are never mutated.
23
19
 
20
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
21
+ > It is written to be read by coding agents as much as by people, and is generated from this
22
+ > package's source — edit `src/index.ts` JSDoc, not this file.
23
+
24
24
  ## Quick Start
25
25
 
26
26
  ```typescript
@@ -75,52 +75,20 @@ npm install @molecule/api-resource-version-history @molecule/api-database @molec
75
75
 
76
76
  ### Interfaces
77
77
 
78
- #### `CreateVersionInput`
78
+ #### `VersionOwnershipContext`
79
79
 
80
- Input for creating a new version.
80
+ The context an ownership resolver receives to decide access. `userId` is the
81
+ authenticated caller (re-derived from `res.locals.session.userId`, never
82
+ client-supplied).
81
83
 
82
84
  ```typescript
83
- interface CreateVersionInput {
84
- /** The type of resource being versioned. */
85
+ interface VersionOwnershipContext {
86
+ /** The parent resource type (e.g. `'document'`, `'project'`). */
85
87
  resourceType: string
86
- /** The ID of the resource being versioned. */
88
+ /** The parent resource id whose versions are being accessed. */
87
89
  resourceId: string
88
- /** Full snapshot of the resource. */
89
- snapshot: JSONValue
90
- /** ID of the user creating this version, or `null` for system-generated versions. */
91
- userId?: string | null
92
- /** Optional human-readable reason. */
93
- reason?: string | null
94
- }
95
- ```
96
-
97
- #### `PaginatedResult`
98
-
99
- A paginated result set.
100
-
101
- ```typescript
102
- interface PaginatedResult<T> {
103
- /** The result items for the current page. */
104
- data: T[]
105
- /** Total number of matching items across all pages. */
106
- total: number
107
- /** Maximum number of results per page. */
108
- limit: number
109
- /** Number of results skipped. */
110
- offset: number
111
- }
112
- ```
113
-
114
- #### `PaginationOptions`
115
-
116
- Options for paginated queries.
117
-
118
- ```typescript
119
- interface PaginationOptions {
120
- /** Maximum number of results to return. */
121
- limit?: number
122
- /** Number of results to skip. */
123
- offset?: number
90
+ /** The authenticated caller's user id. */
91
+ userId: string
124
92
  }
125
93
  ```
126
94
 
@@ -154,21 +122,6 @@ interface Version {
154
122
  }
155
123
  ```
156
124
 
157
- #### `VersionDiff`
158
-
159
- Result of comparing two versions of the same resource.
160
-
161
- ```typescript
162
- interface VersionDiff {
163
- /** The earlier version. */
164
- from: Version
165
- /** The later version. */
166
- to: Version
167
- /** Per-field changes between `from.snapshot` and `to.snapshot`. */
168
- changes: VersionChanges
169
- }
170
- ```
171
-
172
125
  #### `VersionFieldChange`
173
126
 
174
127
  Per-field change record for a single key. `before` is the previous value,
@@ -183,42 +136,72 @@ interface VersionFieldChange {
183
136
  }
184
137
  ```
185
138
 
186
- #### `VersionOwnershipContext`
139
+ #### `CreateVersionInput`
187
140
 
188
- The context an ownership resolver receives to decide access. `userId` is the
189
- authenticated caller (re-derived from `res.locals.session.userId`, never
190
- client-supplied).
141
+ Input for creating a new version.
191
142
 
192
143
  ```typescript
193
- interface VersionOwnershipContext {
194
- /** The parent resource type (e.g. `'document'`, `'project'`). */
144
+ interface CreateVersionInput {
145
+ /** The type of resource being versioned. */
195
146
  resourceType: string
196
- /** The parent resource id whose versions are being accessed. */
147
+ /** The ID of the resource being versioned. */
197
148
  resourceId: string
198
- /** The authenticated caller's user id. */
199
- userId: string
149
+ /** Full snapshot of the resource. */
150
+ snapshot: JSONValue
151
+ /** ID of the user creating this version, or `null` for system-generated versions. */
152
+ userId?: string | null
153
+ /** Optional human-readable reason. */
154
+ reason?: string | null
200
155
  }
201
156
  ```
202
157
 
203
- ### Types
158
+ #### `VersionDiff`
204
159
 
205
- #### `JSONValue`
160
+ Result of comparing two versions of the same resource.
206
161
 
207
- A JSON-serializable snapshot value. Constrained by what the underlying
208
- `JSONB` column can accept.
162
+ ```typescript
163
+ interface VersionDiff {
164
+ /** The earlier version. */
165
+ from: Version
166
+ /** The later version. */
167
+ to: Version
168
+ /** Per-field changes between `from.snapshot` and `to.snapshot`. */
169
+ changes: VersionChanges
170
+ }
171
+ ```
172
+
173
+ #### `PaginationOptions`
174
+
175
+ Options for paginated queries.
209
176
 
210
177
  ```typescript
211
- type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue }
178
+ interface PaginationOptions {
179
+ /** Maximum number of results to return. */
180
+ limit?: number
181
+ /** Number of results to skip. */
182
+ offset?: number
183
+ }
212
184
  ```
213
185
 
214
- #### `VersionChanges`
186
+ #### `PaginatedResult`
215
187
 
216
- Shallow per-field diff between two snapshots, keyed by field name.
188
+ A paginated result set.
217
189
 
218
190
  ```typescript
219
- type VersionChanges = Record<string, VersionFieldChange>
191
+ interface PaginatedResult<T> {
192
+ /** The result items for the current page. */
193
+ data: T[]
194
+ /** Total number of matching items across all pages. */
195
+ total: number
196
+ /** Maximum number of results per page. */
197
+ limit: number
198
+ /** Number of results skipped. */
199
+ offset: number
200
+ }
220
201
  ```
221
202
 
203
+ ### Types
204
+
222
205
  #### `VersionOwnershipResolver`
223
206
 
224
207
  Resolves whether the authenticated caller may read/restore versions of a
@@ -229,78 +212,95 @@ async (e.g. it can look the parent resource up in the database).
229
212
  type VersionOwnershipResolver = (context: VersionOwnershipContext) => boolean | Promise<boolean>
230
213
  ```
231
214
 
232
- ### Functions
215
+ - `context` — The {@link VersionOwnershipContext} to authorize.
233
216
 
234
- #### `clearOwnershipResolvers()`
217
+ **Returns:** `true` when the caller owns / may access the parent resource.
235
218
 
236
- Clears all registered ownership resolvers. Primarily useful in tests.
219
+ #### `JSONValue`
220
+
221
+ A JSON-serializable snapshot value. Constrained by what the underlying
222
+ `JSONB` column can accept.
237
223
 
238
224
  ```typescript
239
- function clearOwnershipResolvers(): void
225
+ type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue }
240
226
  ```
241
227
 
242
- #### `create(req, res)`
243
-
244
- Captures a new version of a resource.
228
+ #### `VersionChanges`
245
229
 
246
- Secure by default: returns 401 with no session, and 404 (no existence leak)
247
- when the caller is not authorized for the parent resource — a caller can only
248
- capture versions of a resource they own, never inject snapshots into another
249
- tenant's resource.
230
+ Shallow per-field diff between two snapshots, keyed by field name.
250
231
 
251
232
  ```typescript
252
- function create(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
233
+ type VersionChanges = Record<string, VersionFieldChange>
253
234
  ```
254
235
 
255
- - `req` — The request with `resourceType` / `resourceId` params and a snapshot body.
256
- - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
257
-
258
- #### `createVersion(input)`
236
+ ### Functions
259
237
 
260
- Captures a new version of a resource.
238
+ #### `isVersionAuthorized(res, context)`
261
239
 
262
- Reads the latest existing version for `(resourceType, resourceId)` to
263
- compute the next version number and the shallow diff against the prior
264
- snapshot. The resulting row is append-only.
240
+ Authorizes whether the authenticated caller may access versions of a parent
241
+ resource. Admins widened by {@link versionHistoryAdmin} are always allowed;
242
+ otherwise the app-registered {@link VersionOwnershipResolver} for the parent
243
+ `resourceType` decides. **Fail-closed:** when no resolver is registered the
244
+ caller is denied, so the polymorphic version store never leaks a snapshot it
245
+ cannot prove the caller owns.
265
246
 
266
247
  ```typescript
267
- function createVersion(input: CreateVersionInput): Promise<Version>
248
+ function isVersionAuthorized(
249
+ res: MoleculeResponse,
250
+ context: VersionOwnershipContext,
251
+ ): Promise<boolean>
268
252
  ```
269
253
 
270
- - `input` — The version creation input.
254
+ - `res` — The response whose `locals.session`/`locals.versionHistoryAdmin` is inspected.
255
+ - `context` — The {@link VersionOwnershipContext} (parent resource + caller).
271
256
 
272
- **Returns:** The created version.
257
+ **Returns:** `true` when the caller may access the parent resource's versions.
273
258
 
274
- #### `deleteVersionsForResource(resourceType, resourceId)`
259
+ #### `isVersionHistoryAdmin(res)`
275
260
 
276
- Deletes every version for a resource. Intended for cleanup when the parent
277
- resource itself is deleted; never call from user-facing handlers without
278
- authorization checks.
261
+ Resolves whether the current request's session belongs to an actor
262
+ authorized to administer version history (read/restore any user's versions).
263
+ Fail-closed: returns `false` when there is no authenticated session, and
264
+ otherwise only `true` when the session carries an admin claim — `isAdmin ===
265
+ true`, `role === 'admin'`, `roles` containing `'admin'`, or `permissions`
266
+ containing `'admin'` / `'versionHistory:manage'`.
279
267
 
280
268
  ```typescript
281
- function deleteVersionsForResource(resourceType: string, resourceId: string): Promise<number>
269
+ function isVersionHistoryAdmin(res: MoleculeResponse): boolean
282
270
  ```
283
271
 
284
- - `resourceType` — The resource type.
285
- - `resourceId` — The resource ID.
272
+ - `res` — The response whose `locals.session` is inspected.
286
273
 
287
- **Returns:** The number of versions deleted.
274
+ **Returns:** `true` when the session is an authorized version-history admin.
288
275
 
289
- #### `diff(req, res)`
276
+ #### `versionHistoryAdmin()`
290
277
 
291
- Returns the shallow diff between two versions of the same resource.
278
+ Opt-in route middleware that _widens_ an authenticated admin to cross-tenant
279
+ version access by setting `res.locals.versionHistoryAdmin = true`. It never
280
+ blocks: a non-admin (or anonymous) caller passes through unchanged and
281
+ remains subject to the ownership resolver in the handlers, so composing this
282
+ onto a route can only widen for admins, never open the endpoint. Wire it onto
283
+ a dedicated admin route when a support/compliance console needs to read or
284
+ restore every user's versions.
292
285
 
293
- Secure by default: returns 401 with no session, and 404 (no existence leak)
294
- when either version is missing OR the caller is not authorized for the parent
295
- resource the two versions share. An opt-in {@link versionHistoryAdmin} may
296
- diff any versions.
286
+ ```typescript
287
+ function versionHistoryAdmin(): MoleculeRequestHandler
288
+ ```
289
+
290
+ **Returns:** An Express-compatible middleware function.
291
+
292
+ #### `jsonEqual(a, b)`
293
+
294
+ Returns `true` if `a` and `b` are deeply equal as JSON values.
297
295
 
298
296
  ```typescript
299
- function diff(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
297
+ function jsonEqual(a: JSONValue | undefined, b: JSONValue | undefined): boolean
300
298
  ```
301
299
 
302
- - `req` — The request with `fromVersionId` and `toVersionId` params.
303
- - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
300
+ - `a` — First value to compare.
301
+ - `b` — Second value to compare.
302
+
303
+ **Returns:** Whether the two values are structurally equal.
304
304
 
305
305
  #### `diffSnapshots(before, after)`
306
306
 
@@ -320,237 +320,255 @@ function diffSnapshots(before: JSONValue, after: JSONValue): VersionChanges
320
320
 
321
321
  **Returns:** A {@link VersionChanges} record. Empty when the snapshots are equal.
322
322
 
323
- #### `diffVersions(fromVersionId, toVersionId)`
323
+ #### `versionCount(req, res)`
324
324
 
325
- Compares two versions and returns the shallow diff between their snapshots.
325
+ Returns the total number of versions for a resource.
326
326
 
327
- The argument order does not matter — the lower-numbered version is always
328
- treated as `from`, the higher-numbered as `to`, so `changes` describes the
329
- forward delta.
327
+ Secure by default: returns 401 with no session, and 404 (no existence leak)
328
+ when the caller is not authorized for the parent resource.
330
329
 
331
330
  ```typescript
332
- function diffVersions(fromVersionId: string, toVersionId: string): Promise<VersionDiff | null>
331
+ function versionCount(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
333
332
  ```
334
333
 
335
- - `fromVersionId` — One version ID to compare.
336
- - `toVersionId` — The other version ID to compare.
334
+ - `req` — The request with `resourceType` and `resourceId` params.
335
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
337
336
 
338
- **Returns:** The {@link VersionDiff}, or `null` if either version is missing or the two versions belong to different resources.
337
+ #### `create(req, res)`
339
338
 
340
- #### `getLatestVersion(resourceType, resourceId)`
339
+ Captures a new version of a resource.
341
340
 
342
- Returns the most recent version for a resource, or `null` if no versions exist.
341
+ Secure by default: returns 401 with no session, and 404 (no existence leak)
342
+ when the caller is not authorized for the parent resource — a caller can only
343
+ capture versions of a resource they own, never inject snapshots into another
344
+ tenant's resource.
343
345
 
344
346
  ```typescript
345
- function getLatestVersion(resourceType: string, resourceId: string): Promise<Version | null>
347
+ function create(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
346
348
  ```
347
349
 
348
- - `resourceType` — The resource type.
349
- - `resourceId` — The resource ID.
350
+ - `req` — The request with `resourceType` / `resourceId` params and a snapshot body.
351
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
350
352
 
351
- **Returns:** The latest version, or `null`.
353
+ #### `diff(req, res)`
352
354
 
353
- #### `getOwnershipResolver(resourceType)`
355
+ Returns the shallow diff between two versions of the same resource.
354
356
 
355
- Returns the ownership resolver registered for a resource type, or
356
- `undefined` if none has been registered.
357
+ Secure by default: returns 401 with no session, and 404 (no existence leak)
358
+ when either version is missing OR the caller is not authorized for the parent
359
+ resource the two versions share. An opt-in {@link versionHistoryAdmin} may
360
+ diff any versions.
357
361
 
358
362
  ```typescript
359
- function getOwnershipResolver(resourceType: string): VersionOwnershipResolver | undefined
363
+ function diff(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
360
364
  ```
361
365
 
362
- - `resourceType` — The resource type to look up.
366
+ - `req` — The request with `fromVersionId` and `toVersionId` params.
367
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
363
368
 
364
- **Returns:** The resolver, or `undefined`.
369
+ #### `list(req, res)`
365
370
 
366
- #### `getVersionById(versionId)`
371
+ Lists paginated versions for a resource, newest version first.
367
372
 
368
- Retrieves a version by ID.
373
+ Secure by default: returns 401 with no session, and 404 (no existence leak)
374
+ when the caller is not authorized for the parent resource — only the parent
375
+ resource's owner (or an opt-in {@link versionHistoryAdmin}) sees its versions.
369
376
 
370
377
  ```typescript
371
- function getVersionById(versionId: string): Promise<Version | null>
378
+ function list(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
372
379
  ```
373
380
 
374
- - `versionId` — The version ID.
381
+ - `req` — The request with `resourceType` and `resourceId` params.
382
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
375
383
 
376
- **Returns:** The version, or `null` if not found.
384
+ #### `read(req, res)`
377
385
 
378
- #### `getVersionByNumber(resourceType, resourceId, version)`
386
+ Reads a single version by ID.
379
387
 
380
- Retrieves a version by resource and version number.
388
+ Secure by default: returns 401 with no session, and 404 (no existence leak)
389
+ when the version is missing OR the caller is not authorized for its parent
390
+ resource — a non-owner cannot tell the two apart, so another tenant's
391
+ snapshot is never disclosed. An opt-in {@link versionHistoryAdmin} may read
392
+ any version.
381
393
 
382
394
  ```typescript
383
- function getVersionByNumber(
384
- resourceType: string,
385
- resourceId: string,
386
- version: number,
387
- ): Promise<Version | null>
395
+ function read(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
388
396
  ```
389
397
 
390
- - `resourceType` — The resource type.
391
- - `resourceId` — The resource ID.
392
- - `version` — The 1-based version number.
398
+ - `req` — The request with `versionId` param.
399
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
393
400
 
394
- **Returns:** The version, or `null` if not found.
401
+ #### `readByNumber(req, res)`
395
402
 
396
- #### `getVersionCount(resourceType, resourceId)`
403
+ Reads a single version of a resource by 1-based version number.
397
404
 
398
- Returns the total number of versions for a resource.
405
+ Secure by default: returns 401 with no session, and 404 (no existence leak)
406
+ when the caller is not authorized for the parent resource.
399
407
 
400
408
  ```typescript
401
- function getVersionCount(resourceType: string, resourceId: string): Promise<number>
409
+ function readByNumber(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
402
410
  ```
403
411
 
404
- - `resourceType` — The resource type.
405
- - `resourceId` — The resource ID.
412
+ - `req` — The request with `resourceType`, `resourceId`, and `version` params.
413
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
406
414
 
407
- **Returns:** The version count.
415
+ #### `restore(req, res)`
408
416
 
409
- #### `getVersionsForResource(resourceType, resourceId, options)`
417
+ Restores a prior version by appending a new version whose snapshot
418
+ matches it. Append-only — the existing rows are never mutated.
410
419
 
411
- Retrieves paginated versions for a resource, ordered by version number descending.
420
+ Secure by default: returns 401 with no session, and 404 (no existence leak)
421
+ when the version is missing OR the caller is not authorized for its parent
422
+ resource — a non-owner can neither restore another tenant's version nor learn
423
+ that it exists. An opt-in {@link versionHistoryAdmin} may restore any version.
412
424
 
413
425
  ```typescript
414
- function getVersionsForResource(
415
- resourceType: string,
416
- resourceId: string,
417
- options?: PaginationOptions,
418
- ): Promise<PaginatedResult<Version>>
426
+ function restore(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
419
427
  ```
420
428
 
421
- - `resourceType` — The resource type.
422
- - `resourceId` — The resource ID.
423
- - `options` — Pagination options.
429
+ - `req` — The request with `versionId` param.
430
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
424
431
 
425
- **Returns:** A paginated result of versions.
432
+ #### `registerOwnershipResolver(resourceType, resolver)`
426
433
 
427
- #### `isVersionAuthorized(res, context)`
434
+ Registers an ownership resolver for a parent resource type.
428
435
 
429
- Authorizes whether the authenticated caller may access versions of a parent
430
- resource. Admins widened by {@link versionHistoryAdmin} are always allowed;
431
- otherwise the app-registered {@link VersionOwnershipResolver} for the parent
432
- `resourceType` decides. **Fail-closed:** when no resolver is registered the
433
- caller is denied, so the polymorphic version store never leaks a snapshot it
434
- cannot prove the caller owns.
436
+ Subsequent calls with the same `resourceType` overwrite the previous
437
+ registration.
435
438
 
436
439
  ```typescript
437
- function isVersionAuthorized(
438
- res: MoleculeResponse,
439
- context: VersionOwnershipContext,
440
- ): Promise<boolean>
440
+ function registerOwnershipResolver(resourceType: string, resolver: VersionOwnershipResolver): void
441
441
  ```
442
442
 
443
- - `res` — The response whose `locals.session`/`locals.versionHistoryAdmin` is inspected.
444
- - `context` — The {@link VersionOwnershipContext} (parent resource + caller).
443
+ - `resourceType` — The parent resource type the resolver authorizes.
444
+ - `resolver` — The resolver to invoke when authorizing access to versions of this resource type.
445
445
 
446
- **Returns:** `true` when the caller may access the parent resource's versions.
446
+ #### `getOwnershipResolver(resourceType)`
447
447
 
448
- #### `isVersionHistoryAdmin(res)`
448
+ Returns the ownership resolver registered for a resource type, or
449
+ `undefined` if none has been registered.
449
450
 
450
- Resolves whether the current request's session belongs to an actor
451
- authorized to administer version history (read/restore any user's versions).
452
- Fail-closed: returns `false` when there is no authenticated session, and
453
- otherwise only `true` when the session carries an admin claim — `isAdmin ===
454
- true`, `role === 'admin'`, `roles` containing `'admin'`, or `permissions`
455
- containing `'admin'` / `'versionHistory:manage'`.
451
+ ```typescript
452
+ function getOwnershipResolver(resourceType: string): VersionOwnershipResolver | undefined
453
+ ```
454
+
455
+ - `resourceType` — The resource type to look up.
456
+
457
+ **Returns:** The resolver, or `undefined`.
458
+
459
+ #### `unregisterOwnershipResolver(resourceType)`
460
+
461
+ Removes any registered ownership resolver for the given resource type.
456
462
 
457
463
  ```typescript
458
- function isVersionHistoryAdmin(res: MoleculeResponse): boolean
464
+ function unregisterOwnershipResolver(resourceType: string): boolean
459
465
  ```
460
466
 
461
- - `res` — The response whose `locals.session` is inspected.
467
+ - `resourceType` — The resource type whose resolver should be removed.
462
468
 
463
- **Returns:** `true` when the session is an authorized version-history admin.
469
+ **Returns:** `true` if a resolver was removed.
464
470
 
465
- #### `jsonEqual(a, b)`
471
+ #### `clearOwnershipResolvers()`
466
472
 
467
- Returns `true` if `a` and `b` are deeply equal as JSON values.
473
+ Clears all registered ownership resolvers. Primarily useful in tests.
468
474
 
469
475
  ```typescript
470
- function jsonEqual(a: JSONValue | undefined, b: JSONValue | undefined): boolean
476
+ function clearOwnershipResolvers(): void
471
477
  ```
472
478
 
473
- - `a` — First value to compare.
474
- - `b` — Second value to compare.
479
+ #### `createVersion(input)`
475
480
 
476
- **Returns:** Whether the two values are structurally equal.
481
+ Captures a new version of a resource.
477
482
 
478
- #### `list(req, res)`
483
+ Reads the latest existing version for `(resourceType, resourceId)` to
484
+ compute the next version number and the shallow diff against the prior
485
+ snapshot. The resulting row is append-only.
479
486
 
480
- Lists paginated versions for a resource, newest version first.
487
+ ```typescript
488
+ function createVersion(input: CreateVersionInput): Promise<Version>
489
+ ```
481
490
 
482
- Secure by default: returns 401 with no session, and 404 (no existence leak)
483
- when the caller is not authorized for the parent resource — only the parent
484
- resource's owner (or an opt-in {@link versionHistoryAdmin}) sees its versions.
491
+ - `input` — The version creation input.
492
+
493
+ **Returns:** The created version.
494
+
495
+ #### `getLatestVersion(resourceType, resourceId)`
496
+
497
+ Returns the most recent version for a resource, or `null` if no versions exist.
485
498
 
486
499
  ```typescript
487
- function list(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
500
+ function getLatestVersion(resourceType: string, resourceId: string): Promise<Version | null>
488
501
  ```
489
502
 
490
- - `req` — The request with `resourceType` and `resourceId` params.
491
- - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
503
+ - `resourceType` — The resource type.
504
+ - `resourceId` — The resource ID.
492
505
 
493
- #### `read(req, res)`
506
+ **Returns:** The latest version, or `null`.
494
507
 
495
- Reads a single version by ID.
508
+ #### `getVersionsForResource(resourceType, resourceId, options)`
496
509
 
497
- Secure by default: returns 401 with no session, and 404 (no existence leak)
498
- when the version is missing OR the caller is not authorized for its parent
499
- resource — a non-owner cannot tell the two apart, so another tenant's
500
- snapshot is never disclosed. An opt-in {@link versionHistoryAdmin} may read
501
- any version.
510
+ Retrieves paginated versions for a resource, ordered by version number descending.
502
511
 
503
512
  ```typescript
504
- function read(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
513
+ function getVersionsForResource(
514
+ resourceType: string,
515
+ resourceId: string,
516
+ options?: PaginationOptions,
517
+ ): Promise<PaginatedResult<Version>>
505
518
  ```
506
519
 
507
- - `req` — The request with `versionId` param.
508
- - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
520
+ - `resourceType` — The resource type.
521
+ - `resourceId` — The resource ID.
522
+ - `options` — Pagination options.
509
523
 
510
- #### `readByNumber(req, res)`
524
+ **Returns:** A paginated result of versions.
511
525
 
512
- Reads a single version of a resource by 1-based version number.
526
+ #### `getVersionById(versionId)`
513
527
 
514
- Secure by default: returns 401 with no session, and 404 (no existence leak)
515
- when the caller is not authorized for the parent resource.
528
+ Retrieves a version by ID.
516
529
 
517
530
  ```typescript
518
- function readByNumber(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
531
+ function getVersionById(versionId: string): Promise<Version | null>
519
532
  ```
520
533
 
521
- - `req` — The request with `resourceType`, `resourceId`, and `version` params.
522
- - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
534
+ - `versionId` — The version ID.
523
535
 
524
- #### `registerOwnershipResolver(resourceType, resolver)`
536
+ **Returns:** The version, or `null` if not found.
525
537
 
526
- Registers an ownership resolver for a parent resource type.
538
+ #### `getVersionByNumber(resourceType, resourceId, version)`
527
539
 
528
- Subsequent calls with the same `resourceType` overwrite the previous
529
- registration.
540
+ Retrieves a version by resource and version number.
530
541
 
531
542
  ```typescript
532
- function registerOwnershipResolver(resourceType: string, resolver: VersionOwnershipResolver): void
543
+ function getVersionByNumber(
544
+ resourceType: string,
545
+ resourceId: string,
546
+ version: number,
547
+ ): Promise<Version | null>
533
548
  ```
534
549
 
535
- - `resourceType` — The parent resource type the resolver authorizes.
536
- - `resolver` — The resolver to invoke when authorizing access to versions of this resource type.
550
+ - `resourceType` — The resource type.
551
+ - `resourceId` — The resource ID.
552
+ - `version` — The 1-based version number.
537
553
 
538
- #### `restore(req, res)`
554
+ **Returns:** The version, or `null` if not found.
539
555
 
540
- Restores a prior version by appending a new version whose snapshot
541
- matches it. Append-only — the existing rows are never mutated.
556
+ #### `diffVersions(fromVersionId, toVersionId)`
542
557
 
543
- Secure by default: returns 401 with no session, and 404 (no existence leak)
544
- when the version is missing OR the caller is not authorized for its parent
545
- resource — a non-owner can neither restore another tenant's version nor learn
546
- that it exists. An opt-in {@link versionHistoryAdmin} may restore any version.
558
+ Compares two versions and returns the shallow diff between their snapshots.
559
+
560
+ The argument order does not matter — the lower-numbered version is always
561
+ treated as `from`, the higher-numbered as `to`, so `changes` describes the
562
+ forward delta.
547
563
 
548
564
  ```typescript
549
- function restore(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
565
+ function diffVersions(fromVersionId: string, toVersionId: string): Promise<VersionDiff | null>
550
566
  ```
551
567
 
552
- - `req` — The request with `versionId` param.
553
- - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
568
+ - `fromVersionId` — One version ID to compare.
569
+ - `toVersionId` — The other version ID to compare.
570
+
571
+ **Returns:** The {@link VersionDiff}, or `null` if either version is missing or the two versions belong to different resources.
554
572
 
555
573
  #### `restoreVersion(versionId, userId, reason)`
556
574
 
@@ -574,62 +592,62 @@ function restoreVersion(
574
592
 
575
593
  **Returns:** The newly-appended version, or `null` if `versionId` was not found.
576
594
 
577
- #### `unregisterOwnershipResolver(resourceType)`
595
+ #### `deleteVersionsForResource(resourceType, resourceId)`
578
596
 
579
- Removes any registered ownership resolver for the given resource type.
597
+ Deletes every version for a resource. Intended for cleanup when the parent
598
+ resource itself is deleted; never call from user-facing handlers without
599
+ authorization checks.
580
600
 
581
601
  ```typescript
582
- function unregisterOwnershipResolver(resourceType: string): boolean
602
+ function deleteVersionsForResource(resourceType: string, resourceId: string): Promise<number>
583
603
  ```
584
604
 
585
- - `resourceType` — The resource type whose resolver should be removed.
605
+ - `resourceType` — The resource type.
606
+ - `resourceId` — The resource ID.
586
607
 
587
- **Returns:** `true` if a resolver was removed.
608
+ **Returns:** The number of versions deleted.
588
609
 
589
- #### `versionCount(req, res)`
610
+ #### `getVersionCount(resourceType, resourceId)`
590
611
 
591
612
  Returns the total number of versions for a resource.
592
613
 
593
- Secure by default: returns 401 with no session, and 404 (no existence leak)
594
- when the caller is not authorized for the parent resource.
595
-
596
614
  ```typescript
597
- function versionCount(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
615
+ function getVersionCount(resourceType: string, resourceId: string): Promise<number>
598
616
  ```
599
617
 
600
- - `req` — The request with `resourceType` and `resourceId` params.
601
- - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
618
+ - `resourceType` — The resource type.
619
+ - `resourceId` — The resource ID.
602
620
 
603
- #### `versionHistoryAdmin()`
621
+ **Returns:** The version count.
604
622
 
605
- Opt-in route middleware that _widens_ an authenticated admin to cross-tenant
606
- version access by setting `res.locals.versionHistoryAdmin = true`. It never
607
- blocks: a non-admin (or anonymous) caller passes through unchanged and
608
- remains subject to the ownership resolver in the handlers, so composing this
609
- onto a route can only widen for admins, never open the endpoint. Wire it onto
610
- a dedicated admin route when a support/compliance console needs to read or
611
- restore every user's versions.
623
+ ### Constants
624
+
625
+ #### `VERSION_HISTORY_PERMISSION_ACTION`
626
+
627
+ Permission action describing version-history administration, e.g. for an
628
+ app's own `@molecule/api-permissions` wiring.
612
629
 
613
630
  ```typescript
614
- function versionHistoryAdmin(): MoleculeRequestHandler
631
+ const VERSION_HISTORY_PERMISSION_ACTION: 'manage'
615
632
  ```
616
633
 
617
- **Returns:** An Express-compatible middleware function.
634
+ #### `VERSION_HISTORY_PERMISSION_RESOURCE`
618
635
 
619
- ### Constants
636
+ Permission resource describing version-history administration, e.g. for an
637
+ app's own `@molecule/api-permissions` wiring.
620
638
 
621
- #### `createVersionSchema`
639
+ ```typescript
640
+ const VERSION_HISTORY_PERMISSION_RESOURCE: 'versionHistory'
641
+ ```
622
642
 
623
- Schema for validating create-version input.
643
+ #### `VERSION_HISTORY_ADMIN_PERMISSION`
644
+
645
+ Session-claim permission string (`'versionHistory:manage'`) that, when
646
+ present in a session's `permissions` array, marks the caller as a
647
+ version-history admin.
624
648
 
625
649
  ```typescript
626
- const createVersionSchema: z.ZodObject<
627
- {
628
- snapshot: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>
629
- reason: z.ZodNullable<z.ZodOptional<z.ZodString>>
630
- },
631
- z.core.$strip
632
- >
650
+ const VERSION_HISTORY_ADMIN_PERMISSION: 'versionHistory:manage'
633
651
  ```
634
652
 
635
653
  #### `i18nRegistered`
@@ -656,18 +674,6 @@ const requestHandlerMap: {
656
674
  }
657
675
  ```
658
676
 
659
- #### `restoreVersionSchema`
660
-
661
- Schema for validating restore-version input. Body is empty — the version
662
- to restore is identified by URL params.
663
-
664
- ```typescript
665
- const restoreVersionSchema: z.ZodObject<
666
- { reason: z.ZodOptional<z.ZodNullable<z.ZodOptional<z.ZodString>>> },
667
- z.core.$strip
668
- >
669
- ```
670
-
671
677
  #### `routes`
672
678
 
673
679
  Routes for the version-history resource. All routes require `authenticate`;
@@ -721,32 +727,30 @@ const routes: readonly [
721
727
  ]
722
728
  ```
723
729
 
724
- #### `VERSION_HISTORY_ADMIN_PERMISSION`
725
-
726
- Session-claim permission string (`'versionHistory:manage'`) that, when
727
- present in a session's `permissions` array, marks the caller as a
728
- version-history admin.
729
-
730
- ```typescript
731
- const VERSION_HISTORY_ADMIN_PERMISSION: 'versionHistory:manage'
732
- ```
733
-
734
- #### `VERSION_HISTORY_PERMISSION_ACTION`
730
+ #### `createVersionSchema`
735
731
 
736
- Permission action describing version-history administration, e.g. for an
737
- app's own `@molecule/api-permissions` wiring.
732
+ Schema for validating create-version input.
738
733
 
739
734
  ```typescript
740
- const VERSION_HISTORY_PERMISSION_ACTION: 'manage'
735
+ const createVersionSchema: z.ZodObject<
736
+ {
737
+ snapshot: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>
738
+ reason: z.ZodNullable<z.ZodOptional<z.ZodString>>
739
+ },
740
+ z.core.$strip
741
+ >
741
742
  ```
742
743
 
743
- #### `VERSION_HISTORY_PERMISSION_RESOURCE`
744
+ #### `restoreVersionSchema`
744
745
 
745
- Permission resource describing version-history administration, e.g. for an
746
- app's own `@molecule/api-permissions` wiring.
746
+ Schema for validating restore-version input. Body is empty — the version
747
+ to restore is identified by URL params.
747
748
 
748
749
  ```typescript
749
- const VERSION_HISTORY_PERMISSION_RESOURCE: 'versionHistory'
750
+ const restoreVersionSchema: z.ZodObject<
751
+ { reason: z.ZodOptional<z.ZodNullable<z.ZodOptional<z.ZodString>>> },
752
+ z.core.$strip
753
+ >
750
754
  ```
751
755
 
752
756
  ## Injection Notes
@@ -790,7 +794,7 @@ Peer dependencies:
790
794
  either a registered resolver or your own resource-ownership gate.
791
795
 
792
796
  Tables: `src/__setup__/versions.sql` creates `versions`. An mlcl-scaffolded
793
- API replays `__setup__/*.sql` automatically on migrate; anywhere else run it
797
+ API replays `__setup__/*.sql` on migrate (a `CREATE TABLE IF NOT EXISTS`, so a table the app's own migrations already create keeps only its own columns: ALTER in the ones it lacks); anywhere else run it
794
798
  once — nothing at runtime creates them. Handler errors flow through `t()`
795
799
  with English defaults; install `@molecule/api-locales-resource-version-history`
796
800
  and register it with `registerLocaleModule` for translations.
package/dist/index.d.ts CHANGED
@@ -28,7 +28,7 @@
28
28
  * either a registered resolver or your own resource-ownership gate.
29
29
  *
30
30
  * Tables: `src/__setup__/versions.sql` creates `versions`. An mlcl-scaffolded
31
- * API replays `__setup__/*.sql` automatically on migrate; anywhere else run it
31
+ * API replays `__setup__/*.sql` on migrate (a `CREATE TABLE IF NOT EXISTS`, so a table the app's own migrations already create keeps only its own columns: ALTER in the ones it lacks); anywhere else run it
32
32
  * once — nothing at runtime creates them. Handler errors flow through `t()`
33
33
  * with English defaults; install `@molecule/api-locales-resource-version-history`
34
34
  * and register it with `registerLocaleModule` for translations.
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@
28
28
  * either a registered resolver or your own resource-ownership gate.
29
29
  *
30
30
  * Tables: `src/__setup__/versions.sql` creates `versions`. An mlcl-scaffolded
31
- * API replays `__setup__/*.sql` automatically on migrate; anywhere else run it
31
+ * API replays `__setup__/*.sql` on migrate (a `CREATE TABLE IF NOT EXISTS`, so a table the app's own migrations already create keeps only its own columns: ALTER in the ones it lacks); anywhere else run it
32
32
  * once — nothing at runtime creates them. Handler errors flow through `t()`
33
33
  * with English defaults; install `@molecule/api-locales-resource-version-history`
34
34
  * and register it with `registerLocaleModule` for translations.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-resource-version-history",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "Append-only versions table with diff and restore — generic versioning helper for any resource.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -32,10 +32,10 @@
32
32
  "license": "Apache-2.0",
33
33
  "devDependencies": {
34
34
  "@molecule/api-locales-resource-version-history": "1.0.2",
35
- "@types/node": "26.1.2",
35
+ "@types/node": "26.6.5",
36
36
  "typescript": "6.0.3",
37
- "vitest": "4.1.11",
38
- "zod": "4.4.3"
37
+ "vitest": "4.1.12",
38
+ "zod": "4.6.7"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@molecule/api-database": "^1.0.1",