viell-effect-schema-http 0.1.0 → 0.3.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 (56) hide show
  1. package/README.md +44 -29
  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 +25 -13
  6. package/dist/http/Body.d.ts.map +1 -1
  7. package/dist/http/Body.js +18 -8
  8. package/dist/http/Body.js.map +1 -1
  9. package/dist/http/Operation.d.ts +276 -13
  10. package/dist/http/Operation.d.ts.map +1 -1
  11. package/dist/http/Operation.js +210 -11
  12. package/dist/http/Operation.js.map +1 -1
  13. package/dist/http/Policy.d.ts +28 -2
  14. package/dist/http/Policy.d.ts.map +1 -1
  15. package/dist/http/Policy.js +28 -2
  16. package/dist/http/Policy.js.map +1 -1
  17. package/dist/http/Request.d.ts +520 -85
  18. package/dist/http/Request.d.ts.map +1 -1
  19. package/dist/http/Request.js +658 -143
  20. package/dist/http/Request.js.map +1 -1
  21. package/dist/http/Response.d.ts +130 -6
  22. package/dist/http/Response.d.ts.map +1 -1
  23. package/dist/http/Response.js +88 -7
  24. package/dist/http/Response.js.map +1 -1
  25. package/dist/http/UrlEncoding.d.ts +24 -7
  26. package/dist/http/UrlEncoding.d.ts.map +1 -1
  27. package/dist/http/UrlEncoding.js +7 -3
  28. package/dist/http/UrlEncoding.js.map +1 -1
  29. package/dist/http/internal/excess.d.ts +44 -0
  30. package/dist/http/internal/excess.d.ts.map +1 -0
  31. package/dist/http/internal/excess.js +231 -0
  32. package/dist/http/internal/excess.js.map +1 -0
  33. package/dist/http/internal/fields.d.ts +17 -4
  34. package/dist/http/internal/fields.d.ts.map +1 -1
  35. package/dist/http/internal/fields.js +11 -6
  36. package/dist/http/internal/fields.js.map +1 -1
  37. package/dist/http/internal/input.d.ts +70 -0
  38. package/dist/http/internal/input.d.ts.map +1 -0
  39. package/dist/http/internal/input.js +93 -0
  40. package/dist/http/internal/input.js.map +1 -0
  41. package/dist/http/internal/shape.d.ts +63 -0
  42. package/dist/http/internal/shape.d.ts.map +1 -0
  43. package/dist/http/internal/shape.js +225 -0
  44. package/dist/http/internal/shape.js.map +1 -0
  45. package/package.json +13 -12
  46. package/src/concurrency/Interaction.ts +7 -1
  47. package/src/http/Body.ts +41 -18
  48. package/src/http/Operation.ts +474 -33
  49. package/src/http/Policy.ts +30 -2
  50. package/src/http/Request.ts +1176 -253
  51. package/src/http/Response.ts +246 -23
  52. package/src/http/UrlEncoding.ts +32 -8
  53. package/src/http/internal/excess.ts +333 -0
  54. package/src/http/internal/fields.ts +37 -9
  55. package/src/http/internal/input.ts +228 -0
  56. package/src/http/internal/shape.ts +359 -0
@@ -1,50 +1,74 @@
1
- import { Data, Effect, Pipeable, Redacted, Schema } from "effect";
1
+ import { Data, Effect, Option, Pipeable, Redacted, Schema } from "effect";
2
2
  import { Headers, HttpClientRequest, UrlParams, } from "effect/http";
3
3
  import * as Fields from "./internal/fields.js";
4
+ import * as Inputs from "./internal/input.js";
5
+ import * as Shapes from "./internal/shape.js";
4
6
  import * as Transport from "./Transport.js";
5
7
  import * as UrlEncoding from "./UrlEncoding.js";
6
8
  /**
7
9
  * Request preparation failed before dispatch.
8
10
  *
9
11
  * @remarks
10
- * Covers computed-field failures, URL-rendering exceptions, and a GET/HEAD body other than
11
- * `HttpBody.empty`. Schema encoding failures remain separate `SchemaError` values.
12
+ * Covers computed-field failures, URL-rendering and {@link mapBaseUrl} exceptions, a path value
13
+ * that does not encode to one value, and fields that do not fit the schemas bound to their group.
14
+ * Schema failures of the caller's input remain separate `SchemaError` values.
15
+ * A failed check of a group names its fields and leaves out their values, which may be credentials.
12
16
  */
13
17
  export class InvalidRequest extends Data.TaggedError("InvalidRequest") {
14
18
  }
15
19
  const construct = (declaration, prepare) => ({ ...Pipeable.Prototype, declaration, prepare });
20
+ /** Split URL text at its first `#`, which ends the path and query. */
21
+ const splitFragment = (url) => {
22
+ const position = url.indexOf("#");
23
+ return position < 0
24
+ ? [url, undefined]
25
+ : [url.slice(0, position), url.slice(position + 1)];
26
+ };
27
+ /** A written empty segment is text with no name, so it is not a field a schema could allow. */
28
+ const isEmptySegment = (draft, param) => draft.queryText.get(param) === "";
29
+ /** Read one written query segment as an entry that keeps its text. */
30
+ const readSegment = (segment) => {
31
+ // URLSearchParams strips one leading query marker; a marker in the key is data. An empty segment
32
+ // yields no pair, so its name is the empty string.
33
+ const [[key, value] = ["", ""]] = new URLSearchParams(`?${segment}`);
34
+ return [key, segment.includes("=") ? value : null, segment];
35
+ };
16
36
  /**
17
37
  * Describe a request with a method and URL, without sending it.
18
38
  *
19
39
  * @remarks
20
40
  * Use `undefined` as input until a binding adds required fields. A relative path can be combined
21
- * with {@link baseUrl}; {@link path} can supply the complete path from typed input.
22
- * Custom method strings pass through unchanged.
41
+ * with {@link baseUrl}, and {@link path} adds to it, so `""` starts a path written whole in a
42
+ * template. Custom method strings pass through unchanged.
43
+ *
44
+ * A constructor query is passed to the client as written until something edits that entry, so
45
+ * `?a=1;b=2`, `?q=a+b` and `?a=%41` keep their spelling, as do empty `&` segments and a lone `?`.
46
+ * Each entry also has a form-decoded name and value, which {@link setQuery} and {@link removeQuery}
47
+ * compare against. An entry that is edited, or added, is rendered through `UrlEncoding.query`. An
48
+ * entry under a name a {@link query} schema allows goes through that schema, and one under a name
49
+ * no bound schema allows is an incompatible shape. A written empty segment has no name, so it is
50
+ * not a field, and it stays as written.
23
51
  *
24
- * A constructor query is parsed as form data: `+` becomes a space, percent escapes are decoded,
25
- * and empty `&` segments are dropped. Bare keys remain distinct from empty values. Compilation
26
- * renders these entries through `UrlEncoding.query`; a constructor fragment is discarded.
52
+ * A fragment stays on the request, exactly as written, in the native request's `hash` field. It
53
+ * survives {@link path} and query edits, and wins over a fragment in path output or a base URL.
54
+ * Whether it goes out is up to the client; `fetch` does not send one.
27
55
  */
