viell-effect-schema-http 0.3.0 → 0.4.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.
@@ -82,11 +82,14 @@ export type QueryFields = Readonly<
82
82
  * encoded again, with no error. A mix is one level deep in the type. Renamed fields take their
83
83
  * encoded names only when the whole value is on the encoded side, and a value on that side stays
84
84
  * there, even if it would fit the decoded side by losing them.
85
+ * When both names of a renamed field are supplied, the decoded name still wins; give one name.
85
86
  *
86
87
  * Under a union, a member that keeps every field wins over an earlier one that would strip one, on
87
88
  * both sides and at any depth. A field no member can keep beside the others is a `SchemaError` that
88
89
  * names it, because the types allow that value and any member would lose a field the schema states.
89
90
  * A key no member states is stripped, as a struct strips it, and so is a key the tag has ruled out.
91
+ * A required literal tag can choose by its decoded or encoded name. Both views must rule a member
92
+ * out before its fields go; a constructor default is not guessed to make that choice.
90
93
  * A key set to `undefined` is no field, and an accessor on a class is one, as it is to a struct. In a
91
94
  * header or query group, a field a schema stacked with the union takes is not lost. Inside text given
92
95
  * as text, a `Schema.Map`, a `Schema.Option` or a declaration with no struct behind it, the schema's
@@ -95,7 +98,7 @@ export type QueryFields = Readonly<
95
98
  export type Input<S extends Schema.Top> = Inputs.Input<S>;
96
99
 
97
100
  /**
98
- * The whole input of a request: the object its call takes, with every binding's property.
101
+ * The whole input of a request: the object its call takes, assembled from its bindings.
99
102
  *
100
103
  * @example
101
104
  * ```ts
@@ -120,7 +123,9 @@ export type Input<S extends Schema.Top> = Inputs.Input<S>;
120
123
  * @remarks
121
124
  * This takes a request, and {@link Input} takes a schema. `Input` is what one binding takes, such
122
125
  * as the value under `query`, and this is the object that holds them all, which is what
123
- * {@link mapInput} has to return. `Operation.InputOf` gives the same for an operation.
126
+ * {@link mapInput} has to return. A query or header key is optional when that binding's `Input`
127
+ * accepts `{}`; stacked bindings intersect their contributions. `Operation.InputOf` gives the
128
+ * same for an operation.
124
129
  */
125
130
  export type InputOf<R> =
126
131
  R extends Request<infer I, unknown, unknown> ? I : never;
@@ -226,6 +231,8 @@ export interface Draft {
226
231
  readonly takenQuery: Taken | undefined;
227
232
  /** The same for the header group, as in {@link takenQuery}. */
228
233
  readonly takenHeaders: Taken | undefined;
234
+ /** Raw names edited after each binding, recorded before that binding prepares its input. */
235
+ readonly editedFields: ReadonlyMap<Shape, ReadonlySet<string>>;
229
236
  }
230
237
 
231
238
  /**
@@ -447,6 +454,32 @@ const foldQuery: Fields.Fold = (name) => name;
447
454
  /** A raw edit: a request's fields change, and its input, errors and services stay. */
448
455
  type Edit = <I, E, R>(self: Request<I, E, R>) => Request<I, E, R>;
449
456
 
457
+ /** Copy provenance for this evaluation; a binding snapshots it before earlier steps run. */
458
+ const editing = (
459
+ draft: Draft,
460
+ shapes: ReadonlyArray<Shape>,
461
+ names: ReadonlyArray<string>,
462
+ fold: Fields.Fold,
463
+ ): Draft =>
464
+ shapes.length === 0
465
+ ? draft
466
+ : {
467
+ ...draft,
468
+ editedFields: new Map([
469
+ ...draft.editedFields,
470
+ ...shapes.map(
471
+ (shape) =>
472
+ [
473
+ shape,
474
+ new Set([
475
+ ...(draft.editedFields.get(shape) ?? []),
476
+ ...names.map(fold),
477
+ ]),
478
+ ] as const,
479
+ ),
480
+ ]),
481
+ };
482
+
450
483
  const editHeaders =
451
484
  (
452
485
  edited: ReadonlyArray<string>,
@@ -469,7 +502,11 @@ const editHeaders =
469
502
  ).map((name) => ["headers", name] as const),
470
503
  ],
471
504
  },
