viell-effect-schema-http 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +44 -29
  2. package/dist/concurrency/Interaction.d.ts +7 -1
  3. package/dist/concurrency/Interaction.d.ts.map +1 -1
  4. package/dist/concurrency/Interaction.js.map +1 -1
  5. package/dist/http/Body.d.ts +25 -13
  6. package/dist/http/Body.d.ts.map +1 -1
  7. package/dist/http/Body.js +18 -8
  8. package/dist/http/Body.js.map +1 -1
  9. package/dist/http/Operation.d.ts +276 -13
  10. package/dist/http/Operation.d.ts.map +1 -1
  11. package/dist/http/Operation.js +210 -11
  12. package/dist/http/Operation.js.map +1 -1
  13. package/dist/http/Policy.d.ts +28 -2
  14. package/dist/http/Policy.d.ts.map +1 -1
  15. package/dist/http/Policy.js +28 -2
  16. package/dist/http/Policy.js.map +1 -1
  17. package/dist/http/Request.d.ts +520 -85
  18. package/dist/http/Request.d.ts.map +1 -1
  19. package/dist/http/Request.js +658 -143
  20. package/dist/http/Request.js.map +1 -1
  21. package/dist/http/Response.d.ts +130 -6
  22. package/dist/http/Response.d.ts.map +1 -1
  23. package/dist/http/Response.js +88 -7
  24. package/dist/http/Response.js.map +1 -1
  25. package/dist/http/UrlEncoding.d.ts +24 -7
  26. package/dist/http/UrlEncoding.d.ts.map +1 -1
  27. package/dist/http/UrlEncoding.js +7 -3
  28. package/dist/http/UrlEncoding.js.map +1 -1
  29. package/dist/http/internal/excess.d.ts +44 -0
  30. package/dist/http/internal/excess.d.ts.map +1 -0
  31. package/dist/http/internal/excess.js +231 -0
  32. package/dist/http/internal/excess.js.map +1 -0
  33. package/dist/http/internal/fields.d.ts +17 -4
  34. package/dist/http/internal/fields.d.ts.map +1 -1
  35. package/dist/http/internal/fields.js +11 -6
  36. package/dist/http/internal/fields.js.map +1 -1
  37. package/dist/http/internal/input.d.ts +70 -0
  38. package/dist/http/internal/input.d.ts.map +1 -0
  39. package/dist/http/internal/input.js +93 -0
  40. package/dist/http/internal/input.js.map +1 -0
  41. package/dist/http/internal/shape.d.ts +63 -0
  42. package/dist/http/internal/shape.d.ts.map +1 -0
  43. package/dist/http/internal/shape.js +225 -0
  44. package/dist/http/internal/shape.js.map +1 -0
  45. package/package.json +13 -12
  46. package/src/concurrency/Interaction.ts +7 -1
  47. package/src/http/Body.ts +41 -18
  48. package/src/http/Operation.ts +474 -33
  49. package/src/http/Policy.ts +30 -2
  50. package/src/http/Request.ts +1176 -253
  51. package/src/http/Response.ts +246 -23
  52. package/src/http/UrlEncoding.ts +32 -8
  53. package/src/http/internal/excess.ts +333 -0
  54. package/src/http/internal/fields.ts +37 -9
  55. package/src/http/internal/input.ts +228 -0
  56. package/src/http/internal/shape.ts +359 -0
@@ -13,11 +13,14 @@ import * as Transport from "./Transport.js";
13
13
  *
14
14
  * @remarks
15
15
  * Contains no body. Header and cookie visibility depends on the HTTP provider and browser.
16
- * `headerLines` is present only when a provider attached its observed lines.
16
+ * `headerLines` is `None` unless a provider attached its observed lines.
17
17
  */
