viell-effect-schema-http 0.2.0 → 0.4.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 +8 -6
- 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 +2 -0
- package/dist/http/Body.d.ts.map +1 -1
- package/dist/http/Body.js.map +1 -1
- package/dist/http/Operation.d.ts +6 -0
- package/dist/http/Operation.d.ts.map +1 -1
- package/dist/http/Operation.js.map +1 -1
- package/dist/http/Policy.d.ts +25 -0
- package/dist/http/Policy.d.ts.map +1 -1
- package/dist/http/Policy.js +25 -0
- package/dist/http/Policy.js.map +1 -1
- package/dist/http/Request.d.ts +109 -23
- package/dist/http/Request.d.ts.map +1 -1
- package/dist/http/Request.js +121 -21
- package/dist/http/Request.js.map +1 -1
- package/dist/http/Response.d.ts +11 -1
- package/dist/http/Response.d.ts.map +1 -1
- package/dist/http/Response.js.map +1 -1
- package/dist/http/UrlEncoding.d.ts +2 -1
- package/dist/http/UrlEncoding.d.ts.map +1 -1
- 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 +252 -0
- package/dist/http/internal/excess.js.map +1 -0
- package/dist/http/internal/input.d.ts +33 -8
- package/dist/http/internal/input.d.ts.map +1 -1
- package/dist/http/internal/input.js +102 -20
- package/dist/http/internal/input.js.map +1 -1
- package/dist/http/internal/shape.d.ts +21 -0
- package/dist/http/internal/shape.d.ts.map +1 -1
- package/dist/http/internal/shape.js +96 -12
- package/dist/http/internal/shape.js.map +1 -1
- package/package.json +3 -2
- package/src/concurrency/Interaction.ts +7 -1
- package/src/http/Body.ts +2 -0
- package/src/http/Operation.ts +6 -0
- package/src/http/Policy.ts +27 -0
- package/src/http/Request.ts +236 -31
- package/src/http/Response.ts +11 -1
- package/src/http/UrlEncoding.ts +2 -1
- package/src/http/internal/excess.ts +370 -0
- package/src/http/internal/input.ts +200 -37
- package/src/http/internal/shape.ts +148 -12
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import { Equal, Schema, SchemaAST, SchemaIssue } from "effect";
|
|
2
|
+
|
|
3
|
+
/** Where a key sits in a value, one step for each level. */
|
|
4
|
+
export type Path = ReadonlyArray<PropertyKey>;
|
|
5
|
+
|
|
6
|
+
type Ast = SchemaAST.AST;
|
|
7
|
+
|
|
8
|
+
/** Parse options that make a schema refuse what it would strip. */
|
|
9
|
+
export const strict: SchemaAST.ParseOptions = { onExcessProperty: "error" };
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The node a schema's encoding ends at. `toEncoded` gives the same names, but it flattens each
|
|
13
|
+
* field's own encoding away, and that encoding is how a field says what it writes.
|
|
14
|
+
*/
|
|
15
|
+
export const encodedEnd = (ast: Ast): Ast => {
|
|
16
|
+
const last = ast.encoding?.at(-1);
|
|
17
|
+
return last === undefined ? ast : encodedEnd(last.to);
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The parts of a schema this can see. What a declaration holds, as an `Option` or a `Map` does, is
|
|
22
|
+
* not among them: nothing here can reach it, so the schema's own reading applies there.
|
|
23
|
+
*/
|
|
24
|
+
const partsOf = (ast: Ast): ReadonlyArray<Ast> => {
|
|
25
|
+
switch (ast._tag) {
|
|
26
|
+
case "Objects":
|
|
27
|
+
return [...ast.propertySignatures, ...ast.indexSignatures].map(
|
|
28
|
+
({ type }) => type,
|
|
29
|
+
);
|
|
30
|
+
case "Arrays":
|
|
31
|
+
return [...ast.elements, ...ast.rest];
|
|
32
|
+
case "Union":
|
|
33
|
+
return ast.types;
|
|
34
|
+
default:
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** Whether a schema can read an object's keys, and so can strip one of them. */
|
|
40
|
+
const readsKeys = (ast: Ast): boolean =>
|
|
41
|
+
ast._tag === "Objects" ||
|
|
42
|
+
ast._tag === "ObjectKeyword" ||
|
|
43
|
+
ast._tag === "Suspend" ||
|
|
44
|
+
ast._tag === "Unknown" ||
|
|
45
|
+
ast._tag === "Any" ||
|
|
46
|
+
partsOf(ast).some(readsKeys) ||
|
|
47
|
+
(ast.encoding ?? []).some(({ to }) => readsKeys(to));
|
|
48
|
+
|
|
49
|
+
/** A choice of member: a union between objects, or a suspended schema, which may not exist yet. */
|
|
50
|
+
const isMemberChoice = (ast: Ast): boolean =>
|
|
51
|
+
ast._tag === "Suspend" ||
|
|
52
|
+
(ast._tag === "Union" && ast.types.filter(readsKeys).length > 1);
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A choice of side: two ends that do not state the same names, as a renamed field's do, or an
|
|
56
|
+
* encoded end with a rest. A value on the encoded side can then fit the decoded side by losing the
|
|
57
|
+
* names it holds. An encoded side with no keys, such as text, has none to lose.
|
|
58
|
+
*/
|
|
59
|
+
const isSideChoice = (ast: Ast): boolean => {
|
|
60
|
+
const end = encodedEnd(ast);
|
|
61
|
+
if (end === ast || !readsKeys(end)) return false;
|
|
62
|
+
const decoded = fieldsOf(ast).map(({ name }) => name);
|
|
63
|
+
const encoded = fieldsOf(end).map(({ name }) => name);
|
|
64
|
+
return (
|
|
65
|
+
decoded.length !== encoded.length ||
|
|
66
|
+
decoded.some((name) => !encoded.includes(name)) ||
|
|
67
|
+
(end._tag === "Objects" && end.indexSignatures.length > 0)
|
|
68
|
+
);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const holding = (isChoice: (ast: Ast) => boolean) => {
|
|
72
|
+
const holds = (ast: Ast): boolean =>
|
|
73
|
+
isChoice(ast) ||
|
|
74
|
+
partsOf(ast).some(holds) ||
|
|
75
|
+
(ast.encoding ?? []).some(({ to }) => holds(to));
|
|
76
|
+
return holds;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** The fields of a struct or class, as they are declared, with each field's own encoding. */
|
|
80
|
+
export const fieldsOf = (
|
|
81
|
+
ast: Ast,
|
|
82
|
+
): ReadonlyArray<{ readonly name: PropertyKey; readonly type: Ast }> =>
|
|
83
|
+
ast._tag === "Objects"
|
|
84
|
+
? ast.propertySignatures
|
|
85
|
+
: ast._tag === "Declaration" && ast.encoding !== undefined
|
|
86
|
+
? fieldsOf(ast.encoding[0].to)
|
|
87
|
+
: [];
|
|
88
|
+
|
|
89
|
+
const isObject = (value: unknown): value is Record<PropertyKey, unknown> =>
|
|
90
|
+
typeof value === "object" && value !== null;
|
|
91
|
+
|
|
92
|
+
/** A plain object or a list, which can be taken apart. A class instance needs a reason to be. */
|
|
93
|
+
const isPlain = (value: unknown): value is Record<PropertyKey, unknown> => {
|
|
94
|
+
if (!isObject(value)) return false;
|
|
95
|
+
if (Array.isArray(value)) return true;
|
|
96
|
+
const prototype: unknown = Object.getPrototypeOf(value);
|
|
97
|
+
return prototype === Object.prototype || prototype === null;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const keysOf = (value: object): ReadonlyArray<PropertyKey> =>
|
|
101
|
+
Reflect.ownKeys(value).filter((key) =>
|
|
102
|
+
Object.prototype.propertyIsEnumerable.call(value, key),
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
/** Whether a side only holds literals, and this value is none of them. */
|
|
106
|
+
const refuses = (side: Ast, value: unknown): boolean =>
|
|
107
|
+
side._tag === "Literal"
|
|
108
|
+
? side.literal !== value
|
|
109
|
+
: side._tag === "Union" &&
|
|
110
|
+
side.types.every((member) => refuses(member, value));
|
|
111
|
+
|
|
112
|
+
/** Whether a literal field refuses a value on every side, which a tag can rule out by. */
|
|
113
|
+
const refusesLiteral = (type: Ast, value: unknown): boolean =>
|
|
114
|
+
[type, ...(type.encoding ?? []).map(({ to }) => to)].every((side) =>
|
|
115
|
+
refuses(side, value),
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
const onlyLiterals = (ast: Ast): boolean =>
|
|
119
|
+
ast._tag === "Literal" ||
|
|
120
|
+
(ast._tag === "Union" &&
|
|
121
|
+
ast.types.every(
|
|
122
|
+
(member) => member.encoding === undefined && onlyLiterals(member),
|
|
123
|
+
));
|
|
124
|
+
|
|
125
|
+
/** Each side of an object transformation, without guessing which names correspond. */
|
|
126
|
+
const objectSides = (ast: Ast): ReadonlyArray<Ast> => [
|
|
127
|
+
ast,
|
|
128
|
+
...(ast.encoding ?? []).flatMap(({ to }) => objectSides(to)),
|
|
129
|
+
];
|
|
130
|
+
|
|
131
|
+
/** Whether this view's literal tags make it impossible, without reading a default. */
|
|
132
|
+
const tagView = (
|
|
133
|
+
side: Ast,
|
|
134
|
+
value: Record<PropertyKey, unknown>,
|
|
135
|
+
constructing: boolean,
|
|
136
|
+
) => {
|
|
137
|
+
const tags = fieldsOf(side).filter(
|
|
138
|
+
({ type }) =>
|
|
139
|
+
!SchemaAST.isOptional(type) && objectSides(type).every(onlyLiterals),
|
|
140
|
+
);
|
|
141
|
+
const mismatch = tags.some(
|
|
142
|
+
({ name, type }) =>
|
|
143
|
+
value[name] !== undefined && refusesLiteral(type, value[name]),
|
|
144
|
+
);
|
|
145
|
+
const absent = tags.some(
|
|
146
|
+
({ name, type }) =>
|
|
147
|
+
value[name] === undefined &&
|
|
148
|
+
(!constructing || type.context?.constructorDefault === undefined),
|
|
149
|
+
);
|
|
150
|
+
return { impossible: mismatch || absent, mismatch };
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/** A tag can choose on either side; both views must rule a member out before its fields go. */
|
|
154
|
+
const ruledOut = (member: Ast, value: unknown): boolean => {
|
|
155
|
+
if (!isObject(value)) return false;
|
|
156
|
+
const decoded = tagView(member, value, true);
|
|
157
|
+
const encoded = tagView(SchemaAST.toEncoded(member), value, false);
|
|
158
|
+
return (
|
|
159
|
+
decoded.impossible &&
|
|
160
|
+
encoded.impossible &&
|
|
161
|
+
(decoded.mismatch || encoded.mismatch)
|
|
162
|
+
);
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
/** The schemas a value can be read against here: each member its tag leaves, on each side. */
|
|
166
|
+
const sidesOf = (ast: Ast, value: unknown): ReadonlyArray<Ast> => [
|
|
167
|
+
...(ast._tag === "Union"
|
|
168
|
+
? ast.types
|
|
169
|
+
.filter((member) => !ruledOut(member, value))
|
|
170
|
+
.flatMap((member) => sidesOf(member, value))
|
|
171
|
+
: ast._tag === "Suspend"
|
|
172
|
+
? sidesOf(ast.thunk(), value)
|
|
173
|
+
: [ast]),
|
|
174
|
+
...(ast.encoding ?? []).flatMap(({ to }) => sidesOf(to, value)),
|
|
175
|
+
];
|
|
176
|
+
|
|
177
|
+
/** The schemas of what these sides hold under one key. */
|
|
178
|
+
const typesAt = (
|
|
179
|
+
sides: ReadonlyArray<Ast>,
|
|
180
|
+
key: PropertyKey,
|
|
181
|
+
): ReadonlyArray<Ast> =>
|
|
182
|
+
sides.flatMap((side) => {
|
|
183
|
+
if (side._tag === "Arrays") {
|
|
184
|
+
const element = side.elements[Number(key)];
|
|
185
|
+
return element === undefined ? side.rest : [element];
|
|
186
|
+
}
|
|
187
|
+
return side._tag === "Objects"
|
|
188
|
+
? [
|
|
189
|
+
...side.propertySignatures
|
|
190
|
+
.filter(({ name }) => name === key)
|
|
191
|
+
.map(({ type }) => type),
|
|
192
|
+
...side.indexSignatures.map(({ type }) => type),
|
|
193
|
+
]
|
|
194
|
+
: [];
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
/** The names on a schema's decoded side, which a value can use as well as the wire names. */
|
|
198
|
+
const decodedNames = (ast: Ast, value?: unknown): ReadonlyArray<string> =>
|
|
199
|
+
ast._tag === "Union"
|
|
200
|
+
? ast.types
|
|
201
|
+
.filter((member) => !ruledOut(member, value))
|
|
202
|
+
.flatMap((member) => decodedNames(member, value))
|
|
203
|
+
: ast._tag === "Suspend"
|
|
204
|
+
? decodedNames(ast.thunk(), value)
|
|
205
|
+
: fieldsOf(ast).map(({ name }) => String(name));
|
|
206
|
+
|
|
207
|
+
/** Whether these sides leave a value's keys open, so none can be called unstated. */
|
|
208
|
+
const leaveKeysOpen = (sides: ReadonlyArray<Ast>): boolean =>
|
|
209
|
+
sides.some(
|
|
210
|
+
({ _tag }) =>
|
|
211
|
+
_tag === "Any" || _tag === "Unknown" || _tag === "ObjectKeyword",
|
|
212
|
+
) || !sides.some(({ _tag }) => _tag === "Objects" || _tag === "Arrays");
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The names a struct here reads from a value although they are no keys of it, as an accessor on a
|
|
216
|
+
* class is. A strict read only counts keys as excess, so it would strip such a field with no error.
|
|
217
|
+
*/
|
|
218
|
+
const unlisted = (
|
|
219
|
+
sides: ReadonlyArray<Ast>,
|
|
220
|
+
value: Record<PropertyKey, unknown>,
|
|
221
|
+
): ReadonlyArray<PropertyKey> =>
|
|
222
|
+
Array.isArray(value)
|
|
223
|
+
? []
|
|
224
|
+
: Array.from(
|
|
225
|
+
new Set(sides.flatMap(fieldsOf).map(({ name }) => name)),
|
|
226
|
+
).filter(
|
|
227
|
+
(name) =>
|
|
228
|
+
name !== "__proto__" &&
|
|
229
|
+
value[name] !== undefined &&
|
|
230
|
+
!Object.prototype.propertyIsEnumerable.call(value, name),
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Whether only a struct can read a value here. A struct builds a plain object from any object, so a
|
|
235
|
+
* class instance loses nothing by becoming one. A declaration may need the instance itself, so
|
|
236
|
+
* there it keeps its keys, and stays an instance unless something in it has to change.
|
|
237
|
+
*/
|
|
238
|
+
const readAsStruct = (sides: ReadonlyArray<Ast>, open: boolean): boolean =>
|
|
239
|
+
!open && !sides.some(({ _tag }) => _tag === "Declaration");
|
|
240
|
+
|
|
241
|
+
/** Bring a value's {@link unlisted} fields out as keys, at any depth, and take out what `drops` says. */
|
|
242
|
+
const rewriting = (drops: (item: unknown, stated: boolean) => boolean) => {
|
|
243
|
+
const rewrite = (types: ReadonlyArray<Ast>, value: unknown): unknown => {
|
|
244
|
+
if (types.length === 0 || !isObject(value)) return value;
|
|
245
|
+
const sides = types.flatMap((type) => sidesOf(type, value));
|
|
246
|
+
const hidden = unlisted(sides, value);
|
|
247
|
+
const open = leaveKeysOpen(sides);
|
|
248
|
+
const plain = isPlain(value);
|
|
249
|
+
const asStruct = !plain && readAsStruct(sides, open);
|
|
250
|
+
const isList = Array.isArray(value);
|
|
251
|
+
const keys = [...keysOf(value), ...hidden];
|
|
252
|
+
const entries = keys.flatMap((key) => {
|
|
253
|
+
const item = value[key];
|
|
254
|
+
const inner = typesAt(sides, key);
|
|
255
|
+
return (plain || asStruct) &&
|
|
256
|
+
!isList &&
|
|
257
|
+
drops(item, open || inner.length > 0)
|
|
258
|
+
? []
|
|
259
|
+
: [[key, rewrite(inner, item)] as const];
|
|
260
|
+
});
|
|
261
|
+
const same =
|
|
262
|
+
!asStruct &&
|
|
263
|
+
hidden.length === 0 &&
|
|
264
|
+
entries.length === keys.length &&
|
|
265
|
+
entries.every(([key, item]) => item === value[key]);
|
|
266
|
+
return same
|
|
267
|
+
? value
|
|
268
|
+
: isList
|
|
269
|
+
? entries.map(([, item]) => item)
|
|
270
|
+
: Object.fromEntries(entries);
|
|
271
|
+
};
|
|
272
|
+
return rewrite;
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* What a caller means by a value, at any depth of plain objects and lists: no key set to `undefined`,
|
|
277
|
+
* which holds nothing, and no key the schema does not state, which a struct would strip anyway. A
|
|
278
|
+
* member a tag has ruled out states nothing. Returns `value` itself if there is nothing to change.
|
|
279
|
+
*/
|
|
280
|
+
export const normalised = rewriting(
|
|
281
|
+
(item, stated) => item === undefined || !stated,
|
|
282
|
+
);
|
|
283
|
+
|
|
284
|
+
/** A value as the caller gave it, but for what {@link unlisted} brings out as keys. */
|
|
285
|
+
export const exposed = rewriting(() => false);
|
|
286
|
+
|
|
287
|
+
/** The fields of a group the caller gave and a schema states, under either of their names. */
|
|
288
|
+
export const statedFields = (
|
|
289
|
+
ast: Ast,
|
|
290
|
+
value: unknown,
|
|
291
|
+
): ReadonlyArray<PropertyKey> => {
|
|
292
|
+
if (!isObject(value) || Array.isArray(value)) return [];
|
|
293
|
+
const sides = sidesOf(ast, value);
|
|
294
|
+
return [...keysOf(value), ...unlisted(sides, value)].filter(
|
|
295
|
+
(key) => value[key] !== undefined && typesAt(sides, key).length > 0,
|
|
296
|
+
);
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
const has = (value: unknown, key: PropertyKey): boolean =>
|
|
300
|
+
isObject(value) && key in value && value[key] !== undefined;
|
|
301
|
+
|
|
302
|
+
const at = (value: unknown, key: PropertyKey): unknown =>
|
|
303
|
+
isObject(value) ? value[key] : undefined;
|
|
304
|
+
|
|
305
|
+
/** Whether a value's keys mean something here: it is plain, or a struct here reads it. */
|
|
306
|
+
const comparable = (sides: ReadonlyArray<Ast>, value: object): boolean =>
|
|
307
|
+
isPlain(value) || sides.some(({ _tag }) => _tag === "Objects");
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* What a read lost from `given`, a {@link normalised} value, by comparing it with what came out. A
|
|
311
|
+
* field has to be in the decoded value or in what was written. Under a name a member decodes, what
|
|
312
|
+
* was written has to be what was given too, because that name can be another field's on the wire.
|
|
313
|
+
* What this cannot see into, such as text or a `Map`, is left to the schema's own reading.
|
|
314
|
+
*/
|
|
315
|
+
export const missing = (
|
|
316
|
+
types: ReadonlyArray<Ast>,
|
|
317
|
+
given: unknown,
|
|
318
|
+
value: unknown,
|
|
319
|
+
output: unknown,
|
|
320
|
+
path: Path = [],
|
|
321
|
+
): ReadonlyArray<Path> => {
|
|
322
|
+
if (!isObject(given)) return [];
|
|
323
|
+
const sides = types.flatMap((type) => sidesOf(type, given));
|
|
324
|
+
if (!comparable(sides, given)) return [];
|
|
325
|
+
const decoded = new Set(types.flatMap((type) => decodedNames(type, given)));
|
|
326
|
+
const holdsAsWritten = (key: PropertyKey) =>
|
|
327
|
+
has(output, key) &&
|
|
328
|
+
(!isObject(value) ||
|
|
329
|
+
!decoded.has(String(key)) ||
|
|
330
|
+
Equal.equals(at(output, key), given[key]));
|
|
331
|
+
return keysOf(given).flatMap((key) => {
|
|
332
|
+
const here = [...path, Array.isArray(given) ? Number(key) : key];
|
|
333
|
+
return given[key] === undefined || has(value, key) || holdsAsWritten(key)
|
|
334
|
+
? missing(
|
|
335
|
+
typesAt(sides, key),
|
|
336
|
+
given[key],
|
|
337
|
+
at(value, key),
|
|
338
|
+
at(output, key),
|
|
339
|
+
here,
|
|
340
|
+
)
|
|
341
|
+
: [here];
|
|
342
|
+
});
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
const notHeld = new SchemaIssue.InvalidValue({
|
|
346
|
+
message: "The schema cannot keep this field with the rest of the value",
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
/** A refusal that names the fields and, like any other schema failure here, leaves out values. */
|
|
350
|
+
export const refusal = (
|
|
351
|
+
ast: Ast,
|
|
352
|
+
[first, ...others]: readonly [Path, ...ReadonlyArray<Path>],
|
|
353
|
+
): Schema.SchemaError =>
|
|
354
|
+
new Schema.SchemaError(
|
|
355
|
+
new SchemaIssue.Composite(ast, [
|
|
356
|
+
new SchemaIssue.Pointer(first, notHeld),
|
|
357
|
+
...others.map((path) => new SchemaIssue.Pointer(path, notHeld)),
|
|
358
|
+
]),
|
|
359
|
+
);
|
|
360
|
+
|
|
361
|
+
/** Whether a schema holds a choice of member, which only a stacked schema can settle for it. */
|
|
362
|
+
export const choosesMember = holding(isMemberChoice);
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Whether a schema holds a choice that can cost a field, of member or of side, anywhere it can be
|
|
366
|
+
* seen. Any other schema skips the strict pass. `Schema.NullOr` around a struct has no such choice.
|
|
367
|
+
*/
|
|
368
|
+
export const choosing = holding(
|
|
369
|
+
(ast) => isMemberChoice(ast) || isSideChoice(ast),
|
|
370
|
+
);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { Effect, Schema, SchemaAST } from "effect";
|
|
1
|
+
import { Effect, Schema, type SchemaAST } from "effect";
|
|
2
|
+
import * as Excess from "./excess.js";
|
|
2
3
|
|
|
3
4
|
/** What a schema's constructor takes. This is the one place that names the `~`-prefixed key. */
|
|
4
5
|
type ConstructorInput<S extends Schema.Top> = S["~type.make.in"];
|
|
@@ -50,70 +51,110 @@ export type Input<S extends Schema.Top> = EitherSide<
|
|
|
50
51
|
S["Encoded"]
|
|
51
52
|
>;
|
|
52
53
|
|
|
53
|
-
/** The fields of a struct or class, as they are declared, with each field's own encoding. */
|
|
54
|
-
const fieldsOf = (
|
|
55
|
-
ast: SchemaAST.AST,
|
|
56
|
-
): ReadonlyArray<{
|
|
57
|
-
readonly name: PropertyKey;
|
|
58
|
-
readonly type: SchemaAST.AST;
|
|
59
|
-
}> =>
|
|
60
|
-
ast._tag === "Objects"
|
|
61
|
-
? ast.propertySignatures
|
|
62
|
-
: ast._tag === "Declaration" && ast.encoding !== undefined
|
|
63
|
-
? fieldsOf(ast.encoding[0].to)
|
|
64
|
-
: [];
|
|
65
|
-
|
|
66
54
|
/**
|
|
67
55
|
* Bring a value on either side of a schema to its decoded side.
|
|
68
56
|
*
|
|
69
57
|
* @remarks
|
|
70
58
|
* A value that fits the decoded side is read as decoded, so it is encoded once. Anything else goes
|
|
71
59
|
* through the decoder as a whole, then field by field. Both routes validate, and a value that fits
|
|
72
|
-
* neither fails with the decoded side's error, so existing failures read the same.
|
|
60
|
+
* neither fails with the decoded side's error, so existing failures read the same. `options` go to
|
|
61
|
+
* every parse.
|
|
73
62
|
*/
|
|
74
|
-
|
|
63
|
+
const toDecodedWithEvidence = <S extends Schema.Top>(
|
|
64
|
+
contract: S,
|
|
65
|
+
options?: SchemaAST.ParseOptions,
|
|
66
|
+
) => {
|
|
67
|
+
const making = options && { parseOptions: options };
|
|
75
68
|
const make = (input: unknown) =>
|
|
76
69
|
Effect.mapError(
|
|
77
|
-
contract.makeEffect(input),
|
|
70
|
+
contract.makeEffect(input, making),
|
|
78
71
|
(issue) => new Schema.SchemaError(issue),
|
|
79
72
|
);
|
|
80
73
|
const decode = Schema.decodeUnknownEffect(contract);
|
|
81
74
|
const byField = Effect.fnUntraced(function* (input: object) {
|
|
82
75
|
const output: Record<PropertyKey, unknown> = { ...input };
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
76
|
+
// A field need not be a key, as an accessor on a class is not, so it comes from `input`.
|
|
77
|
+
const fields: Record<PropertyKey, unknown> = input as never;
|
|
78
|
+
for (const { name, type } of Excess.fieldsOf(contract.ast))
|
|
79
|
+
if (fields[name] !== undefined)
|
|
80
|
+
output[name] = yield* fromPart(type, fields[name], options);
|
|
86
81
|
return yield* make(output);
|
|
87
82
|
});
|
|
88
83
|
const byMember = (input: object) =>
|
|
89
|
-
contract.ast._tag === "Union"
|
|
84
|
+
contract.ast._tag === "Union" && contract.ast.types.length > 0
|
|
90
85
|
? Effect.firstSuccessOf(
|
|
91
|
-
contract.ast.types.map((member) => fromPart(member, input)),
|
|
86
|
+
contract.ast.types.map((member) => fromPart(member, input, options)),
|
|
92
87
|
)
|
|
93
88
|
: byField(input);
|
|
94
89
|
return (
|
|
95
90
|
input: Input<S>,
|
|
96
|
-
): Effect.Effect<
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
91
|
+
): Effect.Effect<
|
|
92
|
+
Decoded<S["Type"]>,
|
|
93
|
+
Schema.SchemaError,
|
|
94
|
+
S["DecodingServices"]
|
|
95
|
+
> =>
|
|
96
|
+
Effect.catch(
|
|
97
|
+
Effect.map(make(input), (value) => ({ value, constructed: true })),
|
|
98
|
+
(failure) =>
|
|
99
|
+
Effect.mapError(
|
|
100
|
+
Effect.map(
|
|
101
|
+
Effect.catch(decode(input, options), (encodedFailure) =>
|
|
102
|
+
typeof input === "object" && input !== null
|
|
103
|
+
? byMember(input)
|
|
104
|
+
: Effect.fail(encodedFailure),
|
|
105
|
+
),
|
|
106
|
+
(value) => ({ value, constructed: false }),
|
|
107
|
+
),
|
|
108
|
+
() => failure,
|
|
103
109
|
),
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
110
|
+
) as Effect.Effect<
|
|
111
|
+
Decoded<S["Type"]>,
|
|
112
|
+
Schema.SchemaError,
|
|
113
|
+
S["DecodingServices"]
|
|
114
|
+
>;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/** Only the first successful constructor route proves how a group acquired an omitted field. */
|
|
118
|
+
interface Decoded<A> {
|
|
119
|
+
readonly value: A;
|
|
120
|
+
readonly constructed: boolean;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Bring either side to the decoded side, without exposing how it was read. */
|
|
124
|
+
export const toDecoded = <S extends Schema.Top>(
|
|
125
|
+
contract: S,
|
|
126
|
+
options?: SchemaAST.ParseOptions,
|
|
127
|
+
) => {
|
|
128
|
+
const read = toDecodedWithEvidence(contract, options);
|
|
129
|
+
return (input: Input<S>) => Effect.map(read(input), ({ value }) => value);
|
|
107
130
|
};
|
|
108
131
|
|
|
109
132
|
/** Read a field or union member, which may be on either side of its own schema. */
|
|
110
|
-
const fromPart = (
|
|
111
|
-
|
|
133
|
+
const fromPart = (
|
|
134
|
+
ast: SchemaAST.AST,
|
|
135
|
+
value: unknown,
|
|
136
|
+
options?: SchemaAST.ParseOptions,
|
|
137
|
+
): Effect.Effect<unknown, Schema.SchemaError, unknown> =>
|
|
138
|
+
toDecoded(Schema.make<Schema.Top>(ast), options)(value);
|
|
112
139
|
|
|
113
|
-
/**
|
|
114
|
-
export
|
|
140
|
+
/** What a schema wrote, and the fields of its input it would lose, which may be held elsewhere. */
|
|
141
|
+
export interface Written<A> {
|
|
142
|
+
readonly output: A;
|
|
143
|
+
readonly lost: ReadonlyArray<Excess.Path>;
|
|
144
|
+
/** Own data fields from the successful first direct-struct construction, before encoding. */
|
|
145
|
+
readonly constructed: unknown;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Takes a decoded value out through a schema, as the options say. */
|
|
149
|
+
type Write<S extends Schema.Top, A, R> = (
|
|
150
|
+
value: S["Type"],
|
|
151
|
+
options?: SchemaAST.ParseOptions,
|
|
152
|
+
) => Effect.Effect<A, Schema.SchemaError, R>;
|
|
153
|
+
|
|
154
|
+
/** Bring a value to the schema's decoded side, then write it, as Effect reads it. */
|
|
155
|
+
const stripping = <S extends Schema.Top, A, R>(
|
|
115
156
|
contract: S,
|
|
116
|
-
write:
|
|
157
|
+
write: Write<S, A, R>,
|
|
117
158
|
) => {
|
|
118
159
|
const decoded = toDecoded(contract);
|
|
119
160
|
return (
|
|
@@ -121,3 +162,125 @@ export const encoder = <S extends Schema.Top, A, R>(
|
|
|
121
162
|
): Effect.Effect<A, Schema.SchemaError, R | S["DecodingServices"]> =>
|
|
122
163
|
Effect.flatMap(decoded(input), write);
|
|
123
164
|
};
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Bring a value to the schema's decoded side, then write it, and say what that would lose.
|
|
168
|
+
*
|
|
169
|
+
* @remarks
|
|
170
|
+
* Effect takes the first union member that fits and strips what that member does not state, on the
|
|
171
|
+
* decoded side and again when it encodes, so a later member that holds everything would lose to an
|
|
172
|
+
* earlier one that holds part of it. A value on a schema's encoded side can lose to its decoded side
|
|
173
|
+
* in the same way, where the two state different names. So a schema with either choice reads what
|
|
174
|
+
* the caller means strictly, through both steps, and a read that passes has stripped nothing.
|
|
175
|
+
*
|
|
176
|
+
* A value that cannot be read that way is read as Effect reads it, and the result is compared with
|
|
177
|
+
* what went in, so what is lost is what actually went, not what a failure suggests would. The write
|
|
178
|
+
* is strict first, because a loose write can choose another member and lose what the read kept.
|
|
179
|
+
*
|
|
180
|
+
* A schema with neither choice skips the strict read and loss comparison.
|
|
181
|
+
*/
|
|
182
|
+
export const reader = <S extends Schema.Top, A, R>(
|
|
183
|
+
contract: S,
|
|
184
|
+
write: Write<S, A, R>,
|
|
185
|
+
) => {
|
|
186
|
+
const decoded = toDecodedWithEvidence(contract);
|
|
187
|
+
const constructorFields =
|
|
188
|
+
contract.ast._tag === "Objects" && contract.ast.encoding === undefined
|
|
189
|
+
? contract.ast.propertySignatures.filter(
|
|
190
|
+
({ type }) => type.context?.constructorDefault !== undefined,
|
|
191
|
+
)
|
|
192
|
+
: [];
|
|
193
|
+
const construction = ({ value, constructed }: Decoded<S["Type"]>): unknown =>
|
|
194
|
+
constructed &&
|
|
195
|
+
constructorFields.length > 0 &&
|
|
196
|
+
typeof value === "object" &&
|
|
197
|
+
value !== null
|
|
198
|
+
? Object.fromEntries(
|
|
199
|
+
constructorFields.flatMap(({ name }) => {
|
|
200
|
+
const property = Object.getOwnPropertyDescriptor(value, name);
|
|
201
|
+
return property !== undefined && "value" in property
|
|
202
|
+
? [[name, property.value]]
|
|
203
|
+
: [];
|
|
204
|
+
}),
|
|
205
|
+
)
|
|
206
|
+
: undefined;
|
|
207
|
+
const written = (
|
|
208
|
+
reading: ReturnType<typeof decoded>,
|
|
209
|
+
options?: SchemaAST.ParseOptions,
|
|
210
|
+
) =>
|
|
211
|
+
Effect.flatMap(reading, (read) => {
|
|
212
|
+
const constructed = construction(read);
|
|
213
|
+
return Effect.map(write(read.value, options), (output): Written<A> => ({
|
|
214
|
+
output,
|
|
215
|
+
lost: [],
|
|
216
|
+
constructed,
|
|
217
|
+
}));
|
|
218
|
+
});
|
|
219
|
+
if (!Excess.choosing(contract.ast))
|
|
220
|
+
return (input: Input<S>) => written(decoded(input));
|
|
221
|
+
const exact = toDecodedWithEvidence(contract, Excess.strict);
|
|
222
|
+
const kept = (input: Input<S>) => written(exact(input), Excess.strict);
|
|
223
|
+
const compared = (input: Input<S>, given: unknown) =>
|
|
224
|
+
Effect.flatMap(decoded(input), (read) => {
|
|
225
|
+
const constructed = construction(read);
|
|
226
|
+
return Effect.map(
|
|
227
|
+
Effect.catch(write(read.value, Excess.strict), () => write(read.value)),
|
|
228
|
+
(output): Written<A> => ({
|
|
229
|
+
output,
|
|
230
|
+
lost: Excess.missing([contract.ast], given, read.value, output),
|
|
231
|
+
constructed,
|
|
232
|
+
}),
|
|
233
|
+
);
|
|
234
|
+
});
|
|
235
|
+
return (
|
|
236
|
+
input: Input<S>,
|
|
237
|
+
): Effect.Effect<
|
|
238
|
+
Written<A>,
|
|
239
|
+
Schema.SchemaError,
|
|
240
|
+
R | S["DecodingServices"]
|
|
241
|
+
> => {
|
|
242
|
+
const given = Excess.normalised([contract.ast], input);
|
|
243
|
+
// A strict read cannot see a field outside a value's keys, so it may not fall back on `input`.
|
|
244
|
+
const seen = (
|
|
245
|
+
given === input ? input : Excess.exposed([contract.ast], input)
|
|
246
|
+
) as Input<S>;
|
|
247
|
+
return Effect.catch(
|
|
248
|
+
given === input
|
|
249
|
+
? kept(input)
|
|
250
|
+
: Effect.catch(kept(given as Input<S>), () => kept(seen)),
|
|
251
|
+
() => compared(input, given),
|
|
252
|
+
);
|
|
253
|
+
};
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Refuse the fields a schema would lose, unless another schema in the group took them. Only a field
|
|
258
|
+
* of the group itself can be taken, so one further down a value stays lost.
|
|
259
|
+
*/
|
|
260
|
+
export const refuseLost = (
|
|
261
|
+
contract: Schema.Top,
|
|
262
|
+
lost: ReadonlyArray<Excess.Path>,
|
|
263
|
+
taken?: ReadonlySet<PropertyKey>,
|
|
264
|
+
): Effect.Effect<void, Schema.SchemaError> => {
|
|
265
|
+
const [first, ...others] = lost.filter(
|
|
266
|
+
(path) => path.length > 1 || taken?.has(path[0]!) !== true,
|
|
267
|
+
);
|
|
268
|
+
return first === undefined
|
|
269
|
+
? Effect.void
|
|
270
|
+
: Effect.fail(Excess.refusal(contract.ast, [first, ...others]));
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
/** Bring a value to the schema's decoded side and write it, with nothing else to hold what it loses. */
|
|
274
|
+
export const encoder = <S extends Schema.Top, A, R>(
|
|
275
|
+
contract: S,
|
|
276
|
+
write: Write<S, A, R>,
|
|
277
|
+
) => {
|
|
278
|
+
if (!Excess.choosing(contract.ast)) return stripping(contract, write);
|
|
279
|
+
const read = reader(contract, write);
|
|
280
|
+
return (
|
|
281
|
+
input: Input<S>,
|
|
282
|
+
): Effect.Effect<A, Schema.SchemaError, R | S["DecodingServices"]> =>
|
|
283
|
+
Effect.flatMap(read(input), ({ output, lost }) =>
|
|
284
|
+
Effect.as(refuseLost(contract, lost), output),
|
|
285
|
+
);
|
|
286
|
+
};
|