472
- self.prepare,
505
+ (input, draft) =>
506
+ self.prepare(
507
+ input,
508
+ editing(draft, self.declaration.headerShapes, edited, foldHeader),
509
+ ),
473
510
  );
474
511
 
475
512
  const editQuery =
@@ -493,7 +530,11 @@ const editQuery =
493
530
  ).map((name) => ["query", name] as const),
494
531
  ],
495
532
  },
496
- self.prepare,
533
+ (input, draft) =>
534
+ self.prepare(
535
+ input,
536
+ editing(draft, self.declaration.queryShapes, names, foldQuery),
537
+ ),
497
538
  );
498
539
 
499
540
  /**
@@ -516,6 +557,8 @@ const editQuery =
516
557
  * With a {@link headers} schema bound, in either order, the name has to be one a schema allows, and
517
558
  * the value is a default that goes through the schema. Setting a name the schema always writes,
518
559
  * after that schema, is an {@link InvalidRequest}, because the value could never reach the client.
560
+ * A direct struct's constructor-filled optional field is also refused when this preparation
561
+ * supplies and encodes it after the caller leaves it out, as {@link headers} describes.
519
562
  *
520
563
  * In the object form each key replaces its name as above, in key order, and other names stay. A key
521
564
  * set to `undefined` removes that name's declarations and stops no automatic value, which is what
@@ -563,6 +606,8 @@ export const appendHeader = (name: string, value: FieldValue) =>
563
606
  * Names compare without case. Value functions are never evaluated to compare with `value`. Removing
564
607
  * a name a {@link headers} schema always writes, after that schema, is an {@link InvalidRequest},
565
608
  * because the schema puts the value back. Removing an optional field clears its default.
609
+ * A constructor-filled optional field can also put it back and be refused, as {@link headers}
610
+ * describes.
566
611
  *
567
612
  * Without a value, this also stops the library's automatic value for that name: an operation's
568
613
  * `Accept`, or a body's `Content-Type` and `Content-Length`. It stops only that. A value that a
@@ -599,6 +644,8 @@ export const removeHeader = (name: string, value?: string) =>
599
644
  * With a {@link query} schema bound, in either order, the name has to be one a schema allows, and
600
645
  * the value is a default that goes through the schema. Setting a name the schema always writes,
601
646
  * after that schema, is an {@link InvalidRequest}, because the value could never reach the client.
647
+ * A direct struct's constructor-filled optional field is also refused when this preparation
648
+ * supplies and encodes it after the caller leaves it out, as {@link query} describes.
602
649
  *
603
650
  * The object form takes {@link QueryFields}. Each key replaces its name as above, in key order, and
604
651
  * other names stay. Use {@link appendQuery} for exact order across repeated names.
@@ -646,6 +693,8 @@ export const appendQuery = (name: string, value: FieldValue<string | null>) =>
646
693
  * functions are not evaluated for comparison. Removing a name a {@link query} schema always writes,
647
694
  * after that schema, is an {@link InvalidRequest}, because the schema puts the value back. Removing
648
695
  * an optional field clears its default.
696
+ * A constructor-filled optional field can also put it back and be refused, as {@link query}
697
+ * describes.
649
698
  */
650
699
  export const removeQuery = (name: string, value?: string | null) =>
651
700
  editQuery([name], (fields) => Fields.remove(fields, name, value));
@@ -723,6 +772,12 @@ const lostFields = (
723
772
  message: `The ${group} group cannot be built against its schema: with the rest of the group, these fields would be lost: ${listNames(names)}.`,
724
773
  });
725
774
 
775
+ /** Names only: the caller's omitted fields were actually supplied and written by construction. */
776
+ const constructorConflict = (group: string, names: ReadonlyArray<string>) =>
777
+ new InvalidRequest({
778
+ message: `A constructor supplied these omitted ${group} fields and their schema wrote them, so a later raw edit would be lost: ${listNames(names)}. Supply the value as input, set it with Request.mapInput, or use Request.unbind("${group}") first.`,
779
+ });
780
+
726
781
  /** Fields a body's encoder supplies unless the request says otherwise. */
727
782
  const bodyFields = ["content-type", "content-length"] as const;
728
783
 
@@ -746,10 +801,29 @@ const applyDeclaredBodyFields = (
746
801
  );
747
802
  };