28
56
  export const make = (method, url) => {
29
- const hash = url.indexOf("#");
30
- const withoutHash = hash < 0 ? url : url.slice(0, hash);
57
+ const [withoutHash, hash] = splitFragment(url);
31
58
  const start = withoutHash.indexOf("?");
32
- const query = [];
33
- if (start >= 0) {
34
- for (const segment of withoutHash.slice(start + 1).split("&")) {
35
- // URLSearchParams strips one leading query marker; a marker in the key is data.
36
- for (const [key, value] of new URLSearchParams(`?${segment}`))
37
- query.push([key, segment.includes("=") ? value : null]);
38
- }
39
- }
59
+ const written = start < 0 ? "" : withoutHash.slice(start + 1);
40
60
  return construct({
41
61
  method,
42
62
  url: start < 0 ? withoutHash : withoutHash.slice(0, start),
63
+ hash,
43
64
  baseUrl: "",
44
65
  headers: [],
45
- query,
46
- headersBound: false,
47
- queryBound: false,
66
+ query: written === "" ? [] : written.split("&").map(readSegment),
67
+ emptyQuery: start >= 0 && written === "",
68
+ removedHeaders: new Set(),
69
+ headerShapes: [],
70
+ queryShapes: [],
71
+ conflicts: [],
48
72
  }, (_, draft) => Effect.succeed(draft));
49
73
  };
50
74
  /**
@@ -76,7 +100,7 @@ export const patch = (url) => make("PATCH", url);
76
100
  */
77
101
  export const del = (url) => make("DELETE", url);
78
102
  /**
79
- * Describe a HEAD request. Its outgoing body must remain `HttpBody.empty`.
103
+ * Describe a HEAD request. A {@link body} is passed on as for any method; the client may refuse it.
80
104
  */
81
105
  export const head = (url) => make("HEAD", url);
82
106
  /**
@@ -84,7 +108,7 @@ export const head = (url) => make("HEAD", url);
84
108
  */
85
109
  export const options = (url) => make("OPTIONS", url);
86
110
  /**
87
- * Set the shared origin and fixed path prefix for a request.
111
+ * Set the shared origin and fixed path prefix for a request, as text or from an Effect.
88
112
  *
89
113
  * @example
90
114
  * ```ts
@@ -94,68 +118,208 @@ export const options = (url) => make("OPTIONS", url);
94
118
  * const teams = Request.get("/teams").pipe(api);
95
119
  * ```
96
120
  *
121
+ * @example
122
+ * ```ts
123
+ * import { Context, Effect } from "effect";
124
+ * import { Request } from "viell-effect-schema-http";
125
+ * class ApiHost extends Context.Service<ApiHost, string>()("app/ApiHost") {}
126
+ * const discovered = Effect.gen(function* () {
127
+ * const host = yield* ApiHost;
128
+ * return `https://${host}/api/v1`;
129
+ * });
130
+ * const users = Request.get("/users").pipe(Request.baseUrl(discovered));
131
+ * // The request needs ApiHost, as it would need any other service.
132
+ * ```
133
+ *
97
134
  * @remarks
98
135
  * The base is joined after path preparation. With the default URL policy, an absolute request
99
136
  * URL bypasses it; a leading `/` on a relative path keeps the base's prefix. Calling this again
100
- * replaces the base, rather than appending to it. Keep query fields in request combinators.
137
+ * replaces the base, rather than appending to it, and {@link mapBaseUrl} extends it. Keep query
138
+ * fields in request combinators. A fragment in the base is taken off before joining and used if the
139
+ * request has none of its own.
140
+ *
141
+ * An Effect supplies a location that is not known when the request is defined, from a service or a
142
+ * `Config` value, say. Its failures and services join the request's type, so leaving out a service
143
+ * is a compile error. It runs once per evaluation, after the input is encoded and before any
144
+ * attempt, so every retry uses the same base. Its failure is returned as it is, before anything is
145
+ * sent, and a retry policy does not repeat it. What it supplies is treated exactly as text would
146
+ * be, including by a replaced `UrlEncoding.join`.
147
+ *
148
+ * A location that must change between attempts belongs in `Operation.make`'s `transformClient`. A
149
+ * base that is replaced never runs, though the request's types keep what it added.
101
150
  */
102
151
  export const baseUrl = (url) => (self) => construct({ ...self.declaration, baseUrl: url }, self.prepare);
103
- const editHeaders = (edit) => (self) => construct({ ...self.declaration, headers: edit(self.declaration.headers) }, self.prepare);
104
- const editQuery = (edit) => (self) => construct({ ...self.declaration, query: edit(self.declaration.query) }, self.prepare);
152
+ /** A request's base URL as an Effect, whichever form it was declared in. */
153
+ const resolveBaseUrl = ({ baseUrl: url }) => typeof url === "string" ? Effect.succeed(url) : url;
105
154
  /**
106
- * Set a raw header, replacing every existing line with that name.
155
+ * Change the base URL, whether it is text or an Effect, to extend a prefix or swap part of it.
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * import { Request } from "viell-effect-schema-http";
160
+ * const api = Request.baseUrl("https://api.example.test/api/v1");
161
+ * const toAdmin = (url: string) => `${url}/admin`;
162
+ * const admin = Request.mapBaseUrl(toAdmin);
163
+ * const listUsers = Request.get("/users").pipe(api, admin);
164
+ * // https://api.example.test/api/v1/admin/users
165
+ * ```
166
+ *
167
+ * @remarks
168
+ * Use it where a request holds a base you cannot read, as an imported definition does, or one that
169
+ * is not known yet. `f` runs during preparation, once per evaluation, and receives the base as it
170
+ * stands at this step, so `""` where none is set. That is the whole text, including any query or
171
+ * fragment in it, and what `f` returns is joined exactly as a base from {@link baseUrl} would be. A
172
+ * later {@link baseUrl} replaces the result. An exception from `f` is an {@link InvalidRequest}.
173
+ */
174
+ export const mapBaseUrl = (f) => (self) => construct({
175
+ ...self.declaration,
176
+ baseUrl: Effect.flatMap(resolveBaseUrl(self.declaration), (url) => Effect.try({
177
+ try: () => f(url),
178
+ catch: (cause) => new InvalidRequest({
179
+ message: "Failed to map the request's base URL",
180
+ cause,
181
+ }),
182
+ })),
183
+ }, self.prepare);
184
+ /** Header names compare without case; each line keeps the spelling it was given. */
185
+ const foldHeader = (name) => name.toLowerCase();
186
+ /** Query names compare exactly. */
187
+ const foldQuery = (name) => name;
188
+ const editHeaders = (edited, edit, removed = (names) => names) => (self) => construct({
189
+ ...self.declaration,
190
+ headers: edit(self.declaration.headers),
191
+ removedHeaders: removed(self.declaration.removedHeaders),
192
+ conflicts: [
193
+ ...self.declaration.conflicts,
194
+ ...Shapes.required(edited, self.declaration.headerShapes, foldHeader).map((name) => ["headers", name]),
195
+ ],
196
+ }, self.prepare);
197
+ const editQuery = (names, edit) => (self) => construct({
198
+ ...self.declaration,
199
+ query: edit(self.declaration.query),
200
+ conflicts: [
201
+ ...self.declaration.conflicts,
202
+ ...Shapes.required(names, self.declaration.queryShapes, foldQuery).map((name) => ["query", name]),
203
+ ],
204
+ }, self.prepare);
205
+ /**
206
+ * Set a raw header, replacing every existing line with that name, or set several from an object.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * import { Request } from "viell-effect-schema-http";
211
+ * const request = Request.get("https://api.example.test/things").pipe(
212
+ * Request.setHeader("X-One", "1"),
213
+ * Request.setHeader({ "X-Two": "2", "X-Three": () => "3" }),
214
+ * );
215
+ * ```
107
216
  *
108
217
  * @remarks
109
- * Names compare without case and are stored lowercase. Unavailable after a header schema is
110
- * bound. The body encoder owns `Content-Type` and `Content-Length`.
218
+ * Names compare without case, and the new line keeps the spelling of this call. A declared
219
+ * `Accept`, `Content-Type` or `Content-Length` replaces the automatic value, before or after the
220
+ * body.
221
+ *
222
+ * With a {@link headers} schema bound, in either order, the name has to be one a schema allows, and
223
+ * the value is a default that goes through the schema. Setting a name the schema always writes,
224
+ * after that schema, is an {@link InvalidRequest}, because the value could never reach the client.
225
+ *
226
+ * In the object form each key replaces its name as above, in key order, and other names stay. A key
227
+ * set to `undefined` removes that name's declarations and stops no automatic value, which is what
228
+ * {@link removeHeader} is for.
111
229
  */
