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

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 (321) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -0
  3. package/lib/_bundle/aws.js +2 -0
  4. package/lib/_bundle/aws.js.map +1 -0
  5. package/lib/_bundle/base.js +5 -0
  6. package/lib/_bundle/base.js.map +1 -0
  7. package/lib/_bundle/graphql.js +3 -0
  8. package/lib/_bundle/graphql.js.map +1 -0
  9. package/lib/_bundle/grpc.js +3 -0
  10. package/lib/_bundle/grpc.js.map +1 -0
  11. package/lib/_bundle/rest.js +2 -0
  12. package/lib/_bundle/rest.js.map +1 -0
  13. package/lib/_bundle/xml.js +4 -0
  14. package/lib/_bundle/xml.js.map +1 -0
  15. package/lib/annotations.d.ts +17 -0
  16. package/lib/annotations.d.ts.map +1 -0
  17. package/lib/annotations.js +2 -0
  18. package/lib/annotations.js.map +1 -0
  19. package/lib/api.d.ts +220 -51
  20. package/lib/api.d.ts.map +1 -1
  21. package/lib/api.js +1 -178
  22. package/lib/category.d.ts +19 -16
  23. package/lib/category.d.ts.map +1 -1
  24. package/lib/category.js +1 -280
  25. package/lib/chunks.d.ts +3 -0
  26. package/lib/chunks.d.ts.map +1 -0
  27. package/lib/chunks.js +1 -0
  28. package/lib/config.d.ts +81 -0
  29. package/lib/config.d.ts.map +1 -0
  30. package/lib/config.js +1 -0
  31. package/lib/crypto.d.ts +76 -0
  32. package/lib/crypto.d.ts.map +1 -0
  33. package/lib/crypto.js +1 -0
  34. package/lib/error-category.d.ts +1 -1
  35. package/lib/error-category.d.ts.map +1 -1
  36. package/lib/error-category.js +1 -46
  37. package/lib/errors.d.ts +99 -74
  38. package/lib/errors.d.ts.map +1 -1
  39. package/lib/errors.js +1 -186
  40. package/lib/graphql.d.ts +420 -0
  41. package/lib/graphql.d.ts.map +1 -0
  42. package/lib/graphql.js +1 -0
  43. package/lib/graphql.types.d.ts +11 -0
  44. package/lib/graphql.types.d.ts.map +1 -0
  45. package/lib/graphql.types.js +1 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  47. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  48. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  49. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  51. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  53. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  54. package/lib/grpc-transport-node-http2.d.ts +19 -0
  55. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  56. package/lib/grpc-transport-node-http2.js +2 -0
  57. package/lib/grpc-transport-node-http2.js.map +1 -0
  58. package/lib/grpc-transport.d.ts +111 -0
  59. package/lib/grpc-transport.d.ts.map +1 -0
  60. package/lib/grpc-transport.js +1 -0
  61. package/lib/hpack.d.ts +34 -0
  62. package/lib/hpack.d.ts.map +1 -0
  63. package/lib/hpack.js +2 -0
  64. package/lib/hpack.js.map +1 -0
  65. package/lib/index.d.ts +32 -0
  66. package/lib/index.d.ts.map +1 -0
  67. package/lib/index.js +17 -0
  68. package/lib/max-message-bytes.d.ts +42 -0
  69. package/lib/max-message-bytes.d.ts.map +1 -0
  70. package/lib/max-message-bytes.js +2 -0
  71. package/lib/max-message-bytes.js.map +1 -0
  72. package/lib/ndjson.d.ts +3 -0
  73. package/lib/ndjson.d.ts.map +1 -0
  74. package/lib/ndjson.js +2 -0
  75. package/lib/ndjson.js.map +1 -0
  76. package/lib/pagination.d.ts +105 -25
  77. package/lib/pagination.d.ts.map +1 -1
  78. package/lib/pagination.js +1 -182
  79. package/lib/plain-values.d.ts +21 -0
  80. package/lib/plain-values.d.ts.map +1 -0
  81. package/lib/plain-values.js +2 -0
  82. package/lib/plain-values.js.map +1 -0
  83. package/lib/protobuf.d.ts +85 -0
  84. package/lib/protobuf.d.ts.map +1 -0
  85. package/lib/protobuf.js +1 -0
  86. package/lib/protocol-grpc.d.ts +123 -0
  87. package/lib/protocol-grpc.d.ts.map +1 -0
  88. package/lib/protocol-grpc.js +1 -0
  89. package/lib/protocol-http.d.ts +206 -25
  90. package/lib/protocol-http.d.ts.map +1 -1
  91. package/lib/protocol-http.js +1 -554
  92. package/lib/protocol-rest.d.ts +258 -64
  93. package/lib/protocol-rest.d.ts.map +1 -1
  94. package/lib/protocol-rest.js +1 -242
  95. package/lib/protocol.d.ts +113 -0
  96. package/lib/protocol.d.ts.map +1 -0
  97. package/lib/protocol.js +0 -0
  98. package/lib/query.d.ts +29 -0
  99. package/lib/query.d.ts.map +1 -0
  100. package/lib/query.js +1 -0
  101. package/lib/response-validation-strict.d.ts +48 -0
  102. package/lib/response-validation-strict.d.ts.map +1 -0
  103. package/lib/response-validation-strict.js +1 -0
  104. package/lib/response-validation.d.ts +86 -0
  105. package/lib/response-validation.d.ts.map +1 -0
  106. package/lib/response-validation.js +1 -0
  107. package/lib/retry-after.d.ts +4 -4
  108. package/lib/retry-after.d.ts.map +1 -1
  109. package/lib/retry-after.js +1 -112
  110. package/lib/retry-state.d.ts +26 -0
  111. package/lib/retry-state.d.ts.map +1 -0
  112. package/lib/retry-state.js +2 -0
  113. package/lib/retry-state.js.map +1 -0
  114. package/lib/retry.d.ts +141 -42
  115. package/lib/retry.d.ts.map +1 -1
  116. package/lib/retry.js +1 -210
  117. package/lib/schema-lite-impl.d.ts +179 -0
  118. package/lib/schema-lite-impl.d.ts.map +1 -0
  119. package/lib/schema-lite-impl.js +1 -0
  120. package/lib/schema-lite-typed.d.ts +41 -0
  121. package/lib/schema-lite-typed.d.ts.map +1 -0
  122. package/lib/schema-lite-typed.js +1 -0
  123. package/lib/schema-lite.d.ts +41 -0
  124. package/lib/schema-lite.d.ts.map +1 -0
  125. package/lib/schema-lite.js +1 -0
  126. package/lib/schema.d.ts +21 -7
  127. package/lib/schema.d.ts.map +1 -1
  128. package/lib/schema.js +1 -48
  129. package/lib/sdk-error.d.ts +31 -0
  130. package/lib/sdk-error.d.ts.map +1 -0
  131. package/lib/sdk-error.js +1 -0
  132. package/lib/send.d.ts +37 -0
  133. package/lib/send.d.ts.map +1 -0
  134. package/lib/send.js +2 -0
  135. package/lib/send.js.map +1 -0
  136. package/lib/sensitive.d.ts +28 -0
  137. package/lib/sensitive.d.ts.map +1 -0
  138. package/lib/sensitive.js +2 -0
  139. package/lib/sensitive.js.map +1 -0
  140. package/lib/telemetry-debug.d.ts +6 -0
  141. package/lib/telemetry-debug.d.ts.map +1 -0
  142. package/lib/telemetry-debug.js +2 -0
  143. package/lib/telemetry-debug.js.map +1 -0
  144. package/lib/telemetry-hooks.d.ts +32 -0
  145. package/lib/telemetry-hooks.d.ts.map +1 -0
  146. package/lib/telemetry-hooks.js +2 -0
  147. package/lib/telemetry-hooks.js.map +1 -0
  148. package/lib/telemetry-host-rules.d.ts +23 -0
  149. package/lib/telemetry-host-rules.d.ts.map +1 -0
  150. package/lib/telemetry-host-rules.js +2 -0
  151. package/lib/telemetry-host-rules.js.map +1 -0
  152. package/lib/telemetry-lambda-context.d.ts +17 -0
  153. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  154. package/lib/telemetry-lambda-context.js +2 -0
  155. package/lib/telemetry-lambda-context.js.map +1 -0
  156. package/lib/telemetry-message-context.d.ts +52 -0
  157. package/lib/telemetry-message-context.d.ts.map +1 -0
  158. package/lib/telemetry-message-context.js +2 -0
  159. package/lib/telemetry-message-context.js.map +1 -0
  160. package/lib/telemetry-metrics.d.ts +6 -0
  161. package/lib/telemetry-metrics.d.ts.map +1 -0
  162. package/lib/telemetry-metrics.js +2 -0
  163. package/lib/telemetry-metrics.js.map +1 -0
  164. package/lib/telemetry-name-template.d.ts +13 -0
  165. package/lib/telemetry-name-template.d.ts.map +1 -0
  166. package/lib/telemetry-name-template.js +2 -0
  167. package/lib/telemetry-name-template.js.map +1 -0
  168. package/lib/telemetry-stream.d.ts +11 -0
  169. package/lib/telemetry-stream.d.ts.map +1 -0
  170. package/lib/telemetry-stream.js +2 -0
  171. package/lib/telemetry-stream.js.map +1 -0
  172. package/lib/telemetry-xray.d.ts +28 -0
  173. package/lib/telemetry-xray.d.ts.map +1 -0
  174. package/lib/telemetry-xray.js +2 -0
  175. package/lib/telemetry-xray.js.map +1 -0
  176. package/lib/telemetry.d.ts +317 -0
  177. package/lib/telemetry.d.ts.map +1 -0
  178. package/lib/telemetry.js +3 -0
  179. package/lib/telemetry.js.map +1 -0
  180. package/lib/token-cache.d.ts +31 -0
  181. package/lib/token-cache.d.ts.map +1 -0
  182. package/lib/token-cache.js +2 -0
  183. package/lib/token-cache.js.map +1 -0
  184. package/lib/trait.d.ts +94 -20
  185. package/lib/trait.d.ts.map +1 -1
  186. package/lib/trait.js +1 -107
  187. package/lib/unknown-error.d.ts +18 -0
  188. package/lib/unknown-error.d.ts.map +1 -0
  189. package/lib/unknown-error.js +1 -0
  190. package/lib/xml.d.ts +44 -0
  191. package/lib/xml.d.ts.map +1 -0
  192. package/lib/xml.js +1 -0
  193. package/package.json +13 -13
  194. package/src/annotations.ts +53 -0
  195. package/src/api.ts +1597 -234
  196. package/src/category.ts +97 -134
  197. package/src/chunks.ts +30 -0
  198. package/src/config.ts +261 -0
  199. package/src/crypto.ts +202 -0
  200. package/src/error-category.ts +16 -29
  201. package/src/errors.ts +99 -77
  202. package/src/graphql.ts +1817 -0
  203. package/src/graphql.types.ts +120 -0
  204. package/src/grpc-transport-cloudflare-http2.ts +569 -0
  205. package/src/grpc-transport-cloudflare-sockets.ts +368 -0
  206. package/src/grpc-transport-node-http2.ts +307 -0
  207. package/src/grpc-transport.ts +287 -0
  208. package/src/hpack.ts +331 -0
  209. package/src/index.ts +31 -0
  210. package/src/max-message-bytes.ts +58 -0
  211. package/src/ndjson.ts +55 -0
  212. package/src/pagination.ts +379 -94
  213. package/src/plain-values.ts +70 -0
  214. package/src/protobuf.ts +1367 -0
  215. package/src/protocol-grpc.ts +811 -0
  216. package/src/protocol-http.ts +1045 -371
  217. package/src/protocol-rest.ts +908 -255
  218. package/src/protocol.ts +150 -0
  219. package/src/query.ts +39 -0
  220. package/src/response-validation-strict.ts +333 -0
  221. package/src/response-validation.ts +161 -0
  222. package/src/retry-after.ts +8 -14
  223. package/src/retry-state.ts +105 -0
  224. package/src/retry.ts +260 -145
  225. package/src/schema-lite-impl.ts +621 -0
  226. package/src/schema-lite-typed.ts +44 -0
  227. package/src/schema-lite.ts +45 -0
  228. package/src/schema.ts +259 -15
  229. package/src/sdk-error.ts +37 -0
  230. package/src/send.ts +156 -0
  231. package/src/sensitive.ts +188 -0
  232. package/src/telemetry-debug.ts +179 -0
  233. package/src/telemetry-hooks.ts +33 -0
  234. package/src/telemetry-host-rules.ts +39 -0
  235. package/src/telemetry-lambda-context.ts +46 -0
  236. package/src/telemetry-message-context.ts +170 -0
  237. package/src/telemetry-metrics.ts +69 -0
  238. package/src/telemetry-name-template.ts +26 -0
  239. package/src/telemetry-stream.ts +100 -0
  240. package/src/telemetry-xray.ts +66 -0
  241. package/src/telemetry.ts +800 -0
  242. package/src/token-cache.ts +117 -0
  243. package/src/trait.ts +139 -67
  244. package/src/unknown-error.ts +38 -0
  245. package/src/xml.ts +346 -0
  246. package/lib/api.js.map +0 -1
  247. package/lib/category.js.map +0 -1
  248. package/lib/codegen/cli.d.ts +0 -29
  249. package/lib/codegen/cli.d.ts.map +0 -1
  250. package/lib/codegen/cli.js +0 -165
  251. package/lib/codegen/cli.js.map +0 -1
  252. package/lib/codegen/emit.d.ts +0 -129
  253. package/lib/codegen/emit.d.ts.map +0 -1
  254. package/lib/codegen/emit.js +0 -105
  255. package/lib/codegen/emit.js.map +0 -1
  256. package/lib/codegen/format.d.ts +0 -23
  257. package/lib/codegen/format.d.ts.map +0 -1
  258. package/lib/codegen/format.js +0 -28
  259. package/lib/codegen/format.js.map +0 -1
  260. package/lib/codegen/generator.d.ts +0 -334
  261. package/lib/codegen/generator.d.ts.map +0 -1
  262. package/lib/codegen/generator.js +0 -691
  263. package/lib/codegen/generator.js.map +0 -1
  264. package/lib/codegen/graph.d.ts +0 -36
  265. package/lib/codegen/graph.d.ts.map +0 -1
  266. package/lib/codegen/graph.js +0 -136
  267. package/lib/codegen/graph.js.map +0 -1
  268. package/lib/codegen/members.d.ts +0 -25
  269. package/lib/codegen/members.d.ts.map +0 -1
  270. package/lib/codegen/members.js +0 -55
  271. package/lib/codegen/members.js.map +0 -1
  272. package/lib/codegen/naming.d.ts +0 -29
  273. package/lib/codegen/naming.d.ts.map +0 -1
  274. package/lib/codegen/naming.js +0 -74
  275. package/lib/codegen/naming.js.map +0 -1
  276. package/lib/codegen/openapi-cli.d.ts +0 -38
  277. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  278. package/lib/codegen/openapi-cli.js +0 -107
  279. package/lib/codegen/openapi-cli.js.map +0 -1
  280. package/lib/codegen/openapi.d.ts +0 -115
  281. package/lib/codegen/openapi.d.ts.map +0 -1
  282. package/lib/codegen/openapi.js +0 -1220
  283. package/lib/codegen/openapi.js.map +0 -1
  284. package/lib/codegen/operations.d.ts +0 -24
  285. package/lib/codegen/operations.d.ts.map +0 -1
  286. package/lib/codegen/operations.js +0 -56
  287. package/lib/codegen/operations.js.map +0 -1
  288. package/lib/codegen/pagination.d.ts +0 -39
  289. package/lib/codegen/pagination.d.ts.map +0 -1
  290. package/lib/codegen/pagination.js +0 -33
  291. package/lib/codegen/pagination.js.map +0 -1
  292. package/lib/codegen/prelude.d.ts +0 -15
  293. package/lib/codegen/prelude.d.ts.map +0 -1
  294. package/lib/codegen/prelude.js +0 -60
  295. package/lib/codegen/prelude.js.map +0 -1
  296. package/lib/error-category.js.map +0 -1
  297. package/lib/errors.js.map +0 -1
  298. package/lib/json-patch.d.ts +0 -44
  299. package/lib/json-patch.d.ts.map +0 -1
  300. package/lib/json-patch.js +0 -174
  301. package/lib/json-patch.js.map +0 -1
  302. package/lib/pagination.js.map +0 -1
  303. package/lib/protocol-http.js.map +0 -1
  304. package/lib/protocol-rest.js.map +0 -1
  305. package/lib/retry-after.js.map +0 -1
  306. package/lib/retry.js.map +0 -1
  307. package/lib/schema.js.map +0 -1
  308. package/lib/trait.js.map +0 -1
  309. package/src/codegen/cli.ts +0 -268
  310. package/src/codegen/emit.ts +0 -207
  311. package/src/codegen/format.ts +0 -47
  312. package/src/codegen/generator.ts +0 -1153
  313. package/src/codegen/graph.ts +0 -151
  314. package/src/codegen/members.ts +0 -71
  315. package/src/codegen/naming.ts +0 -86
  316. package/src/codegen/openapi-cli.ts +0 -166
  317. package/src/codegen/openapi.ts +0 -1450
  318. package/src/codegen/operations.ts +0 -76
  319. package/src/codegen/pagination.ts +0 -71
  320. package/src/codegen/prelude.ts +0 -70
  321. package/src/json-patch.ts +0 -222
