@distilled.cloud/core 1.0.0-rc.13 → 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 (235) 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.map +1 -1
  9. package/lib/codegen/boolean-string-enums.js +2 -6
  10. package/lib/codegen/boolean-string-enums.js.map +1 -1
  11. package/lib/codegen/boolean-string-enums.test.js +3 -5
  12. package/lib/codegen/boolean-string-enums.test.js.map +1 -1
  13. package/lib/codegen/cli.d.ts +5 -4
  14. package/lib/codegen/cli.d.ts.map +1 -1
  15. package/lib/codegen/cli.js +12 -9
  16. package/lib/codegen/cli.js.map +1 -1
  17. package/lib/codegen/defer-naming.test.d.ts +2 -0
  18. package/lib/codegen/defer-naming.test.d.ts.map +1 -0
  19. package/lib/codegen/defer-naming.test.js +105 -0
  20. package/lib/codegen/defer-naming.test.js.map +1 -0
  21. package/lib/codegen/emit.d.ts.map +1 -1
  22. package/lib/codegen/emit.js +1 -3
  23. package/lib/codegen/emit.js.map +1 -1
  24. package/lib/codegen/format.d.ts +0 -12
  25. package/lib/codegen/format.d.ts.map +1 -1
  26. package/lib/codegen/format.js +10 -6
  27. package/lib/codegen/format.js.map +1 -1
  28. package/lib/codegen/generated-at.d.ts +29 -0
  29. package/lib/codegen/generated-at.d.ts.map +1 -0
  30. package/lib/codegen/generated-at.js +78 -0
  31. package/lib/codegen/generated-at.js.map +1 -0
  32. package/lib/codegen/generated-at.test.d.ts +2 -0
  33. package/lib/codegen/generated-at.test.d.ts.map +1 -0
  34. package/lib/codegen/generated-at.test.js +81 -0
  35. package/lib/codegen/generated-at.test.js.map +1 -0
  36. package/lib/codegen/generator.d.ts +4 -2
  37. package/lib/codegen/generator.d.ts.map +1 -1
  38. package/lib/codegen/generator.js +37 -75
  39. package/lib/codegen/generator.js.map +1 -1
  40. package/lib/codegen/generator.test.js +4 -9
  41. package/lib/codegen/generator.test.js.map +1 -1
  42. package/lib/codegen/graphql-client.d.ts.map +1 -1
  43. package/lib/codegen/graphql-client.js +12 -33
  44. package/lib/codegen/graphql-client.js.map +1 -1
  45. package/lib/codegen/graphql-client.test.js +4 -12
  46. package/lib/codegen/graphql-client.test.js.map +1 -1
  47. package/lib/codegen/graphql.d.ts.map +1 -1
  48. package/lib/codegen/graphql.js +7 -20
  49. package/lib/codegen/graphql.js.map +1 -1
  50. package/lib/codegen/model-diff.d.ts +10 -0
  51. package/lib/codegen/model-diff.d.ts.map +1 -0
  52. package/lib/codegen/model-diff.js +67 -0
  53. package/lib/codegen/model-diff.js.map +1 -0
  54. package/lib/codegen/naming.d.ts.map +1 -1
  55. package/lib/codegen/naming.js.map +1 -1
  56. package/lib/codegen/openapi-binary.test.js +1 -1
  57. package/lib/codegen/openapi-binary.test.js.map +1 -1
  58. package/lib/codegen/openapi-cli.d.ts +11 -11
  59. package/lib/codegen/openapi-cli.d.ts.map +1 -1
  60. package/lib/codegen/openapi-cli.js +26 -51
  61. package/lib/codegen/openapi-cli.js.map +1 -1
  62. package/lib/codegen/openapi.d.ts +9 -1
  63. package/lib/codegen/openapi.d.ts.map +1 -1
  64. package/lib/codegen/openapi.js +48 -42
  65. package/lib/codegen/openapi.js.map +1 -1
  66. package/lib/codegen/operations.d.ts.map +1 -1
  67. package/lib/codegen/operations.js.map +1 -1
  68. package/lib/codegen/pagination.d.ts.map +1 -1
  69. package/lib/codegen/pagination.js +2 -4
  70. package/lib/codegen/pagination.js.map +1 -1
  71. package/lib/codegen/patch-audit.d.ts +84 -0
  72. package/lib/codegen/patch-audit.d.ts.map +1 -0
  73. package/lib/codegen/patch-audit.js +366 -0
  74. package/lib/codegen/patch-audit.js.map +1 -0
  75. package/lib/codegen/patch-audit.test.d.ts +2 -0
  76. package/lib/codegen/patch-audit.test.d.ts.map +1 -0
  77. package/lib/codegen/patch-audit.test.js +141 -0
  78. package/lib/codegen/patch-audit.test.js.map +1 -0
  79. package/lib/codegen/patches.d.ts +59 -10
  80. package/lib/codegen/patches.d.ts.map +1 -1
  81. package/lib/codegen/patches.js +233 -63
  82. package/lib/codegen/patches.js.map +1 -1
  83. package/lib/codegen/patches.test.js +8 -4
  84. package/lib/codegen/patches.test.js.map +1 -1
  85. package/lib/codegen/prelude.js +1 -1
  86. package/lib/codegen/prelude.js.map +1 -1
  87. package/lib/codegen/proto.d.ts.map +1 -1
  88. package/lib/codegen/proto.js +2 -4
  89. package/lib/codegen/proto.js.map +1 -1
  90. package/lib/codegen/protocol-imports.test.d.ts +2 -0
  91. package/lib/codegen/protocol-imports.test.d.ts.map +1 -0
  92. package/lib/codegen/protocol-imports.test.js +36 -0
  93. package/lib/codegen/protocol-imports.test.js.map +1 -0
  94. package/lib/codegen/rewrite-operation-ids.d.ts +23 -0
  95. package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -1
  96. package/lib/codegen/rewrite-operation-ids.js +97 -59
  97. package/lib/codegen/rewrite-operation-ids.js.map +1 -1
  98. package/lib/codegen/rewrite-operation-ids.test.js +19 -101
  99. package/lib/codegen/rewrite-operation-ids.test.js.map +1 -1
  100. package/lib/codegen/spec-path.d.ts +1 -1
  101. package/lib/codegen/spec-path.d.ts.map +1 -1
  102. package/lib/codegen/spec-path.js +1 -1
  103. package/lib/codegen/spec-path.js.map +1 -1
  104. package/lib/codegen/untagged-unions.test.js +1 -1
  105. package/lib/codegen/untagged-unions.test.js.map +1 -1
  106. package/lib/error-category.d.ts.map +1 -1
  107. package/lib/error-category.js.map +1 -1
  108. package/lib/errors.d.ts.map +1 -1
  109. package/lib/errors.js +7 -5
  110. package/lib/errors.js.map +1 -1
  111. package/lib/graphql.d.ts +4 -8
  112. package/lib/graphql.d.ts.map +1 -1
  113. package/lib/graphql.js +20 -48
  114. package/lib/graphql.js.map +1 -1
  115. package/lib/graphql.test.js +6 -6
  116. package/lib/graphql.test.js.map +1 -1
  117. package/lib/graphql.types.d.ts.map +1 -1
  118. package/lib/graphql.types.js.map +1 -1
  119. package/lib/json-patch.d.ts +13 -6
  120. package/lib/json-patch.d.ts.map +1 -1
  121. package/lib/json-patch.js +34 -19
  122. package/lib/json-patch.js.map +1 -1
  123. package/lib/json-patch.test.d.ts +2 -0
  124. package/lib/json-patch.test.d.ts.map +1 -0
  125. package/lib/json-patch.test.js +65 -0
  126. package/lib/json-patch.test.js.map +1 -0
  127. package/lib/pagination.d.ts.map +1 -1
  128. package/lib/pagination.js +6 -16
  129. package/lib/pagination.js.map +1 -1
  130. package/lib/pagination.test.js +3 -6
  131. package/lib/pagination.test.js.map +1 -1
  132. package/lib/protocol-http.d.ts +20 -1
  133. package/lib/protocol-http.d.ts.map +1 -1
  134. package/lib/protocol-http.js +41 -47
  135. package/lib/protocol-http.js.map +1 -1
  136. package/lib/protocol-http.test.js +20 -10
  137. package/lib/protocol-http.test.js.map +1 -1
  138. package/lib/protocol-rest.d.ts.map +1 -1
  139. package/lib/protocol-rest.js +9 -18
  140. package/lib/protocol-rest.js.map +1 -1
  141. package/lib/protocol-rest.test.d.ts +2 -0
  142. package/lib/protocol-rest.test.d.ts.map +1 -0
  143. package/lib/protocol-rest.test.js +498 -0
  144. package/lib/protocol-rest.test.js.map +1 -0
  145. package/lib/response-validation.d.ts.map +1 -1
  146. package/lib/response-validation.js.map +1 -1
  147. package/lib/response-validation.test.js +10 -5
  148. package/lib/response-validation.test.js.map +1 -1
  149. package/lib/retry-after.d.ts.map +1 -1
  150. package/lib/retry-after.js +1 -1
  151. package/lib/retry-after.js.map +1 -1
  152. package/lib/retry-after.test.d.ts +2 -0
  153. package/lib/retry-after.test.d.ts.map +1 -0
  154. package/lib/retry-after.test.js +204 -0
  155. package/lib/retry-after.test.js.map +1 -0
  156. package/lib/retry.d.ts.map +1 -1
  157. package/lib/retry.js +1 -2
  158. package/lib/retry.js.map +1 -1
  159. package/lib/retry.test.d.ts +2 -0
  160. package/lib/retry.test.d.ts.map +1 -0
  161. package/lib/retry.test.js +407 -0
  162. package/lib/retry.test.js.map +1 -0
  163. package/lib/sdks.test.d.ts +2 -0
  164. package/lib/sdks.test.d.ts.map +1 -0
  165. package/lib/sdks.test.js +76 -0
  166. package/lib/sdks.test.js.map +1 -0
  167. package/lib/testing.d.ts +2 -2
  168. package/lib/testing.d.ts.map +1 -1
  169. package/lib/testing.js +1 -1
  170. package/lib/testing.js.map +1 -1
  171. package/lib/trait.d.ts.map +1 -1
  172. package/lib/trait.js.map +1 -1
  173. package/lib/xml.d.ts.map +1 -1
  174. package/lib/xml.js +3 -7
  175. package/lib/xml.js.map +1 -1
  176. package/lib/xml.test.js +11 -12
  177. package/lib/xml.test.js.map +1 -1
  178. package/package.json +7 -10
  179. package/src/api.ts +38 -55
  180. package/src/category.ts +21 -50
  181. package/src/codegen/boolean-string-enums.test.ts +12 -28
  182. package/src/codegen/boolean-string-enums.ts +2 -10
  183. package/src/codegen/cli.ts +29 -47
  184. package/src/codegen/defer-naming.test.ts +113 -0
  185. package/src/codegen/emit.ts +2 -5
  186. package/src/codegen/format.ts +12 -10
  187. package/src/codegen/generated-at.test.ts +89 -0
  188. package/src/codegen/generated-at.ts +88 -0
  189. package/src/codegen/generator.test.ts +8 -22
  190. package/src/codegen/generator.ts +72 -191
  191. package/src/codegen/graphql-client.test.ts +12 -42
  192. package/src/codegen/graphql-client.ts +30 -95
  193. package/src/codegen/graphql.ts +22 -94
  194. package/src/codegen/model-diff.ts +67 -0
  195. package/src/codegen/naming.ts +1 -2
  196. package/src/codegen/openapi-binary.test.ts +5 -12
  197. package/src/codegen/openapi-cli.ts +38 -79
  198. package/src/codegen/openapi.ts +79 -136
  199. package/src/codegen/operations.ts +2 -5
  200. package/src/codegen/pagination.ts +4 -11
  201. package/src/codegen/patch-audit.test.ts +160 -0
  202. package/src/codegen/patch-audit.ts +480 -0
  203. package/src/codegen/patches.test.ts +14 -21
  204. package/src/codegen/patches.ts +313 -103
  205. package/src/codegen/prelude.ts +1 -1
  206. package/src/codegen/proto.ts +18 -54
  207. package/src/codegen/protocol-imports.test.ts +39 -0
  208. package/src/codegen/rewrite-operation-ids.test.ts +23 -114
  209. package/src/codegen/rewrite-operation-ids.ts +111 -98
  210. package/src/codegen/spec-path.ts +3 -6
  211. package/src/codegen/untagged-unions.test.ts +3 -7
  212. package/src/error-category.ts +5 -17
  213. package/src/errors.ts +16 -31
  214. package/src/graphql.test.ts +6 -8
  215. package/src/graphql.ts +76 -219
  216. package/src/graphql.types.ts +10 -25
  217. package/src/json-patch.test.ts +77 -0
  218. package/src/json-patch.ts +54 -60
  219. package/src/pagination.test.ts +13 -35
  220. package/src/pagination.ts +44 -111
  221. package/src/protocol-http.test.ts +36 -30
  222. package/src/protocol-http.ts +73 -138
  223. package/src/protocol-rest.test.ts +703 -0
  224. package/src/protocol-rest.ts +24 -62
  225. package/src/response-validation.test.ts +12 -18
  226. package/src/response-validation.ts +3 -12
  227. package/src/retry-after.test.ts +267 -0
  228. package/src/retry-after.ts +4 -10
  229. package/src/retry.test.ts +566 -0
  230. package/src/retry.ts +6 -21
  231. package/src/sdks.test.ts +87 -0
  232. package/src/testing.ts +4 -10
  233. package/src/trait.ts +21 -67
  234. package/src/xml.test.ts +15 -33
  235. package/src/xml.ts +9 -25
