viell-effect-schema-http 0.2.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.
Files changed (47) hide show
  1. package/README.md +8 -6
  2. package/dist/concurrency/Interaction.d.ts +7 -1
  3. package/dist/concurrency/Interaction.d.ts.map +1 -1
  4. package/dist/concurrency/Interaction.js.map +1 -1
  5. package/dist/http/Body.d.ts +2 -0
  6. package/dist/http/Body.d.ts.map +1 -1
  7. package/dist/http/Body.js.map +1 -1
  8. package/dist/http/Operation.d.ts +6 -0
  9. package/dist/http/Operation.d.ts.map +1 -1
  10. package/dist/http/Operation.js.map +1 -1
  11. package/dist/http/Policy.d.ts +25 -0
  12. package/dist/http/Policy.d.ts.map +1 -1
  13. package/dist/http/Policy.js +25 -0
  14. package/dist/http/Policy.js.map +1 -1
  15. package/dist/http/Request.d.ts +109 -23
  16. package/dist/http/Request.d.ts.map +1 -1
  17. package/dist/http/Request.js +121 -21
  18. package/dist/http/Request.js.map +1 -1
  19. package/dist/http/Response.d.ts +11 -1
  20. package/dist/http/Response.d.ts.map +1 -1
  21. package/dist/http/Response.js.map +1 -1
  22. package/dist/http/UrlEncoding.d.ts +2 -1
  23. package/dist/http/UrlEncoding.d.ts.map +1 -1
  24. package/dist/http/UrlEncoding.js.map +1 -1
  25. package/dist/http/internal/excess.d.ts +44 -0
  26. package/dist/http/internal/excess.d.ts.map +1 -0
  27. package/dist/http/internal/excess.js +252 -0
  28. package/dist/http/internal/excess.js.map +1 -0
  29. package/dist/http/internal/input.d.ts +33 -8
  30. package/dist/http/internal/input.d.ts.map +1 -1
  31. package/dist/http/internal/input.js +102 -20
  32. package/dist/http/internal/input.js.map +1 -1
  33. package/dist/http/internal/shape.d.ts +21 -0
  34. package/dist/http/internal/shape.d.ts.map +1 -1
  35. package/dist/http/internal/shape.js +96 -12
  36. package/dist/http/internal/shape.js.map +1 -1
  37. package/package.json +3 -2
  38. package/src/concurrency/Interaction.ts +7 -1
  39. package/src/http/Body.ts +2 -0
  40. package/src/http/Operation.ts +6 -0
  41. package/src/http/Policy.ts +27 -0
  42. package/src/http/Request.ts +236 -31
  43. package/src/http/Response.ts +11 -1
  44. package/src/http/UrlEncoding.ts +2 -1
  45. package/src/http/internal/excess.ts +370 -0
  46. package/src/http/internal/input.ts +200 -37
  47. package/src/http/internal/shape.ts +148 -12
@@ -59,6 +59,10 @@ const isTransientError = (error: unknown): boolean =>
59
59
  * The statuses are 408, 429, 500, 502, 503 and 504, matching Effect's transient classification.
60
60
  * A declared response with one of these statuses is eligible even when decoding succeeded.
61
61
  * This does not check the method or whether repeating a remote action is safe.
62
+ *
63
+ * It reads what the client reports, and clients differ. A body cut off after its headers is a
64
+ * decoding failure through `fetch`, which is not eligible, and a transport failure through a client
65
+ * that reads the whole response first, which is.
62
66
  */
