@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
package/dist/Entity.js CHANGED
@@ -18,13 +18,28 @@
18
18
  import { Duration, Option, SchemaAST } from "effect";
19
19
  import { getIdentifierField, getPackedFields, getSparseFields, isConfiguredModel, isHidden, isRecordAst, isRecordSchema, isRef, isRefField, } from "./DynamoModel.js";
20
20
  import { makeCompositeNullableError } from "./Errors.js";
21
+ import { refIdAttribute, refIdField } from "./internal/AggregateSchemas.js";
22
+ import { bothKindsKeyRefusal, keyFormValueKind } from "./internal/CompositeCodec.js";
21
23
  import { packedIndexRefusal, resolvePackedPlan } from "./internal/EntityPacked.js";
22
- import { allCompositeAttributes, buildDerivedSchemas, buildFieldEncodings, getFields, getSchemaFields, optionalField, resolveFieldEncoding, resolveSystemFields, resolveUniqueFields, validateNoTransformOverride, } from "./internal/EntitySchemas.js";
23
- import { refuseRepeatedIndex, refuseSharedKeyAttributeOnEverySchema, refuseStoredInTableKey, } from "./internal/SharedKeyAttribute.js";
24
+ import { allCompositeAttributes, buildDerivedSchemas, buildFieldEncodings, getFields, getSchemaFields, optionalField, resolveFieldEncoding, resolveSystemFields, resolveUniqueFields, storedAsOverTransform, validateNoTransformOverride, } from "./internal/EntitySchemas.js";
25
+ import { hasOwnName, isRequiredStored, ownValue, refuseProtoName, setOwn, } from "./internal/OwnNames.js";
26
+ import { refuseUnreadable } from "./internal/SchemaAccessors.js";
27
+ import { refuseReadAsSparseEntry, refuseRepeatedIndex, refuseSharedKeyAttributeOnEverySchema, refuseStoredInKeyAttribute, refuseStoredUnderLibraryAttribute, writtenKey, writtenKeyAttributes, } from "./internal/SharedKeyAttribute.js";
24
28
  import { bindDimension, MAX_ADDRESS_BITS, MAX_DIMENSION_BITS, makeLayout, } from "./internal/ZOrderCurve.js";
25
29
  import { resolveDimension } from "./internal/ZOrderDimension.js";
26
30
  import { isZOrderHalf, normalizeGsiConfig } from "./KeyComposer.js";
27
31
  import { deriveVectorFilterTypes, normalizeVectorIndexConfig, validateVectorIndexes, } from "./VectorIndex.js";
32
+ /** Whether the model field `name` stores something on every write (`isRequiredStored`). */
33
+ const storesUnder = (fields, name) => {
34
+ const field = ownValue(fields, name);
35
+ return field !== undefined && isRequiredStored(field.ast);
36
+ };
37
+ /**
38
+ * Whether an index's key half is composed on every write: each composite it names is a model field
39
+ * that always stores something ({@link storesUnder}). A half whose composites aren't listed (a
40
+ * Z-order sort key) is not known to be.
41
+ */
42
+ const composedAlways = (fields, half) => Array.isArray(half.composite) && half.composite.every((name) => storesUnder(fields, name));
28
43
  // ---------------------------------------------------------------------------
29
44
  // TTL helpers (pure — Duration parsing only)
30
45
  // ---------------------------------------------------------------------------
