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

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 (314) hide show
  1. package/lib/_bundle/base.js +2 -2
  2. package/lib/_bundle/base.js.map +1 -1
  3. package/lib/_bundle/graphql.js +2 -2
  4. package/lib/_bundle/graphql.js.map +1 -1
  5. package/lib/_bundle/grpc.js +2 -0
  6. package/lib/_bundle/grpc.js.map +1 -0
  7. package/lib/_bundle/rest.js +1 -1
  8. package/lib/_bundle/rest.js.map +1 -1
  9. package/lib/_bundle/xml.js +1 -1
  10. package/lib/_bundle/xml.js.map +1 -1
  11. package/lib/annotations.d.ts +17 -0
  12. package/lib/annotations.d.ts.map +1 -0
  13. package/lib/annotations.js +2 -0
  14. package/lib/annotations.js.map +1 -0
  15. package/lib/api.d.ts +52 -1
  16. package/lib/api.d.ts.map +1 -1
  17. package/lib/api.js +1 -1
  18. package/lib/category.d.ts.map +1 -1
  19. package/lib/config.d.ts +54 -13
  20. package/lib/config.d.ts.map +1 -1
  21. package/lib/config.js +1 -1
  22. package/lib/error-category.d.ts.map +1 -1
  23. package/lib/errors.d.ts +3 -13
  24. package/lib/errors.d.ts.map +1 -1
  25. package/lib/errors.js +1 -1
  26. package/lib/graphql.d.ts +26 -5
  27. package/lib/graphql.d.ts.map +1 -1
  28. package/lib/graphql.types.d.ts.map +1 -1
  29. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  30. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  31. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  32. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  33. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  34. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  35. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  36. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  37. package/lib/grpc-transport-node-http2.d.ts +19 -0
  38. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  39. package/lib/grpc-transport-node-http2.js +2 -0
  40. package/lib/grpc-transport-node-http2.js.map +1 -0
  41. package/lib/grpc-transport.d.ts +76 -0
  42. package/lib/grpc-transport.d.ts.map +1 -0
  43. package/lib/grpc-transport.js +1 -0
  44. package/lib/hpack.d.ts +34 -0
  45. package/lib/hpack.d.ts.map +1 -0
  46. package/lib/hpack.js +2 -0
  47. package/lib/hpack.js.map +1 -0
  48. package/lib/index.d.ts +6 -2
  49. package/lib/index.d.ts.map +1 -1
  50. package/lib/index.js +4 -0
  51. package/lib/pagination.d.ts +55 -3
  52. package/lib/pagination.d.ts.map +1 -1
  53. package/lib/pagination.js +1 -1
  54. package/lib/protobuf.d.ts +92 -0
  55. package/lib/protobuf.d.ts.map +1 -0
  56. package/lib/protobuf.js +1 -0
  57. package/lib/protocol-grpc.d.ts +86 -0
  58. package/lib/protocol-grpc.d.ts.map +1 -0
  59. package/lib/protocol-grpc.js +1 -0
  60. package/lib/protocol-http.d.ts +38 -9
  61. package/lib/protocol-http.d.ts.map +1 -1
  62. package/lib/protocol-http.js +1 -1
  63. package/lib/protocol-rest.d.ts +60 -42
  64. package/lib/protocol-rest.d.ts.map +1 -1
  65. package/lib/protocol-rest.js +1 -1
  66. package/lib/response-validation.d.ts +5 -4
  67. package/lib/response-validation.d.ts.map +1 -1
  68. package/lib/schema-lite-typed.js +1 -2
  69. package/lib/sdk-error.d.ts +27 -0
  70. package/lib/sdk-error.d.ts.map +1 -0
  71. package/lib/sdk-error.js +1 -0
  72. package/lib/sensitive.d.ts +28 -0
  73. package/lib/sensitive.d.ts.map +1 -0
  74. package/lib/sensitive.js +2 -0
  75. package/lib/sensitive.js.map +1 -0
  76. package/lib/telemetry-debug.d.ts +6 -0
  77. package/lib/telemetry-debug.d.ts.map +1 -0
  78. package/lib/telemetry-debug.js +2 -0
  79. package/lib/telemetry-debug.js.map +1 -0
  80. package/lib/telemetry-hooks.d.ts +32 -0
  81. package/lib/telemetry-hooks.d.ts.map +1 -0
  82. package/lib/telemetry-hooks.js +2 -0
  83. package/lib/telemetry-hooks.js.map +1 -0
  84. package/lib/telemetry-host-rules.d.ts +23 -0
  85. package/lib/telemetry-host-rules.d.ts.map +1 -0
  86. package/lib/telemetry-host-rules.js +2 -0
  87. package/lib/telemetry-host-rules.js.map +1 -0
  88. package/lib/telemetry-lambda-context.d.ts +17 -0
  89. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  90. package/lib/telemetry-lambda-context.js +2 -0
  91. package/lib/telemetry-lambda-context.js.map +1 -0
  92. package/lib/telemetry-message-context.d.ts +52 -0
  93. package/lib/telemetry-message-context.d.ts.map +1 -0
  94. package/lib/telemetry-message-context.js +2 -0
  95. package/lib/telemetry-message-context.js.map +1 -0
  96. package/lib/telemetry-metrics.d.ts +6 -0
  97. package/lib/telemetry-metrics.d.ts.map +1 -0
  98. package/lib/telemetry-metrics.js +2 -0
  99. package/lib/telemetry-metrics.js.map +1 -0
  100. package/lib/telemetry-name-template.d.ts +13 -0
  101. package/lib/telemetry-name-template.d.ts.map +1 -0
  102. package/lib/telemetry-name-template.js +2 -0
  103. package/lib/telemetry-name-template.js.map +1 -0
  104. package/lib/telemetry-stream.d.ts +11 -0
  105. package/lib/telemetry-stream.d.ts.map +1 -0
  106. package/lib/telemetry-stream.js +2 -0
  107. package/lib/telemetry-stream.js.map +1 -0
  108. package/lib/telemetry-xray.d.ts +28 -0
  109. package/lib/telemetry-xray.d.ts.map +1 -0
  110. package/lib/telemetry-xray.js +2 -0
  111. package/lib/telemetry-xray.js.map +1 -0
  112. package/lib/telemetry.d.ts +288 -0
  113. package/lib/telemetry.d.ts.map +1 -0
  114. package/lib/telemetry.js +3 -0
  115. package/lib/telemetry.js.map +1 -0
  116. package/lib/trait.d.ts +7 -0
  117. package/lib/trait.d.ts.map +1 -1
  118. package/lib/trait.js +1 -1
  119. package/lib/xml.d.ts.map +1 -1
  120. package/package.json +3 -5
  121. package/src/annotations.ts +53 -0
  122. package/src/api.ts +316 -43
  123. package/src/category.ts +21 -22
  124. package/src/config.ts +58 -29
  125. package/src/error-category.ts +12 -14
  126. package/src/errors.ts +11 -7
  127. package/src/graphql.ts +191 -63
  128. package/src/graphql.types.ts +5 -1
  129. package/src/grpc-transport-cloudflare-http2.ts +494 -0
  130. package/src/grpc-transport-cloudflare-sockets.ts +299 -0
  131. package/src/grpc-transport-node-http2.ts +234 -0
  132. package/src/grpc-transport.ts +118 -0
  133. package/src/hpack.ts +331 -0
  134. package/src/index.ts +6 -2
  135. package/src/pagination.ts +193 -8
  136. package/src/protobuf.ts +1332 -0
  137. package/src/protocol-grpc.ts +641 -0
  138. package/src/protocol-http.ts +87 -67
  139. package/src/protocol-rest.ts +183 -191
  140. package/src/response-validation.ts +8 -5
  141. package/src/sdk-error.ts +33 -0
  142. package/src/sensitive.ts +154 -0
  143. package/src/telemetry-debug.ts +179 -0
  144. package/src/telemetry-hooks.ts +33 -0
  145. package/src/telemetry-host-rules.ts +39 -0
  146. package/src/telemetry-lambda-context.ts +46 -0
  147. package/src/telemetry-message-context.ts +170 -0
  148. package/src/telemetry-metrics.ts +69 -0
  149. package/src/telemetry-name-template.ts +26 -0
  150. package/src/telemetry-stream.ts +100 -0
  151. package/src/telemetry-xray.ts +66 -0
  152. package/src/telemetry.ts +832 -0
  153. package/src/trait.ts +10 -0
  154. package/src/xml.ts +10 -1
  155. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  156. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  157. package/lib/codegen/boolean-string-enums.js +0 -147
  158. package/lib/codegen/boolean-string-enums.js.map +0 -1
  159. package/lib/codegen/chunk.d.ts +0 -7
  160. package/lib/codegen/chunk.d.ts.map +0 -1
  161. package/lib/codegen/chunk.js +0 -139
  162. package/lib/codegen/chunk.js.map +0 -1
  163. package/lib/codegen/cli.d.ts +0 -80
  164. package/lib/codegen/cli.d.ts.map +0 -1
  165. package/lib/codegen/cli.js +0 -166
  166. package/lib/codegen/cli.js.map +0 -1
  167. package/lib/codegen/datafy.d.ts +0 -14
  168. package/lib/codegen/datafy.d.ts.map +0 -1
  169. package/lib/codegen/datafy.js +0 -853
  170. package/lib/codegen/datafy.js.map +0 -1
  171. package/lib/codegen/dedupe.d.ts +0 -5
  172. package/lib/codegen/dedupe.d.ts.map +0 -1
  173. package/lib/codegen/dedupe.js +0 -153
  174. package/lib/codegen/dedupe.js.map +0 -1
  175. package/lib/codegen/emit.d.ts +0 -125
  176. package/lib/codegen/emit.d.ts.map +0 -1
  177. package/lib/codegen/emit.js +0 -99
  178. package/lib/codegen/emit.js.map +0 -1
  179. package/lib/codegen/format.d.ts +0 -11
  180. package/lib/codegen/format.d.ts.map +0 -1
  181. package/lib/codegen/format.js +0 -32
  182. package/lib/codegen/format.js.map +0 -1
  183. package/lib/codegen/generated-at.d.ts +0 -29
  184. package/lib/codegen/generated-at.d.ts.map +0 -1
  185. package/lib/codegen/generated-at.js +0 -78
  186. package/lib/codegen/generated-at.js.map +0 -1
  187. package/lib/codegen/generator.d.ts +0 -353
  188. package/lib/codegen/generator.d.ts.map +0 -1
  189. package/lib/codegen/generator.js +0 -810
  190. package/lib/codegen/generator.js.map +0 -1
  191. package/lib/codegen/graph.d.ts +0 -36
  192. package/lib/codegen/graph.d.ts.map +0 -1
  193. package/lib/codegen/graph.js +0 -136
  194. package/lib/codegen/graph.js.map +0 -1
  195. package/lib/codegen/graphql-client.d.ts +0 -70
  196. package/lib/codegen/graphql-client.d.ts.map +0 -1
  197. package/lib/codegen/graphql-client.js +0 -439
  198. package/lib/codegen/graphql-client.js.map +0 -1
  199. package/lib/codegen/graphql.d.ts +0 -207
  200. package/lib/codegen/graphql.d.ts.map +0 -1
  201. package/lib/codegen/graphql.js +0 -786
  202. package/lib/codegen/graphql.js.map +0 -1
  203. package/lib/codegen/latin1.d.ts +0 -3
  204. package/lib/codegen/latin1.d.ts.map +0 -1
  205. package/lib/codegen/latin1.js +0 -126
  206. package/lib/codegen/latin1.js.map +0 -1
  207. package/lib/codegen/members.d.ts +0 -32
  208. package/lib/codegen/members.d.ts.map +0 -1
  209. package/lib/codegen/members.js +0 -62
  210. package/lib/codegen/members.js.map +0 -1
  211. package/lib/codegen/model-diff.d.ts +0 -10
  212. package/lib/codegen/model-diff.d.ts.map +0 -1
  213. package/lib/codegen/model-diff.js +0 -67
  214. package/lib/codegen/model-diff.js.map +0 -1
  215. package/lib/codegen/naming.d.ts +0 -29
  216. package/lib/codegen/naming.d.ts.map +0 -1
  217. package/lib/codegen/naming.js +0 -74
  218. package/lib/codegen/naming.js.map +0 -1
  219. package/lib/codegen/openapi-cli.d.ts +0 -52
  220. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  221. package/lib/codegen/openapi-cli.js +0 -84
  222. package/lib/codegen/openapi-cli.js.map +0 -1
  223. package/lib/codegen/openapi.d.ts +0 -209
  224. package/lib/codegen/openapi.d.ts.map +0 -1
  225. package/lib/codegen/openapi.js +0 -1548
  226. package/lib/codegen/openapi.js.map +0 -1
  227. package/lib/codegen/operations.d.ts +0 -24
  228. package/lib/codegen/operations.d.ts.map +0 -1
  229. package/lib/codegen/operations.js +0 -56
  230. package/lib/codegen/operations.js.map +0 -1
  231. package/lib/codegen/pagination.d.ts +0 -39
  232. package/lib/codegen/pagination.d.ts.map +0 -1
  233. package/lib/codegen/pagination.js +0 -31
  234. package/lib/codegen/pagination.js.map +0 -1
  235. package/lib/codegen/patch-audit.d.ts +0 -84
  236. package/lib/codegen/patch-audit.d.ts.map +0 -1
  237. package/lib/codegen/patch-audit.js +0 -366
  238. package/lib/codegen/patch-audit.js.map +0 -1
  239. package/lib/codegen/patches.d.ts +0 -129
  240. package/lib/codegen/patches.d.ts.map +0 -1
  241. package/lib/codegen/patches.js +0 -472
  242. package/lib/codegen/patches.js.map +0 -1
  243. package/lib/codegen/prelude.d.ts +0 -15
  244. package/lib/codegen/prelude.d.ts.map +0 -1
  245. package/lib/codegen/prelude.js +0 -60
  246. package/lib/codegen/prelude.js.map +0 -1
  247. package/lib/codegen/privatize.d.ts +0 -21
  248. package/lib/codegen/privatize.d.ts.map +0 -1
  249. package/lib/codegen/privatize.js +0 -176
  250. package/lib/codegen/privatize.js.map +0 -1
  251. package/lib/codegen/proto.d.ts +0 -121
  252. package/lib/codegen/proto.d.ts.map +0 -1
  253. package/lib/codegen/proto.js +0 -960
  254. package/lib/codegen/proto.js.map +0 -1
  255. package/lib/codegen/pure.d.ts +0 -6
  256. package/lib/codegen/pure.d.ts.map +0 -1
  257. package/lib/codegen/pure.js +0 -91
  258. package/lib/codegen/pure.js.map +0 -1
  259. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  260. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  261. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  262. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  263. package/lib/codegen/spec-path.d.ts +0 -16
  264. package/lib/codegen/spec-path.d.ts.map +0 -1
  265. package/lib/codegen/spec-path.js +0 -101
  266. package/lib/codegen/spec-path.js.map +0 -1
  267. package/lib/codegen/table.d.ts +0 -5
  268. package/lib/codegen/table.d.ts.map +0 -1
  269. package/lib/codegen/table.js +0 -249
  270. package/lib/codegen/table.js.map +0 -1
  271. package/lib/debug.d.ts +0 -2
  272. package/lib/debug.d.ts.map +0 -1
  273. package/lib/debug.js +0 -1
  274. package/lib/json-patch.d.ts +0 -58
  275. package/lib/json-patch.d.ts.map +0 -1
  276. package/lib/json-patch.js +0 -2
  277. package/lib/json-patch.js.map +0 -1
  278. package/lib/schema-lite-typed.js.map +0 -1
  279. package/lib/testing.d.ts +0 -40
  280. package/lib/testing.d.ts.map +0 -1
  281. package/lib/testing.js +0 -2
  282. package/lib/testing.js.map +0 -1
  283. package/src/codegen/boolean-string-enums.ts +0 -155
  284. package/src/codegen/chunk.ts +0 -147
  285. package/src/codegen/cli.ts +0 -293
  286. package/src/codegen/datafy.ts +0 -874
  287. package/src/codegen/dedupe.ts +0 -173
  288. package/src/codegen/emit.ts +0 -200
  289. package/src/codegen/format.ts +0 -49
  290. package/src/codegen/generated-at.ts +0 -88
  291. package/src/codegen/generator.ts +0 -1229
  292. package/src/codegen/graph.ts +0 -151
  293. package/src/codegen/graphql-client.ts +0 -545
  294. package/src/codegen/graphql.ts +0 -1145
  295. package/src/codegen/latin1.ts +0 -131
  296. package/src/codegen/members.ts +0 -79
  297. package/src/codegen/model-diff.ts +0 -67
  298. package/src/codegen/naming.ts +0 -85
  299. package/src/codegen/openapi-cli.ts +0 -141
  300. package/src/codegen/openapi.ts +0 -1845
  301. package/src/codegen/operations.ts +0 -73
  302. package/src/codegen/pagination.ts +0 -64
  303. package/src/codegen/patch-audit.ts +0 -480
  304. package/src/codegen/patches.ts +0 -581
  305. package/src/codegen/prelude.ts +0 -70
  306. package/src/codegen/privatize.ts +0 -200
  307. package/src/codegen/proto.ts +0 -1092
  308. package/src/codegen/pure.ts +0 -94
  309. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  310. package/src/codegen/spec-path.ts +0 -112
  311. package/src/codegen/table.ts +0 -254
  312. package/src/debug.ts +0 -8
  313. package/src/json-patch.ts +0 -273
  314. package/src/testing.ts +0 -74
