@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.20

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 (291) hide show
  1. package/LICENSE +201 -0
  2. package/lib/_bundle/aws.js +2 -0
  3. package/lib/_bundle/aws.js.map +1 -0
  4. package/lib/_bundle/base.js +5 -0
  5. package/lib/_bundle/base.js.map +1 -0
  6. package/lib/_bundle/graphql.js +3 -0
  7. package/lib/_bundle/graphql.js.map +1 -0
  8. package/lib/_bundle/grpc.js +2 -0
  9. package/lib/_bundle/grpc.js.map +1 -0
  10. package/lib/_bundle/rest.js +2 -0
  11. package/lib/_bundle/rest.js.map +1 -0
  12. package/lib/_bundle/xml.js +4 -0
  13. package/lib/_bundle/xml.js.map +1 -0
  14. package/lib/annotations.d.ts +17 -0
  15. package/lib/annotations.d.ts.map +1 -0
  16. package/lib/annotations.js +2 -0
  17. package/lib/annotations.js.map +1 -0
  18. package/lib/api.d.ts +174 -18
  19. package/lib/api.d.ts.map +1 -1
  20. package/lib/api.js +1 -178
  21. package/lib/category.d.ts +4 -4
  22. package/lib/category.d.ts.map +1 -1
  23. package/lib/category.js +1 -280
  24. package/lib/chunks.d.ts +3 -0
  25. package/lib/chunks.d.ts.map +1 -0
  26. package/lib/chunks.js +1 -0
  27. package/lib/config.d.ts +68 -0
  28. package/lib/config.d.ts.map +1 -0
  29. package/lib/config.js +1 -0
  30. package/lib/crypto.d.ts +76 -0
  31. package/lib/crypto.d.ts.map +1 -0
  32. package/lib/crypto.js +1 -0
  33. package/lib/error-category.d.ts +1 -1
  34. package/lib/error-category.d.ts.map +1 -1
  35. package/lib/error-category.js +1 -46
  36. package/lib/errors.d.ts +64 -72
  37. package/lib/errors.d.ts.map +1 -1
  38. package/lib/errors.js +1 -186
  39. package/lib/graphql.d.ts +403 -0
  40. package/lib/graphql.d.ts.map +1 -0
  41. package/lib/graphql.js +1 -0
  42. package/lib/graphql.types.d.ts +12 -0
  43. package/lib/graphql.types.d.ts.map +1 -0
  44. package/lib/graphql.types.js +1 -0
  45. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  47. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  48. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  49. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  51. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  53. package/lib/grpc-transport-node-http2.d.ts +19 -0
  54. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  55. package/lib/grpc-transport-node-http2.js +2 -0
  56. package/lib/grpc-transport-node-http2.js.map +1 -0
  57. package/lib/grpc-transport.d.ts +76 -0
  58. package/lib/grpc-transport.d.ts.map +1 -0
  59. package/lib/grpc-transport.js +1 -0
  60. package/lib/hpack.d.ts +34 -0
  61. package/lib/hpack.d.ts.map +1 -0
  62. package/lib/hpack.js +2 -0
  63. package/lib/hpack.js.map +1 -0
  64. package/lib/index.d.ts +32 -0
  65. package/lib/index.d.ts.map +1 -0
  66. package/lib/index.js +17 -0
  67. package/lib/pagination.d.ts +101 -24
  68. package/lib/pagination.d.ts.map +1 -1
  69. package/lib/pagination.js +1 -182
  70. package/lib/plain-values.d.ts +10 -0
  71. package/lib/plain-values.d.ts.map +1 -0
  72. package/lib/plain-values.js +2 -0
  73. package/lib/plain-values.js.map +1 -0
  74. package/lib/protobuf.d.ts +92 -0
  75. package/lib/protobuf.d.ts.map +1 -0
  76. package/lib/protobuf.js +1 -0
  77. package/lib/protocol-grpc.d.ts +86 -0
  78. package/lib/protocol-grpc.d.ts.map +1 -0
  79. package/lib/protocol-grpc.js +1 -0
  80. package/lib/protocol-http.d.ts +102 -23
  81. package/lib/protocol-http.d.ts.map +1 -1
  82. package/lib/protocol-http.js +1 -554
  83. package/lib/protocol-rest.d.ts +120 -50
  84. package/lib/protocol-rest.d.ts.map +1 -1
  85. package/lib/protocol-rest.js +1 -242
  86. package/lib/query.d.ts +29 -0
  87. package/lib/query.d.ts.map +1 -0
  88. package/lib/query.js +1 -0
  89. package/lib/response-validation-strict.d.ts +48 -0
  90. package/lib/response-validation-strict.d.ts.map +1 -0
  91. package/lib/response-validation-strict.js +1 -0
  92. package/lib/response-validation.d.ts +86 -0
  93. package/lib/response-validation.d.ts.map +1 -0
  94. package/lib/response-validation.js +1 -0
  95. package/lib/retry-after.d.ts +3 -3
  96. package/lib/retry-after.d.ts.map +1 -1
  97. package/lib/retry-after.js +1 -112
  98. package/lib/retry.d.ts +48 -29
  99. package/lib/retry.d.ts.map +1 -1
  100. package/lib/retry.js +1 -210
  101. package/lib/schema-lite-impl.d.ts +158 -0
  102. package/lib/schema-lite-impl.d.ts.map +1 -0
  103. package/lib/schema-lite-impl.js +1 -0
  104. package/lib/schema-lite-typed.d.ts +41 -0
  105. package/lib/schema-lite-typed.d.ts.map +1 -0
  106. package/lib/schema-lite-typed.js +1 -0
  107. package/lib/schema-lite.d.ts +40 -0
  108. package/lib/schema-lite.d.ts.map +1 -0
  109. package/lib/schema-lite.js +1 -0
  110. package/lib/schema.d.ts +21 -7
  111. package/lib/schema.d.ts.map +1 -1
  112. package/lib/schema.js +1 -48
  113. package/lib/sdk-error.d.ts +27 -0
  114. package/lib/sdk-error.d.ts.map +1 -0
  115. package/lib/sdk-error.js +1 -0
  116. package/lib/sensitive.d.ts +28 -0
  117. package/lib/sensitive.d.ts.map +1 -0
  118. package/lib/sensitive.js +2 -0
  119. package/lib/sensitive.js.map +1 -0
  120. package/lib/telemetry-debug.d.ts +6 -0
  121. package/lib/telemetry-debug.d.ts.map +1 -0
  122. package/lib/telemetry-debug.js +2 -0
  123. package/lib/telemetry-debug.js.map +1 -0
  124. package/lib/telemetry-hooks.d.ts +32 -0
  125. package/lib/telemetry-hooks.d.ts.map +1 -0
  126. package/lib/telemetry-hooks.js +2 -0
  127. package/lib/telemetry-hooks.js.map +1 -0
  128. package/lib/telemetry-host-rules.d.ts +23 -0
  129. package/lib/telemetry-host-rules.d.ts.map +1 -0
  130. package/lib/telemetry-host-rules.js +2 -0
  131. package/lib/telemetry-host-rules.js.map +1 -0
  132. package/lib/telemetry-lambda-context.d.ts +17 -0
  133. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  134. package/lib/telemetry-lambda-context.js +2 -0
  135. package/lib/telemetry-lambda-context.js.map +1 -0
  136. package/lib/telemetry-message-context.d.ts +52 -0
  137. package/lib/telemetry-message-context.d.ts.map +1 -0
  138. package/lib/telemetry-message-context.js +2 -0
  139. package/lib/telemetry-message-context.js.map +1 -0
  140. package/lib/telemetry-metrics.d.ts +6 -0
  141. package/lib/telemetry-metrics.d.ts.map +1 -0
  142. package/lib/telemetry-metrics.js +2 -0
  143. package/lib/telemetry-metrics.js.map +1 -0
  144. package/lib/telemetry-name-template.d.ts +13 -0
  145. package/lib/telemetry-name-template.d.ts.map +1 -0
  146. package/lib/telemetry-name-template.js +2 -0
  147. package/lib/telemetry-name-template.js.map +1 -0
  148. package/lib/telemetry-stream.d.ts +11 -0
  149. package/lib/telemetry-stream.d.ts.map +1 -0
  150. package/lib/telemetry-stream.js +2 -0
  151. package/lib/telemetry-stream.js.map +1 -0
  152. package/lib/telemetry-xray.d.ts +28 -0
  153. package/lib/telemetry-xray.d.ts.map +1 -0
  154. package/lib/telemetry-xray.js +2 -0
  155. package/lib/telemetry-xray.js.map +1 -0
  156. package/lib/telemetry.d.ts +288 -0
  157. package/lib/telemetry.d.ts.map +1 -0
  158. package/lib/telemetry.js +3 -0
  159. package/lib/telemetry.js.map +1 -0
  160. package/lib/trait.d.ts +71 -20
  161. package/lib/trait.d.ts.map +1 -1
  162. package/lib/trait.js +1 -107
  163. package/lib/unknown-error.d.ts +18 -0
  164. package/lib/unknown-error.d.ts.map +1 -0
  165. package/lib/unknown-error.js +1 -0
  166. package/lib/xml.d.ts +44 -0
  167. package/lib/xml.d.ts.map +1 -0
  168. package/lib/xml.js +1 -0
  169. package/package.json +13 -13
  170. package/src/annotations.ts +53 -0
  171. package/src/api.ts +1370 -200
  172. package/src/category.ts +76 -106
  173. package/src/chunks.ts +30 -0
  174. package/src/config.ts +245 -0
  175. package/src/crypto.ts +202 -0
  176. package/src/error-category.ts +16 -29
  177. package/src/errors.ts +75 -75
  178. package/src/graphql.ts +1778 -0
  179. package/src/graphql.types.ts +105 -0
  180. package/src/grpc-transport-cloudflare-http2.ts +494 -0
  181. package/src/grpc-transport-cloudflare-sockets.ts +299 -0
  182. package/src/grpc-transport-node-http2.ts +234 -0
  183. package/src/grpc-transport.ts +118 -0
  184. package/src/hpack.ts +331 -0
  185. package/src/index.ts +31 -0
  186. package/src/pagination.ts +368 -94
  187. package/src/plain-values.ts +41 -0
  188. package/src/protobuf.ts +1332 -0
  189. package/src/protocol-grpc.ts +641 -0
  190. package/src/protocol-http.ts +622 -322
  191. package/src/protocol-rest.ts +440 -227
  192. package/src/query.ts +39 -0
  193. package/src/response-validation-strict.ts +327 -0
  194. package/src/response-validation.ts +161 -0
  195. package/src/retry-after.ts +7 -13
  196. package/src/retry.ts +96 -110
  197. package/src/schema-lite-impl.ts +550 -0
  198. package/src/schema-lite-typed.ts +44 -0
  199. package/src/schema-lite.ts +44 -0
  200. package/src/schema.ts +259 -15
  201. package/src/sdk-error.ts +33 -0
  202. package/src/sensitive.ts +154 -0
  203. package/src/telemetry-debug.ts +179 -0
  204. package/src/telemetry-hooks.ts +33 -0
  205. package/src/telemetry-host-rules.ts +39 -0
  206. package/src/telemetry-lambda-context.ts +46 -0
  207. package/src/telemetry-message-context.ts +170 -0
  208. package/src/telemetry-metrics.ts +69 -0
  209. package/src/telemetry-name-template.ts +26 -0
  210. package/src/telemetry-stream.ts +100 -0
  211. package/src/telemetry-xray.ts +66 -0
  212. package/src/telemetry.ts +832 -0
  213. package/src/trait.ts +106 -67
  214. package/src/unknown-error.ts +38 -0
  215. package/src/xml.ts +346 -0
  216. package/lib/api.js.map +0 -1
  217. package/lib/category.js.map +0 -1
  218. package/lib/codegen/cli.d.ts +0 -29
  219. package/lib/codegen/cli.d.ts.map +0 -1
  220. package/lib/codegen/cli.js +0 -165
  221. package/lib/codegen/cli.js.map +0 -1
  222. package/lib/codegen/emit.d.ts +0 -129
  223. package/lib/codegen/emit.d.ts.map +0 -1
  224. package/lib/codegen/emit.js +0 -105
  225. package/lib/codegen/emit.js.map +0 -1
  226. package/lib/codegen/format.d.ts +0 -23
  227. package/lib/codegen/format.d.ts.map +0 -1
  228. package/lib/codegen/format.js +0 -28
  229. package/lib/codegen/format.js.map +0 -1
  230. package/lib/codegen/generator.d.ts +0 -334
  231. package/lib/codegen/generator.d.ts.map +0 -1
  232. package/lib/codegen/generator.js +0 -691
  233. package/lib/codegen/generator.js.map +0 -1
  234. package/lib/codegen/graph.d.ts +0 -36
  235. package/lib/codegen/graph.d.ts.map +0 -1
  236. package/lib/codegen/graph.js +0 -136
  237. package/lib/codegen/graph.js.map +0 -1
  238. package/lib/codegen/members.d.ts +0 -25
  239. package/lib/codegen/members.d.ts.map +0 -1
  240. package/lib/codegen/members.js +0 -55
  241. package/lib/codegen/members.js.map +0 -1
  242. package/lib/codegen/naming.d.ts +0 -29
  243. package/lib/codegen/naming.d.ts.map +0 -1
  244. package/lib/codegen/naming.js +0 -74
  245. package/lib/codegen/naming.js.map +0 -1
  246. package/lib/codegen/openapi-cli.d.ts +0 -38
  247. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  248. package/lib/codegen/openapi-cli.js +0 -107
  249. package/lib/codegen/openapi-cli.js.map +0 -1
  250. package/lib/codegen/openapi.d.ts +0 -115
  251. package/lib/codegen/openapi.d.ts.map +0 -1
  252. package/lib/codegen/openapi.js +0 -1220
  253. package/lib/codegen/openapi.js.map +0 -1
  254. package/lib/codegen/operations.d.ts +0 -24
  255. package/lib/codegen/operations.d.ts.map +0 -1
  256. package/lib/codegen/operations.js +0 -56
  257. package/lib/codegen/operations.js.map +0 -1
  258. package/lib/codegen/pagination.d.ts +0 -39
  259. package/lib/codegen/pagination.d.ts.map +0 -1
  260. package/lib/codegen/pagination.js +0 -33
  261. package/lib/codegen/pagination.js.map +0 -1
  262. package/lib/codegen/prelude.d.ts +0 -15
  263. package/lib/codegen/prelude.d.ts.map +0 -1
  264. package/lib/codegen/prelude.js +0 -60
  265. package/lib/codegen/prelude.js.map +0 -1
  266. package/lib/error-category.js.map +0 -1
  267. package/lib/errors.js.map +0 -1
  268. package/lib/json-patch.d.ts +0 -44
  269. package/lib/json-patch.d.ts.map +0 -1
  270. package/lib/json-patch.js +0 -174
  271. package/lib/json-patch.js.map +0 -1
  272. package/lib/pagination.js.map +0 -1
  273. package/lib/protocol-http.js.map +0 -1
  274. package/lib/protocol-rest.js.map +0 -1
  275. package/lib/retry-after.js.map +0 -1
  276. package/lib/retry.js.map +0 -1
  277. package/lib/schema.js.map +0 -1
  278. package/lib/trait.js.map +0 -1
  279. package/src/codegen/cli.ts +0 -268
  280. package/src/codegen/emit.ts +0 -207
  281. package/src/codegen/format.ts +0 -47
  282. package/src/codegen/generator.ts +0 -1153
  283. package/src/codegen/graph.ts +0 -151
  284. package/src/codegen/members.ts +0 -71
  285. package/src/codegen/naming.ts +0 -86
  286. package/src/codegen/openapi-cli.ts +0 -166
  287. package/src/codegen/openapi.ts +0 -1450
  288. package/src/codegen/operations.ts +0 -76
  289. package/src/codegen/pagination.ts +0 -71
  290. package/src/codegen/prelude.ts +0 -70
  291. package/src/json-patch.ts +0 -222