@@ -118,6 +133,7 @@ export const buildEntityDefinition = (config) => {
118
133
  // Unwrap ConfiguredModel to get the raw model and attribute overrides
119
134
  const configured = isConfiguredModel(config.model) ? config.model : undefined;
120
135
  const rawModel = configured ? configured.model : config.model;
136
+ refuseUnreadable(`Entity "${config.entityType}"`, "entity", rawModel);
121
137
  const configuredAttributes = configured?.attributes ?? {};
122
138
  // Schema.Class is a constructable function whose AST is a `Declaration`.
123
139
  // The `typeof` check alone is not enough: since Effect 4.0.0-rc,
@@ -128,10 +144,48 @@ export const buildEntityDefinition = (config) => {
128
144
  rawModel.ast._tag === "Declaration";
129
145
  const modelFields = getFields(rawModel);
130
146
  const hasHiddenFields = Object.values(modelFields).some(isHidden);
131
- const systemFields = resolveSystemFields(config.timestamps, config.versioned, config.timeSeries, modelFields, configuredAttributes, `Entity "${config.entityType}"`);
132
- // ---------------------------------------------------------------------------
133
- // Validate indexes
134
- // ---------------------------------------------------------------------------
147
+ // `Schema.optional(X)` is a union with `Undefined`, which has no date representation of its own,
148
+ // so the value schema is what's read: an optional date is a date, as `Schema.optionalKey(X)`
149
+ // always was. An aggregate's stamp overwrites what a caller supplied, so its optional dates stay
150
+ // the caller's. A date transform carrying a `storedAs` of the other wire kind isn't read through:
151
+ // `Entity.make` refuses one as a stamp outside `Schema.optional`, its stamp could never be read
152
+ // back, and 1.39.0 left such a field the caller's.
153
+ const systemFields = resolveSystemFields(config.timestamps, config.versioned, config.timeSeries, Object.fromEntries(Object.entries(modelFields).map(([name, field]) => {
154
+ const inner = optionalField(field)?.inner;
155
+ return [name, inner === undefined || storedAsOverTransform(inner) ? field : inner];
156
+ })), configuredAttributes, `Entity "${config.entityType}"`);
157
+ const configuredFields = Object.entries(configuredAttributes);
158
+ refuseProtoName(config.entityType, modelFields, {
159
+ renamed: new Set(configuredFields.filter(([, attribute]) => attribute.field !== undefined).map(([n]) => n)),
160
+ packed: new Set(Object.keys(getPackedFields(config.model))),
161
+ }, [
162
+ // A field's attribute holds something on every write only where the field always stores
163
+ // something.
164
+ ...configuredFields.map(([name, attribute]) => ({
165
+ name: attribute.field,
166
+ what: `the attribute the field "${name}" is stored under`,
167
+ always: storesUnder(modelFields, name),
168
+ })),
169
+ { name: systemFields.createdAt, what: "the created timestamp" },
170
+ { name: systemFields.updatedAt, what: "the updated timestamp" },
171
+ { name: systemFields.version, what: "the version field" },
172
+ // The table's key attributes are on every item. A put writes an index's two only where it
173
+ // holds every composite of both halves (a sparse index otherwise), so they are on every
174
+ // item only where each of those always is; an update or upsert that writes one half alone
175
+ // is refused when it's sent (`EDD-9165`).
176
+ ...Object.entries(config.indexes).flatMap(([name, index]) => {
177
+ const always = name === "primary" ||
178
+ (composedAlways(modelFields, index.pk) && composedAlways(modelFields, index.sk));
179
+ return [
180
+ {
181
+ name: index.pk.field,
182
+ what: `the partition key attribute of index "${name}"`,
183
+ always,
184
+ },
185
+ { name: index.sk.field, what: `the sort key attribute of index "${name}"`, always },
186
+ ];
187
+ }),
188
+ ]);
135
189
  const primaryIndex = config.indexes.primary;
136
190
  // Z-order sort keys are secondary-index only (#171): the primary key is
137
191
  // string-composed, and a misplaced `zorder` must not reach the composers.
@@ -168,6 +222,14 @@ export const buildEntityDefinition = (config) => {
168
222
  }
169
223
  }
170
224
  }
225
+ refuseKeysOverMovingValues(config.entityType, config.indexes, systemFields, config.versioned);
226
+ if (systemFields.version !== null &&
227
+ ownValue(configuredAttributes, systemFields.version)?.field !== undefined) {
228
+ throw new Error(`[EDD-9122] Entity "${config.entityType}": "${systemFields.version}" is where \`versioned\` ` +
229
+ `keeps the version, so \`configure\` can't store it under another name: the write would ` +
230
+ `succeed and every later read and write of the item would find no version. To name the ` +
231
+ `attribute, use \`versioned: { field: "..." }\` and give the model's field that name.`);
232
+ }
171
233
  // ---------------------------------------------------------------------------