112
- export const setHeader = (name, value) => editHeaders((fields) => Fields.set(fields, name.toLowerCase(), value));
230
+ export const setHeader = (first, value) => {
231
+ const entries = typeof first === "string"
232
+ ? [[first, value]]
233
+ : Object.entries(first);
234
+ return editHeaders(entries.map(([name]) => name), (fields) => entries.reduce((result, [name, entry]) => Fields.replace(result, name, entry === undefined ? [] : [entry], foldHeader), fields));
235
+ };
113
236
  /**
114
237
  * Add a raw header line after the existing lines, preserving repetition.
115
238
  *
116
239
  * @remarks
117
- * Names are stored lowercase. Unavailable after a header schema is bound. Sending separate
118
- * lines requires a provider that supports them; Fetch may combine or restrict headers.
240
+ * Each line keeps the spelling of its call. A bound {@link headers} schema checks it as it does
241
+ * {@link setHeader}. Sending separate lines requires a provider that supports them; Fetch may
242
+ * combine or restrict headers.
119
243
  */
120
- export const appendHeader = (name, value) => editHeaders((fields) => Fields.append(fields, name.toLowerCase(), value));
244
+ export const appendHeader = (name, value) => editHeaders([name], (fields) => Fields.append(fields, name, value));
121
245
  /**
122
246
  * Remove a raw header, or only its declarations with the supplied fixed value.
123
247
  *
124
248
  * @remarks
125
- * Names compare without case. Value functions are never evaluated to compare with `value`.
126
- * Unavailable after a header schema is bound.
249
+ * Names compare without case. Value functions are never evaluated to compare with `value`. Removing
250
+ * a name a {@link headers} schema always writes, after that schema, is an {@link InvalidRequest},
251
+ * because the schema puts the value back. Removing an optional field clears its default.
252
+ *
253
+ * Without a value, this also stops the library's automatic value for that name: an operation's
254
+ * `Accept`, or a body's `Content-Type` and `Content-Length`. It stops only that. A value that a
255
+ * later declaration, a header schema or {@link mapEffect} supplies still goes out, and the client
256
+ * may add its own. A computed value that returns `undefined` declares nothing, so the removal stays
257
+ * in force. A removal limited to one value stops nothing, as the name may still be declared.
127
258
  */
128
- export const removeHeader = (name, value) => editHeaders((fields) => Fields.remove(fields, name.toLowerCase(), value));
259
+ export const removeHeader = (name, value) => editHeaders([name], (fields) => Fields.remove(fields, name, value, foldHeader), (names) => value === undefined ? new Set([...names, foldHeader(name)]) : names);
129
260
  /**
130
- * Set a raw query field, replacing entries with the same case-sensitive name.
261
+ * Set a raw query field, replacing entries with the same case-sensitive name, or set several from
262
+ * an object.
263
+ *
264
+ * @example
265
+ * ```ts
266
+ * import { Request } from "viell-effect-schema-http";
267
+ * const search = Request.get("https://api.example.test/users").pipe(
268
+ * Request.setQuery({ page: 2, tag: ["a", "b"], preview: null }),
269
+ * );
270
+ * // URL query: ?page=2&tag=a&tag=b&preview
271
+ * ```
131
272
  *
132
273
  * @remarks
133
- * `null` produces a bare key, `""` an empty value, and `undefined` omits the entry.
134
- * Unavailable after a query schema is bound.
274
+ * `null` produces a bare key, `""` an empty value, and `undefined` omits the entry. Names compare
275
+ * with an entry's decoded name, so this can replace an entry written in the constructor; other
276
+ * entries stay as written.
277
+ *
278
+ * With a {@link query} schema bound, in either order, the name has to be one a schema allows, and
279
+ * the value is a default that goes through the schema. Setting a name the schema always writes,
280
+ * after that schema, is an {@link InvalidRequest}, because the value could never reach the client.
281
+ *
282
+ * The object form takes {@link QueryFields}. Each key replaces its name as above, in key order, and
283
+ * other names stay. Use {@link appendQuery} for exact order across repeated names.
135
284
  */
136
- export const setQuery = (name, value) => editQuery((fields) => Fields.set(fields, name, value));
285
+ export const setQuery = (first, value) => {
286
+ const entries = typeof first === "string" ? [[first, value]] : Object.entries(first);
287
+ return editQuery(entries.map(([name]) => name), (fields) => entries.reduce((result, [name, entry]) => Fields.replace(result, name, typeof entry === "function"
288
+ ? [() => UrlEncoding.queryEntries([[name, entry()]])[0]?.[1]]
289
+ : UrlEncoding.queryEntries([[name, entry]]).map(([, text]) => text)), fields));
290
+ };
137
291
  /**
138
292
  * Append a raw query entry, preserving order and repeated names.
139
293
  *
140
294
  * @remarks
141
- * Uses the same value rules as {@link setQuery}. Unavailable after a query schema is bound.
295
+ * Uses the same value rules as {@link setQuery}, and a bound {@link query} schema checks it the
296
+ * same way.
142
297
  */
143
- export const appendQuery = (name, value) => editQuery((fields) => Fields.append(fields, name, value));
298
+ export const appendQuery = (name, value) => editQuery([name], (fields) => Fields.append(fields, name, value));
144
299
  /**
145
300
  * Remove a raw query field, or only declarations with the supplied fixed value.
146
301
  *
147
302
  * @remarks
148
- * Names compare with case. Value functions are not evaluated for comparison.
149
- * Unavailable after a query schema is bound.
303
+ * Names compare with case, and both names and values compare with an entry's decoded form. Value
304
+ * functions are not evaluated for comparison. Removing a name a {@link query} schema always writes,
305
+ * after that schema, is an {@link InvalidRequest}, because the schema puts the value back. Removing
306
+ * an optional field clears its default.
150
307
  */
