rev-dal 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/AGENTS.md +234 -0
  2. package/CONTRIBUTING.md +83 -0
  3. package/LICENSE +121 -0
  4. package/README.md +67 -2
  5. package/dist/index.d.ts +48 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +26 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/lib/clone.d.ts +24 -0
  10. package/dist/lib/clone.d.ts.map +1 -0
  11. package/dist/lib/clone.js +83 -0
  12. package/dist/lib/clone.js.map +1 -0
  13. package/dist/lib/create-model.d.ts +207 -0
  14. package/dist/lib/create-model.d.ts.map +1 -0
  15. package/dist/lib/create-model.js +230 -0
  16. package/dist/lib/create-model.js.map +1 -0
  17. package/dist/lib/data-access-layer.d.ts +140 -0
  18. package/dist/lib/data-access-layer.d.ts.map +1 -0
  19. package/dist/lib/data-access-layer.js +389 -0
  20. package/dist/lib/data-access-layer.js.map +1 -0
  21. package/dist/lib/errors.d.ts +139 -0
  22. package/dist/lib/errors.d.ts.map +1 -0
  23. package/dist/lib/errors.js +206 -0
  24. package/dist/lib/errors.js.map +1 -0
  25. package/dist/lib/filter-where.d.ts +199 -0
  26. package/dist/lib/filter-where.d.ts.map +1 -0
  27. package/dist/lib/filter-where.js +563 -0
  28. package/dist/lib/filter-where.js.map +1 -0
  29. package/dist/lib/ml-string.d.ts +63 -0
  30. package/dist/lib/ml-string.d.ts.map +1 -0
  31. package/dist/lib/ml-string.js +331 -0
  32. package/dist/lib/ml-string.js.map +1 -0
  33. package/dist/lib/model-factory.d.ts +25 -0
  34. package/dist/lib/model-factory.d.ts.map +1 -0
  35. package/dist/lib/model-factory.js +57 -0
  36. package/dist/lib/model-factory.js.map +1 -0
  37. package/dist/lib/model-handle.d.ts +67 -0
  38. package/dist/lib/model-handle.d.ts.map +1 -0
  39. package/dist/lib/model-handle.js +182 -0
  40. package/dist/lib/model-handle.js.map +1 -0
  41. package/dist/lib/model-initializer.d.ts +96 -0
  42. package/dist/lib/model-initializer.d.ts.map +1 -0
  43. package/dist/lib/model-initializer.js +182 -0
  44. package/dist/lib/model-initializer.js.map +1 -0
  45. package/dist/lib/model-manifest.d.ts +112 -0
  46. package/dist/lib/model-manifest.d.ts.map +1 -0
  47. package/dist/lib/model-manifest.js +2 -0
  48. package/dist/lib/model-manifest.js.map +1 -0
  49. package/dist/lib/model-registry.d.ts +81 -0
  50. package/dist/lib/model-registry.d.ts.map +1 -0
  51. package/dist/lib/model-registry.js +139 -0
  52. package/dist/lib/model-registry.js.map +1 -0
  53. package/dist/lib/model-types.d.ts +380 -0
  54. package/dist/lib/model-types.d.ts.map +1 -0
  55. package/dist/lib/model-types.js +2 -0
  56. package/dist/lib/model-types.js.map +1 -0
  57. package/dist/lib/model.d.ts +503 -0
  58. package/dist/lib/model.d.ts.map +1 -0
  59. package/dist/lib/model.js +1423 -0
  60. package/dist/lib/model.js.map +1 -0
  61. package/dist/lib/postgres-config.d.ts +3 -0
  62. package/dist/lib/postgres-config.d.ts.map +1 -0
  63. package/dist/lib/postgres-config.js +2 -0
  64. package/dist/lib/postgres-config.js.map +1 -0
  65. package/dist/lib/query-builder.d.ts +607 -0
  66. package/dist/lib/query-builder.d.ts.map +1 -0
  67. package/dist/lib/query-builder.js +1734 -0
  68. package/dist/lib/query-builder.js.map +1 -0
  69. package/dist/lib/revision.d.ts +55 -0
  70. package/dist/lib/revision.d.ts.map +1 -0
  71. package/dist/lib/revision.js +307 -0
  72. package/dist/lib/revision.js.map +1 -0
  73. package/dist/lib/runtime.d.ts +18 -0
  74. package/dist/lib/runtime.d.ts.map +1 -0
  75. package/dist/lib/runtime.js +134 -0
  76. package/dist/lib/runtime.js.map +1 -0
  77. package/dist/lib/transaction.d.ts +17 -0
  78. package/dist/lib/transaction.d.ts.map +1 -0
  79. package/dist/lib/transaction.js +30 -0
  80. package/dist/lib/transaction.js.map +1 -0
  81. package/dist/lib/type.d.ts +130 -0
  82. package/dist/lib/type.d.ts.map +1 -0
  83. package/dist/lib/type.js +376 -0
  84. package/dist/lib/type.js.map +1 -0
  85. package/docs/models.md +406 -0
  86. package/docs/multilingual-text.md +142 -0
  87. package/docs/queries.md +374 -0
  88. package/docs/revisions.md +61 -0
  89. package/package.json +60 -4
  90. package/releases/0.2.0.md +18 -0
  91. package/releases/0.2.1.md +22 -0
  92. package/releases/README.md +7 -0
  93. package/setup-db-grants.sql +51 -0