63
67
  export const transient = (reason: Reason): boolean => {
64
68
  if (
@@ -107,9 +111,32 @@ export const make = <Out, E = never, R = never>(
107
111
 
108
112
  /**
109
113
  * One attempt, with no retry and no library-imposed timeout.
114
+ *
115
+ * @remarks
116
+ * This is one attempt by the library, not one send. A client can send a request again by itself, as
117
+ * Chromium does, a POST included, when a reused connection ends with no response.
110
118
  */
111
119
  export const none: Policy = make(Schedule.recurs(0));
112
120
 
121
+ /**
122
+ * One attempt with a timeout, and no retry.
123
+ *
124
+ * @example
125
+ * ```ts
126
+ * import { Policy } from "viell-effect-schema-http";
127
+ * const oneQuickAttempt = Policy.timeout("2 seconds");
128
+ * // One attempt, given up after two seconds.
129
+ * ```
130
+ *
131
+ * @remarks
132
+ * This is {@link none} with the `attemptTimeout` of {@link make}, so a timed-out attempt ends the
133
+ * operation. The timeout covers client execution and decoding. It excludes request preparation and
134
+ * result mapping, so a slow base URL Effect or `Operation.mapEffect` step is outside it. Apply
135
+ * `Effect.timeout` around the operation for a limit on all of that.
136
+ */
137
+ export const timeout = (duration: Duration.Input): Policy =>
138
+ make(Schedule.recurs(0), { attemptTimeout: duration });
139
+
113
140
  /**
114
141
  * Read the minimum retry delay requested by a response's `Retry-After` header.
115
142
  *
@@ -16,8 +16,9 @@ import * as UrlEncoding from "./UrlEncoding.js";
16
16
  * Request preparation failed before dispatch.
17
17
  *
18
18
  * @remarks
19
- * Covers computed-field failures, URL-rendering exceptions, and fields that do not fit the schemas
20
- * bound to their group. Schema failures of the caller's input remain separate `SchemaError` values.
19
+ * Covers computed-field failures, URL-rendering and {@link mapBaseUrl} exceptions, a path value
20
+ * that does not encode to one value, and fields that do not fit the schemas bound to their group.
21
+ * Schema failures of the caller's input remain separate `SchemaError` values.
21
22
  * A failed check of a group names its fields and leaves out their values, which may be credentials.
22
23
  */
23
24
  export class InvalidRequest extends Data.TaggedError("InvalidRequest")<{
@@ -79,12 +80,25 @@ export type QueryFields = Readonly<
79
80
  * A value that fits the decoded side is read as decoded. Under a schema whose two sides share a
80
81
  * type, such as one from text to text, an already encoded value fits the decoded side, so it is
81
82
  * encoded again, with no error. A mix is one level deep in the type. Renamed fields take their
82
- * encoded names only when the whole value is on the encoded side.
83
+ * encoded names only when the whole value is on the encoded side, and a value on that side stays
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.
86
+ *
87
+ * Under a union, a member that keeps every field wins over an earlier one that would strip one, on
88
+ * both sides and at any depth. A field no member can keep beside the others is a `SchemaError` that
89
+ * names it, because the types allow that value and any member would lose a field the schema states.
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.
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
94
+ * header or query group, a field a schema stacked with the union takes is not lost. Inside text given
95
+ * as text, a `Schema.Map`, a `Schema.Option` or a declaration with no struct behind it, the schema's
96
+ * own reading applies.
83
97
  */
84
98
  export type Input<S extends Schema.Top> = Inputs.Input<S>;
85
99
 
86
100
  /**
87
- * 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.
88
102
  *
89
103
  * @example
90
104
  * ```ts
@@ -109,7 +123,9 @@ export type Input<S extends Schema.Top> = Inputs.Input<S>;
109
123
  * @remarks
110
124
  * This takes a request, and {@link Input} takes a schema. `Input` is what one binding takes, such
111
125
  * as the value under `query`, and this is the object that holds them all, which is what
112
- * {@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.
113
129
  */
114
130
  export type InputOf<R> =
115
131
  R extends Request<infer I, unknown, unknown> ? I : never;
@@ -121,7 +137,9 @@ export type InputOf<R> =
121
137
  * This is a low-level extension type. Prefer {@link make} and the request combinators.
122
138
  */
123
139
  export interface Declaration {
140
+ /** The HTTP method, passed on as written. */
124
141
  readonly method: string;
142
+ /** The constructor's path or URL, without its query and fragment. */
125
143
  readonly url: string;
126
144
  /** The fragment written in the constructor, without its `#`. */
127
145
  readonly hash: string | undefined;
@@ -130,7 +148,9 @@ export interface Declaration {
130
148
  * and service types carry what that Effect needs. {@link mapBaseUrl} always leaves an Effect.
131
149
  */
132
150
  readonly baseUrl: string | Effect.Effect<string, unknown, unknown>;
151
+ /** The raw header declarations, in order. */
133
152
  readonly headers: Fields.Fields;
153
+ /** The raw query declarations, in order, including entries written in the constructor. */
134
154
  readonly query: Fields.Fields<string | null>;
135
155
  /** The constructor wrote a `?` with nothing after it, which holds no entries. */
136
156
  readonly emptyQuery: boolean;
@@ -148,14 +168,24 @@ export interface Declaration {
148
168
 
149
169
  /**
150
170
  * What one header or query schema says about its group: the names it allows, whether it allows
151
- * others, and the names it always writes.
171
+ * others, the names it always writes, and whether a union in it can lose a field.
152
172
  *
153
173
  * @remarks
154
- * This is a low-level extension type, read from the schema's encoded side when it is bound. Header
155
- * names are lowercase.
174
+ * This is a low-level extension type, read from the schema's encoded side and its fields' own
175
+ * encodings when it is bound. Header names are lowercase.
156
176
  */
157
177
  export type Shape = Shapes.Shape;
158
178
 
179
+ /**
180
+ * What the schemas stacked on a group have told each other during preparation.
181
+ *
182
+ * @remarks
183
+ * This is a low-level extension type. A field a union would lose is not lost if another schema in
184
+ * the group took it, and `settled` is never an answer to that: a schema can allow a name it did not
185
+ * take.
186
+ */
187
+ export type Taken = Shapes.Taken;
188
+
159
189
  /** A part of a request that a binding can supply, and that {@link unbind} can clear. */
160
190
  export type Group = "path" | "query" | "headers" | "body";
161
191
 
@@ -193,6 +223,16 @@ export interface Draft {
193
223
  readonly removedHeaders: ReadonlySet<string>;
194
224
  /** The groups a later {@link unbind} cleared, so their earlier bindings skip themselves. */
195
225
  readonly unbound: ReadonlySet<Group>;
226
+ /**
227
+ * What the schemas stacked on the query group took from the caller, and which raw values are
228
+ * theirs to settle. `undefined` where the group needs no record, because no stacked schema can lose
229
+ * a field.
230
+ */
231
+ readonly takenQuery: Taken | undefined;
232
+ /** The same for the header group, as in {@link takenQuery}. */
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>>;
196
236
  }
197
237
 
198
238
  /**
@@ -205,7 +245,9 @@ export interface Draft {
205
245
  */
206
246
  export interface Request<in I, out E = never, out R = never>
207
247
  extends Pipeable.Pipeable {
248
+ /** What preparation starts from. */
208
249
  readonly declaration: Declaration;
250
+ /** Apply the request's bindings and transforms to a draft, with the call's input. */
209
251
  readonly prepare: (input: I, draft: Draft) => Effect.Effect<Draft, E, R>;
210
252
  }
211
253
 
@@ -412,6 +454,32 @@ const foldQuery: Fields.Fold = (name) => name;
412
454
  /** A raw edit: a request's fields change, and its input, errors and services stay. */
413
455
  type Edit = <I, E, R>(self: Request<I, E, R>) => Request<I, E, R>;
414
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
+
415
483
  const editHeaders =
416
484
  (
417
485
  edited: ReadonlyArray<string>,
@@ -434,7 +502,11 @@ const editHeaders =
434
502
  ).map((name) => ["headers", name] as const),
435
503
  ],
436
504
  },
437
- self.prepare,
505
+ (input, draft) =>
506
+ self.prepare(
507
+ input,
508
+ editing(draft, self.declaration.headerShapes, edited, foldHeader),
509
+ ),
438
510
  );
439
511
 
440
512
  const editQuery =
@@ -458,7 +530,11 @@ const editQuery =
458
530
  ).map((name) => ["query", name] as const),
459
531
  ],
460
532
  },
461
- self.prepare,
533
+ (input, draft) =>
534
+ self.prepare(
535
+ input,
536
+ editing(draft, self.declaration.queryShapes, names, foldQuery),
537
+ ),
462
538
  );
