@effect-dynamodb/schema 1.39.0 → 1.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/Aggregate.d.ts +11 -4
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +9 -2
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/DynamoModel.d.ts +13 -0
  6. package/dist/DynamoModel.d.ts.map +1 -1
  7. package/dist/DynamoModel.js.map +1 -1
  8. package/dist/DynamoSchema.d.ts +5 -0
  9. package/dist/DynamoSchema.d.ts.map +1 -1
  10. package/dist/DynamoSchema.js.map +1 -1
  11. package/dist/Entity.d.ts +61 -8
  12. package/dist/Entity.d.ts.map +1 -1
  13. package/dist/Entity.js +182 -5
  14. package/dist/Entity.js.map +1 -1
  15. package/dist/KeyComposer.d.ts +157 -3
  16. package/dist/KeyComposer.d.ts.map +1 -1
  17. package/dist/KeyComposer.js +355 -9
  18. package/dist/KeyComposer.js.map +1 -1
  19. package/dist/internal/AggregateEdges.d.ts +3 -3
  20. package/dist/internal/AggregateSchemas.d.ts +181 -14
  21. package/dist/internal/AggregateSchemas.d.ts.map +1 -1
  22. package/dist/internal/AggregateSchemas.js +505 -45
  23. package/dist/internal/AggregateSchemas.js.map +1 -1
  24. package/dist/internal/AggregateTypes.d.ts +396 -36
  25. package/dist/internal/AggregateTypes.d.ts.map +1 -1
  26. package/dist/internal/CompositeCodec.d.ts +274 -6
  27. package/dist/internal/CompositeCodec.d.ts.map +1 -1
  28. package/dist/internal/CompositeCodec.js +829 -25
  29. package/dist/internal/CompositeCodec.js.map +1 -1
  30. package/dist/internal/EffectInstances.d.ts +81 -0
  31. package/dist/internal/EffectInstances.d.ts.map +1 -0
  32. package/dist/internal/EffectInstances.js +656 -0
  33. package/dist/internal/EffectInstances.js.map +1 -0
  34. package/dist/internal/EntitySchemas.d.ts +103 -27
  35. package/dist/internal/EntitySchemas.d.ts.map +1 -1
  36. package/dist/internal/EntitySchemas.js +778 -131
  37. package/dist/internal/EntitySchemas.js.map +1 -1
  38. package/dist/internal/EntityTypes.d.ts +67 -11
  39. package/dist/internal/EntityTypes.d.ts.map +1 -1
  40. package/dist/internal/FailingAsBefore.d.ts +25 -0
  41. package/dist/internal/FailingAsBefore.d.ts.map +1 -0
  42. package/dist/internal/FailingAsBefore.js +42 -0
  43. package/dist/internal/FailingAsBefore.js.map +1 -0
  44. package/dist/internal/InstanceReads.d.ts +33 -0
  45. package/dist/internal/InstanceReads.d.ts.map +1 -0
  46. package/dist/internal/InstanceReads.js +165 -0
  47. package/dist/internal/InstanceReads.js.map +1 -0
  48. package/dist/internal/KeyText136.d.ts +4 -2
  49. package/dist/internal/KeyText136.d.ts.map +1 -1
  50. package/dist/internal/KeyText136.js +40 -9
  51. package/dist/internal/KeyText136.js.map +1 -1
  52. package/dist/internal/NumericKey.d.ts +21 -2
  53. package/dist/internal/NumericKey.d.ts.map +1 -1
  54. package/dist/internal/NumericKey.js +19 -1
  55. package/dist/internal/NumericKey.js.map +1 -1
  56. package/dist/internal/PackedCodec.d.ts +8 -1
  57. package/dist/internal/PackedCodec.d.ts.map +1 -1
  58. package/dist/internal/PackedCodec.js +49 -13
  59. package/dist/internal/PackedCodec.js.map +1 -1
  60. package/dist/internal/SchemaAccessors.d.ts +160 -1
  61. package/dist/internal/SchemaAccessors.d.ts.map +1 -1
  62. package/dist/internal/SchemaAccessors.js +994 -1
  63. package/dist/internal/SchemaAccessors.js.map +1 -1
  64. package/dist/internal/SharedKeyAttribute.d.ts +60 -6
  65. package/dist/internal/SharedKeyAttribute.d.ts.map +1 -1
  66. package/dist/internal/SharedKeyAttribute.js +127 -12
  67. package/dist/internal/SharedKeyAttribute.js.map +1 -1
  68. package/dist/internal/SparseKey.d.ts +46 -0
  69. package/dist/internal/SparseKey.d.ts.map +1 -0
  70. package/dist/internal/SparseKey.js +69 -0
  71. package/dist/internal/SparseKey.js.map +1 -0
  72. package/package.json +1 -1
@@ -32,8 +32,27 @@
32
32
  *
33
33
  * Not part of the public API.
34
34
  */
