viell-effect-schema-http 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +88 -2
- package/dist/concurrency/Interaction.d.ts +65 -0
- package/dist/concurrency/Interaction.d.ts.map +1 -0
- package/dist/concurrency/Interaction.js +99 -0
- package/dist/concurrency/Interaction.js.map +1 -0
- package/dist/http/Body.d.ts +162 -0
- package/dist/http/Body.d.ts.map +1 -0
- package/dist/http/Body.js +184 -0
- package/dist/http/Body.js.map +1 -0
- package/dist/http/Operation.d.ts +97 -0
- package/dist/http/Operation.d.ts.map +1 -0
- package/dist/http/Operation.js +146 -0
- package/dist/http/Operation.js.map +1 -0
- package/dist/http/Policy.d.ts +82 -0
- package/dist/http/Policy.d.ts.map +1 -0
- package/dist/http/Policy.js +76 -0
- package/dist/http/Policy.js.map +1 -0
- package/dist/http/Request.d.ts +324 -0
- package/dist/http/Request.d.ts.map +1 -0
- package/dist/http/Request.js +391 -0
- package/dist/http/Request.js.map +1 -0
- package/dist/http/Response.d.ts +126 -0
- package/dist/http/Response.d.ts.map +1 -0
- package/dist/http/Response.js +100 -0
- package/dist/http/Response.js.map +1 -0
- package/dist/http/Transport.d.ts +75 -0
- package/dist/http/Transport.d.ts.map +1 -0
- package/dist/http/Transport.js +91 -0
- package/dist/http/Transport.js.map +1 -0
- package/dist/http/UrlEncoding.d.ts +78 -0
- package/dist/http/UrlEncoding.d.ts.map +1 -0
- package/dist/http/UrlEncoding.js +64 -0
- package/dist/http/UrlEncoding.js.map +1 -0
- package/dist/http/internal/fields.d.ts +12 -0
- package/dist/http/internal/fields.d.ts.map +1 -0
- package/dist/http/internal/fields.js +21 -0
- package/dist/http/internal/fields.js.map +1 -0
- package/dist/main.d.ts +33 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +33 -0
- package/dist/main.js.map +1 -0
- package/package.json +125 -4
- package/src/concurrency/Interaction.ts +192 -0
- package/src/http/Body.ts +318 -0
- package/src/http/Operation.ts +300 -0
- package/src/http/Policy.ts +130 -0
- package/src/http/Request.ts +700 -0
- package/src/http/Response.ts +201 -0
- package/src/http/Transport.ts +143 -0
- package/src/http/UrlEncoding.ts +119 -0
- package/src/http/internal/fields.ts +46 -0
- package/src/main.ts +32 -0
|
@@ -0,0 +1,700 @@
|
|
|
1
|
+
import { Data, Effect, Pipeable, Redacted, Schema } from "effect";
|
|
2
|
+
import {
|
|
3
|
+
Headers,
|
|
4
|
+
HttpClientRequest,
|
|
5
|
+
type HttpMethod,
|
|
6
|
+
UrlParams,
|
|
7
|
+
} from "effect/http";
|
|
8
|
+
import type * as Body from "./Body.js";
|
|
9
|
+
import * as Fields from "./internal/fields.js";
|
|
10
|
+
import * as Transport from "./Transport.js";
|
|
11
|
+
import * as UrlEncoding from "./UrlEncoding.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Request preparation failed before dispatch.
|
|
15
|
+
*
|
|
16
|
+
* @remarks
|
|
17
|
+
* Covers computed-field failures, URL-rendering exceptions, and a GET/HEAD body other than
|
|
18
|
+
* `HttpBody.empty`. Schema encoding failures remain separate `SchemaError` values.
|
|
19
|
+
*/
|
|
20
|
+
export class InvalidRequest extends Data.TaggedError("InvalidRequest")<{
|
|
21
|
+
readonly message: string;
|
|
22
|
+
readonly cause?: unknown;
|
|
23
|
+
}> {}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A fixed header or query value, or a function that supplies it during preparation.
|
|
27
|
+
*
|
|
28
|
+
* @remarks
|
|
29
|
+
* A function runs once each time the request is compiled, not once per retry. `undefined` omits
|
|
30
|
+
* the field. Query fields also accept `null` for a bare key.
|
|
31
|
+
*/
|
|
32
|
+
export type FieldValue<A = string> = Fields.Value<A>;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The method, URL and raw fields from which request preparation starts.
|
|
36
|
+
*
|
|
37
|
+
* @remarks
|
|
38
|
+
* 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
|
+
*/
|
|
41
|
+
export interface Declaration<
|
|
42
|
+
H extends boolean = boolean,
|
|
43
|
+
Q extends boolean = boolean,
|
|
44
|
+
> {
|
|
45
|
+
readonly method: string;
|
|
46
|
+
readonly url: string;
|
|
47
|
+
readonly baseUrl: string;
|
|
48
|
+
readonly headers: Fields.Fields;
|
|
49
|
+
readonly query: Fields.Fields<string | null>;
|
|
50
|
+
/** Whether a schema owns the header group; raw header setters are then unavailable. */
|
|
51
|
+
readonly headersBound: H;
|
|
52
|
+
/** Whether a schema owns the query group; raw query setters are then unavailable. */
|
|
53
|
+
readonly queryBound: Q;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* One entry in Effect's native query collection.
|
|
58
|
+
*
|
|
59
|
+
* @remarks
|
|
60
|
+
* Drafts use entry identity to distinguish bare keys from empty values.
|
|
61
|
+
*/
|
|
62
|
+
export type UrlParam = UrlParams.UrlParams["params"][number];
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The native request and representation details available during input preparation.
|
|
66
|
+
*
|
|
67
|
+
* @remarks
|
|
68
|
+
* The base URL and final query text are applied after preparation. Prefer public combinators
|
|
69
|
+
* unless implementing a low-level extension.
|
|
70
|
+
*/
|
|
71
|
+
export interface Draft {
|
|
72
|
+
/** Method, path or URL, query parameters, normalized headers and body. */
|
|
73
|
+
readonly request: HttpClientRequest.HttpClientRequest;
|
|
74
|
+
/** The authoritative header lines; compilation reconciles them with the native headers. */
|
|
75
|
+
readonly headerLines: Transport.Lines;
|
|
76
|
+
/** Native query entries that render as bare keys. Replacing an entry loses its identity marker. */
|
|
77
|
+
readonly bareKeys: ReadonlySet<UrlParam>;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* An immutable HTTP request description with typed application input.
|
|
82
|
+
*
|
|
83
|
+
* @remarks
|
|
84
|
+
* Construction sends nothing. {@link compile} prepares it; `Operation.make` prepares and sends it.
|
|
85
|
+
* `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
|
+
* `declaration` and `prepare` are low-level extension points.
|
|
88
|
+
*/
|
|
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
|
+
>
|
|
96
|
+
extends Pipeable.Pipeable {
|
|
97
|
+
readonly declaration: Declaration<H, Q>;
|
|
98
|
+
readonly prepare: (input: I, draft: Draft) => Effect.Effect<Draft, E, R>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const construct = <I, E, R, H extends boolean, Q extends boolean>(
|
|
102
|
+
declaration: Declaration<H, Q>,
|
|
103
|
+
prepare: (input: I, draft: Draft) => Effect.Effect<Draft, E, R>,
|
|
104
|
+
): Request<I, E, R, H, Q> => ({ ...Pipeable.Prototype, declaration, prepare });
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Describe a request with a method and URL, without sending it.
|
|
108
|
+
*
|
|
109
|
+
* @remarks
|
|
110
|
+
* Use `undefined` as input until a binding adds required fields. A relative path can be combined
|
|
111
|
+
* with {@link baseUrl}; {@link path} can supply the complete path from typed input.
|
|
112
|
+
* Custom method strings pass through unchanged.
|
|
113
|
+
*
|
|
114
|
+
* A constructor query is parsed as form data: `+` becomes a space, percent escapes are decoded,
|
|
115
|
+
* and empty `&` segments are dropped. Bare keys remain distinct from empty values. Compilation
|
|
116
|
+
* renders these entries through `UrlEncoding.query`; a constructor fragment is discarded.
|
|
117
|
+
*/
|
|
118
|
+
export const make = (method: string, url: string): Request<unknown> => {
|
|
119
|
+
const hash = url.indexOf("#");
|
|
120
|
+
const withoutHash = hash < 0 ? url : url.slice(0, hash);
|
|
121
|
+
const start = withoutHash.indexOf("?");
|
|
122
|
+
const query: Array<readonly [string, string | null]> = [];
|
|
123
|
+
if (start >= 0) {
|
|
124
|
+
for (const segment of withoutHash.slice(start + 1).split("&")) {
|
|
125
|
+
// URLSearchParams strips one leading query marker; a marker in the key is data.
|
|
126
|
+
for (const [key, value] of new URLSearchParams(`?${segment}`))
|
|
127
|
+
query.push([key, segment.includes("=") ? value : null]);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return construct(
|
|
131
|
+
{
|
|
132
|
+
method,
|
|
133
|
+
url: start < 0 ? withoutHash : withoutHash.slice(0, start),
|
|
134
|
+
baseUrl: "",
|
|
135
|
+
headers: [],
|
|
136
|
+
query,
|
|
137
|
+
headersBound: false,
|
|
138
|
+
queryBound: false,
|
|
139
|
+
},
|
|
140
|
+
(_, draft) => Effect.succeed(draft),
|
|
141
|
+
);
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Describe a GET request. Use {@link baseUrl} for a shared origin or path prefix.
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```ts
|
|
149
|
+
* import { Request } from "viell-effect-schema-http";
|
|
150
|
+
* const users = Request.get("/users").pipe(
|
|
151
|
+
* Request.baseUrl("https://api.example.test/api/v1"),
|
|
152
|
+
* );
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
export const get = (url: string): Request<unknown> => make("GET", url);
|
|
156
|
+
/**
|
|
157
|
+
* Describe a POST request. Add typed input with {@link body}, {@link path} or other bindings.
|
|
158
|
+
*/
|
|
159
|
+
export const post = (url: string): Request<unknown> => make("POST", url);
|
|
160
|
+
/**
|
|
161
|
+
* Describe a PUT request. Add an outgoing representation with {@link body}.
|
|
162
|
+
*/
|
|
163
|
+
export const put = (url: string): Request<unknown> => make("PUT", url);
|
|
164
|
+
/**
|
|
165
|
+
* Describe a PATCH request. Add an outgoing representation with {@link body}.
|
|
166
|
+
*/
|
|
167
|
+
export const patch = (url: string): Request<unknown> => make("PATCH", url);
|
|
168
|
+
/**
|
|
169
|
+
* Describe a DELETE request. A response contract decides which deletion outcomes to accept.
|
|
170
|
+
*/
|
|
171
|
+
export const del = (url: string): Request<unknown> => make("DELETE", url);
|
|
172
|
+
/**
|
|
173
|
+
* Describe a HEAD request. Its outgoing body must remain `HttpBody.empty`.
|
|
174
|
+
*/
|
|
175
|
+
export const head = (url: string): Request<unknown> => make("HEAD", url);
|
|
176
|
+
/**
|
|
177
|
+
* Describe an OPTIONS request. The HTTP provider still controls browser preflight behavior.
|
|
178
|
+
*/
|
|
179
|
+
export const options = (url: string): Request<unknown> => make("OPTIONS", url);
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Set the shared origin and fixed path prefix for a request.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* import { Request } from "viell-effect-schema-http";
|
|
187
|
+
* const api = Request.baseUrl("https://api.example.test/api/v1");
|
|
188
|
+
* const users = Request.get("/users").pipe(api);
|
|
189
|
+
* const teams = Request.get("/teams").pipe(api);
|
|
190
|
+
* ```
|
|
191
|
+
*
|
|
192
|
+
* @remarks
|
|
193
|
+
* The base is joined after path preparation. With the default URL policy, an absolute request
|
|
194
|
+
* URL bypasses it; a leading `/` on a relative path keeps the base's prefix. Calling this again
|
|
195
|
+
* replaces the base, rather than appending to it. Keep query fields in request combinators.
|
|
196
|
+
*/
|
|
197
|
+
export const baseUrl =
|
|
198
|
+
(url: string) =>
|
|
199
|
+
<I, E, R, H extends boolean, Q extends boolean>(
|
|
200
|
+
self: Request<I, E, R, H, Q>,
|
|
201
|
+
): Request<I, E, R, H, Q> =>
|
|
202
|
+
construct({ ...self.declaration, baseUrl: url }, self.prepare);
|
|
203
|
+
|
|
204
|
+
const editHeaders =
|
|
205
|
+
(edit: (fields: Fields.Fields) => Fields.Fields) =>
|
|
206
|
+
<I, E, R, Q extends boolean>(
|
|
207
|
+
self: Request<I, E, R, false, Q>,
|
|
208
|
+
): Request<I, E, R, false, Q> =>
|
|
209
|
+
construct(
|
|
210
|
+
{ ...self.declaration, headers: edit(self.declaration.headers) },
|
|
211
|
+
self.prepare,
|
|
212
|
+
);
|
|
213
|
+
|
|
214
|
+
const editQuery =
|
|
215
|
+
(
|
|
216
|
+
edit: (
|
|
217
|
+
fields: Fields.Fields<string | null>,
|
|
218
|
+
) => Fields.Fields<string | null>,
|
|
219
|
+
) =>
|
|
220
|
+
<I, E, R, H extends boolean>(
|
|
221
|
+
self: Request<I, E, R, H, false>,
|
|
222
|
+
): Request<I, E, R, H, false> =>
|
|
223
|
+
construct(
|
|
224
|
+
{ ...self.declaration, query: edit(self.declaration.query) },
|
|
225
|
+
self.prepare,
|
|
226
|
+
);
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Set a raw header, replacing every existing line with that name.
|
|
230
|
+
*
|
|
231
|
+
* @remarks
|
|
232
|
+
* Names compare without case and are stored lowercase. Unavailable after a header schema is
|
|
233
|
+
* bound. The body encoder owns `Content-Type` and `Content-Length`.
|
|
234
|
+
*/
|
|
235
|
+
export const setHeader = (name: string, value: FieldValue) =>
|
|
236
|
+
editHeaders((fields) => Fields.set(fields, name.toLowerCase(), value));
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Add a raw header line after the existing lines, preserving repetition.
|
|
240
|
+
*
|
|
241
|
+
* @remarks
|
|
242
|
+
* Names are stored lowercase. Unavailable after a header schema is bound. Sending separate
|
|
243
|
+
* lines requires a provider that supports them; Fetch may combine or restrict headers.
|
|
244
|
+
*/
|
|
245
|
+
export const appendHeader = (name: string, value: FieldValue) =>
|
|
246
|
+
editHeaders((fields) => Fields.append(fields, name.toLowerCase(), value));
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Remove a raw header, or only its declarations with the supplied fixed value.
|
|
250
|
+
*
|
|
251
|
+
* @remarks
|
|
252
|
+
* Names compare without case. Value functions are never evaluated to compare with `value`.
|
|
253
|
+
* Unavailable after a header schema is bound.
|
|
254
|
+
*/
|
|
255
|
+
export const removeHeader = (name: string, value?: string) =>
|
|
256
|
+
editHeaders((fields) => Fields.remove(fields, name.toLowerCase(), value));
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Set a raw query field, replacing entries with the same case-sensitive name.
|
|
260
|
+
*
|
|
261
|
+
* @remarks
|
|
262
|
+
* `null` produces a bare key, `""` an empty value, and `undefined` omits the entry.
|
|
263
|
+
* Unavailable after a query schema is bound.
|
|
264
|
+
*/
|
|
265
|
+
export const setQuery = (name: string, value: FieldValue<string | null>) =>
|
|
266
|
+
editQuery((fields) => Fields.set(fields, name, value));
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Append a raw query entry, preserving order and repeated names.
|
|
270
|
+
*
|
|
271
|
+
* @remarks
|
|
272
|
+
* Uses the same value rules as {@link setQuery}. Unavailable after a query schema is bound.
|
|
273
|
+
*/
|
|
274
|
+
export const appendQuery = (name: string, value: FieldValue<string | null>) =>
|
|
275
|
+
editQuery((fields) => Fields.append(fields, name, value));
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Remove a raw query field, or only declarations with the supplied fixed value.
|
|
279
|
+
*
|
|
280
|
+
* @remarks
|
|
281
|
+
* Names compare with case. Value functions are not evaluated for comparison.
|
|
282
|
+
* Unavailable after a query schema is bound.
|
|
283
|
+
*/
|
|
284
|
+
export const removeQuery = (name: string, value?: string | null) =>
|
|
285
|
+
editQuery((fields) => Fields.remove(fields, name, value));
|
|
286
|
+
|
|
287
|
+
const replaceQuery = (draft: Draft, entries: UrlEncoding.Query): Draft => {
|
|
288
|
+
const added = entries.map(([key, value]): UrlParam => [key, value ?? ""]);
|
|
289
|
+
const keys = new Set(added.map(([key]) => key));
|
|
290
|
+
const bareKeys = new Set(
|
|
291
|
+
Array.from(draft.bareKeys).filter(([key]) => !keys.has(key)),
|
|
292
|
+
);
|
|
293
|
+
entries.forEach(([, value], index) => {
|
|
294
|
+
if (value === null) bareKeys.add(added[index]!);
|
|
295
|
+
});
|
|
296
|
+
const { request } = draft;
|
|
297
|
+
const params = [
|
|
298
|
+
...request.urlParams.params.filter(([key]) => !keys.has(key)),
|
|
299
|
+
...added,
|
|
300
|
+
];
|
|
301
|
+
return {
|
|
302
|
+
...draft,
|
|
303
|
+
request: HttpClientRequest.makeWith(
|
|
304
|
+
request.method,
|
|
305
|
+
request.url,
|
|
306
|
+
UrlParams.make(params),
|
|
307
|
+
request.hash,
|
|
308
|
+
request.headers,
|
|
309
|
+
request.body,
|
|
310
|
+
),
|
|
311
|
+
bareKeys,
|
|
312
|
+
};
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
/** Fields that describe the body itself rather than the request. */
|
|
316
|
+
const bodyFields = ["content-type", "content-length"] as const;
|
|
317
|
+
|
|
318
|
+
/** Give the body fields their values from `before`, removing those it lacks. */
|
|
319
|
+
const keepBodyFields = (
|
|
320
|
+
headers: Headers.Headers,
|
|
321
|
+
before: Headers.Headers,
|
|
322
|
+
): Headers.Headers =>
|
|
323
|
+
bodyFields.reduce((result, name) => {
|
|
324
|
+
const value = before[name];
|
|
325
|
+
return value === undefined
|
|
326
|
+
? Headers.remove(result, name)
|
|
327
|
+
: Headers.set(result, name, value);
|
|
328
|
+
}, headers);
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Bind a schema to the call's `{ headers }` input.
|
|
332
|
+
*
|
|
333
|
+
* @remarks
|
|
334
|
+
* Encoding produces ordered header lines. The schema replaces raw header declarations and owns
|
|
335
|
+
* the group: later raw setters or another header schema are unavailable.
|
|
336
|
+
* When a body is present, its `Content-Type` and `Content-Length` take precedence, regardless of
|
|
337
|
+
* binding order. Without a body, the schema values apply; a later body binding, including
|
|
338
|
+
* `Body.empty`, replaces those fields according to its encoder.
|
|
339
|
+
*/
|
|
340
|
+
export const headers = <
|
|
341
|
+
S extends Schema.ConstraintCodec<
|
|
342
|
+
unknown,
|
|
343
|
+
Transport.HeaderInput,
|
|
344
|
+
unknown,
|
|
345
|
+
unknown
|
|
346
|
+
>,
|
|
347
|
+
>(
|
|
348
|
+
contract: S,
|
|
349
|
+
) => {
|
|
350
|
+
const encode = Schema.encodeEffect(contract);
|
|
351
|
+
return <I, E, R, Q extends boolean>(
|
|
352
|
+
self: Request<I, E, R, false, Q>,
|
|
353
|
+
): Request<
|
|
354
|
+
I & { readonly headers: S["Type"] },
|
|
355
|
+
E | Schema.SchemaError,
|
|
356
|
+
R | S["EncodingServices"],
|
|
357
|
+
true,
|
|
358
|
+
Q
|
|
359
|
+
> =>
|
|
360
|
+
construct(
|
|
361
|
+
{ ...self.declaration, headers: [], headersBound: true },
|
|
362
|
+
Effect.fnUntraced(function* (
|
|
363
|
+
input: I & { readonly headers: S["Type"] },
|
|
364
|
+
draft: Draft,
|
|
365
|
+
) {
|
|
366
|
+
const encoded = yield* encode(input.headers);
|
|
367
|
+
const prepared = yield* self.prepare(input, draft);
|
|
368
|
+
const headerLines = Transport.entries(encoded);
|
|
369
|
+
const merged = HttpClientRequest.setHeaders(
|
|
370
|
+
prepared.request,
|
|
371
|
+
Transport.toHeaders(headerLines),
|
|
372
|
+
);
|
|
373
|
+
// Compilation then drops the schema's lines for any body field whose value was kept.
|
|
374
|
+
return {
|
|
375
|
+
...prepared,
|
|
376
|
+
request:
|
|
377
|
+
prepared.request.body._tag === "Empty"
|
|
378
|
+
? merged
|
|
379
|
+
: HttpClientRequest.updateHeaders(merged, (fields) =>
|
|
380
|
+
keepBodyFields(fields, prepared.request.headers),
|
|
381
|
+
),
|
|
382
|
+
headerLines,
|
|
383
|
+
};
|
|
384
|
+
}),
|
|
385
|
+
);
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Bind a schema to the call's `{ query }` input.
|
|
390
|
+
*
|
|
391
|
+
* @example
|
|
392
|
+
* ```ts
|
|
393
|
+
* import { Schema } from "effect";
|
|
394
|
+
* import { Request } from "viell-effect-schema-http";
|
|
395
|
+
* const search = Request.get("https://api.example.test/users").pipe(
|
|
396
|
+
* Request.query(Schema.Struct({ page: Schema.NumberFromString })),
|
|
397
|
+
* );
|
|
398
|
+
* // Input: { query: { page: 2 } }; URL query: ?page=2
|
|
399
|
+
* ```
|
|
400
|
+
*
|
|
401
|
+
* @remarks
|
|
402
|
+
* The schema encodes to `UrlEncoding.QueryInput`. It replaces raw query declarations, including
|
|
403
|
+
* the constructor's query string, and owns the group. Later raw setters or another query schema
|
|
404
|
+
* are unavailable. Use {@link mapInput} to supply application defaults.
|
|
405
|
+
*/
|
|
406
|
+
export const query = <
|
|
407
|
+
S extends Schema.ConstraintCodec<
|
|
408
|
+
unknown,
|
|
409
|
+
UrlEncoding.QueryInput,
|
|
410
|
+
unknown,
|
|
411
|
+
unknown
|
|
412
|
+
>,
|
|
413
|
+
>(
|
|
414
|
+
contract: S,
|
|
415
|
+
) => {
|
|
416
|
+
const encode = Schema.encodeEffect(contract);
|
|
417
|
+
return <I, E, R, H extends boolean>(
|
|
418
|
+
self: Request<I, E, R, H, false>,
|
|
419
|
+
): Request<
|
|
420
|
+
I & { readonly query: S["Type"] },
|
|
421
|
+
E | Schema.SchemaError,
|
|
422
|
+
R | S["EncodingServices"],
|
|
423
|
+
H,
|
|
424
|
+
true
|
|
425
|
+
> =>
|
|
426
|
+
construct(
|
|
427
|
+
{ ...self.declaration, query: [], queryBound: true },
|
|
428
|
+
Effect.fnUntraced(function* (
|
|
429
|
+
input: I & { readonly query: S["Type"] },
|
|
430
|
+
draft: Draft,
|
|
431
|
+
) {
|
|
432
|
+
const encoded = yield* encode(input.query);
|
|
433
|
+
const prepared = yield* self.prepare(input, draft);
|
|
434
|
+
return replaceQuery(prepared, UrlEncoding.queryEntries(encoded));
|
|
435
|
+
}),
|
|
436
|
+
);
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Bind a schema to `{ path }` input and render the complete request path.
|
|
441
|
+
*
|
|
442
|
+
* @example
|
|
443
|
+
* ```ts
|
|
444
|
+
* import { Schema } from "effect";
|
|
445
|
+
* import { Request } from "viell-effect-schema-http";
|
|
446
|
+
* const user = Request.get("").pipe(
|
|
447
|
+
* Request.baseUrl("https://api.example.test"),
|
|
448
|
+
* Request.path(Schema.NumberFromString, (id, encode) => `/users/${encode(id)}`),
|
|
449
|
+
* );
|
|
450
|
+
* // Input: { path: 42 }; URL: https://api.example.test/users/42
|
|
451
|
+
* ```
|
|
452
|
+
*
|
|
453
|
+
* @remarks
|
|
454
|
+
* The value under `path` has the schema's application type. A scalar schema takes a scalar;
|
|
455
|
+
* `Schema.Struct({ userId: Schema.NumberFromString })` takes `{ userId: number }`. Use a struct
|
|
456
|
+
* to name one path value or group several. Renderer parameter names do not affect the input type.
|
|
457
|
+
*
|
|
458
|
+
* The renderer receives the schema-encoded value and the active path-value encoder. Escape each
|
|
459
|
+
* dynamic value with that encoder. The returned path replaces the constructor's path; it does
|
|
460
|
+
* not append to it. The shared base URL is joined afterwards. Reuse renderer functions for
|
|
461
|
+
* nested resources rather than stacking path bindings.
|
|
462
|
+
* Renderer or path-encoding exceptions become {@link InvalidRequest}; schema failures remain
|
|
463
|
+
* `SchemaError` values.
|
|
464
|
+
*/
|
|
465
|
+
export const path = <S extends Schema.Constraint>(
|
|
466
|
+
contract: S,
|
|
467
|
+
render: (value: S["Encoded"], encode: UrlEncoding.Service["path"]) => string,
|
|
468
|
+
) => {
|
|
469
|
+
const encode = Schema.encodeEffect(contract);
|
|
470
|
+
return <I, E, R, H extends boolean, Q extends boolean>(
|
|
471
|
+
self: Request<I, E, R, H, Q>,
|
|
472
|
+
): Request<
|
|
473
|
+
I & { readonly path: S["Type"] },
|
|
474
|
+
E | Schema.SchemaError | InvalidRequest,
|
|
475
|
+
R | S["EncodingServices"],
|
|
476
|
+
H,
|
|
477
|
+
Q
|
|
478
|
+
> =>
|
|
479
|
+
construct(
|
|
480
|
+
self.declaration,
|
|
481
|
+
Effect.fnUntraced(function* (
|
|
482
|
+
input: I & { readonly path: S["Type"] },
|
|
483
|
+
draft: Draft,
|
|
484
|
+
) {
|
|
485
|
+
const encoded = yield* encode(input.path);
|
|
486
|
+
const encoding = yield* UrlEncoding.UrlEncoding;
|
|
487
|
+
const prepared = yield* self.prepare(input, draft);
|
|
488
|
+
const url = yield* Effect.try({
|
|
489
|
+
try: () => render(encoded, encoding.path),
|
|
490
|
+
catch: (cause) =>
|
|
491
|
+
new InvalidRequest({
|
|
492
|
+
message: "Failed to render the request path",
|
|
493
|
+
cause,
|
|
494
|
+
}),
|
|
495
|
+
});
|
|
496
|
+
return {
|
|
497
|
+
...prepared,
|
|
498
|
+
request: HttpClientRequest.setUrl(prepared.request, url),
|
|
499
|
+
};
|
|
500
|
+
}),
|
|
501
|
+
);
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Bind an encoder to the call's `{ body }` input.
|
|
506
|
+
*
|
|
507
|
+
* @remarks
|
|
508
|
+
* The body is encoded once per operation evaluation. Its encoder determines `Content-Type` and
|
|
509
|
+
* `Content-Length`; multipart metadata is supplied by the transport.
|
|
510
|
+
*/
|
|
511
|
+
export const body =
|
|
512
|
+
<A, E2, R2>(codec: Body.Encoder<A, E2, R2>) =>
|
|
513
|
+
<I, E, R, H extends boolean, Q extends boolean>(
|
|
514
|
+
self: Request<I, E, R, H, Q>,
|
|
515
|
+
): Request<I & { readonly body: A }, E | E2, R | R2, H, Q> =>
|
|
516
|
+
construct(
|
|
517
|
+
self.declaration,
|
|
518
|
+
Effect.fnUntraced(function* (
|
|
519
|
+
input: I & { readonly body: A },
|
|
520
|
+
draft: Draft,
|
|
521
|
+
) {
|
|
522
|
+
const encoded = yield* codec.encode(input.body);
|
|
523
|
+
const prepared = yield* self.prepare(input, draft);
|
|
524
|
+
return {
|
|
525
|
+
...prepared,
|
|
526
|
+
request: HttpClientRequest.setBody(prepared.request, encoded),
|
|
527
|
+
};
|
|
528
|
+
}),
|
|
529
|
+
);
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Adapt your application's argument to this request's required input.
|
|
533
|
+
*
|
|
534
|
+
* @remarks
|
|
535
|
+
* Use it to rename fields or supply defaults while preserving schema validation. The mapping
|
|
536
|
+
* runs during preparation; a thrown exception is a defect.
|
|
537
|
+
*/
|
|
538
|
+
export const mapInput =
|
|
539
|
+
<I, I2>(f: (input: I2) => I) =>
|
|
540
|
+
<E, R, H extends boolean, Q extends boolean>(
|
|
541
|
+
self: Request<I, E, R, H, Q>,
|
|
542
|
+
): Request<I2, E, R, H, Q> =>
|
|
543
|
+
construct(self.declaration, (input, draft) =>
|
|
544
|
+
Effect.suspend(() => self.prepare(f(input), draft)),
|
|
545
|
+
);
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Edit the native request with an Effect during preparation.
|
|
549
|
+
*
|
|
550
|
+
* @remarks
|
|
551
|
+
* Runs once per evaluation, before attempts, after preceding preparation steps. The base URL
|
|
552
|
+
* and separate query parameters are not yet rendered. Use `Operation.make`'s `transformClient`
|
|
553
|
+
* for per-attempt credentials or signing the materialized URL. Provider normalization still
|
|
554
|
+
* applies afterwards.
|
|
555
|
+
*
|
|
556
|
+
* 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.
|
|
558
|
+
*/
|
|
559
|
+
export const mapEffect =
|
|
560
|
+
<I, E2, R2>(
|
|
561
|
+
f: (
|
|
562
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
563
|
+
input: I,
|
|
564
|
+
) => Effect.Effect<HttpClientRequest.HttpClientRequest, E2, R2>,
|
|
565
|
+
) =>
|
|
566
|
+
<E, R, H extends boolean, Q extends boolean, I2 extends I = I>(
|
|
567
|
+
self: Request<I, E, R, H, Q> | Request<I2, E, R, H, Q>,
|
|
568
|
+
): Request<I2, E | E2, R | R2, H, Q> =>
|
|
569
|
+
construct(self.declaration, (input: I2, draft) =>
|
|
570
|
+
Effect.flatMap(self.prepare(input, draft), (prepared) =>
|
|
571
|
+
Effect.map(f(prepared.request, input), (request) => ({
|
|
572
|
+
...prepared,
|
|
573
|
+
request,
|
|
574
|
+
})),
|
|
575
|
+
),
|
|
576
|
+
);
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* A prepared native request and the header lines a supporting provider can send.
|
|
580
|
+
*/
|
|
581
|
+
export interface Compiled {
|
|
582
|
+
readonly request: HttpClientRequest.HttpClientRequest;
|
|
583
|
+
readonly headerLines: Transport.Lines;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
const initialDraft = (declaration: Declaration): Draft => {
|
|
587
|
+
// Custom method strings pass through at runtime; the method union is narrower than the transport.
|
|
588
|
+
const native = HttpClientRequest.make(
|
|
589
|
+
declaration.method as HttpMethod.HttpMethod,
|
|
590
|
+
)(declaration.url);
|
|
591
|
+
const headerLines = Fields.resolve(declaration.headers);
|
|
592
|
+
return replaceQuery(
|
|
593
|
+
{
|
|
594
|
+
request: HttpClientRequest.setHeaders(
|
|
595
|
+
native,
|
|
596
|
+
Transport.toHeaders(headerLines),
|
|
597
|
+
),
|
|
598
|
+
headerLines,
|
|
599
|
+
bareKeys: new Set(),
|
|
600
|
+
},
|
|
601
|
+
Fields.resolve(declaration.query),
|
|
602
|
+
);
|
|
603
|
+
};
|
|
604
|
+
|
|
605
|
+
const finalize = (
|
|
606
|
+
draft: Draft,
|
|
607
|
+
base: string,
|
|
608
|
+
encoding: UrlEncoding.Service,
|
|
609
|
+
): Compiled => {
|
|
610
|
+
const { request } = draft;
|
|
611
|
+
const url = encoding.join(base, request.url);
|
|
612
|
+
const search = encoding.query(
|
|
613
|
+
request.urlParams.params.map((param) => [
|
|
614
|
+
param[0],
|
|
615
|
+
draft.bareKeys.has(param)
|
|
616
|
+
? null
|
|
617
|
+
: Redacted.isRedacted(param[1])
|
|
618
|
+
? Redacted.value(param[1])
|
|
619
|
+
: param[1],
|
|
620
|
+
]),
|
|
621
|
+
);
|
|
622
|
+
const compiled = HttpClientRequest.makeWith(
|
|
623
|
+
request.method,
|
|
624
|
+
search === "" ? url : `${url}${url.includes("?") ? "&" : "?"}${search}`,
|
|
625
|
+
UrlParams.empty,
|
|
626
|
+
request.hash,
|
|
627
|
+
request.headers,
|
|
628
|
+
request.body,
|
|
629
|
+
);
|
|
630
|
+
return {
|
|
631
|
+
request: compiled,
|
|
632
|
+
headerLines: Transport.reconcile(draft.headerLines, compiled.headers),
|
|
633
|
+
};
|
|
634
|
+
};
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* Prepare a request and its header lines without sending it.
|
|
638
|
+
*
|
|
639
|
+
* @example
|
|
640
|
+
* ```ts
|
|
641
|
+
* import { Effect } from "effect";
|
|
642
|
+
* import { Request } from "viell-effect-schema-http";
|
|
643
|
+
* const result = await Effect.runPromise(
|
|
644
|
+
* Request.compile(Request.get("https://api.example.test/health"), undefined),
|
|
645
|
+
* );
|
|
646
|
+
* // result.request.url === "https://api.example.test/health"
|
|
647
|
+
* ```
|
|
648
|
+
*
|
|
649
|
+
* @remarks
|
|
650
|
+
* Each evaluation resolves computed fields and encodes input once. The returned Effect requires
|
|
651
|
+
* any services used by the input schemas or preparation. Use {@link materialize} when only the
|
|
652
|
+
* native request is needed.
|
|
653
|
+
*/
|
|
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>,
|
|
662
|
+
input: I,
|
|
663
|
+
): Effect.fn.Return<Compiled, E | InvalidRequest, R> {
|
|
664
|
+
const encoding = yield* UrlEncoding.UrlEncoding;
|
|
665
|
+
const initial = yield* Effect.try({
|
|
666
|
+
try: () => initialDraft(self.declaration),
|
|
667
|
+
catch: (cause) =>
|
|
668
|
+
new InvalidRequest({
|
|
669
|
+
message: "Failed to materialize request fields",
|
|
670
|
+
cause,
|
|
671
|
+
}),
|
|
672
|
+
});
|
|
673
|
+
const draft = yield* self.prepare(input, initial);
|
|
674
|
+
const { method } = draft.request;
|
|
675
|
+
if (
|
|
676
|
+
(method === "GET" || method === "HEAD") &&
|
|
677
|
+
draft.request.body._tag !== "Empty"
|
|
678
|
+
) {
|
|
679
|
+
return yield* new InvalidRequest({
|
|
680
|
+
message: `${method} cannot carry a request body`,
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
return yield* Effect.try({
|
|
684
|
+
try: () => finalize(draft, self.declaration.baseUrl, encoding),
|
|
685
|
+
catch: (cause) =>
|
|
686
|
+
new InvalidRequest({ message: "Failed to encode request URL", cause }),
|
|
687
|
+
});
|
|
688
|
+
});
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* Prepare only the native request, without sending it.
|
|
692
|
+
*
|
|
693
|
+
* @remarks
|
|
694
|
+
* Use {@link compile} to retain the original header-line representation as well.
|
|
695
|
+
*/
|
|
696
|
+
export const materialize = <I, E, R, H extends boolean, Q extends boolean>(
|
|
697
|
+
self: Request<I, E, R, H, Q>,
|
|
698
|
+
input: I,
|
|
699
|
+
): Effect.Effect<HttpClientRequest.HttpClientRequest, E | InvalidRequest, R> =>
|
|
700
|
+
Effect.map(compile(self, input), (compiled) => compiled.request);
|