@ai-sdk/provider-utils 2.2.7 → 3.0.0-alpha.1

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/dist/index.mjs CHANGED
@@ -125,7 +125,7 @@ function splitLines(buffer, chunk) {
125
125
  } else if (char === "\r") {
126
126
  lines.push(currentLine);
127
127
  currentLine = "";
128
- if (chunk[i + 1] === "\n") {
128
+ if (chunk[i] === "\n") {
129
129
  i++;
130
130
  }
131
131
  } else {
@@ -146,14 +146,20 @@ function extractResponseHeaders(response) {
146
146
 
147
147
  // src/generate-id.ts
148
148
  import { InvalidArgumentError } from "@ai-sdk/provider";
149
- import { customAlphabet } from "nanoid/non-secure";
150
149
  var createIdGenerator = ({
151
150
  prefix,
152
- size: defaultSize = 16,
151
+ size = 16,
153
152
  alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
154
153
  separator = "-"
155
154
  } = {}) => {
156
- const generator = customAlphabet(alphabet, defaultSize);
155
+ const generator = () => {
156
+ const alphabetLength = alphabet.length;
157
+ const chars = new Array(size);
158
+ for (let i = 0; i < size; i++) {
159
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
160
+ }
161
+ return chars.join("");
162
+ };
157
163
  if (prefix == null) {
158
164
  return generator;
159
165
  }
@@ -163,7 +169,7 @@ var createIdGenerator = ({
163
169
  message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
164
170
  });
165
171
  }
166
- return (size) => `${prefix}${separator}${generator(size)}`;
172
+ return () => `${prefix}${separator}${generator()}`;
167
173
  };
168
174
  var generateId = createIdGenerator();
169
175
 
@@ -277,6 +283,20 @@ var getFromApi = async ({
277
283
  }
278
284
  };
279
285
 
286
+ // src/is-url-supported.ts
287
+ function isUrlSupported({
288
+ mediaType,
289
+ url,
290
+ supportedUrls
291
+ }) {
292
+ url = url.toLowerCase();
293
+ mediaType = mediaType.toLowerCase();
294
+ return Object.entries(supportedUrls).map(([key, value]) => {
295
+ const mediaType2 = key.toLowerCase();
296
+ return mediaType2 === "*" || mediaType2 === "*/*" ? { mediaTypePrefix: "", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\*/, ""), regexes: value };
297
+ }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));
298
+ }
299
+
280
300
  // src/load-api-key.ts
281
301
  import { LoadAPIKeyError } from "@ai-sdk/provider";