package/src/api.ts CHANGED
@@ -13,8 +13,9 @@ import * as Ref from "effect/Ref";
13
13
  import * as S from "effect/Schema";
14
14
  import type * as AST from "effect/SchemaAST";
15
15
  import * as Scope from "effect/Scope";
16
- import type * as Stream from "effect/Stream";
16
+ import * as Stream from "effect/Stream";
17
17
  import { SingleShotGen } from "effect/Utils";
18
+ import { getAnn, rawResponseRootSymbol } from "./annotations.ts";
18
19
  import { isThrottling } from "./category.ts";
19
20
  import * as Pagination from "./pagination.ts";
20
21
  import {
@@ -25,6 +26,8 @@ import {
25
26
  resolveServerRetryHintCapMs,
26
27
  serverHintMillis,
27
28
  } from "./retry.ts";
29
+ import { SdkError } from "./sdk-error.ts";
30
+ import * as Telemetry from "./telemetry.ts";
28
31
 
29
32
  //#region Protocol
30
33
 
@@ -92,6 +95,16 @@ export class Protocol
92
95
  * produce the same request, result and errors as encode/decode.
93
96
  */
94
97
  readonly call?: (operation: PreparedOperation, input: unknown) => Effect.Effect<unknown>;
98
+ /**
99
+ * Server streaming (see {@link makeStreaming}): each response message
100
+ * as it arrives, decoded as one element of the output's `items`.
101
+ * Ending the stream early cancels the call. Protocols that can't
102
+ * stream leave it out.
103
+ */
104
+ readonly stream?: (
105
+ operation: PreparedOperation,
106
+ input: unknown,
107
+ ) => Stream.Stream<unknown, unknown>;
95
108
  }
