@effect-dynamodb/schema 1.39.0 → 1.41.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 (122) hide show
  1. package/dist/Aggregate.d.ts +11 -4
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +12 -2
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/DynamoModel.d.ts +48 -7
  6. package/dist/DynamoModel.d.ts.map +1 -1
  7. package/dist/DynamoModel.js +34 -16
  8. package/dist/DynamoModel.js.map +1 -1
  9. package/dist/DynamoSchema.d.ts +25 -0
  10. package/dist/DynamoSchema.d.ts.map +1 -1
  11. package/dist/DynamoSchema.js.map +1 -1
  12. package/dist/Entity.d.ts +66 -11
  13. package/dist/Entity.d.ts.map +1 -1
  14. package/dist/Entity.js +261 -34
  15. package/dist/Entity.js.map +1 -1
  16. package/dist/Errors.d.ts +61 -4
  17. package/dist/Errors.d.ts.map +1 -1
  18. package/dist/Errors.js +83 -6
  19. package/dist/Errors.js.map +1 -1
  20. package/dist/KeyComposer.d.ts +196 -5
  21. package/dist/KeyComposer.d.ts.map +1 -1
  22. package/dist/KeyComposer.js +490 -54
  23. package/dist/KeyComposer.js.map +1 -1
  24. package/dist/VectorIndex.d.ts.map +1 -1
  25. package/dist/VectorIndex.js +5 -4
  26. package/dist/VectorIndex.js.map +1 -1
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/internal/AggregateEdges.d.ts +3 -3
  32. package/dist/internal/AggregateSchemas.d.ts +306 -14
  33. package/dist/internal/AggregateSchemas.d.ts.map +1 -1
  34. package/dist/internal/AggregateSchemas.js +733 -54
  35. package/dist/internal/AggregateSchemas.js.map +1 -1
  36. package/dist/internal/AggregateTypes.d.ts +396 -36
  37. package/dist/internal/AggregateTypes.d.ts.map +1 -1
  38. package/dist/internal/CompositeCodec.d.ts +298 -8
  39. package/dist/internal/CompositeCodec.d.ts.map +1 -1
  40. package/dist/internal/CompositeCodec.js +940 -34
  41. package/dist/internal/CompositeCodec.js.map +1 -1
  42. package/dist/internal/EffectInstances.d.ts +87 -0
  43. package/dist/internal/EffectInstances.d.ts.map +1 -0
  44. package/dist/internal/EffectInstances.js +662 -0
  45. package/dist/internal/EffectInstances.js.map +1 -0
  46. package/dist/internal/EntityPacked.d.ts.map +1 -1
  47. package/dist/internal/EntityPacked.js +5 -4
  48. package/dist/internal/EntityPacked.js.map +1 -1
  49. package/dist/internal/EntitySchemas.d.ts +239 -30
  50. package/dist/internal/EntitySchemas.d.ts.map +1 -1
  51. package/dist/internal/EntitySchemas.js +1600 -197
  52. package/dist/internal/EntitySchemas.js.map +1 -1
  53. package/dist/internal/EntityTypes.d.ts +114 -25
  54. package/dist/internal/EntityTypes.d.ts.map +1 -1
  55. package/dist/internal/FailingAsBefore.d.ts +25 -0
  56. package/dist/internal/FailingAsBefore.d.ts.map +1 -0
  57. package/dist/internal/FailingAsBefore.js +42 -0
  58. package/dist/internal/FailingAsBefore.js.map +1 -0
  59. package/dist/internal/InstanceReads.d.ts +40 -0
  60. package/dist/internal/InstanceReads.d.ts.map +1 -0
  61. package/dist/internal/InstanceReads.js +183 -0
  62. package/dist/internal/InstanceReads.js.map +1 -0
  63. package/dist/internal/KeyReadings.d.ts +30 -0
  64. package/dist/internal/KeyReadings.d.ts.map +1 -0
  65. package/dist/internal/KeyReadings.js +99 -0
  66. package/dist/internal/KeyReadings.js.map +1 -0
  67. package/dist/internal/KeyText136.d.ts +4 -2
  68. package/dist/internal/KeyText136.d.ts.map +1 -1
  69. package/dist/internal/KeyText136.js +46 -13
  70. package/dist/internal/KeyText136.js.map +1 -1
  71. package/dist/internal/LostValues.d.ts +50 -0
  72. package/dist/internal/LostValues.d.ts.map +1 -0
  73. package/dist/internal/LostValues.js +465 -0
  74. package/dist/internal/LostValues.js.map +1 -0
  75. package/dist/internal/NumericKey.d.ts +21 -2
  76. package/dist/internal/NumericKey.d.ts.map +1 -1
  77. package/dist/internal/NumericKey.js +19 -1
  78. package/dist/internal/NumericKey.js.map +1 -1
  79. package/dist/internal/ObjectKeyText.d.ts +29 -0
  80. package/dist/internal/ObjectKeyText.d.ts.map +1 -0
  81. package/dist/internal/ObjectKeyText.js +50 -0
  82. package/dist/internal/ObjectKeyText.js.map +1 -0
  83. package/dist/internal/OwnNames.d.ts +205 -0
  84. package/dist/internal/OwnNames.d.ts.map +1 -0
  85. package/dist/internal/OwnNames.js +415 -0
  86. package/dist/internal/OwnNames.js.map +1 -0
  87. package/dist/internal/PackedCodec.d.ts +7 -1
  88. package/dist/internal/PackedCodec.d.ts.map +1 -1
  89. package/dist/internal/PackedCodec.js +83 -21
  90. package/dist/internal/PackedCodec.js.map +1 -1
  91. package/dist/internal/RestoredKeyText.d.ts +10 -0
  92. package/dist/internal/RestoredKeyText.d.ts.map +1 -0
  93. package/dist/internal/RestoredKeyText.js +50 -0
  94. package/dist/internal/RestoredKeyText.js.map +1 -0
  95. package/dist/internal/SchemaAccessors.d.ts +280 -1
  96. package/dist/internal/SchemaAccessors.d.ts.map +1 -1
  97. package/dist/internal/SchemaAccessors.js +1717 -1
  98. package/dist/internal/SchemaAccessors.js.map +1 -1
  99. package/dist/internal/SchemaIssue.d.ts +21 -0
  100. package/dist/internal/SchemaIssue.d.ts.map +1 -0
  101. package/dist/internal/SchemaIssue.js +34 -0
  102. package/dist/internal/SchemaIssue.js.map +1 -0
  103. package/dist/internal/SharedKeyAttribute.d.ts +60 -6
  104. package/dist/internal/SharedKeyAttribute.d.ts.map +1 -1
  105. package/dist/internal/SharedKeyAttribute.js +129 -13
  106. package/dist/internal/SharedKeyAttribute.js.map +1 -1
  107. package/dist/internal/SparseKey.d.ts +46 -0
  108. package/dist/internal/SparseKey.d.ts.map +1 -0
  109. package/dist/internal/SparseKey.js +69 -0
  110. package/dist/internal/SparseKey.js.map +1 -0
  111. package/dist/internal/StoredForm.d.ts +139 -0
  112. package/dist/internal/StoredForm.d.ts.map +1 -0
  113. package/dist/internal/StoredForm.js +503 -0
  114. package/dist/internal/StoredForm.js.map +1 -0
  115. package/dist/internal/ZOrderCurve.d.ts.map +1 -1
  116. package/dist/internal/ZOrderCurve.js +2 -1
  117. package/dist/internal/ZOrderCurve.js.map +1 -1
  118. package/dist/internal/ZoneKeyText.d.ts +55 -0
  119. package/dist/internal/ZoneKeyText.d.ts.map +1 -0
  120. package/dist/internal/ZoneKeyText.js +264 -0
  121. package/dist/internal/ZoneKeyText.js.map +1 -0
  122. package/package.json +4 -4
@@ -3,9 +3,15 @@
3
3
  *
4
4
  * Extracted from Entity.ts for decomposition. Not part of the public API.
5
5
  */
6
- import { DateTime, Effect, Redacted, Schema, SchemaAST, SchemaGetter, SchemaIssue } from "effect";
6
+ import { DateTime, Effect, Exit, Option, Redacted, Schema, SchemaAST, SchemaGetter, SchemaIssue, SchemaTransformation, } from "effect";
7
7
  import { getEncoding, isConfiguredModel, isHidden, } from "../DynamoModel.js";
8
- import { firstTypeParameterAst, getSchemaFields, isSchemaLike, numericTypeWithStringEncoding, transformWireKind as transformWireKindImpl, } from "./SchemaAccessors.js";
8
+ import { reviveMarshalledDateTime } from "./EffectInstances.js";
9
+ import { readingInstances } from "./InstanceReads.js";
10
+ import { hasOwnName, ownValue, PROTO_ENTRY, setOwn } from "./OwnNames.js";
11
+ import { BETA_DATE_MARKER, DATE_MARKER } from "./PackedCodec.js";
12
+ import { absentStored, firstTypeParameterAst, getSchemaFields, holdsAbsentValue, holdsPlainBigint, holdsUndefined, isDecodingDefault, isSchemaLike, isSetDeclaration, keyRenamesOf, lackDecision, membersNamedExactly, numericTypeWithStringEncoding, ReadsAbsentAs, rowCanLack, storedList, transformWireKind as transformWireKindImpl, } from "./SchemaAccessors.js";
13
+ import { CANT_SAY, issueOf } from "./SchemaIssue.js";
14
+ import { zonedIsoText } from "./StoredForm.js";
9
15
  import { parseZonedIso } from "./ZonedIso.js";
10
16
  /**
11
17
  * Resolve the effective DynamoEncoding for a model-declared field, applying
@@ -34,9 +40,9 @@ export const resolveFieldEncoding = (fieldSchema, override) => {
34
40
  export const buildFieldEncodings = (modelFields, configuredAttributes) => {
35
41
  const encodings = {};
36
42
  for (const [fieldName, fieldSchema] of Object.entries(modelFields)) {
37
- const encoding = resolveFieldEncoding(fieldSchema, configuredAttributes[fieldName]?.encoding);
43
+ const encoding = resolveFieldEncoding(fieldSchema, ownValue(configuredAttributes, fieldName)?.encoding);
38
44
  if (encoding)
39
- encodings[fieldName] = encoding;
45
+ setOwn(encodings, fieldName, encoding);
40
46
  }
41
47
  return encodings;
42
48
  };
@@ -135,7 +141,7 @@ export const resolveSystemFields = (timestamps, versioned, timeSeries, modelFiel
135
141
  // This preserves existing patterns where users declare `createdAt`
136
142
  // as a plain string composite.
137
143
  let createdAtCollision = false;
138
- if (createdAt && createdAt in modelFields) {
144
+ if (createdAt && hasOwnName(modelFields, createdAt)) {
139
145
  const modelEncoding = resolveFieldEncoding(modelFields[createdAt], configuredAttributes[createdAt]?.encoding);
140
146
  if (modelEncoding) {
141
147
  createdAtEncoding = modelEncoding;
@@ -148,7 +154,7 @@ export const resolveSystemFields = (timestamps, versioned, timeSeries, modelFiel
148
154
  }
149
155
  }
150
156
  let updatedAtCollision = false;
151
- if (updatedAt && updatedAt in modelFields) {
157
+ if (updatedAt && hasOwnName(modelFields, updatedAt)) {
152
158
  const modelEncoding = resolveFieldEncoding(modelFields[updatedAt], configuredAttributes[updatedAt]?.encoding);
153
159
  if (modelEncoding) {
154
160
  updatedAtEncoding = modelEncoding;
@@ -159,7 +165,7 @@ export const resolveSystemFields = (timestamps, versioned, timeSeries, modelFiel
159
165
  updatedAtEncoding = null;
160
166
  }
161
167
  }
162
- const versionCollision = !!(version && version in modelFields);
168
+ const versionCollision = !!(version && hasOwnName(modelFields, version));
163
169
  return {
164
170
  createdAt,
165
171
  createdAtEncoding,
@@ -299,26 +305,42 @@ export const isSelfDateSchema = (schema) => {
299
305
  * the inner AST with an optional context, so it needs no case of its own. The
300
306
  * tolerant `substituteSchemaDeep` walks the same containers (see
301
307
  * `walkedContainer`), except `Suspend`: a recursive schema keeps its own
302
- * codec, so the aggregate encodes it through its own `encode`.
308
+ * codec, so the aggregate encodes it through its own `encode`. A declaration's
309
+ * type parameters are walked too: `Schema.Option(Schema.DateFromString)` stores
310
+ * a string only if it's encoded, and `holdsTransformation` lets it be taken.
303
311
  *
304
312
  * `hasEncodingTransformation` asks the same question of the TOP-LEVEL node
305
313
  * only, and an `Arrays` / `Objects` node never carries an encoding itself — so a
306
314
  * `Schema.Array(DateTimeUtcFromString)` attribute was treated as identity and
307
315
  * its `DateTime`s were marshalled as maps.
316
+ *
317
+ * `throughClasses` looks through a `Schema.Class`'s own step, onto the struct of its fields, and
318
+ * walks those: a class whose fields hold none of the above reads back as it was given.
308
319
  */
