@distilled.cloud/core 1.0.0-rc.16 → 1.0.0-rc.17

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 (69) hide show
  1. package/lib/_bundle/aws.js +2 -0
  2. package/lib/_bundle/aws.js.map +1 -0
  3. package/lib/_bundle/base.js +5 -0
  4. package/lib/_bundle/base.js.map +1 -0
  5. package/lib/_bundle/graphql.js +3 -0
  6. package/lib/_bundle/graphql.js.map +1 -0
  7. package/lib/_bundle/rest.js +2 -0
  8. package/lib/_bundle/rest.js.map +1 -0
  9. package/lib/_bundle/xml.js +4 -0
  10. package/lib/_bundle/xml.js.map +1 -0
  11. package/lib/api.d.ts.map +1 -1
  12. package/lib/api.js +1 -796
  13. package/lib/category.js +1 -278
  14. package/lib/chunks.js +1 -11
  15. package/lib/config.js +1 -161
  16. package/lib/crypto.js +1 -130
  17. package/lib/debug.js +1 -8
  18. package/lib/error-category.js +1 -47
  19. package/lib/errors.js +1 -198
  20. package/lib/graphql.js +1 -1058
  21. package/lib/graphql.types.js +1 -6
  22. package/lib/index.js +0 -15
  23. package/lib/json-patch.js +1 -226
  24. package/lib/json-patch.js.map +1 -1
  25. package/lib/pagination.js +1 -271
  26. package/lib/plain-values.js +1 -39
  27. package/lib/plain-values.js.map +1 -1
  28. package/lib/protocol-http.js +1 -812
  29. package/lib/protocol-rest.js +1 -375
  30. package/lib/query.js +1 -27
  31. package/lib/response-validation-strict.js +1 -284
  32. package/lib/response-validation.js +1 -118
  33. package/lib/retry-after.js +1 -112
  34. package/lib/retry.js +1 -197
  35. package/lib/schema-lite-impl.js +1 -341
  36. package/lib/schema-lite-typed.js +1 -26
  37. package/lib/schema-lite-typed.js.map +1 -1
  38. package/lib/schema-lite.js +1 -31
  39. package/lib/schema.js +1 -220
  40. package/lib/testing.js +1 -41
  41. package/lib/testing.js.map +1 -1
  42. package/lib/trait.js +1 -131
  43. package/lib/xml.js +1 -323
  44. package/package.json +1 -1
  45. package/src/api.ts +7 -6
  46. package/lib/api.js.map +0 -1
  47. package/lib/category.js.map +0 -1
  48. package/lib/chunks.js.map +0 -1
  49. package/lib/config.js.map +0 -1
  50. package/lib/crypto.js.map +0 -1
  51. package/lib/debug.js.map +0 -1
  52. package/lib/error-category.js.map +0 -1
  53. package/lib/errors.js.map +0 -1
  54. package/lib/graphql.js.map +0 -1
  55. package/lib/graphql.types.js.map +0 -1
  56. package/lib/index.js.map +0 -1
  57. package/lib/pagination.js.map +0 -1
  58. package/lib/protocol-http.js.map +0 -1
  59. package/lib/protocol-rest.js.map +0 -1
  60. package/lib/query.js.map +0 -1
  61. package/lib/response-validation-strict.js.map +0 -1
  62. package/lib/response-validation.js.map +0 -1
  63. package/lib/retry-after.js.map +0 -1
  64. package/lib/retry.js.map +0 -1
  65. package/lib/schema-lite-impl.js.map +0 -1
  66. package/lib/schema-lite.js.map +0 -1
  67. package/lib/schema.js.map +0 -1
  68. package/lib/trait.js.map +0 -1
  69. package/lib/xml.js.map +0 -1
