@distilled.cloud/core 1.0.0-rc.20 → 1.0.0-rc.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -0
- package/lib/_bundle/aws.js +1 -1
- package/lib/_bundle/aws.js.map +1 -1
- 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 -1
- package/lib/_bundle/grpc.js.map +1 -1
- package/lib/_bundle/rest.js +1 -1
- package/lib/_bundle/rest.js.map +1 -1
- package/lib/annotations.d.ts.map +1 -1
- package/lib/api.d.ts +71 -58
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -1
- package/lib/category.d.ts +15 -12
- package/lib/category.d.ts.map +1 -1
- package/lib/chunks.d.ts.map +1 -1
- package/lib/config.d.ts +13 -0
- package/lib/config.d.ts.map +1 -1
- package/lib/crypto.d.ts.map +1 -1
- package/lib/error-category.d.ts.map +1 -1
- package/lib/errors.d.ts +35 -2
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -1
- package/lib/graphql.d.ts +21 -4
- package/lib/graphql.d.ts.map +1 -1
- package/lib/graphql.types.d.ts +0 -1
- package/lib/graphql.types.d.ts.map +1 -1
- package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -1
- package/lib/grpc-transport-cloudflare-http2.js +2 -2
- package/lib/grpc-transport-cloudflare-http2.js.map +1 -1
- package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -1
- package/lib/grpc-transport-cloudflare-sockets.js +4 -4
- package/lib/grpc-transport-cloudflare-sockets.js.map +1 -1
- package/lib/grpc-transport-node-http2.d.ts.map +1 -1
- package/lib/grpc-transport-node-http2.js +1 -1
- package/lib/grpc-transport-node-http2.js.map +1 -1
- package/lib/grpc-transport.d.ts +53 -18
- package/lib/grpc-transport.d.ts.map +1 -1
- package/lib/grpc-transport.js +1 -1
- package/lib/hpack.d.ts.map +1 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/max-message-bytes.d.ts +42 -0
- package/lib/max-message-bytes.d.ts.map +1 -0
- package/lib/max-message-bytes.js +2 -0
- package/lib/max-message-bytes.js.map +1 -0
- package/lib/ndjson.d.ts +3 -0
- package/lib/ndjson.d.ts.map +1 -0
- package/lib/ndjson.js +2 -0
- package/lib/ndjson.js.map +1 -0
- package/lib/pagination.d.ts +4 -1
- package/lib/pagination.d.ts.map +1 -1
- package/lib/plain-values.d.ts +11 -0
- package/lib/plain-values.d.ts.map +1 -1
- package/lib/plain-values.js +1 -1
- package/lib/plain-values.js.map +1 -1
- package/lib/protobuf.d.ts +12 -19
- package/lib/protobuf.d.ts.map +1 -1
- package/lib/protobuf.js +1 -1
- package/lib/protocol-grpc.d.ts +47 -10
- package/lib/protocol-grpc.d.ts.map +1 -1
- package/lib/protocol-grpc.js +1 -1
- package/lib/protocol-http.d.ts +110 -8
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +1 -1
- package/lib/protocol-rest.d.ts +161 -37
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +1 -1
- package/lib/protocol.d.ts +113 -0
- package/lib/protocol.d.ts.map +1 -0
- package/lib/protocol.js +0 -0
- package/lib/query.d.ts.map +1 -1
- package/lib/response-validation-strict.d.ts.map +1 -1
- package/lib/response-validation.d.ts.map +1 -1
- package/lib/retry-after.d.ts +1 -1
- package/lib/retry-after.d.ts.map +1 -1
- package/lib/retry-state.d.ts +26 -0
- package/lib/retry-state.d.ts.map +1 -0
- package/lib/retry-state.js +2 -0
- package/lib/retry-state.js.map +1 -0
- package/lib/retry.d.ts +100 -20
- package/lib/retry.d.ts.map +1 -1
- package/lib/retry.js +1 -1
- package/lib/schema-lite-impl.d.ts +25 -4
- package/lib/schema-lite-impl.d.ts.map +1 -1
- package/lib/schema-lite-impl.js +1 -1
- package/lib/schema-lite-typed.d.ts.map +1 -1
- package/lib/schema-lite.d.ts +1 -0
- package/lib/schema-lite.d.ts.map +1 -1
- package/lib/schema-lite.js +1 -1
- package/lib/schema.d.ts.map +1 -1
- package/lib/sdk-error.d.ts +4 -0
- package/lib/sdk-error.d.ts.map +1 -1
- package/lib/send.d.ts +37 -0
- package/lib/send.d.ts.map +1 -0
- package/lib/send.js +2 -0
- package/lib/send.js.map +1 -0
- package/lib/sensitive.d.ts.map +1 -1
- package/lib/sensitive.js +1 -1
- package/lib/sensitive.js.map +1 -1
- 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-hooks.d.ts.map +1 -1
- package/lib/telemetry-host-rules.d.ts.map +1 -1
- package/lib/telemetry-lambda-context.d.ts.map +1 -1
- package/lib/telemetry-message-context.d.ts.map +1 -1
- package/lib/telemetry-metrics.d.ts.map +1 -1
- package/lib/telemetry-metrics.js +1 -1
- package/lib/telemetry-metrics.js.map +1 -1
- package/lib/telemetry-name-template.d.ts.map +1 -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-xray.d.ts.map +1 -1
- package/lib/telemetry.d.ts +29 -0
- package/lib/telemetry.d.ts.map +1 -1
- package/lib/telemetry.js +2 -2
- package/lib/telemetry.js.map +1 -1
- package/lib/token-cache.d.ts +31 -0
- package/lib/token-cache.d.ts.map +1 -0
- package/lib/token-cache.js +2 -0
- package/lib/token-cache.js.map +1 -0
- package/lib/trait.d.ts +24 -1
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +1 -1
- package/lib/unknown-error.d.ts.map +1 -1
- package/lib/xml.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/api.ts +402 -209
- package/src/category.ts +21 -28
- package/src/config.ts +17 -1
- package/src/errors.ts +24 -2
- package/src/graphql.ts +65 -26
- package/src/graphql.types.ts +15 -0
- package/src/grpc-transport-cloudflare-http2.ts +374 -299
- package/src/grpc-transport-cloudflare-sockets.ts +150 -81
- package/src/grpc-transport-node-http2.ts +119 -46
- package/src/grpc-transport.ts +211 -42
- package/src/max-message-bytes.ts +58 -0
- package/src/ndjson.ts +55 -0
- package/src/pagination.ts +26 -15
- package/src/plain-values.ts +30 -1
- package/src/protobuf.ts +40 -5
- package/src/protocol-grpc.ts +518 -348
- package/src/protocol-http.ts +474 -100
- package/src/protocol-rest.ts +580 -140
- package/src/protocol.ts +150 -0
- package/src/response-validation-strict.ts +9 -3
- package/src/retry-after.ts +1 -1
- package/src/retry-state.ts +105 -0
- package/src/retry.ts +176 -47
- package/src/schema-lite-impl.ts +81 -10
- package/src/schema-lite.ts +1 -0
- package/src/sdk-error.ts +4 -0
- package/src/send.ts +156 -0
- package/src/sensitive.ts +49 -15
- package/src/telemetry.ts +2 -34
- package/src/token-cache.ts +117 -0
- package/src/trait.ts +34 -1
package/src/protocol-http.ts
CHANGED
|
@@ -3,7 +3,7 @@ import * as Headers from "effect/http/Headers";
|
|
|
3
3
|
import * as HttpBody from "effect/http/HttpBody";
|
|
4
4
|
import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
5
5
|
/**
|
|
6
|
-
* Generic REST protocol machinery, shared by SDK
|
|
6
|
+
* Generic REST protocol machinery, shared by SDK protocols.
|
|
7
7
|
*
|
|
8
8
|
* Everything here is driven purely by the trait annotations in
|
|
9
9
|
* `core/trait.ts` -- nothing is provider-specific. An SDK protocol (e.g.
|
|
@@ -13,9 +13,12 @@ import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
|
13
13
|
* {@link matchTypedError}).
|
|
14
14
|
*/
|
|
15
15
|
import type * as AST from "effect/SchemaAST";
|
|
16
|
+
import type * as Stream from "effect/Stream";
|
|
16
17
|
import { getAnn, getProps, resolveNode } from "./annotations.ts";
|
|
17
18
|
import * as Category from "./category.ts";
|
|
18
|
-
import {
|
|
19
|
+
import { ConfigError } from "./config.ts";
|
|
20
|
+
import { isEffectStream, isOpaqueValue } from "./plain-values.ts";
|
|
21
|
+
import { parseServerRetryHint } from "./retry-after.ts";
|
|
19
22
|
import * as Schema from "./schema-lite-typed.ts";
|
|
20
23
|
import { SdkError } from "./sdk-error.ts";
|
|
21
24
|
import { restoreStack, suppressStack } from "./telemetry.ts";
|
|
@@ -118,6 +121,47 @@ export const withResponseHeaders = (
|
|
|
118
121
|
|
|
119
122
|
export { isOpaqueValue };
|
|
120
123
|
|
|
124
|
+
/** A key dictionary's lookup tables, each built on first use. */
|
|
125
|
+
const dictionaryTables = /*@__PURE__*/ new WeakMap<
|
|
126
|
+
KeyDictionaryEntries,
|
|
127
|
+
{ encode?: Record<string, string>; decode?: Record<string, string>; first?: Map<string, string> }
|
|
128
|
+
>();
|
|
129
|
+
const tablesOf = (dict: KeyDictionaryEntries) => {
|
|
130
|
+
let tables = dictionaryTables.get(dict);
|
|
131
|
+
if (tables === undefined) dictionaryTables.set(dict, (tables = {}));
|
|
132
|
+
return tables;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/** TS name -> wire name (encode) or every wire spelling -> TS name (decode). */
|
|
136
|
+
const renameTable = (
|
|
137
|
+
dict: KeyDictionaryEntries,
|
|
138
|
+
direction: "encode" | "decode",
|
|
139
|
+
): Record<string, string> =>
|
|
140
|
+
(tablesOf(dict)[direction] ??=
|
|
141
|
+
direction === "decode"
|
|
142
|
+
? Object.fromEntries(
|
|
143
|
+
Object.entries(dict).flatMap(([ts, wire]) =>
|
|
144
|
+
typeof wire === "string" ? [[wire, ts] as const] : wire.map((w) => [w, ts] as const),
|
|
145
|
+
),
|
|
146
|
+
)
|
|
147
|
+
: Object.fromEntries(
|
|
148
|
+
Object.entries(dict).map(([ts, wire]) => [
|
|
149
|
+
ts,
|
|
150
|
+
typeof wire === "string" ? wire : wire[0]!,
|
|
151
|
+
]),
|
|
152
|
+
));
|
|
153
|
+
|
|
154
|
+
/** The TS name of the first entry whose wire name is `wire` (not a list of spellings). */
|
|
155
|
+
const tsNameOf = (dict: KeyDictionaryEntries, wire: string): string | undefined => {
|
|
156
|
+
const tables = tablesOf(dict);
|
|
157
|
+
if (tables.first === undefined) {
|
|
158
|
+
tables.first = new Map();
|
|
159
|
+
for (const [ts, w] of Object.entries(dict))
|
|
160
|
+
if (typeof w === "string" && !tables.first.has(w)) tables.first.set(w, ts);
|
|
161
|
+
}
|
|
162
|
+
return tables.first.get(wire);
|
|
163
|
+
};
|
|
164
|
+
|
|
121
165
|
/**
|
|
122
166
|
* Deep-rename keys via a plain dictionary (see `T.KeyDictionary`). An entry
|
|
123
167
|
* may list several wire spellings; encode uses the first (canonical) one and
|
|
@@ -134,19 +178,7 @@ export const mapKeysByDictionary = (
|
|
|
134
178
|
if (Array.isArray(value)) {
|
|
135
179
|
return value.map((v) => mapKeysByDictionary(dict, v, direction));
|
|
136
180
|
}
|
|
137
|
-
const rename
|
|
138
|
-
direction === "decode"
|
|
139
|
-
? Object.fromEntries(
|
|
140
|
-
Object.entries(dict).flatMap(([ts, wire]) =>
|
|
141
|
-
typeof wire === "string" ? [[wire, ts] as const] : wire.map((w) => [w, ts] as const),
|
|
142
|
-
),
|
|
143
|
-
)
|
|
144
|
-
: Object.fromEntries(
|
|
145
|
-
Object.entries(dict).map(([ts, wire]) => [
|
|
146
|
-
ts,
|
|
147
|
-
typeof wire === "string" ? wire : wire[0]!,
|
|
148
|
-
]),
|
|
149
|
-
);
|
|
181
|
+
const rename = renameTable(dict, direction);
|
|
150
182
|
const out: Record<string, unknown> = {};
|
|
151
183
|
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
152
184
|
if (v === undefined) continue;
|
|
@@ -175,7 +207,8 @@ const stringEncode = (value: unknown): unknown =>
|
|
|
175
207
|
/**
|
|
176
208
|
* Whether {@link mapKeys} returns every value of `root` unchanged (as a deep
|
|
177
209
|
* copy) in `direction` with no fallback dictionary: no member is renamed,
|
|
178
|
-
* string-encoded (encode) or picked by `T.UnionCases` (decode
|
|
210
|
+
* string-encoded (encode) or picked by `T.UnionCases` (decode, or encode for
|
|
211
|
+
* a union whose cases carry member dictionaries), and no
|
|
179
212
|
* `T.KeyDictionary` is in scope anywhere below `root`. Protocols use it to
|
|
180
213
|
* skip the walk. Computed once per schema node and direction.
|
|
181
214
|
*/
|
|
@@ -194,7 +227,11 @@ export const mapsVerbatim = (root: AST.AST, direction: "encode" | "decode"): boo
|
|
|
194
227
|
result = false;
|
|
195
228
|
break;
|
|
196
229
|
}
|
|
197
|
-
|
|
230
|
+
const unionCases = getAnn(ast, unionCasesSymbol) as UnionCasesValue | undefined;
|
|
231
|
+
if (
|
|
232
|
+
unionCases !== undefined &&
|
|
233
|
+
(direction === "decode" || unionCases.dictionaries !== undefined)
|
|
234
|
+
) {
|
|
198
235
|
result = false;
|
|
199
236
|
break;
|
|
200
237
|
}
|
|
@@ -223,19 +260,84 @@ export const mapsVerbatim = (root: AST.AST, direction: "encode" | "decode"): boo
|
|
|
223
260
|
cache.set(root, result);
|
|
224
261
|
return result;
|
|
225
262
|
};
|
|
263
|
+
|
|
264
|
+
/** The value `T.UnionCases` annotates. */
|
|
265
|
+
interface UnionCasesValue {
|
|
266
|
+
readonly cases: ReadonlyArray<ReadonlyArray<string>>;
|
|
267
|
+
readonly discriminator?: UnionDiscriminator;
|
|
268
|
+
readonly dictionaries?: ReadonlyArray<Readonly<Record<string, KeyDictionaryEntries>>>;
|
|
269
|
+
}
|
|
226
270
|
const verbatimEncode = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
|
|
227
271
|
const verbatimDecode = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
|
|
228
272
|
|
|
273
|
+
/** What {@link mapKeys} reads from a schema node, once per node. */
|
|
274
|
+
interface NodeFacts {
|
|
275
|
+
readonly dict: KeyDictionaryEntries | undefined;
|
|
276
|
+
readonly unionCases: UnionCasesValue | undefined;
|
|
277
|
+
readonly node: AST.AST;
|
|
278
|
+
/** A struct's members: TS name, wire name, type, and whether it is `StringEncoded()`. */
|
|
279
|
+
readonly members: ReadonlyArray<readonly [string, string, AST.AST, boolean]>;
|
|
280
|
+
/** The keys the members take: TS names (encode) and wire names (decode). */
|
|
281
|
+
readonly tsNames: ReadonlySet<string>;
|
|
282
|
+
readonly wireNames: ReadonlySet<string>;
|
|
283
|
+
}
|
|
284
|
+
const nodeFacts = /*@__PURE__*/ new WeakMap<AST.AST, NodeFacts>();
|
|
285
|
+
const factsOf = (ast: AST.AST): NodeFacts => {
|
|
286
|
+
let facts = nodeFacts.get(ast);
|
|
287
|
+
if (facts === undefined) {
|
|
288
|
+
const node = resolveNode(ast);
|
|
289
|
+
const members =
|
|
290
|
+
node._tag === "Objects"
|
|
291
|
+
? ((node as any).propertySignatures as readonly AST.PropertySignature[]).map(
|
|
292
|
+
(p) =>
|
|
293
|
+
[
|
|
294
|
+
String(p.name),
|
|
295
|
+
nameOf(p, bodySymbol),
|
|
296
|
+
p.type,
|
|
297
|
+
hasPropAnn(p, stringEncodedSymbol),
|
|
298
|
+
] as const,
|
|
299
|
+
)
|
|
300
|
+
: [];
|
|
301
|
+
facts = {
|
|
302
|
+
dict: getAnn(ast, keyDictionarySymbol) as KeyDictionaryEntries | undefined,
|
|
303
|
+
unionCases: getAnn(ast, unionCasesSymbol) as UnionCasesValue | undefined,
|
|
304
|
+
node,
|
|
305
|
+
members,
|
|
306
|
+
tsNames: new Set(members.map((m) => m[0])),
|
|
307
|
+
wireNames: new Set(members.map((m) => m[1])),
|
|
308
|
+
};
|
|
309
|
+
nodeFacts.set(ast, facts);
|
|
310
|
+
}
|
|
311
|
+
return facts;
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Rename keys between TS names and wire names, per the schema (see
|
|
316
|
+
* {@link walkKeys}). A decode with no fallback dictionary returns `value`
|
|
317
|
+
* itself when the schema renames nothing ({@link mapsVerbatim}): the walk
|
|
318
|
+
* would only copy it.
|
|
319
|
+
*/
|
|
229
320
|
export const mapKeys = (
|
|
230
321
|
ast: AST.AST,
|
|
231
322
|
value: unknown,
|
|
232
323
|
direction: "encode" | "decode",
|
|
233
324
|
fallback?: KeyDictionaryEntries,
|
|
325
|
+
): unknown =>
|
|
326
|
+
fallback === undefined && direction === "decode" && mapsVerbatim(ast, "decode")
|
|
327
|
+
? value
|
|
328
|
+
: walkKeys(ast, value, direction, fallback);
|
|
329
|
+
|
|
330
|
+
const walkKeys = (
|
|
331
|
+
ast: AST.AST,
|
|
332
|
+
value: unknown,
|
|
333
|
+
direction: "encode" | "decode",
|
|
334
|
+
fallback?: KeyDictionaryEntries,
|
|
234
335
|
): unknown => {
|
|
235
336
|
if (value === null || value === undefined || typeof value !== "object" || isOpaqueValue(value)) {
|
|
236
337
|
return value;
|
|
237
338
|
}
|
|
238
|
-
const
|
|
339
|
+
const facts = factsOf(ast);
|
|
340
|
+
const dict = facts.dict ?? fallback;
|
|
239
341
|
|
|
240
342
|
// Discriminated union whose cases the API returns merged (every case's
|
|
241
343
|
// keys present, `null` for the inactive ones). Map wire names, then keep
|
|
@@ -247,27 +349,33 @@ export const mapKeys = (
|
|
|
247
349
|
// active case is the one that best EXPLAINS the value: most present,
|
|
248
350
|
// non-null keys covered, minus present keys the case cannot explain (ties
|
|
249
351
|
// break by coverage, then declaration order).
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
if (
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
352
|
+
//
|
|
353
|
+
// A case member with its own dictionary (`{}` for caller content such as
|
|
354
|
+
// a Worker binding's `json`) maps its value by that one. Encode takes this
|
|
355
|
+
// path only for a union that has such members: it picks the case the same
|
|
356
|
+
// way, then renames the top-level keys.
|
|
357
|
+
const unionCases = facts.unionCases;
|
|
358
|
+
if (
|
|
359
|
+
unionCases &&
|
|
360
|
+
(direction === "decode" || unionCases.dictionaries !== undefined) &&
|
|
361
|
+
!Array.isArray(value)
|
|
362
|
+
) {
|
|
363
|
+
// Top-level keys in TS names; values still as given.
|
|
364
|
+
const rename = dict ? renameTable(dict, direction) : undefined;
|
|
365
|
+
const obj: Record<string, unknown> = {};
|
|
366
|
+
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
367
|
+
if (v !== undefined) obj[direction === "decode" ? (rename?.[k] ?? k) : k] = v;
|
|
368
|
+
}
|
|
261
369
|
const present = Object.keys(obj).filter((k) => obj[k] !== undefined && obj[k] !== null);
|
|
262
370
|
const disc = unionCases.discriminator;
|
|
263
371
|
const tag = disc ? obj[disc.key] : undefined;
|
|
264
372
|
const tagged = typeof tag === "string" ? disc!.values.indexOf(tag) : -1;
|
|
265
|
-
let best: {
|
|
373
|
+
let best: { index: number; score: number; matched: number } | undefined;
|
|
266
374
|
if (tagged >= 0) {
|
|
267
|
-
best = {
|
|
375
|
+
best = { index: tagged, score: 0, matched: 0 };
|
|
268
376
|
} else {
|
|
269
|
-
for (
|
|
270
|
-
const set = new Set(
|
|
377
|
+
for (let index = 0; index < unionCases.cases.length; index++) {
|
|
378
|
+
const set = new Set(unionCases.cases[index]);
|
|
271
379
|
let matched = 0;
|
|
272
380
|
let excess = 0;
|
|
273
381
|
for (const k of present) {
|
|
@@ -279,19 +387,28 @@ export const mapKeys = (
|
|
|
279
387
|
matched > 0 &&
|
|
280
388
|
(!best || score > best.score || (score === best.score && matched > best.matched))
|
|
281
389
|
) {
|
|
282
|
-
best = {
|
|
390
|
+
best = { index, score, matched };
|
|
283
391
|
}
|
|
284
392
|
}
|
|
285
393
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
return
|
|
394
|
+
const own = best ? unionCases.dictionaries?.[best.index] : undefined;
|
|
395
|
+
const mapValue = (k: string, v: unknown): unknown => {
|
|
396
|
+
const d = own?.[k] ?? dict;
|
|
397
|
+
return d ? mapKeysByDictionary(d, v, direction) : v;
|
|
398
|
+
};
|
|
399
|
+
const out: Record<string, unknown> = {};
|
|
400
|
+
if (direction === "encode") {
|
|
401
|
+
// Every given key goes out, like the plain dictionary walk.
|
|
402
|
+
for (const [k, v] of Object.entries(obj)) out[rename?.[k] ?? k] = mapValue(k, v);
|
|
403
|
+
} else {
|
|
404
|
+
for (const k of best ? unionCases.cases[best.index]! : Object.keys(obj)) {
|
|
405
|
+
out[k] = mapValue(k, obj[k]);
|
|
406
|
+
}
|
|
290
407
|
}
|
|
291
|
-
return
|
|
408
|
+
return out;
|
|
292
409
|
}
|
|
293
410
|
|
|
294
|
-
const node =
|
|
411
|
+
const node = facts.node;
|
|
295
412
|
|
|
296
413
|
// Schema-level union member (a merged response struct whose arms disagree
|
|
297
414
|
// on a member's type -- see the codegen's response-union merge): pick the
|
|
@@ -306,7 +423,7 @@ export const mapKeys = (
|
|
|
306
423
|
const arms = (node as AST.Union).types.map(resolveNode);
|
|
307
424
|
if (Array.isArray(value)) {
|
|
308
425
|
const arr = arms.find((t) => t._tag === "Arrays");
|
|
309
|
-
if (arr) return
|
|
426
|
+
if (arr) return walkKeys(arr, value, direction, dict);
|
|
310
427
|
} else {
|
|
311
428
|
let best: AST.AST | undefined;
|
|
312
429
|
let bestScore = 0;
|
|
@@ -322,7 +439,7 @@ export const mapKeys = (
|
|
|
322
439
|
bestScore = score;
|
|
323
440
|
}
|
|
324
441
|
}
|
|
325
|
-
if (best) return
|
|
442
|
+
if (best) return walkKeys(best, value, direction, dict);
|
|
326
443
|
}
|
|
327
444
|
return dict ? mapKeysByDictionary(dict, value, direction) : value;
|
|
328
445
|
}
|
|
@@ -331,48 +448,45 @@ export const mapKeys = (
|
|
|
331
448
|
if (!Array.isArray(value)) return value;
|
|
332
449
|
const elem = (node as any).rest?.[0] as AST.AST | undefined;
|
|
333
450
|
return elem
|
|
334
|
-
? value.map((v) =>
|
|
451
|
+
? value.map((v) => walkKeys(elem, v, direction, dict))
|
|
335
452
|
: dict
|
|
336
453
|
? mapKeysByDictionary(dict, value, direction)
|
|
337
454
|
: value;
|
|
338
455
|
}
|
|
339
456
|
|
|
340
457
|
if (node._tag === "Objects" && !Array.isArray(value)) {
|
|
341
|
-
const
|
|
458
|
+
const members = facts.members;
|
|
342
459
|
const isigs = (node as any).indexSignatures as readonly { type: AST.AST }[] | undefined;
|
|
343
|
-
if (
|
|
460
|
+
if (members.length === 0 && !(isigs && isigs.length)) {
|
|
344
461
|
// opaque object -- dictionary fallback or verbatim
|
|
345
462
|
return dict ? mapKeysByDictionary(dict, value, direction) : value;
|
|
346
463
|
}
|
|
347
464
|
const out: Record<string, unknown> = {};
|
|
348
|
-
const consumed =
|
|
349
|
-
for (const
|
|
350
|
-
const tsName = String(p.name);
|
|
351
|
-
const wire = nameOf(p, bodySymbol);
|
|
465
|
+
const consumed = direction === "encode" ? facts.tsNames : facts.wireNames;
|
|
466
|
+
for (const [tsName, wire, type, stringEncoded] of members) {
|
|
352
467
|
const from = direction === "encode" ? tsName : wire;
|
|
353
468
|
const to = direction === "encode" ? wire : tsName;
|
|
354
|
-
consumed.add(from);
|
|
355
469
|
const v = (value as Record<string, unknown>)[from];
|
|
356
470
|
if (v === undefined) continue;
|
|
357
471
|
// A `StringEncoded()` member nested in a body struct (e.g. Azure's
|
|
358
472
|
// `hardwareProfile.dynamicMemoryEnabled`) stringifies here -- the
|
|
359
473
|
// top-level pass in `buildRequest` only sees the outermost member.
|
|
360
474
|
out[to] =
|
|
361
|
-
direction === "encode" &&
|
|
475
|
+
direction === "encode" && stringEncoded
|
|
362
476
|
? stringEncode(v)
|
|
363
|
-
:
|
|
477
|
+
: walkKeys(type, v, direction, dict);
|
|
364
478
|
}
|
|
365
479
|
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
366
480
|
if (consumed.has(k) || v === undefined) continue;
|
|
367
481
|
const renamed = dict
|
|
368
482
|
? direction === "encode"
|
|
369
483
|
? (dict[k] ?? k)
|
|
370
|
-
: (
|
|
484
|
+
: (tsNameOf(dict, k) ?? k)
|
|
371
485
|
: k;
|
|
372
486
|
|
|
373
487
|
out[typeof renamed === "string" ? renamed : renamed[0]] =
|
|
374
488
|
isigs && isigs.length
|
|
375
|
-
?
|
|
489
|
+
? walkKeys(isigs[0]!.type, v, direction, dict)
|
|
376
490
|
: dict
|
|
377
491
|
? mapKeysByDictionary(dict, v, direction)
|
|
378
492
|
: v;
|
|
@@ -436,6 +550,18 @@ export interface BuildRequestOptions {
|
|
|
436
550
|
* and refuse a bodyless one with 415.
|
|
437
551
|
*/
|
|
438
552
|
readonly emptyJsonBody?: boolean;
|
|
553
|
+
/**
|
|
554
|
+
* How a query member spells a nested object or an array.
|
|
555
|
+
*
|
|
556
|
+
* - `"dotted"` (default): `created.gte=1`; an array repeats the key
|
|
557
|
+
* (`expand=a&expand=b`).
|
|
558
|
+
* - `"brackets"`: `created[gte]=1`; an array indexes the key
|
|
559
|
+
* (`expand[0]=a&expand[1]=b`), the same rule as form-urlencoded bodies.
|
|
560
|
+
* Stripe needs this: its v2 API refuses `key[]` and repeated keys.
|
|
561
|
+
*
|
|
562
|
+
* `T.CommaDelimited` and `T.DeepQuery` members keep their own spelling.
|
|
563
|
+
*/
|
|
564
|
+
readonly queryStyle?: "dotted" | "brackets";
|
|
439
565
|
}
|
|
440
566
|
|
|
441
567
|
/**
|
|
@@ -476,6 +602,12 @@ const flattenToFormPairs = (obj: Record<string, unknown>, prefix = ""): Array<[s
|
|
|
476
602
|
return pairs;
|
|
477
603
|
};
|
|
478
604
|
|
|
605
|
+
/**
|
|
606
|
+
* Marks a raw body member as binary (core `RawBody`): a string is sent as
|
|
607
|
+
* its bytes, never JSON-encoded, even with no declared media type.
|
|
608
|
+
*/
|
|
609
|
+
export const binaryBodySymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/binary-body");
|
|
610
|
+
|
|
479
611
|
/** How an input member binds to the request. */
|
|
480
612
|
type Bind = "label" | "header" | "query" | "deepQuery" | "file" | "httpBody" | "body";
|
|
481
613
|
|
|
@@ -490,11 +622,15 @@ interface MemberPlan {
|
|
|
490
622
|
readonly preserve: string | undefined;
|
|
491
623
|
/** `{name+}` placeholder. */
|
|
492
624
|
readonly greedy: boolean;
|
|
625
|
+
/** The schema marks the member optional (`S.optional`). */
|
|
626
|
+
readonly optional: boolean;
|
|
493
627
|
readonly stringEncoded: boolean;
|
|
494
628
|
/** A list query member sent as one comma-separated parameter. */
|
|
495
629
|
readonly commaDelimited: boolean;
|
|
496
630
|
/** `mapKeys(type, value, "encode", rootDict)` returns the value unchanged. */
|
|
497
631
|
readonly verbatim: boolean;
|
|
632
|
+
/** A binary raw body (see {@link binaryBodySymbol}). */
|
|
633
|
+
readonly binary: boolean;
|
|
498
634
|
}
|
|
499
635
|
|
|
500
636
|
/** What `buildRequest` reads from an input schema, computed once per schema. */
|
|
@@ -556,9 +692,11 @@ const planFor = (inputAst: AST.AST): RequestPlan | SdkError => {
|
|
|
556
692
|
type: prop.type,
|
|
557
693
|
preserve: typeof preserve === "string" ? preserve : undefined,
|
|
558
694
|
greedy,
|
|
695
|
+
optional: prop.type.context?.isOptional === true,
|
|
559
696
|
stringEncoded: hasPropAnn(prop, stringEncodedSymbol),
|
|
560
697
|
commaDelimited: hasPropAnn(prop, commaDelimitedSymbol),
|
|
561
698
|
verbatim: rootDict === undefined && mapsVerbatim(prop.type, "encode"),
|
|
699
|
+
binary: hasPropAnn(prop, binaryBodySymbol),
|
|
562
700
|
});
|
|
563
701
|
}
|
|
564
702
|
plan = { http, rootDict, members, known, hasBodyMembers };
|
|
@@ -589,8 +727,9 @@ export const makeRequest = (
|
|
|
589
727
|
|
|
590
728
|
/**
|
|
591
729
|
* The input cannot be sent: a path label whose value would address another
|
|
592
|
-
* resource (`.` or `..`, which the URL parser resolves to the parent path
|
|
593
|
-
*
|
|
730
|
+
* resource (`.` or `..`, which the URL parser resolves to the parent path,
|
|
731
|
+
* or `""`, which addresses the parent path), or a host label that would
|
|
732
|
+
* address another host. Raised before anything is sent.
|
|
594
733
|
*/
|
|
595
734
|
export class InvalidInput
|
|
596
735
|
extends /*@__PURE__*/ Schema.TaggedError<InvalidInput>()("InvalidInput", {
|
|
@@ -598,20 +737,60 @@ export class InvalidInput
|
|
|
598
737
|
message: Schema.String,
|
|
599
738
|
}).pipe(Category.withBadRequestError) {}
|
|
600
739
|
|
|
740
|
+
/**
|
|
741
|
+
* The refusal for an input no request can carry. `cause` is what a step
|
|
742
|
+
* that only reads the caller's values threw: `JSON.stringify` on a `BigInt`,
|
|
743
|
+
* a walk of an object that contains itself.
|
|
744
|
+
*/
|
|
745
|
+
export const unsendable = (cause: unknown): InvalidInput =>
|
|
746
|
+
new InvalidInput({ member: "input", message: `The input cannot be sent: ${String(cause)}` });
|
|
747
|
+
|
|
748
|
+
/** `value` as the JSON body of `request`, or the refusal for a value JSON cannot carry. */
|
|
749
|
+
const withJsonBody = (
|
|
750
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
751
|
+
value: unknown,
|
|
752
|
+
contentType: string | undefined,
|
|
753
|
+
): HttpClientRequest.HttpClientRequest | InvalidInput => {
|
|
754
|
+
try {
|
|
755
|
+
return HttpClientRequest.setBody(request, HttpBody.jsonUnsafe(value, contentType));
|
|
756
|
+
} catch (cause) {
|
|
757
|
+
return unsendable(cause);
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
|
|
601
761
|
/**
|
|
602
762
|
* The refusal for a path label value that would address another resource,
|
|
603
763
|
* or `undefined`. The URL parser resolves a `.` or `..` segment,
|
|
604
764
|
* percent-encoded or not, so no encoding can carry one
|
|
605
765
|
* (`/projects/p1/branches/..` -> `/projects/p1/`). A greedy label keeps its
|
|
606
766
|
* `/`, so each of its segments counts.
|
|
767
|
+
*
|
|
768
|
+
* Also refuses an empty value, unless the label is `optional`. It leaves the
|
|
769
|
+
* segment empty, and a server that ignores a trailing slash (Smithy routing
|
|
770
|
+
* does) reads `/things/` as the collection `/things`: Kubernetes runs a
|
|
771
|
+
* delete of the Secret `""` as a delete of every Secret in the namespace.
|
|
772
|
+
* A label the schema marks optional is one the API documents as possibly
|
|
773
|
+
* empty (Azure Key Vault's `{secret-version}`), so it may be `""`.
|
|
774
|
+
*
|
|
775
|
+
* Also refuses a value with a lone UTF-16 surrogate (`"\ud800"`):
|
|
776
|
+
* `encodeURIComponent` throws `URIError` on it, and no encoding keeps the
|
|
777
|
+
* name as written.
|
|
607
778
|
*/
|
|
608
779
|
export const invalidLabel = (
|
|
609
780
|
member: string,
|
|
610
781
|
value: unknown,
|
|
611
782
|
greedy?: boolean,
|
|
783
|
+
optional?: boolean,
|
|
612
784
|
): InvalidInput | undefined => {
|
|
613
785
|
const text = String(value);
|
|
614
|
-
|
|
786
|
+
if (!text.isWellFormed()) {
|
|
787
|
+
return new InvalidInput({
|
|
788
|
+
member,
|
|
789
|
+
message: `Input member ${member} cannot be ${JSON.stringify(text)}: it has a lone UTF-16 surrogate, which a URL cannot carry`,
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
return (text === "" && !optional) ||
|
|
793
|
+
(greedy ? text.split("/") : [text]).some((s) => s === "." || s === "..")
|
|
615
794
|
? new InvalidInput({
|
|
616
795
|
member,
|
|
617
796
|
message: `Input member ${member} cannot be ${JSON.stringify(text)}: as a path label it would address another resource`,
|
|
@@ -619,6 +798,102 @@ export const invalidLabel = (
|
|
|
619
798
|
: undefined;
|
|
620
799
|
};
|
|
621
800
|
|
|
801
|
+
/**
|
|
802
|
+
* A path label value, percent-encoded, or the {@link InvalidInput} that
|
|
803
|
+
* {@link invalidLabel} refuses it with. A greedy label keeps its `/` and
|
|
804
|
+
* encodes each segment ({@link encodeGreedyLabel}). Use it wherever a
|
|
805
|
+
* caller's value goes into a URL path, so the check can't be skipped.
|
|
806
|
+
*/
|
|
807
|
+
export const encodeLabel = (
|
|
808
|
+
member: string,
|
|
809
|
+
value: unknown,
|
|
810
|
+
greedy?: boolean,
|
|
811
|
+
optional?: boolean,
|
|
812
|
+
): string | InvalidInput =>
|
|
813
|
+
invalidLabel(member, value, greedy, optional) ??
|
|
814
|
+
(greedy ? encodeGreedyLabel(String(value)) : encodeURIComponent(String(value)));
|
|
815
|
+
|
|
816
|
+
/** One RFC 1123 DNS label: 1-63 letters, digits and `-`, no `-` at either end. */
|
|
817
|
+
const HOST_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* Whether `value` is one DNS host label (RFC 1123), or with
|
|
821
|
+
* `allowSubDomains` a dot-separated name made of them. A value that goes into
|
|
822
|
+
* a URL host must pass it: any other character (`/`, `@`, `#`, `?`, `:`)
|
|
823
|
+
* can move the request to another host, and no encoding fixes a host.
|
|
824
|
+
*/
|
|
825
|
+
export const isHostLabel = (value: unknown, allowSubDomains?: boolean): boolean =>
|
|
826
|
+
typeof value === "string" &&
|
|
827
|
+
(allowSubDomains ? value.split(".") : [value]).every((label) => HOST_LABEL.test(label));
|
|
828
|
+
|
|
829
|
+
/**
|
|
830
|
+
* The refusal for a value that goes into a URL host but is not a host label
|
|
831
|
+
* ({@link isHostLabel}), or `undefined`. The host-side counterpart of
|
|
832
|
+
* {@link invalidLabel}. A value read from credentials config fails with
|
|
833
|
+
* {@link invalidHostLabelConfig} instead.
|
|
834
|
+
*/
|
|
835
|
+
export const invalidHostLabel = (
|
|
836
|
+
member: string,
|
|
837
|
+
value: unknown,
|
|
838
|
+
allowSubDomains?: boolean,
|
|
839
|
+
): InvalidInput | undefined =>
|
|
840
|
+
isHostLabel(value, allowSubDomains)
|
|
841
|
+
? undefined
|
|
842
|
+
: new InvalidInput({
|
|
843
|
+
member,
|
|
844
|
+
message: `Input member ${member} cannot be ${JSON.stringify(String(value))}: as a host label it would address another host`,
|
|
845
|
+
});
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* {@link invalidHostLabel} for a value read from credentials config: the
|
|
849
|
+
* refusal is a `ConfigError` naming the setting (`"S2 basin"`,
|
|
850
|
+
* `"STACKIT region"`), or `undefined`.
|
|
851
|
+
*/
|
|
852
|
+
export const invalidHostLabelConfig = (
|
|
853
|
+
name: string,
|
|
854
|
+
value: unknown,
|
|
855
|
+
allowSubDomains?: boolean,
|
|
856
|
+
): ConfigError | undefined =>
|
|
857
|
+
isHostLabel(value, allowSubDomains)
|
|
858
|
+
? undefined
|
|
859
|
+
: new ConfigError({
|
|
860
|
+
message: `${name} ${JSON.stringify(String(value))} cannot go into a host name: it must be ${allowSubDomains ? "DNS labels separated by dots, each" : "one DNS label:"} letters, digits and hyphens, at most 63 characters`,
|
|
861
|
+
});
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* The origin (`https://host[:port]`) that a host or origin read from
|
|
865
|
+
* credentials config names, or the `ConfigError` refusing it. The value is
|
|
866
|
+
* a host (`acme.zendesk.com`, `udm.lan:8443`, given `defaultScheme`) or an
|
|
867
|
+
* origin (`https://acme.zendesk.com/`). It picks the host and nothing else:
|
|
868
|
+
* a user, path, query or fragment, a scheme other than `http`/`https`, or a
|
|
869
|
+
* host name that is not DNS labels ({@link isHostLabel}) or an IPv6 literal
|
|
870
|
+
* is refused.
|
|
871
|
+
*/
|
|
872
|
+
export const originFromConfig = (
|
|
873
|
+
name: string,
|
|
874
|
+
value: string,
|
|
875
|
+
defaultScheme: "https" | "http" = "https",
|
|
876
|
+
): string | ConfigError => {
|
|
877
|
+
const refuse = (reason: string) =>
|
|
878
|
+
new ConfigError({ message: `${name} ${JSON.stringify(value)} ${reason}` });
|
|
879
|
+
const trimmed = value.replace(/\/+$/, "");
|
|
880
|
+
const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)
|
|
881
|
+
? trimmed
|
|
882
|
+
: `${defaultScheme}://${trimmed}`;
|
|
883
|
+
if (!URL.canParse(candidate)) return refuse("is not a host name or origin");
|
|
884
|
+
const url = new URL(candidate);
|
|
885
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
886
|
+
return refuse("must use https:// or http://");
|
|
887
|
+
}
|
|
888
|
+
if (url.href !== `${url.origin}/`) {
|
|
889
|
+
return refuse("must be a host, such as example.com, with no user, path, query or fragment");
|
|
890
|
+
}
|
|
891
|
+
if (!url.hostname.startsWith("[") && !isHostLabel(url.hostname, true)) {
|
|
892
|
+
return refuse("cannot be a host name: each label must be letters, digits and hyphens");
|
|
893
|
+
}
|
|
894
|
+
return url.origin;
|
|
895
|
+
};
|
|
896
|
+
|
|
622
897
|
/**
|
|
623
898
|
* Build an HTTP request from an operation input and its schema, driven by
|
|
624
899
|
* the trait annotations: `Http()` supplies method + URI template, `Label()`
|
|
@@ -631,8 +906,14 @@ export const invalidLabel = (
|
|
|
631
906
|
* The schema is read once per input schema (see `planFor`); later calls only
|
|
632
907
|
* walk the input value.
|
|
633
908
|
*
|
|
909
|
+
* An optional label left out of the input is an empty segment, like `""`
|
|
910
|
+
* (Azure Key Vault's `/secrets/{name}/{version}` -> `/secrets/db/`).
|
|
911
|
+
*
|
|
634
912
|
* Fails with {@link InvalidInput}, before anything is sent, when a label is
|
|
635
|
-
* `.` or `..` (for a greedy `{name+}` label, when any of its segments is)
|
|
913
|
+
* `.` or `..` (for a greedy `{name+}` label, when any of its segments is),
|
|
914
|
+
* is `""` and the schema marks it required, or has a lone UTF-16 surrogate,
|
|
915
|
+
* and when a JSON body holds a value JSON cannot carry (a `BigInt`, an
|
|
916
|
+
* object that contains itself).
|
|
636
917
|
* Fails with {@link SdkError} when the input schema is missing the `Http()`
|
|
637
918
|
* trait (a codegen bug the generator refuses).
|
|
638
919
|
*/
|
|
@@ -653,6 +934,7 @@ const requestOrInvalid = ({
|
|
|
653
934
|
mapMemberHeader,
|
|
654
935
|
unknownKeyToWire,
|
|
655
936
|
emptyJsonBody,
|
|
937
|
+
queryStyle,
|
|
656
938
|
}: BuildRequestOptions): HttpClientRequest.HttpClientRequest | InvalidInput | SdkError => {
|
|
657
939
|
const inputObj = (input ?? {}) as Record<string, unknown>;
|
|
658
940
|
const plan = planFor(inputAst);
|
|
@@ -664,6 +946,7 @@ const requestOrInvalid = ({
|
|
|
664
946
|
const body: Record<string, unknown> = {};
|
|
665
947
|
let bodyKeys = 0;
|
|
666
948
|
let rawBody: unknown; // whole-body member (T.HttpBody) -- sent as-is
|
|
949
|
+
let rawBinary = false; // that member is binary: a string goes out as its bytes
|
|
667
950
|
let files: Array<Blob | File> | undefined;
|
|
668
951
|
let query: URLSearchParams | undefined;
|
|
669
952
|
let uri = http.uri;
|
|
@@ -674,23 +957,26 @@ const requestOrInvalid = ({
|
|
|
674
957
|
for (let i = 0; i < members.length; i++) {
|
|
675
958
|
const m = members[i]!;
|
|
676
959
|
const value = inputObj[m.key];
|
|
677
|
-
if (value === undefined)
|
|
960
|
+
if (value === undefined) {
|
|
961
|
+
// An omitted optional label is an empty segment, the same as `""`.
|
|
962
|
+
if (m.bind === "label" && m.optional) {
|
|
963
|
+
uri = uri.replace(m.greedy ? `{${m.name}+}` : `{${m.name}}`, "");
|
|
964
|
+
}
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
678
967
|
switch (m.bind) {
|
|
679
968
|
case "label": {
|
|
680
|
-
const
|
|
681
|
-
if (
|
|
682
|
-
const encoded = encodeURIComponent(String(value));
|
|
969
|
+
const encoded = encodeLabel(m.key, value, m.greedy, m.optional);
|
|
970
|
+
if (encoded instanceof InvalidInput) return encoded;
|
|
683
971
|
const preserve = m.preserve;
|
|
684
972
|
const label =
|
|
685
|
-
preserve !== undefined
|
|
973
|
+
preserve !== undefined && !m.greedy
|
|
686
974
|
? encoded.replace(/%[0-9A-F]{2}/g, (escape) => {
|
|
687
975
|
const character = String.fromCharCode(Number.parseInt(escape.slice(1), 16));
|
|
688
976
|
return preserve.includes(character) ? character : escape;
|
|
689
977
|
})
|
|
690
978
|
: encoded;
|
|
691
|
-
uri = m.greedy
|
|
692
|
-
? uri.replace(`{${m.name}+}`, () => encodeGreedyLabel(String(value)))
|
|
693
|
-
: uri.replace(`{${m.name}}`, () => label);
|
|
979
|
+
uri = uri.replace(m.greedy ? `{${m.name}+}` : `{${m.name}}`, () => label);
|
|
694
980
|
break;
|
|
695
981
|
}
|
|
696
982
|
case "header": {
|
|
@@ -702,6 +988,9 @@ const requestOrInvalid = ({
|
|
|
702
988
|
case "query":
|
|
703
989
|
if (m.commaDelimited && Array.isArray(value)) {
|
|
704
990
|
(query ??= new URLSearchParams()).append(m.name, value.map(String).join(","));
|
|
991
|
+
} else if (queryStyle === "brackets") {
|
|
992
|
+
query ??= new URLSearchParams();
|
|
993
|
+
for (const [k, v] of flattenToFormPairs({ [m.name]: value })) query.append(k, v);
|
|
705
994
|
} else {
|
|
706
995
|
appendQuery((query ??= new URLSearchParams()), m.name, value);
|
|
707
996
|
}
|
|
@@ -729,6 +1018,7 @@ const requestOrInvalid = ({
|
|
|
729
1018
|
break;
|
|
730
1019
|
case "httpBody":
|
|
731
1020
|
rawBody = m.verbatim ? value : mapKeys(m.type, value, "encode", rootDict);
|
|
1021
|
+
rawBinary = m.binary;
|
|
732
1022
|
break;
|
|
733
1023
|
default:
|
|
734
1024
|
// T.StringEncoded(): the API takes this member's value only as its
|
|
@@ -767,33 +1057,36 @@ const requestOrInvalid = ({
|
|
|
767
1057
|
const bodied = !BODYLESS.has(http.method);
|
|
768
1058
|
if (http.contentType === "multipart") {
|
|
769
1059
|
// Multipart upload: each body member is a form part (objects
|
|
770
|
-
// JSON-encoded under their wire name)
|
|
771
|
-
//
|
|
772
|
-
//
|
|
773
|
-
//
|
|
1060
|
+
// JSON-encoded under their wire name). Files and byte buffers become
|
|
1061
|
+
// binary parts under the member's wire name, with a File's own filename
|
|
1062
|
+
// (the wire name for a nameless Blob or a byte buffer); a list of them is
|
|
1063
|
+
// one such part per element, the repeated-field form multipart APIs read
|
|
1064
|
+
// (`-F documents=@a.pdf -F documents=@b.txt`). `FormDataFile()` members
|
|
1065
|
+
// append under each file's own filename instead (below). A whole-body
|
|
1066
|
+
// member (T.HttpBody) that is a record of files becomes one part per
|
|
1067
|
+
// entry (e.g. asset upload: { <hash>: File }).
|
|
774
1068
|
const form = new FormData();
|
|
775
1069
|
const parts =
|
|
776
1070
|
rawBody !== undefined && typeof rawBody === "object"
|
|
777
1071
|
? (rawBody as Record<string, unknown>)
|
|
778
1072
|
: body;
|
|
779
|
-
const
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
if (
|
|
1073
|
+
const isBinary = (v: unknown): v is Blob | Uint8Array | ArrayBuffer =>
|
|
1074
|
+
v instanceof Blob || v instanceof Uint8Array || v instanceof ArrayBuffer;
|
|
1075
|
+
const appendBinary = (key: string, value: Blob | Uint8Array | ArrayBuffer) => {
|
|
1076
|
+
if (value instanceof Blob) {
|
|
783
1077
|
form.append(key, value, value instanceof File ? value.name : key);
|
|
784
|
-
} else
|
|
1078
|
+
} else {
|
|
1079
|
+
// Copy a Uint8Array view's own bytes (a subarray shares a larger buffer).
|
|
785
1080
|
const bytes = value instanceof Uint8Array ? new Uint8Array(value).buffer : value;
|
|
786
1081
|
form.append(key, new Blob([bytes]), key);
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
}
|
|
796
|
-
}
|
|
1082
|
+
}
|
|
1083
|
+
};
|
|
1084
|
+
for (const [key, value] of Object.entries(parts)) {
|
|
1085
|
+
if (value === undefined || value === null) continue;
|
|
1086
|
+
if (isBinary(value)) {
|
|
1087
|
+
appendBinary(key, value);
|
|
1088
|
+
} else if (Array.isArray(value) && value.length > 0 && value.every(isBinary)) {
|
|
1089
|
+
for (const element of value) appendBinary(key, element);
|
|
797
1090
|
} else if (typeof value === "object") {
|
|
798
1091
|
form.append(key, JSON.stringify(value));
|
|
799
1092
|
} else {
|
|
@@ -826,13 +1119,27 @@ const requestOrInvalid = ({
|
|
|
826
1119
|
// Binary payloads (Blob / ArrayBuffer / Uint8Array) send verbatim
|
|
827
1120
|
// (raw object uploads). With a bodyMediaType, the member is a
|
|
828
1121
|
// preserialized payload (string / bytes) sent verbatim; otherwise it's
|
|
829
|
-
// JSON.
|
|
1122
|
+
// JSON, under the Content-Type member when set (e.g. Kubernetes'
|
|
1123
|
+
// application/merge-patch+json).
|
|
830
1124
|
//
|
|
831
1125
|
// `setBody` overwrites the Content-Type header with the body's media
|
|
832
1126
|
// type (and removes it when that is undefined), so the body carries the
|
|
833
1127
|
// modeled Content-Type member when the caller set one, else the declared
|
|
834
1128
|
// bodyMediaType (e.g. application/x-ndjson for Vectorize insert/upsert).
|
|
835
1129
|
const mediaType = memberContentType ?? http.bodyMediaType;
|
|
1130
|
+
if (isEffectStream(rawBody)) {
|
|
1131
|
+
// Sent as it is pulled, chunked unless a modeled `Content-Length`
|
|
1132
|
+
// member gave its size. The REST protocol never retries it.
|
|
1133
|
+
const length = headers["content-length"];
|
|
1134
|
+
return HttpClientRequest.setBody(
|
|
1135
|
+
request,
|
|
1136
|
+
HttpBody.stream(
|
|
1137
|
+
rawBody as Stream.Stream<Uint8Array, unknown>,
|
|
1138
|
+
mediaType,
|
|
1139
|
+
length === undefined ? undefined : Number(length),
|
|
1140
|
+
),
|
|
1141
|
+
);
|
|
1142
|
+
}
|
|
836
1143
|
if (rawBody instanceof Blob || rawBody instanceof ArrayBuffer) {
|
|
837
1144
|
// With no media type at all, fetch falls back to the Blob's own type.
|
|
838
1145
|
return HttpClientRequest.setBody(request, HttpBody.raw(rawBody, { contentType: mediaType }));
|
|
@@ -840,15 +1147,17 @@ const requestOrInvalid = ({
|
|
|
840
1147
|
if (rawBody instanceof Uint8Array) {
|
|
841
1148
|
return HttpClientRequest.setBody(request, HttpBody.uint8Array(rawBody, mediaType));
|
|
842
1149
|
}
|
|
843
|
-
if (http.bodyMediaType) {
|
|
1150
|
+
if (http.bodyMediaType || rawBinary) {
|
|
1151
|
+
// A binary member's text with no media type is still bytes.
|
|
1152
|
+
const contentType = mediaType ?? "application/octet-stream";
|
|
844
1153
|
return HttpClientRequest.setBody(
|
|
845
1154
|
request,
|
|
846
1155
|
typeof rawBody === "string"
|
|
847
|
-
? HttpBody.text(rawBody,
|
|
848
|
-
: HttpBody.uint8Array(rawBody as Uint8Array,
|
|
1156
|
+
? HttpBody.text(rawBody, contentType)
|
|
1157
|
+
: HttpBody.uint8Array(rawBody as Uint8Array, contentType),
|
|
849
1158
|
);
|
|
850
1159
|
}
|
|
851
|
-
return
|
|
1160
|
+
return withJsonBody(request, rawBody, memberContentType);
|
|
852
1161
|
}
|
|
853
1162
|
if (
|
|
854
1163
|
// A GET/HEAD sends a body only when body members actually carry values.
|
|
@@ -864,8 +1173,10 @@ const requestOrInvalid = ({
|
|
|
864
1173
|
((hasBodyMembers || emptyJsonBody === true) && bodied && http.method !== "DELETE")
|
|
865
1174
|
) {
|
|
866
1175
|
// Send `{}` rather than no body when the schema declares body members --
|
|
867
|
-
// some endpoints reject a missing JSON body outright.
|
|
868
|
-
|
|
1176
|
+
// some endpoints reject a missing JSON body outright. A Content-Type
|
|
1177
|
+
// member names the JSON media type, as for a whole body above (a
|
|
1178
|
+
// Kubernetes merge patch is `application/merge-patch+json`).
|
|
1179
|
+
return withJsonBody(request, body, memberContentType);
|
|
869
1180
|
}
|
|
870
1181
|
return request;
|
|
871
1182
|
};
|
|
@@ -877,6 +1188,11 @@ const requestOrInvalid = ({
|
|
|
877
1188
|
export interface ErrorResponse {
|
|
878
1189
|
readonly body?: unknown;
|
|
879
1190
|
readonly headers?: Readonly<Record<string, string | undefined>>;
|
|
1191
|
+
/**
|
|
1192
|
+
* JSON pointer to the object that holds the error's fields when the
|
|
1193
|
+
* provider nests them, e.g. `"/error"` for `{ error: { status, details } }`.
|
|
1194
|
+
*/
|
|
1195
|
+
readonly fieldsAt?: string;
|
|
880
1196
|
}
|
|
881
1197
|
|
|
882
1198
|
const matchesText = (matcher: ErrorTextMatcher, value: unknown): boolean => {
|
|
@@ -954,6 +1270,56 @@ export const matchesExpression = (
|
|
|
954
1270
|
return true;
|
|
955
1271
|
};
|
|
956
1272
|
|
|
1273
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
1274
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1275
|
+
|
|
1276
|
+
/**
|
|
1277
|
+
* The body values whose keys the error class declares as fields: from the
|
|
1278
|
+
* object at `fieldsAt` first, then from the top level.
|
|
1279
|
+
*/
|
|
1280
|
+
const declaredBodyFields = (
|
|
1281
|
+
fields: Record<string, unknown> | undefined,
|
|
1282
|
+
body: unknown,
|
|
1283
|
+
fieldsAt: string | undefined,
|
|
1284
|
+
): Record<string, unknown> => {
|
|
1285
|
+
if (fields === undefined) return {};
|
|
1286
|
+
const nested = fieldsAt === undefined ? undefined : atPointer(body, fieldsAt);
|
|
1287
|
+
const out: Record<string, unknown> = {};
|
|
1288
|
+
for (const key of Object.keys(fields)) {
|
|
1289
|
+
if (isRecord(nested) && Object.hasOwn(nested, key)) out[key] = nested[key];
|
|
1290
|
+
else if (isRecord(body) && Object.hasOwn(body, key)) out[key] = body[key];
|
|
1291
|
+
}
|
|
1292
|
+
return out;
|
|
1293
|
+
};
|
|
1294
|
+
|
|
1295
|
+
/**
|
|
1296
|
+
* The fields every error built from a response gets, when its class declares
|
|
1297
|
+
* them: the body (keys mapped to TS names when the class types it), the
|
|
1298
|
+
* headers, and the server's retry hint from `Retry-After` or `RateLimit`.
|
|
1299
|
+
*/
|
|
1300
|
+
export const responseErrorFields = (
|
|
1301
|
+
fields: Record<string, unknown> | undefined,
|
|
1302
|
+
response: ErrorResponse,
|
|
1303
|
+
): Record<string, unknown> => {
|
|
1304
|
+
// A typed body (the provider's documented error schema) gets the TS names
|
|
1305
|
+
// a success body gets; an untyped one stays as the wire sent it.
|
|
1306
|
+
const bodyAst = (fields?.body as { readonly ast?: AST.AST } | undefined)?.ast;
|
|
1307
|
+
const out: Record<string, unknown> = {
|
|
1308
|
+
body:
|
|
1309
|
+
bodyAst !== undefined &&
|
|
1310
|
+
typeof response.body === "object" &&
|
|
1311
|
+
response.body !== null &&
|
|
1312
|
+
!mapsVerbatim(bodyAst, "decode")
|
|
1313
|
+
? mapKeys(bodyAst, response.body, "decode")
|
|
1314
|
+
: response.body,
|
|
1315
|
+
headers: response.headers,
|
|
1316
|
+
};
|
|
1317
|
+
if (fields !== undefined && Object.hasOwn(fields, "retryAfter") && response.headers) {
|
|
1318
|
+
out.retryAfter = parseServerRetryHint(response.headers);
|
|
1319
|
+
}
|
|
1320
|
+
return out;
|
|
1321
|
+
};
|
|
1322
|
+
|
|
957
1323
|
/**
|
|
958
1324
|
* Pick the operation's typed error class for a failed response: among all
|
|
959
1325
|
* declared classes whose matchers (see `applyErrorMatchers`) match the wire
|
|
@@ -961,14 +1327,21 @@ export const matchesExpression = (
|
|
|
961
1327
|
* Empty error lists use an HTTP-status message so body/header-only failures can
|
|
962
1328
|
* still match. The constructor receives the raw body and headers as well as
|
|
963
1329
|
* code/message; error schemas can declare these fields to expose them to callers.
|
|
1330
|
+
* Any other field the class declares is read from the JSON body's key of the
|
|
1331
|
+
* same name -- at `response.fieldsAt` first, then at the top level -- so a
|
|
1332
|
+
* patch that adds `requestId` to an error gets the body's `requestId`. A
|
|
1333
|
+
* declared `retryAfter` gets the `Retry-After` / `RateLimit` header hint. The
|
|
1334
|
+
* matched `code` and `message` always win over the body's.
|
|
964
1335
|
*/
|
|
965
|
-
export
|
|
966
|
-
errorClasses: ReadonlyArray<
|
|
1336
|
+
export function matchTypedError<E>(
|
|
1337
|
+
errorClasses: ReadonlyArray<new (...args: any[]) => E>,
|
|
967
1338
|
status: number,
|
|
968
1339
|
errors: ReadonlyArray<{ code?: number; message: string }>,
|
|
969
1340
|
response: ErrorResponse = {},
|
|
970
|
-
):
|
|
971
|
-
let best:
|
|
1341
|
+
): E | undefined {
|
|
1342
|
+
let best:
|
|
1343
|
+
| { cls: new (...args: any[]) => E; specificity: number; code?: number; message: string }
|
|
1344
|
+
| undefined;
|
|
972
1345
|
const wireErrors = errors.length > 0 ? errors : [{ message: `HTTP ${status}` }];
|
|
973
1346
|
for (const cls of errorClasses) {
|
|
974
1347
|
const matchers = getErrorMatchers(cls);
|
|
@@ -984,16 +1357,17 @@ export const matchTypedError = (
|
|
|
984
1357
|
}
|
|
985
1358
|
}
|
|
986
1359
|
if (!best) return undefined;
|
|
1360
|
+
const fields = (best.cls as { fields?: Record<string, unknown> }).fields;
|
|
987
1361
|
const saved = suppressStack();
|
|
988
1362
|
try {
|
|
989
|
-
return new
|
|
1363
|
+
return new best.cls({
|
|
1364
|
+
...declaredBodyFields(fields, response.body, response.fieldsAt),
|
|
990
1365
|
code: best.code ?? 0,
|
|
991
1366
|
message: best.message,
|
|
992
|
-
|
|
993
|
-
headers: response.headers,
|
|
1367
|
+
...responseErrorFields(fields, response),
|
|
994
1368
|
});
|
|
995
1369
|
} finally {
|
|
996
1370
|
restoreStack(saved);
|
|
997
1371
|
}
|
|
998
|
-
}
|
|
1372
|
+
}
|
|
999
1373
|
//#endregion
|