viell-effect-schema-http 0.1.0 → 0.2.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 +43 -29
  2. package/dist/http/Body.d.ts +23 -13
  3. package/dist/http/Body.d.ts.map +1 -1
  4. package/dist/http/Body.js +18 -8
  5. package/dist/http/Body.js.map +1 -1
  6. package/dist/http/Operation.d.ts +270 -13
  7. package/dist/http/Operation.d.ts.map +1 -1
  8. package/dist/http/Operation.js +210 -11
  9. package/dist/http/Operation.js.map +1 -1
  10. package/dist/http/Policy.d.ts +3 -2
  11. package/dist/http/Policy.d.ts.map +1 -1
  12. package/dist/http/Policy.js +3 -2
  13. package/dist/http/Policy.js.map +1 -1
  14. package/dist/http/Request.d.ts +477 -85
  15. package/dist/http/Request.d.ts.map +1 -1
  16. package/dist/http/Request.js +621 -141
  17. package/dist/http/Request.js.map +1 -1
  18. package/dist/http/Response.d.ts +119 -5
  19. package/dist/http/Response.d.ts.map +1 -1
  20. package/dist/http/Response.js +88 -7
  21. package/dist/http/Response.js.map +1 -1
  22. package/dist/http/UrlEncoding.d.ts +23 -7
  23. package/dist/http/UrlEncoding.d.ts.map +1 -1
  24. package/dist/http/UrlEncoding.js +7 -3
  25. package/dist/http/UrlEncoding.js.map +1 -1
  26. package/dist/http/internal/fields.d.ts +17 -4
  27. package/dist/http/internal/fields.d.ts.map +1 -1
  28. package/dist/http/internal/fields.js +11 -6
  29. package/dist/http/internal/fields.js.map +1 -1
  30. package/dist/http/internal/input.d.ts +39 -0
  31. package/dist/http/internal/input.d.ts.map +1 -0
  32. package/dist/http/internal/input.js +40 -0
  33. package/dist/http/internal/input.js.map +1 -0
  34. package/dist/http/internal/shape.d.ts +44 -0
  35. package/dist/http/internal/shape.d.ts.map +1 -0
  36. package/dist/http/internal/shape.js +179 -0
  37. package/dist/http/internal/shape.js.map +1 -0
  38. package/package.json +12 -12
  39. package/src/http/Body.ts +39 -18
  40. package/src/http/Operation.ts +468 -33
  41. package/src/http/Policy.ts +3 -2
  42. package/src/http/Request.ts +1075 -251
  43. package/src/http/Response.ts +235 -22
  44. package/src/http/UrlEncoding.ts +31 -8
  45. package/src/http/internal/fields.ts +37 -9
  46. package/src/http/internal/input.ts +123 -0
  47. package/src/http/internal/shape.ts +279 -0
