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