@distilled.cloud/core 1.0.0-rc.12 → 1.0.0-rc.14

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 (276) hide show
  1. package/lib/api.d.ts +4 -4
  2. package/lib/api.d.ts.map +1 -1
  3. package/lib/api.js +3 -5
  4. package/lib/api.js.map +1 -1
  5. package/lib/category.d.ts.map +1 -1
  6. package/lib/category.js +3 -5
  7. package/lib/category.js.map +1 -1
  8. package/lib/codegen/boolean-string-enums.d.ts +8 -8
  9. package/lib/codegen/boolean-string-enums.d.ts.map +1 -1
  10. package/lib/codegen/boolean-string-enums.js +83 -30
  11. package/lib/codegen/boolean-string-enums.js.map +1 -1
  12. package/lib/codegen/boolean-string-enums.test.js +130 -2
  13. package/lib/codegen/boolean-string-enums.test.js.map +1 -1
  14. package/lib/codegen/cli.d.ts +5 -4
  15. package/lib/codegen/cli.d.ts.map +1 -1
  16. package/lib/codegen/cli.js +12 -9
  17. package/lib/codegen/cli.js.map +1 -1
  18. package/lib/codegen/defer-naming.test.d.ts +2 -0
  19. package/lib/codegen/defer-naming.test.d.ts.map +1 -0
  20. package/lib/codegen/defer-naming.test.js +105 -0
  21. package/lib/codegen/defer-naming.test.js.map +1 -0
  22. package/lib/codegen/emit.d.ts.map +1 -1
  23. package/lib/codegen/emit.js +1 -3
  24. package/lib/codegen/emit.js.map +1 -1
  25. package/lib/codegen/format.d.ts +0 -12
  26. package/lib/codegen/format.d.ts.map +1 -1
  27. package/lib/codegen/format.js +10 -6
  28. package/lib/codegen/format.js.map +1 -1
  29. package/lib/codegen/generated-at.d.ts +29 -0
  30. package/lib/codegen/generated-at.d.ts.map +1 -0
  31. package/lib/codegen/generated-at.js +78 -0
  32. package/lib/codegen/generated-at.js.map +1 -0
  33. package/lib/codegen/generated-at.test.d.ts +2 -0
  34. package/lib/codegen/generated-at.test.d.ts.map +1 -0
  35. package/lib/codegen/generated-at.test.js +81 -0
  36. package/lib/codegen/generated-at.test.js.map +1 -0
  37. package/lib/codegen/generator.d.ts +24 -5
  38. package/lib/codegen/generator.d.ts.map +1 -1
  39. package/lib/codegen/generator.js +69 -80
  40. package/lib/codegen/generator.js.map +1 -1
  41. package/lib/codegen/generator.test.d.ts +2 -0
  42. package/lib/codegen/generator.test.d.ts.map +1 -0
  43. package/lib/codegen/generator.test.js +121 -0
  44. package/lib/codegen/generator.test.js.map +1 -0
  45. package/lib/codegen/graphql-client.d.ts +7 -1
  46. package/lib/codegen/graphql-client.d.ts.map +1 -1
  47. package/lib/codegen/graphql-client.js +264 -148
  48. package/lib/codegen/graphql-client.js.map +1 -1
  49. package/lib/codegen/graphql-client.test.js +98 -238
  50. package/lib/codegen/graphql-client.test.js.map +1 -1
  51. package/lib/codegen/graphql.d.ts.map +1 -1
  52. package/lib/codegen/graphql.js +7 -20
  53. package/lib/codegen/graphql.js.map +1 -1
  54. package/lib/codegen/model-diff.d.ts +10 -0
  55. package/lib/codegen/model-diff.d.ts.map +1 -0
  56. package/lib/codegen/model-diff.js +67 -0
  57. package/lib/codegen/model-diff.js.map +1 -0
  58. package/lib/codegen/naming.d.ts.map +1 -1
  59. package/lib/codegen/naming.js.map +1 -1
  60. package/lib/codegen/openapi-binary.test.d.ts +2 -0
  61. package/lib/codegen/openapi-binary.test.d.ts.map +1 -0
  62. package/lib/codegen/openapi-binary.test.js +67 -0
  63. package/lib/codegen/openapi-binary.test.js.map +1 -0
  64. package/lib/codegen/openapi-cli.d.ts +11 -11
  65. package/lib/codegen/openapi-cli.d.ts.map +1 -1
  66. package/lib/codegen/openapi-cli.js +26 -51
  67. package/lib/codegen/openapi-cli.js.map +1 -1
  68. package/lib/codegen/openapi.d.ts +16 -2
  69. package/lib/codegen/openapi.d.ts.map +1 -1
  70. package/lib/codegen/openapi.js +56 -39
  71. package/lib/codegen/openapi.js.map +1 -1
  72. package/lib/codegen/operations.d.ts.map +1 -1
  73. package/lib/codegen/operations.js.map +1 -1
  74. package/lib/codegen/pagination.d.ts.map +1 -1
  75. package/lib/codegen/pagination.js +2 -4
  76. package/lib/codegen/pagination.js.map +1 -1
  77. package/lib/codegen/patch-audit.d.ts +84 -0
  78. package/lib/codegen/patch-audit.d.ts.map +1 -0
  79. package/lib/codegen/patch-audit.js +366 -0
  80. package/lib/codegen/patch-audit.js.map +1 -0
  81. package/lib/codegen/patch-audit.test.d.ts +2 -0
  82. package/lib/codegen/patch-audit.test.d.ts.map +1 -0
  83. package/lib/codegen/patch-audit.test.js +141 -0
  84. package/lib/codegen/patch-audit.test.js.map +1 -0
  85. package/lib/codegen/patches.d.ts +75 -11
  86. package/lib/codegen/patches.d.ts.map +1 -1
  87. package/lib/codegen/patches.js +301 -65
  88. package/lib/codegen/patches.js.map +1 -1
  89. package/lib/codegen/patches.test.js +55 -5
  90. package/lib/codegen/patches.test.js.map +1 -1
  91. package/lib/codegen/prelude.js +1 -1
  92. package/lib/codegen/prelude.js.map +1 -1
  93. package/lib/codegen/proto.d.ts.map +1 -1
  94. package/lib/codegen/proto.js +2 -4
  95. package/lib/codegen/proto.js.map +1 -1
  96. package/lib/codegen/protocol-imports.test.d.ts +2 -0
  97. package/lib/codegen/protocol-imports.test.d.ts.map +1 -0
  98. package/lib/codegen/protocol-imports.test.js +36 -0
  99. package/lib/codegen/protocol-imports.test.js.map +1 -0
  100. package/lib/codegen/rewrite-operation-ids.d.ts +23 -0
  101. package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -1
  102. package/lib/codegen/rewrite-operation-ids.js +97 -59
  103. package/lib/codegen/rewrite-operation-ids.js.map +1 -1
  104. package/lib/codegen/rewrite-operation-ids.test.js +19 -101
  105. package/lib/codegen/rewrite-operation-ids.test.js.map +1 -1
  106. package/lib/codegen/spec-path.d.ts +1 -1
  107. package/lib/codegen/spec-path.d.ts.map +1 -1
  108. package/lib/codegen/spec-path.js +1 -1
  109. package/lib/codegen/spec-path.js.map +1 -1
  110. package/lib/codegen/untagged-unions.test.d.ts +2 -0
  111. package/lib/codegen/untagged-unions.test.d.ts.map +1 -0
  112. package/lib/codegen/untagged-unions.test.js +80 -0
  113. package/lib/codegen/untagged-unions.test.js.map +1 -0
  114. package/lib/error-category.d.ts.map +1 -1
  115. package/lib/error-category.js.map +1 -1
  116. package/lib/errors.d.ts +2 -1
  117. package/lib/errors.d.ts.map +1 -1
  118. package/lib/errors.js +9 -4
  119. package/lib/errors.js.map +1 -1
  120. package/lib/fixtures/xml/upstream-validator.json +397 -0
  121. package/lib/graphql.d.ts +292 -205
  122. package/lib/graphql.d.ts.map +1 -1
  123. package/lib/graphql.js +945 -636
  124. package/lib/graphql.js.map +1 -1
  125. package/lib/graphql.test.js +135 -764
  126. package/lib/graphql.test.js.map +1 -1
  127. package/lib/graphql.types.d.ts +10 -0
  128. package/lib/graphql.types.d.ts.map +1 -1
  129. package/lib/graphql.types.js +4 -44
  130. package/lib/graphql.types.js.map +1 -1
  131. package/lib/index.d.ts +27 -0
  132. package/lib/index.d.ts.map +1 -0
  133. package/lib/index.js +27 -0
  134. package/lib/index.js.map +1 -0
  135. package/lib/json-patch.d.ts +13 -6
  136. package/lib/json-patch.d.ts.map +1 -1
  137. package/lib/json-patch.js +34 -19
  138. package/lib/json-patch.js.map +1 -1
  139. package/lib/json-patch.test.d.ts +2 -0
  140. package/lib/json-patch.test.d.ts.map +1 -0
  141. package/lib/json-patch.test.js +65 -0
  142. package/lib/json-patch.test.js.map +1 -0
  143. package/lib/pagination.d.ts +2 -1
  144. package/lib/pagination.d.ts.map +1 -1
  145. package/lib/pagination.js +28 -30
  146. package/lib/pagination.js.map +1 -1
  147. package/lib/pagination.test.d.ts +2 -0
  148. package/lib/pagination.test.d.ts.map +1 -0
  149. package/lib/pagination.test.js +131 -0
  150. package/lib/pagination.test.js.map +1 -0
  151. package/lib/protocol-http.d.ts +30 -16
  152. package/lib/protocol-http.d.ts.map +1 -1
  153. package/lib/protocol-http.js +133 -84
  154. package/lib/protocol-http.js.map +1 -1
  155. package/lib/protocol-http.test.js +141 -1
  156. package/lib/protocol-http.test.js.map +1 -1
  157. package/lib/protocol-rest.d.ts +18 -1
  158. package/lib/protocol-rest.d.ts.map +1 -1
  159. package/lib/protocol-rest.js +32 -21
  160. package/lib/protocol-rest.js.map +1 -1
  161. package/lib/protocol-rest.test.d.ts +2 -0
  162. package/lib/protocol-rest.test.d.ts.map +1 -0
  163. package/lib/protocol-rest.test.js +498 -0
  164. package/lib/protocol-rest.test.js.map +1 -0
  165. package/lib/query.d.ts +29 -0
  166. package/lib/query.d.ts.map +1 -0
  167. package/lib/query.js +27 -0
  168. package/lib/query.js.map +1 -0
  169. package/lib/response-validation.d.ts +67 -0
  170. package/lib/response-validation.d.ts.map +1 -0
  171. package/lib/response-validation.js +76 -0
  172. package/lib/response-validation.js.map +1 -0
  173. package/lib/response-validation.test.d.ts +2 -0
  174. package/lib/response-validation.test.d.ts.map +1 -0
  175. package/lib/response-validation.test.js +72 -0
  176. package/lib/response-validation.test.js.map +1 -0
  177. package/lib/retry-after.d.ts.map +1 -1
  178. package/lib/retry-after.js +1 -1
  179. package/lib/retry-after.js.map +1 -1
  180. package/lib/retry-after.test.d.ts +2 -0
  181. package/lib/retry-after.test.d.ts.map +1 -0
  182. package/lib/retry-after.test.js +204 -0
  183. package/lib/retry-after.test.js.map +1 -0
  184. package/lib/retry.d.ts.map +1 -1
  185. package/lib/retry.js +1 -2
  186. package/lib/retry.js.map +1 -1
  187. package/lib/retry.test.d.ts +2 -0
  188. package/lib/retry.test.d.ts.map +1 -0
  189. package/lib/retry.test.js +407 -0
  190. package/lib/retry.test.js.map +1 -0
  191. package/lib/sdks.test.d.ts +2 -0
  192. package/lib/sdks.test.d.ts.map +1 -0
  193. package/lib/sdks.test.js +76 -0
  194. package/lib/sdks.test.js.map +1 -0
  195. package/lib/testing.d.ts +39 -0
  196. package/lib/testing.d.ts.map +1 -0
  197. package/lib/testing.js +41 -0
  198. package/lib/testing.js.map +1 -0
  199. package/lib/trait.d.ts +29 -9
  200. package/lib/trait.d.ts.map +1 -1
  201. package/lib/trait.js +8 -0
  202. package/lib/trait.js.map +1 -1
  203. package/lib/xml.d.ts +44 -0
  204. package/lib/xml.d.ts.map +1 -0
  205. package/lib/xml.js +311 -0
  206. package/lib/xml.js.map +1 -0
  207. package/lib/xml.test.d.ts +2 -0
  208. package/lib/xml.test.d.ts.map +1 -0
  209. package/lib/xml.test.js +210 -0
  210. package/lib/xml.test.js.map +1 -0
  211. package/package.json +8 -11
  212. package/src/api.ts +38 -55
  213. package/src/category.ts +21 -50
  214. package/src/codegen/boolean-string-enums.test.ts +148 -17
  215. package/src/codegen/boolean-string-enums.ts +81 -32
  216. package/src/codegen/cli.ts +29 -47
  217. package/src/codegen/defer-naming.test.ts +113 -0
  218. package/src/codegen/emit.ts +2 -5
  219. package/src/codegen/format.ts +12 -10
  220. package/src/codegen/generated-at.test.ts +89 -0
  221. package/src/codegen/generated-at.ts +88 -0
  222. package/src/codegen/generator.test.ts +137 -0
  223. package/src/codegen/generator.ts +132 -193
  224. package/src/codegen/graphql-client.test.ts +100 -297
  225. package/src/codegen/graphql-client.ts +302 -210
  226. package/src/codegen/graphql.ts +22 -94
  227. package/src/codegen/model-diff.ts +67 -0
  228. package/src/codegen/naming.ts +1 -2
  229. package/src/codegen/openapi-binary.test.ts +91 -0
  230. package/src/codegen/openapi-cli.ts +38 -79
  231. package/src/codegen/openapi.ts +98 -133
  232. package/src/codegen/operations.ts +2 -5
  233. package/src/codegen/pagination.ts +4 -11
  234. package/src/codegen/patch-audit.test.ts +160 -0
  235. package/src/codegen/patch-audit.ts +480 -0
  236. package/src/codegen/patches.test.ts +73 -15
  237. package/src/codegen/patches.ts +389 -99
  238. package/src/codegen/prelude.ts +1 -1
  239. package/src/codegen/proto.ts +18 -54
  240. package/src/codegen/protocol-imports.test.ts +39 -0
  241. package/src/codegen/rewrite-operation-ids.test.ts +23 -114
  242. package/src/codegen/rewrite-operation-ids.ts +111 -98
  243. package/src/codegen/spec-path.ts +3 -6
  244. package/src/codegen/untagged-unions.test.ts +85 -0
  245. package/src/error-category.ts +5 -17
  246. package/src/errors.ts +18 -30
  247. package/src/fixtures/xml/upstream-validator.json +397 -0
  248. package/src/graphql.test.ts +173 -949
  249. package/src/graphql.ts +1468 -1186
  250. package/src/graphql.types.ts +78 -164
  251. package/src/index.ts +26 -0
  252. package/src/json-patch.test.ts +77 -0
  253. package/src/json-patch.ts +54 -60
  254. package/src/pagination.test.ts +169 -0
  255. package/src/pagination.ts +46 -103
  256. package/src/protocol-http.test.ts +178 -9
  257. package/src/protocol-http.ts +174 -163
  258. package/src/protocol-rest.test.ts +703 -0
  259. package/src/protocol-rest.ts +76 -65
  260. package/src/query.ts +39 -0
  261. package/src/response-validation.test.ts +89 -0
  262. package/src/response-validation.ts +107 -0
  263. package/src/retry-after.test.ts +267 -0
  264. package/src/retry-after.ts +4 -10
  265. package/src/retry.test.ts +566 -0
  266. package/src/retry.ts +6 -21
  267. package/src/sdks.test.ts +87 -0
  268. package/src/testing.ts +72 -0
  269. package/src/trait.ts +48 -63
  270. package/src/xml.test.ts +251 -0
  271. package/src/xml.ts +323 -0
  272. package/lib/graphql.fixture.d.ts +0 -249
  273. package/lib/graphql.fixture.d.ts.map +0 -1
  274. package/lib/graphql.fixture.js +0 -240
  275. package/lib/graphql.fixture.js.map +0 -1
  276. package/src/graphql.fixture.ts +0 -371