18
18
  export interface Metadata {
19
+ /** The HTTP status code. */
19
20
  readonly status: number;
21
+ /** The normalized headers: lowercase names, with repeated lines joined. */
20
22
  readonly headers: Headers.Headers;
23
+ /** The cookies the response set, as far as the provider shows them. */
21
24
  readonly cookies: Cookies.Cookies;
22
25
  /** Provider-observed lines, when the provider supplied them. Normalized headers are always available. */
23
26
  readonly headerLines: Option.Option<Transport.Lines>;
@@ -51,14 +54,118 @@ export class DecodeError<out E> extends Data.TaggedError("DecodeError")<{
51
54
  * @remarks
52
55
  * Build cases with {@link status} or {@link when}, then combine them with {@link orElse}.
53
56
  * A declared status, including 4xx or 5xx, returns the decoder's value if decoding succeeds.
57
+ * Adjust a contract with {@link replace} and {@link remove}.
58
+ *
59
+ * `C` records each case and its key, which is what lets a replaced case leave the type. Annotating
60
+ * a value as `Response<A, E, R>` drops the keys, so no case of it can be addressed any more.
54
61
  */
55
- export interface Response<out A, out E = never, out R = never>
62
+ export interface Response<
63
+ out A,
64
+ out E = never,
65
+ out R = never,
66
+ out C extends AnyCase = AnyCase,
67
+ >
56
68
  extends Pipeable.Pipeable {
69
+ /** The decoder of the first case that matches, if any case does. */
57
70
  readonly select: (metadata: Metadata) => Option.Option<Body.Decoder<A, E, R>>;
58
71
  /** Media types contributed to the automatic `Accept` header, in declaration order. */
59
72
  readonly accepts: ReadonlyArray<string>;
73
+ /** The contract's cases, in priority order. */
74
+ readonly cases: ReadonlyArray<C>;
75
+ }
76
+
77
+ /**
78
+ * One case of a contract: when it applies, what decodes it, and the key that addresses it.
79
+ *
80
+ * @remarks
81
+ * A {@link status} case is keyed by its status, and a {@link when} case by its `key` option, or
82
+ * `undefined` without one. Tags from {@link tag} are labels on results, not keys: they are optional
83
+ * and can repeat.
84
+ */
85
+ export interface Case<out K, out A, out E, out R> {
86
+ /** What addresses this case in {@link replace} and {@link remove}. */
87
+ readonly key: K;
88
+ /** Whether this case applies, from the metadata alone. */
89
+ readonly matches: (metadata: Metadata) => boolean;
90
+ /** What reads the body when this case is selected. */
91
+ readonly decoder: Body.Decoder<A, E, R>;
60
92
  }
61
93
 
94
+ /** Any case of any contract: the bound of {@link Response}'s case parameter. */
95
+ export type AnyCase = Case<unknown, unknown, unknown, unknown>;
96
+
97
+ /** A value that can address a case: a status, or the `key` option of {@link when}. */
98
+ export type Key = string | number;
99
+
100
+ /**
101
+ * The results of a set of cases.
102
+ *
103
+ * @remarks
104
+ * This and the other helpers below are public so that the declaration of a transform held in an
105
+ * exported variable, such as `export const asText = Response.replace(200, Body.text)`, can name
106
+ * them. A private interface there stops the declaration emitting, and a private alias printed in
107
+ * full can lose its meaning.
108
+ */
109
+ export type CaseValue<C> =
110
+ C extends Case<unknown, infer A, unknown, unknown> ? A : never;
111
+
112
+ /** The decoder failures of a set of cases. */
113
+ export type CaseFailure<C> =
114
+ C extends Case<unknown, unknown, infer E, unknown> ? E : never;
115
+
116
+ /** The services a set of cases requires. */
117
+ export type CaseServices<C> =
118
+ C extends Case<unknown, unknown, unknown, infer R> ? R : never;
119
+
120
+ type IsUnion<K, All = K> = K extends unknown
121
+ ? [All] extends [K]
122
+ ? false
123
+ : true
124
+ : never;
125
+
126
+ /** A record over a literal requires that key; one over `number`, `string` or a pattern does not. */
127
+ type IsLiteral<K> =
128
+ Record<never, never> extends Record<K & Key, unknown> ? false : true;
129
+
130
+ /**
131
+ * The keys of `C` that can be addressed. A widened or union key proves nothing about which case
132
+ * this is, so the type could not say what an edit leaves behind.
133
+ */
134
+ export type KeyOf<C> =
135
+ C extends Case<infer K, unknown, unknown, unknown>
136
+ ? IsUnion<K> extends false
137
+ ? IsLiteral<K> extends true
138
+ ? K
139
+ : never
140
+ : never
141
+ : never;
142
+
143
+ /** The cases of `C` other than those keyed exactly `K`. */
144
+ export type Without<C, K> =
145
+ C extends Case<infer CK, unknown, unknown, unknown>
146
+ ? [CK] extends [K]
147
+ ? never
148
+ : C
149
+ : never;
150
+
151
+ /** The compile error for a union of keys. Its one member's name is the message. */
152
+ export interface OneKeyAtATime<K> {
153
+ readonly "Pass one key at a time. Only the value passed is touched at run time, so a union of keys would leave cases the type says are gone.": K;
154
+ }
155
+
156
+ /** The compile error for a key the contract lacks. Its one member's name is the message. */
157
+ export interface NoSuchCase<K> {
158
+ readonly "This contract has no case with this literal key. Only a literal status or `key` option can be addressed.": K;
159
+ }
160
+
161
+ /**
162
+ * The union check stays a separate member: nested in the other conditional it refuses nothing. The
163
+ * type would drop every member of the union, but at run time only the value passed is touched, so
164
+ * the other cases would stay and could reach a mapping that no longer expects them.
165
+ */
166
+ type Addresses<C, K> = (IsUnion<K> extends false ? unknown : OneKeyAtATime<K>) &
167
+ ([K] extends [KeyOf<C>] ? unknown : NoSuchCase<K>);
168
+
62
169
  /**
63
170
  * Read metadata from an Effect HTTP response without consuming its body.
64
171
  */
@@ -71,30 +178,65 @@ export const metadata = (
71
178
  headerLines: Transport.responseHeaderLines(response),
72
179
  });
73
180
 
74
- const make = <A, E, R>(
75
- select: Response<A, E, R>["select"],
76
- accepts: ReadonlyArray<string>,
77
- ): Response<A, E, R> => ({
181
+ const fromCases = <A, E, R, C extends AnyCase>(
182
+ cases: ReadonlyArray<C>,
183
+ ): Response<A, E, R, C> => ({
78
184
  ...Pipeable.Prototype,
79
- select,
80
- accepts,
185
+ cases,
186
+ select: (info) => {
187
+ const selected = cases.find((entry) => entry.matches(info));
188
+ return selected === undefined
189
+ ? Option.none()
190
+ : Option.some(selected.decoder as Body.Decoder<A, E, R>);
191
+ },
192
+ accepts: Array.from(
193
+ new Set(
194
+ cases.flatMap(({ decoder }) =>
195
+ decoder.mediaType === undefined ? [] : [decoder.mediaType],
196
+ ),
197
+ ),
198
+ ),
81
199
  });
82
200
 
201
+ /** A contract after an edit. Its signature states the types, which depend on the key removed. */
202
+ const edited = <Result>(cases: ReadonlyArray<AnyCase>): Result => {
203
+ const contract: unknown = fromCases(cases);
204
+ return contract as Result;
205
+ };
206
+
207
+ /** The first position of a key. A key that got past the types must not silently edit nothing. */
208
+ const positionOf = (cases: ReadonlyArray<AnyCase>, key: Key): number => {
209
+ const position =
210
+ key === undefined ? -1 : cases.findIndex((entry) => entry.key === key);
211
+ if (position === -1)
212
+ throw new Error(
213
+ `This response contract has no case ${typeof key === "string" ? JSON.stringify(key) : String(key)}`,
214
+ );
215
+ return position;
216
+ };
217
+
83
218
  /**
84
219
  * Select a body decoder when a predicate accepts the response metadata.
85
220
  *
221
+ * @example
222
+ * ```ts
223
+ * import { Body, Response } from "viell-effect-schema-http";
224
+ * const serverError = Response.when((info) => info.status >= 500, Body.text, {
225
+ * key: "server",
226
+ * });
227
+ * ```
228
+ *
86
229
  * @remarks
87
230
  * The predicate runs before body decoding. It cannot select by payload contents; use one schema
88
- * with alternatives for payloads sharing the same metadata.
231
+ * with alternatives for payloads sharing the same metadata. A `key` lets {@link replace} and
232
+ * {@link remove} address the case; it has no effect on selection.
89
233
  */
90
- export const when = <A, E, R>(
234
+ export const when = <A, E, R, const K extends Key | undefined = undefined>(
91
235
  predicate: (metadata: Metadata) => boolean,
92
236
  body: Body.Decoder<A, E, R>,
93
- ): Response<A, E, R> =>
94
- make(
95
- (info) => (predicate(info) ? Option.some(body) : Option.none()),
96
- body.mediaType === undefined ? [] : [body.mediaType],
97
- );
237
+ options?: { readonly key?: K },
238
+ ): Response<A, E, R, Case<K, A, E, R>> =>
239
+ fromCases([{ key: options?.key as K, matches: predicate, decoder: body }]);
98
240
 
99
241
  /**
100
242
  * Select a body decoder for one exact HTTP status.
@@ -105,10 +247,13 @@ export const when = <A, E, R>(
105
247
  * const health = Response.status(200, Body.text);
106
248
  * ```
107
249
  */
108
- export const status = <A, E, R>(
109
- code: number,
250
+ export const status = <A, E, R, const K extends number = number>(
251
+ code: K,
110
252
  body: Body.Decoder<A, E, R>,
111
- ): Response<A, E, R> => when((info) => info.status === code, body);
253
+ ): Response<A, E, R, Case<K, A, E, R>> =>
254
+ fromCases([
255
+ { key: code, matches: (info) => info.status === code, decoder: body },
256
+ ]);
112
257
 
113
258
  /**
114
259
  * Use another response contract when this one has no matching case.
@@ -118,12 +263,87 @@ export const status = <A, E, R>(
118
263
  * A selected decoder's failure never tries the fallback.
119
264
  */
120
265
  export const orElse =
121
- <B, E2, R2>(that: Response<B, E2, R2>) =>
122
- <A, E, R>(self: Response<A, E, R>): Response<A | B, E | E2, R | R2> =>
123
- make<A | B, E | E2, R | R2>(
124
- (info) => Option.orElse(self.select(info), () => that.select(info)),
125
- Array.from(new Set([...self.accepts, ...that.accepts])),
266
+ <B, E2, R2, C2 extends AnyCase = AnyCase>(that: Response<B, E2, R2, C2>) =>
267
+ <A, E, R, C extends AnyCase = AnyCase>(
268
+ self: Response<A, E, R, C>,
269
+ ): Response<A | B, E | E2, R | R2, C | C2> =>
270
+ fromCases([...self.cases, ...that.cases]);
271
+
272
+ /**
273
+ * Replace the decoder of the case with this key, keeping its position and its match rule.
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * import { Body, Response } from "viell-effect-schema-http";
278
+ * const full = Response.status(200, Body.json).pipe(
279
+ * Response.orElse(Response.status(404, Body.empty)),
280
+ * );
281
+ * const asText = full.pipe(Response.replace(200, Body.text));
282
+ * // A 200 is now text. The 404 case is unchanged, and `full` still reads JSON.
283
+ * ```
284
+ *
285
+ * @remarks
286
+ * Declaration order is priority, so only the decoder changes. If several cases share the key, the
287
+ * first keeps its position and the others go. The result type holds only the cases that can still
288
+ * occur, and the automatic `Accept` follows the new decoder.
289
+ *
290
+ * The key must be one literal the contract declares: a key that is absent, widened to `number` or
291
+ * `string`, or a union is a compile error. One that gets past the types with a cast throws here,
292
+ * when the contract is built. To add a case, use {@link orElse} or place the new case first.
293
+ */
294
+ export const replace =
295
+ <const K extends Key, B, E2, R2>(key: K, body: Body.Decoder<B, E2, R2>) =>
296
+ <A, E, R, C extends AnyCase>(
297
+ self: Response<A, E, R, C> & Addresses<C, K>,
298
+ ): Response<
299
+ CaseValue<Without<C, K>> | B,
300
+ CaseFailure<Without<C, K>> | E2,
301
+ CaseServices<Without<C, K>> | R2,
302
+ Without<C, K> | Case<K, B, E2, R2>
303
+ > => {
304
+ const position = positionOf(self.cases, key);
305
+ return edited(
306
+ self.cases.flatMap((entry, index) =>
307
+ index === position
308
+ ? [{ ...entry, decoder: body }]
309
+ : entry.key === key
310
+ ? []
311
+ : [entry],
312
+ ),
126
313
  );
314
+ };
315
+
316
+ /**
317
+ * Remove every case with this key.
318
+ *
319
+ * @example
320
+ * ```ts
321
+ * import { Body, Response } from "viell-effect-schema-http";
322
+ * const full = Response.status(200, Body.json).pipe(
323
+ * Response.orElse(Response.status(404, Body.empty)),
324
+ * );
325
+ * const onlyFound = full.pipe(Response.remove(404));
326
+ * // A 404 now falls through to any later case, or fails with UnexpectedResponse.
327
+ * ```
328
+ *
329
+ * @remarks
330
+ * The result type holds only the cases that can still occur. The key follows the same rules as in
331
+ * {@link replace}: a key that is absent, not literal or a union is a compile error, and one that
332
+ * gets past the types throws here.
333
+ */
334
+ export const remove =
335
+ <const K extends Key>(key: K) =>
336
+ <A, E, R, C extends AnyCase>(
337
+ self: Response<A, E, R, C> & Addresses<C, K>,
338
+ ): Response<
339
+ CaseValue<Without<C, K>>,
340
+ CaseFailure<Without<C, K>>,
341
+ CaseServices<Without<C, K>>,
342
+ Without<C, K>
343
+ > => {
344
+ positionOf(self.cases, key);
345
+ return edited(self.cases.filter((entry) => entry.key !== key));
346
+ };
127
347
 
128
348
  /**
129
349
  * A decoded value labelled with its case name and response metadata.
@@ -132,8 +352,11 @@ export const orElse =
132
352
  * Checking `_tag` narrows the value type when several tagged outcomes form a union.
133
353
  */
134
354
  export interface Tagged<Tag extends string, A> {
355
+ /** The case name given to {@link tag}. */
135
356
  readonly _tag: Tag;
357
+ /** The decoded value. */
136
358
  readonly value: A;
359
+ /** The metadata of the response it came from. */
137
360
  readonly metadata: Metadata;
138
361
  }
139
362
 
@@ -12,9 +12,18 @@ export type Query = ReadonlyArray<readonly [string, string | null]>;
12
12
  * A scalar query value before conversion to URL text.
13
13
  *
14
14
  * @remarks
15
- * `null` keeps a bare key and `undefined` omits an entry. Other values are converted to strings.
15
+ * `null` keeps a bare key and `undefined` omits an entry. A `Date` becomes its ISO text, and other
16
+ * values are converted to strings. An invalid `Date` has no ISO text, so it goes out as
17
+ * `String(value)`, and a schema such as `Schema.Date` refuses it before that.
16
18
  */
17
- export type QueryValue = string | number | bigint | boolean | null | undefined;
19
+ export type QueryValue =
20
+ string | number | bigint | boolean | Date | null | undefined;
21
+
22
+ /** The URL text of a value that has one. */
23
+ const queryText = (value: Exclude<QueryValue, null | undefined>): string =>
24
+ value instanceof Date && !Number.isNaN(value.getTime())
25
+ ? value.toISOString()
26
+ : String(value);
18
27
 
19
28
  /**
20
29
  * A record or iterable of query pairs accepted as a schema's encoded output.
@@ -37,8 +46,8 @@ export type QueryInput =
37
46
  * ```
38
47
  *
39
48
  * @remarks
40
- * Omits `undefined`, keeps `null`, and converts other scalar values to strings. URL escaping
41
- * happens later through the query renderer.
49
+ * Omits `undefined`, keeps `null`, writes a `Date` as ISO text, and converts other scalar values to
50
+ * strings. URL escaping happens later through the query renderer.
42
51
  */
43
52
  export const queryEntries = (input: QueryInput): Query => {
44
53
  const entries =
@@ -48,7 +57,7 @@ export const queryEntries = (input: QueryInput): Query => {
48
57
  (Array.isArray(value) ? value : [value]).flatMap((entry: QueryValue) =>
49
58
  entry === undefined
50
59
  ? []
51
- : [[key, entry === null ? null : String(entry)] as const],
60
+ : [[key, entry === null ? null : queryText(entry)] as const],
52
61
  ),
53
62
  );
54
63
  };
@@ -61,11 +70,26 @@ export const queryEntries = (input: QueryInput): Query => {
61
70
  * service that needs another URL representation.
62
71
  */
63
72
  export interface Service {
64
- /** Escape one dynamic path value; the renderer supplies separators between values. */
73
+ /** Escape one dynamic path value; a template or renderer supplies the text between values. */
65
74
  readonly path: (value: string) => string;
66
- /** Render ordered query entries without a leading `?`. */
75
+ /**
76
+ * Render ordered query entries without a leading `?`.
77
+ *
78
+ * @remarks
79
+ * Text written in a request's constructor stays as written and is not passed here. Where it
80
+ * stands between other entries, each run of them is rendered by a separate call, keeping the
81
+ * order of the query. A request with no entries gets one call with an empty array, and a query
82
+ * made only of written text gets no call, so add a fixed entry with `Request.setQuery` in a
83
+ * shared transform rather than here.
84
+ */
67
85
  readonly query: (entries: Query) => string;
68
- /** Combine the base origin/prefix and the request's rendered path or absolute URL. */
86
+ /**
87
+ * Combine the base origin/prefix and the request's rendered path or absolute URL.
88
+ *
89
+ * @remarks
90
+ * Both arrive without a fragment. A fragment in the result moves to the request's `hash`, so the
91
+ * query goes before it, unless a fragment from the request or the base wins.
92
+ */
69
93
  readonly join: (base: string, path: string) => string;
70
94
  }
71
95