35
- import { Option, Schema, SchemaAST } from "effect";
36
- import { getSchemaFields, hasEncodingTransformation, numericTypeWithStringEncoding, } from "./SchemaAccessors.js";
35
+ import { Equal, Option, Schema, SchemaAST } from "effect";
36
+ import { substituteSchemaDeep } from "./EntitySchemas.js";
37
+ import { isStoredNaN, KeyValueError, STORED_NAN } from "./NumericKey.js";
38
+ import { getSchemaFields, hasEncodingTransformation, holdsPlainBigint, numericTypeWithStringEncoding, } from "./SchemaAccessors.js";
39
+ /** The same encoded composite value: a scalar, or a `Date` of the same instant. */
40
+ const sameValue = (a, b) => Object.is(a, b) || (a instanceof Date && b instanceof Date && a.getTime() === b.getTime());
41
+ /**
42
+ * The refusal of a composite's number its declared kind can't hold exactly (the
43
+ * `reason` {@link makeCompositeKeyForm} gives `onError`), `[EDD-9050]`. Thrown as
44
+ * a value key composition can't place (`KeyValueError`, as `NaN` is), so every
45
+ * path that takes the value fails with a `ValidationError`, nothing sent, rather
46
+ * than dying. `composite` names it: `Composite "n" on entity "E"`.
47
+ */
48
+ export const refuseInexact = (composite, value, reason) => {
49
+ throw new KeyValueError({
50
+ value,
51
+ reason,
52
+ message: `[EDD-9050] ${composite} has no key text: ${reason}, so a row storing it is one the ` +
53
+ `field can't read.`,
54
+ });
55
+ };
37
56
  /**
38
57
  * Build a `CompositeKeyForm` for a model/derived schema.
39
58
  *
@@ -43,7 +62,9 @@ import { getSchemaFields, hasEncodingTransformation, numericTypeWithStringEncodi
43
62
  * already a wire-shaped string.
44
63
  * 2. **Numeric Type with string Encoded** — the rule's exception. Target is the
45
64
  * numeric Type value: keep a `number` / `bigint` as-is, otherwise `decode`
46
- * to reach it.
65
+ * to reach it. A `NaN` is handed on as `NumericKey.STORED_NAN`: the field
66
+ * stores it (`"NaN"`), which no other numeric field can, so with
67
+ * `escapeKeys` off it keeps the key text 1.36 gave it.
47
68
  * 3. **Anything else** — target is the Encoded value. A field with no encoding
48
69
  * transformation is identity by construction (a numeric one still coerced
49
70
  * to its declared kind, as in case 2) (`SchemaAST` documents
@@ -52,19 +73,46 @@ import { getSchemaFields, hasEncodingTransformation, numericTypeWithStringEncodi
52
73
  * like `gte(t.status, "d")` on a `Schema.Literals` composite is deliberately
53
74
  * not a valid value and must not be rejected by a codec. Otherwise `encode`,
54
75
  * with `decode -> encode` as the fallback so an already-encoded value
55
- * round-trips to itself (`Entity.put`'s strategy).
76
+ * round-trips to itself (`Entity.put`'s strategy), and then, for a value
77
+ * neither takes, the same two from the numeric kind the Encoded side is
78
+ * stored as: a row read back holds a stored `bigint` as a number.
56
79
  *
57
- * `onError` fires when the value reaches neither target form — refuse loudly
58
- * rather than compose a key that silently matches nothing.
80
+ * A codec whose `encode` takes its own output (`x:` prepended,
81
+ * `Schema.StringFromBase64`, a number scaled) takes its stored text too, so
82
+ * `encode` alone can't tell the two sides apart. A value that is its own
83
+ * stored text (`encode(decode(value))` is the value) is that text, keyed as
84
+ * it is: `put` holds `"x:MiX"` for `"MiX"` and keys `x:mix`. Up to 1.39.0
85
+ * it was encoded once more, so `put` keyed `x:x:mix` (`text139` composes
86
+ * that, for `rekey`, and keeps an aggregate's keys, which only its own
87
+ * paths compose, from domain values). A domain value can be such a text as
88
+ * well (`"x:MiX"` itself): a path holding domain values encodes them first
89
+ * ({@link makeCompositeDomainKeyForm}), so the key form only ever sees
90
+ * stored text from it. A codec whose `encode` refuses its own output never
91
+ * reaches this: its stored text takes the `decode -> encode` fallback.
92
+ *
93
+ * `onError` fires when the value of an attribute a key is composed from
94
+ * reaches neither target form — refuse loudly rather than compose a key that
95
+ * silently matches nothing. `reason` says why, when it's a number its numeric
96
+ * kind can't hold exactly, which `onError` refuses with {@link refuseInexact}.
97
+ * `reads` names those attributes, when the records normalised hold others too
98
+ * (a whole row read back from DynamoDB): any other attribute's value is never
99
+ * key text, so one that reaches neither form is left as it is. Without `reads`,
100
+ * every attribute is one.
59
101
  */
