@ai-sdk/provider-utils 5.0.74 → 5.0.76
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 +28 -0
- package/dist/experimental-decision/index.js.map +1 -1
- package/dist/experimental-evaluation/index.js.map +1 -1
- package/dist/index.d.ts +68 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +376 -30
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/detect-media-type.ts +7 -4
- package/src/fetch-with-validated-redirects.ts +13 -0
- package/src/index.ts +4 -0
- package/src/json-binary-field-scanner.ts +457 -0
- package/src/read-response-with-size-limit.ts +11 -1
- package/src/resolve-provider-options.ts +68 -0
- package/src/response-handler.ts +57 -8
package/dist/index.js
CHANGED
|
@@ -624,7 +624,7 @@ function handleFetchError({ error, url, requestBodyValues }) {
|
|
|
624
624
|
}
|
|
625
625
|
//#endregion
|
|
626
626
|
//#region src/version.ts
|
|
627
|
-
const VERSION = "5.0.
|
|
627
|
+
const VERSION = "5.0.76";
|
|
628
628
|
//#endregion
|
|
629
629
|
//#region src/normalize-headers.ts
|
|
630
630
|
/**
|
|
@@ -1062,11 +1062,10 @@ function detectMediaType({ data, topLevelType }) {
|
|
|
1062
1062
|
...videoMediaTypeSignatures
|
|
1063
1063
|
]
|
|
1064
1064
|
});
|
|
1065
|
-
|
|
1066
|
-
if (signatures === void 0) return;
|
|
1065
|
+
if (!Object.prototype.hasOwnProperty.call(topLevelSignatureTables, topLevelType)) return;
|
|
1067
1066
|
return detectMediaTypeBySignatures({
|
|
1068
1067
|
data,
|
|
1069
|
-
signatures
|
|
1068
|
+
signatures: topLevelSignatureTables[topLevelType]
|
|
1070
1069
|
});
|
|
1071
1070
|
}
|
|
1072
1071
|
/**
|
|
@@ -1475,6 +1474,9 @@ async function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trust
|
|
|
1475
1474
|
* target (e.g. an internal address) before we ever see its URL, defeating the
|
|
1476
1475
|
* guard.
|
|
1477
1476
|
*
|
|
1477
|
+
* Manually followed redirects from HTTPS to HTTP are rejected before requesting
|
|
1478
|
+
* the target.
|
|
1479
|
+
*
|
|
1478
1480
|
* Request headers are also protected: {@link sanitizeRequestHeaders} strips
|
|
1479
1481
|
* proxy/metadata/cookie/hop-by-hop headers before the first request, and all
|
|
1480
1482
|
* caller headers except `User-Agent` are dropped on a cross-origin redirect.
|
|
@@ -1540,6 +1542,10 @@ async function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedir
|
|
|
1540
1542
|
if (REDIRECT_STATUS_CODES.has(response.status) && location) {
|
|
1541
1543
|
cancelResponseBody(response);
|
|
1542
1544
|
const nextUrl = new URL(location, currentUrl).toString();
|
|
1545
|
+
if (new URL(currentUrl).protocol === "https:" && new URL(nextUrl).protocol === "http:") throw new DownloadError({
|
|
1546
|
+
url,
|
|
1547
|
+
message: "Redirect from HTTPS to HTTP was blocked"
|
|
1548
|
+
});
|
|
1543
1549
|
if (currentHeaders !== void 0 && !isSameOrigin(nextUrl, currentUrl)) {
|
|
1544
1550
|
const userAgent = currentHeaders.get("user-agent");
|
|
1545
1551
|
currentHeaders = new Headers(userAgent == null ? void 0 : { "user-agent": userAgent });
|
|
@@ -1633,10 +1639,13 @@ const DEFAULT_MAX_DOWNLOAD_SIZE = 2147483648;
|
|
|
1633
1639
|
* @param response - The fetch Response to read.
|
|
1634
1640
|
* @param url - The URL being downloaded (used in error messages).
|
|
1635
1641
|
* @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
|
|
1642
|
+
* @param onChunk - Optional. Receives each chunk instead of the chunks being
|
|
1643
|
+
* collected, so the body is not held in memory, and the returned array is empty.
|
|
1644
|
+
* The chunk may be a view on a larger buffer, copy what you keep.
|
|
1636
1645
|
* @returns A Uint8Array containing the response body.
|
|
1637
1646
|
* @throws DownloadError if the response exceeds maxBytes.
|
|
1638
1647
|
*/
|
|
1639
|
-
async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) {
|
|
1648
|
+
async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE, onChunk }) {
|
|
1640
1649
|
const contentLength = response.headers.get("content-length");
|
|
1641
1650
|
if (contentLength != null) {
|
|
1642
1651
|
const length = parseInt(contentLength, 10);
|
|
@@ -1662,6 +1671,10 @@ async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX
|
|
|
1662
1671
|
url,
|
|
1663
1672
|
message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`
|
|
1664
1673
|
});
|
|
1674
|
+
if (onChunk != null) {
|
|
1675
|
+
onChunk(value);
|
|
1676
|
+
continue;
|
|
1677
|
+
}
|
|
1665
1678
|
chunks.push(value.byteLength < value.buffer.byteLength ? new Uint8Array(value) : value);
|
|
1666
1679
|
}
|
|
1667
1680
|
} finally {
|
|
@@ -1671,7 +1684,7 @@ async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX
|
|
|
1671
1684
|
reader.releaseLock();
|
|
1672
1685
|
}
|
|
1673
1686
|
}
|
|
1674
|
-
const result = new Uint8Array(totalBytes);
|
|
1687
|
+
const result = new Uint8Array(onChunk != null ? 0 : totalBytes);
|
|
1675
1688
|
let offset = 0;
|
|
1676
1689
|
for (const chunk of chunks) {
|
|
1677
1690
|
result.set(chunk, offset);
|
|
@@ -3435,6 +3448,41 @@ async function parseProviderOptions({ provider, providerOptions, schema }) {
|
|
|
3435
3448
|
return parsedProviderOptions.value;
|
|
3436
3449
|
}
|
|
3437
3450
|
//#endregion
|
|
3451
|
+
//#region src/resolve-provider-options.ts
|
|
3452
|
+
/**
|
|
3453
|
+
* Parses provider options that a model accepts under more than one
|
|
3454
|
+
* `providerOptions` namespace, e.g. a canonical key plus a provider-specific
|
|
3455
|
+
* or legacy alias.
|
|
3456
|
+
*
|
|
3457
|
+
* Each present namespace is validated against `schema` exactly like
|
|
3458
|
+
* `parseProviderOptions` does, so an invalid namespace throws.
|
|
3459
|
+
*
|
|
3460
|
+
* @returns the resolved options (`undefined` when no namespace is present)
|
|
3461
|
+
* and the namespaces that contributed to them, in resolution order.
|
|
3462
|
+
*/
|
|
3463
|
+
async function resolveProviderOptions({ providerOptions, namespaces, resolution, schema }) {
|
|
3464
|
+
const parsed = [];
|
|
3465
|
+
const matched = [];
|
|
3466
|
+
for (const namespace of new Set(namespaces)) {
|
|
3467
|
+
const options = await parseProviderOptions({
|
|
3468
|
+
provider: namespace,
|
|
3469
|
+
providerOptions,
|
|
3470
|
+
schema
|
|
3471
|
+
});
|
|
3472
|
+
if (options == null) continue;
|
|
3473
|
+
if (resolution === "first") return {
|
|
3474
|
+
options,
|
|
3475
|
+
namespaces: [namespace]
|
|
3476
|
+
};
|
|
3477
|
+
parsed.push(options);
|
|
3478
|
+
matched.push(namespace);
|
|
3479
|
+
}
|
|
3480
|
+
return {
|
|
3481
|
+
options: parsed.length === 0 ? void 0 : Object.assign({}, ...parsed),
|
|
3482
|
+
namespaces: matched
|
|
3483
|
+
};
|
|
3484
|
+
}
|
|
3485
|
+
//#endregion
|
|
3438
3486
|
//#region src/post-multipart-stream-to-api.ts
|
|
3439
3487
|
const getOriginalFetch$1 = () => globalThis.fetch;
|
|
3440
3488
|
function escapeMultipartHeaderValue(value) {
|
|
@@ -3830,6 +3878,288 @@ async function retryWithExponentialBackoffInternal(f, { maxRetries, delayInMs, b
|
|
|
3830
3878
|
}
|
|
3831
3879
|
}
|
|
3832
3880
|
//#endregion
|
|
3881
|
+
//#region src/json-binary-field-scanner.ts
|
|
3882
|
+
/**
|
|
3883
|
+
* Streaming extraction of large base64 strings from a JSON response body.
|
|
3884
|
+
*
|
|
3885
|
+
* A JSON response that carries an image or a file is mostly one very long
|
|
3886
|
+
* base64 string. The regular pipeline (collect chunks, concatenate, decode to
|
|
3887
|
+
* text, `JSON.parse`, decode base64) holds about four copies of that string at
|
|
3888
|
+
* once. The scanner reads the body chunk by chunk instead: strings at the
|
|
3889
|
+
* configured paths are decoded to bytes while they stream in, and the text that
|
|
3890
|
+
* is handed to `JSON.parse` (the "skeleton") holds a short placeholder in their
|
|
3891
|
+
* place.
|
|
3892
|
+
*
|
|
3893
|
+
* - The skeleton is the original body except for the extracted strings, so
|
|
3894
|
+
* `secureJsonParse` still sees every key (a base64 string cannot contain a
|
|
3895
|
+
* quote, so it cannot hide one).
|
|
3896
|
+
* - A string is extracted only if it is canonical standard-alphabet base64
|
|
3897
|
+
* (length divisible by 4, `=` only as the final padding, zero trailing bits,
|
|
3898
|
+
* no escape sequences or whitespace). The bytes are then exactly what `atob`
|
|
3899
|
+
* gives for it. Everything else stays a string. What was decoded before a
|
|
3900
|
+
* string turned out not to qualify is encoded back, which gives the original
|
|
3901
|
+
* characters.
|
|
3902
|
+
*/
|
|
3903
|
+
/** Strings that decode to fewer bytes stay strings. */
|
|
3904
|
+
const DEFAULT_BINARY_FIELD_MIN_BYTES = 65536;
|
|
3905
|
+
const QUOTE = 34;
|
|
3906
|
+
const BACKSLASH = 92;
|
|
3907
|
+
const EQUALS = 61;
|
|
3908
|
+
const COMMA = 44;
|
|
3909
|
+
const COLON = 58;
|
|
3910
|
+
const LEFT_BRACE = 123;
|
|
3911
|
+
const RIGHT_BRACE = 125;
|
|
3912
|
+
const LEFT_BRACKET = 91;
|
|
3913
|
+
const RIGHT_BRACKET = 93;
|
|
3914
|
+
const OUTSIDE = 0;
|
|
3915
|
+
const KEY = 1;
|
|
3916
|
+
const SKIP = 2;
|
|
3917
|
+
const BLOB = 3;
|
|
3918
|
+
/**
|
|
3919
|
+
* Compiles paths such as `images[*]` or `content[*].data.data`: plain object
|
|
3920
|
+
* keys (letters, digits, `_` and `-`) joined by `.`, and `[*]` for every
|
|
3921
|
+
* element of an array. Keys are compared with the raw bytes of the key in the
|
|
3922
|
+
* body, so a key written with an escape sequence never matches.
|
|
3923
|
+
*/
|
|
3924
|
+
function compileBinaryFieldPaths(paths) {
|
|
3925
|
+
const root = /* @__PURE__ */ new Map();
|
|
3926
|
+
for (const path of paths) {
|
|
3927
|
+
if (!/^(?:[\w-]+|\[\*])(?:\.[\w-]+|\[\*])*$/.test(path)) throw new InvalidArgumentError({
|
|
3928
|
+
argument: "experimental_binaryFields",
|
|
3929
|
+
message: `Invalid binary field path "${path}"`
|
|
3930
|
+
});
|
|
3931
|
+
let node = root;
|
|
3932
|
+
for (const segment of path.match(/\[\*]|[\w-]+/g)) {
|
|
3933
|
+
const edges = segment === "[*]" ? [null] : new TextEncoder().encode(`${segment}"`);
|
|
3934
|
+
for (const edge of edges) {
|
|
3935
|
+
let next = node.get(edge);
|
|
3936
|
+
if (next === void 0) node.set(edge, next = /* @__PURE__ */ new Map());
|
|
3937
|
+
node = next;
|
|
3938
|
+
}
|
|
3939
|
+
}
|
|
3940
|
+
node.set(true, node);
|
|
3941
|
+
}
|
|
3942
|
+
return root;
|
|
3943
|
+
}
|
|
3944
|
+
function join(parts, length) {
|
|
3945
|
+
const bytes = new Uint8Array(length);
|
|
3946
|
+
let at = 0;
|
|
3947
|
+
for (const part of parts) {
|
|
3948
|
+
bytes.set(part, at);
|
|
3949
|
+
at += part.length;
|
|
3950
|
+
}
|
|
3951
|
+
return bytes;
|
|
3952
|
+
}
|
|
3953
|
+
function createJsonBinaryFieldScanner(paths, minBytes = DEFAULT_BINARY_FIELD_MIN_BYTES) {
|
|
3954
|
+
const sextet = (/* @__PURE__ */ new Uint8Array(256)).fill(64);
|
|
3955
|
+
for (let index = 0; index < 64; index++) sextet["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(index)] = index;
|
|
3956
|
+
const encoder = new TextEncoder();
|
|
3957
|
+
const pieces = [];
|
|
3958
|
+
let piece = /* @__PURE__ */ new Uint8Array(65536);
|
|
3959
|
+
let pieceLength = 0;
|
|
3960
|
+
let size = 0;
|
|
3961
|
+
const binaries = /* @__PURE__ */ new Map();
|
|
3962
|
+
const frames = [];
|
|
3963
|
+
let skipped = 0;
|
|
3964
|
+
let mode = OUTSIDE;
|
|
3965
|
+
let escaped = false;
|
|
3966
|
+
let last = 0;
|
|
3967
|
+
let key;
|
|
3968
|
+
let segments = [];
|
|
3969
|
+
let segment = /* @__PURE__ */ new Uint8Array(0);
|
|
3970
|
+
let at = 0;
|
|
3971
|
+
let total = 0;
|
|
3972
|
+
let bits = 0;
|
|
3973
|
+
let chars = 0;
|
|
3974
|
+
let padding = 0;
|
|
3975
|
+
const add = (bytes) => {
|
|
3976
|
+
for (let offset = 0; offset < bytes.length;) {
|
|
3977
|
+
const length = Math.min(piece.length - pieceLength, bytes.length - offset);
|
|
3978
|
+
piece.set(bytes.subarray(offset, offset + length), pieceLength);
|
|
3979
|
+
pieceLength += length;
|
|
3980
|
+
offset += length;
|
|
3981
|
+
size += length;
|
|
3982
|
+
if (pieceLength === piece.length) {
|
|
3983
|
+
pieces.push(piece);
|
|
3984
|
+
piece = /* @__PURE__ */ new Uint8Array(65536);
|
|
3985
|
+
pieceLength = 0;
|
|
3986
|
+
}
|
|
3987
|
+
}
|
|
3988
|
+
};
|
|
3989
|
+
const emit = (chunk, start, end) => add(chunk.subarray(start, end));
|
|
3990
|
+
const reset = () => {
|
|
3991
|
+
segments = [];
|
|
3992
|
+
segment = /* @__PURE__ */ new Uint8Array(0);
|
|
3993
|
+
at = 0;
|
|
3994
|
+
total = 0;
|
|
3995
|
+
bits = 0;
|
|
3996
|
+
chars = 0;
|
|
3997
|
+
padding = 0;
|
|
3998
|
+
};
|
|
3999
|
+
const grow = () => {
|
|
4000
|
+
if (at > 0) segments.push(segment.subarray(0, at));
|
|
4001
|
+
segment = new Uint8Array(Math.min(Math.max(total, 4096), 4 << 20));
|
|
4002
|
+
at = 0;
|
|
4003
|
+
};
|
|
4004
|
+
const rest = () => bits << (4 - chars) * 6;
|
|
4005
|
+
const restore = () => {
|
|
4006
|
+
for (const part of [...segments, segment.subarray(0, at)]) add(encoder.encode(convertUint8ArrayToBase64(part)));
|
|
4007
|
+
const group = rest();
|
|
4008
|
+
add(encoder.encode(convertUint8ArrayToBase64(Uint8Array.of(group >> 16, group >> 8, group)).slice(0, chars) + "=".repeat(padding)));
|
|
4009
|
+
reset();
|
|
4010
|
+
};
|
|
4011
|
+
const closeBlob = () => {
|
|
4012
|
+
mode = OUTSIDE;
|
|
4013
|
+
const tail = chars && chars - 1;
|
|
4014
|
+
if (padding === (4 - chars) % 4 && !(bits & (1 << (4 - chars) * 2) - 1) && total + tail >= minBytes) {
|
|
4015
|
+
const group = rest();
|
|
4016
|
+
const bytes = join([...segments, segment.subarray(0, at)], total + tail);
|
|
4017
|
+
for (let index = 0; index < tail; index++) bytes[total + index] = group >> 16 - 8 * index;
|
|
4018
|
+
const placeholder = `[binary data: ${bytes.length} bytes; ref ${crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(2)).join("-")}]`;
|
|
4019
|
+
binaries.set(placeholder, bytes);
|
|
4020
|
+
add(encoder.encode(placeholder));
|
|
4021
|
+
reset();
|
|
4022
|
+
} else restore();
|
|
4023
|
+
};
|
|
4024
|
+
const push = (chunk) => {
|
|
4025
|
+
let from = 0;
|
|
4026
|
+
const { length } = chunk;
|
|
4027
|
+
for (let index = 0; index < length; index++) {
|
|
4028
|
+
let byte = chunk[index];
|
|
4029
|
+
if (mode === BLOB) {
|
|
4030
|
+
if (padding === 0) {
|
|
4031
|
+
let pending = bits;
|
|
4032
|
+
let count = chars;
|
|
4033
|
+
for (let value; index < length && (value = sextet[chunk[index]]) < 64; index++) {
|
|
4034
|
+
pending = pending << 6 | value;
|
|
4035
|
+
if (++count === 4) {
|
|
4036
|
+
if (at + 3 > segment.length) grow();
|
|
4037
|
+
segment[at++] = pending >> 16;
|
|
4038
|
+
segment[at++] = pending >> 8;
|
|
4039
|
+
segment[at++] = pending;
|
|
4040
|
+
total += 3;
|
|
4041
|
+
pending = 0;
|
|
4042
|
+
count = 0;
|
|
4043
|
+
}
|
|
4044
|
+
}
|
|
4045
|
+
bits = pending;
|
|
4046
|
+
chars = count;
|
|
4047
|
+
}
|
|
4048
|
+
if (index >= length) break;
|
|
4049
|
+
byte = chunk[index];
|
|
4050
|
+
if (byte === QUOTE) {
|
|
4051
|
+
closeBlob();
|
|
4052
|
+
from = index;
|
|
4053
|
+
} else if (byte === EQUALS && chars > 1 && padding < 4 - chars) padding++;
|
|
4054
|
+
else {
|
|
4055
|
+
restore();
|
|
4056
|
+
mode = SKIP;
|
|
4057
|
+
from = index--;
|
|
4058
|
+
}
|
|
4059
|
+
} else if (mode !== OUTSIDE) {
|
|
4060
|
+
if (mode === KEY) key = key?.get(byte);
|
|
4061
|
+
if (escaped) escaped = false;
|
|
4062
|
+
else if (byte === BACKSLASH) escaped = true;
|
|
4063
|
+
else if (byte === QUOTE) {
|
|
4064
|
+
if (mode === KEY) frames.at(-1).next = key;
|
|
4065
|
+
mode = OUTSIDE;
|
|
4066
|
+
}
|
|
4067
|
+
} else if (byte === QUOTE) {
|
|
4068
|
+
const frame = frames.at(-1);
|
|
4069
|
+
if (skipped > 0) mode = SKIP;
|
|
4070
|
+
else if (frame?.keys && (last === LEFT_BRACE || last === COMMA)) {
|
|
4071
|
+
mode = KEY;
|
|
4072
|
+
key = frame.keys;
|
|
4073
|
+
} else if ((frame ? frame.next : paths)?.get(true)) {
|
|
4074
|
+
mode = BLOB;
|
|
4075
|
+
emit(chunk, from, index + 1);
|
|
4076
|
+
} else mode = SKIP;
|
|
4077
|
+
} else if (byte === LEFT_BRACE || byte === LEFT_BRACKET) {
|
|
4078
|
+
last = byte;
|
|
4079
|
+
const frame = frames.at(-1);
|
|
4080
|
+
const node = skipped > 0 ? void 0 : frame ? frame.next : paths;
|
|
4081
|
+
const items = node?.get(null);
|
|
4082
|
+
if (byte === LEFT_BRACE && node) frames.push({ keys: node });
|
|
4083
|
+
else if (byte === LEFT_BRACKET && items) frames.push({
|
|
4084
|
+
keys: null,
|
|
4085
|
+
next: items
|
|
4086
|
+
});
|
|
4087
|
+
else skipped++;
|
|
4088
|
+
} else if (byte === RIGHT_BRACE || byte === RIGHT_BRACKET) {
|
|
4089
|
+
if (skipped > 0) skipped--;
|
|
4090
|
+
else frames.pop();
|
|
4091
|
+
} else if (byte === COMMA || byte === COLON) last = byte;
|
|
4092
|
+
}
|
|
4093
|
+
if (mode !== BLOB) emit(chunk, from, length);
|
|
4094
|
+
};
|
|
4095
|
+
const finish = () => {
|
|
4096
|
+
if (mode === BLOB) restore();
|
|
4097
|
+
return {
|
|
4098
|
+
text: new TextDecoder().decode(join([...pieces, piece.subarray(0, pieceLength)], size)),
|
|
4099
|
+
binaries
|
|
4100
|
+
};
|
|
4101
|
+
};
|
|
4102
|
+
return {
|
|
4103
|
+
push,
|
|
4104
|
+
finish
|
|
4105
|
+
};
|
|
4106
|
+
}
|
|
4107
|
+
/**
|
|
4108
|
+
* Replaces the placeholders in a parsed value with the bytes they stand for.
|
|
4109
|
+
* Objects and arrays are copied, the parsed value is not modified. A
|
|
4110
|
+
* placeholder holds a random number, so a string that equals one is ours.
|
|
4111
|
+
*/
|
|
4112
|
+
function replaceBinaryFieldPlaceholders(value, binaries) {
|
|
4113
|
+
if (typeof value === "string") return binaries.get(value) ?? value;
|
|
4114
|
+
if (Array.isArray(value)) return value.map((item) => replaceBinaryFieldPlaceholders(item, binaries));
|
|
4115
|
+
if (value != null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, replaceBinaryFieldPlaceholders(item, binaries)]));
|
|
4116
|
+
return value;
|
|
4117
|
+
}
|
|
4118
|
+
/**
|
|
4119
|
+
* Makes `JSON.stringify` give the placeholder for each of the arrays, instead
|
|
4120
|
+
* of `{"0":…,"1":…}` with an entry for every byte: 24 MiB of bytes would
|
|
4121
|
+
* become a string of more than 300 MB. That is what a validator, or the code
|
|
4122
|
+
* that reports its issues, does with a value it puts into an error message.
|
|
4123
|
+
* The property is not enumerable, so the arrays look the same otherwise.
|
|
4124
|
+
* Returns the function that removes it again.
|
|
4125
|
+
*/
|
|
4126
|
+
function maskBinariesInJson(binaries) {
|
|
4127
|
+
for (const [placeholder, bytes] of binaries) Object.defineProperty(bytes, "toJSON", {
|
|
4128
|
+
value: () => placeholder,
|
|
4129
|
+
configurable: true
|
|
4130
|
+
});
|
|
4131
|
+
return () => {
|
|
4132
|
+
for (const bytes of binaries.values()) Reflect.deleteProperty(bytes, "toJSON");
|
|
4133
|
+
};
|
|
4134
|
+
}
|
|
4135
|
+
/**
|
|
4136
|
+
* Wraps a schema so that it validates the extracted bytes in place of their
|
|
4137
|
+
* placeholders. The value parsed from the skeleton, and the value of the
|
|
4138
|
+
* validation error of the response, keep the placeholders: reporting an error
|
|
4139
|
+
* never prints the bytes.
|
|
4140
|
+
*
|
|
4141
|
+
* The errors of the schema itself may hold the bytes: a Standard Schema
|
|
4142
|
+
* validator wraps the value it was given into an error, and the issues it
|
|
4143
|
+
* reports may carry the offending input. So that their messages do not grow
|
|
4144
|
+
* with the image, the arrays stringify as their placeholders, and keep doing
|
|
4145
|
+
* so as long as an error can refer to them. When the validation succeeds the
|
|
4146
|
+
* arrays are plain again, for whoever receives them.
|
|
4147
|
+
*/
|
|
4148
|
+
function withBinaryFields(schema, binaries) {
|
|
4149
|
+
if (binaries.size === 0) return schema;
|
|
4150
|
+
const actualSchema = asSchema(schema);
|
|
4151
|
+
return jsonSchema({}, { validate: async (value) => {
|
|
4152
|
+
const replaced = replaceBinaryFieldPlaceholders(value, binaries);
|
|
4153
|
+
const unmask = maskBinariesInJson(binaries);
|
|
4154
|
+
const result = actualSchema.validate ? await actualSchema.validate(replaced) : {
|
|
4155
|
+
success: true,
|
|
4156
|
+
value: replaced
|
|
4157
|
+
};
|
|
4158
|
+
if (result.success) unmask();
|
|
4159
|
+
return result;
|
|
4160
|
+
} });
|
|
4161
|
+
}
|
|
4162
|
+
//#endregion
|
|
3833
4163
|
//#region src/response-handler.ts
|
|
3834
4164
|
const textDecoder = new TextDecoder();
|
|
3835
4165
|
const DEFAULT_MAX_JSON_LINE_BYTES = 67108864;
|
|
@@ -3953,29 +4283,45 @@ const createEventSourceResponseHandler = (chunkSchema) => async ({ response, url
|
|
|
3953
4283
|
})
|
|
3954
4284
|
};
|
|
3955
4285
|
};
|
|
3956
|
-
const createJsonResponseHandler = (responseSchema
|
|
3957
|
-
const
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3961
|
-
|
|
3962
|
-
|
|
3963
|
-
|
|
3964
|
-
|
|
3965
|
-
|
|
3966
|
-
|
|
3967
|
-
|
|
3968
|
-
|
|
3969
|
-
|
|
3970
|
-
|
|
3971
|
-
|
|
3972
|
-
|
|
3973
|
-
|
|
3974
|
-
|
|
3975
|
-
|
|
3976
|
-
|
|
3977
|
-
|
|
3978
|
-
|
|
4286
|
+
const createJsonResponseHandler = (responseSchema, { experimental_binaryFields } = {}) => {
|
|
4287
|
+
const binaryFieldPaths = experimental_binaryFields?.length ? compileBinaryFieldPaths(experimental_binaryFields) : void 0;
|
|
4288
|
+
return async ({ response, url, requestBodyValues }) => {
|
|
4289
|
+
let responseBody;
|
|
4290
|
+
let schema = responseSchema;
|
|
4291
|
+
if (binaryFieldPaths == null) responseBody = await readResponseBodyAsText({
|
|
4292
|
+
response,
|
|
4293
|
+
url
|
|
4294
|
+
});
|
|
4295
|
+
else {
|
|
4296
|
+
const scanner = createJsonBinaryFieldScanner(binaryFieldPaths);
|
|
4297
|
+
await readResponseWithSizeLimit({
|
|
4298
|
+
response,
|
|
4299
|
+
url,
|
|
4300
|
+
onChunk: scanner.push
|
|
4301
|
+
});
|
|
4302
|
+
const scanned = scanner.finish();
|
|
4303
|
+
responseBody = scanned.text;
|
|
4304
|
+
schema = withBinaryFields(responseSchema, scanned.binaries);
|
|
4305
|
+
}
|
|
4306
|
+
const parsedResult = await safeParseJSON({
|
|
4307
|
+
text: responseBody,
|
|
4308
|
+
schema
|
|
4309
|
+
});
|
|
4310
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
4311
|
+
if (!parsedResult.success) throw new APICallError({
|
|
4312
|
+
message: "Invalid JSON response",
|
|
4313
|
+
cause: parsedResult.error,
|
|
4314
|
+
statusCode: response.status,
|
|
4315
|
+
responseHeaders,
|
|
4316
|
+
responseBody,
|
|
4317
|
+
url,
|
|
4318
|
+
requestBodyValues
|
|
4319
|
+
});
|
|
4320
|
+
return {
|
|
4321
|
+
responseHeaders,
|
|
4322
|
+
value: parsedResult.value,
|
|
4323
|
+
rawValue: parsedResult.rawValue
|
|
4324
|
+
};
|
|
3979
4325
|
};
|
|
3980
4326
|
};
|
|
3981
4327
|
const createJsonLinesResponseHandler = (responseSchema, { maxLineBytes = DEFAULT_MAX_JSON_LINE_BYTES } = {}) => {
|
|
@@ -5006,6 +5352,6 @@ function stringifyWithBigIntAndCycles(value) {
|
|
|
5006
5352
|
});
|
|
5007
5353
|
}
|
|
5008
5354
|
//#endregion
|
|
5009
|
-
export { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER as EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, SPEECH_STREAM_START_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_START_FRAME_TYPE, SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE, SPEECH_STREAM_TEXT_DONE_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_TEXT_DONE_FRAME_TYPE, TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE, TRANSCRIPTION_STREAM_START_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE, EventSourceParserStream, SerializationError, StreamingToolCallTracker, VERSION, WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, asArray, asSchema, cancelResponseBody, combineHeaders, connectToWebSocket, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertJsonResponseToolStream, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createBinaryStreamResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonLinesResponseHandler, createJsonResponseHandler, createLanguageModelResponseMetadata, createNullLanguageModelUsage, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createProviderExecutedToolFactory, createProviderStreamError, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, deleteFromApi, detectMediaType, downloadBlob, dynamicTool, encodePathSegment, executeTool, getToolCaller as experimental_getToolCaller, parseSpeechStreamClientFrame as experimental_parseSpeechStreamClientFrame, parseSpeechStreamPart as experimental_parseSpeechStreamPart, parseTranscriptionStreamClientFrame as experimental_parseTranscriptionStreamClientFrame, parseTranscriptionStreamPart as experimental_parseTranscriptionStreamPart, serializeSpeechStreamPart as experimental_serializeSpeechStreamPart, serializeTranscriptionStreamPart as experimental_serializeTranscriptionStreamPart, toolCaller as experimental_toolCaller, extractLines, extractResponseHeaders, fetchUntrustedUrl, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, filterNullable, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, injectJsonInstructionIntoMessages, isAbortError, isArrayBuffer, isBrowserRuntime, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isProviderStreamError, isRecord, isSameOrigin, isUint8Array, isUrlSupported, isValidHostnamePart, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeBatchRequestCounts, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postMultipartStreamToApi, postToApi, readResponseWithSizeLimit, readWebSocketMessageText, removeUndefinedEntries, resolve, resolveFullMediaType, resolveProviderReference, resolveWith, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, serializeModelOptions, stringifyWithBigIntAndCycles, stripFileExtension, toWebSocketUrl, tool, validateBaseURL, validateDownloadUrl, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
|
|
5355
|
+
export { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER as EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, SPEECH_STREAM_START_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_START_FRAME_TYPE, SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE, SPEECH_STREAM_TEXT_DONE_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_TEXT_DONE_FRAME_TYPE, TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE, TRANSCRIPTION_STREAM_START_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE, EventSourceParserStream, SerializationError, StreamingToolCallTracker, VERSION, WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, asArray, asSchema, cancelResponseBody, combineHeaders, connectToWebSocket, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertJsonResponseToolStream, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createBinaryStreamResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonLinesResponseHandler, createJsonResponseHandler, createLanguageModelResponseMetadata, createNullLanguageModelUsage, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createProviderExecutedToolFactory, createProviderStreamError, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, deleteFromApi, detectMediaType, downloadBlob, dynamicTool, encodePathSegment, executeTool, getToolCaller as experimental_getToolCaller, parseSpeechStreamClientFrame as experimental_parseSpeechStreamClientFrame, parseSpeechStreamPart as experimental_parseSpeechStreamPart, parseTranscriptionStreamClientFrame as experimental_parseTranscriptionStreamClientFrame, parseTranscriptionStreamPart as experimental_parseTranscriptionStreamPart, serializeSpeechStreamPart as experimental_serializeSpeechStreamPart, serializeTranscriptionStreamPart as experimental_serializeTranscriptionStreamPart, toolCaller as experimental_toolCaller, extractLines, extractResponseHeaders, fetchUntrustedUrl, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, filterNullable, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, injectJsonInstructionIntoMessages, isAbortError, isArrayBuffer, isBrowserRuntime, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isProviderStreamError, isRecord, isSameOrigin, isUint8Array, isUrlSupported, isValidHostnamePart, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeBatchRequestCounts, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postMultipartStreamToApi, postToApi, readResponseWithSizeLimit, readWebSocketMessageText, removeUndefinedEntries, resolve, resolveFullMediaType, resolveProviderOptions, resolveProviderReference, resolveWith, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, serializeModelOptions, stringifyWithBigIntAndCycles, stripFileExtension, toWebSocketUrl, tool, validateBaseURL, validateDownloadUrl, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
|
|
5010
5356
|
|
|
5011
5357
|
//# sourceMappingURL=index.js.map
|