@@ -1,375 +1 @@
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
- import * as Context from "effect/Context";
29
- import * as Effect from "effect/Effect";
30
- import * as HttpClient from "effect/http/HttpClient";
31
- import * as Layer from "effect/Layer";
32
- import * as Redacted from "effect/Redacted";
33
- import * as API from "./api.js";
34
- import { debugHttp } from "./debug.js";
35
- import { HTTP_STATUS_MAP, InternalServerError } from "./errors.js";
36
- import { isOpaqueValue, unwrapRedactedDeep } from "./plain-values.js";
37
- import { buildRequest, getAnn, getPropAnn, getProps, mapKeys, mapsVerbatim, matchTypedError, resolveNode, responseHeaderMembers, withResponseHeaders, } from "./protocol-http.js";
38
- import { checkResponse, withholdActual } from "./response-validation.js";
39
- import { parseRetryAfterForStatus } from "./retry-after.js";
40
- import { httpSymbol, makeAnnotation } from "./trait.js";
41
- // =============================================================================
42
- // Traits
43
- // =============================================================================
44
- export const sensitiveValueSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/sensitive-value");
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
- export const SensitiveValue = (_value) => makeAnnotation(sensitiveValueSymbol, true);
53
- export const rawResponseSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/raw-response");
54
-
55
-
56
-
57
-
58
- export const RawResponse = (_value) => makeAnnotation(rawResponseSymbol, true);
59
- export const rawResponseRootSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/raw-response-root");
60
-
61
-
62
-
63
-
64
-
65
-
66
- export const RawResponseRoot = () => makeAnnotation(rawResponseRootSymbol, true);
67
- export const binaryResponseSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/binary-response");
68
-
69
- export const BinaryResponse = () => makeAnnotation(binaryResponseSymbol, true);
70
- // =============================================================================
71
- // Value helpers
72
- // =============================================================================
73
- export { unwrapRedactedDeep };
74
-
75
-
76
-
77
-
78
-
79
- export const wrapSensitive = (ast, value) => {
80
- if (value === null || typeof value !== "object" || isOpaqueValue(value)) {
81
- return value;
82
- }
83
- const node = resolveNode(ast);
84
- if (node._tag === "Union") {
85
- // Redact every possible sensitive member, including in partial responses.
86
- return node.types.reduce((redacted, arm) => wrapSensitive(arm, redacted), value);
87
- }
88
- if (node._tag === "Arrays") {
89
- if (!Array.isArray(value))
90
- return value;
91
- const elem = node.rest?.[0];
92
- return elem ? value.map((v) => wrapSensitive(elem, v)) : value;
93
- }
94
- if (node._tag === "Objects" && !Array.isArray(value)) {
95
- const props = getProps(node);
96
- if (props.length === 0)
97
- return value;
98
- const byName = new Map(props.map((p) => [String(p.name), p]));
99
- const out = {};
100
- for (const [k, v] of Object.entries(value)) {
101
- if (v === undefined)
102
- continue;
103
- const prop = byName.get(k);
104
- if (!prop) {
105
- out[k] = v;
106
- }
107
- else if (getPropAnn(prop, sensitiveValueSymbol) !== undefined && typeof v === "string") {
108
- out[k] = Redacted.make(v);
109
- }
110
- else {
111
- out[k] = wrapSensitive(prop.type, v);
112
- }
113
- }
114
- return out;
115
- }
116
- return value;
117
- };
118
- const sensitiveOutputs = /*@__PURE__*/ new WeakMap();
119
-
120
-
121
-
122
-
123
-
124
- export const hasSensitiveMember = (ast) => {
125
- const cached = sensitiveOutputs.get(ast);
126
- if (cached !== undefined)
127
- return cached;
128
- const seen = new Set();
129
- const visit = (node) => {
130
- node = resolveNode(node);
131
- if (seen.has(node))
132
- return false;
133
- seen.add(node);
134
- if (node._tag === "Union")
135
- return node.types.some(visit);
136
- if (node._tag === "Arrays") {
137
- return [...node.elements, ...node.rest].some((e) => getAnn(e, sensitiveValueSymbol) !== undefined || visit(e));
138
- }
139
- if (node._tag !== "Objects")
140
- return false;
141
- return [...node.propertySignatures, ...node.indexSignatures].some((member) => getAnn(member.type, sensitiveValueSymbol) !== undefined || visit(member.type));
142
- };
143
- const result = visit(ast);
144
- sensitiveOutputs.set(ast, result);
145
- return result;
146
- };
147
- const defaultErrorEnvelope = (body) => {
148
- if (body === null || typeof body !== "object")
149
- return undefined;
150
- const b = body;
151
- const code = typeof b.code === "string" || typeof b.code === "number" ? b.code : undefined;
152
- const message = typeof b.message === "string" ? b.message : typeof b.error === "string" ? b.error : undefined;
153
- return { code, message };
154
- };
155
- // Bridge: Protocol.decode is typed as Effect<unknown> (no error channel),
156
- // but REST failures are real typed errors that operations re-surface via
157
- // their `errors: [...]` lists. Fail with the instance and erase the type
158
- // here; the generated operation annotations reintroduce it for callers.
159
- const fail = (e) => Effect.fail(e);
160
-
161
- export const hasSensitive = (root) => {
162
- let result = sensitiveCache.get(root);
163
- if (result !== undefined)
164
- return result;
165
- result = false;
166
- const seen = new Set();
167
- const stack = [root];
168
- walk: while (stack.length > 0) {
169
- const ast = stack.pop();
170
- if (seen.has(ast))
171
- continue;
172
- seen.add(ast);
173
- const node = resolveNode(ast);
174
- if (node._tag === "Union") {
175
- for (const t of node.types)
176
- stack.push(t);
177
- }
178
- else if (node._tag === "Arrays") {
179
- const elem = node.rest?.[0];
180
- if (elem)
181
- stack.push(elem);
182
- }
183
- else if (node._tag === "Objects") {
184
- for (const p of getProps(node)) {
185
- if (getPropAnn(p, sensitiveValueSymbol) !== undefined) {
186
- result = true;
187
- break walk;
188
- }
189
- stack.push(p.type);
190
- }
191
- }
192
- }
193
- sensitiveCache.set(root, result);
194
- return result;
195
- };
196
- const sensitiveCache = /*@__PURE__*/ new WeakMap();
197
- const decodePlans = /*@__PURE__*/ new WeakMap();
198
- const decodePlanFor = (outputAst) => {
199
- let plan = decodePlans.get(outputAst);
200
- if (plan === undefined) {
201
- plan = {
202
- binary: getAnn(outputAst, binaryResponseSymbol) !== undefined,
203
- verbatim: mapsVerbatim(outputAst, "decode"),
204
- sensitive: hasSensitive(outputAst),
205
- withholdBody: hasSensitiveMember(outputAst),
206
- headers: responseHeaderMembers(outputAst),
207
- };
208
- decodePlans.set(outputAst, plan);
209
- }
210
- return plan;
211
- };
212
-
213
-
214
-
215
-
216
-
217
- export const makeRestProtocol = (options) => {
218
- const errorEnvelope = options.errorEnvelope ?? defaultErrorEnvelope;
219
- const statusMap = options.statusMap ?? HTTP_STATUS_MAP;
220
- const credentialsKey = Context.isKey(options.credentials)
221
- ? options.credentials
222
- : undefined;
223
- const credentialsEffect = options.credentials;
224
-
225
- const withCredentials = (context, f) => API.withValue(credentialsKey === undefined ? credentialsEffect : Context.get(context, credentialsKey), f);
226
-
227
- const requestFor = (creds, input, inputAst) => {
228
- const http = getAnn(inputAst, httpSymbol);
229
- let baseUrl;
230
- try {
231
- baseUrl = options.baseUrl(creds, {
232
- uri: http?.uri ?? "",
233
- method: http?.method ?? "",
234
- });
235
- }
236
- catch (e) {
237
- // A baseUrl that refuses the route (missing scope in the
238
- // credentials) fails the call with that error, typed for callers by
239
- // the operation's declared error channel.
240
- return { refused: e };
241
- }
242
- return buildRequest({
243
- input: unwrapRedactedDeep(input),
244
- inputAst,
245
- baseUrl,
246
- headers: options.headers(creds),
247
- mapMemberHeader: options.mapMemberHeader,
248
- unknownKeyToWire: options.unknownKeyToWire,
249
- });
250
- };
251
-
252
- const decodeText = (context, status, headers, text, outputAst, errorClasses) => {
253
- // Read as text and parse tolerantly -- error pages are often non-JSON.
254
- if (debugHttp()) {
255
- console.error(`[distilled] <- ${status}`);
256
- }
257
- let json;
258
- let nonJson = false;
259
- if (text.trim().length > 0) {
260
- try {
261
- json = JSON.parse(text);
262
- }
263
- catch {
264
- nonJson = true;
265
- }
266
- }
267
- if (status >= 400) {
268
- const env = (nonJson ? undefined : errorEnvelope(json)) ?? {};
269
- const message = env.message ?? (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
270
- // 1. Per-operation typed error (matcher metadata on the class).
271
- const typed = matchTypedError(errorClasses, status, [
272
- {
273
- code: typeof env.code === "number" ? env.code : undefined,
274
- message,
275
- },
276
- ], { body: nonJson ? text : json, headers });
277
- if (typed !== undefined)
278
- return { ok: false, error: typed };
279
- // 2. Status-mapped class (retryAfter only stamps on retryable
280
- // statuses -- parseRetryAfterForStatus gates on that).
281
- const StatusErrorClass = statusMap[status];
282
- if (StatusErrorClass) {
283
- return {
284
- ok: false,
285
- error: new StatusErrorClass({
286
- message,
287
- retryAfter: parseRetryAfterForStatus(status, headers),
288
- }),
289
- };
290
- }
291
- // 3. Unmapped 5xx (e.g. proxy-specific statuses) -> retryable server
292
- // error rather than the unknown fallback.
293
- if (status >= 500) {
294
- return {
295
- ok: false,
296
- error: new InternalServerError({
297
- message,
298
- retryAfter: parseRetryAfterForStatus(status, headers),
299
- }),
300
- };
301
- }
302
- // 4. Provider fallback.
303
- return {
304
- ok: false,
305
- error: options.unknownError({
306
- status,
307
- code: env.code,
308
- message,
309
- body: nonJson ? text : json,
310
- headers,
311
- }),
312
- };
313
- }
314
- // 2xx: the response body IS the payload (no envelope). Wire->TS key
315
- // mapping is schema-driven; `RawResponseRoot` responses are the body
316
- // verbatim (mapKeys handles arrays/scalars structurally either way).
317
- // Strict mode (core/response-validation) checks the mapped body against
318
- // the output schema -- a non-JSON body reaches it as a string and fails
319
- // there unless the operation's output is itself a string. For an output
320
- // with sensitive members, a non-JSON body fails in every mode and parse
321
- // errors withhold the body.
322
- const plan = decodePlanFor(outputAst);
323
- if (nonJson && plan.withholdBody) {
324
- return {
325
- ok: false,
326
- error: options.parseError({ body: "[REDACTED]", cause: "Invalid JSON response" }),
327
- };
328
- }
329
- let body = nonJson ? text : (json ?? {});
330
- if (options.transformResponse)
331
- body = options.transformResponse(body);
332
- const mapped = withResponseHeaders(plan.headers, plan.verbatim ? body : mapKeys(outputAst, body, "decode"), headers);
333
- const invalid = checkResponse(context, outputAst, mapped);
334
- if (invalid !== undefined) {
335
- return {
336
- ok: false,
337
- error: options.parseError({
338
- body: plan.withholdBody ? "[REDACTED]" : nonJson ? text : json,
339
- cause: plan.withholdBody ? withholdActual(invalid) : invalid,
340
- }),
341
- };
342
- }
343
- return { ok: true, value: plan.sensitive ? wrapSensitive(outputAst, mapped) : mapped };
344
- };
345
- const decodeResponse = (context, response, outputAst, errorClasses) => response.status >= 200 && response.status < 300 && decodePlanFor(outputAst).binary
346
- ? Effect.map(Effect.orDie(response.arrayBuffer), (bytes) => new Uint8Array(bytes))
347
- : Effect.matchEffect(response.text, {
348
- onFailure: Effect.die,
349
- onSuccess: (text) => {
350
- const decoded = decodeText(context, response.status, response.headers, text ?? "", outputAst, errorClasses);
351
- return decoded.ok ? Effect.succeed(decoded.value) : fail(decoded.error);
352
- },
353
- });
354
- const call = (op, input) => Effect.withFiber((fiber) => {
355
- const context = fiber.context;
356
- return withCredentials(context, (creds) => {
357
- const request = requestFor(creds, input, op.inputAst);
358
- if ("refused" in request)
359
- return fail(request.refused);
360
- const client = Context.get(context, HttpClient.HttpClient);
361
- return Effect.flatMap(client.execute(request), (response) => decodeResponse(context, response, op.outputAst, op.errors));
362
- });
363
- });
364
- return Layer.succeed(API.Protocol, API.Protocol.of({
365
- // Erase encode's credentials requirement (resolved on the calling
366
- // fiber; see RestProtocolOptions.credentials).
367
- encode: ({ input, inputAst }) => Effect.withFiber((fiber) => withCredentials(fiber.context, (creds) => {
368
- const request = requestFor(creds, input, inputAst);
369
- return "refused" in request ? fail(request.refused) : Effect.succeed(request);
370
- })),
371
- decode: ({ response, outputAst, errors }) => Effect.withFiber((fiber) => decodeResponse(fiber.context, response, outputAst, errors)),
372
- call,
373
- }));
374
- };
375
- //# sourceMappingURL=protocol-rest.js.map
1
+ export { protocol_rest$BinaryResponse as BinaryResponse, protocol_rest$RawResponse as RawResponse, protocol_rest$RawResponseRoot as RawResponseRoot, protocol_rest$SensitiveValue as SensitiveValue, protocol_rest$binaryResponseSymbol as binaryResponseSymbol, protocol_rest$hasSensitive as hasSensitive, protocol_rest$hasSensitiveMember as hasSensitiveMember, protocol_rest$makeRestProtocol as makeRestProtocol, protocol_rest$rawResponseRootSymbol as rawResponseRootSymbol, protocol_rest$rawResponseSymbol as rawResponseSymbol, protocol_rest$sensitiveValueSymbol as sensitiveValueSymbol, protocol_rest$unwrapRedactedDeep as unwrapRedactedDeep, protocol_rest$wrapSensitive as wrapSensitive } from "./_bundle/rest.js";
package/lib/query.js CHANGED
@@ -1,27 +1 @@
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
- import { filterQuery, flatMapQuery, itemsQuery, mapQuery, ofQuery, pagesQuery, queryFn, } from "./graphql.js";
18
- export const Query = {
19
- fn: queryFn,
20
- filter: filterQuery,
21
- map: mapQuery,
22
- flatMap: flatMapQuery,
23
- of: ofQuery,
24
- pages: pagesQuery,
25
- items: itemsQuery,
26
- };
27
- //# sourceMappingURL=query.js.map
1
+ export { query$Query as Query } from "./_bundle/graphql.js";
@@ -1,284 +1 @@
1
-
2
- export class SchemaMismatch extends Error {
3
- name = "SchemaError";
4
-
5
- path;
6
-
7
- expected;
8
- actual;
9
- constructor(path, expected, actual) {
10
- super(`Expected ${expected}, got ${show(actual)}${path.length ? ` at ${JSON.stringify(path.map((k) => (typeof k === "symbol" ? String(k) : k)))}` : ""}`);
11
- this.path = path;
12
- this.expected = expected;
13
- this.actual = actual;
14
- }
15
- }
16
-
17
-
18
-
19
-
20
- export const withholdActual = (mismatch) => new SchemaMismatch(mismatch.path, mismatch.expected, "[REDACTED]");
21
- const show = (u) => {
22
- if (u === MISSING)
23
- return "nothing (missing key)";
24
- if (u === undefined)
25
- return "undefined";
26
- if (typeof u === "string")
27
- return JSON.stringify(u.length > 40 ? `${u.slice(0, 40)}...` : u);
28
- if (Array.isArray(u))
29
- return "an array";
30
- if (u !== null && typeof u === "object")
31
- return "an object";
32
- return String(u);
33
- };
34
- const MISSING = Symbol("missing");
35
-
36
-
37
-
38
-
39
- const makeCompile = (exact) => {
40
- const fail = (expected, actual) => ({ path: [], expected, actual });
41
- const ok = () => undefined;
42
- const typeOf = (t) => (u) => typeof u === t ? undefined : fail(t, u);
43
- const compiled = new WeakMap();
44
- const compile = (n) => {
45
- let c = compiled.get(n);
46
- if (c === undefined) {
47
- // A node reached again while it compiles (only through Suspend) calls
48
- // through this slot.
49
- let self;
50
- compiled.set(n, (u) => self(u));
51
- self = c = withChecks(n, build(n));
52
- compiled.set(n, c);
53
- }
54
- return c;
55
- };
56
-
57
- const withChecks = (n, base) => {
58
- const checks = n.checks;
59
- if (!checks?.length || isLite(n))
60
- return base;
61
- const flat = [];
62
- const add = (c) => (c._tag === "FilterGroup" ? c.checks.forEach(add) : flat.push(c));
63
- checks.forEach(add);
64
- return (u) => {
65
- const f = base(u);
66
- if (f)
67
- return f;
68
- for (const c of flat) {
69
- const r = c.run(u, n, {});
70
- if (r !== undefined && r !== true)
71
- return fail(String(c.annotations?.expected ?? "a valid value"), u);
72
- }
73
- return undefined;
74
- };
75
- };
76
- const isLite = (n) => n["~lite"] === true;
77
- const isOptional = (n) => n.context?.isOptional === true;
78
- const build = (n) => {
79
- // A real node that decodes from another form is checked in that form (the
80
- // body as read); lite encodings are type-side only.
81
- const encoding = n.encoding;
82
- if (encoding?.length && !isLite(n))
83
- return compile(encoding[encoding.length - 1].to);
84
- switch (n._tag) {
85
- case "String":
86
- case "TemplateLiteral":
87
- return typeOf("string");
88
- case "Number":
89
- return typeOf("number");
90
- case "Boolean":
91
- return typeOf("boolean");
92
- case "BigInt":
93
- return typeOf("bigint");
94
- case "Symbol":
95
- return typeOf("symbol");
96
- case "Null":
97
- return (u) => (u === null ? undefined : fail("null", u));
98
- case "Undefined":
99
- return (u) => (u === undefined ? undefined : fail("undefined", u));
100
- case "Never":
101
- return (u) => fail("never", u);
102
- case "Literal":
103
- case "UniqueSymbol": {
104
- const lit = n._tag === "Literal" ? n.literal : n.symbol;
105
- return (u) => (u === lit ? undefined : fail(show(lit), u));
106
- }
107
- case "Enum": {
108
- const values = n.enums.map((e) => e[1]);
109
- return (u) => (values.includes(u) ? undefined : fail("an enum value", u));
110
- }
111
- case "ObjectKeyword":
112
- return (u) => (typeof u === "object" && u !== null) || typeof u === "function"
113
- ? undefined
114
- : fail("object | function", u);
115
- case "Union":
116
- return union(n);
117
- case "Arrays":
118
- return arrays(n);
119
- case "Objects":
120
- return objects(n);
121
- case "Suspend": {
122
- let inner;
123
- return (u) => (inner ??= compile(n.thunk()))(u);
124
- }
125
- case "Declaration": {
126
- if (isLite(n)) {
127
- const check = n.check;
128
- const name = String(n.annotations?.identifier ?? "a valid value");
129
- return check ? (u) => (check(u) ? undefined : fail(name, u)) : ok;
130
- }
131
- return declaration(n);
132
- }
133
- default:
134
- // Unknown, Any, Void (Effect's `void` accepts any value) and anything
135
- // without structure.
136
- return ok;
137
- }
138
- };
139
-
140
- const declaration = (n) => {
141
- const run = n.run;
142
- if (!run || n.typeParameters?.length)
143
- return ok;
144
- let parse;
145
- return (u) => {
146
- const exit = (parse ??= run([]))(u, n, {});
147
- return exit?._tag === "Failure"
148
- ? fail(String(n.annotations?.identifier ?? n.annotations?.expected ?? "a valid value"), u)
149
- : undefined;
150
- };
151
- };
152
- const union = (n) => {
153
- const members = n.types.map(compile);
154
- return (u) => {
155
- let first;
156
- for (let i = 0; i < members.length; i++) {
157
- const f = members[i](u);
158
- if (f === undefined)
159
- return undefined;
160
- first ??= f;
161
- }
162
- return members.length === 1 ? first : fail("a union member", u);
163
- };
164
- };
165
- const arrays = (n) => {
166
- const elements = (n.elements ?? []).map((e) => [compile(e), isOptional(e)]);
167
- const rest = (n.rest ?? []).map(compile);
168
- const head = rest[0];
169
- const tail = rest.slice(1);
170
- return (u) => {
171
- if (!Array.isArray(u))
172
- return fail("array", u);
173
- const len = u.length;
174
- for (let i = 0; i < elements.length; i++) {
175
- const [check, optional] = elements[i];
176
- if (i >= len) {
177
- if (optional)
178
- continue;
179
- return at(fail("an element", MISSING), i);
180
- }
181
- const f = check(u[i]);
182
- if (f)
183
- return at(f, i);
184
- }
185
- if (head === undefined) {
186
- return len > elements.length
187
- ? at(fail("never", u[elements.length]), elements.length)
188
- : undefined;
189
- }
190
- const end = len - tail.length;
191
- if (end < elements.length)
192
- return at(fail("an element", MISSING), len);
193
- for (let i = elements.length; i < end; i++) {
194
- const f = head(u[i]);
195
- if (f)
196
- return at(f, i);
197
- }
198
- for (let j = 0; j < tail.length; j++) {
199
- const f = tail[j](u[end + j]);
200
- if (f)
201
- return at(f, end + j);
202
- }
203
- return undefined;
204
- };
205
- };
206
- const at = (f, key) => {
207
- f.path.push(key);
208
- return f;
209
- };
210
- const objects = (n) => {
211
- const props = (n.propertySignatures ?? []).map((p) => [p.name, compile(p.type), isOptional(p.type)]);
212
- const index = (n.indexSignatures ?? []).map((s) => [compile(s.parameter), compile(s.type)]);
213
- const known = new Set(props.map((p) => p[0]));
214
- // Effect's empty struct is TypeScript's `{}`: any value but null and undefined.
215
- // Exact mode leaves it open too: generated code emits `{}` for outputs
216
- // it does not model.
217
- if (props.length === 0 && index.length === 0) {
218
- return (u) => (u === null || u === undefined ? fail("{}", u) : undefined);
219
- }
220
- return (u) => {
221
- if (typeof u !== "object" || u === null || Array.isArray(u))
222
- return fail("object", u);
223
- const o = u;
224
- for (let i = 0; i < props.length; i++) {
225
- const [name, check, optional] = props[i];
226
- if (!(name === "__proto__" ? Object.hasOwn(o, name) : name in o)) {
227
- if (optional)
228
- continue;
229
- return at(fail("a value", MISSING), name);
230
- }
231
- const f = check(o[name]);
232
- if (f)
233
- return at(f, name);
234
- }
235
- if (index.length || exact) {
236
- for (const key of Object.keys(o)) {
237
- if (known.has(key))
238
- continue;
239
- let covered = false;
240
- for (const [param, check] of index) {
241
- if (param(key) !== undefined)
242
- continue;
243
- covered = true;
244
- const f = check(o[key]);
245
- if (f)
246
- return at(f, key);
247
- }
248
- if (exact && !covered) {
249
- return at(fail("no value (the schema does not model this key)", o[key]), key);
250
- }
251
- }
252
- }
253
- return undefined;
254
- };
255
- };
256
- return compile;
257
- };
258
- let compileNode;
259
- let compileExact;
260
-
261
-
262
-
263
-
264
-
265
- export const decoderFor = (ast, exact = false) => {
266
- const decoders = exact ? exactDecoders : openDecoders;
267
- let decode = decoders.get(ast);
268
- if (decode === undefined) {
269
- const check = exact
270
- ? (compileExact ??= makeCompile(true))(ast)
271
- : (compileNode ??= makeCompile(false))(ast);
272
- decode = (input) => {
273
- const f = check(input);
274
- return f === undefined
275
- ? undefined
276
- : new SchemaMismatch(f.path.reverse(), f.expected, f.actual);
277
- };
278
- decoders.set(ast, decode);
279
- }
280
- return decode;
281
- };
282
- const openDecoders = /*@__PURE__*/ new WeakMap();
283
- const exactDecoders = /*@__PURE__*/ new WeakMap();
284
- //# sourceMappingURL=response-validation-strict.js.map
1
+ export { response_validation_strict$SchemaMismatch as SchemaMismatch, response_validation_strict$decoderFor as decoderFor, response_validation_strict$withholdActual as withholdActual } from "./_bundle/base.js";