282
302
  function loadApiKey({
@@ -368,14 +388,59 @@ function loadSetting({
368
388
  // src/parse-json.ts
369
389
  import {
370
390
  JSONParseError,
371
- TypeValidationError as TypeValidationError2
391
+ TypeValidationError as TypeValidationError3
372
392
  } from "@ai-sdk/provider";
373
- import SecureJSON from "secure-json-parse";
393
+
394
+ // src/secure-json-parse.ts
395
+ var suspectProtoRx = /"__proto__"\s*:/;
396
+ var suspectConstructorRx = /"constructor"\s*:/;
397
+ function _parse(text) {
398
+ const obj = JSON.parse(text);
399
+ if (obj === null || typeof obj !== "object") {
400
+ return obj;
401
+ }
402
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
403
+ return obj;
404
+ }
405
+ return filter(obj);
406
+ }
407
+ function filter(obj) {
408
+ let next = [obj];
409
+ while (next.length) {
410
+ const nodes = next;
411
+ next = [];
412
+ for (const node of nodes) {
413
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
414
+ throw new SyntaxError("Object contains forbidden prototype property");
415
+ }
416
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
417
+ throw new SyntaxError("Object contains forbidden prototype property");
418
+ }
419
+ for (const key in node) {
420
+ const value = node[key];
421
+ if (value && typeof value === "object") {
422
+ next.push(value);
423
+ }
424
+ }
425
+ }
426
+ }
427
+ return obj;
428
+ }
429
+ function secureJsonParse(text) {
430
+ const { stackTraceLimit } = Error;
431
+ Error.stackTraceLimit = 0;
432
+ try {
433
+ return _parse(text);
434
+ } finally {
435
+ Error.stackTraceLimit = stackTraceLimit;
436
+ }
437
+ }
374
438
 
375
439
  // src/validate-types.ts
376
- import { TypeValidationError } from "@ai-sdk/provider";
440
+ import { TypeValidationError as TypeValidationError2 } from "@ai-sdk/provider";
377
441
 
378
442
  // src/validator.ts
443
+ import { TypeValidationError } from "@ai-sdk/provider";
379
444
  var validatorSymbol = Symbol.for("vercel.ai.validator");
380
445
  function validator(validate) {
381
446
  return { [validatorSymbol]: true, validate };
@@ -384,99 +449,124 @@ function isValidator(value) {
384
449
  return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
385
450
  }
386
451
  function asValidator(value) {
387
- return isValidator(value) ? value : zodValidator(value);
452
+ return isValidator(value) ? value : standardSchemaValidator(value);
388
453
  }
389
- function zodValidator(zodSchema) {
390
- return validator((value) => {
391
- const result = zodSchema.safeParse(value);
392
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
454
+ function standardSchemaValidator(standardSchema) {
455
+ return validator(async (value) => {
456
+ const result = await standardSchema["~standard"].validate(value);
457
+ return result.issues == null ? { success: true, value: result.value } : {
458
+ success: false,
459
+ error: new TypeValidationError({
460
+ value,
461
+ cause: result.issues
462
+ })
463
+ };
393
464
  });
394
465
  }
395
466
 
396
467
  // src/validate-types.ts
397
- function validateTypes({
468
+ async function validateTypes({
398
469
  value,
399
- schema: inputSchema
470
+ schema
400
471
  }) {
401
- const result = safeValidateTypes({ value, schema: inputSchema });
472
+ const result = await safeValidateTypes({ value, schema });
402
473
  if (!result.success) {
403
- throw TypeValidationError.wrap({ value, cause: result.error });
474
+ throw TypeValidationError2.wrap({ value, cause: result.error });
404
475
  }
405
476
  return result.value;
406
477
  }
407
- function safeValidateTypes({
478
+ async function safeValidateTypes({
408
479
  value,
409
480
  schema
410
481
  }) {
411
482
  const validator2 = asValidator(schema);
412
483
  try {
413
484
  if (validator2.validate == null) {
414
- return { success: true, value };
485
+ return { success: true, value, rawValue: value };
415
486
  }
416
- const result = validator2.validate(value);
487
+ const result = await validator2.validate(value);
417
488
  if (result.success) {
418
- return result;
489
+ return { success: true, value: result.value, rawValue: value };
419
490
  }
420
491
  return {
421
492
  success: false,
422
- error: TypeValidationError.wrap({ value, cause: result.error })
493
+ error: TypeValidationError2.wrap({ value, cause: result.error }),
494
+ rawValue: value
423
495
  };
424
496
  } catch (error) {
425
497
  return {
426
498
  success: false,
427
- error: TypeValidationError.wrap({ value, cause: error })
499
+ error: TypeValidationError2.wrap({ value, cause: error }),
500
+ rawValue: value
428
501
  };
429
502
  }
430
503
  }
431
504
 
432
505
  // src/parse-json.ts
433
- function parseJSON({
506
+ async function parseJSON({
434
507
  text,
435
508
  schema
436
509
  }) {
437
510
  try {
438
- const value = SecureJSON.parse(text);
511
+ const value = secureJsonParse(text);
439
512
  if (schema == null) {
440
513
  return value;
441
514
  }
442
515
  return validateTypes({ value, schema });
443
516
  } catch (error) {
444
- if (JSONParseError.isInstance(error) || TypeValidationError2.isInstance(error)) {
517
+ if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {
445
518
  throw error;
446
519
  }
447
520
  throw new JSONParseError({ text, cause: error });
448
521
  }
449
522
  }
450
- function safeParseJSON({
523
+ async function safeParseJSON({
451
524
  text,
452
525
  schema
453
526
  }) {
454
527
  try {
455
- const value = SecureJSON.parse(text);
528
+ const value = secureJsonParse(text);
456
529
  if (schema == null) {
457
530
  return { success: true, value, rawValue: value };
458
531
  }
459
- const validationResult = safeValidateTypes({ value, schema });
460
- return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
532
+ return await safeValidateTypes({ value, schema });
461
533
  } catch (error) {
462
534
  return {
463
535
  success: false,
464
- error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
536
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
537
+ rawValue: void 0
465
538
  };
466
539
  }
467
540
  }
468
541
  function isParsableJson(input) {
469
542
  try {
470
- SecureJSON.parse(input);
543
+ secureJsonParse(input);
471
544
  return true;
472
545
  } catch (e) {
473
546
  return false;
474
547
  }
475
548
  }
476
549
 
550
+ // src/parse-json-event-stream.ts
551
+ function parseJsonEventStream({
552
+ stream,
553
+ schema
554
+ }) {
555
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(createEventSourceParserStream()).pipeThrough(
556
+ new TransformStream({
557
+ async transform({ data }, controller) {
558
+ if (data === "[DONE]") {
559
+ return;
560
+ }
561
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
562
+ }
563
+ })
564
+ );
565
+ }
566
+
477
567
  // src/parse-provider-options.ts
478
568
  import { InvalidArgumentError as InvalidArgumentError2 } from "@ai-sdk/provider";
479
- function parseProviderOptions({
569
+ async function parseProviderOptions({
480
570
  provider,
481
571
  providerOptions,
482
572
  schema
@@ -484,7 +574,7 @@ function parseProviderOptions({
484
574
  if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
485
575
  return void 0;
486
576
  }
487
- const parsedProviderOptions = safeValidateTypes({
577
+ const parsedProviderOptions = await safeValidateTypes({
488
578
  value: providerOptions[provider],
489
579
  schema
490
580
  });
@@ -658,7 +748,7 @@ var createJsonErrorResponseHandler = ({
658
748
  };
659
749
  }
660
750
  try {
661
- const parsedError = parseJSON({
751
+ const parsedError = await parseJSON({
662
752
  text: responseBody,
663
753
  schema: errorSchema
664
754
  });
@@ -697,21 +787,10 @@ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) =>
697
787
  }
698
788
  return {
699
789
  responseHeaders,
700
- value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(createEventSourceParserStream()).pipeThrough(
701
- new TransformStream({
702
- transform({ data }, controller) {
703
- if (data === "[DONE]") {
704
- return;
705
- }
706
- controller.enqueue(
707
- safeParseJSON({
708
- text: data,
709
- schema: chunkSchema
710
- })
711
- );
712
- }
713
- })
714
- )
790
+ value: parseJsonEventStream({
791
+ stream: response.body,
792
+ schema: chunkSchema
793
+ })
715
794
  };
716
795
  };
717
796
  var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
@@ -724,10 +803,10 @@ var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
724
803
  responseHeaders,
725
804
  value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(
726
805
  new TransformStream({
727
- transform(chunkText, controller) {
806
+ async transform(chunkText, controller) {
728
807
  if (chunkText.endsWith("\n")) {
729
808
  controller.enqueue(
730
- safeParseJSON({
809
+ await safeParseJSON({
731
810
  text: buffer + chunkText,
732
811
  schema: chunkSchema
733
812
  })
@@ -743,7 +822,7 @@ var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
743
822
  };
744
823
  var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
745
824
  const responseBody = await response.text();
746
- const parsedResult = safeParseJSON({
825
+ const parsedResult = await safeParseJSON({
747
826
  text: responseBody,
748
827
  schema: responseSchema
749
828
  });
@@ -811,6 +890,50 @@ var createStatusCodeErrorResponseHandler = () => async ({ response, url, request
811
890
  };
812
891
  };
813
892
 
893
+ // src/zod-schema.ts
894
+ import zodToJsonSchema from "zod-to-json-schema";
895
+ function zodSchema(zodSchema2, options) {
896
+ var _a;
897
+ const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
898
+ return jsonSchema(
899
+ zodToJsonSchema(zodSchema2, {
900
+ $refStrategy: useReferences ? "root" : "none",
901
+ target: "jsonSchema7"
902
+ // note: openai mode breaks various gemini conversions
903
+ }),
904
+ {
905
+ validate: (value) => {
906
+ const result = zodSchema2.safeParse(value);
907
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
908
+ }
909
+ }
910
+ );
911
+ }
912
+
913
+ // src/schema.ts
914
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
915
+ function jsonSchema(jsonSchema2, {
916
+ validate
917
+ } = {}) {
918
+ return {
919
+ [schemaSymbol]: true,
920
+ _type: void 0,
921
+ // should never be used directly
922
+ [validatorSymbol]: true,
923
+ jsonSchema: jsonSchema2,
924
+ validate
925
+ };
926
+ }
927
+ function isSchema(value) {
928
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
929
+ }
930
+ function asSchema(schema) {
931
+ return schema == null ? jsonSchema({
932
+ properties: {},
933
+ additionalProperties: false
934
+ }) : isSchema(schema) ? schema : zodSchema(schema);
935
+ }
936
+
814
937
  // src/uint8-utils.ts
815
938
  var { btoa, atob } = globalThis;
816
939
  function convertBase64ToUint8Array(base64String) {
@@ -825,16 +948,24 @@ function convertUint8ArrayToBase64(array) {
825
948
  }
826
949
  return btoa(latin1string);
827
950
  }
951
+ function convertToBase64(value) {
952
+ return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
953
+ }
828
954
 
829
955
  // src/without-trailing-slash.ts
830
956
  function withoutTrailingSlash(url) {
831
957
  return url == null ? void 0 : url.replace(/\/$/, "");
832
958
  }
959
+
960
+ // src/index.ts
961
+ export * from "@standard-schema/spec";
833
962
  export {
963
+ asSchema,
834
964
  asValidator,
835
965
  combineHeaders,
836
966
  convertAsyncIteratorToReadableStream,
837
967
  convertBase64ToUint8Array,
968
+ convertToBase64,
838
969
  convertUint8ArrayToBase64,
839
970
  createBinaryResponseHandler,
840
971
  createEventSourceParserStream,
@@ -851,11 +982,14 @@ export {
851
982
  getFromApi,
852
983
  isAbortError,
853
984
  isParsableJson,
985
+ isUrlSupported,
854
986
  isValidator,
987
+ jsonSchema,
855
988
  loadApiKey,
856
989
  loadOptionalSetting,
857
990
  loadSetting,
858
991
  parseJSON,
992
+ parseJsonEventStream,
859
993
  parseProviderOptions,
860
994
  postFormDataToApi,
861
995
  postJsonToApi,
@@ -864,10 +998,11 @@ export {
864
998
  resolve,
865
999
  safeParseJSON,
866
1000
  safeValidateTypes,
1001
+ standardSchemaValidator,
867
1002
  validateTypes,
868
1003
  validator,
869
1004
  validatorSymbol,
870
1005
  withoutTrailingSlash,
871
- zodValidator
1006
+ zodSchema
872
1007
  };
873
1008
  //# sourceMappingURL=index.mjs.map