@@ -1,4 +1,4 @@
1
- import { Data, Effect, Pipeable, Redacted, Schema } from "effect";
1
+ import { Data, Effect, Option, Pipeable, Redacted, Schema } from "effect";
2
2
  import {
3
3
  Headers,
4
4
  HttpClientRequest,
@@ -7,6 +7,8 @@ import {
7
7
  } from "effect/http";
8
8
  import type * as Body from "./Body.js";
9
9
  import * as Fields from "./internal/fields.js";
10
+ import * as Inputs from "./internal/input.js";
11
+ import * as Shapes from "./internal/shape.js";
10
12
  import * as Transport from "./Transport.js";
11
13
  import * as UrlEncoding from "./UrlEncoding.js";
12
14
 
@@ -14,8 +16,9 @@ import * as UrlEncoding from "./UrlEncoding.js";
14
16
  * Request preparation failed before dispatch.
15
17
  *
16
18
  * @remarks
17
- * Covers computed-field failures, URL-rendering exceptions, and a GET/HEAD body other than
18
- * `HttpBody.empty`. Schema encoding failures remain separate `SchemaError` values.
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.
21
+ * A failed check of a group names its fields and leaves out their values, which may be credentials.
19
22
  */
20
23
  export class InvalidRequest extends Data.TaggedError("InvalidRequest")<{
21
24
  readonly message: string;
@@ -31,33 +34,137 @@ export class InvalidRequest extends Data.TaggedError("InvalidRequest")<{
31
34
  */
32
35
  export type FieldValue<A = string> = Fields.Value<A>;
33
36
 
37
+ /**
38
+ * Headers declared together: a name's value, or `undefined` to remove its declarations.
39
+ *
40
+ * @remarks
41
+ * Use with {@link setHeader}. A value is text or a function that supplies it, as in
42
+ * {@link FieldValue}.
43
+ */
44
+ export type HeaderFields = Readonly<Record<string, FieldValue | undefined>>;
45
+
46
+ /**
47
+ * Query fields declared together: what a query schema may encode to, or a function.
48
+ *
49
+ * @remarks
50
+ * Use with {@link setQuery}. Numbers, bigints and booleans become text, a `Date` becomes ISO text,
51
+ * `null` is a bare key, an array repeats the name, and `undefined` removes the name's declarations.
52
+ * A function supplies one such value during preparation, written the same way, and `undefined`
53
+ * from it declares nothing, as in {@link FieldValue}. Fields apply in the object's key order, in
54
+ * which JavaScript puts integer-like keys first.
55
+ */
56
+ export type QueryFields = Readonly<
57
+ Record<
58
+ string,
59
+ | UrlEncoding.QueryValue
60
+ | ReadonlyArray<UrlEncoding.QueryValue>
61
+ | (() => UrlEncoding.QueryValue)
62
+ >
63
+ >;
64
+
65
+ /**
66
+ * What a schema-backed input takes: the schema's decoded side, its encoded side, or a mix by field.
67
+ *
68
+ * @remarks
69
+ * The decoded side is what the schema's constructor takes, so a plain object works for a
70
+ * `Schema.Class`, and a field with a constructor default can be left out. The encoded side is what
71
+ * goes on the wire, and {@link path}, {@link query}, {@link headers} and the schema body encoders
72
+ * all take it. The request always carries what the schema writes.
73
+ *
74
+ * Preparation tries the decoded side first, then the decoder as a whole, then the decoder field by
75
+ * field. If all fail, it reports the decoded side's error, a `SchemaError` before dispatch. Both
76
+ * routes validate, so text cannot get past a schema, but a weak schema lets more through:
77
+ * `Schema.NumberFromString` turns `"many"` into `NaN`, and `Schema.FiniteFromString` refuses it.
78
+ *
79
+ * A value that fits the decoded side is read as decoded. Under a schema whose two sides share a
80
+ * type, such as one from text to text, an already encoded value fits the decoded side, so it is
81
+ * 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
+ */
84
+ export type Input<S extends Schema.Top> = Inputs.Input<S>;
85
+
86
+ /**
87
+ * The whole input of a request: the object its call takes, with every binding's property.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { Schema } from "effect";
92
+ * import { Request } from "viell-effect-schema-http";
93
+ * const listThings = Request.get("https://api.example.test/things").pipe(
94
+ * Request.query(Schema.Struct({ sort: Schema.String })),
95
+ * Request.headers(Schema.Struct({ authorization: Schema.String })),
96
+ * );
97
+ * type ListInput = Request.InputOf<typeof listThings>;
98
+ * const withToken = listThings.pipe(
99
+ * Request.mapInput(
100
+ * (input: Omit<ListInput, "headers">): ListInput => ({
101
+ * ...input,
102
+ * headers: { authorization: "Bearer token" },
103
+ * }),
104
+ * ),
105
+ * );
106
+ * // Input: { query: { sort: "name" } }
107
+ * ```
108
+ *
109
+ * @remarks
110
+ * This takes a request, and {@link Input} takes a schema. `Input` is what one binding takes, such
111
+ * 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.
113
+ */
114
+ export type InputOf<R> =
115
+ R extends Request<infer I, unknown, unknown> ? I : never;
116
+
34
117
  /**
35
118
  * The method, URL and raw fields from which request preparation starts.
36
119
  *
37
120
  * @remarks
38
121
  * This is a low-level extension type. Prefer {@link make} and the request combinators.
39
- * `H` and `Q` record whether a schema owns each field group.
40
122
  */
41
- export interface Declaration<
42
- H extends boolean = boolean,
43
- Q extends boolean = boolean,
44
- > {
123
+ export interface Declaration {
45
124
  readonly method: string;
46
125
  readonly url: string;
47
- readonly baseUrl: string;
126
+ /** The fragment written in the constructor, without its `#`. */
127
+ readonly hash: string | undefined;
128
+ /**
129
+ * The base URL as text, or an Effect that supplies it during preparation. The request's own error
130
+ * and service types carry what that Effect needs. {@link mapBaseUrl} always leaves an Effect.
131
+ */
132
+ readonly baseUrl: string | Effect.Effect<string, unknown, unknown>;
48
133
  readonly headers: Fields.Fields;
49
134
  readonly query: Fields.Fields<string | null>;
50
- /** Whether a schema owns the header group; raw header setters are then unavailable. */
51
- readonly headersBound: H;
52
- /** Whether a schema owns the query group; raw query setters are then unavailable. */
53
- readonly queryBound: Q;
135
+ /** The constructor wrote a `?` with nothing after it, which holds no entries. */
136
+ readonly emptyQuery: boolean;
137
+ /** Lowercase header names the request removed, so the library adds no automatic value. */
138
+ readonly removedHeaders: ReadonlySet<string>;
139
+ /** The schemas bound to the header group, which together state its shape. */
140
+ readonly headerShapes: ReadonlyArray<Shape>;
141
+ /** The schemas bound to the query group, which together state its shape. */
142
+ readonly queryShapes: ReadonlyArray<Shape>;
143
+ /** Raw edits, after a schema, of a name it always writes, which could never reach the client. */
144
+ readonly conflicts: ReadonlyArray<
145
+ readonly [group: "query" | "headers", name: string]
146
+ >;
54
147
  }
55
148
 
149
+ /**
150
+ * 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.
152
+ *
153
+ * @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.
156
+ */
157
+ export type Shape = Shapes.Shape;
158
+
159
+ /** A part of a request that a binding can supply, and that {@link unbind} can clear. */
160
+ export type Group = "path" | "query" | "headers" | "body";
161
+
56
162
  /**
57
163
  * One entry in Effect's native query collection.
58
164
  *
59
165
  * @remarks
60
- * Drafts use entry identity to distinguish bare keys from empty values.
166
+ * Drafts use entry identity to distinguish bare keys from empty values, and to keep the text a
167
+ * constructor entry was written with.
61
168
  */
62
169
  export type UrlParam = UrlParams.UrlParams["params"][number];
63
170
 
@@ -75,6 +182,17 @@ export interface Draft {
75
182
  readonly headerLines: Transport.Lines;
76
183
  /** Native query entries that render as bare keys. Replacing an entry loses its identity marker. */
77
184
  readonly bareKeys: ReadonlySet<UrlParam>;
185
+ /** Native query entries that keep their written text. Replacing an entry loses that text. */
186
+ readonly queryText: ReadonlyMap<UrlParam, string>;
187
+ /**
188
+ * Native query entries the request declared, which a bound schema checks. A native edit makes a
189
+ * new entry, so {@link mapEffect} stays outside the check.
190
+ */
191
+ readonly declaredQuery: ReadonlySet<UrlParam>;
192
+ /** Lowercase header names the request removed, so the library adds no automatic value. */
193
+ readonly removedHeaders: ReadonlySet<string>;
194
+ /** The groups a later {@link unbind} cleared, so their earlier bindings skip themselves. */
195
+ readonly unbound: ReadonlySet<Group>;
78
196
  }
79
197
 
80
198
  /**
@@ -83,59 +201,76 @@ export interface Draft {
83
201
  * @remarks
84
202
  * Construction sends nothing. {@link compile} prepares it; `Operation.make` prepares and sends it.
85
203
  * `I` is the complete input, `E` its preparation errors, and `R` its required services.
86
- * `H` and `Q` record whether schemas own the header and query groups.
87
204
  * `declaration` and `prepare` are low-level extension points.
88
205
  */
89
- export interface Request<
90
- in I,
91
- out E = never,
92
- out R = never,
93
- out H extends boolean = false,
94
- out Q extends boolean = false,
95
- >
206
+ export interface Request<in I, out E = never, out R = never>
96
207
  extends Pipeable.Pipeable {
97
- readonly declaration: Declaration<H, Q>;
208
+ readonly declaration: Declaration;
98
209
  readonly prepare: (input: I, draft: Draft) => Effect.Effect<Draft, E, R>;
99
210
  }
100
211
 
101
- const construct = <I, E, R, H extends boolean, Q extends boolean>(
102
- declaration: Declaration<H, Q>,
212
+ const construct = <I, E, R>(
213
+ declaration: Declaration,
103
214
  prepare: (input: I, draft: Draft) => Effect.Effect<Draft, E, R>,
104
- ): Request<I, E, R, H, Q> => ({ ...Pipeable.Prototype, declaration, prepare });
215
+ ): Request<I, E, R> => ({ ...Pipeable.Prototype, declaration, prepare });
216
+
217
+ /** Split URL text at its first `#`, which ends the path and query. */
218
+ const splitFragment = (url: string): readonly [string, string | undefined] => {
219
+ const position = url.indexOf("#");
220
+ return position < 0
221
+ ? [url, undefined]
222
+ : [url.slice(0, position), url.slice(position + 1)];
223
+ };
224
+
225
+ /** A written empty segment is text with no name, so it is not a field a schema could allow. */
226
+ const isEmptySegment = (draft: Draft, param: UrlParam): boolean =>
227
+ draft.queryText.get(param) === "";
228
+
229
+ /** Read one written query segment as an entry that keeps its text. */
230
+ const readSegment = (segment: string): Fields.Field<string | null> => {
231
+ // URLSearchParams strips one leading query marker; a marker in the key is data. An empty segment
232
+ // yields no pair, so its name is the empty string.
233
+ const [[key, value] = ["", ""]] = new URLSearchParams(`?${segment}`);
234
+ return [key, segment.includes("=") ? value : null, segment];
235
+ };
105
236
 
106
237
  /**
107
238
  * Describe a request with a method and URL, without sending it.
108
239
  *
109
240
  * @remarks
110
241
  * Use `undefined` as input until a binding adds required fields. A relative path can be combined
111
- * with {@link baseUrl}; {@link path} can supply the complete path from typed input.
112
- * Custom method strings pass through unchanged.
242
+ * with {@link baseUrl}, and {@link path} adds to it, so `""` starts a path written whole in a
243
+ * template. Custom method strings pass through unchanged.
244
+ *
245
+ * A constructor query is passed to the client as written until something edits that entry, so
246
+ * `?a=1;b=2`, `?q=a+b` and `?a=%41` keep their spelling, as do empty `&` segments and a lone `?`.
247
+ * Each entry also has a form-decoded name and value, which {@link setQuery} and {@link removeQuery}
248
+ * compare against. An entry that is edited, or added, is rendered through `UrlEncoding.query`. An
249
+ * entry under a name a {@link query} schema allows goes through that schema, and one under a name
250
+ * no bound schema allows is an incompatible shape. A written empty segment has no name, so it is
251
+ * not a field, and it stays as written.
113
252
  *
114
- * A constructor query is parsed as form data: `+` becomes a space, percent escapes are decoded,
115
- * and empty `&` segments are dropped. Bare keys remain distinct from empty values. Compilation
116
- * renders these entries through `UrlEncoding.query`; a constructor fragment is discarded.
253
+ * A fragment stays on the request, exactly as written, in the native request's `hash` field. It
254
+ * survives {@link path} and query edits, and wins over a fragment in path output or a base URL.
255
+ * Whether it goes out is up to the client; `fetch` does not send one.
117
256
  */
118
257
  export const make = (method: string, url: string): Request<unknown> => {
119
- const hash = url.indexOf("#");
120
- const withoutHash = hash < 0 ? url : url.slice(0, hash);
258
+ const [withoutHash, hash] = splitFragment(url);
121
259
  const start = withoutHash.indexOf("?");
122
- const query: Array<readonly [string, string | null]> = [];
123
- if (start >= 0) {
124
- for (const segment of withoutHash.slice(start + 1).split("&")) {
125
- // URLSearchParams strips one leading query marker; a marker in the key is data.
126
- for (const [key, value] of new URLSearchParams(`?${segment}`))
127
- query.push([key, segment.includes("=") ? value : null]);
128
- }
129
- }
260
+ const written = start < 0 ? "" : withoutHash.slice(start + 1);
130
261
  return construct(
131
262
  {
132
263
  method,
133
264
  url: start < 0 ? withoutHash : withoutHash.slice(0, start),
265
+ hash,
134
266
  baseUrl: "",
135
267
  headers: [],
136
- query,
137
- headersBound: false,
138
- queryBound: false,
268
+ query: written === "" ? [] : written.split("&").map(readSegment),
269
+ emptyQuery: start >= 0 && written === "",
270
+ removedHeaders: new Set(),
271
+ headerShapes: [],
272
+ queryShapes: [],
273
+ conflicts: [],
139
274
  },
140
275
  (_, draft) => Effect.succeed(draft),
141
276
  );
@@ -170,7 +305,7 @@ export const patch = (url: string): Request<unknown> => make("PATCH", url);
170
305
  */
171
306
  export const del = (url: string): Request<unknown> => make("DELETE", url);
172
307
  /**
173
- * Describe a HEAD request. Its outgoing body must remain `HttpBody.empty`.
308
+ * Describe a HEAD request. A {@link body} is passed on as for any method; the client may refuse it.
174
309
  */
175
310
  export const head = (url: string): Request<unknown> => make("HEAD", url);
176
311
  /**
@@ -179,7 +314,7 @@ export const head = (url: string): Request<unknown> => make("HEAD", url);
179
314
  export const options = (url: string): Request<unknown> => make("OPTIONS", url);
180
315
 
181
316
  /**
182
- * Set the shared origin and fixed path prefix for a request.
317
+ * Set the shared origin and fixed path prefix for a request, as text or from an Effect.
183
318
  *
184
319
  * @example
185
320
  * ```ts
@@ -189,109 +324,319 @@ export const options = (url: string): Request<unknown> => make("OPTIONS", url);
189
324
  * const teams = Request.get("/teams").pipe(api);
190
325
  * ```
191
326
  *
327
+ * @example
328
+ * ```ts
329
+ * import { Context, Effect } from "effect";
330
+ * import { Request } from "viell-effect-schema-http";
331
+ * class ApiHost extends Context.Service<ApiHost, string>()("app/ApiHost") {}
332
+ * const discovered = Effect.gen(function* () {
333
+ * const host = yield* ApiHost;
334
+ * return `https://${host}/api/v1`;
335
+ * });
336
+ * const users = Request.get("/users").pipe(Request.baseUrl(discovered));
337
+ * // The request needs ApiHost, as it would need any other service.
338
+ * ```
339
+ *
192
340
  * @remarks
193
341
  * The base is joined after path preparation. With the default URL policy, an absolute request
194
342
  * URL bypasses it; a leading `/` on a relative path keeps the base's prefix. Calling this again
195
- * replaces the base, rather than appending to it. Keep query fields in request combinators.
343
+ * replaces the base, rather than appending to it, and {@link mapBaseUrl} extends it. Keep query
344
+ * fields in request combinators. A fragment in the base is taken off before joining and used if the
345
+ * request has none of its own.
346
+ *
347
+ * An Effect supplies a location that is not known when the request is defined, from a service or a
348
+ * `Config` value, say. Its failures and services join the request's type, so leaving out a service
349
+ * is a compile error. It runs once per evaluation, after the input is encoded and before any
350
+ * attempt, so every retry uses the same base. Its failure is returned as it is, before anything is
351
+ * sent, and a retry policy does not repeat it. What it supplies is treated exactly as text would
352
+ * be, including by a replaced `UrlEncoding.join`.
353
+ *
354
+ * A location that must change between attempts belongs in `Operation.make`'s `transformClient`. A
355
+ * base that is replaced never runs, though the request's types keep what it added.
196
356
  */
197
357
  export const baseUrl =
198
- (url: string) =>
199
- <I, E, R, H extends boolean, Q extends boolean>(
200
- self: Request<I, E, R, H, Q>,
201
- ): Request<I, E, R, H, Q> =>
358
+ <E2 = never, R2 = never>(url: string | Effect.Effect<string, E2, R2>) =>
359
+ <I, E, R>(self: Request<I, E, R>): Request<I, E | E2, R | R2> =>
202
360
  construct({ ...self.declaration, baseUrl: url }, self.prepare);
203
361
 
362
+ /** A request's base URL as an Effect, whichever form it was declared in. */
363
+ const resolveBaseUrl = ({ baseUrl: url }: Declaration) =>
364
+ typeof url === "string" ? Effect.succeed(url) : url;
365
+
366
+ /**
367
+ * Change the base URL, whether it is text or an Effect, to extend a prefix or swap part of it.
368
+ *
369
+ * @example
370
+ * ```ts
371
+ * import { Request } from "viell-effect-schema-http";
372
+ * const api = Request.baseUrl("https://api.example.test/api/v1");
373
+ * const toAdmin = (url: string) => `${url}/admin`;
374
+ * const admin = Request.mapBaseUrl(toAdmin);
375
+ * const listUsers = Request.get("/users").pipe(api, admin);
376
+ * // https://api.example.test/api/v1/admin/users
377
+ * ```
378
+ *
379
+ * @remarks
380
+ * Use it where a request holds a base you cannot read, as an imported definition does, or one that
381
+ * is not known yet. `f` runs during preparation, once per evaluation, and receives the base as it
382
+ * stands at this step, so `""` where none is set. That is the whole text, including any query or
383
+ * fragment in it, and what `f` returns is joined exactly as a base from {@link baseUrl} would be. A
384
+ * later {@link baseUrl} replaces the result. An exception from `f` is an {@link InvalidRequest}.
385
+ */
386
+ export const mapBaseUrl =
387
+ (f: (url: string) => string): Edit =>
388
+ (self) =>
389
+ construct(
390
+ {
391
+ ...self.declaration,
392
+ baseUrl: Effect.flatMap(resolveBaseUrl(self.declaration), (url) =>
393
+ Effect.try({
394
+ try: () => f(url),
395
+ catch: (cause) =>
396
+ new InvalidRequest({
397
+ message: "Failed to map the request's base URL",
398
+ cause,
399
+ }),
400
+ }),
401
+ ),
402
+ },
403
+ self.prepare,
404
+ );
405
+
406
+ /** Header names compare without case; each line keeps the spelling it was given. */
407
+ const foldHeader: Fields.Fold = (name) => name.toLowerCase();
408
+
409
+ /** Query names compare exactly. */
410
+ const foldQuery: Fields.Fold = (name) => name;
411
+
412
+ /** A raw edit: a request's fields change, and its input, errors and services stay. */
413
+ type Edit = <I, E, R>(self: Request<I, E, R>) => Request<I, E, R>;
414
+
204
415
  const editHeaders =
205
- (edit: (fields: Fields.Fields) => Fields.Fields) =>
206
- <I, E, R, Q extends boolean>(
207
- self: Request<I, E, R, false, Q>,
208
- ): Request<I, E, R, false, Q> =>
416
+ (
417
+ edited: ReadonlyArray<string>,
418
+ edit: (fields: Fields.Fields) => Fields.Fields,
419
+ removed: (names: ReadonlySet<string>) => ReadonlySet<string> = (names) =>
420
+ names,
421
+ ): Edit =>
422
+ (self) =>
209
423
  construct(
210
- { ...self.declaration, headers: edit(self.declaration.headers) },
424
+ {
425
+ ...self.declaration,
426
+ headers: edit(self.declaration.headers),
427
+ removedHeaders: removed(self.declaration.removedHeaders),
428
+ conflicts: [
429
+ ...self.declaration.conflicts,
430
+ ...Shapes.required(
431
+ edited,
432
+ self.declaration.headerShapes,
433
+ foldHeader,
434
+ ).map((name) => ["headers", name] as const),
435
+ ],
436
+ },
211
437
  self.prepare,
212
438
  );
213
439
 
214
440
  const editQuery =
215
441
  (
442
+ names: ReadonlyArray<string>,
216
443
  edit: (
217
444
  fields: Fields.Fields<string | null>,
218
445
  ) => Fields.Fields<string | null>,
219
- ) =>
220
- <I, E, R, H extends boolean>(
221
- self: Request<I, E, R, H, false>,
222
- ): Request<I, E, R, H, false> =>
446
+ ): Edit =>
447
+ (self) =>
223
448
  construct(
224
- { ...self.declaration, query: edit(self.declaration.query) },
449
+ {
450
+ ...self.declaration,
451
+ query: edit(self.declaration.query),
452
+ conflicts: [
453
+ ...self.declaration.conflicts,
454
+ ...Shapes.required(
455
+ names,
456
+ self.declaration.queryShapes,
457
+ foldQuery,
458
+ ).map((name) => ["query", name] as const),
459
+ ],
460
+ },
225
461
  self.prepare,
226
462
  );
227
463
 
228
464
  /**
229
- * Set a raw header, replacing every existing line with that name.
465
+ * Set a raw header, replacing every existing line with that name, or set several from an object.
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * import { Request } from "viell-effect-schema-http";
470
+ * const request = Request.get("https://api.example.test/things").pipe(
471
+ * Request.setHeader("X-One", "1"),
472
+ * Request.setHeader({ "X-Two": "2", "X-Three": () => "3" }),
473
+ * );
474
+ * ```
230
475
  *
231
476
  * @remarks
232
- * Names compare without case and are stored lowercase. Unavailable after a header schema is
233
- * bound. The body encoder owns `Content-Type` and `Content-Length`.
477
+ * Names compare without case, and the new line keeps the spelling of this call. A declared
478
+ * `Accept`, `Content-Type` or `Content-Length` replaces the automatic value, before or after the
479
+ * body.
480
+ *
481
+ * With a {@link headers} schema bound, in either order, the name has to be one a schema allows, and
482
+ * the value is a default that goes through the schema. Setting a name the schema always writes,
483
+ * after that schema, is an {@link InvalidRequest}, because the value could never reach the client.
484
+ *
485
+ * In the object form each key replaces its name as above, in key order, and other names stay. A key
486
+ * set to `undefined` removes that name's declarations and stops no automatic value, which is what
487
+ * {@link removeHeader} is for.
234
488
  */
235
- export const setHeader = (name: string, value: FieldValue) =>
236
- editHeaders((fields) => Fields.set(fields, name.toLowerCase(), value));
489
+ export const setHeader: {
490
+ (name: string, value: FieldValue): Edit;
491
+ (fields: HeaderFields): Edit;
492
+ } = (first: string | HeaderFields, value?: FieldValue) => {
493
+ const entries =
494
+ typeof first === "string"
495
+ ? [[first, value] as const]
496
+ : Object.entries(first);
497
+ return editHeaders(
498
+ entries.map(([name]) => name),
499
+ (fields) =>
500
+ entries.reduce(
501
+ (result, [name, entry]) =>
502
+ Fields.replace(
503
+ result,
504
+ name,
505
+ entry === undefined ? [] : [entry],
506
+ foldHeader,
507
+ ),
508
+ fields,
509
+ ),
510
+ );
511
+ };
237
512
 
238
513
  /**
239
514
  * Add a raw header line after the existing lines, preserving repetition.
240
515
  *
241
516
  * @remarks
242
- * Names are stored lowercase. Unavailable after a header schema is bound. Sending separate
243
- * lines requires a provider that supports them; Fetch may combine or restrict headers.
517
+ * Each line keeps the spelling of its call. A bound {@link headers} schema checks it as it does
518
+ * {@link setHeader}. Sending separate lines requires a provider that supports them; Fetch may
519
+ * combine or restrict headers.
244
520
  */
245
521
  export const appendHeader = (name: string, value: FieldValue) =>
246
- editHeaders((fields) => Fields.append(fields, name.toLowerCase(), value));
522
+ editHeaders([name], (fields) => Fields.append(fields, name, value));
247
523
 
248
524
  /**
249
525
  * Remove a raw header, or only its declarations with the supplied fixed value.
250
526
  *
251
527
  * @remarks
252
- * Names compare without case. Value functions are never evaluated to compare with `value`.
253
- * Unavailable after a header schema is bound.
528
+ * Names compare without case. Value functions are never evaluated to compare with `value`. Removing
529
+ * a name a {@link headers} schema always writes, after that schema, is an {@link InvalidRequest},
530
+ * because the schema puts the value back. Removing an optional field clears its default.
531
+ *
532
+ * Without a value, this also stops the library's automatic value for that name: an operation's
533
+ * `Accept`, or a body's `Content-Type` and `Content-Length`. It stops only that. A value that a
534
+ * later declaration, a header schema or {@link mapEffect} supplies still goes out, and the client
535
+ * may add its own. A computed value that returns `undefined` declares nothing, so the removal stays
536
+ * in force. A removal limited to one value stops nothing, as the name may still be declared.
254
537
  */
255
538
  export const removeHeader = (name: string, value?: string) =>
256
- editHeaders((fields) => Fields.remove(fields, name.toLowerCase(), value));
539
+ editHeaders(
540
+ [name],
541
+ (fields) => Fields.remove(fields, name, value, foldHeader),
542
+ (names) =>
543
+ value === undefined ? new Set([...names, foldHeader(name)]) : names,
544
+ );
257
545
 
258
546
  /**
259
- * Set a raw query field, replacing entries with the same case-sensitive name.
547
+ * Set a raw query field, replacing entries with the same case-sensitive name, or set several from
548
+ * an object.
549
+ *
550
+ * @example
551
+ * ```ts
552
+ * import { Request } from "viell-effect-schema-http";
553
+ * const search = Request.get("https://api.example.test/users").pipe(
554
+ * Request.setQuery({ page: 2, tag: ["a", "b"], preview: null }),
555
+ * );
556
+ * // URL query: ?page=2&tag=a&tag=b&preview
557
+ * ```
260
558
  *
261
559
  * @remarks
262
- * `null` produces a bare key, `""` an empty value, and `undefined` omits the entry.
263
- * Unavailable after a query schema is bound.
560
+ * `null` produces a bare key, `""` an empty value, and `undefined` omits the entry. Names compare
561
+ * with an entry's decoded name, so this can replace an entry written in the constructor; other
562
+ * entries stay as written.
563
+ *
564
+ * With a {@link query} schema bound, in either order, the name has to be one a schema allows, and
565
+ * the value is a default that goes through the schema. Setting a name the schema always writes,
566
+ * after that schema, is an {@link InvalidRequest}, because the value could never reach the client.
567
+ *
568
+ * The object form takes {@link QueryFields}. Each key replaces its name as above, in key order, and
569
+ * other names stay. Use {@link appendQuery} for exact order across repeated names.
264
570
  */
265
- export const setQuery = (name: string, value: FieldValue<string | null>) =>
266
- editQuery((fields) => Fields.set(fields, name, value));
571
+ export const setQuery: {
572
+ (name: string, value: FieldValue<string | null>): Edit;
573
+ (fields: QueryFields): Edit;
574
+ } = (first: string | QueryFields, value?: FieldValue<string | null>) => {
575
+ const entries: ReadonlyArray<readonly [string, QueryFields[string]]> =
576
+ typeof first === "string" ? [[first, value]] : Object.entries(first);
577
+ return editQuery(
578
+ entries.map(([name]) => name),
579
+ (fields) =>
580
+ entries.reduce(
581
+ (result, [name, entry]) =>
582
+ Fields.replace(
583
+ result,
584
+ name,
585
+ typeof entry === "function"
586
+ ? [() => UrlEncoding.queryEntries([[name, entry()]])[0]?.[1]]
587
+ : UrlEncoding.queryEntries([[name, entry]]).map(
588
+ ([, text]) => text,
589
+ ),
590
+ ),
591
+ fields,
592
+ ),
593
+ );
594
+ };
267
595
 
268
596
  /**
269
597
  * Append a raw query entry, preserving order and repeated names.
270
598
  *
271
599
  * @remarks
272
- * Uses the same value rules as {@link setQuery}. Unavailable after a query schema is bound.
600
+ * Uses the same value rules as {@link setQuery}, and a bound {@link query} schema checks it the
601
+ * same way.
273
602
  */
274
603
  export const appendQuery = (name: string, value: FieldValue<string | null>) =>
275
- editQuery((fields) => Fields.append(fields, name, value));
604
+ editQuery([name], (fields) => Fields.append(fields, name, value));
276
605
 
277
606
  /**
278
607
  * Remove a raw query field, or only declarations with the supplied fixed value.
279
608
  *
280
609
  * @remarks
281
- * Names compare with case. Value functions are not evaluated for comparison.
282
- * Unavailable after a query schema is bound.
610
+ * Names compare with case, and both names and values compare with an entry's decoded form. Value
611
+ * functions are not evaluated for comparison. Removing a name a {@link query} schema always writes,
612
+ * after that schema, is an {@link InvalidRequest}, because the schema puts the value back. Removing
613
+ * an optional field clears its default.
283
614
  */
284
615
  export const removeQuery = (name: string, value?: string | null) =>
285
- editQuery((fields) => Fields.remove(fields, name, value));
616
+ editQuery([name], (fields) => Fields.remove(fields, name, value));
286
617
 
287
- const replaceQuery = (draft: Draft, entries: UrlEncoding.Query): Draft => {
618
+ /** Put entries after the existing ones, in place of every entry under the `keys` names. */
619
+ const replaceQuery = (
620
+ draft: Draft,
621
+ entries: ReadonlyArray<
622
+ readonly [string, string | null, written?: string | undefined]
623
+ >,
624
+ keys: ReadonlySet<string> = new Set(entries.map(([key]) => key)),
625
+ ): Draft => {
288
626
  const added = entries.map(([key, value]): UrlParam => [key, value ?? ""]);
289
- const keys = new Set(added.map(([key]) => key));
290
627
  const bareKeys = new Set(
291
628
  Array.from(draft.bareKeys).filter(([key]) => !keys.has(key)),
292
629
  );
293
- entries.forEach(([, value], index) => {
630
+ const queryText = new Map(
631
+ Array.from(draft.queryText).filter(([[key]]) => !keys.has(key)),
632
+ );
633
+ const declaredQuery = new Set([
634
+ ...Array.from(draft.declaredQuery).filter(([key]) => !keys.has(key)),
635
+ ...added,
636
+ ]);
637
+ entries.forEach(([, value, written], index) => {
294
638
  if (value === null) bareKeys.add(added[index]!);
639
+ if (written !== undefined) queryText.set(added[index]!, written);
295
640
  });
296
641
  const { request } = draft;
297
642
  const params = [
@@ -309,77 +654,154 @@ const replaceQuery = (draft: Draft, entries: UrlEncoding.Query): Draft => {
309
654
  request.body,
310
655
  ),
311
656
  bareKeys,
657
+ queryText,
658
+ declaredQuery,
312
659
  };
313
660
  };
314
661
 
315
- /** Fields that describe the body itself rather than the request. */
662
+ /** What a native query entry holds: text, or `null` for a bare key. */
663
+ const queryValue = (draft: Draft, param: UrlParam): string | null =>
664
+ draft.bareKeys.has(param)
665
+ ? null
666
+ : Redacted.isRedacted(param[1])
667
+ ? Redacted.value(param[1])
668
+ : param[1];
669
+
670
+ const listNames = (names: ReadonlyArray<string>): string =>
671
+ Array.from(new Set(names), (name) => JSON.stringify(name)).join(", ");
672
+
673
+ /** Names only: a default's value may be a credential, and a schema's error would repeat it. */
674
+ const misfit = (
675
+ group: string,
676
+ defaults: ReadonlyArray<readonly [string, unknown]>,
677
+ ): InvalidRequest =>
678
+ new InvalidRequest({
679
+ message: `The ${group} group cannot be built against its schema with these declared values: ${listNames(defaults.map(([name]) => name))}.`,
680
+ });
681
+
682
+ /** Names only, and only those that would go: what the schema kept fits it. */
683
+ const lostFields = (
684
+ group: string,
685
+ names: ReadonlyArray<string>,
686
+ ): InvalidRequest =>
687
+ new InvalidRequest({
688
+ message: `The ${group} group cannot be built against its schema: with the rest of the group, these fields would be lost: ${listNames(names)}.`,
689
+ });
690
+
691
+ /** Fields a body's encoder supplies unless the request says otherwise. */
316
692
  const bodyFields = ["content-type", "content-length"] as const;
317
693
 
318
- /** Give the body fields their values from `before`, removing those it lacks. */
319
- const keepBodyFields = (
320
- headers: Headers.Headers,
321
- before: Headers.Headers,
322
- ): Headers.Headers =>
323
- bodyFields.reduce((result, name) => {
324
- const value = before[name];
325
- return value === undefined
326
- ? Headers.remove(result, name)
327
- : Headers.set(result, name, value);
328
- }, headers);
694
+ /** After an encoder set the body fields, apply what the request itself says about them. */
695
+ const applyDeclaredBodyFields = (
696
+ encoded: HttpClientRequest.HttpClientRequest,
697
+ prepared: Draft,
698
+ ): HttpClientRequest.HttpClientRequest => {
699
+ const declared = Transport.toHeaders(prepared.headerLines);
700
+ return HttpClientRequest.updateHeaders(encoded, (fields) =>
701
+ bodyFields.reduce((result, name) => {
702
+ const value =
703
+ declared[name] ??
704
+ (prepared.removedHeaders.has(name)
705
+ ? prepared.request.headers[name]
706
+ : result[name]);
707
+ return value === undefined
708
+ ? Headers.remove(result, name)
709
+ : Headers.set(result, name, value);
710
+ }, fields),
711
+ );
712
+ };
329
713
 
330
714
  /**
331
715
  * Bind a schema to the call's `{ headers }` input.
332
716
  *
333
717
  * @remarks
334
- * Encoding produces ordered header lines. The schema replaces raw header declarations and owns
335
- * the group: later raw setters or another header schema are unavailable.
336
- * When a body is present, its `Content-Type` and `Content-Length` take precedence, regardless of
337
- * binding order. Without a body, the schema values apply; a later body binding, including
338
- * `Body.empty`, replaces those fields according to its encoder.
718
+ * The input is an {@link Input} of the schema. Encoding produces ordered header lines. The schema
719
+ * states the shape of the group, whatever the order of the calls: once any schema is bound, every
720
+ * header the request declares must be a name some schema allows. A raw header under such a name
721
+ * is a default: what the schema writes replaces it, and otherwise it goes through the schema,
722
+ * which writes its value, spelling and order. An omitted optional field therefore leaves the
723
+ * default in place. A raw header under a name no schema allows is an {@link InvalidRequest} before
724
+ * anything is sent. A record or `Schema.StructWithRest` allows any name. Names compare without
725
+ * case.
726
+ *
727
+ * 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.
729
+ *
730
+ * Header schemas stack: a second one adds its fields, and together they state the shape. Use
731
+ * {@link unbind} to start again.
732
+ *
733
+ * A field the schema produces wins over an automatic `Accept`, `Content-Type` or `Content-Length`,
734
+ * whether the schema is bound before or after the body, and so does a default. An optional field
735
+ * left out with no default declares nothing, so the automatic value still applies.
736
+ *
737
+ * Header values are text, so a schema writes its own. A query schema can encode to a `Date`, but
738
+ * HTTP date headers are not ISO text, and `Schema.DateTimeUtcFromHttpDate` writes them.
339
739
  */
340
740
  export const headers = <
341
- S extends Schema.ConstraintCodec<
342
- unknown,
343
- Transport.HeaderInput,
344
- unknown,
345
- unknown
346
- >,
741
+ S extends Schema.Top &
742
+ Schema.ConstraintCodec<unknown, Transport.HeaderInput, unknown, unknown>,
347
743
  >(
348
744
  contract: S,
349
745
  ) => {
350
- const encode = Schema.encodeEffect(contract);
351
- return <I, E, R, Q extends boolean>(
352
- self: Request<I, E, R, false, Q>,
746
+ const encode = Inputs.encoder(contract, Schema.encodeEffect(contract));
747
+ const { shape, settle } = Shapes.bind(contract, foldHeader);
748
+ return <I, E, R>(
749
+ self: Request<I, E, R>,
353
750
  ): Request<
354
- I & { readonly headers: S["Type"] },
355
- E | Schema.SchemaError,
356
- R | S["EncodingServices"],
357
- true,
358
- Q
751
+ I & { readonly headers: Input<S> },
752
+ E | Schema.SchemaError | InvalidRequest,
753
+ R | S["EncodingServices"] | S["DecodingServices"]
359
754
  > =>
360
755
  construct(
361
- { ...self.declaration, headers: [], headersBound: true },
756
+ {
757
+ ...self.declaration,
758
+ headerShapes: [...self.declaration.headerShapes, shape],
759
+ },
362
760
  Effect.fnUntraced(function* (
363
- input: I & { readonly headers: S["Type"] },
761
+ input: I & { readonly headers: Input<S> },
364
762
  draft: Draft,
365
763
  ) {
366
- const encoded = yield* encode(input.headers);
764
+ if (draft.unbound.has("headers"))
765
+ return yield* self.prepare(input, draft);
766
+ const output = yield* encode(input.headers);
367
767
  const prepared = yield* self.prepare(input, draft);
368
- const headerLines = Transport.entries(encoded);
369
- const merged = HttpClientRequest.setHeaders(
768
+ const names = Shapes.written(output, foldHeader);
769
+ const defaults = prepared.headerLines.filter(
770
+ ([name]) =>
771
+ !names.has(foldHeader(name)) &&
772
+ Shapes.allows(shape, foldHeader(name)),
773
+ );
774
+ const settled = yield* Effect.mapError(settle(output, defaults), () =>
775
+ misfit("header", defaults),
776
+ );
777
+ // A field the schema does not write back would be lost, as a union member can lose one.
778
+ const lost = Shapes.lost(output, defaults, settled, foldHeader);
779
+ if (lost.length > 0) return yield* lostFields("header", lost);
780
+ const lines = Transport.entries(settled);
781
+ const replaced = new Set([
782
+ ...names,
783
+ ...defaults.map(([name]) => foldHeader(name)),
784
+ ]);
785
+ const cleared = HttpClientRequest.updateHeaders(
370
786
  prepared.request,
371
- Transport.toHeaders(headerLines),
787
+ (fields) =>
788
+ prepared.headerLines
789
+ .map(([name]) => foldHeader(name))
790
+ .filter((name) => replaced.has(name))
791
+ .reduce((result, name) => Headers.remove(result, name), fields),
372
792
  );
373
- // Compilation then drops the schema's lines for any body field whose value was kept.
374
793
  return {
375
794
  ...prepared,
376
- request:
377
- prepared.request.body._tag === "Empty"
378
- ? merged
379
- : HttpClientRequest.updateHeaders(merged, (fields) =>
380
- keepBodyFields(fields, prepared.request.headers),
381
- ),
382
- headerLines,
795
+ request: HttpClientRequest.setHeaders(
796
+ cleared,
797
+ Transport.toHeaders(lines),
798
+ ),
799
+ headerLines: [
800
+ ...prepared.headerLines.filter(
801
+ ([name]) => !replaced.has(foldHeader(name)),
802
+ ),
803
+ ...lines,
804
+ ],
383
805
  };
384
806
  }),
385
807
  );
@@ -393,99 +815,121 @@ export const headers = <
393
815
  * import { Schema } from "effect";
394
816
  * import { Request } from "viell-effect-schema-http";
395
817
  * const search = Request.get("https://api.example.test/users").pipe(
396
- * Request.query(Schema.Struct({ page: Schema.NumberFromString })),
818
+ * Request.query(Schema.Struct({ page: Schema.FiniteFromString })),
397
819
  * );
398
820
  * // Input: { query: { page: 2 } }; URL query: ?page=2
399
821
  * ```
400
822
  *
401
823
  * @remarks
402
- * The schema encodes to `UrlEncoding.QueryInput`. It replaces raw query declarations, including
403
- * the constructor's query string, and owns the group. Later raw setters or another query schema
404
- * are unavailable. Use {@link mapInput} to supply application defaults.
824
+ * The input is an {@link Input} of the schema. The schema encodes to `UrlEncoding.QueryInput` and
825
+ * states the shape of the group, whatever the order of the calls: once any schema is bound, every
826
+ * query field the request declares must be a name some schema allows. A raw entry under such a
827
+ * name is a default, including one written in the constructor: what the schema writes replaces
828
+ * it, and otherwise it goes through the schema, which writes its value and order. An omitted
829
+ * optional field therefore leaves the default in place. A raw entry under a name no schema allows
830
+ * is an {@link InvalidRequest} before anything is sent. A record, `Schema.StructWithRest` or a list
831
+ * of pairs allows any name.
832
+ *
833
+ * 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.
835
+ *
836
+ * A field can encode to a `Date`, which is written as ISO text. Text under a field that encodes to
837
+ * a number, boolean, bigint or `Date` is read as one first, and a single value under a list field
838
+ * fits it. Date text is read as `Schema.DateFromString` reads it. The check is as strict as the
839
+ * schema. A `?` in a base URL or path output is text in the URL, not a field, so it is outside this
840
+ * check.
841
+ *
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.
405
844
  */
406
845
  export const query = <
407
- S extends Schema.ConstraintCodec<
408
- unknown,
409
- UrlEncoding.QueryInput,
410
- unknown,
411
- unknown
412
- >,
846
+ S extends Schema.Top &
847
+ Schema.ConstraintCodec<unknown, UrlEncoding.QueryInput, unknown, unknown>,
413
848
  >(
414
849
  contract: S,
415
850
  ) => {
416
- const encode = Schema.encodeEffect(contract);
417
- return <I, E, R, H extends boolean>(
418
- self: Request<I, E, R, H, false>,
851
+ const encode = Inputs.encoder(contract, Schema.encodeEffect(contract));
852
+ const { shape, settle } = Shapes.bind(contract, foldQuery);
853
+ return <I, E, R>(
854
+ self: Request<I, E, R>,
419
855
  ): Request<
420
- I & { readonly query: S["Type"] },
421
- E | Schema.SchemaError,
422
- R | S["EncodingServices"],
423
- H,
424
- true
856
+ I & { readonly query: Input<S> },
857
+ E | Schema.SchemaError | InvalidRequest,
858
+ R | S["EncodingServices"] | S["DecodingServices"]
425
859
  > =>
426
860
  construct(
427
- { ...self.declaration, query: [], queryBound: true },
861
+ {
862
+ ...self.declaration,
863
+ queryShapes: [...self.declaration.queryShapes, shape],
864
+ },
428
865
  Effect.fnUntraced(function* (
429
- input: I & { readonly query: S["Type"] },
866
+ input: I & { readonly query: Input<S> },
430
867
  draft: Draft,
431
868
  ) {
432
- const encoded = yield* encode(input.query);
869
+ if (draft.unbound.has("query"))
870
+ return yield* self.prepare(input, draft);
871
+ const output = yield* encode(input.query);
433
872
  const prepared = yield* self.prepare(input, draft);
434
- return replaceQuery(prepared, UrlEncoding.queryEntries(encoded));
873
+ const names = Shapes.written(output, foldQuery);
874
+ const defaults = prepared.request.urlParams.params
875
+ .filter(
876
+ (param) =>
877
+ prepared.declaredQuery.has(param) &&
878
+ !isEmptySegment(prepared, param) &&
879
+ !names.has(param[0]) &&
880
+ Shapes.allows(shape, param[0]),
881
+ )
882
+ .map((param) => [param[0], queryValue(prepared, param)] as const);
883
+ const settled = yield* Effect.mapError(settle(output, defaults), () =>
884
+ misfit("query", defaults),
885
+ );
886
+ // A field the schema does not write back would be lost, as a union member can lose one.
887
+ const lost = Shapes.lost(output, defaults, settled, foldQuery);
888
+ if (lost.length > 0) return yield* lostFields("query", lost);
889
+ return replaceQuery(
890
+ prepared,
891
+ UrlEncoding.queryEntries(settled),
892
+ new Set([...names, ...defaults.map(([name]) => name)]),
893
+ );
435
894
  }),
436
895
  );
437
896
  };
438
897
 
439
- /**
440
- * Bind a schema to `{ path }` input and render the complete request path.
441
- *
442
- * @example
443
- * ```ts
444
- * import { Schema } from "effect";
445
- * import { Request } from "viell-effect-schema-http";
446
- * const user = Request.get("").pipe(
447
- * Request.baseUrl("https://api.example.test"),
448
- * Request.path(Schema.NumberFromString, (id, encode) => `/users/${encode(id)}`),
449
- * );
450
- * // Input: { path: 42 }; URL: https://api.example.test/users/42
451
- * ```
452
- *
453
- * @remarks
454
- * The value under `path` has the schema's application type. A scalar schema takes a scalar;
455
- * `Schema.Struct({ userId: Schema.NumberFromString })` takes `{ userId: number }`. Use a struct
456
- * to name one path value or group several. Renderer parameter names do not affect the input type.
457
- *
458
- * The renderer receives the schema-encoded value and the active path-value encoder. Escape each
459
- * dynamic value with that encoder. The returned path replaces the constructor's path; it does
460
- * not append to it. The shared base URL is joined afterwards. Reuse renderer functions for
461
- * nested resources rather than stacking path bindings.
462
- * Renderer or path-encoding exceptions become {@link InvalidRequest}; schema failures remain
463
- * `SchemaError` values.
464
- */
465
- export const path = <S extends Schema.Constraint>(
466
- contract: S,
467
- render: (value: S["Encoded"], encode: UrlEncoding.Service["path"]) => string,
468
- ) => {
469
- const encode = Schema.encodeEffect(contract);
470
- return <I, E, R, H extends boolean, Q extends boolean>(
471
- self: Request<I, E, R, H, Q>,
472
- ): Request<
473
- I & { readonly path: S["Type"] },
474
- E | Schema.SchemaError | InvalidRequest,
475
- R | S["EncodingServices"],
476
- H,
477
- Q
478
- > =>
898
+ /** A renderer: what to add to the path, from the encoded value and the path-value encoder. */
899
+ type PathRenderer<A> = (
900
+ value: A,
901
+ encode: UrlEncoding.Service["path"],
902
+ ) => string;
903
+
904
+ /** Put text after the path so far, exactly as written. */
905
+ const extendPath = (draft: Draft, text: string): Draft => ({
906
+ ...draft,
907
+ request: HttpClientRequest.setUrl(
908
+ draft.request,
909
+ `${draft.request.url}${text}`,
910
+ ),
911
+ });
912
+
913
+ /** Add to the path what `render` makes of the encoded `{ path }` input. */
914
+ const bindPath =
915
+ <In, A, E2, R2>(
916
+ encode: (input: In) => Effect.Effect<A, E2, R2>,
917
+ render: PathRenderer<A>,
918
+ ) =>
919
+ <I, E, R>(
920
+ self: Request<I, E, R>,
921
+ ): Request<I & { readonly path: In }, E | E2 | InvalidRequest, R | R2> =>
479
922
  construct(
480
923
  self.declaration,
481
924
  Effect.fnUntraced(function* (
482
- input: I & { readonly path: S["Type"] },
925
+ input: I & { readonly path: In },
483
926
  draft: Draft,
484
927
  ) {
928
+ if (draft.unbound.has("path")) return yield* self.prepare(input, draft);
485
929
  const encoded = yield* encode(input.path);
486
930
  const encoding = yield* UrlEncoding.UrlEncoding;
487
931
  const prepared = yield* self.prepare(input, draft);
488
- const url = yield* Effect.try({
932
+ const added = yield* Effect.try({
489
933
  try: () => render(encoded, encoding.path),
490
934
  catch: (cause) =>
491
935
  new InvalidRequest({
@@ -493,53 +937,352 @@ export const path = <S extends Schema.Constraint>(
493
937
  cause,
494
938
  }),
495
939
  });
496
- return {
497
- ...prepared,
498
- request: HttpClientRequest.setUrl(prepared.request, url),
499
- };
940
+ return extendPath(prepared, added);
500
941
  }),
501
942
  );
943
+
944
+ /** What a {@link PathValue}'s schema may encode to: one value with an obvious URL text. */
945
+ export type PathScalar = string | number | bigint | boolean;
946
+
947
+ /** A schema that encodes to one {@link PathScalar}, so its value fits in a path. */
948
+ export type PathSchema = Schema.Top &
949
+ Schema.ConstraintCodec<unknown, PathScalar, unknown, unknown>;
950
+
951
+ /**
952
+ * A named value for a {@link path} template.
953
+ *
954
+ * @remarks
955
+ * Declare one with {@link pathValue}. `name` is its field under `path` in the input, and `schema` is
956
+ * what checks and encodes it.
957
+ */
958
+ export interface PathValue<
959
+ K extends string = string,
960
+ S extends PathSchema = PathSchema,
961
+ > {
962
+ readonly name: K;
963
+ readonly schema: S;
964
+ }
965
+
966
+ /**
967
+ * Declare a named value for a {@link path} template.
968
+ *
969
+ * @example
970
+ * ```ts
971
+ * import { Schema } from "effect";
972
+ * import { Request } from "viell-effect-schema-http";
973
+ * const customer = Request.pathValue("customer");
974
+ * const calendar = Request.pathValue("calendar", Schema.FiniteFromString);
975
+ * const getCalendar = Request.get("").pipe(
976
+ * Request.path`/customers/${customer}/calendars/${calendar}`,
977
+ * );
978
+ * // Input: { path: { customer: "a/b", calendar: 7 } }
979
+ * ```
980
+ *
981
+ * @remarks
982
+ * The value arrives under its name in `{ path }`, and without a schema it is a string. A schema has
983
+ * to encode to one {@link PathScalar}, and a value that gets past that type, as under `Schema.Any`,
984
+ * is an {@link InvalidRequest}. The input is an {@link Input} of the schema, so it takes either side.
985
+ * Declare a value once and reuse it across templates and definitions.
986
+ */
987
+ export const pathValue: {
988
+ <const K extends string>(name: K): PathValue<K, typeof Schema.String>;
989
+ <const K extends string, S extends PathSchema>(
990
+ name: K,
991
+ schema: S,
992
+ ): PathValue<K, S>;
993
+ } = (name: string, schema: PathSchema = Schema.String) =>
994
+ ({ name, schema }) as never;
995
+
996
+ /** Add fixed text, which needs no input and cannot fail. */
997
+ const fixedPath =
998
+ (text: string): Edit =>
999
+ (self) =>
1000
+ construct(self.declaration, (input, draft) =>
1001
+ draft.unbound.has("path")
1002
+ ? self.prepare(input, draft)
1003
+ : Effect.map(self.prepare(input, draft), (prepared) =>
1004
+ extendPath(prepared, text),
1005
+ ),
1006
+ );
1007
+
1008
+ const isPathScalar = (value: unknown): value is PathScalar =>
1009
+ ["string", "number", "bigint", "boolean"].includes(typeof value);
1010
+
1011
+ /**
1012
+ * Read one value from a `{ path }` input and write it as text.
1013
+ *
1014
+ * @remarks
1015
+ * A struct takes the one field from a `path` that holds others, and names it in an error. An
1016
+ * optional key or `Schema.Any` gets past the type of {@link PathSchema}, so the value is checked
1017
+ * here rather than written as `undefined` or `[object Object]`.
1018
+ */
1019
+ const pathValueEncoder = ({ name, schema }: PathValue) => {
1020
+ const contract = Schema.Struct({ [name]: schema });
1021
+ const encode = Inputs.encoder(contract, Schema.encodeEffect(contract));
1022
+ return (input: never) =>
1023
+ Effect.flatMap(encode(input), ({ [name]: value }) =>
1024
+ isPathScalar(value)
1025
+ ? Effect.succeed(String(value))
1026
+ : Effect.fail(
1027
+ new InvalidRequest({
1028
+ message: `The path value ${JSON.stringify(name)} did not encode to one value`,
1029
+ }),
1030
+ ),
1031
+ );
502
1032
  };
503
1033
 
1034
+ /** Bind a template: each value goes through its own schema, and its text stays as written. */
1035
+ const templatePath = (
1036
+ text: TemplateStringsArray,
1037
+ values: ReadonlyArray<PathValue>,
1038
+ ) => {
1039
+ const encoders = values.map(pathValueEncoder);
1040
+ return encoders.length === 0
1041
+ ? fixedPath(text.raw[0]!)
1042
+ : bindPath(
1043
+ (input: never) => Effect.forEach(encoders, (encode) => encode(input)),
1044
+ (encoded, encode) =>
1045
+ encoded.reduce(
1046
+ (added, value, index) =>
1047
+ `${added}${encode(value)}${text.raw[index + 1]!}`,
1048
+ text.raw[0]!,
1049
+ ),
1050
+ );
1051
+ };
1052
+
1053
+ const isTemplate = (
1054
+ value: TemplateStringsArray | Schema.Top,
1055
+ ): value is TemplateStringsArray => Array.isArray(value);
1056
+
1057
+ /** Bind a renderer: it receives its schema's encoded value and the path-value encoder. */
1058
+ const renderedPath = <S extends Schema.Top>(
1059
+ contract: S,
1060
+ render: PathRenderer<S["Encoded"]>,
1061
+ ) => bindPath(Inputs.encoder(contract, Schema.encodeEffect(contract)), render);
1062
+
1063
+ /**
1064
+ * Add to the request's path, from a template or from a renderer.
1065
+ *
1066
+ * @example
1067
+ * ```ts
1068
+ * import { Schema } from "effect";
1069
+ * import { Request } from "viell-effect-schema-http";
1070
+ * const customer = Request.pathValue("customer");
1071
+ * const calendar = Request.pathValue("calendar", Schema.FiniteFromString);
1072
+ * const getCalendar = Request.get("").pipe(
1073
+ * Request.baseUrl("https://api.example.test/v1"),
1074
+ * Request.path`/customers/${customer}/calendars/${calendar}`,
1075
+ * );
1076
+ * // Input: { path: { customer: "a/b", calendar: 7 } }
1077
+ * // URL: https://api.example.test/v1/customers/a%2Fb/calendars/7
1078
+ * ```
1079
+ *
1080
+ * @example
1081
+ * ```ts
1082
+ * import { Schema } from "effect";
1083
+ * import { Request } from "viell-effect-schema-http";
1084
+ * const listFolder = Request.get("/files").pipe(
1085
+ * Request.path(Schema.String, (folder, encode) =>
1086
+ * folder === "" ? "/" : `/${folder.split("/").map(encode).join("/")}/`,
1087
+ * ),
1088
+ * );
1089
+ * // Input: { path: "a b/c" }; URL: /files/a%20b/c/
1090
+ * ```
1091
+ *
1092
+ * @remarks
1093
+ * The path is the constructor's path followed by what each `path` call adds, in order, joined
1094
+ * exactly as written. The library adds no `/` and removes none, so `/users` and `42` make
1095
+ * `/users42`, and `/users/` and `/42` make `/users//42`. The base URL is joined afterwards. A `?` or
1096
+ * `#` in the text is URL syntax, so a `#` starts the fragment for all that follows it. A fragment
1097
+ * moves to the compiled request's `hash`, so the query still goes before it. The result is passed
1098
+ * to the client as written, and the client may rewrite or refuse it.
1099
+ *
1100
+ * Use a template when the path has a fixed shape. Only a {@link pathValue} can go in one, so each
1101
+ * value has its schema and always goes through the active `UrlEncoding` path encoder, and a run-time
1102
+ * string is a compile error. A template with no values adds fixed text. The text is used as written
1103
+ * and never parsed, so a backslash is a backslash and not an escape. Stacked templates add their
1104
+ * fields to one `path` input, and a name used more than once gets the same value.
1105
+ *
1106
+ * Use a renderer when the shape of the path depends on the value, such as a value holding several
1107
+ * segments or a whole URL. It receives the schema-encoded value and the active path-value encoder,
1108
+ * and escaping each dynamic value is up to it. The value under `path` is an {@link Input} of the
1109
+ * schema, so a scalar schema takes a scalar and a struct takes its fields. A scalar is one value for
1110
+ * the whole `path`, so it does not stack with another scalar of a different type or with a template.
1111
+ *
1112
+ * Encoding does not make a value safe. A `/` in a value cannot add a segment, but `..` and an empty
1113
+ * string have nothing to encode, and the client may resolve a dot segment. Constrain a value from a
1114
+ * user in its schema.
1115
+ *
1116
+ * {@link unbind} removes what earlier calls added, and {@link setPath} replaces the constructor's
1117
+ * text. Renderer or path-encoding exceptions become {@link InvalidRequest}; schema failures remain
1118
+ * `SchemaError` values.
1119
+ */
1120
+ export const path: {
1121
+ (text: TemplateStringsArray): Edit;
1122
+ <const V extends readonly [PathValue, ...ReadonlyArray<PathValue>]>(
1123
+ text: TemplateStringsArray,
1124
+ ...values: V
1125
+ ): <I, E, R>(
1126
+ self: Request<I, E, R>,
1127
+ ) => Request<
1128
+ I & {
1129
+ readonly path: {
1130
+ readonly [P in V[number] as P["name"]]: Input<P["schema"]>;
1131
+ };
1132
+ },
1133
+ E | Schema.SchemaError | InvalidRequest,
1134
+ | R
1135
+ | V[number]["schema"]["EncodingServices"]
1136
+ | V[number]["schema"]["DecodingServices"]
1137
+ >;
1138
+ <S extends Schema.Top>(
1139
+ contract: S,
1140
+ render: (
1141
+ value: S["Encoded"],
1142
+ encode: UrlEncoding.Service["path"],
1143
+ ) => string,
1144
+ ): <I, E, R>(
1145
+ self: Request<I, E, R>,
1146
+ ) => Request<
1147
+ I & { readonly path: Input<S> },
1148
+ E | Schema.SchemaError | InvalidRequest,
1149
+ R | S["EncodingServices"] | S["DecodingServices"]
1150
+ >;
1151
+ } = (
1152
+ first: TemplateStringsArray | Schema.Top,
1153
+ ...rest: ReadonlyArray<PathValue> | readonly [PathRenderer<never>]
1154
+ ) =>
1155
+ (isTemplate(first)
1156
+ ? templatePath(first, rest as ReadonlyArray<PathValue>)
1157
+ : renderedPath(first, rest[0] as PathRenderer<unknown>)) as never;
1158
+
1159
+ /**
1160
+ * Replace the constructor's path, leaving every {@link path} binding in place.
1161
+ *
1162
+ * @example
1163
+ * ```ts
1164
+ * import { Request } from "viell-effect-schema-http";
1165
+ * const id = Request.pathValue("id");
1166
+ * const current = Request.get("/things").pipe(Request.path`/${id}`);
1167
+ * const legacy = current.pipe(Request.setPath("/legacy/things"));
1168
+ * // Input: { path: { id: "a" } }; URL: /legacy/things/a
1169
+ * ```
1170
+ *
1171
+ * @remarks
1172
+ * Only the path changes. A constructor's query and fragment stay, and a `?` or `#` in this text is
1173
+ * URL text, as it is in {@link path}. To replace a whole path, use {@link unbind} and this together.
1174
+ */
1175
+ export const setPath =
1176
+ (url: string): Edit =>
1177
+ (self) =>
1178
+ construct({ ...self.declaration, url }, self.prepare);
1179
+
504
1180
  /**
505
1181
  * Bind an encoder to the call's `{ body }` input.
506
1182
  *
507
1183
  * @remarks
508
- * The body is encoded once per operation evaluation. Its encoder determines `Content-Type` and
509
- * `Content-Length`; multipart metadata is supplied by the transport.
1184
+ * The body is encoded once per operation evaluation. Its encoder supplies `Content-Type` and
1185
+ * `Content-Length`; multipart metadata is supplied by the transport. A value the request declares
1186
+ * for either field wins, before or after this binding, and {@link removeHeader} stops the automatic
1187
+ * value. Neither changes the encoded bytes.
1188
+ *
1189
+ * Any method can carry a body, and the library adds no check of its own. A client can refuse the
1190
+ * request: `fetch` does so for GET and HEAD, which surfaces as a transport failure.
510
1191
  */
511
1192
  export const body =
512
1193
  <A, E2, R2>(codec: Body.Encoder<A, E2, R2>) =>
513
- <I, E, R, H extends boolean, Q extends boolean>(
514
- self: Request<I, E, R, H, Q>,
515
- ): Request<I & { readonly body: A }, E | E2, R | R2, H, Q> =>
1194
+ <I, E, R>(
1195
+ self: Request<I, E, R>,
1196
+ ): Request<I & { readonly body: A }, E | E2, R | R2> =>
516
1197
  construct(
517
1198
  self.declaration,
518
1199
  Effect.fnUntraced(function* (
519
1200
  input: I & { readonly body: A },
520
1201
  draft: Draft,
521
1202
  ) {
1203
+ if (draft.unbound.has("body")) return yield* self.prepare(input, draft);
522
1204
  const encoded = yield* codec.encode(input.body);
523
1205
  const prepared = yield* self.prepare(input, draft);
524
1206
  return {
525
1207
  ...prepared,
526
- request: HttpClientRequest.setBody(prepared.request, encoded),
1208
+ request: applyDeclaredBodyFields(
1209
+ HttpClientRequest.setBody(prepared.request, encoded),
1210
+ prepared,
1211
+ ),
527
1212
  };
528
1213
  }),
529
1214
  );
530
1215
 
1216
+ /**
1217
+ * A request's input once {@link unbind} has cleared a group: the same, without that property.
1218
+ *
1219
+ * @remarks
1220
+ * An input left with no properties becomes `unknown`, so `undefined` satisfies it.
1221
+ */
1222
+ export type Unbound<I, K extends Group> = K extends keyof I
1223
+ ? [keyof Omit<I, K>] extends [never]
1224
+ ? unknown
1225
+ : Omit<I, K>
1226
+ : I;
1227
+
1228
+ /**
1229
+ * Remove a group's earlier bindings, their input and the shape they state.
1230
+ *
1231
+ * @example
1232
+ * ```ts
1233
+ * import { Schema } from "effect";
1234
+ * import { Request } from "viell-effect-schema-http";
1235
+ * const paged = Request.get("https://api.example.test/things").pipe(
1236
+ * Request.query(Schema.Struct({ page: Schema.FiniteFromString })),
1237
+ * );
1238
+ * const sorted = paged.pipe(
1239
+ * Request.unbind("query"),
1240
+ * Request.query(Schema.Struct({ sort: Schema.String })),
1241
+ * );
1242
+ * // Input: { query: { sort: "name" } }; URL query: ?sort=name
1243
+ * ```
1244
+ *
1245
+ * @remarks
1246
+ * Takes `"path"`, `"query"`, `"headers"` or `"body"`, and affects only bindings before it. To
1247
+ * replace a binding, unbind the group and bind again. Raw declarations stay, and go out unchecked
1248
+ * once no schema states the group's shape. A constructor path and query are declarations, so they
1249
+ * stay too. For `"path"`, the text of earlier {@link path} calls goes with their values, and
1250
+ * {@link setPath} is what changes the constructor's path.
1251
+ *
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.
1255
+ */
1256
+ export const unbind =
1257
+ <K extends Group>(group: K) =>
1258
+ <I, E, R>(self: Request<I, E, R>): Request<Unbound<I, K>, E, R> =>
1259
+ construct(
1260
+ {
1261
+ ...self.declaration,
1262
+ headerShapes: group === "headers" ? [] : self.declaration.headerShapes,
1263
+ queryShapes: group === "query" ? [] : self.declaration.queryShapes,
1264
+ conflicts: self.declaration.conflicts.filter(
1265
+ ([owner]) => owner !== group,
1266
+ ),
1267
+ },
1268
+ (input, draft) =>
1269
+ self.prepare(input as I, {
1270
+ ...draft,
1271
+ unbound: new Set([...draft.unbound, group]),
1272
+ }),
1273
+ );
1274
+
531
1275
  /**
532
1276
  * Adapt your application's argument to this request's required input.
533
1277
  *
534
1278
  * @remarks
535
1279
  * Use it to rename fields or supply defaults while preserving schema validation. The mapping
536
- * runs during preparation; a thrown exception is a defect.
1280
+ * runs during preparation; a thrown exception is a defect. It returns the request's whole input,
1281
+ * which {@link InputOf} names.
537
1282
  */
538
1283
  export const mapInput =
539
1284
  <I, I2>(f: (input: I2) => I) =>
540
- <E, R, H extends boolean, Q extends boolean>(
541
- self: Request<I, E, R, H, Q>,
542
- ): Request<I2, E, R, H, Q> =>
1285
+ <E, R>(self: Request<I, E, R>): Request<I2, E, R> =>
543
1286
  construct(self.declaration, (input, draft) =>
544
1287
  Effect.suspend(() => self.prepare(f(input), draft)),
545
1288
  );
@@ -554,7 +1297,8 @@ export const mapInput =
554
1297
  * applies afterwards.
555
1298
  *
556
1299
  * A transform can be reused on requests whose input contains what its function reads. Inline
557
- * callbacks in `pipe` infer their input from the request.
1300
+ * callbacks in `pipe` infer their input from the request. This is the deliberate way around a
1301
+ * group's schemas: what it edits on the native request is outside their check.
558
1302
  */
559
1303
  export const mapEffect =
560
1304
  <I, E2, R2>(
@@ -563,9 +1307,9 @@ export const mapEffect =
563
1307
  input: I,
564
1308
  ) => Effect.Effect<HttpClientRequest.HttpClientRequest, E2, R2>,
565
1309
  ) =>
566
- <E, R, H extends boolean, Q extends boolean, I2 extends I = I>(
567
- self: Request<I, E, R, H, Q> | Request<I2, E, R, H, Q>,
568
- ): Request<I2, E | E2, R | R2, H, Q> =>
1310
+ <E, R, I2 extends I = I>(
1311
+ self: Request<I, E, R> | Request<I2, E, R>,
1312
+ ): Request<I2, E | E2, R | R2> =>
569
1313
  construct(self.declaration, (input: I2, draft) =>
570
1314
  Effect.flatMap(self.prepare(input, draft), (prepared) =>
571
1315
  Effect.map(f(prepared.request, input), (request) => ({
@@ -577,10 +1321,15 @@ export const mapEffect =
577
1321
 
578
1322
  /**
579
1323
  * A prepared native request and the header lines a supporting provider can send.
1324
+ *
1325
+ * @remarks
1326
+ * `request.url` holds the joined URL and its query. A fragment is in `request.hash`, as written.
580
1327
  */
581
1328
  export interface Compiled {
582
1329
  readonly request: HttpClientRequest.HttpClientRequest;
583
1330
  readonly headerLines: Transport.Lines;
1331
+ /** Lowercase header names the request removed, so the library adds no automatic value. */
1332
+ readonly removedHeaders: ReadonlySet<string>;
584
1333
  }
585
1334
 
586
1335
  const initialDraft = (declaration: Declaration): Draft => {
@@ -592,47 +1341,126 @@ const initialDraft = (declaration: Declaration): Draft => {
592
1341
  return replaceQuery(
593
1342
  {
594
1343
  request: HttpClientRequest.setHeaders(
595
- native,
1344
+ // An empty fragment counts, and the options of `make` would skip it.
1345
+ declaration.hash === undefined
1346
+ ? native
1347
+ : HttpClientRequest.setHash(native, declaration.hash),
596
1348
  Transport.toHeaders(headerLines),
597
1349
  ),
598
1350
  headerLines,
599
1351
  bareKeys: new Set(),
1352
+ queryText: new Map(),
1353
+ declaredQuery: new Set(),
1354
+ removedHeaders: declaration.removedHeaders,
1355
+ unbound: new Set(),
600
1356
  },
601
- Fields.resolve(declaration.query),
1357
+ declaration.query.flatMap((field) =>
1358
+ Fields.resolve([field]).map(
1359
+ ([key, value]) => [key, value, field[2]] as const,
1360
+ ),
1361
+ ),
602
1362
  );
603
1363
  };
604
1364
 
1365
+ /**
1366
+ * Render query entries in order. Written text stays as it is, and each run of entries between it
1367
+ * goes through the encoder. With no entries at all, the encoder still has its say.
1368
+ */
1369
+ const renderQuery = (draft: Draft, encoding: UrlEncoding.Service): string => {
1370
+ const parts: Array<string> = [];
1371
+ let run: Array<readonly [string, string | null]> = [];
1372
+ const endRun = () => {
1373
+ const rendered = run.length === 0 ? "" : encoding.query(run);
1374
+ if (rendered !== "") parts.push(rendered);
1375
+ run = [];
1376
+ };
1377
+ for (const param of draft.request.urlParams.params) {
1378
+ const written = draft.queryText.get(param);
1379
+ if (written !== undefined) {
1380
+ endRun();
1381
+ parts.push(written);
1382
+ } else {
1383
+ run.push([param[0], queryValue(draft, param)]);
1384
+ }
1385
+ }
1386
+ endRun();
1387
+ return parts.length === 0 ? encoding.query([]) : parts.join("&");
1388
+ };
1389
+
605
1390
  const finalize = (
606
1391
  draft: Draft,
607
- base: string,
1392
+ declaration: Declaration,
1393
+ baseText: string,
608
1394
  encoding: UrlEncoding.Service,
609
1395
  ): Compiled => {
610
1396
  const { request } = draft;
611
- const url = encoding.join(base, request.url);
612
- const search = encoding.query(
613
- request.urlParams.params.map((param) => [
614
- param[0],
615
- draft.bareKeys.has(param)
616
- ? null
617
- : Redacted.isRedacted(param[1])
618
- ? Redacted.value(param[1])
619
- : param[1],
620
- ]),
621
- );
1397
+ const [base, baseFragment] = splitFragment(baseText);
1398
+ const [target, targetFragment] = splitFragment(request.url);
1399
+ const [url, joinFragment] = splitFragment(encoding.join(base, target));
1400
+ const search = renderQuery(draft, encoding);
1401
+ const separator = url.includes("?") ? "&" : "?";
622
1402
  const compiled = HttpClientRequest.makeWith(
623
1403
  request.method,
624
- search === "" ? url : `${url}${url.includes("?") ? "&" : "?"}${search}`,
1404
+ search !== ""
1405
+ ? `${url}${separator}${search}`
1406
+ : declaration.emptyQuery && separator === "?"
1407
+ ? `${url}?`
1408
+ : url,
625
1409
  UrlParams.empty,
626
- request.hash,
1410
+ Option.orElse(request.hash, () =>
1411
+ Option.fromUndefinedOr(targetFragment ?? baseFragment ?? joinFragment),
1412
+ ),
627
1413
  request.headers,
628
1414
  request.body,
629
1415
  );
630
1416
  return {
631
1417
  request: compiled,
632
1418
  headerLines: Transport.reconcile(draft.headerLines, compiled.headers),
1419
+ removedHeaders: draft.removedHeaders,
633
1420
  };
634
1421
  };
635
1422
 
1423
+ /** Why a request's fields cannot be built against their schemas, by name and never by value. */
1424
+ const fieldProblems = (
1425
+ declaration: Declaration,
1426
+ draft: Draft,
1427
+ ): ReadonlyArray<string> =>
1428
+ (
1429
+ [
1430
+ [
1431
+ "query",
1432
+ draft.request.urlParams.params
1433
+ .filter((param) => !isEmptySegment(draft, param))
1434
+ .map(([name]) => name),
1435
+ declaration.queryShapes,
1436
+ foldQuery,
1437
+ ],
1438
+ [
1439
+ "headers",
1440
+ draft.headerLines.map(([name]) => name),
1441
+ declaration.headerShapes,
1442
+ foldHeader,
1443
+ ],
1444
+ ] as const
1445
+ ).flatMap(([group, names, shapes, fold]) => {
1446
+ const conflicts = declaration.conflicts
1447
+ .filter(([owner]) => owner === group)
1448
+ .map(([, name]) => name);
1449
+ const stray = Shapes.outside(names, shapes, fold);
1450
+ return [
1451
+ ...(conflicts.length === 0
1452
+ ? []
1453
+ : [
1454
+ `A schema bound to the ${group} group always writes these names, so a raw edit could never reach the client: ${listNames(conflicts)}. Supply the value as input, set it with Request.mapInput, or use Request.unbind("${group}") first.`,
1455
+ ]),
1456
+ ...(stray.length === 0
1457
+ ? []
1458
+ : [
1459
+ `No schema bound to the ${group} group allows these declared names: ${listNames(stray)}. Add them to a schema, remove them, or use Request.unbind("${group}") first.`,
1460
+ ]),
1461
+ ];
1462
+ });
1463
+
636
1464
  /**
637
1465
  * Prepare a request and its header lines without sending it.
638
1466
  *
@@ -647,18 +1475,14 @@ const finalize = (
647
1475
  * ```
648
1476
  *
649
1477
  * @remarks
650
- * Each evaluation resolves computed fields and encodes input once. The returned Effect requires
651
- * any services used by the input schemas or preparation. Use {@link materialize} when only the
652
- * native request is needed.
1478
+ * Each evaluation resolves computed fields, encodes input and resolves the base URL once, in that
1479
+ * order. The returned Effect requires any services used by the input schemas, preparation or the
1480
+ * base URL. A declared field that does not fit the schemas bound to its group fails here with
1481
+ * {@link InvalidRequest}, whatever the input. Use {@link materialize} when only the native request
1482
+ * is needed.
653
1483
  */
654
- export const compile = Effect.fnUntraced(function* <
655
- I,
656
- E,
657
- R,
658
- H extends boolean,
659
- Q extends boolean,
660
- >(
661
- self: Request<I, E, R, H, Q>,
1484
+ export const compile = Effect.fnUntraced(function* <I, E, R>(
1485
+ self: Request<I, E, R>,
662
1486
  input: I,
663
1487
  ): Effect.fn.Return<Compiled, E | InvalidRequest, R> {
664
1488
  const encoding = yield* UrlEncoding.UrlEncoding;
@@ -670,18 +1494,18 @@ export const compile = Effect.fnUntraced(function* <
670
1494
  cause,
671
1495
  }),
672
1496
  });
1497
+ const problems = fieldProblems(self.declaration, initial);
1498
+ if (problems.length > 0)
1499
+ return yield* new InvalidRequest({ message: problems.join(" ") });
673
1500
  const draft = yield* self.prepare(input, initial);
674
- const { method } = draft.request;
675
- if (
676
- (method === "GET" || method === "HEAD") &&
677
- draft.request.body._tag !== "Empty"
678
- ) {
679
- return yield* new InvalidRequest({
680
- message: `${method} cannot carry a request body`,
681
- });
682
- }
1501
+ // Only `baseUrl` and `mapBaseUrl` set an Effect, and what it needs is already in `E` and `R`.
1502
+ const baseText = yield* resolveBaseUrl(self.declaration) as Effect.Effect<
1503
+ string,
1504
+ E | InvalidRequest,
1505
+ R
1506
+ >;
683
1507
  return yield* Effect.try({
684
- try: () => finalize(draft, self.declaration.baseUrl, encoding),
1508
+ try: () => finalize(draft, self.declaration, baseText, encoding),
685
1509
  catch: (cause) =>
686
1510
  new InvalidRequest({ message: "Failed to encode request URL", cause }),
687
1511
  });
@@ -693,8 +1517,8 @@ export const compile = Effect.fnUntraced(function* <
693
1517
  * @remarks
694
1518
  * Use {@link compile} to retain the original header-line representation as well.
695
1519
  */
696
- export const materialize = <I, E, R, H extends boolean, Q extends boolean>(
697
- self: Request<I, E, R, H, Q>,
1520
+ export const materialize = <I, E, R>(
1521
+ self: Request<I, E, R>,
698
1522
  input: I,
699
1523
  ): Effect.Effect<HttpClientRequest.HttpClientRequest, E | InvalidRequest, R> =>
700
1524
  Effect.map(compile(self, input), (compiled) => compiled.request);