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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/LICENSE +201 -0
  2. package/lib/_bundle/aws.js +2 -0
  3. package/lib/_bundle/aws.js.map +1 -0
  4. package/lib/_bundle/base.js +5 -0
  5. package/lib/_bundle/base.js.map +1 -0
  6. package/lib/_bundle/graphql.js +3 -0
  7. package/lib/_bundle/graphql.js.map +1 -0
  8. package/lib/_bundle/grpc.js +2 -0
  9. package/lib/_bundle/grpc.js.map +1 -0
  10. package/lib/_bundle/rest.js +2 -0
  11. package/lib/_bundle/rest.js.map +1 -0
  12. package/lib/_bundle/xml.js +4 -0
  13. package/lib/_bundle/xml.js.map +1 -0
  14. package/lib/annotations.d.ts +17 -0
  15. package/lib/annotations.d.ts.map +1 -0
  16. package/lib/annotations.js +2 -0
  17. package/lib/annotations.js.map +1 -0
  18. package/lib/api.d.ts +174 -18
  19. package/lib/api.d.ts.map +1 -1
  20. package/lib/api.js +1 -178
  21. package/lib/category.d.ts +4 -4
  22. package/lib/category.d.ts.map +1 -1
  23. package/lib/category.js +1 -280
  24. package/lib/chunks.d.ts +3 -0
  25. package/lib/chunks.d.ts.map +1 -0
  26. package/lib/chunks.js +1 -0
  27. package/lib/config.d.ts +68 -0
  28. package/lib/config.d.ts.map +1 -0
  29. package/lib/config.js +1 -0
  30. package/lib/crypto.d.ts +76 -0
  31. package/lib/crypto.d.ts.map +1 -0
  32. package/lib/crypto.js +1 -0
  33. package/lib/error-category.d.ts +1 -1
  34. package/lib/error-category.d.ts.map +1 -1
  35. package/lib/error-category.js +1 -46
  36. package/lib/errors.d.ts +64 -72
  37. package/lib/errors.d.ts.map +1 -1
  38. package/lib/errors.js +1 -186
  39. package/lib/graphql.d.ts +403 -0
  40. package/lib/graphql.d.ts.map +1 -0
  41. package/lib/graphql.js +1 -0
  42. package/lib/graphql.types.d.ts +12 -0
  43. package/lib/graphql.types.d.ts.map +1 -0
  44. package/lib/graphql.types.js +1 -0
  45. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  47. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  48. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  49. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  51. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  53. package/lib/grpc-transport-node-http2.d.ts +19 -0
  54. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  55. package/lib/grpc-transport-node-http2.js +2 -0
  56. package/lib/grpc-transport-node-http2.js.map +1 -0
  57. package/lib/grpc-transport.d.ts +76 -0
  58. package/lib/grpc-transport.d.ts.map +1 -0
  59. package/lib/grpc-transport.js +1 -0
  60. package/lib/hpack.d.ts +34 -0
  61. package/lib/hpack.d.ts.map +1 -0
  62. package/lib/hpack.js +2 -0
  63. package/lib/hpack.js.map +1 -0
  64. package/lib/index.d.ts +32 -0
  65. package/lib/index.d.ts.map +1 -0
  66. package/lib/index.js +17 -0
  67. package/lib/pagination.d.ts +101 -24
  68. package/lib/pagination.d.ts.map +1 -1
  69. package/lib/pagination.js +1 -182
  70. package/lib/plain-values.d.ts +10 -0
  71. package/lib/plain-values.d.ts.map +1 -0
  72. package/lib/plain-values.js +2 -0
  73. package/lib/plain-values.js.map +1 -0
  74. package/lib/protobuf.d.ts +92 -0
  75. package/lib/protobuf.d.ts.map +1 -0
  76. package/lib/protobuf.js +1 -0
  77. package/lib/protocol-grpc.d.ts +86 -0
  78. package/lib/protocol-grpc.d.ts.map +1 -0
  79. package/lib/protocol-grpc.js +1 -0
  80. package/lib/protocol-http.d.ts +102 -23
  81. package/lib/protocol-http.d.ts.map +1 -1
  82. package/lib/protocol-http.js +1 -554
  83. package/lib/protocol-rest.d.ts +120 -50
  84. package/lib/protocol-rest.d.ts.map +1 -1
  85. package/lib/protocol-rest.js +1 -242
  86. package/lib/query.d.ts +29 -0
  87. package/lib/query.d.ts.map +1 -0
  88. package/lib/query.js +1 -0
  89. package/lib/response-validation-strict.d.ts +48 -0
  90. package/lib/response-validation-strict.d.ts.map +1 -0
  91. package/lib/response-validation-strict.js +1 -0
  92. package/lib/response-validation.d.ts +86 -0
  93. package/lib/response-validation.d.ts.map +1 -0
  94. package/lib/response-validation.js +1 -0
  95. package/lib/retry-after.d.ts +3 -3
  96. package/lib/retry-after.d.ts.map +1 -1
  97. package/lib/retry-after.js +1 -112
  98. package/lib/retry.d.ts +48 -29
  99. package/lib/retry.d.ts.map +1 -1
  100. package/lib/retry.js +1 -210
  101. package/lib/schema-lite-impl.d.ts +158 -0
  102. package/lib/schema-lite-impl.d.ts.map +1 -0
  103. package/lib/schema-lite-impl.js +1 -0
  104. package/lib/schema-lite-typed.d.ts +41 -0
  105. package/lib/schema-lite-typed.d.ts.map +1 -0
  106. package/lib/schema-lite-typed.js +1 -0
  107. package/lib/schema-lite.d.ts +40 -0
  108. package/lib/schema-lite.d.ts.map +1 -0
  109. package/lib/schema-lite.js +1 -0
  110. package/lib/schema.d.ts +21 -7
  111. package/lib/schema.d.ts.map +1 -1
  112. package/lib/schema.js +1 -48
  113. package/lib/sdk-error.d.ts +27 -0
  114. package/lib/sdk-error.d.ts.map +1 -0
  115. package/lib/sdk-error.js +1 -0
  116. package/lib/sensitive.d.ts +28 -0
  117. package/lib/sensitive.d.ts.map +1 -0
  118. package/lib/sensitive.js +2 -0
  119. package/lib/sensitive.js.map +1 -0
  120. package/lib/telemetry-debug.d.ts +6 -0
  121. package/lib/telemetry-debug.d.ts.map +1 -0
  122. package/lib/telemetry-debug.js +2 -0
  123. package/lib/telemetry-debug.js.map +1 -0
  124. package/lib/telemetry-hooks.d.ts +32 -0
  125. package/lib/telemetry-hooks.d.ts.map +1 -0
  126. package/lib/telemetry-hooks.js +2 -0
  127. package/lib/telemetry-hooks.js.map +1 -0
  128. package/lib/telemetry-host-rules.d.ts +23 -0
  129. package/lib/telemetry-host-rules.d.ts.map +1 -0
  130. package/lib/telemetry-host-rules.js +2 -0
  131. package/lib/telemetry-host-rules.js.map +1 -0
  132. package/lib/telemetry-lambda-context.d.ts +17 -0
  133. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  134. package/lib/telemetry-lambda-context.js +2 -0
  135. package/lib/telemetry-lambda-context.js.map +1 -0
  136. package/lib/telemetry-message-context.d.ts +52 -0
  137. package/lib/telemetry-message-context.d.ts.map +1 -0
  138. package/lib/telemetry-message-context.js +2 -0
  139. package/lib/telemetry-message-context.js.map +1 -0
  140. package/lib/telemetry-metrics.d.ts +6 -0
  141. package/lib/telemetry-metrics.d.ts.map +1 -0
  142. package/lib/telemetry-metrics.js +2 -0
  143. package/lib/telemetry-metrics.js.map +1 -0
  144. package/lib/telemetry-name-template.d.ts +13 -0
  145. package/lib/telemetry-name-template.d.ts.map +1 -0
  146. package/lib/telemetry-name-template.js +2 -0
  147. package/lib/telemetry-name-template.js.map +1 -0
  148. package/lib/telemetry-stream.d.ts +11 -0
  149. package/lib/telemetry-stream.d.ts.map +1 -0
  150. package/lib/telemetry-stream.js +2 -0
  151. package/lib/telemetry-stream.js.map +1 -0
  152. package/lib/telemetry-xray.d.ts +28 -0
  153. package/lib/telemetry-xray.d.ts.map +1 -0
  154. package/lib/telemetry-xray.js +2 -0
  155. package/lib/telemetry-xray.js.map +1 -0
  156. package/lib/telemetry.d.ts +288 -0
  157. package/lib/telemetry.d.ts.map +1 -0
  158. package/lib/telemetry.js +3 -0
  159. package/lib/telemetry.js.map +1 -0
  160. package/lib/trait.d.ts +71 -20
  161. package/lib/trait.d.ts.map +1 -1
  162. package/lib/trait.js +1 -107
  163. package/lib/unknown-error.d.ts +18 -0
  164. package/lib/unknown-error.d.ts.map +1 -0
  165. package/lib/unknown-error.js +1 -0
  166. package/lib/xml.d.ts +44 -0
  167. package/lib/xml.d.ts.map +1 -0
  168. package/lib/xml.js +1 -0
  169. package/package.json +13 -13
  170. package/src/annotations.ts +53 -0
  171. package/src/api.ts +1370 -200
  172. package/src/category.ts +76 -106
  173. package/src/chunks.ts +30 -0
  174. package/src/config.ts +245 -0
  175. package/src/crypto.ts +202 -0
  176. package/src/error-category.ts +16 -29
  177. package/src/errors.ts +75 -75
  178. package/src/graphql.ts +1778 -0
  179. package/src/graphql.types.ts +105 -0
  180. package/src/grpc-transport-cloudflare-http2.ts +494 -0
  181. package/src/grpc-transport-cloudflare-sockets.ts +299 -0
  182. package/src/grpc-transport-node-http2.ts +234 -0
  183. package/src/grpc-transport.ts +118 -0
  184. package/src/hpack.ts +331 -0
  185. package/src/index.ts +31 -0
  186. package/src/pagination.ts +368 -94
  187. package/src/plain-values.ts +41 -0
  188. package/src/protobuf.ts +1332 -0
  189. package/src/protocol-grpc.ts +641 -0
  190. package/src/protocol-http.ts +622 -322
  191. package/src/protocol-rest.ts +440 -227
  192. package/src/query.ts +39 -0
  193. package/src/response-validation-strict.ts +327 -0
  194. package/src/response-validation.ts +161 -0
  195. package/src/retry-after.ts +7 -13
  196. package/src/retry.ts +96 -110
  197. package/src/schema-lite-impl.ts +550 -0
  198. package/src/schema-lite-typed.ts +44 -0
  199. package/src/schema-lite.ts +44 -0
  200. package/src/schema.ts +259 -15
  201. package/src/sdk-error.ts +33 -0
  202. package/src/sensitive.ts +154 -0
  203. package/src/telemetry-debug.ts +179 -0
  204. package/src/telemetry-hooks.ts +33 -0
  205. package/src/telemetry-host-rules.ts +39 -0
  206. package/src/telemetry-lambda-context.ts +46 -0
  207. package/src/telemetry-message-context.ts +170 -0
  208. package/src/telemetry-metrics.ts +69 -0
  209. package/src/telemetry-name-template.ts +26 -0
  210. package/src/telemetry-stream.ts +100 -0
  211. package/src/telemetry-xray.ts +66 -0
  212. package/src/telemetry.ts +832 -0
  213. package/src/trait.ts +106 -67
  214. package/src/unknown-error.ts +38 -0
  215. package/src/xml.ts +346 -0
  216. package/lib/api.js.map +0 -1
  217. package/lib/category.js.map +0 -1
  218. package/lib/codegen/cli.d.ts +0 -29
  219. package/lib/codegen/cli.d.ts.map +0 -1
  220. package/lib/codegen/cli.js +0 -165
  221. package/lib/codegen/cli.js.map +0 -1
  222. package/lib/codegen/emit.d.ts +0 -129
  223. package/lib/codegen/emit.d.ts.map +0 -1
  224. package/lib/codegen/emit.js +0 -105
  225. package/lib/codegen/emit.js.map +0 -1
  226. package/lib/codegen/format.d.ts +0 -23
  227. package/lib/codegen/format.d.ts.map +0 -1
  228. package/lib/codegen/format.js +0 -28
  229. package/lib/codegen/format.js.map +0 -1
  230. package/lib/codegen/generator.d.ts +0 -334
  231. package/lib/codegen/generator.d.ts.map +0 -1
  232. package/lib/codegen/generator.js +0 -691
  233. package/lib/codegen/generator.js.map +0 -1
  234. package/lib/codegen/graph.d.ts +0 -36
  235. package/lib/codegen/graph.d.ts.map +0 -1
  236. package/lib/codegen/graph.js +0 -136
  237. package/lib/codegen/graph.js.map +0 -1
  238. package/lib/codegen/members.d.ts +0 -25
  239. package/lib/codegen/members.d.ts.map +0 -1
  240. package/lib/codegen/members.js +0 -55
  241. package/lib/codegen/members.js.map +0 -1
  242. package/lib/codegen/naming.d.ts +0 -29
  243. package/lib/codegen/naming.d.ts.map +0 -1
  244. package/lib/codegen/naming.js +0 -74
  245. package/lib/codegen/naming.js.map +0 -1
  246. package/lib/codegen/openapi-cli.d.ts +0 -38
  247. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  248. package/lib/codegen/openapi-cli.js +0 -107
  249. package/lib/codegen/openapi-cli.js.map +0 -1
  250. package/lib/codegen/openapi.d.ts +0 -115
  251. package/lib/codegen/openapi.d.ts.map +0 -1
  252. package/lib/codegen/openapi.js +0 -1220
  253. package/lib/codegen/openapi.js.map +0 -1
  254. package/lib/codegen/operations.d.ts +0 -24
  255. package/lib/codegen/operations.d.ts.map +0 -1
  256. package/lib/codegen/operations.js +0 -56
  257. package/lib/codegen/operations.js.map +0 -1
  258. package/lib/codegen/pagination.d.ts +0 -39
  259. package/lib/codegen/pagination.d.ts.map +0 -1
  260. package/lib/codegen/pagination.js +0 -33
  261. package/lib/codegen/pagination.js.map +0 -1
  262. package/lib/codegen/prelude.d.ts +0 -15
  263. package/lib/codegen/prelude.d.ts.map +0 -1
  264. package/lib/codegen/prelude.js +0 -60
  265. package/lib/codegen/prelude.js.map +0 -1
  266. package/lib/error-category.js.map +0 -1
  267. package/lib/errors.js.map +0 -1
  268. package/lib/json-patch.d.ts +0 -44
  269. package/lib/json-patch.d.ts.map +0 -1
  270. package/lib/json-patch.js +0 -174
  271. package/lib/json-patch.js.map +0 -1
  272. package/lib/pagination.js.map +0 -1
  273. package/lib/protocol-http.js.map +0 -1
  274. package/lib/protocol-rest.js.map +0 -1
  275. package/lib/retry-after.js.map +0 -1
  276. package/lib/retry.js.map +0 -1
  277. package/lib/schema.js.map +0 -1
  278. package/lib/trait.js.map +0 -1
  279. package/src/codegen/cli.ts +0 -268
  280. package/src/codegen/emit.ts +0 -207
  281. package/src/codegen/format.ts +0 -47
  282. package/src/codegen/generator.ts +0 -1153
  283. package/src/codegen/graph.ts +0 -151
  284. package/src/codegen/members.ts +0 -71
  285. package/src/codegen/naming.ts +0 -86
  286. package/src/codegen/openapi-cli.ts +0 -166
  287. package/src/codegen/openapi.ts +0 -1450
  288. package/src/codegen/operations.ts +0 -76
  289. package/src/codegen/pagination.ts +0 -71
  290. package/src/codegen/prelude.ts +0 -70
  291. package/src/json-patch.ts +0 -222
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Response validation mode, shared by every distilled SDK.
3
+ *
4
+ * Generated SDKs carry a schema for every operation's output. What a
5
+ * protocol does with it on a 2xx response depends on the mode:
6
+ *
7
+ * lenient (default): the response is returned as the protocol read it.
8
+ * A body that does not match the declared output type
9
+ * (a missing member, a wrong primitive, a non-JSON
10
+ * body) still succeeds, except that a non-JSON body for
11
+ * an output with sensitive members fails in every mode
12
+ * (REST-style protocols through core's `checkSuccess`
13
+ * in `protocol-rest`, plus ZeroSSL and AWS).
14
+ * additionalProperties: the response is checked against the output
15
+ * schema, and a mismatch fails the call with the SDK's
16
+ * `<Sdk>ParseError` (AWS: `ParseError`). Keys the
17
+ * schema does not model are allowed and kept.
18
+ * strict: as `additionalProperties`, and a key the schema does
19
+ * not model also fails the call, at any depth. Open
20
+ * objects (an index signature, e.g. OpenAPI
21
+ * `additionalProperties`) and empty structs (opaque
22
+ * outputs) still accept any key.
23
+ *
24
+ * The mode is one {@link ResponseValidation} reference keyed by a string, so
25
+ * a single `Layer` switches every distilled SDK in a program -- AWS,
26
+ * Cloudflare, Neon, ... -- at once, and nests like any other Effect service:
27
+ *
28
+ * ```ts
29
+ * import { ResponseValidation } from "@distilled.cloud/core";
30
+ *
31
+ * // whole program
32
+ * program.pipe(Effect.provide(ResponseValidation.strict));
33
+ *
34
+ * // one call back to lenient inside a strict program
35
+ * Neon.getProject({ projectId }).pipe(Effect.provide(ResponseValidation.lenient));
36
+ * ```
37
+ *
38
+ * The mode is set only by these layers; without one, every call is lenient.
39
+ */
40
+ import * as Context from "effect/Context";
41
+ import * as Effect from "effect/Effect";
42
+ import * as Layer from "effect/Layer";
43
+ import type * as AST from "effect/SchemaAST";
44
+ import { type Decode, SchemaMismatch } from "./response-validation-strict.ts";
45
+ export { SchemaMismatch, withholdActual } from "./response-validation-strict.ts";
46
+ export type Mode = "lenient" | "additionalProperties" | "strict";
47
+ /**
48
+ * The active validation mode. Read by protocols at call time on the calling
49
+ * fiber; `lenient` unless an {@link additionalProperties} or {@link strict}
50
+ * layer is provided.
51
+ */
52
+ export declare const ResponseValidation: Context.Reference<Mode>;
53
+ /**
54
+ * The checker the validating modes use (`exact`: reject unmodeled keys). The
55
+ * `additionalProperties` and `strict` layers provide it, so the checker is
56
+ * bundled only with programs that validate.
57
+ */
58
+ export declare const StrictDecoder: Context.Reference<((ast: AST.AST, exact: boolean) => Decode) | undefined>;
59
+ /**
60
+ * Check every 2xx response against its output schema and fail on a
61
+ * mismatch, including any key the schema does not model.
62
+ */
63
+ export declare const strict: Layer.Layer<never>;
64
+ /**
65
+ * Check every 2xx response against its output schema and fail on a
66
+ * mismatch; keys the schema does not model are allowed.
67
+ */
68
+ export declare const additionalProperties: Layer.Layer<never>;
69
+ /** Return 2xx responses as read, without checking them against the schema. */
70
+ export declare const lenient: Layer.Layer<never>;
71
+ /** Whether the calling fiber validates responses (any mode but lenient). */
72
+ export declare const isValidating: Effect.Effect<boolean>;
73
+ /**
74
+ * For a 2xx body the protocol could not read into the shape it transforms
75
+ * (e.g. invalid JSON): fail with `error` when validating, succeed with
76
+ * `asRead` (usually the body text) in lenient mode.
77
+ */
78
+ export declare const failUnlessLenient: <A, E>(error: E, asRead: A) => Effect.Effect<A, E>;
79
+ /**
80
+ * The schema error for `value` against `outputAst` when validating,
81
+ * `undefined` when it matches or the mode is lenient. Synchronous, for
82
+ * protocols that already hold the calling fiber's context.
83
+ */
84
+ export declare const checkResponse: (context: Context.Context<any>, outputAst: AST.AST, value: unknown) => SchemaMismatch | undefined;
85
+ export declare const validateResponse: <E>(outputAst: AST.AST, value: unknown, onError: (cause: SchemaMismatch) => E) => Effect.Effect<unknown, E>;
86
+ //# sourceMappingURL=response-validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-validation.d.ts","sourceRoot":"","sources":["../src/response-validation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,KAAK,GAAG,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,KAAK,MAAM,EAAc,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAE1F,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEjF,MAAM,MAAM,IAAI,GAAG,SAAS,GAAG,sBAAsB,GAAG,QAAQ,CAAC;AAEjE;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,yBAG9B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,2BACjB,GAAG,CAAC,GAAG,SAAS,OAAO,KAAK,MAAM,cACmD,CAAC;AAoB/F;;;GAGG;AACH,eAAO,MAAM,MAAM,EAAE,KAAK,CAAC,KAAK,CAAC,KAAK,CAMrC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,oBAAoB,EAAE,KAAK,CAAC,KAAK,CAAC,KAAK,CAMnD,CAAC;AAEF,8EAA8E;AAC9E,eAAO,MAAM,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,KAAK,CAEtC,CAAC;AAEF,4EAA4E;AAC5E,eAAO,MAAM,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,CAG/C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,GAAI,CAAC,EAAE,CAAC,SAAS,CAAC,UAAU,CAAC,KAAG,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAG7E,CAAC;AAEJ;;;;GAIG;AACH,eAAO,MAAM,aAAa,YACf,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,aAClB,GAAG,CAAC,GAAG,SACX,OAAO,KACb,cAAc,GAAG,SAUnB,CAAC;AAEF,eAAO,MAAM,gBAAgB,GAAI,CAAC,aACrB,GAAG,CAAC,GAAG,SACX,OAAO,WACL,CAAC,KAAK,EAAE,cAAc,KAAK,CAAC,KACpC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAIvB,CAAC"}
@@ -0,0 +1 @@
1
+ export { response_validation$ResponseValidation as ResponseValidation, response_validation$SchemaMismatch as SchemaMismatch, response_validation$StrictDecoder as StrictDecoder, response_validation$additionalProperties as additionalProperties, response_validation$checkResponse as checkResponse, response_validation$failUnlessLenient as failUnlessLenient, response_validation$isValidating as isValidating, response_validation$lenient as lenient, response_validation$strict as strict, response_validation$validateResponse as validateResponse, response_validation$withholdActual as withholdActual } from "./_bundle/base.js";
@@ -16,7 +16,7 @@
16
16
  */
