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