package/docs/models.md ADDED
@@ -0,0 +1,406 @@
1
+ # Models and bootstrap
2
+
3
+ [README](../README.md) · [Queries](queries.md) · [Revisions](revisions.md)
4
+
5
+ ## Bootstrap & Lifecycle
6
+
7
+ ```ts
8
+ import createDataAccessLayer from 'rev-dal';
9
+ import { initializeManifestModels } from 'rev-dal/lib/create-model';
10
+ import { setBootstrapResolver } from 'rev-dal/lib/model-handle';
11
+
12
+ // Import every runtime model module so defineModel() registers its manifest.
13
+ import './models/user.js';
14
+ import './models/team.js';
15
+
16
+ const dal = createDataAccessLayer();
17
+ setBootstrapResolver(() => ({
18
+ getModel: name => dal.modelRegistry.get(name),
19
+ }));
20
+ await dal.connect();
21
+ initializeManifestModels(dal);
22
+ ```
23
+
24
+ Importing a plain manifest alone does not register it; import the module that calls
25
+ `defineModel()`. Include related models such as `user_metas` in your application's
26
+ imports as well. Configure the resolver before initializing models so lazy relation
27
+ targets can resolve through the registry. Call model methods after initialization.
28
+
29
+ The DAL is initialised once at startup. Tests and fixtures may spin up isolated instances; disconnecting a DAL clears its registry so cached constructors do not leak across runs. Model proxies and references use the globally configured bootstrap resolver; when switching DAL instances, update that resolver to point at the intended instance, or resolve models from the instance itself as described below.
30
+
31
+ ### Resolving Models from a DAL Instance
32
+
33
+ Each DAL keeps its own registry of constructors. `dal.getModel()` reads only that
34
+ registry, so code that receives a DAL can use it without touching the global
35
+ resolver:
36
+
37
+ ```ts
38
+ import type { DataAccessLayer } from 'rev-dal/lib/model-types';
39
+ import User from './models/user.js';
40
+
41
+ export async function getDisplayNames(dal: DataAccessLayer, userIds: string[]) {
42
+ const Users = dal.getModel(User);
43
+ return Users.filterWhere({}).whereIn('id', userIds).select('id', 'displayName');
44
+ }
45
+ ```
46
+
47
+ `getModel()` accepts:
48
+
49
+ | Argument | Result type |
50
+ | --- | --- |
51
+ | `defineModel()` or `referenceModel()` handle, including one cast to a model type (such as `referenceModel(manifest) as UserModel`) | This DAL's constructor for the handle's manifest, typed like the handle. A `defineModel()` handle's type includes methods passed in its options. |
52
+ | Model manifest | `InferConstructor<typeof manifest>`, including methods declared inside the manifest. Methods passed separately to `defineModel()` are attached at runtime but missing from the type; pass the handle to get them. |
53
+ | Model constructor registered on another DAL | This DAL's constructor for the same model, found by the registry key the argument was registered under, and typed like the argument. |
54
+ | Table name or registry key | Untyped `ModelConstructor`, or the record types you pass as type arguments. |
55
+
56
+ What rev-dal guarantees:
57
+
58
+ - The returned value is the constructor registered on that DAL, the same one
59
+ `dal.getModel(manifest.tableName)` returns. Its queries, writes, revision helpers
60
+ and relation loading use that DAL.
61
+ - Lookup is synchronous. It does not query the database, register models, or call
62
+ the bootstrap resolver. Register models first (for example with
63
+ `initializeManifestModels(dal)`).
64
+ - A model missing from the DAL throws `Model '<tableName>' not found`, even if
65
+ another DAL or the global resolver has it. After `disconnect()`, lookups fail
66
+ until models are registered again.
67
+ - Handles and manifests resolve by their manifest `tableName`; on a DAL with a
68
+ `schemaNamespace`, that is the registry key. Anything that is not a name,
69
+ handle, registered constructor or manifest with a non-empty `tableName` throws
70
+ a `TypeError`.
71
+
72
+ What it does not do:
73
+
74
+ - Check that a manifest matches the registered model. The manifest only supplies
75
+ types, so pass the manifest the model was defined with.
76
+ - Change what your custom methods call. A method that uses another model through
77
+ its global handle or `referenceModel()` still resolves that model globally; use
78
+ `this.dal.getModel(...)` inside the method to stay on the same DAL.
79
+ - Copy handle-only values. `defineModel()`'s `statics` and the fallback methods
80
+ passed to `referenceModel()` live only on the global handle. Because the result
81
+ is typed like the handle, its type still lists them; read them from the handle.
82
+ - Run queries inside a transaction. Pass a transaction client as described in
83
+ [Saving revisions and edit conflicts](revisions.md#saving-revisions-and-edit-conflicts).
84
+
85
+ ## Defining Models
86
+
87
+ Models are split across two directories to avoid circular imports:
88
+
89
+ - **`models/manifests/`** – Schema declarations, types, validation helpers, and cross-model reference functions
90
+ - **`models/`** – Runtime behavior (complex static/instance methods that depend on other models)
91
+
92
+ ### Basic Structure
93
+
94
+ ```ts
95
+ // models/manifests/user.ts - Schema, types, validation helpers
96
+ import dal from 'rev-dal';
97
+ import type { ManifestInstance, ManifestModel } from 'rev-dal/lib/create-model';
98
+ import { referenceModel } from 'rev-dal/lib/model-handle';
99
+ import type { ModelManifest } from 'rev-dal/lib/model-manifest';
100
+ import type { ModelInstance } from 'rev-dal/lib/model-types';
101
+ import type { TeamInstance } from './team.js';
102
+
103
+ const { types } = dal;
104
+
105
+ // Model-specific options and helpers
106
+ const userOptions = {
107
+ maxChars: 128,
108
+ illegalChars: /[<>;"&?!./_]/,
109
+ minPasswordLength: 6,
110
+ };
111
+
112
+ export function canonicalize(name: string): string {
113
+ return name.toUpperCase();
114
+ }
115
+
116
+ function containsOnlyLegalCharacters(name: string): true {
117
+ if (userOptions.illegalChars.test(name)) {
118
+ throw new Error(`Username ${name} contains invalid characters.`);
119
+ }
120
+ return true;
121
+ }
122
+
123
+ const userManifest = {
124
+ tableName: 'users',
125
+ hasRevisions: false as const,
126
+ schema: {
127
+ id: types.string().uuid(4),
128
+ email: types.string(),
129
+ userMetaID: types.string().uuid(4),
130
+ displayName: types
131
+ .string()
132
+ .max(userOptions.maxChars)
133
+ .validator(containsOnlyLegalCharacters)
134
+ .required(),
135
+ suppressedNotices: types.array(types.string()),
136
+ urlName: types
137
+ .virtual()
138
+ .returns<string | undefined>()
139
+ .default(function (this: ModelInstance) {
140
+ const displayName = this.getValue('displayName');
141
+ return displayName ? encodeURIComponent(String(displayName).replace(/ /g, '_')) : undefined;
142
+ }),
143
+ },
144
+ camelToSnake: {
145
+ displayName: 'display_name',
146
+ suppressedNotices: 'suppressed_notices',
147
+ userMetaID: 'user_meta_id',
148
+ },
149
+ relations: [
150
+ {
151
+ name: 'meta',
152
+ targetTable: 'user_metas',
153
+ sourceKey: 'userMetaID',
154
+ targetKey: 'id',
155
+ hasRevisions: true,
156
+ cardinality: 'one',
157
+ },
158
+ {
159
+ name: 'teams',
160
+ targetTable: 'teams',
161
+ sourceKey: 'id',
162
+ targetKey: 'id',
163
+ hasRevisions: true,
164
+ cardinality: 'many',
165
+ through: {
166
+ table: 'team_members',
167
+ sourceForeignKey: 'user_id',
168
+ targetForeignKey: 'team_id',
169
+ },
170
+ },
171
+ ] as const,
172
+ } as const satisfies ModelManifest;
173
+
174
+ export type UserInstance = ManifestInstance<typeof userManifest> & {
175
+ teams?: TeamInstance[];
176
+ };
177
+ export type UserModel = ManifestModel<typeof userManifest>;
178
+
179
+ // For models WITH relations, use intersection pattern for strong typing:
180
+ // export type UserInstance = ManifestInstance<typeof userManifest> & {
181
+ // meta?: UserMetaInstance;
182
+ // teams?: TeamInstance[];
183
+ // };
184
+
185
+ // Export reference helper for other models to use
186
+ export function referenceUser(): UserModel {
187
+ return referenceModel(userManifest) as UserModel;
188
+ }
189
+
190
+ export { userOptions };
191
+ export default userManifest;
192
+ ```
193
+
194
+ ### Relation Definition
195
+
196
+ Relations are defined as plain objects in the manifest's `relations` array:
197
+
198
+ ```ts
199
+ interface RelationDefinition {
200
+ name: string; // Field name on the instance
201
+ targetTable?: string; // Target table name, OR use target()
202
+ target?: () => unknown; // Lazy model reference (has tableName)
203
+ sourceKey?: string; // Column on this model (default: 'id')
204
+ targetKey?: string; // Column on target model (default: 'id')
205
+ cardinality?: 'one' | 'many'; // Affects join strategy when using `true`
206
+ hasRevisions?: boolean; // Apply revision guards to joined records
207
+ through?: { // For many-to-many via junction table
208
+ table: string;
209
+ sourceForeignKey?: string;
210
+ targetForeignKey?: string;
211
+ };
212
+ }
213
+ ```
214
+
215
+ Example with a many-to-many relation:
216
+
217
+ ```ts
218
+ relations: [
219
+ {
220
+ name: 'teams',
221
+ targetTable: 'teams',
222
+ sourceKey: 'id',
223
+ targetKey: 'id',
224
+ hasRevisions: true,
225
+ through: {
226
+ table: 'team_members',
227
+ sourceForeignKey: 'user_id',
228
+ targetForeignKey: 'team_id',
229
+ },
230
+ cardinality: 'many',
231
+ },
232
+ ]
233
+ ```
234
+
235
+ ```ts
236
+ // models/user.ts - Runtime behavior
237
+ import { defineModel, defineStaticMethods } from 'rev-dal/lib/create-model';
238
+ import userManifest, { type UserInstance, type UserModel } from './manifests/user.ts';
239
+ import type { TeamInstance } from './manifests/team.ts';
240
+
241
+ const userStaticMethods = defineStaticMethods(userManifest, {
242
+ async findByEmail(this: UserModel, email: string) {
243
+ return this.filterWhere({ email }).run();
244
+ },
245
+
246
+ async getWithTeams(this: UserModel, id: string) {
247
+ const user = await this.get(id);
248
+ if (user) {
249
+ const teamsByUser = await this.loadManyRelated('teams', [id]);
250
+ (user as UserInstance).teams = (teamsByUser.get(id) ?? []) as TeamInstance[];
251
+ }
252
+ return user;
253
+ }
254
+ });
255
+
256
+ export default defineModel(userManifest, { staticMethods: userStaticMethods });
257
+ ```
258
+
259
+ ### Atomic upsert
260
+
261
+ Non-revisioned models expose `upsert(data, options)` to insert or update a row
262
+ in one PostgreSQL statement:
263
+
264
+ ```typescript
265
+ const override = await EditorOverride.upsert(
266
+ { userId, status, reason, actorId, decidedAt: new Date() },
267
+ {
268
+ conflictFields: ['userId'],
269
+ updateFields: ['status', 'reason', 'actorId', 'decidedAt'],
270
+ transaction, // optional existing transaction handle
271
+ }
272
+ );
273
+ ```
274
+
275
+ `conflictFields` must match a database unique constraint/index; composite keys
276
+ are supported. Both field lists must be non-empty and contain distinct persisted
277
+ schema field names. Field mappings, defaults and validators apply. Each update
278
+ field needs an explicit, defined value in `data`; only listed fields change on
279
+ conflict. The method returns the persisted model instance, including database
280
+ defaults, and rejects unknown and virtual fields. Conflict key values must be
281
+ non-null. Concurrent calls use PostgreSQL's atomic conflict handling.
282
+
283
+ Sensitive values may be inserted as with `create()`. Updating a sensitive field
284
+ requires listing it in `updateSensitive`; sensitive fields are omitted from the
285
+ returned instance unless listed in `includeSensitive`. Revisioned models reject
286
+ upsert to preserve revision history. `save()` keeps its existing behavior.
287
+
288
+ ### Type Inference
289
+
290
+ Manifests drive all type inference. With TypeScript's `strictNullChecks` enabled,
291
+ required schema fields infer their value type, while optional fields also allow
292
+ `null` and `undefined`. Defaults do not by themselves mark a field as required.
293
+
294
+ The following helpers derive model types from manifests:
295
+
296
+ - **Low-level helpers** (internal):
297
+ - `InferData` and `InferVirtual` extract stored and virtual fields from schema builders
298
+ - `InferInstance` switches between `ModelInstance` and `VersionedModelInstance` based on `hasRevisions`
299
+ - `InferConstructor` produces the typed model constructor with CRUD methods
300
+ - **Convenience helpers** (recommended for manifest files):
301
+ - `ManifestInstance<Manifest, InstanceMethods>` - cleaner than `InferInstance<MergeManifestMethods<...>>`
302
+ - `ManifestModel<Manifest, StaticMethods, InstanceMethods>` - cleaner than `InferConstructor<MergeManifestMethods<...>>`
303
+ - **Bundle helpers for manifests**:
304
+ - `ManifestTypes<Manifest, StaticMethods, InstanceMethods, Relations>` packages the data, virtual, instance, and model types
305
+ into a single object.
306
+ - `ManifestBundle<Manifest, Relations, StaticMethods, InstanceMethods>` builds on `ManifestTypes` and additionally returns
307
+ typed `StaticMethods`/`InstanceMethods` mappings. Use this to keep manifest exports short without circular aliases.
308
+ - **Method mapping helpers**:
309
+ - `StaticMethodsFrom`/`InstanceMethodsFrom` map plain method signatures to manifest-aware `this` types so authors don't need
310
+ to annotate every method with `this: ModelType` or `this: InstanceType`. The generics are ordered as manifest, method map,
311
+ then relation fields (plus instance methods for static methods) to match the call graph.
312
+ - Static/instance methods declared via `defineStaticMethods`/`defineInstanceMethods` receive correctly typed `this` via contextual `ThisType`
313
+
314
+ Example using `ManifestBundle` to keep manifests terse:
315
+
316
+ ```ts
317
+ type ThingRelations = { files?: FileInstance[] };
318
+
319
+ type ThingTypes = ManifestBundle<
320
+ typeof thingManifest,
321
+ ThingRelations,
322
+ { getWithData(id: string): Promise<ThingTypes['Instance']> },
323
+ { populateUserInfo(user: UserAccessContext | null | undefined): void }
324
+ >;
325
+
326
+ type ThingInstance = ThingTypes['Instance'];
327
+ type ThingStaticMethods = ThingTypes['StaticMethods'];
328
+ type ThingInstanceMethods = ThingTypes['InstanceMethods'];
329
+ ```
330
+
331
+ Method implementations can then omit explicit `this` annotations while still receiving the fully-typed model/instance context in the body.
332
+
333
+ **Relation Field Typing**: Use the intersection pattern to add strongly-typed relation fields:
334
+
335
+ ```ts
336
+ // If you have static/instance methods, define base types first
337
+ type UserInstanceBase = ManifestInstance<typeof userManifest, UserInstanceMethods>;
338
+
339
+ // Add relation types via intersection - fields are optional since they're
340
+ // only populated when explicitly loaded via getJoin() or custom queries
341
+ export type UserInstance = UserInstanceBase & {
342
+ meta?: UserMetaInstance;
343
+ teams?: TeamInstance[];
344
+ };
345
+ ```
346
+
347
+ This pattern avoids circular type errors when two models reference each other (e.g., Thing ↔ Review).
348
+
349
+ ### Cross-Model References
350
+
351
+ Use `referenceModel()` to safely import other models without circular dependencies:
352
+
353
+ ```ts
354
+ // In models/thing.ts
355
+ import { referenceReview, type ReviewInstance } from './manifests/review.ts';
356
+
357
+ const Review = referenceReview();
358
+
359
+ // Can now call Review.filterWhere(...) safely
360
+ const reviews = await Review.filterWhere({ thingID: thing.id }).run();
361
+ ```
362
+
363
+ The manifest exports a typed reference function that returns a lazy proxy. The actual model is resolved at runtime after bootstrap completes.
364
+
365
+ ### What Goes Where?
366
+
367
+ **Manifests** (`models/manifests/`) contain:
368
+ - Schema definitions as plain objects with `as const satisfies ModelManifest`
369
+ - Type exports (`UserInstance`, `UserModel`, etc.)
370
+ - Validation functions used in schema validators
371
+ - Model-specific constants and options
372
+ - Cross-model reference functions (`referenceUser()`, etc.)
373
+ - Simple helper functions with no external model dependencies
374
+
375
+ **Runtime models** (`models/`) contain:
376
+ - Complex static methods that query other models
377
+ - Instance methods that interact with related models
378
+ - Business logic that requires calling multiple models
379
+ - Methods that need fully-initialized DAL helpers
380
+
381
+ **Rule of thumb**: If it needs to call another model's methods, put it in `models/`. If it's pure validation, types, or schema, put it in `models/manifests/`.
382
+
383
+ ## Debug Logger
384
+
385
+ `setDebugLogger` wires DAL logs into your app's logging system. The logger must
386
+ expose `db` and `error` functions; any additional arguments are ignored.
387
+
388
+ ## SQL Grants Script
389
+
390
+ `setup-db-grants.sql` is parameterized. Example:
391
+
392
+ ```bash
393
+ psql -v app_db=libreviews -v app_user=libreviews_user \
394
+ -v test_db=libreviews_test -v test_user=libreviews_user \
395
+ -f setup-db-grants.sql
396
+ ```
397
+
398
+ ## Core Building Blocks
399
+
400
+ - **DataAccessLayer (`src/lib/data-access-layer.ts`)** – Owns the shared `pg.Pool`, manages migrations, and keeps a per-instance `ModelRegistry` so constructors are isolated between DALs (useful for fixtures/tests). `getModel()` resolves names, handles and manifests in that registry; see [Resolving Models from a DAL Instance](#resolving-models-from-a-dal-instance).
401
+ - **Model runtime (`src/lib/model.ts`)** – Implements camelCase ↔︎ snake_case mapping, validation/default handling, change tracking, and persistence primitives consumed by every manifest-driven model.
402
+ - **Manifest system (`src/lib/create-model.ts`, `src/lib/model-manifest.ts`)** – Declarative manifests define schema, relations, revision support, and custom methods. `defineModel` returns a lazy proxy constructor whose types are inferred from the manifest.
403
+ - **Query builder (`src/lib/query-builder.ts`)** – Builds SQL fragments for predicates, joins, ordering, pagination, and deletes. `filterWhere` wraps it with typed predicates for day-to-day usage.
404
+ - Chainables include `orderBy/limit/offset`, `whereIn`, `getJoin` (auto-selects inline or batch join based on cardinality; a to-one relation whose table is already in the query, such as a second relation to the same table, is batch-loaded). A relation's `_apply: qb => …` callback can filter (`filterWhere`), sort (`orderBy`/`asc`/`desc`), drop fields (`without`) and `limit` the related records per parent row, `whereRelated` (predicate on a related table via manifest metadata), and `chronologicalFeed` for date-backed limit+1 pagination.
405
+ - **Revision helpers (`src/lib/revision.ts`)** – Adds static/instance helpers (`createFirstRevision`, `newRevision`, etc.) to models flagged with `hasRevisions: true`.
406
+ - **Type helpers (`src/lib/type.ts`)** – Fluent schema builders that feed manifest inference, including virtual field descriptors and multilingual string support via `mlString`.
@@ -0,0 +1,142 @@
1
+ # Multilingual text
2
+
3
+ [README](../README.md) · [Models](models.md) · [Queries](queries.md)
4
+
5
+ The DAL provides runtime-validated multilingual string schemas via `mlString` (imported from `rev-dal/lib/ml-string`). These distinguish text fields that reject tag-like input from fields that allow HTML. They do not escape entities or sanitize HTML.
6
+
7
+ ## Storage Format
8
+
9
+ The intended application convention is to store entity-escaped text (e.g.,
10
+ `My &amp; Co`, `I &lt;3 JS`). Callers must perform this escaping before passing
11
+ values to the DAL. Validation accepts both `A & B` and `A &amp; B` unchanged;
12
+ it neither enforces nor produces an entity-escaped representation.
13
+
14
+ - User types `A & B` → caller escapes it to `A &amp; B` → DAL stores `{ en: "A &amp; B" }`
15
+ - To preserve literal `I <3 JS`, the caller must escape it to `I &lt;3 JS` before validation; the unescaped input is rejected by the tag-stripping check.
16
+ - To remove external markup, callers may explicitly use `stripHTML()` before escaping and storing the result. Validation itself rejects markup rather than removing it.
17
+ - For plain text contexts (emails, exports), decode entities with `decodeHTML()` from the `entities` package when the application follows the escaped-storage convention.
18
+
19
+ ## Schema Methods
20
+
21
+ **Text with tag rejection** – For labels, titles, names, descriptions
22
+
23
+ ```ts
24
+ import mlString from 'rev-dal/lib/ml-string';
25
+
26
+ const thingManifest = {
27
+ hasRevisions: true as const,
28
+ schema: {
29
+ label: mlString.getSafeTextSchema({ maxLength: 256 }),
30
+ aliases: mlString.getSafeTextSchema({ array: true, maxLength: 256 }),
31
+ },
32
+ // ... other fields
33
+ } as const satisfies ModelManifest;
34
+ ```
35
+
36
+ Throws `ValidationError` whenever `striptags(value) !== value`, including for
37
+ some literal angle-bracket text such as `I <3 JS`. This check does not decode
38
+ entities: `&lt;b&gt;Title&lt;/b&gt;` passes unchanged. Strings that pass validation
39
+ are returned unchanged, including raw ampersands and quotes. Passing validation
40
+ alone does not guarantee safe insertion into an HTML text or attribute context.
41
+ The same check applies to each string when `array: true`.
42
+
43
+ **HTML Content** – For cached rendered markdown output
44
+
45
+ ```ts
46
+ const reviewManifest = {
47
+ hasRevisions: true as const,
48
+ schema: {
49
+ html: mlString.getHTMLSchema(),
50
+ },
51
+ // ... other fields
52
+ } as const satisfies ModelManifest;
53
+ ```
54
+
55
+ Permits full HTML markup without sanitizing it. Use only for content sanitized by the caller.
56
+
57
+ **Rich Text (Nested)** – For fields storing both markdown source and cached HTML
58
+
59
+ ```ts
60
+ const teamManifest = {
61
+ hasRevisions: true as const,
62
+ schema: {
63
+ description: mlString.getRichTextSchema(),
64
+ // Expects: { text: { en: "markdown" }, html: { en: "<p>HTML</p>" } }
65
+ },
66
+ // ... other fields
67
+ } as const satisfies ModelManifest;
68
+ ```
69
+
70
+ Validates nested structure: `text` uses the same tag-rejection check as
71
+ `getSafeTextSchema()`, and `html` may contain tags. Neither branch transforms
72
+ entities or sanitizes content.
73
+
74
+ ## Template Rendering
75
+
76
+ ```handlebars
77
+ {{!-- Plain text (entity-escaped at storage) --}}
78
+ <h1>{{mlSafeText review.title}}</h1>
79
+ <meta content="{{mlSafeText thing.label false}}" />
80
+
81
+ {{!-- Pre-rendered HTML --}}
82
+ <div>{{{mlHTML review.html}}}</div>
83
+ <div>{{{mlHTML team.description.html}}}</div>
84
+ ```
85
+
86
+ These are application-provided helpers, not exports of rev-dal. In the consuming
87
+ applications they support language fallbacks and optional language indicators.
88
+ Rendering must account for the storage convention and output context, including
89
+ attribute quoting; DAL validation alone is not an HTML escaping guarantee.
90
+
91
+ ## Security Model
92
+
93
+ Responsibilities when using the escaped-storage convention:
94
+
95
+ 1. **Application input handling** – Adapters/forms escape text entities before writes and sanitize HTML content separately.
96
+ 2. **DAL validation** – Text schemas reject values changed by `striptags`; HTML schemas allow markup. Neither escapes entities.
97
+ 3. **Application rendering** – Templates/helpers handle text and sanitized HTML according to their storage format and output context.
98
+ 4. **Application user feedback** – Middleware may convert validation errors to localized messages; rev-dal does not supply this middleware.
99
+
100
+ ## Helper Methods
101
+
102
+ ```ts
103
+ // Resolve translation with fallbacks
104
+ const resolved = mlString.resolve('de', thing.label);
105
+ // Returns: { str: "Label text", lang: "en" }
106
+
107
+ // Resolve with metadata (preferred languages + available languages)
108
+ const resolvedWithMetadata = mlString.resolveWithMetadata(['de', 'en'], thing.label);
109
+
110
+ // Strip HTML from external data
111
+ const cleaned = mlString.stripHTML({ en: '<b>Bold</b> text' });
112
+ // Returns: { en: 'Bold text' }
113
+
114
+ // Build JSONB query predicates
115
+ const query = mlString.buildQuery('label', 'en', searchTerm, 'ILIKE');
116
+ // Returns: "label->>'en' ILIKE $1"
117
+ ```
118
+
119
+ `stripHTML()` decodes entities first, then strips tags, and does not re-escape
120
+ the result. For example, both `<b>Title</b>` and
121
+ `&lt;b&gt;Title&lt;/b&gt;` become `Title`: escaped literal markup is removed too.
122
+ `A &amp; B` becomes `A & B`, and `I <3 JS` becomes `I ` under the stripping
123
+ library's rules. It is therefore a lossy cleanup helper, not a way to preserve
124
+ arbitrary literal text. Escape its output before storage if your application
125
+ uses the escaped-storage convention. `stripHTMLFromArray()` applies this helper
126
+ to each multilingual object; `stripHTMLFromArrayValues()` uses the same
127
+ decode-then-strip order for each string in multilingual array values.
128
+
129
+ ## Language Provider
130
+
131
+ `mlString` relies on a language provider with these methods:
132
+
133
+ ```ts
134
+ interface DalLanguageProvider {
135
+ getValidLanguagesAndUndetermined(): string[];
136
+ getFallbacks(lang: string): string[];
137
+ }
138
+ ```
139
+
140
+ If you don't call `setLanguageProvider`, rev-dal uses a superset of the language
141
+ lists currently used in lib.reviews and agpwiki. Apps that require strict language
142
+ validation should set their own provider.