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

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 (318) hide show
  1. package/lib/_bundle/aws.js +2 -0
  2. package/lib/_bundle/aws.js.map +1 -0
  3. package/lib/_bundle/base.js +5 -0
  4. package/lib/_bundle/base.js.map +1 -0
  5. package/lib/_bundle/graphql.js +3 -0
  6. package/lib/_bundle/graphql.js.map +1 -0
  7. package/lib/_bundle/rest.js +2 -0
  8. package/lib/_bundle/rest.js.map +1 -0
  9. package/lib/_bundle/xml.js +4 -0
  10. package/lib/_bundle/xml.js.map +1 -0
  11. package/lib/api.d.ts +118 -13
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -188
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/category.js +1 -278
  16. package/lib/chunks.d.ts +3 -0
  17. package/lib/chunks.d.ts.map +1 -0
  18. package/lib/chunks.js +1 -0
  19. package/lib/codegen/boolean-string-enums.js +36 -36
  20. package/lib/codegen/chunk.d.ts +7 -0
  21. package/lib/codegen/chunk.d.ts.map +1 -0
  22. package/lib/codegen/chunk.js +139 -0
  23. package/lib/codegen/chunk.js.map +1 -0
  24. package/lib/codegen/cli.d.ts.map +1 -1
  25. package/lib/codegen/cli.js +28 -14
  26. package/lib/codegen/cli.js.map +1 -1
  27. package/lib/codegen/datafy.d.ts +14 -0
  28. package/lib/codegen/datafy.d.ts.map +1 -0
  29. package/lib/codegen/datafy.js +853 -0
  30. package/lib/codegen/datafy.js.map +1 -0
  31. package/lib/codegen/dedupe.d.ts +5 -0
  32. package/lib/codegen/dedupe.d.ts.map +1 -0
  33. package/lib/codegen/dedupe.js +153 -0
  34. package/lib/codegen/dedupe.js.map +1 -0
  35. package/lib/codegen/emit.js +56 -56
  36. package/lib/codegen/format.js +18 -18
  37. package/lib/codegen/generated-at.js +29 -29
  38. package/lib/codegen/generator.d.ts.map +1 -1
  39. package/lib/codegen/generator.js +92 -84
  40. package/lib/codegen/generator.js.map +1 -1
  41. package/lib/codegen/graph.js +36 -36
  42. package/lib/codegen/graphql-client.d.ts +2 -0
  43. package/lib/codegen/graphql-client.d.ts.map +1 -1
  44. package/lib/codegen/graphql-client.js +55 -26
  45. package/lib/codegen/graphql-client.js.map +1 -1
  46. package/lib/codegen/graphql.js +113 -113
  47. package/lib/codegen/latin1.d.ts +3 -0
  48. package/lib/codegen/latin1.d.ts.map +1 -0
  49. package/lib/codegen/latin1.js +126 -0
  50. package/lib/codegen/latin1.js.map +1 -0
  51. package/lib/codegen/members.d.ts +7 -0
  52. package/lib/codegen/members.d.ts.map +1 -1
  53. package/lib/codegen/members.js +26 -19
  54. package/lib/codegen/members.js.map +1 -1
  55. package/lib/codegen/model-diff.js +6 -6
  56. package/lib/codegen/naming.js +19 -19
  57. package/lib/codegen/openapi-cli.js +15 -15
  58. package/lib/codegen/openapi.d.ts +17 -0
  59. package/lib/codegen/openapi.d.ts.map +1 -1
  60. package/lib/codegen/openapi.js +323 -169
  61. package/lib/codegen/openapi.js.map +1 -1
  62. package/lib/codegen/operations.js +14 -14
  63. package/lib/codegen/pagination.js +11 -11
  64. package/lib/codegen/patch-audit.js +57 -57
  65. package/lib/codegen/patches.js +79 -79
  66. package/lib/codegen/prelude.js +19 -19
  67. package/lib/codegen/privatize.d.ts +21 -0
  68. package/lib/codegen/privatize.d.ts.map +1 -0
  69. package/lib/codegen/privatize.js +176 -0
  70. package/lib/codegen/privatize.js.map +1 -0
  71. package/lib/codegen/proto.js +25 -25
  72. package/lib/codegen/pure.d.ts +6 -0
  73. package/lib/codegen/pure.d.ts.map +1 -0
  74. package/lib/codegen/pure.js +91 -0
  75. package/lib/codegen/pure.js.map +1 -0
  76. package/lib/codegen/rewrite-operation-ids.js +108 -108
  77. package/lib/codegen/spec-path.js +57 -57
  78. package/lib/codegen/table.d.ts +5 -0
  79. package/lib/codegen/table.d.ts.map +1 -0
  80. package/lib/codegen/table.js +249 -0
  81. package/lib/codegen/table.js.map +1 -0
  82. package/lib/config.d.ts +27 -0
  83. package/lib/config.d.ts.map +1 -0
  84. package/lib/config.js +1 -0
  85. package/lib/crypto.d.ts +76 -0
  86. package/lib/crypto.d.ts.map +1 -0
  87. package/lib/crypto.js +1 -0
  88. package/lib/debug.d.ts +2 -0
  89. package/lib/debug.d.ts.map +1 -0
  90. package/lib/debug.js +1 -0
  91. package/lib/error-category.d.ts +1 -1
  92. package/lib/error-category.d.ts.map +1 -1
  93. package/lib/error-category.js +1 -46
  94. package/lib/errors.d.ts +62 -62
  95. package/lib/errors.d.ts.map +1 -1
  96. package/lib/errors.js +1 -195
  97. package/lib/graphql.d.ts +31 -20
  98. package/lib/graphql.d.ts.map +1 -1
  99. package/lib/graphql.js +1 -1027
  100. package/lib/graphql.types.js +1 -5
  101. package/lib/index.d.ts +3 -2
  102. package/lib/index.d.ts.map +1 -1
  103. package/lib/index.js +1 -15
  104. package/lib/json-patch.d.ts +2 -2
  105. package/lib/json-patch.js +1 -226
  106. package/lib/json-patch.js.map +1 -1
  107. package/lib/pagination.d.ts +9 -25
  108. package/lib/pagination.d.ts.map +1 -1
  109. package/lib/pagination.js +1 -266
  110. package/lib/plain-values.d.ts +10 -0
  111. package/lib/plain-values.d.ts.map +1 -0
  112. package/lib/plain-values.js +2 -0
  113. package/lib/plain-values.js.map +1 -0
  114. package/lib/protocol-http.d.ts +50 -14
  115. package/lib/protocol-http.d.ts.map +1 -1
  116. package/lib/protocol-http.js +1 -639
  117. package/lib/protocol-rest.d.ts +38 -25
  118. package/lib/protocol-rest.d.ts.map +1 -1
  119. package/lib/protocol-rest.js +1 -267
  120. package/lib/query.js +1 -27
  121. package/lib/response-validation-strict.d.ts +48 -0
  122. package/lib/response-validation-strict.d.ts.map +1 -0
  123. package/lib/response-validation-strict.js +1 -0
  124. package/lib/response-validation.d.ts +43 -25
  125. package/lib/response-validation.d.ts.map +1 -1
  126. package/lib/response-validation.js +1 -76
  127. package/lib/retry-after.d.ts +3 -3
  128. package/lib/retry-after.js +1 -112
  129. package/lib/retry.d.ts +48 -29
  130. package/lib/retry.d.ts.map +1 -1
  131. package/lib/retry.js +1 -209
  132. package/lib/schema-lite-impl.d.ts +158 -0
  133. package/lib/schema-lite-impl.d.ts.map +1 -0
  134. package/lib/schema-lite-impl.js +1 -0
  135. package/lib/schema-lite-typed.d.ts +41 -0
  136. package/lib/schema-lite-typed.d.ts.map +1 -0
  137. package/lib/schema-lite-typed.js +2 -0
  138. package/lib/schema-lite-typed.js.map +1 -0
  139. package/lib/schema-lite.d.ts +40 -0
  140. package/lib/schema-lite.d.ts.map +1 -0
  141. package/lib/schema-lite.js +1 -0
  142. package/lib/schema.d.ts +20 -6
  143. package/lib/schema.d.ts.map +1 -1
  144. package/lib/schema.js +1 -48
  145. package/lib/testing.d.ts +3 -2
  146. package/lib/testing.d.ts.map +1 -1
  147. package/lib/testing.js +1 -40
  148. package/lib/testing.js.map +1 -1
  149. package/lib/trait.d.ts +13 -13
  150. package/lib/trait.d.ts.map +1 -1
  151. package/lib/trait.js +1 -131
  152. package/lib/xml.d.ts +1 -1
  153. package/lib/xml.d.ts.map +1 -1
  154. package/lib/xml.js +1 -311
  155. package/package.json +9 -7
  156. package/src/api.ts +1080 -180
  157. package/src/category.ts +33 -33
  158. package/src/chunks.ts +30 -0
  159. package/src/codegen/chunk.ts +147 -0
  160. package/src/codegen/cli.ts +27 -1
  161. package/src/codegen/datafy.ts +874 -0
  162. package/src/codegen/dedupe.ts +173 -0
  163. package/src/codegen/generator.ts +10 -3
  164. package/src/codegen/graphql-client.ts +49 -15
  165. package/src/codegen/latin1.ts +131 -0
  166. package/src/codegen/members.ts +8 -0
  167. package/src/codegen/openapi.ts +194 -3
  168. package/src/codegen/privatize.ts +200 -0
  169. package/src/codegen/pure.ts +94 -0
  170. package/src/codegen/table.ts +254 -0
  171. package/src/config.ts +216 -0
  172. package/src/crypto.ts +202 -0
  173. package/src/debug.ts +8 -0
  174. package/src/error-category.ts +2 -1
  175. package/src/errors.ts +65 -56
  176. package/src/graphql.ts +109 -62
  177. package/src/graphql.types.ts +9 -7
  178. package/src/index.ts +3 -2
  179. package/src/json-patch.ts +2 -2
  180. package/src/pagination.ts +37 -18
  181. package/src/plain-values.ts +41 -0
  182. package/src/protocol-http.ts +378 -145
  183. package/src/protocol-rest.ts +337 -169
  184. package/src/response-validation-strict.ts +327 -0
  185. package/src/response-validation.ts +101 -50
  186. package/src/retry-after.ts +3 -3
  187. package/src/retry.ts +94 -93
  188. package/src/schema-lite-impl.ts +550 -0
  189. package/src/schema-lite-typed.ts +44 -0
  190. package/src/schema-lite.ts +44 -0
  191. package/src/schema.ts +258 -14
  192. package/src/testing.ts +4 -2
  193. package/src/trait.ts +36 -28
  194. package/src/xml.ts +31 -17
  195. package/lib/api.js.map +0 -1
  196. package/lib/category.js.map +0 -1
  197. package/lib/codegen/boolean-string-enums.test.d.ts +0 -2
  198. package/lib/codegen/boolean-string-enums.test.d.ts.map +0 -1
  199. package/lib/codegen/boolean-string-enums.test.js +0 -275
  200. package/lib/codegen/boolean-string-enums.test.js.map +0 -1
  201. package/lib/codegen/defer-naming.test.d.ts +0 -2
  202. package/lib/codegen/defer-naming.test.d.ts.map +0 -1
  203. package/lib/codegen/defer-naming.test.js +0 -105
  204. package/lib/codegen/defer-naming.test.js.map +0 -1
  205. package/lib/codegen/generated-at.test.d.ts +0 -2
  206. package/lib/codegen/generated-at.test.d.ts.map +0 -1
  207. package/lib/codegen/generated-at.test.js +0 -81
  208. package/lib/codegen/generated-at.test.js.map +0 -1
  209. package/lib/codegen/generator.test.d.ts +0 -2
  210. package/lib/codegen/generator.test.d.ts.map +0 -1
  211. package/lib/codegen/generator.test.js +0 -121
  212. package/lib/codegen/generator.test.js.map +0 -1
  213. package/lib/codegen/graphql-client.test.d.ts +0 -2
  214. package/lib/codegen/graphql-client.test.d.ts.map +0 -1
  215. package/lib/codegen/graphql-client.test.js +0 -171
  216. package/lib/codegen/graphql-client.test.js.map +0 -1
  217. package/lib/codegen/openapi-binary.test.d.ts +0 -2
  218. package/lib/codegen/openapi-binary.test.d.ts.map +0 -1
  219. package/lib/codegen/openapi-binary.test.js +0 -67
  220. package/lib/codegen/openapi-binary.test.js.map +0 -1
  221. package/lib/codegen/patch-audit.test.d.ts +0 -2
  222. package/lib/codegen/patch-audit.test.d.ts.map +0 -1
  223. package/lib/codegen/patch-audit.test.js +0 -141
  224. package/lib/codegen/patch-audit.test.js.map +0 -1
  225. package/lib/codegen/patches.test.d.ts +0 -2
  226. package/lib/codegen/patches.test.d.ts.map +0 -1
  227. package/lib/codegen/patches.test.js +0 -155
  228. package/lib/codegen/patches.test.js.map +0 -1
  229. package/lib/codegen/protocol-imports.test.d.ts +0 -2
  230. package/lib/codegen/protocol-imports.test.d.ts.map +0 -1
  231. package/lib/codegen/protocol-imports.test.js +0 -36
  232. package/lib/codegen/protocol-imports.test.js.map +0 -1
  233. package/lib/codegen/rewrite-operation-ids.test.d.ts +0 -2
  234. package/lib/codegen/rewrite-operation-ids.test.d.ts.map +0 -1
  235. package/lib/codegen/rewrite-operation-ids.test.js +0 -451
  236. package/lib/codegen/rewrite-operation-ids.test.js.map +0 -1
  237. package/lib/codegen/untagged-unions.test.d.ts +0 -2
  238. package/lib/codegen/untagged-unions.test.d.ts.map +0 -1
  239. package/lib/codegen/untagged-unions.test.js +0 -80
  240. package/lib/codegen/untagged-unions.test.js.map +0 -1
  241. package/lib/error-category.js.map +0 -1
  242. package/lib/errors.js.map +0 -1
  243. package/lib/fixtures/xml/upstream-validator.json +0 -397
  244. package/lib/graphql.js.map +0 -1
  245. package/lib/graphql.test.d.ts +0 -2
  246. package/lib/graphql.test.d.ts.map +0 -1
  247. package/lib/graphql.test.js +0 -151
  248. package/lib/graphql.test.js.map +0 -1
  249. package/lib/graphql.types.js.map +0 -1
  250. package/lib/index.js.map +0 -1
  251. package/lib/json-patch.test.d.ts +0 -2
  252. package/lib/json-patch.test.d.ts.map +0 -1
  253. package/lib/json-patch.test.js +0 -65
  254. package/lib/json-patch.test.js.map +0 -1
  255. package/lib/pagination.js.map +0 -1
  256. package/lib/pagination.test.d.ts +0 -2
  257. package/lib/pagination.test.d.ts.map +0 -1
  258. package/lib/pagination.test.js +0 -131
  259. package/lib/pagination.test.js.map +0 -1
  260. package/lib/protocol-http.js.map +0 -1
  261. package/lib/protocol-http.test.d.ts +0 -2
  262. package/lib/protocol-http.test.d.ts.map +0 -1
  263. package/lib/protocol-http.test.js +0 -228
  264. package/lib/protocol-http.test.js.map +0 -1
  265. package/lib/protocol-rest.js.map +0 -1
  266. package/lib/protocol-rest.test.d.ts +0 -2
  267. package/lib/protocol-rest.test.d.ts.map +0 -1
  268. package/lib/protocol-rest.test.js +0 -498
  269. package/lib/protocol-rest.test.js.map +0 -1
  270. package/lib/query.js.map +0 -1
  271. package/lib/response-validation.js.map +0 -1
  272. package/lib/response-validation.test.d.ts +0 -2
  273. package/lib/response-validation.test.d.ts.map +0 -1
  274. package/lib/response-validation.test.js +0 -72
  275. package/lib/response-validation.test.js.map +0 -1
  276. package/lib/retry-after.js.map +0 -1
  277. package/lib/retry-after.test.d.ts +0 -2
  278. package/lib/retry-after.test.d.ts.map +0 -1
  279. package/lib/retry-after.test.js +0 -204
  280. package/lib/retry-after.test.js.map +0 -1
  281. package/lib/retry.js.map +0 -1
  282. package/lib/retry.test.d.ts +0 -2
  283. package/lib/retry.test.d.ts.map +0 -1
  284. package/lib/retry.test.js +0 -407
  285. package/lib/retry.test.js.map +0 -1
  286. package/lib/schema.js.map +0 -1
  287. package/lib/sdks.test.d.ts +0 -2
  288. package/lib/sdks.test.d.ts.map +0 -1
  289. package/lib/sdks.test.js +0 -76
  290. package/lib/sdks.test.js.map +0 -1
  291. package/lib/trait.js.map +0 -1
  292. package/lib/xml.js.map +0 -1
  293. package/lib/xml.test.d.ts +0 -2
  294. package/lib/xml.test.d.ts.map +0 -1
  295. package/lib/xml.test.js +0 -210
  296. package/lib/xml.test.js.map +0 -1
  297. package/src/codegen/boolean-string-enums.test.ts +0 -299
  298. package/src/codegen/defer-naming.test.ts +0 -113
  299. package/src/codegen/generated-at.test.ts +0 -89
  300. package/src/codegen/generator.test.ts +0 -137
  301. package/src/codegen/graphql-client.test.ts +0 -189
  302. package/src/codegen/openapi-binary.test.ts +0 -91
  303. package/src/codegen/patch-audit.test.ts +0 -160
  304. package/src/codegen/patches.test.ts +0 -188
  305. package/src/codegen/protocol-imports.test.ts +0 -39
  306. package/src/codegen/rewrite-operation-ids.test.ts +0 -472
  307. package/src/codegen/untagged-unions.test.ts +0 -85
  308. package/src/fixtures/xml/upstream-validator.json +0 -397
  309. package/src/graphql.test.ts +0 -198
  310. package/src/json-patch.test.ts +0 -77
  311. package/src/pagination.test.ts +0 -169
  312. package/src/protocol-http.test.ts +0 -276
  313. package/src/protocol-rest.test.ts +0 -703
  314. package/src/response-validation.test.ts +0 -89
  315. package/src/retry-after.test.ts +0 -267
  316. package/src/retry.test.ts +0 -566
  317. package/src/sdks.test.ts +0 -87
  318. package/src/xml.test.ts +0 -251
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Replace module-private schema consts with a lazily filled table
3
+ * (dev-time only; runs after `chunkSchemas`).
4
+ *
5
+ * const Customer = __L.at(__c12, 3) as any as S.Schema<Customer>;
6
+ * const Customer2 = Customer;
7
+ * const Status = S.String;
8
+ * ... S.optional(Customer2) ... S.optional(Status) ...
9
+ * becomes
10
+ * ... S.optional(__S(99, __c12, 3)) ... S.optional(S.String) ...
11
+ * const __s: any[] = [];
12
+ * function __S(i: number, f: (j: number) => unknown, j: number): any { return (__s[i] ??= __L.at(f, j)); }
13
+ *
14
+ * A top-level const costs memory at import even when its schema is never
15
+ * built: a context slot, its name in the module's scope info, bytecode in
16
+ * the module body and the lazy wrapper it holds. With the table, importing
17
+ * a module allocates nothing per schema; a schema's lazy wrapper is made the
18
+ * first time any code reaches it, and is the same object every time after.
19
+ */
20
+ import { parseAst } from "rolldown/parseAst";
21
+
22
+ type Node = { readonly type: string; readonly start: number; readonly end: number } & Record<
23
+ string,
24
+ unknown
25
+ >;
26
+
27
+ const isNode = (v: unknown): v is Node =>
28
+ v !== null && typeof v === "object" && typeof (v as Node).type === "string";
29
+
30
+ const stripCasts = (n: Node): Node => {
31
+ while (
32
+ n.type === "TSAsExpression" ||
33
+ n.type === "TSSatisfiesExpression" ||
34
+ n.type === "ParenthesizedExpression"
35
+ )
36
+ n = n.expression as Node;
37
+ return n;
38
+ };
39
+
40
+ export const tableSchemas = (
41
+ code: string,
42
+ filename = "generated.ts",
43
+ ): { code: string; tabled: number } => {
44
+ const program = parseAst(code, { sourceType: "module", lang: "ts" }, filename);
45
+ const body = program.body as unknown as Node[];
46
+
47
+ type Entry =
48
+ | { kind: "at"; chunk: number; j: number; cast?: string }
49
+ | { kind: "alias"; to: string; cast?: string }
50
+ | { kind: "leaf"; text: string; cast?: string };
51
+ const entries = new Map<string, Entry>();
52
+ const removals: Array<[number, number]> = [];
53
+ const declStart = new Map<string, number>();
54
+ let chunkSize = 0;
55
+
56
+ for (const st of body) {
57
+ if (st.type !== "VariableDeclaration" || (st.declarations as Node[]).length !== 1) continue;
58
+ const d = (st.declarations as Node[])[0]!;
59
+ const id = d.id as Node;
60
+ if (id.type !== "Identifier" || !isNode(d.init)) continue;
61
+ const name = id.name as string;
62
+ if (name.startsWith("__")) continue;
63
+ const init = stripCasts(d.init);
64
+ let entry: Entry | undefined;
65
+ if (
66
+ init.type === "CallExpression" &&
67
+ code.slice((init.callee as Node).start, (init.callee as Node).end) === "__L.at"
68
+ ) {
69
+ const [c, j] = init.arguments as Node[];
70
+ const m = /^__c(\d+)$/.exec(code.slice(c!.start, c!.end));
71
+ if (m && j!.type === "Literal")
72
+ entry = { kind: "at", chunk: Number(m[1]), j: j!.value as number };
73
+ } else if (init.type === "Identifier") {
74
+ entry = { kind: "alias", to: init.name as string };
75
+ } else if (
76
+ init.type === "MemberExpression" &&
77
+ !init.computed &&
78
+ (init.object as Node).type === "Identifier" &&
79
+ (init.object as Node).name === "S"
80
+ ) {
81
+ entry = { kind: "leaf", text: code.slice(init.start, init.end) };
82
+ }
83
+ if (!entry) continue;
84
+ // `as any as S.Schema<X>`: the type operation configs infer from.
85
+ const cast = /\bas (?:any as )?(S\.(?:Schema|Codec)<[\s\S]*>)\s*$/.exec(
86
+ code.slice(init.end, (d.init as Node).end),
87
+ )?.[1];
88
+ if (cast) entry.cast = cast;
89
+ entries.set(name, entry);
90
+ declStart.set(name, st.start);
91
+ removals.push([st.start, st.end]);
92
+ }
93
+ // Names also bound inside functions (params, locals, destructuring) stay consts: no scope analysis needed.
94
+ const nested = new Set<string>();
95
+ const collectBindings = (n: unknown): void => {
96
+ if (Array.isArray(n)) return n.forEach(collectBindings);
97
+ if (!isNode(n)) return;
98
+ if (n.type === "Identifier") nested.add(n.name as string);
99
+ else if (n.type === "ObjectPattern")
100
+ for (const p of n.properties as Node[])
101
+ collectBindings(p.type === "RestElement" ? p.argument : p.value);
102
+ else if (n.type === "ArrayPattern") for (const e of n.elements as Node[]) collectBindings(e);
103
+ else if (n.type === "AssignmentPattern") collectBindings(n.left);
104
+ else if (n.type === "RestElement") collectBindings(n.argument);
105
+ };
106
+ const scan = (n: unknown, inFunction: boolean): void => {
107
+ if (Array.isArray(n)) return n.forEach((c) => scan(c, inFunction));
108
+ if (!isNode(n)) return;
109
+ const fn =
110
+ n.type === "ArrowFunctionExpression" ||
111
+ n.type === "FunctionExpression" ||
112
+ n.type === "FunctionDeclaration";
113
+ if (fn) for (const p of n.params as Node[]) collectBindings(p);
114
+ if (inFunction && n.type === "VariableDeclarator") collectBindings(n.id);
115
+ if (
116
+ inFunction &&
117
+ (n.type === "FunctionDeclaration" || n.type === "ClassDeclaration") &&
118
+ isNode(n.id)
119
+ )
120
+ collectBindings(n.id);
121
+ if (n.type === "CatchClause" && n.param) collectBindings(n.param);
122
+ for (const [k, v] of Object.entries(n))
123
+ if (k !== "type" && v !== null && typeof v === "object") scan(v, inFunction || fn);
124
+ };
125
+ scan(body, false);
126
+ // Names exported by an `export { ... }` list must stay bindings.
127
+ for (const st of body)
128
+ if (st.type === "ExportNamedDeclaration" && !st.declaration)
129
+ for (const sp of st.specifiers as Node[]) nested.add((sp.local as Node).name as string);
130
+ for (const name of nested) entries.delete(name);
131
+ // Aliases must end at a table entry or a leaf; anything else stays a const.
132
+ const resolve = (name: string, seen = new Set<string>()): Entry | undefined => {
133
+ const e = entries.get(name);
134
+ if (!e || e.kind !== "alias") return e;
135
+ if (seen.has(name)) return undefined;
136
+ seen.add(name);
137
+ return resolve(e.to, seen);
138
+ };
139
+ // Repeat: deleting one entry can strand aliases that pointed at it.
140
+ for (let changed = true; changed;) {
141
+ changed = false;
142
+ for (const [name, e] of [...entries])
143
+ if (e.kind === "alias" && !resolve(name)) {
144
+ entries.delete(name);
145
+ changed = true;
146
+ }
147
+ }
148
+ const removed = new Set(entries.keys());
149
+ removals.splice(
150
+ 0,
151
+ removals.length,
152
+ ...removals.filter(([start]) => [...removed].some((n) => declStart.get(n) === start)),
153
+ );
154
+ if (![...entries.values()].some((e) => e.kind === "at")) return { code, tabled: 0 };
155
+ for (const e of entries.values()) if (e.kind === "at") chunkSize = Math.max(chunkSize, e.j + 1);
156
+ const shift = Math.ceil(Math.log2(Math.max(2, chunkSize)));
157
+
158
+ const replacement = (name: string): string | undefined => {
159
+ const e = resolve(name);
160
+ if (!e) return undefined;
161
+ if (e.kind === "leaf") return e.text;
162
+ // The builder is named at the call site, so a bundler keeps only the builders a program reaches.
163
+ if (e.kind === "at") return `__S(${(e.chunk << shift) | e.j}, __c${e.chunk}, ${e.j})`;
164
+ return undefined;
165
+ };
166
+
167
+ // Value references (not keys, member names, type positions or the removed declarations).
168
+ const edits: Array<[number, number, string]> = [];
169
+ const removedIds = new Set<number>();
170
+ const visit = (node: unknown, parent?: Node, key?: string): void => {
171
+ if (Array.isArray(node)) {
172
+ for (const c of node) visit(c, parent, key);
173
+ return;
174
+ }
175
+ if (!isNode(node)) return;
176
+ if (
177
+ node.type.startsWith("TS") &&
178
+ node.type !== "TSAsExpression" &&
179
+ node.type !== "TSSatisfiesExpression" &&
180
+ node.type !== "TSNonNullExpression"
181
+ )
182
+ return;
183
+ if (node.type === "Identifier") {
184
+ const isKey =
185
+ parent?.type === "Property" && key === "key" && !parent.computed && !parent.shorthand;
186
+ const isMember =
187
+ parent?.type === "MemberExpression" && key === "property" && !parent.computed;
188
+ const isDecl = parent?.type === "VariableDeclarator" && key === "id";
189
+ if (!isKey && !isMember && !isDecl && entries.has(node.name as string)) {
190
+ let r = replacement(node.name as string);
191
+ const cast = entries.get(node.name as string)?.cast ?? resolve(node.name as string)?.cast;
192
+ if (
193
+ r &&
194
+ cast &&
195
+ parent?.type === "Property" &&
196
+ key === "value" &&
197
+ isNode(parent.key) &&
198
+ ["input", "output"].includes(parent.key.name as string)
199
+ )
200
+ r = `(${r} as any as ${cast})`;
201
+ if (r) {
202
+ const shorthand = parent?.type === "Property" && parent.shorthand;
203
+ edits.push([node.start, node.end, shorthand ? `${node.name}: ${r}` : r]);
204
+ }
205
+ }
206
+ return;
207
+ }
208
+ for (const [k, v] of Object.entries(node)) {
209
+ if (
210
+ k === "type" ||
211
+ k === "start" ||
212
+ k === "end" ||
213
+ k === "typeAnnotation" ||
214
+ k === "typeArguments" ||
215
+ k === "typeParameters" ||
216
+ k === "returnType"
217
+ )
218
+ continue;
219
+ if (v !== null && typeof v === "object") visit(v, node, k);
220
+ }
221
+ };
222
+ for (const st of body) {
223
+ // Import and export lists name bindings of other modules or re-export; not schema references.
224
+ if (st.type === "ImportDeclaration" || st.type === "ExportAllDeclaration") continue;
225
+ if (st.type === "ExportNamedDeclaration" && !st.declaration) continue;
226
+ const isRemoved = removals.some(([s]) => s === st.start);
227
+ if (isRemoved) {
228
+ removedIds.add(st.start);
229
+ continue;
230
+ }
231
+ visit(st);
232
+ }
233
+
234
+ const all: Array<[number, number, string]> = [
235
+ ...edits,
236
+ ...removals.map(([s, e]) => [s, e, ""] as [number, number, string]),
237
+ ];
238
+ all.sort((a, b) => b[0] - a[0]);
239
+ let out = code;
240
+ for (const [s, e, t] of all) {
241
+ let end = e;
242
+ if (t === "") while (out[end] === "\n") end++;
243
+ out = out.slice(0, s) + t + out.slice(end);
244
+ }
245
+ // The table array goes right after the imports: error classes reach schemas while the module evaluates.
246
+ const lastImport = [...body].reverse().find((st) => st.type === "ImportDeclaration");
247
+ const importEnd = lastImport ? lastImport.end : 0;
248
+ // Edits only shift text after their position; the imports precede every edit.
249
+ out = `${out.slice(0, importEnd)}\n// Schema table, filled on first reach (see __S at the end).\nconst __s: any[] = [];${out.slice(importEnd)}`;
250
+ out +=
251
+ "\n// Schema table: entry i is schema j of builder f, made on first reach.\n" +
252
+ `function __S(i: number, f: (j: number) => unknown, j: number): any {\n return (__s[i] ??= __L.at(f, j));\n}\n`;
253
+ return { code: out, tabled: entries.size };
254
+ };
package/src/config.ts ADDED
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Environment configuration for credentials, endpoints and regions: the
3
+ * small part of `effect/Config` that SDKs use, as plain Effects.
4
+ *
5
+ * Importing `effect/Config` costs about 280 KB of heap per process (it pulls
6
+ * in ConfigProvider, Schema-based parsing and their dependencies), and every
7
+ * SDK whose credentials read the environment paid it at import. These
8
+ * readers do the same lookups without it:
9
+ *
10
+ * - When the caller provided a `ConfigProvider` (found by its context key),
11
+ * the value comes from that provider, so `ConfigProvider.fromUnknown(...)`
12
+ * in tests and custom providers on Workers keep working.
13
+ * - Otherwise the value comes from `process.env`, which is what Effect's
14
+ * default provider reads.
15
+ *
16
+ * A missing variable fails with {@link ConfigMissing} (tag `ConfigError`, like
17
+ * Effect's), which `withDefault`, `option` and `orElse` handle.
18
+ *
19
+ * Credentials read these on every request, so without a provider a whole
20
+ * reader tree (`all`, `withDefault`, `orElse`, ...) runs as one synchronous
21
+ * read of `process.env` in a single fiber step: each reader carries a plain
22
+ * `read` function next to its effect, and the combinators compose those.
23
+ * A missing value inside the tree is a plain marker; the tagged error is
24
+ * only built if the whole tree fails.
25
+ */
26
+ import * as Context from "effect/Context";
27
+ import * as Data from "effect/Data";
28
+ import * as Effect from "effect/Effect";
29
+ import * as Option from "effect/Option";
30
+ import * as Redact from "effect/Redacted";
31
+
32
+ /** A required configuration value is missing. */
33
+ export class ConfigMissing
34
+ extends /*@__PURE__*/ Data.TaggedError("ConfigError")<{
35
+ readonly name: string;
36
+ readonly message: string;
37
+ }> {}
38
+
39
+ const CONFIG_PROVIDER_KEY = "effect/ConfigProvider";
40
+
41
+ interface ProvidedConfigProvider {
42
+ readonly load: (
43
+ path: ReadonlyArray<string>,
44
+ ) => Effect.Effect<{ readonly _tag: string; readonly value?: string } | undefined, unknown>;
45
+ }
46
+
47
+ const fromEnv = (name: string): string | undefined =>
48
+ (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.[name];
49
+
50
+ /** A required value that is missing, inside a synchronous read. */
51
+ class Missing {
52
+ constructor(readonly name: string) {}
53
+ }
54
+
55
+ /**
56
+ * A synchronous read that cannot finish on its own (an `orElse` fallback
57
+ * that is an arbitrary effect): the outermost reader runs its effect path.
58
+ */
59
+ const DEFER: unique symbol = /*@__PURE__*/ Symbol("defer");
60
+ type Read<A> = A | Missing | typeof DEFER;
61
+
62
+ const readSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/config/read");
63
+
64
+ /**
65
+ * A reader: an effect, plus the same read as a plain function of
66
+ * `process.env` (used when no `ConfigProvider` is in the context) and the
67
+ * effect-based read used when one is (or when the read defers).
68
+ */
69
+ interface Reader<A> {
70
+ readonly read: () => Read<A>;
71
+ readonly viaEffect: () => Effect.Effect<A, any, any>;
72
+ }
73
+
74
+ const readerOf = <A, E, R>(self: Effect.Effect<A, E, R>): Reader<A> | undefined =>
75
+ (self as unknown as { [readSymbol]?: Reader<A> })[readSymbol];
76
+
77
+ // Looked up by its string key so `effect/ConfigProvider` stays out of bundles.
78
+ const providerKey = { key: CONFIG_PROVIDER_KEY } as Context.Key<never, ProvidedConfigProvider>;
79
+
80
+ const hasProvider = (context: Context.Context<never>): boolean =>
81
+ Context.getOrUndefined(context, providerKey) !== undefined;
82
+
83
+ const missingError = (m: Missing) =>
84
+ new ConfigMissing({ name: m.name, message: `Expected ${m.name} to be set` });
85
+
86
+ const fromReader = <A>(reader: Reader<A>): Effect.Effect<A, any, any> => {
87
+ const effect = Effect.withFiber((fiber) => {
88
+ if (hasProvider(fiber.context as Context.Context<never>)) return reader.viaEffect();
89
+ const value = reader.read();
90
+ if (value === DEFER) return reader.viaEffect();
91
+ return value instanceof Missing ? Effect.fail(missingError(value)) : Effect.succeed(value);
92
+ });
93
+ (effect as unknown as { [readSymbol]: Reader<A> })[readSymbol] = reader;
94
+ return effect;
95
+ };
96
+
97
+ /** The raw value of `name` from the provided `ConfigProvider`, or undefined when unset. */
98
+ const lookup = (name: string): Effect.Effect<string | undefined> =>
99
+ Effect.flatMap(Effect.context<never>(), (context) => {
100
+ const provider = context.mapUnsafe.get(CONFIG_PROVIDER_KEY) as
101
+ | ProvidedConfigProvider
102
+ | undefined;
103
+ if (!provider) return Effect.succeed(fromEnv(name));
104
+ return provider.load([name]).pipe(
105
+ Effect.map((node) => (node?._tag === "Value" ? node.value : undefined)),
106
+ Effect.orElseSucceed(() => undefined),
107
+ );
108
+ });
109
+
110
+ const required = (name: string): Effect.Effect<string, ConfigMissing> =>
111
+ fromReader({
112
+ read: () => fromEnv(name) ?? new Missing(name),
113
+ viaEffect: () =>
114
+ Effect.flatMap(lookup(name), (value) =>
115
+ value === undefined ? Effect.fail(missingError(new Missing(name))) : Effect.succeed(value),
116
+ ),
117
+ }) as Effect.Effect<string, ConfigMissing>;
118
+
119
+ /** The string value of environment variable `name`. */
120
+ export const String = (name: string): Effect.Effect<string, ConfigMissing> => required(name);
121
+
122
+ /** The value of `name`, redacted. */
123
+ export const Redacted = (name: string): Effect.Effect<Redact.Redacted<string>, ConfigMissing> =>
124
+ map((value: string) => Redact.make(value))(required(name));
125
+
126
+ /** The value as an `Option`: `None` when missing. */
127
+ export const option = <A, E, R>(
128
+ self: Effect.Effect<A, E, R>,
129
+ ): Effect.Effect<Option.Option<A>, never, R> => {
130
+ const viaEffect = () =>
131
+ Effect.catch(Effect.map(self, Option.some), () => Effect.succeed(Option.none<A>()));
132
+ const reader = readerOf(self);
133
+ if (!reader) return viaEffect();
134
+ return fromReader({
135
+ read: () => {
136
+ const value = reader.read();
137
+ if (value === DEFER) return DEFER;
138
+ return value instanceof Missing ? Option.none<A>() : Option.some(value);
139
+ },
140
+ viaEffect,
141
+ }) as Effect.Effect<Option.Option<A>, never, R>;
142
+ };
143
+
144
+ /** Use `value` when missing. */
145
+ export const withDefault =
146
+ <B>(value: B) =>
147
+ <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A | B, never, R> => {
148
+ const viaEffect = () => Effect.catch(self, () => Effect.succeed(value));
149
+ const reader = readerOf(self);
150
+ if (!reader) return viaEffect();
151
+ return fromReader<A | B>({
152
+ read: () => {
153
+ const v = reader.read();
154
+ return v instanceof Missing ? value : v;
155
+ },
156
+ viaEffect,
157
+ }) as Effect.Effect<A | B, never, R>;
158
+ };
159
+
160
+ /** Try `that` when missing. */
161
+ export const orElse =
162
+ <A2, E2, R2>(that: () => Effect.Effect<A2, E2, R2>) =>
163
+ <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A | A2, E2, R | R2> => {
164
+ const viaEffect = () => Effect.catch(self, () => that());
165
+ const reader = readerOf(self);
166
+ if (!reader) return viaEffect();
167
+ return fromReader<A | A2>({
168
+ read: () => {
169
+ const v = reader.read();
170
+ if (!(v instanceof Missing)) return v;
171
+ const fallback = readerOf(that());
172
+ return fallback ? fallback.read() : DEFER;
173
+ },
174
+ viaEffect,
175
+ }) as Effect.Effect<A | A2, E2, R | R2>;
176
+ };
177
+
178
+ export const map =
179
+ <A, B>(f: (a: A) => B) =>
180
+ <E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<B, E, R> => {
181
+ const reader = readerOf(self);
182
+ if (!reader) return Effect.map(self, f);
183
+ return fromReader({
184
+ read: () => {
185
+ const v = reader.read();
186
+ return v === DEFER || v instanceof Missing ? v : f(v);
187
+ },
188
+ viaEffect: () => Effect.map(reader.viaEffect(), f),
189
+ }) as Effect.Effect<B, E, R>;
190
+ };
191
+
192
+ /** Read every value of a struct of readers. */
193
+ export const all = <const T extends Record<string, Effect.Effect<any, any, any>>>(
194
+ readers: T,
195
+ ): Effect.Effect<
196
+ { -readonly [K in keyof T]: Effect.Success<T[K]> },
197
+ Effect.Error<T[keyof T]>,
198
+ Effect.Services<T[keyof T]>
199
+ > => {
200
+ const viaEffect = () => Effect.all(readers) as any;
201
+ const keys = Object.keys(readers);
202
+ const parts = keys.map((k) => readerOf(readers[k]!));
203
+ if (parts.some((r) => r === undefined)) return viaEffect();
204
+ return fromReader({
205
+ read: () => {
206
+ const out: Record<string, unknown> = {};
207
+ for (let i = 0; i < keys.length; i++) {
208
+ const v = parts[i]!.read();
209
+ if (v === DEFER || v instanceof Missing) return v;
210
+ out[keys[i]!] = v;
211
+ }
212
+ return out;
213
+ },
214
+ viaEffect: viaEffect,
215
+ }) as any;
216
+ };
package/src/crypto.ts ADDED
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Hashing and HMAC for request signing, as a swappable service.
3
+ *
4
+ * SDKs that sign requests (AWS SigV4, webhook verification, ...) read
5
+ * {@link Crypto} from the context. It is a reference with a default, so it
6
+ * never appears in an operation's requirements: by default it uses
7
+ * `node:crypto` when the runtime has it (Node, Bun, Deno -- synchronous, and
8
+ * several times faster than WebCrypto for small inputs) and WebCrypto
9
+ * (`crypto.subtle`) everywhere else.
10
+ *
11
+ * Provide a layer to choose or replace the implementation:
12
+ *
13
+ * ```ts
14
+ * import { Crypto } from "@distilled.cloud/core";
15
+ * program.pipe(Effect.provide(Crypto.webCrypto)); // force WebCrypto
16
+ * program.pipe(Effect.provide(Crypto.layer(myHsmBackedCrypto)));
17
+ * ```
18
+ *
19
+ * HMAC keys are imported once into an implementation-specific handle
20
+ * ({@link HmacKey}) so callers can cache them: preparing a raw key is most of
21
+ * an HMAC's cost in both `node:crypto` and WebCrypto.
22
+ */
23
+ import * as Context from "effect/Context";
24
+ import * as Data from "effect/Data";
25
+ import * as Effect from "effect/Effect";
26
+ import * as Layer from "effect/Layer";
27
+
28
+ /** A hashing or HMAC operation failed in the crypto implementation. */
29
+ export class CryptoError
30
+ extends /*@__PURE__*/ Data.TaggedError("CryptoError")<{
31
+ readonly operation: "hmac" | "sha256" | "importKey";
32
+ readonly cause: unknown;
33
+ }> {}
34
+
35
+ /** An imported HMAC-SHA256 key. Opaque: only the implementation that made it can use it. */
36
+ export interface HmacKey {
37
+ readonly "~distilled/HmacKey": unique symbol;
38
+ }
39
+
40
+ export type Bytes = Uint8Array | string;
41
+
42
+ export interface CryptoImpl {
43
+ /** Name for diagnostics, e.g. "node:crypto" or "webcrypto". */
44
+ readonly name: string;
45
+ readonly sha256: (data: Bytes) => Effect.Effect<Uint8Array, CryptoError>;
46
+ readonly importHmacKey: (key: Bytes) => Effect.Effect<HmacKey, CryptoError>;
47
+ readonly hmacSha256: (key: HmacKey, data: Bytes) => Effect.Effect<Uint8Array, CryptoError>;
48
+ /**
49
+ * The same operations as plain functions, for implementations that are
50
+ * synchronous (node:crypto). They throw on failure. Signers use them to
51
+ * skip the per-operation effects when present.
52
+ */
53
+ readonly sync?: {
54
+ readonly sha256: (data: Bytes) => Uint8Array;
55
+ readonly importHmacKey: (key: Bytes) => HmacKey;
56
+ readonly hmacSha256: (key: HmacKey, data: Bytes) => Uint8Array;
57
+ /** `hex(sha256(data))`, when the implementation can produce hex itself. */
58
+ readonly sha256Hex?: (data: Bytes) => string;
59
+ /** `hex(hmacSha256(key, data))`, when the implementation can produce hex itself. */
60
+ readonly hmacSha256Hex?: (key: HmacKey, data: Bytes) => string;
61
+ };
62
+ }
63
+
64
+ //#region node:crypto
65
+
66
+ interface Digest {
67
+ update(d: Bytes): { digest(): Uint8Array; digest(encoding: "hex"): string };
68
+ }
69
+
70
+ interface NodeCryptoModule {
71
+ createSecretKey(key: Uint8Array): object;
72
+ createHmac(alg: string, key: object): Digest;
73
+ createHash(alg: string): Digest;
74
+ /** One-shot hashing (Node 20.12+/21.7+). */
75
+ hash?: (alg: string, data: Bytes, encoding: "hex") => string;
76
+ }
77
+
78
+ /** `node:crypto`, found without a static import so this module loads in any runtime. */
79
+ const nodeModule = (): NodeCryptoModule | undefined => {
80
+ try {
81
+ const p = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;
82
+ return p?.getBuiltinModule?.("node:crypto") as NodeCryptoModule | undefined;
83
+ } catch {
84
+ return undefined;
85
+ }
86
+ };
87
+
88
+ const encoder = /*@__PURE__*/ new TextEncoder();
89
+ const toBytes = (data: Bytes): Uint8Array =>
90
+ typeof data === "string" ? encoder.encode(data) : data;
91
+
92
+ /** `node:crypto` implementation, or undefined when the runtime has no `node:crypto`. */
93
+ export const makeNodeCrypto = (): CryptoImpl | undefined => {
94
+ const c = nodeModule();
95
+ if (!c) return undefined;
96
+ return {
97
+ name: "node:crypto",
98
+ sync: {
99
+ sha256: (data) => c.createHash("sha256").update(data).digest(),
100
+ importHmacKey: (key) => c.createSecretKey(toBytes(key)) as unknown as HmacKey,
101
+ hmacSha256: (key, data) =>
102
+ c
103
+ .createHmac("sha256", key as unknown as object)
104
+ .update(data)
105
+ .digest(),
106
+ sha256Hex: c.hash
107
+ ? (data) => c.hash!("sha256", data, "hex")
108
+ : (data) => c.createHash("sha256").update(data).digest("hex"),
109
+ hmacSha256Hex: (key, data) =>
110
+ c
111
+ .createHmac("sha256", key as unknown as object)
112
+ .update(data)
113
+ .digest("hex"),
114
+ },
115
+ sha256: (data) =>
116
+ Effect.try({
117
+ try: () => c.createHash("sha256").update(data).digest(),
118
+ catch: (cause) => new CryptoError({ operation: "sha256", cause }),
119
+ }),
120
+ importHmacKey: (key) =>
121
+ Effect.try({
122
+ try: () => c.createSecretKey(toBytes(key)) as unknown as HmacKey,
123
+ catch: (cause) => new CryptoError({ operation: "importKey", cause }),
124
+ }),
125
+ hmacSha256: (key, data) =>
126
+ Effect.try({
127
+ try: () =>
128
+ c
129
+ .createHmac("sha256", key as unknown as object)
130
+ .update(data)
131
+ .digest(),
132
+ catch: (cause) => new CryptoError({ operation: "hmac", cause }),
133
+ }),
134
+ };
135
+ };
136
+
137
+ //#endregion
138
+
139
+ //#region WebCrypto
140
+
141
+ const buffer = (data: Bytes): Uint8Array<ArrayBuffer> => {
142
+ const b = toBytes(data);
143
+ return b.buffer instanceof ArrayBuffer ? (b as Uint8Array<ArrayBuffer>) : new Uint8Array(b);
144
+ };
145
+
146
+ /** WebCrypto (`crypto.subtle`) implementation. */
147
+ export const makeWebCrypto = (): CryptoImpl => ({
148
+ name: "webcrypto",
149
+ sha256: (data) =>
150
+ Effect.tryPromise({
151
+ try: async () => new Uint8Array(await crypto.subtle.digest("SHA-256", buffer(data))),
152
+ catch: (cause) => new CryptoError({ operation: "sha256", cause }),
153
+ }),
154
+ importHmacKey: (key) =>
155
+ Effect.tryPromise({
156
+ try: () =>
157
+ crypto.subtle.importKey("raw", buffer(key), { name: "HMAC", hash: "SHA-256" }, false, [
158
+ "sign",
159
+ ]) as Promise<unknown> as Promise<HmacKey>,
160
+ catch: (cause) => new CryptoError({ operation: "importKey", cause }),
161
+ }),
162
+ hmacSha256: (key, data) =>
163
+ Effect.tryPromise({
164
+ try: async () =>
165
+ new Uint8Array(await crypto.subtle.sign("HMAC", key as unknown as CryptoKey, buffer(data))),
166
+ catch: (cause) => new CryptoError({ operation: "hmac", cause }),
167
+ }),
168
+ });
169
+
170
+ //#endregion
171
+
172
+ /** The crypto implementation signing code uses. Defaults to `node:crypto` when available, else WebCrypto. */
173
+ export const Crypto = /*@__PURE__*/ Context.Reference<CryptoImpl>("@distilled.cloud/core/Crypto", {
174
+ defaultValue: () => makeNodeCrypto() ?? makeWebCrypto(),
175
+ });
176
+
177
+ /** Use a custom implementation. */
178
+ export const layer = (impl: CryptoImpl): Layer.Layer<never> => Layer.succeed(Crypto, impl);
179
+
180
+ /** Force WebCrypto, even where `node:crypto` exists. */
181
+ export const webCrypto: Layer.Layer<never> = /*@__PURE__*/ Layer.sync(Crypto, makeWebCrypto);
182
+
183
+ /** Force `node:crypto`; fails at layer build when the runtime has none. */
184
+ export const nodeCrypto: Layer.Layer<never, CryptoError> = /*@__PURE__*/ Layer.effect(
185
+ Crypto,
186
+ /*@__PURE__*/ Effect.suspend(() => {
187
+ const impl = makeNodeCrypto();
188
+ return impl
189
+ ? Effect.succeed(impl)
190
+ : Effect.fail(
191
+ new CryptoError({ operation: "importKey", cause: "node:crypto is not available" }),
192
+ );
193
+ }),
194
+ );
195
+
196
+ const HEX = /*@__PURE__*/ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
197
+ /** Lowercase hex of bytes. */
198
+ export const hex = (bytes: Uint8Array): string => {
199
+ let out = "";
200
+ for (let i = 0; i < bytes.length; i++) out += HEX[bytes[i]!];
201
+ return out;
202
+ };
package/src/debug.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `DISTILLED_DEBUG_HTTP`, read once. Protocols check it on every request,
3
+ * and a `process.env` read is a C++ getter call: about 1 us each.
4
+ */
5
+ let flag: boolean | undefined;
6
+ export const debugHttp = (): boolean =>
7
+ (flag ??= !!(globalThis as { process?: { env?: Record<string, string | undefined> } }).process
8
+ ?.env?.DISTILLED_DEBUG_HTTP);
@@ -1,4 +1,5 @@
1
- import { Effect, Predicate } from "effect";
1
+ import * as Effect from "effect/Effect";
2
+ import * as Predicate from "effect/Predicate";
2
3
 
3
4
  export const categoriesKey = "@distilled/meta/error-categories";
4
5