96
109
  >()("Protocol") {}
97
110
 
@@ -239,6 +252,14 @@ export interface OperationConfig<
239
252
  * {@link ProtocolOperationConfig.endpointHostPrefix}).
240
253
  */
241
254
  endpointHostPrefix?: string;
255
+ /** The service's `com.distilled.telemetry#service` trait (a module const). */
256
+ telemetry?: Telemetry.ServiceTelemetry;
257
+ /**
258
+ * The operation's `com.distilled.telemetry#operation` trait, with its
259
+ * input rules; only what differs from the service's rules when it names
260
+ * its `op` (a string is just the op).
261
+ */
262
+ span?: Telemetry.SpanConfig | string;
242
263
  }
243
264
 
244
265
  /**
@@ -264,6 +285,26 @@ const backoffDelay = (b: Backoff, attempt: number, error: unknown): Effect.Effec
264
285
 
265
286
  const NO_BACKOFF: Backoff = { baseMs: 0, factor: 1, capMs: 0 };
266
287
 
288
+ /**
289
+ * BRAINSTORM: the sleep before retry `attempt` (1-based). The retry is
290
+ * recorded on the operation span; debug mode also makes the sleep a span.
291
+ */
292
+ const backoffSleep = (
293
+ delay: Duration.Input,
294
+ attempt: number,
295
+ error: unknown,
296
+ ): Effect.Effect<void> =>
297
+ Effect.withFiber((fiber) => {
298
+ const context = fiber.context as Context.Context<any>;
299
+ const delayMs = typeof delay === "number" ? delay : 0;
300
+ Telemetry.retried(context, attempt, error, delayMs);
301
+ return Telemetry.phase(context, "distilled.retry.backoff", Effect.sleep(delay), {
302
+ "distilled.retry.attempt": attempt,
303
+ "distilled.retry.delay_ms": Math.round(delayMs),
304
+ "distilled.retry.reason": (error as { _tag?: string } | null)?._tag,
305
+ });
306
+ });
307
+
267
308
  /**
268
309
  * Wrap one operation call with the caller-provided retry policy, if the
269
310
  * operation declares a retry tag. The call runs once with no retry
@@ -271,35 +312,44 @@ const NO_BACKOFF: Backoff = { baseMs: 0, factor: 1, capMs: 0 };
271
312
  * {@link Backoff} data run by a small loop; a caller-supplied `schedule`
272
313
  * runs under `Effect.retry`, with the first failure replayed as attempt one
273
314
  * so delays and counts match running the whole call under it.
315
+ *
316
+ * With `TelemetryDebug.layer`, every try runs as `Attempt` span n.
274
317
  */