463
539
 
464
540
  /**
@@ -481,6 +557,8 @@ const editQuery =
481
557
  * With a {@link headers} schema bound, in either order, the name has to be one a schema allows, and
482
558
  * the value is a default that goes through the schema. Setting a name the schema always writes,
483
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.
484
562
  *
485
563
  * In the object form each key replaces its name as above, in key order, and other names stay. A key
486
564
  * set to `undefined` removes that name's declarations and stops no automatic value, which is what
@@ -528,6 +606,8 @@ export const appendHeader = (name: string, value: FieldValue) =>
528
606
  * Names compare without case. Value functions are never evaluated to compare with `value`. Removing
529
607
  * a name a {@link headers} schema always writes, after that schema, is an {@link InvalidRequest},
530
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.
531
611
  *
532
612
  * Without a value, this also stops the library's automatic value for that name: an operation's
533
613
  * `Accept`, or a body's `Content-Type` and `Content-Length`. It stops only that. A value that a
@@ -564,6 +644,8 @@ export const removeHeader = (name: string, value?: string) =>
564
644
  * With a {@link query} schema bound, in either order, the name has to be one a schema allows, and
565
645
  * the value is a default that goes through the schema. Setting a name the schema always writes,
566
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.
567
649
  *
568
650
  * The object form takes {@link QueryFields}. Each key replaces its name as above, in key order, and
569
651
  * other names stay. Use {@link appendQuery} for exact order across repeated names.
@@ -611,6 +693,8 @@ export const appendQuery = (name: string, value: FieldValue<string | null>) =>
611
693
  * functions are not evaluated for comparison. Removing a name a {@link query} schema always writes,
612
694
  * after that schema, is an {@link InvalidRequest}, because the schema puts the value back. Removing
613
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.
614
698
  */