package/src/api.ts CHANGED
@@ -1,20 +1,38 @@
1
+ import * as Cause from "effect/Cause";
1
2
  import * as Context from "effect/Context";
3
+ import * as Duration from "effect/Duration";
2
4
  import * as Effect from "effect/Effect";
3
- import * as Layer from "effect/Layer";
5
+ import * as Exit from "effect/Exit";
6
+ import * as HttpClient from "effect/http/HttpClient";
7
+ import type * as HttpClientError from "effect/http/HttpClientError";
8
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
4
9
  import * as Option from "effect/Option";
5
- import * as S from "effect/Schema";
6
- import type * as AST from "effect/SchemaAST";
7
10
  import { pipeArguments } from "effect/Pipeable";
8
11
  import * as Ref from "effect/Ref";
9
- import * as Scope from "effect/Scope";
10
- import type * as Stream from "effect/Stream";
12
+ import * as References from "effect/References";
13
+ import * as S from "effect/Schema";
14
+ import type * as AST from "effect/SchemaAST";
15
+ import * as Stream from "effect/Stream";
11
16
  import { SingleShotGen } from "effect/Utils";
17
+ import { getAnn, getProps, rawResponseRootSymbol } from "./annotations.ts";
18
+ import { isThrottling } from "./category.ts";
12
19
  import * as Pagination from "./pagination.ts";
13
- import { makeDefault, type Policy as RetryPolicy } from "./retry.ts";
14
- import * as HttpClient from "effect/unstable/http/HttpClient";
15
- import type * as HttpClientError from "effect/unstable/http/HttpClientError";
16
- import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
17
- import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
20
+ import type { Operation, Protocol } from "./protocol.ts";
21
+ import { takeLastRequest } from "./retry-state.ts";
22
+ import {
23
+ type Backoff,
24
+ BOUNDED_HINT_MAX_EXTRA_MS,
25
+ defaultOptions,
26
+ type Options as RetryOptions,
27
+ type Policy as RetryPolicy,
28
+ type RetryOverride,
29
+ defaultWith,
30
+ resolveServerRetryHintCapMs,
31
+ } from "./retry.ts";
32
+ import { SdkError } from "./sdk-error.ts";
33
+ import * as Send from "./send.ts";
34
+ import * as Telemetry from "./telemetry.ts";
35
+ import { idempotencyTokenSymbol } from "./trait.ts";
18
36
 
19
37
  //#region Protocol
20
38
 
@@ -42,43 +60,55 @@ export interface ProtocolOperationConfig {
42
60
  */
43
61
  readonly endpointHostPrefix?: string;
44
62
  readonly pagination?: Pagination.PaginatedTrait;
63
+ /**
64
+ * How a server-streaming operation's body is framed, for protocols that
65
+ * read it per operation (core/protocol-rest takes a `StreamFraming`, e.g.
66
+ * `ndjson` from core/ndjson). Set only on the operations that stream, so
67
+ * programs that call none never bundle the framing.
68
+ */
69
+ readonly framing?: unknown;
70
+ /**
71
+ * One frame of `.stream()`, for an operation whose plain call has its own
72
+ * output and streams only when its input asks (see
73
+ * {@link OperationConfig.streamInput}). Protocols decode each frame
74
+ * against it instead of an element of the output's `items`.
75
+ */
76
+ readonly items?: S.Top;
45
77
  }
46
78
 
47
79
  /**
48
- * The Protocol service knows how to turn a value into an HTTP request using
49
- * only the input schema's trait annotations, and how to turn a response back
50
- * into an output value using the output schema's trait annotations.
51
- *
52
- * Swap implementations by providing a different `Layer<Protocol>`.
80
+ * One operation as a protocol's {@link Protocol.call} sees it. Built once per
81
+ * operation on its first call; the same object is passed on every call.
53
82
  */
54
- export class Protocol extends Context.Service<
55
- Protocol,
56
- {
57
- readonly encode: (args: {
58
- readonly input: unknown;
59
- readonly inputAst: AST.AST;
60
- /** The operation's config (memoized per operation — see {@link ProtocolOperationConfig}). */
61
- readonly config: ProtocolOperationConfig;
62
- }) => Effect.Effect<HttpClientRequest.HttpClientRequest>;
63
- readonly decode: (args: {
64
- readonly response: HttpClientResponse.HttpClientResponse;
65
- readonly outputAst: AST.AST;
66
- /**
67
- * The operation's declared error classes (from `OperationConfig.errors`).
68
- * Protocols use these to surface wire failures as the operation's typed
69
- * errors — e.g. by consulting matcher metadata stamped on the class.
70
- */
71
- readonly errors: ReadonlyArray<ApiErrorClass>;
72
- /** The operation's config (memoized per operation — see {@link ProtocolOperationConfig}). */
73
- readonly config: ProtocolOperationConfig;
74
- }) => Effect.Effect<unknown>;
75
- }
76
- >()("Protocol") {}
83
+ export interface PreparedOperation {
84
+ readonly config: ProtocolOperationConfig;
85
+ readonly inputAst: AST.AST;
86
+ readonly outputAst: AST.AST;
87
+ readonly errors: ReadonlyArray<ApiErrorClass>;
88
+ /** Per-operation slot owned by the operation's protocol (compiled codecs). */
89
+ compiled?: unknown;
90
+ }
77
91
 
78
92
  //#endregion
79
93
 
80
94
  //#region Make
81
95
 
