@distilled.cloud/core 1.0.0-rc.15 → 1.0.0-rc.16
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.
- package/lib/api.d.ts +118 -13
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +755 -147
- package/lib/api.js.map +1 -1
- package/lib/category.d.ts.map +1 -1
- package/lib/category.js +146 -146
- package/lib/category.js.map +1 -1
- package/lib/chunks.d.ts +3 -0
- package/lib/chunks.d.ts.map +1 -0
- package/lib/chunks.js +11 -0
- package/lib/chunks.js.map +1 -0
- package/lib/codegen/boolean-string-enums.js +36 -36
- package/lib/codegen/chunk.d.ts +7 -0
- package/lib/codegen/chunk.d.ts.map +1 -0
- package/lib/codegen/chunk.js +139 -0
- package/lib/codegen/chunk.js.map +1 -0
- package/lib/codegen/cli.d.ts.map +1 -1
- package/lib/codegen/cli.js +28 -14
- package/lib/codegen/cli.js.map +1 -1
- package/lib/codegen/datafy.d.ts +14 -0
- package/lib/codegen/datafy.d.ts.map +1 -0
- package/lib/codegen/datafy.js +853 -0
- package/lib/codegen/datafy.js.map +1 -0
- package/lib/codegen/dedupe.d.ts +5 -0
- package/lib/codegen/dedupe.d.ts.map +1 -0
- package/lib/codegen/dedupe.js +153 -0
- package/lib/codegen/dedupe.js.map +1 -0
- package/lib/codegen/emit.js +56 -56
- package/lib/codegen/format.js +18 -18
- package/lib/codegen/generated-at.js +29 -29
- package/lib/codegen/generator.d.ts.map +1 -1
- package/lib/codegen/generator.js +92 -84
- package/lib/codegen/generator.js.map +1 -1
- package/lib/codegen/graph.js +36 -36
- package/lib/codegen/graphql-client.d.ts +2 -0
- package/lib/codegen/graphql-client.d.ts.map +1 -1
- package/lib/codegen/graphql-client.js +55 -26
- package/lib/codegen/graphql-client.js.map +1 -1
- package/lib/codegen/graphql.js +113 -113
- package/lib/codegen/latin1.d.ts +3 -0
- package/lib/codegen/latin1.d.ts.map +1 -0
- package/lib/codegen/latin1.js +126 -0
- package/lib/codegen/latin1.js.map +1 -0
- package/lib/codegen/members.d.ts +7 -0
- package/lib/codegen/members.d.ts.map +1 -1
- package/lib/codegen/members.js +26 -19
- package/lib/codegen/members.js.map +1 -1
- package/lib/codegen/model-diff.js +6 -6
- package/lib/codegen/naming.js +19 -19
- package/lib/codegen/openapi-cli.js +15 -15
- package/lib/codegen/openapi.d.ts +17 -0
- package/lib/codegen/openapi.d.ts.map +1 -1
- package/lib/codegen/openapi.js +323 -169
- package/lib/codegen/openapi.js.map +1 -1
- package/lib/codegen/operations.js +14 -14
- package/lib/codegen/pagination.js +11 -11
- package/lib/codegen/patch-audit.js +57 -57
- package/lib/codegen/patches.js +79 -79
- package/lib/codegen/prelude.js +19 -19
- package/lib/codegen/privatize.d.ts +21 -0
- package/lib/codegen/privatize.d.ts.map +1 -0
- package/lib/codegen/privatize.js +176 -0
- package/lib/codegen/privatize.js.map +1 -0
- package/lib/codegen/proto.js +25 -25
- package/lib/codegen/pure.d.ts +6 -0
- package/lib/codegen/pure.d.ts.map +1 -0
- package/lib/codegen/pure.js +91 -0
- package/lib/codegen/pure.js.map +1 -0
- package/lib/codegen/rewrite-operation-ids.js +108 -108
- package/lib/codegen/spec-path.js +57 -57
- package/lib/codegen/table.d.ts +5 -0
- package/lib/codegen/table.d.ts.map +1 -0
- package/lib/codegen/table.js +249 -0
- package/lib/codegen/table.js.map +1 -0
- package/lib/config.d.ts +27 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +161 -0
- package/lib/config.js.map +1 -0
- package/lib/crypto.d.ts +76 -0
- package/lib/crypto.d.ts.map +1 -0
- package/lib/crypto.js +130 -0
- package/lib/crypto.js.map +1 -0
- package/lib/debug.d.ts +2 -0
- package/lib/debug.d.ts.map +1 -0
- package/lib/debug.js +8 -0
- package/lib/debug.js.map +1 -0
- package/lib/error-category.d.ts +1 -1
- package/lib/error-category.d.ts.map +1 -1
- package/lib/error-category.js +7 -6
- package/lib/error-category.js.map +1 -1
- package/lib/errors.d.ts +62 -62
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +117 -114
- package/lib/errors.js.map +1 -1
- package/lib/graphql.d.ts +31 -20
- package/lib/graphql.d.ts.map +1 -1
- package/lib/graphql.js +150 -119
- package/lib/graphql.js.map +1 -1
- package/lib/graphql.types.js +4 -3
- package/lib/graphql.types.js.map +1 -1
- package/lib/index.d.ts +3 -2
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +15 -14
- package/lib/index.js.map +1 -1
- package/lib/json-patch.d.ts +2 -2
- package/lib/json-patch.js +28 -28
- package/lib/pagination.d.ts +9 -25
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +95 -90
- package/lib/pagination.js.map +1 -1
- package/lib/plain-values.d.ts +10 -0
- package/lib/plain-values.d.ts.map +1 -0
- package/lib/plain-values.js +40 -0
- package/lib/plain-values.js.map +1 -0
- package/lib/protocol-http.d.ts +50 -14
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +351 -178
- package/lib/protocol-http.js.map +1 -1
- package/lib/protocol-rest.d.ts +38 -25
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +238 -130
- package/lib/protocol-rest.js.map +1 -1
- package/lib/query.js +16 -16
- package/lib/response-validation-strict.d.ts +48 -0
- package/lib/response-validation-strict.d.ts.map +1 -0
- package/lib/response-validation-strict.js +284 -0
- package/lib/response-validation-strict.js.map +1 -0
- package/lib/response-validation.d.ts +43 -25
- package/lib/response-validation.d.ts.map +1 -1
- package/lib/response-validation.js +112 -70
- package/lib/response-validation.js.map +1 -1
- package/lib/retry-after.d.ts +3 -3
- package/lib/retry-after.js +49 -49
- package/lib/retry.d.ts +48 -29
- package/lib/retry.d.ts.map +1 -1
- package/lib/retry.js +142 -154
- package/lib/retry.js.map +1 -1
- package/lib/schema-lite-impl.d.ts +158 -0
- package/lib/schema-lite-impl.d.ts.map +1 -0
- package/lib/schema-lite-impl.js +341 -0
- package/lib/schema-lite-impl.js.map +1 -0
- package/lib/schema-lite-typed.d.ts +41 -0
- package/lib/schema-lite-typed.d.ts.map +1 -0
- package/lib/schema-lite-typed.js +27 -0
- package/lib/schema-lite-typed.js.map +1 -0
- package/lib/schema-lite.d.ts +40 -0
- package/lib/schema-lite.d.ts.map +1 -0
- package/lib/schema-lite.js +31 -0
- package/lib/schema-lite.js.map +1 -0
- package/lib/schema.d.ts +20 -6
- package/lib/schema.d.ts.map +1 -1
- package/lib/schema.js +202 -30
- package/lib/schema.js.map +1 -1
- package/lib/testing.d.ts +3 -2
- package/lib/testing.d.ts.map +1 -1
- package/lib/testing.js +22 -21
- package/lib/testing.js.map +1 -1
- package/lib/trait.d.ts +13 -13
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +80 -80
- package/lib/trait.js.map +1 -1
- package/lib/xml.d.ts +1 -1
- package/lib/xml.d.ts.map +1 -1
- package/lib/xml.js +38 -26
- package/lib/xml.js.map +1 -1
- package/package.json +9 -7
- package/src/api.ts +1079 -180
- package/src/category.ts +33 -33
- package/src/chunks.ts +30 -0
- package/src/codegen/chunk.ts +147 -0
- package/src/codegen/cli.ts +27 -1
- package/src/codegen/datafy.ts +874 -0
- package/src/codegen/dedupe.ts +173 -0
- package/src/codegen/generator.ts +10 -3
- package/src/codegen/graphql-client.ts +49 -15
- package/src/codegen/latin1.ts +131 -0
- package/src/codegen/members.ts +8 -0
- package/src/codegen/openapi.ts +194 -3
- package/src/codegen/privatize.ts +200 -0
- package/src/codegen/pure.ts +94 -0
- package/src/codegen/table.ts +254 -0
- package/src/config.ts +216 -0
- package/src/crypto.ts +202 -0
- package/src/debug.ts +8 -0
- package/src/error-category.ts +2 -1
- package/src/errors.ts +65 -56
- package/src/graphql.ts +109 -62
- package/src/graphql.types.ts +9 -7
- package/src/index.ts +3 -2
- package/src/json-patch.ts +2 -2
- package/src/pagination.ts +37 -18
- package/src/plain-values.ts +41 -0
- package/src/protocol-http.ts +378 -145
- package/src/protocol-rest.ts +337 -169
- package/src/response-validation-strict.ts +327 -0
- package/src/response-validation.ts +101 -50
- package/src/retry-after.ts +3 -3
- package/src/retry.ts +94 -93
- package/src/schema-lite-impl.ts +550 -0
- package/src/schema-lite-typed.ts +44 -0
- package/src/schema-lite.ts +44 -0
- package/src/schema.ts +258 -14
- package/src/testing.ts +4 -2
- package/src/trait.ts +36 -28
- package/src/xml.ts +31 -17
- package/lib/codegen/boolean-string-enums.test.d.ts +0 -2
- package/lib/codegen/boolean-string-enums.test.d.ts.map +0 -1
- package/lib/codegen/boolean-string-enums.test.js +0 -275
- package/lib/codegen/boolean-string-enums.test.js.map +0 -1
- package/lib/codegen/defer-naming.test.d.ts +0 -2
- package/lib/codegen/defer-naming.test.d.ts.map +0 -1
- package/lib/codegen/defer-naming.test.js +0 -105
- package/lib/codegen/defer-naming.test.js.map +0 -1
- package/lib/codegen/generated-at.test.d.ts +0 -2
- package/lib/codegen/generated-at.test.d.ts.map +0 -1
- package/lib/codegen/generated-at.test.js +0 -81
- package/lib/codegen/generated-at.test.js.map +0 -1
- package/lib/codegen/generator.test.d.ts +0 -2
- package/lib/codegen/generator.test.d.ts.map +0 -1
- package/lib/codegen/generator.test.js +0 -121
- package/lib/codegen/generator.test.js.map +0 -1
- package/lib/codegen/graphql-client.test.d.ts +0 -2
- package/lib/codegen/graphql-client.test.d.ts.map +0 -1
- package/lib/codegen/graphql-client.test.js +0 -171
- package/lib/codegen/graphql-client.test.js.map +0 -1
- package/lib/codegen/openapi-binary.test.d.ts +0 -2
- package/lib/codegen/openapi-binary.test.d.ts.map +0 -1
- package/lib/codegen/openapi-binary.test.js +0 -67
- package/lib/codegen/openapi-binary.test.js.map +0 -1
- package/lib/codegen/patch-audit.test.d.ts +0 -2
- package/lib/codegen/patch-audit.test.d.ts.map +0 -1
- package/lib/codegen/patch-audit.test.js +0 -141
- package/lib/codegen/patch-audit.test.js.map +0 -1
- package/lib/codegen/patches.test.d.ts +0 -2
- package/lib/codegen/patches.test.d.ts.map +0 -1
- package/lib/codegen/patches.test.js +0 -155
- package/lib/codegen/patches.test.js.map +0 -1
- package/lib/codegen/protocol-imports.test.d.ts +0 -2
- package/lib/codegen/protocol-imports.test.d.ts.map +0 -1
- package/lib/codegen/protocol-imports.test.js +0 -36
- package/lib/codegen/protocol-imports.test.js.map +0 -1
- package/lib/codegen/rewrite-operation-ids.test.d.ts +0 -2
- package/lib/codegen/rewrite-operation-ids.test.d.ts.map +0 -1
- package/lib/codegen/rewrite-operation-ids.test.js +0 -451
- package/lib/codegen/rewrite-operation-ids.test.js.map +0 -1
- package/lib/codegen/untagged-unions.test.d.ts +0 -2
- package/lib/codegen/untagged-unions.test.d.ts.map +0 -1
- package/lib/codegen/untagged-unions.test.js +0 -80
- package/lib/codegen/untagged-unions.test.js.map +0 -1
- package/lib/fixtures/xml/upstream-validator.json +0 -397
- package/lib/graphql.test.d.ts +0 -2
- package/lib/graphql.test.d.ts.map +0 -1
- package/lib/graphql.test.js +0 -151
- package/lib/graphql.test.js.map +0 -1
- package/lib/json-patch.test.d.ts +0 -2
- package/lib/json-patch.test.d.ts.map +0 -1
- package/lib/json-patch.test.js +0 -65
- package/lib/json-patch.test.js.map +0 -1
- package/lib/pagination.test.d.ts +0 -2
- package/lib/pagination.test.d.ts.map +0 -1
- package/lib/pagination.test.js +0 -131
- package/lib/pagination.test.js.map +0 -1
- package/lib/protocol-http.test.d.ts +0 -2
- package/lib/protocol-http.test.d.ts.map +0 -1
- package/lib/protocol-http.test.js +0 -228
- package/lib/protocol-http.test.js.map +0 -1
- package/lib/protocol-rest.test.d.ts +0 -2
- package/lib/protocol-rest.test.d.ts.map +0 -1
- package/lib/protocol-rest.test.js +0 -498
- package/lib/protocol-rest.test.js.map +0 -1
- package/lib/response-validation.test.d.ts +0 -2
- package/lib/response-validation.test.d.ts.map +0 -1
- package/lib/response-validation.test.js +0 -72
- package/lib/response-validation.test.js.map +0 -1
- package/lib/retry-after.test.d.ts +0 -2
- package/lib/retry-after.test.d.ts.map +0 -1
- package/lib/retry-after.test.js +0 -204
- package/lib/retry-after.test.js.map +0 -1
- package/lib/retry.test.d.ts +0 -2
- package/lib/retry.test.d.ts.map +0 -1
- package/lib/retry.test.js +0 -407
- package/lib/retry.test.js.map +0 -1
- package/lib/sdks.test.d.ts +0 -2
- package/lib/sdks.test.d.ts.map +0 -1
- package/lib/sdks.test.js +0 -76
- package/lib/sdks.test.js.map +0 -1
- package/lib/xml.test.d.ts +0 -2
- package/lib/xml.test.d.ts.map +0 -1
- package/lib/xml.test.js +0 -210
- package/lib/xml.test.js.map +0 -1
- package/src/codegen/boolean-string-enums.test.ts +0 -299
- package/src/codegen/defer-naming.test.ts +0 -113
- package/src/codegen/generated-at.test.ts +0 -89
- package/src/codegen/generator.test.ts +0 -137
- package/src/codegen/graphql-client.test.ts +0 -189
- package/src/codegen/openapi-binary.test.ts +0 -91
- package/src/codegen/patch-audit.test.ts +0 -160
- package/src/codegen/patches.test.ts +0 -188
- package/src/codegen/protocol-imports.test.ts +0 -39
- package/src/codegen/rewrite-operation-ids.test.ts +0 -472
- package/src/codegen/untagged-unions.test.ts +0 -85
- package/src/fixtures/xml/upstream-validator.json +0 -397
- package/src/graphql.test.ts +0 -198
- package/src/json-patch.test.ts +0 -77
- package/src/pagination.test.ts +0 -169
- package/src/protocol-http.test.ts +0 -276
- package/src/protocol-rest.test.ts +0 -703
- package/src/response-validation.test.ts +0 -89
- package/src/retry-after.test.ts +0 -267
- package/src/retry.test.ts +0 -566
- package/src/sdks.test.ts +0 -87
- 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);
|
package/src/error-category.ts
CHANGED