615
699
  export const removeQuery = (name: string, value?: string | null) =>
616
700
  editQuery([name], (fields) => Fields.remove(fields, name, value));
@@ -688,6 +772,12 @@ const lostFields = (
688
772
  message: `The ${group} group cannot be built against its schema: with the rest of the group, these fields would be lost: ${listNames(names)}.`,
689
773
  });
690
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
+
691
781
  /** Fields a body's encoder supplies unless the request says otherwise. */
692
782
  const bodyFields = ["content-type", "content-length"] as const;
693
783
 
@@ -711,10 +801,29 @@ const applyDeclaredBodyFields = (
711
801
  );
712
802
  };
713
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
+
714
810
  /**
715
811
  * Bind a schema to the call's `{ headers }` input.
716
812
  *
717
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
+ *
718
827
  * The input is an {@link Input} of the schema. Encoding produces ordered header lines. The schema
719
828
  * states the shape of the group, whatever the order of the calls: once any schema is bound, every
720
829
  * header the request declares must be a name some schema allows. A raw header under such a name
@@ -725,10 +834,12 @@ const applyDeclaredBodyFields = (
725
834
  * case.
726
835
  *
727
836
  * Under a union, the defaults and what the schema wrote have to fit one member together. A field
728
- * that would be lost otherwise is an {@link InvalidRequest}, which names that field.
837
+ * that would be lost otherwise is an {@link InvalidRequest}, which names that field. The caller's
838
+ * own value is read before that, as {@link Input} describes.
729
839
  *
730
- * Header schemas stack: a second one adds its fields, and together they state the shape. Use
731
- * {@link unbind} to start again.
840
+ * Header schemas stack: a second one adds its fields, and together they state the shape. A field
841
+ * one of them takes stays with it, whatever a union beside it leaves out. Use {@link unbind} to
842
+ * start again.
732
843
  *
733
844
  * A field the schema produces wins over an automatic `Accept`, `Content-Type` or `Content-Length`,
734
845
  * whether the schema is bound before or after the body, and so does a default. An optional field
@@ -743,12 +854,15 @@ export const headers = <
743
854
  >(
744
855
  contract: S,
745
856
  ) => {
746
- const encode = Inputs.encoder(contract, Schema.encodeEffect(contract));
747
- const { shape, settle } = Shapes.bind(contract, foldHeader);
857
+ const read = Inputs.reader(contract, Schema.encodeEffect(contract));
858
+ const { shape, settle, taken, candidates, filled } = Shapes.bind(
859
+ contract,
860
+ foldHeader,
861
+ );
748
862
  return <I, E, R>(
749
863
  self: Request<I, E, R>,
750
864
  ): Request<
751
- I & { readonly headers: Input<S> },
865
+ I & GroupInput<"headers", Input<S>>,
752
866
  E | Schema.SchemaError | InvalidRequest,
753
867
  R | S["EncodingServices"] | S["DecodingServices"]
754
868
  > =>
@@ -758,17 +872,45 @@ export const headers = <
758
872
  headerShapes: [...self.declaration.headerShapes, shape],
759
873
  },
760
874
  Effect.fnUntraced(function* (
761
- input: I & { readonly headers: Input<S> },
875
+ input: I & GroupInput<"headers", Input<S>>,
762
876
  draft: Draft,
763
877
  ) {
764
878
  if (draft.unbound.has("headers"))
765
879
  return yield* self.prepare(input, draft);
766
- const output = yield* encode(input.headers);
767
- const prepared = yield* self.prepare(input, draft);
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);
887
+ const prepared = yield* self.prepare(
888
+ input,
889
+ own === undefined
890
+ ? draft
891
+ : {
892
+ ...draft,
893
+ takenHeaders: Shapes.taking(draft.takenHeaders, own),
894
+ },
895
+ );
896
+ if (lostFromInput.length > 0)
897
+ yield* Inputs.refuseLost(
898
+ contract,
899
+ lostFromInput,
900
+ prepared.takenHeaders?.fields,
901
+ );
902
+ if (conflicts.length > 0)
903
+ return yield* constructorConflict("headers", conflicts);
768
904
  const names = Shapes.written(output, foldHeader);
905
+ const elsewhere = Shapes.others(
906
+ shape,
907
+ prepared.takenHeaders,
908
+ foldHeader,
909
+ );
769
910
  const defaults = prepared.headerLines.filter(
770
911
  ([name]) =>
771
912
  !names.has(foldHeader(name)) &&
913
+ !elsewhere.has(foldHeader(name)) &&
772
914
  Shapes.allows(shape, foldHeader(name)),
773
915
  );
774
916
  const settled = yield* Effect.mapError(settle(output, defaults), () =>
@@ -821,6 +963,19 @@ export const headers = <
821
963
  * ```
822
964
  *
823
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
+ *
824
979
  * The input is an {@link Input} of the schema. The schema encodes to `UrlEncoding.QueryInput` and
825
980
  * states the shape of the group, whatever the order of the calls: once any schema is bound, every
826
981
  * query field the request declares must be a name some schema allows. A raw entry under such a
@@ -831,7 +986,8 @@ export const headers = <
831
986
  * of pairs allows any name.
832
987
  *
833
988
  * Under a union, the defaults and what the schema wrote have to fit one member together. A field
834
- * that would be lost otherwise is an {@link InvalidRequest}, which names that field.
989
+ * that would be lost otherwise is an {@link InvalidRequest}, which names that field. The caller's
990
+ * own value is read before that, as {@link Input} describes.
835
991
  *
836
992
  * A field can encode to a `Date`, which is written as ISO text. Text under a field that encodes to
837
993
  * a number, boolean, bigint or `Date` is read as one first, and a single value under a list field
@@ -839,8 +995,9 @@ export const headers = <
839
995
  * schema. A `?` in a base URL or path output is text in the URL, not a field, so it is outside this
840
996
  * check.
841
997
  *
842
- * Query schemas stack: a second one adds its fields, and together they state the shape. Use
843
- * {@link unbind} to start again, and {@link mapInput} to supply a required field's value.
998
+ * Query schemas stack: a second one adds its fields, and together they state the shape. A field one
999
+ * of them takes stays with it, whatever a union beside it leaves out. Use {@link unbind} to start
1000
+ * again, and {@link mapInput} to supply a required field's value.
844
1001
  */