96
+ /**
97
+ * Run `f` on the value of `effect` -- directly when `effect` is already a
98
+ * successful `Exit` (e.g. a `Credentials` service holding
99
+ * `Effect.succeed(config)`), so a resolved value costs no fiber step.
100
+ */
101
+ export const withValue = <A, E, R, B, E2, R2>(
102
+ effect: Effect.Effect<A, E, R>,
103
+ f: (a: A) => Effect.Effect<B, E2, R2>,
104
+ ): Effect.Effect<B, E | E2, R | R2> =>
105
+ Exit.isExit(effect)
106
+ ? Exit.isSuccess(effect)
107
+ ? f(effect.value as A)
108
+ : // A failed Exit never produces its value.
109
+ (effect as Exit.Exit<never, E>)
110
+ : Effect.flatMap(effect, f);
111
+
82
112
  export type ApiErrorClass = {
83
113
  new (...args: any[]): {
84
114
  readonly _tag: string;
@@ -87,11 +117,11 @@ export type ApiErrorClass = {
87
117
  };
88
118
 
89
119
  /**
90
- * The shape of a generated SDK operation — usable two ways (mirrors the
120
+ * The shape of a generated SDK operation -- usable two ways (mirrors the
91
121
  * distilled repo's OperationMethod):
92
122
  *
93
- * 1. Direct call: `yield* operation(input)` — an Effect with requirements.
94
- * 2. Yield first: `const fn = yield* operation` — captures the current
123
+ * 1. Direct call: `yield* operation(input)` -- an Effect with requirements.
124
+ * 2. Yield first: `const fn = yield* operation` -- captures the current
95
125
  * context and returns a requirement-free call function.
96
126
  *
97
127
  * Generated service files annotate every exported operation with this type
@@ -103,11 +133,22 @@ export type OperationMethod<I, O, E, R> = Effect.Effect<
103
133
  never,
104
134
  R
105
135
  > &
106
- ((input: I) => Effect.Effect<O, E, R>);
136
+ ((input: I) => Effect.Effect<O, E, R>) &
137
+ OperationSchemas<I, O>;
138
+
139
+ /**
140
+ * An operation's request and response schemas, built on first access.
141
+ * Generated modules export operations, errors and types; the schemas
142
+ * themselves are module-private, so this is how to reach them as values.
143
+ */
144
+ export interface OperationSchemas<I, O> {
145
+ readonly input: S.Codec<I, any>;
146
+ readonly output: S.Codec<O, any>;
147
+ }
107
148
 
108
149
  // NOTE: request/response ASTs are handed to the protocol RAW (Suspend nodes
109
150
  // included). Pre-resolving Suspends here would drop annotations that sit on
110
- // intermediate nodes — e.g. a bare-payload response whose payload type is
151
+ // intermediate nodes -- e.g. a bare-payload response whose payload type is
111
152
  // itself a suspended schema carries its EnvelopePayloadRoot marker on the
112
153
  // inner Suspend, and unwrapping it silently degrades decode to the struct
113
154
  // path. The protocol helpers (core/protocol-http getAnn/getProps) descend
@@ -115,37 +156,11 @@ export type OperationMethod<I, O, E, R> = Effect.Effect<
115
156
  // nothing extra.
116
157
 
117
158
  /**
118
- * Protocol layers are built once per process and shared by every operation
119
- * call (keyed by layer value identity — generated operations all reference the
120
- * same module-level layer const). The build runs against a process-lifetime
121
- * scope, and concurrent first calls are deduplicated through a private
122
- * MemoMap.
123
- *
124
- * Contract for protocol implementations: the layer build must not capture
125
- * per-call context. Anything call-dependent — credentials, per-request
126
- * options — must be resolved inside `encode`/`decode`, which execute on the
127
- * calling fiber and therefore see the caller's services on every request.
128
- */
129
- const protocolMemoMap = Layer.makeMemoMapUnsafe();
130
- const protocolScope = Scope.makeUnsafe();
131
- const protocolContexts = new WeakMap<
132
- Layer.Layer<Protocol, any, any>,
133
- Context.Context<Protocol>
134
- >();
135
-
136
- const protocolContext = <PE, PR>(
137
- layer: Layer.Layer<Protocol, PE, PR>,
138
- ): Effect.Effect<Context.Context<Protocol>, PE, PR> => {
139
- const cached = protocolContexts.get(layer);
140
- if (cached) return Effect.succeed(cached);
141
- return Effect.map(
142
- Layer.buildWithMemoMap(layer, protocolMemoMap, protocolScope),
143
- (ctx) => {
144
- protocolContexts.set(layer, ctx);
145
- return ctx;
146
- },
147
- );
148
- };
159
+ * The operation's protocol, kept on `prepared` from its first call on (the
160
+ * warm path reads it there).
161
+ */
162
+ const protocolOf = (prepared: Prepared): Effect.Effect<Protocol<any, any>> =>
163
+ Effect.succeed((prepared.service = prepared.cfg.protocol));
149
164
 
150
165
  export interface OperationConfig<
151
166
  I extends S.Top,
@@ -153,23 +168,38 @@ export interface OperationConfig<
153
168
  PE,
154
169
  PR,
155
170
  E extends readonly ApiErrorClass[] = readonly ApiErrorClass[],
171
+ SE extends readonly ApiErrorClass[] = readonly ApiErrorClass[],
156
172
  > {
157
173
  input?: I;
158
174
  output?: O;
175
+ /** The errors declared on the operation: only this operation returns them. */
159
176
  errors?: E;
160
177
  /**
161
- * The protocol layer that knows how to encode/decode this operation's wire
162
- * format. Built once per process and shared across all operations that
163
- * reference the same layer value — it must resolve call-dependent services
164
- * (credentials etc.) inside encode/decode, not at build time.
178
+ * The errors declared on the operation's service: the same list on every
179
+ * operation of the service. The protocol matches a failed response
180
+ * against the operation's classes, then these.
165
181
  */
166
- protocol: Layer.Layer<Protocol, PE, PR>;
182
+ serviceErrors?: SE;
183
+ /**
184
+ * What encodes and decodes this operation's wire format: a protocol
185
+ * (core/protocol), an object whose type states the errors the protocol
186
+ * declares (`PE`) and what its methods read (`PR`), so the operation's
187
+ * type gets them from the protocol. It resolves call-dependent services
188
+ * (credentials etc.) inside encode/decode, on the calling fiber.
189
+ */
190
+ protocol: Protocol<PE, PR>;
167
191
  /**
168
192
  * SDK-specific retry service tag (see `core/retry`). When provided and the
169
193
  * caller's context carries a policy under this tag, every call is retried
170
194
  * per that policy (e.g. `Layer.succeed(Cloudflare.Retry.Retry, factory)`).
171
195
  */
172
196
  retry?: Context.Key<any, RetryPolicy>;
197
+ /**
198
+ * The operation's `distilled.retry#policy` trait (the service's, with the
199
+ * operation's on top): numbers that replace the default policy's when the
200
+ * caller's context carries no policy. A caller's policy ignores it.
201
+ */
202
+ retryPolicy?: RetryOverride;
173
203
  /**
174
204
  * The wire operation name for RPC-style protocols (see
175
205
  * {@link ProtocolOperationConfig.operationName}).
@@ -180,141 +210,588 @@ export interface OperationConfig<
180
210
  * {@link ProtocolOperationConfig.endpointHostPrefix}).
181
211
  */
182
212
  endpointHostPrefix?: string;
213
+ /** The service's `com.distilled.telemetry#service` trait (a module const). */
214
+ telemetry?: Telemetry.ServiceTelemetry;
215
+ /**
216
+ * The operation's `com.distilled.telemetry#operation` trait, with its
217
+ * input rules; only what differs from the service's rules when it names
218
+ * its `op` (a string is just the op).
219
+ */
220
+ span?: Telemetry.SpanConfig | string;
221
+ /** The body framing of a server-streaming operation (see {@link ProtocolOperationConfig.framing}). */
222
+ framing?: unknown;
223
+ /** One frame of `.stream()` (see {@link ProtocolOperationConfig.items}). */
224
+ items?: S.Top;
225
+ /**
226
+ * Input members `.stream()` sets over the caller's, for an operation that
227
+ * streams only when its input asks (Boat's `executeSandboxCommand` with
228
+ * `stream: true`). The plain call sends the caller's input as given.
229
+ */
230
+ streamInput?: Readonly<Record<string, unknown>>;
183
231
  }
184
232
 
185
233
  /**
186
234
  * Wrap one operation call with the caller-provided retry policy, if the
187
235
  * operation declares a retry tag and the context carries a policy for it.
188
236
  */
237
+ /**
238
+ * Delay before retry `attempt` (0-based) under `b`, in milliseconds, or
239
+ * `undefined` when the server asked for a wait over the hint cap.
240
+ * `boundedHintMs` is the response's `x-amz-retry-after` /
241
+ * `x-distilled-retry-after`.
242
+ */
243
+ const backoffDelay = (
244
+ b: Backoff,
245
+ attempt: number,
246
+ error: unknown,
247
+ boundedHintMs: number | undefined,
248
+ ): Effect.Effect<number | undefined> => {
249
+ const throttling = isThrottling(error);
250
+ let t: number;
251
+ if (b.fullJitter) {
252
+ const base = throttling && b.throttlingBaseMs !== undefined ? b.throttlingBaseMs : b.baseMs;
253
+ t = Math.random() * Math.min(base * b.factor ** attempt, b.capMs);
254
+ } else {
255
+ const base = Math.min(b.baseMs * b.factor ** attempt, b.capMs);
256
+ const floored =
257
+ b.minThrottleMs !== undefined && base < b.minThrottleMs && throttling
258
+ ? b.minThrottleMs
259
+ : base;
260
+ t = floored + Math.random() * (b.jitterMs ?? 0);
261
+ }
262
+ if (!b.serverHint) return Effect.succeed(t);
263
+ if (boundedHintMs !== undefined) {
264
+ return Effect.succeed(Math.min(Math.max(boundedHintMs, t), t + BOUNDED_HINT_MAX_EXTRA_MS));
265
+ }
266
+ const hint = (error as { retryAfter?: unknown } | null)?.retryAfter;
267
+ if (!Duration.isDuration(hint)) return Effect.succeed(t);
268
+ const hintMs = Duration.toMillis(hint);
269
+ return Effect.map(resolveServerRetryHintCapMs(), (capMs) =>
270
+ hintMs > capMs ? undefined : Math.max(t, hintMs),
271
+ );
272
+ };
273
+
274
+ const NO_BACKOFF: Backoff = { baseMs: 0, factor: 1, capMs: 0 };
275
+
276
+ /**
277
+ * BRAINSTORM: the sleep before retry `attempt` (1-based). The retry is
278
+ * recorded on the operation span; debug mode also makes the sleep a span.
279
+ */
280
+ const backoffSleep = (
281
+ delay: Duration.Input,
282
+ attempt: number,
283
+ error: unknown,
284
+ ): Effect.Effect<void> =>
285
+ Effect.withFiber((fiber) => {
286
+ const context = fiber.context as Context.Context<any>;
287
+ const delayMs = typeof delay === "number" ? delay : 0;
288
+ Telemetry.retried(context, attempt, error, delayMs);
289
+ return Telemetry.phase(context, "distilled.retry.backoff", Effect.sleep(delay), {
290
+ "distilled.retry.attempt": attempt,
291
+ "distilled.retry.delay_ms": Math.round(delayMs),
292
+ "distilled.retry.reason": (error as { _tag?: string } | null)?._tag,
293
+ });
294
+ });
295
+
296
+ /**
297
+ * Wrap one operation call with the caller-provided retry policy, if the
298
+ * operation declares a retry tag. The call runs once with no retry
299
+ * machinery; the policy is read only after a failure. Built-in policies are
300
+ * {@link Backoff} data run by a small loop; a caller-supplied `schedule`
301
+ * runs under `Effect.retry`, with the first failure replayed as attempt one
302
+ * so delays and counts match running the whole call under it.
303
+ *
304
+ * With `TelemetryDebug.layer`, every try runs as `Attempt` span n.
305
+ */
189
306
  const applyRetry = (
190
307
  base: Effect.Effect<any, any, any>,
191
- retryKey: Context.Key<any, RetryPolicy> | undefined,
192
- ): Effect.Effect<any, any, any> =>
193
- retryKey === undefined
194
- ? base
195
- : Effect.flatMap(Effect.serviceOption(retryKey), (opt) =>
196
- Effect.gen(function* () {
197
- const lastError = yield* Ref.make<unknown>(undefined);
198
- // No policy in context → makeDefault (transient/throttling/server
199
- // errors, capped exponential backoff + jitter, honors server
200
- // retryAfter hints). Mirrors the distilled client.
201
- const policy = Option.isSome(opt) ? opt.value : makeDefault;
202
- const opts =
203
- typeof policy === "function" ? policy(lastError) : policy;
204
- if (!opts.while) return yield* base;
205
- return yield* base.pipe(
206
- Effect.tapError((e) => Ref.set(lastError, e)),
207
- Effect.retry({
208
- while: (e: unknown) => opts.while!(e),
209
- ...(opts.schedule ? { schedule: opts.schedule as any } : {}),
210
- }),
308
+ cfg: OperationConfig<any, any, any, any, any>,
309
+ debug: Telemetry.DebugHooks | undefined,
310
+ ): Effect.Effect<any, any, any> => {
311
+ const retryKey = cfg.retry;
312
+ const first = debug === undefined ? base : debug.attempt(base, 1);
313
+ return retryKey === undefined
314
+ ? first
315
+ : Effect.catch(first, (error) =>
316
+ Effect.flatMap(Effect.serviceOption(retryKey), (opt) => {
317
+ if (Option.isNone(opt)) {
318
+ const options =
319
+ cfg.retryPolicy === undefined ? defaultOptions : defaultWith(cfg.retryPolicy);
320
+ return retryWith(base, options, error, debug);
321
+ }
322
+ const policy = opt.value;
323
+ if (typeof policy !== "function") return retryWith(base, policy, error, debug);
324
+ return Effect.flatMap(Ref.make<unknown>(error), (lastError) =>
325
+ retryWith(
326
+ Effect.tapError(base, (e) => Ref.set(lastError, e)),
327
+ policy(lastError),
328
+ error,
329
+ debug,
330
+ ),
211
331
  );
212
332
  }),
213
333
  );
334
+ };
214
335
 
215
- export function make<
216
- I extends S.Top,
217
- O extends S.Top,
218
- PE,
219
- PR,
220
- const E extends readonly ApiErrorClass[] = readonly [],
221
- >(
222
- configFn: () => OperationConfig<I, O, PE, PR, E>,
223
- ): OperationMethod<
224
- S.Schema.Type<I>,
225
- S.Schema.Type<O>,
226
- InstanceType<E[number]> | PE | HttpClientError.HttpClientError,
227
- PR | HttpClient.HttpClient
228
- > {
229
- // Lazily resolve the operation config + schema ASTs on first call, not at
230
- // module-load time. Generated SDKs wrap each request/response schema in
231
- // `Schema.suspend(() => ...)`; forcing them here (rather than when the
232
- // `export const` is evaluated) keeps importing a service module cheap and
233
- // only pays the schema-construction cost for operations that are actually
234
- // called. Memoized so subsequent calls are free.
235
- interface Prepared {
236
- readonly cfg: OperationConfig<I, O, PE, PR, E>;
237
- readonly inputAst: AST.AST;
238
- readonly outputAst: AST.AST;
239
- }
240
- let prepared: Prepared | undefined;
241
- const prepare = (): Prepared => {
242
- if (prepared) return prepared;
243
- const cfg = configFn();
244
- prepared = {
245
- cfg,
246
- inputAst: cfg.input!.ast,
247
- outputAst: cfg.output!.ast,
336
+ const retryWith = (
337
+ base: Effect.Effect<any, any, any>,
338
+ opts: RetryOptions,
339
+ error: unknown,
340
+ debug: Telemetry.DebugHooks | undefined,
341
+ ): Effect.Effect<any, any, any> => {
342
+ const keepGoing = opts.while;
343
+ if (!keepGoing || !keepGoing(error)) return Effect.fail(error);
344
+ // Attempt n (2, 3, ...) of the call.
345
+ const again = (n: number) => (debug === undefined ? base : debug.attempt(base, n));
346
+ if (opts.schedule) {
347
+ // Drive the caller's schedule through its own `step`, as Effect.retry
348
+ // does, without importing the Schedule module into every bundle: the
349
+ // first failure is the schedule's first input; a step that fails means
350
+ // the schedule is done.
351
+ const schedule = opts.schedule as unknown as {
352
+ readonly step: Effect.Effect<
353
+ (now: number, input: unknown) => Effect.Effect<readonly [unknown, Duration.Input], unknown>
354
+ >;
248
355
  };
249
- return prepared;
250
- };
251
- const fn = (input: unknown) =>
252
- Effect.suspend(() => {
253
- const { cfg, inputAst, outputAst } = prepare();
254
- const call = Effect.flatMap(
255
- protocolContext(cfg.protocol),
256
- (protocolCtx) =>
257
- Effect.gen(function* () {
258
- const protocol = yield* Protocol;
259
- const client = yield* HttpClient.HttpClient;
260
- const request = yield* protocol.encode({
261
- input,
262
- inputAst,
263
- config: cfg,
264
- });
265
- const response = yield* client.execute(request);
266
- return yield* protocol.decode({
267
- response,
268
- outputAst,
269
- errors: cfg.errors ?? [],
270
- config: cfg,
356
+ return Effect.flatMap(schedule.step, (next) => {
357
+ let attempt = 0;
358
+ // A request whose body could be read only once is never sent again.
359
+ const loop = (e: unknown): Effect.Effect<any, any, any> =>
360
+ !keepGoing(e) || takeLastRequest().oneShot
361
+ ? Effect.fail(e)
362
+ : Effect.clockWith((clock) =>
363
+ Effect.matchEffect(next(clock.currentTimeMillisUnsafe(), e), {
364
+ onFailure: () => Effect.fail(e),
365
+ onSuccess: ([, delay]) =>
366
+ Effect.flatMap(backoffSleep(delay, ++attempt, e), () =>
367
+ Effect.catch(again(attempt + 1), loop),
368
+ ),
369
+ }),
370
+ );
371
+ return loop(error);
372
+ });
373
+ }
374
+ const b = opts.backoff ?? NO_BACKOFF;
375
+ const budget = b.budget;
376
+ const step = (e: unknown, n: number): Effect.Effect<any, any, any> => {
377
+ if (!keepGoing(e) || (b.maxRetries !== undefined && n >= b.maxRetries)) {
378
+ return Effect.fail(e);
379
+ }
380
+ // Read now, on the fiber that sent the request that failed.
381
+ const last = takeLastRequest();
382
+ // Its body could be read only once: a retry would send it empty.
383
+ if (last.oneShot) return Effect.fail(e);
384
+ return Effect.flatMap(backoffDelay(b, n, e, last.hintMs), (ms) => {
385
+ if (ms === undefined) return Effect.fail(e);
386
+ // No host: the request went out without `send` (`./send.ts`), so no
387
+ // success would ever refill a bucket. Such calls are not budgeted.
388
+ const budgeted = budget !== undefined && last.host !== "";
389
+ const cost = budgeted ? budget.withdraw(last.host, isThrottling(e)) : undefined;
390
+ if (budgeted && cost === undefined) {
391
+ return b.longPoll ? Effect.flatMap(Effect.sleep(ms), () => Effect.fail(e)) : Effect.fail(e);
392
+ }
393
+ const next =
394
+ cost === undefined
395
+ ? again(n + 2)
396
+ : Effect.map(again(n + 2), (value) => {
397
+ budget!.refund(last.host, cost);
398
+ return value;
271
399
  });
272
- }).pipe(Effect.provideContext(protocolCtx)),
400
+ return Effect.flatMap(backoffSleep(ms, n + 1, e), () =>
401
+ Effect.catch(next, (failed) => step(failed, n + 1)),
273
402
  );
274
- return applyRetry(call, cfg.retry);
275
403
  });
404
+ };
405
+ return step(error, 0);
406
+ };
407
+
408
+ /**
409
+ * Per-operation state. Kept to one small object per exported operation:
410
+ * importing a service module creates every operation in it, so anything
411
+ * allocated here is paid hundreds of times per import (EC2 has 807
412
+ * operations) whether or not the operation is ever called.
413
+ */
414
+ interface OperationState {
415
+ readonly configFn: () => OperationConfig<any, any, any, any, any>;
416
+ prepared?: Prepared;
417
+ /** Paginated operations only. */
418
+ readonly strategy?: Pagination.PaginationStrategy;
419
+ }
420
+
421
+ interface Prepared extends Operation {
422
+ readonly cfg: OperationConfig<any, any, any, any, any>;
423
+ /** The operation's protocol, from its first call on (see {@link protocolOf}). */
424
+ service?: Protocol<any, any>;
425
+ /** The operation span's facts, from the telemetry traits. */
426
+ readonly info: Telemetry.OperationInfo;
427
+ /** Input members marked `T.IdempotencyToken()`, with their format; read on the first call. */
428
+ idempotencyTokens?: ReadonlyArray<readonly [name: string, format: unknown]>;
429
+ }
430
+
431
+ /** A UUIDv7 (RFC 9562): 48-bit Unix milliseconds, then version, variant and random bits. */
432
+ const uuidv7 = (): string => {
433
+ const b = globalThis.crypto.getRandomValues(new Uint8Array(16));
434
+ const ms = Date.now();
435
+ const high = Math.floor(ms / 2 ** 32);
436
+ const low = ms % 2 ** 32;
437
+ b[0] = high >>> 8;
438
+ b[1] = high & 0xff;
439
+ b[2] = low >>> 24;
440
+ b[3] = (low >>> 16) & 0xff;
441
+ b[4] = (low >>> 8) & 0xff;
442
+ b[5] = low & 0xff;
443
+ b[6] = (b[6]! & 0x0f) | 0x70;
444
+ b[8] = (b[8]! & 0x3f) | 0x80;
445
+ let hex = "";
446
+ for (const x of b) hex += x.toString(16).padStart(2, "0");
447
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
448
+ };
449
+
450
+ /**
451
+ * `input` with each missing idempotency token set to a new UUID. Called once
452
+ * per call, outside the retry, so every attempt sends the same token; the
453
+ * caller's own value and object are left as they are.
454
+ */
455
+ const withIdempotencyTokens = (p: Prepared, input: unknown): unknown => {
456
+ const tokens = (p.idempotencyTokens ??= getProps(p.inputAst).flatMap((prop) => {
457
+ const format = getAnn(prop.type, idempotencyTokenSymbol);
458
+ return typeof prop.name === "string" && format !== undefined
459
+ ? [[prop.name, format] as const]
460
+ : [];
461
+ }));
462
+ if (tokens.length === 0 || input === null || typeof input !== "object") return input;
463
+ let filled: Record<string, unknown> | undefined;
464
+ for (const [name, format] of tokens) {
465
+ if ((input as Record<string, unknown>)[name] === undefined) {
466
+ filled ??= { ...(input as Record<string, unknown>) };
467
+ // `globalThis.crypto`, not `node:crypto`, so this runs in browsers too.
468
+ filled[name] = format === "uuidv7" ? uuidv7() : globalThis.crypto.randomUUID();
469
+ }
470
+ }
471
+ return filled ?? input;
472
+ };
473
+
474
+ const stateKey = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/OperationState");
475
+
476
+ // Lazily resolve the operation config + schema ASTs on first call, not at
477
+ // module-load time. Generated SDKs wrap each request/response schema in
478
+ // `Schema.suspend(() => ...)`; forcing them here (rather than when the
479
+ // `export const` is evaluated) keeps importing a service module cheap and
480
+ // only pays the schema-construction cost for operations that are actually
481
+ // called. Memoized so subsequent calls are free.
482
+ const prepare = (state: OperationState): Prepared => {
483
+ if (state.prepared) return state.prepared;
484
+ const cfg = state.configFn();
485
+ const inputAst: AST.AST = cfg.input!.ast;
486
+ return (state.prepared = {
487
+ cfg,
488
+ config: cfg,
489
+ inputAst,
490
+ info: Telemetry.operationInfo(cfg.telemetry, cfg.span, cfg.operationName, inputAst),
491
+ outputAst: cfg.output!.ast,
492
+ // What the protocol matches a failed response against: the operation's
493
+ // declared classes, then its service's. The protocol receives them as
494
+ // `DeclaredErrorClass` (core/protocol).
495
+ errors:
496
+ cfg.serviceErrors === undefined
497
+ ? (cfg.errors ?? [])
498
+ : [...(cfg.errors ?? []), ...cfg.serviceErrors],
499
+ compiled: undefined,
500
+ service: undefined,
501
+ });
502
+ };
503
+
504
+ /**
505
+ * {@link prepare} for the call paths: a config that can't be built (a
506
+ * generated config that throws, a lazy service whose module doesn't match
507
+ * its stub) fails the call with {@link SdkError} instead of crashing it.
508
+ */
509
+ const prepareOr = (state: OperationState): Prepared | SdkError => {
510
+ if (state.prepared) return state.prepared;
511
+ try {
512
+ return prepare(state);
513
+ } catch (cause) {
514
+ return new SdkError({
515
+ message: `the operation could not be loaded: ${cause instanceof Error ? cause.message : String(cause)}`,
516
+ });
517
+ }
518
+ };
519
+
520
+ const stateOf = (op: unknown): OperationState => (op as Record<symbol, OperationState>)[stateKey]!;
276
521
 
277
- // Make the operation itself yieldable: `yield* operation` captures the
278
- // current context and returns a requirement-free call function (mirrors
279
- // the distilled repo's OperationMethod).
280
- const Proto = {
522
+ /**
523
+ * The defect boundary: what a failed operation fails with. Nothing thrown
524
+ * while an operation runs crashes the fiber: a `throw` in a plain helper
525
+ * under its protocol's `encode`, `decode`, `call` or `stream`, a
526
+ * `JSON.parse`, a property read on a `null` the spec says is an object. It
527
+ * becomes the failure of an {@link SdkError} that names the operation and
528
+ * what was thrown, and carries the thrown value as its `cause`. Any other
529
+ * cause (a typed failure, an interrupt) fails as it is.
530
+ *
531
+ * With a `callSite`, the failure also gets the operation as a stack frame
532
+ * at the caller's line, so `Cause.pretty` prints
533
+ * `at S3.GetObject (user.ts:12:5)`; no stack-frame context is provided per
534
+ * call.
535
+ *
536
+ * A call that succeeds pays no Effect step of its own for the boundary: the
537
+ * places that run an operation (the call, `.stream()`, `.pages()` and
538
+ * `.items()`, {@link encodeRequest}) come here from the one failure handler
539
+ * around them.
540
+ */
541
+ const failed = (
542
+ state: OperationState,
543
+ cause: Cause.Cause<unknown>,
544
+ callSite?: (() => string | undefined) | undefined,
545
+ ): Effect.Effect<never, unknown> => {
546
+ // Not loaded: nothing of the operation ran.
547
+ const prepared = state.prepared;
548
+ if (prepared === undefined) return Effect.failCause(cause);
549
+ const name = prepared.info.name;
550
+ const die = cause.reasons.find(Cause.isDieReason);
551
+ if (die !== undefined) {
552
+ const error = new SdkError({ message: `${name} threw: ${String(die.defect)}` });
553
+ error.cause = die.defect;
554
+ cause = Cause.fail(error);
555
+ }
556
+ if (callSite === undefined) return Effect.failCause(cause);
557
+ return Effect.withFiber((fiber) =>
558
+ Effect.failCause(
559
+ Cause.annotate(
560
+ cause,
561
+ Context.make(Cause.StackTrace, {
562
+ name,
563
+ stack: callSite,
564
+ parent:
565
+ Context.getOrUndefined(Cause.annotations(cause), Cause.StackTrace) ??
566
+ fiber.getRef(References.CurrentStackFrame),
567
+ }),
568
+ { overwrite: true },
569
+ ),
570
+ ),
571
+ );
572
+ };
573
+
574
+ /**
575
+ * The span facts an operation's calls carry (name, kind, fixed attributes,
576
+ * input rules), as the runtime builds them from its generated config. For
577
+ * tests and tooling.
578
+ */
579
+ export const describeOperation = (op: unknown): Telemetry.OperationInfo =>
580
+ prepare(stateOf(op)).info;
581
+
582
+ /**
583
+ * The HTTP request a call to `op` with `input` would send, built by the
584
+ * operation's protocol (`Protocol.encode`) and not sent: no retry, no span,
585
+ * no response. It fails as the call would before sending (bad input,
586
+ * credentials, endpoint), or with {@link SdkError} when the operation can't
587
+ * be loaded; the operation's type does not tell those failures from a
588
+ * response's, so the error is `unknown`. Presigning builds on it.
589
+ */
590
+ export const encodeRequest = <I, O, E, R>(
591
+ op: OperationMethod<I, O, E, R>,
592
+ input: I,
593
+ ): Effect.Effect<HttpClientRequest.HttpClientRequest, unknown, R> =>
594
+ Effect.suspend(() => {
595
+ const state = stateOf(op) as OperationState | undefined;
596
+ if (state === undefined) return Effect.fail(new SdkError({ message: "not an operation" }));
597
+ const prepared = prepareOr(state);
598
+ if (prepared instanceof SdkError) return Effect.fail(prepared);
599
+ const encode = (service: Protocol<any, any>) =>
600
+ Effect.catchCause(
601
+ Effect.suspend(() =>
602
+ service.encode({
603
+ input: withIdempotencyTokens(prepared, input),
604
+ inputAst: prepared.inputAst,
605
+ config: prepared.cfg,
606
+ }),
607
+ ),
608
+ (cause) => failed(state, cause),
609
+ );
610
+ if (prepared.service !== undefined) return encode(prepared.service);
611
+ return Effect.flatMap(protocolOf(prepared), encode);
612
+ });
613
+
614
+ const defineState = (op: unknown, state: OperationState): OperationState => {
615
+ Object.defineProperty(op, stateKey, { value: state });
616
+ return state;
617
+ };
618
+
619
+ const runWith = (
620
+ p: Prepared,
621
+ protocol: Protocol<any, any>,
622
+ input: unknown,
623
+ ): Effect.Effect<any, any, any> => {
624
+ if (protocol.call !== undefined) return protocol.call(p, input);
625
+ const { cfg, inputAst, outputAst, errors } = p;
626
+ return Effect.withFiber((fiber) => {
627
+ const context = fiber.context as Context.Context<any>;
628
+ const client = Context.get(context, HttpClient.HttpClient);
629
+ return Effect.flatMap(protocol.encode({ input, inputAst, config: cfg }), (request) =>
630
+ Effect.flatMap(Send.send(context, client, request), (response) =>
631
+ protocol.decode({ response, outputAst, errors, config: cfg }),
632
+ ),
633
+ );
634
+ });
635
+ };
636
+
637
+ const callUntraced = (
638
+ p: Prepared,
639
+ input: unknown,
640
+ debug: Telemetry.DebugHooks | undefined,
641
+ ): Effect.Effect<any, any, any> => {
642
+ // Warm path: the operation has its protocol, so the call is whatever the
643
+ // protocol returns, with no wrapper effects around it.
644
+ if (p.service !== undefined) {
645
+ return applyRetry(runWith(p, p.service, withIdempotencyTokens(p, input)), p.cfg, debug);
646
+ }
647
+ return Effect.suspend(() => {
648
+ const callInput = withIdempotencyTokens(p, input);
649
+ // The retry wraps only `runWith`, as on the warm path, so a protocol's
650
+ // `call` runs once per call.
651
+ return Effect.flatMap(
652
+ debug === undefined
653
+ ? protocolOf(p)
654
+ : debug.phase("distilled.setup", protocolOf(p), {
655
+ "distilled.setup.first_call": true,
656
+ }),
657
+ (service) => applyRetry(runWith(p, service, callInput), p.cfg, debug),
658
+ );
659
+ });
660
+ };
661
+
662
+ /**
663
+ * BRAINSTORM: the call in its operation span (recorded only when an
664
+ * exporter is installed), whose stack frame is the caller (captured here,
665
+ * synchronously, while the caller is still on the JS stack).
666
+ *
667
+ * The one `catchCause` around the call is where every failed call ends up
668
+ * ({@link failed}). The whole call runs under it, the part that runs before
669
+ * any Effect of the protocol does included.
670
+ */
671
+ const callOperation = (
672
+ state: OperationState,
673
+ input: unknown,
674
+ entry: Function,
675
+ ): Effect.Effect<any, any, any> => {
676
+ const callSite = Telemetry.captureCallSite(entry);
677
+ return Effect.catchCause(
678
+ Effect.withFiber((fiber) => {
679
+ const debug = fiber.getRef(Telemetry.Debug);
680
+ const prepared = prepareOr(state);
681
+ if (prepared instanceof SdkError) return Effect.fail(prepared);
682
+ return Telemetry.operationSpan(
683
+ fiber,
684
+ debug,
685
+ prepared.info,
686
+ callSite,
687
+ input,
688
+ (sent) => callUntraced(prepared, sent, debug),
689
+ debug === undefined ? undefined : { input: prepared.inputAst, output: prepared.outputAst },
690
+ );
691
+ }),
692
+ (cause) => failed(state, cause, callSite),
693
+ );
694
+ };
695
+
696
+ /**
697
+ * `const fn = yield* operation`: a requirement-free call function over the
698
+ * current context. The captured context is a FALLBACK, not a snapshot:
699
+ * entries present on the calling fiber at call time win, so per-call
700
+ * overrides -- e.g. providing `Endpoint` with a discovered data-plane address
701
+ * around one invocation -- take effect instead of being shadowed by the
702
+ * context captured at yield time.
703
+ */
704
+ const bindContext = (op: (input: unknown) => Effect.Effect<any, any, any>) =>
705
+ Effect.map(
706
+ Effect.context(),
707
+ (context) => (input: unknown) =>
708
+ // `Context` is contravariant, so `Context<never>` is not assignable
709
+ // to the `Context<any>` updateContext expects -- the widening cast is
710
+ // sound (the merge only ever adds entries).
711
+ Effect.updateContext(op(input), (current): Context.Context<any> =>
712
+ Context.merge(context, current),
713
+ ),
714
+ );
715
+
716
+ /**
717
+ * Shared by every operation function (its prototype; it inherits from
718
+ * `Function.prototype`, so operations stay ordinary callables). Makes the
719
+ * operation yieldable -- `yield* operation` returns a requirement-free call
720
+ * function, mirroring the distilled repo's OperationMethod -- and carries the
721
+ * debug/introspection surface (`op.input` / `.output` / `.errors` /
722
+ * `.operationName` / `.pagination`) as lazy getters, so importing a service
723
+ * module doesn't force its suspended schemas.
724
+ */
725
+ const OperationProto: object = /*@__PURE__*/ Object.setPrototypeOf(
726
+ {
281
727
  [Symbol.iterator](this: any) {
282
728
  return new SingleShotGen(this.asEffect());
283
729
  },
284
730
  pipe(this: any) {
285
731
  return pipeArguments(this.asEffect(), arguments);
286
732
  },
287
- asEffect() {
288
- return Effect.map(
289
- Effect.context(),
290
- (context) => (input: unknown) =>
291
- Effect.provideContext(fn(input), context),
292
- );
733
+ asEffect(this: any) {
734
+ return bindContext(this);
293
735
  },
294
- };
295
- Object.assign(fn, Proto);
296
-
297
- // Debug/introspection surface carried over from the distilled client:
298
- // the operation's metadata is readable off the exported callable
299
- // (e.g. `iam.listRoles.input` / `.output` / `.errors` / `.operationName`
300
- // / `.pagination`). Lazy getters, so importing a service module doesn't
301
- // force its suspended schemas.
302
- Object.defineProperties(fn, {
303
- input: { get: () => prepare().cfg.input, configurable: true },
304
- output: { get: () => prepare().cfg.output, configurable: true },
305
- errors: { get: () => prepare().cfg.errors ?? [], configurable: true },
306
- operationName: {
307
- get: () => prepare().cfg.operationName,
308
- configurable: true,
736
+ get input() {
737
+ return prepare(stateOf(this)).cfg.input;
309
738
  },
310
- pagination: {
311
- get: () =>
312
- (prepare().cfg as PaginatedOperationConfig<I, O, PE, PR, E>).pagination,
313
- configurable: true,
739
+ get output() {
740
+ return prepare(stateOf(this)).cfg.output;
314
741
  },
315
- });
742
+ get errors() {
743
+ return prepare(stateOf(this)).cfg.errors ?? [];
744
+ },
745
+ get operationName() {
746
+ return prepare(stateOf(this)).cfg.operationName;
747
+ },
748
+ get pagination() {
749
+ return (prepare(stateOf(this)).cfg as PaginatedOperationConfig<any, any, any, any>)
750
+ .pagination;
751
+ },
752
+ },
753
+ Function.prototype,
754
+ );
755
+
756
+ const makeOperation = (state: OperationState, proto: object): any => {
757
+ const fn = (input: unknown) => callOperation(state, input, fn);
758
+ defineState(fn, state);
759
+ return Object.setPrototypeOf(fn, proto);
760
+ };
316
761
 
317
- return fn as any;
762
+ /**
763
+ * What an operation `make` builds can fail with: its own errors, its
764
+ * service's, its protocol's, the HTTP client's, and {@link SdkError}, which
765
+ * `make` itself fails with when the operation's config can't be loaded or
766
+ * its protocol can't stream.
767
+ */
768
+ export type MadeError<
769
+ E extends readonly ApiErrorClass[],
770
+ SE extends readonly ApiErrorClass[],
771
+ PE,
772
+ > =
773
+ | InstanceType<E[number]>
774
+ | InstanceType<SE[number]>
775
+ | PE
776
+ | HttpClientError.HttpClientError
777
+ | SdkError;
778
+
779
+ export function make<
780
+ I extends S.Top,
781
+ O extends S.Top,
782
+ PE,
783
+ PR,
784
+ const E extends readonly ApiErrorClass[] = readonly [],
785
+ const SE extends readonly ApiErrorClass[] = readonly [],
786
+ >(
787
+ configFn: () => OperationConfig<I, O, PE, PR, E, SE>,
788
+ ): OperationMethod<
789
+ S.Schema.Type<I>,
790
+ S.Schema.Type<O>,
791
+ MadeError<E, SE, PE>,
792
+ PR | HttpClient.HttpClient
793
+ > {
794
+ return makeOperation({ configFn }, OperationProto);
318
795
  }
319
796
 
320
797
  //#endregion
@@ -326,7 +803,7 @@ export function make<
326
803
  * element of the page response itself, or of its `result` member.
327
804
  *
328
805
  * It can only see shapes it was taught, so any other envelope
329
- * (`{ branches: […] }`, `{ data: […] }`, …) lands on `unknown` — which is
806
+ * (`{ branches: [...] }`, `{ data: [...] }`, ...) lands on `unknown` -- which is
330
807
  * why generators pass the item type EXPLICITLY as
331
808
  * {@link PaginatedOperationMethod}'s `Item` argument, resolved from the
332
809
  * pagination trait's `items` path against the response shape. This default
@@ -346,7 +823,7 @@ export type PaginatedItem<A> =
346
823
  * `.pages(input)` streaming every page response and `.items(input)` streaming
347
824
  * the individual items across pages.
348
825
  *
349
- * Used twice in {@link PaginatedOperationMethod} — once with the operation's
826
+ * Used twice in {@link PaginatedOperationMethod} -- once with the operation's
350
827
  * requirements (`R`) for the direct-call style, once with `R = never` for the
351
828
  * value `yield* operation` hands back, which has the caller's context baked in.
352
829
  */
@@ -358,18 +835,17 @@ export interface PaginatedCall<I, O, E, R, Item> {
358
835
 
359
836
  /**
360
837
  * A paginated operation: usable both ways an {@link OperationMethod} is, with
361
- * `.pages` / `.items` on BOTH — the operation object for
838
+ * `.pages` / `.items` on BOTH -- the operation object for
362
839
  * `yield* op.items(input)`, and the requirement-free call function for
363
840
  * `const op = yield* operation; yield* op.items(input)` (distilled #145).
364
841
  */
365
- export type PaginatedOperationMethod<
366
- I,
367
- O,
368
- E,
369
- R,
370
- Item = PaginatedItem<O>,
371
- > = Effect.Effect<PaginatedCall<I, O, E, never, Item>, never, R> &
372
- PaginatedCall<I, O, E, R, Item>;
842
+ export type PaginatedOperationMethod<I, O, E, R, Item = PaginatedItem<O>> = Effect.Effect<
843
+ PaginatedCall<I, O, E, never, Item>,
844
+ never,
845
+ R
846
+ > &
847
+ PaginatedCall<I, O, E, R, Item> &
848
+ OperationSchemas<I, O>;
373
849
 
374
850
  export interface PaginatedOperationConfig<
375
851
  I extends S.Top,
@@ -377,11 +853,82 @@ export interface PaginatedOperationConfig<
377
853
  PE,
378
854
  PR,
379
855
  E extends readonly ApiErrorClass[] = readonly ApiErrorClass[],
380
- > extends OperationConfig<I, O, PE, PR, E> {
856
+ SE extends readonly ApiErrorClass[] = readonly ApiErrorClass[],
857
+ > extends OperationConfig<I, O, PE, PR, E, SE> {
381
858
  /** How to advance between pages (mirrors the `smithy.api#paginated` trait). */
382
859
  pagination: Pagination.PaginatedTrait;
383
860
  }
384
861
 
862
+ /** `.pages` / `.items` over any call function (the operation itself or a context-bound one). */
863
+ const streamsOf = (state: OperationState, call: (input: any) => Effect.Effect<any, any, any>) => {
864
+ // The defect boundary of a stream of pages (see `failed`): each page is a
865
+ // call with its own, and this one is for the code that runs between two
866
+ // pages (the strategy that reads the next token, the items of a page).
867
+ // Each pull runs under the handler: `Stream.catchCause` would do the same
868
+ // and adds about 300 bytes to every bundle with a paginated operation.
869
+ const guarded = (make: () => Stream.Stream<any, any, any>): Stream.Stream<any, any, any> =>
870
+ Stream.transformPull(Stream.suspend(make), (pull) =>
871
+ Effect.succeed(Effect.catchCause(pull, (cause) => failed(state, cause))),
872
+ );
873
+ const pagesOf = (prepared: Prepared, input: Record<string, unknown>) => {
874
+ const cfg = prepared.cfg as PaginatedOperationConfig<any, any, any, any> & {
875
+ strategy?: Pagination.PaginationStrategy;
876
+ };
877
+ // Data operations carry their strategy in the config.
878
+ const paginate = state.strategy ?? cfg.strategy ?? Pagination.paginateWithDefaults;
879
+ return paginate(call, input, cfg.pagination);
880
+ };
881
+ const pages = (input: Record<string, unknown>): Stream.Stream<any, any, any> =>
882
+ guarded(() => {
883
+ const prepared = prepareOr(state);
884
+ return prepared instanceof SdkError ? Stream.fail(prepared) : pagesOf(prepared, input);
885
+ });
886
+ const items = (input: Record<string, unknown>): Stream.Stream<any, any, any> =>
887
+ guarded(() => {
888
+ const prepared = prepareOr(state);
889
+ if (prepared instanceof SdkError) return Stream.fail(prepared);
890
+ const p = (prepared.cfg as PaginatedOperationConfig<any, any, any, any>).pagination;
891
+ if (!p.items) return pagesOf(prepared, input);
892
+ // A bare-array response's schema is its sole member's value
893
+ // (`RawResponseRoot`), so the member `items` names is the page itself.
894
+ return getAnn(prepared.outputAst, rawResponseRootSymbol) !== undefined
895
+ ? Pagination.extractArrayItems(pagesOf(prepared, input))
896
+ : Pagination.extractItems(pagesOf(prepared, input), p.items);
897
+ });
898
+ return { pages, items };
899
+ };
900
+
901
+ /**
902
+ * `.pages` / `.items` are getters that build the stream functions on first
903
+ * access and cache them on the operation, so they cost nothing until used
904
+ * and stay detachable (`const { items } = op` works).
905
+ */
906
+ const streamGetter = (name: "pages" | "items") =>
907
+ function (this: any) {
908
+ const fns = streamsOf(stateOf(this), this);
909
+ Object.defineProperties(this, {
910
+ pages: { value: fns.pages, configurable: true },
911
+ items: { value: fns.items, configurable: true },
912
+ });
913
+ return fns[name];
914
+ };
915
+
916
+ const PaginatedOperationProto: object = /*@__PURE__*/ Object.create(OperationProto, {
917
+ pages: { get: /*@__PURE__*/ streamGetter("pages"), configurable: true },
918
+ items: { get: /*@__PURE__*/ streamGetter("items"), configurable: true },
919
+ // `yield* operation` returns a fresh context-bound function; give it
920
+ // `.pages` / `.items` too (distilled #145). Same fallback (not snapshot)
921
+ // semantics as the plain operation.
922
+ asEffect: {
923
+ value(this: any) {
924
+ const state = stateOf(this);
925
+ return Effect.map(bindContext(this), (call) => Object.assign(call, streamsOf(state, call)));
926
+ },
927
+ configurable: true,
928
+ writable: true,
929
+ },
930
+ });
931
+
385
932
  /**
386
933
  * Like {@link make}, plus `.pages()` / `.items()` streaming built on the
387
934
  * operation's pagination trait. The SDK can pass a provider-specific
@@ -395,52 +942,868 @@ export function makePaginated<
395
942
  PE,
396
943
  PR,
397
944
  const E extends readonly ApiErrorClass[] = readonly [],
945
+ const SE extends readonly ApiErrorClass[] = readonly [],
398
946
  >(
399
- configFn: () => PaginatedOperationConfig<I, O, PE, PR, E>,
947
+ configFn: () => PaginatedOperationConfig<I, O, PE, PR, E, SE>,
400
948
  strategy?: Pagination.PaginationStrategy,
401
949
  ): PaginatedOperationMethod<
402
950
  S.Schema.Type<I>,
403
951
  S.Schema.Type<O>,
404
- InstanceType<E[number]> | PE | HttpClientError.HttpClientError,
952
+ MadeError<E, SE, PE>,
405
953
  PR | HttpClient.HttpClient
406
954
  > {
407
- const fn: any = make(configFn);
408
- // configFn is a cheap object literal over already-constructed consts —
409
- // re-invoking it here just reads the pagination trait (memoized).
410
- let pagination: Pagination.PaginatedTrait | undefined;
411
- const pag = () => (pagination ??= configFn().pagination);
412
- const paginate = strategy ?? Pagination.paginateWithDefaults;
413
-
414
- // The streams are built over a CALL FUNCTION, so the same code serves both
415
- // call styles: the operation itself (requirements intact), and the
416
- // context-bound function `yield* operation` hands back — whose streams
417
- // inherit that captured context and so need nothing after the yield.
418
- const withStreams = (
419
- call: (input: any) => Effect.Effect<any, any, any>,
420
- ): any => {
421
- const pages = (input: Record<string, unknown>) =>
422
- paginate(call, input, pag());
423
- const items = (input: Record<string, unknown>) => {
424
- const p = pag();
425
- return p.items
426
- ? Pagination.extractItems(pages(input), p.items)
427
- : pages(input);
428
- };
429
- return Object.assign(call, { pages, items });
430
- };
955
+ return makeOperation(strategy ? { configFn, strategy } : { configFn }, PaginatedOperationProto);
956
+ }
957
+
958
+ //#endregion
431
959
 
432
- // `yield* operation` runs through `make`'s Proto.asEffect, which builds a
433
- // fresh arrow and would drop `.pages` / `.items` (distilled #145). Override
434
- // it here — Proto's `[Symbol.iterator]`/`pipe` dispatch on `this`, so both
435
- // pick this up. Only paginated operations pay for it.
436
- fn.asEffect = () =>
437
- Effect.map(Effect.context(), (context) =>
438
- withStreams((input: unknown) =>
439
- Effect.provideContext(fn(input), context),
960
+ //#region MakeStreaming
961
+
962
+ /** The message type of a server-streaming output, `{ items: Message[] }`. */
963
+ export type StreamedItem<O> = O extends { readonly items: ReadonlyArray<infer Item> }
964
+ ? Item
965
+ : O extends { readonly items?: ReadonlyArray<infer Item> | undefined }
966
+ ? Item
967
+ : unknown;
968
+
969
+ /**
970
+ * The callable half of a server-streaming operation: the call, which
971
+ * collects the whole stream into `{ items }`, plus `.stream(input)`, which
972
+ * emits each message as it arrives.
973
+ */
974
+ export interface StreamingCall<I, O, E, R, Item> {
975
+ (input: I): Effect.Effect<O, E, R>;
976
+ readonly stream: (input: I) => Stream.Stream<Item, E, R>;
977
+ }
978
+
979
+ /**
980
+ * A server-streaming operation: usable both ways an {@link OperationMethod}
981
+ * is, with `.stream` on both the operation and the requirement-free call
982
+ * function `yield* operation` returns.
983
+ */
984
+ export type StreamingOperationMethod<I, O, E, R, Item = StreamedItem<O>> = Effect.Effect<
985
+ StreamingCall<I, O, E, never, Item>,
986
+ never,
987
+ R
988
+ > &
989
+ StreamingCall<I, O, E, R, Item> &
990
+ OperationSchemas<I, O>;
991
+
992
+ /** The `.stream()` of an operation its protocol can't stream: fails with {@link SdkError}. */
993
+ export const cannotStream = (
994
+ operation: Pick<PreparedOperation, "config">,
995
+ ): Stream.Stream<never, SdkError> =>
996
+ Stream.fail(
997
+ new SdkError({
998
+ message: `${operation.config.operationName ?? "this operation"}: its protocol can't stream`,
999
+ }),
1000
+ );
1001
+
1002
+ /** `.stream(input)` over an operation's protocol. */
1003
+ const streamCall =
1004
+ (state: OperationState) =>
1005
+ (input: unknown): Stream.Stream<any, any, any> =>
1006
+ Stream.catchCause(
1007
+ Stream.unwrap(
1008
+ Effect.suspend(() => {
1009
+ const prepared = prepareOr(state);
1010
+ if (prepared instanceof SdkError) return Effect.succeed(Stream.fail(prepared));
1011
+ const fixed = prepared.cfg.streamInput;
1012
+ const sent = fixed === undefined ? input : { ...(input as object), ...fixed };
1013
+ const run = (service: Protocol<any, any>) =>
1014
+ service.stream === undefined ? cannotStream(prepared) : service.stream(prepared, sent);
1015
+ return prepared.service !== undefined
1016
+ ? Effect.succeed(run(prepared.service))
1017
+ : Effect.map(protocolOf(prepared), run);
1018
+ }),
440
1019
  ),
1020
+ (cause) => Stream.fromEffect(failed(state, cause)),
1021
+ );
1022
+
1023
+ const StreamingOperationProto: object = /*@__PURE__*/ Object.create(OperationProto, {
1024
+ stream: {
1025
+ get(this: any) {
1026
+ const fn = streamCall(stateOf(this));
1027
+ Object.defineProperty(this, "stream", { value: fn, configurable: true });
1028
+ return fn;
1029
+ },
1030
+ configurable: true,
1031
+ },
1032
+ // `yield* operation` returns a context-bound call; its `.stream` gets the
1033
+ // same fallback (not snapshot) context.
1034
+ asEffect: {
1035
+ value(this: any) {
1036
+ const state = stateOf(this);
1037
+ return Effect.map(Effect.context(), (context) => {
1038
+ const merge = (current: Context.Context<any>): Context.Context<any> =>
1039
+ Context.merge(context, current);
1040
+ const call = (input: unknown) => Effect.updateContext(this(input), merge);
1041
+ return Object.assign(call, {
1042
+ stream: (input: unknown) => Stream.updateContext(streamCall(state)(input), merge),
1043
+ });
1044
+ });
1045
+ },
1046
+ configurable: true,
1047
+ writable: true,
1048
+ },
1049
+ });
1050
+
1051
+ /**
1052
+ * Like {@link make}, for a server-streaming RPC whose output is `{ items }`:
1053
+ * calling it collects the stream, and `.stream(input)` emits each message as
1054
+ * the protocol receives it (see {@link Protocol.stream}).
1055
+ *
1056
+ * An operation that streams only when its input asks keeps its own output:
1057
+ * its config sets `items` (one frame) and `streamInput` (what `.stream()`
1058
+ * sends), and the plain call is a normal call.
1059
+ */
1060
+ export function makeStreaming<
1061
+ I extends S.Top,
1062
+ O extends S.Top,
1063
+ PE,
1064
+ PR,
1065
+ const E extends readonly ApiErrorClass[] = readonly [],
1066
+ const SE extends readonly ApiErrorClass[] = readonly [],
1067
+ >(
1068
+ configFn: () => OperationConfig<I, O, PE, PR, E, SE>,
1069
+ ): StreamingOperationMethod<
1070
+ S.Schema.Type<I>,
1071
+ S.Schema.Type<O>,
1072
+ MadeError<E, SE, PE>,
1073
+ PR | HttpClient.HttpClient
1074
+ > {
1075
+ return makeOperation({ configFn }, StreamingOperationProto);
1076
+ }
1077
+
1078
+ //#endregion
1079
+
1080
+ //#region Data operations
1081
+
1082
+ /**
1083
+ * Generated operations described by data instead of code.
1084
+ *
1085
+ * A service module holds each operation as one arrow that is both the
1086
+ * callable operation and the holder of its description:
1087
+ *
1088
+ * export const getFile = API.op((i) => i === API.D ? ['{input:#1,...};__more', [__0, __4, ...]] : API.call(getFile, i));
1089
+ *
1090
+ * Called with {@link D}, it returns `[data, refs]`: `;`-separated entries
1091
+ * in a small expression language (below) and the values they name. `refs[0]`
1092
+ * is the schema-lite `at` (lazy schema wrapper). Schemas reached by more
1093
+ * than one operation live in shared holders, `function __d3() { return
1094
+ * [data, refs]; }`, named in `refs` so a bundler keeps only the holders an
1095
+ * operation reaches. Entry 0 of an operation is its config; the rest are
1096
+ * schemas and thunk bodies. Evaluating an entry calls the same
1097
+ * constructors the code form called, in the same order, so the result is
1098
+ * the same schema.
1099
+ *
1100
+ * Importing a module allocates one function per operation and one per
1101
+ * holder; the data stays text in the module source until first use. A
1102
+ * holder's refs may also be values built from module code on first use
1103
+ * (service traits, endpoint rules), which its value entries name.
1104
+ *
1105
+ * Grammar (`;` never appears outside an entry separator; strings escape it):
1106
+ *
1107
+ * $N refs[N]
1108
+ * #N #R:N schema entry N of this holder / of the holder refs[R] (lazy, memoized)
1109
+ * ~N ~R:N value entry N of this holder / of refs[R] (a constant, evaluated once)
1110
+ * >N thunk `() => entry N`
1111
+ * "..." -1.5 true false null JSON literal u undefined
1112
+ * {k:e,"k":e} object [e,e] array
1113
+ * e(a,b) call e.name member e.name(a,b) method call e@"X" e.annotate({ identifier: "X" })
1114
+ */
1115
+ export const D: unique symbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/D") as any;
1116
+
1117
+ type DataFn = (i?: unknown) => any;
1118
+
1119
+ interface Source {
1120
+ readonly fn: DataFn;
1121
+ e?: string[];
1122
+ r?: ReadonlyArray<any>;
1123
+ b?: (j: number) => unknown;
1124
+ readonly c: unknown[];
1125
+ /** Data error classes: the built base class. */
1126
+ k?: Function;
1127
+ }
1128
+
1129
+ const sources = /*@__PURE__*/ new WeakMap<DataFn, Source>();
1130
+
1131
+ const sourceOf = (fn: DataFn): Source => {
1132
+ let src = sources.get(fn);
1133
+ if (!src) sources.set(fn, (src = { fn, c: [] }));
1134
+ if (!src.e) {
1135
+ // Called with itself as `this`: a lazy error placeholder finds its data by it.
1136
+ const [s, r] = fn.call(fn, D);
1137
+ src.e = s.split(";");
1138
+ src.r = r;
1139
+ }
1140
+ return src;
1141
+ };
1142
+
1143
+ /** Schema `j` of a holder, wrapped by `at` (lazy until first use). */
1144
+ const schemaOf = (src: Source, j: number): unknown =>
1145
+ (src.c[j] ??= src.r![0]((src.b ??= (k: number) => evalEntry(src, k)), j));
1146
+
1147
+ /** A schema of a holder, for module-level code (error classes) that names one at import. */
1148
+ export const schema = (fn: DataFn, j: number): any => schemaOf(sourceOf(fn), j);
1149
+
1150
+ const TOKEN = /"(?:[^"\\]|\\.)*"|[\w$.+-]*/y;
1151
+ const NAME = /[\w$]*/y;
1152
+
1153
+ const evalEntry = (src: Source, j: number): any => {
1154
+ const s = src.e![j]!;
1155
+ const r = src.r!;
1156
+ let p = 0;
1157
+ const tok = (re = NAME): string => {
1158
+ re.lastIndex = p;
1159
+ const t = re.exec(s)![0];
1160
+ p += t.length;
1161
+ return t;
1162
+ };
1163
+ const list = (close: string): any[] => {
1164
+ const a: any[] = [];
1165
+ if (s[p] === close) p++;
1166
+ else
1167
+ do a.push(expr());
1168
+ while (s[p++] !== close);
1169
+ return a;
1170
+ };
1171
+ const expr = (): any => {
1172
+ let v: any;
1173
+ const c = s[p++]!;
1174
+ if (c === "{") {
1175
+ v = {};
1176
+ if (s[p] === "}") p++;
1177
+ else
1178
+ do {
1179
+ const k = tok(TOKEN);
1180
+ p++;
1181
+ v[k[0] === '"' ? JSON.parse(k) : k] = expr();
1182
+ } while (s[p++] !== "}");
1183
+ } else if (c === "[") v = list("]");
1184
+ else if ("$#~>".includes(c)) {
1185
+ let h = src;
1186
+ let k = +tok();
1187
+ if (s[p] === ":") {
1188
+ p++;
1189
+ h = sourceOf(r[k]);
1190
+ k = +tok();
1191
+ }
1192
+ // A value entry is evaluated once, unwrapped.
1193
+ v =
1194
+ c === "$"
1195
+ ? r[k]
1196
+ : c === ">"
1197
+ ? () => evalEntry(src, k)
1198
+ : c === "#"
1199
+ ? schemaOf(h, k)
1200
+ : (h.c[k] ??= evalEntry(h, k));
1201
+ } else {
1202
+ p--;
1203
+ const t = tok(TOKEN);
1204
+ v = t === "u" ? undefined : JSON.parse(t);
1205
+ }
1206
+ for (;;) {
1207
+ const d = s[p++];
1208
+ if (d === "(") v = v(...list(")"));
1209
+ else if (d === "@") v = v.annotate({ identifier: JSON.parse(tok(TOKEN)) });
1210
+ else if (d === ".") {
1211
+ const name = tok();
1212
+ v = s[p] === "(" ? (p++, v[name](...list(")"))) : v[name];
1213
+ } else return (p--, v);
1214
+ }
1215
+ };
1216
+ return expr();
1217
+ };
1218
+
1219
+ // A data operation gets its state on first use, from this inherited getter.
1220
+ // Its descriptors are written inline: nothing keeps them after the prototype is made.
1221
+ const dataState = function (this: DataFn): OperationState {
1222
+ return defineState(this, { configFn: () => evalEntry(sourceOf(this), 0) });
1223
+ };
1224
+ let dataProto: object | undefined;
1225
+ let dataPaginatedProto: object | undefined;
1226
+ let dataStreamingProto: object | undefined;
1227
+ /**
1228
+ * While a lazy service loads its full module (see {@link lazyService}), the module's
1229
+ * definitions go to it instead (kind 0 operation, 1 paginated, 2 error class,
1230
+ * 3 streaming).
1231
+ */
1232
+ let definer: ((fn: DataFn, kind: 0 | 1 | 2 | 3) => unknown) | undefined;
1233
+
1234
+ /** Runs `f` with `d` receiving the definitions it evaluates. */
1235
+ const defining = (d: typeof definer, f: () => void): void => {
1236
+ const outer = definer;
1237
+ definer = d;
1238
+ try {
1239
+ f();
1240
+ } finally {
1241
+ definer = outer;
1242
+ }
1243
+ };
1244
+
1245
+ /**
1246
+ * The data of an operation whose name recurs in its strings: `%` in them
1247
+ * stands for `stem` (a literal `%` is escaped).
1248
+ */
1249
+ export const named = (stem: string, data: string, refs: unknown): [string, unknown] => [
1250
+ data.replaceAll("%", stem),
1251
+ refs,
1252
+ ];
1253
+
1254
+ const asOp = (fn: DataFn): any =>
1255
+ Object.setPrototypeOf(
1256
+ fn,
1257
+ (dataProto ??= Object.create(OperationProto, {
1258
+ [stateKey]: { get: dataState, configurable: true },
1259
+ })),
1260
+ );
1261
+
1262
+ const asOpPaginated = (fn: DataFn): any =>
1263
+ Object.setPrototypeOf(
1264
+ fn,
1265
+ (dataPaginatedProto ??= Object.create(PaginatedOperationProto, {
1266
+ [stateKey]: { get: dataState, configurable: true },
1267
+ })),
1268
+ );
1269
+
1270
+ const asOpStreaming = (fn: DataFn): any =>
1271
+ Object.setPrototypeOf(
1272
+ fn,
1273
+ (dataStreamingProto ??= Object.create(StreamingOperationProto, {
1274
+ [stateKey]: { get: dataState, configurable: true },
1275
+ })),
1276
+ );
1277
+
1278
+ /** An operation described by data (see the region header). */
1279
+ export const op = (fn: DataFn): any => (definer ? definer(fn, 0) : asOp(fn));
1280
+
1281
+ /** A paginated operation described by data; its config may name a `strategy`. */
1282
+ export const opPaginated = (fn: DataFn): any => (definer ? definer(fn, 1) : asOpPaginated(fn));
1283
+
1284
+ /** A server-streaming operation described by data. */
1285
+ export const opStreaming = (fn: DataFn): any => (definer ? definer(fn, 3) : asOpStreaming(fn));
1286
+
1287
+ /** The call path of a data operation. */
1288
+ export const call = (op: unknown, input: unknown): Effect.Effect<any, any, any> =>
1289
+ callOperation(stateOf(op), input, op as Function);
1290
+
1291
+ /**
1292
+ * Generated error classes described by data:
1293
+ *
1294
+ * export const Oops = API.error(function Oops(i) {
1295
+ * return API.newError(i, new.target, ['$1()("Oops",{...})', [...]]);
1296
+ * });
1297
+ *
1298
+ * The function is the class callers see: `new Oops(props)` constructs, a
1299
+ * plain call returns the data. Entry 0 of the data is the expression the
1300
+ * class extended (e.g. `S.TaggedError()(...).pipe(category)`). The first
1301
+ * `new`, or the first read of a static the function does not own (`ast`,
1302
+ * `fields`, `identifier`, error matchers, ...), builds that base class and
1303
+ * puts it underneath: the function's statics and prototype then inherit
1304
+ * from it as `class Oops extends Base {}` did, so `instanceof`, `_tag`,
1305
+ * categories and subclasses behave as before. Until then an error class
1306
+ * costs one function. The `in` operator sees only `Function` members until
1307
+ * the class is built.
1308
+ */
1309
+ const errorBase = (f: any): Function | undefined => {
1310
+ // `f` may be a subclass: find the data class it extends.
1311
+ while (f && Object.getPrototypeOf(f) !== lazyErrorStatics && !sources.get(f)?.k)
1312
+ f = Object.getPrototypeOf(f);
1313
+ if (!f) return undefined;
1314
+ const src = sourceOf(f);
1315
+ if (!src.k) {
1316
+ const base = evalEntry(src, 0) as Function;
1317
+ src.k = base;
1318
+ Object.setPrototypeOf(f, base);
1319
+ Object.setPrototypeOf(f.prototype, base.prototype);
1320
+ }
1321
+ return src.k;
1322
+ };
1323
+
1324
+ // The statics of an unbuilt error class: `Function.prototype` members answer
1325
+ // directly; any other read builds the class, then reads again. Made on first
1326
+ // use, so bundles without data errors drop it.
1327
+ let lazyErrorStatics: object | undefined;
1328
+ const LazyErrorStatics = (): object =>
1329
+ (lazyErrorStatics ??= new Proxy(Object.create(Function.prototype), {
1330
+ get: (target, key, receiver) =>
1331
+ key in target || !errorBase(receiver)
1332
+ ? Reflect.get(target, key, receiver)
1333
+ : Reflect.get(receiver, key, receiver),
1334
+ }));
1335
+
1336
+ const asError = (fn: DataFn): any => Object.setPrototypeOf(fn, LazyErrorStatics());
1337
+
1338
+ /** An error class described by data (see {@link errorBase}). */
1339
+ export const error = (fn: DataFn): any => (definer ? definer(fn, 2) : asError(fn));
1340
+
1341
+ /**
1342
+ * The body of a data error class: with `new`, an instance of the built
1343
+ * base whose prototype is `newTarget`'s; called plainly, the class's data.
1344
+ */
1345
+ export const newError = (props: unknown, newTarget: Function | undefined, data: unknown): any =>
1346
+ newTarget ? Reflect.construct(errorBase(newTarget)!, [props], newTarget) : data;
1347
+
1348
+ //#endregion
1349
+
1350
+ //#region Lazy service modules
1351
+
1352
+ /**
1353
+ * A Node process that enables the `distilled-lazy` export condition loads a
1354
+ * service module as a stub (`lib/services.lazy/<name>.js`): one cheap
1355
+ * placeholder per operation and error class, no operation data. Its first use
1356
+ * loads the full module (`lib/services/<name>.js`, what every other condition
1357
+ * resolves) with `require(esm)`.
1358
+ *
1359
+ * const { o, e, E } = API.lazyService(import.meta.url, "../services/sqs.js", "oop", [$0], at, len);
1360
+ * export const { OverLimit, QueueDoesNotExist } = E; // or OverLimit = e("OverLimit"), ...
1361
+ * export const addPermission = o(), _1 = o(), listQueues = o();
1362
+ *
1363
+ * Generated stubs reach this through their package's `_bundle/lazy.js`,
1364
+ * which passes its own URL and the namespaces every stub imports.
1365
+ *
1366
+ * `kinds` has one letter per operation definition of the full module: `o`
1367
+ * plain, `p` paginated, `s` server-streaming. While the stub's load evaluates the full module,
1368
+ * `op` / `opPaginated` / `error` hand back the stub's placeholders in
1369
+ * definition order instead of new values, and each placeholder takes the
1370
+ * data function it stands for: the full module's operations, error lists
1371
+ * and exports are the very objects the stub exported.
1372
+ *
1373
+ * With a slice index (below), a placeholder's first use evaluates only what
1374
+ * its operation reaches instead of the whole full module. A full module that
1375
+ * was imported directly (lib code names services through the package, so
1376
+ * it resolves the stub too; only an import by file path does) keeps
1377
+ * its own objects, separate from the stub's.
1378
+ */
1379
+ interface LazyService {
1380
+ readonly url: string;
1381
+ readonly spec: string;
1382
+ readonly kinds: string;
1383
+ /** Namespaces of the full module's imports, when it has a slice index. */
1384
+ readonly ns: readonly any[] | undefined;
1385
+ /** Byte range of the slice index, a comment at the end of the full module. */
1386
+ readonly at: number | undefined;
1387
+ readonly len: number | undefined;
1388
+ /** The slice index (see {@link sliced}); false: load the whole module. */
1389
+ ix?: SliceIndex | false;
1390
+ readonly o: any[];
1391
+ readonly e: any[];
1392
+ /** Data functions by placeholder, filled while the full module loads. */
1393
+ od?: DataFn[];
1394
+ ed?: DataFn[];
1395
+ oi: number;
1396
+ ei: number;
1397
+ }
1398
+
1399
+ /** The stub letter of each operation kind (see {@link lazyService}). */
1400
+ const KIND_LETTERS = ["o", "p", "", "s"] as const;
1401
+
1402
+ const define = (svc: LazyService, fn: DataFn, kind: 0 | 1 | 2 | 3): any => {
1403
+ if (kind === 2) {
1404
+ const i = svc.ei++;
1405
+ if (i >= svc.e.length) throw new Error(`distilled: ${svc.spec}: error ${i} has no stub`);
1406
+ svc.ed![i] = fn;
1407
+ return svc.e[i];
1408
+ }
1409
+ const i = svc.oi++;
1410
+ if (i >= svc.o.length || svc.kinds[i] !== KIND_LETTERS[kind])
1411
+ throw new Error(`distilled: ${svc.spec}: operation ${i} does not match its stub`);
1412
+ svc.od![i] = fn;
1413
+ return svc.o[i];
1414
+ };
1415
+
1416
+ const load = (svc: LazyService): void => {
1417
+ if (svc.od) return;
1418
+ svc.od = [];
1419
+ svc.ed = [];
1420
+ try {
1421
+ defining(
1422
+ (fn, kind) => define(svc, fn, kind),
1423
+ () =>
1424
+ (globalThis as any).process.getBuiltinModule("node:module").createRequire(svc.url)(
1425
+ svc.spec,
1426
+ ),
1427
+ );
1428
+ } catch (e) {
1429
+ svc.od = svc.ed = undefined;
1430
+ svc.oi = svc.ei = 0;
1431
+ throw e;
1432
+ }
1433
+ if (svc.oi !== svc.o.length || svc.ei !== svc.e.length)
1434
+ throw new Error(
1435
+ `distilled: ${svc.spec} defined ${svc.oi} of ${svc.o.length} operations and ${svc.ei} of ${svc.e.length} errors (was it imported directly before?)`,
441
1436
  );
1437
+ };
442
1438
 
443
- return withStreams(fn);
1439
+ /**
1440
+ * Per-operation loading. bundle-lib ends a full module with a comment
1441
+ * holding its slice index (see scripts/lazy-services.ts): for every top-level
1442
+ * declaration, the byte range of its expression and the declarations it may
1443
+ * read. A placeholder's first use evaluates only its own data function and,
1444
+ * on demand, what that reaches -- one `Function` per declaration, the
1445
+ * module's imports and its dependencies passed in as parameters -- instead
1446
+ * of the whole module. Function declarations (the shared schema holders)
1447
+ * become forwarding functions compiled on their first call, so cycles
1448
+ * between them need no order. Without an index, or where code generation
1449
+ * from strings is disallowed, the whole module is loaded instead.
1450
+ */
1451
+ interface SliceIndex {
1452
+ readonly file: string;
1453
+ /** Open while a burst of evaluations runs; closed in a microtask. */
1454
+ fd?: number;
1455
+ /** The index text, and where its sections start. */
1456
+ readonly raw: string;
1457
+ readonly imports: number;
1458
+ readonly importsAt: number;
1459
+ readonly tableAt: number;
1460
+ readonly linesAt: number;
1461
+ /** Split on first use. */
1462
+ specs?: string[];
1463
+ readonly importValues: unknown[];
1464
+ /** Values by declaration; `busy` marks one being evaluated. */
1465
+ readonly v: unknown[];
444
1466
  }
445
1467
 
1468
+ const busy = {};
1469
+
1470
+ const node = (m: string): any => (globalThis as any).process?.getBuiltinModule?.(m);
1471
+
1472
+ /** Reads `length` bytes at `position` of the full module. */
1473
+ const read = (ix: { file: string; fd?: number }, position: number, length: number): string => {
1474
+ const fs = node("node:fs");
1475
+ if (ix.fd === undefined) {
1476
+ ix.fd = fs.openSync(ix.file, "r") as number;
1477
+ queueMicrotask(() => {
1478
+ fs.closeSync(ix.fd);
1479
+ ix.fd = undefined;
1480
+ });
1481
+ }
1482
+ const buf = (globalThis as any).Buffer.allocUnsafe(length);
1483
+ fs.readSync(ix.fd, buf, 0, length, position);
1484
+ return buf.toString("utf8", 0, length);
1485
+ };
1486
+
1487
+ const indexOf = (file: string, raw: string): SliceIndex => {
1488
+ const importsAt = raw.indexOf("\n") + 1;
1489
+ const tableAt = raw.indexOf("\n", importsAt) + 1;
1490
+ return {
1491
+ file,
1492
+ raw,
1493
+ imports: parseInt(raw),
1494
+ importsAt,
1495
+ tableAt,
1496
+ linesAt: raw.indexOf("\n", tableAt) + 1,
1497
+ importValues: [],
1498
+ v: [],
1499
+ };
1500
+ };
1501
+
1502
+ const fileOf = (svc: LazyService): string =>
1503
+ // A plain POSIX file URL is its path (URL parsing costs ~0.1 ms the first time).
1504
+ /^file:\/\/\/[^%?#]*$/.test(svc.url) && (globalThis as any).process.platform !== "win32"
1505
+ ? svc.url.slice(7, svc.url.lastIndexOf("/") + 1) + svc.spec
1506
+ : node("node:url").fileURLToPath(new URL(svc.spec, svc.url));
1507
+
1508
+ const sliced = (svc: LazyService): SliceIndex | false => {
1509
+ if (svc.ix !== undefined) return svc.ix;
1510
+ svc.ix = false;
1511
+ if (svc.at === undefined || svc.od) return false;
1512
+ try {
1513
+ // oxlint-disable-next-line distilled/no-function-constructor -- probes whether the host allows it (a CSP may not)
1514
+ Function("");
1515
+ const file = fileOf(svc);
1516
+ svc.ix = indexOf(file, read({ file }, svc.at, svc.len!));
1517
+ svc.od = [];
1518
+ svc.ed = [];
1519
+ } catch {
1520
+ // Code from strings is blocked, or the slice can't be read: load the
1521
+ // whole module instead (`svc.ix` stays `false`).
1522
+ svc.ix = false;
1523
+ }
1524
+ return svc.ix;
1525
+ };
1526
+
1527
+ /**
1528
+ * The first lazy service of a process reads its slice index right after it
1529
+ * is imported (in a microtask, so before the import settles), instead of on
1530
+ * its first call: that read also pays Node's one-time costs of the slice path
1531
+ * (~0.2 ms). Later services read theirs on first use; nothing else is read
1532
+ * ahead, so importing a whole provider holds one index.
1533
+ */
1534
+ let primed = false;
1535
+ const prime = (svc: LazyService): void => {
1536
+ primed = true;
1537
+ queueMicrotask(() => {
1538
+ const ix = sliced(svc);
1539
+ // The first read of an export through a module namespace is slow.
1540
+ if (ix && ix.imports > 0) importOf(svc, ix, 0);
1541
+ });
1542
+ };
1543
+
1544
+ /** The index line of declaration `k`. */
1545
+ const lineOf = (ix: SliceIndex, k: number): string => {
1546
+ const at = ix.tableAt + 5 * k;
1547
+ return ix.raw.slice(
1548
+ ix.linesAt + parseInt(ix.raw.slice(at, at + 5), 36),
1549
+ ix.linesAt + parseInt(ix.raw.slice(at + 5, at + 10), 36) - 1,
1550
+ );
1551
+ };
1552
+
1553
+ const nameOf = (ix: SliceIndex, k: number): string => lineOf(ix, k).split("|")[0]!.split(" ")[3]!;
1554
+
1555
+ const importSpec = (ix: SliceIndex, j: number): string[] =>
1556
+ (ix.specs ??= ix.raw.slice(ix.importsAt, ix.tableAt - 1).split(" "))[j]!.split(":");
1557
+
1558
+ const importOf = (svc: LazyService, ix: SliceIndex, j: number): unknown => {
1559
+ if (j in ix.importValues) return ix.importValues[j];
1560
+ const [, source, name] = importSpec(ix, j);
1561
+ return (ix.importValues[j] = svc.ns![+source!][name!]);
1562
+ };
1563
+
1564
+ /** A top-level name of the full module: imports first, then declarations. */
1565
+ const refOf = (svc: LazyService, ix: SliceIndex, j: number): unknown =>
1566
+ j < ix.imports ? importOf(svc, ix, j) : valueOf(svc, ix, j - ix.imports);
1567
+
1568
+ /**
1569
+ * Evaluates declaration `k` that is not a data function in its generated
1570
+ * shape: compiled with its dependencies in scope; a function with plain
1571
+ * parameters from its body, so it is parsed once, bound to those values.
1572
+ */
1573
+ const evaluate = (svc: LazyService, ix: SliceIndex, k: number): any => {
1574
+ const [head, fn, depText] = lineOf(ix, k).split("|");
1575
+ const deps = depText ? depText.split(" ").map((x) => parseInt(x, 36)) : [];
1576
+ const names = deps.map((j) =>
1577
+ j < ix.imports ? importSpec(ix, j)[0]! : nameOf(ix, j - ix.imports),
1578
+ );
1579
+ const values = deps.map((j) => refOf(svc, ix, j));
1580
+ const url = `\n//# sourceURL=${ix.file}#${nameOf(ix, k)}`;
1581
+ if (fn && fn[0] !== "(") {
1582
+ const [params, range] = fn.split(";");
1583
+ const [start, end, expr] = range!.split(" ").map((x) => parseInt(x, 36));
1584
+ return compileBody(
1585
+ ix,
1586
+ names,
1587
+ values,
1588
+ params ? params.split(",") : [],
1589
+ start!,
1590
+ end!,
1591
+ expr!,
1592
+ url,
1593
+ );
1594
+ }
1595
+ const [, start, end] = head!.split(" ").map((x) => parseInt(x, 36));
1596
+ let text: string;
1597
+ if (fn?.[0] === "(") {
1598
+ // Functions it passes compile on their first call (many never are): it
1599
+ // reads the text around them only.
1600
+ const args = fn.slice(1).split(",");
1601
+ const outer = { names: names.slice(), values: values.slice() };
1602
+ text = "";
1603
+ let at = start!;
1604
+ args.forEach((arg, i) => {
1605
+ const [a, b, bs, be, expr] = arg.split(" ").map((x) => parseInt(x, 36));
1606
+ const params = arg.split(" ")[5];
1607
+ let compiled: Function | undefined;
1608
+ names.push(`$lazy${i}`);
1609
+ values.push(function (this: unknown) {
1610
+ compiled ??= compileBody(
1611
+ ix,
1612
+ outer.names,
1613
+ outer.values,
1614
+ params ? params.split("+") : [],
1615
+ bs!,
1616
+ be!,
1617
+ expr!,
1618
+ url,
1619
+ );
1620
+ return compiled.apply(this, arguments);
1621
+ });
1622
+ text += `${read(ix, at, a! - at)}$lazy${i}`;
1623
+ at = b!;
1624
+ });
1625
+ text += read(ix, at, end! - at);
1626
+ } else text = read(ix, start!, end! - start!);
1627
+ // oxlint-disable-next-line distilled/no-function-constructor -- the distilled-lazy loader compiles one declaration of a bundled service
1628
+ return Function(...names, `"use strict";return(${text}\n)${url}`)(...values);
1629
+ };
1630
+
1631
+ /**
1632
+ * A function with plain parameters, compiled from its body (parsed once)
1633
+ * with `names` in scope bound to `values`; its parameters shadow them.
1634
+ */
1635
+ const compileBody = (
1636
+ ix: SliceIndex,
1637
+ names: string[],
1638
+ values: unknown[],
1639
+ own: string[],
1640
+ start: number,
1641
+ end: number,
1642
+ expr: number,
1643
+ url: string,
1644
+ ): Function => {
1645
+ const text = read(ix, start, end - start);
1646
+ const keep = names.map((n) => !own.includes(n));
1647
+ // oxlint-disable-next-line distilled/no-function-constructor -- the distilled-lazy loader compiles one declaration of a bundled service
1648
+ return Function(
1649
+ ...names.filter((_, i) => keep[i]),
1650
+ ...own,
1651
+ // A block: the body's own declarations shadow the names in scope, as they did.
1652
+ `"use strict";${expr ? `return(${text}\n)` : `{${text}\n}`}${url}`,
1653
+ ).bind(undefined, ...values.filter((_, i) => keep[i]));
1654
+ };
1655
+
1656
+ /**
1657
+ * The data function of a data line (`=stem;start end;refs`): reads the data
1658
+ * and resolves its refs, compiling nothing.
1659
+ */
1660
+ const dataFn = (svc: LazyService, ix: SliceIndex, fn: string): [string, unknown[]] => {
1661
+ const [stem, range, refs] = fn.slice(1).split(";");
1662
+ const sp = range!.indexOf(" ");
1663
+ const start = parseInt(range!, 36);
1664
+ const data = read(ix, start, parseInt(range!.slice(sp + 1), 36) - start);
1665
+ const values: unknown[] = [];
1666
+ if (refs)
1667
+ for (const x of refs.split(",")) {
1668
+ const j = parseInt(x, 36);
1669
+ values.push(j < ix.imports ? importOf(svc, ix, j) : slot(svc, ix, j - ix.imports, false));
1670
+ }
1671
+ return [stem ? data.replaceAll("%", stem) : data, values];
1672
+ };
1673
+
1674
+ /**
1675
+ * The value declaration `k` of the full module has; with `own`, for an
1676
+ * operation or error class, its data function instead of its placeholder.
1677
+ */
1678
+ const slot = (svc: LazyService, ix: SliceIndex, k: number, own: boolean): any => {
1679
+ if (!own) {
1680
+ if (k in ix.v) return ix.v[k] === busy ? undefined : ix.v[k];
1681
+ const ops = svc.o.length;
1682
+ if (k < ops) return (ix.v[k] = svc.o[k]);
1683
+ if (k < ops + svc.e.length) return (ix.v[k] = svc.e[k - ops]);
1684
+ }
1685
+ const at = ix.tableAt + 5 * k;
1686
+ const line = ix.raw.slice(
1687
+ ix.linesAt + parseInt(ix.raw.slice(at, at + 5), 36),
1688
+ ix.linesAt + parseInt(ix.raw.slice(at + 5, at + 10), 36) - 1,
1689
+ );
1690
+ const bar = line.indexOf("|");
1691
+ if (line[bar + 1] === "=") {
1692
+ const fn = dataFn.bind(undefined, svc, ix, line.slice(bar + 1)) as DataFn;
1693
+ return own ? fn : (ix.v[k] = fn);
1694
+ }
1695
+ if (own) return evaluate(svc, ix, k);
1696
+ if (line[0] === "1") {
1697
+ // A function declaration: compiled on its first call, so cycles need no order.
1698
+ let fn: Function | undefined;
1699
+ return (ix.v[k] = function (this: unknown) {
1700
+ return (fn ??= evaluate(svc, ix, k)).apply(this, arguments);
1701
+ });
1702
+ }
1703
+ ix.v[k] = busy;
1704
+ return (ix.v[k] = evaluate(svc, ix, k));
1705
+ };
1706
+
1707
+ const valueOf = (svc: LazyService, ix: SliceIndex, k: number): unknown => slot(svc, ix, k, false);
1708
+
1709
+ /** The data function of placeholder `i` (`kind` 0: operation, 1: error class). */
1710
+ const dataOf = (svc: LazyService, kind: 0 | 1, i: number): DataFn => {
1711
+ const loaded = kind === 0 ? svc.od : svc.ed;
1712
+ if (loaded?.[i]) return loaded[i]!;
1713
+ const ix = sliced(svc);
1714
+ if (!ix) {
1715
+ load(svc);
1716
+ return (kind === 0 ? svc.od : svc.ed)![i]!;
1717
+ }
1718
+ return ((kind === 0 ? svc.od : svc.ed)![i] = slot(
1719
+ svc,
1720
+ ix,
1721
+ kind === 0 ? i : svc.o.length + i,
1722
+ true,
1723
+ ));
1724
+ };
1725
+
1726
+ /**
1727
+ * The placeholders of a lazy service module (see the region header): `o()`
1728
+ * and `e()` make the next operation / error class. A placeholder finds its
1729
+ * data by its index; it closes over nothing of its own, so it costs one
1730
+ * function.
1731
+ */
1732
+ export const lazyService = (
1733
+ url: string,
1734
+ spec: string,
1735
+ kinds: string,
1736
+ ns?: readonly any[],
1737
+ at?: number,
1738
+ len?: number,
1739
+ ): { readonly o: () => any; readonly e: (name: string) => any; readonly E: any } => {
1740
+ const svc: LazyService = { url, spec, kinds, ns, at, len, o: [], e: [], oi: 0, ei: 0 };
1741
+ if (!primed && at !== undefined) prime(svc);
1742
+ return {
1743
+ o: () => {
1744
+ const kind = kinds[svc.o.length];
1745
+ const f: DataFn = function op(x) {
1746
+ return x === D ? dataOf(svc, 0, svc.o.indexOf(op))(D) : call(op, x);
1747
+ };
1748
+ svc.o.push(kind === "p" ? asOpPaginated(f) : kind === "s" ? asOpStreaming(f) : asOp(f));
1749
+ return f;
1750
+ },
1751
+ e: (name: string) => {
1752
+ // A computed key names the function without a property of its own.
1753
+ const f = {
1754
+ [name]: function (this: unknown, x: unknown) {
1755
+ return new.target
1756
+ ? newError(x, new.target, undefined)
1757
+ : dataOf(svc, 1, svc.e.indexOf(this))(x);
1758
+ },
1759
+ }[name]!;
1760
+ svc.e.push(asError(f));
1761
+ return f;
1762
+ },
1763
+ // Destructured once by the stub: each property read makes the error class of that name.
1764
+ get E() {
1765
+ const e = this.e;
1766
+ return new Proxy({}, { get: (_, name) => e(name as string) });
1767
+ },
1768
+ };
1769
+ };
1770
+
1771
+ /**
1772
+ * A service barrel's stand-in for `export * as sqs from "./sqs.js"` in Node:
1773
+ * a namespace whose module is loaded (`require(esm)`) on first access, so
1774
+ * importing a provider's barrel loads no service module. Reads, `in`,
1775
+ * `Object.keys` and spreading see the module's exports; it is read-only.
1776
+ */
1777
+ interface LazyNamespace {
1778
+ readonly url: string;
1779
+ readonly spec: string;
1780
+ ns?: any;
1781
+ }
1782
+
1783
+ const namespaceOf = (t: LazyNamespace): any =>
1784
+ (t.ns ??= (globalThis as any).process.getBuiltinModule("node:module").createRequire(t.url)(
1785
+ t.spec,
1786
+ ));
1787
+
1788
+ let lazyNamespaceHandler: ProxyHandler<LazyNamespace> | undefined;
1789
+
1790
+ export const lazyNamespace = (url: string, spec: string): any =>
1791
+ new Proxy<LazyNamespace>(
1792
+ { url, spec },
1793
+ (lazyNamespaceHandler ??= {
1794
+ get: (t, k) => namespaceOf(t)[k],
1795
+ has: (t, k) => k in namespaceOf(t),
1796
+ ownKeys: (t) => Reflect.ownKeys(namespaceOf(t)),
1797
+ getOwnPropertyDescriptor: (t, k) => {
1798
+ const d = Reflect.getOwnPropertyDescriptor(namespaceOf(t), k);
1799
+ // The target does not hold these: a proxy may only report them configurable.
1800
+ return d && { ...d, configurable: true };
1801
+ },
1802
+ getPrototypeOf: () => null,
1803
+ set: () => false,
1804
+ defineProperty: () => false,
1805
+ deleteProperty: () => false,
1806
+ }),
1807
+ );
1808
+
446
1809
  //#endregion