@ai-sdk/provider-utils 3.1.0-beta.9 → 4.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 4.0.0-beta.11
4
+
5
+ ### Patch Changes
6
+
7
+ - 95f65c2: chore: use import \* from zod/v4
8
+ - 95f65c2: chore: load zod schemas lazily
9
+
10
+ ## 4.0.0-beta.10
11
+
12
+ ### Major Changes
13
+
14
+ - dee8b05: ai SDK 6 beta
15
+
16
+ ### Patch Changes
17
+
18
+ - Updated dependencies [dee8b05]
19
+ - @ai-sdk/provider@3.0.0-beta.6
20
+
3
21
  ## 3.1.0-beta.9
4
22
 
5
23
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV3Prompt, JSONSchema7, SharedV3ProviderOptions, LanguageModelV3ToolResultOutput, LanguageModelV3ToolResultPart } from '@ai-sdk/provider';
2
2
  import * as z4 from 'zod/v4';
3
- import { ZodType, z } from 'zod/v4';
4
- import * as z3 from 'zod/v3';
3
+ import { ZodType } from 'zod/v4';
5
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
6
5
  export * from '@standard-schema/spec';
6
+ import * as z3 from 'zod/v3';
7
7
  export { EventSourceMessage, EventSourceParserStream } from 'eventsource-parser/stream';
8
8
 
9
9
  declare function combineHeaders(...headers: Array<Record<string, string | undefined> | undefined>): Record<string, string | undefined>;