151
- export const removeQuery = (name, value) => editQuery((fields) => Fields.remove(fields, name, value));
152
- const replaceQuery = (draft, entries) => {
308
+ export const removeQuery = (name, value) => editQuery([name], (fields) => Fields.remove(fields, name, value));
309
+ /** Put entries after the existing ones, in place of every entry under the `keys` names. */
310
+ const replaceQuery = (draft, entries, keys = new Set(entries.map(([key]) => key))) => {
153
311
  const added = entries.map(([key, value]) => [key, value ?? ""]);
154
- const keys = new Set(added.map(([key]) => key));
155
312
  const bareKeys = new Set(Array.from(draft.bareKeys).filter(([key]) => !keys.has(key)));
156
- entries.forEach(([, value], index) => {
313
+ const queryText = new Map(Array.from(draft.queryText).filter(([[key]]) => !keys.has(key)));
314
+ const declaredQuery = new Set([
315
+ ...Array.from(draft.declaredQuery).filter(([key]) => !keys.has(key)),
316
+ ...added,
317
+ ]);
318
+ entries.forEach(([, value, written], index) => {
157
319
  if (value === null)
158
320
  bareKeys.add(added[index]);
321
+ if (written !== undefined)
322
+ queryText.set(added[index], written);
159
323
  });
160
324
  const { request } = draft;
161
325
  const params = [
@@ -166,41 +330,113 @@ const replaceQuery = (draft, entries) => {
166
330
  ...draft,
167
331
  request: HttpClientRequest.makeWith(request.method, request.url, UrlParams.make(params), request.hash, request.headers, request.body),
168
332
  bareKeys,
333
+ queryText,
334
+ declaredQuery,
169
335
  };
170
336
  };
171
- /** Fields that describe the body itself rather than the request. */
337
+ /** What a native query entry holds: text, or `null` for a bare key. */
338
+ const queryValue = (draft, param) => draft.bareKeys.has(param)
339
+ ? null
340
+ : Redacted.isRedacted(param[1])
341
+ ? Redacted.value(param[1])
342
+ : param[1];
343
+ const listNames = (names) => Array.from(new Set(names), (name) => JSON.stringify(name)).join(", ");
344
+ /** Names only: a default's value may be a credential, and a schema's error would repeat it. */
345
+ const misfit = (group, defaults) => new InvalidRequest({
346
+ message: `The ${group} group cannot be built against its schema with these declared values: ${listNames(defaults.map(([name]) => name))}.`,
347
+ });
348
+ /** Names only, and only those that would go: what the schema kept fits it. */
349
+ const lostFields = (group, names) => new InvalidRequest({
350
+ message: `The ${group} group cannot be built against its schema: with the rest of the group, these fields would be lost: ${listNames(names)}.`,
351
+ });
352
+ /** Fields a body's encoder supplies unless the request says otherwise. */
172
353
  const bodyFields = ["content-type", "content-length"];
173
- /** Give the body fields their values from `before`, removing those it lacks. */
174
- const keepBodyFields = (headers, before) => bodyFields.reduce((result, name) => {
175
- const value = before[name];
176
- return value === undefined
177
- ? Headers.remove(result, name)
178
- : Headers.set(result, name, value);
179
- }, headers);
354
+ /** After an encoder set the body fields, apply what the request itself says about them. */
355
+ const applyDeclaredBodyFields = (encoded, prepared) => {
356
+ const declared = Transport.toHeaders(prepared.headerLines);
357
+ return HttpClientRequest.updateHeaders(encoded, (fields) => bodyFields.reduce((result, name) => {
358
+ const value = declared[name] ??
359
+ (prepared.removedHeaders.has(name)
360
+ ? prepared.request.headers[name]
361
+ : result[name]);
362
+ return value === undefined
363
+ ? Headers.remove(result, name)
364
+ : Headers.set(result, name, value);
365
+ }, fields));
366
+ };
180
367
  /**
181
368
  * Bind a schema to the call's `{ headers }` input.
182
369
  *
183
370
  * @remarks
184
- * Encoding produces ordered header lines. The schema replaces raw header declarations and owns
185
- * the group: later raw setters or another header schema are unavailable.
186
- * When a body is present, its `Content-Type` and `Content-Length` take precedence, regardless of
187
- * binding order. Without a body, the schema values apply; a later body binding, including
188
- * `Body.empty`, replaces those fields according to its encoder.
371
+ * The input is an {@link Input} of the schema. Encoding produces ordered header lines. The schema
372
+ * states the shape of the group, whatever the order of the calls: once any schema is bound, every
373
+ * header the request declares must be a name some schema allows. A raw header under such a name
374
+ * is a default: what the schema writes replaces it, and otherwise it goes through the schema,
375
+ * which writes its value, spelling and order. An omitted optional field therefore leaves the
376
+ * default in place. A raw header under a name no schema allows is an {@link InvalidRequest} before
377
+ * anything is sent. A record or `Schema.StructWithRest` allows any name. Names compare without
378
+ * case.
379
+ *
380
+ * Under a union, the defaults and what the schema wrote have to fit one member together. A field
381
+ * that would be lost otherwise is an {@link InvalidRequest}, which names that field. The caller's
382
+ * own value is read before that, as {@link Input} describes.
383
+ *
384
+ * Header schemas stack: a second one adds its fields, and together they state the shape. A field
385
+ * one of them takes stays with it, whatever a union beside it leaves out. Use {@link unbind} to
386
+ * start again.
387
+ *
388
+ * A field the schema produces wins over an automatic `Accept`, `Content-Type` or `Content-Length`,
389
+ * whether the schema is bound before or after the body, and so does a default. An optional field
390
+ * left out with no default declares nothing, so the automatic value still applies.
391
+ *
392
+ * Header values are text, so a schema writes its own. A query schema can encode to a `Date`, but
393
+ * HTTP date headers are not ISO text, and `Schema.DateTimeUtcFromHttpDate` writes them.
189
394
  */
190
395
  export const headers = (contract) => {
191
- const encode = Schema.encodeEffect(contract);
192
- return (self) => construct({ ...self.declaration, headers: [], headersBound: true }, Effect.fnUntraced(function* (input, draft) {
193
- const encoded = yield* encode(input.headers);
194
- const prepared = yield* self.prepare(input, draft);
195
- const headerLines = Transport.entries(encoded);
196
- const merged = HttpClientRequest.setHeaders(prepared.request, Transport.toHeaders(headerLines));
197
- // Compilation then drops the schema's lines for any body field whose value was kept.
396
+ const read = Inputs.reader(contract, Schema.encodeEffect(contract));
397
+ const { shape, settle, taken } = Shapes.bind(contract, foldHeader);
398
+ return (self) => construct({
399
+ ...self.declaration,
400
+ headerShapes: [...self.declaration.headerShapes, shape],
401
+ }, Effect.fnUntraced(function* (input, draft) {
402
+ if (draft.unbound.has("headers"))
403
+ return yield* self.prepare(input, draft);
404
+ const { output, lost: lostFromInput } = yield* read(input.headers);
405
+ const own = draft.takenHeaders && taken(input.headers, output, lostFromInput);
406
+ const prepared = yield* self.prepare(input, own === undefined
407
+ ? draft
408
+ : {
409
+ ...draft,
410
+ takenHeaders: Shapes.taking(draft.takenHeaders, own),
411
+ });
412
+ if (lostFromInput.length > 0)
413
+ yield* Inputs.refuseLost(contract, lostFromInput, prepared.takenHeaders?.fields);
414
+ const names = Shapes.written(output, foldHeader);
415
+ const elsewhere = Shapes.others(shape, prepared.takenHeaders, foldHeader);
416
+ const defaults = prepared.headerLines.filter(([name]) => !names.has(foldHeader(name)) &&
417
+ !elsewhere.has(foldHeader(name)) &&
418
+ Shapes.allows(shape, foldHeader(name)));
419
+ const settled = yield* Effect.mapError(settle(output, defaults), () => misfit("header", defaults));
420
+ // A field the schema does not write back would be lost, as a union member can lose one.
421
+ const lost = Shapes.lost(output, defaults, settled, foldHeader);
422
+ if (lost.length > 0)
423
+ return yield* lostFields("header", lost);
424
+ const lines = Transport.entries(settled);
425
+ const replaced = new Set([
426
+ ...names,
427
+ ...defaults.map(([name]) => foldHeader(name)),
428
+ ]);
429
+ const cleared = HttpClientRequest.updateHeaders(prepared.request, (fields) => prepared.headerLines
430
+ .map(([name]) => foldHeader(name))
431
+ .filter((name) => replaced.has(name))
432
+ .reduce((result, name) => Headers.remove(result, name), fields));
198
433
  return {
199
434
  ...prepared,
200
- request: prepared.request.body._tag === "Empty"
201
- ? merged
202
- : HttpClientRequest.updateHeaders(merged, (fields) => keepBodyFields(fields, prepared.request.headers)),
203
- headerLines,
435
+ request: HttpClientRequest.setHeaders(cleared, Transport.toHeaders(lines)),
436
+ headerLines: [
437
+ ...prepared.headerLines.filter(([name]) => !replaced.has(foldHeader(name))),
438
+ ...lines,
439
+ ],
204
440
  };
205
441
  }));
206
442
  };
@@ -212,90 +448,290 @@ export const headers = (contract) => {
212
448
  * import { Schema } from "effect";
213
449
  * import { Request } from "viell-effect-schema-http";
214
450
  * const search = Request.get("https://api.example.test/users").pipe(
215
- * Request.query(Schema.Struct({ page: Schema.NumberFromString })),
451
+ * Request.query(Schema.Struct({ page: Schema.FiniteFromString })),
216
452
  * );
217
453
  * // Input: { query: { page: 2 } }; URL query: ?page=2
218
454
  * ```
219
455
  *
220
456
  * @remarks
221
- * The schema encodes to `UrlEncoding.QueryInput`. It replaces raw query declarations, including
222
- * the constructor's query string, and owns the group. Later raw setters or another query schema
223
- * are unavailable. Use {@link mapInput} to supply application defaults.
457
+ * The input is an {@link Input} of the schema. The schema encodes to `UrlEncoding.QueryInput` and
458
+ * states the shape of the group, whatever the order of the calls: once any schema is bound, every
459
+ * query field the request declares must be a name some schema allows. A raw entry under such a
460
+ * name is a default, including one written in the constructor: what the schema writes replaces
461
+ * it, and otherwise it goes through the schema, which writes its value and order. An omitted
462
+ * optional field therefore leaves the default in place. A raw entry under a name no schema allows
463
+ * is an {@link InvalidRequest} before anything is sent. A record, `Schema.StructWithRest` or a list
464
+ * of pairs allows any name.
465
+ *
466
+ * Under a union, the defaults and what the schema wrote have to fit one member together. A field
467
+ * that would be lost otherwise is an {@link InvalidRequest}, which names that field. The caller's
468
+ * own value is read before that, as {@link Input} describes.
469
+ *
470
+ * A field can encode to a `Date`, which is written as ISO text. Text under a field that encodes to
471
+ * a number, boolean, bigint or `Date` is read as one first, and a single value under a list field
472
+ * fits it. Date text is read as `Schema.DateFromString` reads it. The check is as strict as the
473
+ * schema. A `?` in a base URL or path output is text in the URL, not a field, so it is outside this
474
+ * check.
475
+ *
476
+ * Query schemas stack: a second one adds its fields, and together they state the shape. A field one
477
+ * of them takes stays with it, whatever a union beside it leaves out. Use {@link unbind} to start
478
+ * again, and {@link mapInput} to supply a required field's value.
224
479
  */
225
480
  export const query = (contract) => {
226
- const encode = Schema.encodeEffect(contract);
227
- return (self) => construct({ ...self.declaration, query: [], queryBound: true }, Effect.fnUntraced(function* (input, draft) {
228
- const encoded = yield* encode(input.query);
229
- const prepared = yield* self.prepare(input, draft);
230
- return replaceQuery(prepared, UrlEncoding.queryEntries(encoded));
481
+ const read = Inputs.reader(contract, Schema.encodeEffect(contract));
482
+ const { shape, settle, taken } = Shapes.bind(contract, foldQuery);
483
+ return (self) => construct({
484
+ ...self.declaration,
485
+ queryShapes: [...self.declaration.queryShapes, shape],
486
+ }, Effect.fnUntraced(function* (input, draft) {
487
+ if (draft.unbound.has("query"))
488
+ return yield* self.prepare(input, draft);
489
+ const { output, lost: lostFromInput } = yield* read(input.query);
490
+ const own = draft.takenQuery && taken(input.query, output, lostFromInput);
491
+ const prepared = yield* self.prepare(input, own === undefined
492
+ ? draft
493
+ : {
494
+ ...draft,
495
+ takenQuery: Shapes.taking(draft.takenQuery, own),
496
+ });
497
+ if (lostFromInput.length > 0)
498
+ yield* Inputs.refuseLost(contract, lostFromInput, prepared.takenQuery?.fields);
499
+ const names = Shapes.written(output, foldQuery);
500
+ const elsewhere = Shapes.others(shape, prepared.takenQuery, foldQuery);
501
+ const defaults = prepared.request.urlParams.params
502
+ .filter((param) => prepared.declaredQuery.has(param) &&
503
+ !isEmptySegment(prepared, param) &&
504
+ !names.has(param[0]) &&
505
+ !elsewhere.has(param[0]) &&
506
+ Shapes.allows(shape, param[0]))
507
+ .map((param) => [param[0], queryValue(prepared, param)]);
508
+ const settled = yield* Effect.mapError(settle(output, defaults), () => misfit("query", defaults));
509
+ // A field the schema does not write back would be lost, as a union member can lose one.
510
+ const lost = Shapes.lost(output, defaults, settled, foldQuery);
511
+ if (lost.length > 0)
512
+ return yield* lostFields("query", lost);
513
+ return replaceQuery(prepared, UrlEncoding.queryEntries(settled), new Set([...names, ...defaults.map(([name]) => name)]));
231
514
  }));
232
515
  };
516
+ /** Put text after the path so far, exactly as written. */
517
+ const extendPath = (draft, text) => ({
518
+ ...draft,
519
+ request: HttpClientRequest.setUrl(draft.request, `${draft.request.url}${text}`),
520
+ });
521
+ /** Add to the path what `render` makes of the encoded `{ path }` input. */
522
+ const bindPath = (encode, render) => (self) => construct(self.declaration, Effect.fnUntraced(function* (input, draft) {
523
+ if (draft.unbound.has("path"))
524
+ return yield* self.prepare(input, draft);
525
+ const encoded = yield* encode(input.path);
526
+ const encoding = yield* UrlEncoding.UrlEncoding;
527
+ const prepared = yield* self.prepare(input, draft);
528
+ const added = yield* Effect.try({
529
+ try: () => render(encoded, encoding.path),
530
+ catch: (cause) => new InvalidRequest({
531
+ message: "Failed to render the request path",
532
+ cause,
533
+ }),
534
+ });
535
+ return extendPath(prepared, added);
536
+ }));
233
537
  /**
234
- * Bind a schema to `{ path }` input and render the complete request path.
538
+ * Declare a named value for a {@link path} template.
235
539
  *
236
540
  * @example
237
541
  * ```ts
238
542
  * import { Schema } from "effect";
239
543
  * import { Request } from "viell-effect-schema-http";
240
- * const user = Request.get("").pipe(
241
- * Request.baseUrl("https://api.example.test"),
242
- * Request.path(Schema.NumberFromString, (id, encode) => `/users/${encode(id)}`),
544
+ * const customer = Request.pathValue("customer");
545
+ * const calendar = Request.pathValue("calendar", Schema.FiniteFromString);
546
+ * const getCalendar = Request.get("").pipe(
547
+ * Request.path`/customers/${customer}/calendars/${calendar}`,
243
548
  * );
244
- * // Input: { path: 42 }; URL: https://api.example.test/users/42
549
+ * // Input: { path: { customer: "a/b", calendar: 7 } }
245
550
  * ```
246
551
  *
247
552
  * @remarks
248
- * The value under `path` has the schema's application type. A scalar schema takes a scalar;
249
- * `Schema.Struct({ userId: Schema.NumberFromString })` takes `{ userId: number }`. Use a struct
250
- * to name one path value or group several. Renderer parameter names do not affect the input type.
251
- *
252
- * The renderer receives the schema-encoded value and the active path-value encoder. Escape each
253
- * dynamic value with that encoder. The returned path replaces the constructor's path; it does
254
- * not append to it. The shared base URL is joined afterwards. Reuse renderer functions for
255
- * nested resources rather than stacking path bindings.
256
- * Renderer or path-encoding exceptions become {@link InvalidRequest}; schema failures remain
257
- * `SchemaError` values.
553
+ * The value arrives under its name in `{ path }`, and without a schema it is a string. A schema has
554
+ * to encode to one {@link PathScalar}, and a value that gets past that type, as under `Schema.Any`,
555
+ * is an {@link InvalidRequest}. The input is an {@link Input} of the schema, so it takes either side.
556
+ * Declare a value once and reuse it across templates and definitions.
258
557
  */
259
- export const path = (contract, render) => {
260
- const encode = Schema.encodeEffect(contract);
261
- return (self) => construct(self.declaration, Effect.fnUntraced(function* (input, draft) {
262
- const encoded = yield* encode(input.path);
263
- const encoding = yield* UrlEncoding.UrlEncoding;
264
- const prepared = yield* self.prepare(input, draft);
265
- const url = yield* Effect.try({
266
- try: () => render(encoded, encoding.path),
267
- catch: (cause) => new InvalidRequest({
268
- message: "Failed to render the request path",
269
- cause,
270
- }),
271
- });
272
- return {
273
- ...prepared,
274
- request: HttpClientRequest.setUrl(prepared.request, url),
275
- };
276
- }));
558
+ export const pathValue = (name, schema = Schema.String) => ({ name, schema });
559
+ /** Add fixed text, which needs no input and cannot fail. */
560
+ const fixedPath = (text) => (self) => construct(self.declaration, (input, draft) => draft.unbound.has("path")
561
+ ? self.prepare(input, draft)
562
+ : Effect.map(self.prepare(input, draft), (prepared) => extendPath(prepared, text)));
563
+ const isPathScalar = (value) => ["string", "number", "bigint", "boolean"].includes(typeof value);
564
+ /**
565
+ * Read one value from a `{ path }` input and write it as text.
566
+ *
567
+ * @remarks
568
+ * A struct takes the one field from a `path` that holds others, and names it in an error. An
569
+ * optional key or `Schema.Any` gets past the type of {@link PathSchema}, so the value is checked
570
+ * here rather than written as `undefined` or `[object Object]`.
571
+ */
572
+ const pathValueEncoder = ({ name, schema }) => {
573
+ const contract = Schema.Struct({ [name]: schema });
574
+ const encode = Inputs.encoder(contract, Schema.encodeEffect(contract));
575
+ return (input) => Effect.flatMap(encode(input), ({ [name]: value }) => isPathScalar(value)
576
+ ? Effect.succeed(String(value))
577
+ : Effect.fail(new InvalidRequest({
578
+ message: `The path value ${JSON.stringify(name)} did not encode to one value`,
579
+ })));
277
580
  };
581
+ /** Bind a template: each value goes through its own schema, and its text stays as written. */
582
+ const templatePath = (text, values) => {
583
+ const encoders = values.map(pathValueEncoder);
584
+ return encoders.length === 0
585
+ ? fixedPath(text.raw[0])
586
+ : bindPath((input) => Effect.forEach(encoders, (encode) => encode(input)), (encoded, encode) => encoded.reduce((added, value, index) => `${added}${encode(value)}${text.raw[index + 1]}`, text.raw[0]));
587
+ };
588
+ const isTemplate = (value) => Array.isArray(value);
589
+ /** Bind a renderer: it receives its schema's encoded value and the path-value encoder. */
590
+ const renderedPath = (contract, render) => bindPath(Inputs.encoder(contract, Schema.encodeEffect(contract)), render);
591
+ /**
592
+ * Add to the request's path, from a template or from a renderer.
593
+ *
594
+ * @example
595
+ * ```ts
596
+ * import { Schema } from "effect";
597
+ * import { Request } from "viell-effect-schema-http";
598
+ * const customer = Request.pathValue("customer");
599
+ * const calendar = Request.pathValue("calendar", Schema.FiniteFromString);
600
+ * const getCalendar = Request.get("").pipe(
601
+ * Request.baseUrl("https://api.example.test/v1"),
602
+ * Request.path`/customers/${customer}/calendars/${calendar}`,
603
+ * );
604
+ * // Input: { path: { customer: "a/b", calendar: 7 } }
605
+ * // URL: https://api.example.test/v1/customers/a%2Fb/calendars/7
606
+ * ```
607
+ *
608
+ * @example
609
+ * ```ts
610
+ * import { Schema } from "effect";
611
+ * import { Request } from "viell-effect-schema-http";
612
+ * const listFolder = Request.get("/files").pipe(
613
+ * Request.path(Schema.String, (folder, encode) =>
614
+ * folder === "" ? "/" : `/${folder.split("/").map(encode).join("/")}/`,
615
+ * ),
616
+ * );
617
+ * // Input: { path: "a b/c" }; URL: /files/a%20b/c/
618
+ * ```
619
+ *
620
+ * @remarks
621
+ * The path is the constructor's path followed by what each `path` call adds, in order, joined
622
+ * exactly as written. The library adds no `/` and removes none, so `/users` and `42` make
623
+ * `/users42`, and `/users/` and `/42` make `/users//42`. The base URL is joined afterwards. A `?` or
624
+ * `#` in the text is URL syntax, so a `#` starts the fragment for all that follows it. A fragment
625
+ * moves to the compiled request's `hash`, so the query still goes before it. The result is passed
626
+ * to the client as written, and the client may rewrite or refuse it.
627
+ *
628
+ * Use a template when the path has a fixed shape. Only a {@link pathValue} can go in one, so each
629
+ * value has its schema and always goes through the active `UrlEncoding` path encoder, and a run-time
630
+ * string is a compile error. A template with no values adds fixed text. The text is used as written
631
+ * and never parsed, so a backslash is a backslash and not an escape. Stacked templates add their
632
+ * fields to one `path` input, and a name used more than once gets the same value.
633
+ *
634
+ * Use a renderer when the shape of the path depends on the value, such as a value holding several
635
+ * segments or a whole URL. It receives the schema-encoded value and the active path-value encoder,
636
+ * and escaping each dynamic value is up to it. The value under `path` is an {@link Input} of the
637
+ * schema, so a scalar schema takes a scalar and a struct takes its fields. A scalar is one value for
638
+ * the whole `path`, so it does not stack with another scalar of a different type or with a template.
639
+ *
640
+ * Encoding does not make a value safe. A `/` in a value cannot add a segment, but `..` and an empty
641
+ * string have nothing to encode, and the client may resolve a dot segment. Constrain a value from a
642
+ * user in its schema.
643
+ *
644
+ * {@link unbind} removes what earlier calls added, and {@link setPath} replaces the constructor's
645
+ * text. Renderer or path-encoding exceptions become {@link InvalidRequest}; schema failures remain
646
+ * `SchemaError` values.
647
+ */
648
+ export const path = (first, ...rest) => (isTemplate(first)
649
+ ? templatePath(first, rest)
650
+ : renderedPath(first, rest[0]));
651
+ /**
652
+ * Replace the constructor's path, leaving every {@link path} binding in place.
653
+ *
654
+ * @example
655
+ * ```ts
656
+ * import { Request } from "viell-effect-schema-http";
657
+ * const id = Request.pathValue("id");
658
+ * const current = Request.get("/things").pipe(Request.path`/${id}`);
659
+ * const legacy = current.pipe(Request.setPath("/legacy/things"));
660
+ * // Input: { path: { id: "a" } }; URL: /legacy/things/a
661
+ * ```
662
+ *
663
+ * @remarks
664
+ * Only the path changes. A constructor's query and fragment stay, and a `?` or `#` in this text is
665
+ * URL text, as it is in {@link path}. To replace a whole path, use {@link unbind} and this together.
666
+ */
667
+ export const setPath = (url) => (self) => construct({ ...self.declaration, url }, self.prepare);
278
668
  /**
279
669
  * Bind an encoder to the call's `{ body }` input.
280
670
  *
281
671
  * @remarks
282
- * The body is encoded once per operation evaluation. Its encoder determines `Content-Type` and
283
- * `Content-Length`; multipart metadata is supplied by the transport.
672
+ * The body is encoded once per operation evaluation. Its encoder supplies `Content-Type` and
673
+ * `Content-Length`; multipart metadata is supplied by the transport. A value the request declares
674
+ * for either field wins, before or after this binding, and {@link removeHeader} stops the automatic
675
+ * value. Neither changes the encoded bytes.
676
+ *
677
+ * Any method can carry a body, and the library adds no check of its own. A client can refuse the
678
+ * request: `fetch` does so for GET and HEAD, which surfaces as a transport failure.
284
679
  */
285
680
  export const body = (codec) => (self) => construct(self.declaration, Effect.fnUntraced(function* (input, draft) {
681
+ if (draft.unbound.has("body"))
682
+ return yield* self.prepare(input, draft);
286
683
  const encoded = yield* codec.encode(input.body);
287
684
  const prepared = yield* self.prepare(input, draft);
288
685
  return {
289
686
  ...prepared,
290
- request: HttpClientRequest.setBody(prepared.request, encoded),
687
+ request: applyDeclaredBodyFields(HttpClientRequest.setBody(prepared.request, encoded), prepared),
291
688
  };
292
689
  }));
690
+ /**
691
+ * Remove a group's earlier bindings, their input and the shape they state.
692
+ *
693
+ * @example
694
+ * ```ts
695
+ * import { Schema } from "effect";
696
+ * import { Request } from "viell-effect-schema-http";
697
+ * const paged = Request.get("https://api.example.test/things").pipe(
698
+ * Request.query(Schema.Struct({ page: Schema.FiniteFromString })),
699
+ * );
700
+ * const sorted = paged.pipe(
701
+ * Request.unbind("query"),
702
+ * Request.query(Schema.Struct({ sort: Schema.String })),
703
+ * );
704
+ * // Input: { query: { sort: "name" } }; URL query: ?sort=name
705
+ * ```
706
+ *
707
+ * @remarks
708
+ * Takes `"path"`, `"query"`, `"headers"` or `"body"`, and affects only bindings before it. To
709
+ * replace a binding, unbind the group and bind again. Raw declarations stay, and go out unchecked
710
+ * once no schema states the group's shape. A constructor path and query are declarations, so they
711
+ * stay too. For `"path"`, the text of earlier {@link path} calls goes with their values, and
712
+ * {@link setPath} is what changes the constructor's path.
713
+ *
714
+ * Other steps stay as well. A {@link mapEffect} finds the removed property `undefined`, and where
715
+ * no other input is left the whole input is `undefined`, so reading the property there is a defect.
716
+ * After {@link mapInput}, the binding is skipped, but the mapped input keeps whatever the mapping
717
+ * requires. The request's error and service types keep what the removed bindings added.
718
+ */
719
+ export const unbind = (group) => (self) => construct({
720
+ ...self.declaration,
721
+ headerShapes: group === "headers" ? [] : self.declaration.headerShapes,
722
+ queryShapes: group === "query" ? [] : self.declaration.queryShapes,
723
+ conflicts: self.declaration.conflicts.filter(([owner]) => owner !== group),
724
+ }, (input, draft) => self.prepare(input, {
725
+ ...draft,
726
+ unbound: new Set([...draft.unbound, group]),
727
+ }));
293
728
  /**
294
729
  * Adapt your application's argument to this request's required input.
295
730
  *
296
731
  * @remarks
297
732
  * Use it to rename fields or supply defaults while preserving schema validation. The mapping
298
- * runs during preparation; a thrown exception is a defect.
733
+ * runs during preparation; a thrown exception is a defect. It returns the request's whole input,
734
+ * which {@link InputOf} names.
299
735
  */
300
736
  export const mapInput = (f) => (self) => construct(self.declaration, (input, draft) => Effect.suspend(() => self.prepare(f(input), draft)));
301
737
  /**
@@ -308,39 +744,118 @@ export const mapInput = (f) => (self) => construct(self.declaration, (input, dra
308
744
  * applies afterwards.
309
745
  *
310
746
  * A transform can be reused on requests whose input contains what its function reads. Inline
311
- * callbacks in `pipe` infer their input from the request.
747
+ * callbacks in `pipe` infer their input from the request. This is the deliberate way around a
748
+ * group's schemas: what it edits on the native request is outside their check.
312
749
  */
313
750
  export const mapEffect = (f) => (self) => construct(self.declaration, (input, draft) => Effect.flatMap(self.prepare(input, draft), (prepared) => Effect.map(f(prepared.request, input), (request) => ({
314
751
  ...prepared,
315
752
  request,
316
753
  }))));
754
+ /** A record to start from where a schema in the group can lose a field to another one. */
755
+ const takenRecord = (shapes) => shapes.length > 1 && shapes.some(({ chooses }) => chooses)
756
+ ? {
757
+ fields: new Set(),
758
+ settled: new Set(shapes.flatMap(({ chooses, names }) => chooses ? [] : Array.from(names))),
759
+ }
760
+ : undefined;
317
761
  const initialDraft = (declaration) => {
318
762
  // Custom method strings pass through at runtime; the method union is narrower than the transport.
319
763
  const native = HttpClientRequest.make(declaration.method)(declaration.url);
320
764
  const headerLines = Fields.resolve(declaration.headers);
321
765
  return replaceQuery({
322
- request: HttpClientRequest.setHeaders(native, Transport.toHeaders(headerLines)),
766
+ request: HttpClientRequest.setHeaders(
767
+ // An empty fragment counts, and the options of `make` would skip it.
768
+ declaration.hash === undefined
769
+ ? native
770
+ : HttpClientRequest.setHash(native, declaration.hash), Transport.toHeaders(headerLines)),
323
771
  headerLines,
324
772
  bareKeys: new Set(),
325
- }, Fields.resolve(declaration.query));
773
+ queryText: new Map(),
774
+ declaredQuery: new Set(),
775
+ removedHeaders: declaration.removedHeaders,
776
+ unbound: new Set(),
777
+ takenQuery: takenRecord(declaration.queryShapes),
778
+ takenHeaders: takenRecord(declaration.headerShapes),
779
+ }, declaration.query.flatMap((field) => Fields.resolve([field]).map(([key, value]) => [key, value, field[2]])));
780
+ };
781
+ /**
782
+ * Render query entries in order. Written text stays as it is, and each run of entries between it
783
+ * goes through the encoder. With no entries at all, the encoder still has its say.
784
+ */
785
+ const renderQuery = (draft, encoding) => {
786
+ const parts = [];
787
+ let run = [];
788
+ const endRun = () => {
789
+ const rendered = run.length === 0 ? "" : encoding.query(run);
790
+ if (rendered !== "")
791
+ parts.push(rendered);
792
+ run = [];
793
+ };
794
+ for (const param of draft.request.urlParams.params) {
795
+ const written = draft.queryText.get(param);
796
+ if (written !== undefined) {
797
+ endRun();
798
+ parts.push(written);
799
+ }
800
+ else {
801
+ run.push([param[0], queryValue(draft, param)]);
802
+ }
803
+ }
804
+ endRun();
805
+ return parts.length === 0 ? encoding.query([]) : parts.join("&");
326
806
  };
327
- const finalize = (draft, base, encoding) => {
807
+ const finalize = (draft, declaration, baseText, encoding) => {
328
808
  const { request } = draft;
329
- const url = encoding.join(base, request.url);
330
- const search = encoding.query(request.urlParams.params.map((param) => [
331
- param[0],
332
- draft.bareKeys.has(param)
333
- ? null
334
- : Redacted.isRedacted(param[1])
335
- ? Redacted.value(param[1])
336
- : param[1],
337
- ]));
338
- const compiled = HttpClientRequest.makeWith(request.method, search === "" ? url : `${url}${url.includes("?") ? "&" : "?"}${search}`, UrlParams.empty, request.hash, request.headers, request.body);
809
+ const [base, baseFragment] = splitFragment(baseText);
810
+ const [target, targetFragment] = splitFragment(request.url);
811
+ const [url, joinFragment] = splitFragment(encoding.join(base, target));
812
+ const search = renderQuery(draft, encoding);
813
+ const separator = url.includes("?") ? "&" : "?";
814
+ const compiled = HttpClientRequest.makeWith(request.method, search !== ""
815
+ ? `${url}${separator}${search}`
816
+ : declaration.emptyQuery && separator === "?"
817
+ ? `${url}?`
818
+ : url, UrlParams.empty, Option.orElse(request.hash, () => Option.fromUndefinedOr(targetFragment ?? baseFragment ?? joinFragment)), request.headers, request.body);
339
819
  return {
340
820
  request: compiled,
341
821
  headerLines: Transport.reconcile(draft.headerLines, compiled.headers),
822
+ removedHeaders: draft.removedHeaders,
342
823
  };
343
824
  };
825
+ /** Why a request's fields cannot be built against their schemas, by name and never by value. */
826
+ const fieldProblems = (declaration, draft) => [
827
+ [
828
+ "query",
829
+ draft.request.urlParams.params
830
+ .filter((param) => !isEmptySegment(draft, param))
831
+ .map(([name]) => name),
832
+ declaration.queryShapes,
833
+ foldQuery,
834
+ ],
835
+ [
836
+ "headers",
837
+ draft.headerLines.map(([name]) => name),
838
+ declaration.headerShapes,
839
+ foldHeader,
840
+ ],
841
+ ].flatMap(([group, names, shapes, fold]) => {
842
+ const conflicts = declaration.conflicts
843
+ .filter(([owner]) => owner === group)
844
+ .map(([, name]) => name);
845
+ const stray = Shapes.outside(names, shapes, fold);
846
+ return [
847
+ ...(conflicts.length === 0
848
+ ? []
849
+ : [
850
+ `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.`,
851
+ ]),
852
+ ...(stray.length === 0
853
+ ? []
854
+ : [
855
+ `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.`,
856
+ ]),
857
+ ];
858
+ });
344
859
  /**
345
860
  * Prepare a request and its header lines without sending it.
346
861
  *
@@ -355,9 +870,11 @@ const finalize = (draft, base, encoding) => {
355
870
  * ```
356
871
  *
357
872
  * @remarks
358
- * Each evaluation resolves computed fields and encodes input once. The returned Effect requires
359
- * any services used by the input schemas or preparation. Use {@link materialize} when only the
360
- * native request is needed.
873
+ * Each evaluation resolves computed fields, encodes input and resolves the base URL once, in that
874
+ * order. The returned Effect requires any services used by the input schemas, preparation or the
875
+ * base URL. A declared field that does not fit the schemas bound to its group fails here with
876
+ * {@link InvalidRequest}, whatever the input. Use {@link materialize} when only the native request
877
+ * is needed.
361
878
  */
362
879
  export const compile = Effect.fnUntraced(function* (self, input) {
363
880
  const encoding = yield* UrlEncoding.UrlEncoding;
@@ -368,16 +885,14 @@ export const compile = Effect.fnUntraced(function* (self, input) {
368
885
  cause,
369
886
  }),
370
887
  });
888
+ const problems = fieldProblems(self.declaration, initial);
889
+ if (problems.length > 0)
890
+ return yield* new InvalidRequest({ message: problems.join(" ") });
371
891
  const draft = yield* self.prepare(input, initial);
372
- const { method } = draft.request;
373
- if ((method === "GET" || method === "HEAD") &&
374
- draft.request.body._tag !== "Empty") {
375
- return yield* new InvalidRequest({
376
- message: `${method} cannot carry a request body`,
377
- });
378
- }
892
+ // Only `baseUrl` and `mapBaseUrl` set an Effect, and what it needs is already in `E` and `R`.
893
+ const baseText = yield* resolveBaseUrl(self.declaration);
379
894
  return yield* Effect.try({
380
- try: () => finalize(draft, self.declaration.baseUrl, encoding),
895
+ try: () => finalize(draft, self.declaration, baseText, encoding),
381
896
  catch: (cause) => new InvalidRequest({ message: "Failed to encode request URL", cause }),
382
897
  });
383
898
  });