@effect-dynamodb/schema 1.41.0 → 1.42.1

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.
@@ -1123,6 +1123,9 @@ const childOptions = (container, deeper, index, opts) => {
1123
1123
  strictWireKind: true,
1124
1124
  collidingKinds,
1125
1125
  ...(opts?.unionDateOverride ? { dateEncodingOverride: opts.unionDateOverride } : {}),
1126
+ ...(opts?.unionDateOverride && opts.readsDeclaredStorage ? { readsDeclaredStorage: true } : {}),
1127
+ // A nullable ref (`NullOr(Team)`): its struct member holds what the ref's entity holds.
1128
+ ...(opts?.configuredStorage ? { configuredStorage: opts.configuredStorage } : {}),
1126
1129
  };
1127
1130
  };
1128
1131
  /** The options an optional wrapper hands its inner schema: it is transparent. */
@@ -1188,12 +1191,17 @@ const decodingDefaultField = (field) => {
1188
1191
  const writesFirstMemberOnly = (opts) => !opts?.decodeOnly && !opts?.absentReads && !opts?.undefinedPositionsOnly;
1189
1192
  const throughOptional = (opts) => {
1190
1193
  const deeper = descend(opts);
1191
- return opts?.unionDateOverride || opts?.collidingKinds || opts?.dateEncodingOverride
1194
+ return opts?.unionDateOverride ||
1195
+ opts?.collidingKinds ||
1196
+ opts?.dateEncodingOverride ||
1197
+ opts?.configuredStorage
1192
1198
  ? {
1193
1199
  ...deeper,
1194
1200
  ...(opts.unionDateOverride ? { unionDateOverride: opts.unionDateOverride } : {}),
1195
1201
  ...(opts.collidingKinds ? { collidingKinds: opts.collidingKinds } : {}),
1196
1202
  ...(opts.dateEncodingOverride ? { dateEncodingOverride: opts.dateEncodingOverride } : {}),
1203
+ ...(opts.readsDeclaredStorage ? { readsDeclaredStorage: true } : {}),
1204
+ ...(opts.configuredStorage ? { configuredStorage: opts.configuredStorage } : {}),
1197
1205
  }
1198
1206
  : deeper;
1199
1207
  };
@@ -1231,14 +1239,46 @@ const selfDatePlan = (schema, opts) => {
1231
1239
  }
1232
1240
  return { encoding, canonicalOnly };
1233
1241
  };
