@ai-sdk/provider-utils 4.0.0-beta.14 → 4.0.0-beta.16

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
@@ -194,7 +194,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
194
194
  }
195
195
 
196
196
  // src/version.ts
197
- var VERSION = true ? "4.0.0-beta.14" : "0.0.0-test";
197
+ var VERSION = true ? "4.0.0-beta.16" : "0.0.0-test";
198
198
 
199
199
  // src/get-from-api.ts
200
200
  var getOriginalFetch = () => globalThis.fetch;
@@ -474,1865 +474,1829 @@ function secureJsonParse(text) {
474
474
  // src/validate-types.ts
475
475
  import { TypeValidationError as TypeValidationError2 } from "@ai-sdk/provider";
476
476
 
477
- // src/validator.ts
477
+ // src/schema.ts
478
478
  import { TypeValidationError } from "@ai-sdk/provider";
479
- var validatorSymbol = Symbol.for("vercel.ai.validator");
480
- function validator(validate) {
481
- return { [validatorSymbol]: true, validate };
482
- }
483
- function isValidator(value) {
484
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
485
- }
486
- function lazyValidator(createValidator) {
487
- let validator2;
488
- return () => {
489
- if (validator2 == null) {
490
- validator2 = createValidator();
479
+ import * as z4 from "zod/v4";
480
+
481
+ // src/to-json-schema/arktype-to-json-schema.ts
482
+ var arktypeToJsonSchema = (schema) => () => {
483
+ return schema.toJsonSchema();
484
+ };
485
+
486
+ // src/to-json-schema/effect-to-json-schema.ts
487
+ var effectToJsonSchema = (schema) => async () => {
488
+ try {
489
+ const { JSONSchema } = await import("effect");
490
+ return JSONSchema.make(schema);
491
+ } catch (e) {
492
+ throw new Error(`Failed to import module 'effect'`);
493
+ }
494
+ };
495
+
496
+ // src/to-json-schema/valibot-to-json-schema.ts
497
+ var valibotToJsonSchema = (schema) => {
498
+ return async () => {
499
+ try {
500
+ const { toJsonSchema } = await import("@valibot/to-json-schema");
501
+ return toJsonSchema(schema);
502
+ } catch (e) {
503
+ throw new Error(`Failed to import module '@valibot/to-json-schema'`);
491
504
  }
492
- return validator2;
493
505
  };
494
- }
495
- function asValidator(value) {
496
- return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
497
- }
498
- function standardSchemaValidator(standardSchema2) {
499
- return validator(async (value) => {
500
- const result = await standardSchema2["~standard"].validate(value);
501
- return result.issues == null ? { success: true, value: result.value } : {
502
- success: false,
503
- error: new TypeValidationError({
504
- value,
505
- cause: result.issues
506
- })
507
- };
508
- });
506
+ };
507
+
508
+ // src/to-json-schema/zod3-to-json-schema/options.ts
509
+ var ignoreOverride = Symbol(
510
+ "Let zodToJsonSchema decide on which parser to use"
511
+ );
512
+ var defaultOptions = {
513
+ name: void 0,
514
+ $refStrategy: "root",
515
+ basePath: ["#"],
516
+ effectStrategy: "input",
517
+ pipeStrategy: "all",
518
+ dateStrategy: "format:date-time",
519
+ mapStrategy: "entries",
520
+ removeAdditionalStrategy: "passthrough",
521
+ allowedAdditionalProperties: true,
522
+ rejectedAdditionalProperties: false,
523
+ definitionPath: "definitions",
524
+ strictUnions: false,
525
+ definitions: {},
526
+ errorMessages: false,
527
+ patternStrategy: "escape",
528
+ applyRegexFlags: false,
529
+ emailStrategy: "format:email",
530
+ base64Strategy: "contentEncoding:base64",
531
+ nameStrategy: "ref"
532
+ };
533
+ var getDefaultOptions = (options) => typeof options === "string" ? {
534
+ ...defaultOptions,
535
+ name: options
536
+ } : {
537
+ ...defaultOptions,
538
+ ...options
539
+ };
540
+
541
+ // src/to-json-schema/zod3-to-json-schema/select-parser.ts
542
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
543
+
544
+ // src/to-json-schema/zod3-to-json-schema/parsers/any.ts
545
+ function parseAnyDef() {
546
+ return {};
509
547
  }
510
548
 
511
- // src/validate-types.ts
512
- async function validateTypes({
513
- value,
514
- schema
515
- }) {
516
- const result = await safeValidateTypes({ value, schema });
517
- if (!result.success) {
518
- throw TypeValidationError2.wrap({ value, cause: result.error });
549
+ // src/to-json-schema/zod3-to-json-schema/parsers/array.ts
550
+ import { ZodFirstPartyTypeKind } from "zod/v3";
551
+ function parseArrayDef(def, refs) {
552
+ var _a, _b, _c;
553
+ const res = {
554
+ type: "array"
555
+ };
556
+ if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
557
+ res.items = parseDef(def.type._def, {
558
+ ...refs,
559
+ currentPath: [...refs.currentPath, "items"]
560
+ });
519
561
  }
520
- return result.value;
521
- }
522
- async function safeValidateTypes({
523
- value,
524
- schema
525
- }) {
526
- const validator2 = asValidator(schema);
527
- try {
528
- if (validator2.validate == null) {
529
- return { success: true, value, rawValue: value };
530
- }
531
- const result = await validator2.validate(value);
532
- if (result.success) {
533
- return { success: true, value: result.value, rawValue: value };
534
- }
535
- return {
536
- success: false,
537
- error: TypeValidationError2.wrap({ value, cause: result.error }),
538
- rawValue: value
539
- };
540
- } catch (error) {
541
- return {
542
- success: false,
543
- error: TypeValidationError2.wrap({ value, cause: error }),
544
- rawValue: value
545
- };
562
+ if (def.minLength) {
563
+ res.minItems = def.minLength.value;
564
+ }
565
+ if (def.maxLength) {
566
+ res.maxItems = def.maxLength.value;
546
567
  }
568
+ if (def.exactLength) {
569
+ res.minItems = def.exactLength.value;
570
+ res.maxItems = def.exactLength.value;
571
+ }
572
+ return res;
547
573
  }
548
574
 
549
- // src/parse-json.ts
550
- async function parseJSON({
551
- text,
552
- schema
553
- }) {
554
- try {
555
- const value = secureJsonParse(text);
556
- if (schema == null) {
557
- return value;
558
- }
559
- return validateTypes({ value, schema });
560
- } catch (error) {
561
- if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {
562
- throw error;
575
+ // src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts
576
+ function parseBigintDef(def) {
577
+ const res = {
578
+ type: "integer",
579
+ format: "int64"
580
+ };
581
+ if (!def.checks) return res;
582
+ for (const check of def.checks) {
583
+ switch (check.kind) {
584
+ case "min":
585
+ if (check.inclusive) {
586
+ res.minimum = check.value;
587
+ } else {
588
+ res.exclusiveMinimum = check.value;
589
+ }
590
+ break;
591
+ case "max":
592
+ if (check.inclusive) {
593
+ res.maximum = check.value;
594
+ } else {
595
+ res.exclusiveMaximum = check.value;
596
+ }
597
+ break;
598
+ case "multipleOf":
599
+ res.multipleOf = check.value;
600
+ break;
563
601
  }
564
- throw new JSONParseError({ text, cause: error });
565
602
  }
603
+ return res;
566
604
  }
567
- async function safeParseJSON({
568
- text,
569
- schema
570
- }) {
571
- try {
572
- const value = secureJsonParse(text);
573
- if (schema == null) {
574
- return { success: true, value, rawValue: value };
575
- }
576
- return await safeValidateTypes({ value, schema });
577
- } catch (error) {
605
+
606
+ // src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts
607
+ function parseBooleanDef() {
608
+ return { type: "boolean" };
609
+ }
610
+
611
+ // src/to-json-schema/zod3-to-json-schema/parsers/branded.ts
612
+ function parseBrandedDef(_def, refs) {
613
+ return parseDef(_def.type._def, refs);
614
+ }
615
+
616
+ // src/to-json-schema/zod3-to-json-schema/parsers/catch.ts
617
+ var parseCatchDef = (def, refs) => {
618
+ return parseDef(def.innerType._def, refs);
619
+ };
620
+
621
+ // src/to-json-schema/zod3-to-json-schema/parsers/date.ts
622
+ function parseDateDef(def, refs, overrideDateStrategy) {
623
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
624
+ if (Array.isArray(strategy)) {
578
625
  return {
579
- success: false,
580
- error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
581
- rawValue: void 0
626
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
582
627
  };
583
628
  }
629
+ switch (strategy) {
630
+ case "string":
631
+ case "format:date-time":
632
+ return {
633
+ type: "string",
634
+ format: "date-time"
635
+ };
636
+ case "format:date":
637
+ return {
638
+ type: "string",
639
+ format: "date"
640
+ };
641
+ case "integer":
642
+ return integerDateParser(def);
643
+ }
584
644
  }
585
- function isParsableJson(input) {
586
- try {
587
- secureJsonParse(input);
588
- return true;
589
- } catch (e) {
590
- return false;
645
+ var integerDateParser = (def) => {
646
+ const res = {
647
+ type: "integer",
648
+ format: "unix-time"
649
+ };
650
+ for (const check of def.checks) {
651
+ switch (check.kind) {
652
+ case "min":
653
+ res.minimum = check.value;
654
+ break;
655
+ case "max":
656
+ res.maximum = check.value;
657
+ break;
658
+ }
591
659
  }
660
+ return res;
661
+ };
662
+
663
+ // src/to-json-schema/zod3-to-json-schema/parsers/default.ts
664
+ function parseDefaultDef(_def, refs) {
665
+ return {
666
+ ...parseDef(_def.innerType._def, refs),
667
+ default: _def.defaultValue()
668
+ };
592
669
  }
593
670
 
594
- // src/parse-json-event-stream.ts
595
- import {
596
- EventSourceParserStream
597
- } from "eventsource-parser/stream";
598
- function parseJsonEventStream({
599
- stream,
600
- schema
601
- }) {
602
- return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
603
- new TransformStream({
604
- async transform({ data }, controller) {
605
- if (data === "[DONE]") {
606
- return;
607
- }
608
- controller.enqueue(await safeParseJSON({ text: data, schema }));
609
- }
610
- })
611
- );
671
+ // src/to-json-schema/zod3-to-json-schema/parsers/effects.ts
672
+ function parseEffectsDef(_def, refs) {
673
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
612
674
  }
613
675
 
614
- // src/parse-provider-options.ts
615
- import { InvalidArgumentError as InvalidArgumentError2 } from "@ai-sdk/provider";
616
- async function parseProviderOptions({
617
- provider,
618
- providerOptions,
619
- schema
620
- }) {
621
- if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
622
- return void 0;
623
- }
624
- const parsedProviderOptions = await safeValidateTypes({
625
- value: providerOptions[provider],
626
- schema
627
- });
628
- if (!parsedProviderOptions.success) {
629
- throw new InvalidArgumentError2({
630
- argument: "providerOptions",
631
- message: `invalid ${provider} provider options`,
632
- cause: parsedProviderOptions.error
633
- });
634
- }
635
- return parsedProviderOptions.value;
676
+ // src/to-json-schema/zod3-to-json-schema/parsers/enum.ts
677
+ function parseEnumDef(def) {
678
+ return {
679
+ type: "string",
680
+ enum: Array.from(def.values)
681
+ };
636
682
  }
637
683
 
638
- // src/post-to-api.ts
639
- import { APICallError as APICallError3 } from "@ai-sdk/provider";
640
- var getOriginalFetch2 = () => globalThis.fetch;
641
- var postJsonToApi = async ({
642
- url,
643
- headers,
644
- body,
645
- failedResponseHandler,
646
- successfulResponseHandler,
647
- abortSignal,
648
- fetch
649
- }) => postToApi({
650
- url,
651
- headers: {
652
- "Content-Type": "application/json",
653
- ...headers
654
- },
655
- body: {
656
- content: JSON.stringify(body),
657
- values: body
658
- },
659
- failedResponseHandler,
660
- successfulResponseHandler,
661
- abortSignal,
662
- fetch
663
- });
664
- var postFormDataToApi = async ({
665
- url,
666
- headers,
667
- formData,
668
- failedResponseHandler,
669
- successfulResponseHandler,
670
- abortSignal,
671
- fetch
672
- }) => postToApi({
673
- url,
674
- headers,
675
- body: {
676
- content: formData,
677
- values: Object.fromEntries(formData.entries())
678
- },
679
- failedResponseHandler,
680
- successfulResponseHandler,
681
- abortSignal,
682
- fetch
683
- });
684
- var postToApi = async ({
685
- url,
686
- headers = {},
687
- body,
688
- successfulResponseHandler,
689
- failedResponseHandler,
690
- abortSignal,
691
- fetch = getOriginalFetch2()
692
- }) => {
693
- try {
694
- const response = await fetch(url, {
695
- method: "POST",
696
- headers: withUserAgentSuffix(
697
- headers,
698
- `ai-sdk/provider-utils/${VERSION}`,
699
- getRuntimeEnvironmentUserAgent()
700
- ),
701
- body: body.content,
702
- signal: abortSignal
703
- });
704
- const responseHeaders = extractResponseHeaders(response);
705
- if (!response.ok) {
706
- let errorInformation;
707
- try {
708
- errorInformation = await failedResponseHandler({
709
- response,
710
- url,
711
- requestBodyValues: body.values
712
- });
713
- } catch (error) {
714
- if (isAbortError(error) || APICallError3.isInstance(error)) {
715
- throw error;
716
- }
717
- throw new APICallError3({
718
- message: "Failed to process error response",
719
- cause: error,
720
- statusCode: response.status,
721
- url,
722
- responseHeaders,
723
- requestBodyValues: body.values
724
- });
725
- }
726
- throw errorInformation.value;
727
- }
728
- try {
729
- return await successfulResponseHandler({
730
- response,
731
- url,
732
- requestBodyValues: body.values
733
- });
734
- } catch (error) {
735
- if (error instanceof Error) {
736
- if (isAbortError(error) || APICallError3.isInstance(error)) {
737
- throw error;
738
- }
684
+ // src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts
685
+ var isJsonSchema7AllOfType = (type) => {
686
+ if ("type" in type && type.type === "string") return false;
687
+ return "allOf" in type;
688
+ };
689
+ function parseIntersectionDef(def, refs) {
690
+ const allOf = [
691
+ parseDef(def.left._def, {
692
+ ...refs,
693
+ currentPath: [...refs.currentPath, "allOf", "0"]
694
+ }),
695
+ parseDef(def.right._def, {
696
+ ...refs,
697
+ currentPath: [...refs.currentPath, "allOf", "1"]
698
+ })
699
+ ].filter((x) => !!x);
700
+ const mergedAllOf = [];
701
+ allOf.forEach((schema) => {
702
+ if (isJsonSchema7AllOfType(schema)) {
703
+ mergedAllOf.push(...schema.allOf);
704
+ } else {
705
+ let nestedSchema = schema;
706
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
707
+ const { additionalProperties, ...rest } = schema;
708
+ nestedSchema = rest;
739
709
  }
740
- throw new APICallError3({
741
- message: "Failed to process successful response",
742
- cause: error,
743
- statusCode: response.status,
744
- url,
745
- responseHeaders,
746
- requestBodyValues: body.values
747
- });
710
+ mergedAllOf.push(nestedSchema);
748
711
  }
749
- } catch (error) {
750
- throw handleFetchError({ error, url, requestBodyValues: body.values });
751
- }
752
- };
753
-
754
- // src/types/tool.ts
755
- function tool(tool2) {
756
- return tool2;
757
- }
758
- function dynamicTool(tool2) {
759
- return { ...tool2, type: "dynamic" };
760
- }
761
-
762
- // src/provider-defined-tool-factory.ts
763
- function createProviderDefinedToolFactory({
764
- id,
765
- name,
766
- inputSchema
767
- }) {
768
- return ({
769
- execute,
770
- outputSchema,
771
- needsApproval,
772
- toModelOutput,
773
- onInputStart,
774
- onInputDelta,
775
- onInputAvailable,
776
- ...args
777
- }) => tool({
778
- type: "provider-defined",
779
- id,
780
- name,
781
- args,
782
- inputSchema,
783
- outputSchema,
784
- execute,
785
- needsApproval,
786
- toModelOutput,
787
- onInputStart,
788
- onInputDelta,
789
- onInputAvailable
790
- });
791
- }
792
- function createProviderDefinedToolFactoryWithOutputSchema({
793
- id,
794
- name,
795
- inputSchema,
796
- outputSchema
797
- }) {
798
- return ({
799
- execute,
800
- needsApproval,
801
- toModelOutput,
802
- onInputStart,
803
- onInputDelta,
804
- onInputAvailable,
805
- ...args
806
- }) => tool({
807
- type: "provider-defined",
808
- id,
809
- name,
810
- args,
811
- inputSchema,
812
- outputSchema,
813
- execute,
814
- needsApproval,
815
- toModelOutput,
816
- onInputStart,
817
- onInputDelta,
818
- onInputAvailable
819
712
  });
713
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
820
714
  }
821
715
 
822
- // src/resolve.ts
823
- async function resolve(value) {
824
- if (typeof value === "function") {
825
- value = value();
716
+ // src/to-json-schema/zod3-to-json-schema/parsers/literal.ts
717
+ function parseLiteralDef(def) {
718
+ const parsedType = typeof def.value;
719
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
720
+ return {
721
+ type: Array.isArray(def.value) ? "array" : "object"
722
+ };
826
723
  }
827
- return Promise.resolve(value);
724
+ return {
725
+ type: parsedType === "bigint" ? "integer" : parsedType,
726
+ const: def.value
727
+ };
828
728
  }
829
729
 
830
- // src/response-handler.ts
831
- import { APICallError as APICallError4, EmptyResponseBodyError } from "@ai-sdk/provider";
832
- var createJsonErrorResponseHandler = ({
833
- errorSchema,
834
- errorToMessage,
835
- isRetryable
836
- }) => async ({ response, url, requestBodyValues }) => {
837
- const responseBody = await response.text();
838
- const responseHeaders = extractResponseHeaders(response);
839
- if (responseBody.trim() === "") {
840
- return {
841
- responseHeaders,
842
- value: new APICallError4({
843
- message: response.statusText,
844
- url,
845
- requestBodyValues,
846
- statusCode: response.status,
847
- responseHeaders,
848
- responseBody,
849
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
850
- })
851
- };
852
- }
853
- try {
854
- const parsedError = await parseJSON({
855
- text: responseBody,
856
- schema: errorSchema
857
- });
858
- return {
859
- responseHeaders,
860
- value: new APICallError4({
861
- message: errorToMessage(parsedError),
862
- url,
863
- requestBodyValues,
864
- statusCode: response.status,
865
- responseHeaders,
866
- responseBody,
867
- data: parsedError,
868
- isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
869
- })
870
- };
871
- } catch (parseError) {
872
- return {
873
- responseHeaders,
874
- value: new APICallError4({
875
- message: response.statusText,
876
- url,
877
- requestBodyValues,
878
- statusCode: response.status,
879
- responseHeaders,
880
- responseBody,
881
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
882
- })
883
- };
884
- }
885
- };
886
- var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
887
- const responseHeaders = extractResponseHeaders(response);
888
- if (response.body == null) {
889
- throw new EmptyResponseBodyError({});
890
- }
891
- return {
892
- responseHeaders,
893
- value: parseJsonEventStream({
894
- stream: response.body,
895
- schema: chunkSchema
896
- })
897
- };
898
- };
899
- var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
900
- const responseHeaders = extractResponseHeaders(response);
901
- if (response.body == null) {
902
- throw new EmptyResponseBodyError({});
903
- }
904
- let buffer = "";
905
- return {
906
- responseHeaders,
907
- value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(
908
- new TransformStream({
909
- async transform(chunkText, controller) {
910
- if (chunkText.endsWith("\n")) {
911
- controller.enqueue(
912
- await safeParseJSON({
913
- text: buffer + chunkText,
914
- schema: chunkSchema
915
- })
916
- );
917
- buffer = "";
918
- } else {
919
- buffer += chunkText;
920
- }
921
- }
922
- })
923
- )
924
- };
925
- };
926
- var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
927
- const responseBody = await response.text();
928
- const parsedResult = await safeParseJSON({
929
- text: responseBody,
930
- schema: responseSchema
931
- });
932
- const responseHeaders = extractResponseHeaders(response);
933
- if (!parsedResult.success) {
934
- throw new APICallError4({
935
- message: "Invalid JSON response",
936
- cause: parsedResult.error,
937
- statusCode: response.status,
938
- responseHeaders,
939
- responseBody,
940
- url,
941
- requestBodyValues
942
- });
943
- }
944
- return {
945
- responseHeaders,
946
- value: parsedResult.value,
947
- rawValue: parsedResult.rawValue
948
- };
949
- };
950
- var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
951
- const responseHeaders = extractResponseHeaders(response);
952
- if (!response.body) {
953
- throw new APICallError4({
954
- message: "Response body is empty",
955
- url,
956
- requestBodyValues,
957
- statusCode: response.status,
958
- responseHeaders,
959
- responseBody: void 0
960
- });
961
- }
962
- try {
963
- const buffer = await response.arrayBuffer();
964
- return {
965
- responseHeaders,
966
- value: new Uint8Array(buffer)
967
- };
968
- } catch (error) {
969
- throw new APICallError4({
970
- message: "Failed to read response as array buffer",
971
- url,
972
- requestBodyValues,
973
- statusCode: response.status,
974
- responseHeaders,
975
- responseBody: void 0,
976
- cause: error
977
- });
978
- }
979
- };
980
- var createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {
981
- const responseHeaders = extractResponseHeaders(response);
982
- const responseBody = await response.text();
983
- return {
984
- responseHeaders,
985
- value: new APICallError4({
986
- message: response.statusText,
987
- url,
988
- requestBodyValues,
989
- statusCode: response.status,
990
- responseHeaders,
991
- responseBody
992
- })
993
- };
994
- };
995
-
996
- // src/schema.ts
997
- import { TypeValidationError as TypeValidationError4 } from "@ai-sdk/provider";
998
- import * as z4 from "zod/v4";
999
-
1000
- // src/to-json-schema/arktype-to-json-schema.ts
1001
- var arktypeToJsonSchema = async (schema) => {
1002
- return schema.toJsonSchema();
1003
- };
1004
-
1005
- // src/to-json-schema/effect-to-json-schema.ts
1006
- var effectToJsonSchema = async (schema) => {
1007
- try {
1008
- const { JSONSchema } = await import("effect");
1009
- return JSONSchema.make(schema);
1010
- } catch (e) {
1011
- throw new Error(`Failed to import module 'effect'`);
1012
- }
1013
- };
1014
-
1015
- // src/to-json-schema/valibot-to-json-schema.ts
1016
- var valibotToJsonSchema = async (schema) => {
1017
- try {
1018
- const { toJsonSchema } = await import("@valibot/to-json-schema");
1019
- return toJsonSchema(schema);
1020
- } catch (e) {
1021
- throw new Error(`Failed to import module '@valibot/to-json-schema'`);
1022
- }
1023
- };
1024
-
1025
- // src/zod-to-json-schema/get-relative-path.ts
1026
- var getRelativePath = (pathA, pathB) => {
1027
- let i = 0;
1028
- for (; i < pathA.length && i < pathB.length; i++) {
1029
- if (pathA[i] !== pathB[i]) break;
1030
- }
1031
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1032
- };
730
+ // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
731
+ import {
732
+ ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
733
+ } from "zod/v3";
1033
734
 
1034
- // src/zod-to-json-schema/options.ts
1035
- var ignoreOverride = Symbol(
1036
- "Let zodToJsonSchema decide on which parser to use"
1037
- );
1038
- var defaultOptions = {
1039
- name: void 0,
1040
- $refStrategy: "root",
1041
- basePath: ["#"],
1042
- effectStrategy: "input",
1043
- pipeStrategy: "all",
1044
- dateStrategy: "format:date-time",
1045
- mapStrategy: "entries",
1046
- removeAdditionalStrategy: "passthrough",
1047
- allowedAdditionalProperties: true,
1048
- rejectedAdditionalProperties: false,
1049
- definitionPath: "definitions",
1050
- strictUnions: false,
1051
- definitions: {},
1052
- errorMessages: false,
1053
- patternStrategy: "escape",
1054
- applyRegexFlags: false,
1055
- emailStrategy: "format:email",
1056
- base64Strategy: "contentEncoding:base64",
1057
- nameStrategy: "ref"
1058
- };
1059
- var getDefaultOptions = (options) => typeof options === "string" ? {
1060
- ...defaultOptions,
1061
- name: options
1062
- } : {
1063
- ...defaultOptions,
1064
- ...options
735
+ // src/to-json-schema/zod3-to-json-schema/parsers/string.ts
736
+ var emojiRegex = void 0;
737
+ var zodPatterns = {
738
+ /**
739
+ * `c` was changed to `[cC]` to replicate /i flag
740
+ */
741
+ cuid: /^[cC][^\s-]{8,}$/,
742
+ cuid2: /^[0-9a-z]+$/,
743
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
744
+ /**
745
+ * `a-z` was added to replicate /i flag
746
+ */
747
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
748
+ /**
749
+ * Constructed a valid Unicode RegExp
750
+ *
751
+ * Lazily instantiate since this type of regex isn't supported
752
+ * in all envs (e.g. React Native).
753
+ *
754
+ * See:
755
+ * https://github.com/colinhacks/zod/issues/2433
756
+ * Fix in Zod:
757
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
758
+ */
759
+ emoji: () => {
760
+ if (emojiRegex === void 0) {
761
+ emojiRegex = RegExp(
762
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
763
+ "u"
764
+ );
765
+ }
766
+ return emojiRegex;
767
+ },
768
+ /**
769
+ * Unused
770
+ */
771
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
772
+ /**
773
+ * Unused
774
+ */
775
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
776
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
777
+ /**
778
+ * Unused
779
+ */
780
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
781
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
782
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
783
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
784
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
785
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1065
786
  };
1066
-
1067
- // src/zod-to-json-schema/select-parser.ts
1068
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
1069
-
1070
- // src/zod-to-json-schema/parsers/any.ts
1071
- function parseAnyDef() {
1072
- return {};
1073
- }
1074
-
1075
- // src/zod-to-json-schema/parsers/array.ts
1076
- import { ZodFirstPartyTypeKind } from "zod/v3";
1077
- function parseArrayDef(def, refs) {
1078
- var _a, _b, _c;
1079
- const res = {
1080
- type: "array"
1081
- };
1082
- if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
1083
- res.items = parseDef(def.type._def, {
1084
- ...refs,
1085
- currentPath: [...refs.currentPath, "items"]
1086
- });
1087
- }
1088
- if (def.minLength) {
1089
- res.minItems = def.minLength.value;
1090
- }
1091
- if (def.maxLength) {
1092
- res.maxItems = def.maxLength.value;
1093
- }
1094
- if (def.exactLength) {
1095
- res.minItems = def.exactLength.value;
1096
- res.maxItems = def.exactLength.value;
1097
- }
1098
- return res;
1099
- }
1100
-
1101
- // src/zod-to-json-schema/parsers/bigint.ts
1102
- function parseBigintDef(def) {
787
+ function parseStringDef(def, refs) {
1103
788
  const res = {
1104
- type: "integer",
1105
- format: "int64"
789
+ type: "string"
1106
790
  };
1107
- if (!def.checks) return res;
1108
- for (const check of def.checks) {
1109
- switch (check.kind) {
1110
- case "min":
1111
- if (check.inclusive) {
1112
- res.minimum = check.value;
1113
- } else {
1114
- res.exclusiveMinimum = check.value;
791
+ if (def.checks) {
792
+ for (const check of def.checks) {
793
+ switch (check.kind) {
794
+ case "min":
795
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
796
+ break;
797
+ case "max":
798
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
799
+ break;
800
+ case "email":
801
+ switch (refs.emailStrategy) {
802
+ case "format:email":
803
+ addFormat(res, "email", check.message, refs);
804
+ break;
805
+ case "format:idn-email":
806
+ addFormat(res, "idn-email", check.message, refs);
807
+ break;
808
+ case "pattern:zod":
809
+ addPattern(res, zodPatterns.email, check.message, refs);
810
+ break;
811
+ }
812
+ break;
813
+ case "url":
814
+ addFormat(res, "uri", check.message, refs);
815
+ break;
816
+ case "uuid":
817
+ addFormat(res, "uuid", check.message, refs);
818
+ break;
819
+ case "regex":
820
+ addPattern(res, check.regex, check.message, refs);
821
+ break;
822
+ case "cuid":
823
+ addPattern(res, zodPatterns.cuid, check.message, refs);
824
+ break;
825
+ case "cuid2":
826
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
827
+ break;
828
+ case "startsWith":
829
+ addPattern(
830
+ res,
831
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
832
+ check.message,
833
+ refs
834
+ );
835
+ break;
836
+ case "endsWith":
837
+ addPattern(
838
+ res,
839
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
840
+ check.message,
841
+ refs
842
+ );
843
+ break;
844
+ case "datetime":
845
+ addFormat(res, "date-time", check.message, refs);
846
+ break;
847
+ case "date":
848
+ addFormat(res, "date", check.message, refs);
849
+ break;
850
+ case "time":
851
+ addFormat(res, "time", check.message, refs);
852
+ break;
853
+ case "duration":
854
+ addFormat(res, "duration", check.message, refs);
855
+ break;
856
+ case "length":
857
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
858
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
859
+ break;
860
+ case "includes": {
861
+ addPattern(
862
+ res,
863
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
864
+ check.message,
865
+ refs
866
+ );
867
+ break;
1115
868
  }
1116
- break;
1117
- case "max":
1118
- if (check.inclusive) {
1119
- res.maximum = check.value;
1120
- } else {
1121
- res.exclusiveMaximum = check.value;
869
+ case "ip": {
870
+ if (check.version !== "v6") {
871
+ addFormat(res, "ipv4", check.message, refs);
872
+ }
873
+ if (check.version !== "v4") {
874
+ addFormat(res, "ipv6", check.message, refs);
875
+ }
876
+ break;
877
+ }
878
+ case "base64url":
879
+ addPattern(res, zodPatterns.base64url, check.message, refs);
880
+ break;
881
+ case "jwt":
882
+ addPattern(res, zodPatterns.jwt, check.message, refs);
883
+ break;
884
+ case "cidr": {
885
+ if (check.version !== "v6") {
886
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
887
+ }
888
+ if (check.version !== "v4") {
889
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
890
+ }
891
+ break;
892
+ }
893
+ case "emoji":
894
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
895
+ break;
896
+ case "ulid": {
897
+ addPattern(res, zodPatterns.ulid, check.message, refs);
898
+ break;
899
+ }
900
+ case "base64": {
901
+ switch (refs.base64Strategy) {
902
+ case "format:binary": {
903
+ addFormat(res, "binary", check.message, refs);
904
+ break;
905
+ }
906
+ case "contentEncoding:base64": {
907
+ res.contentEncoding = "base64";
908
+ break;
909
+ }
910
+ case "pattern:zod": {
911
+ addPattern(res, zodPatterns.base64, check.message, refs);
912
+ break;
913
+ }
914
+ }
915
+ break;
916
+ }
917
+ case "nanoid": {
918
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1122
919
  }
1123
- break;
1124
- case "multipleOf":
1125
- res.multipleOf = check.value;
1126
- break;
920
+ case "toLowerCase":
921
+ case "toUpperCase":
922
+ case "trim":
923
+ break;
924
+ default:
925
+ /* @__PURE__ */ ((_) => {
926
+ })(check);
927
+ }
1127
928
  }
1128
929
  }
1129
930
  return res;
1130
931
  }
1131
-
1132
- // src/zod-to-json-schema/parsers/boolean.ts
1133
- function parseBooleanDef() {
1134
- return { type: "boolean" };
932
+ function escapeLiteralCheckValue(literal, refs) {
933
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1135
934
  }
1136
-
1137
- // src/zod-to-json-schema/parsers/branded.ts
1138
- function parseBrandedDef(_def, refs) {
1139
- return parseDef(_def.type._def, refs);
935
+ var ALPHA_NUMERIC = new Set(
936
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
937
+ );
938
+ function escapeNonAlphaNumeric(source) {
939
+ let result = "";
940
+ for (let i = 0; i < source.length; i++) {
941
+ if (!ALPHA_NUMERIC.has(source[i])) {
942
+ result += "\\";
943
+ }
944
+ result += source[i];
945
+ }
946
+ return result;
1140
947
  }
1141
-
1142
- // src/zod-to-json-schema/parsers/catch.ts
1143
- var parseCatchDef = (def, refs) => {
1144
- return parseDef(def.innerType._def, refs);
1145
- };
1146
-
1147
- // src/zod-to-json-schema/parsers/date.ts
1148
- function parseDateDef(def, refs, overrideDateStrategy) {
1149
- const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
1150
- if (Array.isArray(strategy)) {
1151
- return {
1152
- anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
1153
- };
948
+ function addFormat(schema, value, message, refs) {
949
+ var _a;
950
+ if (schema.format || ((_a = schema.anyOf) == null ? void 0 : _a.some((x) => x.format))) {
951
+ if (!schema.anyOf) {
952
+ schema.anyOf = [];
953
+ }
954
+ if (schema.format) {
955
+ schema.anyOf.push({
956
+ format: schema.format
957
+ });
958
+ delete schema.format;
959
+ }
960
+ schema.anyOf.push({
961
+ format: value,
962
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
963
+ });
964
+ } else {
965
+ schema.format = value;
1154
966
  }
1155
- switch (strategy) {
1156
- case "string":
1157
- case "format:date-time":
1158
- return {
1159
- type: "string",
1160
- format: "date-time"
1161
- };
1162
- case "format:date":
1163
- return {
1164
- type: "string",
1165
- format: "date"
1166
- };
1167
- case "integer":
1168
- return integerDateParser(def);
967
+ }
968
+ function addPattern(schema, regex, message, refs) {
969
+ var _a;
970
+ if (schema.pattern || ((_a = schema.allOf) == null ? void 0 : _a.some((x) => x.pattern))) {
971
+ if (!schema.allOf) {
972
+ schema.allOf = [];
973
+ }
974
+ if (schema.pattern) {
975
+ schema.allOf.push({
976
+ pattern: schema.pattern
977
+ });
978
+ delete schema.pattern;
979
+ }
980
+ schema.allOf.push({
981
+ pattern: stringifyRegExpWithFlags(regex, refs),
982
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
983
+ });
984
+ } else {
985
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1169
986
  }
1170
987
  }
1171
- var integerDateParser = (def) => {
1172
- const res = {
1173
- type: "integer",
1174
- format: "unix-time"
988
+ function stringifyRegExpWithFlags(regex, refs) {
989
+ var _a;
990
+ if (!refs.applyRegexFlags || !regex.flags) {
991
+ return regex.source;
992
+ }
993
+ const flags = {
994
+ i: regex.flags.includes("i"),
995
+ // Case-insensitive
996
+ m: regex.flags.includes("m"),
997
+ // `^` and `$` matches adjacent to newline characters
998
+ s: regex.flags.includes("s")
999
+ // `.` matches newlines
1175
1000
  };
1176
- for (const check of def.checks) {
1177
- switch (check.kind) {
1178
- case "min":
1179
- res.minimum = check.value;
1180
- break;
1181
- case "max":
1182
- res.maximum = check.value;
1183
- break;
1001
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1002
+ let pattern = "";
1003
+ let isEscaped = false;
1004
+ let inCharGroup = false;
1005
+ let inCharRange = false;
1006
+ for (let i = 0; i < source.length; i++) {
1007
+ if (isEscaped) {
1008
+ pattern += source[i];
1009
+ isEscaped = false;
1010
+ continue;
1011
+ }
1012
+ if (flags.i) {
1013
+ if (inCharGroup) {
1014
+ if (source[i].match(/[a-z]/)) {
1015
+ if (inCharRange) {
1016
+ pattern += source[i];
1017
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1018
+ inCharRange = false;
1019
+ } else if (source[i + 1] === "-" && ((_a = source[i + 2]) == null ? void 0 : _a.match(/[a-z]/))) {
1020
+ pattern += source[i];
1021
+ inCharRange = true;
1022
+ } else {
1023
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1024
+ }
1025
+ continue;
1026
+ }
1027
+ } else if (source[i].match(/[a-z]/)) {
1028
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1029
+ continue;
1030
+ }
1031
+ }
1032
+ if (flags.m) {
1033
+ if (source[i] === "^") {
1034
+ pattern += `(^|(?<=[\r
1035
+ ]))`;
1036
+ continue;
1037
+ } else if (source[i] === "$") {
1038
+ pattern += `($|(?=[\r
1039
+ ]))`;
1040
+ continue;
1041
+ }
1042
+ }
1043
+ if (flags.s && source[i] === ".") {
1044
+ pattern += inCharGroup ? `${source[i]}\r
1045
+ ` : `[${source[i]}\r
1046
+ ]`;
1047
+ continue;
1048
+ }
1049
+ pattern += source[i];
1050
+ if (source[i] === "\\") {
1051
+ isEscaped = true;
1052
+ } else if (inCharGroup && source[i] === "]") {
1053
+ inCharGroup = false;
1054
+ } else if (!inCharGroup && source[i] === "[") {
1055
+ inCharGroup = true;
1184
1056
  }
1185
1057
  }
1186
- return res;
1187
- };
1058
+ try {
1059
+ new RegExp(pattern);
1060
+ } catch (e) {
1061
+ console.warn(
1062
+ `Could not convert regex pattern at ${refs.currentPath.join(
1063
+ "/"
1064
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1065
+ );
1066
+ return regex.source;
1067
+ }
1068
+ return pattern;
1069
+ }
1188
1070
 
1189
- // src/zod-to-json-schema/parsers/default.ts
1190
- function parseDefaultDef(_def, refs) {
1191
- return {
1192
- ...parseDef(_def.innerType._def, refs),
1193
- default: _def.defaultValue()
1071
+ // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
1072
+ function parseRecordDef(def, refs) {
1073
+ var _a, _b, _c, _d, _e, _f;
1074
+ const schema = {
1075
+ type: "object",
1076
+ additionalProperties: (_a = parseDef(def.valueType._def, {
1077
+ ...refs,
1078
+ currentPath: [...refs.currentPath, "additionalProperties"]
1079
+ })) != null ? _a : refs.allowedAdditionalProperties
1194
1080
  };
1081
+ if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1082
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1083
+ return {
1084
+ ...schema,
1085
+ propertyNames: keyType
1086
+ };
1087
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1088
+ return {
1089
+ ...schema,
1090
+ propertyNames: {
1091
+ enum: def.keyType._def.values
1092
+ }
1093
+ };
1094
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1095
+ const { type, ...keyType } = parseBrandedDef(
1096
+ def.keyType._def,
1097
+ refs
1098
+ );
1099
+ return {
1100
+ ...schema,
1101
+ propertyNames: keyType
1102
+ };
1103
+ }
1104
+ return schema;
1195
1105
  }
1196
1106
 
1197
- // src/zod-to-json-schema/parsers/effects.ts
1198
- function parseEffectsDef(_def, refs) {
1199
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
1107
+ // src/to-json-schema/zod3-to-json-schema/parsers/map.ts
1108
+ function parseMapDef(def, refs) {
1109
+ if (refs.mapStrategy === "record") {
1110
+ return parseRecordDef(def, refs);
1111
+ }
1112
+ const keys = parseDef(def.keyType._def, {
1113
+ ...refs,
1114
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1115
+ }) || parseAnyDef();
1116
+ const values = parseDef(def.valueType._def, {
1117
+ ...refs,
1118
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1119
+ }) || parseAnyDef();
1120
+ return {
1121
+ type: "array",
1122
+ maxItems: 125,
1123
+ items: {
1124
+ type: "array",
1125
+ items: [keys, values],
1126
+ minItems: 2,
1127
+ maxItems: 2
1128
+ }
1129
+ };
1200
1130
  }
1201
1131
 
1202
- // src/zod-to-json-schema/parsers/enum.ts
1203
- function parseEnumDef(def) {
1132
+ // src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts
1133
+ function parseNativeEnumDef(def) {
1134
+ const object = def.values;
1135
+ const actualKeys = Object.keys(def.values).filter((key) => {
1136
+ return typeof object[object[key]] !== "number";
1137
+ });
1138
+ const actualValues = actualKeys.map((key) => object[key]);
1139
+ const parsedTypes = Array.from(
1140
+ new Set(actualValues.map((values) => typeof values))
1141
+ );
1204
1142
  return {
1205
- type: "string",
1206
- enum: Array.from(def.values)
1143
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1144
+ enum: actualValues
1207
1145
  };
1208
1146
  }
1209
1147
 
1210
- // src/zod-to-json-schema/parsers/intersection.ts
1211
- var isJsonSchema7AllOfType = (type) => {
1212
- if ("type" in type && type.type === "string") return false;
1213
- return "allOf" in type;
1214
- };
1215
- function parseIntersectionDef(def, refs) {
1216
- const allOf = [
1217
- parseDef(def.left._def, {
1218
- ...refs,
1219
- currentPath: [...refs.currentPath, "allOf", "0"]
1220
- }),
1221
- parseDef(def.right._def, {
1222
- ...refs,
1223
- currentPath: [...refs.currentPath, "allOf", "1"]
1224
- })
1225
- ].filter((x) => !!x);
1226
- const mergedAllOf = [];
1227
- allOf.forEach((schema) => {
1228
- if (isJsonSchema7AllOfType(schema)) {
1229
- mergedAllOf.push(...schema.allOf);
1230
- } else {
1231
- let nestedSchema = schema;
1232
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
1233
- const { additionalProperties, ...rest } = schema;
1234
- nestedSchema = rest;
1235
- }
1236
- mergedAllOf.push(nestedSchema);
1237
- }
1238
- });
1239
- return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
1148
+ // src/to-json-schema/zod3-to-json-schema/parsers/never.ts
1149
+ function parseNeverDef() {
1150
+ return { not: parseAnyDef() };
1240
1151
  }
1241
1152
 
1242
- // src/zod-to-json-schema/parsers/literal.ts
1243
- function parseLiteralDef(def) {
1244
- const parsedType = typeof def.value;
1245
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1246
- return {
1247
- type: Array.isArray(def.value) ? "array" : "object"
1248
- };
1249
- }
1153
+ // src/to-json-schema/zod3-to-json-schema/parsers/null.ts
1154
+ function parseNullDef() {
1250
1155
  return {
1251
- type: parsedType === "bigint" ? "integer" : parsedType,
1252
- const: def.value
1156
+ type: "null"
1253
1157
  };
1254
1158
  }
1255
1159
 
1256
- // src/zod-to-json-schema/parsers/record.ts
1257
- import {
1258
- ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
1259
- } from "zod/v3";
1260
-
1261
- // src/zod-to-json-schema/parsers/string.ts
1262
- var emojiRegex = void 0;
1263
- var zodPatterns = {
1264
- /**
1265
- * `c` was changed to `[cC]` to replicate /i flag
1266
- */
1267
- cuid: /^[cC][^\s-]{8,}$/,
1268
- cuid2: /^[0-9a-z]+$/,
1269
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1270
- /**
1271
- * `a-z` was added to replicate /i flag
1272
- */
1273
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1274
- /**
1275
- * Constructed a valid Unicode RegExp
1276
- *
1277
- * Lazily instantiate since this type of regex isn't supported
1278
- * in all envs (e.g. React Native).
1279
- *
1280
- * See:
1281
- * https://github.com/colinhacks/zod/issues/2433
1282
- * Fix in Zod:
1283
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1284
- */
1285
- emoji: () => {
1286
- if (emojiRegex === void 0) {
1287
- emojiRegex = RegExp(
1288
- "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
1289
- "u"
1290
- );
1291
- }
1292
- return emojiRegex;
1293
- },
1294
- /**
1295
- * Unused
1296
- */
1297
- uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
1298
- /**
1299
- * Unused
1300
- */
1301
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
1302
- ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
1303
- /**
1304
- * Unused
1305
- */
1306
- ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
1307
- ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
1308
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1309
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1310
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
1311
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1160
+ // src/to-json-schema/zod3-to-json-schema/parsers/union.ts
1161
+ var primitiveMappings = {
1162
+ ZodString: "string",
1163
+ ZodNumber: "number",
1164
+ ZodBigInt: "integer",
1165
+ ZodBoolean: "boolean",
1166
+ ZodNull: "null"
1312
1167
  };
1313
- function parseStringDef(def, refs) {
1314
- const res = {
1315
- type: "string"
1316
- };
1317
- if (def.checks) {
1318
- for (const check of def.checks) {
1319
- switch (check.kind) {
1320
- case "min":
1321
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1322
- break;
1323
- case "max":
1324
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1325
- break;
1326
- case "email":
1327
- switch (refs.emailStrategy) {
1328
- case "format:email":
1329
- addFormat(res, "email", check.message, refs);
1330
- break;
1331
- case "format:idn-email":
1332
- addFormat(res, "idn-email", check.message, refs);
1333
- break;
1334
- case "pattern:zod":
1335
- addPattern(res, zodPatterns.email, check.message, refs);
1336
- break;
1337
- }
1338
- break;
1339
- case "url":
1340
- addFormat(res, "uri", check.message, refs);
1341
- break;
1342
- case "uuid":
1343
- addFormat(res, "uuid", check.message, refs);
1344
- break;
1345
- case "regex":
1346
- addPattern(res, check.regex, check.message, refs);
1347
- break;
1348
- case "cuid":
1349
- addPattern(res, zodPatterns.cuid, check.message, refs);
1350
- break;
1351
- case "cuid2":
1352
- addPattern(res, zodPatterns.cuid2, check.message, refs);
1353
- break;
1354
- case "startsWith":
1355
- addPattern(
1356
- res,
1357
- RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1358
- check.message,
1359
- refs
1360
- );
1361
- break;
1362
- case "endsWith":
1363
- addPattern(
1364
- res,
1365
- RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1366
- check.message,
1367
- refs
1368
- );
1369
- break;
1370
- case "datetime":
1371
- addFormat(res, "date-time", check.message, refs);
1372
- break;
1373
- case "date":
1374
- addFormat(res, "date", check.message, refs);
1375
- break;
1376
- case "time":
1377
- addFormat(res, "time", check.message, refs);
1378
- break;
1379
- case "duration":
1380
- addFormat(res, "duration", check.message, refs);
1381
- break;
1382
- case "length":
1383
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1384
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1385
- break;
1386
- case "includes": {
1387
- addPattern(
1388
- res,
1389
- RegExp(escapeLiteralCheckValue(check.value, refs)),
1390
- check.message,
1391
- refs
1392
- );
1393
- break;
1394
- }
1395
- case "ip": {
1396
- if (check.version !== "v6") {
1397
- addFormat(res, "ipv4", check.message, refs);
1398
- }
1399
- if (check.version !== "v4") {
1400
- addFormat(res, "ipv6", check.message, refs);
1401
- }
1402
- break;
1403
- }
1404
- case "base64url":
1405
- addPattern(res, zodPatterns.base64url, check.message, refs);
1406
- break;
1407
- case "jwt":
1408
- addPattern(res, zodPatterns.jwt, check.message, refs);
1409
- break;
1410
- case "cidr": {
1411
- if (check.version !== "v6") {
1412
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1413
- }
1414
- if (check.version !== "v4") {
1415
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1416
- }
1417
- break;
1418
- }
1419
- case "emoji":
1420
- addPattern(res, zodPatterns.emoji(), check.message, refs);
1421
- break;
1422
- case "ulid": {
1423
- addPattern(res, zodPatterns.ulid, check.message, refs);
1424
- break;
1425
- }
1426
- case "base64": {
1427
- switch (refs.base64Strategy) {
1428
- case "format:binary": {
1429
- addFormat(res, "binary", check.message, refs);
1430
- break;
1431
- }
1432
- case "contentEncoding:base64": {
1433
- res.contentEncoding = "base64";
1434
- break;
1435
- }
1436
- case "pattern:zod": {
1437
- addPattern(res, zodPatterns.base64, check.message, refs);
1438
- break;
1439
- }
1440
- }
1441
- break;
1442
- }
1443
- case "nanoid": {
1444
- addPattern(res, zodPatterns.nanoid, check.message, refs);
1168
+ function parseUnionDef(def, refs) {
1169
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1170
+ if (options.every(
1171
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1172
+ )) {
1173
+ const types = options.reduce((types2, x) => {
1174
+ const type = primitiveMappings[x._def.typeName];
1175
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1176
+ }, []);
1177
+ return {
1178
+ type: types.length > 1 ? types : types[0]
1179
+ };
1180
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1181
+ const types = options.reduce(
1182
+ (acc, x) => {
1183
+ const type = typeof x._def.value;
1184
+ switch (type) {
1185
+ case "string":
1186
+ case "number":
1187
+ case "boolean":
1188
+ return [...acc, type];
1189
+ case "bigint":
1190
+ return [...acc, "integer"];
1191
+ case "object":
1192
+ if (x._def.value === null) return [...acc, "null"];
1193
+ case "symbol":
1194
+ case "undefined":
1195
+ case "function":
1196
+ default:
1197
+ return acc;
1445
1198
  }
1446
- case "toLowerCase":
1447
- case "toUpperCase":
1448
- case "trim":
1449
- break;
1450
- default:
1451
- /* @__PURE__ */ ((_) => {
1452
- })(check);
1453
- }
1199
+ },
1200
+ []
1201
+ );
1202
+ if (types.length === options.length) {
1203
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1204
+ return {
1205
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1206
+ enum: options.reduce(
1207
+ (acc, x) => {
1208
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1209
+ },
1210
+ []
1211
+ )
1212
+ };
1454
1213
  }
1214
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1215
+ return {
1216
+ type: "string",
1217
+ enum: options.reduce(
1218
+ (acc, x) => [
1219
+ ...acc,
1220
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1221
+ ],
1222
+ []
1223
+ )
1224
+ };
1455
1225
  }
1456
- return res;
1226
+ return asAnyOf(def, refs);
1457
1227
  }
1458
- function escapeLiteralCheckValue(literal, refs) {
1459
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1228
+ var asAnyOf = (def, refs) => {
1229
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1230
+ (x, i) => parseDef(x._def, {
1231
+ ...refs,
1232
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1233
+ })
1234
+ ).filter(
1235
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1236
+ );
1237
+ return anyOf.length ? { anyOf } : void 0;
1238
+ };
1239
+
1240
+ // src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts
1241
+ function parseNullableDef(def, refs) {
1242
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1243
+ def.innerType._def.typeName
1244
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1245
+ return {
1246
+ type: [
1247
+ primitiveMappings[def.innerType._def.typeName],
1248
+ "null"
1249
+ ]
1250
+ };
1251
+ }
1252
+ const base = parseDef(def.innerType._def, {
1253
+ ...refs,
1254
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1255
+ });
1256
+ return base && { anyOf: [base, { type: "null" }] };
1460
1257
  }
1461
- var ALPHA_NUMERIC = new Set(
1462
- "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1463
- );
1464
- function escapeNonAlphaNumeric(source) {
1465
- let result = "";
1466
- for (let i = 0; i < source.length; i++) {
1467
- if (!ALPHA_NUMERIC.has(source[i])) {
1468
- result += "\\";
1258
+
1259
+ // src/to-json-schema/zod3-to-json-schema/parsers/number.ts
1260
+ function parseNumberDef(def) {
1261
+ const res = {
1262
+ type: "number"
1263
+ };
1264
+ if (!def.checks) return res;
1265
+ for (const check of def.checks) {
1266
+ switch (check.kind) {
1267
+ case "int":
1268
+ res.type = "integer";
1269
+ break;
1270
+ case "min":
1271
+ if (check.inclusive) {
1272
+ res.minimum = check.value;
1273
+ } else {
1274
+ res.exclusiveMinimum = check.value;
1275
+ }
1276
+ break;
1277
+ case "max":
1278
+ if (check.inclusive) {
1279
+ res.maximum = check.value;
1280
+ } else {
1281
+ res.exclusiveMaximum = check.value;
1282
+ }
1283
+ break;
1284
+ case "multipleOf":
1285
+ res.multipleOf = check.value;
1286
+ break;
1469
1287
  }
1470
- result += source[i];
1471
1288
  }
1472
- return result;
1289
+ return res;
1473
1290
  }
1474
- function addFormat(schema, value, message, refs) {
1475
- var _a;
1476
- if (schema.format || ((_a = schema.anyOf) == null ? void 0 : _a.some((x) => x.format))) {
1477
- if (!schema.anyOf) {
1478
- schema.anyOf = [];
1291
+
1292
+ // src/to-json-schema/zod3-to-json-schema/parsers/object.ts
1293
+ function parseObjectDef(def, refs) {
1294
+ const result = {
1295
+ type: "object",
1296
+ properties: {}
1297
+ };
1298
+ const required = [];
1299
+ const shape = def.shape();
1300
+ for (const propName in shape) {
1301
+ let propDef = shape[propName];
1302
+ if (propDef === void 0 || propDef._def === void 0) {
1303
+ continue;
1479
1304
  }
1480
- if (schema.format) {
1481
- schema.anyOf.push({
1482
- format: schema.format
1483
- });
1484
- delete schema.format;
1305
+ const propOptional = safeIsOptional(propDef);
1306
+ const parsedDef = parseDef(propDef._def, {
1307
+ ...refs,
1308
+ currentPath: [...refs.currentPath, "properties", propName],
1309
+ propertyPath: [...refs.currentPath, "properties", propName]
1310
+ });
1311
+ if (parsedDef === void 0) {
1312
+ continue;
1485
1313
  }
1486
- schema.anyOf.push({
1487
- format: value,
1488
- ...message && refs.errorMessages && { errorMessage: { format: message } }
1314
+ result.properties[propName] = parsedDef;
1315
+ if (!propOptional) {
1316
+ required.push(propName);
1317
+ }
1318
+ }
1319
+ if (required.length) {
1320
+ result.required = required;
1321
+ }
1322
+ const additionalProperties = decideAdditionalProperties(def, refs);
1323
+ if (additionalProperties !== void 0) {
1324
+ result.additionalProperties = additionalProperties;
1325
+ }
1326
+ return result;
1327
+ }
1328
+ function decideAdditionalProperties(def, refs) {
1329
+ if (def.catchall._def.typeName !== "ZodNever") {
1330
+ return parseDef(def.catchall._def, {
1331
+ ...refs,
1332
+ currentPath: [...refs.currentPath, "additionalProperties"]
1489
1333
  });
1334
+ }
1335
+ switch (def.unknownKeys) {
1336
+ case "passthrough":
1337
+ return refs.allowedAdditionalProperties;
1338
+ case "strict":
1339
+ return refs.rejectedAdditionalProperties;
1340
+ case "strip":
1341
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1342
+ }
1343
+ }
1344
+ function safeIsOptional(schema) {
1345
+ try {
1346
+ return schema.isOptional();
1347
+ } catch (e) {
1348
+ return true;
1349
+ }
1350
+ }
1351
+
1352
+ // src/to-json-schema/zod3-to-json-schema/parsers/optional.ts
1353
+ var parseOptionalDef = (def, refs) => {
1354
+ var _a;
1355
+ if (refs.currentPath.toString() === ((_a = refs.propertyPath) == null ? void 0 : _a.toString())) {
1356
+ return parseDef(def.innerType._def, refs);
1357
+ }
1358
+ const innerSchema = parseDef(def.innerType._def, {
1359
+ ...refs,
1360
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1361
+ });
1362
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1363
+ };
1364
+
1365
+ // src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts
1366
+ var parsePipelineDef = (def, refs) => {
1367
+ if (refs.pipeStrategy === "input") {
1368
+ return parseDef(def.in._def, refs);
1369
+ } else if (refs.pipeStrategy === "output") {
1370
+ return parseDef(def.out._def, refs);
1371
+ }
1372
+ const a = parseDef(def.in._def, {
1373
+ ...refs,
1374
+ currentPath: [...refs.currentPath, "allOf", "0"]
1375
+ });
1376
+ const b = parseDef(def.out._def, {
1377
+ ...refs,
1378
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1379
+ });
1380
+ return {
1381
+ allOf: [a, b].filter((x) => x !== void 0)
1382
+ };
1383
+ };
1384
+
1385
+ // src/to-json-schema/zod3-to-json-schema/parsers/promise.ts
1386
+ function parsePromiseDef(def, refs) {
1387
+ return parseDef(def.type._def, refs);
1388
+ }
1389
+
1390
+ // src/to-json-schema/zod3-to-json-schema/parsers/set.ts
1391
+ function parseSetDef(def, refs) {
1392
+ const items = parseDef(def.valueType._def, {
1393
+ ...refs,
1394
+ currentPath: [...refs.currentPath, "items"]
1395
+ });
1396
+ const schema = {
1397
+ type: "array",
1398
+ uniqueItems: true,
1399
+ items
1400
+ };
1401
+ if (def.minSize) {
1402
+ schema.minItems = def.minSize.value;
1403
+ }
1404
+ if (def.maxSize) {
1405
+ schema.maxItems = def.maxSize.value;
1406
+ }
1407
+ return schema;
1408
+ }
1409
+
1410
+ // src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts
1411
+ function parseTupleDef(def, refs) {
1412
+ if (def.rest) {
1413
+ return {
1414
+ type: "array",
1415
+ minItems: def.items.length,
1416
+ items: def.items.map(
1417
+ (x, i) => parseDef(x._def, {
1418
+ ...refs,
1419
+ currentPath: [...refs.currentPath, "items", `${i}`]
1420
+ })
1421
+ ).reduce(
1422
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1423
+ []
1424
+ ),
1425
+ additionalItems: parseDef(def.rest._def, {
1426
+ ...refs,
1427
+ currentPath: [...refs.currentPath, "additionalItems"]
1428
+ })
1429
+ };
1490
1430
  } else {
1491
- schema.format = value;
1431
+ return {
1432
+ type: "array",
1433
+ minItems: def.items.length,
1434
+ maxItems: def.items.length,
1435
+ items: def.items.map(
1436
+ (x, i) => parseDef(x._def, {
1437
+ ...refs,
1438
+ currentPath: [...refs.currentPath, "items", `${i}`]
1439
+ })
1440
+ ).reduce(
1441
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1442
+ []
1443
+ )
1444
+ };
1492
1445
  }
1493
1446
  }
1494
- function addPattern(schema, regex, message, refs) {
1447
+
1448
+ // src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts
1449
+ function parseUndefinedDef() {
1450
+ return {
1451
+ not: parseAnyDef()
1452
+ };
1453
+ }
1454
+
1455
+ // src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts
1456
+ function parseUnknownDef() {
1457
+ return parseAnyDef();
1458
+ }
1459
+
1460
+ // src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts
1461
+ var parseReadonlyDef = (def, refs) => {
1462
+ return parseDef(def.innerType._def, refs);
1463
+ };
1464
+
1465
+ // src/to-json-schema/zod3-to-json-schema/select-parser.ts
1466
+ var selectParser = (def, typeName, refs) => {
1467
+ switch (typeName) {
1468
+ case ZodFirstPartyTypeKind3.ZodString:
1469
+ return parseStringDef(def, refs);
1470
+ case ZodFirstPartyTypeKind3.ZodNumber:
1471
+ return parseNumberDef(def);
1472
+ case ZodFirstPartyTypeKind3.ZodObject:
1473
+ return parseObjectDef(def, refs);
1474
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1475
+ return parseBigintDef(def);
1476
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1477
+ return parseBooleanDef();
1478
+ case ZodFirstPartyTypeKind3.ZodDate:
1479
+ return parseDateDef(def, refs);
1480
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1481
+ return parseUndefinedDef();
1482
+ case ZodFirstPartyTypeKind3.ZodNull:
1483
+ return parseNullDef();
1484
+ case ZodFirstPartyTypeKind3.ZodArray:
1485
+ return parseArrayDef(def, refs);
1486
+ case ZodFirstPartyTypeKind3.ZodUnion:
1487
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1488
+ return parseUnionDef(def, refs);
1489
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1490
+ return parseIntersectionDef(def, refs);
1491
+ case ZodFirstPartyTypeKind3.ZodTuple:
1492
+ return parseTupleDef(def, refs);
1493
+ case ZodFirstPartyTypeKind3.ZodRecord:
1494
+ return parseRecordDef(def, refs);
1495
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1496
+ return parseLiteralDef(def);
1497
+ case ZodFirstPartyTypeKind3.ZodEnum:
1498
+ return parseEnumDef(def);
1499
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1500
+ return parseNativeEnumDef(def);
1501
+ case ZodFirstPartyTypeKind3.ZodNullable:
1502
+ return parseNullableDef(def, refs);
1503
+ case ZodFirstPartyTypeKind3.ZodOptional:
1504
+ return parseOptionalDef(def, refs);
1505
+ case ZodFirstPartyTypeKind3.ZodMap:
1506
+ return parseMapDef(def, refs);
1507
+ case ZodFirstPartyTypeKind3.ZodSet:
1508
+ return parseSetDef(def, refs);
1509
+ case ZodFirstPartyTypeKind3.ZodLazy:
1510
+ return () => def.getter()._def;
1511
+ case ZodFirstPartyTypeKind3.ZodPromise:
1512
+ return parsePromiseDef(def, refs);
1513
+ case ZodFirstPartyTypeKind3.ZodNaN:
1514
+ case ZodFirstPartyTypeKind3.ZodNever:
1515
+ return parseNeverDef();
1516
+ case ZodFirstPartyTypeKind3.ZodEffects:
1517
+ return parseEffectsDef(def, refs);
1518
+ case ZodFirstPartyTypeKind3.ZodAny:
1519
+ return parseAnyDef();
1520
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1521
+ return parseUnknownDef();
1522
+ case ZodFirstPartyTypeKind3.ZodDefault:
1523
+ return parseDefaultDef(def, refs);
1524
+ case ZodFirstPartyTypeKind3.ZodBranded:
1525
+ return parseBrandedDef(def, refs);
1526
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1527
+ return parseReadonlyDef(def, refs);
1528
+ case ZodFirstPartyTypeKind3.ZodCatch:
1529
+ return parseCatchDef(def, refs);
1530
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1531
+ return parsePipelineDef(def, refs);
1532
+ case ZodFirstPartyTypeKind3.ZodFunction:
1533
+ case ZodFirstPartyTypeKind3.ZodVoid:
1534
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1535
+ return void 0;
1536
+ default:
1537
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1538
+ }
1539
+ };
1540
+
1541
+ // src/to-json-schema/zod3-to-json-schema/get-relative-path.ts
1542
+ var getRelativePath = (pathA, pathB) => {
1543
+ let i = 0;
1544
+ for (; i < pathA.length && i < pathB.length; i++) {
1545
+ if (pathA[i] !== pathB[i]) break;
1546
+ }
1547
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1548
+ };
1549
+
1550
+ // src/to-json-schema/zod3-to-json-schema/parse-def.ts
1551
+ function parseDef(def, refs, forceResolution = false) {
1495
1552
  var _a;
1496
- if (schema.pattern || ((_a = schema.allOf) == null ? void 0 : _a.some((x) => x.pattern))) {
1497
- if (!schema.allOf) {
1498
- schema.allOf = [];
1553
+ const seenItem = refs.seen.get(def);
1554
+ if (refs.override) {
1555
+ const overrideResult = (_a = refs.override) == null ? void 0 : _a.call(
1556
+ refs,
1557
+ def,
1558
+ refs,
1559
+ seenItem,
1560
+ forceResolution
1561
+ );
1562
+ if (overrideResult !== ignoreOverride) {
1563
+ return overrideResult;
1499
1564
  }
1500
- if (schema.pattern) {
1501
- schema.allOf.push({
1502
- pattern: schema.pattern
1503
- });
1504
- delete schema.pattern;
1565
+ }
1566
+ if (seenItem && !forceResolution) {
1567
+ const seenSchema = get$ref(seenItem, refs);
1568
+ if (seenSchema !== void 0) {
1569
+ return seenSchema;
1505
1570
  }
1506
- schema.allOf.push({
1507
- pattern: stringifyRegExpWithFlags(regex, refs),
1508
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1509
- });
1510
- } else {
1511
- schema.pattern = stringifyRegExpWithFlags(regex, refs);
1512
1571
  }
1513
- }
1514
- function stringifyRegExpWithFlags(regex, refs) {
1515
- var _a;
1516
- if (!refs.applyRegexFlags || !regex.flags) {
1517
- return regex.source;
1572
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1573
+ refs.seen.set(def, newItem);
1574
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1575
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1576
+ if (jsonSchema2) {
1577
+ addMeta(def, refs, jsonSchema2);
1518
1578
  }
1519
- const flags = {
1520
- i: regex.flags.includes("i"),
1521
- // Case-insensitive
1522
- m: regex.flags.includes("m"),
1523
- // `^` and `$` matches adjacent to newline characters
1524
- s: regex.flags.includes("s")
1525
- // `.` matches newlines
1526
- };
1527
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
1528
- let pattern = "";
1529
- let isEscaped = false;
1530
- let inCharGroup = false;
1531
- let inCharRange = false;
1532
- for (let i = 0; i < source.length; i++) {
1533
- if (isEscaped) {
1534
- pattern += source[i];
1535
- isEscaped = false;
1536
- continue;
1537
- }
1538
- if (flags.i) {
1539
- if (inCharGroup) {
1540
- if (source[i].match(/[a-z]/)) {
1541
- if (inCharRange) {
1542
- pattern += source[i];
1543
- pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1544
- inCharRange = false;
1545
- } else if (source[i + 1] === "-" && ((_a = source[i + 2]) == null ? void 0 : _a.match(/[a-z]/))) {
1546
- pattern += source[i];
1547
- inCharRange = true;
1548
- } else {
1549
- pattern += `${source[i]}${source[i].toUpperCase()}`;
1550
- }
1551
- continue;
1552
- }
1553
- } else if (source[i].match(/[a-z]/)) {
1554
- pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1555
- continue;
1556
- }
1557
- }
1558
- if (flags.m) {
1559
- if (source[i] === "^") {
1560
- pattern += `(^|(?<=[\r
1561
- ]))`;
1562
- continue;
1563
- } else if (source[i] === "$") {
1564
- pattern += `($|(?=[\r
1565
- ]))`;
1566
- continue;
1567
- }
1568
- }
1569
- if (flags.s && source[i] === ".") {
1570
- pattern += inCharGroup ? `${source[i]}\r
1571
- ` : `[${source[i]}\r
1572
- ]`;
1573
- continue;
1574
- }
1575
- pattern += source[i];
1576
- if (source[i] === "\\") {
1577
- isEscaped = true;
1578
- } else if (inCharGroup && source[i] === "]") {
1579
- inCharGroup = false;
1580
- } else if (!inCharGroup && source[i] === "[") {
1581
- inCharGroup = true;
1582
- }
1579
+ if (refs.postProcess) {
1580
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1581
+ newItem.jsonSchema = jsonSchema2;
1582
+ return postProcessResult;
1583
1583
  }
1584
- try {
1585
- new RegExp(pattern);
1586
- } catch (e) {
1587
- console.warn(
1588
- `Could not convert regex pattern at ${refs.currentPath.join(
1589
- "/"
1590
- )} to a flag-independent form! Falling back to the flag-ignorant source`
1591
- );
1592
- return regex.source;
1584
+ newItem.jsonSchema = jsonSchema2;
1585
+ return jsonSchema2;
1586
+ }
1587
+ var get$ref = (item, refs) => {
1588
+ switch (refs.$refStrategy) {
1589
+ case "root":
1590
+ return { $ref: item.path.join("/") };
1591
+ case "relative":
1592
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1593
+ case "none":
1594
+ case "seen": {
1595
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1596
+ console.warn(
1597
+ `Recursive reference detected at ${refs.currentPath.join(
1598
+ "/"
1599
+ )}! Defaulting to any`
1600
+ );
1601
+ return parseAnyDef();
1602
+ }
1603
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1604
+ }
1593
1605
  }
1594
- return pattern;
1595
- }
1606
+ };
1607
+ var addMeta = (def, refs, jsonSchema2) => {
1608
+ if (def.description) {
1609
+ jsonSchema2.description = def.description;
1610
+ }
1611
+ return jsonSchema2;
1612
+ };
1596
1613
 
1597
- // src/zod-to-json-schema/parsers/record.ts
1598
- function parseRecordDef(def, refs) {
1599
- var _a, _b, _c, _d, _e, _f;
1600
- const schema = {
1601
- type: "object",
1602
- additionalProperties: (_a = parseDef(def.valueType._def, {
1603
- ...refs,
1604
- currentPath: [...refs.currentPath, "additionalProperties"]
1605
- })) != null ? _a : refs.allowedAdditionalProperties
1614
+ // src/to-json-schema/zod3-to-json-schema/refs.ts
1615
+ var getRefs = (options) => {
1616
+ const _options = getDefaultOptions(options);
1617
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1618
+ return {
1619
+ ..._options,
1620
+ currentPath,
1621
+ propertyPath: void 0,
1622
+ seen: new Map(
1623
+ Object.entries(_options.definitions).map(([name, def]) => [
1624
+ def._def,
1625
+ {
1626
+ def: def._def,
1627
+ path: [..._options.basePath, _options.definitionPath, name],
1628
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1629
+ jsonSchema: void 0
1630
+ }
1631
+ ])
1632
+ )
1606
1633
  };
1607
- if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1608
- const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1609
- return {
1610
- ...schema,
1611
- propertyNames: keyType
1612
- };
1613
- } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1614
- return {
1615
- ...schema,
1616
- propertyNames: {
1617
- enum: def.keyType._def.values
1618
- }
1619
- };
1620
- } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1621
- const { type, ...keyType } = parseBrandedDef(
1622
- def.keyType._def,
1623
- refs
1624
- );
1625
- return {
1626
- ...schema,
1627
- propertyNames: keyType
1628
- };
1629
- }
1630
- return schema;
1631
- }
1634
+ };
1632
1635
 
1633
- // src/zod-to-json-schema/parsers/map.ts
1634
- function parseMapDef(def, refs) {
1635
- if (refs.mapStrategy === "record") {
1636
- return parseRecordDef(def, refs);
1636
+ // src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts
1637
+ var zod3ToJsonSchema = (schema, options) => {
1638
+ var _a;
1639
+ const refs = getRefs(options);
1640
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1641
+ (acc, [name2, schema2]) => {
1642
+ var _a2;
1643
+ return {
1644
+ ...acc,
1645
+ [name2]: (_a2 = parseDef(
1646
+ schema2._def,
1647
+ {
1648
+ ...refs,
1649
+ currentPath: [...refs.basePath, refs.definitionPath, name2]
1650
+ },
1651
+ true
1652
+ )) != null ? _a2 : parseAnyDef()
1653
+ };
1654
+ },
1655
+ {}
1656
+ ) : void 0;
1657
+ const name = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1658
+ const main = (_a = parseDef(
1659
+ schema._def,
1660
+ name === void 0 ? refs : {
1661
+ ...refs,
1662
+ currentPath: [...refs.basePath, refs.definitionPath, name]
1663
+ },
1664
+ false
1665
+ )) != null ? _a : parseAnyDef();
1666
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1667
+ if (title !== void 0) {
1668
+ main.title = title;
1637
1669
  }
1638
- const keys = parseDef(def.keyType._def, {
1639
- ...refs,
1640
- currentPath: [...refs.currentPath, "items", "items", "0"]
1641
- }) || parseAnyDef();
1642
- const values = parseDef(def.valueType._def, {
1643
- ...refs,
1644
- currentPath: [...refs.currentPath, "items", "items", "1"]
1645
- }) || parseAnyDef();
1646
- return {
1647
- type: "array",
1648
- maxItems: 125,
1649
- items: {
1650
- type: "array",
1651
- items: [keys, values],
1652
- minItems: 2,
1653
- maxItems: 2
1670
+ const combined = name === void 0 ? definitions ? {
1671
+ ...main,
1672
+ [refs.definitionPath]: definitions
1673
+ } : main : {
1674
+ $ref: [
1675
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1676
+ refs.definitionPath,
1677
+ name
1678
+ ].join("/"),
1679
+ [refs.definitionPath]: {
1680
+ ...definitions,
1681
+ [name]: main
1654
1682
  }
1655
1683
  };
1656
- }
1684
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1685
+ return combined;
1686
+ };
1657
1687
 
1658
- // src/zod-to-json-schema/parsers/native-enum.ts
1659
- function parseNativeEnumDef(def) {
1660
- const object = def.values;
1661
- const actualKeys = Object.keys(def.values).filter((key) => {
1662
- return typeof object[object[key]] !== "number";
1663
- });
1664
- const actualValues = actualKeys.map((key) => object[key]);
1665
- const parsedTypes = Array.from(
1666
- new Set(actualValues.map((values) => typeof values))
1667
- );
1668
- return {
1669
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1670
- enum: actualValues
1688
+ // src/schema.ts
1689
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1690
+ function lazySchema(createSchema) {
1691
+ let schema;
1692
+ return () => {
1693
+ if (schema == null) {
1694
+ schema = createSchema();
1695
+ }
1696
+ return schema;
1671
1697
  };
1672
1698
  }
1673
-
1674
- // src/zod-to-json-schema/parsers/never.ts
1675
- function parseNeverDef() {
1676
- return { not: parseAnyDef() };
1677
- }
1678
-
1679
- // src/zod-to-json-schema/parsers/null.ts
1680
- function parseNullDef() {
1699
+ function jsonSchema(jsonSchema2, {
1700
+ validate
1701
+ } = {}) {
1681
1702
  return {
1682
- type: "null"
1703
+ [schemaSymbol]: true,
1704
+ _type: void 0,
1705
+ // should never be used directly
1706
+ get jsonSchema() {
1707
+ if (typeof jsonSchema2 === "function") {
1708
+ jsonSchema2 = jsonSchema2();
1709
+ }
1710
+ return jsonSchema2;
1711
+ },
1712
+ validate
1683
1713
  };
1684
1714
  }
1685
-
1686
- // src/zod-to-json-schema/parsers/union.ts
1687
- var primitiveMappings = {
1688
- ZodString: "string",
1689
- ZodNumber: "number",
1690
- ZodBigInt: "integer",
1691
- ZodBoolean: "boolean",
1692
- ZodNull: "null"
1693
- };
1694
- function parseUnionDef(def, refs) {
1695
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1696
- if (options.every(
1697
- (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1698
- )) {
1699
- const types = options.reduce((types2, x) => {
1700
- const type = primitiveMappings[x._def.typeName];
1701
- return type && !types2.includes(type) ? [...types2, type] : types2;
1702
- }, []);
1703
- return {
1704
- type: types.length > 1 ? types : types[0]
1705
- };
1706
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1707
- const types = options.reduce(
1708
- (acc, x) => {
1709
- const type = typeof x._def.value;
1710
- switch (type) {
1711
- case "string":
1712
- case "number":
1713
- case "boolean":
1714
- return [...acc, type];
1715
- case "bigint":
1716
- return [...acc, "integer"];
1717
- case "object":
1718
- if (x._def.value === null) return [...acc, "null"];
1719
- case "symbol":
1720
- case "undefined":
1721
- case "function":
1722
- default:
1723
- return acc;
1724
- }
1725
- },
1726
- []
1727
- );
1728
- if (types.length === options.length) {
1729
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1730
- return {
1731
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1732
- enum: options.reduce(
1733
- (acc, x) => {
1734
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1735
- },
1736
- []
1737
- )
1738
- };
1715
+ function isSchema(value) {
1716
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1717
+ }
1718
+ function asSchema(schema) {
1719
+ return schema == null ? jsonSchema({
1720
+ properties: {},
1721
+ additionalProperties: false
1722
+ }) : isSchema(schema) ? schema : "~standard" in schema ? standardSchema(schema) : schema();
1723
+ }
1724
+ function standardSchema(standardSchema2) {
1725
+ const vendor = standardSchema2["~standard"].vendor;
1726
+ switch (vendor) {
1727
+ case "zod": {
1728
+ return zodSchema(
1729
+ standardSchema2
1730
+ );
1731
+ }
1732
+ case "arktype": {
1733
+ return standardSchemaWithJsonSchemaResolver(
1734
+ standardSchema2,
1735
+ arktypeToJsonSchema
1736
+ );
1737
+ }
1738
+ case "effect": {
1739
+ return standardSchemaWithJsonSchemaResolver(
1740
+ standardSchema2,
1741
+ effectToJsonSchema
1742
+ );
1743
+ }
1744
+ case "valibot": {
1745
+ return standardSchemaWithJsonSchemaResolver(
1746
+ standardSchema2,
1747
+ valibotToJsonSchema
1748
+ );
1749
+ }
1750
+ default: {
1751
+ return standardSchemaWithJsonSchemaResolver(standardSchema2, () => () => {
1752
+ throw new Error(`Unsupported standard schema vendor: ${vendor}`);
1753
+ });
1739
1754
  }
1740
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1741
- return {
1742
- type: "string",
1743
- enum: options.reduce(
1744
- (acc, x) => [
1745
- ...acc,
1746
- ...x._def.values.filter((x2) => !acc.includes(x2))
1747
- ],
1748
- []
1749
- )
1750
- };
1751
1755
  }
1752
- return asAnyOf(def, refs);
1753
1756
  }
1754
- var asAnyOf = (def, refs) => {
1755
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1756
- (x, i) => parseDef(x._def, {
1757
- ...refs,
1758
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
1759
- })
1760
- ).filter(
1761
- (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1762
- );
1763
- return anyOf.length ? { anyOf } : void 0;
1764
- };
1765
-
1766
- // src/zod-to-json-schema/parsers/nullable.ts
1767
- function parseNullableDef(def, refs) {
1768
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1769
- def.innerType._def.typeName
1770
- ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1771
- return {
1772
- type: [
1773
- primitiveMappings[def.innerType._def.typeName],
1774
- "null"
1775
- ]
1776
- };
1777
- }
1778
- const base = parseDef(def.innerType._def, {
1779
- ...refs,
1780
- currentPath: [...refs.currentPath, "anyOf", "0"]
1757
+ function standardSchemaWithJsonSchemaResolver(standardSchema2, jsonSchemaResolver) {
1758
+ return jsonSchema(jsonSchemaResolver(standardSchema2), {
1759
+ validate: async (value) => {
1760
+ const result = await standardSchema2["~standard"].validate(value);
1761
+ return "value" in result ? { success: true, value: result.value } : {
1762
+ success: false,
1763
+ error: new TypeValidationError({
1764
+ value,
1765
+ cause: result.issues
1766
+ })
1767
+ };
1768
+ }
1781
1769
  });
1782
- return base && { anyOf: [base, { type: "null" }] };
1783
1770
  }
1784
-
1785
- // src/zod-to-json-schema/parsers/number.ts
1786
- function parseNumberDef(def) {
1787
- const res = {
1788
- type: "number"
1789
- };
1790
- if (!def.checks) return res;
1791
- for (const check of def.checks) {
1792
- switch (check.kind) {
1793
- case "int":
1794
- res.type = "integer";
1795
- break;
1796
- case "min":
1797
- if (check.inclusive) {
1798
- res.minimum = check.value;
1799
- } else {
1800
- res.exclusiveMinimum = check.value;
1801
- }
1802
- break;
1803
- case "max":
1804
- if (check.inclusive) {
1805
- res.maximum = check.value;
1806
- } else {
1807
- res.exclusiveMaximum = check.value;
1808
- }
1809
- break;
1810
- case "multipleOf":
1811
- res.multipleOf = check.value;
1812
- break;
1771
+ function zod3Schema(zodSchema2, options) {
1772
+ var _a;
1773
+ const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
1774
+ return jsonSchema(
1775
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1776
+ () => zod3ToJsonSchema(zodSchema2, {
1777
+ $refStrategy: useReferences ? "root" : "none"
1778
+ }),
1779
+ {
1780
+ validate: async (value) => {
1781
+ const result = await zodSchema2.safeParseAsync(value);
1782
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1783
+ }
1813
1784
  }
1785
+ );
1786
+ }
1787
+ function zod4Schema(zodSchema2, options) {
1788
+ var _a;
1789
+ const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
1790
+ return jsonSchema(
1791
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1792
+ () => z4.toJSONSchema(zodSchema2, {
1793
+ target: "draft-7",
1794
+ io: "output",
1795
+ reused: useReferences ? "ref" : "inline"
1796
+ }),
1797
+ {
1798
+ validate: async (value) => {
1799
+ const result = await z4.safeParseAsync(zodSchema2, value);
1800
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1801
+ }
1802
+ }
1803
+ );
1804
+ }
1805
+ function isZod4Schema(zodSchema2) {
1806
+ return "_zod" in zodSchema2;
1807
+ }
1808
+ function zodSchema(zodSchema2, options) {
1809
+ if (isZod4Schema(zodSchema2)) {
1810
+ return zod4Schema(zodSchema2, options);
1811
+ } else {
1812
+ return zod3Schema(zodSchema2, options);
1814
1813
  }
1815
- return res;
1816
1814
  }
1817
1815
 
1818
- // src/zod-to-json-schema/parsers/object.ts
1819
- function parseObjectDef(def, refs) {
1820
- const result = {
1821
- type: "object",
1822
- properties: {}
1823
- };
1824
- const required = [];
1825
- const shape = def.shape();
1826
- for (const propName in shape) {
1827
- let propDef = shape[propName];
1828
- if (propDef === void 0 || propDef._def === void 0) {
1829
- continue;
1830
- }
1831
- const propOptional = safeIsOptional(propDef);
1832
- const parsedDef = parseDef(propDef._def, {
1833
- ...refs,
1834
- currentPath: [...refs.currentPath, "properties", propName],
1835
- propertyPath: [...refs.currentPath, "properties", propName]
1836
- });
1837
- if (parsedDef === void 0) {
1838
- continue;
1816
+ // src/validate-types.ts
1817
+ async function validateTypes({
1818
+ value,
1819
+ schema
1820
+ }) {
1821
+ const result = await safeValidateTypes({ value, schema });
1822
+ if (!result.success) {
1823
+ throw TypeValidationError2.wrap({ value, cause: result.error });
1824
+ }
1825
+ return result.value;
1826
+ }
1827
+ async function safeValidateTypes({
1828
+ value,
1829
+ schema
1830
+ }) {
1831
+ const actualSchema = asSchema(schema);
1832
+ try {
1833
+ if (actualSchema.validate == null) {
1834
+ return { success: true, value, rawValue: value };
1839
1835
  }
1840
- result.properties[propName] = parsedDef;
1841
- if (!propOptional) {
1842
- required.push(propName);
1836
+ const result = await actualSchema.validate(value);
1837
+ if (result.success) {
1838
+ return { success: true, value: result.value, rawValue: value };
1843
1839
  }
1840
+ return {
1841
+ success: false,
1842
+ error: TypeValidationError2.wrap({ value, cause: result.error }),
1843
+ rawValue: value
1844
+ };
1845
+ } catch (error) {
1846
+ return {
1847
+ success: false,
1848
+ error: TypeValidationError2.wrap({ value, cause: error }),
1849
+ rawValue: value
1850
+ };
1844
1851
  }
1845
- if (required.length) {
1846
- result.required = required;
1847
- }
1848
- const additionalProperties = decideAdditionalProperties(def, refs);
1849
- if (additionalProperties !== void 0) {
1850
- result.additionalProperties = additionalProperties;
1851
- }
1852
- return result;
1853
1852
  }
1854
- function decideAdditionalProperties(def, refs) {
1855
- if (def.catchall._def.typeName !== "ZodNever") {
1856
- return parseDef(def.catchall._def, {
1857
- ...refs,
1858
- currentPath: [...refs.currentPath, "additionalProperties"]
1859
- });
1860
- }
1861
- switch (def.unknownKeys) {
1862
- case "passthrough":
1863
- return refs.allowedAdditionalProperties;
1864
- case "strict":
1865
- return refs.rejectedAdditionalProperties;
1866
- case "strip":
1867
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1853
+
1854
+ // src/parse-json.ts
1855
+ async function parseJSON({
1856
+ text,
1857
+ schema
1858
+ }) {
1859
+ try {
1860
+ const value = secureJsonParse(text);
1861
+ if (schema == null) {
1862
+ return value;
1863
+ }
1864
+ return validateTypes({ value, schema });
1865
+ } catch (error) {
1866
+ if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {
1867
+ throw error;
1868
+ }
1869
+ throw new JSONParseError({ text, cause: error });
1868
1870
  }
1869
1871
  }
1870
- function safeIsOptional(schema) {
1872
+ async function safeParseJSON({
1873
+ text,
1874
+ schema
1875
+ }) {
1871
1876
  try {
1872
- return schema.isOptional();
1873
- } catch (e) {
1874
- return true;
1877
+ const value = secureJsonParse(text);
1878
+ if (schema == null) {
1879
+ return { success: true, value, rawValue: value };
1880
+ }
1881
+ return await safeValidateTypes({ value, schema });
1882
+ } catch (error) {
1883
+ return {
1884
+ success: false,
1885
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
1886
+ rawValue: void 0
1887
+ };
1875
1888
  }
1876
1889
  }
1877
-
1878
- // src/zod-to-json-schema/parsers/optional.ts
1879
- var parseOptionalDef = (def, refs) => {
1880
- var _a;
1881
- if (refs.currentPath.toString() === ((_a = refs.propertyPath) == null ? void 0 : _a.toString())) {
1882
- return parseDef(def.innerType._def, refs);
1883
- }
1884
- const innerSchema = parseDef(def.innerType._def, {
1885
- ...refs,
1886
- currentPath: [...refs.currentPath, "anyOf", "1"]
1887
- });
1888
- return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1889
- };
1890
-
1891
- // src/zod-to-json-schema/parsers/pipeline.ts
1892
- var parsePipelineDef = (def, refs) => {
1893
- if (refs.pipeStrategy === "input") {
1894
- return parseDef(def.in._def, refs);
1895
- } else if (refs.pipeStrategy === "output") {
1896
- return parseDef(def.out._def, refs);
1890
+ function isParsableJson(input) {
1891
+ try {
1892
+ secureJsonParse(input);
1893
+ return true;
1894
+ } catch (e) {
1895
+ return false;
1897
1896
  }
1898
- const a = parseDef(def.in._def, {
1899
- ...refs,
1900
- currentPath: [...refs.currentPath, "allOf", "0"]
1901
- });
1902
- const b = parseDef(def.out._def, {
1903
- ...refs,
1904
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1905
- });
1906
- return {
1907
- allOf: [a, b].filter((x) => x !== void 0)
1908
- };
1909
- };
1897
+ }
1910
1898
 
1911
- // src/zod-to-json-schema/parsers/promise.ts
1912
- function parsePromiseDef(def, refs) {
1913
- return parseDef(def.type._def, refs);
1899
+ // src/parse-json-event-stream.ts
1900
+ import {
1901
+ EventSourceParserStream
1902
+ } from "eventsource-parser/stream";
1903
+ function parseJsonEventStream({
1904
+ stream,
1905
+ schema
1906
+ }) {
1907
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
1908
+ new TransformStream({
1909
+ async transform({ data }, controller) {
1910
+ if (data === "[DONE]") {
1911
+ return;
1912
+ }
1913
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
1914
+ }
1915
+ })
1916
+ );
1914
1917
  }
1915
1918
 
1916
- // src/zod-to-json-schema/parsers/set.ts
1917
- function parseSetDef(def, refs) {
1918
- const items = parseDef(def.valueType._def, {
1919
- ...refs,
1920
- currentPath: [...refs.currentPath, "items"]
1921
- });
1922
- const schema = {
1923
- type: "array",
1924
- uniqueItems: true,
1925
- items
1926
- };
1927
- if (def.minSize) {
1928
- schema.minItems = def.minSize.value;
1919
+ // src/parse-provider-options.ts
1920
+ import { InvalidArgumentError as InvalidArgumentError2 } from "@ai-sdk/provider";
1921
+ async function parseProviderOptions({
1922
+ provider,
1923
+ providerOptions,
1924
+ schema
1925
+ }) {
1926
+ if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
1927
+ return void 0;
1929
1928
  }
1930
- if (def.maxSize) {
1931
- schema.maxItems = def.maxSize.value;
1929
+ const parsedProviderOptions = await safeValidateTypes({
1930
+ value: providerOptions[provider],
1931
+ schema
1932
+ });
1933
+ if (!parsedProviderOptions.success) {
1934
+ throw new InvalidArgumentError2({
1935
+ argument: "providerOptions",
1936
+ message: `invalid ${provider} provider options`,
1937
+ cause: parsedProviderOptions.error
1938
+ });
1932
1939
  }
1933
- return schema;
1940
+ return parsedProviderOptions.value;
1934
1941
  }
1935
1942
 
1936
- // src/zod-to-json-schema/parsers/tuple.ts
1937
- function parseTupleDef(def, refs) {
1938
- if (def.rest) {
1939
- return {
1940
- type: "array",
1941
- minItems: def.items.length,
1942
- items: def.items.map(
1943
- (x, i) => parseDef(x._def, {
1944
- ...refs,
1945
- currentPath: [...refs.currentPath, "items", `${i}`]
1946
- })
1947
- ).reduce(
1948
- (acc, x) => x === void 0 ? acc : [...acc, x],
1949
- []
1943
+ // src/post-to-api.ts
1944
+ import { APICallError as APICallError3 } from "@ai-sdk/provider";
1945
+ var getOriginalFetch2 = () => globalThis.fetch;
1946
+ var postJsonToApi = async ({
1947
+ url,
1948
+ headers,
1949
+ body,
1950
+ failedResponseHandler,
1951
+ successfulResponseHandler,
1952
+ abortSignal,
1953
+ fetch
1954
+ }) => postToApi({
1955
+ url,
1956
+ headers: {
1957
+ "Content-Type": "application/json",
1958
+ ...headers
1959
+ },
1960
+ body: {
1961
+ content: JSON.stringify(body),
1962
+ values: body
1963
+ },
1964
+ failedResponseHandler,
1965
+ successfulResponseHandler,
1966
+ abortSignal,
1967
+ fetch
1968
+ });
1969
+ var postFormDataToApi = async ({
1970
+ url,
1971
+ headers,
1972
+ formData,
1973
+ failedResponseHandler,
1974
+ successfulResponseHandler,
1975
+ abortSignal,
1976
+ fetch
1977
+ }) => postToApi({
1978
+ url,
1979
+ headers,
1980
+ body: {
1981
+ content: formData,
1982
+ values: Object.fromEntries(formData.entries())
1983
+ },
1984
+ failedResponseHandler,
1985
+ successfulResponseHandler,
1986
+ abortSignal,
1987
+ fetch
1988
+ });
1989
+ var postToApi = async ({
1990
+ url,
1991
+ headers = {},
1992
+ body,
1993
+ successfulResponseHandler,
1994
+ failedResponseHandler,
1995
+ abortSignal,
1996
+ fetch = getOriginalFetch2()
1997
+ }) => {
1998
+ try {
1999
+ const response = await fetch(url, {
2000
+ method: "POST",
2001
+ headers: withUserAgentSuffix(
2002
+ headers,
2003
+ `ai-sdk/provider-utils/${VERSION}`,
2004
+ getRuntimeEnvironmentUserAgent()
1950
2005
  ),
1951
- additionalItems: parseDef(def.rest._def, {
1952
- ...refs,
1953
- currentPath: [...refs.currentPath, "additionalItems"]
1954
- })
1955
- };
1956
- } else {
1957
- return {
1958
- type: "array",
1959
- minItems: def.items.length,
1960
- maxItems: def.items.length,
1961
- items: def.items.map(
1962
- (x, i) => parseDef(x._def, {
1963
- ...refs,
1964
- currentPath: [...refs.currentPath, "items", `${i}`]
1965
- })
1966
- ).reduce(
1967
- (acc, x) => x === void 0 ? acc : [...acc, x],
1968
- []
1969
- )
1970
- };
2006
+ body: body.content,
2007
+ signal: abortSignal
2008
+ });
2009
+ const responseHeaders = extractResponseHeaders(response);
2010
+ if (!response.ok) {
2011
+ let errorInformation;
2012
+ try {
2013
+ errorInformation = await failedResponseHandler({
2014
+ response,
2015
+ url,
2016
+ requestBodyValues: body.values
2017
+ });
2018
+ } catch (error) {
2019
+ if (isAbortError(error) || APICallError3.isInstance(error)) {
2020
+ throw error;
2021
+ }
2022
+ throw new APICallError3({
2023
+ message: "Failed to process error response",
2024
+ cause: error,
2025
+ statusCode: response.status,
2026
+ url,
2027
+ responseHeaders,
2028
+ requestBodyValues: body.values
2029
+ });
2030
+ }
2031
+ throw errorInformation.value;
2032
+ }
2033
+ try {
2034
+ return await successfulResponseHandler({
2035
+ response,
2036
+ url,
2037
+ requestBodyValues: body.values
2038
+ });
2039
+ } catch (error) {
2040
+ if (error instanceof Error) {
2041
+ if (isAbortError(error) || APICallError3.isInstance(error)) {
2042
+ throw error;
2043
+ }
2044
+ }
2045
+ throw new APICallError3({
2046
+ message: "Failed to process successful response",
2047
+ cause: error,
2048
+ statusCode: response.status,
2049
+ url,
2050
+ responseHeaders,
2051
+ requestBodyValues: body.values
2052
+ });
2053
+ }
2054
+ } catch (error) {
2055
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
1971
2056
  }
2057
+ };
2058
+
2059
+ // src/types/tool.ts
2060
+ function tool(tool2) {
2061
+ return tool2;
2062
+ }
2063
+ function dynamicTool(tool2) {
2064
+ return { ...tool2, type: "dynamic" };
1972
2065
  }
1973
2066
 
1974
- // src/zod-to-json-schema/parsers/undefined.ts
1975
- function parseUndefinedDef() {
1976
- return {
1977
- not: parseAnyDef()
1978
- };
2067
+ // src/provider-defined-tool-factory.ts
2068
+ function createProviderDefinedToolFactory({
2069
+ id,
2070
+ name,
2071
+ inputSchema
2072
+ }) {
2073
+ return ({
2074
+ execute,
2075
+ outputSchema,
2076
+ needsApproval,
2077
+ toModelOutput,
2078
+ onInputStart,
2079
+ onInputDelta,
2080
+ onInputAvailable,
2081
+ ...args
2082
+ }) => tool({
2083
+ type: "provider-defined",
2084
+ id,
2085
+ name,
2086
+ args,
2087
+ inputSchema,
2088
+ outputSchema,
2089
+ execute,
2090
+ needsApproval,
2091
+ toModelOutput,
2092
+ onInputStart,
2093
+ onInputDelta,
2094
+ onInputAvailable
2095
+ });
1979
2096
  }
1980
-
1981
- // src/zod-to-json-schema/parsers/unknown.ts
1982
- function parseUnknownDef() {
1983
- return parseAnyDef();
2097
+ function createProviderDefinedToolFactoryWithOutputSchema({
2098
+ id,
2099
+ name,
2100
+ inputSchema,
2101
+ outputSchema
2102
+ }) {
2103
+ return ({
2104
+ execute,
2105
+ needsApproval,
2106
+ toModelOutput,
2107
+ onInputStart,
2108
+ onInputDelta,
2109
+ onInputAvailable,
2110
+ ...args
2111
+ }) => tool({
2112
+ type: "provider-defined",
2113
+ id,
2114
+ name,
2115
+ args,
2116
+ inputSchema,
2117
+ outputSchema,
2118
+ execute,
2119
+ needsApproval,
2120
+ toModelOutput,
2121
+ onInputStart,
2122
+ onInputDelta,
2123
+ onInputAvailable
2124
+ });
1984
2125
  }
1985
2126
 
1986
- // src/zod-to-json-schema/parsers/readonly.ts
1987
- var parseReadonlyDef = (def, refs) => {
1988
- return parseDef(def.innerType._def, refs);
1989
- };
1990
-
1991
- // src/zod-to-json-schema/select-parser.ts
1992
- var selectParser = (def, typeName, refs) => {
1993
- switch (typeName) {
1994
- case ZodFirstPartyTypeKind3.ZodString:
1995
- return parseStringDef(def, refs);
1996
- case ZodFirstPartyTypeKind3.ZodNumber:
1997
- return parseNumberDef(def);
1998
- case ZodFirstPartyTypeKind3.ZodObject:
1999
- return parseObjectDef(def, refs);
2000
- case ZodFirstPartyTypeKind3.ZodBigInt:
2001
- return parseBigintDef(def);
2002
- case ZodFirstPartyTypeKind3.ZodBoolean:
2003
- return parseBooleanDef();
2004
- case ZodFirstPartyTypeKind3.ZodDate:
2005
- return parseDateDef(def, refs);
2006
- case ZodFirstPartyTypeKind3.ZodUndefined:
2007
- return parseUndefinedDef();
2008
- case ZodFirstPartyTypeKind3.ZodNull:
2009
- return parseNullDef();
2010
- case ZodFirstPartyTypeKind3.ZodArray:
2011
- return parseArrayDef(def, refs);
2012
- case ZodFirstPartyTypeKind3.ZodUnion:
2013
- case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
2014
- return parseUnionDef(def, refs);
2015
- case ZodFirstPartyTypeKind3.ZodIntersection:
2016
- return parseIntersectionDef(def, refs);
2017
- case ZodFirstPartyTypeKind3.ZodTuple:
2018
- return parseTupleDef(def, refs);
2019
- case ZodFirstPartyTypeKind3.ZodRecord:
2020
- return parseRecordDef(def, refs);
2021
- case ZodFirstPartyTypeKind3.ZodLiteral:
2022
- return parseLiteralDef(def);
2023
- case ZodFirstPartyTypeKind3.ZodEnum:
2024
- return parseEnumDef(def);
2025
- case ZodFirstPartyTypeKind3.ZodNativeEnum:
2026
- return parseNativeEnumDef(def);
2027
- case ZodFirstPartyTypeKind3.ZodNullable:
2028
- return parseNullableDef(def, refs);
2029
- case ZodFirstPartyTypeKind3.ZodOptional:
2030
- return parseOptionalDef(def, refs);
2031
- case ZodFirstPartyTypeKind3.ZodMap:
2032
- return parseMapDef(def, refs);
2033
- case ZodFirstPartyTypeKind3.ZodSet:
2034
- return parseSetDef(def, refs);
2035
- case ZodFirstPartyTypeKind3.ZodLazy:
2036
- return () => def.getter()._def;
2037
- case ZodFirstPartyTypeKind3.ZodPromise:
2038
- return parsePromiseDef(def, refs);
2039
- case ZodFirstPartyTypeKind3.ZodNaN:
2040
- case ZodFirstPartyTypeKind3.ZodNever:
2041
- return parseNeverDef();
2042
- case ZodFirstPartyTypeKind3.ZodEffects:
2043
- return parseEffectsDef(def, refs);
2044
- case ZodFirstPartyTypeKind3.ZodAny:
2045
- return parseAnyDef();
2046
- case ZodFirstPartyTypeKind3.ZodUnknown:
2047
- return parseUnknownDef();
2048
- case ZodFirstPartyTypeKind3.ZodDefault:
2049
- return parseDefaultDef(def, refs);
2050
- case ZodFirstPartyTypeKind3.ZodBranded:
2051
- return parseBrandedDef(def, refs);
2052
- case ZodFirstPartyTypeKind3.ZodReadonly:
2053
- return parseReadonlyDef(def, refs);
2054
- case ZodFirstPartyTypeKind3.ZodCatch:
2055
- return parseCatchDef(def, refs);
2056
- case ZodFirstPartyTypeKind3.ZodPipeline:
2057
- return parsePipelineDef(def, refs);
2058
- case ZodFirstPartyTypeKind3.ZodFunction:
2059
- case ZodFirstPartyTypeKind3.ZodVoid:
2060
- case ZodFirstPartyTypeKind3.ZodSymbol:
2061
- return void 0;
2062
- default:
2063
- return /* @__PURE__ */ ((_) => void 0)(typeName);
2127
+ // src/resolve.ts
2128
+ async function resolve(value) {
2129
+ if (typeof value === "function") {
2130
+ value = value();
2064
2131
  }
2065
- };
2132
+ return Promise.resolve(value);
2133
+ }
2066
2134
 
2067
- // src/zod-to-json-schema/parse-def.ts
2068
- function parseDef(def, refs, forceResolution = false) {
2069
- var _a;
2070
- const seenItem = refs.seen.get(def);
2071
- if (refs.override) {
2072
- const overrideResult = (_a = refs.override) == null ? void 0 : _a.call(
2073
- refs,
2074
- def,
2075
- refs,
2076
- seenItem,
2077
- forceResolution
2078
- );
2079
- if (overrideResult !== ignoreOverride) {
2080
- return overrideResult;
2081
- }
2082
- }
2083
- if (seenItem && !forceResolution) {
2084
- const seenSchema = get$ref(seenItem, refs);
2085
- if (seenSchema !== void 0) {
2086
- return seenSchema;
2087
- }
2088
- }
2089
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
2090
- refs.seen.set(def, newItem);
2091
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
2092
- const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
2093
- if (jsonSchema2) {
2094
- addMeta(def, refs, jsonSchema2);
2095
- }
2096
- if (refs.postProcess) {
2097
- const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
2098
- newItem.jsonSchema = jsonSchema2;
2099
- return postProcessResult;
2135
+ // src/response-handler.ts
2136
+ import { APICallError as APICallError4, EmptyResponseBodyError } from "@ai-sdk/provider";
2137
+ var createJsonErrorResponseHandler = ({
2138
+ errorSchema,
2139
+ errorToMessage,
2140
+ isRetryable
2141
+ }) => async ({ response, url, requestBodyValues }) => {
2142
+ const responseBody = await response.text();
2143
+ const responseHeaders = extractResponseHeaders(response);
2144
+ if (responseBody.trim() === "") {
2145
+ return {
2146
+ responseHeaders,
2147
+ value: new APICallError4({
2148
+ message: response.statusText,
2149
+ url,
2150
+ requestBodyValues,
2151
+ statusCode: response.status,
2152
+ responseHeaders,
2153
+ responseBody,
2154
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2155
+ })
2156
+ };
2100
2157
  }
2101
- newItem.jsonSchema = jsonSchema2;
2102
- return jsonSchema2;
2103
- }
2104
- var get$ref = (item, refs) => {
2105
- switch (refs.$refStrategy) {
2106
- case "root":
2107
- return { $ref: item.path.join("/") };
2108
- case "relative":
2109
- return { $ref: getRelativePath(refs.currentPath, item.path) };
2110
- case "none":
2111
- case "seen": {
2112
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
2113
- console.warn(
2114
- `Recursive reference detected at ${refs.currentPath.join(
2115
- "/"
2116
- )}! Defaulting to any`
2117
- );
2118
- return parseAnyDef();
2119
- }
2120
- return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
2121
- }
2158
+ try {
2159
+ const parsedError = await parseJSON({
2160
+ text: responseBody,
2161
+ schema: errorSchema
2162
+ });
2163
+ return {
2164
+ responseHeaders,
2165
+ value: new APICallError4({
2166
+ message: errorToMessage(parsedError),
2167
+ url,
2168
+ requestBodyValues,
2169
+ statusCode: response.status,
2170
+ responseHeaders,
2171
+ responseBody,
2172
+ data: parsedError,
2173
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
2174
+ })
2175
+ };
2176
+ } catch (parseError) {
2177
+ return {
2178
+ responseHeaders,
2179
+ value: new APICallError4({
2180
+ message: response.statusText,
2181
+ url,
2182
+ requestBodyValues,
2183
+ statusCode: response.status,
2184
+ responseHeaders,
2185
+ responseBody,
2186
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2187
+ })
2188
+ };
2122
2189
  }
2123
2190
  };
2124
- var addMeta = (def, refs, jsonSchema2) => {
2125
- if (def.description) {
2126
- jsonSchema2.description = def.description;
2191
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
2192
+ const responseHeaders = extractResponseHeaders(response);
2193
+ if (response.body == null) {
2194
+ throw new EmptyResponseBodyError({});
2127
2195
  }
2128
- return jsonSchema2;
2129
- };
2130
-
2131
- // src/zod-to-json-schema/refs.ts
2132
- var getRefs = (options) => {
2133
- const _options = getDefaultOptions(options);
2134
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
2135
2196
  return {
2136
- ..._options,
2137
- currentPath,
2138
- propertyPath: void 0,
2139
- seen: new Map(
2140
- Object.entries(_options.definitions).map(([name, def]) => [
2141
- def._def,
2142
- {
2143
- def: def._def,
2144
- path: [..._options.basePath, _options.definitionPath, name],
2145
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
2146
- jsonSchema: void 0
2197
+ responseHeaders,
2198
+ value: parseJsonEventStream({
2199
+ stream: response.body,
2200
+ schema: chunkSchema
2201
+ })
2202
+ };
2203
+ };
2204
+ var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
2205
+ const responseHeaders = extractResponseHeaders(response);
2206
+ if (response.body == null) {
2207
+ throw new EmptyResponseBodyError({});
2208
+ }
2209
+ let buffer = "";
2210
+ return {
2211
+ responseHeaders,
2212
+ value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(
2213
+ new TransformStream({
2214
+ async transform(chunkText, controller) {
2215
+ if (chunkText.endsWith("\n")) {
2216
+ controller.enqueue(
2217
+ await safeParseJSON({
2218
+ text: buffer + chunkText,
2219
+ schema: chunkSchema
2220
+ })
2221
+ );
2222
+ buffer = "";
2223
+ } else {
2224
+ buffer += chunkText;
2225
+ }
2147
2226
  }
2148
- ])
2227
+ })
2149
2228
  )
2150
2229
  };
2151
2230
  };
2152
-
2153
- // src/zod-to-json-schema/zod-to-json-schema.ts
2154
- var zodToJsonSchema = (schema, options) => {
2155
- var _a;
2156
- const refs = getRefs(options);
2157
- let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
2158
- (acc, [name2, schema2]) => {
2159
- var _a2;
2160
- return {
2161
- ...acc,
2162
- [name2]: (_a2 = parseDef(
2163
- schema2._def,
2164
- {
2165
- ...refs,
2166
- currentPath: [...refs.basePath, refs.definitionPath, name2]
2167
- },
2168
- true
2169
- )) != null ? _a2 : parseAnyDef()
2170
- };
2171
- },
2172
- {}
2173
- ) : void 0;
2174
- const name = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
2175
- const main = (_a = parseDef(
2176
- schema._def,
2177
- name === void 0 ? refs : {
2178
- ...refs,
2179
- currentPath: [...refs.basePath, refs.definitionPath, name]
2180
- },
2181
- false
2182
- )) != null ? _a : parseAnyDef();
2183
- const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
2184
- if (title !== void 0) {
2185
- main.title = title;
2231
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
2232
+ const responseBody = await response.text();
2233
+ const parsedResult = await safeParseJSON({
2234
+ text: responseBody,
2235
+ schema: responseSchema
2236
+ });
2237
+ const responseHeaders = extractResponseHeaders(response);
2238
+ if (!parsedResult.success) {
2239
+ throw new APICallError4({
2240
+ message: "Invalid JSON response",
2241
+ cause: parsedResult.error,
2242
+ statusCode: response.status,
2243
+ responseHeaders,
2244
+ responseBody,
2245
+ url,
2246
+ requestBodyValues
2247
+ });
2186
2248
  }
2187
- const combined = name === void 0 ? definitions ? {
2188
- ...main,
2189
- [refs.definitionPath]: definitions
2190
- } : main : {
2191
- $ref: [
2192
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
2193
- refs.definitionPath,
2194
- name
2195
- ].join("/"),
2196
- [refs.definitionPath]: {
2197
- ...definitions,
2198
- [name]: main
2199
- }
2200
- };
2201
- combined.$schema = "http://json-schema.org/draft-07/schema#";
2202
- return combined;
2203
- };
2204
-
2205
- // src/zod-to-json-schema/index.ts
2206
- var zod_to_json_schema_default = zodToJsonSchema;
2207
-
2208
- // src/schema.ts
2209
- var schemaSymbol = Symbol.for("vercel.ai.schema");
2210
- function lazySchema(createSchema) {
2211
- let schema;
2212
- return () => {
2213
- if (schema == null) {
2214
- schema = createSchema();
2215
- }
2216
- return schema;
2217
- };
2218
- }
2219
- function jsonSchema(jsonSchema2, {
2220
- validate
2221
- } = {}) {
2222
2249
  return {
2223
- [schemaSymbol]: true,
2224
- _type: void 0,
2225
- // should never be used directly
2226
- [validatorSymbol]: true,
2227
- get jsonSchema() {
2228
- if (typeof jsonSchema2 === "function") {
2229
- jsonSchema2 = jsonSchema2();
2230
- }
2231
- return jsonSchema2;
2232
- },
2233
- validate
2250
+ responseHeaders,
2251
+ value: parsedResult.value,
2252
+ rawValue: parsedResult.rawValue
2234
2253
  };
2235
- }
2236
- function isSchema(value) {
2237
- return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2238
- }
2239
- function asSchema(schema) {
2240
- return schema == null ? jsonSchema({
2241
- properties: {},
2242
- additionalProperties: false
2243
- }) : isSchema(schema) ? schema : "~standard" in schema ? standardSchema(schema) : schema();
2244
- }
2245
- function standardSchema(standardSchema2) {
2246
- const vendor = standardSchema2["~standard"].vendor;
2247
- switch (vendor) {
2248
- case "zod": {
2249
- return zodSchema(
2250
- standardSchema2
2251
- );
2252
- }
2253
- case "arktype": {
2254
- return standardSchemaWithJsonSchemaResolver(
2255
- standardSchema2,
2256
- arktypeToJsonSchema
2257
- );
2258
- }
2259
- case "effect": {
2260
- return standardSchemaWithJsonSchemaResolver(
2261
- standardSchema2,
2262
- effectToJsonSchema
2263
- );
2264
- }
2265
- case "valibot": {
2266
- return standardSchemaWithJsonSchemaResolver(
2267
- standardSchema2,
2268
- valibotToJsonSchema
2269
- );
2270
- }
2271
- default: {
2272
- return standardSchemaWithJsonSchemaResolver(standardSchema2, () => {
2273
- throw new Error(`Unsupported standard schema vendor: ${vendor}`);
2274
- });
2275
- }
2254
+ };
2255
+ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
2256
+ const responseHeaders = extractResponseHeaders(response);
2257
+ if (!response.body) {
2258
+ throw new APICallError4({
2259
+ message: "Response body is empty",
2260
+ url,
2261
+ requestBodyValues,
2262
+ statusCode: response.status,
2263
+ responseHeaders,
2264
+ responseBody: void 0
2265
+ });
2276
2266
  }
2277
- }
2278
- function standardSchemaWithJsonSchemaResolver(standardSchema2, jsonSchemaResolver) {
2279
- return jsonSchema(jsonSchemaResolver(standardSchema2), {
2280
- validate: async (value) => {
2281
- const result = await standardSchema2["~standard"].validate(value);
2282
- return "value" in result ? { success: true, value: result.value } : {
2283
- success: false,
2284
- error: new TypeValidationError4({
2285
- value,
2286
- cause: result.issues
2287
- })
2288
- };
2289
- }
2290
- });
2291
- }
2292
- function zod3Schema(zodSchema2, options) {
2293
- var _a;
2294
- const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
2295
- return jsonSchema(
2296
- // defer json schema creation to avoid unnecessary computation when only validation is needed
2297
- () => zod_to_json_schema_default(zodSchema2, {
2298
- $refStrategy: useReferences ? "root" : "none"
2299
- }),
2300
- {
2301
- validate: async (value) => {
2302
- const result = await zodSchema2.safeParseAsync(value);
2303
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2304
- }
2305
- }
2306
- );
2307
- }
2308
- function zod4Schema(zodSchema2, options) {
2309
- var _a;
2310
- const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
2311
- return jsonSchema(
2312
- // defer json schema creation to avoid unnecessary computation when only validation is needed
2313
- () => z4.toJSONSchema(zodSchema2, {
2314
- target: "draft-7",
2315
- io: "output",
2316
- reused: useReferences ? "ref" : "inline"
2317
- }),
2318
- {
2319
- validate: async (value) => {
2320
- const result = await z4.safeParseAsync(zodSchema2, value);
2321
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2322
- }
2323
- }
2324
- );
2325
- }
2326
- function isZod4Schema(zodSchema2) {
2327
- return "_zod" in zodSchema2;
2328
- }
2329
- function zodSchema(zodSchema2, options) {
2330
- if (isZod4Schema(zodSchema2)) {
2331
- return zod4Schema(zodSchema2, options);
2332
- } else {
2333
- return zod3Schema(zodSchema2, options);
2267
+ try {
2268
+ const buffer = await response.arrayBuffer();
2269
+ return {
2270
+ responseHeaders,
2271
+ value: new Uint8Array(buffer)
2272
+ };
2273
+ } catch (error) {
2274
+ throw new APICallError4({
2275
+ message: "Failed to read response as array buffer",
2276
+ url,
2277
+ requestBodyValues,
2278
+ statusCode: response.status,
2279
+ responseHeaders,
2280
+ responseBody: void 0,
2281
+ cause: error
2282
+ });
2334
2283
  }
2335
- }
2284
+ };
2285
+ var createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {
2286
+ const responseHeaders = extractResponseHeaders(response);
2287
+ const responseBody = await response.text();
2288
+ return {
2289
+ responseHeaders,
2290
+ value: new APICallError4({
2291
+ message: response.statusText,
2292
+ url,
2293
+ requestBodyValues,
2294
+ statusCode: response.status,
2295
+ responseHeaders,
2296
+ responseBody
2297
+ })
2298
+ };
2299
+ };
2336
2300
 
2337
2301
  // src/uint8-utils.ts
2338
2302
  var { btoa, atob } = globalThis;
@@ -2390,7 +2354,6 @@ export {
2390
2354
  EventSourceParserStream2 as EventSourceParserStream,
2391
2355
  VERSION,
2392
2356
  asSchema,
2393
- asValidator,
2394
2357
  combineHeaders,
2395
2358
  convertAsyncIteratorToReadableStream,
2396
2359
  convertBase64ToUint8Array,
@@ -2417,10 +2380,8 @@ export {
2417
2380
  isAbortError,
2418
2381
  isParsableJson,
2419
2382
  isUrlSupported,
2420
- isValidator,
2421
2383
  jsonSchema,
2422
2384
  lazySchema,
2423
- lazyValidator,
2424
2385
  loadApiKey,
2425
2386
  loadOptionalSetting,
2426
2387
  loadSetting,
@@ -2435,10 +2396,8 @@ export {
2435
2396
  resolve,
2436
2397
  safeParseJSON,
2437
2398
  safeValidateTypes,
2438
- standardSchemaValidator,
2439
2399
  tool,
2440
2400
  validateTypes,
2441
- validator,
2442
2401
  withUserAgentSuffix,
2443
2402
  withoutTrailingSlash,
2444
2403
  zodSchema