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