17
17
  import * as Duration from "effect/Duration";
18
18
  /**
19
- * Header bag — case-insensitive lookup is the caller's responsibility.
19
+ * Header bag -- case-insensitive lookup is the caller's responsibility.
20
20
  *
21
21
  * The helpers in this module read lowercase keys (`retry-after`, `ratelimit`)
22
22
  * because most HTTP clients normalize headers to lowercase. If your client
@@ -41,7 +41,7 @@ export declare const parseRetryAfter: (headers: Headers) => Duration.Duration |
41
41
  * `RateLimit: r=0, t=30` (compact form)
42
42
  *
43
43
  * Returns the `t` (seconds until reset) value as a Duration, but only when
44
- * `r` (remaining quota) is present and equals `0` — i.e., we're actually
44
+ * `r` (remaining quota) is present and equals `0` -- i.e., we're actually
45
45
  * rate-limited right now. Returns `undefined` otherwise.
46
46
  */
47
47
  export declare const parseRatelimit: (headers: Headers) => Duration.Duration | undefined;
@@ -55,7 +55,7 @@ export declare const parseServerRetryHint: (headers: Headers) => Duration.Durati
55
55
  * unless `status` is one whose error class actually declares a `retryAfter`
56
56
  * field (see `RETRYABLE_HTTP_STATUSES`). Use this in `matchError` when you