275
318
  const applyRetry = (
276
319
  base: Effect.Effect<any, any, any>,
277
320
  retryKey: Context.Key<any, RetryPolicy> | undefined,
278
- ): Effect.Effect<any, any, any> =>
279
- retryKey === undefined
280
- ? base
281
- : Effect.catch(base, (error) =>
321
+ debug: Telemetry.DebugHooks | undefined,
322
+ ): Effect.Effect<any, any, any> => {
323
+ const first = debug === undefined ? base : debug.attempt(base, 1);
324
+ return retryKey === undefined
325
+ ? first
326
+ : Effect.catch(first, (error) =>
282
327
  Effect.flatMap(Effect.serviceOption(retryKey), (opt) => {
283
- if (Option.isNone(opt)) return retryWith(base, defaultOptions, error);
328
+ if (Option.isNone(opt)) return retryWith(base, defaultOptions, error, debug);
284
329
  const policy = opt.value;
285
- if (typeof policy !== "function") return retryWith(base, policy, error);
330
+ if (typeof policy !== "function") return retryWith(base, policy, error, debug);
286
331
  return Effect.flatMap(Ref.make<unknown>(error), (lastError) =>
287
332
  retryWith(
288
333
  Effect.tapError(base, (e) => Ref.set(lastError, e)),
289
334
  policy(lastError),
290
335
  error,
336
+ debug,
291
337
  ),
292
338
  );
293
339
  }),
294
340
  );
341
+ };
295
342
 