@@ -12,7 +12,9 @@
12
12
  * values first)
13
13
  *
14
14
  * response: 2xx JSON → optional `transformResponse` → recursive wire→TS
15
- * key mapping (`mapKeys`) → `Redacted` wrapping of members
15
+ * key mapping (`mapKeys`) → in strict mode, a schema check
16
+ * failing with the provider's `parseError` (see
17
+ * `core/response-validation`) → `Redacted` wrapping of members
16
18
  * marked with {@link SensitiveValue}; non-2xx → typed error:
17
19
  * per-op matcher classes (`matchTypedError`), then the status
18
20
  * map (default `HTTP_STATUS_MAP`), then an `InternalServerError`
@@ -24,13 +26,13 @@
24
26
  * in the provider package — via these options or a hand-written protocol.
25
27
  */
26
28
  import * as Effect from "effect/Effect";
29
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
30
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
27
31
  import * as Layer from "effect/Layer";
28
32
  import * as Redacted from "effect/Redacted";
29
33
  import type * as AST from "effect/SchemaAST";
30
- import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
31
- import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
32
34
  import * as API from "./api.ts";
33
- import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
35
+ import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
34
36
  import {
35
37
  buildRequest,
36
38
  getAnn,
@@ -41,16 +43,15 @@ import {
41
43
  matchTypedError,
42
44
  resolveNode,
43
45
  } from "./protocol-http.ts";
44
- import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
46
+ import { validateResponse } from "./response-validation.ts";
45
47
  import { parseRetryAfterForStatus } from "./retry-after.ts";
48
+ import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
46
49
 
47
50
  // =============================================================================
48
51
  // Traits
49
52
  // =============================================================================
50
53
 
51
- export const sensitiveValueSymbol = Symbol.for(
52
- "@distilled.cloud/core/sensitive-value",
53
- );
54
+ export const sensitiveValueSymbol = Symbol.for("@distilled.cloud/core/sensitive-value");
54
55
  /**
55
56
  * Marks a string member as sensitive (mirrors `smithy.api#sensitive`).
56
57
  * The REST protocol wraps decoded values in `Redacted` on the way out and
@@ -58,30 +59,28 @@ export const sensitiveValueSymbol = Symbol.for(
58
59
  * serialization). Takes an ignored argument so generators can inline the
59
60
  * smithy trait value (`T.SensitiveValue({})`).
60
61
  */
61
- export const SensitiveValue = (_value?: unknown) =>
62
- makeAnnotation(sensitiveValueSymbol, true);
62
+ export const SensitiveValue = (_value?: unknown) => makeAnnotation(sensitiveValueSymbol, true);
63
63
 
64
- export const rawResponseSymbol = Symbol.for(
65
- "@distilled.cloud/core/raw-response",
66
- );
64
+ export const rawResponseSymbol = Symbol.for("@distilled.cloud/core/raw-response");
67
65
  /**
68
66
  * Marks the sole output member that carries a bare (array/scalar) response
69
67
  * body (mirrors `com.distilled.openapi#rawResponse`).
70
68
  */
71
- export const RawResponse = (_value?: unknown) =>
72
- makeAnnotation(rawResponseSymbol, true);
69
+ export const RawResponse = (_value?: unknown) => makeAnnotation(rawResponseSymbol, true);
73
70
 
74
- export const rawResponseRootSymbol = Symbol.for(
75
- "@distilled.cloud/core/raw-response-root",
76
- );
71
+ export const rawResponseRootSymbol = Symbol.for("@distilled.cloud/core/raw-response-root");
77
72
  /**
78
73
  * Marks a response schema whose ENTIRE value is the response body (the
79
74
  * generator's `rootPipe` for synthesized bare-payload wrappers): the emitted
80
75
  * response type IS the payload type and the protocol returns the mapped body
81
76
  * directly.
82
77
  */
83
- export const RawResponseRoot = () =>
84
- makeAnnotation(rawResponseRootSymbol, true);
78
+ export const RawResponseRoot = () => makeAnnotation(rawResponseRootSymbol, true);
79
+
80
+ export const binaryResponseSymbol = Symbol.for("@distilled.cloud/core/binary-response");
81
+
82
+ /** Decode a successful raw binary response as bytes, without text conversion. */
83
+ export const BinaryResponse = () => makeAnnotation(binaryResponseSymbol, true);
85
84
 
86
85
  // =============================================================================
87
86
  // Value helpers
@@ -92,8 +91,7 @@ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
92
91
  typeof v === "object" &&
93
92
  !Array.isArray(v) &&
94
93
  !isOpaqueValue(v) &&
95
- (Object.getPrototypeOf(v) === Object.prototype ||
96
- Object.getPrototypeOf(v) === null);
94
+ (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
97
95
 
98
96
  /**
99
97
  * Deep-unwrap `Redacted` values in an input (plain objects/arrays only —
@@ -125,6 +123,10 @@ export const wrapSensitive = (ast: AST.AST, value: unknown): unknown => {
125
123
  return value;
126
124
  }
127
125
  const node = resolveNode(ast);
126
+ if (node._tag === "Union") {
127
+ // Redact every possible sensitive member, including in partial responses.
128
+ return node.types.reduce<unknown>((redacted, arm) => wrapSensitive(arm, redacted), value);
129
+ }
128
130
  if (node._tag === "Arrays") {
129
131
  if (!Array.isArray(value)) return value;
130
132
  const elem = (node as any).rest?.[0] as AST.AST | undefined;
@@ -140,10 +142,7 @@ export const wrapSensitive = (ast: AST.AST, value: unknown): unknown => {
140
142
  const prop = byName.get(k);
141
143
  if (!prop) {
142
144
  out[k] = v;
143
- } else if (
144
- getPropAnn(prop, sensitiveValueSymbol) !== undefined &&
145
- typeof v === "string"
146
- ) {
145
+ } else if (getPropAnn(prop, sensitiveValueSymbol) !== undefined && typeof v === "string") {
147
146
  out[k] = Redacted.make(v);
148
147
  } else {
149
148
  out[k] = wrapSensitive(prop.type, v);
@@ -169,6 +168,12 @@ export interface RestErrorInfo {
169
168
  readonly headers: Record<string, string | undefined>;
170
169
  }
171
170
 
171
+ /** A 2xx body that failed strict validation, for the `parseError` option. */
172
+ export interface RestParseErrorInfo {
173
+ readonly body: unknown;
174
+ readonly cause: unknown;
175
+ }
176
+
172
177
  export interface RestErrorEnvelope {
173
178
  readonly code?: string | number;
174
179
  readonly message?: string;
@@ -215,6 +220,13 @@ export interface RestProtocolOptions<C> {
215
220
  readonly statusMap?: Readonly<Record<number, new (args: any) => any>>;
216
221
  /** Fallback error for failures nothing else matched. */
217
222
  readonly unknownError: (info: RestErrorInfo) => unknown;
223
+ /**
224
+ * The SDK's `<Sdk>ParseError`, raised when a 2xx body does not match the
225
+ * operation's output schema in strict mode (see
226
+ * `core/response-validation`). `body` is the parsed JSON, or the raw text
227
+ * when the body wasn't JSON; `cause` is the schema error.
228
+ */
229
+ readonly parseError: (info: RestParseErrorInfo) => unknown;
218
230
  /** Transform the parsed 2xx JSON before decoding (e.g. stripNulls). */
219
231
  readonly transformResponse?: (body: unknown) => unknown;
220
232
  /** Passed through to `buildRequest` (member-header transforms). */
@@ -226,16 +238,9 @@ export interface RestProtocolOptions<C> {
226
238
  const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
227
239
  if (body === null || typeof body !== "object") return undefined;
228
240
  const b = body as Record<string, unknown>;
229
- const code =
230
- typeof b.code === "string" || typeof b.code === "number"
231
- ? b.code
232
- : undefined;
241
+ const code = typeof b.code === "string" || typeof b.code === "number" ? b.code : undefined;
233
242
  const message =
234
- typeof b.message === "string"
235
- ? b.message
236
- : typeof b.error === "string"
237
- ? b.error
238
- : undefined;
243
+ typeof b.message === "string" ? b.message : typeof b.error === "string" ? b.error : undefined;
239
244
  return { code, message };
240
245
  };
241
246
 
@@ -243,29 +248,19 @@ const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
243
248
  // but REST failures are real typed errors that operations re-surface via
244
249
  // their `errors: [...]` lists. Fail with the instance and erase the type
245
250
  // here; the generated operation annotations reintroduce it for callers.
246
- const fail = (e: unknown): Effect.Effect<never> =>
247
- Effect.fail(e) as Effect.Effect<never>;
251
+ const fail = (e: unknown): Effect.Effect<never> => Effect.fail(e) as Effect.Effect<never>;
248
252
 
249
253
  /**
250
254
  * Build a `Layer<Protocol>` for a simple REST JSON API. Assign the result to
251
255
  * a module-level const in the provider's `protocol.ts` — `API.make` memoizes
252
256
  * protocol layers by value identity.
253
257
  */
254
- export const makeRestProtocol = <C>(
255
- options: RestProtocolOptions<C>,
256
- ): Layer.Layer<API.Protocol> => {
258
+ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Layer<API.Protocol> => {
257
259
  const errorEnvelope = options.errorEnvelope ?? defaultErrorEnvelope;
258
- const statusMap: Readonly<
259
- Record<number, (new (args: any) => any) | undefined>
260
- > = options.statusMap ?? HTTP_STATUS_MAP;
260
+ const statusMap: Readonly<Record<number, (new (args: any) => any) | undefined>> =
261
+ options.statusMap ?? HTTP_STATUS_MAP;
261
262
 
262
- const encode = ({
263
- input,
264
- inputAst,
265
- }: {
266
- readonly input: unknown;
267
- readonly inputAst: AST.AST;
268
- }) =>
263
+ const encode = ({ input, inputAst }: { readonly input: unknown; readonly inputAst: AST.AST }) =>
269
264
  Effect.gen(function* () {
270
265
  const creds = yield* options.credentials as Effect.Effect<C>;
271
266
  const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
@@ -301,12 +296,18 @@ export const makeRestProtocol = <C>(
301
296
  readonly errors: ReadonlyArray<unknown>;
302
297
  }) =>
303
298
  Effect.gen(function* () {
299
+ if (
300
+ response.status >= 200 &&
301
+ response.status < 300 &&
302
+ getAnn(outputAst, binaryResponseSymbol) !== undefined
303
+ ) {
304
+ const bytes = yield* response.arrayBuffer.pipe(Effect.orDie);
305
+ return new Uint8Array(bytes);
306
+ }
304
307
  // Read as text and parse tolerantly — error pages are often non-JSON.
305
308
  const text = (yield* response.text.pipe(Effect.orDie)) ?? "";
306
309
  if (process.env.DISTILLED_DEBUG_HTTP) {
307
- console.error(
308
- `[distilled] <- ${response.status} ${text.slice(0, 400)}`,
309
- );
310
+ console.error(`[distilled] <- ${response.status}`);
310
311
  }
311
312
  let json: unknown;
312
313
  let nonJson = false;
@@ -322,17 +323,20 @@ export const makeRestProtocol = <C>(
322
323
 
323
324
  if (status >= 400) {
324
325
  const env = (nonJson ? undefined : errorEnvelope(json)) ?? {};
325
- const message =
326
- env.message ??
327
- (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
326
+ const message = env.message ?? (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
328
327
 
329
328
  // 1. Per-operation typed error (matcher metadata on the class).
330
- const typed = matchTypedError(errorClasses, status, [
331
- {
332
- code: typeof env.code === "number" ? env.code : undefined,
333
- message,
334
- },
335
- ]);
329
+ const typed = matchTypedError(
330
+ errorClasses,
331
+ status,
332
+ [
333
+ {
334
+ code: typeof env.code === "number" ? env.code : undefined,
335
+ message,
336
+ },
337
+ ],
338
+ { body: nonJson ? text : json, headers },
339
+ );
336
340
  if (typed !== undefined) return yield* fail(typed);
337
341
 
338
342
  // 2. Status-mapped class (retryAfter only stamps on retryable
@@ -373,9 +377,17 @@ export const makeRestProtocol = <C>(
373
377
  // 2xx: the response body IS the payload (no envelope). Wire→TS key
374
378
  // mapping is schema-driven; `RawResponseRoot` responses are the body
375
379
  // verbatim (mapKeys handles arrays/scalars structurally either way).
380
+ // Strict mode (core/response-validation) checks the mapped body against
381
+ // the output schema — a non-JSON body reaches it as a string and fails
382
+ // there unless the operation's output is itself a string.
376
383
  let body: unknown = nonJson ? text : (json ?? {});
377
384
  if (options.transformResponse) body = options.transformResponse(body);
378
- return wrapSensitive(outputAst, mapKeys(outputAst, body, "decode"));
385
+ const mapped = yield* validateResponse(
386
+ outputAst,
387
+ mapKeys(outputAst, body, "decode"),
388
+ (cause) => options.parseError({ body: nonJson ? text : json, cause }),
389
+ ).pipe(Effect.catch(fail));
390
+ return wrapSensitive(outputAst, mapped);
379
391
  });
380
392
 
381
393
  return Layer.succeed(
@@ -383,8 +395,7 @@ export const makeRestProtocol = <C>(
383
395
  API.Protocol.of({
384
396
  // Erase encode's credentials requirement (resolved on the calling
385
397
  // fiber; see RestProtocolOptions.credentials).
386
- encode: (args) =>
387
- encode(args) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
398
+ encode: (args) => encode(args) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
388
399
  decode,
389
400
  }),
390
401
  );
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,89 @@
1
+ import * as Effect from "effect/Effect";
2
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
3
+ import * as HttpClientResponse from "effect/http/HttpClientResponse";
4
+ import * as Layer from "effect/Layer";
5
+ import * as Schema from "effect/Schema";
6
+ import { describe, expect, test } from "vitest";
7
+ import * as API from "./api.ts";
8
+ import { makeRestProtocol } from "./protocol-rest.ts";
9
+ import * as ResponseValidation from "./response-validation.ts";
10
+
11
+ class TestParseError extends Schema.TaggedError<TestParseError>()("TestParseError", {
12
+ body: Schema.Unknown,
13
+ cause: Schema.Unknown,
14
+ }) {}
15
+
16
+ class TestUnknownError extends Schema.TaggedError<TestUnknownError>()("TestUnknownError", {
17
+ message: Schema.String,
18
+ }) {}
19
+
20
+ const TestProtocol = makeRestProtocol<{}>({
21
+ credentials: Effect.succeed({}),
22
+ baseUrl: () => "https://api.test",
23
+ headers: () => ({}),
24
+ unknownError: ({ message }) => new TestUnknownError({ message }),
25
+ parseError: ({ body, cause }) => new TestParseError({ body, cause }),
26
+ });
27
+
28
+ const Output = Schema.Struct({ id: Schema.String });
29
+
30
+ const decode = (body: string) =>
31
+ Effect.gen(function* () {
32
+ const protocol = yield* API.Protocol;
33
+ const request = HttpClientRequest.get("https://api.test/thing");
34
+ return yield* protocol.decode({
35
+ response: HttpClientResponse.fromWeb(request, new Response(body, { status: 200 })),
36
+ outputAst: Output.ast,
37
+ errors: [],
38
+ config: {},
39
+ });
40
+ }).pipe(Effect.provide(TestProtocol));
41
+
42
+ const run = <A, E>(effect: Effect.Effect<A, E>, layer?: Layer.Layer<never>) =>
43
+ Effect.runPromise(Effect.result(layer ? effect.pipe(Effect.provide(layer)) : effect));
44
+
45
+ describe("makeRestProtocol response validation", () => {
46
+ test("lenient (default) returns a non-JSON 2xx body as text", async () => {
47
+ const result = await run(decode("not json"));
48
+ expect(result).toMatchObject({ _tag: "Success", success: "not json" });
49
+ });
50
+
51
+ test("lenient (default) returns {} for an output that requires id", async () => {
52
+ const result = await run(decode("{}"));
53
+ expect(result).toMatchObject({ _tag: "Success", success: {} });
54
+ });
55
+
56
+ test("strict fails a non-JSON 2xx body with the provider's parse error", async () => {
57
+ const result = await run(decode("not json"), ResponseValidation.strict);
58
+ expect(result._tag).toBe("Failure");
59
+ const error = (result as any).failure;
60
+ expect(error).toBeInstanceOf(TestParseError);
61
+ expect(error.body).toBe("not json");
62
+ });
63
+
64
+ test("strict fails a body missing a required member", async () => {
65
+ const result = await run(decode("{}"), ResponseValidation.strict);
66
+ expect(result._tag).toBe("Failure");
67
+ expect((result as any).failure).toBeInstanceOf(TestParseError);
68
+ expect((result as any).failure.body).toEqual({});
69
+ });
70
+
71
+ test("strict passes a matching body through unchanged, extra members included", async () => {
72
+ const result = await run(
73
+ decode(JSON.stringify({ id: "a", extra: 1 })),
74
+ ResponseValidation.strict,
75
+ );
76
+ expect(result).toMatchObject({
77
+ _tag: "Success",
78
+ success: { id: "a", extra: 1 },
79
+ });
80
+ });
81
+
82
+ test("an inner lenient layer overrides an outer strict one", async () => {
83
+ const result = await run(
84
+ decode("{}").pipe(Effect.provide(ResponseValidation.lenient)),
85
+ ResponseValidation.strict,
86
+ );
87
+ expect(result).toMatchObject({ _tag: "Success", success: {} });
88
+ });
89
+ });
@@ -0,0 +1,107 @@
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.
11
+ * strict: the response is decoded against the output schema,
12
+ * and a mismatch fails the call with the SDK's
13
+ * `<Sdk>ParseError` (AWS: `ParseError`).
14
+ *
15
+ * The mode is one {@link ResponseValidation} reference keyed by a string, so
16
+ * a single `Layer` switches every distilled SDK in a program — AWS,
17
+ * Cloudflare, Neon, … — at once, and nests like any other Effect service:
18
+ *
19
+ * ```ts
20
+ * import { ResponseValidation } from "@distilled.cloud/core";
21
+ *
22
+ * // whole program
23
+ * program.pipe(Effect.provide(ResponseValidation.strict));
24
+ *
25
+ * // one call back to lenient inside a strict program
26
+ * Neon.getProject({ projectId }).pipe(Effect.provide(ResponseValidation.lenient));
27
+ * ```
28
+ *
29
+ * The mode is set only by these layers; without one, every call is lenient.
30
+ */
31
+ import * as Context from "effect/Context";
32
+ import * as Effect from "effect/Effect";
33
+ import * as Layer from "effect/Layer";
34
+ import * as Schema from "effect/Schema";
35
+ import type * as AST from "effect/SchemaAST";
36
+
37
+ export type Mode = "lenient" | "strict";
38
+
39
+ /**
40
+ * The active validation mode. Read by protocols at call time on the calling
41
+ * fiber; `lenient` unless a {@link strict} layer is provided.
42
+ */
43
+ export const ResponseValidation = Context.Reference<Mode>(
44
+ "@distilled.cloud/core/ResponseValidation",
45
+ { defaultValue: () => "lenient" },
46
+ );
47
+
48
+ /** Decode every 2xx response against its output schema; fail on mismatch. */
49
+ export const strict: Layer.Layer<never> = Layer.succeed(ResponseValidation, "strict");
50
+
51
+ /** Return 2xx responses as read, without checking them against the schema. */
52
+ export const lenient: Layer.Layer<never> = Layer.succeed(ResponseValidation, "lenient");
53
+
54
+ /** Whether the calling fiber is in strict mode. */
55
+ export const isStrict: Effect.Effect<boolean> = Effect.map(
56
+ ResponseValidation,
57
+ (mode) => mode === "strict",
58
+ );
59
+
60
+ /**
61
+ * For a 2xx body the protocol could not read into the shape it transforms
62
+ * (e.g. invalid JSON): fail with `error` in strict mode, succeed with
63
+ * `asRead` (usually the body text) in lenient mode.
64
+ */
65
+ export const failIfStrict = <A, E>(error: E, asRead: A): Effect.Effect<A, E> =>
66
+ Effect.flatMap(ResponseValidation, (mode) =>
67
+ mode === "strict" ? Effect.fail(error) : Effect.succeed(asRead),
68
+ );
69
+
70
+ const decoders = new WeakMap<
71
+ AST.AST,
72
+ (input: unknown) => Effect.Effect<unknown, Schema.SchemaError>
73
+ >();
74
+
75
+ const decoderFor = (ast: AST.AST) => {
76
+ let decode = decoders.get(ast);
77
+ if (!decode) {
78
+ decode = Schema.decodeUnknownEffect(Schema.make<Schema.Top>(ast)) as (
79
+ input: unknown,
80
+ ) => Effect.Effect<unknown, Schema.SchemaError>;
81
+ decoders.set(ast, decode);
82
+ }
83
+ return decode;
84
+ };
85
+
86
+ /**
87
+ * Check a 2xx response value against the operation's output schema.
88
+ *
89
+ * Lenient mode returns `value` untouched. Strict mode decodes it and, on a
90
+ * mismatch, fails with `onError(schemaError)` — protocols pass their SDK's
91
+ * `<Sdk>ParseError` constructor. On success the ORIGINAL value is returned
92
+ * (members the schema does not model are kept), so switching modes never
93
+ * changes what a successful call returns.
94
+ *
95
+ * `value` must already be in the schema's shape (TS member names), i.e.
96
+ * after any wire→TS key mapping and before `Redacted` wrapping.
97
+ */
98
+ export const validateResponse = <E>(
99
+ outputAst: AST.AST,
100
+ value: unknown,
101
+ onError: (cause: Schema.SchemaError) => E,
102
+ ): Effect.Effect<unknown, E> =>
103
+ Effect.flatMap(ResponseValidation, (mode) =>
104
+ mode === "lenient"
105
+ ? Effect.succeed(value)
106
+ : decoderFor(outputAst)(value).pipe(Effect.mapError(onError), Effect.as(value)),
107
+ );