57
57
  * dispatch off a generic `HTTP_STATUS_MAP` lookup that includes both
58
- * retryable (429/5xx/423) and non-retryable (4xx) classes — it prevents
58
+ * retryable (429/5xx/423) and non-retryable (4xx) classes -- it prevents
59
59
  * stale `retryAfter` properties from being attached to errors like
60
60
  * `BadRequest` or `NotFound` (which would otherwise leak into JSON output).
61
61
  */
@@ -1 +1 @@
1
- {"version":3,"file":"retry-after.d.ts","sourceRoot":"","sources":["../src/retry-after.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAG5C;;;;;;GAMG;AACH,MAAM,MAAM,OAAO,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izes parsing of:
5
- * - `Retry-After` (RFC 7231 §7.1.3): `delay-seconds` (integer) or `HTTP-date`.
6
- * - `RateLimit` (IETF draft-ietf-httpapi-ratelimit-headers): structured
7
- * dictionary `r=<remaining>, t=<seconds-until-reset>`.
8
- *
9
- * Each SDK's `matchError` calls these helpers and attaches the resulting
10
- * `Duration` to retryable errors via the optional `retryAfter` field, where
11
- * the retry policy will honor it with precedence over the default backoff.
12
- *
13
- * Services that use bespoke headers or body fields are expected to do their
14
- * own parsing in the SDK's `matchError`, optionally falling back to these
15
- * helpers for the standard cases.
16
- */
17
- import * as Duration from "effect/Duration";
18
- import { RETRYABLE_HTTP_STATUSES } from "./errors.js";
19
- /**
20
- * Parse the standard `Retry-After` HTTP header per RFC 7231 §7.1.3.
21
- *
22
- * Accepts either a non-negative integer number of seconds (the common case)
23
- * or an HTTP-date. HTTP-dates in the past produce a zero duration.
24
- *
25
- * Returns `undefined` when the header is missing or unparseable.
26
- */
27
- export const parseRetryAfter = (headers) => {
28
- const raw = headers?.["retry-after"];
29
- if (!raw)
30
- return undefined;
31
- const trimmed = raw.trim();
32
- if (trimmed.length === 0)
33
- return undefined;
34
- // delay-seconds: 1*DIGIT (non-negative decimal integer per RFC).
35
- if (/^\d+$/.test(trimmed)) {
36
- const seconds = Number(trimmed);
37
- if (Number.isFinite(seconds) && seconds >= 0) {
38
- return Duration.seconds(seconds);
39
- }
40
- }
41
- // Reject anything that *looks* numeric but isn't a valid delay-seconds.
42
- // Without this, `Date.parse("-5")` happens to return 0 on some engines and
43
- // would silently yield a zero-duration instead of the expected undefined.
44
- if (/^[-+]?\d+(?:\.\d+)?$/.test(trimmed))
45
- return undefined;
46
- // HTTP-date: try Date.parse, which handles RFC 1123 / RFC 850 / asctime.
47
- const ts = Date.parse(trimmed);
48
- if (!Number.isNaN(ts)) {
49
- const ms = Math.max(0, ts - Date.now());
50
- return Duration.millis(ms);
51
- }
52
- return undefined;
53
- };
54
- /**
55
- * Parse the IETF `RateLimit` structured header.
56
- *
57
- * Examples:
58
- * `RateLimit: limit=100, remaining=0, reset=30` (older draft)
59
- * `RateLimit: "default";r=0;t=30` (newer draft)
60
- * `RateLimit: r=0, t=30` (compact form)
61
- *
62
- * Returns the `t` (seconds until reset) value as a Duration, but only when
63
- * `r` (remaining quota) is present and equals `0` — i.e., we're actually
64
- * rate-limited right now. Returns `undefined` otherwise.
65
- */
66
- export const parseRatelimit = (headers) => {
67
- const raw = headers?.["ratelimit"];
68
- if (!raw)
69
- return undefined;
70
- let remaining;
71
- let reset;
72
- // Tokenize on commas and semicolons; tolerate `key=value` and `key =value`.
73
- for (const piece of raw.split(/[,;]/)) {
74
- const eq = piece.indexOf("=");
75
- if (eq < 0)
76
- continue;
77
- const key = piece.slice(0, eq).trim().toLowerCase();
78
- const value = piece.slice(eq + 1).trim();
79
- const num = Number(value);
80
- if (!Number.isFinite(num))
81
- continue;
82
- if (key === "r" || key === "remaining")
83
- remaining = num;
84
- else if (key === "t" || key === "reset")
85
- reset = num;
86
- }
87
- if (remaining !== undefined && remaining > 0)
88
- return undefined;
89
- if (reset === undefined || reset < 0)
90
- return undefined;
91
- return Duration.seconds(reset);
92
- };
93
- /**
94
- * Convenience: try `Retry-After` first, then `RateLimit`. Returns the first
95
- * successful parse, or `undefined` if neither header yields a usable value.
96
- */
97
- export const parseServerRetryHint = (headers) => parseRetryAfter(headers) ?? parseRatelimit(headers);
98
- /**
99
- * Status-gated variant of {@link parseServerRetryHint}. Returns `undefined`
100
- * unless `status` is one whose error class actually declares a `retryAfter`
101
- * field (see `RETRYABLE_HTTP_STATUSES`). Use this in `matchError` when you
102
- * dispatch off a generic `HTTP_STATUS_MAP` lookup that includes both
103
- * retryable (429/5xx/423) and non-retryable (4xx) classes — it prevents
104
- * stale `retryAfter` properties from being attached to errors like
105
- * `BadRequest` or `NotFound` (which would otherwise leak into JSON output).
106
- */
107
- export const parseRetryAfterForStatus = (status, headers) => {
108
- if (!RETRYABLE_HTTP_STATUSES.has(status))
109
- return undefined;
110
- return parseServerRetryHint(headers);
111
- };
112
- //# sourceMappingURL=retry-after.js.map
1
+ export { retry_after$parseRatelimit as parseRatelimit, retry_after$parseRetryAfter as parseRetryAfter, retry_after$parseRetryAfterForStatus as parseRetryAfterForStatus, retry_after$parseServerRetryHint as parseServerRetryHint } from "./_bundle/rest.js";
package/lib/retry.d.ts CHANGED
@@ -1,11 +1,41 @@
1
+ /**
2
+ * Retry Policy System
3
+ *
4
+ * Provides configurable retry policies for API operations.
5
+ * Each SDK creates its own `Retry` Context.Service tag (via
6
+ * `makeRetryService`) and threads it into `makeAPI({ retry: <SDK>.Retry })`
7
+ * so that callers can install a blanket retry policy at the layer level
8
+ * for that SDK without wrapping every call with `Effect.retry`.
9
+ */
1
10
  import * as Context from "effect/Context";
2
11
  import * as Duration from "effect/Duration";
12
+ import * as Effect from "effect/Effect";
3
13
  import * as Layer from "effect/Layer";
4
14
  import * as Ref from "effect/Ref";
5
15
  import * as Schedule from "effect/Schedule";
6
16
  /**
7
17
  * Retry policy options that match the Effect.retry contract.
8
18
  */
19
+ /**
20
+ * Capped exponential backoff, as plain data: the built-in policies use this
21
+ * instead of an Effect `Schedule`, so bundles do not carry the Schedule
22
+ * machinery unless a caller supplies a schedule of their own.
23
+ *
24
+ * Delay before retry `n` (0-based): `min(baseMs * factor^n, capMs)`; a
25
+ * server `retryAfter` hint replaces it when `serverHint` is set (capped by
26
+ * {@link ServerRetryHintCapMs}); otherwise throttling errors wait at least
27
+ * `minThrottleMs`. Then up to `jitterMs` of random jitter is added.
28
+ */
29
+ export interface Backoff {
30
+ readonly baseMs: number;
31
+ readonly factor: number;
32
+ readonly capMs: number;
33
+ /** Stop after this many retries; unlimited when absent. */
34
+ readonly maxRetries?: number;
35
+ readonly jitterMs?: number;
36
+ readonly minThrottleMs?: number;
37
+ readonly serverHint?: boolean;
38
+ }
9
39
  export interface Options {
10
40
  /**
11
41
  * Predicate to determine if an error should trigger a retry.
@@ -15,6 +45,8 @@ export interface Options {
15
45
  * The schedule to use for retrying.
16
46
  */
17
47
  readonly schedule?: Schedule.Schedule<unknown>;
48
+ /** Used when no `schedule` is given. */
49
+ readonly backoff?: Backoff;
18
50
  }
19
51
  /**
20
52
  * A factory function that creates retry policy options with access to the last error ref.
@@ -74,11 +106,22 @@ export declare const serverRetryHintCapLayer: (capMs: number) => Layer.Layer<num
74
106
  * Effective cap when neither {@link ServerRetryHintCapMs} nor
75
107
  * `DISTILLED_SERVER_RETRY_HINT_CAP_MS` is set: {@link DEFAULT_SERVER_RETRY_HINT_CAP_MS}.
76
108
  *
77
- * Reads the `DISTILLED_SERVER_RETRY_HINT_CAP_MS` environment variable via
78
- * Effect's {@link Config} (must be a non-negative finite number; invalid
79
- * values fall back to the default).
109
+ * Reads the `DISTILLED_SERVER_RETRY_HINT_CAP_MS` environment variable (must
110
+ * be a non-negative finite number; invalid values fall back to the default).
111
+ * It reads `process.env` directly: Effect's `Config` would add about 5 KB
112
+ * gzip to every bundle for this one optional knob. Use
113
+ * {@link ServerRetryHintCapMs} to set the cap from code.
80
114
  */
81
115
  export declare const readServerRetryHintCapMsFromEnv: () => number;
116
+ export declare const resolveServerRetryHintCapMs: () => Effect.Effect<number, never, never>;
117
+ /**
118
+ * Extract a server-provided retry hint (in milliseconds) from an error's
119
+ * optional `retryAfter` field, capped by the effective server-hint cap
120
+ * (see {@link ServerRetryHintCapMs} and {@link readServerRetryHintCapMsFromEnv}).
121
+ *
122
+ * Returns `undefined` when the error doesn't carry a hint.
123
+ */
124
+ export declare const serverHintMillis: (error: unknown, capMs: number) => number | undefined;
82
125
  /**
83
126
  * Creates the default retry policy.
84
127
  *
@@ -98,35 +141,11 @@ export declare const readServerRetryHintCapMsFromEnv: () => number;
98
141
  * high request concurrency routinely outlast a short 5-attempt/3s policy
99
142
  * while a genuinely broken credential still fails within seconds.
100
143
  */
144
+ /** The policy used when the context provides none. */
145
+ export declare const defaultOptions: Options;
101
146
  export declare const makeDefault: Factory;
102
- /**
103
- * Factory for the throttling-only retry policy. Honors server hints when
104
- * present so callers using `<SDK>.Retry.throttling` get correct backoff.
105
- */
106
147
  export declare const throttlingFactory: Factory;
107
- /**
108
- * Retry options that retries all throttling errors indefinitely.
109
- *
110
- * Note: prefer {@link throttlingFactory} when you want server-hint honoring.
111
- * This static `Options` form does not have access to `lastError` and so
112
- * cannot read `error.retryAfter`.
113
- */
114
148
  export declare const throttlingOptions: Options;
115
- /**
116
- * Factory for the transient retry policy. Honors server hints when present
117
- * so callers using `<SDK>.Retry.transient` get correct backoff.
118
- */
119
149
  export declare const transientFactory: Factory;
120
- /**
121
- * Retry options that retries all transient errors indefinitely.
122
- *
123
- * This includes:
124
- * 1. Throttling errors
125
- * 2. Server errors
126
- * 3. Network errors
127
- * 4. Locked errors (423)
128
- *
129
- * Note: prefer {@link transientFactory} when you want server-hint honoring.
130
- */
131
150
  export declare const transientOptions: Options;
132
151
  //# sourceMappingURL=retry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../src/retry.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAG5C,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AAEtC,OAAO,KAAK,GAAG,MAAM,YAAY,CAAC;AAClC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAO5C;;GAEG;AACH,MAAM,WAAW,OAAO;IACtB;;OAEG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;IAC7C;;OAEG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;CAChD;AAED;;;GAGG;AACH,MAAM,MAAM,OAAO,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC;AAE/D;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E7C;;;;;;;;;GASG;AACH,eAAO,MAAM,+BAA+B,QAAO,MAKhD,CAAC;AAqBJ,eAAO,MAAM,2BAA2B,QAAO,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,CAe7E,CAAC;AAEL;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB,UAAW,OAAO,SAAS,MAAM,KAAG,MAAM,GAAG,SAIzE,CAAC;AA2BF;;;;;;;;;;;;;;;;;;GAkBG;AACH,sDAAsD;AACtD,eAAO,MAAM,cAAc,EAAE,OAW5B,CAAC;AAEF,eAAO,MAAM,WAAW,EAAE,OAA8B,CAAC;AAWzD,eAAO,MAAM,iBAAiB,EAAE,OAAwC,CAAC;AAMzE,eAAO,MAAM,iBAAiB,EAAE,OAG/B,CAAC;AAEF,eAAO,MAAM,gBAAgB,EAAE,OAAuC,CAAC;AAGvE,eAAO,MAAM,gBAAgB,EAAE,OAAiE,CAAC"}
package/lib/retry.js CHANGED
@@ -1,210 +1 @@
1
- /**
2
- * Retry Policy System
3
- *
4
- * Provides configurable retry policies for API operations.
5
- * Each SDK creates its own `Retry` Context.Service tag (via
6
- * `makeRetryService`) and threads it into `makeAPI({ retry: <SDK>.Retry })`
7
- * so that callers can install a blanket retry policy at the layer level
8
- * for that SDK without wrapping every call with `Effect.retry`.
9
- */
10
- import * as Config from "effect/Config";
11
- import * as Context from "effect/Context";
12
- import * as Duration from "effect/Duration";
13
- import * as Effect from "effect/Effect";
14
- import { pipe } from "effect/Function";
15
- import * as Layer from "effect/Layer";
16
- import * as Option from "effect/Option";
17
- import * as Ref from "effect/Ref";
18
- import * as Schedule from "effect/Schedule";
19
- import { isThrottling, isTransientError } from "./category.js";
20
- // ============================================================================
21
- // Retry Service Factory
22
- // ============================================================================
23
- /**
24
- * Create a typed Retry service class for an SDK.
25
- * Each SDK creates its own Retry service using this factory; the SDK's
26
- * client wraps `makeAPI` with `retry: <SDK>.Retry` so the policy applies
27
- * to every API call below it.
28
- *
29
- * @example
30
- * ```ts
31
- * // packages/<sdk>/src/retry.ts
32
- * export class Retry extends makeRetryService("PlanetScaleRetry") {}
33
- * ```
34
- */
35
- export const makeRetryService = (name) => Context.Service()(name);
36
- // ============================================================================
37
- // Retry Schedule Utilities
38
- // ============================================================================
39
- /**
40
- * Custom jittered schedule helper.
41
- * Adds random jitter between 0-50ms to avoid thundering herd.
42
- */
43
- export const jittered = Schedule.addDelay(() => Effect.succeed(Duration.millis(Math.random() * 50)));
44
- /**
45
- * Cap delay at a maximum duration.
46
- */
47
- export const capped = (max) => Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.isGreaterThan(duration, max) ? max : duration));
48
- // ============================================================================
49
- // Server Hint Helpers
50
- // ============================================================================
51
- /**
52
- * Default cap (milliseconds) on how long we'll honor a server-provided
53
- * `Retry-After` / `RateLimit` hint. A misbehaving server can otherwise park
54
- * us forever.
55
- */
56
- export const DEFAULT_SERVER_RETRY_HINT_CAP_MS = 60_000;
57
- const ENV_SERVER_RETRY_HINT_CAP_MS = "DISTILLED_SERVER_RETRY_HINT_CAP_MS";
58
- /**
59
- * Optional override for the server-hint cap, in milliseconds. When provided
60
- * via `Layer.succeed(ServerRetryHintCapMs, n)`, that value wins over the
61
- * environment.
62
- *
63
- * @example
64
- * ```ts
65
- * Effect.retry(op, policy).pipe(
66
- * Effect.provide(serverRetryHintCapLayer(120_000)),
67
- * )
68
- * ```
69
- */
70
- export const ServerRetryHintCapMs = Context.Service("@distilled.cloud/core/ServerRetryHintCapMs");
71
- /**
72
- * Layer that pins the server `retryAfter` cap to a fixed value (milliseconds).
73
- */
74
- export const serverRetryHintCapLayer = (capMs) => Layer.succeed(ServerRetryHintCapMs, capMs);
75
- const serverRetryHintCapMsConfig = Config.string(ENV_SERVER_RETRY_HINT_CAP_MS).pipe(Config.map((raw) => {
76
- if (raw === "")
77
- return DEFAULT_SERVER_RETRY_HINT_CAP_MS;
78
- const n = Number(raw);
79
- if (!Number.isFinite(n) || n < 0)
80
- return DEFAULT_SERVER_RETRY_HINT_CAP_MS;
81
- return Math.trunc(n);
82
- }), Config.withDefault(DEFAULT_SERVER_RETRY_HINT_CAP_MS));
83
- /**
84
- * Effective cap when neither {@link ServerRetryHintCapMs} nor
85
- * `DISTILLED_SERVER_RETRY_HINT_CAP_MS` is set: {@link DEFAULT_SERVER_RETRY_HINT_CAP_MS}.
86
- *
87
- * Reads the `DISTILLED_SERVER_RETRY_HINT_CAP_MS` environment variable via
88
- * Effect's {@link Config} (must be a non-negative finite number; invalid
89
- * values fall back to the default).
90
- */
91
- export const readServerRetryHintCapMsFromEnv = () => Effect.runSync(serverRetryHintCapMsConfig.pipe(Effect.orElseSucceed(() => DEFAULT_SERVER_RETRY_HINT_CAP_MS)));
92
- const resolveServerRetryHintCapMs = () => Effect.gen(function* () {
93
- const fromLayer = yield* Effect.serviceOption(ServerRetryHintCapMs);
94
- if (Option.isSome(fromLayer)) {
95
- const n = fromLayer.value;
96
- if (Number.isFinite(n) && n >= 0)
97
- return Math.trunc(n);
98
- }
99
- return yield* serverRetryHintCapMsConfig.pipe(Effect.orElseSucceed(() => DEFAULT_SERVER_RETRY_HINT_CAP_MS));
100
- });
101
- /**
102
- * Extract a server-provided retry hint (in milliseconds) from an error's
103
- * optional `retryAfter` field, capped by the effective server-hint cap
104
- * (see {@link ServerRetryHintCapMs} and {@link readServerRetryHintCapMsFromEnv}).
105
- *
106
- * Returns `undefined` when the error doesn't carry a hint.
107
- */
108
- const serverHintMillis = (error, capMs) => {
109
- const hint = error
110
- ?.retryAfter;
111
- if (!Duration.isDuration(hint))
112
- return undefined;
113
- return Math.min(Duration.toMillis(hint), capMs);
114
- };
115
- /**
116
- * Schedule modifier that honors `error.retryAfter` (set by the SDK's
117
- * `matchError` from `Retry-After` / `RateLimit` headers) with precedence
118
- * over the input delay. Falls back to the original delay when no hint is
119
- * present.
120
- */
121
- const honorServerHint = (lastError, baseline) => Schedule.modifyDelay(Effect.fnUntraced(function* ({ duration }) {
122
- const capMs = yield* resolveServerRetryHintCapMs();
123
- const error = yield* Ref.get(lastError);
124
- const hint = serverHintMillis(error, capMs);
125
- if (hint !== undefined)
126
- return hint;
127
- const adjusted = baseline ? baseline(duration, error) : duration;
128
- return Duration.toMillis(adjusted);
129
- }));
130
- // ============================================================================
131
- // Default Retry Policies
132
- // ============================================================================
133
- /**
134
- * Creates the default retry policy.
135
- *
136
- * This policy:
137
- * - Retries transient errors (throttling, server, network, locked errors)
138
- * - Honors `error.retryAfter` (server-provided hint) with precedence, capped
139
- * by {@link DEFAULT_SERVER_RETRY_HINT_CAP_MS} by default; override with
140
- * `DISTILLED_SERVER_RETRY_HINT_CAP_MS` or {@link ServerRetryHintCapMs}
141
- * - Otherwise uses exponential backoff starting at 250ms with a factor of 2,
142
- * capped at 5s per delay
143
- * - Ensures at least 500ms delay for throttling errors
144
- * - Limits to 8 retry attempts
145
- * - Applies jitter to avoid thundering herd
146
- *
147
- * The 250ms/5s-cap/8-attempt shape (~20s of total patience) comes from
148
- * alchemy's Cloudflare provider suite, where transient auth blips under
149
- * high request concurrency routinely outlast a short 5-attempt/3s policy
150
- * while a genuinely broken credential still fails within seconds.
151
- */
152
- export const makeDefault = (lastError) => ({
153
- while: (error) => isTransientError(error),
154
- // The 5s cap applies to the exponential backoff BEFORE the server hint is
155
- // considered, so a server-provided retryAfter longer than 5s is honored in
156
- // full (bounded only by the 60s hint cap inside honorServerHint). Capping
157
- // after the hint would silently clamp e.g. a Retry-After: 30 to 5s.
158
- schedule: Schedule.max([
159
- pipe(Schedule.exponential(250, 2), capped(Duration.seconds(5)), honorServerHint(lastError, (duration, error) => {
160
- if (isThrottling(error) && Duration.toMillis(duration) < 500) {
161
- return Duration.millis(500);
162
- }
163
- return duration;
164
- }), jittered),
165
- Schedule.recurs(8),
166
- ]),
167
- });
168
- /**
169
- * Factory for the throttling-only retry policy. Honors server hints when
170
- * present so callers using `<SDK>.Retry.throttling` get correct backoff.
171
- */
172
- export const throttlingFactory = (lastError) => ({
173
- while: (error) => isThrottling(error),
174
- schedule: pipe(Schedule.exponential(1000, 2), capped(Duration.seconds(5)), honorServerHint(lastError), jittered),
175
- });
176
- /**
177
- * Retry options that retries all throttling errors indefinitely.
178
- *
179
- * Note: prefer {@link throttlingFactory} when you want server-hint honoring.
180
- * This static `Options` form does not have access to `lastError` and so
181
- * cannot read `error.retryAfter`.
182
- */
183
- export const throttlingOptions = {
184
- while: (error) => isThrottling(error),
185
- schedule: pipe(Schedule.exponential(1000, 2), capped(Duration.seconds(5)), jittered),
186
- };
187
- /**
188
- * Factory for the transient retry policy. Honors server hints when present
189
- * so callers using `<SDK>.Retry.transient` get correct backoff.
190
- */
191
- export const transientFactory = (lastError) => ({
192
- while: isTransientError,
193
- schedule: pipe(Schedule.exponential(1000, 2), capped(Duration.seconds(5)), honorServerHint(lastError), jittered),
194
- });
195
- /**
196
- * Retry options that retries all transient errors indefinitely.
197
- *
198
- * This includes:
199
- * 1. Throttling errors
200
- * 2. Server errors
201
- * 3. Network errors
202
- * 4. Locked errors (423)
203
- *
204
- * Note: prefer {@link transientFactory} when you want server-hint honoring.
205
- */
206
- export const transientOptions = {
207
- while: isTransientError,
208
- schedule: pipe(Schedule.exponential(1000, 2), capped(Duration.seconds(5)), jittered),
209
- };
210
- //# sourceMappingURL=retry.js.map
1
+ export { retry$DEFAULT_SERVER_RETRY_HINT_CAP_MS as DEFAULT_SERVER_RETRY_HINT_CAP_MS, retry$ServerRetryHintCapMs as ServerRetryHintCapMs, retry$capped as capped, retry$defaultOptions as defaultOptions, retry$jittered as jittered, retry$makeDefault as makeDefault, retry$makeRetryService as makeRetryService, retry$readServerRetryHintCapMsFromEnv as readServerRetryHintCapMsFromEnv, retry$resolveServerRetryHintCapMs as resolveServerRetryHintCapMs, retry$serverHintMillis as serverHintMillis, retry$serverRetryHintCapLayer as serverRetryHintCapLayer, retry$throttlingFactory as throttlingFactory, retry$throttlingOptions as throttlingOptions, retry$transientFactory as transientFactory, retry$transientOptions as transientOptions } from "./_bundle/base.js";