@ai-sdk/provider-utils 5.0.73 → 5.0.75
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/CHANGELOG.md +24 -0
- package/dist/index.d.ts +33 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +331 -26
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/json-binary-field-scanner.ts +457 -0
- package/src/read-response-with-size-limit.ts +11 -1
- package/src/response-handler.ts +57 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/provider-utils",
|
|
3
|
-
"version": "5.0.
|
|
3
|
+
"version": "5.0.75",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -42,11 +42,11 @@
|
|
|
42
42
|
}
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@ai-sdk/provider": "4.0.
|
|
45
|
+
"@ai-sdk/provider": "4.0.36",
|
|
46
46
|
"@standard-schema/spec": "^1.1.0",
|
|
47
47
|
"@workflow/serde": "4.1.0",
|
|
48
48
|
"eventsource-parser": "^3.0.8",
|
|
49
|
-
"undici": "^7.29.
|
|
49
|
+
"undici": "^7.29.1"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@types/node": "22.19.19",
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
import { InvalidArgumentError } from '@ai-sdk/provider';
|
|
2
|
+
import { asSchema, jsonSchema, type FlexibleSchema } from './schema';
|
|
3
|
+
import { convertUint8ArrayToBase64 } from './uint8-utils';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Streaming extraction of large base64 strings from a JSON response body.
|
|
7
|
+
*
|
|
8
|
+
* A JSON response that carries an image or a file is mostly one very long
|
|
9
|
+
* base64 string. The regular pipeline (collect chunks, concatenate, decode to
|
|
10
|
+
* text, `JSON.parse`, decode base64) holds about four copies of that string at
|
|
11
|
+
* once. The scanner reads the body chunk by chunk instead: strings at the
|
|
12
|
+
* configured paths are decoded to bytes while they stream in, and the text that
|
|
13
|
+
* is handed to `JSON.parse` (the "skeleton") holds a short placeholder in their
|
|
14
|
+
* place.
|
|
15
|
+
*
|
|
16
|
+
* - The skeleton is the original body except for the extracted strings, so
|
|
17
|
+
* `secureJsonParse` still sees every key (a base64 string cannot contain a
|
|
18
|
+
* quote, so it cannot hide one).
|
|
19
|
+
* - A string is extracted only if it is canonical standard-alphabet base64
|
|
20
|
+
* (length divisible by 4, `=` only as the final padding, zero trailing bits,
|
|
21
|
+
* no escape sequences or whitespace). The bytes are then exactly what `atob`
|
|
22
|
+
* gives for it. Everything else stays a string. What was decoded before a
|
|
23
|
+
* string turned out not to qualify is encoded back, which gives the original
|
|
24
|
+
* characters.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** Strings that decode to fewer bytes stay strings. */
|
|
28
|
+
export const DEFAULT_BINARY_FIELD_MIN_BYTES = 64 * 1024;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The compiled paths, a trie that is walked while scanning. The edges of a node
|
|
32
|
+
* are the bytes of an object key (a key ends with its closing quote), `null`
|
|
33
|
+
* for the items of an array, and `true` for "a path ends here".
|
|
34
|
+
*/
|
|
35
|
+
export type BinaryFieldPaths = Map<number | true | null, BinaryFieldPaths>;
|
|
36
|
+
|
|
37
|
+
const QUOTE = 0x22;
|
|
38
|
+
const BACKSLASH = 0x5c;
|
|
39
|
+
const EQUALS = 0x3d;
|
|
40
|
+
const COMMA = 0x2c;
|
|
41
|
+
const COLON = 0x3a;
|
|
42
|
+
const LEFT_BRACE = 0x7b;
|
|
43
|
+
const RIGHT_BRACE = 0x7d;
|
|
44
|
+
const LEFT_BRACKET = 0x5b;
|
|
45
|
+
const RIGHT_BRACKET = 0x5d;
|
|
46
|
+
|
|
47
|
+
// Where the scanner is.
|
|
48
|
+
const OUTSIDE = 0; // between tokens
|
|
49
|
+
const KEY = 1; // in an object key
|
|
50
|
+
const SKIP = 2; // in a string value that stays as it is
|
|
51
|
+
const BLOB = 3; // in a string value that is decoded while it streams in
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Compiles paths such as `images[*]` or `content[*].data.data`: plain object
|
|
55
|
+
* keys (letters, digits, `_` and `-`) joined by `.`, and `[*]` for every
|
|
56
|
+
* element of an array. Keys are compared with the raw bytes of the key in the
|
|
57
|
+
* body, so a key written with an escape sequence never matches.
|
|
58
|
+
*/
|
|
59
|
+
export function compileBinaryFieldPaths(
|
|
60
|
+
paths: readonly string[],
|
|
61
|
+
): BinaryFieldPaths {
|
|
62
|
+
const root: BinaryFieldPaths = new Map();
|
|
63
|
+
|
|
64
|
+
for (const path of paths) {
|
|
65
|
+
if (!/^(?:[\w-]+|\[\*])(?:\.[\w-]+|\[\*])*$/.test(path)) {
|
|
66
|
+
throw new InvalidArgumentError({
|
|
67
|
+
argument: 'experimental_binaryFields',
|
|
68
|
+
message: `Invalid binary field path "${path}"`,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let node = root;
|
|
73
|
+
for (const segment of path.match(/\[\*]|[\w-]+/g)!) {
|
|
74
|
+
const edges =
|
|
75
|
+
segment === '[*]' ? [null] : new TextEncoder().encode(`${segment}"`);
|
|
76
|
+
for (const edge of edges) {
|
|
77
|
+
let next = node.get(edge);
|
|
78
|
+
if (next === undefined) {
|
|
79
|
+
node.set(edge, (next = new Map()));
|
|
80
|
+
}
|
|
81
|
+
node = next;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
node.set(true, node);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return root;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface JsonBinaryFieldScanResult {
|
|
91
|
+
/** The body with extracted strings replaced by placeholders. */
|
|
92
|
+
text: string;
|
|
93
|
+
/** The extracted bytes by the placeholder text that stands in for them. */
|
|
94
|
+
binaries: ReadonlyMap<string, Uint8Array>;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function join(parts: Uint8Array[], length: number): Uint8Array {
|
|
98
|
+
const bytes = new Uint8Array(length);
|
|
99
|
+
let at = 0;
|
|
100
|
+
for (const part of parts) {
|
|
101
|
+
bytes.set(part, at);
|
|
102
|
+
at += part.length;
|
|
103
|
+
}
|
|
104
|
+
return bytes;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function createJsonBinaryFieldScanner(
|
|
108
|
+
paths: BinaryFieldPaths,
|
|
109
|
+
minBytes = DEFAULT_BINARY_FIELD_MIN_BYTES,
|
|
110
|
+
) {
|
|
111
|
+
// Six-bit value of each base64 character, 64 for everything else.
|
|
112
|
+
const sextet = new Uint8Array(256).fill(64);
|
|
113
|
+
for (let index = 0; index < 64; index++) {
|
|
114
|
+
sextet[
|
|
115
|
+
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charCodeAt(
|
|
116
|
+
index,
|
|
117
|
+
)
|
|
118
|
+
] = index;
|
|
119
|
+
}
|
|
120
|
+
const encoder = new TextEncoder();
|
|
121
|
+
|
|
122
|
+
// The skeleton, as bytes: it is decoded once at the end, like the regular
|
|
123
|
+
// path decodes the whole body.
|
|
124
|
+
const pieces: Uint8Array[] = [];
|
|
125
|
+
let piece = new Uint8Array(64 * 1024);
|
|
126
|
+
let pieceLength = 0;
|
|
127
|
+
let size = 0;
|
|
128
|
+
const binaries = new Map<string, Uint8Array>();
|
|
129
|
+
|
|
130
|
+
// JSON structure. Only the containers on a path get a frame; the ones that
|
|
131
|
+
// are not are counted in `skipped`.
|
|
132
|
+
// - keys: the node whose edges match the next key; null in an array
|
|
133
|
+
// - next: the node of the value that is read next
|
|
134
|
+
const frames: Array<{
|
|
135
|
+
keys: BinaryFieldPaths | null;
|
|
136
|
+
next?: BinaryFieldPaths;
|
|
137
|
+
}> = [];
|
|
138
|
+
let skipped = 0;
|
|
139
|
+
let mode = OUTSIDE;
|
|
140
|
+
let escaped = false;
|
|
141
|
+
let last = 0; // the last `{`, `,` or `:` outside of strings
|
|
142
|
+
let key: BinaryFieldPaths | undefined;
|
|
143
|
+
|
|
144
|
+
// The candidate string: whole groups of four characters are decoded into
|
|
145
|
+
// segments, the characters of an unfinished group are kept in `bits`.
|
|
146
|
+
let segments: Uint8Array[] = [];
|
|
147
|
+
let segment = new Uint8Array(0);
|
|
148
|
+
let at = 0; // bytes used in `segment`
|
|
149
|
+
let total = 0; // bytes decoded
|
|
150
|
+
let bits = 0;
|
|
151
|
+
let chars = 0; // characters in `bits`
|
|
152
|
+
let padding = 0; // `=` characters seen
|
|
153
|
+
|
|
154
|
+
const add = (bytes: Uint8Array) => {
|
|
155
|
+
// Coalesce small fragments: retaining a buffer for each matched string
|
|
156
|
+
// would make metadata grow with the number of values, even empty ones.
|
|
157
|
+
for (let offset = 0; offset < bytes.length; ) {
|
|
158
|
+
const length = Math.min(
|
|
159
|
+
piece.length - pieceLength,
|
|
160
|
+
bytes.length - offset,
|
|
161
|
+
);
|
|
162
|
+
piece.set(bytes.subarray(offset, offset + length), pieceLength);
|
|
163
|
+
pieceLength += length;
|
|
164
|
+
offset += length;
|
|
165
|
+
size += length;
|
|
166
|
+
if (pieceLength === piece.length) {
|
|
167
|
+
pieces.push(piece);
|
|
168
|
+
piece = new Uint8Array(64 * 1024);
|
|
169
|
+
pieceLength = 0;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
// Adds the part of a chunk to the skeleton. It is copied: a view on the
|
|
175
|
+
// chunk would retain all of it.
|
|
176
|
+
const emit = (chunk: Uint8Array, start: number, end: number) =>
|
|
177
|
+
add(chunk.subarray(start, end));
|
|
178
|
+
|
|
179
|
+
const reset = () => {
|
|
180
|
+
segments = [];
|
|
181
|
+
segment = new Uint8Array(0);
|
|
182
|
+
at = 0;
|
|
183
|
+
total = 0;
|
|
184
|
+
bits = 0;
|
|
185
|
+
chars = 0;
|
|
186
|
+
padding = 0;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
// Segments grow with the string, so that a short string does not pin a large
|
|
190
|
+
// buffer.
|
|
191
|
+
const grow = () => {
|
|
192
|
+
if (at > 0) {
|
|
193
|
+
segments.push(segment.subarray(0, at));
|
|
194
|
+
}
|
|
195
|
+
segment = new Uint8Array(Math.min(Math.max(total, 4096), 4 << 20));
|
|
196
|
+
at = 0;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
// The unfinished group, as bytes of a group of three padded with zeros.
|
|
200
|
+
const rest = () => bits << ((4 - chars) * 6);
|
|
201
|
+
|
|
202
|
+
// The string was not extracted: its characters go back into the skeleton.
|
|
203
|
+
const restore = () => {
|
|
204
|
+
for (const part of [...segments, segment.subarray(0, at)]) {
|
|
205
|
+
add(encoder.encode(convertUint8ArrayToBase64(part)));
|
|
206
|
+
}
|
|
207
|
+
const group = rest();
|
|
208
|
+
add(
|
|
209
|
+
encoder.encode(
|
|
210
|
+
convertUint8ArrayToBase64(
|
|
211
|
+
Uint8Array.of(group >> 16, group >> 8, group),
|
|
212
|
+
).slice(0, chars) + '='.repeat(padding),
|
|
213
|
+
),
|
|
214
|
+
);
|
|
215
|
+
reset();
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
// The closing quote of a candidate string was reached.
|
|
219
|
+
const closeBlob = () => {
|
|
220
|
+
mode = OUTSIDE;
|
|
221
|
+
const tail = chars && chars - 1;
|
|
222
|
+
|
|
223
|
+
if (
|
|
224
|
+
padding === (4 - chars) % 4 &&
|
|
225
|
+
!(bits & ((1 << ((4 - chars) * 2)) - 1)) &&
|
|
226
|
+
total + tail >= minBytes
|
|
227
|
+
) {
|
|
228
|
+
const group = rest();
|
|
229
|
+
const bytes = join([...segments, segment.subarray(0, at)], total + tail);
|
|
230
|
+
for (let index = 0; index < tail; index++) {
|
|
231
|
+
bytes[total + index] = group >> (16 - 8 * index);
|
|
232
|
+
}
|
|
233
|
+
const placeholder = `[binary data: ${bytes.length} bytes; ref ${crypto.getRandomValues(new Uint32Array(2)).join('-')}]`;
|
|
234
|
+
binaries.set(placeholder, bytes);
|
|
235
|
+
add(encoder.encode(placeholder));
|
|
236
|
+
reset();
|
|
237
|
+
} else {
|
|
238
|
+
restore();
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const push = (chunk: Uint8Array) => {
|
|
243
|
+
// The first byte of the chunk that is not in the skeleton yet.
|
|
244
|
+
let from = 0;
|
|
245
|
+
const { length } = chunk;
|
|
246
|
+
|
|
247
|
+
for (let index = 0; index < length; index++) {
|
|
248
|
+
let byte = chunk[index];
|
|
249
|
+
|
|
250
|
+
if (mode === BLOB) {
|
|
251
|
+
// The characters of the string, with the unfinished group in local
|
|
252
|
+
// variables. The loop ends at the first byte that is not one.
|
|
253
|
+
if (padding === 0) {
|
|
254
|
+
let pending = bits;
|
|
255
|
+
let count = chars;
|
|
256
|
+
for (
|
|
257
|
+
let value;
|
|
258
|
+
index < length && (value = sextet[chunk[index]]) < 64;
|
|
259
|
+
index++
|
|
260
|
+
) {
|
|
261
|
+
pending = (pending << 6) | value;
|
|
262
|
+
if (++count === 4) {
|
|
263
|
+
if (at + 3 > segment.length) {
|
|
264
|
+
grow();
|
|
265
|
+
}
|
|
266
|
+
segment[at++] = pending >> 16;
|
|
267
|
+
segment[at++] = pending >> 8;
|
|
268
|
+
segment[at++] = pending;
|
|
269
|
+
total += 3;
|
|
270
|
+
pending = 0;
|
|
271
|
+
count = 0;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
bits = pending;
|
|
275
|
+
chars = count;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (index >= length) {
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
byte = chunk[index];
|
|
283
|
+
if (byte === QUOTE) {
|
|
284
|
+
closeBlob();
|
|
285
|
+
from = index;
|
|
286
|
+
} else if (byte === EQUALS && chars > 1 && padding < 4 - chars) {
|
|
287
|
+
// Padding completes a group of two or three characters.
|
|
288
|
+
padding++;
|
|
289
|
+
} else {
|
|
290
|
+
// Not canonical. The string goes on as a regular string, from this
|
|
291
|
+
// byte.
|
|
292
|
+
restore();
|
|
293
|
+
mode = SKIP;
|
|
294
|
+
from = index--;
|
|
295
|
+
}
|
|
296
|
+
} else if (mode !== OUTSIDE) {
|
|
297
|
+
if (mode === KEY) {
|
|
298
|
+
key = key?.get(byte);
|
|
299
|
+
}
|
|
300
|
+
if (escaped) {
|
|
301
|
+
escaped = false;
|
|
302
|
+
} else if (byte === BACKSLASH) {
|
|
303
|
+
escaped = true;
|
|
304
|
+
} else if (byte === QUOTE) {
|
|
305
|
+
if (mode === KEY) {
|
|
306
|
+
frames.at(-1)!.next = key;
|
|
307
|
+
}
|
|
308
|
+
mode = OUTSIDE;
|
|
309
|
+
}
|
|
310
|
+
} else if (byte === QUOTE) {
|
|
311
|
+
const frame = frames.at(-1);
|
|
312
|
+
if (skipped > 0) {
|
|
313
|
+
mode = SKIP;
|
|
314
|
+
} else if (frame?.keys && (last === LEFT_BRACE || last === COMMA)) {
|
|
315
|
+
mode = KEY;
|
|
316
|
+
key = frame.keys;
|
|
317
|
+
} else if ((frame ? frame.next : paths)?.get(true)) {
|
|
318
|
+
mode = BLOB;
|
|
319
|
+
// The opening quote still belongs to the skeleton.
|
|
320
|
+
emit(chunk, from, index + 1);
|
|
321
|
+
} else {
|
|
322
|
+
mode = SKIP;
|
|
323
|
+
}
|
|
324
|
+
} else if (byte === LEFT_BRACE || byte === LEFT_BRACKET) {
|
|
325
|
+
last = byte;
|
|
326
|
+
const frame = frames.at(-1);
|
|
327
|
+
const node = skipped > 0 ? undefined : frame ? frame.next : paths;
|
|
328
|
+
const items = node?.get(null);
|
|
329
|
+
if (byte === LEFT_BRACE && node) {
|
|
330
|
+
frames.push({ keys: node });
|
|
331
|
+
} else if (byte === LEFT_BRACKET && items) {
|
|
332
|
+
frames.push({ keys: null, next: items });
|
|
333
|
+
} else {
|
|
334
|
+
skipped++;
|
|
335
|
+
}
|
|
336
|
+
} else if (byte === RIGHT_BRACE || byte === RIGHT_BRACKET) {
|
|
337
|
+
if (skipped > 0) {
|
|
338
|
+
skipped--;
|
|
339
|
+
} else {
|
|
340
|
+
frames.pop();
|
|
341
|
+
}
|
|
342
|
+
} else if (byte === COMMA || byte === COLON) {
|
|
343
|
+
last = byte;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (mode !== BLOB) {
|
|
348
|
+
emit(chunk, from, length);
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
const finish = (): JsonBinaryFieldScanResult => {
|
|
353
|
+
// A body that ends inside a candidate string is returned as it was
|
|
354
|
+
// received, so that the regular parser reports the truncation.
|
|
355
|
+
if (mode === BLOB) {
|
|
356
|
+
restore();
|
|
357
|
+
}
|
|
358
|
+
return {
|
|
359
|
+
text: new TextDecoder().decode(
|
|
360
|
+
join([...pieces, piece.subarray(0, pieceLength)], size),
|
|
361
|
+
),
|
|
362
|
+
binaries,
|
|
363
|
+
};
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
return { push, finish };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Replaces the placeholders in a parsed value with the bytes they stand for.
|
|
371
|
+
* Objects and arrays are copied, the parsed value is not modified. A
|
|
372
|
+
* placeholder holds a random number, so a string that equals one is ours.
|
|
373
|
+
*/
|
|
374
|
+
export function replaceBinaryFieldPlaceholders(
|
|
375
|
+
value: unknown,
|
|
376
|
+
binaries: ReadonlyMap<string, Uint8Array>,
|
|
377
|
+
): unknown {
|
|
378
|
+
if (typeof value === 'string') {
|
|
379
|
+
return binaries.get(value) ?? value;
|
|
380
|
+
}
|
|
381
|
+
if (Array.isArray(value)) {
|
|
382
|
+
return value.map(item => replaceBinaryFieldPlaceholders(item, binaries));
|
|
383
|
+
}
|
|
384
|
+
if (value != null && typeof value === 'object') {
|
|
385
|
+
return Object.fromEntries(
|
|
386
|
+
Object.entries(value).map(([name, item]) => [
|
|
387
|
+
name,
|
|
388
|
+
replaceBinaryFieldPlaceholders(item, binaries),
|
|
389
|
+
]),
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
return value;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Makes `JSON.stringify` give the placeholder for each of the arrays, instead
|
|
397
|
+
* of `{"0":…,"1":…}` with an entry for every byte: 24 MiB of bytes would
|
|
398
|
+
* become a string of more than 300 MB. That is what a validator, or the code
|
|
399
|
+
* that reports its issues, does with a value it puts into an error message.
|
|
400
|
+
* The property is not enumerable, so the arrays look the same otherwise.
|
|
401
|
+
* Returns the function that removes it again.
|
|
402
|
+
*/
|
|
403
|
+
function maskBinariesInJson(binaries: ReadonlyMap<string, Uint8Array>) {
|
|
404
|
+
for (const [placeholder, bytes] of binaries) {
|
|
405
|
+
Object.defineProperty(bytes, 'toJSON', {
|
|
406
|
+
value: () => placeholder,
|
|
407
|
+
configurable: true,
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
return () => {
|
|
412
|
+
for (const bytes of binaries.values()) {
|
|
413
|
+
Reflect.deleteProperty(bytes, 'toJSON');
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Wraps a schema so that it validates the extracted bytes in place of their
|
|
420
|
+
* placeholders. The value parsed from the skeleton, and the value of the
|
|
421
|
+
* validation error of the response, keep the placeholders: reporting an error
|
|
422
|
+
* never prints the bytes.
|
|
423
|
+
*
|
|
424
|
+
* The errors of the schema itself may hold the bytes: a Standard Schema
|
|
425
|
+
* validator wraps the value it was given into an error, and the issues it
|
|
426
|
+
* reports may carry the offending input. So that their messages do not grow
|
|
427
|
+
* with the image, the arrays stringify as their placeholders, and keep doing
|
|
428
|
+
* so as long as an error can refer to them. When the validation succeeds the
|
|
429
|
+
* arrays are plain again, for whoever receives them.
|
|
430
|
+
*/
|
|
431
|
+
export function withBinaryFields<T>(
|
|
432
|
+
schema: FlexibleSchema<T>,
|
|
433
|
+
binaries: ReadonlyMap<string, Uint8Array>,
|
|
434
|
+
): FlexibleSchema<T> {
|
|
435
|
+
if (binaries.size === 0) {
|
|
436
|
+
return schema;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const actualSchema = asSchema(schema);
|
|
440
|
+
|
|
441
|
+
return jsonSchema<T>(
|
|
442
|
+
{},
|
|
443
|
+
{
|
|
444
|
+
validate: async value => {
|
|
445
|
+
const replaced = replaceBinaryFieldPlaceholders(value, binaries);
|
|
446
|
+
const unmask = maskBinariesInJson(binaries);
|
|
447
|
+
const result = actualSchema.validate
|
|
448
|
+
? await actualSchema.validate(replaced)
|
|
449
|
+
: { success: true as const, value: replaced as T };
|
|
450
|
+
if (result.success) {
|
|
451
|
+
unmask();
|
|
452
|
+
}
|
|
453
|
+
return result;
|
|
454
|
+
},
|
|
455
|
+
},
|
|
456
|
+
);
|
|
457
|
+
}
|
|
@@ -24,6 +24,9 @@ export const DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
|
|
|
24
24
|
* @param response - The fetch Response to read.
|
|
25
25
|
* @param url - The URL being downloaded (used in error messages).
|
|
26
26
|
* @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
|
|
27
|
+
* @param onChunk - Optional. Receives each chunk instead of the chunks being
|
|
28
|
+
* collected, so the body is not held in memory, and the returned array is empty.
|
|
29
|
+
* The chunk may be a view on a larger buffer, copy what you keep.
|
|
27
30
|
* @returns A Uint8Array containing the response body.
|
|
28
31
|
* @throws DownloadError if the response exceeds maxBytes.
|
|
29
32
|
*/
|
|
@@ -31,10 +34,12 @@ export async function readResponseWithSizeLimit({
|
|
|
31
34
|
response,
|
|
32
35
|
url,
|
|
33
36
|
maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE,
|
|
37
|
+
onChunk,
|
|
34
38
|
}: {
|
|
35
39
|
response: Response;
|
|
36
40
|
url: string;
|
|
37
41
|
maxBytes?: number;
|
|
42
|
+
onChunk?: (chunk: Uint8Array) => void;
|
|
38
43
|
}): Promise<Uint8Array> {
|
|
39
44
|
// Early rejection based on Content-Length header
|
|
40
45
|
const contentLength = response.headers.get('content-length');
|
|
@@ -79,6 +84,11 @@ export async function readResponseWithSizeLimit({
|
|
|
79
84
|
});
|
|
80
85
|
}
|
|
81
86
|
|
|
87
|
+
if (onChunk != null) {
|
|
88
|
+
onChunk(value);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
|
|
82
92
|
// A small chunk can keep a much larger backing buffer alive. Copy such
|
|
83
93
|
// views before retaining them. Unlike Uint8Array, Node Buffer's slice()
|
|
84
94
|
// returns another view, so use the Uint8Array constructor to copy.
|
|
@@ -99,7 +109,7 @@ export async function readResponseWithSizeLimit({
|
|
|
99
109
|
}
|
|
100
110
|
|
|
101
111
|
// Concatenate chunks into a single Uint8Array
|
|
102
|
-
const result = new Uint8Array(totalBytes);
|
|
112
|
+
const result = new Uint8Array(onChunk != null ? 0 : totalBytes);
|
|
103
113
|
let offset = 0;
|
|
104
114
|
for (const chunk of chunks) {
|
|
105
115
|
result.set(chunk, offset);
|
package/src/response-handler.ts
CHANGED
|
@@ -7,6 +7,11 @@ import { DownloadError } from './download-error';
|
|
|
7
7
|
import { extractResponseHeaders } from './extract-response-headers';
|
|
8
8
|
import { handleFetchError } from './handle-fetch-error';
|
|
9
9
|
import { isAbortError } from './is-abort-error';
|
|
10
|
+
import {
|
|
11
|
+
compileBinaryFieldPaths,
|
|
12
|
+
createJsonBinaryFieldScanner,
|
|
13
|
+
withBinaryFields,
|
|
14
|
+
} from './json-binary-field-scanner';
|
|
10
15
|
import { parseJSON, safeParseJSON, type ParseResult } from './parse-json';
|
|
11
16
|
import { parseJsonEventStream } from './parse-json-event-stream';
|
|
12
17
|
import { readResponseWithSizeLimit } from './read-response-with-size-limit';
|
|
@@ -201,15 +206,58 @@ export const createEventSourceResponseHandler =
|
|
|
201
206
|
};
|
|
202
207
|
};
|
|
203
208
|
|
|
204
|
-
export const createJsonResponseHandler =
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
209
|
+
export const createJsonResponseHandler = <T>(
|
|
210
|
+
responseSchema: FlexibleSchema<T>,
|
|
211
|
+
{
|
|
212
|
+
experimental_binaryFields,
|
|
213
|
+
}: {
|
|
214
|
+
/**
|
|
215
|
+
* Paths of string fields that carry large base64 data, e.g. `['images[*]']`
|
|
216
|
+
* or `['content[*].data.data']`. A path is a sequence of plain object keys
|
|
217
|
+
* joined by `.`, with `[*]` for every element of an array.
|
|
218
|
+
*
|
|
219
|
+
* By default the whole body is buffered, decoded to text, parsed, and the
|
|
220
|
+
* base64 string is decoded again later, which holds about four copies of
|
|
221
|
+
* the data at once. With this option the body is read as a stream and the
|
|
222
|
+
* strings at these paths are decoded to `Uint8Array` while they arrive.
|
|
223
|
+
*
|
|
224
|
+
* A string is only decoded if it is canonical base64 (standard alphabet,
|
|
225
|
+
* padded, no whitespace or escape sequences) and decodes to at least 64 KiB.
|
|
226
|
+
* Other strings, and strings at other paths, are parsed as usual, so the
|
|
227
|
+
* schema has to accept both a string and a `Uint8Array` at these paths.
|
|
228
|
+
*
|
|
229
|
+
* Differences to the default behavior:
|
|
230
|
+
* - Validation and the returned `value` contain the decoded `Uint8Array`.
|
|
231
|
+
* - `rawValue`, the `value` of a `TypeValidationError`, the text of a
|
|
232
|
+
* `JSONParseError` and `APICallError.responseBody` contain a short
|
|
233
|
+
* placeholder string such as `[binary data: 2097152 bytes; ref ...]` in
|
|
234
|
+
* place of the data.
|
|
235
|
+
* - `JSON.stringify` of a decoded `Uint8Array` gives the same placeholder
|
|
236
|
+
* as long as the validation can fail, so the message of an error that a
|
|
237
|
+
* validator builds from the value, or from its issues, stays short.
|
|
238
|
+
*/
|
|
239
|
+
experimental_binaryFields?: readonly string[];
|
|
240
|
+
} = {},
|
|
241
|
+
): ResponseHandler<T> => {
|
|
242
|
+
const binaryFieldPaths = experimental_binaryFields?.length
|
|
243
|
+
? compileBinaryFieldPaths(experimental_binaryFields)
|
|
244
|
+
: undefined;
|
|
245
|
+
|
|
246
|
+
return async ({ response, url, requestBodyValues }) => {
|
|
247
|
+
let responseBody: string;
|
|
248
|
+
let schema = responseSchema;
|
|
249
|
+
|
|
250
|
+
if (binaryFieldPaths == null) {
|
|
251
|
+
responseBody = await readResponseBodyAsText({ response, url });
|
|
252
|
+
} else {
|
|
253
|
+
const scanner = createJsonBinaryFieldScanner(binaryFieldPaths);
|
|
254
|
+
await readResponseWithSizeLimit({ response, url, onChunk: scanner.push });
|
|
255
|
+
const scanned = scanner.finish();
|
|
256
|
+
responseBody = scanned.text;
|
|
257
|
+
schema = withBinaryFields(responseSchema, scanned.binaries);
|
|
258
|
+
}
|
|
208
259
|
|
|
209
|
-
const parsedResult = await safeParseJSON({
|
|
210
|
-
text: responseBody,
|
|
211
|
-
schema: responseSchema,
|
|
212
|
-
});
|
|
260
|
+
const parsedResult = await safeParseJSON({ text: responseBody, schema });
|
|
213
261
|
|
|
214
262
|
const responseHeaders = extractResponseHeaders(response);
|
|
215
263
|
|
|
@@ -231,6 +279,7 @@ export const createJsonResponseHandler =
|
|
|
231
279
|
rawValue: parsedResult.rawValue,
|
|
232
280
|
};
|
|
233
281
|
};
|
|
282
|
+
};
|
|
234
283
|
|
|
235
284
|
export const createJsonLinesResponseHandler = <T>(
|
|
236
285
|
responseSchema: FlexibleSchema<T>,
|