309
- export const containsWireTransform = (schema) => astContainsWireTransform(schema.ast, new Set());
310
- const astContainsWireTransform = (ast, seen) => {
320
+ export const containsWireTransform = (schema, options) => astContainsWireTransform(schema.ast, new Set(), options?.throughClasses === true);
321
+ /** A `Schema.Class`'s struct, where its only encoding step is the class's own; undefined otherwise. */
322
+ const classStepStruct = (ast) => {
323
+ if (!SchemaAST.isDeclaration(ast) || ast.encoding?.length !== 1)
324
+ return undefined;
325
+ const to = ast.encoding[0].to;
326
+ return SchemaAST.isObjects(to) && ast.typeParameters[0] === to ? to : undefined;
327
+ };
328
+ const astContainsWireTransform = (ast, seen, throughClasses) => {
311
329
  if (seen.has(ast))
312
330
  return false;
313
331
  seen.add(ast);
314
- if (ast.encoding !== undefined)
315
- return true;
332
+ if (ast.encoding !== undefined) {
333
+ const struct = throughClasses ? classStepStruct(ast) : undefined;
334
+ return struct === undefined || astContainsWireTransform(struct, seen, throughClasses);
335
+ }
316
336
  if (SchemaAST.isDeclaration(ast)) {
317
337
  const resolved = SchemaAST.resolve(ast);
318
338
  const rep = resolved?.representation;
319
- return matchDateRepresentation(resolved) !== undefined || rep?.id === "effect/schema/Redacted";
339
+ return (matchDateRepresentation(resolved) !== undefined ||
340
+ rep?.id === "effect/schema/Redacted" ||
341
+ ast.typeParameters.some((parameter) => astContainsWireTransform(parameter, seen, throughClasses)));
320
342
  }
321
- const walk = (child) => astContainsWireTransform(child, seen);
343
+ const walk = (child) => astContainsWireTransform(child, seen, throughClasses);
322
344
  if (SchemaAST.isArrays(ast))
323
345
  return ast.elements.some(walk) || ast.rest.some(walk);
324
346
  if (SchemaAST.isObjects(ast)) {
@@ -358,55 +380,6 @@ const isPlainObject = (value) => {
358
380
  * `DateTime` API that relies on the prototype.
359
381
  */
360
382
  const isGenuineDateTime = (value) => DateTime.isDateTime(value) && !isPlainObject(value);
361
- const reviveTimeZone = (zone) => {
362
- if (!isPlainObject(zone))
363
- return undefined;
364
- try {
365
- if (zone._tag === "Named" && typeof zone.id === "string") {
366
- return DateTime.zoneMakeNamedUnsafe(zone.id);
367
- }
368
- if (zone._tag === "Offset" && typeof zone.offset === "number") {
369
- return DateTime.zoneMakeOffset(zone.offset);
370
- }
371
- }
372
- catch {
373
- return undefined;
374
- }
375
- return undefined;
376
- };
377
- /**
378
- * Rebuild a `DateTime` from a MARSHALLED instance (#133).
379
- *
380
- * Before #133 an aggregate stored some `DateTime`s by marshalling the instance
381
- * itself, which keeps its own enumerable properties:
382
- *
383
- * - `Utc`: `{ epochMilliseconds, <type-id>, _tag: "Utc" }`
384
- * - `Zoned`: the same plus `zone`, itself `{ id, _tag: "Named" }` or
385
- * `{ offset, _tag: "Offset" }` (a named zone's `Intl` formatter marshals to
386
- * an empty map and is not needed).
387
- *
388
- * The type-id key is `~effect/time/DateTime` on effect 4.0.0-rc and
389
- * `~effect/DateTime` on 4.0.0, so it is deliberately NOT inspected: the instant
390
- * and the tag are what identify the value, and they are all a `DateTime` holds.
391
- * A zoned value is rebuilt only when its zone is recoverable.
392
- *
393
- * Returns `undefined` for anything else — including a genuine `DateTime`, which
394
- * needs no rebuilding.
395
- */
396
- export const reviveMarshalledDateTime = (value) => {
397
- if (!isPlainObject(value))
398
- return undefined;
399
- const epochMs = value.epochMilliseconds;
400
- if (typeof epochMs !== "number" || !Number.isFinite(epochMs))
401
- return undefined;
402
- if (value._tag === "Utc")
403
- return DateTime.makeUnsafe(epochMs);
404
- if (value._tag === "Zoned") {
405
- const timeZone = reviveTimeZone(value.zone);
406
- return timeZone === undefined ? undefined : DateTime.makeZonedUnsafe(epochMs, { timeZone });
407
- }
408
- return undefined;
409
- };
410
383
  /**
411
384
  * Convert any input value (string / number / DateTime / Date) to the wire
412
385
  * primitive for a given encoding. Used by date substitutes' `encode` path.
@@ -445,7 +418,7 @@ const toWirePrimitive = (input, encoding) => {
445
418
  switch (encoding.storage) {
446
419
  case "string":
447
420
  if (encoding.domain === "DateTime.Zoned" && zoned)
448
- return DateTime.formatIsoZoned(zoned);
421
+ return zonedIsoText(zoned);
449
422
  return new Date(epochMs).toISOString();
450
423
  case "epochMs":
451
424
  return epochMs;
@@ -628,9 +601,12 @@ const tryGetRedactedInner = (schema) => {
628
601
  * branch logic in `decode`/`encode` then steers the value to the right
629
602
  * representation.
630
603
  */
631
- const buildRedactedSubstitute = (inner) => {
604
+ const buildRedactedSubstitute = (schema, inner) => {
605
+ const resolved = SchemaAST.resolve(schema.ast);
606
+ const declared = resolved?.representation?.payload?.label;
607
+ const label = typeof declared === "string" ? declared : undefined;
632
608
  return Schema.Any.pipe(Schema.decodeTo(Schema.Redacted(inner), {
633
- decode: SchemaGetter.transform((value) => Redacted.isRedacted(value) ? value : Redacted.make(value)),
609
+ decode: SchemaGetter.transform((value) => Redacted.isRedacted(value) ? value : Redacted.make(value, { label })),
634
610
  encode: SchemaGetter.transform((r) => Redacted.isRedacted(r) ? Redacted.value(r) : r),
635
611
  }));
636
612
  };
@@ -646,15 +622,30 @@ const schemaFieldsOf = (schema) => schema.fields;
646
622
  const isLeafEncodingTransform = (schema) => schemaFieldsOf(schema) === undefined &&
647
623
  !isArraySchema(schema) &&
648
624
  transformWireKindImpl(schema) !== undefined;
625
+ /**
626
+ * What an aggregate takes in either form: any transformation that isn't a class or a struct, whose
627
+ * fields are walked, whatever it's stored as, such as `Schema.Defect()`, a `Schema.toCodecJson` over
628
+ * a map, a map decoded from a record, `Schema.OptionFromNullOr` or a list held as JSON. A step
629
+ * encoded as optional has been unwrapped by now (`decodingDefaultField`), and it has to keep filling
630
+ * a missing key. A list whose elements are substituted is walked from its type side, whatever it's
631
+ * stored as, as an entity's is: what that stores decides what's in rows already written.
632
+ */
633
+ const isTolerantLeaf = (schema) => {
634
+ if (schemaFieldsOf(schema) !== undefined || schema.ast.encoding === undefined)
635
+ return false;
636
+ if (!SchemaAST.isArrays(schema.ast) || schema.ast.elements.length > 0)
637
+ return true;
638
+ const element = arrayElementOf(schema);
639
+ return element === undefined || !needsDeepSubstitution(element, { tolerantTransforms: true });
640
+ };
649
641
  /**
650
642
  * Build a TOLERANT substitute for an arbitrary leaf transform — the general
651
643
  * form of what `buildDateTransform` does for dates.
652
644
  *
653
- * Only reachable under `tolerantTransforms`, i.e. only from the aggregate's
654
- * `decodeSchema`. `Aggregate.update` re-decodes the mutated `state`, whose
655
- * fields may hold EITHER the domain value the caller set (a `bigint` for a
656
- * `Schema.BigIntFromString`) or the wire value that came back from storage (the
657
- * string). A strict transform accepts only the latter, so any update on such a
645
+ * Only reachable under `tolerantTransforms`, i.e. only from an aggregate's
646
+ * schemas. An aggregate's `create` and `update` decode what a caller holds, the
647
+ * domain value (a `bigint` for a `Schema.BigIntFromString`), where a strict
648
+ * transform accepts only the wire value (the string), so any update on such a
658
649
  * model failed before an item was ever built — regardless of which field the
659
650
  * mutation touched.
660
651
  *
@@ -662,16 +653,57 @@ const isLeafEncodingTransform = (schema) => schemaFieldsOf(schema) === undefined
662
653
  * validates the value against the transform's own TYPE side (domain form). A
663
654
  * value that is neither is still rejected, exactly as before — this widens the
664
655
  * accepted input, it does not skip validation.
656
+ *
657
+ * `domainFirst` asks the domain side first, for a value a caller holds (see `domainValues`). What
658
+ * both sides take is the domain value, and comes out as what reading its stored form gives, as it
659
+ * would from an entity: a transformation lowercasing on decode gives the same text either way.
660
+ *
661
+ * `plainForm` also takes what a mutation's plain state holds for that domain (see `plainStateForms`),
662
+ * asked before the stored side: a set held as a list is a domain value, even where what's stored is a list.
663
+ *
664
+ * `domainStored`: for a type side that takes anything (`takesAnything`), any value it takes is a
665
+ * domain value only where the transform stores it, whether or not the transform also reads it as
666
+ * stored. `Unknown` takes another union member's value, a `many` element its ref fetch changed, or a
667
+ * field's stored form; 1.39.0 read those through the member's own struct or the transform, or refused
668
+ * them, and `create` returns what it did.
665
669
  */
666
- const buildTolerantTransform = (schema) => {
670
+ const buildTolerantTransform = (schema, domainFirst = false, plainForm, domainStored = false) => {
667
671
  const typeSide = Schema.make(SchemaAST.toType(schema.ast));
668
672
  const codec = schema;
669
673
  const decodeWire = Schema.decodeUnknownOption(codec);
670
- const validateDomain = Schema.decodeUnknownOption(typeSide);
671
674
  const encodeDomain = Schema.encodeUnknownOption(codec);
675
+ const validateType = Schema.decodeUnknownOption(typeSide);
676
+ // A transform's `encode` is the caller's own code, written for its domain values only.
677
+ const stores = (value) => {
678
+ try {
679
+ return encodeDomain(value)._tag === "Some";
680
+ }
681
+ catch {
682
+ return false;
683
+ }
684
+ };
685
+ const validateDomain = (value) => {
686
+ const typed = validateType(value);
687
+ return domainStored && typed._tag === "Some" && !stores(typed.value) ? Option.none() : typed;
688
+ };
672
689
  const bigintDomain = SchemaAST.isBigInt(SchemaAST.toType(schema.ast));
690
+ const decodePlain = plainForm === undefined
691
+ ? undefined
692
+ : Schema.decodeUnknownOption(Schema.toCodecIso(plainForm));
673
693
  return Schema.Any.pipe(Schema.decodeTo(typeSide, {
674
694
  decode: SchemaGetter.transformEffect((value) => {
695
+ if (domainFirst) {
696
+ const given = validateDomain(reviveMarshalledDateTime(value) ?? value);
697
+ if (given._tag === "Some") {
698
+ const read = decodeWire(value)._tag === "Some"
699
+ ? Option.flatMap(encodeDomain(given.value), decodeWire)
700
+ : given;
701
+ return Effect.succeed(read._tag === "Some" ? read.value : given.value);
702
+ }
703
+ }
704
+ const plain = decodePlain?.(value);
705
+ if (plain?._tag === "Some")
706
+ return Effect.succeed(plain.value);
675
707
  const fromWire = decodeWire(value);
676
708
  if (fromWire._tag === "Some")
677
709
  return Effect.succeed(fromWire.value);
@@ -911,12 +943,14 @@ export const optionalField = (field) => {
911
943
  // `Schema.optional(X)`: the value type is `UndefinedOr(X)`; `.members` exposes
912
944
  // the real X alongside the `Undefined` member.
913
945
  const members = value?.members;
914
- const inner = members?.find((m) => m.ast._tag !== "Undefined");
946
+ const defined = members?.filter((m) => m.ast._tag !== "Undefined");
947
+ const inner = defined?.[0];
915
948
  if (inner === undefined)
916
949
  return undefined;
917
950
  return {
918
951
  inner,
919
952
  rewrap: (s) => Schema.optional(s),
953
+ ...(defined !== undefined && defined.length > 1 ? { union: value } : {}),
920
954
  };
921
955
  }
922
956
  // `Schema.optionalKey(X)`: the value type is X directly (`.schema`).
@@ -932,15 +966,27 @@ const descend = (opts) => opts?.tolerantTransforms ||
932
966
  opts?.resolveRef ||
933
967
  opts?.strictWireKind ||
934
968
  opts?.legacyReads ||
969
+ opts?.exactBigInts ||
970
+ opts?.decodeOnly ||
935
971
  opts?.path ||
936
- opts?.enforceChecks
972
+ opts?.enforceChecks ||
973
+ opts?.absentReads ||
974
+ opts?.plainStateForms ||
975
+ opts?.domainValues ||
976
+ opts?.undefinedPositionsOnly
937
977
  ? {
938
978
  ...(opts?.tolerantTransforms ? { tolerantTransforms: true } : {}),
939
979
  ...(opts?.resolveRef ? { resolveRef: opts.resolveRef } : {}),
940
980
  ...(opts?.strictWireKind ? { strictWireKind: true } : {}),
941
981
  ...(opts?.legacyReads ? { legacyReads: true } : {}),
982
+ ...(opts?.exactBigInts ? { exactBigInts: true } : {}),
983
+ ...(opts?.decodeOnly ? { decodeOnly: true } : {}),
942
984
  ...(opts?.path ? { path: opts.path } : {}),
943
985
  ...(opts?.enforceChecks ? { enforceChecks: true } : {}),
986
+ ...(opts?.absentReads ? { absentReads: opts.absentReads } : {}),
987
+ ...(opts?.plainStateForms ? { plainStateForms: true } : {}),
988
+ ...(opts?.domainValues ? { domainValues: true } : {}),
989
+ ...(opts?.undefinedPositionsOnly ? { undefinedPositionsOnly: true } : {}),
944
990
  }
945
991
  : undefined;
946
992
  /** Options for a struct / class field: the inherited ones, with the field on the path. */
@@ -1053,6 +1099,10 @@ const containerShape = (schema) => {
1053
1099
  }
1054
1100
  return undefined;
1055
1101
  };
1102
+ /** Whether a container holds nothing but dates, `Null` and `Undefined`: what an aggregate's date encoder takes. */
1103
+ const holdsOnlyDates = (container) => container.children.every((member) => SchemaAST.isNull(member.ast) ||
1104
+ SchemaAST.isUndefined(member.ast) ||
1105
+ inferDefaultEncoding(member) !== undefined);
1056
1106
  /** Options for a tolerant container's children: a Union's members decode strictly by kind. */
1057
1107
  const childOptions = (container, deeper, index, opts) => {
1058
1108
  if (!container.isUnion)
@@ -1110,15 +1160,32 @@ const decodingDefaultField = (field) => {
1110
1160
  const withUndefined = SchemaAST.isUnion(lastTo) && lastTo.types.some((t) => SchemaAST.isUndefined(t));
1111
1161
  return {
1112
1162
  inner,
1113
- rewrap: (substitute) => {
1163
+ transforms: !isDecodingDefault(ast, lastTo) || lastTo.encoding !== undefined,
1164
+ declared: field.to ?? inner,
1165
+ defaults: isDecodingDefault(SchemaAST.toEncoded(innerAst), lastTo),
1166
+ withUndefined,
1167
+ rewrap: (substitute, decode = transformation.decode) => {
1114
1168
  const encodedSide = Schema.toEncoded(substitute);
1115
1169
  const optionalEncoded = withUndefined
1116
1170
  ? Schema.optional(encodedSide)
1117
1171
  : Schema.optionalKey(encodedSide);
1118
- return optionalEncoded.pipe(Schema.decodeTo(substitute, transformation));
1172
+ return optionalEncoded.pipe(Schema.decodeTo(substitute, {
1173
+ decode,
1174
+ encode: transformation.encode,
1175
+ }));
1119
1176
  },
1120
1177
  };
1121
1178
  };
1179
+ /**
1180
+ * Whether this substitution is an entity's or an aggregate's write, which substitutes only the first
1181
+ * member of a union under `Schema.optionalKey`. Later members are written as declared, so what's
1182
+ * stored for them stays what every release has stored: a `Schema.DateTimeUtc` declared after a
1183
+ * `Schema.String` is Effect's internal form, and one declared before it is a string. Changing that
1184
+ * would change a stored format. A read takes each member's forms in the order they're declared
1185
+ * (`declaredOrder`), as a later date isn't stored as the text a string before it takes, and a number
1186
+ * under a first `Schema.BigInt` was written as that bigint.
1187
+ */
1188
+ const writesFirstMemberOnly = (opts) => !opts?.decodeOnly && !opts?.absentReads && !opts?.undefinedPositionsOnly;
1122
1189
  const throughOptional = (opts) => {
1123
1190
  const deeper = descend(opts);
1124
1191
  return opts?.unionDateOverride || opts?.collidingKinds || opts?.dateEncodingOverride
@@ -1198,10 +1265,204 @@ const needsLegacyRead = (schema, opts) => opts?.legacyReads === true &&
1198
1265
  schemaFieldsOf(schema) === undefined &&
1199
1266
  !isArraySchema(schema) &&
1200
1267
  (isDateTransform(schema) || numericTypeWithStringEncoding(schema));
1201
- /** Whether a plain `Schema.BigInt` leaf gets the read lift (aggregate decode, entity reads). */
1202
- const needsBigIntLift = (schema, opts) => (opts?.tolerantTransforms === true || opts?.legacyReads === true) &&
1203
- opts.strictWireKind !== true &&
1204
- isSelfBigInt(schema);
1268
+ /** Whether a plain `Schema.BigInt` gets the read lift here (aggregate decode, entity reads). */
1269
+ const liftsBigInts = (opts) => (opts?.tolerantTransforms === true || opts?.legacyReads === true) && opts.exactBigInts !== true;
1270
+ const needsBigIntLift = (schema, opts) => liftsBigInts(opts) && isSelfBigInt(schema);
1271
+ /** Whether what's stored for a schema the substitution can't walk holds a plain `Schema.BigInt`. */
1272
+ const holdsUnwalkedBigInt = (schema) => holdsPlainBigint(SchemaAST.toEncoded(schema.ast));
1273
+ /**
1274
+ * A list with a step on it that an entity writes through as declared, which is one with no date or
1275
+ * redacted value on its type side. A read walking that type side would skip the step, so it finds what
1276
+ * the step makes where the stored form is. This reads it as declared, with its bigints lifted, unless
1277
+ * nothing's in the way of the walk: a list stored as one, with no plain bigint on either side.
1278
+ */
1279
+ const readsListAsDeclared = (schema, opts) => {
1280
+ if (opts?.legacyReads !== true)
1281
+ return false;
1282
+ const { ast } = schema;
1283
+ if (!SchemaAST.isArrays(ast) || ast.encoding === undefined)
1284
+ return false;
1285
+ if (needsDeepSubstitution(schema, undefined))
1286
+ return false;
1287
+ return (storedList(ast.encoding[ast.encoding.length - 1].to) === undefined ||
1288
+ holdsUnwalkedBigInt(schema) ||
1289
+ [...ast.elements, ...ast.rest].some((element) => holdsPlainBigint(SchemaAST.toEncoded(element))));
1290
+ };
1291
+ /** Whether what's stored for a schema the substitution can't walk can leave a value out. */
1292
+ const holdsUnwalkedAbsent = (schema) => holdsAbsentValue(SchemaAST.toEncoded(schema.ast));
1293
+ /** Whether a plain `Schema.BigInt` is anywhere the substitution walks. */
1294
+ const holdsBigInt = (schema) => {
1295
+ const opt = optionalField(schema);
1296
+ const defaulted = decodingDefaultField(schema);
1297
+ // What's beneath a step that isn't a default isn't what's stored, and it isn't walked.
1298
+ if (defaulted !== undefined && !defaulted.defaults)
1299
+ return holdsUnwalkedBigInt(schema);
1300
+ const inner = opt?.union ?? opt?.inner ?? defaulted?.declared;
1301
+ if (inner !== undefined)
1302
+ return holdsBigInt(inner);
1303
+ if (isSelfBigInt(schema))
1304
+ return true;
1305
+ const container = walkedContainer(schema);
1306
+ if (container !== undefined)
1307
+ return container.children.some((child) => holdsBigInt(child));
1308
+ if (isArraySchema(schema)) {
1309
+ const element = arrayElementOf(schema);
1310
+ return element !== undefined && holdsBigInt(element);
1311
+ }
1312
+ const fields = schemaFieldsOf(schema);
1313
+ return fields === undefined
1314
+ ? holdsUnwalkedBigInt(schema)
1315
+ : Object.values(fields).some((field) => holdsBigInt(field));
1316
+ };
1317
+ /**
1318
+ * What the substitution works on beneath a decoding default (see `decodeOnly`). A read doesn't
1319
+ * enforce a check on what it rebuilds (see `enforceChecks`), and a write schema keeps the one added
1320
+ * after the default.
1321
+ */
1322
+ const beneathDefault = (schema, defaulted, opts) => (opts?.legacyReads || opts?.decodeOnly) &&
1323
+ !(opts.enforceChecks && defaulted.declared.ast.checks !== schema.ast.checks)
1324
+ ? defaulted.declared
1325
+ : defaulted.inner;
1326
+ /**
1327
+ * What an absent field reads as, for what asks for the domain value first (see `domainValues`), and
1328
+ * anything else as it was given. A decoding default is in the stored form and a step makes something
1329
+ * else of nothing at all, so absent is read through the field as declared, and what's beneath gets
1330
+ * the domain value that gives.
1331
+ */
1332
+ const absentAsDeclared = (schema, withUndefined) => {
1333
+ const read = Schema.decodeUnknownEffect(Schema.Struct({ field: schema }));
1334
+ return SchemaGetter.transformOptionalEffect((input) => Option.isSome(input) && !(withUndefined && input.value === undefined)
1335
+ ? Effect.succeed(input)
1336
+ : read({}).pipe(Effect.map(({ field }) => Option.some(field)), Effect.mapError((error) => error.issue)));
1337
+ };
1338
+ /** `undefined`, or a set holding nothing once `undefined` is removed: no attribute is stored. */
1339
+ const storesNothing = (value) => value === undefined ||
1340
+ (value instanceof Set && [...value].every((element) => element === undefined));
1341
+ /**
1342
+ * The annotation marking a field {@link protoAbsent} made: an annotation, not identity, since the
1343
+ * modules reading it may be loaded twice (the package's source beside its build).
1344
+ */
1345
+ const PROTO_ABSENT = Symbol.for("@effect-dynamodb/schema/ProtoAbsent");
1346
+ /** Whether `field` is one {@link protoAbsent} made. */
1347
+ export const isProtoAbsent = (field) => {
1348
+ const ast = field?.ast;
1349
+ return ast?.annotations?.[PROTO_ABSENT] === true;
1350
+ };
1351
+ /**
1352
+ * A field named `__proto__`, stored under that name, of a struct the library builds over the
1353
+ * model's (#239). 1.40.0 built each such struct by assignment, `fields[name] = schema`, and
1354
+ * assigning `__proto__` set the map's prototype instead: the field wasn't in the struct. A payload
1355
+ * leaving it out was taken, and one giving it lost the value, which the parser dropped. Here a
1356
+ * payload leaving it out, or giving a value that stores nothing (`undefined`, a `None` encoded as
1357
+ * `undefined`, a set holding nothing), is read as 1.40.0 read it: the field isn't in what the struct
1358
+ * makes. A value that stores something is refused (`EDD-9165`), since no write can store it and no
1359
+ * read can return it. What a value stores is what the field, as declared, makes of it on the way to
1360
+ * storage: encoded, or as it is where it's already in its stored form.
1361
+ */
1362
+ const protoAbsent = (field) => {
1363
+ const holder = Schema.Struct({ v: field });
1364
+ const decode = Schema.decodeUnknownExit(holder);
1365
+ const encode = Schema.encodeUnknownExit(holder);
1366
+ /** The value as stored, `undefined` for none; the value as given where the field takes neither. */
1367
+ const stored = (value, encoding) => {
1368
+ const asIs = () => Exit.isSuccess(decode({ v: value })) ? Exit.succeed({ v: value }) : undefined;
1369
+ const toStored = () => {
1370
+ const encoded = encode({ v: value });
1371
+ return Exit.isSuccess(encoded) ? encoded : undefined;
1372
+ };
1373
+ for (const attempt of encoding ? [toStored, asIs] : [asIs, toStored]) {
1374
+ const held = attempt();
1375
+ if (held !== undefined && Exit.isSuccess(held)) {
1376
+ return Object.hasOwn(held.value, "v") ? held.value.v : undefined;
1377
+ }
1378
+ }
1379
+ return value;
1380
+ };
1381
+ const judge = (encoding) => SchemaGetter.transformOptionalEffect((given) => Option.isNone(given) ||
1382
+ storesNothing(given.value) ||
1383
+ storesNothing(stored(given.value, encoding))
1384
+ ? Effect.succeed(Option.none())
1385
+ : Effect.fail(new SchemaIssue.InvalidValue({ message: `${PROTO_ENTRY} [EDD-9165]` }, Option.some(given.value))));
1386
+ return Schema.optionalKey(Schema.Unknown.pipe(Schema.decodeTo(Schema.Unknown.annotate({ [PROTO_ABSENT]: true }), new SchemaTransformation.Transformation(judge(false), judge(true)))));
1387
+ };
1388
+ /**
1389
+ * `field` under `name`: where that's `__proto__`, stored so, the field {@link protoAbsent} makes of
1390
+ * the one the model `declared`, whose encoding is the stored form.
1391
+ */
1392
+ const fieldNamed = (name, field, declared, storedAsProto = true) => name === "__proto__" && storedAsProto && !isProtoAbsent(field) ? protoAbsent(declared) : field;
1393
+ /**
1394
+ * The field, reading an absent attribute as the value it stands for (`absentStored`), which is what
1395
+ * its `declared` schema says, if the field is that schema read some other way.
1396
+ */
1397
+ const readingAbsent = (field, declared = field) => {
1398
+ const reading = absentStored(declared);
1399
+ if (reading === undefined)
1400
+ return field;
1401
+ // A stored value is read as `field` alone (`ReadsAbsentAs`): the default runs where none is.
1402
+ return field
1403
+ .pipe(Schema.withDecodingDefaultKey(Effect.succeed(reading.stored)))
1404
+ .annotate({ [ReadsAbsentAs]: field.ast });
1405
+ };
1406
+ /** Whether a struct field anywhere in the schema reads an absent attribute as a value. */
1407
+ const holdsAbsentRead = (schema) => {
1408
+ const opt = optionalField(schema);
1409
+ if (opt !== undefined)
1410
+ return holdsAbsentRead(opt.union ?? opt.inner);
1411
+ const defaulted = decodingDefaultField(schema);
1412
+ if (defaulted !== undefined)
1413
+ return holdsAbsentRead(defaulted.inner);
1414
+ const container = walkedContainer(schema);
1415
+ if (container !== undefined)
1416
+ return container.children.some((child) => holdsAbsentRead(child));
1417
+ if (isArraySchema(schema)) {
1418
+ const element = arrayElementOf(schema);
1419
+ return element !== undefined && holdsAbsentRead(element);
1420
+ }
1421
+ const fields = schemaFieldsOf(schema);
1422
+ return (fields !== undefined &&
1423
+ Object.values(fields).some((field) => absentStored(field) !== undefined || holdsAbsentRead(field)));
1424
+ };
1425
+ /** Whether a tuple has a fixed position that can hold `undefined`. */
1426
+ const hasUndefinedPosition = (schema) => SchemaAST.isArrays(schema.ast) && schema.ast.elements.some((element) => holdsUndefined(element));
1427
+ /** Whether a tuple with a position that can hold `undefined` is anywhere in the schema. */
1428
+ const holdsUndefinedPosition = (schema) => {
1429
+ const opt = optionalField(schema);
1430
+ const inner = opt?.union ?? opt?.inner ?? decodingDefaultField(schema)?.inner;
1431
+ if (inner !== undefined)
1432
+ return holdsUndefinedPosition(inner);
1433
+ if (hasUndefinedPosition(schema))
1434
+ return true;
1435
+ const container = walkedContainer(schema);
1436
+ if (container !== undefined) {
1437
+ return container.children.some((child) => holdsUndefinedPosition(child));
1438
+ }
1439
+ if (isArraySchema(schema)) {
1440
+ const element = arrayElementOf(schema);
1441
+ return element !== undefined && holdsUndefinedPosition(element);
1442
+ }
1443
+ const fields = schemaFieldsOf(schema);
1444
+ return (fields !== undefined && Object.values(fields).some((field) => holdsUndefinedPosition(field)));
1445
+ };
1446
+ /**
1447
+ * Marshalling drops `undefined` from a list, closing it up. In a tuple that moves
1448
+ * the values after it to other positions, or leaves a required position empty, so
1449
+ * the row reads back wrong or not at all. Only a last optional position can go, and
1450
+ * a position in a tuple's rest, which is a list.
1451
+ */
1452
+ const refusingUndefinedPositions = (tuple) => {
1453
+ const optional = tuple.ast.elements.map((element) => SchemaAST.isOptional(element));
1454
+ return tuple.check(Schema.makeFilter((values) => {
1455
+ const position = values.findIndex((value, index) => value === undefined &&
1456
+ index < optional.length &&
1457
+ (optional[index] !== true ||
1458
+ values.slice(index + 1).some((later) => later !== undefined)));
1459
+ return (position === -1 ||
1460
+ `Position ${position} holds undefined, and a list can't keep an empty position: ` +
1461
+ "the values after it would move, or the row couldn't be read");
1462
+ }));
1463
+ };
1464
+ /** Whether a substitution of this schema refuses what its tuple positions can't keep. */
1465
+ const refusesUndefinedPositions = (schema, opts) => opts?.enforceChecks === true && opts.absentReads !== "only" && hasUndefinedPosition(schema);
1205
1466
  /**
1206
1467
  * Recursively determine whether a schema contains — at any depth reachable
1207
1468
  * through nested `Schema.Struct` / `Schema.Class` / `Schema.Array` — a leaf that
@@ -1216,6 +1477,18 @@ const needsBigIntLift = (schema, opts) => (opts?.tolerantTransforms === true ||
1216
1477
  const needsDeepSubstitution = (schema, opts) => {
1217
1478
  if (schema == null || schema.ast == null)
1218
1479
  return false;
1480
+ // A ref held as less than its class (`refHeldTarget`) is another schema than the field it
1481
+ // re-points, whatever its leaves.
1482
+ if (heldStructs.has(schema))
1483
+ return true;
1484
+ if (opts?.undefinedPositionsOnly)
1485
+ return holdsUndefinedPosition(schema);
1486
+ if (opts?.absentReads === "only")
1487
+ return holdsAbsentRead(schema);
1488
+ if (opts?.absentReads && holdsUnwalkedAbsent(schema))
1489
+ return true;
1490
+ if (opts?.enforceChecks && hasUndefinedPosition(schema))
1491
+ return true;
1219
1492
  // `tolerantTransforms` AND `resolveRef` propagate through the recursion;
1220
1493
  // `skipTopLevel` names top-level fields only, so it is dropped below.
1221
1494
  //
@@ -1223,7 +1496,7 @@ const needsDeepSubstitution = (schema, opts) => {
1223
1496
  // model is annotated, and `Schema.annotate` drops a `Schema.Class`'s `.fields`,
1224
1497
  // so the walker cannot see through it and the target's own transformed fields
1225
1498
  // keep their strict schemas. Only callers that pass `resolveRef` are affected
1226
- // — the entity derivation passes no options at all (#116).
1499
+ // — the entity derivation passes none (#116).
1227
1500
  const deeper = descend(opts);
1228
1501
  // Optional wrapper FIRST — unwrap to the REAL inner before the leaf / array /
1229
1502
  // struct checks. `optionalKey(X)` is a bare AST (Declaration/Arrays) with an
@@ -1232,11 +1505,19 @@ const needsDeepSubstitution = (schema, opts) => {
1232
1505
  // required date and drop the optionality; and an `optionalKey(Array)` wrapper
1233
1506
  // has the `Arrays` AST but no runtime `.value`.
1234
1507
  const opt = optionalField(schema);
1235
- if (opt !== undefined)
1236
- return needsDeepSubstitution(opt.inner, throughOptional(opts));
1508
+ if (opt !== undefined) {
1509
+ const read = writesFirstMemberOnly(opts) ? undefined : opt.union;
1510
+ return needsDeepSubstitution(read ?? opt.inner, throughOptional(opts));
1511
+ }
1237
1512
  const defaulted = decodingDefaultField(schema);
1238
- if (defaulted !== undefined)
1239
- return needsDeepSubstitution(defaulted.inner, opts);
1513
+ if (defaulted !== undefined) {
1514
+ return defaulted.defaults
1515
+ ? (defaulted.transforms && liftsBigInts(opts) && holdsUnwalkedBigInt(schema)) ||
1516
+ needsDeepSubstitution(beneathDefault(schema, defaulted, opts), opts)
1517
+ : opts?.domainValues === true || (liftsBigInts(opts) && holdsUnwalkedBigInt(schema));
1518
+ }
1519
+ if (readsListAsDeclared(schema, opts))
1520
+ return readingUnwalked(schema, opts) !== schema;
1240
1521
  if (isSelfDateSchema(schema))
1241
1522
  return true;
1242
1523
  if (opts?.tolerantTransforms && isDateTransform(schema))
@@ -1245,10 +1526,14 @@ const needsDeepSubstitution = (schema, opts) => {
1245
1526
  return true;
1246
1527
  // Any other leaf transform, tolerant mode only — same reason as the date
1247
1528
  // case: after a mutation the field may hold either form (#116).
1248
- if (opts?.tolerantTransforms && isLeafEncodingTransform(schema))
1529
+ if (opts?.tolerantTransforms && isTolerantLeaf(schema))
1249
1530
  return true;
1250
1531
  if (needsLegacyRead(schema, opts) || needsBigIntLift(schema, opts))
1251
1532
  return true;
1533
+ if (opts?.plainStateForms && holdsPlainForm(schema.ast))
1534
+ return true;
1535
+ if (opts?.tolerantTransforms && holdsTransformation(schema.ast))
1536
+ return true;
1252
1537
  const container = walkedContainer(schema);
1253
1538
  if (container !== undefined) {
1254
1539
  return container.children.some((child, index) => needsDeepSubstitution(child, childOptions(container, deeper, index, opts)));
@@ -1268,6 +1553,68 @@ const needsDeepSubstitution = (schema, opts) => {
1268
1553
  return needsDeepSubstitution(refTarget ?? field, deeper);
1269
1554
  });
1270
1555
  }
1556
+ return liftsBigInts(opts) && holdsUnwalkedBigInt(schema);
1557
+ };
1558
+ /**
1559
+ * Whether a mutation can hold this as something else: a declaration of Effect's or a custom one,
1560
+ * as opposed to a `Schema.Class`, whose AST is a declaration encoded as its struct and whose
1561
+ * fields are walked, or whatever a `Schema.suspend` holds, which isn't. See `plainStateForms`.
1562
+ */
1563
+ const holdsPlainForm = (ast) => (ast._tag === "Declaration" && ast.encoding === undefined) || SchemaAST.isSuspend(ast);
1564
+ /**
1565
+ * A declaration with a transformation inside, such as `Schema.Option(Schema.DateFromString)`, or a
1566
+ * `Schema.suspend` with one. The tolerant substitution doesn't reach under either, so an aggregate's
1567
+ * `create` would be handed the domain value and refuse it.
1568
+ */
1569
+ const holdsTransformation = (ast) => SchemaAST.isSuspend(ast)
1570
+ ? astContainsWireTransform(ast, new Set(), false)
1571
+ : holdsPlainForm(ast) &&
1572
+ ast.typeParameters.some((parameter) => SchemaAST.toType(parameter) !== parameter);
1573
+ /** A declaration or a suspended schema, or its domain value. See `holdsTransformation`. */
1574
+ const acceptingDomainForm = (declaration) => Schema.Union([declaration, Schema.toType(declaration)]);
1575
+ /**
1576
+ * A declaration, or either of what a mutation can hand back for it: the domain value it was
1577
+ * given, or the form its plain state holds it as. See `plainStateForms`.
1578
+ */
1579
+ const acceptingPlainForm = (declaration) => buildTolerantTransform(declaration, true, declaration);
1580
+ /**
1581
+ * A type side whose own check takes what isn't the transform's: `Unknown`, `Any`, or a declaration
1582
+ * with nothing inside it (`Schema.declare`, `Schema.instanceOf`).
1583
+ */
1584
+ const takesAnything = (type) => SchemaAST.isUnknown(type) ||
1585
+ SchemaAST.isAny(type) ||
1586
+ (SchemaAST.isDeclaration(type) && type.typeParameters.length === 0);
1587
+ /** A tolerant substitute for a field a read makes `read` of. See `buildTolerantTransform`. */
1588
+ const tolerantLeaf = (schema, opts, read) => {
1589
+ const type = SchemaAST.toType(schema.ast);
1590
+ return buildTolerantTransform(read, opts?.domainValues,
1591
+ // A plain state holds a declaration in another form. With nothing beneath the domain side that
1592
+ // is one, the plain form is the domain value: asked first, a value read wire first (an
1593
+ // aggregate's `decompose` input) would be taken as the domain value instead.
1594
+ opts?.plainStateForms && holdsDeclaration(type, new Set())
1595
+ ? Schema.make(type)
1596
+ : undefined,
1597
+ // 1.39.0's own leaves (stored as a string or a number) take a domain value as they did.
1598
+ !isLeafEncodingTransform(schema) && takesAnything(type));
1599
+ };
1600
+ /** Whether a declaration (a set, an `Option`, a class, a date) is anywhere in `ast`. */
1601
+ const holdsDeclaration = (ast, seen) => {
1602
+ if (seen.has(ast))
1603
+ return false;
1604
+ seen.add(ast);
1605
+ if (SchemaAST.isDeclaration(ast))
1606
+ return true;
1607
+ const walk = (child) => holdsDeclaration(child, seen);
1608
+ if (SchemaAST.isArrays(ast))
1609
+ return ast.elements.some(walk) || ast.rest.some(walk);
1610
+ if (SchemaAST.isObjects(ast)) {
1611
+ return (ast.propertySignatures.some((ps) => walk(ps.type)) ||
1612
+ ast.indexSignatures.some((is) => walk(is.type)));
1613
+ }
1614
+ if (SchemaAST.isUnion(ast))
1615
+ return ast.types.some(walk);
1616
+ if (SchemaAST.isSuspend(ast))
1617
+ return walk(ast.thunk());
1271
1618
  return false;
1272
1619
  };
1273
1620
  /**
@@ -1296,7 +1643,7 @@ export const substituteSchemaDeep = (schema, opts) => {
1296
1643
  // model is annotated, and `Schema.annotate` drops a `Schema.Class`'s `.fields`,
1297
1644
  // so the walker cannot see through it and the target's own transformed fields
1298
1645
  // keep their strict schemas. Only callers that pass `resolveRef` are affected
1299
- // — the entity derivation passes no options at all (#116).
1646
+ // — the entity derivation passes none (#116).
1300
1647
  const deeper = descend(opts);
1301
1648
  // Optional wrapper FIRST — unwrap to the REAL inner, substitute it, then
1302
1649
  // re-apply the same optionality. Handled BEFORE the leaf / array / struct
@@ -1305,14 +1652,53 @@ export const substituteSchemaDeep = (schema, opts) => {
1305
1652
  // the optional key), and an optional array's `.value` lives only on the inner.
1306
1653
  const opt = optionalField(schema);
1307
1654
  if (opt !== undefined) {
1308
- return opt.rewrap(substituteSchemaDeep(opt.inner, throughOptional(opts)));
1655
+ const first = substituteSchemaDeep(opt.inner, throughOptional(opts));
1656
+ if (opt.union === undefined)
1657
+ return opt.rewrap(first);
1658
+ if (!writesFirstMemberOnly(opts)) {
1659
+ const read = substituteSchemaDeep(opt.union, {
1660
+ ...throughOptional(opts),
1661
+ declaredOrder: true,
1662
+ });
1663
+ // A member of a union reads only its own forms, so it doesn't claim a later member's rows.
1664
+ // The first was read as the whole field until now, and a row it took then still reads.
1665
+ return opt.rewrap(first === opt.inner
1666
+ ? read
1667
+ : Schema.Union([
1668
+ read,
1669
+ first,
1670
+ ]));
1671
+ }
1672
+ // Over the members themselves, so `optionalField` still tells them apart in what's built here.
1673
+ return Schema.optionalKey(opt.union.mapMembers((members) => [
1674
+ ...members.map((member) => (member === opt.inner ? first : member)),
1675
+ Schema.Undefined,
1676
+ ], { unsafePreserveChecks: true }));
1309
1677
  }
1310
1678
  // A decoding default (or any optional-encoded step) on top: substitute the
1311
1679
  // field beneath it and keep the step, so a missing key still defaults (#133).
1680
+ // What the walk below can't enter: a declaration, a `Schema.suspend` or a transformation. What a
1681
+ // read makes of a plain bigint or an absent value in one, it makes of it where it sits.
1682
+ const unwalked = () => readingUnwalked(schema, opts);
1312
1683
  const defaulted = decodingDefaultField(schema);
1313
1684
  if (defaulted !== undefined) {
1314
- return defaulted.rewrap(substituteSchemaDeep(defaulted.inner, opts));
1685
+ const domainValues = opts?.domainValues === true;
1686
+ // A step that isn't a default turns what's stored into something else. What's beneath it isn't
1687
+ // what's stored, so it stays as declared, and a caller, who holds that something else, goes round it.
1688
+ if (!defaulted.defaults) {
1689
+ return domainValues
1690
+ ? defaulted.rewrap(tolerantLeaf(schema, opts, schema), absentAsDeclared(schema, defaulted.withUndefined))
1691
+ : unwalked();
1692
+ }
1693
+ if (defaulted.transforms && !domainValues && unwalked() !== schema)
1694
+ return unwalked();
1695
+ const beneath = substituteSchemaDeep(beneathDefault(schema, defaulted, opts), opts);
1696
+ return defaulted.rewrap(refusesUndefinedPositions(defaulted.inner, opts)
1697
+ ? refusingUndefinedPositions(beneath)
1698
+ : beneath, domainValues ? absentAsDeclared(schema, defaulted.withUndefined) : undefined);
1315
1699
  }
1700
+ if (readsListAsDeclared(schema, opts))
1701
+ return unwalked();
1316
1702
  // Leaf: self-date schema → tolerant bidirectional date transform.
1317
1703
  if (isSelfDateSchema(schema))
1318
1704
  return selfDateSubstitute(schema, opts);
@@ -1324,7 +1710,7 @@ export const substituteSchemaDeep = (schema, opts) => {
1324
1710
  // enough to claim a value that belongs to a later member (#133).
1325
1711
  if (opts?.tolerantTransforms && isDateTransform(schema)) {
1326
1712
  if (opts.strictWireKind)
1327
- return buildTolerantTransform(schema);
1713
+ return buildTolerantTransform(unwalked(), opts.domainValues);
1328
1714
  const encoding = getEncoding(schema) ?? inferDefaultEncoding(schema);
1329
1715
  if (encoding)
1330
1716
  return buildDateTransform(encoding);
@@ -1332,21 +1718,28 @@ export const substituteSchemaDeep = (schema, opts) => {
1332
1718
  // Leaf: RedactedFromValue → tolerant Redacted transform.
1333
1719
  const redactedInner = tryGetRedactedInner(schema);
1334
1720
  if (redactedInner !== undefined)
1335
- return buildRedactedSubstitute(redactedInner);
1721
+ return buildRedactedSubstitute(schema, redactedInner);
1336
1722
  // Leaf: any OTHER encoding transform (only under `tolerantTransforms`) →
1337
1723
  // a substitute whose decode accepts the wire form and the domain form. Placed
1338
1724
  // after the date and Redacted branches so those keep their dedicated
1339
1725
  // substitutes, and before the array / struct recursion so containers are
1340
1726
  // still walked rather than swallowed (#116).
1341
- if (opts?.tolerantTransforms && isLeafEncodingTransform(schema)) {
1342
- return buildTolerantTransform(schema);
1727
+ if (opts?.tolerantTransforms && isTolerantLeaf(schema)) {
1728
+ return tolerantLeaf(schema, opts, unwalked());
1343
1729
  }
1344
1730
  // Leaf: read leniency for legacy domain-form values (entity read schemas) and
1345
1731
  // the plain-bigint lift (#133).
1346
1732
  if (needsLegacyRead(schema, opts))
1347
- return buildLegacyReadTransform(schema);
1733
+ return buildLegacyReadTransform(unwalked());
1348
1734
  if (needsBigIntLift(schema, opts))
1349
1735
  return buildBigIntLift(schema);
1736
+ if (opts?.plainStateForms && holdsPlainForm(schema.ast))
1737
+ return acceptingPlainForm(unwalked());
1738
+ if (holdsTransformation(schema.ast)) {
1739
+ return opts?.domainValues
1740
+ ? buildTolerantTransform(unwalked(), true)
1741
+ : acceptingDomainForm(unwalked());
1742
+ }
1350
1743
  // Union / Record / Tuple / *WithRest: substitute every child and rebuild the
1351
1744
  // same container kind, metadata included (#133). Without `tolerantTransforms`
1352
1745
  // (entity derivation) only self-date / Redacted leaves inside are
@@ -1356,14 +1749,71 @@ export const substituteSchemaDeep = (schema, opts) => {
1356
1749
  if (container !== undefined) {
1357
1750
  const children = container.children.map((child, index) => {
1358
1751
  const childOpts = childOptions(container, deeper, index, opts);
1752
+ const member = substituteSchemaDeep(child, childOpts);
1753
+ // An aggregate stores a first date transform in its date encoding, not its own wire form, and
1754
+ // a date in a union of nothing else but null in the form its domain infers, whatever it declares.
1755
+ const stored = !opts?.tolerantTransforms
1756
+ ? undefined
1757
+ : holdsOnlyDates(container)
1758
+ ? inferDefaultEncoding(child)
1759
+ : index === 0 && opts.declaredOrder
1760
+ ? (getEncoding(child) ?? inferDefaultEncoding(child))
1761
+ : undefined;
1359
1762
  return {
1360
- substituted: substituteSchemaDeep(child, childOpts),
1361
- first: container.isUnion && isCanonicalDateMember(child, childOpts),
1763
+ child,
1764
+ childOpts,
1765
+ substituted: stored === undefined
1766
+ ? member
1767
+ : Schema.Union([
1768
+ member,
1769
+ buildDateTransform(stored, {
1770
+ strictWireKind: true,
1771
+ canonicalOnly: true,
1772
+ }),
1773
+ ]),
1774
+ first: container.isUnion &&
1775
+ opts?.absentReads !== "only" &&
1776
+ !opts?.declaredOrder &&
1777
+ isCanonicalDateMember(child, childOpts),
1362
1778
  };
1363
1779
  });
1780
+ const ordered = [...children.filter((c) => c.first), ...children.filter((c) => !c.first)];
1781
+ const lifting = (c) => container.isUnion &&
1782
+ liftsBigInts(c.childOpts) &&
1783
+ holdsBigInt(c.child) &&
1784
+ !(opts?.declaredOrder && c === ordered[0]);
1785
+ const lenient = ordered.filter((c) => (opts?.absentReads && holdsAbsentRead(c.child)) ||
1786
+ (opts?.absentReads === true && holdsUnwalkedAbsent(c.child)) ||
1787
+ lifting(c) ||
1788
+ (opts?.plainStateForms && holdsPlainForm(c.child.ast)));
1789
+ if (!container.isUnion || lenient.length === 0) {
1790
+ const rebuilt = container.rebuild(ordered.map((c) => c.substituted));
1791
+ return refusesUndefinedPositions(schema, opts) ? refusingUndefinedPositions(rebuilt) : rebuilt;
1792
+ }
1793
+ // A member reading an absent attribute as a value, or lifting a number to a
1794
+ // bigint, accepts more than it declares, enough to claim a row of a later
1795
+ // member. So every member gets its try as declared first, and only a row none
1796
+ // of them takes reads absent or is lifted. A `oneOf` union refuses a value two
1797
+ // members accept: it stays as declared, with only the lift tried outside it,
1798
+ // since a row as a bigint is what it was written as.
1799
+ const declared = (c) => opts?.absentReads === "only"
1800
+ ? c.child
1801
+ : substituteSchemaDeep(c.child, {
1802
+ ...c.childOpts,
1803
+ absentReads: undefined,
1804
+ plainStateForms: undefined,
1805
+ exactBigInts: true,
1806
+ });
1807
+ if (schema.ast.options?.mode === "oneOf") {
1808
+ const exact = container.rebuild(ordered.map((c) => declared(c)));
1809
+ const lifted = ordered.filter((c) => lifting(c)).map((c) => c.substituted);
1810
+ return lifted.length === 0
1811
+ ? exact
1812
+ : withMetadataOf(schema, Schema.Union([exact, ...lifted]));
1813
+ }
1364
1814
  return container.rebuild([
1365
- ...children.filter((c) => c.first).map((c) => c.substituted),
1366
- ...children.filter((c) => !c.first).map((c) => c.substituted),
1815
+ ...ordered.map((c) => (lenient.includes(c) ? declared(c) : c.substituted)),
1816
+ ...lenient.map((c) => c.substituted),
1367
1817
  ]);
1368
1818
  }
1369
1819
  // Array: substitute the element schema.
@@ -1381,20 +1831,26 @@ export const substituteSchemaDeep = (schema, opts) => {
1381
1831
  // by the recursion (and class instance identity is preserved).
1382
1832
  const fields = schemaFieldsOf(schema);
1383
1833
  if (fields) {
1834
+ // A field named `__proto__` is one 1.40.0's rebuilt struct didn't hold (`protoAbsent`).
1384
1835
  const subFields = {};
1385
1836
  for (const [name, field] of Object.entries(fields)) {
1386
1837
  if (opts?.skipTopLevel?.has(name) === true) {
1387
- subFields[name] = field;
1838
+ setOwn(subFields, name, fieldNamed(name, field, field));
1388
1839
  continue;
1389
1840
  }
1390
1841
  const refTarget = opts?.resolveRef?.(name, field);
1391
1842
  if (refTarget !== undefined) {
1392
1843
  const fieldOpt = optionalField(field);
1393
1844
  const sub = substituteSchemaDeep(refTarget, atField(deeper, opts, name));
1394
- subFields[name] = fieldOpt ? fieldOpt.rewrap(sub) : sub;
1845
+ setOwn(subFields, name, fieldNamed(name, fieldOpt ? fieldOpt.rewrap(sub) : sub, field));
1395
1846
  }
1396
1847
  else {
1397
- subFields[name] = substituteSchemaDeep(field, atField(deeper, opts, name));
1848
+ const sub = substituteSchemaDeep(field, atField(deeper, opts, name));
1849
+ setOwn(subFields, name, name === "__proto__"
1850
+ ? fieldNamed(name, sub, field)
1851
+ : opts?.absentReads
1852
+ ? readingAbsent(sub)
1853
+ : sub);
1398
1854
  }
1399
1855
  }
1400
1856
  const plainStruct = Schema.Struct(subFields);
@@ -1415,8 +1871,214 @@ export const substituteSchemaDeep = (schema, opts) => {
1415
1871
  encode: SchemaGetter.transform((instance) => ({ ...instance })),
1416
1872
  }));
1417
1873
  }
1418
- return schema;
1874
+ return unwalked();
1875
+ };
1876
+ /**
1877
+ * What a declaration is, when its stored form is a marshalled `DateTime`. A `.check()`, a brand or an
1878
+ * annotation keeps the declaration, so it's still the date it was; a transformation over one isn't,
1879
+ * and the date beneath it is reached through its encoding.
1880
+ */
1881
+ const isMarshalledDate = (ast) => {
1882
+ if (!SchemaAST.isDeclaration(ast) || ast.encoding !== undefined)
1883
+ return false;
1884
+ const domain = matchDateRepresentation(ast.annotations)?.domain;
1885
+ return domain === "DateTime.Utc" || domain === "DateTime.Zoned";
1886
+ };
1887
+ /**
1888
+ * A stored date, rebuilt, before it meets its declaration. Only a value carrying the marker a
1889
+ * marshalled date carries is touched: the declaration's guard takes the current one, so what it
1890
+ * accepts doesn't change, and the one Effect's betas and early rcs wrote is the one form added. Any
1891
+ * other value goes on to the declaration as it was, which refuses it or takes it as it always has, so
1892
+ * a union picks the member it picked before.
1893
+ */
1894
+ const rebuildingMarshalledDate = {
1895
+ decode: SchemaGetter.transform((value) => typeof value === "object" &&
1896
+ value !== null &&
1897
+ (DATE_MARKER in value || BETA_DATE_MARKER in value)
1898
+ ? (reviveMarshalledDateTime(value) ?? value)
1899
+ : value),
1900
+ encode: SchemaGetter.passthrough(),
1901
+ };
1902
+ /** A plain `Schema.BigInt`, checked or branded or not, stored as `N`: a transformation is reached through. */
1903
+ const isMarshalledBigInt = (ast) => SchemaAST.isBigInt(ast) && ast.encoding === undefined;
1904
+ /**
1905
+ * A stored bigint, lifted, before it meets its declaration: a number that's a safe integer becomes
1906
+ * the bigint it was, and a bigint the unmarshaller returned stays one. Any other value goes on to the
1907
+ * declaration as it was. The walker refuses a union in which another member takes the number
1908
+ * (`EDD-9125`), so a number reaching this is a number no member takes.
1909
+ */
1910
+ const liftingMarshalledBigInt = {
1911
+ decode: SchemaGetter.transform((value) => legacyBigInt(value) ?? value),
1912
+ encode: SchemaGetter.passthrough(),
1913
+ };
1914
+ const astWith = (ast, changes) => Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, changes);
1915
+ /**
1916
+ * The same node with its children through `f`, or the node itself when none of them changed. Walks
1917
+ * the AST, not the schema's accessors, so it reaches every position: a `Schema.annotate` drops a
1918
+ * class's `.fields`, and a declaration's type parameters and a transformation's encoded side have no
1919
+ * accessor at all. A suspended schema is walked when it's forced, as a recursive one has no end.
1920
+ */
1921
+ const withChildren = (ast, f, absentValues = false) => {
1922
+ switch (ast._tag) {
1923
+ case "Declaration": {
1924
+ const typeParameters = SchemaAST.mapOrSame(ast.typeParameters, (parameter) => absentValues ? readingAbsentParameter(parameter, f(parameter)) : f(parameter));
1925
+ return typeParameters === ast.typeParameters ? ast : astWith(ast, { typeParameters });
1926
+ }
1927
+ case "Arrays": {
1928
+ const elements = SchemaAST.mapOrSame(ast.elements, f);
1929
+ const rest = SchemaAST.mapOrSame(ast.rest, f);
1930
+ return elements === ast.elements && rest === ast.rest ? ast : astWith(ast, { elements, rest });
1931
+ }
1932
+ case "Objects": {
1933
+ const propertySignatures = SchemaAST.mapOrSame(ast.propertySignatures, (property) => {
1934
+ const read = f(property.type);
1935
+ const type = absentValues
1936
+ ? readingAbsent(Schema.make(read), Schema.make(property.type)).ast
1937
+ : read;
1938
+ return type === property.type
1939
+ ? property
1940
+ : new SchemaAST.PropertySignature(property.name, type);
1941
+ });
1942
+ const indexSignatures = SchemaAST.mapOrSame(ast.indexSignatures, (index) => {
1943
+ const type = f(index.type);
1944
+ return type === index.type ? index : new SchemaAST.IndexSignature(index.parameter, type);
1945
+ });
1946
+ return propertySignatures === ast.propertySignatures &&
1947
+ indexSignatures === ast.indexSignatures
1948
+ ? ast
1949
+ : astWith(ast, { propertySignatures, indexSignatures });
1950
+ }
1951
+ case "Union": {
1952
+ const types = SchemaAST.mapOrSame(ast.types, f);
1953
+ return types === ast.types ? ast : astWith(ast, { types });
1954
+ }
1955
+ case "Suspend":
1956
+ return astWith(ast, { thunk: () => f(ast.thunk()) });
1957
+ default:
1958
+ return ast;
1959
+ }
1960
+ };
1961
+ /**
1962
+ * A declaration's value, read as what it stands for when it's absent. The marshaller leaves an empty
1963
+ * set out of what it stores, and an `Option`, a `Result`, an `Exit` or a `Cause` holding one then has
1964
+ * no value at all. `undefined` needs nothing: it's what an absent one reads as already.
1965
+ */
1966
+ const readingAbsentParameter = (declared, read) => {
1967
+ const stored = absentStored(Schema.make(declared))?.stored;
1968
+ if (stored === undefined)
1969
+ return read;
1970
+ return Schema.Unknown.pipe(Schema.decodeTo(Schema.make(read), {
1971
+ decode: SchemaGetter.transform((value) => value === undefined ? stored : value),
1972
+ encode: SchemaGetter.passthrough(),
1973
+ })).ast;
1974
+ };
1975
+ /**
1976
+ * A union where a member takes more than it declares, by reading an absent value, is what
1977
+ * `substituteSchemaDeep` makes one it can walk: enough to claim a row of a later member, so the
1978
+ * members as declared get their try first, and only a row none of them takes reads absent. Each side
1979
+ * stays whole, so a `oneOf` one still refuses a value two members take.
1980
+ */
1981
+ const tryingDeclaredFirst = (ast, read, declared) => ast.types.some((member) => holdsAbsentValue(SchemaAST.toEncoded(member)))
1982
+ ? astWith(ast, {
1983
+ types: [astWith(ast, { types: ast.types.map((member) => declared(member)) }), read],
1984
+ options: { ...ast.options, mode: "anyOf" },
1985
+ })
1986
+ : read;
1987
+ /**
1988
+ * A schema with what `rebuildOf` names, wherever it sits, rebuilt before it meets its node, and with
1989
+ * `absentValues` a value the marshaller left out read as what it stands for.
1990
+ */
1991
+ const readingStored = (rebuildOf, absentValues = false) => {
1992
+ const declared = absentValues ? readingStored(rebuildOf) : undefined;
1993
+ const memo = new WeakMap();
1994
+ const reading = (ast) => {
1995
+ const known = memo.get(ast);
1996
+ if (known !== undefined)
1997
+ return known;
1998
+ let read;
1999
+ const rebuild = rebuildOf(ast);
2000
+ if (rebuild !== undefined) {
2001
+ const stored = ast.context?.isOptional ? Schema.optionalKey(Schema.Unknown) : Schema.Unknown;
2002
+ read = stored.pipe(Schema.decodeTo(Schema.make(ast), rebuild)).ast;
2003
+ }
2004
+ else {
2005
+ // What's stored is the encoded side: a type side holds what its transformation made, and
2006
+ // nothing was left out of that.
2007
+ const stored = declared !== undefined && ast.encoding === undefined;
2008
+ read = stored ? withChildren(ast, reading, true) : withChildren(ast, declared ?? reading);
2009
+ if (stored && SchemaAST.isUnion(ast)) {
2010
+ read = tryingDeclaredFirst(ast, read, declared);
2011
+ }
2012
+ const encoding = ast.encoding &&
2013
+ SchemaAST.mapOrSame(ast.encoding, (link) => {
2014
+ const to = reading(link.to);
2015
+ return to === link.to ? link : new SchemaAST.Link(to, link.transformation);
2016
+ });
2017
+ if (encoding !== ast.encoding)
2018
+ read = astWith(read, { encoding });
2019
+ }
2020
+ memo.set(ast, read);
2021
+ return read;
2022
+ };
2023
+ return reading;
2024
+ };
2025
+ /**
2026
+ * Every marshalled date and bigint in a schema, wherever it sits, read back as a real one, and every
2027
+ * value the marshaller left out as what it stands for.
2028
+ */
2029
+ const readingMarshalled = readingStored((ast) => isMarshalledDate(ast)
2030
+ ? rebuildingMarshalledDate
2031
+ : isMarshalledBigInt(ast)
2032
+ ? liftingMarshalledBigInt
2033
+ : undefined, true);
2034
+ const bigIntRebuild = (ast) => isMarshalledBigInt(ast) ? liftingMarshalledBigInt : undefined;
2035
+ const liftingBigInts = readingStored(bigIntRebuild);
2036
+ const liftingBigIntsAndAbsent = readingStored(bigIntRebuild, true);
2037
+ /**
2038
+ * A schema the substitution can't walk, read as the walk reads what it can reach: every plain bigint
2039
+ * in it as one, and on a read that wants them, every absent value as what it stands for.
2040
+ */
2041
+ const readingUnwalked = (schema, opts) => {
2042
+ if (opts?.absentReads === true && holdsUnwalkedAbsent(schema)) {
2043
+ return Schema.make(liftingBigIntsAndAbsent(schema.ast));
2044
+ }
2045
+ return liftsBigInts(opts) && holdsUnwalkedBigInt(schema)
2046
+ ? Schema.make(liftingBigInts(schema.ast))
2047
+ : schema;
1419
2048
  };
2049
+ /**
2050
+ * The read schema of a value the library stores but doesn't derive: an event, its metadata, a
2051
+ * snapshot state, an outbox effect. Every read of one goes through it, so anything a stream's read
2052
+ * does differently from its declaration belongs here. Differently, as it stands, in four ways:
2053
+ *
2054
+ * - An absent attribute reads as the value it stands for (`absentStored`).
2055
+ * - A `Schema.DateTimeUtc` or `Schema.DateTimeZoned` comes back as a real date. Nothing substitutes
2056
+ * these on write, so one is stored as the map the marshaller makes of it, and Effect's guard only
2057
+ * looks for the marker and the tag, which that map has. Left to the guard, it reads back as a plain
2058
+ * object that passes `DateTime.isDateTime` and isn't one: `Equal` is false, and on a named zone
2059
+ * `DateTime.getPart` throws.
2060
+ * - A `Schema.BigInt` comes back as a bigint. The marshaller stores one as a number, and the
2061
+ * unmarshaller returns a safe integer as a number, so without this only the values past 2^53 read.
2062
+ * - Each of Effect's other look-alike declarations (a `BigDecimal`, a `Duration`, a zone, an address,
2063
+ * ...) comes back as a real instance, where the read takes one (`readingInstances`).
2064
+ *
2065
+ * Returned as it came when none applies to it.
2066
+ *
2067
+ * @internal
2068
+ */
2069
+ export const readingStreamValues = (schema) => {
2070
+ const absent = substituteSchemaDeep(schema, { absentReads: "only", enforceChecks: true });
2071
+ const read = readingMarshalled(absent.ast);
2072
+ return readingInstances(read === absent.ast ? absent : Schema.make(read));
2073
+ };
2074
+ /**
2075
+ * A schema the library stores but doesn't derive, refusing a tuple position holding
2076
+ * `undefined` that a stored list can't keep, and otherwise exactly as declared.
2077
+ * Unchanged when no tuple of it can hold one.
2078
+ *
2079
+ * @internal
2080
+ */
2081
+ export const writingTuplePositions = (schema) => substituteSchemaDeep(schema, { undefinedPositionsOnly: true, enforceChecks: true });
1420
2082
  /**
1421
2083
  * Substitute model fields with bidirectional transforms where needed:
1422
2084
  *
@@ -1444,9 +2106,11 @@ export const substituteSchemaDeep = (schema, opts) => {
1444
2106
  */
1445
2107
  export const substituteSchemas = (modelFields, fieldEncodings, options) => {
1446
2108
  const out = {};
2109
+ const storedAsProto = options?.protoRenamed !== true;
1447
2110
  const deep = {
1448
2111
  ...(options?.legacyReads ? { legacyReads: true } : {}),
1449
2112
  ...(options?.enforceChecks ? { enforceChecks: true } : {}),
2113
+ ...(options?.absentReads ? { absentReads: true } : {}),
1450
2114
  };
1451
2115
  for (const [name, schema] of Object.entries(modelFields)) {
1452
2116
  // 1. Self-date substitution. Pattern A: user declared `Schema.DateTimeUtc`
@@ -1454,18 +2118,18 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
1454
2118
  // tolerant date transform so the encode pipeline produces the right
1455
2119
  // wire primitive.
1456
2120
  if (isSelfDateSchema(schema)) {
1457
- const enc = fieldEncodings[name];
2121
+ const enc = ownValue(fieldEncodings, name);
1458
2122
  if (enc) {
1459
- out[name] = buildDateTransform(enc);
2123
+ setOwn(out, name, fieldNamed(name, buildDateTransform(enc), schema, storedAsProto));
1460
2124
  continue;
1461
2125
  }
1462
2126
  }
1463
2127
  // …also beneath a decoding default, which is kept on top (#133).
1464
2128
  const defaulted = decodingDefaultField(schema);
1465
2129
  if (defaulted !== undefined && isSelfDateSchema(defaulted.inner)) {
1466
- const enc = fieldEncodings[name];
2130
+ const enc = ownValue(fieldEncodings, name);
1467
2131
  if (enc) {
1468
- out[name] = defaulted.rewrap(buildDateTransform(enc));
2132
+ setOwn(out, name, fieldNamed(name, defaulted.rewrap(buildDateTransform(enc)), schema, storedAsProto));
1469
2133
  continue;
1470
2134
  }
1471
2135
  }
@@ -1474,7 +2138,7 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
1474
2138
  // transform so the round-trip works for storage.
1475
2139
  const redactedInner = tryGetRedactedInner(schema);
1476
2140
  if (redactedInner !== undefined) {
1477
- out[name] = buildRedactedSubstitute(redactedInner);
2141
+ setOwn(out, name, fieldNamed(name, buildRedactedSubstitute(schema, redactedInner), schema, storedAsProto));
1478
2142
  continue;
1479
2143
  }
1480
2144
  // 3. Default: recurse for nested substitution. Pattern B transforms
@@ -1486,12 +2150,18 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
1486
2150
  // identity, and returns the schema unchanged when nothing nested needs it.
1487
2151
  // A configured storage override on a UNION field (`NullOr(DateTimeUtc)`)
1488
2152
  // is applied to the union's self-date member (#133).
1489
- const unionOverride = unionDateOverride(name, schema, fieldEncodings[name]);
1490
- out[name] = substituteSchemaDeep(schema, {
2153
+ const unionOverride = unionDateOverride(name, schema, ownValue(fieldEncodings, name));
2154
+ setOwn(out, name, fieldNamed(name, substituteSchemaDeep(schema, {
1491
2155
  ...deep,
1492
2156
  path: [name],
1493
2157
  ...(unionOverride === undefined ? {} : { unionDateOverride: unionOverride }),
1494
- });
2158
+ }), schema, storedAsProto));
2159
+ }
2160
+ if (options?.absentReads) {
2161
+ for (const [name, field] of Object.entries(out)) {
2162
+ if (!isProtoAbsent(field))
2163
+ setOwn(out, name, readingAbsent(field));
2164
+ }
1495
2165
  }
1496
2166
  return out;
1497
2167
  };
@@ -1552,30 +2222,38 @@ export const validateNoTransformOverride = (modelFields, configuredAttributes) =
1552
2222
  if (!isDateTransform(schema))
1553
2223
  continue;
1554
2224
  // 1. ConfiguredModel.storedAs override?
1555
- const configOverride = configuredAttributes[name]?.encoding;
2225
+ const configOverride = ownValue(configuredAttributes, name)?.encoding;
1556
2226
  if (configOverride !== undefined) {
1557
2227
  throw new Error(conflictMessage(name));
1558
2228
  }
1559
- // 2. DynamoModel.storedAs() modifier on the schema itself? The modifier
1560
- // applies a `DynamoEncoding` annotation to the AST. Detect a conflict
1561
- // by comparing the annotation's storage with the transform's actual
1562
- // wire format (resolved via `transformWireKind`, which walks the typed
1563
- // `Base.encoding` chain to its leaf). Granularity: we can distinguish
1564
- // "string" vs "number" wire forms; we cannot distinguish epochMs vs
1565
- // epochSeconds at this layer. The string-vs-number mismatch covers the
1566
- // most common breaking case.
1567
- const annotated = getEncoding(schema);
1568
- if (annotated === undefined)
1569
- continue;
1570
- const transformWire = transformWireKind(schema);
1571
- if (transformWire === undefined)
1572
- continue;
1573
- const annotatedKind = annotated.storage === "string" ? "string" : "number";
1574
- if (transformWire !== annotatedKind) {
2229
+ // 2. DynamoModel.storedAs() modifier on the schema itself?
2230
+ if (storedAsOverTransform(schema)) {
1575
2231
  throw new Error(conflictMessage(name));
1576
2232
  }
1577
2233
  }
1578
2234
  };
2235
+ /**
2236
+ * Whether a date transform schema carries a `DynamoModel.storedAs(...)` annotation of the other wire
2237
+ * kind: one {@link validateNoTransformOverride} refuses. The modifier applies a `DynamoEncoding`
2238
+ * annotation to the AST; it conflicts when its storage disagrees with the transform's actual wire
2239
+ * format (resolved via `transformWireKind`, which walks the typed `Base.encoding` chain to its leaf).
2240
+ * Granularity: "string" vs "number" wire forms; epochMs vs epochSeconds can't be told apart at this
2241
+ * layer. The string-vs-number mismatch covers the most common breaking case. Such a field stores the
2242
+ * transform's form, so a value in the annotation's form can't be read back from it.
2243
+ *
2244
+ * @internal Also read by `Entity.make`: a `Schema.optional` date of this kind isn't a stamp.
2245
+ */
2246
+ export const storedAsOverTransform = (schema) => {
2247
+ if (!isDateTransform(schema))
2248
+ return false;
2249
+ const annotated = getEncoding(schema);
2250
+ if (annotated === undefined)
2251
+ return false;
2252
+ const transformWire = transformWireKind(schema);
2253
+ if (transformWire === undefined)
2254
+ return false;
2255
+ return transformWire !== (annotated.storage === "string" ? "string" : "number");
2256
+ };
1579
2257
  /**
1580
2258
  * Read the wire form ("string" or "number") that a transform schema actually
1581
2259
  * encodes to, by walking the encoding chain. Returns undefined when the chain
@@ -1586,7 +2264,52 @@ export const validateNoTransformOverride = (modelFields, configuredAttributes) =
1586
2264
  * leaf `Link.to` AST.
1587
2265
  */
1588
2266
  const transformWireKind = (schema) => transformWireKindImpl(schema);
1589
- export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolvedRefs = [], immutableFields = new Set(), identifierField = undefined, timeSeries = undefined, fieldEncodings = {}, generatedIdField = undefined) => {
2267
+ /**
2268
+ * @internal The `DynamoModel.Hidden` fields of a model: a read in "model" or "record" mode leaves
2269
+ * them out, of the entity's own items and of a ref to it ({@link refHeldSchema}).
2270
+ */
2271
+ export const hiddenFieldNamesOf = (fields) => new Set(Object.keys(fields).filter((name) => isHidden(fields[name])));
2272
+ /** The targets {@link refHeldTarget} decided, each once. */
2273
+ const refHeldTargets = new WeakMap();
2274
+ /** The schemas {@link refHeldTarget} built: a target's fields without its hidden ones. */
2275
+ const heldStructs = new WeakSet();
2276
+ /**
2277
+ * @internal What a ref to an entity of model `target` holds (#241), the one decision every ref
2278
+ * position takes (an entity's `refs`, an aggregate's edges and the refs nested in their entities):
2279
+ * what a read of that entity returns, which put-time hydration and a cascade store, both through
2280
+ * `refDataOf` (the entity's own read schema encoding the item it read). A read leaves out the
2281
+ * target's `DynamoModel.Hidden` fields ({@link hiddenFieldNamesOf}), so the stored ref holds none
2282
+ * of them. Where a hidden field read absent fails, as a read decodes it (`Missing key`), the ref is
2283
+ * the target's other fields, a plain object as the entity's own read decodes it: up to 1.40.0 it
2284
+ * was the whole target, so the referencing row failed every read, after its write. Every other
2285
+ * target is held as declared, a class read back as its instance, as up to 1.40.0: one whose hidden
2286
+ * fields are optional, or read absent as a value (`Schema.Unknown`, `Schema.Any`,
2287
+ * `Schema.UndefinedOr`, a decoding default).
2288
+ */
2289
+ export const refHeldTarget = (target) => {
2290
+ const decided = refHeldTargets.get(target);
2291
+ if (decided !== undefined)
2292
+ return decided;
2293
+ const fields = getSchemaFields(target);
2294
+ const hidden = fields === undefined ? new Set() : hiddenFieldNamesOf(fields);
2295
+ // A hidden field read absent, as a read of the referencing row decodes it.
2296
+ const failsAbsent = (name) => Option.isNone(Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct({ [name]: fields[name] }), {
2297
+ legacyReads: true,
2298
+ absentReads: true,
2299
+ }))({}));
2300
+ const held = fields !== undefined && [...hidden].some(failsAbsent)
2301
+ ? Schema.Struct(Object.fromEntries(Object.entries(fields).filter(([name]) => !hidden.has(name))))
2302
+ : target;
2303
+ if (held !== target)
2304
+ heldStructs.add(held);
2305
+ refHeldTargets.set(target, held);
2306
+ return held;
2307
+ };
2308
+ /** @internal {@link refHeldTarget}, substituted as a read or a write takes it (`options`). */
2309
+ export const refHeldSchema = (target, options) => substituteSchemaDeep(refHeldTarget(target), options);
2310
+ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolvedRefs = [], immutableFields = new Set(), identifierField = undefined, timeSeries = undefined, fieldEncodings = {}, generatedIdField = undefined,
2311
+ /** The field `__proto__` is stored under another attribute: see `substituteSchemas`. */
2312
+ protoRenamed = false) => {
1590
2313
  // --- Substitute model fields ---
1591
2314
  // Self date schemas (with effective encoding) are replaced with bidirectional
1592
2315
  // transforms that produce the configured wire primitive. RedactedFromValue
@@ -1595,12 +2318,20 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1595
2318
  // transform IS the wire format and we never override it.
1596
2319
  // WRITE schemas (input / create / update / key) enforce the container checks
1597
2320
  // the substitution rebuilds; the READ schemas below do not (#133).
1598
- const fields = substituteSchemas(modelFields, fieldEncodings, { enforceChecks: true });
2321
+ const fields = substituteSchemas(modelFields, fieldEncodings, {
2322
+ enforceChecks: true,
2323
+ protoRenamed,
2324
+ });
1599
2325
  // READ schemas (model / record / item / deleted / history decode) also take
1600
- // the domain-form values earlier releases left on transform fields (#133).
2326
+ // the domain-form values earlier releases left on transform fields (#133),
2327
+ // and read an absent attribute as the value it stands for (`absentStored`).
1601
2328
  // Their encode is the strict one, and keys are composed from `inputSchema`,
1602
2329
  // so neither writes nor keys see a difference.
1603
- const readFields = substituteSchemas(modelFields, fieldEncodings, { legacyReads: true });
2330
+ const readFields = substituteSchemas(modelFields, fieldEncodings, {
2331
+ legacyReads: true,
2332
+ absentReads: true,
2333
+ protoRenamed,
2334
+ });
1604
2335
  // Ref fields carry the `DynamoModel.ref` annotation (an opaque Declaration that
1605
2336
  // hides the target's fields), so `substituteSchemaDeep` above can't see into
1606
2337
  // them. Re-point each denormalized ref field at its target model, recursively
@@ -1609,13 +2340,28 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1609
2340
  // only model/record/item schemas — input/create/update replace refs with IDs.
1610
2341
  for (const ref of resolvedRefs) {
1611
2342
  const targetModel = ref.refEntity?.model;
1612
- if (!targetModel || !(ref.fieldName in fields))
2343
+ if (!targetModel || !hasOwnName(fields, ref.fieldName))
1613
2344
  continue;
1614
2345
  const resolved = isConfiguredModel(targetModel)
1615
2346
  ? targetModel.model
1616
2347
  : targetModel;
1617
- fields[ref.fieldName] = substituteSchemaDeep(resolved, { enforceChecks: true });
1618
- readFields[ref.fieldName] = substituteSchemaDeep(resolved, { legacyReads: true });
2348
+ // As optional as the model declares it (#241): a row an optional ref was left out of, or
2349
+ // removed from, reads without it. Up to 1.40.0 the target replaced the declaration whole.
2350
+ const optional = optionalField(ownValue(modelFields, ref.fieldName));
2351
+ const asDeclared = (target) => optional === undefined ? target : optional.rewrap(target);
2352
+ // What a read of the target returns (`refHeldSchema`): its required hidden fields left out.
2353
+ setOwn(fields, ref.fieldName, asDeclared(refHeldSchema(resolved, { enforceChecks: true })));
2354
+ setOwn(readFields, ref.fieldName, asDeclared(refHeldSchema(resolved, {
2355
+ legacyReads: true,
2356
+ absentReads: true,
2357
+ })));
2358
+ }
2359
+ // Each of Effect's look-alike declarations (a `BigDecimal`, a `Duration`, an address, a date in
2360
+ // an `Option`, ...) reads back as a real instance, not the map DynamoDB hands back for it. A field
2361
+ // holding none is the same schema it was. Encoding through one is as it was.
2362
+ for (const [name, field] of Object.entries(readFields)) {
2363
+ if (!isProtoAbsent(field))
2364
+ setOwn(readFields, name, readingInstances(field));
1619
2365
  }
1620
2366
  // --- Model Schema: pure model fields (decode of stored items in "model" mode) ---
1621
2367
  const modelSchema = Schema.Struct(readFields);
@@ -1626,19 +2372,19 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1626
2372
  // already in `fields` and we don't add a system-schema entry.
1627
2373
  const systemSchemaFields = {};
1628
2374
  if (systemFields.createdAt && !systemFields.createdAtCollision) {
1629
- systemSchemaFields[systemFields.createdAt] = systemFields.createdAtEncoding
2375
+ setOwn(systemSchemaFields, systemFields.createdAt, systemFields.createdAtEncoding
1630
2376
  ? buildDateTransform(systemFields.createdAtEncoding)
1631
- : Schema.DateTimeUtcFromString;
2377
+ : Schema.DateTimeUtcFromString);
1632
2378
  }
1633
2379
  if (systemFields.updatedAt && !systemFields.updatedAtCollision) {
1634
- systemSchemaFields[systemFields.updatedAt] = systemFields.updatedAtEncoding
2380
+ setOwn(systemSchemaFields, systemFields.updatedAt, systemFields.updatedAtEncoding
1635
2381
  ? buildDateTransform(systemFields.updatedAtEncoding)
1636
- : Schema.DateTimeUtcFromString;
2382
+ : Schema.DateTimeUtcFromString);
1637
2383
  }
1638
2384
  if (systemFields.version && !systemFields.versionCollision) {
1639
2385
  // An item written before the entity was `versioned` has no version: it
1640
2386
  // reads as version 0 — real versions start at 1 (#133).
1641
- systemSchemaFields[systemFields.version] = Schema.Number.pipe(Schema.withDecodingDefaultKey(Effect.succeed(0)));
2387
+ setOwn(systemSchemaFields, systemFields.version, Schema.Number.pipe(Schema.withDecodingDefaultKey(Effect.succeed(0))));
1642
2388
  }
1643
2389
  const recordSchema = Schema.Struct({
1644
2390
  ...readFields,
@@ -1678,6 +2424,14 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1678
2424
  };
1679
2425
  // --- Input Schema: ref-aware (swap ref fields for ID fields when refs present) ---
1680
2426
  const refFieldSet = new Set(resolvedRefs.map((r) => r.fieldName));
2427
+ // A ref's id is taken as the model takes the ref (#241): required where it's required, and left
2428
+ // out (`Schema.optionalKey`) or `undefined` too (`Schema.optional`) where the model declares the
2429
+ // ref optional, which then stores no ref. Up to 1.40.0 the id was always required.
2430
+ const refIdInput = (ref) => {
2431
+ const declared = modelFields[ref.fieldName];
2432
+ const optional = declared === undefined ? undefined : optionalField(declared);
2433
+ return optional === undefined ? ref.keySchema : optional.rewrap(ref.keySchema);
2434
+ };
1681
2435
  const buildInputFieldsAcc = () => {
1682
2436
  const acc = {};
1683
2437
  for (const [key, field] of Object.entries(fields)) {
@@ -1685,10 +2439,10 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1685
2439
  continue;
1686
2440
  const adjusted = applySystemCollisionAdjustments(key, field, "input");
1687
2441
  if (adjusted !== null)
1688
- acc[key] = adjusted;
2442
+ setOwn(acc, key, adjusted);
1689
2443
  }
1690
2444
  for (const ref of resolvedRefs) {
1691
- acc[ref.idFieldName] = ref.identifierSchema;
2445
+ setOwn(acc, ref.idFieldName, refIdInput(ref));
1692
2446
  }
1693
2447
  return acc;
1694
2448
  };
@@ -1704,23 +2458,26 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1704
2458
  continue; // skip ref fields (replaced by ID fields)
1705
2459
  const adjusted = applySystemCollisionAdjustments(key, field, "input");
1706
2460
  if (adjusted !== null)
1707
- createFieldsAcc[key] = adjusted;
2461
+ setOwn(createFieldsAcc, key, adjusted);
1708
2462
  }
1709
2463
  // Add ID fields for each ref (skip if the ref field is an omitted field)
1710
2464
  for (const ref of resolvedRefs) {
1711
2465
  if (createOmitFields.has(ref.fieldName))
1712
2466
  continue;
1713
- createFieldsAcc[ref.idFieldName] = ref.identifierSchema;
2467
+ setOwn(createFieldsAcc, ref.idFieldName, refIdInput(ref));
1714
2468
  }
1715
2469
  const createSchema = Schema.Struct(createFieldsAcc);
1716
2470
  // --- Update Schema: optional model fields minus key composites & immutable ---
1717
- // Each field is wrapped in `Schema.optional` so the key may be omitted
1718
- // entirely (the structural composer treats absent keys as absent for GSI
1719
- // composition under v3's two-way classification). The field's value type
1720
- // matches the model declaration exactly — there is no `null` widening,
1721
- // because EDD-9025 prevents composites from declaring `null` and the
1722
- // standard update payload follows the same shape. If the model declares a
1723
- // non-composite attribute as `Schema.NullOr(X)`, `set({ attr: null })`
2471
+ // The key may always be omitted (the structural composer treats absent keys
2472
+ // as absent for GSI composition under v3's two-way classification). Whether
2473
+ // its value may be `undefined` follows the row: `undefined` clears the field,
2474
+ // so a field a row can lack takes `Schema.optional` and one it can't takes
2475
+ // `Schema.optionalKey`, as do ref ids. A library-generated value (a colliding
2476
+ // `updatedAt`) stays `Schema.optional`: `undefined` there means generate it.
2477
+ // The field's value type matches the model declaration exactly — there is
2478
+ // no `null` widening, because EDD-9025 prevents composites from declaring
2479
+ // `null` and the standard update payload follows the same shape. If the model
2480
+ // declares a non-composite attribute as `Schema.NullOr(X)`, `set({ attr: null })`
1724
2481
  // still typechecks; the v1.6 `NullishOr` wrap that allowed null on
1725
2482
  // arbitrary fields (regardless of model declaration) is removed.
1726
2483
  const buildUpdateFieldsAcc = () => {
@@ -1734,25 +2491,34 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1734
2491
  continue;
1735
2492
  if (strippedFromUpdate.has(key))
1736
2493
  continue;
1737
- acc[key] = Schema.optional(field);
2494
+ // A field 1.40.0's map didn't hold is one an update may leave out already (`protoAbsent`).
2495
+ if (isProtoAbsent(field)) {
2496
+ setOwn(acc, key, field);
2497
+ continue;
2498
+ }
2499
+ const clearable = optionalOnCollide.has(key) || lackDecision(field) !== "refuse";
2500
+ setOwn(acc, key, clearable ? Schema.optional(field) : Schema.optionalKey(field));
1738
2501
  }
1739
2502
  for (const ref of resolvedRefs) {
1740
- if (pkComposites.has(ref.fieldName))
2503
+ // A ref's id that is a primary key composite is part of the key, which no update changes.
2504
+ if (pkComposites.has(ref.fieldName) || pkComposites.has(ref.idFieldName))
1741
2505
  continue;
1742
2506
  if (immutableFields.has(ref.fieldName))
1743
2507
  continue;
1744
- acc[ref.idFieldName] = Schema.optional(ref.identifierSchema);
2508
+ setOwn(acc, ref.idFieldName, Schema.optionalKey(ref.keySchema));
1745
2509
  }
1746
2510
  return acc;
1747
2511
  };
1748
2512
  const updateSchema = Schema.Struct(buildUpdateFieldsAcc());
1749
2513
  // --- Key Schema: primary key composite attributes only ---
2514
+ // A composite is a model field or a ref's id (`projectId` for `project`), which a key takes as
2515
+ // the input does. Up to 1.40.0 a ref's id was left out, and every key-taking operation died.
1750
2516
  const keyCompositeNames = primaryKeyComposites(indexes);
1751
2517
  const keyFields = {};
1752
2518
  for (const name of keyCompositeNames) {
1753
- const field = fields[name];
2519
+ const field = ownValue(fields, name) ?? resolvedRefs.find((ref) => ref.idFieldName === name)?.keySchema;
1754
2520
  if (field)
1755
- keyFields[name] = field;
2521
+ setOwn(keyFields, name, field);
1756
2522
  }
1757
2523
  const keySchema = Schema.Struct(keyFields);
1758
2524
  // --- Item Schema: record + key attrs (pk, sk, gsi*) + __edd_e__ ---
@@ -1769,9 +2535,7 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1769
2535
  }
1770
2536
  const keyAttrFields = {};
1771
2537
  for (const fieldName of allKeyFieldNames(indexes)) {
1772
- keyAttrFields[fieldName] = primaryKeyFieldNames.has(fieldName)
1773
- ? Schema.String
1774
- : Schema.optional(Schema.String);
2538
+ setOwn(keyAttrFields, fieldName, primaryKeyFieldNames.has(fieldName) ? Schema.String : Schema.optional(Schema.String));
1775
2539
  }
1776
2540
  const itemSchema = Schema.Struct({
1777
2541
  ...readFields,
@@ -1788,11 +2552,7 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1788
2552
  // --- Hidden-aware decode schemas: strip DynamoModel.Hidden fields from model/record ---
1789
2553
  // These are used for "model" and "record" decode modes. Hidden fields are
1790
2554
  // still present in "item" and "native" modes.
1791
- const hiddenFieldNames = new Set();
1792
- for (const [fieldName, fieldSchema] of Object.entries(modelFields)) {
1793
- if (isHidden(fieldSchema))
1794
- hiddenFieldNames.add(fieldName);
1795
- }
2555
+ const hiddenFieldNames = hiddenFieldNamesOf(modelFields);
1796
2556
  const hasHiddenFields = hiddenFieldNames.size > 0;
1797
2557
  const modelVisibleSchema = hasHiddenFields
1798
2558
  ? Schema.Struct(Object.fromEntries(Object.entries(readFields).filter(([k]) => !hiddenFieldNames.has(k))))
@@ -1820,7 +2580,10 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
1820
2580
  // Compute encodings for the appendInput fields (annotation +
1821
2581
  // inferred from typeConstructor for self schemas).
1822
2582
  const appendEncodings = buildFieldEncodings(userFields, {});
1823
- const subbedFields = substituteSchemas(userFields, appendEncodings, { enforceChecks: true });
2583
+ const subbedFields = substituteSchemas(userFields, appendEncodings, {
2584
+ enforceChecks: true,
2585
+ protoRenamed,
2586
+ });
1824
2587
  return Schema.Struct(subbedFields);
1825
2588
  })()
1826
2589
  : null;
@@ -1855,11 +2618,12 @@ export const resolveUniqueFields = (def) => Array.isArray(def) ? def : def.field
1855
2618
  // ---------------------------------------------------------------------------
1856
2619
  /** The schema one path segment addresses inside `schema`, or `undefined`. */
1857
2620
  const childAtSegment = (schema, segment) => {
1858
- const inner = optionalField(schema)?.inner ?? schema;
2621
+ const opt = optionalField(schema);
2622
+ const inner = opt?.union ?? opt?.inner ?? schema;
1859
2623
  const s = inner;
1860
2624
  const fields = schemaFieldsOf(inner);
1861
2625
  if (fields !== undefined)
1862
- return typeof segment === "string" ? fields[segment] : undefined;
2626
+ return typeof segment === "string" ? ownValue(fields, segment) : undefined;
1863
2627
  // An OPAQUE class — `X.check(…)`, `X.annotate(…)`, a `DynamoModel.ref` nested
1864
2628
  // in a ref target — is deliberately NOT followed. Its `.fields` are gone, so
1865
2629
  // the derived read schema keeps it unsubstituted and decodes its leaves
@@ -1898,7 +2662,7 @@ const childAtSegment = (schema, segment) => {
1898
2662
  if (isSchemaLike(s.value) && isSchemaLike(s.key))
1899
2663
  return s.value;
1900
2664
  if (isSchemaLike(s.schema) && Array.isArray(s.records)) {
1901
- const declared = schemaFieldsOf(s.schema)?.[segment];
2665
+ const declared = ownValue(schemaFieldsOf(s.schema), segment);
1902
2666
  if (declared !== undefined)
1903
2667
  return declared;
1904
2668
  const record = s.records[0];
@@ -1909,7 +2673,18 @@ const childAtSegment = (schema, segment) => {
1909
2673
  };
1910
2674
  /** The element schema of the list a path addresses (for append / prepend). */
1911
2675
  const listElementOf = (schema) => {
1912
- const inner = optionalField(schema)?.inner ?? schema;
2676
+ const opt = optionalField(schema);
2677
+ if (opt?.union !== undefined) {
2678
+ const members = opt.union
2679
+ .members;
2680
+ for (const member of members) {
2681
+ const element = listElementOf(member);
2682
+ if (element !== undefined)
2683
+ return element;
2684
+ }
2685
+ return undefined;
2686
+ }
2687
+ const inner = opt?.inner ?? schema;
1913
2688
  if (!SchemaAST.isArrays(inner.ast))
1914
2689
  return undefined;
1915
2690
  const value = inner.value;
@@ -1928,7 +2703,8 @@ const sameValue = (a, b) => {
1928
2703
  }
1929
2704
  if (isPlainObject(a) && isPlainObject(b)) {
1930
2705
  const keys = Object.keys(a);
1931
- return keys.length === Object.keys(b).length && keys.every((k) => sameValue(a[k], b[k]));
2706
+ return (keys.length === Object.keys(b).length &&
2707
+ keys.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k])));
1932
2708
  }
1933
2709
  return false;
1934
2710
  };
@@ -1954,14 +2730,24 @@ const makeAmbiguityCheck = (original) => {
1954
2730
  return () => false;
1955
2731
  // "Already wire" means the value DECODES as wire — a plain string that is not
1956
2732
  // valid base64 is a domain value for `StringFromBase64`, and is encoded.
1957
- const decodesAsWire = Schema.decodeUnknownOption(original);
2733
+ const decodesAsWire = Schema.decodeUnknownExit(original);
1958
2734
  const isType = Schema.is(Schema.make(SchemaAST.toType(original.ast)));
1959
- const encode = Schema.encodeUnknownOption(original);
2735
+ const encode = Schema.encodeUnknownExit(original);
2736
+ // A transform that can't run synchronously can't tell (#236).
1960
2737
  return (value) => {
1961
- if (decodesAsWire(value)._tag === "None" || !isType(value))
2738
+ const asWire = issueOf(() => decodesAsWire(value));
2739
+ if (asWire === CANT_SAY)
2740
+ return CANT_SAY;
2741
+ if (asWire !== undefined || !isType(value))
1962
2742
  return false;
1963
- const encoded = encode(value);
1964
- return encoded._tag === "Some" && !sameValue(encoded.value, value);
2743
+ let encoded;
2744
+ const issue = issueOf(() => {
2745
+ encoded = encode(value);
2746
+ return encoded;
2747
+ });
2748
+ if (issue === CANT_SAY)
2749
+ return CANT_SAY;
2750
+ return encoded !== undefined && Exit.isSuccess(encoded) && !sameValue(encoded.value, value);
1965
2751
  };
1966
2752
  };
1967
2753
  /**
@@ -1978,7 +2764,7 @@ const asStored = (value) => {
1978
2764
  const out = {};
1979
2765
  for (const [key, entry] of Object.entries(value)) {
1980
2766
  if (entry !== undefined)
1981
- out[key] = asStored(entry);
2767
+ setOwn(out, key, asStored(entry));
1982
2768
  }
1983
2769
  return out;
1984
2770
  };
@@ -1989,6 +2775,98 @@ const isWalkableObject = (value) => value !== null &&
1989
2775
  !(value instanceof Date) &&
1990
2776
  !DateTime.isDateTime(value) &&
1991
2777
  !Redacted.isRedacted(value);
2778
+ /**
2779
+ * What `contains` compares in what a field stores (#242): an element of a list (`Schema.Array`, a
2780
+ * tuple), a member of a set (`Schema.ReadonlySet`, stored as DynamoDB's set), and otherwise a
2781
+ * substring of text.
2782
+ *
2783
+ * @internal
2784
+ */
2785
+ export const containedKindOf = (field) => {
2786
+ const inner = optionalField(field)?.inner ?? field;
2787
+ return SchemaAST.isArrays(inner.ast) ? "list" : isSetDeclaration(inner.ast) ? "set" : "text";
2788
+ };
2789
+ /**
2790
+ * A `contains` operand in the form the field stores what it compares (#242), from what a write of
2791
+ * a whole value there stores (`value`) and of one list element (`element`): the element as a list
2792
+ * stores it; the single member of a write of a set holding it; the text a write of it stores, when
2793
+ * that's text. `undefined` when the field doesn't take it so, and the operand is sent as given.
2794
+ *
2795
+ * @internal
2796
+ */
2797
+ export const containedOperand = (kind, value, element) => (operand) => {
2798
+ if (kind === "list")
2799
+ return element(operand);
2800
+ if (kind === "set") {
2801
+ const set = value(new Set([operand]))?.stored;
2802
+ return set instanceof Set && set.size === 1 ? { stored: [...set][0] } : undefined;
2803
+ }
2804
+ const text = value(operand);
2805
+ return typeof text?.stored === "string" ? text : undefined;
2806
+ };
2807
+ /** Whether a node carries nothing a read runs: no transformation, no check. */
2808
+ const plainNode = (ast) => ast.checks === undefined &&
2809
+ ast.encoding === undefined &&
2810
+ ast.encodingChecks === undefined;
2811
+ /** The members of a plain union, each union among them in turn; any other schema alone. */
2812
+ const membersOf = (schema) => {
2813
+ const members = schema.members;
2814
+ if (!SchemaAST.isUnion(schema.ast) || !plainNode(schema.ast) || !Array.isArray(members)) {
2815
+ return [schema];
2816
+ }
2817
+ return members.flatMap(membersOf);
2818
+ };
2819
+ const SCALAR_TAGS = new Set([
2820
+ "Null",
2821
+ "Undefined",
2822
+ "String",
2823
+ "Number",
2824
+ "Boolean",
2825
+ "BigInt",
2826
+ "Symbol",
2827
+ "Literal",
2828
+ "UniqueSymbol",
2829
+ "Enum",
2830
+ "TemplateLiteral",
2831
+ ]);
2832
+ /** What holds a path's next segment: a plain struct, a plain record, or something else. */
2833
+ const parentOf = (member) => {
2834
+ const ast = member.ast;
2835
+ if (!SchemaAST.isObjects(ast) || !plainNode(ast))
2836
+ return "other";
2837
+ if (ast.indexSignatures.length === 0)
2838
+ return "struct";
2839
+ return ast.propertySignatures.length === 0 ? "record" : "other";
2840
+ };
2841
+ /** A way's end where a member doesn't hold the path's next segment ({@link UnionWay}). */
2842
+ const missingAt = (member, segment) => {
2843
+ const ast = member.ast;
2844
+ if (!plainNode(ast))
2845
+ return { _tag: "Unknown" };
2846
+ if (SCALAR_TAGS.has(ast._tag))
2847
+ return { _tag: "CannotHold" };
2848
+ if (SchemaAST.isArrays(ast))
2849
+ return { _tag: typeof segment === "string" ? "CannotHold" : "Unknown" };
2850
+ if (SchemaAST.isObjects(ast) && ast.indexSignatures.length === 0) {
2851
+ return { _tag: typeof segment === "string" ? "Unread" : "CannotHold" };
2852
+ }
2853
+ return { _tag: "Unknown" };
2854
+ };
2855
+ /**
2856
+ * A union's member as a path's judgement reads it (#238): a struct that renames its keys as it's
2857
+ * stored ({@link keyRenamesOf}) is read as the struct it renames, by its properties' own names,
2858
+ * which a path names (each written under its stored name, which the struct reads it from).
2859
+ * Anything else as it is.
2860
+ */
2861
+ const readAs = (member) => {
2862
+ const ast = member.ast;
2863
+ if (!SchemaAST.isObjects(ast) || ast.encoding === undefined || !keyRenamesOf(ast))
2864
+ return member;
2865
+ const renamed = member.to;
2866
+ return isSchemaLike(renamed) && SchemaAST.isObjects(renamed.ast) && plainNode(renamed.ast)
2867
+ ? renamed
2868
+ : member;
2869
+ };
1992
2870
  /**
1993
2871
  * Encoders for the VALUES of path-based updates (`pathSet`, `pathAppend`,
1994
2872
  * `pathPrepend`, `pathIfNotExists`) and record-based `append` (#133).
@@ -2014,7 +2892,14 @@ export const makePathValueEncoder = (modelFields, writeFields,
2014
2892
  * field name. A ref field's own schema is opaque (the annotation drops its
2015
2893
  * `.fields`), so a path under it is followed through the target model.
2016
2894
  */
2017
- refTargets = {}) => {
2895
+ refTargets = {},
2896
+ /**
2897
+ * Whether DynamoDB can store an encoded value: an operand whose stored form it can't store is
2898
+ * sent as given ({@link operand}).
2899
+ */
2900
+ storable,
2901
+ /** The entity's READ schemas of the model's fields, which a row is decoded by (`readsAsGiven`). */
2902
+ readFields = {}) => {
2018
2903
  const recordFields = writeFields;
2019
2904
  const cache = new Map();
2020
2905
  const encoderFor = (key, resolve) => {
@@ -2042,27 +2927,50 @@ refTargets = {}) => {
2042
2927
  const element = leafAwareEncoder(originalElement, storedElement);
2043
2928
  return (value) => (Array.isArray(value) ? value.map((entry) => element(entry)) : value);
2044
2929
  }
2045
- const encode = Schema.encodeUnknownOption(stored);
2046
- const decode = Schema.decodeUnknownOption(stored);
2930
+ const encodeExit = Schema.encodeUnknownExit(stored);
2931
+ const decodeExit = Schema.decodeUnknownExit(stored);
2932
+ /** A synchronous run's value, `undefined` on a schema issue, `CANT_SAY` when it can't finish. */
2933
+ const attempt = (run, value) => {
2934
+ let exit;
2935
+ const verdict = issueOf(() => {
2936
+ exit = run(value);
2937
+ return exit;
2938
+ });
2939
+ if (verdict === CANT_SAY)
2940
+ return CANT_SAY;
2941
+ return verdict === undefined && exit !== undefined && Exit.isSuccess(exit)
2942
+ ? { value: exit.value }
2943
+ : undefined;
2944
+ };
2047
2945
  const ambiguous = makeAmbiguityCheck(original);
2048
2946
  return (value) => {
2049
- if (ambiguous(value))
2947
+ // Where the check can't tell (a schema that can't run synchronously), the value is
2948
+ // encoded as a domain value, and written as given if that can't finish either.
2949
+ if (ambiguous(value) === true)
2050
2950
  return value;
2051
2951
  // A container holding an ambiguous wire leaf (`{ b64: "aGk=", at }`) is
2052
2952
  // encoded part by part, so that leaf follows the leaf rule instead of
2053
2953
  // being encoded a second time by the whole-value encode.
2054
2954
  if (holdsAmbiguousLeaf(original, value))
2055
2955
  return encodeByParts(original, value);
2056
- const encoded = encode(value);
2057
- if (encoded._tag === "Some")
2956
+ // A schema that can't run synchronously (an asynchronous step, a defect) says nothing of
2957
+ // the value: it's written as given, as at a position nothing checks (#236).
2958
+ const encoded = attempt(encodeExit, value);
2959
+ if (encoded === CANT_SAY)
2960
+ return value;
2961
+ if (encoded !== undefined)
2058
2962
  return encoded.value;
2059
2963
  // `decode -> encode`, as `.set()` / `put` do: a plain object given for a
2060
2964
  // class-typed field, or a value already in wire form, round-trips to its
2061
2965
  // wire form instead of being marshalled as given.
2062
- const decoded = decode(value);
2063
- if (decoded._tag === "Some") {
2064
- const reencoded = encode(decoded.value);
2065
- if (reencoded._tag === "Some")
2966
+ const decoded = attempt(decodeExit, value);
2967
+ if (decoded === CANT_SAY)
2968
+ return value;
2969
+ if (decoded !== undefined) {
2970
+ const reencoded = attempt(encodeExit, decoded.value);
2971
+ if (reencoded === CANT_SAY)
2972
+ return value;
2973
+ if (reencoded !== undefined)
2066
2974
  return reencoded.value;
2067
2975
  }
2068
2976
  return encodeByParts(original, value);
@@ -2075,7 +2983,7 @@ refTargets = {}) => {
2075
2983
  check = makeAmbiguityCheck(optionalField(schema)?.inner ?? schema);
2076
2984
  ambiguityChecks.set(schema, check);
2077
2985
  }
2078
- return check(value);
2986
+ return check(value) === true;
2079
2987
  };
2080
2988
  /**
2081
2989
  * Whether a container value holds, at any depth, a leaf in ambiguous wire
@@ -2128,31 +3036,42 @@ refTargets = {}) => {
2128
3036
  const out = {};
2129
3037
  for (const [key, entry] of Object.entries(value)) {
2130
3038
  const child = childAtSegment(schema, key);
2131
- out[key] = child === undefined ? entry : partEncoder(child)(entry);
3039
+ setOwn(out, key, child === undefined ? entry : partEncoder(child)(entry));
2132
3040
  }
2133
3041
  return out;
2134
3042
  };
2135
- /** The model's own schema at a path, before any substitution. */
3043
+ /**
3044
+ * The model's own schema at a path, before any substitution, and whether the path goes through a
3045
+ * later member of an optional union, which is written as declared ({@link writesFirstMemberOnly}).
3046
+ */
2136
3047
  const originalAt = (segments) => {
2137
3048
  const [head, ...rest] = segments;
2138
3049
  if (typeof head !== "string")
2139
3050
  return undefined;
2140
- let current = refTargets[head] ?? modelFields[head];
3051
+ let current = ownValue(refTargets, head) ?? ownValue(modelFields, head);
3052
+ let asDeclared = false;
2141
3053
  for (const segment of rest) {
2142
3054
  if (current === undefined)
2143
3055
  return undefined;
3056
+ const opt = optionalField(current);
3057
+ if (opt?.union !== undefined && childAtSegment(opt.inner, segment) === undefined) {
3058
+ asDeclared = true;
3059
+ }
2144
3060
  current = childAtSegment(current, segment);
2145
3061
  }
2146
- return current;
3062
+ return current === undefined ? undefined : { schema: current, asDeclared };
2147
3063
  };
2148
3064
  const schemaAt = (segments) => {
2149
- const original = originalAt(segments);
2150
- if (original === undefined)
3065
+ const at = originalAt(segments);
3066
+ if (at === undefined)
2151
3067
  return undefined;
3068
+ const original = at.schema;
2152
3069
  const head = segments[0];
2153
3070
  const stored = segments.length === 1
2154
- ? recordFields[head]
2155
- : substituteSchemaDeep(original, { enforceChecks: true });
3071
+ ? ownValue(recordFields, head)
3072
+ : at.asDeclared
3073
+ ? original
3074
+ : substituteSchemaDeep(original, { enforceChecks: true });
2156
3075
  return stored === undefined ? undefined : { original, stored };
2157
3076
  };
2158
3077
  const validators = new Map();
@@ -2165,15 +3084,499 @@ refTargets = {}) => {
2165
3084
  ? null
2166
3085
  : (() => {
2167
3086
  const decode = Schema.decodeUnknownExit(schema);
3087
+ // Only a schema issue refuses: a decode that can't finish synchronously says
3088
+ // nothing of the value (#236).
2168
3089
  return (encoded) => {
2169
- const exit = decode(asStored(encoded));
2170
- return exit._tag === "Success" ? undefined : exit.cause;
3090
+ const issue = issueOf(() => decode(asStored(encoded)));
3091
+ return issue === CANT_SAY ? undefined : issue;
2171
3092
  };
2172
3093
  })();
2173
3094
  validators.set(key, fn);
2174
3095
  return fn;
2175
3096
  };
3097
+ /**
3098
+ * Every schema a row can hold the value at `segments` under (#242), each with whether it's written
3099
+ * as declared ({@link writesFirstMemberOnly}), or `undefined` where the schema alone doesn't
3100
+ * determine what a row holds there. The walk follows EVERY union member that can hold the path,
3101
+ * not only the first: a row holding a later member stores its value there under that member's
3102
+ * schema. A position that can't hold the rest of the path (a string, a number, a literal, `null`,
3103
+ * a struct without the field) is left out. One that could hold it but isn't modelled here (an
3104
+ * `Unknown` or `Any`, a suspended schema, a declaration such as an `Option` or an opaque class, a
3105
+ * container the walk can't read) makes the path undetermined, and so does an `Unknown` or `Any` at
3106
+ * the path itself.
3107
+ */
3108
+ const declaredAt = (segments) => {
3109
+ const [head, ...rest] = segments;
3110
+ if (typeof head !== "string")
3111
+ return undefined;
3112
+ const top = refTargets[head] ?? modelFields[head];
3113
+ if (top === undefined)
3114
+ return undefined;
3115
+ const holdsNoPath = new Set([
3116
+ "Null",
3117
+ "Undefined",
3118
+ "Void",
3119
+ "Never",
3120
+ "String",
3121
+ "Number",
3122
+ "Boolean",
3123
+ "BigInt",
3124
+ "Symbol",
3125
+ "UniqueSymbol",
3126
+ "Literal",
3127
+ "TemplateLiteral",
3128
+ "Enum",
3129
+ ]);
3130
+ const membersOf = (union) => {
3131
+ const members = union.members;
3132
+ return Array.isArray(members) ? members : undefined;
3133
+ };
3134
+ const through = (members, segment, asDeclared) => {
3135
+ const out = [];
3136
+ for (const [index, member] of members.entries()) {
3137
+ const reached = reach(member, segment, asDeclared(index));
3138
+ if (reached === undefined)
3139
+ return undefined;
3140
+ out.push(...reached);
3141
+ }
3142
+ return out;
3143
+ };
3144
+ const reach = (schema, segment, asDeclared) => {
3145
+ const opt = optionalField(schema);
3146
+ if (opt?.union !== undefined) {
3147
+ // An optional union writes its first member substituted and the later ones as declared.
3148
+ const members = membersOf(opt.union)?.filter((m) => m.ast._tag !== "Undefined");
3149
+ if (members === undefined)
3150
+ return undefined;
3151
+ return through(members, segment, (index) => asDeclared || index > 0);
3152
+ }
3153
+ const inner = opt?.inner ?? schema;
3154
+ const fields = schemaFieldsOf(inner);
3155
+ if (fields !== undefined) {
3156
+ const child = typeof segment === "string" ? fields[segment] : undefined;
3157
+ return child === undefined ? [] : [{ schema: child, asDeclared }];
3158
+ }
3159
+ const ast = inner.ast;
3160
+ if (holdsNoPath.has(ast._tag))
3161
+ return [];
3162
+ if (SchemaAST.isUnion(ast)) {
3163
+ const members = membersOf(inner);
3164
+ return members === undefined ? undefined : through(members, segment, () => asDeclared);
3165
+ }
3166
+ if (SchemaAST.isArrays(ast)) {
3167
+ if (typeof segment !== "number")
3168
+ return [];
3169
+ const child = childAtSegment(inner, segment);
3170
+ if (child !== undefined)
3171
+ return [{ schema: child, asDeclared }];
3172
+ // A tuple with no element there and no rest holds nothing there.
3173
+ const s = inner;
3174
+ return Array.isArray(s.elements) && ast.rest.length === 0 ? [] : undefined;
3175
+ }
3176
+ if (SchemaAST.isObjects(ast)) {
3177
+ if (typeof segment !== "string")
3178
+ return [];
3179
+ const child = childAtSegment(inner, segment);
3180
+ return child === undefined ? undefined : [{ schema: child, asDeclared }];
3181
+ }
3182
+ return undefined;
3183
+ };
3184
+ let positions = [{ schema: top, asDeclared: false }];
3185
+ for (const segment of rest) {
3186
+ const next = [];
3187
+ for (const position of positions) {
3188
+ const reached = reach(position.schema, segment, position.asDeclared);
3189
+ if (reached === undefined)
3190
+ return undefined;
3191
+ for (const p of reached) {
3192
+ if (!next.some((q) => q.schema === p.schema && q.asDeclared === p.asDeclared))
3193
+ next.push(p);
3194
+ }
3195
+ }
3196
+ positions = next;
3197
+ }
3198
+ const holdsAnything = (schema) => {
3199
+ const tag = (optionalField(schema)?.inner ?? schema).ast._tag;
3200
+ return tag === "Unknown" || tag === "Any";
3201
+ };
3202
+ return positions.some((p) => holdsAnything(p.schema)) ? undefined : positions;
3203
+ };
3204
+ const operandForms = new Map();
3205
+ const formsAt = (segments) => {
3206
+ const key = JSON.stringify(segments);
3207
+ const cached = operandForms.get(key);
3208
+ if (cached !== undefined)
3209
+ return cached;
3210
+ const declared = declaredAt(segments);
3211
+ const head = segments[0];
3212
+ const forms = declared === undefined || declared.length === 0
3213
+ ? null
3214
+ : declared.flatMap((position) => {
3215
+ const original = position.schema;
3216
+ const stored = segments.length === 1
3217
+ ? recordFields[head]
3218
+ : position.asDeclared
3219
+ ? original
3220
+ : substituteSchemaDeep(original, { enforceChecks: true });
3221
+ if (stored === undefined)
3222
+ return [];
3223
+ const formOf = (from, to) => {
3224
+ const encode = leafAwareEncoder(from, to);
3225
+ const decode = Schema.decodeUnknownExit(to);
3226
+ return (value) => {
3227
+ const encoded = encode(value);
3228
+ if (decode(asStored(encoded))._tag !== "Success")
3229
+ return undefined;
3230
+ if (storable !== undefined && !storable(encoded))
3231
+ return undefined;
3232
+ return { stored: encoded };
3233
+ };
3234
+ };
3235
+ const value = formOf(original, stored);
3236
+ const originalElement = listElementOf(original);
3237
+ const storedElement = listElementOf(stored);
3238
+ const contained = containedOperand(containedKindOf(original), value, originalElement !== undefined && storedElement !== undefined
3239
+ ? formOf(originalElement, storedElement)
3240
+ : () => undefined);
3241
+ return [{ value, contained }];
3242
+ });
3243
+ const result = forms === null || forms.length === 0 ? null : forms;
3244
+ operandForms.set(key, result);
3245
+ return result;
3246
+ };
3247
+ /**
3248
+ * Every way to the end of a path through the model's schema, by the member it takes at each union
3249
+ * of several members on the way (`choices`, keyed by where the union is: the path up to the map
3250
+ * it reads). Within a union's member a path is followed as {@link childAtSegment} follows it.
3251
+ */
3252
+ const waysTo = (segments) => {
3253
+ const [head, ...rest] = segments;
3254
+ if (typeof head !== "string")
3255
+ return [];
3256
+ const start = refTargets[head] ?? modelFields[head];
3257
+ if (start === undefined)
3258
+ return [];
3259
+ const ways = [];
3260
+ const walk = (schema, depth, choices, asDeclared, parent) => {
3261
+ if (depth === rest.length) {
3262
+ ways.push({ choices, end: { _tag: "At", original: schema, asDeclared, parent } });
3263
+ return;
3264
+ }
3265
+ const segment = rest[depth];
3266
+ const opt = optionalField(schema);
3267
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3268
+ // Through a later member of an optional union, a path is written as declared, as
3269
+ // `originalAt` writes it ({@link writesFirstMemberOnly}).
3270
+ const first = opt?.union === undefined ? undefined : new Set(membersOf(opt.inner));
3271
+ const at = JSON.stringify(segments.slice(0, depth + 1));
3272
+ for (const member of members) {
3273
+ const chosen = members.length > 1 ? new Map(choices).set(at, member) : choices;
3274
+ const declared = asDeclared || (first !== undefined && !first.has(member));
3275
+ const child = childAtSegment(member, segment);
3276
+ if (child !== undefined)
3277
+ walk(child, depth + 1, chosen, declared, parentOf(member));
3278
+ else
3279
+ ways.push({ choices: chosen, end: missingAt(member, segment) });
3280
+ }
3281
+ };
3282
+ walk(start, 0, new Map(), false, "other");
3283
+ return ways;
3284
+ };
3285
+ const wayStored = new Map();
3286
+ const wayDeclared = (way) => {
3287
+ if (way.asDeclared)
3288
+ return way.original;
3289
+ const found = wayStored.get(way.original);
3290
+ if (found !== undefined)
3291
+ return found;
3292
+ const stored = substituteSchemaDeep(way.original, { enforceChecks: true });
3293
+ wayStored.set(way.original, stored);
3294
+ return stored;
3295
+ };
3296
+ const wayValidators = new Map();
3297
+ const wayValidator = (way) => {
3298
+ const stored = wayDeclared(way);
3299
+ const found = wayValidators.get(stored);
3300
+ if (found !== undefined)
3301
+ return found;
3302
+ const decode = Schema.decodeUnknownExit(stored);
3303
+ const fn = (encoded) => {
3304
+ const exit = decode(asStored(encoded));
3305
+ return exit._tag === "Success" ? undefined : exit.cause;
3306
+ };
3307
+ wayValidators.set(stored, fn);
3308
+ return fn;
3309
+ };
3310
+ const wayEncoders = new Map();
3311
+ const wayEncoder = (way) => {
3312
+ const stored = wayDeclared(way);
3313
+ const found = wayEncoders.get(stored);
3314
+ if (found !== undefined)
3315
+ return found;
3316
+ const fn = leafAwareEncoder(way.original, stored);
3317
+ wayEncoders.set(stored, fn);
3318
+ return fn;
3319
+ };
3320
+ /**
3321
+ * What one clause leaves at the node it ends at (`schema`, reached as `asDeclared` says, held by a
3322
+ * `parent`): read, not read, or `"unknown"`, which the schema can't judge — a copy, an
3323
+ * increment, an append, a whole field, a list position removed.
3324
+ */
3325
+ const endVerdict = (clause, at) => {
3326
+ if (clause._tag === "Other")
3327
+ return "unknown";
3328
+ if (clause._tag === "Value")
3329
+ return wayValidator(at)(clause.encoded) === undefined;
3330
+ if (typeof clause.segments[clause.segments.length - 1] !== "string")
3331
+ return "unknown";
3332
+ if (at.parent === "record")
3333
+ return true;
3334
+ if (at.parent === "struct")
3335
+ return rowCanLack(at.original);
3336
+ return "unknown";
3337
+ };
3338
+ /** The clauses going further from a node, by the segment they take next, in order. */
3339
+ const bySegment = (below) => {
3340
+ const groups = [];
3341
+ for (const { rest, clause } of below) {
3342
+ if (rest.length === 0)
3343
+ continue;
3344
+ const [segment, ...after] = rest;
3345
+ const group = groups.find(([held]) => held === segment);
3346
+ const entry = { rest: after, clause };
3347
+ if (group === undefined)
3348
+ groups.push([segment, [entry]]);
3349
+ else
3350
+ group[1].push(entry);
3351
+ }
3352
+ return groups;
3353
+ };
3354
+ /**
3355
+ * The judgement of an update's clauses inside one field (#238), at a node: `schema`, reached as
3356
+ * `asDeclared` says ({@link writesFirstMemberOnly}), held by a `parent`.
3357
+ *
3358
+ * `strict` asks whether what they leave is read WHATEVER the row holds there, at every union the
3359
+ * clauses pass, passed through or ended at, at any depth: at a union, either (a) every member
3360
+ * reads what they leave below it, or (b) they write every property of one member that reads it
3361
+ * ({@link fixes}), so that the update itself sets which member the row holds. A member without
3362
+ * the next segment reads past it (a plain struct), or holds nothing there for DynamoDB to write
3363
+ * into (a scalar, a list given a property, a struct given a position), which refuses the update
3364
+ * and leaves the row as it was. Anything the schema can't judge isn't read, and two clauses on
3365
+ * one path (which DynamoDB refuses) aren't either.
3366
+ *
3367
+ * Otherwise it asks whether SOME row reads what they leave: one member at each union reads every
3368
+ * clause below it, the member taken alike for every clause under the same union. Anything the
3369
+ * schema can't judge is taken as read, and a member holding nothing there as not reading it.
3370
+ */
3371
+ const judge = (schema, below, asDeclared, parent, strict) => {
3372
+ const ending = below.filter(({ rest }) => rest.length === 0);
3373
+ const further = bySegment(below);
3374
+ const at = { _tag: "At", original: schema, asDeclared, parent };
3375
+ if (strict && ending.length > 0 && (ending.length > 1 || further.length > 0))
3376
+ return false;
3377
+ for (const { clause } of ending) {
3378
+ const verdict = endVerdict(clause, at);
3379
+ if (verdict === "unknown" ? !strict : verdict)
3380
+ continue;
3381
+ return false;
3382
+ }
3383
+ if (further.length === 0)
3384
+ return true;
3385
+ const opt = optionalField(schema);
3386
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3387
+ // Through a later member of an optional union, a path is written as declared, as `originalAt`
3388
+ // writes it ({@link writesFirstMemberOnly}).
3389
+ const first = opt?.union === undefined ? undefined : new Set(membersOf(opt.inner));
3390
+ const declaredFor = (member) => asDeclared || (first !== undefined && !first.has(member));
3391
+ const reads = (member) => memberReads(member, further, declaredFor(member), strict);
3392
+ if (members.length === 1)
3393
+ return reads(members[0]);
3394
+ // Members that don't name every segment alike are written as 1.40.0 wrote them, by the names
3395
+ // given ({@link membersNamedExactly}): what they leave isn't judged.
3396
+ if (!membersNamedExactly(members))
3397
+ return !strict;
3398
+ if (!strict)
3399
+ return members.some(reads);
3400
+ return (members.every(reads) ||
3401
+ members.some((member) => fixes(member, further, declaredFor(member)) && reads(member)));
3402
+ };
3403
+ /** {@link judge} under one member, for the clauses going further, by segment. */
3404
+ const memberReads = (member, further, asDeclared, strict) => further.every(([segment, below]) => {
3405
+ const read = readAs(member);
3406
+ const child = childAtSegment(read, segment);
3407
+ if (child !== undefined)
3408
+ return judge(child, below, asDeclared, parentOf(read), strict);
3409
+ const end = missingAt(read, segment);
3410
+ if (strict)
3411
+ return end._tag !== "Unknown";
3412
+ // A clause the schema can't judge is taken as read, wherever the member leaves it.
3413
+ if (below.every(({ clause }) => clause._tag === "Other"))
3414
+ return true;
3415
+ return end._tag === "Unread" || end._tag === "Unknown";
3416
+ });
3417
+ /**
3418
+ * Whether the clauses going further from a union's member write every property of it (#238):
3419
+ * each set or removed, or, for a property holding a plain struct, every property of THAT written
3420
+ * in turn, or for one holding a union, every property of one of its members that reads what they
3421
+ * leave. What the member holds after the update is then all theirs, whatever the row held. A
3422
+ * member that isn't a plain struct isn't known to be.
3423
+ */
3424
+ const fixes = (member, further, asDeclared) => {
3425
+ const read = readAs(member);
3426
+ if (parentOf(read) !== "struct")
3427
+ return false;
3428
+ return read.ast.propertySignatures.every((property) => {
3429
+ const group = further.find(([segment]) => segment === property.name);
3430
+ if (group === undefined)
3431
+ return false;
3432
+ const child = childAtSegment(read, property.name);
3433
+ return child !== undefined && fixedBy(child, group[1], asDeclared);
3434
+ });
3435
+ };
3436
+ /** Whether the clauses below a node set all of it ({@link fixes}). */
3437
+ const fixedBy = (schema, below, asDeclared) => {
3438
+ const ending = below.filter(({ rest }) => rest.length === 0);
3439
+ if (ending.length > 0) {
3440
+ return ending.length === 1 && below.length === 1 && ending[0].clause._tag !== "Other";
3441
+ }
3442
+ const further = bySegment(below);
3443
+ const opt = optionalField(schema);
3444
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3445
+ const first = opt?.union === undefined ? undefined : new Set(membersOf(opt.inner));
3446
+ if (members.length > 1 && !membersNamedExactly(members))
3447
+ return false;
3448
+ return members.some((member) => {
3449
+ const declared = asDeclared || (first !== undefined && !first.has(member));
3450
+ return (fixes(member, further, declared) &&
3451
+ (members.length === 1 || memberReads(member, further, declared, true)));
3452
+ });
3453
+ };
3454
+ const reads = (clauses, strict) => {
3455
+ const head = clauses[0]?.segments[0];
3456
+ const start = typeof head === "string" ? (refTargets[head] ?? modelFields[head]) : undefined;
3457
+ // A field the walk can't follow is one the schema can't judge.
3458
+ if (start === undefined || clauses.some((clause) => clause.segments[0] !== head)) {
3459
+ return !strict;
3460
+ }
3461
+ const below = clauses.map((clause) => ({ rest: clause.segments.slice(1), clause }));
3462
+ return judge(start, below, false, "other", strict);
3463
+ };
3464
+ const readDecoders = new WeakMap();
3465
+ const readDecoder = (schema) => {
3466
+ const found = readDecoders.get(schema);
3467
+ if (found !== undefined)
3468
+ return found;
3469
+ const decode = Schema.decodeUnknownExit(schema);
3470
+ const fn = (value) => decode(asStored(value))._tag === "Success";
3471
+ readDecoders.set(schema, fn);
3472
+ return fn;
3473
+ };
3474
+ /**
3475
+ * A class as a read decodes it: from the struct of its fields (`from`), which a path into it
3476
+ * walks. Any other schema as it is.
3477
+ */
3478
+ const readSide = (schema) => {
3479
+ const { from, to } = schema;
3480
+ return schemaFieldsOf(schema) === undefined &&
3481
+ isSchemaLike(from) &&
3482
+ schemaFieldsOf(from) !== undefined &&
3483
+ isSchemaLike(to) &&
3484
+ SchemaAST.isDeclaration(to.ast)
3485
+ ? from
3486
+ : schema;
3487
+ };
3488
+ /** The READ schema's nodes at the end of a path: one by each member of each union on the way. */
3489
+ const readNodesAt = (segments) => {
3490
+ const [head, ...rest] = segments;
3491
+ if (typeof head !== "string" || !Object.hasOwn(readFields, head))
3492
+ return [];
3493
+ const nodes = [];
3494
+ const walk = (schema, depth) => {
3495
+ const opt = optionalField(schema);
3496
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3497
+ if (depth === rest.length) {
3498
+ nodes.push(...members);
3499
+ return;
3500
+ }
3501
+ for (const member of members) {
3502
+ const child = childAtSegment(readSide(member), rest[depth]);
3503
+ if (child !== undefined)
3504
+ walk(child, depth + 1);
3505
+ }
3506
+ };
3507
+ walk(readFields[head], 0);
3508
+ return nodes;
3509
+ };
2176
3510
  return {
3511
+ operand: (segments, value, kind) => {
3512
+ const forms = formsAt(segments);
3513
+ if (forms === null)
3514
+ return value;
3515
+ let chosen;
3516
+ for (const form of forms) {
3517
+ // A position that can't hold the value holds no row it could match.
3518
+ const stored = kind === "value" ? form.value(value) : form.contained(value);
3519
+ if (stored === undefined)
3520
+ continue;
3521
+ if (chosen !== undefined && !sameValue(chosen.stored, stored.stored))
3522
+ return value;
3523
+ chosen = stored;
3524
+ }
3525
+ return chosen === undefined ? value : chosen.stored;
3526
+ },
3527
+ readsAsGiven: (segments, value, kind) => {
3528
+ const nodes = readNodesAt(segments);
3529
+ if (kind === "value")
3530
+ return nodes.some((node) => readDecoder(node)(value));
3531
+ if (!Array.isArray(value))
3532
+ return false;
3533
+ return nodes.some((node) => {
3534
+ const element = listElementOf(node);
3535
+ return element !== undefined && value.every((each) => readDecoder(element)(each));
3536
+ });
3537
+ },
3538
+ pathSet: (segments, value) => {
3539
+ const first = schemaAt(segments);
3540
+ const encoded = encoderFor(`v:${JSON.stringify(segments)}`, () => first);
3541
+ const firstValidator = validatorFor(`v:${JSON.stringify(segments)}`, () => first?.stored);
3542
+ const written = encoded === null ? value : encoded(value);
3543
+ const check = (read) => (firstValidator === null ? undefined : firstValidator(read));
3544
+ const issue = check(written);
3545
+ if (issue === undefined)
3546
+ return { encoded: written, issue, otherWay: false, check };
3547
+ for (const way of waysTo(segments)) {
3548
+ if (way.end._tag !== "At")
3549
+ continue;
3550
+ const other = wayEncoder(way.end)(value);
3551
+ const taken = wayValidator(way.end);
3552
+ if (taken(other) === undefined) {
3553
+ return {
3554
+ encoded: other,
3555
+ issue: undefined,
3556
+ otherWay: true,
3557
+ refusedBefore: issue,
3558
+ check: taken,
3559
+ };
3560
+ }
3561
+ }
3562
+ return { encoded: written, issue, otherWay: false, check };
3563
+ },
3564
+ reads,
3565
+ passesUnion: (segments) => waysTo(segments).some((way) => way.choices.size > 0),
3566
+ checks: (segments, kind) => {
3567
+ const at = schemaAt(segments);
3568
+ if (at === undefined)
3569
+ return false;
3570
+ if (kind === "value")
3571
+ return true;
3572
+ // Elements are checked one by one: only a list that checks nothing of its own, and isn't
3573
+ // transformed as a whole, reads what they leave as they're checked.
3574
+ const opt = optionalField(at.stored);
3575
+ const lists = opt?.union !== undefined ? membersOf(opt.union) : [opt?.inner ?? at.stored];
3576
+ return (listElementOf(at.stored) !== undefined &&
3577
+ lists.every((list) => !SchemaAST.isArrays(list.ast) ||
3578
+ (plainNode(list.ast) && list.ast.encoding === undefined)));
3579
+ },
2177
3580
  validate: (segments, encoded) => {
2178
3581
  const fn = validatorFor(`v:${JSON.stringify(segments)}`, () => schemaAt(segments)?.stored);
2179
3582
  return fn === null ? undefined : fn(encoded);