@distilled.cloud/core 1.0.0-rc.18 → 1.0.0-rc.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/_bundle/base.js +2 -2
- package/lib/_bundle/base.js.map +1 -1
- package/lib/_bundle/graphql.js +2 -2
- package/lib/_bundle/graphql.js.map +1 -1
- package/lib/_bundle/grpc.js +2 -0
- package/lib/_bundle/grpc.js.map +1 -0
- package/lib/_bundle/rest.js +1 -1
- package/lib/_bundle/rest.js.map +1 -1
- package/lib/_bundle/xml.js +1 -1
- package/lib/_bundle/xml.js.map +1 -1
- package/lib/annotations.d.ts +2 -0
- package/lib/annotations.d.ts.map +1 -1
- package/lib/annotations.js +1 -1
- package/lib/annotations.js.map +1 -1
- package/lib/api.d.ts +37 -1
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -1
- package/lib/errors.d.ts +1 -0
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -1
- package/lib/graphql.d.ts +12 -5
- package/lib/graphql.d.ts.map +1 -1
- package/lib/graphql.types.d.ts.map +1 -1
- package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-http2.js +6 -0
- package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.js +5 -0
- package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
- package/lib/grpc-transport-node-http2.d.ts +19 -0
- package/lib/grpc-transport-node-http2.d.ts.map +1 -0
- package/lib/grpc-transport-node-http2.js +2 -0
- package/lib/grpc-transport-node-http2.js.map +1 -0
- package/lib/grpc-transport.d.ts +76 -0
- package/lib/grpc-transport.d.ts.map +1 -0
- package/lib/grpc-transport.js +1 -0
- package/lib/hpack.d.ts +34 -0
- package/lib/hpack.d.ts.map +1 -0
- package/lib/hpack.js +2 -0
- package/lib/hpack.js.map +1 -0
- package/lib/index.d.ts +3 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +3 -0
- package/lib/pagination.d.ts +22 -2
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +1 -1
- package/lib/protobuf.d.ts +92 -0
- package/lib/protobuf.d.ts.map +1 -0
- package/lib/protobuf.js +1 -0
- package/lib/protocol-grpc.d.ts +86 -0
- package/lib/protocol-grpc.d.ts.map +1 -0
- package/lib/protocol-grpc.js +1 -0
- package/lib/protocol-http.d.ts +11 -6
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-rest.d.ts +12 -8
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/response-validation.d.ts +1 -1
- package/lib/response-validation.d.ts.map +1 -1
- package/lib/sdk-error.d.ts +27 -0
- package/lib/sdk-error.d.ts.map +1 -0
- package/lib/sdk-error.js +1 -0
- package/lib/sensitive.d.ts +28 -0
- package/lib/sensitive.d.ts.map +1 -0
- package/lib/sensitive.js +2 -0
- package/lib/sensitive.js.map +1 -0
- package/lib/telemetry-debug.d.ts +2 -10
- package/lib/telemetry-debug.d.ts.map +1 -1
- package/lib/telemetry-debug.js +1 -1
- package/lib/telemetry-debug.js.map +1 -1
- package/lib/telemetry-stream.d.ts +3 -1
- package/lib/telemetry-stream.d.ts.map +1 -1
- package/lib/telemetry-stream.js +1 -1
- package/lib/telemetry-stream.js.map +1 -1
- package/lib/telemetry.d.ts +23 -4
- package/lib/telemetry.d.ts.map +1 -1
- package/lib/telemetry.js +2 -2
- package/lib/telemetry.js.map +1 -1
- package/lib/trait.d.ts +7 -0
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +1 -1
- package/lib/xml.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/annotations.ts +16 -0
- package/src/api.ts +199 -25
- package/src/errors.ts +4 -0
- package/src/graphql.ts +68 -45
- package/src/graphql.types.ts +5 -1
- package/src/grpc-transport-cloudflare-http2.ts +494 -0
- package/src/grpc-transport-cloudflare-sockets.ts +299 -0
- package/src/grpc-transport-node-http2.ts +234 -0
- package/src/grpc-transport.ts +118 -0
- package/src/hpack.ts +331 -0
- package/src/index.ts +3 -0
- package/src/pagination.ts +75 -3
- package/src/protobuf.ts +1332 -0
- package/src/protocol-grpc.ts +641 -0
- package/src/protocol-http.ts +30 -30
- package/src/protocol-rest.ts +49 -118
- package/src/response-validation.ts +4 -2
- package/src/sdk-error.ts +33 -0
- package/src/sensitive.ts +154 -0
- package/src/telemetry-debug.ts +65 -21
- package/src/telemetry-stream.ts +16 -7
- package/src/telemetry.ts +91 -27
- package/src/trait.ts +10 -0
- package/src/xml.ts +10 -1
- package/lib/debug.d.ts +0 -2
- package/lib/debug.d.ts.map +0 -1
- package/lib/debug.js +0 -1
- package/src/debug.ts +0 -11
package/src/protocol-http.ts
CHANGED
|
@@ -13,14 +13,15 @@ import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
|
13
13
|
* {@link matchTypedError}).
|
|
14
14
|
*/
|
|
15
15
|
import type * as AST from "effect/SchemaAST";
|
|
16
|
-
import { getAnn, getProps } from "./annotations.ts";
|
|
16
|
+
import { getAnn, getProps, resolveNode } from "./annotations.ts";
|
|
17
17
|
import * as Category from "./category.ts";
|
|
18
|
-
import { debugHttp } from "./debug.ts";
|
|
19
18
|
import { isOpaqueValue } from "./plain-values.ts";
|
|
20
19
|
import * as Schema from "./schema-lite-typed.ts";
|
|
20
|
+
import { SdkError } from "./sdk-error.ts";
|
|
21
21
|
import { restoreStack, suppressStack } from "./telemetry.ts";
|
|
22
22
|
import {
|
|
23
23
|
bodySymbol,
|
|
24
|
+
commaDelimitedSymbol,
|
|
24
25
|
deepQuerySymbol,
|
|
25
26
|
formDataFileSymbol,
|
|
26
27
|
getErrorMatchers,
|
|
@@ -42,7 +43,7 @@ import {
|
|
|
42
43
|
|
|
43
44
|
//#region AST helpers (survive S.optional / Suspend / transforms)
|
|
44
45
|
|
|
45
|
-
export { getAnn, getProps } from "./annotations.ts";
|
|
46
|
+
export { getAnn, getProps, resolveNode } from "./annotations.ts";
|
|
46
47
|
|
|
47
48
|
export const getPropAnn = (prop: AST.PropertySignature, symbol: symbol): unknown =>
|
|
48
49
|
getAnn(prop.type, symbol);
|
|
@@ -53,21 +54,6 @@ export const nameOf = (prop: AST.PropertySignature, symbol: symbol): string => {
|
|
|
53
54
|
return typeof v === "string" ? v : String(prop.name);
|
|
54
55
|
};
|
|
55
56
|
|
|
56
|
-
/** Resolve wrappers to the real node: Suspend, encoding, optional/null unions. */
|
|
57
|
-
export const resolveNode = (ast: AST.AST): AST.AST => {
|
|
58
|
-
if (ast._tag === "Suspend") return resolveNode(ast.thunk());
|
|
59
|
-
if (ast.encoding && ast.encoding.length > 0) return resolveNode(ast.encoding[0]!.to);
|
|
60
|
-
if (ast._tag === "Union") {
|
|
61
|
-
const real = (ast as AST.Union).types.filter(
|
|
62
|
-
(t) =>
|
|
63
|
-
t._tag !== "Undefined" &&
|
|
64
|
-
t._tag !== "Null" &&
|
|
65
|
-
!(t._tag === "Literal" && (t as any).literal === null),
|
|
66
|
-
);
|
|
67
|
-
if (real.length === 1) return resolveNode(real[0]!);
|
|
68
|
-
}
|
|
69
|
-
return ast;
|
|
70
|
-
};
|
|
71
57
|
//#endregion
|
|
72
58
|
|
|
73
59
|
//#region Response headers on outputs
|
|
@@ -444,6 +430,12 @@ export interface BuildRequestOptions {
|
|
|
444
430
|
* Defaults to the key verbatim.
|
|
445
431
|
*/
|
|
446
432
|
readonly unknownKeyToWire?: (key: string) => string;
|
|
433
|
+
/**
|
|
434
|
+
* Send `{}` on a method that takes a body even when the input declares no
|
|
435
|
+
* body members. Connect unary RPCs (E2B's envd) POST JSON for every call,
|
|
436
|
+
* and refuse a bodyless one with 415.
|
|
437
|
+
*/
|
|
438
|
+
readonly emptyJsonBody?: boolean;
|
|
447
439
|
}
|
|
448
440
|
|
|
449
441
|
/**
|
|
@@ -499,6 +491,8 @@ interface MemberPlan {
|
|
|
499
491
|
/** `{name+}` placeholder. */
|
|
500
492
|
readonly greedy: boolean;
|
|
501
493
|
readonly stringEncoded: boolean;
|
|
494
|
+
/** A list query member sent as one comma-separated parameter. */
|
|
495
|
+
readonly commaDelimited: boolean;
|
|
502
496
|
/** `mapKeys(type, value, "encode", rootDict)` returns the value unchanged. */
|
|
503
497
|
readonly verbatim: boolean;
|
|
504
498
|
}
|
|
@@ -515,12 +509,12 @@ interface RequestPlan {
|
|
|
515
509
|
|
|
516
510
|
const plans = /*@__PURE__*/ new WeakMap<AST.AST, RequestPlan>();
|
|
517
511
|
|
|
518
|
-
const planFor = (inputAst: AST.AST): RequestPlan => {
|
|
512
|
+
const planFor = (inputAst: AST.AST): RequestPlan | SdkError => {
|
|
519
513
|
let plan = plans.get(inputAst);
|
|
520
514
|
if (plan !== undefined) return plan;
|
|
521
515
|
const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
|
|
522
516
|
if (!http) {
|
|
523
|
-
|
|
517
|
+
return new SdkError({ message: "operation input is missing the Http() trait" });
|
|
524
518
|
}
|
|
525
519
|
const rootDict = getAnn(inputAst, keyDictionarySymbol) as KeyDictionaryEntries | undefined;
|
|
526
520
|
const members: MemberPlan[] = [];
|
|
@@ -563,6 +557,7 @@ const planFor = (inputAst: AST.AST): RequestPlan => {
|
|
|
563
557
|
preserve: typeof preserve === "string" ? preserve : undefined,
|
|
564
558
|
greedy,
|
|
565
559
|
stringEncoded: hasPropAnn(prop, stringEncodedSymbol),
|
|
560
|
+
commaDelimited: hasPropAnn(prop, commaDelimitedSymbol),
|
|
566
561
|
verbatim: rootDict === undefined && mapsVerbatim(prop.type, "encode"),
|
|
567
562
|
});
|
|
568
563
|
}
|
|
@@ -638,14 +633,16 @@ export const invalidLabel = (
|
|
|
638
633
|
*
|
|
639
634
|
* Fails with {@link InvalidInput}, before anything is sent, when a label is
|
|
640
635
|
* `.` or `..` (for a greedy `{name+}` label, when any of its segments is).
|
|
641
|
-
*
|
|
642
|
-
*
|
|
636
|
+
* Fails with {@link SdkError} when the input schema is missing the `Http()`
|
|
637
|
+
* trait (a codegen bug the generator refuses).
|
|
643
638
|
*/
|
|
644
639
|
export const buildRequest = (
|
|
645
640
|
options: BuildRequestOptions,
|
|
646
|
-
): Effect.Effect<HttpClientRequest.HttpClientRequest, InvalidInput> => {
|
|
641
|
+
): Effect.Effect<HttpClientRequest.HttpClientRequest, InvalidInput | SdkError> => {
|
|
647
642
|
const request = requestOrInvalid(options);
|
|
648
|
-
return request instanceof InvalidInput
|
|
643
|
+
return request instanceof InvalidInput || request instanceof SdkError
|
|
644
|
+
? Effect.fail(request)
|
|
645
|
+
: Effect.succeed(request);
|
|
649
646
|
};
|
|
650
647
|
|
|
651
648
|
const requestOrInvalid = ({
|
|
@@ -655,9 +652,11 @@ const requestOrInvalid = ({
|
|
|
655
652
|
headers: baseHeaders,
|
|
656
653
|
mapMemberHeader,
|
|
657
654
|
unknownKeyToWire,
|
|
658
|
-
|
|
655
|
+
emptyJsonBody,
|
|
656
|
+
}: BuildRequestOptions): HttpClientRequest.HttpClientRequest | InvalidInput | SdkError => {
|
|
659
657
|
const inputObj = (input ?? {}) as Record<string, unknown>;
|
|
660
658
|
const plan = planFor(inputAst);
|
|
659
|
+
if (plan instanceof SdkError) return plan;
|
|
661
660
|
const { http, rootDict, members, known } = plan;
|
|
662
661
|
let hasBodyMembers = plan.hasBodyMembers;
|
|
663
662
|
|
|
@@ -701,7 +700,11 @@ const requestOrInvalid = ({
|
|
|
701
700
|
break;
|
|
702
701
|
}
|
|
703
702
|
case "query":
|
|
704
|
-
|
|
703
|
+
if (m.commaDelimited && Array.isArray(value)) {
|
|
704
|
+
(query ??= new URLSearchParams()).append(m.name, value.map(String).join(","));
|
|
705
|
+
} else {
|
|
706
|
+
appendQuery((query ??= new URLSearchParams()), m.name, value);
|
|
707
|
+
}
|
|
705
708
|
break;
|
|
706
709
|
case "deepQuery": {
|
|
707
710
|
// Deep-object query member (T.DeepQuery): a nested struct expands into
|
|
@@ -759,9 +762,6 @@ const requestOrInvalid = ({
|
|
|
759
762
|
|
|
760
763
|
const qs = query === undefined ? "" : query.toString();
|
|
761
764
|
const url = qs ? `${baseUrl}${uri}?${qs}` : `${baseUrl}${uri}`;
|
|
762
|
-
if (debugHttp()) {
|
|
763
|
-
console.error(`[distilled] -> ${http.method} ${http.uri}`);
|
|
764
|
-
}
|
|
765
765
|
|
|
766
766
|
const request = makeRequest(http.method, url, headers);
|
|
767
767
|
const bodied = !BODYLESS.has(http.method);
|
|
@@ -861,7 +861,7 @@ const requestOrInvalid = ({
|
|
|
861
861
|
// The `{}`-when-empty rule below stays limited to methods that expect a
|
|
862
862
|
// body, so a bodyless method with nothing set still sends nothing.
|
|
863
863
|
bodyKeys > 0 ||
|
|
864
|
-
(hasBodyMembers && bodied && http.method !== "DELETE")
|
|
864
|
+
((hasBodyMembers || emptyJsonBody === true) && bodied && http.method !== "DELETE")
|
|
865
865
|
) {
|
|
866
866
|
// Send `{}` rather than no body when the schema declares body members --
|
|
867
867
|
// some endpoints reject a missing JSON body outright.
|
package/src/protocol-rest.ts
CHANGED
|
@@ -4,28 +4,27 @@ import * as HttpClient from "effect/http/HttpClient";
|
|
|
4
4
|
import type * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
5
5
|
import type * as HttpClientResponse from "effect/http/HttpClientResponse";
|
|
6
6
|
import * as Layer from "effect/Layer";
|
|
7
|
-
import * as Redacted from "effect/Redacted";
|
|
8
7
|
import type * as AST from "effect/SchemaAST";
|
|
9
|
-
import { rawResponseRootSymbol } from "./annotations.ts";
|
|
8
|
+
import { rawResponseRootSymbol, resolveNode } from "./annotations.ts";
|
|
10
9
|
import * as API from "./api.ts";
|
|
11
|
-
import { debugHttp } from "./debug.ts";
|
|
12
10
|
import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
|
|
13
11
|
import { recordPageHeaders } from "./pagination.ts";
|
|
14
|
-
import {
|
|
12
|
+
import { unwrapRedactedDeep } from "./plain-values.ts";
|
|
15
13
|
import {
|
|
16
14
|
buildRequest,
|
|
17
15
|
getAnn,
|
|
18
16
|
getProps,
|
|
17
|
+
hasPropAnn,
|
|
19
18
|
mapKeys,
|
|
20
19
|
mapsVerbatim,
|
|
21
20
|
matchTypedError,
|
|
22
|
-
resolveNode,
|
|
23
21
|
responseHeaderMembers,
|
|
24
22
|
withResponseHeaders,
|
|
25
23
|
type ResponseHeaderMember,
|
|
26
24
|
} from "./protocol-http.ts";
|
|
27
25
|
import { checkResponse, withholdActual } from "./response-validation.ts";
|
|
28
26
|
import { parseRetryAfterForStatus } from "./retry-after.ts";
|
|
27
|
+
import { holdsSensitive, sensitiveValueSymbol, wrapSensitive } from "./sensitive.ts";
|
|
29
28
|
/**
|
|
30
29
|
* Generic REST protocol factory for simple bearer/header-auth JSON APIs
|
|
31
30
|
* (Neon, Fly.io, PlanetScale, Supabase, Turso, ...).
|
|
@@ -44,7 +43,8 @@ import { parseRetryAfterForStatus } from "./retry-after.ts";
|
|
|
44
43
|
* failing with the provider's `parseError` (see
|
|
45
44
|
* `core/response-validation`) -> `Redacted` wrapping of members
|
|
46
45
|
* marked with {@link SensitiveValue}; non-2xx -> typed error:
|
|
47
|
-
*
|
|
46
|
+
* the provider's `classifyError`, then per-op matcher
|
|
47
|
+
* classes (`matchTypedError`), then the status
|
|
48
48
|
* map (default `HTTP_STATUS_MAP`), then an `InternalServerError`
|
|
49
49
|
* for unmapped 5xx, then the provider's `unknownError` fallback
|
|
50
50
|
* -- with `retryAfter` durations stamped from the standard hint
|
|
@@ -60,9 +60,7 @@ import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
|
|
|
60
60
|
// Traits
|
|
61
61
|
// =============================================================================
|
|
62
62
|
|
|
63
|
-
export
|
|
64
|
-
"@distilled.cloud/core/sensitive-value",
|
|
65
|
-
);
|
|
63
|
+
export { sensitiveValueSymbol };
|
|
66
64
|
/**
|
|
67
65
|
* Marks a string member, map value or list element as sensitive (mirrors
|
|
68
66
|
* `smithy.api#sensitive`). The REST protocol wraps decoded values in
|
|
@@ -102,83 +100,7 @@ export const BinaryResponse = () => makeAnnotation(binaryResponseSymbol, true);
|
|
|
102
100
|
|
|
103
101
|
export { unwrapRedactedDeep };
|
|
104
102
|
|
|
105
|
-
|
|
106
|
-
* A sensitive value that {@link wrapSensitive} wraps: a string, or any
|
|
107
|
-
* non-null value of an untyped (`S.Unknown`) schema, such as a JSON scalar or
|
|
108
|
-
* object. A typed struct is walked so its own sensitive members are wrapped
|
|
109
|
-
* and its type stays accurate.
|
|
110
|
-
*/
|
|
111
|
-
const isSecretValue = (type: AST.AST, v: unknown): boolean =>
|
|
112
|
-
typeof v === "string" || (v !== null && resolveNode(type)._tag === "Unknown");
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Walk a decoded (TS-named) value alongside its schema AST, wrapping values
|
|
116
|
-
* marked {@link SensitiveValue} (members, map values, list elements) in
|
|
117
|
-
* `Redacted`. Keys the schema doesn't model pass through. A union applies
|
|
118
|
-
* every arm in turn; a map arm skips keys a sibling arm names.
|
|
119
|
-
*/
|
|
120
|
-
export const wrapSensitive = (
|
|
121
|
-
ast: AST.AST,
|
|
122
|
-
value: unknown,
|
|
123
|
-
siblingNames?: ReadonlySet<string>,
|
|
124
|
-
): unknown => {
|
|
125
|
-
if (
|
|
126
|
-
value === null ||
|
|
127
|
-
typeof value !== "object" ||
|
|
128
|
-
isOpaqueValue(value) ||
|
|
129
|
-
Redacted.isRedacted(value)
|
|
130
|
-
) {
|
|
131
|
-
return value;
|
|
132
|
-
}
|
|
133
|
-
const node = resolveNode(ast);
|
|
134
|
-
if (node._tag === "Union") {
|
|
135
|
-
// Redact every possible sensitive member, including in partial responses.
|
|
136
|
-
const named = new Set(
|
|
137
|
-
node.types.flatMap((arm) => {
|
|
138
|
-
const armNode = resolveNode(arm);
|
|
139
|
-
return armNode._tag === "Objects" ? getProps(armNode).map((p) => String(p.name)) : [];
|
|
140
|
-
}),
|
|
141
|
-
);
|
|
142
|
-
return node.types.reduce<unknown>(
|
|
143
|
-
(redacted, arm) => wrapSensitive(arm, redacted, named),
|
|
144
|
-
value,
|
|
145
|
-
);
|
|
146
|
-
}
|
|
147
|
-
if (node._tag === "Arrays") {
|
|
148
|
-
if (!Array.isArray(value)) return value;
|
|
149
|
-
const elem = (node as any).rest?.[0] as AST.AST | undefined;
|
|
150
|
-
if (!elem) return value;
|
|
151
|
-
const sensitive = getAnn(elem, sensitiveValueSymbol) !== undefined;
|
|
152
|
-
return value.map((v) =>
|
|
153
|
-
sensitive && isSecretValue(elem, v) && !Redacted.isRedacted(v)
|
|
154
|
-
? Redacted.make(v)
|
|
155
|
-
: wrapSensitive(elem, v),
|
|
156
|
-
);
|
|
157
|
-
}
|
|
158
|
-
if (node._tag === "Objects" && !Array.isArray(value)) {
|
|
159
|
-
const props = getProps(node);
|
|
160
|
-
const mapValue = node.indexSignatures[0]?.type;
|
|
161
|
-
if (props.length === 0 && mapValue === undefined) return value;
|
|
162
|
-
const byName = new Map(props.map((p) => [String(p.name), p]));
|
|
163
|
-
// fromEntries keeps a `__proto__` key an entry instead of the prototype.
|
|
164
|
-
return Object.fromEntries(
|
|
165
|
-
Object.entries(value as Record<string, unknown>).flatMap<[string, unknown]>(([k, v]) => {
|
|
166
|
-
if (v === undefined) return [];
|
|
167
|
-
const prop = byName.get(k);
|
|
168
|
-
const type = prop?.type ?? (siblingNames?.has(k) ? undefined : mapValue);
|
|
169
|
-
if (type === undefined) return [[k, v]];
|
|
170
|
-
// Union arms run over each other's output: keep a value one already wrapped.
|
|
171
|
-
if (getAnn(type, sensitiveValueSymbol) !== undefined && isSecretValue(type, v)) {
|
|
172
|
-
return [[k, Redacted.isRedacted(v) ? v : Redacted.make(v)]];
|
|
173
|
-
}
|
|
174
|
-
return [[k, wrapSensitive(type, v)]];
|
|
175
|
-
}),
|
|
176
|
-
);
|
|
177
|
-
}
|
|
178
|
-
return value;
|
|
179
|
-
};
|
|
180
|
-
|
|
181
|
-
const sensitiveOutputs = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
|
|
103
|
+
export { wrapSensitive };
|
|
182
104
|
|
|
183
105
|
/**
|
|
184
106
|
* Whether any member, map value or list element reachable from `ast` is
|
|
@@ -186,29 +108,7 @@ const sensitiveOutputs = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
|
|
|
186
108
|
* {@link wrapSensitive}, and its parse errors withhold the response body (see
|
|
187
109
|
* {@link checkSuccess}, which every REST-style protocol's success path uses).
|
|
188
110
|
*/
|
|
189
|
-
export const hasSensitiveMember
|
|
190
|
-
const cached = sensitiveOutputs.get(ast);
|
|
191
|
-
if (cached !== undefined) return cached;
|
|
192
|
-
const seen = new Set<AST.AST>();
|
|
193
|
-
const visit = (node: AST.AST): boolean => {
|
|
194
|
-
node = resolveNode(node);
|
|
195
|
-
if (seen.has(node)) return false;
|
|
196
|
-
seen.add(node);
|
|
197
|
-
if (node._tag === "Union") return node.types.some(visit);
|
|
198
|
-
if (node._tag === "Arrays") {
|
|
199
|
-
return [...node.elements, ...node.rest].some(
|
|
200
|
-
(e) => getAnn(e, sensitiveValueSymbol) !== undefined || visit(e),
|
|
201
|
-
);
|
|
202
|
-
}
|
|
203
|
-
if (node._tag !== "Objects") return false;
|
|
204
|
-
return [...node.propertySignatures, ...node.indexSignatures].some(
|
|
205
|
-
(member) => getAnn(member.type, sensitiveValueSymbol) !== undefined || visit(member.type),
|
|
206
|
-
);
|
|
207
|
-
};
|
|
208
|
-
const result = visit(ast);
|
|
209
|
-
sensitiveOutputs.set(ast, result);
|
|
210
|
-
return result;
|
|
211
|
-
};
|
|
111
|
+
export const hasSensitiveMember: (ast: AST.AST) => boolean = holdsSensitive;
|
|
212
112
|
|
|
213
113
|
// =============================================================================
|
|
214
114
|
// Protocol factory
|
|
@@ -281,6 +181,13 @@ export interface RestProtocolOptions<C> {
|
|
|
281
181
|
* else to {@link unknownError}.
|
|
282
182
|
*/
|
|
283
183
|
readonly statusMap?: Readonly<Record<number, new (args: any) => any>>;
|
|
184
|
+
/**
|
|
185
|
+
* The provider's own reading of a failure, consulted before per-op typed
|
|
186
|
+
* matching and the status map: return the error to fail with, or
|
|
187
|
+
* `undefined` to decode the failure as usual. For rules a status alone
|
|
188
|
+
* can't express, e.g. a 403 that is a rate limit because of its headers.
|
|
189
|
+
*/
|
|
190
|
+
readonly classifyError?: (info: RestErrorInfo) => unknown;
|
|
284
191
|
/** Fallback error for failures nothing else matched. */
|
|
285
192
|
readonly unknownError: (info: RestErrorInfo) => unknown;
|
|
286
193
|
/**
|
|
@@ -299,6 +206,8 @@ export interface RestProtocolOptions<C> {
|
|
|
299
206
|
readonly mapMemberHeader?: (name: string, value: string) => string;
|
|
300
207
|
/** Passed through to `buildRequest` (wire names for unmodeled input keys). */
|
|
301
208
|
readonly unknownKeyToWire?: (key: string) => string;
|
|
209
|
+
/** Passed through to `buildRequest`: send `{}` when a bodied call has no body members. */
|
|
210
|
+
readonly emptyJsonBody?: boolean;
|
|
302
211
|
}
|
|
303
212
|
|
|
304
213
|
const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
|
|
@@ -390,6 +299,14 @@ export const validateSuccess = <E>(
|
|
|
390
299
|
interface DecodePlan {
|
|
391
300
|
readonly binary: boolean;
|
|
392
301
|
readonly verbatim: boolean;
|
|
302
|
+
/**
|
|
303
|
+
* A member of a structure output that receives the whole body
|
|
304
|
+
* (`T.RawResponse()` next to header members), e.g. a bare JSON array with
|
|
305
|
+
* its next-page token in a response header.
|
|
306
|
+
*/
|
|
307
|
+
readonly bodyMember: AST.PropertySignature | undefined;
|
|
308
|
+
/** The output is a bare string, so an empty body decodes to `""`. */
|
|
309
|
+
readonly text: boolean;
|
|
393
310
|
/** Members read from response headers (`T.Header`). */
|
|
394
311
|
readonly headers: ReadonlyArray<ResponseHeaderMember>;
|
|
395
312
|
}
|
|
@@ -401,7 +318,9 @@ const decodePlanFor = (outputAst: AST.AST): DecodePlan => {
|
|
|
401
318
|
plan = {
|
|
402
319
|
binary: getAnn(outputAst, binaryResponseSymbol) !== undefined,
|
|
403
320
|
verbatim: mapsVerbatim(outputAst, "decode"),
|
|
321
|
+
text: resolveNode(outputAst)._tag === "String",
|
|
404
322
|
headers: responseHeaderMembers(outputAst),
|
|
323
|
+
bodyMember: getProps(outputAst).find((prop) => hasPropAnn(prop, rawResponseSymbol)),
|
|
405
324
|
};
|
|
406
325
|
decodePlans.set(outputAst, plan);
|
|
407
326
|
}
|
|
@@ -469,6 +388,7 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
|
|
|
469
388
|
headers: options.headers(creds),
|
|
470
389
|
mapMemberHeader: options.mapMemberHeader,
|
|
471
390
|
unknownKeyToWire: options.unknownKeyToWire,
|
|
391
|
+
emptyJsonBody: options.emptyJsonBody,
|
|
472
392
|
}) as Effect.Effect<HttpClientRequest.HttpClientRequest>;
|
|
473
393
|
};
|
|
474
394
|
|
|
@@ -482,9 +402,6 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
|
|
|
482
402
|
errorClasses: ReadonlyArray<unknown>,
|
|
483
403
|
): Decoded => {
|
|
484
404
|
// Read as text and parse tolerantly -- error pages are often non-JSON.
|
|
485
|
-
if (debugHttp()) {
|
|
486
|
-
console.error(`[distilled] <- ${status}`);
|
|
487
|
-
}
|
|
488
405
|
let json: unknown;
|
|
489
406
|
let nonJson = false;
|
|
490
407
|
if (text.trim().length > 0) {
|
|
@@ -499,6 +416,18 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
|
|
|
499
416
|
const env = (nonJson ? undefined : errorEnvelope(json)) ?? {};
|
|
500
417
|
const message = env.message ?? (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
|
|
501
418
|
|
|
419
|
+
// 0. The provider's own reading of the failure.
|
|
420
|
+
if (options.classifyError) {
|
|
421
|
+
const classified = options.classifyError({
|
|
422
|
+
status,
|
|
423
|
+
code: env.code,
|
|
424
|
+
message,
|
|
425
|
+
body: nonJson ? text : json,
|
|
426
|
+
headers,
|
|
427
|
+
});
|
|
428
|
+
if (classified !== undefined) return { ok: false, error: classified };
|
|
429
|
+
}
|
|
430
|
+
|
|
502
431
|
// 1. Per-operation typed error (matcher metadata on the class).
|
|
503
432
|
const typed = matchTypedError(
|
|
504
433
|
errorClasses,
|
|
@@ -560,14 +489,16 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
|
|
|
560
489
|
// with sensitive members, a non-JSON body fails in every mode and parse
|
|
561
490
|
// errors withhold the body.
|
|
562
491
|
const plan = decodePlanFor(outputAst);
|
|
563
|
-
let body: unknown = nonJson ? text : (json ?? {});
|
|
492
|
+
let body: unknown = nonJson ? text : (json ?? (plan.text ? "" : {}));
|
|
564
493
|
if (options.transformResponse) body = options.transformResponse(body);
|
|
494
|
+
const mapped =
|
|
495
|
+
plan.bodyMember !== undefined
|
|
496
|
+
? { [plan.bodyMember.name]: mapKeys(plan.bodyMember.type, body, "decode") }
|
|
497
|
+
: plan.verbatim
|
|
498
|
+
? body
|
|
499
|
+
: mapKeys(outputAst, body, "decode");
|
|
565
500
|
const checked = checkSuccess(context, outputAst, {
|
|
566
|
-
value: withResponseHeaders(
|
|
567
|
-
plan.headers,
|
|
568
|
-
plan.verbatim ? body : mapKeys(outputAst, body, "decode"),
|
|
569
|
-
headers,
|
|
570
|
-
),
|
|
501
|
+
value: withResponseHeaders(plan.headers, mapped, headers),
|
|
571
502
|
body: nonJson ? text : json,
|
|
572
503
|
nonJson,
|
|
573
504
|
});
|
|
@@ -41,7 +41,7 @@ import * as Context from "effect/Context";
|
|
|
41
41
|
import * as Effect from "effect/Effect";
|
|
42
42
|
import * as Layer from "effect/Layer";
|
|
43
43
|
import type * as AST from "effect/SchemaAST";
|
|
44
|
-
import { type Decode, decoderFor,
|
|
44
|
+
import { type Decode, decoderFor, SchemaMismatch } from "./response-validation-strict.ts";
|
|
45
45
|
|
|
46
46
|
export { SchemaMismatch, withholdActual } from "./response-validation-strict.ts";
|
|
47
47
|
|
|
@@ -143,7 +143,9 @@ export const checkResponse = (
|
|
|
143
143
|
if (mode === "lenient") return undefined;
|
|
144
144
|
const decoderOf = Context.get(context, StrictDecoder);
|
|
145
145
|
if (!decoderOf) {
|
|
146
|
-
|
|
146
|
+
// The mode was set without the layer that brings its decoder: the
|
|
147
|
+
// response can't be checked, so the call fails as a mismatch.
|
|
148
|
+
return new SchemaMismatch([], `the ResponseValidation.${mode} layer`, mode);
|
|
147
149
|
}
|
|
148
150
|
return decoderOf(outputAst, mode === "strict")(value);
|
|
149
151
|
};
|
package/src/sdk-error.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The error an operation fails with when the SDK itself cannot make the
|
|
3
|
+
* call: its generated config or a core module is broken (a paginated
|
|
4
|
+
* operation without the fields its strategy reads, a gRPC operation
|
|
5
|
+
* without a descriptor, ...), or one of its own modules fails to load. No
|
|
6
|
+
* input or response causes it; the generator refuses the configs that
|
|
7
|
+
* would. It is typed, so it fails the call instead of crashing the fiber,
|
|
8
|
+
* and it is never retried.
|
|
9
|
+
*
|
|
10
|
+
* Defined on its own, in core's `base` bundle group, so pagination and
|
|
11
|
+
* the protocols fail with it without importing the REST modules.
|
|
12
|
+
*/
|
|
13
|
+
import * as Effect from "effect/Effect";
|
|
14
|
+
import * as Schema from "./schema-lite-typed.ts";
|
|
15
|
+
|
|
16
|
+
export class SdkError
|
|
17
|
+
extends /*@__PURE__*/ Schema.TaggedError<SdkError>()("SdkError", {
|
|
18
|
+
message: Schema.String,
|
|
19
|
+
}) {}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Load one of the SDK's own modules on first use (`() => import("./x.ts")`).
|
|
23
|
+
* A rejected import -- a chunk missing from a bundle, a browser chunk that
|
|
24
|
+
* fails to download -- fails with {@link SdkError}.
|
|
25
|
+
*/
|
|
26
|
+
export const loadModule = <A>(load: () => PromiseLike<A>): Effect.Effect<A, SdkError> =>
|
|
27
|
+
Effect.tryPromise({
|
|
28
|
+
try: () => load(),
|
|
29
|
+
catch: (cause) =>
|
|
30
|
+
new SdkError({
|
|
31
|
+
message: `an SDK module failed to load: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
32
|
+
}),
|
|
33
|
+
});
|
package/src/sensitive.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Secrets in values, logs and error messages: one rule for every SDK.
|
|
3
|
+
*
|
|
4
|
+
* A schema holds a secret when a value it reaches is marked sensitive
|
|
5
|
+
* ({@link sensitiveValueSymbol}: `T.SensitiveValue` in the REST SDKs, the
|
|
6
|
+
* `Sensitive*` schemas in AWS). An operation's input and its output are
|
|
7
|
+
* judged independently, each by its own schema:
|
|
8
|
+
*
|
|
9
|
+
* - its plain form (a serialized request, a response body, the value a
|
|
10
|
+
* parse failure quotes) is {@link REDACTED} whole: {@link redactPlain};
|
|
11
|
+
* - its parsed form shows only the sensitive values as `Redacted`:
|
|
12
|
+
* {@link redactParsed} for logs, {@link wrapSensitive} for decoded output.
|
|
13
|
+
*
|
|
14
|
+
* Imports only `effect/Redacted` and the AST helpers, so a protocol can use
|
|
15
|
+
* it without loading the REST protocol.
|
|
16
|
+
*/
|
|
17
|
+
import * as Redacted from "effect/Redacted";
|
|
18
|
+
import type * as AST from "effect/SchemaAST";
|
|
19
|
+
import { getAnn, getProps, resolveNode } from "./annotations.ts";
|
|
20
|
+
import { isOpaqueValue } from "./plain-values.ts";
|
|
21
|
+
|
|
22
|
+
export const sensitiveValueSymbol = /*@__PURE__*/ Symbol.for(
|
|
23
|
+
"@distilled.cloud/core/sensitive-value",
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
/** What the plain form of a value that can hold a secret is shown as. */
|
|
27
|
+
export const REDACTED = "[REDACTED]";
|
|
28
|
+
|
|
29
|
+
/** Whether `ast` is marked sensitive (through optional, Suspend and encoding wrappers). */
|
|
30
|
+
export const isSensitive = (ast: AST.AST): boolean =>
|
|
31
|
+
getAnn(ast, sensitiveValueSymbol) !== undefined;
|
|
32
|
+
|
|
33
|
+
const holds = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Whether a value of the type `ast` can hold a sensitive value, at any depth:
|
|
37
|
+
* the type itself, members, map values, list elements and union arms.
|
|
38
|
+
*/
|
|
39
|
+
export const holdsSensitive = (ast: AST.AST): boolean => {
|
|
40
|
+
const cached = holds.get(ast);
|
|
41
|
+
if (cached !== undefined) return cached;
|
|
42
|
+
const seen = new Set<AST.AST>();
|
|
43
|
+
const visit = (n: AST.AST): boolean => {
|
|
44
|
+
if (isSensitive(n)) return true;
|
|
45
|
+
const node = resolveNode(n);
|
|
46
|
+
if (seen.has(node)) return false;
|
|
47
|
+
seen.add(node);
|
|
48
|
+
switch (node._tag) {
|
|
49
|
+
case "Union":
|
|
50
|
+
return node.types.some(visit);
|
|
51
|
+
case "Arrays":
|
|
52
|
+
return [...(node.elements ?? []), ...(node.rest ?? [])].some(visit);
|
|
53
|
+
case "Objects":
|
|
54
|
+
return [...(node.propertySignatures ?? []), ...(node.indexSignatures ?? [])].some((m) =>
|
|
55
|
+
visit(m.type),
|
|
56
|
+
);
|
|
57
|
+
default:
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const result = visit(ast);
|
|
62
|
+
holds.set(ast, result);
|
|
63
|
+
return result;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** `plain`, the plain form of a value of the type `ast`: {@link REDACTED} when it can hold a secret. */
|
|
67
|
+
export const redactPlain = <A>(ast: AST.AST, plain: A): A | typeof REDACTED =>
|
|
68
|
+
holdsSensitive(ast) ? REDACTED : plain;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* `value`, a parsed value of the type `ast`, as a log shows it: every
|
|
72
|
+
* sensitive value `Redacted` whole, whatever its type, and the rest as is.
|
|
73
|
+
*/
|
|
74
|
+
export const redactParsed = (ast: AST.AST, value: unknown): unknown =>
|
|
75
|
+
holdsSensitive(ast) ? wrap(ast, value, true) : value;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Walk a decoded (TS-named) value alongside its schema AST, wrapping values
|
|
79
|
+
* marked sensitive (members, map values, list elements) in `Redacted`: a
|
|
80
|
+
* string, or any non-null value of an untyped (`S.Unknown`) schema. A typed
|
|
81
|
+
* struct is walked so its own sensitive members are wrapped and its type
|
|
82
|
+
* stays accurate. Keys the schema doesn't model pass through. A union
|
|
83
|
+
* applies every arm in turn; a map arm skips keys a sibling arm names.
|
|
84
|
+
*/
|
|
85
|
+
export const wrapSensitive = (
|
|
86
|
+
ast: AST.AST,
|
|
87
|
+
value: unknown,
|
|
88
|
+
siblingNames?: ReadonlySet<string>,
|
|
89
|
+
): unknown => wrap(ast, value, false, siblingNames);
|
|
90
|
+
|
|
91
|
+
/** Whether `wrap` wraps `v`, a value of the sensitive type `type`. */
|
|
92
|
+
const isSecretValue = (type: AST.AST, v: unknown, whole: boolean): boolean =>
|
|
93
|
+
whole
|
|
94
|
+
? v !== null && v !== undefined
|
|
95
|
+
: typeof v === "string" || (v !== null && resolveNode(type)._tag === "Unknown");
|
|
96
|
+
|
|
97
|
+
const wrap = (
|
|
98
|
+
ast: AST.AST,
|
|
99
|
+
value: unknown,
|
|
100
|
+
whole: boolean,
|
|
101
|
+
siblingNames?: ReadonlySet<string>,
|
|
102
|
+
): unknown => {
|
|
103
|
+
if (
|
|
104
|
+
value === null ||
|
|
105
|
+
typeof value !== "object" ||
|
|
106
|
+
isOpaqueValue(value) ||
|
|
107
|
+
Redacted.isRedacted(value)
|
|
108
|
+
) {
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
const node = resolveNode(ast);
|
|
112
|
+
if (node._tag === "Union") {
|
|
113
|
+
// Redact every possible sensitive member, including in partial responses.
|
|
114
|
+
const named = new Set(
|
|
115
|
+
node.types.flatMap((arm) => {
|
|
116
|
+
const armNode = resolveNode(arm);
|
|
117
|
+
return armNode._tag === "Objects" ? getProps(armNode).map((p) => String(p.name)) : [];
|
|
118
|
+
}),
|
|
119
|
+
);
|
|
120
|
+
return node.types.reduce<unknown>((redacted, arm) => wrap(arm, redacted, whole, named), value);
|
|
121
|
+
}
|
|
122
|
+
if (node._tag === "Arrays") {
|
|
123
|
+
if (!Array.isArray(value)) return value;
|
|
124
|
+
const elem = node.rest?.[0];
|
|
125
|
+
if (!elem) return value;
|
|
126
|
+
const sensitive = isSensitive(elem);
|
|
127
|
+
return value.map((v) =>
|
|
128
|
+
sensitive && isSecretValue(elem, v, whole) && !Redacted.isRedacted(v)
|
|
129
|
+
? Redacted.make(v)
|
|
130
|
+
: wrap(elem, v, whole),
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
if (node._tag === "Objects" && !Array.isArray(value)) {
|
|
134
|
+
const props = getProps(node);
|
|
135
|
+
const mapValue = node.indexSignatures?.[0]?.type;
|
|
136
|
+
if (props.length === 0 && mapValue === undefined) return value;
|
|
137
|
+
const byName = new Map(props.map((p) => [String(p.name), p]));
|
|
138
|
+
// fromEntries keeps a `__proto__` key an entry instead of the prototype.
|
|
139
|
+
return Object.fromEntries(
|
|
140
|
+
Object.entries(value as Record<string, unknown>).flatMap<[string, unknown]>(([k, v]) => {
|
|
141
|
+
if (v === undefined) return [];
|
|
142
|
+
const prop = byName.get(k);
|
|
143
|
+
const type = prop?.type ?? (siblingNames?.has(k) ? undefined : mapValue);
|
|
144
|
+
if (type === undefined) return [[k, v]];
|
|
145
|
+
// Union arms run over each other's output: keep a value one already wrapped.
|
|
146
|
+
if (isSensitive(type) && isSecretValue(type, v, whole)) {
|
|
147
|
+
return [[k, Redacted.isRedacted(v) ? v : Redacted.make(v)]];
|
|
148
|
+
}
|
|
149
|
+
return [[k, wrap(type, v, whole)]];
|
|
150
|
+
}),
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
return value;
|
|
154
|
+
};
|