@effect-dynamodb/schema 1.40.0 → 1.42.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 (104) hide show
  1. package/dist/Aggregate.d.ts.map +1 -1
  2. package/dist/Aggregate.js +4 -1
  3. package/dist/Aggregate.js.map +1 -1
  4. package/dist/DynamoModel.d.ts +35 -7
  5. package/dist/DynamoModel.d.ts.map +1 -1
  6. package/dist/DynamoModel.js +34 -16
  7. package/dist/DynamoModel.js.map +1 -1
  8. package/dist/DynamoSchema.d.ts +20 -0
  9. package/dist/DynamoSchema.d.ts.map +1 -1
  10. package/dist/DynamoSchema.js.map +1 -1
  11. package/dist/Entity.d.ts +18 -6
  12. package/dist/Entity.d.ts.map +1 -1
  13. package/dist/Entity.js +97 -34
  14. package/dist/Entity.js.map +1 -1
  15. package/dist/Errors.d.ts +61 -4
  16. package/dist/Errors.d.ts.map +1 -1
  17. package/dist/Errors.js +83 -6
  18. package/dist/Errors.js.map +1 -1
  19. package/dist/KeyComposer.d.ts +55 -9
  20. package/dist/KeyComposer.d.ts.map +1 -1
  21. package/dist/KeyComposer.js +157 -58
  22. package/dist/KeyComposer.js.map +1 -1
  23. package/dist/VectorIndex.d.ts.map +1 -1
  24. package/dist/VectorIndex.js +5 -4
  25. package/dist/VectorIndex.js.map +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +1 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/internal/AggregateSchemas.d.ts +131 -6
  31. package/dist/internal/AggregateSchemas.d.ts.map +1 -1
  32. package/dist/internal/AggregateSchemas.js +250 -31
  33. package/dist/internal/AggregateSchemas.js.map +1 -1
  34. package/dist/internal/CompositeCodec.d.ts +26 -4
  35. package/dist/internal/CompositeCodec.d.ts.map +1 -1
  36. package/dist/internal/CompositeCodec.js +127 -25
  37. package/dist/internal/CompositeCodec.js.map +1 -1
  38. package/dist/internal/EffectInstances.d.ts +8 -2
  39. package/dist/internal/EffectInstances.d.ts.map +1 -1
  40. package/dist/internal/EffectInstances.js +33 -27
  41. package/dist/internal/EffectInstances.js.map +1 -1
  42. package/dist/internal/EntityPacked.d.ts.map +1 -1
  43. package/dist/internal/EntityPacked.js +5 -4
  44. package/dist/internal/EntityPacked.js.map +1 -1
  45. package/dist/internal/EntitySchemas.d.ts +163 -3
  46. package/dist/internal/EntitySchemas.d.ts.map +1 -1
  47. package/dist/internal/EntitySchemas.js +972 -85
  48. package/dist/internal/EntitySchemas.js.map +1 -1
  49. package/dist/internal/EntityTypes.d.ts +53 -20
  50. package/dist/internal/EntityTypes.d.ts.map +1 -1
  51. package/dist/internal/InstanceReads.d.ts +7 -0
  52. package/dist/internal/InstanceReads.d.ts.map +1 -1
  53. package/dist/internal/InstanceReads.js +47 -29
  54. package/dist/internal/InstanceReads.js.map +1 -1
  55. package/dist/internal/KeyReadings.d.ts +30 -0
  56. package/dist/internal/KeyReadings.d.ts.map +1 -0
  57. package/dist/internal/KeyReadings.js +99 -0
  58. package/dist/internal/KeyReadings.js.map +1 -0
  59. package/dist/internal/KeyText136.d.ts.map +1 -1
  60. package/dist/internal/KeyText136.js +6 -4
  61. package/dist/internal/KeyText136.js.map +1 -1
  62. package/dist/internal/LostValues.d.ts +50 -0
  63. package/dist/internal/LostValues.d.ts.map +1 -0
  64. package/dist/internal/LostValues.js +465 -0
  65. package/dist/internal/LostValues.js.map +1 -0
  66. package/dist/internal/ObjectKeyText.d.ts +29 -0
  67. package/dist/internal/ObjectKeyText.d.ts.map +1 -0
  68. package/dist/internal/ObjectKeyText.js +50 -0
  69. package/dist/internal/ObjectKeyText.js.map +1 -0
  70. package/dist/internal/OwnNames.d.ts +205 -0
  71. package/dist/internal/OwnNames.d.ts.map +1 -0
  72. package/dist/internal/OwnNames.js +415 -0
  73. package/dist/internal/OwnNames.js.map +1 -0
  74. package/dist/internal/PackedCodec.d.ts +7 -8
  75. package/dist/internal/PackedCodec.d.ts.map +1 -1
  76. package/dist/internal/PackedCodec.js +81 -55
  77. package/dist/internal/PackedCodec.js.map +1 -1
  78. package/dist/internal/RestoredKeyText.d.ts +10 -0
  79. package/dist/internal/RestoredKeyText.d.ts.map +1 -0
  80. package/dist/internal/RestoredKeyText.js +50 -0
  81. package/dist/internal/RestoredKeyText.js.map +1 -0
  82. package/dist/internal/SchemaAccessors.d.ts +132 -12
  83. package/dist/internal/SchemaAccessors.d.ts.map +1 -1
  84. package/dist/internal/SchemaAccessors.js +779 -56
  85. package/dist/internal/SchemaAccessors.js.map +1 -1
  86. package/dist/internal/SchemaIssue.d.ts +21 -0
  87. package/dist/internal/SchemaIssue.d.ts.map +1 -0
  88. package/dist/internal/SchemaIssue.js +34 -0
  89. package/dist/internal/SchemaIssue.js.map +1 -0
  90. package/dist/internal/SharedKeyAttribute.d.ts.map +1 -1
  91. package/dist/internal/SharedKeyAttribute.js +2 -1
  92. package/dist/internal/SharedKeyAttribute.js.map +1 -1
  93. package/dist/internal/StoredForm.d.ts +139 -0
  94. package/dist/internal/StoredForm.d.ts.map +1 -0
  95. package/dist/internal/StoredForm.js +503 -0
  96. package/dist/internal/StoredForm.js.map +1 -0
  97. package/dist/internal/ZOrderCurve.d.ts.map +1 -1
  98. package/dist/internal/ZOrderCurve.js +2 -1
  99. package/dist/internal/ZOrderCurve.js.map +1 -1
  100. package/dist/internal/ZoneKeyText.d.ts +55 -0
  101. package/dist/internal/ZoneKeyText.d.ts.map +1 -0
  102. package/dist/internal/ZoneKeyText.js +264 -0
  103. package/dist/internal/ZoneKeyText.js.map +1 -0
  104. package/package.json +4 -4
@@ -3,12 +3,15 @@
3
3
  *
4
4
  * Extracted from Entity.ts for decomposition. Not part of the public API.
5
5
  */
6
- import { DateTime, Effect, Option, 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
8
  import { reviveMarshalledDateTime } from "./EffectInstances.js";
9
9
  import { readingInstances } from "./InstanceReads.js";
10
+ import { hasOwnName, ownValue, PROTO_ENTRY, setOwn } from "./OwnNames.js";
10
11
  import { BETA_DATE_MARKER, DATE_MARKER } from "./PackedCodec.js";
11
- import { absentStored, firstTypeParameterAst, getSchemaFields, holdsAbsentValue, holdsPlainBigint, holdsUndefined, isDecodingDefault, isSchemaLike, lackDecision, numericTypeWithStringEncoding, storedList, transformWireKind as transformWireKindImpl, } from "./SchemaAccessors.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";
12
15
  import { parseZonedIso } from "./ZonedIso.js";
13
16
  /**
14
17
  * Resolve the effective DynamoEncoding for a model-declared field, applying
@@ -37,9 +40,9 @@ export const resolveFieldEncoding = (fieldSchema, override) => {
37
40
  export const buildFieldEncodings = (modelFields, configuredAttributes) => {
38
41
  const encodings = {};
39
42
  for (const [fieldName, fieldSchema] of Object.entries(modelFields)) {
40
- const encoding = resolveFieldEncoding(fieldSchema, configuredAttributes[fieldName]?.encoding);
43
+ const encoding = resolveFieldEncoding(fieldSchema, ownValue(configuredAttributes, fieldName)?.encoding);
41
44
  if (encoding)
42
- encodings[fieldName] = encoding;
45
+ setOwn(encodings, fieldName, encoding);
43
46
  }
44
47
  return encodings;
45
48
  };
@@ -138,7 +141,7 @@ export const resolveSystemFields = (timestamps, versioned, timeSeries, modelFiel
138
141
  // This preserves existing patterns where users declare `createdAt`
139
142
  // as a plain string composite.
140
143
  let createdAtCollision = false;
141
- if (createdAt && createdAt in modelFields) {
144
+ if (createdAt && hasOwnName(modelFields, createdAt)) {
142
145
  const modelEncoding = resolveFieldEncoding(modelFields[createdAt], configuredAttributes[createdAt]?.encoding);
143
146
  if (modelEncoding) {
144
147
  createdAtEncoding = modelEncoding;
@@ -151,7 +154,7 @@ export const resolveSystemFields = (timestamps, versioned, timeSeries, modelFiel
151
154
  }
152
155
  }
153
156
  let updatedAtCollision = false;
154
- if (updatedAt && updatedAt in modelFields) {
157
+ if (updatedAt && hasOwnName(modelFields, updatedAt)) {
155
158
  const modelEncoding = resolveFieldEncoding(modelFields[updatedAt], configuredAttributes[updatedAt]?.encoding);
156
159
  if (modelEncoding) {
157
160
  updatedAtEncoding = modelEncoding;
@@ -162,7 +165,7 @@ export const resolveSystemFields = (timestamps, versioned, timeSeries, modelFiel
162
165
  updatedAtEncoding = null;
163
166
  }
164
167
  }
165
- const versionCollision = !!(version && version in modelFields);
168
+ const versionCollision = !!(version && hasOwnName(modelFields, version));
166
169
  return {
167
170
  createdAt,
168
171
  createdAtEncoding,
@@ -415,7 +418,7 @@ const toWirePrimitive = (input, encoding) => {
415
418
  switch (encoding.storage) {
416
419
  case "string":
417
420
  if (encoding.domain === "DateTime.Zoned" && zoned)
418
- return DateTime.formatIsoZoned(zoned);
421
+ return zonedIsoText(zoned);
419
422
  return new Date(epochMs).toISOString();
420
423
  case "epochMs":
421
424
  return epochMs;
@@ -1120,6 +1123,7 @@ const childOptions = (container, deeper, index, opts) => {
1120
1123
  strictWireKind: true,
1121
1124
  collidingKinds,
1122
1125
  ...(opts?.unionDateOverride ? { dateEncodingOverride: opts.unionDateOverride } : {}),
1126
+ ...(opts?.unionDateOverride && opts.readsDeclaredStorage ? { readsDeclaredStorage: true } : {}),
1123
1127
  };
1124
1128
  };
1125
1129
  /** The options an optional wrapper hands its inner schema: it is transparent. */
@@ -1191,6 +1195,7 @@ const throughOptional = (opts) => {
1191
1195
  ...(opts.unionDateOverride ? { unionDateOverride: opts.unionDateOverride } : {}),
1192
1196
  ...(opts.collidingKinds ? { collidingKinds: opts.collidingKinds } : {}),
1193
1197
  ...(opts.dateEncodingOverride ? { dateEncodingOverride: opts.dateEncodingOverride } : {}),
1198
+ ...(opts.readsDeclaredStorage ? { readsDeclaredStorage: true } : {}),
1194
1199
  }
1195
1200
  : deeper;
1196
1201
  };