@@ -43,20 +43,6 @@ declare function extractResponseHeaders(response: Response): {
43
43
  */
44
44
  type FetchFunction = typeof globalThis.fetch;
45
45
 
46
- declare function getRuntimeEnvironmentUserAgent(globalThisAny?: any): string;
47
-
48
- /**
49
- * Appends suffix parts to the `user-agent` header.
50
- * If a `user-agent` header already exists, the suffix parts are appended to it.
51
- * If no `user-agent` header exists, a new one is created with the suffix parts.
52
- * Automatically removes undefined entries from the headers.
53
- *
54
- * @param headers - The original headers.
55
- * @param userAgentSuffixParts - The parts to append to the `user-agent` header.
56
- * @returns The new headers with the `user-agent` header set or updated.
57
- */
58
- declare function withUserAgentSuffix(headers: HeadersInit | Record<string, string | undefined> | undefined, ...userAgentSuffixParts: string[]): Record<string, string>;
59
-
60
46
  /**
61
47
  Creates an ID generator.
62
48
  The total length of the ID is the sum of the prefix, separator, and random part length.
@@ -114,7 +100,19 @@ type Validator<OBJECT = unknown> = {
114
100
  */
115
101
  declare function validator<OBJECT>(validate?: undefined | ((value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>)): Validator<OBJECT>;
116
102
  declare function isValidator(value: unknown): value is Validator;
117
- declare function asValidator<OBJECT>(value: Validator<OBJECT> | StandardSchemaV1<unknown, OBJECT>): Validator<OBJECT>;
103
+ /**
104
+ * Creates a validator with deferred creation.
105
+ * This is important to reduce the startup time of the library
106
+ * and to avoid initializing unused validators.
107
+ *
108
+ * @param createValidator A function that creates a validator.
109
+ * @returns A function that returns a validator.
110
+ */
111
+ declare function lazyValidator<OBJECT>(createValidator: () => Validator<OBJECT>): LazyValidator<OBJECT>;
112
+ type LazyValidator<OBJECT> = () => Validator<OBJECT>;
113
+ type FlexibleValidator<OBJECT> = Validator<OBJECT> | LazyValidator<OBJECT> | StandardSchemaV1<unknown, OBJECT>;
114
+ type InferValidator<SCHEMA> = SCHEMA extends StandardSchemaV1<unknown, infer T> ? T : SCHEMA extends LazyValidator<infer T> ? T : SCHEMA extends Validator<infer T> ? T : never;
115
+ declare function asValidator<OBJECT>(value: FlexibleValidator<OBJECT>): Validator<OBJECT>;
118
116
  declare function standardSchemaValidator<OBJECT>(standardSchema: StandardSchemaV1<unknown, OBJECT>): Validator<OBJECT>;
119
117
 
120
118
  /**
@@ -137,7 +135,7 @@ declare function parseJSON(options: {
137
135
  */
138
136
  declare function parseJSON<T>(options: {
139
137
  text: string;
140
- schema: z4.core.$ZodType<T> | z3.Schema<T> | Validator<T>;
138
+ schema: FlexibleValidator<T>;
141
139
  }): Promise<T>;
142
140
  type ParseResult<T> = {
143
141
  success: true;
@@ -168,7 +166,7 @@ declare function safeParseJSON(options: {
168
166
  */
169
167
  declare function safeParseJSON<T>(options: {
170
168
  text: string;
171
- schema: z4.core.$ZodType<T> | z3.Schema<T> | Validator<T>;
169
+ schema: FlexibleValidator<T>;
172
170
  }): Promise<ParseResult<T>>;
173
171
  declare function isParsableJson(input: string): boolean;
174
172
 
@@ -182,13 +180,13 @@ type ResponseHandler<RETURN_TYPE> = (options: {
182
180
  responseHeaders?: Record<string, string>;
183
181
  }>;
184
182
  declare const createJsonErrorResponseHandler: <T>({ errorSchema, errorToMessage, isRetryable, }: {
185
- errorSchema: ZodType<T>;
183
+ errorSchema: FlexibleValidator<T>;
186
184
  errorToMessage: (error: T) => string;
187
185
  isRetryable?: (response: Response, error?: T) => boolean;
188
186
  }) => ResponseHandler<APICallError>;
189
- declare const createEventSourceResponseHandler: <T>(chunkSchema: ZodType<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
187
+ declare const createEventSourceResponseHandler: <T>(chunkSchema: FlexibleValidator<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
190
188
  declare const createJsonStreamResponseHandler: <T>(chunkSchema: ZodType<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
191
- declare const createJsonResponseHandler: <T>(responseSchema: ZodType<T>) => ResponseHandler<T>;
189
+ declare const createJsonResponseHandler: <T>(responseSchema: FlexibleValidator<T>) => ResponseHandler<T>;
192
190
  declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
193
191
  declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
194
192
 
@@ -205,6 +203,8 @@ declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedR
205
203
  responseHeaders?: Record<string, string>;
206
204
  }>;
207
205
 
206
+ declare function getRuntimeEnvironmentUserAgent(globalThisAny?: any): string;
207
+
208
208
  declare function injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix, }: {
209
209
  messages: LanguageModelV3Prompt;
210
210
  schema?: JSONSchema7;
@@ -282,14 +282,14 @@ declare function mediaTypeToExtension(mediaType: string): string;
282
282
  */
283
283
  declare function parseJsonEventStream<T>({ stream, schema, }: {
284
284
  stream: ReadableStream<Uint8Array>;
285
- schema: ZodType<T>;
285
+ schema: FlexibleValidator<T>;
286
286
  }): ReadableStream<ParseResult<T>>;
287
287
 
288
- declare function parseProviderOptions<T>({ provider, providerOptions, schema, }: {
288
+ declare function parseProviderOptions<OPTIONS>({ provider, providerOptions, schema, }: {
289
289
  provider: string;
290
290
  providerOptions: Record<string, unknown> | undefined;
291
- schema: z.core.$ZodType<T, any>;
292
- }): Promise<T | undefined>;
291
+ schema: FlexibleValidator<OPTIONS>;
292
+ }): Promise<OPTIONS | undefined>;
293
293
 
294
294
  declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
295
295
  url: string;
@@ -352,18 +352,28 @@ type Schema<OBJECT = unknown> = Validator<OBJECT> & {
352
352
  */
353
353
  readonly jsonSchema: JSONSchema7;
354
354
  };
355
- type FlexibleSchema<T> = z4.core.$ZodType<T, any> | z3.Schema<T, z3.ZodTypeDef, any> | Schema<T>;
356
- type InferSchema<SCHEMA> = SCHEMA extends z3.Schema ? z3.infer<SCHEMA> : SCHEMA extends z4.core.$ZodType ? z4.infer<SCHEMA> : SCHEMA extends Schema<infer T> ? T : never;
355
+ /**
356
+ * Creates a schema with deferred creation.
357
+ * This is important to reduce the startup time of the library
358
+ * and to avoid initializing unused validators.
359
+ *
360
+ * @param createValidator A function that creates a schema.
361
+ * @returns A function that returns a schema.
362
+ */
363
+ declare function lazySchema<SCHEMA>(createSchema: () => Schema<SCHEMA>): LazySchema<SCHEMA>;
364
+ type LazySchema<SCHEMA> = () => Schema<SCHEMA>;
365
+ type FlexibleSchema<SCHEMA> = z4.core.$ZodType<SCHEMA, any> | z3.Schema<SCHEMA, z3.ZodTypeDef, any> | Schema<SCHEMA> | LazySchema<SCHEMA>;
366
+ type InferSchema<SCHEMA> = SCHEMA extends z3.Schema ? z3.infer<SCHEMA> : SCHEMA extends z4.core.$ZodType ? z4.infer<SCHEMA> : SCHEMA extends LazySchema<infer T> ? T : SCHEMA extends Schema<infer T> ? T : never;
357
367
  /**
358
368
  * Create a schema using a JSON Schema.
359
369
  *
360
370
  * @param jsonSchema The JSON Schema for the schema.
361
371
  * @param options.validate Optional. A validation function for the schema.
362
372
  */
363
- declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7, { validate, }?: {
373
+ declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7 | (() => JSONSchema7), { validate, }?: {
364
374
  validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
365
375
  }): Schema<OBJECT>;
366
- declare function asSchema<OBJECT>(schema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any> | Schema<OBJECT> | undefined): Schema<OBJECT>;
376
+ declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
367
377
 
368
378
  /**
369
379
  Additional provider-specific options.
@@ -855,7 +865,7 @@ declare function convertToBase64(value: string | Uint8Array): string;
855
865
  */
856
866
  declare function validateTypes<OBJECT>({ value, schema, }: {
857
867
  value: unknown;
858
- schema: StandardSchemaV1<unknown, OBJECT> | Validator<OBJECT>;
868
+ schema: FlexibleValidator<OBJECT>;
859
869
  }): Promise<OBJECT>;
860
870
  /**
861
871
  * Safely validates the types of an unknown object using a schema and
@@ -868,7 +878,7 @@ declare function validateTypes<OBJECT>({ value, schema, }: {
868
878
  */
869
879
  declare function safeValidateTypes<OBJECT>({ value, schema, }: {
870
880
  value: unknown;
871
- schema: StandardSchemaV1<unknown, OBJECT> | Validator<OBJECT>;
881
+ schema: FlexibleValidator<OBJECT>;
872
882
  }): Promise<{
873
883
  success: true;
874
884
  value: OBJECT;
@@ -879,6 +889,20 @@ declare function safeValidateTypes<OBJECT>({ value, schema, }: {
879
889
  rawValue: unknown;
880
890
  }>;
881
891
 
892
+ declare const VERSION: string;
893
+
894
+ /**
895
+ * Appends suffix parts to the `user-agent` header.
896
+ * If a `user-agent` header already exists, the suffix parts are appended to it.
897
+ * If no `user-agent` header exists, a new one is created with the suffix parts.
898
+ * Automatically removes undefined entries from the headers.
899
+ *
900
+ * @param headers - The original headers.
901
+ * @param userAgentSuffixParts - The parts to append to the `user-agent` header.
902
+ * @returns The new headers with the `user-agent` header set or updated.
903
+ */
904
+ declare function withUserAgentSuffix(headers: HeadersInit | Record<string, string | undefined> | undefined, ...userAgentSuffixParts: string[]): Record<string, string>;
905
+
882
906
  declare function withoutTrailingSlash(url: string | undefined): string | undefined;
883
907
 
884
908
  declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
@@ -962,6 +986,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
962
986
  dynamic?: boolean;
963
987
  }
964
988
 
965
- declare const VERSION: string;
966
-
967
- export { type AssistantContent, type AssistantModelMessage, type DataContent, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isParsableJson, isUrlSupported, isValidator, jsonSchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateTypes, validator, validatorSymbol, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
989
+ export { type AssistantContent, type AssistantModelMessage, type DataContent, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isParsableJson, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV3Prompt, JSONSchema7, SharedV3ProviderOptions, LanguageModelV3ToolResultOutput, LanguageModelV3ToolResultPart } from '@ai-sdk/provider';
2
2
  import * as z4 from 'zod/v4';
3
- import { ZodType, z } from 'zod/v4';
4
- import * as z3 from 'zod/v3';
3
+ import { ZodType } from 'zod/v4';
5
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
6
5
  export * from '@standard-schema/spec';
6
+ import * as z3 from 'zod/v3';
7
7
  export { EventSourceMessage, EventSourceParserStream } from 'eventsource-parser/stream';
8
8
 
9
9
  declare function combineHeaders(...headers: Array<Record<string, string | undefined> | undefined>): Record<string, string | undefined>;
@@ -43,20 +43,6 @@ declare function extractResponseHeaders(response: Response): {
43
43
  */
44
44
  type FetchFunction = typeof globalThis.fetch;
45
45
 
46
- declare function getRuntimeEnvironmentUserAgent(globalThisAny?: any): string;
47
-
48
- /**
49
- * Appends suffix parts to the `user-agent` header.
50
- * If a `user-agent` header already exists, the suffix parts are appended to it.
51
- * If no `user-agent` header exists, a new one is created with the suffix parts.
52
- * Automatically removes undefined entries from the headers.
53
- *
54
- * @param headers - The original headers.
55
- * @param userAgentSuffixParts - The parts to append to the `user-agent` header.
56
- * @returns The new headers with the `user-agent` header set or updated.
57
- */
58
- declare function withUserAgentSuffix(headers: HeadersInit | Record<string, string | undefined> | undefined, ...userAgentSuffixParts: string[]): Record<string, string>;
59
-
60
46
  /**
61
47
  Creates an ID generator.
62
48
  The total length of the ID is the sum of the prefix, separator, and random part length.
@@ -114,7 +100,19 @@ type Validator<OBJECT = unknown> = {
114
100
  */
115
101
  declare function validator<OBJECT>(validate?: undefined | ((value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>)): Validator<OBJECT>;
116
102
  declare function isValidator(value: unknown): value is Validator;
117
- declare function asValidator<OBJECT>(value: Validator<OBJECT> | StandardSchemaV1<unknown, OBJECT>): Validator<OBJECT>;
103
+ /**
104
+ * Creates a validator with deferred creation.
105
+ * This is important to reduce the startup time of the library
106
+ * and to avoid initializing unused validators.
107
+ *
108
+ * @param createValidator A function that creates a validator.
109
+ * @returns A function that returns a validator.
110
+ */
111
+ declare function lazyValidator<OBJECT>(createValidator: () => Validator<OBJECT>): LazyValidator<OBJECT>;
112
+ type LazyValidator<OBJECT> = () => Validator<OBJECT>;
113
+ type FlexibleValidator<OBJECT> = Validator<OBJECT> | LazyValidator<OBJECT> | StandardSchemaV1<unknown, OBJECT>;
114
+ type InferValidator<SCHEMA> = SCHEMA extends StandardSchemaV1<unknown, infer T> ? T : SCHEMA extends LazyValidator<infer T> ? T : SCHEMA extends Validator<infer T> ? T : never;
115
+ declare function asValidator<OBJECT>(value: FlexibleValidator<OBJECT>): Validator<OBJECT>;
118
116
  declare function standardSchemaValidator<OBJECT>(standardSchema: StandardSchemaV1<unknown, OBJECT>): Validator<OBJECT>;
119
117
 
120
118
  /**
@@ -137,7 +135,7 @@ declare function parseJSON(options: {
137
135
  */
138
136
  declare function parseJSON<T>(options: {
139
137
  text: string;
140
- schema: z4.core.$ZodType<T> | z3.Schema<T> | Validator<T>;
138
+ schema: FlexibleValidator<T>;
141
139
  }): Promise<T>;
142
140
  type ParseResult<T> = {
143
141
  success: true;
@@ -168,7 +166,7 @@ declare function safeParseJSON(options: {
168
166
  */
169
167
  declare function safeParseJSON<T>(options: {
170
168
  text: string;
171
- schema: z4.core.$ZodType<T> | z3.Schema<T> | Validator<T>;
169
+ schema: FlexibleValidator<T>;
172
170
  }): Promise<ParseResult<T>>;
173
171
  declare function isParsableJson(input: string): boolean;
174
172
 
@@ -182,13 +180,13 @@ type ResponseHandler<RETURN_TYPE> = (options: {
182
180
  responseHeaders?: Record<string, string>;
183
181
  }>;
184
182
  declare const createJsonErrorResponseHandler: <T>({ errorSchema, errorToMessage, isRetryable, }: {
185
- errorSchema: ZodType<T>;
183
+ errorSchema: FlexibleValidator<T>;
186
184
  errorToMessage: (error: T) => string;
187
185
  isRetryable?: (response: Response, error?: T) => boolean;
188
186
  }) => ResponseHandler<APICallError>;
189
- declare const createEventSourceResponseHandler: <T>(chunkSchema: ZodType<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
187
+ declare const createEventSourceResponseHandler: <T>(chunkSchema: FlexibleValidator<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
190
188
  declare const createJsonStreamResponseHandler: <T>(chunkSchema: ZodType<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
191
- declare const createJsonResponseHandler: <T>(responseSchema: ZodType<T>) => ResponseHandler<T>;
189
+ declare const createJsonResponseHandler: <T>(responseSchema: FlexibleValidator<T>) => ResponseHandler<T>;
192
190
  declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
193
191
  declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
194
192
 
@@ -205,6 +203,8 @@ declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedR
205
203
  responseHeaders?: Record<string, string>;
206
204
  }>;
207
205
 
206
+ declare function getRuntimeEnvironmentUserAgent(globalThisAny?: any): string;
207
+
208
208
  declare function injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix, }: {
209
209
  messages: LanguageModelV3Prompt;
210
210
  schema?: JSONSchema7;
@@ -282,14 +282,14 @@ declare function mediaTypeToExtension(mediaType: string): string;
282
282
  */
283
283
  declare function parseJsonEventStream<T>({ stream, schema, }: {
284
284
  stream: ReadableStream<Uint8Array>;
285
- schema: ZodType<T>;
285
+ schema: FlexibleValidator<T>;
286
286
  }): ReadableStream<ParseResult<T>>;
287
287
 
288
- declare function parseProviderOptions<T>({ provider, providerOptions, schema, }: {
288
+ declare function parseProviderOptions<OPTIONS>({ provider, providerOptions, schema, }: {
289
289
  provider: string;
290
290
  providerOptions: Record<string, unknown> | undefined;
291
- schema: z.core.$ZodType<T, any>;
292
- }): Promise<T | undefined>;
291
+ schema: FlexibleValidator<OPTIONS>;
292
+ }): Promise<OPTIONS | undefined>;
293
293
 
294
294
  declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
295
295
  url: string;
@@ -352,18 +352,28 @@ type Schema<OBJECT = unknown> = Validator<OBJECT> & {
352
352
  */
353
353
  readonly jsonSchema: JSONSchema7;
354
354
  };
355
- type FlexibleSchema<T> = z4.core.$ZodType<T, any> | z3.Schema<T, z3.ZodTypeDef, any> | Schema<T>;
356
- type InferSchema<SCHEMA> = SCHEMA extends z3.Schema ? z3.infer<SCHEMA> : SCHEMA extends z4.core.$ZodType ? z4.infer<SCHEMA> : SCHEMA extends Schema<infer T> ? T : never;
355
+ /**
356
+ * Creates a schema with deferred creation.
357
+ * This is important to reduce the startup time of the library
358
+ * and to avoid initializing unused validators.
359
+ *
360
+ * @param createValidator A function that creates a schema.
361
+ * @returns A function that returns a schema.
362
+ */
363
+ declare function lazySchema<SCHEMA>(createSchema: () => Schema<SCHEMA>): LazySchema<SCHEMA>;
364
+ type LazySchema<SCHEMA> = () => Schema<SCHEMA>;
365
+ type FlexibleSchema<SCHEMA> = z4.core.$ZodType<SCHEMA, any> | z3.Schema<SCHEMA, z3.ZodTypeDef, any> | Schema<SCHEMA> | LazySchema<SCHEMA>;
366
+ type InferSchema<SCHEMA> = SCHEMA extends z3.Schema ? z3.infer<SCHEMA> : SCHEMA extends z4.core.$ZodType ? z4.infer<SCHEMA> : SCHEMA extends LazySchema<infer T> ? T : SCHEMA extends Schema<infer T> ? T : never;
357
367
  /**
358
368
  * Create a schema using a JSON Schema.
359
369
  *
360
370
  * @param jsonSchema The JSON Schema for the schema.
361
371
  * @param options.validate Optional. A validation function for the schema.
362
372
  */
363
- declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7, { validate, }?: {
373
+ declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7 | (() => JSONSchema7), { validate, }?: {
364
374
  validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
365
375
  }): Schema<OBJECT>;
366
- declare function asSchema<OBJECT>(schema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any> | Schema<OBJECT> | undefined): Schema<OBJECT>;
376
+ declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
367
377
 
368
378
  /**
369
379
  Additional provider-specific options.
@@ -855,7 +865,7 @@ declare function convertToBase64(value: string | Uint8Array): string;
855
865
  */
856
866
  declare function validateTypes<OBJECT>({ value, schema, }: {
857
867
  value: unknown;
858
- schema: StandardSchemaV1<unknown, OBJECT> | Validator<OBJECT>;
868
+ schema: FlexibleValidator<OBJECT>;
859
869
  }): Promise<OBJECT>;
860
870
  /**
861
871
  * Safely validates the types of an unknown object using a schema and
@@ -868,7 +878,7 @@ declare function validateTypes<OBJECT>({ value, schema, }: {
868
878
  */
869
879
  declare function safeValidateTypes<OBJECT>({ value, schema, }: {
870
880
  value: unknown;
871
- schema: StandardSchemaV1<unknown, OBJECT> | Validator<OBJECT>;
881
+ schema: FlexibleValidator<OBJECT>;
872
882
  }): Promise<{
873
883
  success: true;
874
884
  value: OBJECT;
@@ -879,6 +889,20 @@ declare function safeValidateTypes<OBJECT>({ value, schema, }: {
879
889
  rawValue: unknown;
880
890
  }>;
881
891
 
892
+ declare const VERSION: string;
893
+
894
+ /**
895
+ * Appends suffix parts to the `user-agent` header.
896
+ * If a `user-agent` header already exists, the suffix parts are appended to it.
897
+ * If no `user-agent` header exists, a new one is created with the suffix parts.
898
+ * Automatically removes undefined entries from the headers.
899
+ *
900
+ * @param headers - The original headers.
901
+ * @param userAgentSuffixParts - The parts to append to the `user-agent` header.
902
+ * @returns The new headers with the `user-agent` header set or updated.
903
+ */
904
+ declare function withUserAgentSuffix(headers: HeadersInit | Record<string, string | undefined> | undefined, ...userAgentSuffixParts: string[]): Record<string, string>;
905
+
882
906
  declare function withoutTrailingSlash(url: string | undefined): string | undefined;
883
907
 
884
908
  declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
@@ -962,6 +986,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
962
986
  dynamic?: boolean;
963
987
  }
964
988
 
965
- declare const VERSION: string;
966
-
967
- export { type AssistantContent, type AssistantModelMessage, type DataContent, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isParsableJson, isUrlSupported, isValidator, jsonSchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateTypes, validator, validatorSymbol, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
989
+ export { type AssistantContent, type AssistantModelMessage, type DataContent, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isParsableJson, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.js CHANGED
@@ -63,6 +63,8 @@ __export(src_exports, {
63
63
  isUrlSupported: () => isUrlSupported,
64
64
  isValidator: () => isValidator,
65
65
  jsonSchema: () => jsonSchema,
66
+ lazySchema: () => lazySchema,
67
+ lazyValidator: () => lazyValidator,
66
68
  loadApiKey: () => loadApiKey,
67
69
  loadOptionalSetting: () => loadOptionalSetting,
68
70
  loadSetting: () => loadSetting,
@@ -81,7 +83,6 @@ __export(src_exports, {
81
83
  tool: () => tool,
82
84
  validateTypes: () => validateTypes,
83
85
  validator: () => validator,
84
- validatorSymbol: () => validatorSymbol,
85
86
  withUserAgentSuffix: () => withUserAgentSuffix,
86
87
  withoutTrailingSlash: () => withoutTrailingSlash,
87
88
  zodSchema: () => zodSchema
@@ -163,45 +164,6 @@ function extractResponseHeaders(response) {
163
164
  return Object.fromEntries([...response.headers]);
164
165
  }
165
166
 
166
- // src/get-runtime-environment-user-agent.ts
167
- function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
168
- var _a, _b, _c;
169
- if (globalThisAny.window) {
170
- return `runtime/browser`;
171
- }
172
- if ((_a = globalThisAny.navigator) == null ? void 0 : _a.userAgent) {
173
- return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
174
- }
175
- if ((_c = (_b = globalThisAny.process) == null ? void 0 : _b.versions) == null ? void 0 : _c.node) {
176
- return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
177
- }
178
- if (globalThisAny.EdgeRuntime) {
179
- return `runtime/vercel-edge`;
180
- }
181
- return "runtime/unknown";
182
- }
183
-
184
- // src/remove-undefined-entries.ts
185
- function removeUndefinedEntries(record) {
186
- return Object.fromEntries(
187
- Object.entries(record).filter(([_key, value]) => value != null)
188
- );
189
- }
190
-
191
- // src/with-user-agent-suffix.ts
192
- function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
193
- const cleanedHeaders = removeUndefinedEntries(
194
- headers != null ? headers : {}
195
- );
196
- const normalizedHeaders = new Headers(cleanedHeaders);
197
- const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
198
- normalizedHeaders.set(
199
- "user-agent",
200
- [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
201
- );
202
- return Object.fromEntries(normalizedHeaders);
203
- }
204
-
205
167
  // src/generate-id.ts
206
168
  var import_provider = require("@ai-sdk/provider");
207
169
  var createIdGenerator = ({
@@ -283,8 +245,47 @@ function handleFetchError({
283
245
  return error;
284
246
  }
285
247
 
248
+ // src/get-runtime-environment-user-agent.ts
249
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
250
+ var _a, _b, _c;
251
+ if (globalThisAny.window) {
252
+ return `runtime/browser`;
253
+ }
254
+ if ((_a = globalThisAny.navigator) == null ? void 0 : _a.userAgent) {
255
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
256
+ }
257
+ if ((_c = (_b = globalThisAny.process) == null ? void 0 : _b.versions) == null ? void 0 : _c.node) {
258
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
259
+ }
260
+ if (globalThisAny.EdgeRuntime) {
261
+ return `runtime/vercel-edge`;
262
+ }
263
+ return "runtime/unknown";
264
+ }
265
+
266
+ // src/remove-undefined-entries.ts
267
+ function removeUndefinedEntries(record) {
268
+ return Object.fromEntries(
269
+ Object.entries(record).filter(([_key, value]) => value != null)
270
+ );
271
+ }
272
+
273
+ // src/with-user-agent-suffix.ts
274
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
275
+ const cleanedHeaders = removeUndefinedEntries(
276
+ headers != null ? headers : {}
277
+ );
278
+ const normalizedHeaders = new Headers(cleanedHeaders);
279
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
280
+ normalizedHeaders.set(
281
+ "user-agent",
282
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
283
+ );
284
+ return Object.fromEntries(normalizedHeaders);
285
+ }
286
+
286
287
  // src/version.ts
287
- var VERSION = true ? "3.1.0-beta.9" : "0.0.0-test";
288
+ var VERSION = true ? "4.0.0-beta.11" : "0.0.0-test";
288
289
 
289
290
  // src/get-from-api.ts
290
291
  var getOriginalFetch = () => globalThis.fetch;
@@ -570,8 +571,17 @@ function validator(validate) {
570
571
  function isValidator(value) {
571
572
  return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
572
573
  }
574
+ function lazyValidator(createValidator) {
575
+ let validator2;
576
+ return () => {
577
+ if (validator2 == null) {
578
+ validator2 = createValidator();
579
+ }
580
+ return validator2;
581
+ };
582
+ }
573
583
  function asValidator(value) {
574
- return isValidator(value) ? value : standardSchemaValidator(value);
584
+ return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
575
585
  }
576
586
  function standardSchemaValidator(standardSchema) {
577
587
  return validator(async (value) => {
@@ -2258,7 +2268,8 @@ function zod3Schema(zodSchema2, options) {
2258
2268
  var _a;
2259
2269
  const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
2260
2270
  return jsonSchema(
2261
- zod_to_json_schema_default(zodSchema2, {
2271
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
2272
+ () => zod_to_json_schema_default(zodSchema2, {
2262
2273
  $refStrategy: useReferences ? "root" : "none"
2263
2274
  }),
2264
2275
  {
@@ -2272,17 +2283,20 @@ function zod3Schema(zodSchema2, options) {
2272
2283
  function zod4Schema(zodSchema2, options) {
2273
2284
  var _a;
2274
2285
  const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
2275
- const z4JSONSchema = z4.toJSONSchema(zodSchema2, {
2276
- target: "draft-7",
2277
- io: "output",
2278
- reused: useReferences ? "ref" : "inline"
2279
- });
2280
- return jsonSchema(z4JSONSchema, {
2281
- validate: async (value) => {
2282
- const result = await z4.safeParseAsync(zodSchema2, value);
2283
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2286
+ return jsonSchema(
2287
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
2288
+ () => z4.toJSONSchema(zodSchema2, {
2289
+ target: "draft-7",
2290
+ io: "output",
2291
+ reused: useReferences ? "ref" : "inline"
2292
+ }),
2293
+ {
2294
+ validate: async (value) => {
2295
+ const result = await z4.safeParseAsync(zodSchema2, value);
2296
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2297
+ }
2284
2298
  }
2285
- });
2299
+ );
2286
2300
  }
2287
2301
  function isZod4Schema(zodSchema2) {
2288
2302
  return "_zod" in zodSchema2;
@@ -2297,6 +2311,15 @@ function zodSchema(zodSchema2, options) {
2297
2311
 
2298
2312
  // src/schema.ts
2299
2313
  var schemaSymbol = Symbol.for("vercel.ai.schema");
2314
+ function lazySchema(createSchema) {
2315
+ let schema;
2316
+ return () => {
2317
+ if (schema == null) {
2318
+ schema = createSchema();
2319
+ }
2320
+ return schema;
2321
+ };
2322
+ }
2300
2323
  function jsonSchema(jsonSchema2, {
2301
2324
  validate
2302
2325
  } = {}) {
@@ -2305,7 +2328,12 @@ function jsonSchema(jsonSchema2, {
2305
2328
  _type: void 0,
2306
2329
  // should never be used directly
2307
2330
  [validatorSymbol]: true,
2308
- jsonSchema: jsonSchema2,
2331
+ get jsonSchema() {
2332
+ if (typeof jsonSchema2 === "function") {
2333
+ jsonSchema2 = jsonSchema2();
2334
+ }
2335
+ return jsonSchema2;
2336
+ },
2309
2337
  validate
2310
2338
  };
2311
2339
  }
@@ -2316,7 +2344,7 @@ function asSchema(schema) {
2316
2344
  return schema == null ? jsonSchema({
2317
2345
  properties: {},
2318
2346
  additionalProperties: false
2319
- }) : isSchema(schema) ? schema : zodSchema(schema);
2347
+ }) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
2320
2348
  }
2321
2349
 
2322
2350
  // src/uint8-utils.ts
@@ -2403,6 +2431,8 @@ var import_stream2 = require("eventsource-parser/stream");
2403
2431
  isUrlSupported,
2404
2432
  isValidator,
2405
2433
  jsonSchema,
2434
+ lazySchema,
2435
+ lazyValidator,
2406
2436
  loadApiKey,
2407
2437
  loadOptionalSetting,
2408
2438
  loadSetting,
@@ -2421,7 +2451,6 @@ var import_stream2 = require("eventsource-parser/stream");
2421
2451
  tool,
2422
2452
  validateTypes,
2423
2453
  validator,
2424
- validatorSymbol,
2425
2454
  withUserAgentSuffix,
2426
2455
  withoutTrailingSlash,
2427
2456
  zodSchema,