@@ -0,0 +1,703 @@
1
+ import * as Context from "effect/Context";
2
+ import * as Duration from "effect/Duration";
3
+ import * as Effect from "effect/Effect";
4
+ import * as HttpClient from "effect/http/HttpClient";
5
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
6
+ import * as HttpClientResponse from "effect/http/HttpClientResponse";
7
+ import * as Layer from "effect/Layer";
8
+ import * as Redacted from "effect/Redacted";
9
+ import * as Result from "effect/Result";
10
+ import * as Schema from "effect/Schema";
11
+ import { describe, expect, test } from "vitest";
12
+ import * as API from "./api.ts";
13
+ import {
14
+ BadRequest,
15
+ InternalServerError,
16
+ NotFound,
17
+ ServiceUnavailable,
18
+ TooManyRequests,
19
+ } from "./errors.ts";
20
+ import {
21
+ BinaryResponse,
22
+ makeRestProtocol,
23
+ RawResponseRoot,
24
+ SensitiveValue,
25
+ type RestErrorInfo,
26
+ type RestParseErrorInfo,
27
+ type RestProtocolOptions,
28
+ } from "./protocol-rest.ts";
29
+ import * as ResponseValidation from "./response-validation.ts";
30
+ import * as S from "./schema.ts";
31
+ import * as T from "./trait.ts";
32
+
33
+ // =============================================================================
34
+ // Fixtures
35
+ // =============================================================================
36
+
37
+ interface Creds {
38
+ readonly token: string;
39
+ readonly host: string;
40
+ }
41
+
42
+ class TestCreds extends Context.Service<TestCreds, Creds>()("ProtocolRestTest/Creds") {}
43
+
44
+ class TestUnknownError extends Schema.TaggedError<TestUnknownError>()("TestUnknownError", {
45
+ info: Schema.Unknown,
46
+ }) {}
47
+
48
+ class TestParseError extends Schema.TaggedError<TestParseError>()("TestParseError", {
49
+ info: Schema.Unknown,
50
+ }) {}
51
+
52
+ class ThingLocked extends T.applyErrorMatchers(
53
+ Schema.TaggedError<ThingLocked>()("ThingLocked", { message: Schema.String }),
54
+ [{ status: 409, message: { includes: "locked" } }],
55
+ ) {}
56
+
57
+ class QuotaExceeded extends T.applyErrorMatchers(
58
+ Schema.TaggedError<QuotaExceeded>()("QuotaExceeded", { message: Schema.String }),
59
+ [{ code: 4001 }],
60
+ ) {}
61
+
62
+ class QuotaExceededOnCreate extends T.applyErrorMatchers(
63
+ Schema.TaggedError<QuotaExceededOnCreate>()("QuotaExceededOnCreate", {
64
+ message: Schema.String,
65
+ }),
66
+ [{ code: 4001, status: 403 }],
67
+ ) {}
68
+
69
+ class Teapot extends T.applyErrorMatchers(
70
+ Schema.TaggedError<Teapot>()("Teapot", {
71
+ message: Schema.String,
72
+ body: Schema.Unknown,
73
+ headers: Schema.Unknown,
74
+ }),
75
+ [{ status: 418, headers: { "X-Reason": "teapot" } }],
76
+ ) {}
77
+
78
+ class Gone extends T.applyErrorMatchers(
79
+ Schema.TaggedError<Gone>()("Gone", { message: Schema.String }),
80
+ [{ body: { "/detail/kind": "gone" } }],
81
+ ) {}
82
+
83
+ const baseOptions: RestProtocolOptions<Creds> = {
84
+ credentials: Effect.gen(function* () {
85
+ return yield* TestCreds;
86
+ }),
87
+ baseUrl: (creds) => `https://${creds.host}`,
88
+ headers: (creds) => ({ authorization: `Bearer ${creds.token}` }),
89
+ unknownError: (info) => new TestUnknownError({ info }),
90
+ parseError: (info) => new TestParseError({ info }),
91
+ };
92
+
93
+ // `API.make` memoizes protocol layers by identity, so each variant is a
94
+ // module-level const like a provider's `protocol.ts`.
95
+ const DefaultProtocol = makeRestProtocol(baseOptions);
96
+
97
+ const ThingInput = S.Struct({
98
+ id: S.String.pipe(T.Label()),
99
+ limit: S.optional(S.Number.pipe(T.Query("limit"))),
100
+ tags: S.optional(S.Array(S.String).pipe(T.Query("tag"))),
101
+ trace: S.optional(S.String.pipe(T.Header("X-Trace-Id"))),
102
+ displayName: S.optional(S.String.pipe(T.Body("display_name"))),
103
+ secret: S.optional(S.String.pipe(SensitiveValue(), T.Body("secret_value"))),
104
+ }).pipe(T.Http({ method: "POST", uri: "/things/{id}" }));
105
+
106
+ const ThingOutput = S.Struct({
107
+ id: S.optional(S.String),
108
+ displayName: S.optional(S.String.pipe(T.Body("display_name"))),
109
+ secret: S.optional(S.String.pipe(SensitiveValue(), T.Body("secret_value"))),
110
+ });
111
+
112
+ const thingOp = (protocol: Layer.Layer<API.Protocol>, errors: ReadonlyArray<any> = []) =>
113
+ API.make(() => ({
114
+ input: ThingInput,
115
+ output: ThingOutput,
116
+ errors: errors as any,
117
+ protocol,
118
+ })) as unknown as (input: Record<string, unknown>) => Effect.Effect<any, any, any>;
119
+
120
+ const createThing = thingOp(DefaultProtocol);
121
+ const createThingWithErrors = thingOp(DefaultProtocol, [
122
+ ThingLocked,
123
+ QuotaExceeded,
124
+ QuotaExceededOnCreate,
125
+ Teapot,
126
+ Gone,
127
+ ]);
128
+
129
+ interface Recorded {
130
+ readonly requests: Array<HttpClientRequest.HttpClientRequest>;
131
+ }
132
+
133
+ const fakeClient = (
134
+ respond: (request: HttpClientRequest.HttpClientRequest) => Response,
135
+ recorded: Recorded = { requests: [] },
136
+ ) =>
137
+ Layer.succeed(
138
+ HttpClient.HttpClient,
139
+ HttpClient.make((request) =>
140
+ Effect.sync(() => {
141
+ recorded.requests.push(request);
142
+ return HttpClientResponse.fromWeb(request, respond(request));
143
+ }),
144
+ ),
145
+ );
146
+
147
+ const creds = (token = "tok-1", host = "api.test") => Layer.succeed(TestCreds, { token, host });
148
+
149
+ const json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>
150
+ new Response(JSON.stringify(body), {
151
+ status,
152
+ headers: { "content-type": "application/json", ...headers },
153
+ });
154
+
155
+ const run = <A, E>(effect: Effect.Effect<A, E, any>, ...layers: Array<Layer.Any>) =>
156
+ Effect.runPromise(
157
+ Effect.result(
158
+ effect.pipe(Effect.provide(Layer.mergeAll(...(layers as [any])))),
159
+ ) as Effect.Effect<any, never, never>,
160
+ );
161
+
162
+ const succeed = async <A>(effect: Effect.Effect<A, any, any>, ...layers: Array<Layer.Any>) => {
163
+ const result = await run(effect, ...layers);
164
+ if (result._tag !== "Success") throw new Error(`expected success, got ${String(result.failure)}`);
165
+ return result.success as any;
166
+ };
167
+
168
+ const failWith = async (effect: Effect.Effect<any, any, any>, ...layers: Array<Layer.Any>) => {
169
+ const result = await run(effect, ...layers);
170
+ if (result._tag !== "Failure") throw new Error("expected failure");
171
+ return result.failure as any;
172
+ };
173
+
174
+ const failOn = (response: () => Response, op = createThingWithErrors) =>
175
+ failWith(op({ id: "t1" }), fakeClient(response), creds());
176
+
177
+ const bodyText = (request: HttpClientRequest.HttpClientRequest): string | undefined => {
178
+ const body = request.body as any;
179
+ if (body._tag === "Uint8Array") return new TextDecoder().decode(body.body);
180
+ if (body._tag === "Text") return body.body;
181
+ return undefined;
182
+ };
183
+
184
+ // =============================================================================
185
+ // Request
186
+ // =============================================================================
187
+
188
+ describe("makeRestProtocol request encoding", () => {
189
+ test("builds path, query, header and JSON body members from the input schema", async () => {
190
+ const recorded: Recorded = { requests: [] };
191
+ await succeed(
192
+ createThing({
193
+ id: "a b/c",
194
+ limit: 5,
195
+ tags: ["x", "y"],
196
+ trace: "trace-1",
197
+ displayName: "Widget",
198
+ }),
199
+ fakeClient(() => json({}), recorded),
200
+ creds(),
201
+ );
202
+ const [request] = recorded.requests;
203
+ expect(request!.method).toBe("POST");
204
+ expect(request!.url).toBe("https://api.test/things/a%20b%2Fc?limit=5&tag=x&tag=y");
205
+ expect(request!.headers["x-trace-id"]).toBe("trace-1");
206
+ expect(JSON.parse(bodyText(request!)!)).toEqual({ display_name: "Widget" });
207
+ });
208
+
209
+ test("unwraps Redacted input values before serializing them", async () => {
210
+ const recorded: Recorded = { requests: [] };
211
+ await succeed(
212
+ createThing({ id: "t1", secret: Redacted.make("s3cret") }),
213
+ fakeClient(() => json({}), recorded),
214
+ creds(),
215
+ );
216
+ expect(JSON.parse(bodyText(recorded.requests[0]!)!)).toEqual({ secret_value: "s3cret" });
217
+ });
218
+
219
+ test("applies the headers hook from the resolved credentials", async () => {
220
+ const recorded: Recorded = { requests: [] };
221
+ await succeed(
222
+ createThing({ id: "t1" }),
223
+ fakeClient(() => json({}), recorded),
224
+ creds("tok-abc"),
225
+ );
226
+ expect(recorded.requests[0]!.headers.authorization).toBe("Bearer tok-abc");
227
+ });
228
+
229
+ test("resolves credentials on every request from the calling fiber's context", async () => {
230
+ const recorded: Recorded = { requests: [] };
231
+ const client = fakeClient(() => json({}), recorded);
232
+ await succeed(createThing({ id: "t1" }), client, creds("first", "one.test"));
233
+ await succeed(createThing({ id: "t1" }), client, creds("second", "two.test"));
234
+ expect(recorded.requests.map((r) => [r.url, r.headers.authorization])).toEqual([
235
+ ["https://one.test/things/t1", "Bearer first"],
236
+ ["https://two.test/things/t1", "Bearer second"],
237
+ ]);
238
+ });
239
+
240
+ test("a credentials failure fails the call before any request is sent", async () => {
241
+ const CredsFailProtocol = makeRestProtocol<Creds>({
242
+ ...baseOptions,
243
+ credentials: Effect.fail(new BadRequest({ message: "no creds" })),
244
+ });
245
+ const recorded: Recorded = { requests: [] };
246
+ const error = await failWith(
247
+ thingOp(CredsFailProtocol)({ id: "t1" }),
248
+ fakeClient(() => json({}), recorded),
249
+ );
250
+ expect(error).toBeInstanceOf(BadRequest);
251
+ expect(recorded.requests).toHaveLength(0);
252
+ });
253
+
254
+ test("baseUrl receives the operation's route", async () => {
255
+ const targets: Array<unknown> = [];
256
+ const RoutingProtocol = makeRestProtocol<Creds>({
257
+ ...baseOptions,
258
+ baseUrl: (c, target) => {
259
+ targets.push(target);
260
+ return `https://routed.${c.host}`;
261
+ },
262
+ });
263
+ const recorded: Recorded = { requests: [] };
264
+ await succeed(
265
+ thingOp(RoutingProtocol)({ id: "t1" }),
266
+ fakeClient(() => json({}), recorded),
267
+ creds(),
268
+ );
269
+ expect(targets).toEqual([{ uri: "/things/{id}", method: "POST" }]);
270
+ expect(recorded.requests[0]!.url).toBe("https://routed.api.test/things/t1");
271
+ });
272
+
273
+ test("an error thrown by baseUrl fails the call instead of dying", async () => {
274
+ const refusal = new BadRequest({ message: "scope missing" });
275
+ const RefusingProtocol = makeRestProtocol<Creds>({
276
+ ...baseOptions,
277
+ baseUrl: () => {
278
+ throw refusal;
279
+ },
280
+ });
281
+ const recorded: Recorded = { requests: [] };
282
+ const error = await failWith(
283
+ thingOp(RefusingProtocol)({ id: "t1" }),
284
+ fakeClient(() => json({}), recorded),
285
+ creds(),
286
+ );
287
+ expect(error).toBe(refusal);
288
+ expect(recorded.requests).toHaveLength(0);
289
+ });
290
+
291
+ test("mapMemberHeader transforms member headers but not the auth headers", async () => {
292
+ const MappedHeaderProtocol = makeRestProtocol<Creds>({
293
+ ...baseOptions,
294
+ mapMemberHeader: (name, value) => `${name}=${value.toUpperCase()}`,
295
+ });
296
+ const recorded: Recorded = { requests: [] };
297
+ await succeed(
298
+ thingOp(MappedHeaderProtocol)({ id: "t1", trace: "abc" }),
299
+ fakeClient(() => json({}), recorded),
300
+ creds(),
301
+ );
302
+ expect(recorded.requests[0]!.headers["x-trace-id"]).toBe("x-trace-id=ABC");
303
+ expect(recorded.requests[0]!.headers.authorization).toBe("Bearer tok-1");
304
+ });
305
+
306
+ test("unknownKeyToWire names input keys the schema does not model", async () => {
307
+ const SnakeProtocol = makeRestProtocol<Creds>({
308
+ ...baseOptions,
309
+ unknownKeyToWire: (key) => key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`),
310
+ });
311
+ const recorded: Recorded = { requests: [] };
312
+ await succeed(
313
+ thingOp(SnakeProtocol)({ id: "t1", extraField: 1 }),
314
+ fakeClient(() => json({}), recorded),
315
+ creds(),
316
+ );
317
+ expect(JSON.parse(bodyText(recorded.requests[0]!)!)).toEqual({ extra_field: 1 });
318
+ });
319
+
320
+ test("without unknownKeyToWire, unmodeled input keys pass through verbatim", async () => {
321
+ const recorded: Recorded = { requests: [] };
322
+ await succeed(
323
+ createThing({ id: "t1", extraField: 1 }),
324
+ fakeClient(() => json({}), recorded),
325
+ creds(),
326
+ );
327
+ expect(JSON.parse(bodyText(recorded.requests[0]!)!)).toEqual({ extraField: 1 });
328
+ });
329
+ });
330
+
331
+ describe("makeRestProtocol raw request bodies", () => {
332
+ // Shaped like Cloudflare R2 putObject: a raw body, a Content-Type header
333
+ // member, and a declared bodyMediaType.
334
+ const UploadInput = S.Struct({
335
+ key: S.String.pipe(T.Label()),
336
+ body: S.optional(S.String.pipe(T.HttpBody())),
337
+ contentType: S.optional(S.String.pipe(T.Header("Content-Type"))),
338
+ }).pipe(
339
+ T.Http({ method: "PUT", uri: "/objects/{key}", bodyMediaType: "application/octet-stream" }),
340
+ );
341
+ const NdjsonInput = S.Struct({
342
+ body: S.optional(S.String.pipe(T.HttpBody())),
343
+ }).pipe(T.Http({ method: "POST", uri: "/insert", bodyMediaType: "application/x-ndjson" }));
344
+ const UntypedUploadInput = S.Struct({
345
+ body: S.optional(S.Unknown.pipe(T.HttpBody())),
346
+ }).pipe(T.Http({ method: "PUT", uri: "/blob" }));
347
+
348
+ const op = (input: S.Top) =>
349
+ API.make(() => ({
350
+ input,
351
+ output: S.Struct({}),
352
+ errors: [],
353
+ protocol: DefaultProtocol,
354
+ })) as unknown as (input: Record<string, unknown>) => Effect.Effect<any, any, any>;
355
+ const upload = op(UploadInput);
356
+ const insert = op(NdjsonInput);
357
+ const untypedUpload = op(UntypedUploadInput);
358
+
359
+ // The request as `fetch` would receive it.
360
+ const send = async (effect: Effect.Effect<any, any, any>) => {
361
+ const recorded: Recorded = { requests: [] };
362
+ await succeed(
363
+ effect,
364
+ fakeClient(() => json({}), recorded),
365
+ creds(),
366
+ );
367
+ return Result.getOrThrow(HttpClientRequest.toWebResult(recorded.requests[0]!));
368
+ };
369
+
370
+ test("a raw body is sent under the caller's Content-Type, for every body type", async () => {
371
+ const bytes = new Uint8Array([1, 2, 3]);
372
+ for (const body of [bytes, bytes.buffer, new Blob([bytes]), "#EXTM3U"]) {
373
+ const request = await send(upload({ key: "a.mp4", body, contentType: "video/mp4" }));
374
+ expect(request.headers.get("content-type")).toBe("video/mp4");
375
+ }
376
+ const request = await send(upload({ key: "a.mp4", body: bytes, contentType: "video/mp4" }));
377
+ expect(new Uint8Array(await request.arrayBuffer())).toEqual(bytes);
378
+ });
379
+
380
+ test("without a Content-Type member value, the declared bodyMediaType is used", async () => {
381
+ const object = await send(upload({ key: "a.bin", body: new Uint8Array([1]) }));
382
+ expect(object.headers.get("content-type")).toBe("application/octet-stream");
383
+ const ndjson = await send(insert({ body: '{"id":"1"}\n' }));
384
+ expect(ndjson.headers.get("content-type")).toBe("application/x-ndjson");
385
+ expect(await ndjson.text()).toBe('{"id":"1"}\n');
386
+ });
387
+
388
+ test("with neither, a Blob body is sent under its own type", async () => {
389
+ const request = await send(untypedUpload({ body: new Blob(["<p>"], { type: "text/html" }) }));
390
+ expect(request.headers.get("content-type")).toBe("text/html");
391
+ });
392
+ });
393
+
394
+ // =============================================================================
395
+ // Success responses
396
+ // =============================================================================
397
+
398
+ describe("makeRestProtocol success decoding", () => {
399
+ test("maps wire keys to TS names and wraps sensitive members in Redacted", async () => {
400
+ const out = await succeed(
401
+ createThing({ id: "t1" }),
402
+ fakeClient(() =>
403
+ json({ id: "t1", display_name: "Widget", secret_value: "s3cret", extra: 1 }),
404
+ ),
405
+ creds(),
406
+ );
407
+ expect(out).toEqual({
408
+ id: "t1",
409
+ displayName: "Widget",
410
+ secret: Redacted.make("s3cret"),
411
+ extra: 1,
412
+ });
413
+ expect(Redacted.value(out.secret)).toBe("s3cret");
414
+ expect(JSON.stringify(out)).not.toContain("s3cret");
415
+ });
416
+
417
+ test("a 204 with no body decodes to an empty object", async () => {
418
+ const out = await succeed(
419
+ createThing({ id: "t1" }),
420
+ fakeClient(() => new Response(null, { status: 204 })),
421
+ creds(),
422
+ );
423
+ expect(out).toEqual({});
424
+ });
425
+
426
+ test("a whitespace-only 200 body decodes to an empty object", async () => {
427
+ const out = await succeed(
428
+ createThing({ id: "t1" }),
429
+ fakeClient(() => new Response(" \n", { status: 200 })),
430
+ creds(),
431
+ );
432
+ expect(out).toEqual({});
433
+ });
434
+
435
+ test("transformResponse runs on the parsed body before key mapping", async () => {
436
+ const seen: Array<unknown> = [];
437
+ const UnwrapProtocol = makeRestProtocol<Creds>({
438
+ ...baseOptions,
439
+ transformResponse: (body) => {
440
+ seen.push(body);
441
+ return (body as { data: unknown }).data;
442
+ },
443
+ });
444
+ const out = await succeed(
445
+ thingOp(UnwrapProtocol)({ id: "t1" }),
446
+ fakeClient(() => json({ data: { id: "t1", display_name: "Widget" } })),
447
+ creds(),
448
+ );
449
+ expect(seen).toEqual([{ data: { id: "t1", display_name: "Widget" } }]);
450
+ expect(out).toEqual({ id: "t1", displayName: "Widget" });
451
+ });
452
+
453
+ test("transformResponse is not applied to error responses", async () => {
454
+ let calls = 0;
455
+ const CountingProtocol = makeRestProtocol<Creds>({
456
+ ...baseOptions,
457
+ transformResponse: (body) => {
458
+ calls++;
459
+ return body;
460
+ },
461
+ });
462
+ await failWith(
463
+ thingOp(CountingProtocol)({ id: "t1" }),
464
+ fakeClient(() => json({ message: "nope" }, 404)),
465
+ creds(),
466
+ );
467
+ expect(calls).toBe(0);
468
+ });
469
+
470
+ test("strict validation failures go through the parseError hook with the raw body", async () => {
471
+ const StrictOutput = S.Struct({ id: S.String });
472
+ const strictOp = API.make(() => ({
473
+ input: ThingInput,
474
+ output: StrictOutput,
475
+ protocol: DefaultProtocol,
476
+ })) as unknown as (input: Record<string, unknown>) => Effect.Effect<any, any, any>;
477
+ const error = await failWith(
478
+ strictOp({ id: "t1" }),
479
+ fakeClient(() => json({ id: 42 })),
480
+ creds(),
481
+ ResponseValidation.strict,
482
+ );
483
+ expect(error).toBeInstanceOf(TestParseError);
484
+ const info = error.info as RestParseErrorInfo;
485
+ expect(info.body).toEqual({ id: 42 });
486
+ expect(info.cause).toBeDefined();
487
+ });
488
+
489
+ test("RawResponseRoot outputs return a bare array body as-is", async () => {
490
+ const ListOutput = S.Array(S.Struct({ id: S.String })).pipe(RawResponseRoot());
491
+ const listOp = API.make(() => ({
492
+ input: ThingInput,
493
+ output: ListOutput,
494
+ protocol: DefaultProtocol,
495
+ })) as unknown as (input: Record<string, unknown>) => Effect.Effect<any, any, any>;
496
+ const out = await succeed(
497
+ listOp({ id: "t1" }),
498
+ fakeClient(() => json([{ id: "a" }, { id: "b" }])),
499
+ creds(),
500
+ );
501
+ expect(out).toEqual([{ id: "a" }, { id: "b" }]);
502
+ });
503
+
504
+ test("BinaryResponse outputs return the body bytes untouched", async () => {
505
+ const bytes = new Uint8Array([0, 255, 1, 128, 10]);
506
+ const BinaryOutput = S.Unknown.pipe(BinaryResponse());
507
+ const binaryOp = API.make(() => ({
508
+ input: ThingInput,
509
+ output: BinaryOutput,
510
+ protocol: DefaultProtocol,
511
+ })) as unknown as (input: Record<string, unknown>) => Effect.Effect<any, any, any>;
512
+ const out = await succeed(
513
+ binaryOp({ id: "t1" }),
514
+ fakeClient(() => new Response(bytes, { status: 200 })),
515
+ creds(),
516
+ );
517
+ expect(out).toBeInstanceOf(Uint8Array);
518
+ expect(Array.from(out)).toEqual(Array.from(bytes));
519
+ });
520
+ });
521
+
522
+ // =============================================================================
523
+ // Error responses
524
+ // =============================================================================
525
+
526
+ describe("makeRestProtocol typed error matching", () => {
527
+ test("a declared error whose status and message matcher match wins over the status map", async () => {
528
+ const error = await failOn(() => json({ message: "thing is locked" }, 409));
529
+ expect(error).toBeInstanceOf(ThingLocked);
530
+ expect(error.message).toBe("thing is locked");
531
+ });
532
+
533
+ test("a numeric envelope code selects the declared error with that code", async () => {
534
+ const error = await failOn(() => json({ code: 4001, message: "quota" }, 400));
535
+ expect(error).toBeInstanceOf(QuotaExceeded);
536
+ expect(error.message).toBe("quota");
537
+ });
538
+
539
+ test("the most specific matching declared error wins", async () => {
540
+ const error = await failOn(() => json({ code: 4001, message: "quota" }, 403));
541
+ expect(error).toBeInstanceOf(QuotaExceededOnCreate);
542
+ });
543
+
544
+ test("a string envelope code never satisfies a numeric code matcher", async () => {
545
+ const error = await failOn(() => json({ code: "4001", message: "quota" }, 400));
546
+ expect(error).toBeInstanceOf(BadRequest);
547
+ });
548
+
549
+ test("header matchers see the response headers case-insensitively, with body and headers passed to the class", async () => {
550
+ const error = await failOn(() =>
551
+ json({ message: "short and stout" }, 418, { "x-reason": "teapot" }),
552
+ );
553
+ expect(error).toBeInstanceOf(Teapot);
554
+ expect(error.body).toEqual({ message: "short and stout" });
555
+ expect(error.headers["x-reason"]).toBe("teapot");
556
+ });
557
+
558
+ test("body pointer matchers see the parsed JSON body", async () => {
559
+ const error = await failOn(() => json({ message: "bye", detail: { kind: "gone" } }, 410));
560
+ expect(error).toBeInstanceOf(Gone);
561
+ });
562
+
563
+ test("declared errors are ignored when nothing matches", async () => {
564
+ const error = await failOn(() => json({ message: "thing is busy" }, 409));
565
+ expect(error._tag).toBe("Conflict");
566
+ expect(error.message).toBe("thing is busy");
567
+ });
568
+
569
+ test("operations without declared errors fall straight to the status map", async () => {
570
+ const error = await failOn(() => json({ message: "thing is locked" }, 409), createThing);
571
+ expect(error._tag).toBe("Conflict");
572
+ });
573
+ });
574
+
575
+ describe("makeRestProtocol status mapping and fallbacks", () => {
576
+ test("mapped 4xx statuses become core HTTP errors with the envelope message", async () => {
577
+ const error = await failOn(() => json({ message: "no such thing" }, 404));
578
+ expect(error).toBeInstanceOf(NotFound);
579
+ expect(error.message).toBe("no such thing");
580
+ });
581
+
582
+ test("the default envelope falls back to a string `error` field for the message", async () => {
583
+ const error = await failOn(() => json({ error: "bad input" }, 400));
584
+ expect(error).toBeInstanceOf(BadRequest);
585
+ expect(error.message).toBe("bad input");
586
+ });
587
+
588
+ test("a JSON body without a message yields an `HTTP <status>` message", async () => {
589
+ const error = await failOn(() => json({ detail: "x" }, 400));
590
+ expect(error.message).toBe("HTTP 400");
591
+ });
592
+
593
+ test("retryable statuses carry retryAfter from the Retry-After header", async () => {
594
+ const error = await failOn(() => json({ message: "slow down" }, 429, { "retry-after": "7" }));
595
+ expect(error).toBeInstanceOf(TooManyRequests);
596
+ expect(Duration.toMillis(error.retryAfter)).toBe(7_000);
597
+ });
598
+
599
+ test("retryable statuses carry retryAfter from the RateLimit header", async () => {
600
+ const error = await failOn(() => json({}, 503, { ratelimit: "r=0, t=12" }));
601
+ expect(error).toBeInstanceOf(ServiceUnavailable);
602
+ expect(Duration.toMillis(error.retryAfter)).toBe(12_000);
603
+ });
604
+
605
+ test("non-retryable statuses never carry retryAfter", async () => {
606
+ const error = await failOn(() => json({ message: "gone" }, 404, { "retry-after": "7" }));
607
+ expect(error).toBeInstanceOf(NotFound);
608
+ expect(error.retryAfter).toBeUndefined();
609
+ });
610
+
611
+ test("unmapped 5xx statuses become a retryable InternalServerError", async () => {
612
+ const error = await failOn(() => json({ message: "origin down" }, 521, { "retry-after": "3" }));
613
+ expect(error).toBeInstanceOf(InternalServerError);
614
+ expect(error.message).toBe("origin down");
615
+ // 521 is not in RETRYABLE_HTTP_STATUSES, so its hint is not stamped.
616
+ expect(error.retryAfter).toBeUndefined();
617
+ });
618
+
619
+ test("unmapped 4xx statuses go to the unknownError hook with the wire details", async () => {
620
+ const error = await failOn(() =>
621
+ json({ code: "PAYMENT", message: "pay up" }, 402, { "x-id": "r1" }),
622
+ );
623
+ expect(error).toBeInstanceOf(TestUnknownError);
624
+ const info = error.info as RestErrorInfo;
625
+ expect(info.status).toBe(402);
626
+ expect(info.code).toBe("PAYMENT");
627
+ expect(info.message).toBe("pay up");
628
+ expect(info.body).toEqual({ code: "PAYMENT", message: "pay up" });
629
+ expect(info.headers["x-id"]).toBe("r1");
630
+ });
631
+
632
+ test("a non-JSON error body becomes the trimmed message and the raw body", async () => {
633
+ const error = await failOn(
634
+ () => new Response(" <html>Bad gateway thing</html>\n", { status: 402 }),
635
+ );
636
+ const info = error.info as RestErrorInfo;
637
+ expect(info.message).toBe("<html>Bad gateway thing</html>");
638
+ expect(info.body).toBe(" <html>Bad gateway thing</html>\n");
639
+ expect(info.code).toBeUndefined();
640
+ });
641
+
642
+ test("a non-JSON error body can still be matched by a declared message matcher", async () => {
643
+ const error = await failOn(
644
+ () => new Response("resource locked by another op", { status: 409 }),
645
+ );
646
+ expect(error).toBeInstanceOf(ThingLocked);
647
+ expect(error.message).toBe("resource locked by another op");
648
+ });
649
+
650
+ test("a non-JSON mapped error keeps the text as the message", async () => {
651
+ const error = await failOn(() => new Response("Service Unavailable", { status: 503 }));
652
+ expect(error).toBeInstanceOf(ServiceUnavailable);
653
+ expect(error.message).toBe("Service Unavailable");
654
+ });
655
+
656
+ test("an empty error body yields an `HTTP <status>` message", async () => {
657
+ const error = await failOn(() => new Response(null, { status: 402 }));
658
+ const info = error.info as RestErrorInfo;
659
+ expect(info.message).toBe("HTTP 402");
660
+ expect(info.body).toBeUndefined();
661
+ });
662
+ });
663
+
664
+ class CustomNotFound extends Schema.TaggedError<CustomNotFound>()("CustomNotFound", {
665
+ message: Schema.String,
666
+ retryAfter: Schema.optional(Schema.Unknown),
667
+ }) {}
668
+
669
+ const CustomEnvelopeProtocol = makeRestProtocol<Creds>({
670
+ ...baseOptions,
671
+ errorEnvelope: (body) => {
672
+ const err = (body as { err?: { id?: number; text?: string } } | null)?.err;
673
+ return err ? { code: err.id, message: err.text } : undefined;
674
+ },
675
+ statusMap: { 404: CustomNotFound },
676
+ });
677
+ const customOp = thingOp(CustomEnvelopeProtocol, [QuotaExceeded]);
678
+
679
+ describe("makeRestProtocol errorEnvelope and statusMap options", () => {
680
+ test("a custom errorEnvelope supplies the code and message used for matching", async () => {
681
+ const error = await failOn(() => json({ err: { id: 4001, text: "quota" } }, 400), customOp);
682
+ expect(error).toBeInstanceOf(QuotaExceeded);
683
+ expect(error.message).toBe("quota");
684
+ });
685
+
686
+ test("a custom errorEnvelope returning undefined falls back to `HTTP <status>`", async () => {
687
+ const error = await failOn(() => json({ message: "ignored" }, 404), customOp);
688
+ expect(error).toBeInstanceOf(CustomNotFound);
689
+ expect(error.message).toBe("HTTP 404");
690
+ });
691
+
692
+ test("a custom statusMap replaces the default map rather than extending it", async () => {
693
+ const error = await failOn(() => json({ err: { text: "bad" } }, 400), customOp);
694
+ expect(error).toBeInstanceOf(TestUnknownError);
695
+ expect((error.info as RestErrorInfo).message).toBe("bad");
696
+ });
697
+
698
+ test("unmapped 5xx still become InternalServerError with a custom statusMap", async () => {
699
+ const error = await failOn(() => json({ err: { text: "boom" } }, 500), customOp);
700
+ expect(error).toBeInstanceOf(InternalServerError);
701
+ expect(error.message).toBe("boom");
702
+ });
703
+ });