package/src/query.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Query combinators for GraphQL SDKs.
3
+ *
4
+ * Import this module next to a generated client:
5
+ *
6
+ * import { Query } from "@distilled.cloud/core/query"
7
+ * import { Railway } from "@distilled.cloud/railway"
8
+ *
9
+ * `Query.fn` takes a **builder** (plain function, not `Effect.gen`) that
10
+ * returns a plan of `Query<Value>` and `Effect` values. It walks Map /
11
+ * Filter / FlatMap / Of, posts one GraphQL document, then interprets the
12
+ * plan. Roots (`Railway.me`) come from the generated SDK; they are not
13
+ * combinators.
14
+ *
15
+ * @see {@link file://./graphql.ts} for the algebra, compiler, and transport.
16
+ */
17
+ import {
18
+ filterQuery,
19
+ flatMapQuery,
20
+ itemsQuery,
21
+ mapQuery,
22
+ ofQuery,
23
+ pagesQuery,
24
+ queryFn,
25
+ type Query as QueryType,
26
+ } from "./graphql.ts";
27
+
28
+ export type Query<Value, Error = never> = QueryType<Value, Error>;
29
+ export type { PlanError, QueryError, UnwrapPlan } from "./graphql.ts";
30
+
31
+ export const Query = {
32
+ fn: queryFn,
33
+ filter: filterQuery,
34
+ map: mapQuery,
35
+ flatMap: flatMapQuery,
36
+ of: ofQuery,
37
+ pages: pagesQuery,
38
+ items: itemsQuery,
39
+ };
@@ -0,0 +1,327 @@
1
+ /**
2
+ * The strict response checker: validates a decoded response against its
3
+ * output AST without Effect Schema.
4
+ *
5
+ * Generated output schemas are lite nodes (`schema-lite-impl.ts`); the
6
+ * checker accepts what Effect Schema's decoder accepted for the schema
7
+ * `toEffect` built from them (`response-validation-strict.test.ts` compares
8
+ * the two on random schemas and values). Each AST node compiles once to a
9
+ * closure, so a check walks the value only.
10
+ *
11
+ * Two modes: `additionalProperties` lets keys an object does not model
12
+ * through (Effect's default), `strict` (`exact`) rejects them (Effect's
13
+ * `onExcessProperty: "error"`). In both, an index signature covers only the
14
+ * keys the object does not declare (OpenAPI `additionalProperties`), and an
15
+ * empty struct accepts any object (generated code's opaque output).
16
+ *
17
+ * Hand-written protocols may pass real Effect ASTs. Their structure is
18
+ * checked the same way; refinement `checks` run, but a real `Declaration`
19
+ * with type parameters and `TemplateLiteral` contents are not checked.
20
+ */
21
+ import type * as AST from "effect/SchemaAST";
22
+ import type { Node } from "./schema-lite-impl.ts";
23
+
24
+ /** A response that does not match its output schema (the `cause` of a strict `<Sdk>ParseError`). */
25
+ export class SchemaMismatch extends Error {
26
+ override readonly name = "SchemaError";
27
+ /** Where in the response the mismatch is, outermost key first. */
28
+ readonly path: ReadonlyArray<PropertyKey>;
29
+ /** What the schema expected there, e.g. `string`. */
30
+ readonly expected: string;
31
+ readonly actual: unknown;
32
+ constructor(path: ReadonlyArray<PropertyKey>, expected: string, actual: unknown) {
33
+ super(
34
+ `Expected ${expected}, got ${show(actual)}${path.length ? ` at ${JSON.stringify(path.map((k) => (typeof k === "symbol" ? String(k) : k)))}` : ""}`,
35
+ );
36
+ this.path = path;
37
+ this.expected = expected;
38
+ this.actual = actual;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * `mismatch` with its offending value replaced by `"[REDACTED]"`, for a parse
44
+ * error that withholds the body (the value may be a secret).
45
+ */
46
+ export const withholdActual = (mismatch: SchemaMismatch): SchemaMismatch =>
47
+ new SchemaMismatch(mismatch.path, mismatch.expected, "[REDACTED]");
48
+
49
+ /**
50
+ * Validate `input` synchronously: `undefined` when it matches, else the
51
+ * mismatch.
52
+ */
53
+ export type Decode = (input: unknown) => SchemaMismatch | undefined;
54
+
55
+ const show = (u: unknown): string => {
56
+ if (u === MISSING) return "nothing (missing key)";
57
+ if (u === undefined) return "undefined";
58
+ if (typeof u === "string") return JSON.stringify(u.length > 40 ? `${u.slice(0, 40)}...` : u);
59
+ if (Array.isArray(u)) return "an array";
60
+ if (u !== null && typeof u === "object") return "an object";
61
+ return String(u);
62
+ };
63
+
64
+ /** A failed check: the path is filled in on the way out, innermost key first. */
65
+ interface Fail {
66
+ readonly path: PropertyKey[];
67
+ readonly expected: string;
68
+ readonly actual: unknown;
69
+ }
70
+ type Check = (u: unknown) => Fail | undefined;
71
+
72
+ const MISSING: unique symbol = Symbol("missing");
73
+ /**
74
+ * The node compiler, built on the first strict check: importing this module
75
+ * (every REST program does, through the protocol) allocates almost nothing.
76
+ */
77
+ const makeCompile = (exact: boolean): ((n: Node) => Check) => {
78
+ const fail = (expected: string, actual: unknown): Fail => ({ path: [], expected, actual });
79
+ const ok: Check = () => undefined;
80
+ const typeOf =
81
+ (t: string): Check =>
82
+ (u) =>
83
+ typeof u === t ? undefined : fail(t, u);
84
+
85
+ const compiled = new WeakMap<object, Check>();
86
+
87
+ const compile = (n: Node): Check => {
88
+ let c = compiled.get(n);
89
+ if (c === undefined) {
90
+ // A node reached again while it compiles (only through Suspend) calls
91
+ // through this slot.
92
+ let self: Check | undefined;
93
+ compiled.set(n, (u) => self!(u));
94
+ self = c = withChecks(n, build(n));
95
+ compiled.set(n, c);
96
+ }
97
+ return c;
98
+ };
99
+
100
+ /** Effect refinements (`checks`) on real nodes run after the structural check. */
101
+ const withChecks = (n: Node, base: Check): Check => {
102
+ const checks = (n as { checks?: ReadonlyArray<any> }).checks;
103
+ if (!checks?.length || isLite(n)) return base;
104
+ const flat: any[] = [];
105
+ const add = (c: any) => (c._tag === "FilterGroup" ? c.checks.forEach(add) : flat.push(c));
106
+ checks.forEach(add);
107
+ return (u) => {
108
+ const f = base(u);
109
+ if (f) return f;
110
+ for (const c of flat) {
111
+ const r = c.run(u, n, {});
112
+ if (r !== undefined && r !== true)
113
+ return fail(String(c.annotations?.expected ?? "a valid value"), u);
114
+ }
115
+ return undefined;
116
+ };
117
+ };
118
+
119
+ const isLite = (n: Node): boolean => (n as any)["~lite"] === true;
120
+
121
+ const isOptional = (n: Node): boolean => n.context?.isOptional === true;
122
+
123
+ const build = (n: Node): Check => {
124
+ // A real node that decodes from another form is checked in that form (the
125
+ // body as read); lite encodings are type-side only.
126
+ const encoding = (n as { encoding?: ReadonlyArray<{ to: Node }> }).encoding;
127
+ if (encoding?.length && !isLite(n)) return compile(encoding[encoding.length - 1]!.to);
128
+ switch (n._tag) {
129
+ case "String":
130
+ case "TemplateLiteral":
131
+ return typeOf("string");
132
+ case "Number":
133
+ return typeOf("number");
134
+ case "Boolean":
135
+ return typeOf("boolean");
136
+ case "BigInt":
137
+ return typeOf("bigint");
138
+ case "Symbol":
139
+ return typeOf("symbol");
140
+ case "Null":
141
+ return (u) => (u === null ? undefined : fail("null", u));
142
+ case "Undefined":
143
+ return (u) => (u === undefined ? undefined : fail("undefined", u));
144
+ case "Never":
145
+ return (u) => fail("never", u);
146
+ case "Literal":
147
+ case "UniqueSymbol": {
148
+ const lit = n._tag === "Literal" ? n.literal : (n as any).symbol;
149
+ return (u) => (u === lit ? undefined : fail(show(lit), u));
150
+ }
151
+ case "Enum": {
152
+ const values = ((n as any).enums as ReadonlyArray<readonly [string, unknown]>).map(
153
+ (e) => e[1],
154
+ );
155
+ return (u) => (values.includes(u) ? undefined : fail("an enum value", u));
156
+ }
157
+ case "ObjectKeyword":
158
+ return (u) =>
159
+ (typeof u === "object" && u !== null) || typeof u === "function"
160
+ ? undefined
161
+ : fail("object | function", u);
162
+ case "Union":
163
+ return union(n);
164
+ case "Arrays":
165
+ return arrays(n);
166
+ case "Objects":
167
+ return objects(n);
168
+ case "Suspend": {
169
+ let inner: Check | undefined;
170
+ return (u) => (inner ??= compile(n.thunk!()))(u);
171
+ }
172
+ case "Declaration": {
173
+ if (isLite(n)) {
174
+ const check = n.check;
175
+ const name = String(n.annotations?.identifier ?? "a valid value");
176
+ return check ? (u) => (check(u) ? undefined : fail(name, u)) : ok;
177
+ }
178
+ return declaration(n);
179
+ }
180
+ default:
181
+ // Unknown, Any, Void (Effect's `void` accepts any value) and anything
182
+ // without structure.
183
+ return ok;
184
+ }
185
+ };
186
+
187
+ /** A real Effect declaration without type parameters runs its own parser (synchronous ones only). */
188
+ const declaration = (n: Node): Check => {
189
+ const run = (n as any).run as ((tps: ReadonlyArray<unknown>) => any) | undefined;
190
+ if (!run || n.typeParameters?.length) return ok;
191
+ let parse: any;
192
+ return (u) => {
193
+ const exit = (parse ??= run([]))(u, n, {});
194
+ return exit?._tag === "Failure"
195
+ ? fail(String(n.annotations?.identifier ?? n.annotations?.expected ?? "a valid value"), u)
196
+ : undefined;
197
+ };
198
+ };
199
+
200
+ const union = (n: Node): Check => {
201
+ const members = n.types!.map(compile);
202
+ return (u) => {
203
+ let first: Fail | undefined;
204
+ for (let i = 0; i < members.length; i++) {
205
+ const f = members[i]!(u);
206
+ if (f === undefined) return undefined;
207
+ first ??= f;
208
+ }
209
+ return members.length === 1 ? first : fail("a union member", u);
210
+ };
211
+ };
212
+
213
+ const arrays = (n: Node): Check => {
214
+ const elements = (n.elements ?? []).map((e) => [compile(e), isOptional(e)] as const);
215
+ const rest = (n.rest ?? []).map(compile);
216
+ const head = rest[0];
217
+ const tail = rest.slice(1);
218
+ return (u) => {
219
+ if (!Array.isArray(u)) return fail("array", u);
220
+ const len = u.length;
221
+ for (let i = 0; i < elements.length; i++) {
222
+ const [check, optional] = elements[i]!;
223
+ if (i >= len) {
224
+ if (optional) continue;
225
+ return at(fail("an element", MISSING), i);
226
+ }
227
+ const f = check(u[i]);
228
+ if (f) return at(f, i);
229
+ }
230
+ if (head === undefined) {
231
+ return len > elements.length
232
+ ? at(fail("never", u[elements.length]), elements.length)
233
+ : undefined;
234
+ }
235
+ const end = len - tail.length;
236
+ if (end < elements.length) return at(fail("an element", MISSING), len);
237
+ for (let i = elements.length; i < end; i++) {
238
+ const f = head(u[i]);
239
+ if (f) return at(f, i);
240
+ }
241
+ for (let j = 0; j < tail.length; j++) {
242
+ const f = tail[j]!(u[end + j]);
243
+ if (f) return at(f, end + j);
244
+ }
245
+ return undefined;
246
+ };
247
+ };
248
+
249
+ const at = (f: Fail, key: PropertyKey): Fail => {
250
+ f.path.push(key);
251
+ return f;
252
+ };
253
+
254
+ const objects = (n: Node): Check => {
255
+ const props = (n.propertySignatures ?? []).map(
256
+ (p) => [p.name, compile(p.type), isOptional(p.type)] as const,
257
+ );
258
+ const index = (n.indexSignatures ?? []).map(
259
+ (s) => [compile(s.parameter), compile(s.type)] as const,
260
+ );
261
+ const known = new Set(props.map((p) => p[0]));
262
+ // Effect's empty struct is TypeScript's `{}`: any value but null and undefined.
263
+ // Exact mode leaves it open too: generated code emits `{}` for outputs
264
+ // it does not model.
265
+ if (props.length === 0 && index.length === 0) {
266
+ return (u) => (u === null || u === undefined ? fail("{}", u) : undefined);
267
+ }
268
+ return (u) => {
269
+ if (typeof u !== "object" || u === null || Array.isArray(u)) return fail("object", u);
270
+ const o = u as Record<PropertyKey, unknown>;
271
+ for (let i = 0; i < props.length; i++) {
272
+ const [name, check, optional] = props[i]!;
273
+ if (!(name === "__proto__" ? Object.hasOwn(o, name) : name in o)) {
274
+ if (optional) continue;
275
+ return at(fail("a value", MISSING), name);
276
+ }
277
+ const f = check(o[name]);
278
+ if (f) return at(f, name);
279
+ }
280
+ if (index.length || exact) {
281
+ for (const key of Object.keys(o)) {
282
+ if (known.has(key)) continue;
283
+ let covered = false;
284
+ for (const [param, check] of index) {
285
+ if (param(key) !== undefined) continue;
286
+ covered = true;
287
+ const f = check(o[key]);
288
+ if (f) return at(f, key);
289
+ }
290
+ if (exact && !covered) {
291
+ return at(fail("no value (the schema does not model this key)", o[key]), key);
292
+ }
293
+ }
294
+ }
295
+ return undefined;
296
+ };
297
+ };
298
+
299
+ return compile;
300
+ };
301
+ let compileNode: ((n: Node) => Check) | undefined;
302
+ let compileExact: ((n: Node) => Check) | undefined;
303
+
304
+ /**
305
+ * The checker for an output AST: compiled once per node and mode, then
306
+ * reused. `exact` also rejects keys an object does not model (the `strict`
307
+ * mode); without it they pass (`additionalProperties`).
308
+ */
309
+ export const decoderFor = (ast: AST.AST, exact = false): Decode => {
310
+ const decoders = exact ? exactDecoders : openDecoders;
311
+ let decode = decoders.get(ast);
312
+ if (decode === undefined) {
313
+ const check = exact
314
+ ? (compileExact ??= makeCompile(true))(ast as unknown as Node)
315
+ : (compileNode ??= makeCompile(false))(ast as unknown as Node);
316
+ decode = (input) => {
317
+ const f = check(input);
318
+ return f === undefined
319
+ ? undefined
320
+ : new SchemaMismatch(f.path.reverse(), f.expected, f.actual);
321
+ };
322
+ decoders.set(ast, decode);
323
+ }
324
+ return decode;
325
+ };
326
+ const openDecoders = /*@__PURE__*/ new WeakMap<AST.AST, Decode>();
327
+ const exactDecoders = /*@__PURE__*/ new WeakMap<AST.AST, Decode>();
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Response validation mode, shared by every distilled SDK.
3
+ *
4
+ * Generated SDKs carry a schema for every operation's output. What a
5
+ * protocol does with it on a 2xx response depends on the mode:
6
+ *
7
+ * lenient (default): the response is returned as the protocol read it.
8
+ * A body that does not match the declared output type
9
+ * (a missing member, a wrong primitive, a non-JSON
10
+ * body) still succeeds, except that a non-JSON body for
11
+ * an output with sensitive members fails in every mode
12
+ * (REST-style protocols through core's `checkSuccess`
13
+ * in `protocol-rest`, plus ZeroSSL and AWS).
14
+ * additionalProperties: the response is checked against the output
15
+ * schema, and a mismatch fails the call with the SDK's
16
+ * `<Sdk>ParseError` (AWS: `ParseError`). Keys the
17
+ * schema does not model are allowed and kept.
18
+ * strict: as `additionalProperties`, and a key the schema does
19
+ * not model also fails the call, at any depth. Open
20
+ * objects (an index signature, e.g. OpenAPI
21
+ * `additionalProperties`) and empty structs (opaque
22
+ * outputs) still accept any key.
23
+ *
24
+ * The mode is one {@link ResponseValidation} reference keyed by a string, so
25
+ * a single `Layer` switches every distilled SDK in a program -- AWS,
26
+ * Cloudflare, Neon, ... -- at once, and nests like any other Effect service:
27
+ *
28
+ * ```ts
29
+ * import { ResponseValidation } from "@distilled.cloud/core";
30
+ *
31
+ * // whole program
32
+ * program.pipe(Effect.provide(ResponseValidation.strict));
33
+ *
34
+ * // one call back to lenient inside a strict program
35
+ * Neon.getProject({ projectId }).pipe(Effect.provide(ResponseValidation.lenient));
36
+ * ```
37
+ *
38
+ * The mode is set only by these layers; without one, every call is lenient.
39
+ */
40
+ import * as Context from "effect/Context";
41
+ import * as Effect from "effect/Effect";
42
+ import * as Layer from "effect/Layer";
43
+ import type * as AST from "effect/SchemaAST";
44
+ import { type Decode, decoderFor, SchemaMismatch } from "./response-validation-strict.ts";
45
+
46
+ export { SchemaMismatch, withholdActual } from "./response-validation-strict.ts";
47
+
48
+ export type Mode = "lenient" | "additionalProperties" | "strict";
49
+
50
+ /**
51
+ * The active validation mode. Read by protocols at call time on the calling
52
+ * fiber; `lenient` unless an {@link additionalProperties} or {@link strict}
53
+ * layer is provided.
54
+ */
55
+ export const ResponseValidation = /*@__PURE__*/ Context.Reference<Mode>(
56
+ "@distilled.cloud/core/ResponseValidation",
57
+ { defaultValue: () => "lenient" },
58
+ );
59
+
60
+ /**
61
+ * The checker the validating modes use (`exact`: reject unmodeled keys). The
62
+ * `additionalProperties` and `strict` layers provide it, so the checker is
63
+ * bundled only with programs that validate.
64
+ */
65
+ export const StrictDecoder = /*@__PURE__*/ Context.Reference<
66
+ ((ast: AST.AST, exact: boolean) => Decode) | undefined
67
+ >("@distilled.cloud/core/ResponseValidation/StrictDecoder", { defaultValue: () => undefined });
68
+
69
+ /**
70
+ * A layer that is also the `Context` it provides. `Effect.provide` treats a
71
+ * `Context` as a plain `provideContext`, so `Effect.provide(strict)` around
72
+ * a single call costs a context merge instead of a layer build (scope, memo
73
+ * map and a few fibers steps per call); every other use sees an ordinary
74
+ * `Layer`. The context state is read through the prototype.
75
+ */
76
+ const layerOfContext = (context: Context.Context<never>): Layer.Layer<never> => {
77
+ const layer = Layer.succeedContext(context);
78
+ const both = Object.create(context);
79
+ const layerProto = Object.getPrototypeOf(layer);
80
+ for (const key of Reflect.ownKeys(layerProto)) {
81
+ if (key !== "pipe") both[key] = layerProto[key];
82
+ }
83
+ both.build = (layer as unknown as { build: unknown }).build;
84
+ return both;
85
+ };
86
+
87
+ /**
88
+ * Check every 2xx response against its output schema and fail on a
89
+ * mismatch, including any key the schema does not model.
90
+ */
91
+ export const strict: Layer.Layer<never> = /*@__PURE__*/ layerOfContext(
92
+ /*@__PURE__*/ Context.add(
93
+ /*@__PURE__*/ Context.make(ResponseValidation, "strict"),
94
+ StrictDecoder,
95
+ decoderFor,
96
+ ),
97
+ );
98
+
99
+ /**
100
+ * Check every 2xx response against its output schema and fail on a
101
+ * mismatch; keys the schema does not model are allowed.
102
+ */
103
+ export const additionalProperties: Layer.Layer<never> = /*@__PURE__*/ layerOfContext(
104
+ /*@__PURE__*/ Context.add(
105
+ /*@__PURE__*/ Context.make(ResponseValidation, "additionalProperties"),
106
+ StrictDecoder,
107
+ decoderFor,
108
+ ),
109
+ );
110
+
111
+ /** Return 2xx responses as read, without checking them against the schema. */
112
+ export const lenient: Layer.Layer<never> = /*@__PURE__*/ layerOfContext(
113
+ /*@__PURE__*/ Context.make(ResponseValidation, "lenient"),
114
+ );
115
+
116
+ /** Whether the calling fiber validates responses (any mode but lenient). */
117
+ export const isValidating: Effect.Effect<boolean> = /*@__PURE__*/ Effect.map(
118
+ ResponseValidation,
119
+ (mode) => mode !== "lenient",
120
+ );
121
+
122
+ /**
123
+ * For a 2xx body the protocol could not read into the shape it transforms
124
+ * (e.g. invalid JSON): fail with `error` when validating, succeed with
125
+ * `asRead` (usually the body text) in lenient mode.
126
+ */
127
+ export const failUnlessLenient = <A, E>(error: E, asRead: A): Effect.Effect<A, E> =>
128
+ Effect.flatMap(ResponseValidation, (mode) =>
129
+ mode === "lenient" ? Effect.succeed(asRead) : Effect.fail(error),
130
+ );
131
+
132
+ /**
133
+ * The schema error for `value` against `outputAst` when validating,
134
+ * `undefined` when it matches or the mode is lenient. Synchronous, for
135
+ * protocols that already hold the calling fiber's context.
136
+ */
137
+ export const checkResponse = (
138
+ context: Context.Context<any>,
139
+ outputAst: AST.AST,
140
+ value: unknown,
141
+ ): SchemaMismatch | undefined => {
142
+ const mode = Context.get(context, ResponseValidation);
143
+ if (mode === "lenient") return undefined;
144
+ const decoderOf = Context.get(context, StrictDecoder);
145
+ if (!decoderOf) {
146
+ // The mode was set without the layer that brings its decoder: the
147
+ // response can't be checked, so the call fails as a mismatch.
148
+ return new SchemaMismatch([], `the ResponseValidation.${mode} layer`, mode);
149
+ }
150
+ return decoderOf(outputAst, mode === "strict")(value);
151
+ };
152
+
153
+ export const validateResponse = <E>(
154
+ outputAst: AST.AST,
155
+ value: unknown,
156
+ onError: (cause: SchemaMismatch) => E,
157
+ ): Effect.Effect<unknown, E> =>
158
+ Effect.withFiber((fiber) => {
159
+ const error = checkResponse(fiber.context as Context.Context<any>, outputAst, value);
160
+ return error === undefined ? Effect.succeed(value) : Effect.fail(onError(error));
161
+ });
@@ -18,7 +18,7 @@ import * as Duration from "effect/Duration";
18
18
  import { RETRYABLE_HTTP_STATUSES } from "./errors.ts";
19
19
 
20
20
  /**
21
- * Header bag — case-insensitive lookup is the caller's responsibility.
21
+ * Header bag -- case-insensitive lookup is the caller's responsibility.
22
22
  *
23
23
  * The helpers in this module read lowercase keys (`retry-after`, `ratelimit`)
24
24
  * because most HTTP clients normalize headers to lowercase. If your client
@@ -34,9 +34,7 @@ export type Headers = Record<string, string | undefined> | undefined;
34
34
  *
35
35
  * Returns `undefined` when the header is missing or unparseable.
36
36
  */
37
- export const parseRetryAfter = (
38
- headers: Headers,
39
- ): Duration.Duration | undefined => {
37
+ export const parseRetryAfter = (headers: Headers): Duration.Duration | undefined => {
40
38
  const raw = headers?.["retry-after"];
41
39
  if (!raw) return undefined;
42
40
  const trimmed = raw.trim();
@@ -74,12 +72,10 @@ export const parseRetryAfter = (
74
72
  * `RateLimit: r=0, t=30` (compact form)
75
73
  *
76
74
  * Returns the `t` (seconds until reset) value as a Duration, but only when
77
- * `r` (remaining quota) is present and equals `0` — i.e., we're actually
75
+ * `r` (remaining quota) is present and equals `0` -- i.e., we're actually
78
76
  * rate-limited right now. Returns `undefined` otherwise.
79
77
  */
80
- export const parseRatelimit = (
81
- headers: Headers,
82
- ): Duration.Duration | undefined => {
78
+ export const parseRatelimit = (headers: Headers): Duration.Duration | undefined => {
83
79
  const raw = headers?.["ratelimit"];
84
80
  if (!raw) return undefined;
85
81
 
@@ -99,7 +95,7 @@ export const parseRatelimit = (
99
95
  else if (key === "t" || key === "reset") reset = num;
100
96
  }
101
97
 
102
- if (remaining !== undefined && remaining > 0) return undefined;
98
+ if (remaining !== 0) return undefined;
103
99
  if (reset === undefined || reset < 0) return undefined;
104
100
  return Duration.seconds(reset);
105
101
  };
@@ -108,9 +104,7 @@ export const parseRatelimit = (
108
104
  * Convenience: try `Retry-After` first, then `RateLimit`. Returns the first
109
105
  * successful parse, or `undefined` if neither header yields a usable value.
110
106
  */
111
- export const parseServerRetryHint = (
112
- headers: Headers,
113
- ): Duration.Duration | undefined =>
107
+ export const parseServerRetryHint = (headers: Headers): Duration.Duration | undefined =>
114
108
  parseRetryAfter(headers) ?? parseRatelimit(headers);
115
109
 
116
110
  /**
@@ -118,7 +112,7 @@ export const parseServerRetryHint = (
118
112
  * unless `status` is one whose error class actually declares a `retryAfter`
119
113
  * field (see `RETRYABLE_HTTP_STATUSES`). Use this in `matchError` when you
120
114
  * dispatch off a generic `HTTP_STATUS_MAP` lookup that includes both
121
- * retryable (429/5xx/423) and non-retryable (4xx) classes — it prevents
115
+ * retryable (429/5xx/423) and non-retryable (4xx) classes -- it prevents
122
116
  * stale `retryAfter` properties from being attached to errors like
123
117
  * `BadRequest` or `NotFound` (which would otherwise leak into JSON output).
124
118
  */