@@ -1228,14 +1233,46 @@ const selfDatePlan = (schema, opts) => {
1228
1233
  }
1229
1234
  return { encoding, canonicalOnly };
1230
1235
  };
1236
+ /**
1237
+ * Under `readsDeclaredStorage`, in a union: the plan of the storage the date declares, where the
1238
+ * override reads another kind of value (see `readsDeclaredStorage`). Out of a union the override's
1239
+ * transform reads a value by its kind already, text as ISO text and a number in its own scale.
1240
+ */
1241
+ const declaredStoragePlan = (schema, opts) => {
1242
+ if (!opts?.readsDeclaredStorage || !opts.strictWireKind || !opts.dateEncodingOverride) {
1243
+ return undefined;
1244
+ }
1245
+ const own = getEncoding(schema) ?? inferDefaultEncoding(schema);
1246
+ const text = (encoding) => encoding.storage === "string";
1247
+ if (own === undefined || text(own) === text(opts.dateEncodingOverride))
1248
+ return undefined;
1249
+ try {
1250
+ return selfDatePlan(schema, { ...opts, dateEncodingOverride: undefined });
1251
+ }
1252
+ catch {
1253
+ // An epoch beside a number member (EDD-9058) is refused where it's the storage, not here.
1254
+ return undefined;
1255
+ }
1256
+ };
1231
1257
  const selfDateSubstitute = (schema, opts) => {
1232
1258
  const plan = selfDatePlan(schema, opts);
1233
1259
  if (plan === undefined)
1234
1260
  return schema;
1235
- return buildDateTransform(plan.encoding, {
1261
+ const substitute = buildDateTransform(plan.encoding, {
1236
1262
  strictWireKind: opts?.strictWireKind,
1237
1263
  canonicalOnly: plan.canonicalOnly,
1238
1264
  });
1265
+ // Encodes as the override, and reads either form, as an aggregate's union member does.
1266
+ const declared = declaredStoragePlan(schema, opts);
1267
+ return declared === undefined
1268
+ ? substitute
1269
+ : Schema.Union([
1270
+ substitute,
1271
+ buildDateTransform(declared.encoding, {
1272
+ strictWireKind: true,
1273
+ canonicalOnly: declared.canonicalOnly,
1274
+ }),
1275
+ ]);
1239
1276
  };
1240
1277
  /**
1241
1278
  * Whether a union member is a self date that claims only its canonical form
@@ -1247,8 +1284,10 @@ const selfDateSubstitute = (schema, opts) => {
1247
1284
  */
1248
1285
  const isCanonicalDateMember = (member, opts) => {
1249
1286
  const inner = optionalField(member)?.inner ?? member;
1250
- if (isSelfDateSchema(inner))
1251
- return selfDatePlan(inner, opts)?.canonicalOnly === true;
1287
+ if (isSelfDateSchema(inner)) {
1288
+ return (selfDatePlan(inner, opts)?.canonicalOnly === true ||
1289
+ declaredStoragePlan(inner, opts)?.canonicalOnly === true);
1290
+ }
1252
1291
  // A nested union holding such a member (`NullOr(DateTimeUtc)` next to a
1253
1292
  // `String`) is decoded first for the same reason.
1254
1293
  const container = walkedContainer(inner);
@@ -1332,6 +1371,61 @@ const absentAsDeclared = (schema, withUndefined) => {
1332
1371
  ? Effect.succeed(input)
1333
1372
  : read({}).pipe(Effect.map(({ field }) => Option.some(field)), Effect.mapError((error) => error.issue)));
1334
1373
  };
1374
+ /** `undefined`, or a set holding nothing once `undefined` is removed: no attribute is stored. */
1375
+ const storesNothing = (value) => value === undefined ||
1376
+ (value instanceof Set && [...value].every((element) => element === undefined));
1377
+ /**
1378
+ * The annotation marking a field {@link protoAbsent} made: an annotation, not identity, since the
1379
+ * modules reading it may be loaded twice (the package's source beside its build).
1380
+ */
1381
+ const PROTO_ABSENT = Symbol.for("@effect-dynamodb/schema/ProtoAbsent");
1382
+ /** Whether `field` is one {@link protoAbsent} made. */
1383
+ export const isProtoAbsent = (field) => {
1384
+ const ast = field?.ast;
1385
+ return ast?.annotations?.[PROTO_ABSENT] === true;
1386
+ };
1387
+ /**
1388
+ * A field named `__proto__`, stored under that name, of a struct the library builds over the
1389
+ * model's (#239). 1.40.0 built each such struct by assignment, `fields[name] = schema`, and
1390
+ * assigning `__proto__` set the map's prototype instead: the field wasn't in the struct. A payload
1391
+ * leaving it out was taken, and one giving it lost the value, which the parser dropped. Here a
1392
+ * payload leaving it out, or giving a value that stores nothing (`undefined`, a `None` encoded as
1393
+ * `undefined`, a set holding nothing), is read as 1.40.0 read it: the field isn't in what the struct
1394
+ * makes. A value that stores something is refused (`EDD-9165`), since no write can store it and no
1395
+ * read can return it. What a value stores is what the field, as declared, makes of it on the way to
1396
+ * storage: encoded, or as it is where it's already in its stored form.
1397
+ */
1398
+ const protoAbsent = (field) => {
1399
+ const holder = Schema.Struct({ v: field });
1400
+ const decode = Schema.decodeUnknownExit(holder);
1401
+ const encode = Schema.encodeUnknownExit(holder);
1402
+ /** The value as stored, `undefined` for none; the value as given where the field takes neither. */
1403
+ const stored = (value, encoding) => {
1404
+ const asIs = () => Exit.isSuccess(decode({ v: value })) ? Exit.succeed({ v: value }) : undefined;
1405
+ const toStored = () => {
1406
+ const encoded = encode({ v: value });
1407
+ return Exit.isSuccess(encoded) ? encoded : undefined;
1408
+ };
1409
+ for (const attempt of encoding ? [toStored, asIs] : [asIs, toStored]) {
1410
+ const held = attempt();
1411
+ if (held !== undefined && Exit.isSuccess(held)) {
1412
+ return Object.hasOwn(held.value, "v") ? held.value.v : undefined;
1413
+ }
1414
+ }
1415
+ return value;
1416
+ };
1417
+ const judge = (encoding) => SchemaGetter.transformOptionalEffect((given) => Option.isNone(given) ||
1418
+ storesNothing(given.value) ||
1419
+ storesNothing(stored(given.value, encoding))
1420
+ ? Effect.succeed(Option.none())
1421
+ : Effect.fail(new SchemaIssue.InvalidValue({ message: `${PROTO_ENTRY} [EDD-9165]` }, Option.some(given.value))));
1422
+ return Schema.optionalKey(Schema.Unknown.pipe(Schema.decodeTo(Schema.Unknown.annotate({ [PROTO_ABSENT]: true }), new SchemaTransformation.Transformation(judge(false), judge(true)))));
1423
+ };
1424
+ /**
1425
+ * `field` under `name`: where that's `__proto__`, stored so, the field {@link protoAbsent} makes of
1426
+ * the one the model `declared`, whose encoding is the stored form.
1427
+ */
1428
+ const fieldNamed = (name, field, declared, storedAsProto = true) => name === "__proto__" && storedAsProto && !isProtoAbsent(field) ? protoAbsent(declared) : field;
1335
1429
  /**
1336
1430
  * The field, reading an absent attribute as the value it stands for (`absentStored`), which is what
1337
1431
  * its `declared` schema says, if the field is that schema read some other way.
@@ -1340,7 +1434,10 @@ const readingAbsent = (field, declared = field) => {
1340
1434
  const reading = absentStored(declared);
1341
1435
  if (reading === undefined)
1342
1436
  return field;
1343
- return field.pipe(Schema.withDecodingDefaultKey(Effect.succeed(reading.stored)));
1437
+ // A stored value is read as `field` alone (`ReadsAbsentAs`): the default runs where none is.
1438
+ return field
1439
+ .pipe(Schema.withDecodingDefaultKey(Effect.succeed(reading.stored)))
1440
+ .annotate({ [ReadsAbsentAs]: field.ast });
1344
1441
  };
1345
1442
  /** Whether a struct field anywhere in the schema reads an absent attribute as a value. */
1346
1443
  const holdsAbsentRead = (schema) => {
@@ -1416,6 +1513,10 @@ const refusesUndefinedPositions = (schema, opts) => opts?.enforceChecks === true
1416
1513
  const needsDeepSubstitution = (schema, opts) => {
1417
1514
  if (schema == null || schema.ast == null)
1418
1515
  return false;
1516
+ // A ref held as less than its class (`refHeldTarget`) is another schema than the field it
1517
+ // re-points, whatever its leaves.
1518
+ if (heldStructs.has(schema))
1519
+ return true;
1419
1520
  if (opts?.undefinedPositionsOnly)
1420
1521
  return holdsUndefinedPosition(schema);
1421
1522
  if (opts?.absentReads === "only")
@@ -1766,21 +1867,26 @@ export const substituteSchemaDeep = (schema, opts) => {
1766
1867
  // by the recursion (and class instance identity is preserved).
1767
1868
  const fields = schemaFieldsOf(schema);
1768
1869
  if (fields) {
1870
+ // A field named `__proto__` is one 1.40.0's rebuilt struct didn't hold (`protoAbsent`).
1769
1871
  const subFields = {};
1770
1872
  for (const [name, field] of Object.entries(fields)) {
1771
1873
  if (opts?.skipTopLevel?.has(name) === true) {
1772
- subFields[name] = field;
1874
+ setOwn(subFields, name, fieldNamed(name, field, field));
1773
1875
  continue;
1774
1876
  }
1775
1877
  const refTarget = opts?.resolveRef?.(name, field);
1776
1878
  if (refTarget !== undefined) {
1777
1879
  const fieldOpt = optionalField(field);
1778
1880
  const sub = substituteSchemaDeep(refTarget, atField(deeper, opts, name));
1779
- subFields[name] = fieldOpt ? fieldOpt.rewrap(sub) : sub;
1881
+ setOwn(subFields, name, fieldNamed(name, fieldOpt ? fieldOpt.rewrap(sub) : sub, field));
1780
1882
  }
1781
1883
  else {
1782
- const sub = substituteSchemaDeep(field, atField(deeper, opts, name));
1783
- subFields[name] = opts?.absentReads ? readingAbsent(sub) : sub;
1884
+ const sub = substituteSchemaDeep(field, withConfiguredStorage(atField(deeper, opts, name), name, field, ownValue(opts?.configuredStorage, name)));
1885
+ setOwn(subFields, name, name === "__proto__"
1886
+ ? fieldNamed(name, sub, field)
1887
+ : opts?.absentReads
1888
+ ? readingAbsent(sub)
1889
+ : sub);
1784
1890
  }
1785
1891
  }
1786
1892
  const plainStruct = Schema.Struct(subFields);
@@ -2036,6 +2142,7 @@ export const writingTuplePositions = (schema) => substituteSchemaDeep(schema, {
2036
2142
  */
2037
2143
  export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2038
2144
  const out = {};
2145
+ const storedAsProto = options?.protoRenamed !== true;
2039
2146
  const deep = {
2040
2147
  ...(options?.legacyReads ? { legacyReads: true } : {}),
2041
2148
  ...(options?.enforceChecks ? { enforceChecks: true } : {}),
@@ -2047,18 +2154,18 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2047
2154
  // tolerant date transform so the encode pipeline produces the right
2048
2155
  // wire primitive.
2049
2156
  if (isSelfDateSchema(schema)) {
2050
- const enc = fieldEncodings[name];
2157
+ const enc = ownValue(fieldEncodings, name);
2051
2158
  if (enc) {
2052
- out[name] = buildDateTransform(enc);
2159
+ setOwn(out, name, fieldNamed(name, buildDateTransform(enc), schema, storedAsProto));
2053
2160
  continue;
2054
2161
  }
2055
2162
  }
2056
2163
  // …also beneath a decoding default, which is kept on top (#133).
2057
2164
  const defaulted = decodingDefaultField(schema);
2058
2165
  if (defaulted !== undefined && isSelfDateSchema(defaulted.inner)) {
2059
- const enc = fieldEncodings[name];
2166
+ const enc = ownValue(fieldEncodings, name);
2060
2167
  if (enc) {
2061
- out[name] = defaulted.rewrap(buildDateTransform(enc));
2168
+ setOwn(out, name, fieldNamed(name, defaulted.rewrap(buildDateTransform(enc)), schema, storedAsProto));
2062
2169
  continue;
2063
2170
  }
2064
2171
  }
@@ -2067,7 +2174,7 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2067
2174
  // transform so the round-trip works for storage.
2068
2175
  const redactedInner = tryGetRedactedInner(schema);
2069
2176
  if (redactedInner !== undefined) {
2070
- out[name] = buildRedactedSubstitute(schema, redactedInner);
2177
+ setOwn(out, name, fieldNamed(name, buildRedactedSubstitute(schema, redactedInner), schema, storedAsProto));
2071
2178
  continue;
2072
2179
  }
2073
2180
  // 3. Default: recurse for nested substitution. Pattern B transforms
@@ -2079,16 +2186,18 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2079
2186
  // identity, and returns the schema unchanged when nothing nested needs it.
2080
2187
  // A configured storage override on a UNION field (`NullOr(DateTimeUtc)`)
2081
2188
  // is applied to the union's self-date member (#133).
2082
- const unionOverride = unionDateOverride(name, schema, fieldEncodings[name]);
2083
- out[name] = substituteSchemaDeep(schema, {
2189
+ const unionOverride = unionDateOverride(name, schema, ownValue(fieldEncodings, name));
2190
+ setOwn(out, name, fieldNamed(name, substituteSchemaDeep(schema, {
2084
2191
  ...deep,
2085
2192
  path: [name],
2086
2193
  ...(unionOverride === undefined ? {} : { unionDateOverride: unionOverride }),
2087
- });
2194
+ }), schema, storedAsProto));
2088
2195
  }
2089
2196
  if (options?.absentReads) {
2090
- for (const [name, field] of Object.entries(out))
2091
- out[name] = readingAbsent(field);
2197
+ for (const [name, field] of Object.entries(out)) {
2198
+ if (!isProtoAbsent(field))
2199
+ setOwn(out, name, readingAbsent(field));
2200
+ }
2092
2201
  }
2093
2202
  return out;
2094
2203
  };
@@ -2119,6 +2228,39 @@ const unionDateOverride = (name, schema, encoding) => {
2119
2228
  }
2120
2229
  return encoding;
2121
2230
  };
2231
+ /**
2232
+ * @internal The storage `DynamoModel.configure` gives a model's fields (`storedAs` a date schema),
2233
+ * by name, or `undefined` for a model with none. What a ref to the model's entity holds such a
2234
+ * field in (`DeepSubstitutionOptions.configuredStorage`).
2235
+ */
2236
+ export const configuredStorageOf = (model) => {
2237
+ if (!isConfiguredModel(model))
2238
+ return undefined;
2239
+ const storage = {};
2240
+ for (const [name, attribute] of Object.entries(model.attributes)) {
2241
+ if (attribute.encoding !== undefined)
2242
+ setOwn(storage, name, attribute.encoding);
2243
+ }
2244
+ return Object.keys(storage).length === 0 ? undefined : storage;
2245
+ };
2246
+ /**
2247
+ * A field's substitution options with the storage `encoding` its model's `DynamoModel.configure`
2248
+ * gives it, where its entity applies that storage ({@link substituteSchemas} decides by the same
2249
+ * tests): a date (a `Schema.optionalKey` one too, or one beneath a decoding default), or a union's
2250
+ * date member. Elsewhere, and without one, `options` as given. A read (`legacyReads`) also takes
2251
+ * the form the date's own storage writes (`readsDeclaredStorage`).
2252
+ */
2253
+ const withConfiguredStorage = (options, name, field, encoding) => {
2254
+ if (encoding === undefined)
2255
+ return options;
2256
+ const reads = options.legacyReads ? { readsDeclaredStorage: true } : {};
2257
+ const defaulted = decodingDefaultField(field);
2258
+ if (isSelfDateSchema(field) || (defaulted !== undefined && isSelfDateSchema(defaulted.inner))) {
2259
+ return { ...options, dateEncodingOverride: encoding, ...reads };
2260
+ }
2261
+ const union = unionDateOverride(name, field, encoding);
2262
+ return union === undefined ? options : { ...options, unionDateOverride: union, ...reads };
2263
+ };
2122
2264
  /**
2123
2265
  * Validate that no model field combines a transform schema with a storage
2124
2266
  * override. The two configuration paths are mutually exclusive: either declare
@@ -2149,7 +2291,7 @@ export const validateNoTransformOverride = (modelFields, configuredAttributes) =
2149
2291
  if (!isDateTransform(schema))
2150
2292
  continue;
2151
2293
  // 1. ConfiguredModel.storedAs override?
2152
- const configOverride = configuredAttributes[name]?.encoding;
2294
+ const configOverride = ownValue(configuredAttributes, name)?.encoding;
2153
2295
  if (configOverride !== undefined) {
2154
2296
  throw new Error(conflictMessage(name));
2155
2297
  }
@@ -2191,7 +2333,52 @@ export const storedAsOverTransform = (schema) => {
2191
2333
  * leaf `Link.to` AST.
2192
2334
  */
2193
2335
  const transformWireKind = (schema) => transformWireKindImpl(schema);
2194
- export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolvedRefs = [], immutableFields = new Set(), identifierField = undefined, timeSeries = undefined, fieldEncodings = {}, generatedIdField = undefined) => {
2336
+ /**
2337
+ * @internal The `DynamoModel.Hidden` fields of a model: a read in "model" or "record" mode leaves
2338
+ * them out, of the entity's own items and of a ref to it ({@link refHeldSchema}).
2339
+ */
2340
+ export const hiddenFieldNamesOf = (fields) => new Set(Object.keys(fields).filter((name) => isHidden(fields[name])));
2341
+ /** The targets {@link refHeldTarget} decided, each once. */
2342
+ const refHeldTargets = new WeakMap();
2343
+ /** The schemas {@link refHeldTarget} built: a target's fields without its hidden ones. */
2344
+ const heldStructs = new WeakSet();
2345
+ /**
2346
+ * @internal What a ref to an entity of model `target` holds (#241), the one decision every ref
2347
+ * position takes (an entity's `refs`, an aggregate's edges and the refs nested in their entities):
2348
+ * what a read of that entity returns, which put-time hydration and a cascade store, both through
2349
+ * `refDataOf` (the entity's own read schema encoding the item it read). A read leaves out the
2350
+ * target's `DynamoModel.Hidden` fields ({@link hiddenFieldNamesOf}), so the stored ref holds none
2351
+ * of them. Where a hidden field read absent fails, as a read decodes it (`Missing key`), the ref is
2352
+ * the target's other fields, a plain object as the entity's own read decodes it: up to 1.40.0 it
2353
+ * was the whole target, so the referencing row failed every read, after its write. Every other
2354
+ * target is held as declared, a class read back as its instance, as up to 1.40.0: one whose hidden
2355
+ * fields are optional, or read absent as a value (`Schema.Unknown`, `Schema.Any`,
2356
+ * `Schema.UndefinedOr`, a decoding default).
2357
+ */
2358
+ export const refHeldTarget = (target) => {
2359
+ const decided = refHeldTargets.get(target);
2360
+ if (decided !== undefined)
2361
+ return decided;
2362
+ const fields = getSchemaFields(target);
2363
+ const hidden = fields === undefined ? new Set() : hiddenFieldNamesOf(fields);
2364
+ // A hidden field read absent, as a read of the referencing row decodes it.
2365
+ const failsAbsent = (name) => Option.isNone(Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct({ [name]: fields[name] }), {
2366
+ legacyReads: true,
2367
+ absentReads: true,
2368
+ }))({}));
2369
+ const held = fields !== undefined && [...hidden].some(failsAbsent)
2370
+ ? Schema.Struct(Object.fromEntries(Object.entries(fields).filter(([name]) => !hidden.has(name))))
2371
+ : target;
2372
+ if (held !== target)
2373
+ heldStructs.add(held);
2374
+ refHeldTargets.set(target, held);
2375
+ return held;
2376
+ };
2377
+ /** @internal {@link refHeldTarget}, substituted as a read or a write takes it (`options`). */
2378
+ export const refHeldSchema = (target, options) => substituteSchemaDeep(refHeldTarget(target), options);
2379
+ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolvedRefs = [], immutableFields = new Set(), identifierField = undefined, timeSeries = undefined, fieldEncodings = {}, generatedIdField = undefined,
2380
+ /** The field `__proto__` is stored under another attribute: see `substituteSchemas`. */
2381
+ protoRenamed = false) => {
2195
2382
  // --- Substitute model fields ---
2196
2383
  // Self date schemas (with effective encoding) are replaced with bidirectional
2197
2384
  // transforms that produce the configured wire primitive. RedactedFromValue
@@ -2200,7 +2387,10 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2200
2387
  // transform IS the wire format and we never override it.
2201
2388
  // WRITE schemas (input / create / update / key) enforce the container checks
2202
2389
  // the substitution rebuilds; the READ schemas below do not (#133).
2203
- const fields = substituteSchemas(modelFields, fieldEncodings, { enforceChecks: true });
2390
+ const fields = substituteSchemas(modelFields, fieldEncodings, {
2391
+ enforceChecks: true,
2392
+ protoRenamed,
2393
+ });
2204
2394
  // READ schemas (model / record / item / deleted / history decode) also take
2205
2395
  // the domain-form values earlier releases left on transform fields (#133),
2206
2396
  // and read an absent attribute as the value it stands for (`absentStored`).
@@ -2209,6 +2399,7 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2209
2399
  const readFields = substituteSchemas(modelFields, fieldEncodings, {
2210
2400
  legacyReads: true,
2211
2401
  absentReads: true,
2402
+ protoRenamed,
2212
2403
  });
2213
2404
  // Ref fields carry the `DynamoModel.ref` annotation (an opaque Declaration that
2214
2405
  // hides the target's fields), so `substituteSchemaDeep` above can't see into
@@ -2218,22 +2409,34 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2218
2409
  // only model/record/item schemas — input/create/update replace refs with IDs.
2219
2410
  for (const ref of resolvedRefs) {
2220
2411
  const targetModel = ref.refEntity?.model;
2221
- if (!targetModel || !(ref.fieldName in fields))
2412
+ if (!targetModel || !hasOwnName(fields, ref.fieldName))
2222
2413
  continue;
2223
2414
  const resolved = isConfiguredModel(targetModel)
2224
2415
  ? targetModel.model
2225
2416
  : targetModel;
2226
- fields[ref.fieldName] = substituteSchemaDeep(resolved, { enforceChecks: true });
2227
- readFields[ref.fieldName] = substituteSchemaDeep(resolved, {
2417
+ // As optional as the model declares it (#241): a row an optional ref was left out of, or
2418
+ // removed from, reads without it. Up to 1.40.0 the target replaced the declaration whole.
2419
+ const optional = optionalField(ownValue(modelFields, ref.fieldName));
2420
+ const asDeclared = (target) => optional === undefined ? target : optional.rewrap(target);
2421
+ // In the storage the target's `DynamoModel.configure` gives its fields, which the ref holds them
2422
+ // in (`refDataOf`). Up to 1.41.0 the default: a date stored as epoch seconds read back as
2423
+ // milliseconds, and a condition or `pathSet` on it sent ISO text.
2424
+ const storage = configuredStorageOf(targetModel);
2425
+ const configured = storage === undefined ? {} : { configuredStorage: storage };
2426
+ // What a read of the target returns (`refHeldSchema`): its required hidden fields left out.
2427
+ setOwn(fields, ref.fieldName, asDeclared(refHeldSchema(resolved, { enforceChecks: true, ...configured })));
2428
+ setOwn(readFields, ref.fieldName, asDeclared(refHeldSchema(resolved, {
2228
2429
  legacyReads: true,
2229
2430
  absentReads: true,
2230
- });
2431
+ ...configured,
2432
+ })));
2231
2433
  }
2232
2434
  // Each of Effect's look-alike declarations (a `BigDecimal`, a `Duration`, an address, a date in
2233
2435
  // an `Option`, ...) reads back as a real instance, not the map DynamoDB hands back for it. A field
2234
2436
  // holding none is the same schema it was. Encoding through one is as it was.
2235
2437
  for (const [name, field] of Object.entries(readFields)) {
2236
- readFields[name] = readingInstances(field);
2438
+ if (!isProtoAbsent(field))
2439
+ setOwn(readFields, name, readingInstances(field));
2237
2440
  }
2238
2441
  // --- Model Schema: pure model fields (decode of stored items in "model" mode) ---
2239
2442
  const modelSchema = Schema.Struct(readFields);
@@ -2244,19 +2447,19 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2244
2447
  // already in `fields` and we don't add a system-schema entry.
2245
2448
  const systemSchemaFields = {};
2246
2449
  if (systemFields.createdAt && !systemFields.createdAtCollision) {
2247
- systemSchemaFields[systemFields.createdAt] = systemFields.createdAtEncoding
2450
+ setOwn(systemSchemaFields, systemFields.createdAt, systemFields.createdAtEncoding
2248
2451
  ? buildDateTransform(systemFields.createdAtEncoding)
2249
- : Schema.DateTimeUtcFromString;
2452
+ : Schema.DateTimeUtcFromString);
2250
2453
  }
2251
2454
  if (systemFields.updatedAt && !systemFields.updatedAtCollision) {
2252
- systemSchemaFields[systemFields.updatedAt] = systemFields.updatedAtEncoding
2455
+ setOwn(systemSchemaFields, systemFields.updatedAt, systemFields.updatedAtEncoding
2253
2456
  ? buildDateTransform(systemFields.updatedAtEncoding)
2254
- : Schema.DateTimeUtcFromString;
2457
+ : Schema.DateTimeUtcFromString);
2255
2458
  }
2256
2459
  if (systemFields.version && !systemFields.versionCollision) {
2257
2460
  // An item written before the entity was `versioned` has no version: it
2258
2461
  // reads as version 0 — real versions start at 1 (#133).
2259
- systemSchemaFields[systemFields.version] = Schema.Number.pipe(Schema.withDecodingDefaultKey(Effect.succeed(0)));
2462
+ setOwn(systemSchemaFields, systemFields.version, Schema.Number.pipe(Schema.withDecodingDefaultKey(Effect.succeed(0))));
2260
2463
  }
2261
2464
  const recordSchema = Schema.Struct({
2262
2465
  ...readFields,
@@ -2296,6 +2499,14 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2296
2499
  };
2297
2500
  // --- Input Schema: ref-aware (swap ref fields for ID fields when refs present) ---
2298
2501
  const refFieldSet = new Set(resolvedRefs.map((r) => r.fieldName));
2502
+ // A ref's id is taken as the model takes the ref (#241): required where it's required, and left
2503
+ // out (`Schema.optionalKey`) or `undefined` too (`Schema.optional`) where the model declares the
2504
+ // ref optional, which then stores no ref. Up to 1.40.0 the id was always required.
2505
+ const refIdInput = (ref) => {
2506
+ const declared = modelFields[ref.fieldName];
2507
+ const optional = declared === undefined ? undefined : optionalField(declared);
2508
+ return optional === undefined ? ref.keySchema : optional.rewrap(ref.keySchema);
2509
+ };
2299
2510
  const buildInputFieldsAcc = () => {
2300
2511
  const acc = {};
2301
2512
  for (const [key, field] of Object.entries(fields)) {
@@ -2303,10 +2514,10 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2303
2514
  continue;
2304
2515
  const adjusted = applySystemCollisionAdjustments(key, field, "input");
2305
2516
  if (adjusted !== null)
2306
- acc[key] = adjusted;
2517
+ setOwn(acc, key, adjusted);
2307
2518
  }
2308
2519
  for (const ref of resolvedRefs) {
2309
- acc[ref.idFieldName] = ref.identifierSchema;
2520
+ setOwn(acc, ref.idFieldName, refIdInput(ref));
2310
2521
  }
2311
2522
  return acc;
2312
2523
  };
@@ -2322,13 +2533,13 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2322
2533
  continue; // skip ref fields (replaced by ID fields)
2323
2534
  const adjusted = applySystemCollisionAdjustments(key, field, "input");
2324
2535
  if (adjusted !== null)
2325
- createFieldsAcc[key] = adjusted;
2536
+ setOwn(createFieldsAcc, key, adjusted);
2326
2537
  }
2327
2538
  // Add ID fields for each ref (skip if the ref field is an omitted field)
2328
2539
  for (const ref of resolvedRefs) {
2329
2540
  if (createOmitFields.has(ref.fieldName))
2330
2541
  continue;
2331
- createFieldsAcc[ref.idFieldName] = ref.identifierSchema;
2542
+ setOwn(createFieldsAcc, ref.idFieldName, refIdInput(ref));
2332
2543
  }
2333
2544
  const createSchema = Schema.Struct(createFieldsAcc);
2334
2545
  // --- Update Schema: optional model fields minus key composites & immutable ---
@@ -2355,28 +2566,34 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2355
2566
  continue;
2356
2567
  if (strippedFromUpdate.has(key))
2357
2568
  continue;
2569
+ // A field 1.40.0's map didn't hold is one an update may leave out already (`protoAbsent`).
2570
+ if (isProtoAbsent(field)) {
2571
+ setOwn(acc, key, field);
2572
+ continue;
2573
+ }
2358
2574
  const clearable = optionalOnCollide.has(key) || lackDecision(field) !== "refuse";
2359
- acc[key] = clearable
2360
- ? Schema.optional(field)
2361
- : Schema.optionalKey(field);
2575
+ setOwn(acc, key, clearable ? Schema.optional(field) : Schema.optionalKey(field));
2362
2576
  }
2363
2577
  for (const ref of resolvedRefs) {
2364
- if (pkComposites.has(ref.fieldName))
2578
+ // A ref's id that is a primary key composite is part of the key, which no update changes.
2579
+ if (pkComposites.has(ref.fieldName) || pkComposites.has(ref.idFieldName))
2365
2580
  continue;
2366
2581
  if (immutableFields.has(ref.fieldName))
2367
2582
  continue;
2368
- acc[ref.idFieldName] = Schema.optionalKey(ref.identifierSchema);
2583
+ setOwn(acc, ref.idFieldName, Schema.optionalKey(ref.keySchema));
2369
2584
  }
2370
2585
  return acc;
2371
2586
  };
2372
2587
  const updateSchema = Schema.Struct(buildUpdateFieldsAcc());
2373
2588
  // --- Key Schema: primary key composite attributes only ---
2589
+ // A composite is a model field or a ref's id (`projectId` for `project`), which a key takes as
2590
+ // the input does. Up to 1.40.0 a ref's id was left out, and every key-taking operation died.
2374
2591
  const keyCompositeNames = primaryKeyComposites(indexes);
2375
2592
  const keyFields = {};
2376
2593
  for (const name of keyCompositeNames) {
2377
- const field = fields[name];
2594
+ const field = ownValue(fields, name) ?? resolvedRefs.find((ref) => ref.idFieldName === name)?.keySchema;
2378
2595
  if (field)
2379
- keyFields[name] = field;
2596
+ setOwn(keyFields, name, field);
2380
2597
  }
2381
2598
  const keySchema = Schema.Struct(keyFields);
2382
2599
  // --- Item Schema: record + key attrs (pk, sk, gsi*) + __edd_e__ ---
@@ -2393,9 +2610,7 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2393
2610
  }
2394
2611
  const keyAttrFields = {};
2395
2612
  for (const fieldName of allKeyFieldNames(indexes)) {
2396
- keyAttrFields[fieldName] = primaryKeyFieldNames.has(fieldName)
2397
- ? Schema.String
2398
- : Schema.optional(Schema.String);
2613
+ setOwn(keyAttrFields, fieldName, primaryKeyFieldNames.has(fieldName) ? Schema.String : Schema.optional(Schema.String));
2399
2614
  }
2400
2615
  const itemSchema = Schema.Struct({
2401
2616
  ...readFields,
@@ -2412,11 +2627,7 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2412
2627
  // --- Hidden-aware decode schemas: strip DynamoModel.Hidden fields from model/record ---
2413
2628
  // These are used for "model" and "record" decode modes. Hidden fields are
2414
2629
  // still present in "item" and "native" modes.
2415
- const hiddenFieldNames = new Set();
2416
- for (const [fieldName, fieldSchema] of Object.entries(modelFields)) {
2417
- if (isHidden(fieldSchema))
2418
- hiddenFieldNames.add(fieldName);
2419
- }
2630
+ const hiddenFieldNames = hiddenFieldNamesOf(modelFields);
2420
2631
  const hasHiddenFields = hiddenFieldNames.size > 0;
2421
2632
  const modelVisibleSchema = hasHiddenFields
2422
2633
  ? Schema.Struct(Object.fromEntries(Object.entries(readFields).filter(([k]) => !hiddenFieldNames.has(k))))
@@ -2444,7 +2655,10 @@ export const buildDerivedSchemas = (modelFields, indexes, systemFields, resolved
2444
2655
  // Compute encodings for the appendInput fields (annotation +
2445
2656
  // inferred from typeConstructor for self schemas).
2446
2657
  const appendEncodings = buildFieldEncodings(userFields, {});
2447
- const subbedFields = substituteSchemas(userFields, appendEncodings, { enforceChecks: true });
2658
+ const subbedFields = substituteSchemas(userFields, appendEncodings, {
2659
+ enforceChecks: true,
2660
+ protoRenamed,
2661
+ });
2448
2662
  return Schema.Struct(subbedFields);
2449
2663
  })()
2450
2664
  : null;
@@ -2484,7 +2698,7 @@ const childAtSegment = (schema, segment) => {
2484
2698
  const s = inner;
2485
2699
  const fields = schemaFieldsOf(inner);
2486
2700
  if (fields !== undefined)
2487
- return typeof segment === "string" ? fields[segment] : undefined;
2701
+ return typeof segment === "string" ? ownValue(fields, segment) : undefined;
2488
2702
  // An OPAQUE class — `X.check(…)`, `X.annotate(…)`, a `DynamoModel.ref` nested
2489
2703
  // in a ref target — is deliberately NOT followed. Its `.fields` are gone, so
2490
2704
  // the derived read schema keeps it unsubstituted and decodes its leaves
@@ -2523,7 +2737,7 @@ const childAtSegment = (schema, segment) => {
2523
2737
  if (isSchemaLike(s.value) && isSchemaLike(s.key))
2524
2738
  return s.value;
2525
2739
  if (isSchemaLike(s.schema) && Array.isArray(s.records)) {
2526
- const declared = schemaFieldsOf(s.schema)?.[segment];
2740
+ const declared = ownValue(schemaFieldsOf(s.schema), segment);
2527
2741
  if (declared !== undefined)
2528
2742
  return declared;
2529
2743
  const record = s.records[0];
@@ -2564,7 +2778,8 @@ const sameValue = (a, b) => {
2564
2778
  }
2565
2779
  if (isPlainObject(a) && isPlainObject(b)) {
2566
2780
  const keys = Object.keys(a);
2567
- return keys.length === Object.keys(b).length && keys.every((k) => sameValue(a[k], b[k]));
2781
+ return (keys.length === Object.keys(b).length &&
2782
+ keys.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k])));
2568
2783
  }
2569
2784
  return false;
2570
2785
  };
@@ -2590,14 +2805,24 @@ const makeAmbiguityCheck = (original) => {
2590
2805
  return () => false;
2591
2806
  // "Already wire" means the value DECODES as wire — a plain string that is not
2592
2807
  // valid base64 is a domain value for `StringFromBase64`, and is encoded.
2593
- const decodesAsWire = Schema.decodeUnknownOption(original);
2808
+ const decodesAsWire = Schema.decodeUnknownExit(original);
2594
2809
  const isType = Schema.is(Schema.make(SchemaAST.toType(original.ast)));
2595
- const encode = Schema.encodeUnknownOption(original);
2810
+ const encode = Schema.encodeUnknownExit(original);
2811
+ // A transform that can't run synchronously can't tell (#236).
2596
2812
  return (value) => {
2597
- if (decodesAsWire(value)._tag === "None" || !isType(value))
2813
+ const asWire = issueOf(() => decodesAsWire(value));
2814
+ if (asWire === CANT_SAY)
2815
+ return CANT_SAY;
2816
+ if (asWire !== undefined || !isType(value))
2598
2817
  return false;
2599
- const encoded = encode(value);
2600
- return encoded._tag === "Some" && !sameValue(encoded.value, value);
2818
+ let encoded;
2819
+ const issue = issueOf(() => {
2820
+ encoded = encode(value);
2821
+ return encoded;
2822
+ });
2823
+ if (issue === CANT_SAY)
2824
+ return CANT_SAY;
2825
+ return encoded !== undefined && Exit.isSuccess(encoded) && !sameValue(encoded.value, value);
2601
2826
  };
2602
2827
  };
2603
2828
  /**
@@ -2614,10 +2839,26 @@ const asStored = (value) => {
2614
2839
  const out = {};
2615
2840
  for (const [key, entry] of Object.entries(value)) {
2616
2841
  if (entry !== undefined)
2617
- out[key] = asStored(entry);
2842
+ setOwn(out, key, asStored(entry));
2618
2843
  }
2619
2844
  return out;
2620
2845
  };
2846
+ /** Text, a number, a `bigint` or a boolean. */
2847
+ const isPrimitive = (value) => {
2848
+ const type = typeof value;
2849
+ return type === "string" || type === "number" || type === "bigint" || type === "boolean";
2850
+ };
2851
+ /** The type DynamoDB holds a primitive as: text, a number (a `bigint` too), or a boolean. */
2852
+ const dynamoTypeOf = (value) => typeof value === "string" ? "S" : typeof value === "boolean" ? "BOOL" : "N";
2853
+ /**
2854
+ * Whether a condition's or filter's `operand` is sent as given where a write of it stores `stored`
2855
+ * (#242): a primitive is, unless what's stored is a primitive of another type, which no row holds
2856
+ * the operand as (`5` where a `NumberFromString` stores `"5"`). Text where text is stored could be
2857
+ * the stored text itself, a substring for `contains` or a prefix, which the library can't tell
2858
+ * apart, so it is sent as 1.41.0 sent it; so is a number where a number is stored, and a primitive
2859
+ * where what's stored is no primitive.
2860
+ */
2861
+ const keepsAsGiven = (operand, stored) => isPrimitive(operand) && (!isPrimitive(stored) || dynamoTypeOf(stored) === dynamoTypeOf(operand));
2621
2862
  /** A plain object or class instance whose fields a path value can be walked by. */
2622
2863
  const isWalkableObject = (value) => value !== null &&
2623
2864
  typeof value === "object" &&
@@ -2625,6 +2866,103 @@ const isWalkableObject = (value) => value !== null &&
2625
2866
  !(value instanceof Date) &&
2626
2867
  !DateTime.isDateTime(value) &&
2627
2868
  !Redacted.isRedacted(value);
2869
+ /**
2870
+ * What `contains` compares in what a field stores (#242): an element of a list (`Schema.Array`, a
2871
+ * tuple), a member of a set (`Schema.ReadonlySet`, stored as DynamoDB's set), and otherwise a
2872
+ * substring of text.
2873
+ *
2874
+ * @internal
2875
+ */
2876
+ export const containedKindOf = (field) => {
2877
+ const inner = optionalField(field)?.inner ?? field;
2878
+ return SchemaAST.isArrays(inner.ast) ? "list" : isSetDeclaration(inner.ast) ? "set" : "text";
2879
+ };
2880
+ /**
2881
+ * A `contains` operand in the form the field stores what it compares (#242), from what a write of
2882
+ * a whole value there stores (`value`) and of one list element (`element`): the element as a list
2883
+ * stores it; the single member of a write of a set holding it (a primitive member as given, unless
2884
+ * the set stores it as a primitive of another type: {@link keepsAsGiven}); the text a write of it
2885
+ * stores, when that's text. `undefined` when the field doesn't take it so, and the operand is sent
2886
+ * as given.
2887
+ *
2888
+ * @internal
2889
+ */
2890
+ export const containedOperand = (kind, value, element) => (operand) => {
2891
+ if (kind === "list")
2892
+ return element(operand);
2893
+ if (kind === "set") {
2894
+ const set = value(new Set([operand]))?.stored;
2895
+ if (!(set instanceof Set) || set.size !== 1)
2896
+ return undefined;
2897
+ const member = [...set][0];
2898
+ return { stored: keepsAsGiven(operand, member) ? operand : member };
2899
+ }
2900
+ const text = value(operand);
2901
+ return typeof text?.stored === "string" ? text : undefined;
2902
+ };
2903
+ /** Whether a node carries nothing a read runs: no transformation, no check. */
2904
+ const plainNode = (ast) => ast.checks === undefined &&
2905
+ ast.encoding === undefined &&
2906
+ ast.encodingChecks === undefined;
2907
+ /** The members of a plain union, each union among them in turn; any other schema alone. */
2908
+ const membersOf = (schema) => {
2909
+ const members = schema.members;
2910
+ if (!SchemaAST.isUnion(schema.ast) || !plainNode(schema.ast) || !Array.isArray(members)) {
2911
+ return [schema];
2912
+ }
2913
+ return members.flatMap(membersOf);
2914
+ };
2915
+ const SCALAR_TAGS = new Set([
2916
+ "Null",
2917
+ "Undefined",
2918
+ "String",
2919
+ "Number",
2920
+ "Boolean",
2921
+ "BigInt",
2922
+ "Symbol",
2923
+ "Literal",
2924
+ "UniqueSymbol",
2925
+ "Enum",
2926
+ "TemplateLiteral",
2927
+ ]);
2928
+ /** What holds a path's next segment: a plain struct, a plain record, or something else. */
2929
+ const parentOf = (member) => {
2930
+ const ast = member.ast;
2931
+ if (!SchemaAST.isObjects(ast) || !plainNode(ast))
2932
+ return "other";
2933
+ if (ast.indexSignatures.length === 0)
2934
+ return "struct";
2935
+ return ast.propertySignatures.length === 0 ? "record" : "other";
2936
+ };
2937
+ /** A way's end where a member doesn't hold the path's next segment ({@link UnionWay}). */
2938
+ const missingAt = (member, segment) => {
2939
+ const ast = member.ast;
2940
+ if (!plainNode(ast))
2941
+ return { _tag: "Unknown" };
2942
+ if (SCALAR_TAGS.has(ast._tag))
2943
+ return { _tag: "CannotHold" };
2944
+ if (SchemaAST.isArrays(ast))
2945
+ return { _tag: typeof segment === "string" ? "CannotHold" : "Unknown" };
2946
+ if (SchemaAST.isObjects(ast) && ast.indexSignatures.length === 0) {
2947
+ return { _tag: typeof segment === "string" ? "Unread" : "CannotHold" };
2948
+ }
2949
+ return { _tag: "Unknown" };
2950
+ };
2951
+ /**
2952
+ * A union's member as a path's judgement reads it (#238): a struct that renames its keys as it's
2953
+ * stored ({@link keyRenamesOf}) is read as the struct it renames, by its properties' own names,
2954
+ * which a path names (each written under its stored name, which the struct reads it from).
2955
+ * Anything else as it is.
2956
+ */
2957
+ const readAs = (member) => {
2958
+ const ast = member.ast;
2959
+ if (!SchemaAST.isObjects(ast) || ast.encoding === undefined || !keyRenamesOf(ast))
2960
+ return member;
2961
+ const renamed = member.to;
2962
+ return isSchemaLike(renamed) && SchemaAST.isObjects(renamed.ast) && plainNode(renamed.ast)
2963
+ ? renamed
2964
+ : member;
2965
+ };
2628
2966
  /**
2629
2967
  * Encoders for the VALUES of path-based updates (`pathSet`, `pathAppend`,
2630
2968
  * `pathPrepend`, `pathIfNotExists`) and record-based `append` (#133).
@@ -2650,7 +2988,19 @@ export const makePathValueEncoder = (modelFields, writeFields,
2650
2988
  * field name. A ref field's own schema is opaque (the annotation drops its
2651
2989
  * `.fields`), so a path under it is followed through the target model.
2652
2990
  */
2653
- refTargets = {}) => {
2991
+ refTargets = {},
2992
+ /**
2993
+ * Whether DynamoDB can store an encoded value: an operand whose stored form it can't store is
2994
+ * sent as given ({@link operand}).
2995
+ */
2996
+ storable,
2997
+ /** The entity's READ schemas of the model's fields, which a row is decoded by (`readsAsGiven`). */
2998
+ readFields = {},
2999
+ /**
3000
+ * The storage the `DynamoModel.configure` of each ref's target gives its fields
3001
+ * (`configuredStorageOf`), keyed by ref field: the ref holds them in it, as its schemas do.
3002
+ */
3003
+ refStorage = {}) => {
2654
3004
  const recordFields = writeFields;
2655
3005
  const cache = new Map();
2656
3006
  const encoderFor = (key, resolve) => {
@@ -2678,27 +3028,50 @@ refTargets = {}) => {
2678
3028
  const element = leafAwareEncoder(originalElement, storedElement);
2679
3029
  return (value) => (Array.isArray(value) ? value.map((entry) => element(entry)) : value);
2680
3030
  }
2681
- const encode = Schema.encodeUnknownOption(stored);
2682
- const decode = Schema.decodeUnknownOption(stored);
3031
+ const encodeExit = Schema.encodeUnknownExit(stored);
3032
+ const decodeExit = Schema.decodeUnknownExit(stored);
3033
+ /** A synchronous run's value, `undefined` on a schema issue, `CANT_SAY` when it can't finish. */
3034
+ const attempt = (run, value) => {
3035
+ let exit;
3036
+ const verdict = issueOf(() => {
3037
+ exit = run(value);
3038
+ return exit;
3039
+ });
3040
+ if (verdict === CANT_SAY)
3041
+ return CANT_SAY;
3042
+ return verdict === undefined && exit !== undefined && Exit.isSuccess(exit)
3043
+ ? { value: exit.value }
3044
+ : undefined;
3045
+ };
2683
3046
  const ambiguous = makeAmbiguityCheck(original);
2684
3047
  return (value) => {
2685
- if (ambiguous(value))
3048
+ // Where the check can't tell (a schema that can't run synchronously), the value is
3049
+ // encoded as a domain value, and written as given if that can't finish either.
3050
+ if (ambiguous(value) === true)
2686
3051
  return value;
2687
3052
  // A container holding an ambiguous wire leaf (`{ b64: "aGk=", at }`) is
2688
3053
  // encoded part by part, so that leaf follows the leaf rule instead of
2689
3054
  // being encoded a second time by the whole-value encode.
2690
3055
  if (holdsAmbiguousLeaf(original, value))
2691
3056
  return encodeByParts(original, value);
2692
- const encoded = encode(value);
2693
- if (encoded._tag === "Some")
3057
+ // A schema that can't run synchronously (an asynchronous step, a defect) says nothing of
3058
+ // the value: it's written as given, as at a position nothing checks (#236).
3059
+ const encoded = attempt(encodeExit, value);
3060
+ if (encoded === CANT_SAY)
3061
+ return value;
3062
+ if (encoded !== undefined)
2694
3063
  return encoded.value;
2695
3064
  // `decode -> encode`, as `.set()` / `put` do: a plain object given for a
2696
3065
  // class-typed field, or a value already in wire form, round-trips to its
2697
3066
  // wire form instead of being marshalled as given.
2698
- const decoded = decode(value);
2699
- if (decoded._tag === "Some") {
2700
- const reencoded = encode(decoded.value);
2701
- if (reencoded._tag === "Some")
3067
+ const decoded = attempt(decodeExit, value);
3068
+ if (decoded === CANT_SAY)
3069
+ return value;
3070
+ if (decoded !== undefined) {
3071
+ const reencoded = attempt(encodeExit, decoded.value);
3072
+ if (reencoded === CANT_SAY)
3073
+ return value;
3074
+ if (reencoded !== undefined)
2702
3075
  return reencoded.value;
2703
3076
  }
2704
3077
  return encodeByParts(original, value);
@@ -2711,7 +3084,7 @@ refTargets = {}) => {
2711
3084
  check = makeAmbiguityCheck(optionalField(schema)?.inner ?? schema);
2712
3085
  ambiguityChecks.set(schema, check);
2713
3086
  }
2714
- return check(value);
3087
+ return check(value) === true;
2715
3088
  };
2716
3089
  /**
2717
3090
  * Whether a container value holds, at any depth, a leaf in ambiguous wire
@@ -2764,7 +3137,7 @@ refTargets = {}) => {
2764
3137
  const out = {};
2765
3138
  for (const [key, entry] of Object.entries(value)) {
2766
3139
  const child = childAtSegment(schema, key);
2767
- out[key] = child === undefined ? entry : partEncoder(child)(entry);
3140
+ setOwn(out, key, child === undefined ? entry : partEncoder(child)(entry));
2768
3141
  }
2769
3142
  return out;
2770
3143
  };
@@ -2776,7 +3149,7 @@ refTargets = {}) => {
2776
3149
  const [head, ...rest] = segments;
2777
3150
  if (typeof head !== "string")
2778
3151
  return undefined;
2779
- let current = refTargets[head] ?? modelFields[head];
3152
+ let current = ownValue(refTargets, head) ?? ownValue(modelFields, head);
2780
3153
  let asDeclared = false;
2781
3154
  for (const segment of rest) {
2782
3155
  if (current === undefined)
@@ -2789,6 +3162,18 @@ refTargets = {}) => {
2789
3162
  }
2790
3163
  return current === undefined ? undefined : { schema: current, asDeclared };
2791
3164
  };
3165
+ /**
3166
+ * `original`, the model's schema at `segments` (below a field), as a write stores it: a field of a
3167
+ * ref's target in the storage its `DynamoModel.configure` gives it, which the ref holds it in
3168
+ * (`refStorage`), as the ref's own schemas do.
3169
+ */
3170
+ const storedSchema = (segments, original) => {
3171
+ const [head, name] = segments;
3172
+ const encoding = segments.length === 2 && typeof head === "string" && typeof name === "string"
3173
+ ? ownValue(ownValue(refStorage, head), name)
3174
+ : undefined;
3175
+ return substituteSchemaDeep(original, withConfiguredStorage({ enforceChecks: true }, name, original, encoding));
3176
+ };
2792
3177
  const schemaAt = (segments) => {
2793
3178
  const at = originalAt(segments);
2794
3179
  if (at === undefined)
@@ -2796,10 +3181,10 @@ refTargets = {}) => {
2796
3181
  const original = at.schema;
2797
3182
  const head = segments[0];
2798
3183
  const stored = segments.length === 1
2799
- ? recordFields[head]
3184
+ ? ownValue(recordFields, head)
2800
3185
  : at.asDeclared
2801
3186
  ? original
2802
- : substituteSchemaDeep(original, { enforceChecks: true });
3187
+ : storedSchema(segments, original);
2803
3188
  return stored === undefined ? undefined : { original, stored };
2804
3189
  };
2805
3190
  const validators = new Map();
@@ -2812,15 +3197,517 @@ refTargets = {}) => {
2812
3197
  ? null
2813
3198
  : (() => {
2814
3199
  const decode = Schema.decodeUnknownExit(schema);
3200
+ // Only a schema issue refuses: a decode that can't finish synchronously says
3201
+ // nothing of the value (#236).
2815
3202
  return (encoded) => {
2816
- const exit = decode(asStored(encoded));
2817
- return exit._tag === "Success" ? undefined : exit.cause;
3203
+ const issue = issueOf(() => decode(asStored(encoded)));
3204
+ return issue === CANT_SAY ? undefined : issue;
2818
3205
  };
2819
3206
  })();
2820
3207
  validators.set(key, fn);
2821
3208
  return fn;
2822
3209
  };