1242
+ /**
1243
+ * Under `readsDeclaredStorage`, in a union: the plan of the storage the date declares, where the
1244
+ * override reads another kind of value (see `readsDeclaredStorage`). Out of a union the override's
1245
+ * transform reads a value by its kind already, text as ISO text and a number in its own scale.
1246
+ */
1247
+ const declaredStoragePlan = (schema, opts) => {
1248
+ if (!opts?.readsDeclaredStorage || !opts.strictWireKind || !opts.dateEncodingOverride) {
1249
+ return undefined;
1250
+ }
1251
+ const own = getEncoding(schema) ?? inferDefaultEncoding(schema);
1252
+ const text = (encoding) => encoding.storage === "string";
1253
+ if (own === undefined || text(own) === text(opts.dateEncodingOverride))
1254
+ return undefined;
1255
+ try {
1256
+ return selfDatePlan(schema, { ...opts, dateEncodingOverride: undefined });
1257
+ }
1258
+ catch {
1259
+ // An epoch beside a number member (EDD-9058) is refused where it's the storage, not here.
1260
+ return undefined;
1261
+ }
1262
+ };
1234
1263
  const selfDateSubstitute = (schema, opts) => {
1235
1264
  const plan = selfDatePlan(schema, opts);
1236
1265
  if (plan === undefined)
1237
1266
  return schema;
1238
- return buildDateTransform(plan.encoding, {
1267
+ const substitute = buildDateTransform(plan.encoding, {
1239
1268
  strictWireKind: opts?.strictWireKind,
1240
1269
  canonicalOnly: plan.canonicalOnly,
1241
1270
  });
1271
+ // Encodes as the override, and reads either form, as an aggregate's union member does.
1272
+ const declared = declaredStoragePlan(schema, opts);
1273
+ return declared === undefined
1274
+ ? substitute
1275
+ : Schema.Union([
1276
+ substitute,
1277
+ buildDateTransform(declared.encoding, {
1278
+ strictWireKind: true,
1279
+ canonicalOnly: declared.canonicalOnly,
1280
+ }),
1281
+ ]);
1242
1282
  };
1243
1283
  /**
1244
1284
  * Whether a union member is a self date that claims only its canonical form
@@ -1250,8 +1290,10 @@ const selfDateSubstitute = (schema, opts) => {
1250
1290
  */
1251
1291
  const isCanonicalDateMember = (member, opts) => {
1252
1292
  const inner = optionalField(member)?.inner ?? member;
1253
- if (isSelfDateSchema(inner))
1254
- return selfDatePlan(inner, opts)?.canonicalOnly === true;
1293
+ if (isSelfDateSchema(inner)) {
1294
+ return (selfDatePlan(inner, opts)?.canonicalOnly === true ||
1295
+ declaredStoragePlan(inner, opts)?.canonicalOnly === true);
1296
+ }
1255
1297
  // A nested union holding such a member (`NullOr(DateTimeUtc)` next to a
1256
1298
  // `String`) is decoded first for the same reason.
1257
1299
  const container = walkedContainer(inner);
@@ -1845,7 +1887,7 @@ export const substituteSchemaDeep = (schema, opts) => {
1845
1887
  setOwn(subFields, name, fieldNamed(name, fieldOpt ? fieldOpt.rewrap(sub) : sub, field));
1846
1888
  }
1847
1889
  else {
1848
- const sub = substituteSchemaDeep(field, atField(deeper, opts, name));
1890
+ const sub = substituteSchemaDeep(field, withConfiguredStorage(atField(deeper, opts, name), name, field, ownValue(opts?.configuredStorage?.fields, name), ownValue(opts?.configuredStorage?.refs, name)));
1849
1891
  setOwn(subFields, name, name === "__proto__"
1850
1892
  ? fieldNamed(name, sub, field)
1851
1893
  : opts?.absentReads
@@ -2116,8 +2158,8 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2116
2158
  // 1. Self-date substitution. Pattern A: user declared `Schema.DateTimeUtc`
2117
2159
  // and chose a wire format via annotation. We substitute with the
2118
2160
  // tolerant date transform so the encode pipeline produces the right
2119
- // wire primitive.
2120
- if (isSelfDateSchema(schema)) {
2161
+ // wire primitive. An optional one keeps its wrapper (step 3).
2162
+ if (isSelfDateSchema(schema) && optionalField(schema) === undefined) {
2121
2163
  const enc = ownValue(fieldEncodings, name);
2122
2164
  if (enc) {
2123
2165
  setOwn(out, name, fieldNamed(name, buildDateTransform(enc), schema, storedAsProto));
@@ -2149,13 +2191,9 @@ export const substituteSchemas = (modelFields, fieldEncodings, options) => {
2149
2191
  // — `substituteSchemaDeep` substitutes those while preserving class
2150
2192
  // identity, and returns the schema unchanged when nothing nested needs it.
2151
2193
  // A configured storage override on a UNION field (`NullOr(DateTimeUtc)`)
2152
- // is applied to the union's self-date member (#133).
2153
- const unionOverride = unionDateOverride(name, schema, ownValue(fieldEncodings, name));
2154
- setOwn(out, name, fieldNamed(name, substituteSchemaDeep(schema, {
2155
- ...deep,
2156
- path: [name],
2157
- ...(unionOverride === undefined ? {} : { unionDateOverride: unionOverride }),
2158
- }), schema, storedAsProto));
2194
+ // is applied to the union's self-date member (#133), and on an optional
2195
+ // date to the date beneath the wrapper (`withConfiguredStorage`).
2196
+ setOwn(out, name, fieldNamed(name, substituteSchemaDeep(schema, withConfiguredStorage({ ...deep, path: [name] }, name, schema, ownValue(fieldEncodings, name))), schema, storedAsProto));
2159
2197
  }
2160
2198
  if (options?.absentReads) {
2161
2199
  for (const [name, field] of Object.entries(out)) {
@@ -2192,6 +2230,91 @@ const unionDateOverride = (name, schema, encoding) => {
2192
2230
  }
2193
2231
  return encoding;
2194
2232
  };
2233
+ /**
2234
+ * @internal The storage `DynamoModel.configure` gives a model's fields (`storedAs` a date schema),
2235
+ * by name, or `undefined` for a model with none.
2236
+ */
2237
+ export const configuredStorageOf = (model) => {
2238
+ if (!isConfiguredModel(model))
2239
+ return undefined;
2240
+ const storage = {};
2241
+ for (const [name, attribute] of Object.entries(model.attributes)) {
2242
+ if (attribute.encoding !== undefined)
2243
+ setOwn(storage, name, attribute.encoding);
2244
+ }
2245
+ return Object.keys(storage).length === 0 ? undefined : storage;
2246
+ };
2247
+ /** Each entity's {@link HeldStorage}, by its derived schemas (shared by its pure and runtime forms). */
2248
+ const heldStorages = new WeakMap();
2249
+ /**
2250
+ * @internal Record what an entity holds (`fields`, the storage its schemas apply to its own fields;
2251
+ * `refs`, by ref field, each entity it refs), when it's made. An entity can only ref one made
2252
+ * before it, so the tree is finite.
2253
+ */
2254
+ export const holdStorage = (schemas, fields, refs) => {
2255
+ const held = {};
2256
+ for (const ref of refs) {
2257
+ const storage = heldStorageOf(ref.refEntity);
2258
+ if (storage !== undefined)
2259
+ setOwn(held, ref.fieldName, storage);
2260
+ }
2261
+ heldStorages.set(schemas, { fields: fields ?? {}, refs: held });
2262
+ };
2263
+ /**
2264
+ * @internal The {@link HeldStorage} of a ref's entity, or `undefined` where it holds every field in
2265
+ * the default storage. An entity this module didn't make is taken by its model's `configure`.
2266
+ */
2267
+ export const heldStorageOf = (entity) => {
2268
+ const { schemas, model } = (entity ?? {});
2269
+ const held = typeof schemas === "object" && schemas !== null ? heldStorages.get(schemas) : undefined;
2270
+ if (held === undefined) {
2271
+ const fields = configuredStorageOf(model);
2272
+ return fields === undefined ? undefined : { fields, refs: {} };
2273
+ }
2274
+ return Object.keys(held.fields).length === 0 && Object.keys(held.refs).length === 0
2275
+ ? undefined
2276
+ : held;
2277
+ };
2278
+ /**
2279
+ * @internal Whether the storage `DynamoModel.configure` gives this field was left unapplied up to
2280
+ * 1.41.0: a date beneath an optional wrapper that is a union (`Schema.optional(date)`,
2281
+ * `Schema.optionalKey(Schema.NullOr(date))`), which those releases stored as ISO text.
2282
+ */
2283
+ export const configuredStorageWasIgnored = (field) => {
2284
+ const optional = optionalField(field);
2285
+ return optional !== undefined && !isSelfDateSchema(field) && isSelfDateSchema(optional.inner);
2286
+ };
2287
+ /**
2288
+ * A field's substitution options with the storage `encoding` its model's `DynamoModel.configure`
2289
+ * gives it: a date, the date beneath an optional wrapper (`Schema.optionalKey`, `Schema.optional`,
2290
+ * the first member of an `optionalKey` union, as `optionalKey(NullOr(date))`), or beneath a
2291
+ * decoding default, or a union's date member. The wrapper is kept as declared. A field holding a
2292
+ * ref takes what that ref's entity holds (`refs`). Elsewhere, and without either, `options` as
2293
+ * given. A read (`legacyReads`) also takes the form the date's own storage writes
2294
+ * (`readsDeclaredStorage`). Up to 1.41.0 an entity's own `optional` date and the date of an
2295
+ * `optionalKey(NullOr(…))` were stored as ISO text, and an `optionalKey` date became required.
2296
+ */
2297
+ const withConfiguredStorage = (options, name, field, encoding, refs) => {
2298
+ if (refs !== undefined)
2299
+ return { ...options, configuredStorage: refs };
2300
+ if (encoding === undefined)
2301
+ return options;
2302
+ const reads = options.legacyReads ? { readsDeclaredStorage: true } : {};
2303
+ const optional = optionalField(field);
2304
+ const date = optional?.inner ?? decodingDefaultField(field)?.inner ?? field;
2305
+ if (isSelfDateSchema(date)) {
2306
+ // A read takes the whole union beneath `optionalKey`, its date member in this storage too.
2307
+ const union = optional?.union === undefined ? undefined : unionDateOverride(name, optional.union, encoding);
2308
+ return {
2309
+ ...options,
2310
+ dateEncodingOverride: encoding,
2311
+ ...(union === undefined ? {} : { unionDateOverride: union }),
2312
+ ...reads,
2313
+ };
2314
+ }
2315
+ const union = unionDateOverride(name, field, encoding);
2316
+ return union === undefined ? options : { ...options, unionDateOverride: union, ...reads };
2317
+ };
2195
2318
  /**
2196
2319
  * Validate that no model field combines a transform schema with a storage
2197
2320
  * override. The two configuration paths are mutually exclusive: either declare
@@ -2349,11 +2472,17 @@ protoRenamed = false) => {
2349
2472
  // removed from, reads without it. Up to 1.40.0 the target replaced the declaration whole.
2350
2473
  const optional = optionalField(ownValue(modelFields, ref.fieldName));
2351
2474
  const asDeclared = (target) => optional === undefined ? target : optional.rewrap(target);
2475
+ // In the storage the target's `DynamoModel.configure` gives its fields, which the ref holds them
2476
+ // in (`refDataOf`), and its refs' fields in theirs. Up to 1.41.0 the default: a date stored as
2477
+ // epoch seconds read back as milliseconds, and a condition or `pathSet` on it sent ISO text.
2478
+ const storage = heldStorageOf(ref.refEntity);
2479
+ const configured = storage === undefined ? {} : { configuredStorage: storage };
2352
2480
  // What a read of the target returns (`refHeldSchema`): its required hidden fields left out.
2353
- setOwn(fields, ref.fieldName, asDeclared(refHeldSchema(resolved, { enforceChecks: true })));
2481
+ setOwn(fields, ref.fieldName, asDeclared(refHeldSchema(resolved, { enforceChecks: true, ...configured })));
2354
2482
  setOwn(readFields, ref.fieldName, asDeclared(refHeldSchema(resolved, {
2355
2483
  legacyReads: true,
2356
2484
  absentReads: true,
2485
+ ...configured,
2357
2486
  })));
2358
2487
  }
2359
2488
  // Each of Effect's look-alike declarations (a `BigDecimal`, a `Duration`, an address, a date in
@@ -2768,6 +2897,22 @@ const asStored = (value) => {
2768
2897
  }
2769
2898
  return out;
2770
2899
  };
2900
+ /** Text, a number, a `bigint` or a boolean. */
2901
+ const isPrimitive = (value) => {
2902
+ const type = typeof value;
2903
+ return type === "string" || type === "number" || type === "bigint" || type === "boolean";
2904
+ };
2905
+ /** The type DynamoDB holds a primitive as: text, a number (a `bigint` too), or a boolean. */
2906
+ const dynamoTypeOf = (value) => typeof value === "string" ? "S" : typeof value === "boolean" ? "BOOL" : "N";
2907
+ /**
2908
+ * Whether a condition's or filter's `operand` is sent as given where a write of it stores `stored`
2909
+ * (#242): a primitive is, unless what's stored is a primitive of another type, which no row holds
2910
+ * the operand as (`5` where a `NumberFromString` stores `"5"`). Text where text is stored could be
2911
+ * the stored text itself, a substring for `contains` or a prefix, which the library can't tell
2912
+ * apart, so it is sent as 1.41.0 sent it; so is a number where a number is stored, and a primitive
2913
+ * where what's stored is no primitive.
2914
+ */
2915
+ const keepsAsGiven = (operand, stored) => isPrimitive(operand) && (!isPrimitive(stored) || dynamoTypeOf(stored) === dynamoTypeOf(operand));
2771
2916
  /** A plain object or class instance whose fields a path value can be walked by. */
2772
2917
  const isWalkableObject = (value) => value !== null &&
2773
2918
  typeof value === "object" &&
@@ -2789,8 +2934,10 @@ export const containedKindOf = (field) => {
2789
2934
  /**
2790
2935
  * A `contains` operand in the form the field stores what it compares (#242), from what a write of
2791
2936
  * a whole value there stores (`value`) and of one list element (`element`): the element as a list
2792
- * stores it; the single member of a write of a set holding it; the text a write of it stores, when
2793
- * that's text. `undefined` when the field doesn't take it so, and the operand is sent as given.
2937
+ * stores it; the single member of a write of a set holding it (a primitive member as given, unless
2938
+ * the set stores it as a primitive of another type: {@link keepsAsGiven}); the text a write of it
2939
+ * stores, when that's text. `undefined` when the field doesn't take it so, and the operand is sent
2940
+ * as given.
2794
2941
  *
2795
2942
  * @internal
2796
2943
  */
@@ -2799,7 +2946,10 @@ export const containedOperand = (kind, value, element) => (operand) => {
2799
2946
  return element(operand);
2800
2947
  if (kind === "set") {
2801
2948
  const set = value(new Set([operand]))?.stored;
2802
- return set instanceof Set && set.size === 1 ? { stored: [...set][0] } : undefined;
2949
+ if (!(set instanceof Set) || set.size !== 1)
2950
+ return undefined;
2951
+ const member = [...set][0];
2952
+ return { stored: keepsAsGiven(operand, member) ? operand : member };
2803
2953
  }
2804
2954
  const text = value(operand);
2805
2955
  return typeof text?.stored === "string" ? text : undefined;
@@ -2899,7 +3049,12 @@ refTargets = {},
2899
3049
  */
2900
3050
  storable,
2901
3051
  /** The entity's READ schemas of the model's fields, which a row is decoded by (`readsAsGiven`). */
2902
- readFields = {}) => {
3052
+ readFields = {},
3053
+ /**
3054
+ * What each ref's entity holds its fields in (`heldStorageOf`), its own refs' included, keyed by
3055
+ * ref field: the ref holds them in it, as its schemas do.
3056
+ */
3057
+ refStorage = {}) => {
2903
3058
  const recordFields = writeFields;
2904
3059
  const cache = new Map();
2905
3060
  const encoderFor = (key, resolve) => {
@@ -3061,6 +3216,21 @@ readFields = {}) => {
3061
3216
  }
3062
3217
  return current === undefined ? undefined : { schema: current, asDeclared };
3063
3218
  };
3219
+ /**
3220
+ * `original`, the model's schema at `segments` (below a field), as a write stores it: a field of a
3221
+ * ref's target in the storage its `DynamoModel.configure` gives it, which the ref holds it in
3222
+ * (`refStorage`), as the ref's own schemas do, and a field of a ref that target holds in turn in
3223
+ * its entity's.
3224
+ */
3225
+ const storedSchema = (segments, original) => {
3226
+ const name = segments[segments.length - 1];
3227
+ let held = typeof segments[0] === "string" ? ownValue(refStorage, segments[0]) : undefined;
3228
+ for (const segment of segments.slice(1, -1)) {
3229
+ held = typeof segment === "string" ? ownValue(held?.refs, segment) : undefined;
3230
+ }
3231
+ const named = typeof name === "string";
3232
+ return substituteSchemaDeep(original, withConfiguredStorage({ enforceChecks: true }, name, original, named ? ownValue(held?.fields, name) : undefined, named ? ownValue(held?.refs, name) : undefined));
3233
+ };
3064
3234
  const schemaAt = (segments) => {
3065
3235
  const at = originalAt(segments);
3066
3236
  if (at === undefined)
@@ -3071,7 +3241,7 @@ readFields = {}) => {
3071
3241
  ? ownValue(recordFields, head)
3072
3242
  : at.asDeclared
3073
3243
  ? original
3074
- : substituteSchemaDeep(original, { enforceChecks: true });
3244
+ : storedSchema(segments, original);
3075
3245
  return stored === undefined ? undefined : { original, stored };
3076
3246
  };
3077
3247
  const validators = new Map();
@@ -3109,7 +3279,7 @@ readFields = {}) => {
3109
3279
  const [head, ...rest] = segments;
3110
3280
  if (typeof head !== "string")
3111
3281
  return undefined;
3112
- const top = refTargets[head] ?? modelFields[head];
3282
+ const top = ownValue(refTargets, head) ?? ownValue(modelFields, head);
3113
3283
  if (top === undefined)
3114
3284
  return undefined;
3115
3285
  const holdsNoPath = new Set([
@@ -3214,16 +3384,32 @@ readFields = {}) => {
3214
3384
  : declared.flatMap((position) => {
3215
3385
  const original = position.schema;
3216
3386
  const stored = segments.length === 1
3217
- ? recordFields[head]
3387
+ ? ownValue(recordFields, head)
3218
3388
  : position.asDeclared
3219
3389
  ? original
3220
- : substituteSchemaDeep(original, { enforceChecks: true });
3390
+ : storedSchema(segments, original);
3221
3391
  if (stored === undefined)
3222
3392
  return [];
3223
3393
  const formOf = (from, to) => {
3224
3394
  const encode = leafAwareEncoder(from, to);
3225
3395
  const decode = Schema.decodeUnknownExit(to);
3226
3396
  return (value) => {
3397
+ if (isPrimitive(value)) {
3398
+ // A primitive is put in its stored form only where that is a primitive of
3399
+ // another type (`5` where a `NumberFromString` stores `"5"`), and is sent as
3400
+ // given anywhere else, as up to 1.41.0 ({@link keepsAsGiven}).
3401
+ const encoded = encode(value);
3402
+ const issue = issueOf(() => decode(asStored(encoded)));
3403
+ if (issue === CANT_SAY)
3404
+ return { stored: value };
3405
+ if (issue !== undefined)
3406
+ return undefined;
3407
+ if (keepsAsGiven(value, encoded))
3408
+ return { stored: value };
3409
+ return storable === undefined || storable(encoded)
3410
+ ? { stored: encoded }
3411
+ : undefined;
3412
+ }
3227
3413
  const encoded = encode(value);
3228
3414
  if (decode(asStored(encoded))._tag !== "Success")
3229
3415
  return undefined;
@@ -3253,7 +3439,7 @@ readFields = {}) => {
3253
3439
  const [head, ...rest] = segments;
3254
3440
  if (typeof head !== "string")
3255
3441
  return [];
3256
- const start = refTargets[head] ?? modelFields[head];
3442
+ const start = ownValue(refTargets, head) ?? ownValue(modelFields, head);
3257
3443
  if (start === undefined)
3258
3444
  return [];
3259
3445
  const ways = [];
@@ -3453,7 +3639,9 @@ readFields = {}) => {
3453
3639
  };
3454
3640
  const reads = (clauses, strict) => {
3455
3641
  const head = clauses[0]?.segments[0];
3456
- const start = typeof head === "string" ? (refTargets[head] ?? modelFields[head]) : undefined;
3642
+ const start = typeof head === "string"
3643
+ ? (ownValue(refTargets, head) ?? ownValue(modelFields, head))
3644
+ : undefined;
3457
3645
  // A field the walk can't follow is one the schema can't judge.
3458
3646
  if (start === undefined || clauses.some((clause) => clause.segments[0] !== head)) {
3459
3647
  return !strict;