845
1002
  export const query = <
846
1003
  S extends Schema.Top &
@@ -848,12 +1005,15 @@ export const query = <
848
1005
  >(
849
1006
  contract: S,
850
1007
  ) => {
851
- const encode = Inputs.encoder(contract, Schema.encodeEffect(contract));
852
- const { shape, settle } = Shapes.bind(contract, foldQuery);
1008
+ const read = Inputs.reader(contract, Schema.encodeEffect(contract));
1009
+ const { shape, settle, taken, candidates, filled } = Shapes.bind(
1010
+ contract,
1011
+ foldQuery,
1012
+ );
853
1013
  return <I, E, R>(
854
1014
  self: Request<I, E, R>,
855
1015
  ): Request<
856
- I & { readonly query: Input<S> },
1016
+ I & GroupInput<"query", Input<S>>,
857
1017
  E | Schema.SchemaError | InvalidRequest,
858
1018
  R | S["EncodingServices"] | S["DecodingServices"]
859
1019
  > =>
@@ -863,20 +1023,44 @@ export const query = <
863
1023
  queryShapes: [...self.declaration.queryShapes, shape],
864
1024
  },
865
1025
  Effect.fnUntraced(function* (
866
- input: I & { readonly query: Input<S> },
1026
+ input: I & GroupInput<"query", Input<S>>,
867
1027
  draft: Draft,
868
1028
  ) {
869
1029
  if (draft.unbound.has("query"))
870
1030
  return yield* self.prepare(input, draft);
871
- const output = yield* encode(input.query);
872
- const prepared = yield* self.prepare(input, draft);
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);
1038
+ const prepared = yield* self.prepare(
1039
+ input,
1040
+ own === undefined
1041
+ ? draft
1042
+ : {
1043
+ ...draft,
1044
+ takenQuery: Shapes.taking(draft.takenQuery, own),
1045
+ },
1046
+ );
1047
+ if (lostFromInput.length > 0)
1048
+ yield* Inputs.refuseLost(
1049
+ contract,
1050
+ lostFromInput,
1051
+ prepared.takenQuery?.fields,
1052
+ );
1053
+ if (conflicts.length > 0)
1054
+ return yield* constructorConflict("query", conflicts);
873
1055
  const names = Shapes.written(output, foldQuery);
1056
+ const elsewhere = Shapes.others(shape, prepared.takenQuery, foldQuery);
874
1057
  const defaults = prepared.request.urlParams.params
875
1058
  .filter(
876
1059
  (param) =>
877
1060
  prepared.declaredQuery.has(param) &&
878
1061
  !isEmptySegment(prepared, param) &&
879
1062
  !names.has(param[0]) &&
1063
+ !elsewhere.has(param[0]) &&
880
1064
  Shapes.allows(shape, param[0]),
881
1065
  )
882
1066
  .map((param) => [param[0], queryValue(prepared, param)] as const);
@@ -959,7 +1143,9 @@ export interface PathValue<
959
1143
  K extends string = string,
960
1144
  S extends PathSchema = PathSchema,
961
1145
  > {
1146
+ /** The value's field under `path` in the input. */
962
1147
  readonly name: K;
1148
+ /** What checks and encodes the value. */
963
1149
  readonly schema: S;
964
1150
  }
965
1151
 
@@ -1249,9 +1435,10 @@ export type Unbound<I, K extends Group> = K extends keyof I
1249
1435
  * stay too. For `"path"`, the text of earlier {@link path} calls goes with their values, and
1250
1436
  * {@link setPath} is what changes the constructor's path.
1251
1437
  *
1252
- * Other steps stay as well. A {@link mapEffect} that reads the removed input receives `undefined`
1253
- * for it. After {@link mapInput}, the binding is skipped, but the mapped input keeps whatever the
1254
- * mapping requires. The request's error and service types keep what the removed bindings added.
1438
+ * Other steps stay as well. A {@link mapEffect} finds the removed property `undefined`, and where
1439
+ * no other input is left the whole input is `undefined`, so reading the property there is a defect.
1440
+ * After {@link mapInput}, the binding is skipped, but the mapped input keeps whatever the mapping
1441
+ * requires. The request's error and service types keep what the removed bindings added.
1255
1442
  */
1256
1443
  export const unbind =
1257
1444
  <K extends Group>(group: K) =>
@@ -1326,12 +1513,27 @@ export const mapEffect =
1326
1513
  * `request.url` holds the joined URL and its query. A fragment is in `request.hash`, as written.
1327
1514
  */
1328
1515
  export interface Compiled {
1516
+ /** The native request, with its URL and query joined. */
1329
1517
  readonly request: HttpClientRequest.HttpClientRequest;
1518
+ /** The header lines, in the spelling they were written with. */
1330
1519
  readonly headerLines: Transport.Lines;
1331
1520
  /** Lowercase header names the request removed, so the library adds no automatic value. */
1332
1521
  readonly removedHeaders: ReadonlySet<string>;
1333
1522
  }
1334
1523
 
1524
+ /** A record to start from where a schema in the group can lose a field to another one. */
1525
+ const takenRecord = (shapes: ReadonlyArray<Shape>): Taken | undefined =>
1526
+ shapes.length > 1 && shapes.some(({ chooses }) => chooses)
1527
+ ? {
1528
+ fields: new Set(),
1529
+ settled: new Set(
1530
+ shapes.flatMap(({ chooses, names }) =>
1531
+ chooses ? [] : Array.from(names),
1532
+ ),
1533
+ ),
1534
+ }
1535
+ : undefined;
1536
+
1335
1537
  const initialDraft = (declaration: Declaration): Draft => {
1336
1538
  // Custom method strings pass through at runtime; the method union is narrower than the transport.
1337
1539
  const native = HttpClientRequest.make(
@@ -1353,6 +1555,9 @@ const initialDraft = (declaration: Declaration): Draft => {
1353
1555
  declaredQuery: new Set(),
1354
1556
  removedHeaders: declaration.removedHeaders,
1355
1557
  unbound: new Set(),
1558
+ takenQuery: takenRecord(declaration.queryShapes),
1559
+ takenHeaders: takenRecord(declaration.headerShapes),
1560
+ editedFields: new Map(),
1356
1561
  },
1357
1562
  declaration.query.flatMap((field) =>
1358
1563
  Fields.resolve([field]).map(
@@ -13,11 +13,14 @@ import * as Transport from "./Transport.js";
13
13
  *
14
14
  * @remarks
15
15
  * Contains no body. Header and cookie visibility depends on the HTTP provider and browser.
16
- * `headerLines` is present only when a provider attached its observed lines.
16
+ * `headerLines` is `None` unless a provider attached its observed lines.
17
17
  */
18
18
  export interface Metadata {
19
+ /** The HTTP status code. */
19
20
  readonly status: number;
21
+ /** The normalized headers: lowercase names, with repeated lines joined. */
20
22
  readonly headers: Headers.Headers;
23
+ /** The cookies the response set, as far as the provider shows them. */
21
24
  readonly cookies: Cookies.Cookies;
22
25
  /** Provider-observed lines, when the provider supplied them. Normalized headers are always available. */
23
26
  readonly headerLines: Option.Option<Transport.Lines>;
@@ -63,6 +66,7 @@ export interface Response<
63
66
  out C extends AnyCase = AnyCase,
64
67
  >
65
68
  extends Pipeable.Pipeable {
69
+ /** The decoder of the first case that matches, if any case does. */
66
70
  readonly select: (metadata: Metadata) => Option.Option<Body.Decoder<A, E, R>>;
67
71
  /** Media types contributed to the automatic `Accept` header, in declaration order. */
68
72
  readonly accepts: ReadonlyArray<string>;
@@ -79,8 +83,11 @@ export interface Response<
79
83
  * and can repeat.
80
84
  */
81
85
  export interface Case<out K, out A, out E, out R> {
86
+ /** What addresses this case in {@link replace} and {@link remove}. */
82
87
  readonly key: K;
88
+ /** Whether this case applies, from the metadata alone. */
83
89
  readonly matches: (metadata: Metadata) => boolean;
90
+ /** What reads the body when this case is selected. */
84
91
  readonly decoder: Body.Decoder<A, E, R>;
85
92
  }
86
93
 
@@ -345,8 +352,11 @@ export const remove =
345
352
  * Checking `_tag` narrows the value type when several tagged outcomes form a union.
346
353
  */
347
354
  export interface Tagged<Tag extends string, A> {
355
+ /** The case name given to {@link tag}. */
348
356
  readonly _tag: Tag;
357
+ /** The decoded value. */
349
358
  readonly value: A;
359
+ /** The metadata of the response it came from. */
350
360
  readonly metadata: Metadata;
351
361
  }
352
362
 
@@ -87,7 +87,8 @@ export interface Service {
87
87
  * Combine the base origin/prefix and the request's rendered path or absolute URL.
88
88
  *
89
89
  * @remarks
90
- * Both arrive without a fragment. A fragment in the result is moved after the query.
90
+ * Both arrive without a fragment. A fragment in the result moves to the request's `hash`, so the
91
+ * query goes before it, unless a fragment from the request or the base wins.
91
92
  */
92
93
  readonly join: (base: string, path: string) => string;
93
94
  }