@molecule/api-resource-version-history 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,845 @@
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-08-04T01:49:24.369Z
7
+ -->
8
+
9
+ # @molecule/api-resource-version-history
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
+ Append-only version history resource for molecule.dev.
16
+
17
+ Polymorphic, append-only `versions` table that captures full snapshots of
18
+ any resource type, plus a shallow diff against the prior version. Routes
19
+ surface list / read / count / diff / restore — there is no UPDATE or
20
+ DELETE for individual versions, by design. Restoring a prior version
21
+ appends a new version whose snapshot equals the target's; the existing
22
+ rows are never mutated.
23
+
24
+ ## Quick Start
25
+
26
+ ```typescript
27
+ import {
28
+ routes,
29
+ requestHandlerMap,
30
+ createVersion,
31
+ registerOwnershipResolver,
32
+ } from '@molecule/api-resource-version-history'
33
+
34
+ // REQUIRED before mounting the routes: tell version-history how to check
35
+ // parent-resource ownership for each resource type you version. Without this
36
+ // every read/list/diff/restore fails closed (404) — the routes are never open.
37
+ registerOwnershipResolver('document', async ({ resourceId, userId }) => {
38
+ const doc = await findById('documents', resourceId)
39
+ return doc?.userId === userId
40
+ })
41
+
42
+ // Wire routes via mlcl inject:
43
+ // POST /:resourceType/:resourceId/versions
44
+ // GET /:resourceType/:resourceId/versions
45
+ // GET /:resourceType/:resourceId/versions/count
46
+ // GET /:resourceType/:resourceId/versions/:version
47
+ // GET /versions/:versionId
48
+ // POST /versions/:versionId/restore
49
+ // GET /versions/:fromVersionId/diff/:toVersionId
50
+
51
+ // Or call the service directly from another resource's update handler.
52
+ // The acting user ALWAYS comes from the session (res.locals.session) —
53
+ // never from the request body:
54
+ const userId = (res.locals.session as { userId?: string } | undefined)?.userId
55
+ await createVersion({
56
+ resourceType: 'document',
57
+ resourceId: doc.id,
58
+ userId: userId ?? null,
59
+ snapshot: doc,
60
+ reason: 'autosave',
61
+ })
62
+ ```
63
+
64
+ ## Type
65
+
66
+ `resource`
67
+
68
+ ## Installation
69
+
70
+ ```bash
71
+ npm install @molecule/api-resource-version-history @molecule/api-database @molecule/api-i18n @molecule/api-locales-resource-version-history @molecule/api-logger @molecule/api-resource zod
72
+ ```
73
+
74
+ ## API
75
+
76
+ ### Interfaces
77
+
78
+ #### `CreateVersionInput`
79
+
80
+ Input for creating a new version.
81
+
82
+ ```typescript
83
+ interface CreateVersionInput {
84
+ /** The type of resource being versioned. */
85
+ resourceType: string
86
+ /** The ID of the resource being versioned. */
87
+ 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
124
+ }
125
+ ```
126
+
127
+ #### `Version`
128
+
129
+ A point-in-time snapshot of a resource.
130
+
131
+ Versions are append-only. A new row is created each time the resource
132
+ changes; old rows are never mutated.
133
+
134
+ ```typescript
135
+ interface Version {
136
+ /** Unique version identifier. */
137
+ id: string
138
+ /** The type of resource this version belongs to (e.g. `'document'`, `'project'`). */
139
+ resourceType: string
140
+ /** The ID of the resource this version belongs to. */
141
+ resourceId: string
142
+ /** The monotonically-increasing version number for this resource (1-based). */
143
+ version: number
144
+ /** The ID of the user who created this version, or `null` if system-generated. */
145
+ userId: string | null
146
+ /** Full snapshot of the resource at this point in time. */
147
+ snapshot: JSONValue
148
+ /** Shallow diff against the previous version, or `null` if this is the first version. */
149
+ changes: VersionChanges | null
150
+ /** Optional human-readable reason for this version (e.g. commit message). */
151
+ reason: string | null
152
+ /** When this version was created (ISO 8601). */
153
+ createdAt: string
154
+ }
155
+ ```
156
+
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
+ #### `VersionFieldChange`
173
+
174
+ Per-field change record for a single key. `before` is the previous value,
175
+ `after` is the new value. Either may be `undefined` for added/removed fields.
176
+
177
+ ```typescript
178
+ interface VersionFieldChange {
179
+ /** Previous value (`undefined` if the field was added). */
180
+ before?: JSONValue
181
+ /** New value (`undefined` if the field was removed). */
182
+ after?: JSONValue
183
+ }
184
+ ```
185
+
186
+ #### `VersionOwnershipContext`
187
+
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).
191
+
192
+ ```typescript
193
+ interface VersionOwnershipContext {
194
+ /** The parent resource type (e.g. `'document'`, `'project'`). */
195
+ resourceType: string
196
+ /** The parent resource id whose versions are being accessed. */
197
+ resourceId: string
198
+ /** The authenticated caller's user id. */
199
+ userId: string
200
+ }
201
+ ```
202
+
203
+ ### Types
204
+
205
+ #### `JSONValue`
206
+
207
+ A JSON-serializable snapshot value. Constrained by what the underlying
208
+ `JSONB` column can accept.
209
+
210
+ ```typescript
211
+ type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue }
212
+ ```
213
+
214
+ #### `VersionChanges`
215
+
216
+ Shallow per-field diff between two snapshots, keyed by field name.
217
+
218
+ ```typescript
219
+ type VersionChanges = Record<string, VersionFieldChange>
220
+ ```
221
+
222
+ #### `VersionOwnershipResolver`
223
+
224
+ Resolves whether the authenticated caller may read/restore versions of a
225
+ given parent resource. Return `true` to allow, `false` to deny. May be
226
+ async (e.g. it can look the parent resource up in the database).
227
+
228
+ ```typescript
229
+ type VersionOwnershipResolver = (context: VersionOwnershipContext) => boolean | Promise<boolean>
230
+ ```
231
+
232
+ ### Functions
233
+
234
+ #### `clearOwnershipResolvers()`
235
+
236
+ Clears all registered ownership resolvers. Primarily useful in tests.
237
+
238
+ ```typescript
239
+ function clearOwnershipResolvers(): void
240
+ ```
241
+
242
+ #### `create(req, res)`
243
+
244
+ Captures a new version of a resource.
245
+
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.
250
+
251
+ ```typescript
252
+ function create(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
253
+ ```
254
+
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)`
259
+
260
+ Captures a new version of a resource.
261
+
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.
265
+
266
+ ```typescript
267
+ function createVersion(input: CreateVersionInput): Promise<Version>
268
+ ```
269
+
270
+ - `input` — The version creation input.
271
+
272
+ **Returns:** The created version.
273
+
274
+ #### `deleteVersionsForResource(resourceType, resourceId)`
275
+
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.
279
+
280
+ ```typescript
281
+ function deleteVersionsForResource(resourceType: string, resourceId: string): Promise<number>
282
+ ```
283
+
284
+ - `resourceType` — The resource type.
285
+ - `resourceId` — The resource ID.
286
+
287
+ **Returns:** The number of versions deleted.
288
+
289
+ #### `diff(req, res)`
290
+
291
+ Returns the shallow diff between two versions of the same resource.
292
+
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.
297
+
298
+ ```typescript
299
+ function diff(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
300
+ ```
301
+
302
+ - `req` — The request with `fromVersionId` and `toVersionId` params.
303
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
304
+
305
+ #### `diffSnapshots(before, after)`
306
+
307
+ Computes a shallow per-field diff between two JSON snapshots.
308
+
309
+ For object snapshots, every key present in either snapshot is examined;
310
+ keys whose values differ (by deep equality) are included in the result.
311
+ For non-object snapshots, the entire value is reported under the
312
+ synthetic key `$value`.
313
+
314
+ ```typescript
315
+ function diffSnapshots(before: JSONValue, after: JSONValue): VersionChanges
316
+ ```
317
+
318
+ - `before` — The previous snapshot, or `null` if this is the first version.
319
+ - `after` — The new snapshot.
320
+
321
+ **Returns:** A {@link VersionChanges} record. Empty when the snapshots are equal.
322
+
323
+ #### `diffVersions(fromVersionId, toVersionId)`
324
+
325
+ Compares two versions and returns the shallow diff between their snapshots.
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.
330
+
331
+ ```typescript
332
+ function diffVersions(fromVersionId: string, toVersionId: string): Promise<VersionDiff | null>
333
+ ```
334
+
335
+ - `fromVersionId` — One version ID to compare.
336
+ - `toVersionId` — The other version ID to compare.
337
+
338
+ **Returns:** The {@link VersionDiff}, or `null` if either version is missing or the two versions belong to different resources.
339
+
340
+ #### `getLatestVersion(resourceType, resourceId)`
341
+
342
+ Returns the most recent version for a resource, or `null` if no versions exist.
343
+
344
+ ```typescript
345
+ function getLatestVersion(resourceType: string, resourceId: string): Promise<Version | null>
346
+ ```
347
+
348
+ - `resourceType` — The resource type.
349
+ - `resourceId` — The resource ID.
350
+
351
+ **Returns:** The latest version, or `null`.
352
+
353
+ #### `getOwnershipResolver(resourceType)`
354
+
355
+ Returns the ownership resolver registered for a resource type, or
356
+ `undefined` if none has been registered.
357
+
358
+ ```typescript
359
+ function getOwnershipResolver(resourceType: string): VersionOwnershipResolver | undefined
360
+ ```
361
+
362
+ - `resourceType` — The resource type to look up.
363
+
364
+ **Returns:** The resolver, or `undefined`.
365
+
366
+ #### `getVersionById(versionId)`
367
+
368
+ Retrieves a version by ID.
369
+
370
+ ```typescript
371
+ function getVersionById(versionId: string): Promise<Version | null>
372
+ ```
373
+
374
+ - `versionId` — The version ID.
375
+
376
+ **Returns:** The version, or `null` if not found.
377
+
378
+ #### `getVersionByNumber(resourceType, resourceId, version)`
379
+
380
+ Retrieves a version by resource and version number.
381
+
382
+ ```typescript
383
+ function getVersionByNumber(
384
+ resourceType: string,
385
+ resourceId: string,
386
+ version: number,
387
+ ): Promise<Version | null>
388
+ ```
389
+
390
+ - `resourceType` — The resource type.
391
+ - `resourceId` — The resource ID.
392
+ - `version` — The 1-based version number.
393
+
394
+ **Returns:** The version, or `null` if not found.
395
+
396
+ #### `getVersionCount(resourceType, resourceId)`
397
+
398
+ Returns the total number of versions for a resource.
399
+
400
+ ```typescript
401
+ function getVersionCount(resourceType: string, resourceId: string): Promise<number>
402
+ ```
403
+
404
+ - `resourceType` — The resource type.
405
+ - `resourceId` — The resource ID.
406
+
407
+ **Returns:** The version count.
408
+
409
+ #### `getVersionsForResource(resourceType, resourceId, options)`
410
+
411
+ Retrieves paginated versions for a resource, ordered by version number descending.
412
+
413
+ ```typescript
414
+ function getVersionsForResource(
415
+ resourceType: string,
416
+ resourceId: string,
417
+ options?: PaginationOptions,
418
+ ): Promise<PaginatedResult<Version>>
419
+ ```
420
+
421
+ - `resourceType` — The resource type.
422
+ - `resourceId` — The resource ID.
423
+ - `options` — Pagination options.
424
+
425
+ **Returns:** A paginated result of versions.
426
+
427
+ #### `isVersionAuthorized(res, context)`
428
+
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.
435
+
436
+ ```typescript
437
+ function isVersionAuthorized(
438
+ res: MoleculeResponse,
439
+ context: VersionOwnershipContext,
440
+ ): Promise<boolean>
441
+ ```
442
+
443
+ - `res` — The response whose `locals.session`/`locals.versionHistoryAdmin` is inspected.
444
+ - `context` — The {@link VersionOwnershipContext} (parent resource + caller).
445
+
446
+ **Returns:** `true` when the caller may access the parent resource's versions.
447
+
448
+ #### `isVersionHistoryAdmin(res)`
449
+
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'`.
456
+
457
+ ```typescript
458
+ function isVersionHistoryAdmin(res: MoleculeResponse): boolean
459
+ ```
460
+
461
+ - `res` — The response whose `locals.session` is inspected.
462
+
463
+ **Returns:** `true` when the session is an authorized version-history admin.
464
+
465
+ #### `jsonEqual(a, b)`
466
+
467
+ Returns `true` if `a` and `b` are deeply equal as JSON values.
468
+
469
+ ```typescript
470
+ function jsonEqual(a: JSONValue | undefined, b: JSONValue | undefined): boolean
471
+ ```
472
+
473
+ - `a` — First value to compare.
474
+ - `b` — Second value to compare.
475
+
476
+ **Returns:** Whether the two values are structurally equal.
477
+
478
+ #### `list(req, res)`
479
+
480
+ Lists paginated versions for a resource, newest version first.
481
+
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.
485
+
486
+ ```typescript
487
+ function list(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
488
+ ```
489
+
490
+ - `req` — The request with `resourceType` and `resourceId` params.
491
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
492
+
493
+ #### `read(req, res)`
494
+
495
+ Reads a single version by ID.
496
+
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.
502
+
503
+ ```typescript
504
+ function read(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
505
+ ```
506
+
507
+ - `req` — The request with `versionId` param.
508
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
509
+
510
+ #### `readByNumber(req, res)`
511
+
512
+ Reads a single version of a resource by 1-based version number.
513
+
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.
516
+
517
+ ```typescript
518
+ function readByNumber(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
519
+ ```
520
+
521
+ - `req` — The request with `resourceType`, `resourceId`, and `version` params.
522
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
523
+
524
+ #### `registerOwnershipResolver(resourceType, resolver)`
525
+
526
+ Registers an ownership resolver for a parent resource type.
527
+
528
+ Subsequent calls with the same `resourceType` overwrite the previous
529
+ registration.
530
+
531
+ ```typescript
532
+ function registerOwnershipResolver(resourceType: string, resolver: VersionOwnershipResolver): void
533
+ ```
534
+
535
+ - `resourceType` — The parent resource type the resolver authorizes.
536
+ - `resolver` — The resolver to invoke when authorizing access to versions of this resource type.
537
+
538
+ #### `restore(req, res)`
539
+
540
+ Restores a prior version by appending a new version whose snapshot
541
+ matches it. Append-only — the existing rows are never mutated.
542
+
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.
547
+
548
+ ```typescript
549
+ function restore(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
550
+ ```
551
+
552
+ - `req` — The request with `versionId` param.
553
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
554
+
555
+ #### `restoreVersion(versionId, userId, reason)`
556
+
557
+ Restores a prior version by appending a new version whose snapshot matches it.
558
+
559
+ Append-only: the existing rows are never mutated. The newly-appended
560
+ version has its own monotonically-increasing `version` number, and its
561
+ `reason` defaults to `Restored from version <n>` when no reason is supplied.
562
+
563
+ ```typescript
564
+ function restoreVersion(
565
+ versionId: string,
566
+ userId: string | null,
567
+ reason?: string | null,
568
+ ): Promise<Version | null>
569
+ ```
570
+
571
+ - `versionId` — The version ID to restore.
572
+ - `userId` — The user performing the restore, or `null` for system.
573
+ - `reason` — Optional human-readable reason. When omitted, a default `Restored from version <n>` reason is recorded.
574
+
575
+ **Returns:** The newly-appended version, or `null` if `versionId` was not found.
576
+
577
+ #### `unregisterOwnershipResolver(resourceType)`
578
+
579
+ Removes any registered ownership resolver for the given resource type.
580
+
581
+ ```typescript
582
+ function unregisterOwnershipResolver(resourceType: string): boolean
583
+ ```
584
+
585
+ - `resourceType` — The resource type whose resolver should be removed.
586
+
587
+ **Returns:** `true` if a resolver was removed.
588
+
589
+ #### `versionCount(req, res)`
590
+
591
+ Returns the total number of versions for a resource.
592
+
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
+ ```typescript
597
+ function versionCount(req: MoleculeRequest, res: MoleculeResponse): Promise<void>
598
+ ```
599
+
600
+ - `req` — The request with `resourceType` and `resourceId` params.
601
+ - `res` — The response object (reads `locals.session`/`locals.versionHistoryAdmin`).
602
+
603
+ #### `versionHistoryAdmin()`
604
+
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.
612
+
613
+ ```typescript
614
+ function versionHistoryAdmin(): MoleculeRequestHandler
615
+ ```
616
+
617
+ **Returns:** An Express-compatible middleware function.
618
+
619
+ ### Constants
620
+
621
+ #### `createVersionSchema`
622
+
623
+ Schema for validating create-version input.
624
+
625
+ ```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
+ >
633
+ ```
634
+
635
+ #### `i18nRegistered`
636
+
637
+ The i18n registered.
638
+
639
+ ```typescript
640
+ const i18nRegistered: true
641
+ ```
642
+
643
+ #### `requestHandlerMap`
644
+
645
+ Handler map for version-history routes.
646
+
647
+ ```typescript
648
+ const requestHandlerMap: {
649
+ readonly create: typeof create
650
+ readonly list: typeof list
651
+ readonly versionCount: typeof versionCount
652
+ readonly readByNumber: typeof readByNumber
653
+ readonly read: typeof read
654
+ readonly restore: typeof restore
655
+ readonly diff: typeof diff
656
+ }
657
+ ```
658
+
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
+ #### `routes`
672
+
673
+ Routes for the version-history resource. All routes require `authenticate`;
674
+ the handlers additionally authorize every read/mutation against the caller's
675
+ ownership of the parent resource.
676
+
677
+ ```typescript
678
+ const routes: readonly [
679
+ {
680
+ readonly method: 'post'
681
+ readonly path: '/:resourceType/:resourceId/versions'
682
+ readonly handler: 'create'
683
+ readonly middlewares: readonly ['authenticate']
684
+ },
685
+ {
686
+ readonly method: 'get'
687
+ readonly path: '/:resourceType/:resourceId/versions'
688
+ readonly handler: 'list'
689
+ readonly middlewares: readonly ['authenticate']
690
+ },
691
+ {
692
+ readonly method: 'get'
693
+ readonly path: '/:resourceType/:resourceId/versions/count'
694
+ readonly handler: 'versionCount'
695
+ readonly middlewares: readonly ['authenticate']
696
+ },
697
+ {
698
+ readonly method: 'get'
699
+ readonly path: '/:resourceType/:resourceId/versions/:version'
700
+ readonly handler: 'readByNumber'
701
+ readonly middlewares: readonly ['authenticate']
702
+ },
703
+ {
704
+ readonly method: 'get'
705
+ readonly path: '/versions/:versionId'
706
+ readonly handler: 'read'
707
+ readonly middlewares: readonly ['authenticate']
708
+ },
709
+ {
710
+ readonly method: 'post'
711
+ readonly path: '/versions/:versionId/restore'
712
+ readonly handler: 'restore'
713
+ readonly middlewares: readonly ['authenticate']
714
+ },
715
+ {
716
+ readonly method: 'get'
717
+ readonly path: '/versions/:fromVersionId/diff/:toVersionId'
718
+ readonly handler: 'diff'
719
+ readonly middlewares: readonly ['authenticate']
720
+ },
721
+ ]
722
+ ```
723
+
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`
735
+
736
+ Permission action describing version-history administration, e.g. for an
737
+ app's own `@molecule/api-permissions` wiring.
738
+
739
+ ```typescript
740
+ const VERSION_HISTORY_PERMISSION_ACTION: 'manage'
741
+ ```
742
+
743
+ #### `VERSION_HISTORY_PERMISSION_RESOURCE`
744
+
745
+ Permission resource describing version-history administration, e.g. for an
746
+ app's own `@molecule/api-permissions` wiring.
747
+
748
+ ```typescript
749
+ const VERSION_HISTORY_PERMISSION_RESOURCE: 'versionHistory'
750
+ ```
751
+
752
+ ## Injection Notes
753
+
754
+ ### Requirements
755
+
756
+ Peer dependencies:
757
+
758
+ - `@molecule/api-database` ^1.0.1
759
+ - `@molecule/api-i18n` ^1.0.1
760
+ - `@molecule/api-locales-resource-version-history` ^1.0.1
761
+ - `@molecule/api-logger` ^1.0.1
762
+ - `@molecule/api-resource` ^1.0.1
763
+ - `zod` ^4.0.0
764
+
765
+ ### Runtime Dependencies
766
+
767
+ - `@molecule/api-database`
768
+ - `@molecule/api-i18n`
769
+ - `@molecule/api-locales-resource-version-history`
770
+ - `@molecule/api-logger`
771
+ - `@molecule/api-resource`
772
+ - `zod`
773
+
774
+ - **List endpoints return a PAGINATED envelope** `{ data, total, limit, offset }`, not a
775
+ bare array — read the rows off `result.data` (server). On the client, `unwrapList(res)`
776
+ from `@molecule/app-http` normalizes this envelope (pass it the whole HttpResponse), so
777
+ the rows come back; reading the response as a bare array — or `res.data` alone (which is
778
+ the envelope) — yields an EMPTY list.
779
+ **Security — the raw routes are NOT open.** Snapshots can contain any
780
+ tenant's data, so every route requires an authenticated session AND each
781
+ handler re-derives the caller from `res.locals.session.userId` and authorizes
782
+ access to the _parent_ resource via {@link isVersionAuthorized}. Access is
783
+ **fail-closed and pluggable**: because the store is polymorphic it cannot
784
+ know who owns an arbitrary `(resourceType, resourceId)`, so an app mounting
785
+ these routes MUST register a {@link VersionOwnershipResolver} per resource
786
+ type at startup via {@link registerOwnershipResolver} — until it does, every
787
+ read/list/diff/restore returns 404 (no existence leak) rather than exposing
788
+ another tenant's snapshots. Cross-tenant admin access is opt-in via the
789
+ {@link versionHistoryAdmin} middleware. Do NOT mount the raw routes without
790
+ either a registered resolver or your own resource-ownership gate.
791
+
792
+ Tables: `src/__setup__/versions.sql` creates `versions`. An mlcl-scaffolded
793
+ API replays `__setup__/*.sql` automatically on migrate; anywhere else run it
794
+ once — nothing at runtime creates them. Handler errors flow through `t()`
795
+ with English defaults; install `@molecule/api-locales-resource-version-history`
796
+ and register it with `registerLocaleModule` for translations.
797
+
798
+ ## E2E Tests
799
+
800
+ Versioning-correctness checklist — drive the real UI (live preview, no mocks)
801
+ wherever this app surfaces revisions/history, adapt each item to the actual
802
+ screens, and check every box. A box you can't check is a versioning bug to
803
+ fix — not a skip. The point is to PROVE versions are recorded, ordered,
804
+ diffable, restorable, and tamper-evident, not just that CRUD compiles:
805
+
806
+ - [ ] Editing a versioned resource RECORDS a new version: after a save the
807
+ history count grows by exactly one, the prior version is RETAINED (its
808
+ snapshot unchanged — not overwritten), and the new row carries the next
809
+ 1-based `version` number (previous + 1), the acting user as `userId`
810
+ (author), and a fresh `createdAt`. The very first save has `changes: null`;
811
+ later saves record a `changes` shallow diff (before/after per field)
812
+ against the prior snapshot.
813
+ - [ ] Listing history returns versions newest-first (by `version` descending)
814
+ with `total` reflecting every version, each row showing its number, author
815
+ (`userId`), `reason`, and `createdAt` — and the count only ever GROWS across
816
+ saves (append-only: no save shrinks or rewrites history).
817
+ - [ ] Viewing an old version shows that version's full `snapshot`; diffing two
818
+ versions renders the per-field `changes` as a forward delta (the
819
+ lower-numbered version is `from`, the higher is `to`), and a diff across two
820
+ different resources is rejected (no cross-resource diff).
821
+ - [ ] Reverting/restoring an old version makes it current AND itself APPENDS a
822
+ new version whose snapshot equals the target's — the prior current version
823
+ and the restored-from version both still exist afterward, the new version's
824
+ number is the next in sequence, its author is the acting user, and its
825
+ `reason` records the restore (default `Restored from version <n>`). History
826
+ is never lost by a revert.
827
+ - [ ] Retention is append-only and unbounded — nothing prunes: there is no UI
828
+ or endpoint to edit or delete an individual version (no UPDATE/DELETE
829
+ route), so a resource's history count never decreases. (If the app layers
830
+ its own retention policy on top, verify it prunes oldest-first per that
831
+ policy and never drops the current version.)
832
+ - [ ] AUTHORIZATION — a resource's version history is reachable only by a user
833
+ who can access that resource: a different user id-guessing the
834
+ `(resourceType, resourceId)` or a `versionId` gets 404 (no existence leak),
835
+ never another tenant's history, and with no ownership resolver registered
836
+ every read/list/diff/restore fails closed. The version author is always the
837
+ session user (`res.locals.session.userId`), never a body-supplied id — a
838
+ caller cannot attribute a change to someone else. A user cannot fabricate or
839
+ delete history to hide a change: versions are append-only and a revert
840
+ appends rather than rewrites; only the opt-in `versionHistoryAdmin`
841
+ middleware crosses tenants.
842
+
843
+ ## Translations
844
+
845
+ Translation strings are provided by `@molecule/api-locales-resource-version-history`.
@@ -1 +1 @@
1
- {"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../../src/handlers/list.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAK/E;;;;;;;;;GASG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CA4CrF"}
1
+ {"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../../src/handlers/list.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAQ/E;;;;;;;;;GASG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CA4CrF"}
@@ -7,6 +7,8 @@ import { t } from '@molecule/api-i18n';
7
7
  import { logger } from '@molecule/api-logger';
8
8
  import { isVersionAuthorized } from '../authorizers/ownership.js';
9
9
  import { getVersionsForResource } from '../service.js';
10
+ /** Upper bound for the list page size — an uncapped `limit` is a table-dump primitive (e.g. `?limit=999999999`). */
11
+ const MAX_LIST_LIMIT = 500;
10
12
  /**
11
13
  * Lists paginated versions for a resource, newest version first.
12
14
  *
@@ -43,7 +45,7 @@ export async function list(req, res) {
43
45
  });
44
46
  return;
45
47
  }
46
- const limit = parseInt(req.query.limit, 10) || 20;
48
+ const limit = Math.min(MAX_LIST_LIMIT, Math.max(1, parseInt(req.query.limit, 10) || 20));
47
49
  const offset = parseInt(req.query.offset, 10) || 0;
48
50
  try {
49
51
  const result = await getVersionsForResource(resourceType, resourceId, { limit, offset });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-resource-version-history",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
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",
@@ -17,7 +17,8 @@
17
17
  }
18
18
  },
19
19
  "files": [
20
- "dist"
20
+ "dist",
21
+ "README.md"
21
22
  ],
22
23
  "keywords": [
23
24
  "molecule",
@@ -29,18 +30,18 @@
29
30
  ],
30
31
  "license": "Apache-2.0",
31
32
  "devDependencies": {
32
- "@molecule/api-locales-resource-version-history": "1.0.0",
33
+ "@molecule/api-locales-resource-version-history": "1.0.1",
33
34
  "@types/node": "26.1.2",
34
35
  "typescript": "6.0.3",
35
- "vitest": "4.1.10",
36
+ "vitest": "4.1.11",
36
37
  "zod": "4.4.3"
37
38
  },
38
39
  "peerDependencies": {
39
- "@molecule/api-database": "^1.0.0",
40
- "@molecule/api-i18n": "^1.0.0",
41
- "@molecule/api-locales-resource-version-history": "^1.0.0",
42
- "@molecule/api-logger": "^1.0.0",
43
- "@molecule/api-resource": "^1.0.0",
40
+ "@molecule/api-database": "^1.0.1",
41
+ "@molecule/api-i18n": "^1.0.1",
42
+ "@molecule/api-locales-resource-version-history": "^1.0.1",
43
+ "@molecule/api-logger": "^1.0.1",
44
+ "@molecule/api-resource": "^1.0.1",
44
45
  "zod": "^4.0.0"
45
46
  },
46
47
  "peerDependenciesMeta": {