296
343
  const retryWith = (
297
344
  base: Effect.Effect<any, any, any>,
298
345
  opts: RetryOptions,
299
346
  error: unknown,
347
+ debug: Telemetry.DebugHooks | undefined,
300
348
  ): Effect.Effect<any, any, any> => {
301
349
  const keepGoing = opts.while;
302
350
  if (!keepGoing || !keepGoing(error)) return Effect.fail(error);
351
+ // Attempt n (2, 3, ...) of the call.
352
+ const again = (n: number) => (debug === undefined ? base : debug.attempt(base, n));
303
353
  if (opts.schedule) {
304
354
  // Drive the caller's schedule through its own `step`, as Effect.retry
305
355
  // does, without importing the Schedule module into every bundle: the
@@ -311,6 +361,7 @@ const retryWith = (
311
361
  >;
312
362
  };
313
363
  return Effect.flatMap(schedule.step, (next) => {
364
+ let attempt = 0;
314
365
  const loop = (e: unknown): Effect.Effect<any, any, any> =>
315
366
  !keepGoing(e)
316
367
  ? Effect.fail(e)
@@ -318,7 +369,9 @@ const retryWith = (
318
369
  Effect.matchEffect(next(clock.currentTimeMillisUnsafe(), e), {
319
370
  onFailure: () => Effect.fail(e),
320
371
  onSuccess: ([, delay]) =>
321
- Effect.flatMap(Effect.sleep(delay), () => Effect.catch(base, loop)),
372
+ Effect.flatMap(backoffSleep(delay, ++attempt, e), () =>
373
+ Effect.catch(again(attempt + 1), loop),
374
+ ),
322
375
  }),
323
376
  );
324
377
  return loop(error);
@@ -329,7 +382,9 @@ const retryWith = (
329
382
  !keepGoing(e) || (b.maxRetries !== undefined && n >= b.maxRetries)
330
383
  ? Effect.fail(e)
331
384
  : Effect.flatMap(backoffDelay(b, n, e), (ms) =>
332
- Effect.flatMap(Effect.sleep(ms), () => Effect.catch(base, (next) => step(next, n + 1))),
385
+ Effect.flatMap(backoffSleep(ms, n + 1, e), () =>
386
+ Effect.catch(again(n + 2), (next) => step(next, n + 1)),
387
+ ),
333
388
  );
334
389
  return step(error, 0);
335
390
  };
@@ -351,8 +406,18 @@ interface Prepared extends PreparedOperation {
351
406
  readonly cfg: OperationConfig<any, any, any, any, any>;
352
407
  /** The built protocol service, once its layer has been built. */
353
408
  service?: ProtocolShape;
409
+ /** The operation span's facts, from the telemetry traits; built on the first traced call. */
410
+ info?: Telemetry.OperationInfo;
354
411
  }
355
412
 
413
+ const infoOf = (p: Prepared): Telemetry.OperationInfo =>
414
+ (p.info ??= Telemetry.operationInfo(
415
+ p.cfg.telemetry,
416
+ p.cfg.span,
417
+ p.cfg.operationName,
418
+ p.inputAst,
419
+ ));
420
+
356
421
  const stateKey = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/OperationState");
357
422
 
358
423
  // Lazily resolve the operation config + schema ASTs on first call, not at
@@ -375,8 +440,32 @@ const prepare = (state: OperationState): Prepared => {
375
440
  });
376
441
  };
377
442
 
443
+ /**
444
+ * {@link prepare} for the call paths: a config that can't be built (a
445
+ * generated config that throws, a lazy service whose module doesn't match
446
+ * its stub) fails the call with {@link SdkError} instead of crashing it.
447
+ */
448
+ const prepareOr = (state: OperationState): Prepared | SdkError => {
449
+ if (state.prepared) return state.prepared;
450
+ try {
451
+ return prepare(state);
452
+ } catch (cause) {
453
+ return new SdkError({
454
+ message: `the operation could not be loaded: ${cause instanceof Error ? cause.message : String(cause)}`,
455
+ });
456
+ }
457
+ };
458
+
378
459
  const stateOf = (op: unknown): OperationState => (op as Record<symbol, OperationState>)[stateKey]!;
379
460
 
461
+ /**
462
+ * The span facts an operation's calls carry (name, kind, fixed attributes,
463
+ * input rules), as the runtime builds them from its generated config. For
464
+ * tests and tooling.
465
+ */
466
+ export const describeOperation = (op: unknown): Telemetry.OperationInfo =>
467
+ infoOf(prepare(stateOf(op)));
468
+
380
469
  const defineState = (op: unknown, state: OperationState): OperationState => {
381
470
  Object.defineProperty(op, stateKey, { value: state });
382
471
  return state;
@@ -389,27 +478,68 @@ const runWith = (
389
478
  ): Effect.Effect<any, any, any> => {
390
479
  if (protocol.call !== undefined) return protocol.call(p, input);
391
480
  const { cfg, inputAst, outputAst, errors } = p;
392
- return Effect.flatMap(HttpClient.HttpClient, (client) =>
393
- Effect.flatMap(protocol.encode({ input, inputAst, config: cfg }), (request) =>
394
- Effect.flatMap(client.execute(request), (response) =>
481
+ return Effect.withFiber((fiber) => {
482
+ const context = fiber.context as Context.Context<any>;
483
+ const client = Context.get(context, HttpClient.HttpClient);
484
+ return Effect.flatMap(protocol.encode({ input, inputAst, config: cfg }), (request) =>
485
+ Effect.flatMap(Telemetry.execute(context, client, request), (response) =>
395
486
  protocol.decode({ response, outputAst, errors, config: cfg }),
396
487
  ),
397
- ),
398
- );
488
+ );
489
+ });
399
490
  };
400
491
 
401
- const callOperation = (state: OperationState, input: unknown): Effect.Effect<any, any, any> => {
492
+ const callUntraced = (
493
+ state: OperationState,
494
+ input: unknown,
495
+ debug: Telemetry.DebugHooks | undefined,
496
+ ): Effect.Effect<any, any, any> => {
402
497
  // Warm path: the operation is prepared and its protocol built, so the call
403
498
  // is whatever the protocol returns, with no wrapper effects around it.
404
499
  const p = state.prepared;
405
- if (p?.service !== undefined) return applyRetry(runWith(p, p.service, input), p.cfg.retry);
500
+ if (p?.service !== undefined) return applyRetry(runWith(p, p.service, input), p.cfg.retry, debug);
406
501
  return Effect.suspend(() => {
407
- const prepared = prepare(state);
408
- const call = Effect.flatMap(protocolContext(prepared.cfg.protocol), (protocolCtx) => {
409
- const service = (prepared.service = Context.get(protocolCtx, Protocol));
410
- return runWith(prepared, service, input);
411
- });
412
- return applyRetry(call, prepared.cfg.retry);
502
+ const prepared = prepareOr(state);
503
+ if (prepared instanceof SdkError) return Effect.fail(prepared);
504
+ const call = Effect.flatMap(
505
+ debug === undefined
506
+ ? protocolContext(prepared.cfg.protocol)
507
+ : debug.phase("distilled.setup", protocolContext(prepared.cfg.protocol), {
508
+ "distilled.setup.first_call": true,
509
+ }),
510
+ (protocolCtx) => {
511
+ const service = (prepared.service = Context.get(protocolCtx, Protocol));
512
+ return runWith(prepared, service, input);
513
+ },
514
+ );
515
+ return applyRetry(call, prepared.cfg.retry, debug);
516
+ });
517
+ };
518
+
519
+ /**
520
+ * BRAINSTORM: the call in its operation span (recorded only when an
521
+ * exporter is installed), whose stack frame is the caller (captured here,
522
+ * synchronously, while the caller is still on the JS stack).
523
+ */
524
+ const callOperation = (
525
+ state: OperationState,
526
+ input: unknown,
527
+ entry: Function,
528
+ ): Effect.Effect<any, any, any> => {
529
+ const callSite = Telemetry.captureCallSite(entry);
530
+ return Effect.withFiber((fiber) => {
531
+ const debug = fiber.getRef(Telemetry.Debug);
532
+ const prepared = prepareOr(state);
533
+ if (prepared instanceof SdkError) return Effect.fail(prepared);
534
+ return Telemetry.operationSpan(
535
+ fiber,
536
+ debug,
537
+ infoOf(prepared),
538
+ callSite,
539
+ input,
540
+ (sent) => callUntraced(state, sent, debug),
541
+ debug === undefined ? undefined : { input: prepared.inputAst, output: prepared.outputAst },
542
+ );
413
543
  });
414
544
  };
415
545
 
@@ -474,7 +604,7 @@ const OperationProto: object = /*@__PURE__*/ Object.setPrototypeOf(
474
604
  );
475
605
 
476
606
  const makeOperation = (state: OperationState, proto: object): any => {
477
- const fn = (input: unknown) => callOperation(state, input);
607
+ const fn = (input: unknown) => callOperation(state, input, fn);
478
608
  defineState(fn, state);
479
609
  return Object.setPrototypeOf(fn, proto);
480
610
  };
@@ -562,16 +692,28 @@ export interface PaginatedOperationConfig<
562
692
 
563
693
  /** `.pages` / `.items` over any call function (the operation itself or a context-bound one). */
564
694
  const streamsOf = (state: OperationState, call: (input: any) => Effect.Effect<any, any, any>) => {
565
- const pag = () => (prepare(state).cfg as PaginatedOperationConfig<any, any, any, any>).pagination;
566
- // Data operations carry their strategy in the config.
567
- const paginate =
568
- state.strategy ??
569
- (prepare(state).cfg as { strategy?: Pagination.PaginationStrategy }).strategy ??
570
- Pagination.paginateWithDefaults;
571
- const pages = (input: Record<string, unknown>) => paginate(call, input, pag());
572
- const items = (input: Record<string, unknown>) => {
573
- const p = pag();
574
- return p.items ? Pagination.extractItems(pages(input), p.items) : pages(input);
695
+ const pagesOf = (prepared: Prepared, input: Record<string, unknown>) => {
696
+ const cfg = prepared.cfg as PaginatedOperationConfig<any, any, any, any> & {
697
+ strategy?: Pagination.PaginationStrategy;
698
+ };
699
+ // Data operations carry their strategy in the config.
700
+ const paginate = state.strategy ?? cfg.strategy ?? Pagination.paginateWithDefaults;
701
+ return paginate(call, input, cfg.pagination);
702
+ };
703
+ const pages = (input: Record<string, unknown>): Stream.Stream<any, any, any> => {
704
+ const prepared = prepareOr(state);
705
+ return prepared instanceof SdkError ? Stream.fail(prepared) : pagesOf(prepared, input);
706
+ };
707
+ const items = (input: Record<string, unknown>): Stream.Stream<any, any, any> => {
708
+ const prepared = prepareOr(state);
709
+ if (prepared instanceof SdkError) return Stream.fail(prepared);
710
+ const p = (prepared.cfg as PaginatedOperationConfig<any, any, any, any>).pagination;
711
+ if (!p.items) return pagesOf(prepared, input);
712
+ // A bare-array response's schema is its sole member's value
713
+ // (`RawResponseRoot`), so the member `items` names is the page itself.
714
+ return getAnn(prepared.outputAst, rawResponseRootSymbol) !== undefined
715
+ ? Pagination.extractArrayItems(pagesOf(prepared, input))
716
+ : Pagination.extractItems(pagesOf(prepared, input), p.items);
575
717
  };
576
718
  return { pages, items };
577
719
  };
@@ -634,6 +776,114 @@ export function makePaginated<
634
776
 
635
777
  //#endregion
636
778
 
779
+ //#region MakeStreaming
780
+
781
+ /** The message type of a server-streaming output, `{ items: Message[] }`. */
782
+ export type StreamedItem<O> = O extends { readonly items: ReadonlyArray<infer Item> }
783
+ ? Item
784
+ : O extends { readonly items?: ReadonlyArray<infer Item> | undefined }
785
+ ? Item
786
+ : unknown;
787
+
788
+ /**
789
+ * The callable half of a server-streaming operation: the call, which
790
+ * collects the whole stream into `{ items }`, plus `.stream(input)`, which
791
+ * emits each message as it arrives.
792
+ */
793
+ export interface StreamingCall<I, O, E, R, Item> {
794
+ (input: I): Effect.Effect<O, E, R>;
795
+ readonly stream: (input: I) => Stream.Stream<Item, E, R>;
796
+ }
797
+
798
+ /**
799
+ * A server-streaming operation: usable both ways an {@link OperationMethod}
800
+ * is, with `.stream` on both the operation and the requirement-free call
801
+ * function `yield* operation` returns.
802
+ */
803
+ export type StreamingOperationMethod<I, O, E, R, Item = StreamedItem<O>> = Effect.Effect<
804
+ StreamingCall<I, O, E, never, Item>,
805
+ never,
806
+ R
807
+ > &
808
+ StreamingCall<I, O, E, R, Item> &
809
+ OperationSchemas<I, O>;
810
+
811
+ /** `.stream(input)` over an operation's protocol. */
812
+ const streamCall =
813
+ (state: OperationState) =>
814
+ (input: unknown): Stream.Stream<any, any, any> =>
815
+ Stream.unwrap(
816
+ Effect.suspend(() => {
817
+ const prepared = prepareOr(state);
818
+ if (prepared instanceof SdkError) return Effect.succeed(Stream.fail(prepared));
819
+ const run = (service: ProtocolShape) =>
820
+ service.stream === undefined
821
+ ? Stream.fail(
822
+ new SdkError({
823
+ message: `${prepared.cfg.operationName ?? "this operation"}: its protocol can't stream`,
824
+ }),
825
+ )
826
+ : service.stream(prepared, input);
827
+ return prepared.service !== undefined
828
+ ? Effect.succeed(run(prepared.service))
829
+ : Effect.map(protocolContext(prepared.cfg.protocol), (ctx) =>
830
+ run((prepared.service = Context.get(ctx, Protocol))),
831
+ );
832
+ }),
833
+ );
834
+
835
+ const StreamingOperationProto: object = /*@__PURE__*/ Object.create(OperationProto, {
836
+ stream: {
837
+ get(this: any) {
838
+ const fn = streamCall(stateOf(this));
839
+ Object.defineProperty(this, "stream", { value: fn, configurable: true });
840
+ return fn;
841
+ },
842
+ configurable: true,
843
+ },
844
+ // `yield* operation` returns a context-bound call; its `.stream` gets the
845
+ // same fallback (not snapshot) context.
846
+ asEffect: {
847
+ value(this: any) {
848
+ const state = stateOf(this);
849
+ return Effect.map(Effect.context(), (context) => {
850
+ const merge = (current: Context.Context<any>): Context.Context<any> =>
851
+ Context.merge(context, current);
852
+ const call = (input: unknown) => Effect.updateContext(this(input), merge);
853
+ return Object.assign(call, {
854
+ stream: (input: unknown) => Stream.updateContext(streamCall(state)(input), merge),
855
+ });
856
+ });
857
+ },
858
+ configurable: true,
859
+ writable: true,
860
+ },
861
+ });
862
+
863
+ /**
864
+ * Like {@link make}, for a server-streaming RPC whose output is `{ items }`:
865
+ * calling it collects the stream, and `.stream(input)` emits each message as
866
+ * the protocol receives it (see {@link ProtocolShape.stream}).
867
+ */
868
+ export function makeStreaming<
869
+ I extends S.Top,
870
+ O extends S.Top,
871
+ PE,
872
+ PR,
873
+ const E extends readonly ApiErrorClass[] = readonly [],
874
+ >(
875
+ configFn: () => OperationConfig<I, O, PE, PR, E>,
876
+ ): StreamingOperationMethod<
877
+ S.Schema.Type<I>,
878
+ S.Schema.Type<O>,
879
+ InstanceType<E[number]> | PE | HttpClientError.HttpClientError,
880
+ PR | HttpClient.HttpClient
881
+ > {
882
+ return makeOperation({ configFn }, StreamingOperationProto);
883
+ }
884
+
885
+ //#endregion
886
+
637
887
  //#region Data operations
638
888
 
639
889
  /**
@@ -780,11 +1030,13 @@ const dataState = function (this: DataFn): OperationState {
780
1030
  };
781
1031
  let dataProto: object | undefined;
782
1032
  let dataPaginatedProto: object | undefined;
1033
+ let dataStreamingProto: object | undefined;
783
1034
  /**
784
1035
  * While a lazy service loads its full module (see {@link lazyService}), the module's
785
- * definitions go to it instead (kind 0 operation, 1 paginated, 2 error class).
1036
+ * definitions go to it instead (kind 0 operation, 1 paginated, 2 error class,
1037
+ * 3 streaming).
786
1038
  */
787
- let definer: ((fn: DataFn, kind: 0 | 1 | 2) => unknown) | undefined;
1039
+ let definer: ((fn: DataFn, kind: 0 | 1 | 2 | 3) => unknown) | undefined;
788
1040
 
789
1041
  /** Runs `f` with `d` receiving the definitions it evaluates. */
790
1042
  const defining = (d: typeof definer, f: () => void): void => {
@@ -822,15 +1074,26 @@ const asOpPaginated = (fn: DataFn): any =>
822
1074
  })),
823
1075
  );
824
1076
 
1077
+ const asOpStreaming = (fn: DataFn): any =>
1078
+ Object.setPrototypeOf(
1079
+ fn,
1080
+ (dataStreamingProto ??= Object.create(StreamingOperationProto, {
1081
+ [stateKey]: { get: dataState, configurable: true },
1082
+ })),
1083
+ );
1084
+
825
1085
  /** An operation described by data (see the region header). */
826
1086
  export const op = (fn: DataFn): any => (definer ? definer(fn, 0) : asOp(fn));
827
1087
 
828
1088
  /** A paginated operation described by data; its config may name a `strategy`. */
829
1089
  export const opPaginated = (fn: DataFn): any => (definer ? definer(fn, 1) : asOpPaginated(fn));
830
1090
 
1091
+ /** A server-streaming operation described by data. */
1092
+ export const opStreaming = (fn: DataFn): any => (definer ? definer(fn, 3) : asOpStreaming(fn));
1093
+
831
1094
  /** The call path of a data operation. */
832
1095
  export const call = (op: unknown, input: unknown): Effect.Effect<any, any, any> =>
833
- callOperation(stateOf(op), input);
1096
+ callOperation(stateOf(op), input, op as Function);
834
1097
 
835
1098
  /**
836
1099
  * Generated error classes described by data:
@@ -908,7 +1171,7 @@ export const newError = (props: unknown, newTarget: Function | undefined, data:
908
1171
  * which passes its own URL and the namespaces every stub imports.
909
1172
  *
910
1173
  * `kinds` has one letter per operation definition of the full module: `o`
911
- * plain, `p` paginated. While the stub's load evaluates the full module,
1174
+ * plain, `p` paginated, `s` server-streaming. While the stub's load evaluates the full module,
912
1175
  * `op` / `opPaginated` / `error` hand back the stub's placeholders in
913
1176
  * definition order instead of new values, and each placeholder takes the
914
1177
  * data function it stands for: the full module's operations, error lists
@@ -940,7 +1203,10 @@ interface LazyService {
940
1203
  ei: number;
941
1204
  }
942
1205
 
943
- const define = (svc: LazyService, fn: DataFn, kind: 0 | 1 | 2): any => {
1206
+ /** The stub letter of each operation kind (see {@link lazyService}). */
1207
+ const KIND_LETTERS = ["o", "p", "", "s"] as const;
1208
+
1209
+ const define = (svc: LazyService, fn: DataFn, kind: 0 | 1 | 2 | 3): any => {
944
1210
  if (kind === 2) {
945
1211
  const i = svc.ei++;
946
1212
  if (i >= svc.e.length) throw new Error(`distilled: ${svc.spec}: error ${i} has no stub`);
@@ -948,7 +1214,7 @@ const define = (svc: LazyService, fn: DataFn, kind: 0 | 1 | 2): any => {
948
1214
  return svc.e[i];
949
1215
  }
950
1216
  const i = svc.oi++;
951
- if (i >= svc.o.length || (svc.kinds[i] === "p") !== (kind === 1))
1217
+ if (i >= svc.o.length || svc.kinds[i] !== KIND_LETTERS[kind])
952
1218
  throw new Error(`distilled: ${svc.spec}: operation ${i} does not match its stub`);
953
1219
  svc.od![i] = fn;
954
1220
  return svc.o[i];
@@ -1051,12 +1317,17 @@ const sliced = (svc: LazyService): SliceIndex | false => {
1051
1317
  svc.ix = false;
1052
1318
  if (svc.at === undefined || svc.od) return false;
1053
1319
  try {
1320
+ // oxlint-disable-next-line distilled/no-function-constructor -- probes whether the host allows it (a CSP may not)
1054
1321
  Function("");
1055
1322
  const file = fileOf(svc);
1056
1323
  svc.ix = indexOf(file, read({ file }, svc.at, svc.len!));
1057
1324
  svc.od = [];
1058
1325
  svc.ed = [];
1059
- } catch {}
1326
+ } catch {
1327
+ // Code from strings is blocked, or the slice can't be read: load the
1328
+ // whole module instead (`svc.ix` stays `false`).
1329
+ svc.ix = false;
1330
+ }
1060
1331
  return svc.ix;
1061
1332
  };
1062
1333
 
@@ -1160,6 +1431,7 @@ const evaluate = (svc: LazyService, ix: SliceIndex, k: number): any => {
1160
1431
  });
1161
1432
  text += read(ix, at, end! - at);
1162
1433
  } else text = read(ix, start!, end! - start!);
1434
+ // oxlint-disable-next-line distilled/no-function-constructor -- the distilled-lazy loader compiles one declaration of a bundled service
1163
1435
  return Function(...names, `"use strict";return(${text}\n)${url}`)(...values);
1164
1436
  };
1165
1437
 
@@ -1179,6 +1451,7 @@ const compileBody = (
1179
1451
  ): Function => {
1180
1452
  const text = read(ix, start, end - start);
1181
1453
  const keep = names.map((n) => !own.includes(n));
1454
+ // oxlint-disable-next-line distilled/no-function-constructor -- the distilled-lazy loader compiles one declaration of a bundled service
1182
1455
  return Function(
1183
1456
  ...names.filter((_, i) => keep[i]),
1184
1457
  ...own,
@@ -1272,14 +1545,14 @@ export const lazyService = (
1272
1545
  len?: number,
1273
1546
  ): { readonly o: () => any; readonly e: (name: string) => any; readonly E: any } => {
1274
1547
  const svc: LazyService = { url, spec, kinds, ns, at, len, o: [], e: [], oi: 0, ei: 0 };
1275
- if (!primed && at !== undefined && !(globalThis as any).process?.env?.NOPRIME) prime(svc);
1548
+ if (!primed && at !== undefined) prime(svc);
1276
1549
  return {
1277
1550
  o: () => {
1278
- const paginated = kinds[svc.o.length] === "p";
1551
+ const kind = kinds[svc.o.length];
1279
1552
  const f: DataFn = function op(x) {
1280
1553
  return x === D ? dataOf(svc, 0, svc.o.indexOf(op))(D) : call(op, x);
1281
1554
  };
1282
- svc.o.push(paginated ? asOpPaginated(f) : asOp(f));
1555
+ svc.o.push(kind === "p" ? asOpPaginated(f) : kind === "s" ? asOpStreaming(f) : asOp(f));
1283
1556
  return f;
1284
1557
  },
1285
1558
  e: (name: string) => {
package/src/category.ts CHANGED
@@ -320,19 +320,19 @@ const makeCatcher =
320
320
  * )
321
321
  * ```
322
322
  */
323
- export const catchErrors =
324
- <Categories extends Category[], A2, E2, R2>(
325
- ...args: [...Categories, (err: any) => Effect.Effect<A2, E2, R2>]
326
- ) =>
327
- <A, E, R>(effect: Effect.Effect<A, E, R>) => {
328
- const handler = args.pop() as (err: any) => Effect.Effect<A2, E2, R2>;
329
- const categories = args as unknown as Categories;
330
- return Effect.catchIf(
323
+ export const catchErrors = <Categories extends Category[], A2, E2, R2>(
324
+ ...args: [...Categories, (err: any) => Effect.Effect<A2, E2, R2>]
325
+ ) => {
326
+ // Split once, without mutating `args`, so one catcher can be reused.
327
+ const handler = args[args.length - 1] as (err: any) => Effect.Effect<A2, E2, R2>;
328
+ const categories = args.slice(0, -1) as unknown as Categories;
329
+ return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
330
+ Effect.catchIf(
331
331
  effect,
332
332
  (e) => categories.some((cat) => hasCategory(e, cat)),
333
333
  handler,
334
334
  ) as Effect.Effect<A | A2, E | E2, R | R2>;
335
- };
335
+ };
336
336
 
337
337
  // Alias for convenience
338
338
  export { catchErrors as catch };
@@ -364,19 +364,18 @@ export const catchDependencyViolationError = /*@__PURE__*/ makeCatcher(Dependenc
364
364
  * )
365
365
  * ```
366
366
  */
367
- export const catchCategory =
368
- <E, const Categories extends Array<AllKeys<E>>, A2, E2, R2>(
369
- ...args: [
370
- ...Categories,
371
- f: (err: ExtractAll<E, Categories[number]>) => Effect.Effect<A2, E2, R2>,
372
- ]
373
- ) =>
374
- <A, R>(
367
+ export const catchCategory = <E, const Categories extends Array<AllKeys<E>>, A2, E2, R2>(
368
+ ...args: [...Categories, f: (err: ExtractAll<E, Categories[number]>) => Effect.Effect<A2, E2, R2>]
369
+ ) => {
370
+ // Split once, without mutating `args`, so one catcher can be reused.
371
+ const f = args[args.length - 1] as (
372
+ err: ExtractAll<E, Categories[number]>,
373
+ ) => Effect.Effect<A2, E2, R2>;
374
+ const categories = args.slice(0, -1) as unknown as Categories;
375
+ return <A, R>(
375
376
  effect: Effect.Effect<A, E, R>,
376
- ): Effect.Effect<A | A2, E2 | Exclude<E, ExtractAll<E, Categories[number]>>, R | R2> => {
377
- const f = args.pop()!;
378
- const categories = args;
379
- return Effect.catchIf(
377
+ ): Effect.Effect<A | A2, E2 | Exclude<E, ExtractAll<E, Categories[number]>>, R | R2> =>
378
+ Effect.catchIf(
380
379
  effect,
381
380
  (e) => {
382
381
  if (Predicate.isObject(e) && Predicate.hasProperty(categoriesKey)(e)) {
@@ -392,4 +391,4 @@ export const catchCategory =
392
391
  // @ts-expect-error - type narrowing limitation
393
392
  (e) => f(e),
394
393
  ) as any;
395
- };
394
+ };