60
- export const makeCompositeKeyForm = (source, onError) => {
102
+ export const makeCompositeKeyForm = (source, onError, options) => {
103
+ const keysStoredText = options?.text139 !== true;
61
104
  const fields = getSchemaFields(source);
62
105
  const cache = new Map();
106
+ const reads = options?.reads;
107
+ const refuse = (attr, value, reason) => reads === undefined || reads(attr) ? onError(attr, value, reason) : value;
108
+ /** `value` as `kind` holds it exactly, or refused (a row storing it is one `attr` can't read). */
109
+ const exactly = (attr, kind, value) => exactIn(kind, value) ??
110
+ refuse(attr, value, `${String(value)} is a value no ${kind} holds exactly`);
63
111
  const resolve = (attr) => {
64
112
  const cached = cache.get(attr);
65
113
  if (cached !== undefined)
66
114
  return cached;
67
- const field = fields?.[attr];
115
+ const field = declared(fields, attr);
68
116
  // Case 1.
69
117
  if (field === undefined) {
70
118
  cache.set(attr, null);
@@ -85,18 +133,17 @@ export const makeCompositeKeyForm = (source, onError) => {
85
133
  if (numericTypeWithStringEncoding(field)) {
86
134
  const wantsBigInt = SchemaAST.isBigInt(SchemaAST.toType(field.ast));
87
135
  const decode = Schema.decodeUnknownOption(codec);
136
+ const stored = (value) => storedNaNKeyForm(field, value);
88
137
  const fn = (value) => {
89
- if (typeof value === "bigint")
90
- return wantsBigInt ? value : Number(value);
91
- if (typeof value === "number") {
92
- if (!wantsBigInt)
93
- return value;
94
- return Number.isInteger(value) ? BigInt(value) : onError(attr, value);
138
+ if (isStoredNaN(value))
139
+ return value;
140
+ if (typeof value === "bigint" || typeof value === "number") {
141
+ return stored(exactly(attr, wantsBigInt ? "bigint" : "number", value));
95
142
  }
96
143
  const decoded = decode(value);
97
144
  if (Option.isSome(decoded))
98
- return decoded.value;
99
- return onError(attr, value);
145
+ return stored(decoded.value);
146
+ return refuse(attr, value);
100
147
  };
101
148
  cache.set(attr, fn);
102
149
  return fn;
@@ -106,19 +153,736 @@ export const makeCompositeKeyForm = (source, onError) => {
106
153
  // value unmarshalls as a number (and a `Schema.Number` past 2^53 as a
107
154
  // bigint), so a key re-derived from a stored row would compose at the
108
155
  // other kind's width.
156
+ // A union of kinds storing one numeric kind (`Union([String, BigInt])`) takes it the same way: a
157
+ // stored `N` can only have been that kind. One storing both is left: its value alone can't say.
158
+ // A number the kind can't hold exactly is refused, never rounded: a row holding one is one its
159
+ // field can't read (`rekey` reports it, and its sentinels stay where they are).
109
160
  if (!hasEncodingTransformation(field)) {
110
- const kind = keyFormValueKind(field);
111
- const fn = kind === "bigint"
112
- ? (value) => typeof value === "number" && Number.isInteger(value) ? BigInt(value) : value
113
- : kind === "number"
114
- ? (value) => (typeof value === "bigint" ? Number(value) : value)
115
- : null;
161
+ const declared = keyFormValueKind(field);
162
+ const kind = declared === "bigint" || declared === "number"
163
+ ? declared
164
+ : declared === undefined
165
+ ? onlyNumericKind(storedNumericKinds(field))
166
+ : undefined;
167
+ const fn = kind === undefined
168
+ ? null
169
+ : (value) => typeof value === "number" || typeof value === "bigint"
170
+ ? exactly(attr, kind, value)
171
+ : value;
116
172
  cache.set(attr, fn);
117
173
  return fn;
118
174
  }
119
175
  // Case 3b — target is the Encoded side.
120
176
  const encode = Schema.encodeUnknownOption(codec);
121
177
  const decode = Schema.decodeUnknownOption(codec);
178
+ /** Is `value` its own stored text: what `encode` gives for what it decodes to? */
179
+ const isStoredText = (value) => {
180
+ const decoded = decode(value);
181
+ if (Option.isNone(decoded))
182
+ return false;
183
+ const reencoded = encode(decoded.value);
184
+ return Option.isSome(reencoded) && sameValue(reencoded.value, value);
185
+ };
186
+ const toEncoded = (value) => {
187
+ const direct = encode(value);
188
+ if (Option.isSome(direct)) {
189
+ // `encode` takes the value and changes it: a domain value, or, for a codec whose
190
+ // `encode` takes its own output, its stored text, which is its key text.
191
+ if (keysStoredText && !sameValue(direct.value, value) && isStoredText(value)) {
192
+ return Option.some(value);
193
+ }
194
+ return direct;
195
+ }
196
+ return Option.flatMap(decode(value), (decoded) => encode(decoded));
197
+ };
198
+ // The stored form, as case 3a takes it (`OptionFromNullOr(BigInt)`, a
199
+ // `BigInt` under a decoding default): asked only when the value as given
200
+ // reaches neither form. It is the value `put` handed this rule (the write
201
+ // path holds encoded records), so it takes the steps `put`'s value took.
202
+ const stored = storedNumericForm(field);
203
+ // A row read back holds a stored bigint beneath the field's step as a number
204
+ // (`Schema.Array(Schema.BigInt)` under a decoding default stores `[5n]`, which
205
+ // comes back `[5]`). A read lifts it back, so the value is taken as a read
206
+ // decodes it, and encoded again: asked last, of a value nothing else takes.
207
+ let readDecode;
208
+ const asRead = (value) => {
209
+ if (readDecode === undefined) {
210
+ readDecode = holdsPlainBigint(SchemaAST.toEncoded(field.ast)) ? readDecodeOf(field) : null;
211
+ }
212
+ return readDecode === null ? Option.none() : readDecode(value);
213
+ };
214
+ const fn = (value) => {
215
+ const given = toEncoded(value);
216
+ if (Option.isSome(given))
217
+ return given.value;
218
+ const lifted = stored?.(value);
219
+ if (lifted !== undefined) {
220
+ const fromStored = toEncoded(lifted);
221
+ if (Option.isSome(fromStored))
222
+ return fromStored.value;
223
+ }
224
+ const fromRead = Option.flatMap(asRead(value), (decoded) => encode(decoded));
225
+ if (Option.isSome(fromRead))
226
+ return fromRead.value;
227
+ return refuse(attr, value);
228
+ };
229
+ cache.set(attr, fn);
230
+ return fn;
231
+ };
232
+ // A value of a field storing a declaration may be one read back from a row, which the unmarshaller
233
+ // hands back as a plain map, list or set: it's taken as the field reads it first. Only for an
234
+ // attribute a key reads, when `reads` names them: no other is key text.
235
+ const readBacks = new Map();
236
+ const readBack = (attr) => {
237
+ if (!readBacks.has(attr)) {
238
+ const field = declared(fields, attr);
239
+ readBacks.set(attr, field === undefined ? undefined : storedFormOfDeclaration(field));
240
+ }
241
+ const fn = readBacks.get(attr);
242
+ return fn === undefined || reads === undefined || reads(attr) ? fn : undefined;
243
+ };
244
+ return (attr, value) => {
245
+ if (value === undefined || value === null)
246
+ return value;
247
+ const read = readBack(attr)?.(value);
248
+ const given = read === undefined ? value : read;
249
+ const fn = resolve(attr);
250
+ return fn === null ? given : fn(given);
251
+ };
252
+ };
253
+ /**
254
+ * Whether a schema's Encoded side holds a declaration anywhere (`Schema.Option`, `Schema.Result`,
255
+ * `Schema.ReadonlySet`, `Schema.Duration`, …): at its top, or in a member, property, element or
256
+ * suspension.
257
+ */
258
+ const holdsDeclaration = (ast, seen = new Set()) => {
259
+ if (seen.has(ast))
260
+ return false;
261
+ seen.add(ast);
262
+ if (SchemaAST.isDeclaration(ast))
263
+ return true;
264
+ if (SchemaAST.isSuspend(ast))
265
+ return holdsDeclaration(ast.thunk(), seen);
266
+ if (SchemaAST.isUnion(ast))
267
+ return ast.types.some((member) => holdsDeclaration(member, seen));
268
+ if (SchemaAST.isObjects(ast)) {
269
+ return (ast.propertySignatures.some((property) => holdsDeclaration(property.type, seen)) ||
270
+ ast.indexSignatures.some((index) => holdsDeclaration(index.type, seen)));
271
+ }
272
+ if (SchemaAST.isArrays(ast)) {
273
+ return [...ast.elements, ...ast.rest].some((element) => holdsDeclaration(element, seen));
274
+ }
275
+ return false;
276
+ };
277
+ /**
278
+ * A field's decode as an entity's read decodes a row's value (`legacyReads`): what the marshaller
279
+ * changed is taken back first, a stored bigint read back as a number lifted wherever it sits (in a
280
+ * list, a struct, a declaration's value).
281
+ */
282
+ const readDecodeOf = (field) => Schema.decodeUnknownOption(substituteSchemaDeep(field, { legacyReads: true }));
283
+ /**
284
+ * The value a field storing a declaration ({@link holdsDeclaration}) stored, from what a read of it
285
+ * hands back: the value decoded through the field, as a read decodes it ({@link readDecodeOf}), and
286
+ * encoded again, as a write encodes it. A declaration's value goes to DynamoDB as a map, a list or a
287
+ * set, and comes back a plain one: `Option.some(5)` composes `some(5)`, and the map read back
288
+ * `[object Object]`, until the field decodes it to `Option.some(5)` again; `Option.some(5n)` comes
289
+ * back a map holding `5`, which a read lifts to `5n`. `undefined` for a field storing none, and from
290
+ * the function returned for a value that isn't an object or that the field doesn't decode, which is
291
+ * then taken as it is.
292
+ */
293
+ export const storedFormOfDeclaration = (field) => {
294
+ if (!holdsDeclaration(SchemaAST.toEncoded(field.ast)))
295
+ return undefined;
296
+ const codec = field;
297
+ const asRead = readDecodeOf(field);
298
+ const decode = Schema.decodeUnknownOption(codec);
299
+ const encode = Schema.encodeUnknownOption(codec);
300
+ return (value) => {
301
+ if (typeof value !== "object" || value === null)
302
+ return undefined;
303
+ const read = asRead(value);
304
+ const decoded = Option.isSome(read) ? read : decode(value);
305
+ const stored = Option.flatMap(decoded, (domain) => encode(domain));
306
+ return Option.isSome(stored) ? stored.value : undefined;
307
+ };
308
+ };
309
+ /**
310
+ * The value a field held when it was stored, from what the unmarshaller hands
311
+ * back for it. A field whose Encoded side is a `bigint` is stored as `N` and
312
+ * comes back as a number while it is a safe integer; one whose Encoded side is
313
+ * a number comes back as a `bigint` past 2^53. `undefined` when the field's
314
+ * Encoded side isn't one numeric kind, and from the function returned for a
315
+ * value already of that kind (or not a number at all).
316
+ */
317
+ export const storedNumericForm = (field) => liftToKind(storedNumericKinds(field));
318
+ /** {@link storedNumericForm}, from the kinds a field stores. */
319
+ const liftToKind = (kinds) => {
320
+ if (kinds.size !== 1)
321
+ return undefined;
322
+ if (kinds.has("bigint")) {
323
+ return (value) => typeof value === "number" && Number.isSafeInteger(value) ? BigInt(value) : undefined;
324
+ }
325
+ return (value) => typeof value === "bigint" && Number.isSafeInteger(Number(value)) ? Number(value) : undefined;
326
+ };
327
+ /** The one numeric kind of `kinds`, when there's one. */
328
+ const onlyNumericKind = (kinds) => kinds.size === 1 ? [...kinds][0] : undefined;
329
+ /**
330
+ * `value` as `kind` holds it, exactly: a bigint as a number only within the safe range (a number
331
+ * can't be written past it, and DynamoDB hands one back as a bigint there), a number as a bigint
332
+ * only when it's an integer. `undefined` when `kind` can't hold it: a row storing that value is one
333
+ * a field of that kind can't read.
334
+ */
335
+ const exactIn = (kind, value) => kind === "bigint"
336
+ ? typeof value === "bigint"
337
+ ? value
338
+ : Number.isInteger(value)
339
+ ? BigInt(value)
340
+ : undefined
341
+ : typeof value === "number"
342
+ ? value
343
+ : Number.isSafeInteger(Number(value))
344
+ ? Number(value)
345
+ : undefined;
346
+ /**
347
+ * The numeric kinds a field's stored `N` can have been written from: those its Encoded side admits.
348
+ * `Schema.BigInt` and `Schema.Union([Schema.String, Schema.BigInt])` store only a `bigint`;
349
+ * `Schema.Union([Schema.Number, Schema.BigInt])` stores both, and so does an unknown value. Read back,
350
+ * a field storing one kind is that kind ({@link storedNumericForm}); a field storing both can't say
351
+ * which from the value alone, so no key is composed from one: declared, it's refused at load
352
+ * ({@link bothKindsKeyRefusal}), and a key whose kinds can't be read (`Schema.Unknown`, a declaration)
353
+ * refuses a value that reads back otherwise at write ({@link readsBackOtherwise}).
354
+ */
355
+ export const storedNumericKinds = (field) => numericKinds(field, true);
356
+ /**
357
+ * The numeric kinds a field's Encoded side declares: {@link storedNumericKinds} but for what
358
+ * `Schema.Unknown` and `Schema.Any` take, which declare no kind.
359
+ */
360
+ const numericKinds = (field, open) => {
361
+ const kinds = new Set();
362
+ const seen = new Set();
363
+ const walk = (ast) => {
364
+ if (SchemaAST.isSuspend(ast)) {
365
+ if (seen.has(ast))
366
+ return;
367
+ seen.add(ast);
368
+ walk(ast.thunk());
369
+ }
370
+ else if (SchemaAST.isNumber(ast))
371
+ kinds.add("number");
372
+ else if (SchemaAST.isBigInt(ast))
373
+ kinds.add("bigint");
374
+ else if (SchemaAST.isUnknown(ast) || SchemaAST.isAny(ast)) {
375
+ if (open) {
376
+ kinds.add("number");
377
+ kinds.add("bigint");
378
+ }
379
+ }
380
+ else if (SchemaAST.isLiteral(ast)) {
381
+ if (typeof ast.literal === "number")
382
+ kinds.add("number");
383
+ if (typeof ast.literal === "bigint")
384
+ kinds.add("bigint");
385
+ }
386
+ else if (SchemaAST.isEnum(ast)) {
387
+ for (const [, value] of ast.enums)
388
+ if (typeof value === "number")
389
+ kinds.add("number");
390
+ }
391
+ else if (SchemaAST.isUnion(ast)) {
392
+ for (const member of ast.types)
393
+ walk(member);
394
+ }
395
+ };
396
+ walk(SchemaAST.toEncoded(field.ast));
397
+ return kinds;
398
+ };
399
+ /**
400
+ * `[EDD-9128]`: a key composite declaring both numeric kinds, or `undefined` for one that doesn't.
401
+ * DynamoDB stores `5` and `5n` alike, as `{N:"5"}`, and a safe integer reads back as a `number`
402
+ * whichever was written, while the two compose different key text (16 digits, 38). So a key composed
403
+ * again from a row read back (`restore`, an update reading the item first, a delete releasing a
404
+ * unique constraint, `rekey`, an aggregate's `update` and `list`) wouldn't be the key `put` wrote,
405
+ * and the value can't say which kind it was. Refused at load wherever a value is composed into key
406
+ * text: a key, a unique constraint, a vector partition, a time-series `orderBy`. A field no key reads
407
+ * may store both. `Schema.Unknown` and `Schema.Any` declare no kind, and a key over one that holds
408
+ * strings works, so they're judged by value at write instead ({@link readsBackOtherwise}), as is a
409
+ * declaration and a transformation whose Encoded side is one of these.
410
+ */
411
+ export const bothKindsKeyRefusal = (owner, where, attr, field) => {
412
+ if (numericKinds(field, false).size < 2)
413
+ return undefined;
414
+ return new Error(`[EDD-9128] ${owner}: ${where} can't be composed from "${attr}", which stores both a number ` +
415
+ `and a bigint. DynamoDB stores 5 and 5n alike and reads a safe integer back as a number, ` +
416
+ `and the two compose different key text, so a key composed again from a stored row ` +
417
+ `wouldn't be the key the write composed. Declare the one kind it holds, such as ` +
418
+ `Schema.Number or Schema.BigInt.`);
419
+ };
420
+ /**
421
+ * Whether the numeric kinds a field stores can't be read off its schema: its Encoded side holds a
422
+ * `Schema.Unknown`, a `Schema.Any` or a declaration (`Schema.declare`), alone, in a union or behind a
423
+ * `Schema.suspend`. A transformation is judged by its Encoded side, so `Schema.Unknown` decoded to a
424
+ * `Schema.BigInt` is one.
425
+ */
426
+ const kindsUnreadable = (field) => {
427
+ const seen = new Set();
428
+ const walk = (ast) => {
429
+ if (SchemaAST.isSuspend(ast)) {
430
+ if (seen.has(ast))
431
+ return false;
432
+ seen.add(ast);
433
+ return walk(ast.thunk());
434
+ }
435
+ if (SchemaAST.isUnknown(ast) || SchemaAST.isAny(ast) || SchemaAST.isDeclaration(ast))
436
+ return true;
437
+ return SchemaAST.isUnion(ast) && ast.types.some(walk);
438
+ };
439
+ return walk(SchemaAST.toEncoded(field.ast));
440
+ };
441
+ /** Whether a schema transforms anywhere: at its top, or in a member, property, element or suspension. */
442
+ const transformsAnywhere = (ast, seen = new Set()) => {
443
+ if (seen.has(ast))
444
+ return false;
445
+ seen.add(ast);
446
+ if (ast.encoding !== undefined)
447
+ return true;
448
+ if (SchemaAST.isSuspend(ast))
449
+ return transformsAnywhere(ast.thunk(), seen);
450
+ if (SchemaAST.isUnion(ast))
451
+ return ast.types.some((member) => transformsAnywhere(member, seen));
452
+ if (SchemaAST.isObjects(ast)) {
453
+ return (ast.propertySignatures.some((property) => transformsAnywhere(property.type, seen)) ||
454
+ ast.indexSignatures.some((index) => transformsAnywhere(index.type, seen)));
455
+ }
456
+ if (SchemaAST.isArrays(ast)) {
457
+ return [...ast.elements, ...ast.rest].some((element) => transformsAnywhere(element, seen));
458
+ }
459
+ if (SchemaAST.isDeclaration(ast)) {
460
+ return ast.typeParameters.some((parameter) => transformsAnywhere(parameter, seen));
461
+ }
462
+ return false;
463
+ };
464
+ /**
465
+ * Whether a key composite's read-back can't be guaranteed at load, so a write judges each value it
466
+ * stores: a field whose numeric kinds can't be read off its schema (`Schema.Unknown`, `Schema.Any`, a
467
+ * declaration, alone or in a union), or one with a transformation anywhere on it. Only a field of
468
+ * known kinds with no transformation reads back as itself by construction: the marshaller's only
469
+ * changes to such a value (a safe-integer `bigint` read back as a number, a number past 2^53 as a
470
+ * `bigint`, `-0` as `0`) compose the same key text.
471
+ */
472
+ export const readBackUnsure = (field) => kindsUnreadable(field) || transformsAnywhere(field.ast);
473
+ /**
474
+ * The value a field stored, from what a read of it hands back, for composing a key from a row read
475
+ * back: `undefined` when it's that already. A field storing one numeric kind takes it
476
+ * ({@link storedNumericForm}). A field whose kinds can't be read off its schema ({@link
477
+ * kindsUnreadable}) is decoded through the field, as a read decodes it, and encoded again, as a write
478
+ * encodes it: `Schema.Unknown` decoded to a `Schema.BigInt` with `BigInt(n)` stored `5n`, which reads
479
+ * back as `5`, and decoding `5` gives `5n` again. A field storing a declaration takes an object the
480
+ * same way ({@link storedFormOfDeclaration}): `Option.some(5)` comes back a plain map. Only these
481
+ * are taken this way, the only values DynamoDB hands back otherwise, and for any other field nothing
482
+ * is.
483
+ */
484
+ export const storedFormOfRead = (field) => {
485
+ const lift = storedNumericForm(field);
486
+ const declared = storedFormOfDeclaration(field);
487
+ const numeric = lift ?? (kindsUnreadable(field) ? numericFormOfRead(field) : undefined);
488
+ if (declared === undefined)
489
+ return numeric;
490
+ return (value) => typeof value === "object" && value !== null ? declared(value) : numeric?.(value);
491
+ };
492
+ /** {@link storedFormOfRead} of a number or a bigint, for a field whose kinds can't be read off it. */
493
+ const numericFormOfRead = (field) => {
494
+ const codec = field;
495
+ const decode = Schema.decodeUnknownOption(codec);
496
+ const encode = Schema.encodeUnknownOption(codec);
497
+ return (value) => {
498
+ if (typeof value !== "number" && typeof value !== "bigint")
499
+ return undefined;
500
+ const stored = Option.flatMap(decode(value), (decoded) => encode(decoded));
501
+ return Option.isSome(stored) && !Object.is(stored.value, value) ? stored.value : undefined;
502
+ };
503
+ };
504
+ /**
505
+ * Whether two decoded values compose the same key text: the same value, or the same number (`-0` and
506
+ * `0` compose the same text).
507
+ */
508
+ const sameKeyValue = (a, b) => typeof a === typeof b &&
509
+ (Object.is(a, b) || (typeof a === "number" && a === b) || Equal.equals(a, b));
510
+ /**
511
+ * For a key composite whose read-back can't be guaranteed at load ({@link readBackUnsure}, of the
512
+ * field that reads it back or of the one a write encodes it with): what a value a write stores reads
513
+ * back as, when a key composed again from the row read back wouldn't be the key written. `"a
514
+ * number"` or `"a bigint"` for a value read back as the other kind, `"a value the field refuses"`,
515
+ * or the value it reads back as. `undefined` for a value that reads back as written.
516
+ *
517
+ * `asRead` is what DynamoDB hands back for a stored value, the marshaller and the unmarshaller run
518
+ * for real: a safe-integer `bigint` comes back as a `number`, and `-0` as `0`. A `number` past
519
+ * 2^53 the marshaller refuses, which the write's own marshalling reports (`EDD-9124`). A value that
520
+ * comes back as it went is never judged. One that doesn't is judged twice: each of `texts` composed
521
+ * from the value written and from the value read back must be the same text, and a value that isn't
522
+ * an object, read back and decoded through `field`, must be the value written decoded (when that
523
+ * decodes). An object is judged by its texts alone: `Option.some(5)` comes back a plain map, which
524
+ * the key form decodes to `Option.some(5)` again ({@link storedFormOfDeclaration}), so it composes
525
+ * the text written, while a struct holding a `bigint` reads back holding a number its field refuses,
526
+ * and composes the text written all the same. `Schema.Unknown` reads `5n` back as `5`, and a
527
+ * declaration of either kind does the same, so both are refused; `Schema.Unknown` decoded to a
528
+ * `Schema.BigInt` with `BigInt(n)` reads it back as `5n`, and is stored. A codec decoding `-0` and
529
+ * `0` to different values refuses `-0`. The judge itself is `undefined` for a field that reads back
530
+ * as itself by construction, which never needs asking.
531
+ */
532
+ export const readsBackOtherwise = (field, options) => {
533
+ if (!readBackUnsure(field) &&
534
+ (options.written === undefined || !readBackUnsure(options.written))) {
535
+ return undefined;
536
+ }
537
+ const decode = Schema.decodeUnknownOption(field);
538
+ // A read takes what DynamoDB hands back as the one numeric kind the field stores, when it stores
539
+ // one ({@link storedNumericForm}): `OptionFromNullOr(Schema.BigInt)` reads `5` as `5n`.
540
+ const lift = storedNumericForm(field);
541
+ const texts = options.texts ?? [];
542
+ return (stored) => {
543
+ // A string or a boolean comes back as it went.
544
+ if (typeof stored === "string" || typeof stored === "boolean")
545
+ return undefined;
546
+ let returned;
547
+ try {
548
+ returned = options.asRead(stored);
549
+ }
550
+ catch {
551
+ // A value the marshaller refuses is the write's own marshalling's to report.
552
+ return undefined;
553
+ }
554
+ if (Object.is(returned, stored))
555
+ return undefined;
556
+ const read = decode(lift?.(returned) ?? returned);
557
+ const written = decode(stored);
558
+ const textMoved = texts.some((text) => {
559
+ const at = text.written(stored);
560
+ return at !== undefined && text.read(returned) !== at;
561
+ });
562
+ // An object's key text is its texts' to judge: what each composes from the value read back is
563
+ // what a key composed again from the row holds.
564
+ const valueMoved = Option.isSome(written) &&
565
+ typeof written.value !== "object" &&
566
+ typeof written.value !== "function" &&
567
+ (Option.isNone(read) || !sameKeyValue(read.value, written.value));
568
+ if (!textMoved && !valueMoved)
569
+ return undefined;
570
+ return readBackAs(read, Option.isSome(written) ? written.value : stored);
571
+ };
572
+ };
573
+ /**
574
+ * What a value reads back as, in the words of {@link readsBackOtherwise}: `"a value the field
575
+ * refuses"` when the read fails, `"a number"` or `"a bigint"` for one of another kind than `was`, the
576
+ * value written, and otherwise the value read back.
577
+ */
578
+ export const readBackAs = (read, was) => {
579
+ if (Option.isNone(read))
580
+ return "a value the field refuses";
581
+ if (typeof read.value !== typeof was) {
582
+ return typeof read.value === "bigint"
583
+ ? "a bigint"
584
+ : typeof read.value === "number"
585
+ ? "a number"
586
+ : "something else";
587
+ }
588
+ return typeof read.value === "bigint"
589
+ ? `${read.value}n`
590
+ : typeof read.value === "number" || typeof read.value === "boolean"
591
+ ? String(read.value)
592
+ : typeof read.value === "string"
593
+ ? JSON.stringify(read.value)
594
+ : "something else";
595
+ };
596
+ /**
597
+ * The field a composite names by its dotted path (`nested.n`): the first segment a field of
598
+ * `fields`, each further one looked up through what holds it on the way — `Schema.optional`,
599
+ * `Schema.optionalKey`, `Schema.NullOr` or another union with `null` or `undefined`,
600
+ * `Schema.suspend`, and a `Schema.Class` — as the value holds it. A union of structs naming the
601
+ * segment in several members gives the union of their fields. `undefined` where a segment names
602
+ * nothing.
603
+ */
604
+ export const fieldAtPath = (fields, path) => followPath(fields, path, (ast) => ast);
605
+ /**
606
+ * {@link fieldAtPath} on the stored side: each segment looked up in what its holder is stored as, so
607
+ * a transformation of a value on the way (a struct decoded to another struct) is kept, and the field
608
+ * found is the one a row holds. `Schema.Struct({ n: Schema.Number })` decoded to a struct whose `n`
609
+ * is `Schema.Union([Schema.Number, Schema.BigInt])` stores a number at `nested.n`.
610
+ */
611
+ export const storedFieldAtPath = (fields, path) => followPath(fields, path, (ast) => SchemaAST.toEncoded(ast));
612
+ /**
613
+ * The field a model declares under `name`. Never a member every object
614
+ * inherits: an attribute named `toString` that the model doesn't declare (a
615
+ * version or timestamp attribute) is not a field.
616
+ */
617
+ const declared = (fields, name) => fields !== undefined && Object.hasOwn(fields, name) ? fields[name] : undefined;
618
+ const followPath = (fields, path, side) => {
619
+ const [first, ...rest] = path.split(".");
620
+ const top = declared(fields, first);
621
+ if (top === undefined || rest.length === 0)
622
+ return top;
623
+ let at = [side(top.ast)];
624
+ for (const segment of rest) {
625
+ at = at.flatMap((ast) => propertyAt(ast, segment, new Set()));
626
+ if (at.length === 0)
627
+ return undefined;
628
+ }
629
+ return at.length === 1
630
+ ? Schema.make(at[0])
631
+ : Schema.Union(at.map((ast) => Schema.make(ast)));
632
+ };
633
+ const propertyAt = (ast, name, seen) => {
634
+ if (SchemaAST.isSuspend(ast)) {
635
+ if (seen.has(ast))
636
+ return [];
637
+ seen.add(ast);
638
+ return propertyAt(ast.thunk(), name, seen);
639
+ }
640
+ if (SchemaAST.isUnion(ast)) {
641
+ return ast.types.flatMap((member) => SchemaAST.isUndefined(member) || SchemaAST.isNull(member)
642
+ ? []
643
+ : propertyAt(member, name, seen));
644
+ }
645
+ if (SchemaAST.isObjects(ast)) {
646
+ const property = ast.propertySignatures.find((signature) => signature.name === name);
647
+ return property === undefined ? [] : [property.type];
648
+ }
649
+ // A class: a declaration of its struct, which is what it's stored as.
650
+ if (SchemaAST.isDeclaration(ast) &&
651
+ ast.typeParameters.length === 1 &&
652
+ SchemaAST.isObjects(SchemaAST.toEncoded(ast))) {
653
+ return propertyAt(ast.typeParameters[0], name, seen);
654
+ }
655
+ return [];
656
+ };
657
+ /**
658
+ * A number or bigint as the other kind, read from `stored`, the `N` its field stored, when there
659
+ * is one: a bigint past 2^53 keeps its digits, and a number that isn't an integer has no bigint.
660
+ * `undefined` for anything else.
661
+ */
662
+ export const otherNumericKind = (value, stored) => {
663
+ if (typeof value === "bigint")
664
+ return Number(stored ?? value);
665
+ if (typeof value !== "number")
666
+ return undefined;
667
+ const integer = stored !== undefined ? /^-?\d+$/.test(stored) : Number.isInteger(value);
668
+ return integer ? BigInt(stored ?? value) : undefined;
669
+ };
670
+ /** {@link KindTargets} over `texts`: sorted once, then each question is a binary search. */
671
+ export const kindTargets = (texts) => {
672
+ // Compared by UTF-16 code unit, as `<` and `startsWith` compare: the texts beginning with a
673
+ // prefix sort together, from the first one not below it.
674
+ const sorted = [...new Set(texts)].sort();
675
+ const from = (text) => {
676
+ let low = 0;
677
+ let high = sorted.length;
678
+ while (low < high) {
679
+ const middle = (low + high) >>> 1;
680
+ if (sorted[middle] < text)
681
+ low = middle + 1;
682
+ else
683
+ high = middle;
684
+ }
685
+ return sorted[low];
686
+ };
687
+ return {
688
+ has: (text) => from(text) === text,
689
+ hasPrefix: (prefix) => from(prefix)?.startsWith(prefix) ?? false,
690
+ };
691
+ };
692
+ /**
693
+ * The reading of `record` whose `compose` is `stored`, or one of the texts in `stored`: each of
694
+ * `fields` that holds a number or a bigint given as its own kind or as the other one ({@link
695
+ * otherNumericKind}, the other read from `digits`, the `N` the field stored). A field that stored
696
+ * both kinds (`Schema.Union([Schema.Number, Schema.BigInt])` before {@link bothKindsKeyRefusal},
697
+ * or a `Schema.Unknown`) composed each value's own kind's text, so `rekey` looks for a row stored
698
+ * under the other kind's. `compose` gives `undefined` for values with no text there.
699
+ *
700
+ * `compose` may give its text in segments, whose concatenation is the text (a key's partition and
701
+ * sort key halves): a value is looked for once in each segment, so a composite in both halves of a
702
+ * key is found in both. Each field is one decision, its kind, whichever segments it is in.
703
+ *
704
+ * `record` as it is comes first, and when its text is looked for nothing else is composed: that is
705
+ * a row under its current key, every row of a clean run. Otherwise each field is composed once as
706
+ * the other kind by itself, which shows where its value lies in each segment: the stretch where
707
+ * that segment and `record`'s differ. The readings are then walked stretch by stretch from the
708
+ * left, keeping those whose text so far begins a text looked for, a field's later stretches
709
+ * following its first, and one left whole at the end is composed to confirm it. That is one
710
+ * composition per field and one or two more, never one per combination, and no text is split on
711
+ * its delimiters. When two fields' stretches overlap in a segment, a composer that doesn't keep
712
+ * each value in a stretch of its own, each field is read as the other kind only alone.
713
+ */
714
+ export const kindReadingOf = (record, fields, digits, compose, stored) => {
715
+ const targets = typeof stored === "string"
716
+ ? { has: (text) => text === stored, hasPrefix: (prefix) => stored.startsWith(prefix) }
717
+ : stored;
718
+ const composed = (reading) => {
719
+ try {
720
+ const out = compose(reading);
721
+ return out === undefined ? undefined : typeof out === "string" ? [out] : out;
722
+ }
723
+ catch {
724
+ return undefined;
725
+ }
726
+ };
727
+ const given = { record, asOther: new Set() };
728
+ const segments = composed(given);
729
+ if (segments === undefined)
730
+ return undefined;
731
+ const base = segments.join("");
732
+ if (targets.has(base))
733
+ return given;
734
+ const offsets = [];
735
+ let offset = 0;
736
+ for (const segment of segments) {
737
+ offsets.push(offset);
738
+ offset += segment.length;
739
+ }
740
+ const others = new Map();
741
+ const edits = [];
742
+ for (const field of new Set(fields)) {
743
+ const other = otherNumericKind(record[field], digits(field));
744
+ if (other === undefined)
745
+ continue;
746
+ const alone = { record: { ...record, [field]: other }, asOther: new Set([field]) };
747
+ const parts = composed(alone);
748
+ if (parts === undefined)
749
+ continue;
750
+ const text = parts.join("");
751
+ if (text === base)
752
+ continue;
753
+ if (targets.has(text))
754
+ return alone;
755
+ // Segments that don't line up can't be compared stretch by stretch: read alone only.
756
+ if (parts.length !== segments.length)
757
+ continue;
758
+ others.set(field, other);
759
+ for (let i = 0; i < segments.length; i++) {
760
+ const was = segments[i];
761
+ const now = parts[i];
762
+ if (was === now)
763
+ continue;
764
+ let start = 0;
765
+ while (start < was.length && start < now.length && was[start] === now[start])
766
+ start++;
767
+ let tail = 0;
768
+ while (tail < was.length - start &&
769
+ tail < now.length - start &&
770
+ was[was.length - 1 - tail] === now[now.length - 1 - tail]) {
771
+ tail++;
772
+ }
773
+ edits.push({
774
+ field,
775
+ other,
776
+ start: offsets[i] + start,
777
+ end: offsets[i] + was.length - tail,
778
+ text: now.slice(start, now.length - tail),
779
+ });
780
+ }
781
+ }
782
+ // Each field alone has been tried.
783
+ if (others.size < 2)
784
+ return undefined;
785
+ edits.sort((a, b) => a.start - b.start || a.end - b.end);
786
+ if (edits.some((edit, i) => i > 0 && edit.start <= edits[i - 1].start))
787
+ return undefined;
788
+ if (edits.some((edit, i) => i > 0 && edit.start < edits[i - 1].end))
789
+ return undefined;
790
+ // Where each field's last stretch is: a decision is followed until then.
791
+ const last = new Map();
792
+ for (let i = 0; i < edits.length; i++)
793
+ last.set(edits[i].field, i);
794
+ let walked = new Map([["", { text: "", decided: new Map() }]]);
795
+ let at = 0;
796
+ for (let i = 0; i < edits.length; i++) {
797
+ const edit = edits[i];
798
+ const next = new Map();
799
+ const between = base.slice(at, edit.start);
800
+ for (const { text, decided } of walked.values()) {
801
+ const made = decided.get(edit.field);
802
+ for (const asOther of made === undefined ? [false, true] : [made]) {
803
+ const sofar = `${text}${between}${asOther ? edit.text : base.slice(edit.start, edit.end)}`;
804
+ if (!targets.hasPrefix(sofar))
805
+ continue;
806
+ const now = new Map(decided).set(edit.field, asOther);
807
+ // Readings with one text so far differ only in decisions still to be followed.
808
+ const pending = [...now]
809
+ .filter(([field]) => last.get(field) > i)
810
+ .map(([field, flipped]) => `${field}:${flipped ? 1 : 0}`)
811
+ .join(",");
812
+ const key = `${sofar}\u0000${pending}`;
813
+ if (!next.has(key))
814
+ next.set(key, { text: sofar, decided: now });
815
+ }
816
+ }
817
+ if (next.size === 0)
818
+ return undefined;
819
+ walked = next;
820
+ at = edit.end;
821
+ }
822
+ const rest = base.slice(at);
823
+ for (const { text, decided } of walked.values()) {
824
+ const flipped = [...decided].filter(([, asOther]) => asOther).map(([field]) => field);
825
+ if (flipped.length < 2 || !targets.has(`${text}${rest}`))
826
+ continue;
827
+ const values = { ...record };
828
+ for (const field of flipped)
829
+ values[field] = others.get(field);
830
+ const reading = { record: values, asOther: new Set(flipped) };
831
+ const confirmed = composed(reading);
832
+ if (confirmed !== undefined && targets.has(confirmed.join("")))
833
+ return reading;
834
+ }
835
+ return undefined;
836
+ };
837
+ /**
838
+ * Build the function that puts a composite's DOMAIN value into the form
839
+ * `Entity.put` stores it in, before `makeCompositeKeyForm`'s normaliser composes
840
+ * a key from it — so a key composed from a caller's value is the key `put`
841
+ * wrote for it.
842
+ *
843
+ * `put` encodes its input (`encode`, else `decode -> encode`), then composes
844
+ * keys through the key-form normaliser, which keys that stored text as it is.
845
+ * For a codec that `encode` takes on its own output (`x:` prepended by
846
+ * `encode`, stripped by `decode`; a number scaled by `encode`), a caller's
847
+ * value is therefore encoded here first, once: the normaliser can't tell
848
+ * `"x:MiX"` given as a domain value from `"MiX"`'s stored text.
849
+ *
850
+ * A codec inside a wrapper (`Schema.optional(Schema.NumberFromString)`, a union
851
+ * of a codec and a literal) is encoded here too, as `put` encodes it. The
852
+ * normaliser takes such a field as it comes, so `put` keys its stored text
853
+ * (`id_5`), and a caller's `5` composed `id_0000000000000005`, a key `put` never
854
+ * writes.
855
+ *
856
+ * Every other composite is untouched here — an untransformed one, a numeric one
857
+ * stored as a string (the normaliser takes either side), and a codec whose
858
+ * `encode` refuses its own output compose the same key whichever form they come
859
+ * in.
860
+ *
861
+ * A value no step takes is passed through, for the normaliser to refuse.
862
+ */
863
+ export const makeCompositeStoredForm = (source) => {
864
+ const storedForm = compositeStoredForm(source);
865
+ return (record) => toCompositeKeyRecord(storedForm, record);
866
+ };
867
+ /** {@link makeCompositeStoredForm}, one attribute at a time. */
868
+ const compositeStoredForm = (source) => {
869
+ const fields = getSchemaFields(source);
870
+ const cache = new Map();
871
+ const resolve = (attr) => {
872
+ const cached = cache.get(attr);
873
+ if (cached !== undefined)
874
+ return cached;
875
+ const field = declared(fields, attr);
876
+ if (field === undefined ||
877
+ numericTypeWithStringEncoding(field) ||
878
+ // No transformation anywhere in it, a wrapper's included: stored as given.
879
+ SchemaAST.toEncoded(field.ast) === field.ast) {
880
+ cache.set(attr, null);
881
+ return null;
882
+ }
883
+ const codec = field;
884
+ const encode = Schema.encodeUnknownOption(codec);
885
+ const decode = Schema.decodeUnknownOption(codec);
122
886
  const fn = (value) => {
123
887
  const direct = encode(value);
124
888
  if (Option.isSome(direct))
@@ -129,7 +893,7 @@ export const makeCompositeKeyForm = (source, onError) => {
129
893
  if (Option.isSome(reencoded))
130
894
  return reencoded.value;
131
895
  }
132
- return onError(attr, value);
896
+ return value;
133
897
  };
134
898
  cache.set(attr, fn);
135
899
  return fn;
@@ -141,6 +905,22 @@ export const makeCompositeKeyForm = (source, onError) => {
141
905
  return fn === null ? value : fn(value);
142
906
  };
143
907
  };
908
+ /**
909
+ * The key form of a caller's DOMAIN value: {@link makeCompositeStoredForm}'s
910
+ * stored form, then `makeCompositeKeyForm`'s key form — what `Entity.put`
911
+ * composes for the value: encode a domain value once, then key that text.
912
+ * Every path that composes a key from values a caller gives (an accessor's
913
+ * composites, a `.where()` or `.within()` bound, a collection's or a vector
914
+ * index's partition, a geo search's filter, a multi-item op's key, a
915
+ * projection's row) composes through it, so it finds what `put` wrote. Except
916
+ * for a domain value that is also its codec's stored text (`"x:MiX"`), it is
917
+ * exactly the key form.
918
+ */
919
+ export const makeCompositeDomainKeyForm = (source, onError) => {
920
+ const keyForm = makeCompositeKeyForm(source, onError);
921
+ const storedForm = compositeStoredForm(source);
922
+ return (attr, value) => keyForm(attr, storedForm(attr, value));
923
+ };
144
924
  /**
145
925
  * Apply a `CompositeKeyForm` across every entry of a record, so a whole key or
146
926
  * composite record can be normalised in one call.
@@ -163,7 +943,11 @@ export const compositeKeyFormKind = (source, attr) => {
163
943
  return "identity";
164
944
  return "encoded";
165
945
  };
166
- const astKeyFormValueKind = (ast) => {
946
+ const astKeyFormValueKind = (ast, seen = new Set()) => {
947
+ // A suspended schema is the schema it suspends (`Schema.suspend(() => Schema.BigInt)`).
948
+ if (SchemaAST.isSuspend(ast)) {
949
+ return seen.has(ast) ? undefined : astKeyFormValueKind(ast.thunk(), new Set([...seen, ast]));
950
+ }
167
951
  if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast))
168
952
  return "string";
169
953
  if (SchemaAST.isNumber(ast))
@@ -179,7 +963,7 @@ const astKeyFormValueKind = (ast) => {
179
963
  : SchemaAST.isUnion(ast)
180
964
  ? ast.types
181
965
  .filter((member) => !SchemaAST.isUndefined(member) && !SchemaAST.isNull(member))
182
- .map((member) => astKeyFormValueKind(member))
966
+ .map((member) => astKeyFormValueKind(member, seen))
183
967
  : [undefined];
184
968
  const [first] = kinds;
185
969
  return first !== undefined && kinds.every((kind) => kind === first) ? first : undefined;
@@ -195,6 +979,26 @@ export const keyFormValueKind = (field) => {
195
979
  }
196
980
  return astKeyFormValueKind(SchemaAST.toEncoded(field.ast));
197
981
  };
982
+ /**
983
+ * `value` in key form where it's the `NaN` of a number `field` stores as a string
984
+ * (`Schema.NumberFromString`): `NumericKey.STORED_NAN`. The field stores it as `"NaN"`, so a row
985
+ * can hold it, and with `escapeKeys` off it composes the text 1.36 gave it, as up to 1.39.0. A
986
+ * `number`'s own `NaN`, which no row holds, has no key text. Any other value as it is. The one
987
+ * place the two are told apart: the composite key form, and an aggregate's `many` edge sort key,
988
+ * which is composed from the element's values.
989
+ */
990
+ export const storedNaNKeyForm = (field, value) => typeof value === "number" &&
991
+ Number.isNaN(value) &&
992
+ field !== undefined &&
993
+ numericTypeWithStringEncoding(field) &&
994
+ !SchemaAST.isBigInt(SchemaAST.toType(field.ast))
995
+ ? STORED_NAN
996
+ : value;
997
+ /**
998
+ * The JavaScript type of a key-form value, to compare with {@link keyFormValueKind}: `"number"` for
999
+ * `NumericKey.STORED_NAN`, the `NaN` a number stored as a string hands on, as for any other number.
1000
+ */
1001
+ export const keyFormValueKindOf = (value) => isStoredNaN(value) ? "number" : typeof value;
198
1002
  /**
199
1003
  * The literal members a field's key form is limited to (a literal, a union of
200
1004
  * literals or an enum), or `undefined` when it isn't limited to literals.