@effect-dynamodb/schema 1.39.0 → 1.40.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 (72) hide show
  1. package/dist/Aggregate.d.ts +11 -4
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +9 -2
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/DynamoModel.d.ts +13 -0
  6. package/dist/DynamoModel.d.ts.map +1 -1
  7. package/dist/DynamoModel.js.map +1 -1
  8. package/dist/DynamoSchema.d.ts +5 -0
  9. package/dist/DynamoSchema.d.ts.map +1 -1
  10. package/dist/DynamoSchema.js.map +1 -1
  11. package/dist/Entity.d.ts +61 -8
  12. package/dist/Entity.d.ts.map +1 -1
  13. package/dist/Entity.js +182 -5
  14. package/dist/Entity.js.map +1 -1
  15. package/dist/KeyComposer.d.ts +157 -3
  16. package/dist/KeyComposer.d.ts.map +1 -1
  17. package/dist/KeyComposer.js +355 -9
  18. package/dist/KeyComposer.js.map +1 -1
  19. package/dist/internal/AggregateEdges.d.ts +3 -3
  20. package/dist/internal/AggregateSchemas.d.ts +181 -14
  21. package/dist/internal/AggregateSchemas.d.ts.map +1 -1
  22. package/dist/internal/AggregateSchemas.js +505 -45
  23. package/dist/internal/AggregateSchemas.js.map +1 -1
  24. package/dist/internal/AggregateTypes.d.ts +396 -36
  25. package/dist/internal/AggregateTypes.d.ts.map +1 -1
  26. package/dist/internal/CompositeCodec.d.ts +274 -6
  27. package/dist/internal/CompositeCodec.d.ts.map +1 -1
  28. package/dist/internal/CompositeCodec.js +829 -25
  29. package/dist/internal/CompositeCodec.js.map +1 -1
  30. package/dist/internal/EffectInstances.d.ts +81 -0
  31. package/dist/internal/EffectInstances.d.ts.map +1 -0
  32. package/dist/internal/EffectInstances.js +656 -0
  33. package/dist/internal/EffectInstances.js.map +1 -0
  34. package/dist/internal/EntitySchemas.d.ts +103 -27
  35. package/dist/internal/EntitySchemas.d.ts.map +1 -1
  36. package/dist/internal/EntitySchemas.js +778 -131
  37. package/dist/internal/EntitySchemas.js.map +1 -1
  38. package/dist/internal/EntityTypes.d.ts +67 -11
  39. package/dist/internal/EntityTypes.d.ts.map +1 -1
  40. package/dist/internal/FailingAsBefore.d.ts +25 -0
  41. package/dist/internal/FailingAsBefore.d.ts.map +1 -0
  42. package/dist/internal/FailingAsBefore.js +42 -0
  43. package/dist/internal/FailingAsBefore.js.map +1 -0
  44. package/dist/internal/InstanceReads.d.ts +33 -0
  45. package/dist/internal/InstanceReads.d.ts.map +1 -0
  46. package/dist/internal/InstanceReads.js +165 -0
  47. package/dist/internal/InstanceReads.js.map +1 -0
  48. package/dist/internal/KeyText136.d.ts +4 -2
  49. package/dist/internal/KeyText136.d.ts.map +1 -1
  50. package/dist/internal/KeyText136.js +40 -9
  51. package/dist/internal/KeyText136.js.map +1 -1
  52. package/dist/internal/NumericKey.d.ts +21 -2
  53. package/dist/internal/NumericKey.d.ts.map +1 -1
  54. package/dist/internal/NumericKey.js +19 -1
  55. package/dist/internal/NumericKey.js.map +1 -1
  56. package/dist/internal/PackedCodec.d.ts +8 -1
  57. package/dist/internal/PackedCodec.d.ts.map +1 -1
  58. package/dist/internal/PackedCodec.js +49 -13
  59. package/dist/internal/PackedCodec.js.map +1 -1
  60. package/dist/internal/SchemaAccessors.d.ts +160 -1
  61. package/dist/internal/SchemaAccessors.d.ts.map +1 -1
  62. package/dist/internal/SchemaAccessors.js +994 -1
  63. package/dist/internal/SchemaAccessors.js.map +1 -1
  64. package/dist/internal/SharedKeyAttribute.d.ts +60 -6
  65. package/dist/internal/SharedKeyAttribute.d.ts.map +1 -1
  66. package/dist/internal/SharedKeyAttribute.js +127 -12
  67. package/dist/internal/SharedKeyAttribute.js.map +1 -1
  68. package/dist/internal/SparseKey.d.ts +46 -0
  69. package/dist/internal/SparseKey.d.ts.map +1 -0
  70. package/dist/internal/SparseKey.js +69 -0
  71. package/dist/internal/SparseKey.js.map +1 -0
  72. package/package.json +1 -1
@@ -12,7 +12,8 @@
12
12
  *
13
13
  * Not part of the public API.
14
14
  */
15
- import { SchemaAST } from "effect";
15
+ import { Exit, Schema, SchemaAST } from "effect";
16
+ import { effectDeclarationOf } from "./EffectInstances.js";
16
17
  /**
17
18
  * Read `.fields` from a `Schema.Struct` or `Schema.Class`.
18
19
  *
@@ -81,6 +82,28 @@ export const extractArrayElement = (fieldSchema) => {
81
82
  }
82
83
  return undefined;
83
84
  };
85
+ /**
86
+ * The value schema of a keyed collection a custom `decompose` takes apart: `Schema.Record(K, T)`,
87
+ * under `optional` / `optionalKey` too. Returns `T`.
88
+ */
89
+ export const extractKeyedValue = (fieldSchema) => {
90
+ const keyed = (schema) => getSchemaProp(schema, "key") === undefined ? undefined : getSchemaProp(schema, "value");
91
+ if (SchemaAST.isOptional(fieldSchema.ast)) {
92
+ const inner = getSchemaProp(fieldSchema, "schema");
93
+ if (inner === undefined)
94
+ return undefined;
95
+ const members = getSchemaMembers(inner);
96
+ if (members === undefined)
97
+ return keyed(inner);
98
+ for (const member of members) {
99
+ const value = keyed(member);
100
+ if (value !== undefined)
101
+ return value;
102
+ }
103
+ return undefined;
104
+ }
105
+ return keyed(fieldSchema);
106
+ };
84
107
  /** Read the typed `.value` element schema off an `Array`/`NonEmptyArray` schema. */
85
108
  const arrayValue = (schema) => getSchemaProp(schema, "value");
86
109
  /** Read the typed `.members` array off a `Union` schema, if present. */
@@ -209,4 +232,974 @@ export const numericTypeWithStringEncoding = (schema) => {
209
232
  const encodedAst = SchemaAST.toEncoded(schema.ast);
210
233
  return ((SchemaAST.isNumber(typeAst) || SchemaAST.isBigInt(typeAst)) && SchemaAST.isString(encodedAst));
211
234
  };
