@ai-sdk/provider-utils 3.0.0-canary.8 → 3.0.0
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 +406 -0
- package/dist/index.d.mts +538 -54
- package/dist/index.d.ts +538 -54
- package/dist/index.js +349 -230
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +315 -213
- package/dist/index.mjs.map +1 -1
- package/dist/test/index.d.mts +1 -1
- package/dist/test/index.d.ts +1 -1
- package/dist/test/index.js +8 -2
- package/dist/test/index.js.map +1 -1
- package/dist/test/index.mjs +8 -2
- package/dist/test/index.mjs.map +1 -1
- package/package.json +12 -6
- package/test.d.ts +1 -0
package/dist/index.js
CHANGED
@@ -1,7 +1,9 @@
|
|
1
1
|
"use strict";
|
2
|
+
var __create = Object.create;
|
2
3
|
var __defProp = Object.defineProperty;
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
6
8
|
var __export = (target, all) => {
|
7
9
|
for (var name in all)
|
@@ -15,11 +17,22 @@ var __copyProps = (to, from, except, desc) => {
|
|
15
17
|
}
|
16
18
|
return to;
|
17
19
|
};
|
20
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
26
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
27
|
+
mod
|
28
|
+
));
|
18
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
19
30
|
|
20
31
|
// src/index.ts
|
21
32
|
var src_exports = {};
|
22
33
|
__export(src_exports, {
|
34
|
+
EventSourceParserStream: () => import_stream2.EventSourceParserStream,
|
35
|
+
asSchema: () => asSchema,
|
23
36
|
asValidator: () => asValidator,
|
24
37
|
combineHeaders: () => combineHeaders,
|
25
38
|
convertAsyncIteratorToReadableStream: () => convertAsyncIteratorToReadableStream,
|
@@ -27,25 +40,30 @@ __export(src_exports, {
|
|
27
40
|
convertToBase64: () => convertToBase64,
|
28
41
|
convertUint8ArrayToBase64: () => convertUint8ArrayToBase64,
|
29
42
|
createBinaryResponseHandler: () => createBinaryResponseHandler,
|
30
|
-
createEventSourceParserStream: () => createEventSourceParserStream,
|
31
43
|
createEventSourceResponseHandler: () => createEventSourceResponseHandler,
|
32
44
|
createIdGenerator: () => createIdGenerator,
|
33
45
|
createJsonErrorResponseHandler: () => createJsonErrorResponseHandler,
|
34
46
|
createJsonResponseHandler: () => createJsonResponseHandler,
|
35
47
|
createJsonStreamResponseHandler: () => createJsonStreamResponseHandler,
|
48
|
+
createProviderDefinedToolFactory: () => createProviderDefinedToolFactory,
|
49
|
+
createProviderDefinedToolFactoryWithOutputSchema: () => createProviderDefinedToolFactoryWithOutputSchema,
|
36
50
|
createStatusCodeErrorResponseHandler: () => createStatusCodeErrorResponseHandler,
|
37
51
|
delay: () => delay,
|
52
|
+
dynamicTool: () => dynamicTool,
|
38
53
|
extractResponseHeaders: () => extractResponseHeaders,
|
39
54
|
generateId: () => generateId,
|
40
55
|
getErrorMessage: () => getErrorMessage,
|
41
56
|
getFromApi: () => getFromApi,
|
42
57
|
isAbortError: () => isAbortError,
|
43
58
|
isParsableJson: () => isParsableJson,
|
59
|
+
isUrlSupported: () => isUrlSupported,
|
44
60
|
isValidator: () => isValidator,
|
61
|
+
jsonSchema: () => jsonSchema,
|
45
62
|
loadApiKey: () => loadApiKey,
|
46
63
|
loadOptionalSetting: () => loadOptionalSetting,
|
47
64
|
loadSetting: () => loadSetting,
|
48
65
|
parseJSON: () => parseJSON,
|
66
|
+
parseJsonEventStream: () => parseJsonEventStream,
|
49
67
|
parseProviderOptions: () => parseProviderOptions,
|
50
68
|
postFormDataToApi: () => postFormDataToApi,
|
51
69
|
postJsonToApi: () => postJsonToApi,
|
@@ -54,11 +72,13 @@ __export(src_exports, {
|
|
54
72
|
resolve: () => resolve,
|
55
73
|
safeParseJSON: () => safeParseJSON,
|
56
74
|
safeValidateTypes: () => safeValidateTypes,
|
75
|
+
standardSchemaValidator: () => standardSchemaValidator,
|
76
|
+
tool: () => tool,
|
57
77
|
validateTypes: () => validateTypes,
|
58
78
|
validator: () => validator,
|
59
79
|
validatorSymbol: () => validatorSymbol,
|
60
80
|
withoutTrailingSlash: () => withoutTrailingSlash,
|
61
|
-
|
81
|
+
zodSchema: () => zodSchema
|
62
82
|
});
|
63
83
|
module.exports = __toCommonJS(src_exports);
|
64
84
|
|
@@ -103,134 +123,56 @@ function convertAsyncIteratorToReadableStream(iterator) {
|
|
103
123
|
}
|
104
124
|
|
105
125
|
// src/delay.ts
|
106
|
-
async function delay(delayInMs) {
|
107
|
-
|
108
|
-
|
109
|
-
|
110
|
-
// src/event-source-parser-stream.ts
|
111
|
-
function createEventSourceParserStream() {
|
112
|
-
let buffer = "";
|
113
|
-
let event = void 0;
|
114
|
-
let data = [];
|
115
|
-
let lastEventId = void 0;
|
116
|
-
let retry = void 0;
|
117
|
-
function parseLine(line, controller) {
|
118
|
-
if (line === "") {
|
119
|
-
dispatchEvent(controller);
|
120
|
-
return;
|
121
|
-
}
|
122
|
-
if (line.startsWith(":")) {
|
123
|
-
return;
|
124
|
-
}
|
125
|
-
const colonIndex = line.indexOf(":");
|
126
|
-
if (colonIndex === -1) {
|
127
|
-
handleField(line, "");
|
128
|
-
return;
|
129
|
-
}
|
130
|
-
const field = line.slice(0, colonIndex);
|
131
|
-
const valueStart = colonIndex + 1;
|
132
|
-
const value = valueStart < line.length && line[valueStart] === " " ? line.slice(valueStart + 1) : line.slice(valueStart);
|
133
|
-
handleField(field, value);
|
134
|
-
}
|
135
|
-
function dispatchEvent(controller) {
|
136
|
-
if (data.length > 0) {
|
137
|
-
controller.enqueue({
|
138
|
-
event,
|
139
|
-
data: data.join("\n"),
|
140
|
-
id: lastEventId,
|
141
|
-
retry
|
142
|
-
});
|
143
|
-
data = [];
|
144
|
-
event = void 0;
|
145
|
-
retry = void 0;
|
146
|
-
}
|
147
|
-
}
|
148
|
-
function handleField(field, value) {
|
149
|
-
switch (field) {
|
150
|
-
case "event":
|
151
|
-
event = value;
|
152
|
-
break;
|
153
|
-
case "data":
|
154
|
-
data.push(value);
|
155
|
-
break;
|
156
|
-
case "id":
|
157
|
-
lastEventId = value;
|
158
|
-
break;
|
159
|
-
case "retry":
|
160
|
-
const parsedRetry = parseInt(value, 10);
|
161
|
-
if (!isNaN(parsedRetry)) {
|
162
|
-
retry = parsedRetry;
|
163
|
-
}
|
164
|
-
break;
|
165
|
-
}
|
126
|
+
async function delay(delayInMs, options) {
|
127
|
+
if (delayInMs == null) {
|
128
|
+
return Promise.resolve();
|
166
129
|
}
|
167
|
-
|
168
|
-
|
169
|
-
|
170
|
-
|
171
|
-
|
172
|
-
parseLine(lines[i], controller);
|
173
|
-
}
|
174
|
-
},
|
175
|
-
flush(controller) {
|
176
|
-
parseLine(buffer, controller);
|
177
|
-
dispatchEvent(controller);
|
130
|
+
const signal = options == null ? void 0 : options.abortSignal;
|
131
|
+
return new Promise((resolve2, reject) => {
|
132
|
+
if (signal == null ? void 0 : signal.aborted) {
|
133
|
+
reject(createAbortError());
|
134
|
+
return;
|
178
135
|
}
|
136
|
+
const timeoutId = setTimeout(() => {
|
137
|
+
cleanup();
|
138
|
+
resolve2();
|
139
|
+
}, delayInMs);
|
140
|
+
const cleanup = () => {
|
141
|
+
clearTimeout(timeoutId);
|
142
|
+
signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
|
143
|
+
};
|
144
|
+
const onAbort = () => {
|
145
|
+
cleanup();
|
146
|
+
reject(createAbortError());
|
147
|
+
};
|
148
|
+
signal == null ? void 0 : signal.addEventListener("abort", onAbort);
|
179
149
|
});
|
180
150
|
}
|
181
|
-
function
|
182
|
-
|
183
|
-
let currentLine = buffer;
|
184
|
-
for (let i = 0; i < chunk.length; ) {
|
185
|
-
const char = chunk[i++];
|
186
|
-
if (char === "\n") {
|
187
|
-
lines.push(currentLine);
|
188
|
-
currentLine = "";
|
189
|
-
} else if (char === "\r") {
|
190
|
-
lines.push(currentLine);
|
191
|
-
currentLine = "";
|
192
|
-
if (chunk[i + 1] === "\n") {
|
193
|
-
i++;
|
194
|
-
}
|
195
|
-
} else {
|
196
|
-
currentLine += char;
|
197
|
-
}
|
198
|
-
}
|
199
|
-
return { lines, incompleteLine: currentLine };
|
151
|
+
function createAbortError() {
|
152
|
+
return new DOMException("Delay was aborted", "AbortError");
|
200
153
|
}
|
201
154
|
|
202
155
|
// src/extract-response-headers.ts
|
203
156
|
function extractResponseHeaders(response) {
|
204
|
-
|
205
|
-
response.headers.forEach((value, key) => {
|
206
|
-
headers[key] = value;
|
207
|
-
});
|
208
|
-
return headers;
|
157
|
+
return Object.fromEntries([...response.headers]);
|
209
158
|
}
|
210
159
|
|
211
160
|
// src/generate-id.ts
|
212
161
|
var import_provider = require("@ai-sdk/provider");
|
213
|
-
|
214
|
-
// src/generate-id-custom-alphabet.ts
|
215
|
-
function customAlphabet(alphabet, defaultSize) {
|
216
|
-
return (size = defaultSize) => {
|
217
|
-
let id = "";
|
218
|
-
let i = size | 0;
|
219
|
-
while (i--) {
|
220
|
-
id += alphabet[Math.random() * alphabet.length | 0];
|
221
|
-
}
|
222
|
-
return id;
|
223
|
-
};
|
224
|
-
}
|
225
|
-
|
226
|
-
// src/generate-id.ts
|
227
162
|
var createIdGenerator = ({
|
228
163
|
prefix,
|
229
|
-
size
|
164
|
+
size = 16,
|
230
165
|
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
231
166
|
separator = "-"
|
232
167
|
} = {}) => {
|
233
|
-
const generator =
|
168
|
+
const generator = () => {
|
169
|
+
const alphabetLength = alphabet.length;
|
170
|
+
const chars = new Array(size);
|
171
|
+
for (let i = 0; i < size; i++) {
|
172
|
+
chars[i] = alphabet[Math.random() * alphabetLength | 0];
|
173
|
+
}
|
174
|
+
return chars.join("");
|
175
|
+
};
|
234
176
|
if (prefix == null) {
|
235
177
|
return generator;
|
236
178
|
}
|
@@ -240,7 +182,7 @@ var createIdGenerator = ({
|
|
240
182
|
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
|
241
183
|
});
|
242
184
|
}
|
243
|
-
return (
|
185
|
+
return () => `${prefix}${separator}${generator()}`;
|
244
186
|
};
|
245
187
|
var generateId = createIdGenerator();
|
246
188
|
|
@@ -259,8 +201,43 @@ function getErrorMessage(error) {
|
|
259
201
|
}
|
260
202
|
|
261
203
|
// src/get-from-api.ts
|
204
|
+
var import_provider3 = require("@ai-sdk/provider");
|
205
|
+
|
206
|
+
// src/handle-fetch-error.ts
|
262
207
|
var import_provider2 = require("@ai-sdk/provider");
|
263
208
|
|
209
|
+
// src/is-abort-error.ts
|
210
|
+
function isAbortError(error) {
|
211
|
+
return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
|
212
|
+
error.name === "TimeoutError");
|
213
|
+
}
|
214
|
+
|
215
|
+
// src/handle-fetch-error.ts
|
216
|
+
var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
|
217
|
+
function handleFetchError({
|
218
|
+
error,
|
219
|
+
url,
|
220
|
+
requestBodyValues
|
221
|
+
}) {
|
222
|
+
if (isAbortError(error)) {
|
223
|
+
return error;
|
224
|
+
}
|
225
|
+
if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
|
226
|
+
const cause = error.cause;
|
227
|
+
if (cause != null) {
|
228
|
+
return new import_provider2.APICallError({
|
229
|
+
message: `Cannot connect to API: ${cause.message}`,
|
230
|
+
cause,
|
231
|
+
url,
|
232
|
+
requestBodyValues,
|
233
|
+
isRetryable: true
|
234
|
+
// retry when network error
|
235
|
+
});
|
236
|
+
}
|
237
|
+
}
|
238
|
+
return error;
|
239
|
+
}
|
240
|
+
|
264
241
|
// src/remove-undefined-entries.ts
|
265
242
|
function removeUndefinedEntries(record) {
|
266
243
|
return Object.fromEntries(
|
@@ -268,11 +245,6 @@ function removeUndefinedEntries(record) {
|
|
268
245
|
);
|
269
246
|
}
|
270
247
|
|
271
|
-
// src/is-abort-error.ts
|
272
|
-
function isAbortError(error) {
|
273
|
-
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
274
|
-
}
|
275
|
-
|
276
248
|
// src/get-from-api.ts
|
277
249
|
var getOriginalFetch = () => globalThis.fetch;
|
278
250
|
var getFromApi = async ({
|
@@ -299,10 +271,10 @@ var getFromApi = async ({
|
|
299
271
|
requestBodyValues: {}
|
300
272
|
});
|
301
273
|
} catch (error) {
|
302
|
-
if (isAbortError(error) ||
|
274
|
+
if (isAbortError(error) || import_provider3.APICallError.isInstance(error)) {
|
303
275
|
throw error;
|
304
276
|
}
|
305
|
-
throw new
|
277
|
+
throw new import_provider3.APICallError({
|
306
278
|
message: "Failed to process error response",
|
307
279
|
cause: error,
|
308
280
|
statusCode: response.status,
|
@@ -321,11 +293,11 @@ var getFromApi = async ({
|
|
321
293
|
});
|
322
294
|
} catch (error) {
|
323
295
|
if (error instanceof Error) {
|
324
|
-
if (isAbortError(error) ||
|
296
|
+
if (isAbortError(error) || import_provider3.APICallError.isInstance(error)) {
|
325
297
|
throw error;
|
326
298
|
}
|
327
299
|
}
|
328
|
-
throw new
|
300
|
+
throw new import_provider3.APICallError({
|
329
301
|
message: "Failed to process successful response",
|
330
302
|
cause: error,
|
331
303
|
statusCode: response.status,
|
@@ -335,27 +307,26 @@ var getFromApi = async ({
|
|
335
307
|
});
|
336
308
|
}
|
337
309
|
} catch (error) {
|
338
|
-
|
339
|
-
throw error;
|
340
|
-
}
|
341
|
-
if (error instanceof TypeError && error.message === "fetch failed") {
|
342
|
-
const cause = error.cause;
|
343
|
-
if (cause != null) {
|
344
|
-
throw new import_provider2.APICallError({
|
345
|
-
message: `Cannot connect to API: ${cause.message}`,
|
346
|
-
cause,
|
347
|
-
url,
|
348
|
-
isRetryable: true,
|
349
|
-
requestBodyValues: {}
|
350
|
-
});
|
351
|
-
}
|
352
|
-
}
|
353
|
-
throw error;
|
310
|
+
throw handleFetchError({ error, url, requestBodyValues: {} });
|
354
311
|
}
|
355
312
|
};
|
356
313
|
|
314
|
+
// src/is-url-supported.ts
|
315
|
+
function isUrlSupported({
|
316
|
+
mediaType,
|
317
|
+
url,
|
318
|
+
supportedUrls
|
319
|
+
}) {
|
320
|
+
url = url.toLowerCase();
|
321
|
+
mediaType = mediaType.toLowerCase();
|
322
|
+
return Object.entries(supportedUrls).map(([key, value]) => {
|
323
|
+
const mediaType2 = key.toLowerCase();
|
324
|
+
return mediaType2 === "*" || mediaType2 === "*/*" ? { mediaTypePrefix: "", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\*/, ""), regexes: value };
|
325
|
+
}).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));
|
326
|
+
}
|
327
|
+
|
357
328
|
// src/load-api-key.ts
|
358
|
-
var
|
329
|
+
var import_provider4 = require("@ai-sdk/provider");
|
359
330
|
function loadApiKey({
|
360
331
|
apiKey,
|
361
332
|
environmentVariableName,
|
@@ -366,23 +337,23 @@ function loadApiKey({
|
|
366
337
|
return apiKey;
|
367
338
|
}
|
368
339
|
if (apiKey != null) {
|
369
|
-
throw new
|
340
|
+
throw new import_provider4.LoadAPIKeyError({
|
370
341
|
message: `${description} API key must be a string.`
|
371
342
|
});
|
372
343
|
}
|
373
344
|
if (typeof process === "undefined") {
|
374
|
-
throw new
|
345
|
+
throw new import_provider4.LoadAPIKeyError({
|
375
346
|
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
|
376
347
|
});
|
377
348
|
}
|
378
349
|
apiKey = process.env[environmentVariableName];
|
379
350
|
if (apiKey == null) {
|
380
|
-
throw new
|
351
|
+
throw new import_provider4.LoadAPIKeyError({
|
381
352
|
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
|
382
353
|
});
|
383
354
|
}
|
384
355
|
if (typeof apiKey !== "string") {
|
385
|
-
throw new
|
356
|
+
throw new import_provider4.LoadAPIKeyError({
|
386
357
|
message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
|
387
358
|
});
|
388
359
|
}
|
@@ -408,7 +379,7 @@ function loadOptionalSetting({
|
|
408
379
|
}
|
409
380
|
|
410
381
|
// src/load-setting.ts
|
411
|
-
var
|
382
|
+
var import_provider5 = require("@ai-sdk/provider");
|
412
383
|
function loadSetting({
|
413
384
|
settingValue,
|
414
385
|
environmentVariableName,
|
@@ -419,23 +390,23 @@ function loadSetting({
|
|
419
390
|
return settingValue;
|
420
391
|
}
|
421
392
|
if (settingValue != null) {
|
422
|
-
throw new
|
393
|
+
throw new import_provider5.LoadSettingError({
|
423
394
|
message: `${description} setting must be a string.`
|
424
395
|
});
|
425
396
|
}
|
426
397
|
if (typeof process === "undefined") {
|
427
|
-
throw new
|
398
|
+
throw new import_provider5.LoadSettingError({
|
428
399
|
message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.`
|
429
400
|
});
|
430
401
|
}
|
431
402
|
settingValue = process.env[environmentVariableName];
|
432
403
|
if (settingValue == null) {
|
433
|
-
throw new
|
404
|
+
throw new import_provider5.LoadSettingError({
|
434
405
|
message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.`
|
435
406
|
});
|
436
407
|
}
|
437
408
|
if (typeof settingValue !== "string") {
|
438
|
-
throw new
|
409
|
+
throw new import_provider5.LoadSettingError({
|
439
410
|
message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
|
440
411
|
});
|
441
412
|
}
|
@@ -443,7 +414,7 @@ function loadSetting({
|
|
443
414
|
}
|
444
415
|
|
445
416
|
// src/parse-json.ts
|
446
|
-
var
|
417
|
+
var import_provider8 = require("@ai-sdk/provider");
|
447
418
|
|
448
419
|
// src/secure-json-parse.ts
|
449
420
|
var suspectProtoRx = /"__proto__"\s*:/;
|
@@ -491,9 +462,10 @@ function secureJsonParse(text) {
|
|
491
462
|
}
|
492
463
|
|
493
464
|
// src/validate-types.ts
|
494
|
-
var
|
465
|
+
var import_provider7 = require("@ai-sdk/provider");
|
495
466
|
|
496
467
|
// src/validator.ts
|
468
|
+
var import_provider6 = require("@ai-sdk/provider");
|
497
469
|
var validatorSymbol = Symbol.for("vercel.ai.validator");
|
498
470
|
function validator(validate) {
|
499
471
|
return { [validatorSymbol]: true, validate };
|
@@ -502,53 +474,61 @@ function isValidator(value) {
|
|
502
474
|
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
503
475
|
}
|
504
476
|
function asValidator(value) {
|
505
|
-
return isValidator(value) ? value :
|
477
|
+
return isValidator(value) ? value : standardSchemaValidator(value);
|
506
478
|
}
|
507
|
-
function
|
508
|
-
return validator((value) => {
|
509
|
-
const result =
|
510
|
-
return result.
|
479
|
+
function standardSchemaValidator(standardSchema) {
|
480
|
+
return validator(async (value) => {
|
481
|
+
const result = await standardSchema["~standard"].validate(value);
|
482
|
+
return result.issues == null ? { success: true, value: result.value } : {
|
483
|
+
success: false,
|
484
|
+
error: new import_provider6.TypeValidationError({
|
485
|
+
value,
|
486
|
+
cause: result.issues
|
487
|
+
})
|
488
|
+
};
|
511
489
|
});
|
512
490
|
}
|
513
491
|
|
514
492
|
// src/validate-types.ts
|
515
|
-
function validateTypes({
|
493
|
+
async function validateTypes({
|
516
494
|
value,
|
517
|
-
schema
|
495
|
+
schema
|
518
496
|
}) {
|
519
|
-
const result = safeValidateTypes({ value, schema
|
497
|
+
const result = await safeValidateTypes({ value, schema });
|
520
498
|
if (!result.success) {
|
521
|
-
throw
|
499
|
+
throw import_provider7.TypeValidationError.wrap({ value, cause: result.error });
|
522
500
|
}
|
523
501
|
return result.value;
|
524
502
|
}
|
525
|
-
function safeValidateTypes({
|
503
|
+
async function safeValidateTypes({
|
526
504
|
value,
|
527
505
|
schema
|
528
506
|
}) {
|
529
507
|
const validator2 = asValidator(schema);
|
530
508
|
try {
|
531
509
|
if (validator2.validate == null) {
|
532
|
-
return { success: true, value };
|
510
|
+
return { success: true, value, rawValue: value };
|
533
511
|
}
|
534
|
-
const result = validator2.validate(value);
|
512
|
+
const result = await validator2.validate(value);
|
535
513
|
if (result.success) {
|
536
|
-
return result;
|
514
|
+
return { success: true, value: result.value, rawValue: value };
|
537
515
|
}
|
538
516
|
return {
|
539
517
|
success: false,
|
540
|
-
error:
|
518
|
+
error: import_provider7.TypeValidationError.wrap({ value, cause: result.error }),
|
519
|
+
rawValue: value
|
541
520
|
};
|
542
521
|
} catch (error) {
|
543
522
|
return {
|
544
523
|
success: false,
|
545
|
-
error:
|
524
|
+
error: import_provider7.TypeValidationError.wrap({ value, cause: error }),
|
525
|
+
rawValue: value
|
546
526
|
};
|
547
527
|
}
|
548
528
|
}
|
549
529
|
|
550
530
|
// src/parse-json.ts
|
551
|
-
function parseJSON({
|
531
|
+
async function parseJSON({
|
552
532
|
text,
|
553
533
|
schema
|
554
534
|
}) {
|
@@ -559,13 +539,13 @@ function parseJSON({
|
|
559
539
|
}
|
560
540
|
return validateTypes({ value, schema });
|
561
541
|
} catch (error) {
|
562
|
-
if (
|
542
|
+
if (import_provider8.JSONParseError.isInstance(error) || import_provider8.TypeValidationError.isInstance(error)) {
|
563
543
|
throw error;
|
564
544
|
}
|
565
|
-
throw new
|
545
|
+
throw new import_provider8.JSONParseError({ text, cause: error });
|
566
546
|
}
|
567
547
|
}
|
568
|
-
function safeParseJSON({
|
548
|
+
async function safeParseJSON({
|
569
549
|
text,
|
570
550
|
schema
|
571
551
|
}) {
|
@@ -574,12 +554,12 @@ function safeParseJSON({
|
|
574
554
|
if (schema == null) {
|
575
555
|
return { success: true, value, rawValue: value };
|
576
556
|
}
|
577
|
-
|
578
|
-
return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
|
557
|
+
return await safeValidateTypes({ value, schema });
|
579
558
|
} catch (error) {
|
580
559
|
return {
|
581
560
|
success: false,
|
582
|
-
error:
|
561
|
+
error: import_provider8.JSONParseError.isInstance(error) ? error : new import_provider8.JSONParseError({ text, cause: error }),
|
562
|
+
rawValue: void 0
|
583
563
|
};
|
584
564
|
}
|
585
565
|
}
|
@@ -592,9 +572,27 @@ function isParsableJson(input) {
|
|
592
572
|
}
|
593
573
|
}
|
594
574
|
|
575
|
+
// src/parse-json-event-stream.ts
|
576
|
+
var import_stream = require("eventsource-parser/stream");
|
577
|
+
function parseJsonEventStream({
|
578
|
+
stream,
|
579
|
+
schema
|
580
|
+
}) {
|
581
|
+
return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new import_stream.EventSourceParserStream()).pipeThrough(
|
582
|
+
new TransformStream({
|
583
|
+
async transform({ data }, controller) {
|
584
|
+
if (data === "[DONE]") {
|
585
|
+
return;
|
586
|
+
}
|
587
|
+
controller.enqueue(await safeParseJSON({ text: data, schema }));
|
588
|
+
}
|
589
|
+
})
|
590
|
+
);
|
591
|
+
}
|
592
|
+
|
595
593
|
// src/parse-provider-options.ts
|
596
|
-
var
|
597
|
-
function parseProviderOptions({
|
594
|
+
var import_provider9 = require("@ai-sdk/provider");
|
595
|
+
async function parseProviderOptions({
|
598
596
|
provider,
|
599
597
|
providerOptions,
|
600
598
|
schema
|
@@ -602,12 +600,12 @@ function parseProviderOptions({
|
|
602
600
|
if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
|
603
601
|
return void 0;
|
604
602
|
}
|
605
|
-
const parsedProviderOptions = safeValidateTypes({
|
603
|
+
const parsedProviderOptions = await safeValidateTypes({
|
606
604
|
value: providerOptions[provider],
|
607
605
|
schema
|
608
606
|
});
|
609
607
|
if (!parsedProviderOptions.success) {
|
610
|
-
throw new
|
608
|
+
throw new import_provider9.InvalidArgumentError({
|
611
609
|
argument: "providerOptions",
|
612
610
|
message: `invalid ${provider} provider options`,
|
613
611
|
cause: parsedProviderOptions.error
|
@@ -617,7 +615,7 @@ function parseProviderOptions({
|
|
617
615
|
}
|
618
616
|
|
619
617
|
// src/post-to-api.ts
|
620
|
-
var
|
618
|
+
var import_provider10 = require("@ai-sdk/provider");
|
621
619
|
var getOriginalFetch2 = () => globalThis.fetch;
|
622
620
|
var postJsonToApi = async ({
|
623
621
|
url,
|
@@ -688,10 +686,10 @@ var postToApi = async ({
|
|
688
686
|
requestBodyValues: body.values
|
689
687
|
});
|
690
688
|
} catch (error) {
|
691
|
-
if (isAbortError(error) ||
|
689
|
+
if (isAbortError(error) || import_provider10.APICallError.isInstance(error)) {
|
692
690
|
throw error;
|
693
691
|
}
|
694
|
-
throw new
|
692
|
+
throw new import_provider10.APICallError({
|
695
693
|
message: "Failed to process error response",
|
696
694
|
cause: error,
|
697
695
|
statusCode: response.status,
|
@@ -710,11 +708,11 @@ var postToApi = async ({
|
|
710
708
|
});
|
711
709
|
} catch (error) {
|
712
710
|
if (error instanceof Error) {
|
713
|
-
if (isAbortError(error) ||
|
711
|
+
if (isAbortError(error) || import_provider10.APICallError.isInstance(error)) {
|
714
712
|
throw error;
|
715
713
|
}
|
716
714
|
}
|
717
|
-
throw new
|
715
|
+
throw new import_provider10.APICallError({
|
718
716
|
message: "Failed to process successful response",
|
719
717
|
cause: error,
|
720
718
|
statusCode: response.status,
|
@@ -724,26 +722,74 @@ var postToApi = async ({
|
|
724
722
|
});
|
725
723
|
}
|
726
724
|
} catch (error) {
|
727
|
-
|
728
|
-
throw error;
|
729
|
-
}
|
730
|
-
if (error instanceof TypeError && error.message === "fetch failed") {
|
731
|
-
const cause = error.cause;
|
732
|
-
if (cause != null) {
|
733
|
-
throw new import_provider8.APICallError({
|
734
|
-
message: `Cannot connect to API: ${cause.message}`,
|
735
|
-
cause,
|
736
|
-
url,
|
737
|
-
requestBodyValues: body.values,
|
738
|
-
isRetryable: true
|
739
|
-
// retry when network error
|
740
|
-
});
|
741
|
-
}
|
742
|
-
}
|
743
|
-
throw error;
|
725
|
+
throw handleFetchError({ error, url, requestBodyValues: body.values });
|
744
726
|
}
|
745
727
|
};
|
746
728
|
|
729
|
+
// src/types/tool.ts
|
730
|
+
function tool(tool2) {
|
731
|
+
return tool2;
|
732
|
+
}
|
733
|
+
function dynamicTool(tool2) {
|
734
|
+
return { ...tool2, type: "dynamic" };
|
735
|
+
}
|
736
|
+
|
737
|
+
// src/provider-defined-tool-factory.ts
|
738
|
+
function createProviderDefinedToolFactory({
|
739
|
+
id,
|
740
|
+
name,
|
741
|
+
inputSchema
|
742
|
+
}) {
|
743
|
+
return ({
|
744
|
+
execute,
|
745
|
+
outputSchema,
|
746
|
+
toModelOutput,
|
747
|
+
onInputStart,
|
748
|
+
onInputDelta,
|
749
|
+
onInputAvailable,
|
750
|
+
...args
|
751
|
+
}) => tool({
|
752
|
+
type: "provider-defined",
|
753
|
+
id,
|
754
|
+
name,
|
755
|
+
args,
|
756
|
+
inputSchema,
|
757
|
+
outputSchema,
|
758
|
+
execute,
|
759
|
+
toModelOutput,
|
760
|
+
onInputStart,
|
761
|
+
onInputDelta,
|
762
|
+
onInputAvailable
|
763
|
+
});
|
764
|
+
}
|
765
|
+
function createProviderDefinedToolFactoryWithOutputSchema({
|
766
|
+
id,
|
767
|
+
name,
|
768
|
+
inputSchema,
|
769
|
+
outputSchema
|
770
|
+
}) {
|
771
|
+
return ({
|
772
|
+
execute,
|
773
|
+
toModelOutput,
|
774
|
+
onInputStart,
|
775
|
+
onInputDelta,
|
776
|
+
onInputAvailable,
|
777
|
+
...args
|
778
|
+
}) => tool({
|
779
|
+
type: "provider-defined",
|
780
|
+
id,
|
781
|
+
name,
|
782
|
+
args,
|
783
|
+
inputSchema,
|
784
|
+
outputSchema,
|
785
|
+
execute,
|
786
|
+
toModelOutput,
|
787
|
+
onInputStart,
|
788
|
+
onInputDelta,
|
789
|
+
onInputAvailable
|
790
|
+
});
|
791
|
+
}
|
792
|
+
|
747
793
|
// src/resolve.ts
|
748
794
|
async function resolve(value) {
|
749
795
|
if (typeof value === "function") {
|
@@ -753,7 +799,7 @@ async function resolve(value) {
|
|
753
799
|
}
|
754
800
|
|
755
801
|
// src/response-handler.ts
|
756
|
-
var
|
802
|
+
var import_provider11 = require("@ai-sdk/provider");
|
757
803
|
var createJsonErrorResponseHandler = ({
|
758
804
|
errorSchema,
|
759
805
|
errorToMessage,
|
@@ -764,7 +810,7 @@ var createJsonErrorResponseHandler = ({
|
|
764
810
|
if (responseBody.trim() === "") {
|
765
811
|
return {
|
766
812
|
responseHeaders,
|
767
|
-
value: new
|
813
|
+
value: new import_provider11.APICallError({
|
768
814
|
message: response.statusText,
|
769
815
|
url,
|
770
816
|
requestBodyValues,
|
@@ -776,13 +822,13 @@ var createJsonErrorResponseHandler = ({
|
|
776
822
|
};
|
777
823
|
}
|
778
824
|
try {
|
779
|
-
const parsedError = parseJSON({
|
825
|
+
const parsedError = await parseJSON({
|
780
826
|
text: responseBody,
|
781
827
|
schema: errorSchema
|
782
828
|
});
|
783
829
|
return {
|
784
830
|
responseHeaders,
|
785
|
-
value: new
|
831
|
+
value: new import_provider11.APICallError({
|
786
832
|
message: errorToMessage(parsedError),
|
787
833
|
url,
|
788
834
|
requestBodyValues,
|
@@ -796,7 +842,7 @@ var createJsonErrorResponseHandler = ({
|
|
796
842
|
} catch (parseError) {
|
797
843
|
return {
|
798
844
|
responseHeaders,
|
799
|
-
value: new
|
845
|
+
value: new import_provider11.APICallError({
|
800
846
|
message: response.statusText,
|
801
847
|
url,
|
802
848
|
requestBodyValues,
|
@@ -811,41 +857,30 @@ var createJsonErrorResponseHandler = ({
|
|
811
857
|
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
|
812
858
|
const responseHeaders = extractResponseHeaders(response);
|
813
859
|
if (response.body == null) {
|
814
|
-
throw new
|
860
|
+
throw new import_provider11.EmptyResponseBodyError({});
|
815
861
|
}
|
816
862
|
return {
|
817
863
|
responseHeaders,
|
818
|
-
value:
|
819
|
-
|
820
|
-
|
821
|
-
|
822
|
-
return;
|
823
|
-
}
|
824
|
-
controller.enqueue(
|
825
|
-
safeParseJSON({
|
826
|
-
text: data,
|
827
|
-
schema: chunkSchema
|
828
|
-
})
|
829
|
-
);
|
830
|
-
}
|
831
|
-
})
|
832
|
-
)
|
864
|
+
value: parseJsonEventStream({
|
865
|
+
stream: response.body,
|
866
|
+
schema: chunkSchema
|
867
|
+
})
|
833
868
|
};
|
834
869
|
};
|
835
870
|
var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
|
836
871
|
const responseHeaders = extractResponseHeaders(response);
|
837
872
|
if (response.body == null) {
|
838
|
-
throw new
|
873
|
+
throw new import_provider11.EmptyResponseBodyError({});
|
839
874
|
}
|
840
875
|
let buffer = "";
|
841
876
|
return {
|
842
877
|
responseHeaders,
|
843
878
|
value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(
|
844
879
|
new TransformStream({
|
845
|
-
transform(chunkText, controller) {
|
880
|
+
async transform(chunkText, controller) {
|
846
881
|
if (chunkText.endsWith("\n")) {
|
847
882
|
controller.enqueue(
|
848
|
-
safeParseJSON({
|
883
|
+
await safeParseJSON({
|
849
884
|
text: buffer + chunkText,
|
850
885
|
schema: chunkSchema
|
851
886
|
})
|
@@ -861,13 +896,13 @@ var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
|
|
861
896
|
};
|
862
897
|
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
|
863
898
|
const responseBody = await response.text();
|
864
|
-
const parsedResult = safeParseJSON({
|
899
|
+
const parsedResult = await safeParseJSON({
|
865
900
|
text: responseBody,
|
866
901
|
schema: responseSchema
|
867
902
|
});
|
868
903
|
const responseHeaders = extractResponseHeaders(response);
|
869
904
|
if (!parsedResult.success) {
|
870
|
-
throw new
|
905
|
+
throw new import_provider11.APICallError({
|
871
906
|
message: "Invalid JSON response",
|
872
907
|
cause: parsedResult.error,
|
873
908
|
statusCode: response.status,
|
@@ -886,7 +921,7 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
|
|
886
921
|
var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
|
887
922
|
const responseHeaders = extractResponseHeaders(response);
|
888
923
|
if (!response.body) {
|
889
|
-
throw new
|
924
|
+
throw new import_provider11.APICallError({
|
890
925
|
message: "Response body is empty",
|
891
926
|
url,
|
892
927
|
requestBodyValues,
|
@@ -902,7 +937,7 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
|
|
902
937
|
value: new Uint8Array(buffer)
|
903
938
|
};
|
904
939
|
} catch (error) {
|
905
|
-
throw new
|
940
|
+
throw new import_provider11.APICallError({
|
906
941
|
message: "Failed to read response as array buffer",
|
907
942
|
url,
|
908
943
|
requestBodyValues,
|
@@ -918,7 +953,7 @@ var createStatusCodeErrorResponseHandler = () => async ({ response, url, request
|
|
918
953
|
const responseBody = await response.text();
|
919
954
|
return {
|
920
955
|
responseHeaders,
|
921
|
-
value: new
|
956
|
+
value: new import_provider11.APICallError({
|
922
957
|
message: response.statusText,
|
923
958
|
url,
|
924
959
|
requestBodyValues,
|
@@ -929,6 +964,76 @@ var createStatusCodeErrorResponseHandler = () => async ({ response, url, request
|
|
929
964
|
};
|
930
965
|
};
|
931
966
|
|
967
|
+
// src/zod-schema.ts
|
968
|
+
var z4 = __toESM(require("zod/v4"));
|
969
|
+
var import_zod_to_json_schema = __toESM(require("zod-to-json-schema"));
|
970
|
+
function zod3Schema(zodSchema2, options) {
|
971
|
+
var _a;
|
972
|
+
const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
|
973
|
+
return jsonSchema(
|
974
|
+
(0, import_zod_to_json_schema.default)(zodSchema2, {
|
975
|
+
$refStrategy: useReferences ? "root" : "none",
|
976
|
+
target: "jsonSchema7"
|
977
|
+
// note: openai mode breaks various gemini conversions
|
978
|
+
}),
|
979
|
+
{
|
980
|
+
validate: async (value) => {
|
981
|
+
const result = await zodSchema2.safeParseAsync(value);
|
982
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
983
|
+
}
|
984
|
+
}
|
985
|
+
);
|
986
|
+
}
|
987
|
+
function zod4Schema(zodSchema2, options) {
|
988
|
+
var _a;
|
989
|
+
const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
|
990
|
+
const z4JSONSchema = z4.toJSONSchema(zodSchema2, {
|
991
|
+
target: "draft-7",
|
992
|
+
io: "output",
|
993
|
+
reused: useReferences ? "ref" : "inline"
|
994
|
+
});
|
995
|
+
return jsonSchema(z4JSONSchema, {
|
996
|
+
validate: async (value) => {
|
997
|
+
const result = await z4.safeParseAsync(zodSchema2, value);
|
998
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
999
|
+
}
|
1000
|
+
});
|
1001
|
+
}
|
1002
|
+
function isZod4Schema(zodSchema2) {
|
1003
|
+
return "_zod" in zodSchema2;
|
1004
|
+
}
|
1005
|
+
function zodSchema(zodSchema2, options) {
|
1006
|
+
if (isZod4Schema(zodSchema2)) {
|
1007
|
+
return zod4Schema(zodSchema2, options);
|
1008
|
+
} else {
|
1009
|
+
return zod3Schema(zodSchema2, options);
|
1010
|
+
}
|
1011
|
+
}
|
1012
|
+
|
1013
|
+
// src/schema.ts
|
1014
|
+
var schemaSymbol = Symbol.for("vercel.ai.schema");
|
1015
|
+
function jsonSchema(jsonSchema2, {
|
1016
|
+
validate
|
1017
|
+
} = {}) {
|
1018
|
+
return {
|
1019
|
+
[schemaSymbol]: true,
|
1020
|
+
_type: void 0,
|
1021
|
+
// should never be used directly
|
1022
|
+
[validatorSymbol]: true,
|
1023
|
+
jsonSchema: jsonSchema2,
|
1024
|
+
validate
|
1025
|
+
};
|
1026
|
+
}
|
1027
|
+
function isSchema(value) {
|
1028
|
+
return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
|
1029
|
+
}
|
1030
|
+
function asSchema(schema) {
|
1031
|
+
return schema == null ? jsonSchema({
|
1032
|
+
properties: {},
|
1033
|
+
additionalProperties: false
|
1034
|
+
}) : isSchema(schema) ? schema : zodSchema(schema);
|
1035
|
+
}
|
1036
|
+
|
932
1037
|
// src/uint8-utils.ts
|
933
1038
|
var { btoa, atob } = globalThis;
|
934
1039
|
function convertBase64ToUint8Array(base64String) {
|
@@ -951,8 +1056,14 @@ function convertToBase64(value) {
|
|
951
1056
|
function withoutTrailingSlash(url) {
|
952
1057
|
return url == null ? void 0 : url.replace(/\/$/, "");
|
953
1058
|
}
|
1059
|
+
|
1060
|
+
// src/index.ts
|
1061
|
+
__reExport(src_exports, require("@standard-schema/spec"), module.exports);
|
1062
|
+
var import_stream2 = require("eventsource-parser/stream");
|
954
1063
|
// Annotate the CommonJS export names for ESM import in node:
|
955
1064
|
0 && (module.exports = {
|
1065
|
+
EventSourceParserStream,
|
1066
|
+
asSchema,
|
956
1067
|
asValidator,
|
957
1068
|
combineHeaders,
|
958
1069
|
convertAsyncIteratorToReadableStream,
|
@@ -960,25 +1071,30 @@ function withoutTrailingSlash(url) {
|
|
960
1071
|
convertToBase64,
|
961
1072
|
convertUint8ArrayToBase64,
|
962
1073
|
createBinaryResponseHandler,
|
963
|
-
createEventSourceParserStream,
|
964
1074
|
createEventSourceResponseHandler,
|
965
1075
|
createIdGenerator,
|
966
1076
|
createJsonErrorResponseHandler,
|
967
1077
|
createJsonResponseHandler,
|
968
1078
|
createJsonStreamResponseHandler,
|
1079
|
+
createProviderDefinedToolFactory,
|
1080
|
+
createProviderDefinedToolFactoryWithOutputSchema,
|
969
1081
|
createStatusCodeErrorResponseHandler,
|
970
1082
|
delay,
|
1083
|
+
dynamicTool,
|
971
1084
|
extractResponseHeaders,
|
972
1085
|
generateId,
|
973
1086
|
getErrorMessage,
|
974
1087
|
getFromApi,
|
975
1088
|
isAbortError,
|
976
1089
|
isParsableJson,
|
1090
|
+
isUrlSupported,
|
977
1091
|
isValidator,
|
1092
|
+
jsonSchema,
|
978
1093
|
loadApiKey,
|
979
1094
|
loadOptionalSetting,
|
980
1095
|
loadSetting,
|
981
1096
|
parseJSON,
|
1097
|
+
parseJsonEventStream,
|
982
1098
|
parseProviderOptions,
|
983
1099
|
postFormDataToApi,
|
984
1100
|
postJsonToApi,
|
@@ -987,10 +1103,13 @@ function withoutTrailingSlash(url) {
|
|
987
1103
|
resolve,
|
988
1104
|
safeParseJSON,
|
989
1105
|
safeValidateTypes,
|
1106
|
+
standardSchemaValidator,
|
1107
|
+
tool,
|
990
1108
|
validateTypes,
|
991
1109
|
validator,
|
992
1110
|
validatorSymbol,
|
993
1111
|
withoutTrailingSlash,
|
994
|
-
|
1112
|
+
zodSchema,
|
1113
|
+
...require("@standard-schema/spec")
|
995
1114
|
});
|
996
1115
|
//# sourceMappingURL=index.js.map
|