@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,58 +3,376 @@
3
3
  *
4
4
  * Extracted from Aggregate.ts for decomposition. Not part of the public API.
5
5
  */
6
- import { Schema } from "effect";
7
- import { ConfiguredModelTag } from "../DynamoModel.js";
8
- import { extractArrayElement as extractArrayElementImpl, getSchemaFields as getSchemaFieldsImpl, isFieldOptional as isFieldOptionalImpl, } from "./SchemaAccessors.js";
9
- export const deriveAggregateSchemas = (schema, edges, pkComposites) => {
6
+ import { Option, Schema, SchemaAST } from "effect";
7
+ import { ConfiguredModelTag, getIdentifierField, getPackedFields } from "../DynamoModel.js";
8
+ import { bothKindsKeyRefusal, storedFieldAtPath } from "./CompositeCodec.js";
9
+ import { optionalField, resolveSystemFields } from "./EntitySchemas.js";
10
+ import { certainStruct, givenData, isRequiredStored, ownValue as own, protoRefusal, requiredProtoPropertyIn, setOwn, } from "./OwnNames.js";
11
+ /**
12
+ * What a caller's aggregate input gives under `name` where `create` reads it for an id, a `many` list
13
+ * or a sub-aggregate: read as 1.40.0 read it (`payload[name]`), and never a function, as 1.40.0 took
14
+ * none there ({@link givenData}).
15
+ */
16
+ export const given = givenData;
17
+ import { extractArrayElement as extractArrayElementImpl, extractKeyedValue, getSchemaFields as getSchemaFieldsImpl, isFieldOptional as isFieldOptionalImpl, } from "./SchemaAccessors.js";
18
+ // ---------------------------------------------------------------------------
19
+ // Timestamps
20
+ // ---------------------------------------------------------------------------
21
+ /**
22
+ * `timestamps` resolved over a value's fields, by the entity's rules: `Schema.optional` wraps the
23
+ * value that's read, a date is the library's, and any other field of that name is the caller's.
24
+ */
25
+ export const resolveAggregateStamps = (timestamps, fields, owner) => resolveSystemFields(timestamps, undefined, undefined, Object.fromEntries(Object.entries(fields ?? {}).map(([name, field]) => [
26
+ name,
27
+ optionalField(field)?.inner ?? field,
28
+ ])), {}, owner);
29
+ /**
30
+ * `[EDD-9121]`: a partition key the library would move on every write. An aggregate's rows all live
31
+ * under its partition key and a write only ever `Put`s rows under it, so the key would stop matching
32
+ * the value at the first update, and nothing could find the aggregate by what it holds.
33
+ */
34
+ export const refuseAggregateKeyOverMovingValue = (aggregate, timestamps, fields, composite) => {
35
+ const { updatedAt } = resolveAggregateStamps(timestamps, fields, `Aggregate "${aggregate}"`);
36
+ if (updatedAt !== null && composite.includes(updatedAt)) {
37
+ throw new Error(`[EDD-9121] Aggregate "${aggregate}": its partition key can't be composed from ` +
38
+ `"${updatedAt}". The library changes it on every write and a partition key never changes, ` +
39
+ `so the key would stop matching the value at the first update. Remove it from the ` +
40
+ `partition key, or use a field the library doesn't manage.`);
41
+ }
42
+ };
43
+ /**
44
+ * The fields of a `many` edge's ELEMENT, read off the parent model's field: the array's element
45
+ * (`players: Schema.Array(PlayerSheet)` → `PlayerSheet`'s), or a keyed collection's value, the
46
+ * elements of a custom `decompose` over it. `undefined` when the field says nothing about what its
47
+ * `decompose` returns, or the element exposes no fields (a scalar, or an opaque ref).
48
+ */
49
+ export const manyElementFields = (parentFields, edgeName) => {
50
+ const element = manyElementSchema(parentFields, edgeName);
51
+ return element === undefined ? undefined : getSchemaFields(element);
52
+ };
53
+ /**
54
+ * `[EDD-9121]`: a `many` edge's sort key the library would move on every write, on the root's edges
55
+ * and those of the sub-aggregates under it. Whose `updatedAt` it is, is the row's: a field of that
56
+ * name of another type is the caller's, and a root's turns the stamp off on every row.
57
+ */
58
+ export const refuseManySortKeysOverMovingValue = (aggregate, timestamps, rootFields, rootEdges) => {
59
+ const owner = `Aggregate "${aggregate}"`;
60
+ if (resolveAggregateStamps(timestamps, rootFields, owner).updatedAt === null)
61
+ return;
62
+ const walk = (fields, edges) => {
63
+ for (const [name, edge] of Object.entries(edges)) {
64
+ if (!("_tag" in edge))
65
+ continue;
66
+ if (edge._tag === "BoundSubAggregate") {
67
+ const sub = edge.aggregate;
68
+ walk(getSchemaFields(sub.schema), sub.edges);
69
+ }
70
+ else if (edge._tag === "ManyEdge") {
71
+ const entity = edge.entity;
72
+ const element = manyElementFields(fields, name) ??
73
+ (entity === undefined ? undefined : getSchemaFields(unwrapModel(entity.model)));
74
+ const { updatedAt } = resolveAggregateStamps(timestamps, element, owner);
75
+ if (updatedAt !== null && edge.sk?.composite.includes(updatedAt) === true) {
76
+ throw new Error(`[EDD-9121] Aggregate "${aggregate}": edge "${name}"'s sort key can't be composed ` +
77
+ `from "${updatedAt}". The library changes it on every write and a sort key never ` +
78
+ `changes, so the key would stop matching the value at the first update.`);
79
+ }
80
+ }
81
+ }
82
+ };
83
+ walk(rootFields, rootEdges);
84
+ };
85
+ /**
86
+ * The names a stored value of `schema` declares: the fields of its stored side, through optionality,
87
+ * classes, unions and suspensions. A record's keys are taken, not declared, and a declaration
88
+ * (`Schema.declare`) declares nothing that can be seen, so neither gives a name.
89
+ */
90
+ export const storedFieldNames = (schema) => {
91
+ const names = new Set();
92
+ const seen = new Set();
93
+ const visit = (ast) => {
94
+ if (seen.has(ast))
95
+ return;
96
+ seen.add(ast);
97
+ if (SchemaAST.isObjects(ast)) {
98
+ for (const property of ast.propertySignatures) {
99
+ if (typeof property.name === "string")
100
+ names.add(property.name);
101
+ }
102
+ }
103
+ else if (SchemaAST.isUnion(ast)) {
104
+ for (const member of ast.types)
105
+ visit(member);
106
+ }
107
+ else if (SchemaAST.isSuspend(ast)) {
108
+ let inner;
109
+ try {
110
+ inner = SchemaAST.toEncoded(ast.thunk());
111
+ }
112
+ catch {
113
+ return;
114
+ }
115
+ visit(inner);
116
+ }
117
+ };
118
+ visit(SchemaAST.toEncoded(schema.ast));
119
+ return names;
120
+ };
121
+ /** The index key attributes a read takes off the root's row. */
122
+ const ROOT_INDEX_ATTRIBUTES = new Set([
123
+ "gsi1pk",
124
+ "gsi1sk",
125
+ "gsi2pk",
126
+ "gsi2sk",
127
+ "gsi3pk",
128
+ "gsi3sk",
129
+ "gsi4pk",
130
+ "gsi4sk",
131
+ "gsi5pk",
132
+ "gsi5sk",
133
+ "lsi1sk",
134
+ "lsi2sk",
135
+ ]);
136
+ /** The names a read takes off every row, whatever its value declares: its type and the table's key. */
137
+ const ROW_RESERVED = new Set(["__edd_e__", "pk", "sk"]);
138
+ /**
139
+ * Whether a read up to 1.40.0 took the attribute `name` off a row of `kind` before handing back the
140
+ * value it holds, whatever the value declared: `__edd_e__`, `pk` and `sk` everywhere; on the root's
141
+ * row the index keys `gsi1pk` … `gsi5sk`, `lsi1sk` and `lsi2sk`; on a sub-aggregate's root row any
142
+ * name starting `pk`, `sk`, `gsi` or `lsi`; on an edge's row any name starting `gsi` or `lsi`.
143
+ * {@link readTakesOff} applies it to a name the value doesn't declare (#241).
144
+ */
145
+ export const takenOffThrough140 = (kind, name) => {
146
+ if (ROW_RESERVED.has(name))
147
+ return true;
148
+ switch (kind) {
149
+ case "root":
150
+ return ROOT_INDEX_ATTRIBUTES.has(name);
151
+ case "subAggregate":
152
+ return (name.startsWith("pk") ||
153
+ name.startsWith("sk") ||
154
+ name.startsWith("gsi") ||
155
+ name.startsWith("lsi"));
156
+ case "edge":
157
+ return name.startsWith("gsi") || name.startsWith("lsi");
158
+ }
159
+ };
160
+ /** A row's {@link ReadRow}: `declared` is what `declaredValueNames` gives for its value. */
161
+ export const readRowOf = (kind, config, declared) => ({
162
+ kind,
163
+ declared: new Set(declared ?? []),
164
+ keys: new Set(rowKeysOn(kind, config).map(([name]) => name)),
165
+ });
166
+ /**
167
+ * Whether a read takes the attribute `name` off a row before handing back the value it holds
168
+ * (#241): `__edd_e__`, `pk` and `sk` always; a name 1.40.0 took off ({@link takenOffThrough140})
169
+ * unless the row's value declares it at that position and the library writes no key attribute of
170
+ * that name there. A name the value doesn't declare is taken off as on 1.40.0, another writer's
171
+ * index key included. The one statement of the rule: every read asks it, and `create`'s refusal
172
+ * of a value given where the library writes another (`EDD-9159`) names the attributes it writes on
173
+ * a row by its write-side twin ({@link rowKeysOn}).
174
+ */
175
+ export const readTakesOff = (row, name) => {
176
+ if (ROW_RESERVED.has(name))
177
+ return true;
178
+ if (!takenOffThrough140(row.kind, name))
179
+ return false;
180
+ return row.keys.has(name) || !row.declared.has(name);
181
+ };
182
+ /**
183
+ * How a sub-aggregate's root row is read (#241): with an edge of its own, as a sub-aggregate's root
184
+ * (`"subAggregate"`); without one, as a `one` edge's row (`"edge"`), since assembly reads a
185
+ * sub-aggregate with no edges as it reads a `one` edge.
186
+ */
187
+ export const subAggregateRowKind = (edges) => Object.values(edges).some((edge) => typeof edge === "object" &&
188
+ edge !== null &&
189
+ "_tag" in edge &&
190
+ (edge._tag === "OneEdge" || edge._tag === "ManyEdge" || edge._tag === "BoundSubAggregate"))
191
+ ? "subAggregate"
192
+ : "edge";
193
+ /**
194
+ * The key attributes the library writes on every row an aggregate writes, over a value's field of
195
+ * the same name (#241): `__edd_e__`, the partition key attribute, `sk` and, with a collection index,
196
+ * the collection sort key's copy.
197
+ */
198
+ export const rowKeyAttributes = (config) => [
199
+ ["__edd_e__", "the attribute holding its entity type"],
200
+ [config.pk.field, "the attribute holding the partition key"],
201
+ ["sk", "the attribute holding its sort key"],
202
+ ...(config.collection.index === undefined || config.collection.sk === undefined
203
+ ? []
204
+ : [
205
+ [
206
+ config.collection.sk.field,
207
+ "the attribute holding the collection sort key's copy",
208
+ ],
209
+ ]),
210
+ ];
211
+ /**
212
+ * The root's list keys, written on its row only when every list composite has a value (they're
213
+ * sparse), over a field of the same name (#241).
214
+ */
215
+ export const listKeyAttributes = (config) => config.list === undefined
216
+ ? []
217
+ : [
218
+ [config.list.pk.field, "the attribute holding its list partition key"],
219
+ [config.list.sk.field, "the attribute holding its list sort key"],
220
+ ];
221
+ /**
222
+ * The key attributes the library writes on a row of `kind` (#241): those of every row
223
+ * ({@link rowKeyAttributes}) and, on the root's, its list keys (sparse, but named whether or not a
224
+ * write composes them).
225
+ */
226
+ export const rowKeysOn = (kind, config) => [
227
+ ...rowKeyAttributes(config),
228
+ ...(kind === "root" ? listKeyAttributes(config) : []),
229
+ ];
230
+ /**
231
+ * The field names the value of each kind of row declares, for {@link readTakesOff}: the root's and
232
+ * a sub-aggregate's own fields (`own`, those no edge claims), a `one` edge's value (the field
233
+ * holding it), a `many` edge's element (none with a custom `decompose`). `undefined` where nothing
234
+ * is declared.
235
+ */
236
+ export const declaredValueNames = {
237
+ own: (fields, edges) => Object.keys(fields ?? {}).filter((name) => !Object.hasOwn(edges, name)),
238
+ one: (fields, edgeName) => {
239
+ const value = own(fields, edgeName);
240
+ return value === undefined ? undefined : storedFieldNames(value);
241
+ },
242
+ many: (fields, edgeName, edge) => {
243
+ if (edge.decompose !== undefined)
244
+ return undefined;
245
+ const element = manyElementSchema(fields, edgeName);
246
+ return element === undefined ? undefined : storedFieldNames(element);
247
+ },
248
+ };
249
+ /**
250
+ * `[EDD-9128]`: a key an aggregate composes from a field storing both numeric kinds
251
+ * (`bothKindsKeyRefusal`): its partition key, its collection and list keys, and a `many` edge's sort
252
+ * key, on the root's edges and those of the sub-aggregates under it. A sort-key composite that's a
253
+ * path into a value (`player.id`) is followed to the field a row stores there, through an optional,
254
+ * nullable, suspended or class value on the way (`storedFieldAtPath`): a value transformed on the
255
+ * way is judged by what it's stored as, so a struct storing a number at `n` and decoding it to a
256
+ * union of both kinds loads, and one storing either kind there doesn't.
257
+ */
258
+ export const refuseAggregateKeysOverBothKinds = (aggregate, rootFields, config, rootEdges) => {
259
+ const owner = `Aggregate "${aggregate}"`;
260
+ const refuse = (where, fields, composites) => {
261
+ for (const attr of composites) {
262
+ const field = storedFieldAtPath(fields, attr);
263
+ if (field === undefined)
264
+ continue;
265
+ const refused = bothKindsKeyRefusal(owner, where, attr, field);
266
+ if (refused !== undefined)
267
+ throw refused;
268
+ }
269
+ };
270
+ refuse("its partition key", rootFields, config.pk.composite);
271
+ refuse("its collection sort key", rootFields, config.collection?.sk?.composite ?? []);
272
+ if (config.list !== undefined) {
273
+ refuse("its list partition key", rootFields, config.list.pk.composite);
274
+ refuse("its list sort key", rootFields, config.list.sk.composite);
275
+ }
276
+ const walk = (fields, edges) => {
277
+ for (const [name, edge] of Object.entries(edges)) {
278
+ if (!("_tag" in edge))
279
+ continue;
280
+ if (edge._tag === "BoundSubAggregate") {
281
+ const sub = edge.aggregate;
282
+ walk(getSchemaFields(sub.schema), sub.edges);
283
+ }
284
+ else if (edge._tag === "ManyEdge") {
285
+ const entity = edge.entity;
286
+ const element = manyElementFields(fields, name) ??
287
+ (entity === undefined ? undefined : getSchemaFields(unwrapModel(entity.model)));
288
+ refuse(`edge "${name}"'s sort key`, element, edge.sk?.composite ?? []);
289
+ }
290
+ }
291
+ };
292
+ walk(rootFields, rootEdges);
293
+ };
294
+ /** The dates the rows of a value with `fields` declare, of those `timestamps` stamps. */
295
+ const managedDates = (stamps, fields) => {
296
+ const own = resolveAggregateStamps(stamps.config, fields, "Aggregate");
297
+ return new Set([own.createdAtCollision ? own.createdAt : null, own.updatedAtCollision ? own.updatedAt : null]
298
+ .filter((name) => name !== null)
299
+ .filter((name) => stamps.names.has(name)));
300
+ };
301
+ /** A managed date's input field: optional, supplied or not. */
302
+ const stampInput = (field) => Schema.optionalKey((optionalField(field)?.inner ?? field));
303
+ /** A row's value on the input: as the model has it, but for the dates the library stamps. */
304
+ const rowInput = (schema, stamps) => {
305
+ const fields = getSchemaFields(schema);
306
+ if (fields === undefined)
307
+ return schema;
308
+ const managed = managedDates(stamps, fields);
309
+ if (managed.size === 0)
310
+ return schema;
311
+ return Schema.Struct(Object.fromEntries(Object.entries(fields).map(([name, field]) => [
312
+ name,
313
+ managed.has(name) ? stampInput(field) : field,
314
+ ])));
315
+ };
316
+ export const deriveAggregateSchemas = (schema, edges, pkComposites, timestamps) => {
317
+ const own = resolveAggregateStamps(timestamps, getSchemaFields(schema), "Aggregate");
318
+ return deriveWithStamps(schema, edges, pkComposites, {
319
+ config: timestamps,
320
+ names: new Set([own.createdAt, own.updatedAt].filter((name) => name !== null)),
321
+ });
322
+ };
323
+ const deriveWithStamps = (schema, edges, pkComposites, stamps) => {
10
324
  const fields = getSchemaFields(schema);
11
325
  if (!fields) {
12
326
  return { inputSchema: schema, createSchema: schema, updateSchema: schema };
13
327
  }
14
328
  const omit = new Set(pkComposites);
329
+ const managed = managedDates(stamps, fields);
15
330
  const newFields = {};
16
331
  for (const [name, fieldSchema] of Object.entries(fields)) {
17
332
  if (omit.has(name))
18
333
  continue;
19
- const edge = edges[name];
334
+ const edge = own(edges, name);
20
335
  if (edge && "_tag" in edge) {
21
336
  const isOpt = isFieldOptional(fieldSchema);
22
- if (edge._tag === "RefEdge" || edge._tag === "OneEdge") {
23
- // RefEdge / OneEdge → ${name}Id: Schema.String
24
- newFields[`${name}Id`] = isOpt ? Schema.optionalKey(Schema.String) : Schema.String;
337
+ if ((edge._tag === "OneEdge" || edge._tag === "RefEdge") &&
338
+ (edge.entity === undefined || refKeyComposite(edge.entity) === undefined)) {
339
+ // Nothing to fetch by: no entity, or one no single id names (its key has two composites,
340
+ // or none). `create` takes the value, and refuses an id for it (`EDD-9129`).
341
+ const value = rowInput(optionalField(fieldSchema)?.inner ?? fieldSchema, stamps);
342
+ setOwn(newFields, name, isOpt ? Schema.optionalKey(value) : value);
343
+ }
344
+ else if (edge._tag === "RefEdge" || edge._tag === "OneEdge") {
345
+ const id = refIdInput(edge.entity);
346
+ newFields[`${name}Id`] = isOpt ? Schema.optionalKey(id) : id;
25
347
  }
26
348
  else if (edge._tag === "BoundSubAggregate") {
27
349
  const sub = edge.aggregate;
28
- const subSchemas = deriveAggregateSchemas(sub.schema, sub.edges, []);
29
- newFields[name] = isOpt
30
- ? Schema.optionalKey(subSchemas.inputSchema)
31
- : subSchemas.inputSchema;
350
+ const subSchemas = deriveWithStamps(sub.schema, sub.edges, [], stamps);
351
+ setOwn(newFields, name, isOpt ? Schema.optionalKey(subSchemas.inputSchema) : subSchemas.inputSchema);
32
352
  }
33
353
  else if (edge._tag === "ManyEdge") {
34
354
  const manyEdge = edge;
35
355
  const fieldKey = manyEdge.inputField ?? name;
36
- const elemSchema = deriveElementInputSchema(fieldSchema, manyEdge.entity);
356
+ const elemSchema = deriveElementInputSchema(fieldSchema, manyEdge.entity, stamps);
37
357
  if (elemSchema) {
38
- newFields[fieldKey] = isOpt
39
- ? Schema.optionalKey(Schema.Array(elemSchema))
40
- : Schema.Array(elemSchema);
358
+ setOwn(newFields, fieldKey, isOpt ? Schema.optionalKey(Schema.Array(elemSchema)) : Schema.Array(elemSchema));
41
359
  }
42
360
  else {
43
- newFields[fieldKey] = fieldSchema;
361
+ setOwn(newFields, fieldKey, keyedInput(fieldSchema, stamps));
44
362
  }
45
363
  }
46
364
  continue;
47
365
  }
48
366
  // Regular field → keep as-is (toCodecJson applied at the end handles Date)
49
- newFields[name] = fieldSchema;
367
+ setOwn(newFields, name, managed.has(name) ? stampInput(fieldSchema) : fieldSchema);
50
368
  }
51
369
  const inputSchema = Schema.toCodecJson(Schema.Struct(newFields));
52
370
  // Update schema: all fields optional
53
371
  const optionalFields = {};
54
372
  for (const [name, fieldSchema] of Object.entries(newFields)) {
55
- optionalFields[name] = isFieldOptional(fieldSchema)
373
+ setOwn(optionalFields, name, isFieldOptional(fieldSchema)
56
374
  ? fieldSchema
57
- : Schema.optional(fieldSchema);
375
+ : Schema.optional(fieldSchema));
58
376
  }
59
377
  const updateSchema = Schema.toCodecJson(Schema.Struct(optionalFields));
60
378
  // Runtime members are `Schema.Codec<unknown>`-shaped; the precise input type
@@ -62,6 +380,20 @@ export const deriveAggregateSchemas = (schema, edges, pkComposites) => {
62
380
  // top-level `Aggregate.make` overload uses. `createSchema` aliases `inputSchema`.
63
381
  return { inputSchema, createSchema: inputSchema, updateSchema };
64
382
  };
383
+ /** A `Schema.Record` many edge's input (a custom `decompose`): its values' stamps are optional. */
384
+ const keyedInput = (fieldSchema, stamps) => {
385
+ const inner = optionalField(fieldSchema)?.inner ?? fieldSchema;
386
+ if (!SchemaAST.isObjects(inner.ast))
387
+ return fieldSchema;
388
+ const record = inner;
389
+ if (record.key === undefined || record.value === undefined)
390
+ return fieldSchema;
391
+ const value = rowInput(record.value, stamps);
392
+ if (value === record.value)
393
+ return fieldSchema;
394
+ const input = Schema.Record(record.key, value);
395
+ return isFieldOptional(fieldSchema) ? Schema.optionalKey(input) : input;
396
+ };
65
397
  /**
66
398
  * Check if a field schema represents an optional field.
67
399
  *
@@ -79,47 +411,392 @@ export const deriveEntityFieldName = (entity) => {
79
411
  const identifier = "identifier" in s && typeof s.identifier === "string" ? s.identifier : entity.entityType;
80
412
  return identifier.charAt(0).toLowerCase() + identifier.slice(1);
81
413
  };
414
+ // ---------------------------------------------------------------------------
415
+ // Ref ids: what one id of an edge's entity names, and which values hold one
416
+ // ---------------------------------------------------------------------------
417
+ /**
418
+ * The distinct attributes an entity's primary key is composed from, its partition key's first. An
419
+ * attribute in both halves (`pk: ["lineId"]`, `sk: ["lineId"]`) is one attribute: one value of it
420
+ * names one item.
421
+ */
422
+ export const refKeyComposites = (entity) => {
423
+ const primary = entity.indexes?.primary;
424
+ return [...new Set([...(primary?.pk?.composite ?? []), ...(primary?.sk?.composite ?? [])])];
425
+ };
426
+ /**
427
+ * The one attribute an id of `entity` is a value of: its primary key's only distinct composite.
428
+ * `undefined` for a key composed from more than one attribute, or none: no one id names one item.
429
+ */
430
+ export const refKeyComposite = (entity) => {
431
+ const composites = refKeyComposites(entity);
432
+ return composites.length === 1 ? composites[0] : undefined;
433
+ };
82
434
  /**
83
- * Derive input schema for a many-edge array element.
84
- * Extracts the element type from the field schema (which may be an Array
85
- * or optional(Array)). If the element IS the entity (matches the entity model),
86
- * transforms to Schema.String. Otherwise, finds the entity-derived field within
87
- * the element and transforms it.
435
+ * The attribute of `entity` an entity-level ref id (`Entity.make({ refs })`'s `${field}Id`) names:
436
+ * its {@link refKeyComposite}, as an aggregate edge's id (#214, #241). It's fetched under that, read
437
+ * back from the stored ref under that (`putValuesOf`, a row check), and a cascade from `entity` is
438
+ * keyed by it. An entity keyed by more than one composite has none: its identifier, as up to
439
+ * 1.40.0. `undefined` with neither.
88
440
  */
89
- export const deriveElementInputSchema = (arrayFieldSchema, entity) => {
441
+ export const refIdAttribute = (entity) => refKeyComposite(entity) ?? getIdentifierField(entity.model)?.name;
442
+ /**
443
+ * The model field an id of `entity` is a value of (its {@link refKeyComposite}), `undefined` when
444
+ * its key has no one composite or its model's fields can't be read.
445
+ */
446
+ export const refIdField = (entity) => {
447
+ const name = refKeyComposite(entity);
448
+ return name === undefined ? undefined : own(getSchemaFields(unwrapModel(entity.model)), name);
449
+ };
450
+ /**
451
+ * The schema `create` takes an id of `entity` as: its key composite's own field, so a number keyed
452
+ * entity takes a number. `Schema.String` when the field can't be read, as before.
453
+ */
454
+ const refIdInput = (entity) => refIdField(entity) ?? Schema.String;
455
+ const jsonCodecs = new WeakMap();
456
+ /** A field's JSON codec (`Schema.toCodecJson`), once per field; `null` where it has none. */
457
+ const jsonCodecOf = (field) => {
458
+ const cached = jsonCodecs.get(field);
459
+ if (cached !== undefined)
460
+ return cached;
461
+ let codec;
462
+ try {
463
+ codec = Schema.toCodecJson(field);
464
+ }
465
+ catch {
466
+ codec = null;
467
+ }
468
+ jsonCodecs.set(field, codec);
469
+ return codec;
470
+ };
471
+ /**
472
+ * An id given for `entity`, as a value of its key composite ({@link refIdField}): the value itself
473
+ * when it is one (`5` of a number, `5n` of a bigint, a `Date`), or what it decodes to from its JSON
474
+ * or stored form (`"5"` of a `NumberFromString` or a bigint, an ISO string of a date). `None` when it
475
+ * is neither: it names no item. Without a key field to read, a string is taken as given and nothing
476
+ * else, as it always was.
477
+ */
478
+ export const refIdValue = (entity, value) => {
479
+ const field = refIdField(entity);
480
+ if (field === undefined)
481
+ return typeof value === "string" ? Option.some(value) : Option.none();
482
+ return keyValueOf(field, value);
483
+ };
484
+ /**
485
+ * A value given for a key composite whose field is `field`, as a value of that field: the value
486
+ * itself when it is one, or what it decodes to from its JSON or stored form. `None` when it is
487
+ * neither. What an aggregate edge's id ({@link refIdValue}) and an entity-level ref's
488
+ * `${field}Id` name are both read through it (#214, #241).
489
+ */
490
+ export const keyValueOf = (field, value) => {
491
+ const codec = field;
492
+ if (Schema.is(codec)(value))
493
+ return Option.some(value);
494
+ const json = jsonCodecOf(field);
495
+ const fromJson = json === null
496
+ ? Option.none()
497
+ : Schema.decodeUnknownOption(json)(value);
498
+ return Option.isSome(fromJson) ? fromJson : Schema.decodeUnknownOption(codec)(value);
499
+ };
500
+ // ---------------------------------------------------------------------------
501
+ // A `many` element's references: which values `create` fetches an entity for
502
+ // ---------------------------------------------------------------------------
503
+ /** What a copy of a schema node may change without changing what the node holds. */
504
+ const notWhatItHolds = new Set(["annotations", "checks", "context"]);
505
+ /**
506
+ * Whether two schema nodes are one schema: the same node, or a copy of it that changes only its
507
+ * annotations (`DynamoModel.ref`, `.annotate`), its checks (`.check`) or the optionality of the key
508
+ * it's under. Every other part is the same object. Decided from the definitions alone: a struct
509
+ * declared again with the same fields is another schema.
510
+ */
511
+ const isSameSchemaNode = (a, b) => {
512
+ if (a === b)
513
+ return true;
514
+ if (a._tag !== b._tag)
515
+ return false;
516
+ const held = (ast) => Object.keys(ast).filter((key) => !notWhatItHolds.has(key));
517
+ const keys = held(a);
518
+ return (keys.length === held(b).length &&
519
+ keys.every((key) => a[key] ===
520
+ b[key]));
521
+ };
522
+ /**
523
+ * Whether a schema is the entity's own model: the schema its definition declares (its
524
+ * `DynamoModel.configure` wrapper taken off), or a copy of it that changes only its annotations, its
525
+ * checks or its brand (`isSameSchemaNode`), compared by reference. An identifier is never identity:
526
+ * a class of the entity's identifier is another schema, as is a struct declared again with the
527
+ * entity's fields. Every question of whether a schema is the entity is asked of this.
528
+ */
529
+ export const isEntityModel = (schema, entity) => isSameSchemaNode(schema.ast, unwrapModel(entity.model).ast);
530
+ /**
531
+ * Whether a field's schema holds the entity's own model ({@link isEntityModel}), under
532
+ * `Schema.optional` / `Schema.optionalKey` at most. An `Option`, a `NullOr` or a `Result` of it holds
533
+ * something else: a record fetched for it is no value of the field.
534
+ */
535
+ const holdsEntityModel = (field, entity) => {
536
+ if (field === undefined)
537
+ return false;
538
+ const optional = optionalField(field);
539
+ if (optional?.union !== undefined)
540
+ return false;
541
+ return isEntityModel(optional?.inner ?? field, entity);
542
+ };
543
+ /**
544
+ * Whether a `many` element is the entity itself (`Array<Umpire>`): the entity's own model
545
+ * ({@link isEntityModel}). Its values are the entity whole, or an id.
546
+ */
547
+ export const isEntityElement = (element, entity) => element !== undefined && isEntityModel(element, entity);
548
+ /**
549
+ * The field of a `many` element that holds the entity, where the element's definition says so,
550
+ * `undefined` where it doesn't. All of these hold:
551
+ *
552
+ * 1. The element is a plain `Schema.Struct` or `Schema.Class`: one with fields of its own. A
553
+ * transformation, a union, a `suspend` or a declaration has none.
554
+ * 2. Its field of the entity's name (`deriveEntityFieldName`) holds the entity's own model
555
+ * (`holdsEntityModel`).
556
+ * 3. It doesn't declare `${field}Id` itself: a declared one is the element's own data.
557
+ *
558
+ * Such an element's input takes an id of the entity's key composite under `${field}Id`.
559
+ */
560
+ export const entityFieldOf = (element, entity) => {
561
+ const fields = element === undefined ? undefined : getSchemaFields(element);
562
+ if (fields === undefined)
563
+ return undefined;
564
+ const name = deriveEntityFieldName(entity);
565
+ if (Object.hasOwn(fields, `${name}Id`))
566
+ return undefined;
567
+ return holdsEntityModel(own(fields, name), entity) ? name : undefined;
568
+ };
569
+ /**
570
+ * Whether `create` fetches `entity` for `value`'s `${field}Id`, `value` a value of a definition
571
+ * declaring `fields` (`undefined` where it declares none: a union, a transformation): the parent
572
+ * model's, its `field` the edge's name, for a `one` or `ref` edge; a `many` element's, its `field`
573
+ * the entity's name (`deriveEntityFieldName`). One rule for every edge:
574
+ *
575
+ * 1. `null` and `undefined` give no id.
576
+ * 2. A string is fetched, exactly as on 1.39.0, whatever the definition declares: it replaces a
577
+ * record given whole in `field` with the one fetched, and a `${field}Id` the definition declares
578
+ * is taken out of the value, as 1.39.0 took it.
579
+ * 3. Any other id (a number, a bigint, a date: a value of the entity's key composite) is fetched only
580
+ * where the definition's `field` holds the entity's own model (`holdsEntityModel`), the definition
581
+ * doesn't declare `${field}Id`, which is then its own data, and `field` isn't given whole: a
582
+ * record given is never replaced or read again. 1.39.0 fetched none of these.
583
+ */
584
+ export const holdsRefId = (fields, field, entity, value) => {
585
+ const id = given(value, `${field}Id`);
586
+ if (id == null)
587
+ return false;
588
+ if (typeof id === "string")
589
+ return true;
590
+ return (fields !== undefined &&
591
+ !Object.hasOwn(fields, `${field}Id`) &&
592
+ holdsEntityModel(own(fields, field), entity) &&
593
+ given(value, field) == null);
594
+ };
595
+ /**
596
+ * Whether 1.39.0 fetched an element that is the entity by its own key `key` (`lineId` of a `Line`
597
+ * keyed by `lineId`) and completed. It fetched under the model's identifier (`id` without one), so
598
+ * only where that is the entity's one key composite; and it took the key out of the element given,
599
+ * so only where the element doesn't require it. Everywhere else it died composing the key, or
600
+ * refused the element without its key.
601
+ */
602
+ const fetchedByOwnKey139 = (fields, entity, key) => {
603
+ const declared = own(fields, key);
604
+ return (refKeyComposite(entity) === key &&
605
+ (getIdentifierField(entity.model)?.name ?? "id") === key &&
606
+ declared !== undefined &&
607
+ isFieldOptional(declared));
608
+ };
609
+ /**
610
+ * {@link holdsRefId} for a `many` element given as an object, of the element's schema. An element
611
+ * that is the entity ({@link isEntityElement}), given whole, holds no id in its own key: where the
612
+ * entity is keyed by `${field}Id` (`lineId` of a `Line`), that is the entity's own value, which
613
+ * 1.39.0 took for an id to fetch and failed on. It is left unfetched exactly where 1.39.0 failed:
614
+ * where 1.39.0 fetched it and completed ({@link fetchedByOwnKey139}), it is fetched.
615
+ */
616
+ export const elementHoldsRef = (element, entity, value) => {
617
+ const field = deriveEntityFieldName(entity);
618
+ const fields = element === undefined ? undefined : getSchemaFields(element);
619
+ if (isEntityElement(element, entity) &&
620
+ refKeyComposites(entity).includes(`${field}Id`) &&
621
+ !fetchedByOwnKey139(fields, entity, `${field}Id`)) {
622
+ return false;
623
+ }
624
+ return holdsRefId(fields, field, entity, value);
625
+ };
626
+ /**
627
+ * The element schema of a `many` edge, read off the parent model's field: the array's element, or a
628
+ * keyed collection's value. `undefined` when the field says nothing of it.
629
+ */
630
+ export const manyElementSchema = (parentFields, edgeName) => {
631
+ const field = own(parentFields, edgeName);
632
+ if (field === undefined)
633
+ return undefined;
634
+ return extractArrayElement(field) ?? extractKeyedValue(field);
635
+ };
636
+ /**
637
+ * Derive input schema for a many-edge array element, as `create` takes it, for an edge whose entity
638
+ * one id names:
639
+ *
640
+ * - **An element that is the entity** ({@link isEntityElement}): an id of the entity's key composite
641
+ * (`refIdInput`), or the entity whole.
642
+ * - **An element whose definition names the field holding the entity** ({@link entityFieldOf}): the
643
+ * element whole, `${field}Id` beside it or not, or with `${field}Id`, an id of the entity's key
644
+ * composite, in place of that field. Neither refuses the other's key: given both, both are kept,
645
+ * and `create` judges them as it judges a value given to it directly (`elementHoldsRef`).
646
+ * - **Any other element**, as on 1.39.0: the field of the entity's name, if it has one, taken as
647
+ * `${field}Id: Schema.String`. An element with no fields of its own (a union among them) is taken
648
+ * as declared.
649
+ *
650
+ * An entity no single id names is given whole, never by id (`EDD-9129`), so its elements are taken as
651
+ * declared. A date the library stamps is optional throughout.
652
+ */
653
+ export const deriveElementInputSchema = (arrayFieldSchema, entity, stamps) => {
90
654
  const elemSchema = extractArrayElement(arrayFieldSchema);
91
655
  if (!elemSchema)
92
656
  return undefined;
93
- const elemFields = getSchemaFields(elemSchema);
94
- // Check if the element itself IS the entity model (e.g., Array<Umpire>)
95
- if (entity && elemFields && isSchemaMatchingEntity(elemSchema, entity)) {
96
- // Element IS the entity → array of IDs (Schema.String)
97
- return Schema.String;
98
- }
99
- if (!elemFields)
100
- return elemSchema;
101
- // Element wraps entity + attributes — find the entity-derived field and transform it
102
- if (entity) {
103
- const entityFieldName = deriveEntityFieldName(entity);
104
- let hasChanges = false;
105
- const newFields = {};
106
- for (const [name, fSchema] of Object.entries(elemFields)) {
107
- if (name === entityFieldName) {
108
- // This field references the entity — transform to ${name}Id: Schema.String
109
- const isOpt = isFieldOptional(fSchema);
110
- newFields[`${name}Id`] = isOpt ? Schema.optionalKey(Schema.String) : Schema.String;
111
- hasChanges = true;
657
+ const fetched = entity !== undefined && refKeyComposite(entity) !== undefined ? entity : undefined;
658
+ if (fetched !== undefined && isEntityElement(elemSchema, fetched)) {
659
+ return Schema.Union([
660
+ refIdInput(fetched),
661
+ stampedElement(elemSchema, stamps),
662
+ ]);
663
+ }
664
+ const fields = getSchemaFields(elemSchema);
665
+ if (fields === undefined || fetched === undefined) {
666
+ return fields === undefined ? elemSchema : stampedElement(elemSchema, stamps);
667
+ }
668
+ const named = entityFieldOf(elemSchema, fetched);
669
+ if (named !== undefined) {
670
+ const own = stampedFields(fields, stamps);
671
+ const id = refIdInput(fetched);
672
+ const byId = {};
673
+ for (const [name, field] of Object.entries(own)) {
674
+ if (name === named) {
675
+ byId[`${name}Id`] = isFieldOptional(field) ? Schema.optionalKey(id) : id;
112
676
  }
113
677
  else {
114
- newFields[name] = fSchema;
678
+ setOwn(byId, name, field);
115
679
  }
116
680
  }
117
- if (!hasChanges)
118
- return elemSchema;
119
- return Schema.Struct(newFields);
681
+ return Schema.Union([
682
+ Schema.Struct({ ...own, [`${named}Id`]: Schema.optional(id) }),
683
+ Schema.Struct(byId),
684
+ ]);
685
+ }
686
+ return element139(elemSchema, fields, deriveEntityFieldName(fetched), stamps);
687
+ };
688
+ /** An element's fields, the dates the library stamps optional. */
689
+ const stampedFields = (fields, stamps) => {
690
+ const managed = stamps === undefined ? undefined : managedDates(stamps, fields);
691
+ return Object.fromEntries(Object.entries(fields).map(([name, field]) => [
692
+ name,
693
+ managed?.has(name) === true ? stampInput(field) : field,
694
+ ]));
695
+ };
696
+ /** An element as declared, the dates the library stamps optional: the element itself when none is. */
697
+ const stampedElement = (element, stamps) => {
698
+ const fields = getSchemaFields(element);
699
+ if (fields === undefined || stamps === undefined || managedDates(stamps, fields).size === 0) {
700
+ return element;
701
+ }
702
+ return Schema.Struct(stampedFields(fields, stamps));
703
+ };
704
+ /**
705
+ * An element as 1.39.0's input took it: its field of the entity's name, if it has one, as
706
+ * `${name}Id: Schema.String`, optional when the field is; the dates the library stamps optional.
707
+ * The element itself when nothing changes.
708
+ */
709
+ const element139 = (element, fields, entityFieldName, stamps) => {
710
+ const managed = stamps === undefined ? undefined : managedDates(stamps, fields);
711
+ let hasChanges = false;
712
+ const newFields = {};
713
+ for (const [name, field] of Object.entries(fields)) {
714
+ if (name === entityFieldName) {
715
+ newFields[`${name}Id`] = isFieldOptional(field)
716
+ ? Schema.optionalKey(Schema.String)
717
+ : Schema.String;
718
+ hasChanges = true;
719
+ }
720
+ else if (managed?.has(name) === true) {
721
+ setOwn(newFields, name, stampInput(field));
722
+ hasChanges = true;
723
+ }
724
+ else {
725
+ setOwn(newFields, name, field);
726
+ }
727
+ }
728
+ return hasChanges ? Schema.Struct(newFields) : element;
729
+ };
730
+ /**
731
+ * The paths of an aggregate's `many` edges, sub-aggregates included. The collection such a field is
732
+ * declared as is taken apart by `decompose` and put back by `assemble`, so it's never stored itself.
733
+ */
734
+ export const manyEdgePaths = (edges, at = "") => {
735
+ const paths = new Set();
736
+ for (const [name, edge] of Object.entries(edges ?? {})) {
737
+ const path = at === "" ? name : `${at}.${name}`;
738
+ const tagged = edge;
739
+ if (tagged._tag === "ManyEdge")
740
+ paths.add(path);
741
+ if (tagged._tag === "BoundSubAggregate") {
742
+ for (const nested of manyEdgePaths(tagged.aggregate?.edges, path))
743
+ paths.add(nested);
744
+ }
120
745
  }
121
- return elemSchema;
746
+ return paths;
122
747
  };
748
+ /**
749
+ * `[EDD-9153]`: an aggregate naming `__proto__` where every row it writes would hold it. A
750
+ * required sub-aggregate's discriminator is an attribute of each of its rows. A root's or a
751
+ * sub-aggregate root's required field is an attribute of its row, and so is a required `ref` edge
752
+ * (its entity is stored inline, under the edge's name); a required property of a required `one`
753
+ * edge's value is an attribute of the edge's row; and a required property of any of those, reached
754
+ * through containers each certain to hold a map, is a property of a stored map
755
+ * (`requiredProtoPropertyIn`). A JavaScript object can't take that name by assignment and the AWS
756
+ * SDK's marshaller drops an attribute or an entry so named, so 1.40.0 failed on such a value, or
757
+ * stored the row without it and then couldn't read it (#239). Wherever a container on the way may be
758
+ * left out or hold no map (an optional or nullable sub-aggregate, edge value or field, a union, a
759
+ * list, a record, an `Option`), the definition loads: a write that gives the name is refused when
760
+ * it's sent (`EDD-9165`). An edge's own name (a `one`, `many` or sub-aggregate edge) is no
761
+ * attribute: it may be `__proto__`. Nothing stored as JSON text is looked into. Thrown at `make`.
762
+ */
763
+ export const refuseAggregateProtoName = (entityType, model, edges) => {
764
+ const refuse = (what) => protoRefusal("EDD-9153", `Aggregate "${entityType}"`, what);
765
+ const walk = (node, nodeEdges, path) => {
766
+ const fields = getSchemaFields(unwrapModel(node)) ?? {};
767
+ for (const name of Object.keys(fields)) {
768
+ const field = own(fields, name);
769
+ const at = path === "" ? name : `${path}.${name}`;
770
+ const edge = own(nodeEdges, name);
771
+ if (edge?._tag === "BoundSubAggregate" && edge.aggregate !== undefined) {
772
+ // A sub-aggregate's rows are written only where the aggregate holds one: an optional or a
773
+ // nullable sub-aggregate may leave them out, and then nothing below it is certain.
774
+ if (certainStruct(field.ast) === undefined)
775
+ continue;
776
+ if (Object.hasOwn(edge.discriminator ?? {}, "__proto__")) {
777
+ throw refuse(`a discriminator of "${at}"`);
778
+ }
779
+ walk(edge.aggregate.schema, edge.aggregate.edges, at);
780
+ continue;
781
+ }
782
+ const ofEdge = edge?._tag === "OneEdge" || edge?._tag === "ManyEdge";
783
+ if (!ofEdge && name === "__proto__" && isRequiredStored(field.ast)) {
784
+ const of = path === "" ? "the root" : `"${path}"`;
785
+ throw refuse(edge?._tag === "RefEdge" ? `a ref edge of ${of}` : `a field of ${of}`);
786
+ }
787
+ if (!ofEdge && packedOf(node).has(name))
788
+ continue;
789
+ // A `one` edge's value is its row: its packed fields are the edge entity's.
790
+ const packed = edge?._tag === "OneEdge" ? packedOf(edge.entity?.model) : undefined;
791
+ const property = requiredProtoPropertyIn(field.ast, at, packed);
792
+ if (property !== undefined)
793
+ throw refuse(`the property at "${property}"`);
794
+ }
795
+ };
796
+ walk(model, edges, "");
797
+ };
798
+ /** The fields `model` stores as JSON text (`DynamoModel.Packed`). */
799
+ const packedOf = (model) => new Set(model === undefined ? [] : Object.keys(getPackedFields(model)));
123
800
  /**
124
801
  * Unwrap a ConfiguredModel to get the raw Schema.Class model.
125
802
  * ConfiguredModel wraps the original model with DynamoDB-specific overrides
@@ -133,10 +810,12 @@ export const unwrapModel = (model) => {
133
810
  return model;
134
811
  };
135
812
  /**
136
- * Check if a schema matches an entity model (same Schema.Class identifier).
137
- * This is used to detect when an array element IS the entity (e.g., Array<Umpire>),
138
- * as opposed to wrapping the entity (e.g., Array<{ umpire: Umpire, role: string }>).
139
- * Unwraps ConfiguredModel if the entity uses DynamoModel.configure.
813
+ * Check if a schema has the same Schema.Class identifier as an entity model,
814
+ * unwrapping ConfiguredModel if the entity uses DynamoModel.configure.
815
+ *
816
+ * An identifier is not identity: two classes can share one. Nothing in the
817
+ * library decides by this any more; whether an element IS the entity (e.g.,
818
+ * Array<Umpire>) is decided by comparing the schema itself (`isEntityModel`).
140
819
  */
141
820
  export const isSchemaMatchingEntity = (schema, entity) => {
142
821
  const s = schema;