235
+ /** The `representation` id Effect gives `Schema.ReadonlySet`, the one type stored as a set. */
236
+ const READONLY_SET = "effect/schema/ReadonlySet";
237
+ /** The `representation` id Effect gives a declaration of its own. A custom one has none. */
238
+ const representationIdOf = (ast) => {
239
+ const representation = ast.annotations?.representation;
240
+ const id = representation?.id;
241
+ return typeof id === "string" ? id : undefined;
242
+ };
243
+ /** Whether an AST is the declaration Effect represents under this id. */
244
+ const isDeclarationOf = (ast, id) => ast._tag === "Declaration" && representationIdOf(ast) === id;
245
+ /** Whether an AST is a `Schema.ReadonlySet`, by the id Effect gives its representation. */
246
+ export const isSetDeclaration = (ast) => isDeclarationOf(ast, READONLY_SET);
247
+ const NO_LONGER_DECODES = "it's stored as an empty map, which no longer decodes";
248
+ /**
249
+ * Effect's declarations that no owner can read back, by the `representation` id Effect gives them,
250
+ * each with a replacement measured on entities, aggregates, streams and outboxes.
251
+ */
252
+ const NEVER_READ_BACK = {
253
+ "effect/schema/ReadonlyMap": {
254
+ name: "Schema.ReadonlyMap",
255
+ why: "it's stored as a map, a map reads back as a plain object, and the row no longer decodes",
256
+ use: "Schema.Record, which is stored the same way and reads back",
257
+ },
258
+ "effect/schema/HashMap": {
259
+ name: "Schema.HashMap",
260
+ why: "a non-empty one can't be written, and an empty one is stored as its internals, which no longer decode",
261
+ use: "Schema.Record",
262
+ },
263
+ "effect/schema/Chunk": {
264
+ name: "Schema.Chunk",
265
+ why: "writing one overflows the stack, so nothing is ever stored",
266
+ use: "Schema.Array",
267
+ },
268
+ "effect/schema/URL": {
269
+ name: "Schema.URL",
270
+ why: "it's stored as a map of its parts, which no longer decodes",
271
+ use: "Schema.URLFromString",
272
+ },
273
+ "effect/schema/URLSearchParams": {
274
+ name: "Schema.URLSearchParams",
275
+ why: "it's stored as a map of its size alone, which no longer decodes",
276
+ use: "Schema.String, holding the parameters as text",
277
+ },
278
+ "effect/schema/RegExp": {
279
+ name: "Schema.RegExp",
280
+ why: NO_LONGER_DECODES,
281
+ use: "Schema.String, holding the pattern as text",
282
+ },
283
+ "effect/schema/FormData": {
284
+ name: "Schema.FormData",
285
+ why: NO_LONGER_DECODES,
286
+ use: "Schema.Record",
287
+ },
288
+ "effect/http/Headers": {
289
+ name: "Schema.Headers",
290
+ why: "it's stored as a map, a map reads back as a plain object, and the row no longer decodes",
291
+ use: "Schema.Record",
292
+ },
293
+ "effect/schema/File": {
294
+ name: "Schema.File",
295
+ why: "it's stored as bytes without its name or type, which no longer decode",
296
+ use: "Schema.Uint8Array",
297
+ },
298
+ "effect/schema/ByteSize": {
299
+ name: "Schema.ByteSize",
300
+ why: "it's stored as a number, which no longer decodes",
301
+ use: "Schema.ByteSizeFromString or Schema.ByteSizeFromNumber",
302
+ },
303
+ "effect/schema/Error": {
304
+ name: "Schema.ErrorInstance",
305
+ why: NO_LONGER_DECODES,
306
+ use: "Schema.Defect()",
307
+ },
308
+ };
309
+ const DATE = "effect/schema/Date";
310
+ const REDACTED = "effect/schema/Redacted";
311
+ /** What an aggregate's date encoder stores as a string. */
312
+ const DATE_DOMAINS = new Set([
313
+ DATE,
314
+ "effect/schema/DateTimeUtc",
315
+ "effect/schema/DateTimeZoned",
316
+ ]);
317
+ const PLAIN_DATE = {
318
+ name: "Schema.Date",
319
+ why: `${NO_LONGER_DECODES}. An entity or an aggregate stores one as a string only where it reaches it, which isn't under another declaration, a Schema.suspend, a transformation or a decoding default on a container`,
320
+ use: "Schema.DateFromString or Schema.DateFromMillis",
321
+ };
322
+ const TRANSFORMED_DATE = {
323
+ name: "a transformation over Schema.Date, such as Schema.DateTimeUtcFromDate",
324
+ why: "its stored form no longer decodes",
325
+ use: "Schema.DateTimeUtcFromString or Schema.DateTimeUtcFromMillis",
326
+ };
327
+ const PLAIN_REDACTED = {
328
+ name: "Schema.Redacted",
329
+ why: "its value isn't stored, and reading it fails. An entity or an aggregate stores the value only where it reaches it, which isn't under another declaration, a Schema.suspend, a transformation or a decoding default on a container",
330
+ use: "Schema.RedactedFromValue",
331
+ };
332
+ const BIGINT_BESIDE_A_NUMBER = {
333
+ name: "a union of Schema.BigInt and something else stored as a number",
334
+ why: "5n and 5 are stored the same, so a read can't tell which one was written",
335
+ use: "Schema.BigIntFromString",
336
+ };
337
+ const BIGINT_LITERAL = {
338
+ name: "a bigint Schema.Literal",
339
+ why: "it's stored as a number, which reads back as a number and no longer decodes",
340
+ use: "a string or a number literal",
341
+ };
342
+ /**
343
+ * Whether a field reached this node through a transformation. A decoding default isn't one, and the
344
+ * owner's substitution sees through it. A transformation is one even when it ends in the type it
345
+ * started from, since the owner stores and reads what's beneath it.
346
+ */
347
+ const isTransformed = (walk) => walk.declared !== undefined && walk.beneath !== "default";
348
+ /** Whether this node, on its own, is something this owner can't read back. */
349
+ const unreadableAt = (ast, walk) => {
350
+ const stored = walk.by !== "schema" && !walk.unreached && !walk.writtenAsIs;
351
+ switch (ast._tag) {
352
+ case "Literal":
353
+ return typeof ast.literal === "bigint" ? BIGINT_LITERAL : undefined;
354
+ case "Declaration": {
355
+ const id = representationIdOf(ast) ?? "";
356
+ if (id === DATE) {
357
+ if (isTransformed(walk))
358
+ return TRANSFORMED_DATE;
359
+ return stored ? undefined : PLAIN_DATE;
360
+ }
361
+ if (id === REDACTED) {
362
+ // A step ending in a redacted value is substituted whole. A step onto anything else, such as
363
+ // `Schema.OptionFromOptional`, writes what's beneath it as declared.
364
+ const overAnother = isTransformed(walk) && representationIdOf(walk.declared) !== REDACTED;
365
+ return stored && !overAnother ? undefined : PLAIN_REDACTED;
366
+ }
367
+ return NEVER_READ_BACK[id];
368
+ }
369
+ default:
370
+ return undefined;
371
+ }
372
+ };
373
+ /** What a suspended node stands for, and the suspensions on the way to it. `undefined` is a cycle. */
374
+ const forced = (ast, seen) => {
375
+ if (!SchemaAST.isSuspend(ast))
376
+ return { node: ast, seen };
377
+ return seen.has(ast) ? undefined : forced(ast.thunk(), new Set(seen).add(ast));
378
+ };
379
+ const JSON_VALUES = new Set([
380
+ "effect/schema/Json",
381
+ "effect/schema/MutableJson",
382
+ ]);
383
+ /** A number may be what it takes: a custom declaration doesn't say, and the rest take any value. */
384
+ const takesAnything = (ast) => SchemaAST.isUnknown(ast) ||
385
+ SchemaAST.isAny(ast) ||
386
+ (SchemaAST.isDeclaration(ast) &&
387
+ (representationIdOf(ast) === undefined || JSON_VALUES.has(representationIdOf(ast))));
388
+ const isNumeric = (ast) => SchemaAST.isNumber(ast) ||
389
+ SchemaAST.isEnum(ast) ||
390
+ (SchemaAST.isLiteral(ast) && typeof ast.literal === "number");
391
+ /** The kind of attribute a node takes, with a bigint's being a number's. */
392
+ const storedKind = (ast) => SchemaAST.isLiteral(ast)
393
+ ? typeof ast.literal
394
+ : isNumeric(ast) || SchemaAST.isBigInt(ast)
395
+ ? "number"
396
+ : SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)
397
+ ? "string"
398
+ : SchemaAST.isBoolean(ast)
399
+ ? "boolean"
400
+ : ast._tag;
401
+ /** Whether a struct's map is one a struct takes: it has every field the struct requires. */
402
+ const hasFieldsOf = (writer, taker) => taker.propertySignatures.every((theirs) => SchemaAST.isOptional(theirs.type) ||
403
+ writer.indexSignatures.length > 0 ||
404
+ writer.propertySignatures.some((mine) => mine.name === theirs.name));
405
+ const storedMap = (tag, marker, fields) => Schema.Struct({
406
+ _op: Schema.String,
407
+ _tag: Schema.Literal(tag),
408
+ [marker]: Schema.Struct({}),
409
+ ...Object.fromEntries(Object.entries(fields).map(([name, ast]) => [name, Schema.make(ast)])),
410
+ }).ast;
411
+ /**
412
+ * The maps the marshaller makes of a declaration, where one holds a value in it. A struct takes a
413
+ * stored value by its fields, so these say which structs take one of these for their own.
414
+ */
415
+ const STORED_MAPS = {
416
+ "effect/schema/Option": ([value]) => [
417
+ storedMap("Some", "~effect/Option", { value: value }),
418
+ storedMap("None", "~effect/Option", {}),
419
+ ],
420
+ "effect/schema/Result": ([success, failure]) => [
421
+ storedMap("Success", "~effect/Result", { success: success }),
422
+ storedMap("Failure", "~effect/Result", { failure: failure }),
423
+ ],
424
+ };
425
+ const storedMapsOf = (ast) => STORED_MAPS[representationIdOf(ast) ?? ""]?.(ast.typeParameters);
426
+ /**
427
+ * Whether a struct declares a marker. Each of Effect's declarations looks for its marker or a class,
428
+ * and none takes any other map or a primitive (measured, each of them), so a struct's map is one of
429
+ * theirs only with a marker in it.
430
+ */
431
+ const declaresMarker = (ast) => ast.propertySignatures.some((property) => typeof property.name === "string" && property.name.startsWith("~effect/"));
432
+ /**
433
+ * Whether a stored value could be one both a declaration of Effect's and this take. What a struct
434
+ * takes of one depends on the map it's stored as. Two declarations, or a struct beside a declaration
435
+ * whose map isn't known, count.
436
+ */
437
+ const declarationCouldBe = (declaration, other, seen) => {
438
+ if (SchemaAST.isDeclaration(other))
439
+ return true;
440
+ if (!SchemaAST.isObjects(other))
441
+ return false;
442
+ const maps = storedMapsOf(declaration);
443
+ return (maps === undefined ||
444
+ maps.some((map) => hasFieldsOf(map, other) && couldBeBoth(map, other, seen)));
445
+ };
446
+ /** Whether a stored value could be one both of these take. What can't be told apart counts. */
447
+ const couldBeBoth = (a, b, seen) => {
448
+ const left = forced(a, seen);
449
+ const right = forced(b, left?.seen ?? seen);
450
+ if (left === undefined || right === undefined)
451
+ return true;
452
+ const [l, r, within] = [left.node, right.node, right.seen];
453
+ if (SchemaAST.isUnion(l))
454
+ return l.types.some((type) => couldBeBoth(type, r, within));
455
+ if (SchemaAST.isUnion(r))
456
+ return r.types.some((type) => couldBeBoth(l, type, within));
457
+ if (takesAnything(l) || takesAnything(r))
458
+ return true;
459
+ if (SchemaAST.isDeclaration(l))
460
+ return declarationCouldBe(l, r, within);
461
+ if (SchemaAST.isDeclaration(r))
462
+ return declarationCouldBe(r, l, within);
463
+ if (SchemaAST.isLiteral(l) && SchemaAST.isLiteral(r))
464
+ return l.literal === r.literal;
465
+ if (SchemaAST.isObjects(l) && SchemaAST.isObjects(r)) {
466
+ // A record takes a field its values could be, and a key it doesn't cover says nothing.
467
+ const fitsRecord = (fields, record) => fields.propertySignatures.every((property) => SchemaAST.isOptional(property.type) ||
468
+ record.propertySignatures.some((named) => named.name === property.name) ||
469
+ record.indexSignatures.every((index) => !SchemaAST.isString(index.parameter) ||
470
+ couldBeBoth(property.type, index.type, within)));
471
+ return (fitsRecord(l, r) &&
472
+ fitsRecord(r, l) &&
473
+ l.propertySignatures.every((property) => {
474
+ const other = r.propertySignatures.find((candidate) => candidate.name === property.name);
475
+ return (other === undefined ||
476
+ (SchemaAST.isOptional(property.type) && SchemaAST.isOptional(other.type)) ||
477
+ couldBeBoth(property.type, other.type, within));
478
+ }));
479
+ }
480
+ return storedKind(l) === storedKind(r);
481
+ };
482
+ /** Whether a stored side holds a plain bigint anywhere. */
483
+ export const holdsPlainBigint = (ast, seen = new Set()) => {
484
+ const found = forced(ast, seen);
485
+ if (found === undefined)
486
+ return false;
487
+ const { node } = found;
488
+ const within = (asts) => asts.some((part) => holdsPlainBigint(part, found.seen));
489
+ switch (node._tag) {
490
+ case "BigInt":
491
+ return true;
492
+ case "Declaration":
493
+ return within(node.typeParameters);
494
+ case "Union":
495
+ return within(node.types);
496
+ case "Arrays":
497
+ return within([...node.elements, ...node.rest]);
498
+ case "Objects":
499
+ return within([
500
+ ...node.propertySignatures.map((property) => property.type),
501
+ ...node.indexSignatures.map((signature) => signature.type),
502
+ ]);
503
+ default:
504
+ return false;
505
+ }
506
+ };
507
+ /**
508
+ * Whether a number can end up on the wrong side of a plain bigint, between two members of a union.
509
+ * The bigint is lifted where it sits and a union tries its members in order, so whichever of the two
510
+ * comes `first` takes what the other stored, if it has what the first requires: a bigint's number
511
+ * kept as a number, or another member's number lifted to a bigint. Two structs apart on a field, as
512
+ * tagged events are, can't. A value lost to an earlier member that has no place for it isn't this:
513
+ * a union of anything does that. What can't be told apart counts.
514
+ */
515
+ const confusesItsBigint = (holder, other, first, seen) => {
516
+ const left = forced(holder, seen);
517
+ const right = forced(other, left?.seen ?? seen);
518
+ if (left === undefined || right === undefined)
519
+ return false;
520
+ const [l, r, within] = [left.node, right.node, right.seen];
521
+ const confused = (mine, theirs) => confusesItsBigint(mine, theirs, first, within);
522
+ if (SchemaAST.isUnion(l))
523
+ return l.types.some((type) => confused(type, r));
524
+ if (SchemaAST.isUnion(r))
525
+ return r.types.some((type) => confused(l, type));
526
+ if (SchemaAST.isBigInt(l))
527
+ return isNumeric(r) || takesAnything(r);
528
+ if (takesAnything(r))
529
+ return !(first && SchemaAST.isDeclaration(l)) && holdsPlainBigint(l);
530
+ if (SchemaAST.isArrays(l)) {
531
+ if (!SchemaAST.isArrays(r))
532
+ return false;
533
+ const fixed = Math.min(l.elements.length, r.elements.length);
534
+ const parts = (ast) => [...ast.elements, ...ast.rest];
535
+ return (l.elements
536
+ .slice(0, fixed)
537
+ .every((element, i) => couldBeBoth(element, r.elements[i], new Set())) &&
538
+ parts(l).some((mine, i) => (i < fixed ? [r.elements[i]] : parts(r)).some((theirs) => confused(mine, theirs))));
539
+ }
540
+ if (SchemaAST.isObjects(l)) {
541
+ if (SchemaAST.isDeclaration(r)) {
542
+ if (!first)
543
+ return declaresMarker(l) && holdsPlainBigint(l);
544
+ return storedMapsOf(r)?.some((map) => confused(l, map)) ?? false;
545
+ }
546
+ if (!SchemaAST.isObjects(r))
547
+ return false;
548
+ if (!(first ? hasFieldsOf(r, l) : hasFieldsOf(l, r)) || !couldBeBoth(l, r, new Set())) {
549
+ return false;
550
+ }
551
+ const records = r.indexSignatures.map((signature) => signature.type);
552
+ return (l.propertySignatures.some((mine) => {
553
+ const named = r.propertySignatures.find((theirs) => theirs.name === mine.name);
554
+ return (named === undefined ? records : [named.type]).some((theirs) => confused(mine.type, theirs));
555
+ }) ||
556
+ l.indexSignatures.some((signature) => [...r.propertySignatures.map((theirs) => theirs.type), ...records].some((theirs) => confused(signature.type, theirs))));
557
+ }
558
+ if (SchemaAST.isDeclaration(l)) {
559
+ if (SchemaAST.isObjects(r)) {
560
+ if (first)
561
+ return declaresMarker(r) && holdsPlainBigint(l);
562
+ if (isSetDeclaration(l))
563
+ return false;
564
+ const maps = storedMapsOf(l);
565
+ return maps === undefined ? holdsPlainBigint(l) : maps.some((map) => confused(map, r));
566
+ }
567
+ return (SchemaAST.isDeclaration(r) &&
568
+ representationIdOf(l) === representationIdOf(r) &&
569
+ l.typeParameters.some((parameter, i) => r.typeParameters[i] !== undefined && confused(parameter, r.typeParameters[i])));
570
+ }
571
+ return false;
572
+ };
573
+ /**
574
+ * Whether a union's members can confuse a bigint with a number. A `oneOf` tries every member, so
575
+ * neither comes first and a value two of them take fails the read.
576
+ */
577
+ const hasBigintBesideANumber = (union) => {
578
+ const members = union.types.map((member) => SchemaAST.toEncoded(member));
579
+ return members.some((holder, at) => members.some((other, position) => position !== at &&
580
+ (union.options?.mode === "oneOf"
581
+ ? confusesItsBigint(holder, other, true, new Set()) ||
582
+ confusesItsBigint(holder, other, false, new Set())
583
+ : confusesItsBigint(holder, other, at < position, new Set()))));
584
+ };
585
+ /** A `Schema.Class`'s own encoding step, onto the struct of its fields, which are walked. */
586
+ const isClassStep = (ast, to) => SchemaAST.isDeclaration(ast) && ast.typeParameters[0] === to;
587
+ /** A union of X and undefined, and nothing else, which is what `Schema.optional(X)` makes of X. */
588
+ const isOptionalOfOne = (ast) => ast.types.filter((member) => !SchemaAST.isUndefined(member)).length === 1;
589
+ /** Whether a stored side has a type's shape: the same kind of node, with the same fields or elements. */
590
+ const sameShape = (type, stored) => {
591
+ if (type._tag !== stored._tag || representationIdOf(type) !== representationIdOf(stored)) {
592
+ return false;
593
+ }
594
+ if (SchemaAST.isArrays(type) && SchemaAST.isArrays(stored))
595
+ return sameElements(type, stored);
596
+ if (!SchemaAST.isObjects(type) || !SchemaAST.isObjects(stored))
597
+ return true;
598
+ const names = new Set(stored.propertySignatures.map((property) => property.name));
599
+ return (type.propertySignatures.length === names.size &&
600
+ type.propertySignatures.every((property) => names.has(property.name)));
601
+ };
602
+ /** Whether two lists hold the same things, which is what makes a step between them invisible. */
603
+ const sameElements = (type, stored) => {
604
+ const same = (a, b) => sameShape(SchemaAST.toType(a), SchemaAST.toType(b));
605
+ return (type.elements.length === stored.elements.length &&
606
+ type.rest.length === stored.rest.length &&
607
+ type.elements.every((element, at) => same(element, stored.elements[at])) &&
608
+ type.rest.every((element, at) => same(element, stored.rest[at])));
609
+ };
610
+ /**
611
+ * Whether a step onto `to` is a decoding default: the stored side may be absent, it's the same type
612
+ * on both sides, where `Schema.OptionFromOptionalKey` is a different one, and nothing else changes
613
+ * it on the way, as a transformation beneath the default would.
614
+ */
615
+ export const isDecodingDefault = (ast, to) => {
616
+ if (to.context?.isOptional !== true)
617
+ return false;
618
+ const steps = ast.encoding ?? [];
619
+ const type = steps.length === 2 ? steps[0].to : ast;
620
+ if (steps.length > 2 || (steps.length === 2 && !isClassStep(ast, type)))
621
+ return false;
622
+ const sides = SchemaAST.isUnion(to) && isOptionalOfOne(to) ? [to, ...to.types] : [to];
623
+ return sides.some((side) => sameShape(type, side));
624
+ };
625
+ /** The list a step's stored side is, if it's one: `Schema.UndefinedOr(Schema.Array(X))` is that array. */
626
+ export const storedList = (to) => {
627
+ const side = SchemaAST.isUnion(to) && isOptionalOfOne(to)
628
+ ? to.types.find((member) => !SchemaAST.isUndefined(member))
629
+ : to;
630
+ return side !== undefined && SchemaAST.isArrays(side) ? side : undefined;
631
+ };
632
+ /** The encoding step onto `to`, unless a class's own. */
633
+ const encodingStep = (ast, to, walk) => {
634
+ if (isClassStep(ast, to) || walk.beneath === "transformation")
635
+ return walk.beneath;
636
+ if (isDecodingDefault(ast, to))
637
+ return "default";
638
+ if (walk.by === "schema" || !SchemaAST.isArrays(ast))
639
+ return "transformation";
640
+ const list = storedList(to);
641
+ return list !== undefined && sameElements(ast, list) ? "list" : "transformation";
642
+ };
643
+ /** What the children of a container beneath an encoding are. A list stays seen through. */
644
+ const unreachedBy = (walk, list) => {
645
+ if (walk.beneath === undefined || (list && walk.beneath !== "transformation"))
646
+ return {};
647
+ return walk.beneath === "default" ? { writtenAsIs: true } : { unreached: true };
648
+ };
649
+ /** A plain date or nothing, as an aggregate's date encoder finds it in an attribute's union. */
650
+ const isNullablePlainDate = (ast) => SchemaAST.isUnion(ast) &&
651
+ ast.types.every((member) => SchemaAST.isNull(member) ||
652
+ SchemaAST.isUndefined(member) ||
653
+ (member.encoding === undefined && DATE_DOMAINS.has(representationIdOf(member))));
654
+ /**
655
+ * A transformation to a date on an aggregate: its date encoder stores the domain value as a string,
656
+ * whatever the transformation is over, except under a union or another declaration. It finds one
657
+ * under a decoding default too, in an attribute of the aggregate's own and not deeper.
658
+ */
659
+ const storedByDateEncoder = (ast, to, path, walk) => {
660
+ if (walk.by !== "aggregate" || walk.unreached || walk.inUnion)
661
+ return false;
662
+ return (DATE_DOMAINS.has(representationIdOf(SchemaAST.toType(ast))) ||
663
+ (to.context?.isOptional === true && !/[.[]/.test(path) && isNullablePlainDate(ast)));
664
+ };
665
+ /**
666
+ * The first thing in this AST that can't be read back, and its path. A cycle through
667
+ * `Schema.suspend` ends where it starts, and a path segment says what kind of value it went through.
668
+ */
669
+ const firstUnreadable = (ast, path, seen, walk) => {
670
+ const firstIn = (asts, at, next) => {
671
+ for (const part of asts) {
672
+ const found = firstUnreadable(part, at, seen, next);
673
+ if (found !== undefined)
674
+ return found;
675
+ }
676
+ return undefined;
677
+ };
678
+ const child = (at, list = false) => ({
679
+ ...walk,
680
+ ...unreachedBy(walk, list),
681
+ declared: undefined,
682
+ edge: walk.manyEdges.has(at),
683
+ });
684
+ const encoding = ast.encoding;
685
+ if (encoding !== undefined) {
686
+ const to = encoding[encoding.length - 1].to;
687
+ if (walk.declared === undefined && storedByDateEncoder(ast, to, path, walk))
688
+ return undefined;
689
+ const beneath = encodingStep(ast, to, walk);
690
+ return firstUnreadable(to, path, seen, {
691
+ ...walk,
692
+ declared: SchemaAST.toType(ast),
693
+ beneath,
694
+ });
695
+ }
696
+ if (!walk.edge) {
697
+ const what = unreadableAt(ast, walk);
698
+ if (what !== undefined)
699
+ return { at: path, what };
700
+ }
701
+ switch (ast._tag) {
702
+ case "Declaration":
703
+ return firstIn(ast.typeParameters, path, walk.edge
704
+ ? { ...walk, declared: undefined, edge: false }
705
+ : { ...walk, declared: undefined, unreached: true });
706
+ case "Suspend": {
707
+ if (seen.has(ast))
708
+ return undefined;
709
+ seen.add(ast);
710
+ return firstUnreadable(ast.thunk(), path, seen, { ...walk, unreached: true });
711
+ }
712
+ case "Union": {
713
+ // Where the substitution reaches a union, every member gets its try as declared and only a
714
+ // number none of them takes is lifted. Anywhere else the lift is on the bigint itself.
715
+ const lifted = walk.by === "schema" || walk.unreached || walk.beneath === "transformation";
716
+ if (lifted && hasBigintBesideANumber(ast)) {
717
+ return { at: path, what: BIGINT_BESIDE_A_NUMBER };
718
+ }
719
+ const members = {
720
+ ...walk,
721
+ // The union `Schema.optional(X)` makes under a default on X, which is X to the substitution.
722
+ ...(isOptionalOfOne(ast) && walk.declared?._tag !== "Union"
723
+ ? {}
724
+ : unreachedBy(walk, false)),
725
+ inUnion: walk.inUnion || ast.context?.isOptional !== true,
726
+ };
727
+ if (ast.context?.isOptional !== true)
728
+ return firstIn(ast.types, path, members);
729
+ // `Schema.optionalKey` over several members: the first is written in its stored form, and the
730
+ // rest as they're declared, unless an aggregate's date encoder finds them in its own attribute.
731
+ const defined = ast.types.filter((member) => !SchemaAST.isUndefined(member));
732
+ const encoded = walk.by === "aggregate" && !/[.[]/.test(path) && isNullablePlainDate(ast);
733
+ return (firstIn(defined.slice(0, 1), path, members) ??
734
+ firstIn(defined.slice(1), path, encoded ? members : { ...members, writtenAsIs: true }));
735
+ }
736
+ case "Arrays":
737
+ return firstIn([...ast.elements, ...ast.rest], `${path}[]`, child(`${path}[]`, ast.elements.length === 0));
738
+ case "Objects": {
739
+ for (const property of ast.propertySignatures) {
740
+ const name = String(property.name);
741
+ const at = path === "" ? name : `${path}.${name}`;
742
+ const found = firstUnreadable(property.type, at, seen, child(at));
743
+ if (found !== undefined)
744
+ return found;
745
+ }
746
+ return firstIn(ast.indexSignatures.map((signature) => signature.type), `${path}[key]`, child(`${path}[key]`));
747
+ }
748
+ default:
749
+ return undefined;
750
+ }
751
+ };
752
+ /**
753
+ * `[EDD-9125]`: a model whose stored side holds something its owner can't read back, at any depth.
754
+ * Either the write fails in a way nothing can recover, or it succeeds and the row no longer decodes,
755
+ * so a definition holding one can't work and fails at load. The stored side is what's read: a map
756
+ * decoded from a record, or under `Schema.toCodecJson`, is stored as that and reads back, and the
757
+ * collection a `many` edge is declared as is rows, of which only the rows are stored.
758
+ *
759
+ * Only Effect's own declarations can be judged here. A `Schema.instanceOf` and a duck-typed
760
+ * `Schema.declare` have the same AST, and one reads back where the other doesn't, so those are
761
+ * judged by value at write ({@link holdsCustomDeclaration}, `EDD-9126`).
762
+ */
763
+ export const refuseUnreadable = (owner, by, model, options) => {
764
+ const found = firstUnreadable(model.ast, "", new Set(), {
765
+ by,
766
+ manyEdges: options?.manyEdges ?? new Set(),
767
+ declared: undefined,
768
+ unreached: false,
769
+ writtenAsIs: false,
770
+ beneath: undefined,
771
+ inUnion: false,
772
+ edge: false,
773
+ });
774
+ if (found === undefined)
775
+ return;
776
+ const { at, what } = found;
777
+ throw new Error(`[EDD-9125] ${owner}: ${at === "" ? (options?.whole ?? "the model") : `field "${at}"`} is ` +
778
+ `${what.name.startsWith("Schema.") ? "a " : ""}${what.name}, which can't be read back: ` +
779
+ `${what.why}. Use ${what.use}.`);
780
+ };
781
+ /**
782
+ * Whether a stored side holds a declaration Effect didn't make, such as a `Schema.instanceOf` or a
783
+ * duck-typed `Schema.declare`. Only a value can say whether one reads back (`internal/RoundTrip.ts`
784
+ * in `effect-dynamodb`), and this says which schemas have such values. A `Schema.Class`, and a struct
785
+ * decoded to a class, have an encoding: what's stored is the struct, and only what's in it counts.
786
+ * Effect's own address and DNS record declarations carry no `representation` id, and read back as
787
+ * the instances they were (`internal/InstanceReads.ts`), so they're not custom: recognised by their
788
+ * parser, never by a name, so a `Schema.declare` of your own under the same identifier still is.
789
+ */
790
+ export const holdsCustomDeclaration = (ast, seen = new Set()) => {
791
+ const encoding = ast.encoding;
792
+ if (encoding !== undefined) {
793
+ return holdsCustomDeclaration(encoding[encoding.length - 1].to, seen);
794
+ }
795
+ const within = (asts) => asts.some((part) => holdsCustomDeclaration(part, seen));
796
+ switch (ast._tag) {
797
+ case "Declaration":
798
+ return ((representationIdOf(ast) === undefined && effectDeclarationOf(ast) === undefined) ||
799
+ within(ast.typeParameters));
800
+ case "Suspend": {
801
+ if (seen.has(ast))
802
+ return false;
803
+ seen.add(ast);
804
+ return holdsCustomDeclaration(ast.thunk(), seen);
805
+ }
806
+ case "Union":
807
+ return within(ast.types);
808
+ case "Arrays":
809
+ return within([...ast.elements, ...ast.rest]);
810
+ case "Objects":
811
+ return within([
812
+ ...ast.propertySignatures.map((property) => property.type),
813
+ ...ast.indexSignatures.map((signature) => signature.type),
814
+ ]);
815
+ default:
816
+ return false;
817
+ }
818
+ };
819
+ /**
820
+ * The value on a stored side that DynamoDB can't store, if there is one. With
821
+ * both in one union, `undefined` is what an absent attribute means.
822
+ */
823
+ const valueWithNoStoredForm = (ast, seen = new Set()) => {
824
+ switch (ast._tag) {
825
+ case "Undefined":
826
+ case "Void":
827
+ case "Unknown":
828
+ case "Any":
829
+ return { stored: undefined };
830
+ case "Declaration":
831
+ return isSetDeclaration(ast) ? { stored: new Set() } : undefined;
832
+ case "Suspend": {
833
+ if (seen.has(ast))
834
+ return undefined;
835
+ seen.add(ast);
836
+ return valueWithNoStoredForm(ast.thunk(), seen);
837
+ }
838
+ case "Union": {
839
+ const found = ast.types.flatMap((member) => valueWithNoStoredForm(member, seen) ?? []);
840
+ return found.find((value) => value.stored === undefined) ?? found[0];
841
+ }
842
+ default:
843
+ return undefined;
844
+ }
845
+ };
846
+ /**
847
+ * Whether a value of this type can be `undefined` and be stored as one: an `undefined` that
848
+ * encodes to something else has a stored form.
849
+ */
850
+ export const holdsUndefined = (ast) => [SchemaAST.toType(ast), SchemaAST.toEncoded(ast)].every((side) => {
851
+ const found = valueWithNoStoredForm(side);
852
+ return found !== undefined && found.stored === undefined;
853
+ });
854
+ /**
855
+ * The value a field's absent attribute stands for, from its schema alone: DynamoDB can't
856
+ * store `undefined` or an empty set, so on a field whose stored side includes one the value
857
+ * is an absent attribute. `undefined` when the rule doesn't apply: the field's key is
858
+ * optional, so absent reads as absent (or as its decoding default), or its stored side holds
859
+ * no such value. Nothing the schema runs is run, so a `.check()` that refuses the value isn't
860
+ * seen here: {@link absentReading} asks it, at a write.
861
+ */
862
+ export const absentStored = (field) => {
863
+ const encoded = SchemaAST.toEncoded(field.ast);
864
+ return SchemaAST.isOptional(encoded) ? undefined : valueWithNoStoredForm(encoded);
865
+ };
866
+ /**
867
+ * The one rule for values with no stored form. DynamoDB can't store `undefined`
868
+ * or an empty set, so on a field whose stored side includes one the value is an
869
+ * absent attribute, and an absent attribute reads back as that value. Returns
870
+ * what it reads back as, or `undefined` when the rule doesn't apply: the field's
871
+ * key is optional, so absent reads as absent (or as its decoding default); or
872
+ * its schema refuses the value, as a `.check()` for a non-empty set does, so no
873
+ * row may be without it.
874
+ *
875
+ * The check decodes for real, running the field's checks and transformations on the value,
876
+ * so it's asked by the write that leaves the attribute out and never while an entity is
877
+ * defined ({@link absentStored} answers there). A transformation that can't run
878
+ * synchronously is taken at its word, reading back as the stored value.
879
+ */
880
+ export const absentReading = (field) => {
881
+ const found = absentStored(field);
882
+ if (found === undefined)
883
+ return undefined;
884
+ const decoded = Schema.decodeUnknownExit(field)(found.stored);
885
+ if (Exit.hasFails(decoded))
886
+ return undefined;
887
+ return { stored: found.stored, value: Exit.isSuccess(decoded) ? decoded.value : found.stored };
888
+ };
889
+ /**
890
+ * Whether a step may make something of a key the stored row is without. A getter that only
891
+ * maps the value it's given (`passthrough`, `transform`, `transformEffect`) leaves an absent
892
+ * key absent. Anything else may act on the absence: a getter handed the `Option`
893
+ * (`SchemaGetter.withDefault` beneath every `Schema.withDecodingDefault*`, a step onto an
894
+ * `Option` as `Schema.OptionFromOptional`'s is, `SchemaGetter.required`), a middleware
895
+ * (`Schema.middlewareDecoding`, `Schema.catchDecoding`), which is handed the read of the
896
+ * missing key and can fill it or fail it, and any kind of step this doesn't know.
897
+ */
898
+ const actsOnAbsentKey = (link) => {
899
+ const transformation = link.transformation;
900
+ if (transformation._tag !== "Transformation")
901
+ return true;
902
+ const step = transformation.decode?._tag;
903
+ return !(step === "Passthrough" || step === "Transform" || step === "TransformEffect");
904
+ };
905
+ /**
906
+ * Whether the model's code may take part in reading a missing key through a node: a step
907
+ * that may act on the absence ({@link actsOnAbsentKey}), anywhere on the way from the most
908
+ * stored side up. A suspension is taken to: what it suspends isn't looked into here, so
909
+ * only reading the absence says.
910
+ */
911
+ const mayReadMissingKey = (ast) => SchemaAST.isSuspend(ast) ||
912
+ (ast.encoding ?? []).some((link) => actsOnAbsentKey(link) || mayReadMissingKey(link.to));
913
+ /**
914
+ * Whether reading through a node runs nothing but Effect's own parsing: no check, no
915
+ * transformation and no declaration of the model's own, anywhere in it. A check on the stored
916
+ * side of a flipped schema (`encodingChecks`) runs on a read too.
917
+ */
918
+ const runsNoCode = (ast, seen = new Set()) => {
919
+ if (seen.has(ast))
920
+ return true;
921
+ seen.add(ast);
922
+ if (ast.checks !== undefined ||
923
+ ast.encoding !== undefined ||
924
+ ast.encodingChecks !== undefined) {
925
+ return false;
926
+ }
927
+ const all = (asts) => asts.every((part) => runsNoCode(part, seen));
928
+ switch (ast._tag) {
929
+ case "Declaration":
930
+ return representationIdOf(ast) !== undefined && all(ast.typeParameters);
931
+ case "Suspend":
932
+ return runsNoCode(ast.thunk(), seen);
933
+ case "Union":
934
+ return all(ast.types);
935
+ case "Arrays":
936
+ return all([...ast.elements, ...ast.rest]);
937
+ case "Objects":
938
+ return all([
939
+ ...ast.propertySignatures.map((property) => property.type),
940
+ ...ast.indexSignatures.flatMap((signature) => [signature.parameter, signature.type]),
941
+ ]);
942
+ default:
943
+ return true;
944
+ }
945
+ };
946
+ export const lackDecision = (field) => {
947
+ if (mayReadMissingKey(field.ast))
948
+ return "decode";
949
+ if (SchemaAST.isOptional(field.ast))
950
+ return "allow";
951
+ if (absentStored(field) === undefined)
952
+ return "refuse";
953
+ return runsNoCode(field.ast) ? "allow" : "decode";
954
+ };
955
+ /**
956
+ * Whether a row without this field's key reads, by reading one: a decoding default, an
957
+ * absent-key step or a middleware runs, and the field's checks see what that makes. Asked
958
+ * by a write that leaves the key out of a row, once, and never while an entity is defined.
959
+ * A default that can't run synchronously is taken at its word.
960
+ */
961
+ const readsMissingKey = (field) => {
962
+ const probe = Schema.Struct({ field });
963
+ return !Exit.hasFails(Schema.decodeUnknownExit(probe)({}));
964
+ };
965
+ /**
966
+ * Whether the field's key is one a stored row may leave out: optional fields
967
+ * (`Schema.optional`, `Schema.optionalKey`, the `OptionFromOptional` family) and
968
+ * a decoding default, whose value a read fills in.
969
+ *
970
+ * The schema answers where nothing it runs takes part: the missing key reaches the read
971
+ * side as missing, so the read side's key says. Where the model's code may take part in
972
+ * reading the missing key ({@link mayReadMissingKey}), the key is read for real, so this
973
+ * belongs to a write and is never asked while an entity is defined.
974
+ */
975
+ export const rowOmits = (field) => mayReadMissingKey(field.ast) ? readsMissingKey(field) : SchemaAST.isOptional(field.ast);
976
+ /**
977
+ * Whether what's stored for this can leave out a value that reads back all the same: a struct's
978
+ * field ({@link absentStored}), or the set an `Option` holds as its value. An `undefined` there
979
+ * reads as what it is without anything being done about it.
980
+ */
981
+ export const holdsAbsentValue = (ast, seen = new Set()) => {
982
+ const found = forced(ast, seen);
983
+ if (found === undefined)
984
+ return false;
985
+ const { node } = found;
986
+ const reading = (part) => absentStored(Schema.make(part));
987
+ const within = (asts) => asts.some((part) => holdsAbsentValue(part, found.seen));
988
+ switch (node._tag) {
989
+ case "Declaration":
990
+ return (node.typeParameters.some((part) => reading(part)?.stored !== undefined) ||
991
+ within(node.typeParameters));
992
+ case "Union":
993
+ return within(node.types);
994
+ case "Arrays":
995
+ return within([...node.elements, ...node.rest]);
996
+ case "Objects": {
997
+ const fields = node.propertySignatures.map((property) => property.type);
998
+ return (fields.some((part) => reading(part) !== undefined) ||
999
+ within([...fields, ...node.indexSignatures.map((signature) => signature.type)]));
1000
+ }
1001
+ default:
1002
+ return false;
1003
+ }
1004
+ };
1005
+ /**
1006
+ * Whether a stored row can be without this field and still be read: its key may
1007
+ * be left out ({@link rowOmits}), or an absent attribute is one of its values
1008
+ * ({@link absentReading}). A required field cannot, nor can a `NullOr`, whose key
1009
+ * is required even though its value may be empty.
1010
+ *
1011
+ * Reads the absence where the model's code takes part in it ({@link lackDecision}), so
1012
+ * this belongs to a write and is never asked while an entity is defined.
1013
+ */
1014
+ export const rowCanLack = (field) => rowOmits(field) || absentReading(field) !== undefined;
1015
+ const SCALARS = new Set([
1016
+ "Null",
1017
+ "Undefined",
1018
+ "String",
1019
+ "Number",
1020
+ "Boolean",
1021
+ "BigInt",
1022
+ "Symbol",
1023
+ "Literal",
1024
+ "UniqueSymbol",
1025
+ "Enum",
1026
+ "TemplateLiteral",
1027
+ ]);
1028
+ /** Whether a node carries nothing of its own a read runs: no transformation, no check. */
1029
+ const bare = (ast) => ast.checks === undefined &&
1030
+ ast.encoding === undefined &&
1031
+ ast.encodingChecks === undefined;
1032
+ /** What the guard models a node as ({@link Modelled}), or `undefined` for one it doesn't. */
1033
+ const modelled = (ast) => {
1034
+ if (SchemaAST.isDeclaration(ast))
1035
+ return classStruct(ast);
1036
+ if (!bare(ast))
1037
+ return undefined;
1038
+ switch (ast._tag) {
1039
+ case "Objects": {
1040
+ if (ast.indexSignatures.length === 0) {
1041
+ return ast.propertySignatures.length > 0 ? { _tag: "Struct", ast } : undefined;
1042
+ }
1043
+ const [index, ...more] = ast.indexSignatures;
1044
+ return index !== undefined &&
1045
+ more.length === 0 &&
1046
+ ast.propertySignatures.length === 0 &&
1047
+ index.parameter._tag === "String" &&
1048
+ bare(index.parameter)
1049
+ ? { _tag: "Record", value: index.type }
1050
+ : undefined;
1051
+ }
1052
+ case "Arrays":
1053
+ return ast.rest.length <= 1 ? { _tag: "List", ast } : undefined;
1054
+ case "Union":
1055
+ return { _tag: "Union", members: ast.types };
1056
+ case "Suspend":
1057
+ return { _tag: "Suspend", suspended: ast.thunk() };
1058
+ default:
1059
+ return SCALARS.has(ast._tag) ? { _tag: "Scalar" } : undefined;
1060
+ }
1061
+ };
1062
+ /**
1063
+ * A `Schema.Class`, as its struct: a declaration read by reading a struct and making an instance
1064
+ * of what that gives, with one step that only maps the value, and no check of its own.
1065
+ */
1066
+ const classStruct = (ast) => {
1067
+ const [link, ...more] = ast.encoding ?? [];
1068
+ if (link === undefined || more.length > 0)
1069
+ return undefined;
1070
+ if (ast.checks !== undefined || ast.encodingChecks !== undefined)
1071
+ return undefined;
1072
+ const transformation = link.transformation;
1073
+ if (transformation._tag !== "Transformation" || transformation.decode?._tag !== "Transform") {
1074
+ return undefined;
1075
+ }
1076
+ const struct = modelled(link.to);
1077
+ return struct?._tag === "Struct" ? struct : undefined;
1078
+ };
1079
+ const endsOf = (ast, segments, ends, seen = new Set()) => {
1080
+ const node = seen.has(ast) ? undefined : modelled(ast);
1081
+ if (node === undefined) {
1082
+ ends.push({ _tag: "Unknown" });
1083
+ return;
1084
+ }
1085
+ if (node._tag === "Union" || node._tag === "Suspend") {
1086
+ const within = new Set(seen).add(ast);
1087
+ for (const member of node._tag === "Union" ? node.members : [node.suspended]) {
1088
+ endsOf(member, segments, ends, within);
1089
+ }
1090
+ return;
1091
+ }
1092
+ const [head, ...rest] = segments;
1093
+ if (head === undefined) {
1094
+ ends.push({ _tag: "At", node });
1095
+ return;
1096
+ }
1097
+ if (node._tag === "Struct" && typeof head === "string") {
1098
+ const property = node.ast.propertySignatures.find((signature) => signature.name === head);
1099
+ if (property === undefined)
1100
+ ends.push({ _tag: "Unread" });
1101
+ else
1102
+ endsOf(property.type, rest, ends);
1103
+ }
1104
+ else if (node._tag === "Record" && typeof head === "string") {
1105
+ endsOf(node.value, rest, ends);
1106
+ }
1107
+ else if (node._tag === "List" && typeof head === "number") {
1108
+ const element = node.ast.elements[head] ?? node.ast.rest[0];
1109
+ if (element !== undefined)
1110
+ endsOf(element, rest, ends);
1111
+ }
1112
+ };
1113
+ /**
1114
+ * Removing a property `name` from the maps at `ends`. A struct requires it when a row can't be
1115
+ * without it ({@link rowCanLack}, asked of the property as of a field). A record never does, and
1116
+ * a struct without it holds no such value, so removing it leaves the value as it was. Lists and
1117
+ * scalars hold no property, so a value of theirs that held one isn't one this reads.
1118
+ */
1119
+ const propertyRemoval = (ends, name) => {
1120
+ if (ends.some((end) => end._tag === "Unknown"))
1121
+ return "unknown";
1122
+ let held = false;
1123
+ for (const end of ends) {
1124
+ if (end._tag === "Unread")
1125
+ return "readable";
1126
+ if (end._tag !== "At")
1127
+ continue;
1128
+ const { node } = end;
1129
+ if (node._tag === "Record")
1130
+ return "readable";
1131
+ if (node._tag !== "Struct")
1132
+ continue;
1133
+ const property = node.ast.propertySignatures.find((signature) => signature.name === name);
1134
+ if (property === undefined || rowCanLack(Schema.make(property.type))) {
1135
+ return "readable";
1136
+ }
1137
+ held = true;
1138
+ }
1139
+ return held ? "required" : "unheld";
1140
+ };
1141
+ /**
1142
+ * Removing list position `position` from the lists at `ends`. A list closes up when an element
1143
+ * is removed, so what's left is one shorter, and is judged by length alone: a list accepts from
1144
+ * its required positions to all of them, or with a rest any length from its required positions
1145
+ * on. Readable when some list may be too short to hold the position (DynamoDB leaves it as it
1146
+ * was), or one shorter than a length some list accepts is a length some list accepts. An element
1147
+ * that can fill a missing one ({@link mayReadMissingKey}) makes the lengths unknown. Structs,
1148
+ * records and scalars hold no list, so a value of theirs that held one isn't one this reads.
1149
+ */
1150
+ const positionRemoval = (ends, position) => {
1151
+ if (ends.some((end) => end._tag === "Unknown"))
1152
+ return "unknown";
1153
+ if (ends.some((end) => end._tag === "Unread"))
1154
+ return "readable";
1155
+ const lengths = [];
1156
+ for (const end of ends) {
1157
+ if (end._tag !== "At" || end.node._tag !== "List")
1158
+ continue;
1159
+ const { elements, rest } = end.node.ast;
1160
+ if (elements.some((element) => mayReadMissingKey(element)))
1161
+ return "unknown";
1162
+ lengths.push({
1163
+ min: elements.filter((element) => !SchemaAST.isOptional(element)).length,
1164
+ max: rest.length > 0 ? Number.POSITIVE_INFINITY : elements.length,
1165
+ });
1166
+ }
1167
+ if (lengths.length === 0)
1168
+ return "unheld";
1169
+ if (lengths.some((list) => list.min <= position))
1170
+ return "readable";
1171
+ const shorter = (list) => lengths.some((other) => other.min <= list.max - 1 && list.min - 1 <= other.max);
1172
+ return lengths.some(shorter) ? "readable" : "required";
1173
+ };
1174
+ /**
1175
+ * Whether removing `segments`, a path inside this field, leaves a value the field's schema
1176
+ * refuses, for every value it reads that holds the path, while none that holds what's above it
1177
+ * is without it. Refused only when the walk from the field passes through nodes it models exactly
1178
+ * as a read decodes them ({@link Modelled}); `false` for anything else, and the removal is sent
1179
+ * as 1.39.0 sent it.
1180
+ *
1181
+ * The walk takes every way through the schema to the path, through unions at every level, so a
1182
+ * value one member holds is judged against every member: a struct member without a property on
1183
+ * the way doesn't read what a value holds under it, so it may read what's left, and the removal
1184
+ * is sent. A property is required when a row can't be without it ({@link rowCanLack}): a required
1185
+ * key nothing fills, whose absent attribute isn't one of its values. A list position is judged by
1186
+ * length alone ({@link positionRemoval}): removing any position of a `[string, string]` is
1187
+ * required; `f[0]` of a `[string, string?]`, either position of
1188
+ * `Union([[string, string], [string]])` and an array's element aren't. Length alone can't see
1189
+ * that what's left puts a value where its position can't hold it (`f[0]` of a
1190
+ * `[string, number?]`), or is a list only a member a tag rules out accepts, so those aren't
1191
+ * either, as 1.39.0 sent them.
1192
+ *
1193
+ * `false` means the schema can't say every such row breaks: a record's keys, a list's elements,
1194
+ * a path no value holds (DynamoDB refuses it, as on 1.39.0), and anything the walk doesn't model.
1195
+ */
1196
+ export const pathIsRequired = (field, segments) => {
1197
+ const last = segments[segments.length - 1];
1198
+ if (last === undefined)
1199
+ return false;
1200
+ const ends = [];
1201
+ endsOf(field.ast, segments.slice(0, -1), ends);
1202
+ const removal = typeof last === "number" ? positionRemoval(ends, last) : propertyRemoval(ends, last);
1203
+ return removal === "required";
1204
+ };
212
1205
  //# sourceMappingURL=SchemaAccessors.js.map