3210
+ /**
3211
+ * Every schema a row can hold the value at `segments` under (#242), each with whether it's written
3212
+ * as declared ({@link writesFirstMemberOnly}), or `undefined` where the schema alone doesn't
3213
+ * determine what a row holds there. The walk follows EVERY union member that can hold the path,
3214
+ * not only the first: a row holding a later member stores its value there under that member's
3215
+ * schema. A position that can't hold the rest of the path (a string, a number, a literal, `null`,
3216
+ * a struct without the field) is left out. One that could hold it but isn't modelled here (an
3217
+ * `Unknown` or `Any`, a suspended schema, a declaration such as an `Option` or an opaque class, a
3218
+ * container the walk can't read) makes the path undetermined, and so does an `Unknown` or `Any` at
3219
+ * the path itself.
3220
+ */
3221
+ const declaredAt = (segments) => {
3222
+ const [head, ...rest] = segments;
3223
+ if (typeof head !== "string")
3224
+ return undefined;
3225
+ const top = ownValue(refTargets, head) ?? ownValue(modelFields, head);
3226
+ if (top === undefined)
3227
+ return undefined;
3228
+ const holdsNoPath = new Set([
3229
+ "Null",
3230
+ "Undefined",
3231
+ "Void",
3232
+ "Never",
3233
+ "String",
3234
+ "Number",
3235
+ "Boolean",
3236
+ "BigInt",
3237
+ "Symbol",
3238
+ "UniqueSymbol",
3239
+ "Literal",
3240
+ "TemplateLiteral",
3241
+ "Enum",
3242
+ ]);
3243
+ const membersOf = (union) => {
3244
+ const members = union.members;
3245
+ return Array.isArray(members) ? members : undefined;
3246
+ };
3247
+ const through = (members, segment, asDeclared) => {
3248
+ const out = [];
3249
+ for (const [index, member] of members.entries()) {
3250
+ const reached = reach(member, segment, asDeclared(index));
3251
+ if (reached === undefined)
3252
+ return undefined;
3253
+ out.push(...reached);
3254
+ }
3255
+ return out;
3256
+ };
3257
+ const reach = (schema, segment, asDeclared) => {
3258
+ const opt = optionalField(schema);
3259
+ if (opt?.union !== undefined) {
3260
+ // An optional union writes its first member substituted and the later ones as declared.
3261
+ const members = membersOf(opt.union)?.filter((m) => m.ast._tag !== "Undefined");
3262
+ if (members === undefined)
3263
+ return undefined;
3264
+ return through(members, segment, (index) => asDeclared || index > 0);
3265
+ }
3266
+ const inner = opt?.inner ?? schema;
3267
+ const fields = schemaFieldsOf(inner);
3268
+ if (fields !== undefined) {
3269
+ const child = typeof segment === "string" ? fields[segment] : undefined;
3270
+ return child === undefined ? [] : [{ schema: child, asDeclared }];
3271
+ }
3272
+ const ast = inner.ast;
3273
+ if (holdsNoPath.has(ast._tag))
3274
+ return [];
3275
+ if (SchemaAST.isUnion(ast)) {
3276
+ const members = membersOf(inner);
3277
+ return members === undefined ? undefined : through(members, segment, () => asDeclared);
3278
+ }
3279
+ if (SchemaAST.isArrays(ast)) {
3280
+ if (typeof segment !== "number")
3281
+ return [];
3282
+ const child = childAtSegment(inner, segment);
3283
+ if (child !== undefined)
3284
+ return [{ schema: child, asDeclared }];
3285
+ // A tuple with no element there and no rest holds nothing there.
3286
+ const s = inner;
3287
+ return Array.isArray(s.elements) && ast.rest.length === 0 ? [] : undefined;
3288
+ }
3289
+ if (SchemaAST.isObjects(ast)) {
3290
+ if (typeof segment !== "string")
3291
+ return [];
3292
+ const child = childAtSegment(inner, segment);
3293
+ return child === undefined ? undefined : [{ schema: child, asDeclared }];
3294
+ }
3295
+ return undefined;
3296
+ };
3297
+ let positions = [{ schema: top, asDeclared: false }];
3298
+ for (const segment of rest) {
3299
+ const next = [];
3300
+ for (const position of positions) {
3301
+ const reached = reach(position.schema, segment, position.asDeclared);
3302
+ if (reached === undefined)
3303
+ return undefined;
3304
+ for (const p of reached) {
3305
+ if (!next.some((q) => q.schema === p.schema && q.asDeclared === p.asDeclared))
3306
+ next.push(p);
3307
+ }
3308
+ }
3309
+ positions = next;
3310
+ }
3311
+ const holdsAnything = (schema) => {
3312
+ const tag = (optionalField(schema)?.inner ?? schema).ast._tag;
3313
+ return tag === "Unknown" || tag === "Any";
3314
+ };
3315
+ return positions.some((p) => holdsAnything(p.schema)) ? undefined : positions;
3316
+ };
3317
+ const operandForms = new Map();
3318
+ const formsAt = (segments) => {
3319
+ const key = JSON.stringify(segments);
3320
+ const cached = operandForms.get(key);
3321
+ if (cached !== undefined)
3322
+ return cached;
3323
+ const declared = declaredAt(segments);
3324
+ const head = segments[0];
3325
+ const forms = declared === undefined || declared.length === 0
3326
+ ? null
3327
+ : declared.flatMap((position) => {
3328
+ const original = position.schema;
3329
+ const stored = segments.length === 1
3330
+ ? ownValue(recordFields, head)
3331
+ : position.asDeclared
3332
+ ? original
3333
+ : storedSchema(segments, original);
3334
+ if (stored === undefined)
3335
+ return [];
3336
+ const formOf = (from, to) => {
3337
+ const encode = leafAwareEncoder(from, to);
3338
+ const decode = Schema.decodeUnknownExit(to);
3339
+ return (value) => {
3340
+ if (isPrimitive(value)) {
3341
+ // A primitive is put in its stored form only where that is a primitive of
3342
+ // another type (`5` where a `NumberFromString` stores `"5"`), and is sent as
3343
+ // given anywhere else, as up to 1.41.0 ({@link keepsAsGiven}).
3344
+ const encoded = encode(value);
3345
+ const issue = issueOf(() => decode(asStored(encoded)));
3346
+ if (issue === CANT_SAY)
3347
+ return { stored: value };
3348
+ if (issue !== undefined)
3349
+ return undefined;
3350
+ if (keepsAsGiven(value, encoded))
3351
+ return { stored: value };
3352
+ return storable === undefined || storable(encoded)
3353
+ ? { stored: encoded }
3354
+ : undefined;
3355
+ }
3356
+ const encoded = encode(value);
3357
+ if (decode(asStored(encoded))._tag !== "Success")
3358
+ return undefined;
3359
+ if (storable !== undefined && !storable(encoded))
3360
+ return undefined;
3361
+ return { stored: encoded };
3362
+ };
3363
+ };
3364
+ const value = formOf(original, stored);
3365
+ const originalElement = listElementOf(original);
3366
+ const storedElement = listElementOf(stored);
3367
+ const contained = containedOperand(containedKindOf(original), value, originalElement !== undefined && storedElement !== undefined
3368
+ ? formOf(originalElement, storedElement)
3369
+ : () => undefined);
3370
+ return [{ value, contained }];
3371
+ });
3372
+ const result = forms === null || forms.length === 0 ? null : forms;
3373
+ operandForms.set(key, result);
3374
+ return result;
3375
+ };
3376
+ /**
3377
+ * Every way to the end of a path through the model's schema, by the member it takes at each union
3378
+ * of several members on the way (`choices`, keyed by where the union is: the path up to the map
3379
+ * it reads). Within a union's member a path is followed as {@link childAtSegment} follows it.
3380
+ */
3381
+ const waysTo = (segments) => {
3382
+ const [head, ...rest] = segments;
3383
+ if (typeof head !== "string")
3384
+ return [];
3385
+ const start = ownValue(refTargets, head) ?? ownValue(modelFields, head);
3386
+ if (start === undefined)
3387
+ return [];
3388
+ const ways = [];
3389
+ const walk = (schema, depth, choices, asDeclared, parent) => {
3390
+ if (depth === rest.length) {
3391
+ ways.push({ choices, end: { _tag: "At", original: schema, asDeclared, parent } });
3392
+ return;
3393
+ }
3394
+ const segment = rest[depth];
3395
+ const opt = optionalField(schema);
3396
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3397
+ // Through a later member of an optional union, a path is written as declared, as
3398
+ // `originalAt` writes it ({@link writesFirstMemberOnly}).
3399
+ const first = opt?.union === undefined ? undefined : new Set(membersOf(opt.inner));
3400
+ const at = JSON.stringify(segments.slice(0, depth + 1));
3401
+ for (const member of members) {
3402
+ const chosen = members.length > 1 ? new Map(choices).set(at, member) : choices;
3403
+ const declared = asDeclared || (first !== undefined && !first.has(member));
3404
+ const child = childAtSegment(member, segment);
3405
+ if (child !== undefined)
3406
+ walk(child, depth + 1, chosen, declared, parentOf(member));
3407
+ else
3408
+ ways.push({ choices: chosen, end: missingAt(member, segment) });
3409
+ }
3410
+ };
3411
+ walk(start, 0, new Map(), false, "other");
3412
+ return ways;
3413
+ };
3414
+ const wayStored = new Map();
3415
+ const wayDeclared = (way) => {
3416
+ if (way.asDeclared)
3417
+ return way.original;
3418
+ const found = wayStored.get(way.original);
3419
+ if (found !== undefined)
3420
+ return found;
3421
+ const stored = substituteSchemaDeep(way.original, { enforceChecks: true });
3422
+ wayStored.set(way.original, stored);
3423
+ return stored;
3424
+ };
3425
+ const wayValidators = new Map();
3426
+ const wayValidator = (way) => {
3427
+ const stored = wayDeclared(way);
3428
+ const found = wayValidators.get(stored);
3429
+ if (found !== undefined)
3430
+ return found;
3431
+ const decode = Schema.decodeUnknownExit(stored);
3432
+ const fn = (encoded) => {
3433
+ const exit = decode(asStored(encoded));
3434
+ return exit._tag === "Success" ? undefined : exit.cause;
3435
+ };
3436
+ wayValidators.set(stored, fn);
3437
+ return fn;
3438
+ };
3439
+ const wayEncoders = new Map();
3440
+ const wayEncoder = (way) => {
3441
+ const stored = wayDeclared(way);
3442
+ const found = wayEncoders.get(stored);
3443
+ if (found !== undefined)
3444
+ return found;
3445
+ const fn = leafAwareEncoder(way.original, stored);
3446
+ wayEncoders.set(stored, fn);
3447
+ return fn;
3448
+ };
3449
+ /**
3450
+ * What one clause leaves at the node it ends at (`schema`, reached as `asDeclared` says, held by a
3451
+ * `parent`): read, not read, or `"unknown"`, which the schema can't judge — a copy, an
3452
+ * increment, an append, a whole field, a list position removed.
3453
+ */
3454
+ const endVerdict = (clause, at) => {
3455
+ if (clause._tag === "Other")
3456
+ return "unknown";
3457
+ if (clause._tag === "Value")
3458
+ return wayValidator(at)(clause.encoded) === undefined;
3459
+ if (typeof clause.segments[clause.segments.length - 1] !== "string")
3460
+ return "unknown";
3461
+ if (at.parent === "record")
3462
+ return true;
3463
+ if (at.parent === "struct")
3464
+ return rowCanLack(at.original);
3465
+ return "unknown";
3466
+ };
3467
+ /** The clauses going further from a node, by the segment they take next, in order. */
3468
+ const bySegment = (below) => {
3469
+ const groups = [];
3470
+ for (const { rest, clause } of below) {
3471
+ if (rest.length === 0)
3472
+ continue;
3473
+ const [segment, ...after] = rest;
3474
+ const group = groups.find(([held]) => held === segment);
3475
+ const entry = { rest: after, clause };
3476
+ if (group === undefined)
3477
+ groups.push([segment, [entry]]);
3478
+ else
3479
+ group[1].push(entry);
3480
+ }
3481
+ return groups;
3482
+ };
3483
+ /**
3484
+ * The judgement of an update's clauses inside one field (#238), at a node: `schema`, reached as
3485
+ * `asDeclared` says ({@link writesFirstMemberOnly}), held by a `parent`.
3486
+ *
3487
+ * `strict` asks whether what they leave is read WHATEVER the row holds there, at every union the
3488
+ * clauses pass, passed through or ended at, at any depth: at a union, either (a) every member
3489
+ * reads what they leave below it, or (b) they write every property of one member that reads it
3490
+ * ({@link fixes}), so that the update itself sets which member the row holds. A member without
3491
+ * the next segment reads past it (a plain struct), or holds nothing there for DynamoDB to write
3492
+ * into (a scalar, a list given a property, a struct given a position), which refuses the update
3493
+ * and leaves the row as it was. Anything the schema can't judge isn't read, and two clauses on
3494
+ * one path (which DynamoDB refuses) aren't either.
3495
+ *
3496
+ * Otherwise it asks whether SOME row reads what they leave: one member at each union reads every
3497
+ * clause below it, the member taken alike for every clause under the same union. Anything the
3498
+ * schema can't judge is taken as read, and a member holding nothing there as not reading it.
3499
+ */
3500
+ const judge = (schema, below, asDeclared, parent, strict) => {
3501
+ const ending = below.filter(({ rest }) => rest.length === 0);
3502
+ const further = bySegment(below);
3503
+ const at = { _tag: "At", original: schema, asDeclared, parent };
3504
+ if (strict && ending.length > 0 && (ending.length > 1 || further.length > 0))
3505
+ return false;
3506
+ for (const { clause } of ending) {
3507
+ const verdict = endVerdict(clause, at);
3508
+ if (verdict === "unknown" ? !strict : verdict)
3509
+ continue;
3510
+ return false;
3511
+ }
3512
+ if (further.length === 0)
3513
+ return true;
3514
+ const opt = optionalField(schema);
3515
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3516
+ // Through a later member of an optional union, a path is written as declared, as `originalAt`
3517
+ // writes it ({@link writesFirstMemberOnly}).
3518
+ const first = opt?.union === undefined ? undefined : new Set(membersOf(opt.inner));
3519
+ const declaredFor = (member) => asDeclared || (first !== undefined && !first.has(member));
3520
+ const reads = (member) => memberReads(member, further, declaredFor(member), strict);
3521
+ if (members.length === 1)
3522
+ return reads(members[0]);
3523
+ // Members that don't name every segment alike are written as 1.40.0 wrote them, by the names
3524
+ // given ({@link membersNamedExactly}): what they leave isn't judged.
3525
+ if (!membersNamedExactly(members))
3526
+ return !strict;
3527
+ if (!strict)
3528
+ return members.some(reads);
3529
+ return (members.every(reads) ||
3530
+ members.some((member) => fixes(member, further, declaredFor(member)) && reads(member)));
3531
+ };
3532
+ /** {@link judge} under one member, for the clauses going further, by segment. */
3533
+ const memberReads = (member, further, asDeclared, strict) => further.every(([segment, below]) => {
3534
+ const read = readAs(member);
3535
+ const child = childAtSegment(read, segment);
3536
+ if (child !== undefined)
3537
+ return judge(child, below, asDeclared, parentOf(read), strict);
3538
+ const end = missingAt(read, segment);
3539
+ if (strict)
3540
+ return end._tag !== "Unknown";
3541
+ // A clause the schema can't judge is taken as read, wherever the member leaves it.
3542
+ if (below.every(({ clause }) => clause._tag === "Other"))
3543
+ return true;
3544
+ return end._tag === "Unread" || end._tag === "Unknown";
3545
+ });
3546
+ /**
3547
+ * Whether the clauses going further from a union's member write every property of it (#238):
3548
+ * each set or removed, or, for a property holding a plain struct, every property of THAT written
3549
+ * in turn, or for one holding a union, every property of one of its members that reads what they
3550
+ * leave. What the member holds after the update is then all theirs, whatever the row held. A
3551
+ * member that isn't a plain struct isn't known to be.
3552
+ */
3553
+ const fixes = (member, further, asDeclared) => {
3554
+ const read = readAs(member);
3555
+ if (parentOf(read) !== "struct")
3556
+ return false;
3557
+ return read.ast.propertySignatures.every((property) => {
3558
+ const group = further.find(([segment]) => segment === property.name);
3559
+ if (group === undefined)
3560
+ return false;
3561
+ const child = childAtSegment(read, property.name);
3562
+ return child !== undefined && fixedBy(child, group[1], asDeclared);
3563
+ });
3564
+ };
3565
+ /** Whether the clauses below a node set all of it ({@link fixes}). */
3566
+ const fixedBy = (schema, below, asDeclared) => {
3567
+ const ending = below.filter(({ rest }) => rest.length === 0);
3568
+ if (ending.length > 0) {
3569
+ return ending.length === 1 && below.length === 1 && ending[0].clause._tag !== "Other";
3570
+ }
3571
+ const further = bySegment(below);
3572
+ const opt = optionalField(schema);
3573
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3574
+ const first = opt?.union === undefined ? undefined : new Set(membersOf(opt.inner));
3575
+ if (members.length > 1 && !membersNamedExactly(members))
3576
+ return false;
3577
+ return members.some((member) => {
3578
+ const declared = asDeclared || (first !== undefined && !first.has(member));
3579
+ return (fixes(member, further, declared) &&
3580
+ (members.length === 1 || memberReads(member, further, declared, true)));
3581
+ });
3582
+ };
3583
+ const reads = (clauses, strict) => {
3584
+ const head = clauses[0]?.segments[0];
3585
+ const start = typeof head === "string"
3586
+ ? (ownValue(refTargets, head) ?? ownValue(modelFields, head))
3587
+ : undefined;
3588
+ // A field the walk can't follow is one the schema can't judge.
3589
+ if (start === undefined || clauses.some((clause) => clause.segments[0] !== head)) {
3590
+ return !strict;
3591
+ }
3592
+ const below = clauses.map((clause) => ({ rest: clause.segments.slice(1), clause }));
3593
+ return judge(start, below, false, "other", strict);
3594
+ };
3595
+ const readDecoders = new WeakMap();
3596
+ const readDecoder = (schema) => {
3597
+ const found = readDecoders.get(schema);
3598
+ if (found !== undefined)
3599
+ return found;
3600
+ const decode = Schema.decodeUnknownExit(schema);
3601
+ const fn = (value) => decode(asStored(value))._tag === "Success";
3602
+ readDecoders.set(schema, fn);
3603
+ return fn;
3604
+ };
3605
+ /**
3606
+ * A class as a read decodes it: from the struct of its fields (`from`), which a path into it
3607
+ * walks. Any other schema as it is.
3608
+ */
3609
+ const readSide = (schema) => {
3610
+ const { from, to } = schema;
3611
+ return schemaFieldsOf(schema) === undefined &&
3612
+ isSchemaLike(from) &&
3613
+ schemaFieldsOf(from) !== undefined &&
3614
+ isSchemaLike(to) &&
3615
+ SchemaAST.isDeclaration(to.ast)
3616
+ ? from
3617
+ : schema;
3618
+ };
3619
+ /** The READ schema's nodes at the end of a path: one by each member of each union on the way. */
3620
+ const readNodesAt = (segments) => {
3621
+ const [head, ...rest] = segments;
3622
+ if (typeof head !== "string" || !Object.hasOwn(readFields, head))
3623
+ return [];
3624
+ const nodes = [];
3625
+ const walk = (schema, depth) => {
3626
+ const opt = optionalField(schema);
3627
+ const members = membersOf(opt?.union ?? opt?.inner ?? schema);
3628
+ if (depth === rest.length) {
3629
+ nodes.push(...members);
3630
+ return;
3631
+ }
3632
+ for (const member of members) {
3633
+ const child = childAtSegment(readSide(member), rest[depth]);
3634
+ if (child !== undefined)
3635
+ walk(child, depth + 1);
3636
+ }
3637
+ };
3638
+ walk(readFields[head], 0);
3639
+ return nodes;
3640
+ };
2823
3641
  return {
3642
+ operand: (segments, value, kind) => {
3643
+ const forms = formsAt(segments);
3644
+ if (forms === null)
3645
+ return value;
3646
+ let chosen;
3647
+ for (const form of forms) {
3648
+ // A position that can't hold the value holds no row it could match.
3649
+ const stored = kind === "value" ? form.value(value) : form.contained(value);
3650
+ if (stored === undefined)
3651
+ continue;
3652
+ if (chosen !== undefined && !sameValue(chosen.stored, stored.stored))
3653
+ return value;
3654
+ chosen = stored;
3655
+ }
3656
+ return chosen === undefined ? value : chosen.stored;
3657
+ },
3658
+ readsAsGiven: (segments, value, kind) => {
3659
+ const nodes = readNodesAt(segments);
3660
+ if (kind === "value")
3661
+ return nodes.some((node) => readDecoder(node)(value));
3662
+ if (!Array.isArray(value))
3663
+ return false;
3664
+ return nodes.some((node) => {
3665
+ const element = listElementOf(node);
3666
+ return element !== undefined && value.every((each) => readDecoder(element)(each));
3667
+ });
3668
+ },
3669
+ pathSet: (segments, value) => {
3670
+ const first = schemaAt(segments);
3671
+ const encoded = encoderFor(`v:${JSON.stringify(segments)}`, () => first);
3672
+ const firstValidator = validatorFor(`v:${JSON.stringify(segments)}`, () => first?.stored);
3673
+ const written = encoded === null ? value : encoded(value);
3674
+ const check = (read) => (firstValidator === null ? undefined : firstValidator(read));
3675
+ const issue = check(written);
3676
+ if (issue === undefined)
3677
+ return { encoded: written, issue, otherWay: false, check };
3678
+ for (const way of waysTo(segments)) {
3679
+ if (way.end._tag !== "At")
3680
+ continue;
3681
+ const other = wayEncoder(way.end)(value);
3682
+ const taken = wayValidator(way.end);
3683
+ if (taken(other) === undefined) {
3684
+ return {
3685
+ encoded: other,
3686
+ issue: undefined,
3687
+ otherWay: true,
3688
+ refusedBefore: issue,
3689
+ check: taken,
3690
+ };
3691
+ }
3692
+ }
3693
+ return { encoded: written, issue, otherWay: false, check };
3694
+ },
3695
+ reads,
3696
+ passesUnion: (segments) => waysTo(segments).some((way) => way.choices.size > 0),
3697
+ checks: (segments, kind) => {
3698
+ const at = schemaAt(segments);
3699
+ if (at === undefined)
3700
+ return false;
3701
+ if (kind === "value")
3702
+ return true;
3703
+ // Elements are checked one by one: only a list that checks nothing of its own, and isn't
3704
+ // transformed as a whole, reads what they leave as they're checked.
3705
+ const opt = optionalField(at.stored);
3706
+ const lists = opt?.union !== undefined ? membersOf(opt.union) : [opt?.inner ?? at.stored];
3707
+ return (listElementOf(at.stored) !== undefined &&
3708
+ lists.every((list) => !SchemaAST.isArrays(list.ast) ||
3709
+ (plainNode(list.ast) && list.ast.encoding === undefined)));
3710
+ },
2824
3711
  validate: (segments, encoded) => {
2825
3712
  const fn = validatorFor(`v:${JSON.stringify(segments)}`, () => schemaAt(segments)?.stored);
2826
3713
  return fn === null ? undefined : fn(encoded);