172
234
  // Packed fields (storedAs: DynamoModel.Packed) — EDD-9072..9075, EDD-9073.
173
235
  // Checked before the other derivations so a packed composite / filter field
@@ -183,14 +245,14 @@ export const buildEntityDefinition = (config) => {
183
245
  unique: config.unique,
184
246
  timeSeries: config.timeSeries,
185
247
  vectorIndexes: config.vectorIndexes,
186
- resolveDbName: (name) => configuredAttributes[name]
248
+ resolveDbName: (name) => ownValue(configuredAttributes, name)
187
249
  ?.field ?? name,
188
250
  });
189
251
  // ---------------------------------------------------------------------------
190
252
  // EDD-9025: composite attribute schemas must not include `null`.
191
253
  // ---------------------------------------------------------------------------
192
254
  const resolveCompositeSchemaForNullCheck = (compositeAttr) => {
193
- if (compositeAttr in modelFields) {
255
+ if (hasOwnName(modelFields, compositeAttr)) {
194
256
  return { schema: modelFields[compositeAttr], source: `model field` };
195
257
  }
196
258
  if (config.refs) {
@@ -256,13 +318,47 @@ export const buildEntityDefinition = (config) => {
256
318
  }
257
319
  }
258
320
  }
321
+ // EDD-9128: no value is composed into key text from a field storing both numeric kinds. A
322
+ // Z-order dimension is quantized, not composed, and its own check refuses a union (EDD-9088).
323
+ // What composes each key composite, in words, for `appendInput`'s check below.
324
+ const composedInto = new Map();
325
+ const refuseBothKinds = (where, attrs) => {
326
+ for (const attr of attrs) {
327
+ if (!composedInto.has(attr))
328
+ composedInto.set(attr, where);
329
+ const resolved = resolveCompositeSchemaForNullCheck(attr);
330
+ if (resolved === undefined)
331
+ continue;
332
+ const refused = bothKindsKeyRefusal(`Entity "${config.entityType}"`, where, attr, resolved.schema);
333
+ if (refused !== undefined)
334
+ throw refused;
335
+ }
336
+ };
337
+ for (const [indexName, indexDef] of Object.entries(config.indexes)) {
338
+ const dimensions = isZOrderHalf(indexDef.sk)
339
+ ? new Set(indexDef.sk.zorderHalf.dimensions.map((dimension) => dimension.field))
340
+ : new Set();
341
+ refuseBothKinds(indexName === "primary" ? "the primary key" : `index "${indexName}"`, [
342
+ ...indexDef.pk.composite,
343
+ ...indexDef.sk.composite.filter((attr) => !dimensions.has(attr)),
344
+ ]);
345
+ }
346
+ for (const [constraintName, constraintDef] of Object.entries(config.unique ?? {})) {
347
+ refuseBothKinds(`unique constraint "${constraintName}"`, resolveUniqueFields(constraintDef));
348
+ }
349
+ for (const [logicalName, vectorConfig] of Object.entries(config.vectorIndexes ?? {})) {
350
+ refuseBothKinds(`vector index "${logicalName}"'s partition`, vectorConfig.partition ?? []);
351
+ }
352
+ if (config.timeSeries !== undefined && config.timeSeries !== null) {
353
+ refuseBothKinds("an event's sort key (timeSeries.orderBy)", [config.timeSeries.orderBy]);
354
+ }
259
355
  // ---------------------------------------------------------------------------
260
356
  // Validate timeSeries config (EDD-9010..9016)
261
357
  // ---------------------------------------------------------------------------
262
358
  if (config.timeSeries !== undefined && config.timeSeries !== null) {
263
359
  const ts = config.timeSeries;
264
360
  const orderBy = ts.orderBy;
265
- if (!(orderBy in modelFields)) {
361
+ if (!hasOwnName(modelFields, orderBy)) {
266
362
  throw new Error(`[EDD-9010] Entity "${config.entityType}": timeSeries.orderBy "${orderBy}" does not name a model field. ` +
267
363
  `Valid model fields: ${Object.keys(modelFields).sort().join(", ")}`);
268
364
  }
@@ -306,6 +402,33 @@ export const buildEntityDefinition = (config) => {
306
402
  `Every PK/SK composite must appear in appendInput so the event can be addressed.`);
307
403
  }
308
404
  }
405
+ // EDD-9128: `.append()` takes its input through `appendInput`, and composes the event's sort key
406
+ // and the current item's keys from it, so `appendInput`'s own fields are refused as the model's
407
+ // are: `orderBy` and every key composite it carries. One composing the other numeric kind's key
408
+ // text than its model field is refused too: the event is keyed by one kind's text and every read
409
+ // composes the other's.
410
+ const appendFields = getSchemaFields(ts.appendInput) ?? {};
411
+ for (const [attr, where] of composedInto) {
412
+ const field = ownValue(appendFields, attr);
413
+ if (field === undefined)
414
+ continue;
415
+ const owner = `Entity "${config.entityType}"`;
416
+ const at = `${where}, through timeSeries.appendInput,`;
417
+ const refused = bothKindsKeyRefusal(owner, at, attr, field);
418
+ if (refused !== undefined)
419
+ throw refused;
420
+ const model = ownValue(modelFields, attr);
421
+ const given = keyFormValueKind(field);
422
+ const read = model === undefined ? undefined : keyFormValueKind(model);
423
+ if ((given === "number" || given === "bigint") &&
424
+ (read === "number" || read === "bigint") &&
425
+ given !== read) {
426
+ throw new Error(`[EDD-9128] ${owner}: ${at} can't be composed from "${attr}", which timeSeries.appendInput ` +
427
+ `holds as a ${given} and the model as a ${read}. The two compose different key text, so ` +
428
+ `an event appended under one would never be found by a read composing the other. ` +
429
+ `Declare the same kind in both.`);
430
+ }
431
+ }
309
432
  for (const fieldName of Object.keys(modelFields)) {
310
433
  if (isRefField(fieldName, config.model)) {
311
434
  if (orderBy === fieldName || orderBy === `${fieldName}Id`) {
@@ -323,7 +446,7 @@ export const buildEntityDefinition = (config) => {
323
446
  }
324
447
  }
325
448
  for (const field of appendInputFields) {
326
- if (!(field in modelFields)) {
449
+ if (!hasOwnName(modelFields, field)) {
327
450
  throw new Error(`[EDD-9013] Entity "${config.entityType}": timeSeries.appendInput field "${field}" is not a ` +
328
451
  `model field. .append() writes each appendInput field to the current item. ` +
329
452
  `Valid model fields: ${Object.keys(modelFields).sort().join(", ")}`);
@@ -336,7 +459,7 @@ export const buildEntityDefinition = (config) => {
336
459
  if (config.unique) {
337
460
  for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
338
461
  for (const field of resolveUniqueFields(constraintDef)) {
339
- if (!(field in modelFields)) {
462
+ if (!hasOwnName(modelFields, field)) {
340
463
  throw new Error(`[EDD-9002] Entity "${config.entityType}": unique constraint "${constraintName}" references ` +
341
464
  `unknown attribute "${field}". Valid attributes: ${Object.keys(modelFields).sort().join(", ")}`);
342
465
  }
@@ -349,7 +472,7 @@ export const buildEntityDefinition = (config) => {
349
472
  if (config.generatedId !== undefined && config.generatedId !== null) {
350
473
  const gid = config.generatedId;
351
474
  const field = gid.field;
352
- if (!(field in modelFields)) {
475
+ if (!hasOwnName(modelFields, field)) {
353
476
  throw new Error(`[EDD-9008] Entity "${config.entityType}": generatedId.field "${field}" does not name a model field. ` +
354
477
  `Valid model fields: ${Object.keys(modelFields).sort().join(", ")}`);
355
478
  }
@@ -369,7 +492,7 @@ export const buildEntityDefinition = (config) => {
369
492
  // Encoded-type tag for a model field, resolving homogeneous literal unions
370
493
  // (e.g. Schema.Literals(["a", "b"]) → "String") so they qualify as filters.
371
494
  const fieldEncodedTag = (field) => {
372
- const fieldSchema = getSchemaFields(rawModel)?.[field];
495
+ const fieldSchema = ownValue(getSchemaFields(rawModel), field);
373
496
  if (fieldSchema?.ast === undefined)
374
497
  return undefined;
375
498
  const resolveTag = (ast) => {
@@ -387,7 +510,7 @@ export const buildEntityDefinition = (config) => {
387
510
  return resolveTag(fieldSchema.ast);
388
511
  };
389
512
  for (const [logicalName, vectorConfig] of Object.entries(config.vectorIndexes)) {
390
- vectorIndexes[logicalName] = normalizeVectorIndexConfig(vectorConfig);
513
+ setOwn(vectorIndexes, logicalName, normalizeVectorIndexConfig(vectorConfig));
391
514
  }
392
515
  // Field-existence validation (EDD-9031..9033, EDD-9070) runs before type derivation
393
516
  // so an unknown filter field reports EDD-9031, not a derivation failure.
@@ -410,7 +533,7 @@ export const buildEntityDefinition = (config) => {
410
533
  const resolvedRefs = config.refs
411
534
  ? Object.entries(config.refs).map(([fieldName, refValue]) => {
412
535
  const refEntity = refValue.entity;
413
- const fieldSchema = modelFields[fieldName];
536
+ const fieldSchema = ownValue(modelFields, fieldName);
414
537
  if (!fieldSchema) {
415
538
  throw new Error(`Entity "${config.entityType}": refs config references field "${fieldName}" which does not exist in the model`);
416
539
  }
@@ -421,11 +544,17 @@ export const buildEntityDefinition = (config) => {
421
544
  if (!idField) {
422
545
  throw new Error(`Entity "${config.entityType}": ref field "${fieldName}" references entity "${refEntity.entityType}" which has no identifier field. Add DynamoModel.identifier to the model field or set { identifier: true } in DynamoModel.configure.`);
423
546
  }
547
+ // An id names the referenced entity's one key composite, as an aggregate edge's id does
548
+ // (#214, #241): it's fetched, and read back, under that. An entity keyed by more than one
549
+ // composite has none: its id is fetched, and read back, under its identifier, as up to
550
+ // 1.40.0, which composes the key wherever the other composites compose without a value
551
+ // (an encoding default) and fails as it did where they don't.
552
+ const keyField = refIdAttribute(refEntity);
424
553
  return {
425
554
  fieldName,
426
555
  idFieldName: `${fieldName}Id`,
427
- identifierField: idField.name,
428
- identifierSchema: idField.schema,
556
+ keyField,
557
+ keySchema: keyField === idField.name ? idField.schema : (refIdField(refEntity) ?? idField.schema),
429
558
  refEntity,
430
559
  refEntityType: refEntity.entityType,
431
560
  };
@@ -471,7 +600,7 @@ export const buildEntityDefinition = (config) => {
471
600
  const generatedIdVersion = config.generatedId !== undefined && config.generatedId !== null
472
601
  ? (config.generatedId.version ?? "v4")
473
602
  : undefined;
474
- const schemas = buildDerivedSchemas(modelFields, initialIndexes, systemFields, resolvedRefs, immutableFields, resolvedIdentifier, config.timeSeries, fieldEncodings, generatedIdField);
603
+ const schemas = buildDerivedSchemas(modelFields, initialIndexes, systemFields, resolvedRefs, immutableFields, resolvedIdentifier, config.timeSeries, fieldEncodings, generatedIdField, (ownValue(configuredAttributes, "__proto__")?.field ?? "__proto__") !== "__proto__");
475
604
  const entityType = config.entityType;
476
605
  const entityVersion = 1;
477
606
  // ---------------------------------------------------------------------------
@@ -481,7 +610,7 @@ export const buildEntityDefinition = (config) => {
481
610
  const hasSparseFields = Object.keys(sparseFields).length > 0;
482
611
  if (hasSparseFields) {
483
612
  for (const fieldName of Object.keys(sparseFields)) {
484
- const fieldSchema = modelFields[fieldName];
613
+ const fieldSchema = ownValue(modelFields, fieldName);
485
614
  if (!fieldSchema) {
486
615
  throw new Error(`[EDD-9020] Entity "${config.entityType}": sparse field "${fieldName}" does not exist on the model`);
487
616
  }
@@ -520,7 +649,7 @@ export const buildEntityDefinition = (config) => {
520
649
  throw new Error(`[EDD-9023] Entity "${config.entityType}": sparse fields "${existing}" and "${fieldName}" share prefix "${sparse.prefix}". Prefixes must be distinct.`);
521
650
  }
522
651
  seenPrefix.set(sparse.prefix, fieldName);
523
- if (sparse.prefix !== fieldName && sparse.prefix in modelFields) {
652
+ if (sparse.prefix !== fieldName && hasOwnName(modelFields, sparse.prefix)) {
524
653
  throw new Error(`[EDD-9023] Entity "${config.entityType}": sparse field "${fieldName}" prefix "${sparse.prefix}" collides with non-sparse field "${sparse.prefix}".`);
525
654
  }
526
655
  }
@@ -558,8 +687,8 @@ export const buildEntityDefinition = (config) => {
558
687
  initialIndexes[indexName] = {
559
688
  ...indexDef,
560
689
  sk: bindZOrderHalf(config.entityType, indexName, indexDef.sk, (field) => ({
561
- schema: inputFields[field],
562
- encoding: fieldEncodings[field] ?? optionalFieldEncoding(modelFields[field]),
690
+ schema: ownValue(inputFields, field),
691
+ encoding: ownValue(fieldEncodings, field) ?? optionalFieldEncoding(ownValue(modelFields, field)),
563
692
  })),
564
693
  };
565
694
  }
@@ -578,25 +707,79 @@ export const buildEntityDefinition = (config) => {
578
707
  // ---------------------------------------------------------------------------
579
708
  // Field renaming: domain name → DynamoDB attribute name (from ConfiguredModel)
580
709
  // ---------------------------------------------------------------------------
581
- const fieldRenames = {};
710
+ // Null-prototype: read by a field's name (`fieldRenames[name] ?? name`), and a model field may be
711
+ // named like an `Object.prototype` member (`valueOf`), which a plain object answers with a function.
712
+ const fieldRenames = Object.create(null);
582
713
  for (const [domainName, attrConfig] of Object.entries(configuredAttributes)) {
583
714
  const field = attrConfig.field;
584
715
  if (field)
585
- fieldRenames[domainName] = field;
716
+ setOwn(fieldRenames, domainName, field);
586
717
  }
587
718
  const hasRenames = Object.keys(fieldRenames).length > 0;
588
- refuseStoredInTableKey(config.entityType, primaryIndex, [
589
- ...Object.keys(modelFields).map((name) => [name, fieldRenames[name] ?? name]),
719
+ const storedAttributes = [
720
+ ...Object.keys(modelFields).map((name) => [name, ownValue(fieldRenames, name) ?? name]),
590
721
  ...[systemFields.createdAt, systemFields.updatedAt, systemFields.version]
591
722
  .filter((name) => name !== null)
592
723
  .map((name) => [name, name]),
593
- ]);
724
+ ];
725
+ const keyAttributes = writtenKeyAttributes(initialIndexes, vectorIndexes);
726
+ refuseStoredInKeyAttribute(config.entityType, keyAttributes, storedAttributes);
727
+ refuseStoredUnderLibraryAttribute(config.entityType, keyAttributes, storedAttributes);
728
+ // Every attribute a row of this entity holds under a name the definition supplies, each by the
729
+ // name it is stored under. The table's TTL attribute is the table configuration's to name:
730
+ // `DynamoClient.make` checks it.
731
+ // A timestamp's or the version's name is the configuration's: looked up among the renames
732
+ // the model declares, never among what every object inherits.
733
+ const storedName = (name) => Object.hasOwn(fieldRenames, name) ? fieldRenames[name] : name;
734
+ const softDeletes = config.softDelete === true || typeof config.softDelete === "object";
735
+ refuseReadAsSparseEntry(config.entityType, [
736
+ ...keyAttributes.map((key) => writtenKey(key)),
737
+ ...Object.keys(modelFields)
738
+ .filter((name) => !Object.hasOwn(sparseFields, name))
739
+ .map((name) => ({
740
+ attribute: storedName(name),
741
+ what: `the attribute the field "${name}" is stored in`,
742
+ })),
743
+ // A sparse map's entries go under its prefix. Under a `field:` rename a put stores the map
744
+ // whole in that attribute.
745
+ ...Object.entries(sparseFields).flatMap(([name, sparse]) => [
746
+ {
747
+ attribute: sparse.prefix,
748
+ what: `the prefix the sparse map "${name}" stores its entries under`,
749
+ },
750
+ ...(Object.hasOwn(fieldRenames, name)
751
+ ? [
752
+ {
753
+ attribute: storedName(name),
754
+ what: `the attribute a put stores the sparse map "${name}" whole in`,
755
+ },
756
+ ]
757
+ : []),
758
+ ]),
759
+ // A timestamp or the version a model field also declares is stored where that field is.
760
+ ...[
761
+ [systemFields.createdAt, "its created timestamp"],
762
+ [systemFields.updatedAt, "its updated timestamp"],
763
+ [systemFields.version, "its version"],
764
+ ].flatMap(([name, holds]) => name === null
765
+ ? []
766
+ : [{ attribute: storedName(name), what: `the attribute that holds ${holds}` }]),
767
+ ...(softDeletes
768
+ ? [
769
+ { attribute: "deletedAt", what: "the attribute that holds when a row was deleted" },
770
+ ...Object.entries(vectorIndexes).map(([name, vector]) => ({
771
+ attribute: vector.stashField,
772
+ what: `the attribute a deleted row keeps vector index "${name}"'s embedding in`,
773
+ })),
774
+ ]
775
+ : []),
776
+ ], sparseFields);
594
777
  const renameToDynamo = (item) => {
595
778
  if (!hasRenames)
596
779
  return;
597
780
  for (const [domain, dynamo] of Object.entries(fieldRenames)) {
598
- if (domain in item) {
599
- item[dynamo] = item[domain];
781
+ if (hasOwnName(item, domain)) {
782
+ setOwn(item, dynamo, item[domain]);
600
783
  delete item[domain];
601
784
  }
602
785
  }
@@ -605,13 +788,13 @@ export const buildEntityDefinition = (config) => {
605
788
  if (!hasRenames)
606
789
  return;
607
790
  for (const [domain, dynamo] of Object.entries(fieldRenames)) {
608
- if (dynamo in item) {
609
- item[domain] = item[dynamo];
791
+ if (hasOwnName(item, dynamo)) {
792
+ setOwn(item, domain, item[dynamo]);
610
793
  delete item[dynamo];
611
794
  }
612
795
  }
613
796
  };
614
- const resolveDbName = (domainName) => fieldRenames[domainName] ?? domainName;
797
+ const resolveDbName = (domainName) => ownValue(fieldRenames, domainName) ?? domainName;
615
798
  return {
616
799
  configuredAttributes: configuredAttributes,
617
800
  rawModel,
@@ -659,6 +842,50 @@ const optionalFieldEncoding = (schema) => {
659
842
  const inner = schema === undefined ? undefined : optionalField(schema)?.inner;
660
843
  return inner === undefined ? undefined : (resolveFieldEncoding(inner, undefined) ?? undefined);
661
844
  };
845
+ /**
846
+ * `[EDD-9121]`: a key over a value the library changes on every write, where the write can't know
847
+ * it or can't move the key (`DESIGN.md` §7, "Composites the library stamps").
848
+ *
849
+ * A plain `versioned` update adds one to the stored version without reading it, so a secondary index
850
+ * over it would never hold a key. `versioned: { retain: true }` reads the item on every write, so
851
+ * the value is known and the key moves with it. A primary key never changes, whatever is known, and
852
+ * a shard follows its source, which a query could then never pin.
853
+ */
854
+ const refuseKeysOverMovingValues = (entityType, indexes, systemFields, versioned) => {
855
+ const { updatedAt, version } = systemFields;
856
+ const retained = typeof versioned === "object" && versioned !== null && versioned.retain === true;
857
+ const moving = [updatedAt, version].filter((field) => field !== null);
858
+ const primary = indexes.primary;
859
+ for (const field of moving) {
860
+ if (primary !== undefined &&
861
+ [...primary.pk.composite, ...primary.sk.composite].includes(field)) {
862
+ throw new Error(`[EDD-9121] Entity "${entityType}": the primary key can't be composed from "${field}". ` +
863
+ `The library changes it on every write and a primary key never changes, so the key ` +
864
+ `would stop matching the value at the first update. Remove it from the primary key, or ` +
865
+ `use a field the library doesn't manage.`);
866
+ }
867
+ }
868
+ for (const [indexName, index] of Object.entries(indexes)) {
869
+ if (indexName === "primary")
870
+ continue;
871
+ for (const field of moving) {
872
+ if (index.shards?.by?.includes(field) === true) {
873
+ throw new Error(`[EDD-9121] Entity "${entityType}": index "${indexName}" shards.by can't name "${field}". ` +
874
+ `The library changes it on every write, so the shard would go stale on each one and ` +
875
+ `no pin could reach the item. Omit it to hash the primary key.`);
876
+ }
877
+ }
878
+ if (version !== null &&
879
+ !retained &&
880
+ [...index.pk.composite, ...index.sk.composite].includes(version)) {
881
+ throw new Error(`[EDD-9121] Entity "${entityType}": index "${indexName}" can't be composed from "${version}". ` +
882
+ `The library adds one to it on every write without reading the item, so the new value ` +
883
+ `isn't known when the key is written and no item would ever hold this key. Remove it ` +
884
+ `from the index, or use \`versioned: { retain: true }\`, which reads the item on every ` +
885
+ `write.`);
886
+ }
887
+ }
888
+ };
662
889
  /** `[EDD-9090]`: a Z-order index is never a collection member. */
663
890
  export const zorderInCollection = (entityType, indexName) => new Error(`[EDD-9090] Entity "${entityType}": index "${indexName}" has a Z-order sort key and ` +
664
891
  `can't belong to a collection — a collection's members share sort-key text, and a ` +
@@ -733,7 +960,7 @@ export const make = (config) => {
733
960
  const gsiIndexes = {};
734
961
  if (config.indexes) {
735
962
  for (const [name, gsi] of Object.entries(config.indexes)) {
736
- gsiIndexes[name] = normalizeGsiConfig(gsi);
963
+ setOwn(gsiIndexes, name, normalizeGsiConfig(gsi));
737
964
  }
738
965
  }
739
966
  const indexes = { primary: config.primaryKey, ...gsiIndexes };
@@ -765,7 +992,7 @@ const makeDefinitionImpl = (config) => {
765
992
  _resolvedRefs: data.resolvedRefs.map((r) => ({
766
993
  fieldName: r.fieldName,
767
994
  idFieldName: r.idFieldName,
768
- identifierField: r.identifierField,
995
+ keyField: r.keyField,
769
996
  refEntityType: r.refEntityType,
770
997
  })),
771
998
  _attachPrototype: attachPrototype,