748
803
 
804
+ /** A query or header binding needs its key only when its input cannot be an empty object. */
805
+ type GroupInput<K extends "query" | "headers", A> =
806
+ Record<never, never> extends A
807
+ ? { readonly [P in K]?: A }
808
+ : { readonly [P in K]: A };
809
+
749
810
  /**
750
811
  * Bind a schema to the call's `{ headers }` input.
751
812
  *
752
813
  * @remarks
814
+ * When {@link Input} accepts `{}`, the `headers` key is optional, as with an all-optional struct
815
+ * or a union with one such member. An absent or `undefined` group is read as `{}` and still goes
816
+ * through the schema, including its refinements and constructor defaults. Other explicit values,
817
+ * including `null`, are validated as given. With exact optional property types, an explicit
818
+ * `undefined` still has to fit `Input`. Stacked schemas allow omission only when each one does;
819
+ * a raw default does not make a required group optional. The invocation object is still required.
820
+ *
821
+ * In a direct struct, a constructor default can supply an omitted optional field. A raw edit
822
+ * after that binding is an {@link InvalidRequest} when this preparation successfully constructs
823
+ * the group and encodes a non-`undefined` value for that field. This reads the preparation's result;
824
+ * it never reruns a default. Construction proof is unavailable after decoder fallback, for group
825
+ * transformations, classes or unions, or for an accessor or inherited input property.
826
+ *
753
827
  * The input is an {@link Input} of the schema. Encoding produces ordered header lines. The schema
754
828
  * states the shape of the group, whatever the order of the calls: once any schema is bound, every
755
829
  * header the request declares must be a name some schema allows. A raw header under such a name
@@ -781,11 +855,14 @@ export const headers = <
781
855
  contract: S,
782
856
  ) => {
783
857
  const read = Inputs.reader(contract, Schema.encodeEffect(contract));
784
- const { shape, settle, taken } = Shapes.bind(contract, foldHeader);
858
+ const { shape, settle, taken, candidates, filled } = Shapes.bind(
859
+ contract,
860
+ foldHeader,
861
+ );
785
862
  return <I, E, R>(
786
863
  self: Request<I, E, R>,
787
864
  ): Request<
788
- I & { readonly headers: Input<S> },
865
+ I & GroupInput<"headers", Input<S>>,
789
866
  E | Schema.SchemaError | InvalidRequest,
790
867
  R | S["EncodingServices"] | S["DecodingServices"]
791
868
  > =>
@@ -795,14 +872,18 @@ export const headers = <
795
872
  headerShapes: [...self.declaration.headerShapes, shape],
796
873
  },
797
874
  Effect.fnUntraced(function* (
798
- input: I & { readonly headers: Input<S> },
875
+ input: I & GroupInput<"headers", Input<S>>,
799
876
  draft: Draft,
800
877
  ) {
801
878
  if (draft.unbound.has("headers"))
802
879
  return yield* self.prepare(input, draft);
803
- const { output, lost: lostFromInput } = yield* read(input.headers);
804
- const own =
805
- draft.takenHeaders && taken(input.headers, output, lostFromInput);
880
+ const value = (
881
+ input.headers === undefined ? {} : input.headers
882
+ ) as Input<S>;
883
+ const edited = candidates(value, draft.editedFields.get(shape));
884
+ const { output, lost: lostFromInput, constructed } = yield* read(value);
885
+ const conflicts = filled(edited, constructed, output);
886
+ const own = draft.takenHeaders && taken(value, output, lostFromInput);
806
887
  const prepared = yield* self.prepare(
807
888
  input,
808
889
  own === undefined
@@ -818,6 +899,8 @@ export const headers = <
818
899
  lostFromInput,
819
900
  prepared.takenHeaders?.fields,
820
901
  );
902
+ if (conflicts.length > 0)
903
+ return yield* constructorConflict("headers", conflicts);
821
904
  const names = Shapes.written(output, foldHeader);
822
905
  const elsewhere = Shapes.others(
823
906
  shape,
@@ -880,6 +963,19 @@ export const headers = <
880
963
  * ```
881
964
  *
882
965
  * @remarks
966
+ * When {@link Input} accepts `{}`, the `query` key is optional, as with an all-optional struct
967
+ * or a union with one such member. An absent or `undefined` group is read as `{}` and still goes
968
+ * through the schema, including its refinements and constructor defaults. Other explicit values,
969
+ * including `null`, are validated as given. With exact optional property types, an explicit
970
+ * `undefined` still has to fit `Input`. Stacked schemas allow omission only when each one does;
971
+ * a raw default does not make a required group optional. The invocation object is still required.
972
+ *
973
+ * In a direct struct, a constructor default can supply an omitted optional field. A raw edit
974
+ * after that binding is an {@link InvalidRequest} when this preparation successfully constructs
975
+ * the group and encodes a non-`undefined` value for that field. This reads the preparation's result;
976
+ * it never reruns a default. Construction proof is unavailable after decoder fallback, for group
977
+ * transformations, classes or unions, or for an accessor or inherited input property.
978
+ *
883
979
  * The input is an {@link Input} of the schema. The schema encodes to `UrlEncoding.QueryInput` and
884
980
  * states the shape of the group, whatever the order of the calls: once any schema is bound, every
885
981
  * query field the request declares must be a name some schema allows. A raw entry under such a
@@ -910,11 +1006,14 @@ export const query = <
910
1006
  contract: S,
911
1007
  ) => {
912
1008
  const read = Inputs.reader(contract, Schema.encodeEffect(contract));
913
- const { shape, settle, taken } = Shapes.bind(contract, foldQuery);
1009
+ const { shape, settle, taken, candidates, filled } = Shapes.bind(
1010
+ contract,
1011
+ foldQuery,
1012
+ );
914
1013
  return <I, E, R>(
915
1014
  self: Request<I, E, R>,
916
1015
  ): Request<
917
- I & { readonly query: Input<S> },
1016
+ I & GroupInput<"query", Input<S>>,
918
1017
  E | Schema.SchemaError | InvalidRequest,
919
1018
  R | S["EncodingServices"] | S["DecodingServices"]
920
1019
  > =>
@@ -924,14 +1023,18 @@ export const query = <
924
1023
  queryShapes: [...self.declaration.queryShapes, shape],
925
1024
  },
926
1025
  Effect.fnUntraced(function* (
927
- input: I & { readonly query: Input<S> },
1026
+ input: I & GroupInput<"query", Input<S>>,
928
1027
  draft: Draft,
929
1028
  ) {
930
1029
  if (draft.unbound.has("query"))
931
1030
  return yield* self.prepare(input, draft);
932
- const { output, lost: lostFromInput } = yield* read(input.query);
933
- const own =
934
- draft.takenQuery && taken(input.query, output, lostFromInput);
1031
+ const value = (
1032
+ input.query === undefined ? {} : input.query
1033
+ ) as Input<S>;
1034
+ const edited = candidates(value, draft.editedFields.get(shape));
1035
+ const { output, lost: lostFromInput, constructed } = yield* read(value);
1036
+ const conflicts = filled(edited, constructed, output);
1037
+ const own = draft.takenQuery && taken(value, output, lostFromInput);
935
1038
  const prepared = yield* self.prepare(
936
1039
  input,
937
1040
  own === undefined
@@ -947,6 +1050,8 @@ export const query = <
947
1050
  lostFromInput,
948
1051
  prepared.takenQuery?.fields,
949
1052
  );
1053
+ if (conflicts.length > 0)
1054
+ return yield* constructorConflict("query", conflicts);
950
1055
  const names = Shapes.written(output, foldQuery);
951
1056
  const elsewhere = Shapes.others(shape, prepared.takenQuery, foldQuery);
952
1057
  const defaults = prepared.request.urlParams.params
@@ -1452,6 +1557,7 @@ const initialDraft = (declaration: Declaration): Draft => {
1452
1557
  unbound: new Set(),
1453
1558
  takenQuery: takenRecord(declaration.queryShapes),
1454
1559
  takenHeaders: takenRecord(declaration.headerShapes),
1560
+ editedFields: new Map(),
1455
1561
  },
1456
1562
  declaration.query.flatMap((field) =>
1457
1563
  Fields.resolve([field]).map(
@@ -115,15 +115,52 @@ const refusesLiteral = (type: Ast, value: unknown): boolean =>
115
115
  refuses(side, value),
116
116
  );
117
117
 
118
- /** Whether a member's tag rules it out for a value, as Effect's union does before it reads one. */
119
- const ruledOut = (member: Ast, value: unknown): boolean =>
120
- isObject(value) &&
121
- fieldsOf(member).some(
118
+ const onlyLiterals = (ast: Ast): boolean =>
119
+ ast._tag === "Literal" ||
120
+ (ast._tag === "Union" &&
121
+ ast.types.every(
122
+ (member) => member.encoding === undefined && onlyLiterals(member),
123
+ ));
124
+
125
+ /** Each side of an object transformation, without guessing which names correspond. */
126
+ const objectSides = (ast: Ast): ReadonlyArray<Ast> => [
127
+ ast,
128
+ ...(ast.encoding ?? []).flatMap(({ to }) => objectSides(to)),
129
+ ];
130
+
131
+ /** Whether this view's literal tags make it impossible, without reading a default. */
132
+ const tagView = (
133
+ side: Ast,
134
+ value: Record<PropertyKey, unknown>,
135
+ constructing: boolean,
136
+ ) => {
137
+ const tags = fieldsOf(side).filter(
138
+ ({ type }) =>
139
+ !SchemaAST.isOptional(type) && objectSides(type).every(onlyLiterals),
140
+ );
141
+ const mismatch = tags.some(
142
+ ({ name, type }) =>
143
+ value[name] !== undefined && refusesLiteral(type, value[name]),
144
+ );
145
+ const absent = tags.some(
122
146
  ({ name, type }) =>
123
- !SchemaAST.isOptional(type) &&
124
- value[name] !== undefined &&
125
- refusesLiteral(type, value[name]),
147
+ value[name] === undefined &&
148
+ (!constructing || type.context?.constructorDefault === undefined),
126
149
  );
150
+ return { impossible: mismatch || absent, mismatch };
151
+ };
152
+
153
+ /** A tag can choose on either side; both views must rule a member out before its fields go. */
154
+ const ruledOut = (member: Ast, value: unknown): boolean => {
155
+ if (!isObject(value)) return false;
156
+ const decoded = tagView(member, value, true);
157
+ const encoded = tagView(SchemaAST.toEncoded(member), value, false);
158
+ return (
159
+ decoded.impossible &&
160
+ encoded.impossible &&
161
+ (decoded.mismatch || encoded.mismatch)
162
+ );
163
+ };
127
164
 
128
165
  /** The schemas a value can be read against here: each member its tag leaves, on each side. */
129
166
  const sidesOf = (ast: Ast, value: unknown): ReadonlyArray<Ast> => [
@@ -60,7 +60,7 @@ export type Input<S extends Schema.Top> = EitherSide<
60
60
  * neither fails with the decoded side's error, so existing failures read the same. `options` go to
61
61
  * every parse.
62
62
  */
63
- export const toDecoded = <S extends Schema.Top>(
63
+ const toDecodedWithEvidence = <S extends Schema.Top>(
64
64
  contract: S,
65
65
  options?: SchemaAST.ParseOptions,
66
66
  ) => {
@@ -88,17 +88,45 @@ export const toDecoded = <S extends Schema.Top>(
88
88
  : byField(input);
89
89
  return (
90
90
  input: Input<S>,
91
- ): Effect.Effect<S["Type"], Schema.SchemaError, S["DecodingServices"]> =>
92
- Effect.catch(make(input), (failure) =>
93
- Effect.mapError(
94
- Effect.catch(decode(input, options), (encodedFailure) =>
95
- typeof input === "object" && input !== null
96
- ? byMember(input)
97
- : Effect.fail(encodedFailure),
91
+ ): Effect.Effect<
92
+ Decoded<S["Type"]>,
93
+ Schema.SchemaError,
94
+ S["DecodingServices"]
95
+ > =>
96
+ Effect.catch(
97
+ Effect.map(make(input), (value) => ({ value, constructed: true })),
98
+ (failure) =>
99
+ Effect.mapError(
100
+ Effect.map(
101
+ Effect.catch(decode(input, options), (encodedFailure) =>
102
+ typeof input === "object" && input !== null
103
+ ? byMember(input)
104
+ : Effect.fail(encodedFailure),
105
+ ),
106
+ (value) => ({ value, constructed: false }),
107
+ ),
108
+ () => failure,
98
109
  ),
99
- () => failure,
100
- ),
101
- ) as Effect.Effect<S["Type"], Schema.SchemaError, S["DecodingServices"]>;
110
+ ) as Effect.Effect<
111
+ Decoded<S["Type"]>,
112
+ Schema.SchemaError,
113
+ S["DecodingServices"]
114
+ >;
115
+ };
116
+
117
+ /** Only the first successful constructor route proves how a group acquired an omitted field. */
118
+ interface Decoded<A> {
119
+ readonly value: A;
120
+ readonly constructed: boolean;
121
+ }
122
+
123
+ /** Bring either side to the decoded side, without exposing how it was read. */
124
+ export const toDecoded = <S extends Schema.Top>(
125
+ contract: S,
126
+ options?: SchemaAST.ParseOptions,
127
+ ) => {
128
+ const read = toDecodedWithEvidence(contract, options);
129
+ return (input: Input<S>) => Effect.map(read(input), ({ value }) => value);
102
130
  };
103
131
 
104
132
  /** Read a field or union member, which may be on either side of its own schema. */
@@ -113,6 +141,8 @@ const fromPart = (
113
141
  export interface Written<A> {
114
142
  readonly output: A;
115
143
  readonly lost: ReadonlyArray<Excess.Path>;
144
+ /** Own data fields from the successful first direct-struct construction, before encoding. */
145
+ readonly constructed: unknown;
116
146
  }
117
147
 
118
148
  /** Takes a decoded value out through a schema, as the options say. */
@@ -147,30 +177,61 @@ const stripping = <S extends Schema.Top, A, R>(
147
177
  * what went in, so what is lost is what actually went, not what a failure suggests would. The write
148
178
  * is strict first, because a loose write can choose another member and lose what the read kept.
149
179
  *
150
- * A schema with neither choice skips all of this, so a plain struct costs what it always did.
180
+ * A schema with neither choice skips the strict read and loss comparison.
151
181
  */
152
182
  export const reader = <S extends Schema.Top, A, R>(
153
183
  contract: S,
154
184
  write: Write<S, A, R>,
155
185
  ) => {
156
- const stripped = stripping(contract, write);
157
- const keepsAll = (output: A): Written<A> => ({ output, lost: [] });
186
+ const decoded = toDecodedWithEvidence(contract);
187
+ const constructorFields =
188
+ contract.ast._tag === "Objects" && contract.ast.encoding === undefined
189
+ ? contract.ast.propertySignatures.filter(
190
+ ({ type }) => type.context?.constructorDefault !== undefined,
191
+ )
192
+ : [];
193
+ const construction = ({ value, constructed }: Decoded<S["Type"]>): unknown =>
194
+ constructed &&
195
+ constructorFields.length > 0 &&
196
+ typeof value === "object" &&
197
+ value !== null
198
+ ? Object.fromEntries(
199
+ constructorFields.flatMap(({ name }) => {
200
+ const property = Object.getOwnPropertyDescriptor(value, name);
201
+ return property !== undefined && "value" in property
202
+ ? [[name, property.value]]
203
+ : [];
204
+ }),
205
+ )
206
+ : undefined;
207
+ const written = (
208
+ reading: ReturnType<typeof decoded>,
209
+ options?: SchemaAST.ParseOptions,
210
+ ) =>
211
+ Effect.flatMap(reading, (read) => {
212
+ const constructed = construction(read);
213
+ return Effect.map(write(read.value, options), (output): Written<A> => ({
214
+ output,
215
+ lost: [],
216
+ constructed,
217
+ }));
218
+ });
158
219
  if (!Excess.choosing(contract.ast))
159
- return (input: Input<S>) => Effect.map(stripped(input), keepsAll);
160
- const decoded = toDecoded(contract);
161
- const exact = toDecoded(contract, Excess.strict);
162
- const kept = (input: Input<S>) =>
163
- Effect.flatMap(exact(input), (value) => write(value, Excess.strict));
220
+ return (input: Input<S>) => written(decoded(input));
221
+ const exact = toDecodedWithEvidence(contract, Excess.strict);
222
+ const kept = (input: Input<S>) => written(exact(input), Excess.strict);
164
223
  const compared = (input: Input<S>, given: unknown) =>
165
- Effect.flatMap(decoded(input), (value) =>
166
- Effect.map(
167
- Effect.catch(write(value, Excess.strict), () => write(value)),
224
+ Effect.flatMap(decoded(input), (read) => {
225
+ const constructed = construction(read);
226
+ return Effect.map(
227
+ Effect.catch(write(read.value, Excess.strict), () => write(read.value)),
168
228
  (output): Written<A> => ({
169
229
  output,
170
- lost: Excess.missing([contract.ast], given, value, output),
230
+ lost: Excess.missing([contract.ast], given, read.value, output),
231
+ constructed,
171
232
  }),
172
- ),
173
- );
233
+ );
234
+ });
174
235
  return (
175
236
  input: Input<S>,
176
237
  ): Effect.Effect<
@@ -184,12 +245,9 @@ export const reader = <S extends Schema.Top, A, R>(
184
245
  given === input ? input : Excess.exposed([contract.ast], input)
185
246
  ) as Input<S>;
186
247
  return Effect.catch(
187
- Effect.map(
188
- given === input
189
- ? kept(input)
190
- : Effect.catch(kept(given as Input<S>), () => kept(seen)),
191
- keepsAll,
192
- ),
248
+ given === input
249
+ ? kept(input)
250
+ : Effect.catch(kept(given as Input<S>), () => kept(seen)),
193
251
  () => compared(input, given),
194
252
  );
195
253
  };
@@ -274,6 +274,14 @@ export const lost = (
274
274
  );
275
275
  };
276
276
 
277
+ /** Only stable absent/data properties prove the caller did not supply this field. */
278
+ const omitted = (input: object, name: string): boolean => {
279
+ const property = Object.getOwnPropertyDescriptor(input, name);
280
+ return property === undefined
281
+ ? !(name in input)
282
+ : "value" in property && property.value === undefined;
283
+ };
284
+
277
285
  /**
278
286
  * Read what a schema says about its group, and build what it sends.
279
287
  *
@@ -300,6 +308,54 @@ export const bind = <S extends Schema.Constraint>(contract: S, fold: Fold) => {
300
308
  required: new Set(Array.from(reading.required, fold)),
301
309
  chooses,
302
310
  };
311
+ // A group transformation or declaration can change names or construct in its own way.
312
+ const constructorNames =
313
+ contract.ast._tag === "Objects" && contract.ast.encoding === undefined
314
+ ? contract.ast.propertySignatures.flatMap(({ name, type }) =>
315
+ typeof name === "string" &&
316
+ type.context?.constructorDefault !== undefined
317
+ ? [name]
318
+ : [],
319
+ )
320
+ : [];
321
+ /** Snapshot caller omission before preparation can run a default or encoder. */
322
+ const candidates = (
323
+ input: unknown,
324
+ edits: ReadonlySet<string> | undefined,
325
+ ): ReadonlyArray<string> =>
326
+ edits !== undefined && typeof input === "object" && input !== null
327
+ ? constructorNames.filter(
328
+ (name) => edits.has(fold(name)) && omitted(input, name),
329
+ )
330
+ : [];
331
+ /** The successful first constructor actually supplied these edited, encoded fields. */
332
+ const filled = (
333
+ names: ReadonlyArray<string>,
334
+ constructed: unknown,
335
+ output: unknown,
336
+ ): ReadonlyArray<string> => {
337
+ if (
338
+ typeof constructed !== "object" ||
339
+ constructed === null ||
340
+ typeof output !== "object" ||
341
+ output === null
342
+ )
343
+ return [];
344
+ return names
345
+ .filter((name) => {
346
+ const made = Object.getOwnPropertyDescriptor(constructed, name);
347
+ const encoded = Object.getOwnPropertyDescriptor(output, name);
348
+ return (
349
+ made !== undefined &&
350
+ "value" in made &&
351
+ made.value !== undefined &&
352
+ encoded?.enumerable === true &&
353
+ "value" in encoded &&
354
+ encoded.value !== undefined
355
+ );
356
+ })
357
+ .map(fold);
358
+ };
303
359
  /**
304
360
  * The caller's fields this schema took: what it wrote, and any it states and the caller gave,
305
361
  * which may be written under another name or not at all. What it would lose is not among them.
@@ -355,5 +411,5 @@ export const bind = <S extends Schema.Constraint>(contract: S, fold: Fold) => {
355
411
  through(),
356
412
  );
357
413
  };
358
- return { shape, settle, taken };
414
+ return { shape, settle, taken, candidates, filled };
359
415
  };