@discomedia/utils 1.0.62 → 1.0.63
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-frontend.cjs +3063 -237
- package/dist/index-frontend.cjs.map +1 -1
- package/dist/index-frontend.mjs +3063 -237
- package/dist/index-frontend.mjs.map +1 -1
- package/dist/index.cjs +3063 -237
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +3063 -237
- package/dist/index.mjs.map +1 -1
- package/dist/package.json +3 -2
- package/dist/test.js +8944 -349
- package/dist/test.js.map +1 -1
- package/dist/types/llm-openai.d.ts +6 -2
- package/dist/types/llm-openai.d.ts.map +1 -1
- package/dist/types/types/llm-types.d.ts +8 -15
- package/dist/types/types/llm-types.d.ts.map +1 -1
- package/dist/types-frontend/llm-openai.d.ts +6 -2
- package/dist/types-frontend/llm-openai.d.ts.map +1 -1
- package/dist/types-frontend/types/llm-types.d.ts +8 -15
- package/dist/types-frontend/types/llm-types.d.ts.map +1 -1
- package/package.json +3 -2
package/dist/index-frontend.cjs
CHANGED
|
@@ -227,7 +227,7 @@ function maybeObj(x) {
|
|
|
227
227
|
return x ?? {};
|
|
228
228
|
}
|
|
229
229
|
// https://stackoverflow.com/a/34491287
|
|
230
|
-
function isEmptyObj(obj) {
|
|
230
|
+
function isEmptyObj$1(obj) {
|
|
231
231
|
if (!obj)
|
|
232
232
|
return true;
|
|
233
233
|
for (const _k in obj)
|
|
@@ -1966,6 +1966,20 @@ let Messages$1 = class Messages extends APIResource {
|
|
|
1966
1966
|
function isChatCompletionFunctionTool(tool) {
|
|
1967
1967
|
return tool !== undefined && 'function' in tool && tool.function !== undefined;
|
|
1968
1968
|
}
|
|
1969
|
+
function makeParseableTextFormat(response_format, parser) {
|
|
1970
|
+
const obj = { ...response_format };
|
|
1971
|
+
Object.defineProperties(obj, {
|
|
1972
|
+
$brand: {
|
|
1973
|
+
value: 'auto-parseable-response-format',
|
|
1974
|
+
enumerable: false,
|
|
1975
|
+
},
|
|
1976
|
+
$parseRaw: {
|
|
1977
|
+
value: parser,
|
|
1978
|
+
enumerable: false,
|
|
1979
|
+
},
|
|
1980
|
+
});
|
|
1981
|
+
return obj;
|
|
1982
|
+
}
|
|
1969
1983
|
function isAutoParsableResponseFormat(response_format) {
|
|
1970
1984
|
return response_format?.['$brand'] === 'auto-parseable-response-format';
|
|
1971
1985
|
}
|
|
@@ -3978,7 +3992,7 @@ const readEnv = (env) => {
|
|
|
3978
3992
|
return undefined;
|
|
3979
3993
|
};
|
|
3980
3994
|
|
|
3981
|
-
var _AssistantStream_instances, _a$
|
|
3995
|
+
var _AssistantStream_instances, _a$2, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun;
|
|
3982
3996
|
class AssistantStream extends EventStream {
|
|
3983
3997
|
constructor() {
|
|
3984
3998
|
super(...arguments);
|
|
@@ -4053,7 +4067,7 @@ class AssistantStream extends EventStream {
|
|
|
4053
4067
|
};
|
|
4054
4068
|
}
|
|
4055
4069
|
static fromReadableStream(stream) {
|
|
4056
|
-
const runner = new _a$
|
|
4070
|
+
const runner = new _a$2();
|
|
4057
4071
|
runner._run(() => runner._fromReadableStream(stream));
|
|
4058
4072
|
return runner;
|
|
4059
4073
|
}
|
|
@@ -4079,7 +4093,7 @@ class AssistantStream extends EventStream {
|
|
|
4079
4093
|
return stream.toReadableStream();
|
|
4080
4094
|
}
|
|
4081
4095
|
static createToolAssistantStream(runId, runs, params, options) {
|
|
4082
|
-
const runner = new _a$
|
|
4096
|
+
const runner = new _a$2();
|
|
4083
4097
|
runner._run(() => runner._runToolAssistantStream(runId, runs, params, {
|
|
4084
4098
|
...options,
|
|
4085
4099
|
headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },
|
|
@@ -4108,7 +4122,7 @@ class AssistantStream extends EventStream {
|
|
|
4108
4122
|
return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
|
|
4109
4123
|
}
|
|
4110
4124
|
static createThreadAssistantStream(params, thread, options) {
|
|
4111
|
-
const runner = new _a$
|
|
4125
|
+
const runner = new _a$2();
|
|
4112
4126
|
runner._run(() => runner._threadAssistantStream(params, thread, {
|
|
4113
4127
|
...options,
|
|
4114
4128
|
headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },
|
|
@@ -4116,7 +4130,7 @@ class AssistantStream extends EventStream {
|
|
|
4116
4130
|
return runner;
|
|
4117
4131
|
}
|
|
4118
4132
|
static createAssistantStream(threadId, runs, params, options) {
|
|
4119
|
-
const runner = new _a$
|
|
4133
|
+
const runner = new _a$2();
|
|
4120
4134
|
runner._run(() => runner._runAssistantStream(threadId, runs, params, {
|
|
4121
4135
|
...options,
|
|
4122
4136
|
headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },
|
|
@@ -4258,7 +4272,7 @@ class AssistantStream extends EventStream {
|
|
|
4258
4272
|
return await this._createToolAssistantStream(runs, runId, params, options);
|
|
4259
4273
|
}
|
|
4260
4274
|
}
|
|
4261
|
-
_a$
|
|
4275
|
+
_a$2 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
|
|
4262
4276
|
if (this.ended)
|
|
4263
4277
|
return;
|
|
4264
4278
|
__classPrivateFieldSet(this, _AssistantStream_currentEvent, event);
|
|
@@ -4436,7 +4450,7 @@ _a$1 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_ad
|
|
|
4436
4450
|
}
|
|
4437
4451
|
let data = event.data;
|
|
4438
4452
|
if (data.delta) {
|
|
4439
|
-
const accumulated = _a$
|
|
4453
|
+
const accumulated = _a$2.accumulateDelta(snapshot, data.delta);
|
|
4440
4454
|
__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
|
|
4441
4455
|
}
|
|
4442
4456
|
return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
|
|
@@ -4490,7 +4504,7 @@ _a$1 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_ad
|
|
|
4490
4504
|
}
|
|
4491
4505
|
throw Error('Tried to accumulate a non-message event');
|
|
4492
4506
|
}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) {
|
|
4493
|
-
return _a$
|
|
4507
|
+
return _a$2.accumulateDelta(currentContent, contentElement);
|
|
4494
4508
|
}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) {
|
|
4495
4509
|
__classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data);
|
|
4496
4510
|
switch (event.event) {
|
|
@@ -6908,7 +6922,7 @@ _Webhooks_instances = new WeakSet(), _Webhooks_validateSecret = function _Webhoo
|
|
|
6908
6922
|
};
|
|
6909
6923
|
|
|
6910
6924
|
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
6911
|
-
var _OpenAI_instances, _a, _OpenAI_encoder, _OpenAI_baseURLOverridden;
|
|
6925
|
+
var _OpenAI_instances, _a$1, _OpenAI_encoder, _OpenAI_baseURLOverridden;
|
|
6912
6926
|
/**
|
|
6913
6927
|
* API Client for interfacing with the OpenAI API.
|
|
6914
6928
|
*/
|
|
@@ -6999,7 +7013,7 @@ class OpenAI {
|
|
|
6999
7013
|
throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
|
|
7000
7014
|
}
|
|
7001
7015
|
this.baseURL = options.baseURL;
|
|
7002
|
-
this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
|
|
7016
|
+
this.timeout = options.timeout ?? _a$1.DEFAULT_TIMEOUT /* 10 minutes */;
|
|
7003
7017
|
this.logger = options.logger ?? console;
|
|
7004
7018
|
const defaultLogLevel = 'warn';
|
|
7005
7019
|
// Set default logLevel early so that we can log a warning in parseLogLevel.
|
|
@@ -7087,7 +7101,7 @@ class OpenAI {
|
|
|
7087
7101
|
new URL(path)
|
|
7088
7102
|
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
|
7089
7103
|
const defaultQuery = this.defaultQuery();
|
|
7090
|
-
if (!isEmptyObj(defaultQuery)) {
|
|
7104
|
+
if (!isEmptyObj$1(defaultQuery)) {
|
|
7091
7105
|
query = { ...defaultQuery, ...query };
|
|
7092
7106
|
}
|
|
7093
7107
|
if (typeof query === 'object' && query && !Array.isArray(query)) {
|
|
@@ -7429,10 +7443,10 @@ class OpenAI {
|
|
|
7429
7443
|
}
|
|
7430
7444
|
}
|
|
7431
7445
|
}
|
|
7432
|
-
_a = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() {
|
|
7446
|
+
_a$1 = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() {
|
|
7433
7447
|
return this.baseURL !== 'https://api.openai.com/v1';
|
|
7434
7448
|
};
|
|
7435
|
-
OpenAI.OpenAI = _a;
|
|
7449
|
+
OpenAI.OpenAI = _a$1;
|
|
7436
7450
|
OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes
|
|
7437
7451
|
OpenAI.OpenAIError = OpenAIError;
|
|
7438
7452
|
OpenAI.APIError = APIError;
|
|
@@ -7472,239 +7486,3013 @@ OpenAI.Containers = Containers;
|
|
|
7472
7486
|
OpenAI.Skills = Skills;
|
|
7473
7487
|
OpenAI.Videos = Videos;
|
|
7474
7488
|
|
|
7475
|
-
//
|
|
7476
|
-
|
|
7477
|
-
const
|
|
7478
|
-
const
|
|
7479
|
-
|
|
7480
|
-
|
|
7481
|
-
|
|
7482
|
-
'gpt-4o': {
|
|
7483
|
-
inputCost: 2.5 / 1_000_000,
|
|
7484
|
-
cacheHitCost: 1.25 / 1_000_000,
|
|
7485
|
-
outputCost: 10 / 1_000_000,
|
|
7486
|
-
},
|
|
7487
|
-
'gpt-4o-mini': {
|
|
7488
|
-
inputCost: 0.15 / 1_000_000,
|
|
7489
|
-
cacheHitCost: 0.075 / 1_000_000,
|
|
7490
|
-
outputCost: 0.6 / 1_000_000,
|
|
7491
|
-
},
|
|
7492
|
-
'o1-mini': {
|
|
7493
|
-
inputCost: 1.1 / 1_000_000,
|
|
7494
|
-
cacheHitCost: 0.55 / 1_000_000,
|
|
7495
|
-
outputCost: 4.4 / 1_000_000,
|
|
7496
|
-
},
|
|
7497
|
-
'o1': {
|
|
7498
|
-
inputCost: 15 / 1_000_000,
|
|
7499
|
-
cacheHitCost: 7.5 / 1_000_000,
|
|
7500
|
-
outputCost: 60 / 1_000_000,
|
|
7501
|
-
},
|
|
7502
|
-
'o3-mini': {
|
|
7503
|
-
inputCost: 1.1 / 1_000_000,
|
|
7504
|
-
cacheHitCost: 0.55 / 1_000_000,
|
|
7505
|
-
outputCost: 4.4 / 1_000_000,
|
|
7506
|
-
},
|
|
7507
|
-
'o3': {
|
|
7508
|
-
inputCost: 2 / 1_000_000,
|
|
7509
|
-
cacheHitCost: 0.5 / 1_000_000,
|
|
7510
|
-
outputCost: 8 / 1_000_000,
|
|
7511
|
-
},
|
|
7512
|
-
'gpt-4.1': {
|
|
7513
|
-
inputCost: 2 / 1_000_000,
|
|
7514
|
-
cacheHitCost: 0.5 / 1_000_000,
|
|
7515
|
-
outputCost: 8 / 1_000_000,
|
|
7516
|
-
},
|
|
7517
|
-
'gpt-4.1-mini': {
|
|
7518
|
-
inputCost: 0.4 / 1_000_000,
|
|
7519
|
-
cacheHitCost: 0.1 / 1_000_000,
|
|
7520
|
-
outputCost: 1.6 / 1_000_000,
|
|
7521
|
-
},
|
|
7522
|
-
'gpt-4.1-nano': {
|
|
7523
|
-
inputCost: 0.1 / 1_000_000,
|
|
7524
|
-
cacheHitCost: 0.025 / 1_000_000,
|
|
7525
|
-
outputCost: 0.4 / 1_000_000,
|
|
7526
|
-
},
|
|
7527
|
-
'gpt-5': {
|
|
7528
|
-
inputCost: 1.25 / 1_000_000,
|
|
7529
|
-
cacheHitCost: 0.125 / 1_000_000,
|
|
7530
|
-
outputCost: 10 / 1_000_000,
|
|
7531
|
-
},
|
|
7532
|
-
'gpt-5-mini': {
|
|
7533
|
-
inputCost: 0.25 / 1_000_000,
|
|
7534
|
-
cacheHitCost: 0.025 / 1_000_000,
|
|
7535
|
-
outputCost: 2 / 1_000_000,
|
|
7536
|
-
},
|
|
7537
|
-
'gpt-5-nano': {
|
|
7538
|
-
inputCost: 0.05 / 1_000_000,
|
|
7539
|
-
cacheHitCost: 0.005 / 1_000_000,
|
|
7540
|
-
outputCost: 0.4 / 1_000_000,
|
|
7541
|
-
},
|
|
7542
|
-
'gpt-5.1': {
|
|
7543
|
-
inputCost: 1.25 / 1_000_000,
|
|
7544
|
-
cacheHitCost: 0.125 / 1_000_000,
|
|
7545
|
-
outputCost: 10 / 1_000_000,
|
|
7546
|
-
},
|
|
7547
|
-
'gpt-5.4': {
|
|
7548
|
-
inputCost: 2.5 / 1_000_000,
|
|
7549
|
-
cacheHitCost: 0.25 / 1_000_000,
|
|
7550
|
-
outputCost: 15 / 1_000_000,
|
|
7551
|
-
},
|
|
7552
|
-
'gpt-5.4-pro': {
|
|
7553
|
-
inputCost: 30 / 1_000_000,
|
|
7554
|
-
outputCost: 180 / 1_000_000,
|
|
7555
|
-
},
|
|
7556
|
-
'gpt-5.2': {
|
|
7557
|
-
inputCost: 1.75 / 1_000_000,
|
|
7558
|
-
cacheHitCost: 0.175 / 1_000_000,
|
|
7559
|
-
outputCost: 14 / 1_000_000,
|
|
7560
|
-
},
|
|
7561
|
-
'gpt-5.2-pro': {
|
|
7562
|
-
inputCost: 21 / 1_000_000,
|
|
7563
|
-
outputCost: 168 / 1_000_000,
|
|
7564
|
-
},
|
|
7565
|
-
'gpt-5.1-codex': {
|
|
7566
|
-
inputCost: 1.25 / 1_000_000,
|
|
7567
|
-
cacheHitCost: 0.125 / 1_000_000,
|
|
7568
|
-
outputCost: 10 / 1_000_000,
|
|
7569
|
-
},
|
|
7570
|
-
'gpt-5.1-codex-max': {
|
|
7571
|
-
inputCost: 1.25 / 1_000_000,
|
|
7572
|
-
cacheHitCost: 0.125 / 1_000_000,
|
|
7573
|
-
outputCost: 10 / 1_000_000,
|
|
7574
|
-
},
|
|
7575
|
-
'o4-mini': {
|
|
7576
|
-
inputCost: 1.1 / 1_000_000,
|
|
7577
|
-
cacheHitCost: 0.275 / 1_000_000,
|
|
7578
|
-
outputCost: 4.4 / 1_000_000,
|
|
7579
|
-
},
|
|
7580
|
-
};
|
|
7581
|
-
const deepseekModelCosts = {
|
|
7582
|
-
'deepseek-chat': {
|
|
7583
|
-
inputCost: 0.27 / 1_000_000, // $0.27 per 1M tokens (Cache miss price)
|
|
7584
|
-
cacheHitCost: 0.07 / 1_000_000, // $0.07 per 1M tokens (Cache hit price)
|
|
7585
|
-
outputCost: 1.1 / 1_000_000, // $1.10 per 1M tokens
|
|
7586
|
-
},
|
|
7587
|
-
'deepseek-reasoner': {
|
|
7588
|
-
inputCost: 0.55 / 1_000_000, // $0.55 per 1M tokens (Cache miss price)
|
|
7589
|
-
cacheHitCost: 0.14 / 1_000_000, // $0.14 per 1M tokens (Cache hit price)
|
|
7590
|
-
outputCost: 2.19 / 1_000_000, // $2.19 per 1M tokens
|
|
7591
|
-
},
|
|
7592
|
-
};
|
|
7593
|
-
function shouldUseGPT54HighContextPricing(model, inputTokens) {
|
|
7594
|
-
return (model === 'gpt-5.4' || model === 'gpt-5.4-pro') && inputTokens > GPT_5_4_HIGH_CONTEXT_THRESHOLD_TOKENS;
|
|
7489
|
+
// functions
|
|
7490
|
+
function getEnumValues(entries) {
|
|
7491
|
+
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
|
|
7492
|
+
const values = Object.entries(entries)
|
|
7493
|
+
.filter(([k, _]) => numericValues.indexOf(+k) === -1)
|
|
7494
|
+
.map(([_, v]) => v);
|
|
7495
|
+
return values;
|
|
7595
7496
|
}
|
|
7596
|
-
|
|
7597
|
-
|
|
7598
|
-
|
|
7599
|
-
|
|
7600
|
-
|
|
7601
|
-
|
|
7602
|
-
* Calculates the cost of generating images using OpenAI's Images API.
|
|
7603
|
-
*
|
|
7604
|
-
* @param model The image generation model name.
|
|
7605
|
-
* @param imageCount The number of images generated.
|
|
7606
|
-
* @returns The cost of generating the images in USD.
|
|
7607
|
-
*/
|
|
7608
|
-
function calculateImageCost(model, imageCount) {
|
|
7609
|
-
if (typeof model !== 'string' || typeof imageCount !== 'number' || imageCount <= 0) {
|
|
7610
|
-
return 0;
|
|
7497
|
+
|
|
7498
|
+
var _a;
|
|
7499
|
+
class $ZodRegistry {
|
|
7500
|
+
constructor() {
|
|
7501
|
+
this._map = new WeakMap();
|
|
7502
|
+
this._idmap = new Map();
|
|
7611
7503
|
}
|
|
7612
|
-
|
|
7613
|
-
|
|
7614
|
-
|
|
7615
|
-
|
|
7616
|
-
|
|
7617
|
-
|
|
7618
|
-
|
|
7619
|
-
*
|
|
7620
|
-
* @param provider The provider of the language model. Supported providers are 'openai' and 'deepseek'.
|
|
7621
|
-
* @param model The name of the language model. Supported models are listed in the `openAiModelCosts` and `deepseekModelCosts` objects.
|
|
7622
|
-
* @param inputTokens The number of input tokens passed to the language model.
|
|
7623
|
-
* @param outputTokens The number of output tokens generated by the language model.
|
|
7624
|
-
* @param reasoningTokens The number of output tokens generated by the language model for reasoning.
|
|
7625
|
-
* @param cacheHitTokens The number of input tokens billed at cached-input rates.
|
|
7626
|
-
* @returns The cost of calling the language model in USD.
|
|
7627
|
-
*/
|
|
7628
|
-
function calculateCost(provider, model, inputTokens, outputTokens, reasoningTokens, cacheHitTokens) {
|
|
7629
|
-
if (typeof provider !== 'string' ||
|
|
7630
|
-
typeof model !== 'string' ||
|
|
7631
|
-
typeof inputTokens !== 'number' ||
|
|
7632
|
-
typeof outputTokens !== 'number' ||
|
|
7633
|
-
(reasoningTokens !== undefined && typeof reasoningTokens !== 'number') ||
|
|
7634
|
-
(cacheHitTokens !== undefined && typeof cacheHitTokens !== 'number')) {
|
|
7635
|
-
return 0;
|
|
7504
|
+
add(schema, ..._meta) {
|
|
7505
|
+
const meta = _meta[0];
|
|
7506
|
+
this._map.set(schema, meta);
|
|
7507
|
+
if (meta && typeof meta === "object" && "id" in meta) {
|
|
7508
|
+
this._idmap.set(meta.id, schema);
|
|
7509
|
+
}
|
|
7510
|
+
return this;
|
|
7636
7511
|
}
|
|
7637
|
-
|
|
7638
|
-
|
|
7639
|
-
|
|
7640
|
-
|
|
7641
|
-
let inputCost = inputTokens * modelCosts.inputCost;
|
|
7642
|
-
if (typeof modelCosts.cacheHitCost === 'number' && boundedCacheHitTokens > 0) {
|
|
7643
|
-
inputCost = boundedCacheHitTokens * modelCosts.cacheHitCost + (inputTokens - boundedCacheHitTokens) * modelCosts.inputCost;
|
|
7512
|
+
clear() {
|
|
7513
|
+
this._map = new WeakMap();
|
|
7514
|
+
this._idmap = new Map();
|
|
7515
|
+
return this;
|
|
7644
7516
|
}
|
|
7645
|
-
|
|
7646
|
-
|
|
7647
|
-
|
|
7648
|
-
|
|
7649
|
-
|
|
7650
|
-
|
|
7517
|
+
remove(schema) {
|
|
7518
|
+
const meta = this._map.get(schema);
|
|
7519
|
+
if (meta && typeof meta === "object" && "id" in meta) {
|
|
7520
|
+
this._idmap.delete(meta.id);
|
|
7521
|
+
}
|
|
7522
|
+
this._map.delete(schema);
|
|
7523
|
+
return this;
|
|
7651
7524
|
}
|
|
7652
|
-
|
|
7525
|
+
get(schema) {
|
|
7526
|
+
// return this._map.get(schema) as any;
|
|
7527
|
+
// inherit metadata
|
|
7528
|
+
const p = schema._zod.parent;
|
|
7529
|
+
if (p) {
|
|
7530
|
+
const pm = { ...(this.get(p) ?? {}) };
|
|
7531
|
+
delete pm.id; // do not inherit id
|
|
7532
|
+
const f = { ...pm, ...this._map.get(schema) };
|
|
7533
|
+
return Object.keys(f).length ? f : undefined;
|
|
7534
|
+
}
|
|
7535
|
+
return this._map.get(schema);
|
|
7536
|
+
}
|
|
7537
|
+
has(schema) {
|
|
7538
|
+
return this._map.has(schema);
|
|
7539
|
+
}
|
|
7540
|
+
}
|
|
7541
|
+
// registries
|
|
7542
|
+
function registry() {
|
|
7543
|
+
return new $ZodRegistry();
|
|
7653
7544
|
}
|
|
7545
|
+
(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
|
|
7546
|
+
const globalRegistry = globalThis.__zod_globalRegistry;
|
|
7654
7547
|
|
|
7655
|
-
|
|
7656
|
-
|
|
7657
|
-
|
|
7658
|
-
|
|
7659
|
-
|
|
7660
|
-
|
|
7661
|
-
|
|
7662
|
-
|
|
7663
|
-
|
|
7664
|
-
|
|
7665
|
-
|
|
7666
|
-
|
|
7667
|
-
|
|
7668
|
-
|
|
7669
|
-
|
|
7670
|
-
|
|
7671
|
-
|
|
7672
|
-
|
|
7673
|
-
|
|
7548
|
+
// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {
|
|
7549
|
+
// return {
|
|
7550
|
+
// processor: inputs.processor,
|
|
7551
|
+
// metadataRegistry: inputs.metadata ?? globalRegistry,
|
|
7552
|
+
// target: inputs.target ?? "draft-2020-12",
|
|
7553
|
+
// unrepresentable: inputs.unrepresentable ?? "throw",
|
|
7554
|
+
// };
|
|
7555
|
+
// }
|
|
7556
|
+
function initializeContext(params) {
|
|
7557
|
+
// Normalize target: convert old non-hyphenated versions to hyphenated versions
|
|
7558
|
+
let target = params?.target ?? "draft-2020-12";
|
|
7559
|
+
if (target === "draft-4")
|
|
7560
|
+
target = "draft-04";
|
|
7561
|
+
if (target === "draft-7")
|
|
7562
|
+
target = "draft-07";
|
|
7563
|
+
return {
|
|
7564
|
+
processors: params.processors ?? {},
|
|
7565
|
+
metadataRegistry: params?.metadata ?? globalRegistry,
|
|
7566
|
+
target,
|
|
7567
|
+
unrepresentable: params?.unrepresentable ?? "throw",
|
|
7568
|
+
override: params?.override ?? (() => { }),
|
|
7569
|
+
io: params?.io ?? "output",
|
|
7570
|
+
counter: 0,
|
|
7571
|
+
seen: new Map(),
|
|
7572
|
+
cycles: params?.cycles ?? "ref",
|
|
7573
|
+
reused: params?.reused ?? "inline",
|
|
7574
|
+
external: params?.external ?? undefined,
|
|
7575
|
+
};
|
|
7576
|
+
}
|
|
7577
|
+
function process$1(schema, ctx, _params = { path: [], schemaPath: [] }) {
|
|
7578
|
+
var _a;
|
|
7579
|
+
const def = schema._zod.def;
|
|
7580
|
+
// check for schema in seens
|
|
7581
|
+
const seen = ctx.seen.get(schema);
|
|
7582
|
+
if (seen) {
|
|
7583
|
+
seen.count++;
|
|
7584
|
+
// check if cycle
|
|
7585
|
+
const isCycle = _params.schemaPath.includes(schema);
|
|
7586
|
+
if (isCycle) {
|
|
7587
|
+
seen.cycle = _params.path;
|
|
7588
|
+
}
|
|
7589
|
+
return seen.schema;
|
|
7590
|
+
}
|
|
7591
|
+
// initialize
|
|
7592
|
+
const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
|
|
7593
|
+
ctx.seen.set(schema, result);
|
|
7594
|
+
// custom method overrides default behavior
|
|
7595
|
+
const overrideSchema = schema._zod.toJSONSchema?.();
|
|
7596
|
+
if (overrideSchema) {
|
|
7597
|
+
result.schema = overrideSchema;
|
|
7598
|
+
}
|
|
7599
|
+
else {
|
|
7600
|
+
const params = {
|
|
7601
|
+
..._params,
|
|
7602
|
+
schemaPath: [..._params.schemaPath, schema],
|
|
7603
|
+
path: _params.path,
|
|
7604
|
+
};
|
|
7605
|
+
if (schema._zod.processJSONSchema) {
|
|
7606
|
+
schema._zod.processJSONSchema(ctx, result.schema, params);
|
|
7607
|
+
}
|
|
7608
|
+
else {
|
|
7609
|
+
const _json = result.schema;
|
|
7610
|
+
const processor = ctx.processors[def.type];
|
|
7611
|
+
if (!processor) {
|
|
7612
|
+
throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
|
|
7613
|
+
}
|
|
7614
|
+
processor(schema, ctx, _json, params);
|
|
7615
|
+
}
|
|
7616
|
+
const parent = schema._zod.parent;
|
|
7617
|
+
if (parent) {
|
|
7618
|
+
// Also set ref if processor didn't (for inheritance)
|
|
7619
|
+
if (!result.ref)
|
|
7620
|
+
result.ref = parent;
|
|
7621
|
+
process$1(parent, ctx, params);
|
|
7622
|
+
ctx.seen.get(parent).isParent = true;
|
|
7623
|
+
}
|
|
7624
|
+
}
|
|
7625
|
+
// metadata
|
|
7626
|
+
const meta = ctx.metadataRegistry.get(schema);
|
|
7627
|
+
if (meta)
|
|
7628
|
+
Object.assign(result.schema, meta);
|
|
7629
|
+
if (ctx.io === "input" && isTransforming(schema)) {
|
|
7630
|
+
// examples/defaults only apply to output type of pipe
|
|
7631
|
+
delete result.schema.examples;
|
|
7632
|
+
delete result.schema.default;
|
|
7633
|
+
}
|
|
7634
|
+
// set prefault as default
|
|
7635
|
+
if (ctx.io === "input" && result.schema._prefault)
|
|
7636
|
+
(_a = result.schema).default ?? (_a.default = result.schema._prefault);
|
|
7637
|
+
delete result.schema._prefault;
|
|
7638
|
+
// pulling fresh from ctx.seen in case it was overwritten
|
|
7639
|
+
const _result = ctx.seen.get(schema);
|
|
7640
|
+
return _result.schema;
|
|
7641
|
+
}
|
|
7642
|
+
function extractDefs(ctx, schema
|
|
7643
|
+
// params: EmitParams
|
|
7644
|
+
) {
|
|
7645
|
+
// iterate over seen map;
|
|
7646
|
+
const root = ctx.seen.get(schema);
|
|
7647
|
+
if (!root)
|
|
7648
|
+
throw new Error("Unprocessed schema. This is a bug in Zod.");
|
|
7649
|
+
// Track ids to detect duplicates across different schemas
|
|
7650
|
+
const idToSchema = new Map();
|
|
7651
|
+
for (const entry of ctx.seen.entries()) {
|
|
7652
|
+
const id = ctx.metadataRegistry.get(entry[0])?.id;
|
|
7653
|
+
if (id) {
|
|
7654
|
+
const existing = idToSchema.get(id);
|
|
7655
|
+
if (existing && existing !== entry[0]) {
|
|
7656
|
+
throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
|
|
7657
|
+
}
|
|
7658
|
+
idToSchema.set(id, entry[0]);
|
|
7659
|
+
}
|
|
7660
|
+
}
|
|
7661
|
+
// returns a ref to the schema
|
|
7662
|
+
// defId will be empty if the ref points to an external schema (or #)
|
|
7663
|
+
const makeURI = (entry) => {
|
|
7664
|
+
// comparing the seen objects because sometimes
|
|
7665
|
+
// multiple schemas map to the same seen object.
|
|
7666
|
+
// e.g. lazy
|
|
7667
|
+
// external is configured
|
|
7668
|
+
const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
|
|
7669
|
+
if (ctx.external) {
|
|
7670
|
+
const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`;
|
|
7671
|
+
// check if schema is in the external registry
|
|
7672
|
+
const uriGenerator = ctx.external.uri ?? ((id) => id);
|
|
7673
|
+
if (externalId) {
|
|
7674
|
+
return { ref: uriGenerator(externalId) };
|
|
7675
|
+
}
|
|
7676
|
+
// otherwise, add to __shared
|
|
7677
|
+
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
|
|
7678
|
+
entry[1].defId = id; // set defId so it will be reused if needed
|
|
7679
|
+
return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
|
|
7680
|
+
}
|
|
7681
|
+
if (entry[1] === root) {
|
|
7682
|
+
return { ref: "#" };
|
|
7683
|
+
}
|
|
7684
|
+
// self-contained schema
|
|
7685
|
+
const uriPrefix = `#`;
|
|
7686
|
+
const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
|
|
7687
|
+
const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
|
|
7688
|
+
return { defId, ref: defUriPrefix + defId };
|
|
7689
|
+
};
|
|
7690
|
+
// stored cached version in `def` property
|
|
7691
|
+
// remove all properties, set $ref
|
|
7692
|
+
const extractToDef = (entry) => {
|
|
7693
|
+
// if the schema is already a reference, do not extract it
|
|
7694
|
+
if (entry[1].schema.$ref) {
|
|
7695
|
+
return;
|
|
7696
|
+
}
|
|
7697
|
+
const seen = entry[1];
|
|
7698
|
+
const { ref, defId } = makeURI(entry);
|
|
7699
|
+
seen.def = { ...seen.schema };
|
|
7700
|
+
// defId won't be set if the schema is a reference to an external schema
|
|
7701
|
+
// or if the schema is the root schema
|
|
7702
|
+
if (defId)
|
|
7703
|
+
seen.defId = defId;
|
|
7704
|
+
// wipe away all properties except $ref
|
|
7705
|
+
const schema = seen.schema;
|
|
7706
|
+
for (const key in schema) {
|
|
7707
|
+
delete schema[key];
|
|
7708
|
+
}
|
|
7709
|
+
schema.$ref = ref;
|
|
7710
|
+
};
|
|
7711
|
+
// throw on cycles
|
|
7712
|
+
// break cycles
|
|
7713
|
+
if (ctx.cycles === "throw") {
|
|
7714
|
+
for (const entry of ctx.seen.entries()) {
|
|
7715
|
+
const seen = entry[1];
|
|
7716
|
+
if (seen.cycle) {
|
|
7717
|
+
throw new Error("Cycle detected: " +
|
|
7718
|
+
`#/${seen.cycle?.join("/")}/<root>` +
|
|
7719
|
+
'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
|
|
7720
|
+
}
|
|
7721
|
+
}
|
|
7722
|
+
}
|
|
7723
|
+
// extract schemas into $defs
|
|
7724
|
+
for (const entry of ctx.seen.entries()) {
|
|
7725
|
+
const seen = entry[1];
|
|
7726
|
+
// convert root schema to # $ref
|
|
7727
|
+
if (schema === entry[0]) {
|
|
7728
|
+
extractToDef(entry); // this has special handling for the root schema
|
|
7729
|
+
continue;
|
|
7730
|
+
}
|
|
7731
|
+
// extract schemas that are in the external registry
|
|
7732
|
+
if (ctx.external) {
|
|
7733
|
+
const ext = ctx.external.registry.get(entry[0])?.id;
|
|
7734
|
+
if (schema !== entry[0] && ext) {
|
|
7735
|
+
extractToDef(entry);
|
|
7736
|
+
continue;
|
|
7674
7737
|
}
|
|
7675
7738
|
}
|
|
7676
|
-
|
|
7677
|
-
|
|
7678
|
-
|
|
7679
|
-
|
|
7680
|
-
|
|
7681
|
-
if (!char)
|
|
7682
|
-
return undefined;
|
|
7683
|
-
if (char === '{')
|
|
7684
|
-
return parseObject();
|
|
7685
|
-
if (char === '[')
|
|
7686
|
-
return parseArray();
|
|
7687
|
-
if (char === '"' || char === "'")
|
|
7688
|
-
return parseString();
|
|
7689
|
-
if (char === 't' && jsonStr.slice(index, index + 4).toLowerCase() === 'true') {
|
|
7690
|
-
index += 4;
|
|
7691
|
-
return true;
|
|
7739
|
+
// extract schemas with `id` meta
|
|
7740
|
+
const id = ctx.metadataRegistry.get(entry[0])?.id;
|
|
7741
|
+
if (id) {
|
|
7742
|
+
extractToDef(entry);
|
|
7743
|
+
continue;
|
|
7692
7744
|
}
|
|
7693
|
-
|
|
7694
|
-
|
|
7695
|
-
|
|
7745
|
+
// break cycles
|
|
7746
|
+
if (seen.cycle) {
|
|
7747
|
+
// any
|
|
7748
|
+
extractToDef(entry);
|
|
7749
|
+
continue;
|
|
7696
7750
|
}
|
|
7697
|
-
|
|
7698
|
-
|
|
7699
|
-
|
|
7751
|
+
// extract reused schemas
|
|
7752
|
+
if (seen.count > 1) {
|
|
7753
|
+
if (ctx.reused === "ref") {
|
|
7754
|
+
extractToDef(entry);
|
|
7755
|
+
// biome-ignore lint:
|
|
7756
|
+
continue;
|
|
7757
|
+
}
|
|
7700
7758
|
}
|
|
7701
|
-
if (/[a-zA-Z]/.test(char))
|
|
7702
|
-
return parseString(); // Unquoted string
|
|
7703
|
-
if (char === '-' || char === '.' || /\d/.test(char))
|
|
7704
|
-
return parseNumber();
|
|
7705
|
-
return undefined; // Unknown character
|
|
7706
7759
|
}
|
|
7707
|
-
|
|
7760
|
+
}
|
|
7761
|
+
function finalize(ctx, schema) {
|
|
7762
|
+
const root = ctx.seen.get(schema);
|
|
7763
|
+
if (!root)
|
|
7764
|
+
throw new Error("Unprocessed schema. This is a bug in Zod.");
|
|
7765
|
+
// flatten refs - inherit properties from parent schemas
|
|
7766
|
+
const flattenRef = (zodSchema) => {
|
|
7767
|
+
const seen = ctx.seen.get(zodSchema);
|
|
7768
|
+
// already processed
|
|
7769
|
+
if (seen.ref === null)
|
|
7770
|
+
return;
|
|
7771
|
+
const schema = seen.def ?? seen.schema;
|
|
7772
|
+
const _cached = { ...schema };
|
|
7773
|
+
const ref = seen.ref;
|
|
7774
|
+
seen.ref = null; // prevent infinite recursion
|
|
7775
|
+
if (ref) {
|
|
7776
|
+
flattenRef(ref);
|
|
7777
|
+
const refSeen = ctx.seen.get(ref);
|
|
7778
|
+
const refSchema = refSeen.schema;
|
|
7779
|
+
// merge referenced schema into current
|
|
7780
|
+
if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
|
|
7781
|
+
// older drafts can't combine $ref with other properties
|
|
7782
|
+
schema.allOf = schema.allOf ?? [];
|
|
7783
|
+
schema.allOf.push(refSchema);
|
|
7784
|
+
}
|
|
7785
|
+
else {
|
|
7786
|
+
Object.assign(schema, refSchema);
|
|
7787
|
+
}
|
|
7788
|
+
// restore child's own properties (child wins)
|
|
7789
|
+
Object.assign(schema, _cached);
|
|
7790
|
+
const isParentRef = zodSchema._zod.parent === ref;
|
|
7791
|
+
// For parent chain, child is a refinement - remove parent-only properties
|
|
7792
|
+
if (isParentRef) {
|
|
7793
|
+
for (const key in schema) {
|
|
7794
|
+
if (key === "$ref" || key === "allOf")
|
|
7795
|
+
continue;
|
|
7796
|
+
if (!(key in _cached)) {
|
|
7797
|
+
delete schema[key];
|
|
7798
|
+
}
|
|
7799
|
+
}
|
|
7800
|
+
}
|
|
7801
|
+
// When ref was extracted to $defs, remove properties that match the definition
|
|
7802
|
+
if (refSchema.$ref && refSeen.def) {
|
|
7803
|
+
for (const key in schema) {
|
|
7804
|
+
if (key === "$ref" || key === "allOf")
|
|
7805
|
+
continue;
|
|
7806
|
+
if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {
|
|
7807
|
+
delete schema[key];
|
|
7808
|
+
}
|
|
7809
|
+
}
|
|
7810
|
+
}
|
|
7811
|
+
}
|
|
7812
|
+
// If parent was extracted (has $ref), propagate $ref to this schema
|
|
7813
|
+
// This handles cases like: readonly().meta({id}).describe()
|
|
7814
|
+
// where processor sets ref to innerType but parent should be referenced
|
|
7815
|
+
const parent = zodSchema._zod.parent;
|
|
7816
|
+
if (parent && parent !== ref) {
|
|
7817
|
+
// Ensure parent is processed first so its def has inherited properties
|
|
7818
|
+
flattenRef(parent);
|
|
7819
|
+
const parentSeen = ctx.seen.get(parent);
|
|
7820
|
+
if (parentSeen?.schema.$ref) {
|
|
7821
|
+
schema.$ref = parentSeen.schema.$ref;
|
|
7822
|
+
// De-duplicate with parent's definition
|
|
7823
|
+
if (parentSeen.def) {
|
|
7824
|
+
for (const key in schema) {
|
|
7825
|
+
if (key === "$ref" || key === "allOf")
|
|
7826
|
+
continue;
|
|
7827
|
+
if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {
|
|
7828
|
+
delete schema[key];
|
|
7829
|
+
}
|
|
7830
|
+
}
|
|
7831
|
+
}
|
|
7832
|
+
}
|
|
7833
|
+
}
|
|
7834
|
+
// execute overrides
|
|
7835
|
+
ctx.override({
|
|
7836
|
+
zodSchema: zodSchema,
|
|
7837
|
+
jsonSchema: schema,
|
|
7838
|
+
path: seen.path ?? [],
|
|
7839
|
+
});
|
|
7840
|
+
};
|
|
7841
|
+
for (const entry of [...ctx.seen.entries()].reverse()) {
|
|
7842
|
+
flattenRef(entry[0]);
|
|
7843
|
+
}
|
|
7844
|
+
const result = {};
|
|
7845
|
+
if (ctx.target === "draft-2020-12") {
|
|
7846
|
+
result.$schema = "https://json-schema.org/draft/2020-12/schema";
|
|
7847
|
+
}
|
|
7848
|
+
else if (ctx.target === "draft-07") {
|
|
7849
|
+
result.$schema = "http://json-schema.org/draft-07/schema#";
|
|
7850
|
+
}
|
|
7851
|
+
else if (ctx.target === "draft-04") {
|
|
7852
|
+
result.$schema = "http://json-schema.org/draft-04/schema#";
|
|
7853
|
+
}
|
|
7854
|
+
else if (ctx.target === "openapi-3.0") ;
|
|
7855
|
+
else ;
|
|
7856
|
+
if (ctx.external?.uri) {
|
|
7857
|
+
const id = ctx.external.registry.get(schema)?.id;
|
|
7858
|
+
if (!id)
|
|
7859
|
+
throw new Error("Schema is missing an `id` property");
|
|
7860
|
+
result.$id = ctx.external.uri(id);
|
|
7861
|
+
}
|
|
7862
|
+
Object.assign(result, root.def ?? root.schema);
|
|
7863
|
+
// build defs object
|
|
7864
|
+
const defs = ctx.external?.defs ?? {};
|
|
7865
|
+
for (const entry of ctx.seen.entries()) {
|
|
7866
|
+
const seen = entry[1];
|
|
7867
|
+
if (seen.def && seen.defId) {
|
|
7868
|
+
defs[seen.defId] = seen.def;
|
|
7869
|
+
}
|
|
7870
|
+
}
|
|
7871
|
+
// set definitions in result
|
|
7872
|
+
if (ctx.external) ;
|
|
7873
|
+
else {
|
|
7874
|
+
if (Object.keys(defs).length > 0) {
|
|
7875
|
+
if (ctx.target === "draft-2020-12") {
|
|
7876
|
+
result.$defs = defs;
|
|
7877
|
+
}
|
|
7878
|
+
else {
|
|
7879
|
+
result.definitions = defs;
|
|
7880
|
+
}
|
|
7881
|
+
}
|
|
7882
|
+
}
|
|
7883
|
+
try {
|
|
7884
|
+
// this "finalizes" this schema and ensures all cycles are removed
|
|
7885
|
+
// each call to finalize() is functionally independent
|
|
7886
|
+
// though the seen map is shared
|
|
7887
|
+
const finalized = JSON.parse(JSON.stringify(result));
|
|
7888
|
+
Object.defineProperty(finalized, "~standard", {
|
|
7889
|
+
value: {
|
|
7890
|
+
...schema["~standard"],
|
|
7891
|
+
jsonSchema: {
|
|
7892
|
+
input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
|
|
7893
|
+
output: createStandardJSONSchemaMethod(schema, "output", ctx.processors),
|
|
7894
|
+
},
|
|
7895
|
+
},
|
|
7896
|
+
enumerable: false,
|
|
7897
|
+
writable: false,
|
|
7898
|
+
});
|
|
7899
|
+
return finalized;
|
|
7900
|
+
}
|
|
7901
|
+
catch (_err) {
|
|
7902
|
+
throw new Error("Error converting schema to JSON.");
|
|
7903
|
+
}
|
|
7904
|
+
}
|
|
7905
|
+
function isTransforming(_schema, _ctx) {
|
|
7906
|
+
const ctx = _ctx ?? { seen: new Set() };
|
|
7907
|
+
if (ctx.seen.has(_schema))
|
|
7908
|
+
return false;
|
|
7909
|
+
ctx.seen.add(_schema);
|
|
7910
|
+
const def = _schema._zod.def;
|
|
7911
|
+
if (def.type === "transform")
|
|
7912
|
+
return true;
|
|
7913
|
+
if (def.type === "array")
|
|
7914
|
+
return isTransforming(def.element, ctx);
|
|
7915
|
+
if (def.type === "set")
|
|
7916
|
+
return isTransforming(def.valueType, ctx);
|
|
7917
|
+
if (def.type === "lazy")
|
|
7918
|
+
return isTransforming(def.getter(), ctx);
|
|
7919
|
+
if (def.type === "promise" ||
|
|
7920
|
+
def.type === "optional" ||
|
|
7921
|
+
def.type === "nonoptional" ||
|
|
7922
|
+
def.type === "nullable" ||
|
|
7923
|
+
def.type === "readonly" ||
|
|
7924
|
+
def.type === "default" ||
|
|
7925
|
+
def.type === "prefault") {
|
|
7926
|
+
return isTransforming(def.innerType, ctx);
|
|
7927
|
+
}
|
|
7928
|
+
if (def.type === "intersection") {
|
|
7929
|
+
return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
|
|
7930
|
+
}
|
|
7931
|
+
if (def.type === "record" || def.type === "map") {
|
|
7932
|
+
return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
|
|
7933
|
+
}
|
|
7934
|
+
if (def.type === "pipe") {
|
|
7935
|
+
return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
|
|
7936
|
+
}
|
|
7937
|
+
if (def.type === "object") {
|
|
7938
|
+
for (const key in def.shape) {
|
|
7939
|
+
if (isTransforming(def.shape[key], ctx))
|
|
7940
|
+
return true;
|
|
7941
|
+
}
|
|
7942
|
+
return false;
|
|
7943
|
+
}
|
|
7944
|
+
if (def.type === "union") {
|
|
7945
|
+
for (const option of def.options) {
|
|
7946
|
+
if (isTransforming(option, ctx))
|
|
7947
|
+
return true;
|
|
7948
|
+
}
|
|
7949
|
+
return false;
|
|
7950
|
+
}
|
|
7951
|
+
if (def.type === "tuple") {
|
|
7952
|
+
for (const item of def.items) {
|
|
7953
|
+
if (isTransforming(item, ctx))
|
|
7954
|
+
return true;
|
|
7955
|
+
}
|
|
7956
|
+
if (def.rest && isTransforming(def.rest, ctx))
|
|
7957
|
+
return true;
|
|
7958
|
+
return false;
|
|
7959
|
+
}
|
|
7960
|
+
return false;
|
|
7961
|
+
}
|
|
7962
|
+
const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
|
|
7963
|
+
const { libraryOptions, target } = params ?? {};
|
|
7964
|
+
const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });
|
|
7965
|
+
process$1(schema, ctx);
|
|
7966
|
+
extractDefs(ctx, schema);
|
|
7967
|
+
return finalize(ctx, schema);
|
|
7968
|
+
};
|
|
7969
|
+
|
|
7970
|
+
const formatMap = {
|
|
7971
|
+
guid: "uuid",
|
|
7972
|
+
url: "uri",
|
|
7973
|
+
datetime: "date-time",
|
|
7974
|
+
json_string: "json-string",
|
|
7975
|
+
regex: "", // do not set
|
|
7976
|
+
};
|
|
7977
|
+
// ==================== SIMPLE TYPE PROCESSORS ====================
|
|
7978
|
+
const stringProcessor = (schema, ctx, _json, _params) => {
|
|
7979
|
+
const json = _json;
|
|
7980
|
+
json.type = "string";
|
|
7981
|
+
const { minimum, maximum, format, patterns, contentEncoding } = schema._zod
|
|
7982
|
+
.bag;
|
|
7983
|
+
if (typeof minimum === "number")
|
|
7984
|
+
json.minLength = minimum;
|
|
7985
|
+
if (typeof maximum === "number")
|
|
7986
|
+
json.maxLength = maximum;
|
|
7987
|
+
// custom pattern overrides format
|
|
7988
|
+
if (format) {
|
|
7989
|
+
json.format = formatMap[format] ?? format;
|
|
7990
|
+
if (json.format === "")
|
|
7991
|
+
delete json.format; // empty format is not valid
|
|
7992
|
+
// JSON Schema format: "time" requires a full time with offset or Z
|
|
7993
|
+
// z.iso.time() does not include timezone information, so format: "time" should never be used
|
|
7994
|
+
if (format === "time") {
|
|
7995
|
+
delete json.format;
|
|
7996
|
+
}
|
|
7997
|
+
}
|
|
7998
|
+
if (contentEncoding)
|
|
7999
|
+
json.contentEncoding = contentEncoding;
|
|
8000
|
+
if (patterns && patterns.size > 0) {
|
|
8001
|
+
const regexes = [...patterns];
|
|
8002
|
+
if (regexes.length === 1)
|
|
8003
|
+
json.pattern = regexes[0].source;
|
|
8004
|
+
else if (regexes.length > 1) {
|
|
8005
|
+
json.allOf = [
|
|
8006
|
+
...regexes.map((regex) => ({
|
|
8007
|
+
...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0"
|
|
8008
|
+
? { type: "string" }
|
|
8009
|
+
: {}),
|
|
8010
|
+
pattern: regex.source,
|
|
8011
|
+
})),
|
|
8012
|
+
];
|
|
8013
|
+
}
|
|
8014
|
+
}
|
|
8015
|
+
};
|
|
8016
|
+
const numberProcessor = (schema, ctx, _json, _params) => {
|
|
8017
|
+
const json = _json;
|
|
8018
|
+
const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
|
|
8019
|
+
if (typeof format === "string" && format.includes("int"))
|
|
8020
|
+
json.type = "integer";
|
|
8021
|
+
else
|
|
8022
|
+
json.type = "number";
|
|
8023
|
+
if (typeof exclusiveMinimum === "number") {
|
|
8024
|
+
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
|
|
8025
|
+
json.minimum = exclusiveMinimum;
|
|
8026
|
+
json.exclusiveMinimum = true;
|
|
8027
|
+
}
|
|
8028
|
+
else {
|
|
8029
|
+
json.exclusiveMinimum = exclusiveMinimum;
|
|
8030
|
+
}
|
|
8031
|
+
}
|
|
8032
|
+
if (typeof minimum === "number") {
|
|
8033
|
+
json.minimum = minimum;
|
|
8034
|
+
if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") {
|
|
8035
|
+
if (exclusiveMinimum >= minimum)
|
|
8036
|
+
delete json.minimum;
|
|
8037
|
+
else
|
|
8038
|
+
delete json.exclusiveMinimum;
|
|
8039
|
+
}
|
|
8040
|
+
}
|
|
8041
|
+
if (typeof exclusiveMaximum === "number") {
|
|
8042
|
+
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
|
|
8043
|
+
json.maximum = exclusiveMaximum;
|
|
8044
|
+
json.exclusiveMaximum = true;
|
|
8045
|
+
}
|
|
8046
|
+
else {
|
|
8047
|
+
json.exclusiveMaximum = exclusiveMaximum;
|
|
8048
|
+
}
|
|
8049
|
+
}
|
|
8050
|
+
if (typeof maximum === "number") {
|
|
8051
|
+
json.maximum = maximum;
|
|
8052
|
+
if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") {
|
|
8053
|
+
if (exclusiveMaximum <= maximum)
|
|
8054
|
+
delete json.maximum;
|
|
8055
|
+
else
|
|
8056
|
+
delete json.exclusiveMaximum;
|
|
8057
|
+
}
|
|
8058
|
+
}
|
|
8059
|
+
if (typeof multipleOf === "number")
|
|
8060
|
+
json.multipleOf = multipleOf;
|
|
8061
|
+
};
|
|
8062
|
+
const booleanProcessor = (_schema, _ctx, json, _params) => {
|
|
8063
|
+
json.type = "boolean";
|
|
8064
|
+
};
|
|
8065
|
+
const bigintProcessor = (_schema, ctx, _json, _params) => {
|
|
8066
|
+
if (ctx.unrepresentable === "throw") {
|
|
8067
|
+
throw new Error("BigInt cannot be represented in JSON Schema");
|
|
8068
|
+
}
|
|
8069
|
+
};
|
|
8070
|
+
const symbolProcessor = (_schema, ctx, _json, _params) => {
|
|
8071
|
+
if (ctx.unrepresentable === "throw") {
|
|
8072
|
+
throw new Error("Symbols cannot be represented in JSON Schema");
|
|
8073
|
+
}
|
|
8074
|
+
};
|
|
8075
|
+
const nullProcessor = (_schema, ctx, json, _params) => {
|
|
8076
|
+
if (ctx.target === "openapi-3.0") {
|
|
8077
|
+
json.type = "string";
|
|
8078
|
+
json.nullable = true;
|
|
8079
|
+
json.enum = [null];
|
|
8080
|
+
}
|
|
8081
|
+
else {
|
|
8082
|
+
json.type = "null";
|
|
8083
|
+
}
|
|
8084
|
+
};
|
|
8085
|
+
const undefinedProcessor = (_schema, ctx, _json, _params) => {
|
|
8086
|
+
if (ctx.unrepresentable === "throw") {
|
|
8087
|
+
throw new Error("Undefined cannot be represented in JSON Schema");
|
|
8088
|
+
}
|
|
8089
|
+
};
|
|
8090
|
+
const voidProcessor = (_schema, ctx, _json, _params) => {
|
|
8091
|
+
if (ctx.unrepresentable === "throw") {
|
|
8092
|
+
throw new Error("Void cannot be represented in JSON Schema");
|
|
8093
|
+
}
|
|
8094
|
+
};
|
|
8095
|
+
const neverProcessor = (_schema, _ctx, json, _params) => {
|
|
8096
|
+
json.not = {};
|
|
8097
|
+
};
|
|
8098
|
+
const anyProcessor = (_schema, _ctx, _json, _params) => {
|
|
8099
|
+
// empty schema accepts anything
|
|
8100
|
+
};
|
|
8101
|
+
const unknownProcessor = (_schema, _ctx, _json, _params) => {
|
|
8102
|
+
// empty schema accepts anything
|
|
8103
|
+
};
|
|
8104
|
+
const dateProcessor = (_schema, ctx, _json, _params) => {
|
|
8105
|
+
if (ctx.unrepresentable === "throw") {
|
|
8106
|
+
throw new Error("Date cannot be represented in JSON Schema");
|
|
8107
|
+
}
|
|
8108
|
+
};
|
|
8109
|
+
const enumProcessor = (schema, _ctx, json, _params) => {
|
|
8110
|
+
const def = schema._zod.def;
|
|
8111
|
+
const values = getEnumValues(def.entries);
|
|
8112
|
+
// Number enums can have both string and number values
|
|
8113
|
+
if (values.every((v) => typeof v === "number"))
|
|
8114
|
+
json.type = "number";
|
|
8115
|
+
if (values.every((v) => typeof v === "string"))
|
|
8116
|
+
json.type = "string";
|
|
8117
|
+
json.enum = values;
|
|
8118
|
+
};
|
|
8119
|
+
const literalProcessor = (schema, ctx, json, _params) => {
|
|
8120
|
+
const def = schema._zod.def;
|
|
8121
|
+
const vals = [];
|
|
8122
|
+
for (const val of def.values) {
|
|
8123
|
+
if (val === undefined) {
|
|
8124
|
+
if (ctx.unrepresentable === "throw") {
|
|
8125
|
+
throw new Error("Literal `undefined` cannot be represented in JSON Schema");
|
|
8126
|
+
}
|
|
8127
|
+
}
|
|
8128
|
+
else if (typeof val === "bigint") {
|
|
8129
|
+
if (ctx.unrepresentable === "throw") {
|
|
8130
|
+
throw new Error("BigInt literals cannot be represented in JSON Schema");
|
|
8131
|
+
}
|
|
8132
|
+
else {
|
|
8133
|
+
vals.push(Number(val));
|
|
8134
|
+
}
|
|
8135
|
+
}
|
|
8136
|
+
else {
|
|
8137
|
+
vals.push(val);
|
|
8138
|
+
}
|
|
8139
|
+
}
|
|
8140
|
+
if (vals.length === 0) ;
|
|
8141
|
+
else if (vals.length === 1) {
|
|
8142
|
+
const val = vals[0];
|
|
8143
|
+
json.type = val === null ? "null" : typeof val;
|
|
8144
|
+
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
|
|
8145
|
+
json.enum = [val];
|
|
8146
|
+
}
|
|
8147
|
+
else {
|
|
8148
|
+
json.const = val;
|
|
8149
|
+
}
|
|
8150
|
+
}
|
|
8151
|
+
else {
|
|
8152
|
+
if (vals.every((v) => typeof v === "number"))
|
|
8153
|
+
json.type = "number";
|
|
8154
|
+
if (vals.every((v) => typeof v === "string"))
|
|
8155
|
+
json.type = "string";
|
|
8156
|
+
if (vals.every((v) => typeof v === "boolean"))
|
|
8157
|
+
json.type = "boolean";
|
|
8158
|
+
if (vals.every((v) => v === null))
|
|
8159
|
+
json.type = "null";
|
|
8160
|
+
json.enum = vals;
|
|
8161
|
+
}
|
|
8162
|
+
};
|
|
8163
|
+
const nanProcessor = (_schema, ctx, _json, _params) => {
|
|
8164
|
+
if (ctx.unrepresentable === "throw") {
|
|
8165
|
+
throw new Error("NaN cannot be represented in JSON Schema");
|
|
8166
|
+
}
|
|
8167
|
+
};
|
|
8168
|
+
const templateLiteralProcessor = (schema, _ctx, json, _params) => {
|
|
8169
|
+
const _json = json;
|
|
8170
|
+
const pattern = schema._zod.pattern;
|
|
8171
|
+
if (!pattern)
|
|
8172
|
+
throw new Error("Pattern not found in template literal");
|
|
8173
|
+
_json.type = "string";
|
|
8174
|
+
_json.pattern = pattern.source;
|
|
8175
|
+
};
|
|
8176
|
+
const fileProcessor = (schema, _ctx, json, _params) => {
|
|
8177
|
+
const _json = json;
|
|
8178
|
+
const file = {
|
|
8179
|
+
type: "string",
|
|
8180
|
+
format: "binary",
|
|
8181
|
+
contentEncoding: "binary",
|
|
8182
|
+
};
|
|
8183
|
+
const { minimum, maximum, mime } = schema._zod.bag;
|
|
8184
|
+
if (minimum !== undefined)
|
|
8185
|
+
file.minLength = minimum;
|
|
8186
|
+
if (maximum !== undefined)
|
|
8187
|
+
file.maxLength = maximum;
|
|
8188
|
+
if (mime) {
|
|
8189
|
+
if (mime.length === 1) {
|
|
8190
|
+
file.contentMediaType = mime[0];
|
|
8191
|
+
Object.assign(_json, file);
|
|
8192
|
+
}
|
|
8193
|
+
else {
|
|
8194
|
+
Object.assign(_json, file); // shared props at root
|
|
8195
|
+
_json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs
|
|
8196
|
+
}
|
|
8197
|
+
}
|
|
8198
|
+
else {
|
|
8199
|
+
Object.assign(_json, file);
|
|
8200
|
+
}
|
|
8201
|
+
};
|
|
8202
|
+
const successProcessor = (_schema, _ctx, json, _params) => {
|
|
8203
|
+
json.type = "boolean";
|
|
8204
|
+
};
|
|
8205
|
+
const customProcessor = (_schema, ctx, _json, _params) => {
|
|
8206
|
+
if (ctx.unrepresentable === "throw") {
|
|
8207
|
+
throw new Error("Custom types cannot be represented in JSON Schema");
|
|
8208
|
+
}
|
|
8209
|
+
};
|
|
8210
|
+
const functionProcessor = (_schema, ctx, _json, _params) => {
|
|
8211
|
+
if (ctx.unrepresentable === "throw") {
|
|
8212
|
+
throw new Error("Function types cannot be represented in JSON Schema");
|
|
8213
|
+
}
|
|
8214
|
+
};
|
|
8215
|
+
const transformProcessor = (_schema, ctx, _json, _params) => {
|
|
8216
|
+
if (ctx.unrepresentable === "throw") {
|
|
8217
|
+
throw new Error("Transforms cannot be represented in JSON Schema");
|
|
8218
|
+
}
|
|
8219
|
+
};
|
|
8220
|
+
const mapProcessor = (_schema, ctx, _json, _params) => {
|
|
8221
|
+
if (ctx.unrepresentable === "throw") {
|
|
8222
|
+
throw new Error("Map cannot be represented in JSON Schema");
|
|
8223
|
+
}
|
|
8224
|
+
};
|
|
8225
|
+
const setProcessor = (_schema, ctx, _json, _params) => {
|
|
8226
|
+
if (ctx.unrepresentable === "throw") {
|
|
8227
|
+
throw new Error("Set cannot be represented in JSON Schema");
|
|
8228
|
+
}
|
|
8229
|
+
};
|
|
8230
|
+
// ==================== COMPOSITE TYPE PROCESSORS ====================
|
|
8231
|
+
const arrayProcessor = (schema, ctx, _json, params) => {
|
|
8232
|
+
const json = _json;
|
|
8233
|
+
const def = schema._zod.def;
|
|
8234
|
+
const { minimum, maximum } = schema._zod.bag;
|
|
8235
|
+
if (typeof minimum === "number")
|
|
8236
|
+
json.minItems = minimum;
|
|
8237
|
+
if (typeof maximum === "number")
|
|
8238
|
+
json.maxItems = maximum;
|
|
8239
|
+
json.type = "array";
|
|
8240
|
+
json.items = process$1(def.element, ctx, { ...params, path: [...params.path, "items"] });
|
|
8241
|
+
};
|
|
8242
|
+
const objectProcessor = (schema, ctx, _json, params) => {
|
|
8243
|
+
const json = _json;
|
|
8244
|
+
const def = schema._zod.def;
|
|
8245
|
+
json.type = "object";
|
|
8246
|
+
json.properties = {};
|
|
8247
|
+
const shape = def.shape;
|
|
8248
|
+
for (const key in shape) {
|
|
8249
|
+
json.properties[key] = process$1(shape[key], ctx, {
|
|
8250
|
+
...params,
|
|
8251
|
+
path: [...params.path, "properties", key],
|
|
8252
|
+
});
|
|
8253
|
+
}
|
|
8254
|
+
// required keys
|
|
8255
|
+
const allKeys = new Set(Object.keys(shape));
|
|
8256
|
+
const requiredKeys = new Set([...allKeys].filter((key) => {
|
|
8257
|
+
const v = def.shape[key]._zod;
|
|
8258
|
+
if (ctx.io === "input") {
|
|
8259
|
+
return v.optin === undefined;
|
|
8260
|
+
}
|
|
8261
|
+
else {
|
|
8262
|
+
return v.optout === undefined;
|
|
8263
|
+
}
|
|
8264
|
+
}));
|
|
8265
|
+
if (requiredKeys.size > 0) {
|
|
8266
|
+
json.required = Array.from(requiredKeys);
|
|
8267
|
+
}
|
|
8268
|
+
// catchall
|
|
8269
|
+
if (def.catchall?._zod.def.type === "never") {
|
|
8270
|
+
// strict
|
|
8271
|
+
json.additionalProperties = false;
|
|
8272
|
+
}
|
|
8273
|
+
else if (!def.catchall) {
|
|
8274
|
+
// regular
|
|
8275
|
+
if (ctx.io === "output")
|
|
8276
|
+
json.additionalProperties = false;
|
|
8277
|
+
}
|
|
8278
|
+
else if (def.catchall) {
|
|
8279
|
+
json.additionalProperties = process$1(def.catchall, ctx, {
|
|
8280
|
+
...params,
|
|
8281
|
+
path: [...params.path, "additionalProperties"],
|
|
8282
|
+
});
|
|
8283
|
+
}
|
|
8284
|
+
};
|
|
8285
|
+
const unionProcessor = (schema, ctx, json, params) => {
|
|
8286
|
+
const def = schema._zod.def;
|
|
8287
|
+
// Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)
|
|
8288
|
+
// This includes both z.xor() and discriminated unions
|
|
8289
|
+
const isExclusive = def.inclusive === false;
|
|
8290
|
+
const options = def.options.map((x, i) => process$1(x, ctx, {
|
|
8291
|
+
...params,
|
|
8292
|
+
path: [...params.path, isExclusive ? "oneOf" : "anyOf", i],
|
|
8293
|
+
}));
|
|
8294
|
+
if (isExclusive) {
|
|
8295
|
+
json.oneOf = options;
|
|
8296
|
+
}
|
|
8297
|
+
else {
|
|
8298
|
+
json.anyOf = options;
|
|
8299
|
+
}
|
|
8300
|
+
};
|
|
8301
|
+
const intersectionProcessor = (schema, ctx, json, params) => {
|
|
8302
|
+
const def = schema._zod.def;
|
|
8303
|
+
const a = process$1(def.left, ctx, {
|
|
8304
|
+
...params,
|
|
8305
|
+
path: [...params.path, "allOf", 0],
|
|
8306
|
+
});
|
|
8307
|
+
const b = process$1(def.right, ctx, {
|
|
8308
|
+
...params,
|
|
8309
|
+
path: [...params.path, "allOf", 1],
|
|
8310
|
+
});
|
|
8311
|
+
const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
|
|
8312
|
+
const allOf = [
|
|
8313
|
+
...(isSimpleIntersection(a) ? a.allOf : [a]),
|
|
8314
|
+
...(isSimpleIntersection(b) ? b.allOf : [b]),
|
|
8315
|
+
];
|
|
8316
|
+
json.allOf = allOf;
|
|
8317
|
+
};
|
|
8318
|
+
const tupleProcessor = (schema, ctx, _json, params) => {
|
|
8319
|
+
const json = _json;
|
|
8320
|
+
const def = schema._zod.def;
|
|
8321
|
+
json.type = "array";
|
|
8322
|
+
const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
|
|
8323
|
+
const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
|
|
8324
|
+
const prefixItems = def.items.map((x, i) => process$1(x, ctx, {
|
|
8325
|
+
...params,
|
|
8326
|
+
path: [...params.path, prefixPath, i],
|
|
8327
|
+
}));
|
|
8328
|
+
const rest = def.rest
|
|
8329
|
+
? process$1(def.rest, ctx, {
|
|
8330
|
+
...params,
|
|
8331
|
+
path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])],
|
|
8332
|
+
})
|
|
8333
|
+
: null;
|
|
8334
|
+
if (ctx.target === "draft-2020-12") {
|
|
8335
|
+
json.prefixItems = prefixItems;
|
|
8336
|
+
if (rest) {
|
|
8337
|
+
json.items = rest;
|
|
8338
|
+
}
|
|
8339
|
+
}
|
|
8340
|
+
else if (ctx.target === "openapi-3.0") {
|
|
8341
|
+
json.items = {
|
|
8342
|
+
anyOf: prefixItems,
|
|
8343
|
+
};
|
|
8344
|
+
if (rest) {
|
|
8345
|
+
json.items.anyOf.push(rest);
|
|
8346
|
+
}
|
|
8347
|
+
json.minItems = prefixItems.length;
|
|
8348
|
+
if (!rest) {
|
|
8349
|
+
json.maxItems = prefixItems.length;
|
|
8350
|
+
}
|
|
8351
|
+
}
|
|
8352
|
+
else {
|
|
8353
|
+
json.items = prefixItems;
|
|
8354
|
+
if (rest) {
|
|
8355
|
+
json.additionalItems = rest;
|
|
8356
|
+
}
|
|
8357
|
+
}
|
|
8358
|
+
// length
|
|
8359
|
+
const { minimum, maximum } = schema._zod.bag;
|
|
8360
|
+
if (typeof minimum === "number")
|
|
8361
|
+
json.minItems = minimum;
|
|
8362
|
+
if (typeof maximum === "number")
|
|
8363
|
+
json.maxItems = maximum;
|
|
8364
|
+
};
|
|
8365
|
+
const recordProcessor = (schema, ctx, _json, params) => {
|
|
8366
|
+
const json = _json;
|
|
8367
|
+
const def = schema._zod.def;
|
|
8368
|
+
json.type = "object";
|
|
8369
|
+
// For looseRecord with regex patterns, use patternProperties
|
|
8370
|
+
// This correctly represents "only validate keys matching the pattern" semantics
|
|
8371
|
+
// and composes well with allOf (intersections)
|
|
8372
|
+
const keyType = def.keyType;
|
|
8373
|
+
const keyBag = keyType._zod.bag;
|
|
8374
|
+
const patterns = keyBag?.patterns;
|
|
8375
|
+
if (def.mode === "loose" && patterns && patterns.size > 0) {
|
|
8376
|
+
// Use patternProperties for looseRecord with regex patterns
|
|
8377
|
+
const valueSchema = process$1(def.valueType, ctx, {
|
|
8378
|
+
...params,
|
|
8379
|
+
path: [...params.path, "patternProperties", "*"],
|
|
8380
|
+
});
|
|
8381
|
+
json.patternProperties = {};
|
|
8382
|
+
for (const pattern of patterns) {
|
|
8383
|
+
json.patternProperties[pattern.source] = valueSchema;
|
|
8384
|
+
}
|
|
8385
|
+
}
|
|
8386
|
+
else {
|
|
8387
|
+
// Default behavior: use propertyNames + additionalProperties
|
|
8388
|
+
if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
|
|
8389
|
+
json.propertyNames = process$1(def.keyType, ctx, {
|
|
8390
|
+
...params,
|
|
8391
|
+
path: [...params.path, "propertyNames"],
|
|
8392
|
+
});
|
|
8393
|
+
}
|
|
8394
|
+
json.additionalProperties = process$1(def.valueType, ctx, {
|
|
8395
|
+
...params,
|
|
8396
|
+
path: [...params.path, "additionalProperties"],
|
|
8397
|
+
});
|
|
8398
|
+
}
|
|
8399
|
+
// Add required for keys with discrete values (enum, literal, etc.)
|
|
8400
|
+
const keyValues = keyType._zod.values;
|
|
8401
|
+
if (keyValues) {
|
|
8402
|
+
const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
|
|
8403
|
+
if (validKeyValues.length > 0) {
|
|
8404
|
+
json.required = validKeyValues;
|
|
8405
|
+
}
|
|
8406
|
+
}
|
|
8407
|
+
};
|
|
8408
|
+
const nullableProcessor = (schema, ctx, json, params) => {
|
|
8409
|
+
const def = schema._zod.def;
|
|
8410
|
+
const inner = process$1(def.innerType, ctx, params);
|
|
8411
|
+
const seen = ctx.seen.get(schema);
|
|
8412
|
+
if (ctx.target === "openapi-3.0") {
|
|
8413
|
+
seen.ref = def.innerType;
|
|
8414
|
+
json.nullable = true;
|
|
8415
|
+
}
|
|
8416
|
+
else {
|
|
8417
|
+
json.anyOf = [inner, { type: "null" }];
|
|
8418
|
+
}
|
|
8419
|
+
};
|
|
8420
|
+
const nonoptionalProcessor = (schema, ctx, _json, params) => {
|
|
8421
|
+
const def = schema._zod.def;
|
|
8422
|
+
process$1(def.innerType, ctx, params);
|
|
8423
|
+
const seen = ctx.seen.get(schema);
|
|
8424
|
+
seen.ref = def.innerType;
|
|
8425
|
+
};
|
|
8426
|
+
const defaultProcessor = (schema, ctx, json, params) => {
|
|
8427
|
+
const def = schema._zod.def;
|
|
8428
|
+
process$1(def.innerType, ctx, params);
|
|
8429
|
+
const seen = ctx.seen.get(schema);
|
|
8430
|
+
seen.ref = def.innerType;
|
|
8431
|
+
json.default = JSON.parse(JSON.stringify(def.defaultValue));
|
|
8432
|
+
};
|
|
8433
|
+
const prefaultProcessor = (schema, ctx, json, params) => {
|
|
8434
|
+
const def = schema._zod.def;
|
|
8435
|
+
process$1(def.innerType, ctx, params);
|
|
8436
|
+
const seen = ctx.seen.get(schema);
|
|
8437
|
+
seen.ref = def.innerType;
|
|
8438
|
+
if (ctx.io === "input")
|
|
8439
|
+
json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
|
|
8440
|
+
};
|
|
8441
|
+
const catchProcessor = (schema, ctx, json, params) => {
|
|
8442
|
+
const def = schema._zod.def;
|
|
8443
|
+
process$1(def.innerType, ctx, params);
|
|
8444
|
+
const seen = ctx.seen.get(schema);
|
|
8445
|
+
seen.ref = def.innerType;
|
|
8446
|
+
let catchValue;
|
|
8447
|
+
try {
|
|
8448
|
+
catchValue = def.catchValue(undefined);
|
|
8449
|
+
}
|
|
8450
|
+
catch {
|
|
8451
|
+
throw new Error("Dynamic catch values are not supported in JSON Schema");
|
|
8452
|
+
}
|
|
8453
|
+
json.default = catchValue;
|
|
8454
|
+
};
|
|
8455
|
+
const pipeProcessor = (schema, ctx, _json, params) => {
|
|
8456
|
+
const def = schema._zod.def;
|
|
8457
|
+
const innerType = ctx.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out;
|
|
8458
|
+
process$1(innerType, ctx, params);
|
|
8459
|
+
const seen = ctx.seen.get(schema);
|
|
8460
|
+
seen.ref = innerType;
|
|
8461
|
+
};
|
|
8462
|
+
const readonlyProcessor = (schema, ctx, json, params) => {
|
|
8463
|
+
const def = schema._zod.def;
|
|
8464
|
+
process$1(def.innerType, ctx, params);
|
|
8465
|
+
const seen = ctx.seen.get(schema);
|
|
8466
|
+
seen.ref = def.innerType;
|
|
8467
|
+
json.readOnly = true;
|
|
8468
|
+
};
|
|
8469
|
+
const promiseProcessor = (schema, ctx, _json, params) => {
|
|
8470
|
+
const def = schema._zod.def;
|
|
8471
|
+
process$1(def.innerType, ctx, params);
|
|
8472
|
+
const seen = ctx.seen.get(schema);
|
|
8473
|
+
seen.ref = def.innerType;
|
|
8474
|
+
};
|
|
8475
|
+
const optionalProcessor = (schema, ctx, _json, params) => {
|
|
8476
|
+
const def = schema._zod.def;
|
|
8477
|
+
process$1(def.innerType, ctx, params);
|
|
8478
|
+
const seen = ctx.seen.get(schema);
|
|
8479
|
+
seen.ref = def.innerType;
|
|
8480
|
+
};
|
|
8481
|
+
const lazyProcessor = (schema, ctx, _json, params) => {
|
|
8482
|
+
const innerType = schema._zod.innerType;
|
|
8483
|
+
process$1(innerType, ctx, params);
|
|
8484
|
+
const seen = ctx.seen.get(schema);
|
|
8485
|
+
seen.ref = innerType;
|
|
8486
|
+
};
|
|
8487
|
+
// ==================== ALL PROCESSORS ====================
|
|
8488
|
+
const allProcessors = {
|
|
8489
|
+
string: stringProcessor,
|
|
8490
|
+
number: numberProcessor,
|
|
8491
|
+
boolean: booleanProcessor,
|
|
8492
|
+
bigint: bigintProcessor,
|
|
8493
|
+
symbol: symbolProcessor,
|
|
8494
|
+
null: nullProcessor,
|
|
8495
|
+
undefined: undefinedProcessor,
|
|
8496
|
+
void: voidProcessor,
|
|
8497
|
+
never: neverProcessor,
|
|
8498
|
+
any: anyProcessor,
|
|
8499
|
+
unknown: unknownProcessor,
|
|
8500
|
+
date: dateProcessor,
|
|
8501
|
+
enum: enumProcessor,
|
|
8502
|
+
literal: literalProcessor,
|
|
8503
|
+
nan: nanProcessor,
|
|
8504
|
+
template_literal: templateLiteralProcessor,
|
|
8505
|
+
file: fileProcessor,
|
|
8506
|
+
success: successProcessor,
|
|
8507
|
+
custom: customProcessor,
|
|
8508
|
+
function: functionProcessor,
|
|
8509
|
+
transform: transformProcessor,
|
|
8510
|
+
map: mapProcessor,
|
|
8511
|
+
set: setProcessor,
|
|
8512
|
+
array: arrayProcessor,
|
|
8513
|
+
object: objectProcessor,
|
|
8514
|
+
union: unionProcessor,
|
|
8515
|
+
intersection: intersectionProcessor,
|
|
8516
|
+
tuple: tupleProcessor,
|
|
8517
|
+
record: recordProcessor,
|
|
8518
|
+
nullable: nullableProcessor,
|
|
8519
|
+
nonoptional: nonoptionalProcessor,
|
|
8520
|
+
default: defaultProcessor,
|
|
8521
|
+
prefault: prefaultProcessor,
|
|
8522
|
+
catch: catchProcessor,
|
|
8523
|
+
pipe: pipeProcessor,
|
|
8524
|
+
readonly: readonlyProcessor,
|
|
8525
|
+
promise: promiseProcessor,
|
|
8526
|
+
optional: optionalProcessor,
|
|
8527
|
+
lazy: lazyProcessor,
|
|
8528
|
+
};
|
|
8529
|
+
function toJSONSchema(input, params) {
|
|
8530
|
+
if ("_idmap" in input) {
|
|
8531
|
+
// Registry case
|
|
8532
|
+
const registry = input;
|
|
8533
|
+
const ctx = initializeContext({ ...params, processors: allProcessors });
|
|
8534
|
+
const defs = {};
|
|
8535
|
+
// First pass: process all schemas to build the seen map
|
|
8536
|
+
for (const entry of registry._idmap.entries()) {
|
|
8537
|
+
const [_, schema] = entry;
|
|
8538
|
+
process$1(schema, ctx);
|
|
8539
|
+
}
|
|
8540
|
+
const schemas = {};
|
|
8541
|
+
const external = {
|
|
8542
|
+
registry,
|
|
8543
|
+
uri: params?.uri,
|
|
8544
|
+
defs,
|
|
8545
|
+
};
|
|
8546
|
+
// Update the context with external configuration
|
|
8547
|
+
ctx.external = external;
|
|
8548
|
+
// Second pass: emit each schema
|
|
8549
|
+
for (const entry of registry._idmap.entries()) {
|
|
8550
|
+
const [key, schema] = entry;
|
|
8551
|
+
extractDefs(ctx, schema);
|
|
8552
|
+
schemas[key] = finalize(ctx, schema);
|
|
8553
|
+
}
|
|
8554
|
+
if (Object.keys(defs).length > 0) {
|
|
8555
|
+
const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
|
|
8556
|
+
schemas.__shared = {
|
|
8557
|
+
[defsSegment]: defs,
|
|
8558
|
+
};
|
|
8559
|
+
}
|
|
8560
|
+
return { schemas };
|
|
8561
|
+
}
|
|
8562
|
+
// Single schema case
|
|
8563
|
+
const ctx = initializeContext({ ...params, processors: allProcessors });
|
|
8564
|
+
process$1(input, ctx);
|
|
8565
|
+
extractDefs(ctx, input);
|
|
8566
|
+
return finalize(ctx, input);
|
|
8567
|
+
}
|
|
8568
|
+
|
|
8569
|
+
const ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use');
|
|
8570
|
+
const defaultOptions = {
|
|
8571
|
+
name: undefined,
|
|
8572
|
+
$refStrategy: 'root',
|
|
8573
|
+
effectStrategy: 'input',
|
|
8574
|
+
pipeStrategy: 'all',
|
|
8575
|
+
dateStrategy: 'format:date-time',
|
|
8576
|
+
mapStrategy: 'entries',
|
|
8577
|
+
nullableStrategy: 'from-target',
|
|
8578
|
+
removeAdditionalStrategy: 'passthrough',
|
|
8579
|
+
definitionPath: 'definitions',
|
|
8580
|
+
target: 'jsonSchema7',
|
|
8581
|
+
strictUnions: false,
|
|
8582
|
+
errorMessages: false,
|
|
8583
|
+
markdownDescription: false,
|
|
8584
|
+
patternStrategy: 'escape',
|
|
8585
|
+
applyRegexFlags: false,
|
|
8586
|
+
emailStrategy: 'format:email',
|
|
8587
|
+
base64Strategy: 'contentEncoding:base64',
|
|
8588
|
+
nameStrategy: 'ref',
|
|
8589
|
+
};
|
|
8590
|
+
const getDefaultOptions = (options) => {
|
|
8591
|
+
// We need to add `definitions` here as we may mutate it
|
|
8592
|
+
return (typeof options === 'string' ?
|
|
8593
|
+
{
|
|
8594
|
+
...defaultOptions,
|
|
8595
|
+
basePath: ['#'],
|
|
8596
|
+
definitions: {},
|
|
8597
|
+
name: options,
|
|
8598
|
+
}
|
|
8599
|
+
: {
|
|
8600
|
+
...defaultOptions,
|
|
8601
|
+
basePath: ['#'],
|
|
8602
|
+
definitions: {},
|
|
8603
|
+
...options,
|
|
8604
|
+
});
|
|
8605
|
+
};
|
|
8606
|
+
|
|
8607
|
+
const zodDef = (zodSchema) => {
|
|
8608
|
+
return '_def' in zodSchema ? zodSchema._def : zodSchema;
|
|
8609
|
+
};
|
|
8610
|
+
function isEmptyObj(obj) {
|
|
8611
|
+
if (!obj)
|
|
8612
|
+
return true;
|
|
8613
|
+
for (const _k in obj)
|
|
8614
|
+
return false;
|
|
8615
|
+
return true;
|
|
8616
|
+
}
|
|
8617
|
+
|
|
8618
|
+
const getRefs = (options) => {
|
|
8619
|
+
const _options = getDefaultOptions(options);
|
|
8620
|
+
const currentPath = _options.name !== undefined ?
|
|
8621
|
+
[..._options.basePath, _options.definitionPath, _options.name]
|
|
8622
|
+
: _options.basePath;
|
|
8623
|
+
return {
|
|
8624
|
+
..._options,
|
|
8625
|
+
currentPath: currentPath,
|
|
8626
|
+
propertyPath: undefined,
|
|
8627
|
+
seenRefs: new Set(),
|
|
8628
|
+
seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
|
|
8629
|
+
zodDef(def),
|
|
8630
|
+
{
|
|
8631
|
+
def: zodDef(def),
|
|
8632
|
+
path: [..._options.basePath, _options.definitionPath, name],
|
|
8633
|
+
// Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
|
|
8634
|
+
jsonSchema: undefined,
|
|
8635
|
+
},
|
|
8636
|
+
])),
|
|
8637
|
+
};
|
|
8638
|
+
};
|
|
8639
|
+
|
|
8640
|
+
function addErrorMessage(res, key, errorMessage, refs) {
|
|
8641
|
+
if (!refs?.errorMessages)
|
|
8642
|
+
return;
|
|
8643
|
+
if (errorMessage) {
|
|
8644
|
+
res.errorMessage = {
|
|
8645
|
+
...res.errorMessage,
|
|
8646
|
+
[key]: errorMessage,
|
|
8647
|
+
};
|
|
8648
|
+
}
|
|
8649
|
+
}
|
|
8650
|
+
function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
|
|
8651
|
+
res[key] = value;
|
|
8652
|
+
addErrorMessage(res, key, errorMessage, refs);
|
|
8653
|
+
}
|
|
8654
|
+
|
|
8655
|
+
var util;
|
|
8656
|
+
(function (util) {
|
|
8657
|
+
util.assertEqual = (_) => { };
|
|
8658
|
+
function assertIs(_arg) { }
|
|
8659
|
+
util.assertIs = assertIs;
|
|
8660
|
+
function assertNever(_x) {
|
|
8661
|
+
throw new Error();
|
|
8662
|
+
}
|
|
8663
|
+
util.assertNever = assertNever;
|
|
8664
|
+
util.arrayToEnum = (items) => {
|
|
8665
|
+
const obj = {};
|
|
8666
|
+
for (const item of items) {
|
|
8667
|
+
obj[item] = item;
|
|
8668
|
+
}
|
|
8669
|
+
return obj;
|
|
8670
|
+
};
|
|
8671
|
+
util.getValidEnumValues = (obj) => {
|
|
8672
|
+
const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
|
|
8673
|
+
const filtered = {};
|
|
8674
|
+
for (const k of validKeys) {
|
|
8675
|
+
filtered[k] = obj[k];
|
|
8676
|
+
}
|
|
8677
|
+
return util.objectValues(filtered);
|
|
8678
|
+
};
|
|
8679
|
+
util.objectValues = (obj) => {
|
|
8680
|
+
return util.objectKeys(obj).map(function (e) {
|
|
8681
|
+
return obj[e];
|
|
8682
|
+
});
|
|
8683
|
+
};
|
|
8684
|
+
util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
|
|
8685
|
+
? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
|
|
8686
|
+
: (object) => {
|
|
8687
|
+
const keys = [];
|
|
8688
|
+
for (const key in object) {
|
|
8689
|
+
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
|
8690
|
+
keys.push(key);
|
|
8691
|
+
}
|
|
8692
|
+
}
|
|
8693
|
+
return keys;
|
|
8694
|
+
};
|
|
8695
|
+
util.find = (arr, checker) => {
|
|
8696
|
+
for (const item of arr) {
|
|
8697
|
+
if (checker(item))
|
|
8698
|
+
return item;
|
|
8699
|
+
}
|
|
8700
|
+
return undefined;
|
|
8701
|
+
};
|
|
8702
|
+
util.isInteger = typeof Number.isInteger === "function"
|
|
8703
|
+
? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
|
|
8704
|
+
: (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
|
|
8705
|
+
function joinValues(array, separator = " | ") {
|
|
8706
|
+
return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
|
|
8707
|
+
}
|
|
8708
|
+
util.joinValues = joinValues;
|
|
8709
|
+
util.jsonStringifyReplacer = (_, value) => {
|
|
8710
|
+
if (typeof value === "bigint") {
|
|
8711
|
+
return value.toString();
|
|
8712
|
+
}
|
|
8713
|
+
return value;
|
|
8714
|
+
};
|
|
8715
|
+
})(util || (util = {}));
|
|
8716
|
+
var objectUtil;
|
|
8717
|
+
(function (objectUtil) {
|
|
8718
|
+
objectUtil.mergeShapes = (first, second) => {
|
|
8719
|
+
return {
|
|
8720
|
+
...first,
|
|
8721
|
+
...second, // second overwrites first
|
|
8722
|
+
};
|
|
8723
|
+
};
|
|
8724
|
+
})(objectUtil || (objectUtil = {}));
|
|
8725
|
+
util.arrayToEnum([
|
|
8726
|
+
"string",
|
|
8727
|
+
"nan",
|
|
8728
|
+
"number",
|
|
8729
|
+
"integer",
|
|
8730
|
+
"float",
|
|
8731
|
+
"boolean",
|
|
8732
|
+
"date",
|
|
8733
|
+
"bigint",
|
|
8734
|
+
"symbol",
|
|
8735
|
+
"function",
|
|
8736
|
+
"undefined",
|
|
8737
|
+
"null",
|
|
8738
|
+
"array",
|
|
8739
|
+
"object",
|
|
8740
|
+
"unknown",
|
|
8741
|
+
"promise",
|
|
8742
|
+
"void",
|
|
8743
|
+
"never",
|
|
8744
|
+
"map",
|
|
8745
|
+
"set",
|
|
8746
|
+
]);
|
|
8747
|
+
|
|
8748
|
+
util.arrayToEnum([
|
|
8749
|
+
"invalid_type",
|
|
8750
|
+
"invalid_literal",
|
|
8751
|
+
"custom",
|
|
8752
|
+
"invalid_union",
|
|
8753
|
+
"invalid_union_discriminator",
|
|
8754
|
+
"invalid_enum_value",
|
|
8755
|
+
"unrecognized_keys",
|
|
8756
|
+
"invalid_arguments",
|
|
8757
|
+
"invalid_return_type",
|
|
8758
|
+
"invalid_date",
|
|
8759
|
+
"invalid_string",
|
|
8760
|
+
"too_small",
|
|
8761
|
+
"too_big",
|
|
8762
|
+
"invalid_intersection_types",
|
|
8763
|
+
"not_multiple_of",
|
|
8764
|
+
"not_finite",
|
|
8765
|
+
]);
|
|
8766
|
+
class ZodError extends Error {
|
|
8767
|
+
get errors() {
|
|
8768
|
+
return this.issues;
|
|
8769
|
+
}
|
|
8770
|
+
constructor(issues) {
|
|
8771
|
+
super();
|
|
8772
|
+
this.issues = [];
|
|
8773
|
+
this.addIssue = (sub) => {
|
|
8774
|
+
this.issues = [...this.issues, sub];
|
|
8775
|
+
};
|
|
8776
|
+
this.addIssues = (subs = []) => {
|
|
8777
|
+
this.issues = [...this.issues, ...subs];
|
|
8778
|
+
};
|
|
8779
|
+
const actualProto = new.target.prototype;
|
|
8780
|
+
if (Object.setPrototypeOf) {
|
|
8781
|
+
// eslint-disable-next-line ban/ban
|
|
8782
|
+
Object.setPrototypeOf(this, actualProto);
|
|
8783
|
+
}
|
|
8784
|
+
else {
|
|
8785
|
+
this.__proto__ = actualProto;
|
|
8786
|
+
}
|
|
8787
|
+
this.name = "ZodError";
|
|
8788
|
+
this.issues = issues;
|
|
8789
|
+
}
|
|
8790
|
+
format(_mapper) {
|
|
8791
|
+
const mapper = _mapper ||
|
|
8792
|
+
function (issue) {
|
|
8793
|
+
return issue.message;
|
|
8794
|
+
};
|
|
8795
|
+
const fieldErrors = { _errors: [] };
|
|
8796
|
+
const processError = (error) => {
|
|
8797
|
+
for (const issue of error.issues) {
|
|
8798
|
+
if (issue.code === "invalid_union") {
|
|
8799
|
+
issue.unionErrors.map(processError);
|
|
8800
|
+
}
|
|
8801
|
+
else if (issue.code === "invalid_return_type") {
|
|
8802
|
+
processError(issue.returnTypeError);
|
|
8803
|
+
}
|
|
8804
|
+
else if (issue.code === "invalid_arguments") {
|
|
8805
|
+
processError(issue.argumentsError);
|
|
8806
|
+
}
|
|
8807
|
+
else if (issue.path.length === 0) {
|
|
8808
|
+
fieldErrors._errors.push(mapper(issue));
|
|
8809
|
+
}
|
|
8810
|
+
else {
|
|
8811
|
+
let curr = fieldErrors;
|
|
8812
|
+
let i = 0;
|
|
8813
|
+
while (i < issue.path.length) {
|
|
8814
|
+
const el = issue.path[i];
|
|
8815
|
+
const terminal = i === issue.path.length - 1;
|
|
8816
|
+
if (!terminal) {
|
|
8817
|
+
curr[el] = curr[el] || { _errors: [] };
|
|
8818
|
+
// if (typeof el === "string") {
|
|
8819
|
+
// curr[el] = curr[el] || { _errors: [] };
|
|
8820
|
+
// } else if (typeof el === "number") {
|
|
8821
|
+
// const errorArray: any = [];
|
|
8822
|
+
// errorArray._errors = [];
|
|
8823
|
+
// curr[el] = curr[el] || errorArray;
|
|
8824
|
+
// }
|
|
8825
|
+
}
|
|
8826
|
+
else {
|
|
8827
|
+
curr[el] = curr[el] || { _errors: [] };
|
|
8828
|
+
curr[el]._errors.push(mapper(issue));
|
|
8829
|
+
}
|
|
8830
|
+
curr = curr[el];
|
|
8831
|
+
i++;
|
|
8832
|
+
}
|
|
8833
|
+
}
|
|
8834
|
+
}
|
|
8835
|
+
};
|
|
8836
|
+
processError(this);
|
|
8837
|
+
return fieldErrors;
|
|
8838
|
+
}
|
|
8839
|
+
static assert(value) {
|
|
8840
|
+
if (!(value instanceof ZodError)) {
|
|
8841
|
+
throw new Error(`Not a ZodError: ${value}`);
|
|
8842
|
+
}
|
|
8843
|
+
}
|
|
8844
|
+
toString() {
|
|
8845
|
+
return this.message;
|
|
8846
|
+
}
|
|
8847
|
+
get message() {
|
|
8848
|
+
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
|
|
8849
|
+
}
|
|
8850
|
+
get isEmpty() {
|
|
8851
|
+
return this.issues.length === 0;
|
|
8852
|
+
}
|
|
8853
|
+
flatten(mapper = (issue) => issue.message) {
|
|
8854
|
+
const fieldErrors = Object.create(null);
|
|
8855
|
+
const formErrors = [];
|
|
8856
|
+
for (const sub of this.issues) {
|
|
8857
|
+
if (sub.path.length > 0) {
|
|
8858
|
+
const firstEl = sub.path[0];
|
|
8859
|
+
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
|
|
8860
|
+
fieldErrors[firstEl].push(mapper(sub));
|
|
8861
|
+
}
|
|
8862
|
+
else {
|
|
8863
|
+
formErrors.push(mapper(sub));
|
|
8864
|
+
}
|
|
8865
|
+
}
|
|
8866
|
+
return { formErrors, fieldErrors };
|
|
8867
|
+
}
|
|
8868
|
+
get formErrors() {
|
|
8869
|
+
return this.flatten();
|
|
8870
|
+
}
|
|
8871
|
+
}
|
|
8872
|
+
ZodError.create = (issues) => {
|
|
8873
|
+
const error = new ZodError(issues);
|
|
8874
|
+
return error;
|
|
8875
|
+
};
|
|
8876
|
+
|
|
8877
|
+
var errorUtil;
|
|
8878
|
+
(function (errorUtil) {
|
|
8879
|
+
errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
|
|
8880
|
+
// biome-ignore lint:
|
|
8881
|
+
errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
|
|
8882
|
+
})(errorUtil || (errorUtil = {}));
|
|
8883
|
+
|
|
8884
|
+
var ZodFirstPartyTypeKind;
|
|
8885
|
+
(function (ZodFirstPartyTypeKind) {
|
|
8886
|
+
ZodFirstPartyTypeKind["ZodString"] = "ZodString";
|
|
8887
|
+
ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
|
|
8888
|
+
ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
|
|
8889
|
+
ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
|
|
8890
|
+
ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
|
|
8891
|
+
ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
|
|
8892
|
+
ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
|
|
8893
|
+
ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
|
|
8894
|
+
ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
|
|
8895
|
+
ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
|
|
8896
|
+
ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
|
|
8897
|
+
ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
|
|
8898
|
+
ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
|
|
8899
|
+
ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
|
|
8900
|
+
ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
|
|
8901
|
+
ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
|
|
8902
|
+
ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
|
|
8903
|
+
ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
|
|
8904
|
+
ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
|
|
8905
|
+
ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
|
|
8906
|
+
ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
|
|
8907
|
+
ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
|
|
8908
|
+
ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
|
|
8909
|
+
ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
|
|
8910
|
+
ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
|
|
8911
|
+
ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
|
|
8912
|
+
ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
|
|
8913
|
+
ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
|
|
8914
|
+
ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
|
|
8915
|
+
ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
|
|
8916
|
+
ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
|
|
8917
|
+
ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
|
|
8918
|
+
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
|
|
8919
|
+
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
|
|
8920
|
+
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
|
|
8921
|
+
ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
|
|
8922
|
+
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
|
|
8923
|
+
|
|
8924
|
+
function parseAnyDef() {
|
|
8925
|
+
return {};
|
|
8926
|
+
}
|
|
8927
|
+
|
|
8928
|
+
function parseArrayDef(def, refs) {
|
|
8929
|
+
const res = {
|
|
8930
|
+
type: 'array',
|
|
8931
|
+
};
|
|
8932
|
+
if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
|
|
8933
|
+
res.items = parseDef(def.type._def, {
|
|
8934
|
+
...refs,
|
|
8935
|
+
currentPath: [...refs.currentPath, 'items'],
|
|
8936
|
+
});
|
|
8937
|
+
}
|
|
8938
|
+
if (def.minLength) {
|
|
8939
|
+
setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs);
|
|
8940
|
+
}
|
|
8941
|
+
if (def.maxLength) {
|
|
8942
|
+
setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs);
|
|
8943
|
+
}
|
|
8944
|
+
if (def.exactLength) {
|
|
8945
|
+
setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs);
|
|
8946
|
+
setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs);
|
|
8947
|
+
}
|
|
8948
|
+
return res;
|
|
8949
|
+
}
|
|
8950
|
+
|
|
8951
|
+
function parseBigintDef(def, refs) {
|
|
8952
|
+
const res = {
|
|
8953
|
+
type: 'integer',
|
|
8954
|
+
format: 'int64',
|
|
8955
|
+
};
|
|
8956
|
+
if (!def.checks)
|
|
8957
|
+
return res;
|
|
8958
|
+
for (const check of def.checks) {
|
|
8959
|
+
switch (check.kind) {
|
|
8960
|
+
case 'min':
|
|
8961
|
+
if (refs.target === 'jsonSchema7') {
|
|
8962
|
+
if (check.inclusive) {
|
|
8963
|
+
setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);
|
|
8964
|
+
}
|
|
8965
|
+
else {
|
|
8966
|
+
setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);
|
|
8967
|
+
}
|
|
8968
|
+
}
|
|
8969
|
+
else {
|
|
8970
|
+
if (!check.inclusive) {
|
|
8971
|
+
res.exclusiveMinimum = true;
|
|
8972
|
+
}
|
|
8973
|
+
setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);
|
|
8974
|
+
}
|
|
8975
|
+
break;
|
|
8976
|
+
case 'max':
|
|
8977
|
+
if (refs.target === 'jsonSchema7') {
|
|
8978
|
+
if (check.inclusive) {
|
|
8979
|
+
setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);
|
|
8980
|
+
}
|
|
8981
|
+
else {
|
|
8982
|
+
setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);
|
|
8983
|
+
}
|
|
8984
|
+
}
|
|
8985
|
+
else {
|
|
8986
|
+
if (!check.inclusive) {
|
|
8987
|
+
res.exclusiveMaximum = true;
|
|
8988
|
+
}
|
|
8989
|
+
setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);
|
|
8990
|
+
}
|
|
8991
|
+
break;
|
|
8992
|
+
case 'multipleOf':
|
|
8993
|
+
setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);
|
|
8994
|
+
break;
|
|
8995
|
+
}
|
|
8996
|
+
}
|
|
8997
|
+
return res;
|
|
8998
|
+
}
|
|
8999
|
+
|
|
9000
|
+
function parseBooleanDef() {
|
|
9001
|
+
return {
|
|
9002
|
+
type: 'boolean',
|
|
9003
|
+
};
|
|
9004
|
+
}
|
|
9005
|
+
|
|
9006
|
+
function parseBrandedDef(_def, refs) {
|
|
9007
|
+
return parseDef(_def.type._def, refs);
|
|
9008
|
+
}
|
|
9009
|
+
|
|
9010
|
+
const parseCatchDef = (def, refs) => {
|
|
9011
|
+
return parseDef(def.innerType._def, refs);
|
|
9012
|
+
};
|
|
9013
|
+
|
|
9014
|
+
function parseDateDef(def, refs, overrideDateStrategy) {
|
|
9015
|
+
const strategy = overrideDateStrategy ?? refs.dateStrategy;
|
|
9016
|
+
if (Array.isArray(strategy)) {
|
|
9017
|
+
return {
|
|
9018
|
+
anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),
|
|
9019
|
+
};
|
|
9020
|
+
}
|
|
9021
|
+
switch (strategy) {
|
|
9022
|
+
case 'string':
|
|
9023
|
+
case 'format:date-time':
|
|
9024
|
+
return {
|
|
9025
|
+
type: 'string',
|
|
9026
|
+
format: 'date-time',
|
|
9027
|
+
};
|
|
9028
|
+
case 'format:date':
|
|
9029
|
+
return {
|
|
9030
|
+
type: 'string',
|
|
9031
|
+
format: 'date',
|
|
9032
|
+
};
|
|
9033
|
+
case 'integer':
|
|
9034
|
+
return integerDateParser(def, refs);
|
|
9035
|
+
}
|
|
9036
|
+
}
|
|
9037
|
+
const integerDateParser = (def, refs) => {
|
|
9038
|
+
const res = {
|
|
9039
|
+
type: 'integer',
|
|
9040
|
+
format: 'unix-time',
|
|
9041
|
+
};
|
|
9042
|
+
if (refs.target === 'openApi3') {
|
|
9043
|
+
return res;
|
|
9044
|
+
}
|
|
9045
|
+
for (const check of def.checks) {
|
|
9046
|
+
switch (check.kind) {
|
|
9047
|
+
case 'min':
|
|
9048
|
+
setResponseValueAndErrors(res, 'minimum', check.value, // This is in milliseconds
|
|
9049
|
+
check.message, refs);
|
|
9050
|
+
break;
|
|
9051
|
+
case 'max':
|
|
9052
|
+
setResponseValueAndErrors(res, 'maximum', check.value, // This is in milliseconds
|
|
9053
|
+
check.message, refs);
|
|
9054
|
+
break;
|
|
9055
|
+
}
|
|
9056
|
+
}
|
|
9057
|
+
return res;
|
|
9058
|
+
};
|
|
9059
|
+
|
|
9060
|
+
function parseDefaultDef(_def, refs) {
|
|
9061
|
+
return {
|
|
9062
|
+
...parseDef(_def.innerType._def, refs),
|
|
9063
|
+
default: _def.defaultValue(),
|
|
9064
|
+
};
|
|
9065
|
+
}
|
|
9066
|
+
|
|
9067
|
+
function parseEffectsDef(_def, refs, forceResolution) {
|
|
9068
|
+
return refs.effectStrategy === 'input' ? parseDef(_def.schema._def, refs, forceResolution) : {};
|
|
9069
|
+
}
|
|
9070
|
+
|
|
9071
|
+
function parseEnumDef(def) {
|
|
9072
|
+
return {
|
|
9073
|
+
type: 'string',
|
|
9074
|
+
enum: [...def.values],
|
|
9075
|
+
};
|
|
9076
|
+
}
|
|
9077
|
+
|
|
9078
|
+
const isJsonSchema7AllOfType = (type) => {
|
|
9079
|
+
if ('type' in type && type.type === 'string')
|
|
9080
|
+
return false;
|
|
9081
|
+
return 'allOf' in type;
|
|
9082
|
+
};
|
|
9083
|
+
function parseIntersectionDef(def, refs) {
|
|
9084
|
+
const allOf = [
|
|
9085
|
+
parseDef(def.left._def, {
|
|
9086
|
+
...refs,
|
|
9087
|
+
currentPath: [...refs.currentPath, 'allOf', '0'],
|
|
9088
|
+
}),
|
|
9089
|
+
parseDef(def.right._def, {
|
|
9090
|
+
...refs,
|
|
9091
|
+
currentPath: [...refs.currentPath, 'allOf', '1'],
|
|
9092
|
+
}),
|
|
9093
|
+
].filter((x) => !!x);
|
|
9094
|
+
let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined;
|
|
9095
|
+
const mergedAllOf = [];
|
|
9096
|
+
// If either of the schemas is an allOf, merge them into a single allOf
|
|
9097
|
+
allOf.forEach((schema) => {
|
|
9098
|
+
if (isJsonSchema7AllOfType(schema)) {
|
|
9099
|
+
mergedAllOf.push(...schema.allOf);
|
|
9100
|
+
if (schema.unevaluatedProperties === undefined) {
|
|
9101
|
+
// If one of the schemas has no unevaluatedProperties set,
|
|
9102
|
+
// the merged schema should also have no unevaluatedProperties set
|
|
9103
|
+
unevaluatedProperties = undefined;
|
|
9104
|
+
}
|
|
9105
|
+
}
|
|
9106
|
+
else {
|
|
9107
|
+
let nestedSchema = schema;
|
|
9108
|
+
if ('additionalProperties' in schema && schema.additionalProperties === false) {
|
|
9109
|
+
const { additionalProperties, ...rest } = schema;
|
|
9110
|
+
nestedSchema = rest;
|
|
9111
|
+
}
|
|
9112
|
+
else {
|
|
9113
|
+
// As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties
|
|
9114
|
+
unevaluatedProperties = undefined;
|
|
9115
|
+
}
|
|
9116
|
+
mergedAllOf.push(nestedSchema);
|
|
9117
|
+
}
|
|
9118
|
+
});
|
|
9119
|
+
return mergedAllOf.length ?
|
|
9120
|
+
{
|
|
9121
|
+
allOf: mergedAllOf,
|
|
9122
|
+
...unevaluatedProperties,
|
|
9123
|
+
}
|
|
9124
|
+
: undefined;
|
|
9125
|
+
}
|
|
9126
|
+
|
|
9127
|
+
function parseLiteralDef(def, refs) {
|
|
9128
|
+
const parsedType = typeof def.value;
|
|
9129
|
+
if (parsedType !== 'bigint' &&
|
|
9130
|
+
parsedType !== 'number' &&
|
|
9131
|
+
parsedType !== 'boolean' &&
|
|
9132
|
+
parsedType !== 'string') {
|
|
9133
|
+
return {
|
|
9134
|
+
type: Array.isArray(def.value) ? 'array' : 'object',
|
|
9135
|
+
};
|
|
9136
|
+
}
|
|
9137
|
+
if (refs.target === 'openApi3') {
|
|
9138
|
+
return {
|
|
9139
|
+
type: parsedType === 'bigint' ? 'integer' : parsedType,
|
|
9140
|
+
enum: [def.value],
|
|
9141
|
+
};
|
|
9142
|
+
}
|
|
9143
|
+
return {
|
|
9144
|
+
type: parsedType === 'bigint' ? 'integer' : parsedType,
|
|
9145
|
+
const: def.value,
|
|
9146
|
+
};
|
|
9147
|
+
}
|
|
9148
|
+
|
|
9149
|
+
let emojiRegex;
|
|
9150
|
+
/**
|
|
9151
|
+
* Generated from the regular expressions found here as of 2024-05-22:
|
|
9152
|
+
* https://github.com/colinhacks/zod/blob/master/src/types.ts.
|
|
9153
|
+
*
|
|
9154
|
+
* Expressions with /i flag have been changed accordingly.
|
|
9155
|
+
*/
|
|
9156
|
+
const zodPatterns = {
|
|
9157
|
+
/**
|
|
9158
|
+
* `c` was changed to `[cC]` to replicate /i flag
|
|
9159
|
+
*/
|
|
9160
|
+
cuid: /^[cC][^\s-]{8,}$/,
|
|
9161
|
+
cuid2: /^[0-9a-z]+$/,
|
|
9162
|
+
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
|
|
9163
|
+
/**
|
|
9164
|
+
* `a-z` was added to replicate /i flag
|
|
9165
|
+
*/
|
|
9166
|
+
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
|
|
9167
|
+
/**
|
|
9168
|
+
* Constructed a valid Unicode RegExp
|
|
9169
|
+
*
|
|
9170
|
+
* Lazily instantiate since this type of regex isn't supported
|
|
9171
|
+
* in all envs (e.g. React Native).
|
|
9172
|
+
*
|
|
9173
|
+
* See:
|
|
9174
|
+
* https://github.com/colinhacks/zod/issues/2433
|
|
9175
|
+
* Fix in Zod:
|
|
9176
|
+
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
|
|
9177
|
+
*/
|
|
9178
|
+
emoji: () => {
|
|
9179
|
+
if (emojiRegex === undefined) {
|
|
9180
|
+
emojiRegex = RegExp('^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$', 'u');
|
|
9181
|
+
}
|
|
9182
|
+
return emojiRegex;
|
|
9183
|
+
},
|
|
9184
|
+
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
|
|
9185
|
+
nanoid: /^[a-zA-Z0-9_-]{21}$/,
|
|
9186
|
+
};
|
|
9187
|
+
function parseStringDef(def, refs) {
|
|
9188
|
+
const res = {
|
|
9189
|
+
type: 'string',
|
|
9190
|
+
};
|
|
9191
|
+
function processPattern(value) {
|
|
9192
|
+
return refs.patternStrategy === 'escape' ? escapeNonAlphaNumeric(value) : value;
|
|
9193
|
+
}
|
|
9194
|
+
if (def.checks) {
|
|
9195
|
+
for (const check of def.checks) {
|
|
9196
|
+
switch (check.kind) {
|
|
9197
|
+
case 'min':
|
|
9198
|
+
setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
|
|
9199
|
+
break;
|
|
9200
|
+
case 'max':
|
|
9201
|
+
setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
|
|
9202
|
+
break;
|
|
9203
|
+
case 'email':
|
|
9204
|
+
switch (refs.emailStrategy) {
|
|
9205
|
+
case 'format:email':
|
|
9206
|
+
addFormat(res, 'email', check.message, refs);
|
|
9207
|
+
break;
|
|
9208
|
+
case 'format:idn-email':
|
|
9209
|
+
addFormat(res, 'idn-email', check.message, refs);
|
|
9210
|
+
break;
|
|
9211
|
+
case 'pattern:zod':
|
|
9212
|
+
addPattern(res, zodPatterns.email, check.message, refs);
|
|
9213
|
+
break;
|
|
9214
|
+
}
|
|
9215
|
+
break;
|
|
9216
|
+
case 'url':
|
|
9217
|
+
addFormat(res, 'uri', check.message, refs);
|
|
9218
|
+
break;
|
|
9219
|
+
case 'uuid':
|
|
9220
|
+
addFormat(res, 'uuid', check.message, refs);
|
|
9221
|
+
break;
|
|
9222
|
+
case 'regex':
|
|
9223
|
+
addPattern(res, check.regex, check.message, refs);
|
|
9224
|
+
break;
|
|
9225
|
+
case 'cuid':
|
|
9226
|
+
addPattern(res, zodPatterns.cuid, check.message, refs);
|
|
9227
|
+
break;
|
|
9228
|
+
case 'cuid2':
|
|
9229
|
+
addPattern(res, zodPatterns.cuid2, check.message, refs);
|
|
9230
|
+
break;
|
|
9231
|
+
case 'startsWith':
|
|
9232
|
+
addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs);
|
|
9233
|
+
break;
|
|
9234
|
+
case 'endsWith':
|
|
9235
|
+
addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs);
|
|
9236
|
+
break;
|
|
9237
|
+
case 'datetime':
|
|
9238
|
+
addFormat(res, 'date-time', check.message, refs);
|
|
9239
|
+
break;
|
|
9240
|
+
case 'date':
|
|
9241
|
+
addFormat(res, 'date', check.message, refs);
|
|
9242
|
+
break;
|
|
9243
|
+
case 'time':
|
|
9244
|
+
addFormat(res, 'time', check.message, refs);
|
|
9245
|
+
break;
|
|
9246
|
+
case 'duration':
|
|
9247
|
+
addFormat(res, 'duration', check.message, refs);
|
|
9248
|
+
break;
|
|
9249
|
+
case 'length':
|
|
9250
|
+
setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
|
|
9251
|
+
setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
|
|
9252
|
+
break;
|
|
9253
|
+
case 'includes': {
|
|
9254
|
+
addPattern(res, RegExp(processPattern(check.value)), check.message, refs);
|
|
9255
|
+
break;
|
|
9256
|
+
}
|
|
9257
|
+
case 'ip': {
|
|
9258
|
+
if (check.version !== 'v6') {
|
|
9259
|
+
addFormat(res, 'ipv4', check.message, refs);
|
|
9260
|
+
}
|
|
9261
|
+
if (check.version !== 'v4') {
|
|
9262
|
+
addFormat(res, 'ipv6', check.message, refs);
|
|
9263
|
+
}
|
|
9264
|
+
break;
|
|
9265
|
+
}
|
|
9266
|
+
case 'emoji':
|
|
9267
|
+
addPattern(res, zodPatterns.emoji, check.message, refs);
|
|
9268
|
+
break;
|
|
9269
|
+
case 'ulid': {
|
|
9270
|
+
addPattern(res, zodPatterns.ulid, check.message, refs);
|
|
9271
|
+
break;
|
|
9272
|
+
}
|
|
9273
|
+
case 'base64': {
|
|
9274
|
+
switch (refs.base64Strategy) {
|
|
9275
|
+
case 'format:binary': {
|
|
9276
|
+
addFormat(res, 'binary', check.message, refs);
|
|
9277
|
+
break;
|
|
9278
|
+
}
|
|
9279
|
+
case 'contentEncoding:base64': {
|
|
9280
|
+
setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs);
|
|
9281
|
+
break;
|
|
9282
|
+
}
|
|
9283
|
+
case 'pattern:zod': {
|
|
9284
|
+
addPattern(res, zodPatterns.base64, check.message, refs);
|
|
9285
|
+
break;
|
|
9286
|
+
}
|
|
9287
|
+
}
|
|
9288
|
+
break;
|
|
9289
|
+
}
|
|
9290
|
+
case 'nanoid': {
|
|
9291
|
+
addPattern(res, zodPatterns.nanoid, check.message, refs);
|
|
9292
|
+
}
|
|
9293
|
+
}
|
|
9294
|
+
}
|
|
9295
|
+
}
|
|
9296
|
+
return res;
|
|
9297
|
+
}
|
|
9298
|
+
const escapeNonAlphaNumeric = (value) => Array.from(value)
|
|
9299
|
+
.map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`))
|
|
9300
|
+
.join('');
|
|
9301
|
+
const addFormat = (schema, value, message, refs) => {
|
|
9302
|
+
if (schema.format || schema.anyOf?.some((x) => x.format)) {
|
|
9303
|
+
if (!schema.anyOf) {
|
|
9304
|
+
schema.anyOf = [];
|
|
9305
|
+
}
|
|
9306
|
+
if (schema.format) {
|
|
9307
|
+
schema.anyOf.push({
|
|
9308
|
+
format: schema.format,
|
|
9309
|
+
...(schema.errorMessage &&
|
|
9310
|
+
refs.errorMessages && {
|
|
9311
|
+
errorMessage: { format: schema.errorMessage.format },
|
|
9312
|
+
}),
|
|
9313
|
+
});
|
|
9314
|
+
delete schema.format;
|
|
9315
|
+
if (schema.errorMessage) {
|
|
9316
|
+
delete schema.errorMessage.format;
|
|
9317
|
+
if (Object.keys(schema.errorMessage).length === 0) {
|
|
9318
|
+
delete schema.errorMessage;
|
|
9319
|
+
}
|
|
9320
|
+
}
|
|
9321
|
+
}
|
|
9322
|
+
schema.anyOf.push({
|
|
9323
|
+
format: value,
|
|
9324
|
+
...(message && refs.errorMessages && { errorMessage: { format: message } }),
|
|
9325
|
+
});
|
|
9326
|
+
}
|
|
9327
|
+
else {
|
|
9328
|
+
setResponseValueAndErrors(schema, 'format', value, message, refs);
|
|
9329
|
+
}
|
|
9330
|
+
};
|
|
9331
|
+
const addPattern = (schema, regex, message, refs) => {
|
|
9332
|
+
if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
|
|
9333
|
+
if (!schema.allOf) {
|
|
9334
|
+
schema.allOf = [];
|
|
9335
|
+
}
|
|
9336
|
+
if (schema.pattern) {
|
|
9337
|
+
schema.allOf.push({
|
|
9338
|
+
pattern: schema.pattern,
|
|
9339
|
+
...(schema.errorMessage &&
|
|
9340
|
+
refs.errorMessages && {
|
|
9341
|
+
errorMessage: { pattern: schema.errorMessage.pattern },
|
|
9342
|
+
}),
|
|
9343
|
+
});
|
|
9344
|
+
delete schema.pattern;
|
|
9345
|
+
if (schema.errorMessage) {
|
|
9346
|
+
delete schema.errorMessage.pattern;
|
|
9347
|
+
if (Object.keys(schema.errorMessage).length === 0) {
|
|
9348
|
+
delete schema.errorMessage;
|
|
9349
|
+
}
|
|
9350
|
+
}
|
|
9351
|
+
}
|
|
9352
|
+
schema.allOf.push({
|
|
9353
|
+
pattern: processRegExp(regex, refs),
|
|
9354
|
+
...(message && refs.errorMessages && { errorMessage: { pattern: message } }),
|
|
9355
|
+
});
|
|
9356
|
+
}
|
|
9357
|
+
else {
|
|
9358
|
+
setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs);
|
|
9359
|
+
}
|
|
9360
|
+
};
|
|
9361
|
+
// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true
|
|
9362
|
+
const processRegExp = (regexOrFunction, refs) => {
|
|
9363
|
+
const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction;
|
|
9364
|
+
if (!refs.applyRegexFlags || !regex.flags)
|
|
9365
|
+
return regex.source;
|
|
9366
|
+
// Currently handled flags
|
|
9367
|
+
const flags = {
|
|
9368
|
+
i: regex.flags.includes('i'), // Case-insensitive
|
|
9369
|
+
m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters
|
|
9370
|
+
s: regex.flags.includes('s'), // `.` matches newlines
|
|
9371
|
+
};
|
|
9372
|
+
// The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!
|
|
9373
|
+
const source = flags.i ? regex.source.toLowerCase() : regex.source;
|
|
9374
|
+
let pattern = '';
|
|
9375
|
+
let isEscaped = false;
|
|
9376
|
+
let inCharGroup = false;
|
|
9377
|
+
let inCharRange = false;
|
|
9378
|
+
for (let i = 0; i < source.length; i++) {
|
|
9379
|
+
if (isEscaped) {
|
|
9380
|
+
pattern += source[i];
|
|
9381
|
+
isEscaped = false;
|
|
9382
|
+
continue;
|
|
9383
|
+
}
|
|
9384
|
+
if (flags.i) {
|
|
9385
|
+
if (inCharGroup) {
|
|
9386
|
+
if (source[i].match(/[a-z]/)) {
|
|
9387
|
+
if (inCharRange) {
|
|
9388
|
+
pattern += source[i];
|
|
9389
|
+
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
|
|
9390
|
+
inCharRange = false;
|
|
9391
|
+
}
|
|
9392
|
+
else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {
|
|
9393
|
+
pattern += source[i];
|
|
9394
|
+
inCharRange = true;
|
|
9395
|
+
}
|
|
9396
|
+
else {
|
|
9397
|
+
pattern += `${source[i]}${source[i].toUpperCase()}`;
|
|
9398
|
+
}
|
|
9399
|
+
continue;
|
|
9400
|
+
}
|
|
9401
|
+
}
|
|
9402
|
+
else if (source[i].match(/[a-z]/)) {
|
|
9403
|
+
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
|
|
9404
|
+
continue;
|
|
9405
|
+
}
|
|
9406
|
+
}
|
|
9407
|
+
if (flags.m) {
|
|
9408
|
+
if (source[i] === '^') {
|
|
9409
|
+
pattern += `(^|(?<=[\r\n]))`;
|
|
9410
|
+
continue;
|
|
9411
|
+
}
|
|
9412
|
+
else if (source[i] === '$') {
|
|
9413
|
+
pattern += `($|(?=[\r\n]))`;
|
|
9414
|
+
continue;
|
|
9415
|
+
}
|
|
9416
|
+
}
|
|
9417
|
+
if (flags.s && source[i] === '.') {
|
|
9418
|
+
pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`;
|
|
9419
|
+
continue;
|
|
9420
|
+
}
|
|
9421
|
+
pattern += source[i];
|
|
9422
|
+
if (source[i] === '\\') {
|
|
9423
|
+
isEscaped = true;
|
|
9424
|
+
}
|
|
9425
|
+
else if (inCharGroup && source[i] === ']') {
|
|
9426
|
+
inCharGroup = false;
|
|
9427
|
+
}
|
|
9428
|
+
else if (!inCharGroup && source[i] === '[') {
|
|
9429
|
+
inCharGroup = true;
|
|
9430
|
+
}
|
|
9431
|
+
}
|
|
9432
|
+
try {
|
|
9433
|
+
const regexTest = new RegExp(pattern);
|
|
9434
|
+
}
|
|
9435
|
+
catch {
|
|
9436
|
+
console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`);
|
|
9437
|
+
return regex.source;
|
|
9438
|
+
}
|
|
9439
|
+
return pattern;
|
|
9440
|
+
};
|
|
9441
|
+
|
|
9442
|
+
function parseRecordDef(def, refs) {
|
|
9443
|
+
if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
|
|
9444
|
+
return {
|
|
9445
|
+
type: 'object',
|
|
9446
|
+
required: def.keyType._def.values,
|
|
9447
|
+
properties: def.keyType._def.values.reduce((acc, key) => ({
|
|
9448
|
+
...acc,
|
|
9449
|
+
[key]: parseDef(def.valueType._def, {
|
|
9450
|
+
...refs,
|
|
9451
|
+
currentPath: [...refs.currentPath, 'properties', key],
|
|
9452
|
+
}) ?? {},
|
|
9453
|
+
}), {}),
|
|
9454
|
+
additionalProperties: false,
|
|
9455
|
+
};
|
|
9456
|
+
}
|
|
9457
|
+
const schema = {
|
|
9458
|
+
type: 'object',
|
|
9459
|
+
additionalProperties: parseDef(def.valueType._def, {
|
|
9460
|
+
...refs,
|
|
9461
|
+
currentPath: [...refs.currentPath, 'additionalProperties'],
|
|
9462
|
+
}) ?? {},
|
|
9463
|
+
};
|
|
9464
|
+
if (refs.target === 'openApi3') {
|
|
9465
|
+
return schema;
|
|
9466
|
+
}
|
|
9467
|
+
if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
|
|
9468
|
+
const keyType = Object.entries(parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {});
|
|
9469
|
+
return {
|
|
9470
|
+
...schema,
|
|
9471
|
+
propertyNames: keyType,
|
|
9472
|
+
};
|
|
9473
|
+
}
|
|
9474
|
+
else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
|
|
9475
|
+
return {
|
|
9476
|
+
...schema,
|
|
9477
|
+
propertyNames: {
|
|
9478
|
+
enum: def.keyType._def.values,
|
|
9479
|
+
},
|
|
9480
|
+
};
|
|
9481
|
+
}
|
|
9482
|
+
return schema;
|
|
9483
|
+
}
|
|
9484
|
+
|
|
9485
|
+
function parseMapDef(def, refs) {
|
|
9486
|
+
if (refs.mapStrategy === 'record') {
|
|
9487
|
+
return parseRecordDef(def, refs);
|
|
9488
|
+
}
|
|
9489
|
+
const keys = parseDef(def.keyType._def, {
|
|
9490
|
+
...refs,
|
|
9491
|
+
currentPath: [...refs.currentPath, 'items', 'items', '0'],
|
|
9492
|
+
}) || {};
|
|
9493
|
+
const values = parseDef(def.valueType._def, {
|
|
9494
|
+
...refs,
|
|
9495
|
+
currentPath: [...refs.currentPath, 'items', 'items', '1'],
|
|
9496
|
+
}) || {};
|
|
9497
|
+
return {
|
|
9498
|
+
type: 'array',
|
|
9499
|
+
maxItems: 125,
|
|
9500
|
+
items: {
|
|
9501
|
+
type: 'array',
|
|
9502
|
+
items: [keys, values],
|
|
9503
|
+
minItems: 2,
|
|
9504
|
+
maxItems: 2,
|
|
9505
|
+
},
|
|
9506
|
+
};
|
|
9507
|
+
}
|
|
9508
|
+
|
|
9509
|
+
function parseNativeEnumDef(def) {
|
|
9510
|
+
const object = def.values;
|
|
9511
|
+
const actualKeys = Object.keys(def.values).filter((key) => {
|
|
9512
|
+
return typeof object[object[key]] !== 'number';
|
|
9513
|
+
});
|
|
9514
|
+
const actualValues = actualKeys.map((key) => object[key]);
|
|
9515
|
+
const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
|
|
9516
|
+
return {
|
|
9517
|
+
type: parsedTypes.length === 1 ?
|
|
9518
|
+
parsedTypes[0] === 'string' ?
|
|
9519
|
+
'string'
|
|
9520
|
+
: 'number'
|
|
9521
|
+
: ['string', 'number'],
|
|
9522
|
+
enum: actualValues,
|
|
9523
|
+
};
|
|
9524
|
+
}
|
|
9525
|
+
|
|
9526
|
+
function parseNeverDef() {
|
|
9527
|
+
return {
|
|
9528
|
+
not: {},
|
|
9529
|
+
};
|
|
9530
|
+
}
|
|
9531
|
+
|
|
9532
|
+
function parseNullDef(refs) {
|
|
9533
|
+
return refs.target === 'openApi3' ?
|
|
9534
|
+
{
|
|
9535
|
+
enum: ['null'],
|
|
9536
|
+
nullable: true,
|
|
9537
|
+
}
|
|
9538
|
+
: {
|
|
9539
|
+
type: 'null',
|
|
9540
|
+
};
|
|
9541
|
+
}
|
|
9542
|
+
|
|
9543
|
+
const primitiveMappings = {
|
|
9544
|
+
ZodString: 'string',
|
|
9545
|
+
ZodNumber: 'number',
|
|
9546
|
+
ZodBigInt: 'integer',
|
|
9547
|
+
ZodBoolean: 'boolean',
|
|
9548
|
+
ZodNull: 'null',
|
|
9549
|
+
};
|
|
9550
|
+
function parseUnionDef(def, refs) {
|
|
9551
|
+
if (refs.target === 'openApi3')
|
|
9552
|
+
return asAnyOf(def, refs);
|
|
9553
|
+
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
|
|
9554
|
+
// This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.
|
|
9555
|
+
if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
|
|
9556
|
+
// all types in union are primitive and lack checks, so might as well squash into {type: [...]}
|
|
9557
|
+
const types = options.reduce((types, x) => {
|
|
9558
|
+
const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43
|
|
9559
|
+
return type && !types.includes(type) ? [...types, type] : types;
|
|
9560
|
+
}, []);
|
|
9561
|
+
return {
|
|
9562
|
+
type: types.length > 1 ? types : types[0],
|
|
9563
|
+
};
|
|
9564
|
+
}
|
|
9565
|
+
else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) {
|
|
9566
|
+
// all options literals
|
|
9567
|
+
const types = options.reduce((acc, x) => {
|
|
9568
|
+
const type = typeof x._def.value;
|
|
9569
|
+
switch (type) {
|
|
9570
|
+
case 'string':
|
|
9571
|
+
case 'number':
|
|
9572
|
+
case 'boolean':
|
|
9573
|
+
return [...acc, type];
|
|
9574
|
+
case 'bigint':
|
|
9575
|
+
return [...acc, 'integer'];
|
|
9576
|
+
case 'object':
|
|
9577
|
+
if (x._def.value === null)
|
|
9578
|
+
return [...acc, 'null'];
|
|
9579
|
+
case 'symbol':
|
|
9580
|
+
case 'undefined':
|
|
9581
|
+
case 'function':
|
|
9582
|
+
default:
|
|
9583
|
+
return acc;
|
|
9584
|
+
}
|
|
9585
|
+
}, []);
|
|
9586
|
+
if (types.length === options.length) {
|
|
9587
|
+
// all the literals are primitive, as far as null can be considered primitive
|
|
9588
|
+
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
|
|
9589
|
+
return {
|
|
9590
|
+
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
|
|
9591
|
+
enum: options.reduce((acc, x) => {
|
|
9592
|
+
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
|
|
9593
|
+
}, []),
|
|
9594
|
+
};
|
|
9595
|
+
}
|
|
9596
|
+
}
|
|
9597
|
+
else if (options.every((x) => x._def.typeName === 'ZodEnum')) {
|
|
9598
|
+
return {
|
|
9599
|
+
type: 'string',
|
|
9600
|
+
enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []),
|
|
9601
|
+
};
|
|
9602
|
+
}
|
|
9603
|
+
return asAnyOf(def, refs);
|
|
9604
|
+
}
|
|
9605
|
+
const asAnyOf = (def, refs) => {
|
|
9606
|
+
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options)
|
|
9607
|
+
.map((x, i) => parseDef(x._def, {
|
|
9608
|
+
...refs,
|
|
9609
|
+
currentPath: [...refs.currentPath, 'anyOf', `${i}`],
|
|
9610
|
+
}))
|
|
9611
|
+
.filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0)));
|
|
9612
|
+
return anyOf.length ? { anyOf } : undefined;
|
|
9613
|
+
};
|
|
9614
|
+
|
|
9615
|
+
function parseNullableDef(def, refs) {
|
|
9616
|
+
if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) &&
|
|
9617
|
+
(!def.innerType._def.checks || !def.innerType._def.checks.length)) {
|
|
9618
|
+
if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') {
|
|
9619
|
+
return {
|
|
9620
|
+
type: primitiveMappings[def.innerType._def.typeName],
|
|
9621
|
+
nullable: true,
|
|
9622
|
+
};
|
|
9623
|
+
}
|
|
9624
|
+
return {
|
|
9625
|
+
type: [primitiveMappings[def.innerType._def.typeName], 'null'],
|
|
9626
|
+
};
|
|
9627
|
+
}
|
|
9628
|
+
if (refs.target === 'openApi3') {
|
|
9629
|
+
const base = parseDef(def.innerType._def, {
|
|
9630
|
+
...refs,
|
|
9631
|
+
currentPath: [...refs.currentPath],
|
|
9632
|
+
});
|
|
9633
|
+
if (base && '$ref' in base)
|
|
9634
|
+
return { allOf: [base], nullable: true };
|
|
9635
|
+
return base && { ...base, nullable: true };
|
|
9636
|
+
}
|
|
9637
|
+
const base = parseDef(def.innerType._def, {
|
|
9638
|
+
...refs,
|
|
9639
|
+
currentPath: [...refs.currentPath, 'anyOf', '0'],
|
|
9640
|
+
});
|
|
9641
|
+
return base && { anyOf: [base, { type: 'null' }] };
|
|
9642
|
+
}
|
|
9643
|
+
|
|
9644
|
+
function parseNumberDef(def, refs) {
|
|
9645
|
+
const res = {
|
|
9646
|
+
type: 'number',
|
|
9647
|
+
};
|
|
9648
|
+
if (!def.checks)
|
|
9649
|
+
return res;
|
|
9650
|
+
for (const check of def.checks) {
|
|
9651
|
+
switch (check.kind) {
|
|
9652
|
+
case 'int':
|
|
9653
|
+
res.type = 'integer';
|
|
9654
|
+
addErrorMessage(res, 'type', check.message, refs);
|
|
9655
|
+
break;
|
|
9656
|
+
case 'min':
|
|
9657
|
+
if (refs.target === 'jsonSchema7') {
|
|
9658
|
+
if (check.inclusive) {
|
|
9659
|
+
setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);
|
|
9660
|
+
}
|
|
9661
|
+
else {
|
|
9662
|
+
setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);
|
|
9663
|
+
}
|
|
9664
|
+
}
|
|
9665
|
+
else {
|
|
9666
|
+
if (!check.inclusive) {
|
|
9667
|
+
res.exclusiveMinimum = true;
|
|
9668
|
+
}
|
|
9669
|
+
setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);
|
|
9670
|
+
}
|
|
9671
|
+
break;
|
|
9672
|
+
case 'max':
|
|
9673
|
+
if (refs.target === 'jsonSchema7') {
|
|
9674
|
+
if (check.inclusive) {
|
|
9675
|
+
setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);
|
|
9676
|
+
}
|
|
9677
|
+
else {
|
|
9678
|
+
setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);
|
|
9679
|
+
}
|
|
9680
|
+
}
|
|
9681
|
+
else {
|
|
9682
|
+
if (!check.inclusive) {
|
|
9683
|
+
res.exclusiveMaximum = true;
|
|
9684
|
+
}
|
|
9685
|
+
setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);
|
|
9686
|
+
}
|
|
9687
|
+
break;
|
|
9688
|
+
case 'multipleOf':
|
|
9689
|
+
setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);
|
|
9690
|
+
break;
|
|
9691
|
+
}
|
|
9692
|
+
}
|
|
9693
|
+
return res;
|
|
9694
|
+
}
|
|
9695
|
+
|
|
9696
|
+
function decideAdditionalProperties(def, refs) {
|
|
9697
|
+
if (refs.removeAdditionalStrategy === 'strict') {
|
|
9698
|
+
return def.catchall._def.typeName === 'ZodNever' ?
|
|
9699
|
+
def.unknownKeys !== 'strict'
|
|
9700
|
+
: parseDef(def.catchall._def, {
|
|
9701
|
+
...refs,
|
|
9702
|
+
currentPath: [...refs.currentPath, 'additionalProperties'],
|
|
9703
|
+
}) ?? true;
|
|
9704
|
+
}
|
|
9705
|
+
else {
|
|
9706
|
+
return def.catchall._def.typeName === 'ZodNever' ?
|
|
9707
|
+
def.unknownKeys === 'passthrough'
|
|
9708
|
+
: parseDef(def.catchall._def, {
|
|
9709
|
+
...refs,
|
|
9710
|
+
currentPath: [...refs.currentPath, 'additionalProperties'],
|
|
9711
|
+
}) ?? true;
|
|
9712
|
+
}
|
|
9713
|
+
}
|
|
9714
|
+
function parseObjectDef(def, refs) {
|
|
9715
|
+
const result = {
|
|
9716
|
+
type: 'object',
|
|
9717
|
+
...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {
|
|
9718
|
+
if (propDef === undefined || propDef._def === undefined)
|
|
9719
|
+
return acc;
|
|
9720
|
+
const propertyPath = [...refs.currentPath, 'properties', propName];
|
|
9721
|
+
const parsedDef = parseDef(propDef._def, {
|
|
9722
|
+
...refs,
|
|
9723
|
+
currentPath: propertyPath,
|
|
9724
|
+
propertyPath,
|
|
9725
|
+
});
|
|
9726
|
+
if (parsedDef === undefined)
|
|
9727
|
+
return acc;
|
|
9728
|
+
if (refs.openaiStrictMode &&
|
|
9729
|
+
propDef.isOptional() &&
|
|
9730
|
+
!propDef.isNullable() &&
|
|
9731
|
+
typeof propDef._def?.defaultValue === 'undefined') {
|
|
9732
|
+
throw new Error(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);
|
|
9733
|
+
}
|
|
9734
|
+
return {
|
|
9735
|
+
properties: {
|
|
9736
|
+
...acc.properties,
|
|
9737
|
+
[propName]: parsedDef,
|
|
9738
|
+
},
|
|
9739
|
+
required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName],
|
|
9740
|
+
};
|
|
9741
|
+
}, { properties: {}, required: [] }),
|
|
9742
|
+
additionalProperties: decideAdditionalProperties(def, refs),
|
|
9743
|
+
};
|
|
9744
|
+
if (!result.required.length)
|
|
9745
|
+
delete result.required;
|
|
9746
|
+
return result;
|
|
9747
|
+
}
|
|
9748
|
+
|
|
9749
|
+
const parseOptionalDef = (def, refs) => {
|
|
9750
|
+
if (refs.propertyPath &&
|
|
9751
|
+
refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString()) {
|
|
9752
|
+
return parseDef(def.innerType._def, { ...refs, currentPath: refs.currentPath });
|
|
9753
|
+
}
|
|
9754
|
+
const innerSchema = parseDef(def.innerType._def, {
|
|
9755
|
+
...refs,
|
|
9756
|
+
currentPath: [...refs.currentPath, 'anyOf', '1'],
|
|
9757
|
+
});
|
|
9758
|
+
return innerSchema ?
|
|
9759
|
+
{
|
|
9760
|
+
anyOf: [
|
|
9761
|
+
{
|
|
9762
|
+
not: {},
|
|
9763
|
+
},
|
|
9764
|
+
innerSchema,
|
|
9765
|
+
],
|
|
9766
|
+
}
|
|
9767
|
+
: {};
|
|
9768
|
+
};
|
|
9769
|
+
|
|
9770
|
+
const parsePipelineDef = (def, refs) => {
|
|
9771
|
+
if (refs.pipeStrategy === 'input') {
|
|
9772
|
+
return parseDef(def.in._def, refs);
|
|
9773
|
+
}
|
|
9774
|
+
else if (refs.pipeStrategy === 'output') {
|
|
9775
|
+
return parseDef(def.out._def, refs);
|
|
9776
|
+
}
|
|
9777
|
+
const a = parseDef(def.in._def, {
|
|
9778
|
+
...refs,
|
|
9779
|
+
currentPath: [...refs.currentPath, 'allOf', '0'],
|
|
9780
|
+
});
|
|
9781
|
+
const b = parseDef(def.out._def, {
|
|
9782
|
+
...refs,
|
|
9783
|
+
currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'],
|
|
9784
|
+
});
|
|
9785
|
+
return {
|
|
9786
|
+
allOf: [a, b].filter((x) => x !== undefined),
|
|
9787
|
+
};
|
|
9788
|
+
};
|
|
9789
|
+
|
|
9790
|
+
function parsePromiseDef(def, refs) {
|
|
9791
|
+
return parseDef(def.type._def, refs);
|
|
9792
|
+
}
|
|
9793
|
+
|
|
9794
|
+
function parseSetDef(def, refs) {
|
|
9795
|
+
const items = parseDef(def.valueType._def, {
|
|
9796
|
+
...refs,
|
|
9797
|
+
currentPath: [...refs.currentPath, 'items'],
|
|
9798
|
+
});
|
|
9799
|
+
const schema = {
|
|
9800
|
+
type: 'array',
|
|
9801
|
+
uniqueItems: true,
|
|
9802
|
+
items,
|
|
9803
|
+
};
|
|
9804
|
+
if (def.minSize) {
|
|
9805
|
+
setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs);
|
|
9806
|
+
}
|
|
9807
|
+
if (def.maxSize) {
|
|
9808
|
+
setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs);
|
|
9809
|
+
}
|
|
9810
|
+
return schema;
|
|
9811
|
+
}
|
|
9812
|
+
|
|
9813
|
+
function parseTupleDef(def, refs) {
|
|
9814
|
+
if (def.rest) {
|
|
9815
|
+
return {
|
|
9816
|
+
type: 'array',
|
|
9817
|
+
minItems: def.items.length,
|
|
9818
|
+
items: def.items
|
|
9819
|
+
.map((x, i) => parseDef(x._def, {
|
|
9820
|
+
...refs,
|
|
9821
|
+
currentPath: [...refs.currentPath, 'items', `${i}`],
|
|
9822
|
+
}))
|
|
9823
|
+
.reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),
|
|
9824
|
+
additionalItems: parseDef(def.rest._def, {
|
|
9825
|
+
...refs,
|
|
9826
|
+
currentPath: [...refs.currentPath, 'additionalItems'],
|
|
9827
|
+
}),
|
|
9828
|
+
};
|
|
9829
|
+
}
|
|
9830
|
+
else {
|
|
9831
|
+
return {
|
|
9832
|
+
type: 'array',
|
|
9833
|
+
minItems: def.items.length,
|
|
9834
|
+
maxItems: def.items.length,
|
|
9835
|
+
items: def.items
|
|
9836
|
+
.map((x, i) => parseDef(x._def, {
|
|
9837
|
+
...refs,
|
|
9838
|
+
currentPath: [...refs.currentPath, 'items', `${i}`],
|
|
9839
|
+
}))
|
|
9840
|
+
.reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),
|
|
9841
|
+
};
|
|
9842
|
+
}
|
|
9843
|
+
}
|
|
9844
|
+
|
|
9845
|
+
function parseUndefinedDef() {
|
|
9846
|
+
return {
|
|
9847
|
+
not: {},
|
|
9848
|
+
};
|
|
9849
|
+
}
|
|
9850
|
+
|
|
9851
|
+
function parseUnknownDef() {
|
|
9852
|
+
return {};
|
|
9853
|
+
}
|
|
9854
|
+
|
|
9855
|
+
const parseReadonlyDef = (def, refs) => {
|
|
9856
|
+
return parseDef(def.innerType._def, refs);
|
|
9857
|
+
};
|
|
9858
|
+
|
|
9859
|
+
function parseDef(def, refs, forceResolution = false) {
|
|
9860
|
+
const seenItem = refs.seen.get(def);
|
|
9861
|
+
if (refs.override) {
|
|
9862
|
+
const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
|
|
9863
|
+
if (overrideResult !== ignoreOverride) {
|
|
9864
|
+
return overrideResult;
|
|
9865
|
+
}
|
|
9866
|
+
}
|
|
9867
|
+
if (seenItem && !forceResolution) {
|
|
9868
|
+
const seenSchema = get$ref(seenItem, refs);
|
|
9869
|
+
if (seenSchema !== undefined) {
|
|
9870
|
+
if ('$ref' in seenSchema) {
|
|
9871
|
+
refs.seenRefs.add(seenSchema.$ref);
|
|
9872
|
+
}
|
|
9873
|
+
return seenSchema;
|
|
9874
|
+
}
|
|
9875
|
+
}
|
|
9876
|
+
const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
|
|
9877
|
+
refs.seen.set(def, newItem);
|
|
9878
|
+
const jsonSchema = selectParser(def, def.typeName, refs, forceResolution);
|
|
9879
|
+
if (jsonSchema) {
|
|
9880
|
+
addMeta(def, refs, jsonSchema);
|
|
9881
|
+
}
|
|
9882
|
+
newItem.jsonSchema = jsonSchema;
|
|
9883
|
+
return jsonSchema;
|
|
9884
|
+
}
|
|
9885
|
+
const get$ref = (item, refs) => {
|
|
9886
|
+
switch (refs.$refStrategy) {
|
|
9887
|
+
case 'root':
|
|
9888
|
+
return { $ref: item.path.join('/') };
|
|
9889
|
+
// this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e.
|
|
9890
|
+
// the top-level schema *must* be `{"type": "object", "properties": {...}}` but if we ever
|
|
9891
|
+
// need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract
|
|
9892
|
+
// the schema to `#/definitions/` and reference that.
|
|
9893
|
+
//
|
|
9894
|
+
// e.g. if we need to reference a schema at
|
|
9895
|
+
// `["#","definitions","contactPerson","properties","person1","properties","name"]`
|
|
9896
|
+
// then we'll extract it out to `contactPerson_properties_person1_properties_name`
|
|
9897
|
+
case 'extract-to-root':
|
|
9898
|
+
const name = item.path.slice(refs.basePath.length + 1).join('_');
|
|
9899
|
+
// we don't need to extract the root schema in this case, as it's already
|
|
9900
|
+
// been added to the definitions
|
|
9901
|
+
if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') {
|
|
9902
|
+
refs.definitions[name] = item.def;
|
|
9903
|
+
}
|
|
9904
|
+
return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') };
|
|
9905
|
+
case 'relative':
|
|
9906
|
+
return { $ref: getRelativePath(refs.currentPath, item.path) };
|
|
9907
|
+
case 'none':
|
|
9908
|
+
case 'seen': {
|
|
9909
|
+
if (item.path.length < refs.currentPath.length &&
|
|
9910
|
+
item.path.every((value, index) => refs.currentPath[index] === value)) {
|
|
9911
|
+
console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`);
|
|
9912
|
+
return {};
|
|
9913
|
+
}
|
|
9914
|
+
return refs.$refStrategy === 'seen' ? {} : undefined;
|
|
9915
|
+
}
|
|
9916
|
+
}
|
|
9917
|
+
};
|
|
9918
|
+
const getRelativePath = (pathA, pathB) => {
|
|
9919
|
+
let i = 0;
|
|
9920
|
+
for (; i < pathA.length && i < pathB.length; i++) {
|
|
9921
|
+
if (pathA[i] !== pathB[i])
|
|
9922
|
+
break;
|
|
9923
|
+
}
|
|
9924
|
+
return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');
|
|
9925
|
+
};
|
|
9926
|
+
const selectParser = (def, typeName, refs, forceResolution) => {
|
|
9927
|
+
switch (typeName) {
|
|
9928
|
+
case ZodFirstPartyTypeKind.ZodString:
|
|
9929
|
+
return parseStringDef(def, refs);
|
|
9930
|
+
case ZodFirstPartyTypeKind.ZodNumber:
|
|
9931
|
+
return parseNumberDef(def, refs);
|
|
9932
|
+
case ZodFirstPartyTypeKind.ZodObject:
|
|
9933
|
+
return parseObjectDef(def, refs);
|
|
9934
|
+
case ZodFirstPartyTypeKind.ZodBigInt:
|
|
9935
|
+
return parseBigintDef(def, refs);
|
|
9936
|
+
case ZodFirstPartyTypeKind.ZodBoolean:
|
|
9937
|
+
return parseBooleanDef();
|
|
9938
|
+
case ZodFirstPartyTypeKind.ZodDate:
|
|
9939
|
+
return parseDateDef(def, refs);
|
|
9940
|
+
case ZodFirstPartyTypeKind.ZodUndefined:
|
|
9941
|
+
return parseUndefinedDef();
|
|
9942
|
+
case ZodFirstPartyTypeKind.ZodNull:
|
|
9943
|
+
return parseNullDef(refs);
|
|
9944
|
+
case ZodFirstPartyTypeKind.ZodArray:
|
|
9945
|
+
return parseArrayDef(def, refs);
|
|
9946
|
+
case ZodFirstPartyTypeKind.ZodUnion:
|
|
9947
|
+
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
|
|
9948
|
+
return parseUnionDef(def, refs);
|
|
9949
|
+
case ZodFirstPartyTypeKind.ZodIntersection:
|
|
9950
|
+
return parseIntersectionDef(def, refs);
|
|
9951
|
+
case ZodFirstPartyTypeKind.ZodTuple:
|
|
9952
|
+
return parseTupleDef(def, refs);
|
|
9953
|
+
case ZodFirstPartyTypeKind.ZodRecord:
|
|
9954
|
+
return parseRecordDef(def, refs);
|
|
9955
|
+
case ZodFirstPartyTypeKind.ZodLiteral:
|
|
9956
|
+
return parseLiteralDef(def, refs);
|
|
9957
|
+
case ZodFirstPartyTypeKind.ZodEnum:
|
|
9958
|
+
return parseEnumDef(def);
|
|
9959
|
+
case ZodFirstPartyTypeKind.ZodNativeEnum:
|
|
9960
|
+
return parseNativeEnumDef(def);
|
|
9961
|
+
case ZodFirstPartyTypeKind.ZodNullable:
|
|
9962
|
+
return parseNullableDef(def, refs);
|
|
9963
|
+
case ZodFirstPartyTypeKind.ZodOptional:
|
|
9964
|
+
return parseOptionalDef(def, refs);
|
|
9965
|
+
case ZodFirstPartyTypeKind.ZodMap:
|
|
9966
|
+
return parseMapDef(def, refs);
|
|
9967
|
+
case ZodFirstPartyTypeKind.ZodSet:
|
|
9968
|
+
return parseSetDef(def, refs);
|
|
9969
|
+
case ZodFirstPartyTypeKind.ZodLazy:
|
|
9970
|
+
return parseDef(def.getter()._def, refs);
|
|
9971
|
+
case ZodFirstPartyTypeKind.ZodPromise:
|
|
9972
|
+
return parsePromiseDef(def, refs);
|
|
9973
|
+
case ZodFirstPartyTypeKind.ZodNaN:
|
|
9974
|
+
case ZodFirstPartyTypeKind.ZodNever:
|
|
9975
|
+
return parseNeverDef();
|
|
9976
|
+
case ZodFirstPartyTypeKind.ZodEffects:
|
|
9977
|
+
return parseEffectsDef(def, refs, forceResolution);
|
|
9978
|
+
case ZodFirstPartyTypeKind.ZodAny:
|
|
9979
|
+
return parseAnyDef();
|
|
9980
|
+
case ZodFirstPartyTypeKind.ZodUnknown:
|
|
9981
|
+
return parseUnknownDef();
|
|
9982
|
+
case ZodFirstPartyTypeKind.ZodDefault:
|
|
9983
|
+
return parseDefaultDef(def, refs);
|
|
9984
|
+
case ZodFirstPartyTypeKind.ZodBranded:
|
|
9985
|
+
return parseBrandedDef(def, refs);
|
|
9986
|
+
case ZodFirstPartyTypeKind.ZodReadonly:
|
|
9987
|
+
return parseReadonlyDef(def, refs);
|
|
9988
|
+
case ZodFirstPartyTypeKind.ZodCatch:
|
|
9989
|
+
return parseCatchDef(def, refs);
|
|
9990
|
+
case ZodFirstPartyTypeKind.ZodPipeline:
|
|
9991
|
+
return parsePipelineDef(def, refs);
|
|
9992
|
+
case ZodFirstPartyTypeKind.ZodFunction:
|
|
9993
|
+
case ZodFirstPartyTypeKind.ZodVoid:
|
|
9994
|
+
case ZodFirstPartyTypeKind.ZodSymbol:
|
|
9995
|
+
return undefined;
|
|
9996
|
+
default:
|
|
9997
|
+
return ((_) => undefined)();
|
|
9998
|
+
}
|
|
9999
|
+
};
|
|
10000
|
+
const addMeta = (def, refs, jsonSchema) => {
|
|
10001
|
+
if (def.description) {
|
|
10002
|
+
jsonSchema.description = def.description;
|
|
10003
|
+
if (refs.markdownDescription) {
|
|
10004
|
+
jsonSchema.markdownDescription = def.description;
|
|
10005
|
+
}
|
|
10006
|
+
}
|
|
10007
|
+
return jsonSchema;
|
|
10008
|
+
};
|
|
10009
|
+
|
|
10010
|
+
const zodToJsonSchema = (schema, options) => {
|
|
10011
|
+
const refs = getRefs(options);
|
|
10012
|
+
const name = typeof options === 'string' ? options
|
|
10013
|
+
: options?.nameStrategy === 'title' ? undefined
|
|
10014
|
+
: options?.name;
|
|
10015
|
+
const main = parseDef(schema._def, name === undefined ? refs : ({
|
|
10016
|
+
...refs,
|
|
10017
|
+
currentPath: [...refs.basePath, refs.definitionPath, name],
|
|
10018
|
+
}), false) ?? {};
|
|
10019
|
+
const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ?
|
|
10020
|
+
options.name
|
|
10021
|
+
: undefined;
|
|
10022
|
+
if (title !== undefined) {
|
|
10023
|
+
main.title = title;
|
|
10024
|
+
}
|
|
10025
|
+
const definitions = (() => {
|
|
10026
|
+
if (isEmptyObj(refs.definitions)) {
|
|
10027
|
+
return undefined;
|
|
10028
|
+
}
|
|
10029
|
+
const definitions = {};
|
|
10030
|
+
const processedDefinitions = new Set();
|
|
10031
|
+
// the call to `parseDef()` here might itself add more entries to `.definitions`
|
|
10032
|
+
// so we need to continually evaluate definitions until we've resolved all of them
|
|
10033
|
+
//
|
|
10034
|
+
// we have a generous iteration limit here to avoid blowing up the stack if there
|
|
10035
|
+
// are any bugs that would otherwise result in us iterating indefinitely
|
|
10036
|
+
for (let i = 0; i < 500; i++) {
|
|
10037
|
+
const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key));
|
|
10038
|
+
if (newDefinitions.length === 0)
|
|
10039
|
+
break;
|
|
10040
|
+
for (const [key, schema] of newDefinitions) {
|
|
10041
|
+
definitions[key] =
|
|
10042
|
+
parseDef(zodDef(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {};
|
|
10043
|
+
processedDefinitions.add(key);
|
|
10044
|
+
}
|
|
10045
|
+
}
|
|
10046
|
+
return definitions;
|
|
10047
|
+
})();
|
|
10048
|
+
const combined = name === undefined ?
|
|
10049
|
+
definitions ?
|
|
10050
|
+
{
|
|
10051
|
+
...main,
|
|
10052
|
+
[refs.definitionPath]: definitions,
|
|
10053
|
+
}
|
|
10054
|
+
: main
|
|
10055
|
+
: refs.nameStrategy === 'duplicate-ref' ?
|
|
10056
|
+
{
|
|
10057
|
+
...main,
|
|
10058
|
+
...(definitions || refs.seenRefs.size ?
|
|
10059
|
+
{
|
|
10060
|
+
[refs.definitionPath]: {
|
|
10061
|
+
...definitions,
|
|
10062
|
+
// only actually duplicate the schema definition if it was ever referenced
|
|
10063
|
+
// otherwise the duplication is completely pointless
|
|
10064
|
+
...(refs.seenRefs.size ? { [name]: main } : undefined),
|
|
10065
|
+
},
|
|
10066
|
+
}
|
|
10067
|
+
: undefined),
|
|
10068
|
+
}
|
|
10069
|
+
: {
|
|
10070
|
+
$ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'),
|
|
10071
|
+
[refs.definitionPath]: {
|
|
10072
|
+
...definitions,
|
|
10073
|
+
[name]: main,
|
|
10074
|
+
},
|
|
10075
|
+
};
|
|
10076
|
+
if (refs.target === 'jsonSchema7') {
|
|
10077
|
+
combined.$schema = 'http://json-schema.org/draft-07/schema#';
|
|
10078
|
+
}
|
|
10079
|
+
else if (refs.target === 'jsonSchema2019-09') {
|
|
10080
|
+
combined.$schema = 'https://json-schema.org/draft/2019-09/schema#';
|
|
10081
|
+
}
|
|
10082
|
+
return combined;
|
|
10083
|
+
};
|
|
10084
|
+
|
|
10085
|
+
function toStrictJsonSchema(schema) {
|
|
10086
|
+
if (schema.type !== 'object') {
|
|
10087
|
+
throw new Error(`Root schema must have type: 'object' but got type: ${schema.type ? `'${schema.type}'` : 'undefined'}`);
|
|
10088
|
+
}
|
|
10089
|
+
const schemaCopy = structuredClone(schema);
|
|
10090
|
+
return ensureStrictJsonSchema(schemaCopy, [], schemaCopy);
|
|
10091
|
+
}
|
|
10092
|
+
function isNullable(schema) {
|
|
10093
|
+
if (typeof schema === 'boolean') {
|
|
10094
|
+
return false;
|
|
10095
|
+
}
|
|
10096
|
+
if (schema.type === 'null') {
|
|
10097
|
+
return true;
|
|
10098
|
+
}
|
|
10099
|
+
for (const oneOfVariant of schema.oneOf ?? []) {
|
|
10100
|
+
if (isNullable(oneOfVariant)) {
|
|
10101
|
+
return true;
|
|
10102
|
+
}
|
|
10103
|
+
}
|
|
10104
|
+
for (const allOfVariant of schema.anyOf ?? []) {
|
|
10105
|
+
if (isNullable(allOfVariant)) {
|
|
10106
|
+
return true;
|
|
10107
|
+
}
|
|
10108
|
+
}
|
|
10109
|
+
return false;
|
|
10110
|
+
}
|
|
10111
|
+
/**
|
|
10112
|
+
* Mutates the given JSON schema to ensure it conforms to the `strict` standard
|
|
10113
|
+
* that the API expects.
|
|
10114
|
+
*/
|
|
10115
|
+
function ensureStrictJsonSchema(jsonSchema, path, root) {
|
|
10116
|
+
if (typeof jsonSchema === 'boolean') {
|
|
10117
|
+
throw new TypeError(`Expected object schema but got boolean; path=${path.join('/')}`);
|
|
10118
|
+
}
|
|
10119
|
+
if (!isObject(jsonSchema)) {
|
|
10120
|
+
throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path.join('/')}`);
|
|
10121
|
+
}
|
|
10122
|
+
// Handle $defs (non-standard but sometimes used)
|
|
10123
|
+
const defs = jsonSchema.$defs;
|
|
10124
|
+
if (isObject(defs)) {
|
|
10125
|
+
for (const [defName, defSchema] of Object.entries(defs)) {
|
|
10126
|
+
ensureStrictJsonSchema(defSchema, [...path, '$defs', defName], root);
|
|
10127
|
+
}
|
|
10128
|
+
}
|
|
10129
|
+
// Handle definitions (draft-04 style, deprecated in draft-07 but still used)
|
|
10130
|
+
const definitions = jsonSchema.definitions;
|
|
10131
|
+
if (isObject(definitions)) {
|
|
10132
|
+
for (const [definitionName, definitionSchema] of Object.entries(definitions)) {
|
|
10133
|
+
ensureStrictJsonSchema(definitionSchema, [...path, 'definitions', definitionName], root);
|
|
10134
|
+
}
|
|
10135
|
+
}
|
|
10136
|
+
// Add additionalProperties: false to object types
|
|
10137
|
+
const typ = jsonSchema.type;
|
|
10138
|
+
if (typ === 'object' && !('additionalProperties' in jsonSchema)) {
|
|
10139
|
+
jsonSchema.additionalProperties = false;
|
|
10140
|
+
}
|
|
10141
|
+
const required = jsonSchema.required ?? [];
|
|
10142
|
+
// Handle object properties
|
|
10143
|
+
const properties = jsonSchema.properties;
|
|
10144
|
+
if (isObject(properties)) {
|
|
10145
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
10146
|
+
if (!isNullable(value) && !required.includes(key)) {
|
|
10147
|
+
throw new Error(`Zod field at \`${[...path, 'properties', key].join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);
|
|
10148
|
+
}
|
|
10149
|
+
}
|
|
10150
|
+
jsonSchema.required = Object.keys(properties);
|
|
10151
|
+
jsonSchema.properties = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [
|
|
10152
|
+
key,
|
|
10153
|
+
ensureStrictJsonSchema(propSchema, [...path, 'properties', key], root),
|
|
10154
|
+
]));
|
|
10155
|
+
}
|
|
10156
|
+
// Handle arrays
|
|
10157
|
+
const items = jsonSchema.items;
|
|
10158
|
+
if (isObject(items)) {
|
|
10159
|
+
jsonSchema.items = ensureStrictJsonSchema(items, [...path, 'items'], root);
|
|
10160
|
+
}
|
|
10161
|
+
// Handle unions (anyOf)
|
|
10162
|
+
const anyOf = jsonSchema.anyOf;
|
|
10163
|
+
if (Array.isArray(anyOf)) {
|
|
10164
|
+
jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path, 'anyOf', String(i)], root));
|
|
10165
|
+
}
|
|
10166
|
+
// Handle intersections (allOf)
|
|
10167
|
+
const allOf = jsonSchema.allOf;
|
|
10168
|
+
if (Array.isArray(allOf)) {
|
|
10169
|
+
if (allOf.length === 1) {
|
|
10170
|
+
const resolved = ensureStrictJsonSchema(allOf[0], [...path, 'allOf', '0'], root);
|
|
10171
|
+
Object.assign(jsonSchema, resolved);
|
|
10172
|
+
delete jsonSchema.allOf;
|
|
10173
|
+
}
|
|
10174
|
+
else {
|
|
10175
|
+
jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path, 'allOf', String(i)], root));
|
|
10176
|
+
}
|
|
10177
|
+
}
|
|
10178
|
+
// Strip `null` defaults as there's no meaningful distinction
|
|
10179
|
+
if (jsonSchema.default === null) {
|
|
10180
|
+
delete jsonSchema.default;
|
|
10181
|
+
}
|
|
10182
|
+
// Handle $ref with additional properties
|
|
10183
|
+
const ref = jsonSchema.$ref;
|
|
10184
|
+
if (ref && hasMoreThanNKeys(jsonSchema, 1)) {
|
|
10185
|
+
if (typeof ref !== 'string') {
|
|
10186
|
+
throw new TypeError(`Received non-string $ref - ${ref}; path=${path.join('/')}`);
|
|
10187
|
+
}
|
|
10188
|
+
const resolved = resolveRef(root, ref);
|
|
10189
|
+
if (typeof resolved === 'boolean') {
|
|
10190
|
+
throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object schema but got boolean`);
|
|
10191
|
+
}
|
|
10192
|
+
if (!isObject(resolved)) {
|
|
10193
|
+
throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object but got ${JSON.stringify(resolved)}`);
|
|
10194
|
+
}
|
|
10195
|
+
// Properties from the json schema take priority over the ones on the `$ref`
|
|
10196
|
+
Object.assign(jsonSchema, { ...resolved, ...jsonSchema });
|
|
10197
|
+
delete jsonSchema.$ref;
|
|
10198
|
+
// Since the schema expanded from `$ref` might not have `additionalProperties: false` applied,
|
|
10199
|
+
// we call `ensureStrictJsonSchema` again to fix the inlined schema and ensure it's valid.
|
|
10200
|
+
return ensureStrictJsonSchema(jsonSchema, path, root);
|
|
10201
|
+
}
|
|
10202
|
+
return jsonSchema;
|
|
10203
|
+
}
|
|
10204
|
+
function resolveRef(root, ref) {
|
|
10205
|
+
if (!ref.startsWith('#/')) {
|
|
10206
|
+
throw new Error(`Unexpected $ref format ${JSON.stringify(ref)}; Does not start with #/`);
|
|
10207
|
+
}
|
|
10208
|
+
const pathParts = ref.slice(2).split('/');
|
|
10209
|
+
let resolved = root;
|
|
10210
|
+
for (const key of pathParts) {
|
|
10211
|
+
if (!isObject(resolved)) {
|
|
10212
|
+
throw new Error(`encountered non-object entry while resolving ${ref} - ${JSON.stringify(resolved)}`);
|
|
10213
|
+
}
|
|
10214
|
+
const value = resolved[key];
|
|
10215
|
+
if (value === undefined) {
|
|
10216
|
+
throw new Error(`Key ${key} not found while resolving ${ref}`);
|
|
10217
|
+
}
|
|
10218
|
+
resolved = value;
|
|
10219
|
+
}
|
|
10220
|
+
return resolved;
|
|
10221
|
+
}
|
|
10222
|
+
function isObject(obj) {
|
|
10223
|
+
return typeof obj === 'object' && obj !== null && !Array.isArray(obj);
|
|
10224
|
+
}
|
|
10225
|
+
function hasMoreThanNKeys(obj, n) {
|
|
10226
|
+
let i = 0;
|
|
10227
|
+
for (const _ in obj) {
|
|
10228
|
+
i++;
|
|
10229
|
+
if (i > n) {
|
|
10230
|
+
return true;
|
|
10231
|
+
}
|
|
10232
|
+
}
|
|
10233
|
+
return false;
|
|
10234
|
+
}
|
|
10235
|
+
|
|
10236
|
+
function zodV3ToJsonSchema(schema, options) {
|
|
10237
|
+
return zodToJsonSchema(schema, {
|
|
10238
|
+
openaiStrictMode: true,
|
|
10239
|
+
name: options.name,
|
|
10240
|
+
nameStrategy: 'duplicate-ref',
|
|
10241
|
+
$refStrategy: 'extract-to-root',
|
|
10242
|
+
nullableStrategy: 'property',
|
|
10243
|
+
});
|
|
10244
|
+
}
|
|
10245
|
+
function zodV4ToJsonSchema(schema) {
|
|
10246
|
+
return toStrictJsonSchema(toJSONSchema(schema, {
|
|
10247
|
+
target: 'draft-7',
|
|
10248
|
+
}));
|
|
10249
|
+
}
|
|
10250
|
+
function isZodV4(zodObject) {
|
|
10251
|
+
return '_zod' in zodObject;
|
|
10252
|
+
}
|
|
10253
|
+
function zodTextFormat(zodObject, name, props) {
|
|
10254
|
+
return makeParseableTextFormat({
|
|
10255
|
+
type: 'json_schema',
|
|
10256
|
+
...props,
|
|
10257
|
+
name,
|
|
10258
|
+
strict: true,
|
|
10259
|
+
schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }),
|
|
10260
|
+
}, (content) => zodObject.parse(JSON.parse(content)));
|
|
10261
|
+
}
|
|
10262
|
+
|
|
10263
|
+
// llm-openai-config.ts
|
|
10264
|
+
const DEFAULT_MODEL = 'gpt-4.1-mini';
|
|
10265
|
+
const GPT_5_4_HIGH_CONTEXT_THRESHOLD_TOKENS = 272_000;
|
|
10266
|
+
const GPT_5_4_HIGH_CONTEXT_INPUT_MULTIPLIER = 2;
|
|
10267
|
+
const GPT_5_4_HIGH_CONTEXT_OUTPUT_MULTIPLIER = 1.5;
|
|
10268
|
+
/** Token costs in USD per 1M tokens. Last updated Mar 2026. */
|
|
10269
|
+
const openAiModelCosts = {
|
|
10270
|
+
'gpt-4o': {
|
|
10271
|
+
inputCost: 2.5 / 1_000_000,
|
|
10272
|
+
cacheHitCost: 1.25 / 1_000_000,
|
|
10273
|
+
outputCost: 10 / 1_000_000,
|
|
10274
|
+
},
|
|
10275
|
+
'gpt-4o-mini': {
|
|
10276
|
+
inputCost: 0.15 / 1_000_000,
|
|
10277
|
+
cacheHitCost: 0.075 / 1_000_000,
|
|
10278
|
+
outputCost: 0.6 / 1_000_000,
|
|
10279
|
+
},
|
|
10280
|
+
'o1-mini': {
|
|
10281
|
+
inputCost: 1.1 / 1_000_000,
|
|
10282
|
+
cacheHitCost: 0.55 / 1_000_000,
|
|
10283
|
+
outputCost: 4.4 / 1_000_000,
|
|
10284
|
+
},
|
|
10285
|
+
'o1': {
|
|
10286
|
+
inputCost: 15 / 1_000_000,
|
|
10287
|
+
cacheHitCost: 7.5 / 1_000_000,
|
|
10288
|
+
outputCost: 60 / 1_000_000,
|
|
10289
|
+
},
|
|
10290
|
+
'o3-mini': {
|
|
10291
|
+
inputCost: 1.1 / 1_000_000,
|
|
10292
|
+
cacheHitCost: 0.55 / 1_000_000,
|
|
10293
|
+
outputCost: 4.4 / 1_000_000,
|
|
10294
|
+
},
|
|
10295
|
+
'o3': {
|
|
10296
|
+
inputCost: 2 / 1_000_000,
|
|
10297
|
+
cacheHitCost: 0.5 / 1_000_000,
|
|
10298
|
+
outputCost: 8 / 1_000_000,
|
|
10299
|
+
},
|
|
10300
|
+
'gpt-4.1': {
|
|
10301
|
+
inputCost: 2 / 1_000_000,
|
|
10302
|
+
cacheHitCost: 0.5 / 1_000_000,
|
|
10303
|
+
outputCost: 8 / 1_000_000,
|
|
10304
|
+
},
|
|
10305
|
+
'gpt-4.1-mini': {
|
|
10306
|
+
inputCost: 0.4 / 1_000_000,
|
|
10307
|
+
cacheHitCost: 0.1 / 1_000_000,
|
|
10308
|
+
outputCost: 1.6 / 1_000_000,
|
|
10309
|
+
},
|
|
10310
|
+
'gpt-4.1-nano': {
|
|
10311
|
+
inputCost: 0.1 / 1_000_000,
|
|
10312
|
+
cacheHitCost: 0.025 / 1_000_000,
|
|
10313
|
+
outputCost: 0.4 / 1_000_000,
|
|
10314
|
+
},
|
|
10315
|
+
'gpt-5': {
|
|
10316
|
+
inputCost: 1.25 / 1_000_000,
|
|
10317
|
+
cacheHitCost: 0.125 / 1_000_000,
|
|
10318
|
+
outputCost: 10 / 1_000_000,
|
|
10319
|
+
},
|
|
10320
|
+
'gpt-5-mini': {
|
|
10321
|
+
inputCost: 0.25 / 1_000_000,
|
|
10322
|
+
cacheHitCost: 0.025 / 1_000_000,
|
|
10323
|
+
outputCost: 2 / 1_000_000,
|
|
10324
|
+
},
|
|
10325
|
+
'gpt-5-nano': {
|
|
10326
|
+
inputCost: 0.05 / 1_000_000,
|
|
10327
|
+
cacheHitCost: 0.005 / 1_000_000,
|
|
10328
|
+
outputCost: 0.4 / 1_000_000,
|
|
10329
|
+
},
|
|
10330
|
+
'gpt-5.1': {
|
|
10331
|
+
inputCost: 1.25 / 1_000_000,
|
|
10332
|
+
cacheHitCost: 0.125 / 1_000_000,
|
|
10333
|
+
outputCost: 10 / 1_000_000,
|
|
10334
|
+
},
|
|
10335
|
+
'gpt-5.4': {
|
|
10336
|
+
inputCost: 2.5 / 1_000_000,
|
|
10337
|
+
cacheHitCost: 0.25 / 1_000_000,
|
|
10338
|
+
outputCost: 15 / 1_000_000,
|
|
10339
|
+
},
|
|
10340
|
+
'gpt-5.4-pro': {
|
|
10341
|
+
inputCost: 30 / 1_000_000,
|
|
10342
|
+
outputCost: 180 / 1_000_000,
|
|
10343
|
+
},
|
|
10344
|
+
'gpt-5.2': {
|
|
10345
|
+
inputCost: 1.75 / 1_000_000,
|
|
10346
|
+
cacheHitCost: 0.175 / 1_000_000,
|
|
10347
|
+
outputCost: 14 / 1_000_000,
|
|
10348
|
+
},
|
|
10349
|
+
'gpt-5.2-pro': {
|
|
10350
|
+
inputCost: 21 / 1_000_000,
|
|
10351
|
+
outputCost: 168 / 1_000_000,
|
|
10352
|
+
},
|
|
10353
|
+
'gpt-5.1-codex': {
|
|
10354
|
+
inputCost: 1.25 / 1_000_000,
|
|
10355
|
+
cacheHitCost: 0.125 / 1_000_000,
|
|
10356
|
+
outputCost: 10 / 1_000_000,
|
|
10357
|
+
},
|
|
10358
|
+
'gpt-5.1-codex-max': {
|
|
10359
|
+
inputCost: 1.25 / 1_000_000,
|
|
10360
|
+
cacheHitCost: 0.125 / 1_000_000,
|
|
10361
|
+
outputCost: 10 / 1_000_000,
|
|
10362
|
+
},
|
|
10363
|
+
'o4-mini': {
|
|
10364
|
+
inputCost: 1.1 / 1_000_000,
|
|
10365
|
+
cacheHitCost: 0.275 / 1_000_000,
|
|
10366
|
+
outputCost: 4.4 / 1_000_000,
|
|
10367
|
+
},
|
|
10368
|
+
};
|
|
10369
|
+
const deepseekModelCosts = {
|
|
10370
|
+
'deepseek-chat': {
|
|
10371
|
+
inputCost: 0.27 / 1_000_000, // $0.27 per 1M tokens (Cache miss price)
|
|
10372
|
+
cacheHitCost: 0.07 / 1_000_000, // $0.07 per 1M tokens (Cache hit price)
|
|
10373
|
+
outputCost: 1.1 / 1_000_000, // $1.10 per 1M tokens
|
|
10374
|
+
},
|
|
10375
|
+
'deepseek-reasoner': {
|
|
10376
|
+
inputCost: 0.55 / 1_000_000, // $0.55 per 1M tokens (Cache miss price)
|
|
10377
|
+
cacheHitCost: 0.14 / 1_000_000, // $0.14 per 1M tokens (Cache hit price)
|
|
10378
|
+
outputCost: 2.19 / 1_000_000, // $2.19 per 1M tokens
|
|
10379
|
+
},
|
|
10380
|
+
};
|
|
10381
|
+
function shouldUseGPT54HighContextPricing(model, inputTokens) {
|
|
10382
|
+
return (model === 'gpt-5.4' || model === 'gpt-5.4-pro') && inputTokens > GPT_5_4_HIGH_CONTEXT_THRESHOLD_TOKENS;
|
|
10383
|
+
}
|
|
10384
|
+
/** Image generation costs in USD per image. Based on OpenAI pricing as of Feb 2025. */
|
|
10385
|
+
const openAiImageCosts = {
|
|
10386
|
+
'gpt-image-1': 0.0075, // $0.0075 per image for gpt-image-1
|
|
10387
|
+
'gpt-image-1.5': 0.0075, // Assumes parity pricing with gpt-image-1 until OpenAI publishes updated rates
|
|
10388
|
+
};
|
|
10389
|
+
/**
|
|
10390
|
+
* Calculates the cost of generating images using OpenAI's Images API.
|
|
10391
|
+
*
|
|
10392
|
+
* @param model The image generation model name.
|
|
10393
|
+
* @param imageCount The number of images generated.
|
|
10394
|
+
* @returns The cost of generating the images in USD.
|
|
10395
|
+
*/
|
|
10396
|
+
function calculateImageCost(model, imageCount) {
|
|
10397
|
+
if (typeof model !== 'string' || typeof imageCount !== 'number' || imageCount <= 0) {
|
|
10398
|
+
return 0;
|
|
10399
|
+
}
|
|
10400
|
+
const costPerImage = openAiImageCosts[model];
|
|
10401
|
+
if (!costPerImage)
|
|
10402
|
+
return 0;
|
|
10403
|
+
return imageCount * costPerImage;
|
|
10404
|
+
}
|
|
10405
|
+
/**
|
|
10406
|
+
* Calculates the cost of calling a language model in USD based on the provider and model, tokens, and given costs per 1M tokens.
|
|
10407
|
+
*
|
|
10408
|
+
* @param provider The provider of the language model. Supported providers are 'openai' and 'deepseek'.
|
|
10409
|
+
* @param model The name of the language model. Supported models are listed in the `openAiModelCosts` and `deepseekModelCosts` objects.
|
|
10410
|
+
* @param inputTokens The number of input tokens passed to the language model.
|
|
10411
|
+
* @param outputTokens The number of output tokens generated by the language model.
|
|
10412
|
+
* @param reasoningTokens The number of output tokens generated by the language model for reasoning.
|
|
10413
|
+
* @param cacheHitTokens The number of input tokens billed at cached-input rates.
|
|
10414
|
+
* @returns The cost of calling the language model in USD.
|
|
10415
|
+
*/
|
|
10416
|
+
function calculateCost(provider, model, inputTokens, outputTokens, reasoningTokens, cacheHitTokens) {
|
|
10417
|
+
if (typeof provider !== 'string' ||
|
|
10418
|
+
typeof model !== 'string' ||
|
|
10419
|
+
typeof inputTokens !== 'number' ||
|
|
10420
|
+
typeof outputTokens !== 'number' ||
|
|
10421
|
+
(reasoningTokens !== undefined && typeof reasoningTokens !== 'number') ||
|
|
10422
|
+
(cacheHitTokens !== undefined && typeof cacheHitTokens !== 'number')) {
|
|
10423
|
+
return 0;
|
|
10424
|
+
}
|
|
10425
|
+
const modelCosts = provider === 'deepseek' ? deepseekModelCosts[model] : openAiModelCosts[model];
|
|
10426
|
+
if (!modelCosts)
|
|
10427
|
+
return 0;
|
|
10428
|
+
const boundedCacheHitTokens = Math.min(Math.max(cacheHitTokens || 0, 0), inputTokens);
|
|
10429
|
+
let inputCost = inputTokens * modelCosts.inputCost;
|
|
10430
|
+
if (typeof modelCosts.cacheHitCost === 'number' && boundedCacheHitTokens > 0) {
|
|
10431
|
+
inputCost = boundedCacheHitTokens * modelCosts.cacheHitCost + (inputTokens - boundedCacheHitTokens) * modelCosts.inputCost;
|
|
10432
|
+
}
|
|
10433
|
+
let outputCost = outputTokens * modelCosts.outputCost;
|
|
10434
|
+
let reasoningCost = (reasoningTokens || 0) * modelCosts.outputCost;
|
|
10435
|
+
if (provider === 'openai' && shouldUseGPT54HighContextPricing(model, inputTokens)) {
|
|
10436
|
+
inputCost *= GPT_5_4_HIGH_CONTEXT_INPUT_MULTIPLIER;
|
|
10437
|
+
outputCost *= GPT_5_4_HIGH_CONTEXT_OUTPUT_MULTIPLIER;
|
|
10438
|
+
reasoningCost *= GPT_5_4_HIGH_CONTEXT_OUTPUT_MULTIPLIER;
|
|
10439
|
+
}
|
|
10440
|
+
return inputCost + outputCost + reasoningCost;
|
|
10441
|
+
}
|
|
10442
|
+
|
|
10443
|
+
/**
|
|
10444
|
+
* Fix a broken JSON string by attempting to extract and parse valid JSON content. This function is very lenient and will attempt to fix many types of JSON errors, including unbalanced brackets, missing or extra commas, improperly escaped $ signs, unquoted strings, trailing commas, missing closing brackets or braces, etc.
|
|
10445
|
+
* @param {string} jsonStr - The broken JSON string to fix
|
|
10446
|
+
* @returns {JsonValue} - The parsed JSON value
|
|
10447
|
+
*/
|
|
10448
|
+
function fixBrokenJson(jsonStr) {
|
|
10449
|
+
// Pre-process: Fix improperly escaped $ signs
|
|
10450
|
+
jsonStr = jsonStr.replace(/\\\$/g, '$');
|
|
10451
|
+
let index = 0;
|
|
10452
|
+
function parse() {
|
|
10453
|
+
const results = [];
|
|
10454
|
+
while (index < jsonStr.length) {
|
|
10455
|
+
skipWhitespace();
|
|
10456
|
+
const value = parseValue();
|
|
10457
|
+
if (value !== undefined) {
|
|
10458
|
+
results.push(value);
|
|
10459
|
+
}
|
|
10460
|
+
else {
|
|
10461
|
+
index++; // Skip invalid character
|
|
10462
|
+
}
|
|
10463
|
+
}
|
|
10464
|
+
return results.length === 1 ? results[0] : results;
|
|
10465
|
+
}
|
|
10466
|
+
function parseValue() {
|
|
10467
|
+
skipWhitespace();
|
|
10468
|
+
const char = getChar();
|
|
10469
|
+
if (!char)
|
|
10470
|
+
return undefined;
|
|
10471
|
+
if (char === '{')
|
|
10472
|
+
return parseObject();
|
|
10473
|
+
if (char === '[')
|
|
10474
|
+
return parseArray();
|
|
10475
|
+
if (char === '"' || char === "'")
|
|
10476
|
+
return parseString();
|
|
10477
|
+
if (char === 't' && jsonStr.slice(index, index + 4).toLowerCase() === 'true') {
|
|
10478
|
+
index += 4;
|
|
10479
|
+
return true;
|
|
10480
|
+
}
|
|
10481
|
+
if (char === 'f' && jsonStr.slice(index, index + 5).toLowerCase() === 'false') {
|
|
10482
|
+
index += 5;
|
|
10483
|
+
return false;
|
|
10484
|
+
}
|
|
10485
|
+
if (char === 'n' && jsonStr.slice(index, index + 4).toLowerCase() === 'null') {
|
|
10486
|
+
index += 4;
|
|
10487
|
+
return null;
|
|
10488
|
+
}
|
|
10489
|
+
if (/[a-zA-Z]/.test(char))
|
|
10490
|
+
return parseString(); // Unquoted string
|
|
10491
|
+
if (char === '-' || char === '.' || /\d/.test(char))
|
|
10492
|
+
return parseNumber();
|
|
10493
|
+
return undefined; // Unknown character
|
|
10494
|
+
}
|
|
10495
|
+
function parseObject() {
|
|
7708
10496
|
const obj = {};
|
|
7709
10497
|
index++; // Skip opening brace
|
|
7710
10498
|
skipWhitespace();
|
|
@@ -8118,6 +10906,32 @@ function supportsStructuredOutputs(model) {
|
|
|
8118
10906
|
function supportsDistillation(model) {
|
|
8119
10907
|
return normalizeModelName(model) !== 'gpt-5.4-pro';
|
|
8120
10908
|
}
|
|
10909
|
+
function isZodSchema(schema) {
|
|
10910
|
+
return typeof schema === 'object' && schema !== null && 'safeParse' in schema;
|
|
10911
|
+
}
|
|
10912
|
+
function buildJsonSchemaFormat(schema, schemaName, schemaDescription, schemaStrict) {
|
|
10913
|
+
if (isZodSchema(schema)) {
|
|
10914
|
+
const zodFormat = zodTextFormat(schema, schemaName, schemaDescription
|
|
10915
|
+
? {
|
|
10916
|
+
description: schemaDescription,
|
|
10917
|
+
}
|
|
10918
|
+
: undefined);
|
|
10919
|
+
return {
|
|
10920
|
+
type: 'json_schema',
|
|
10921
|
+
name: zodFormat.name,
|
|
10922
|
+
schema: zodFormat.schema,
|
|
10923
|
+
...(zodFormat.description ? { description: zodFormat.description } : {}),
|
|
10924
|
+
...(schemaStrict !== undefined ? { strict: schemaStrict } : { strict: zodFormat.strict }),
|
|
10925
|
+
};
|
|
10926
|
+
}
|
|
10927
|
+
return {
|
|
10928
|
+
type: 'json_schema',
|
|
10929
|
+
name: schemaName,
|
|
10930
|
+
schema,
|
|
10931
|
+
...(schemaDescription ? { description: schemaDescription } : {}),
|
|
10932
|
+
...(schemaStrict !== undefined ? { strict: schemaStrict } : {}),
|
|
10933
|
+
};
|
|
10934
|
+
}
|
|
8121
10935
|
/**
|
|
8122
10936
|
* Makes a call to OpenAI's Responses API for more advanced use cases with built-in tools.
|
|
8123
10937
|
*
|
|
@@ -8225,9 +11039,13 @@ const makeResponsesAPICall = async (input, options = {}) => {
|
|
|
8225
11039
|
.join('') || '';
|
|
8226
11040
|
// Determine the format for parsing the response
|
|
8227
11041
|
let parsingFormat = 'text';
|
|
8228
|
-
|
|
11042
|
+
const requestedFormat = requestBody.text?.format;
|
|
11043
|
+
if (requestedFormat?.type === 'json_object') {
|
|
8229
11044
|
parsingFormat = 'json';
|
|
8230
11045
|
}
|
|
11046
|
+
else if (requestedFormat?.type === 'json_schema') {
|
|
11047
|
+
parsingFormat = requestedFormat;
|
|
11048
|
+
}
|
|
8231
11049
|
// Handle regular responses
|
|
8232
11050
|
const parsedResponse = await parseResponse(textContent, parsingFormat);
|
|
8233
11051
|
if (parsedResponse === null) {
|
|
@@ -8265,7 +11083,7 @@ const makeResponsesAPICall = async (input, options = {}) => {
|
|
|
8265
11083
|
* });
|
|
8266
11084
|
*/
|
|
8267
11085
|
async function makeLLMCall(input, options = {}) {
|
|
8268
|
-
const { apiKey, model = DEFAULT_MODEL, responseFormat = 'text', tools, useCodeInterpreter = false, useWebSearch = false, imageBase64, imageDetail = 'high', context, } = options;
|
|
11086
|
+
const { apiKey, model = DEFAULT_MODEL, responseFormat = 'text', schema, schemaName = 'response', schemaDescription, schemaStrict, tools, useCodeInterpreter = false, useWebSearch = false, imageBase64, imageDetail = 'high', context, } = options;
|
|
8269
11087
|
// Validate model
|
|
8270
11088
|
const normalizedModel = normalizeModelName(model);
|
|
8271
11089
|
if (!isSupportedModel(normalizedModel)) {
|
|
@@ -8343,9 +11161,17 @@ async function makeLLMCall(input, options = {}) {
|
|
|
8343
11161
|
responsesOptions.temperature = 0.2;
|
|
8344
11162
|
}
|
|
8345
11163
|
// Configure response format
|
|
8346
|
-
if (
|
|
11164
|
+
if (schema) {
|
|
11165
|
+
responsesOptions.text = {
|
|
11166
|
+
format: buildJsonSchemaFormat(schema, schemaName, schemaDescription, schemaStrict),
|
|
11167
|
+
};
|
|
11168
|
+
}
|
|
11169
|
+
else if (responseFormat === 'json') {
|
|
8347
11170
|
responsesOptions.text = { format: { type: 'json_object' } };
|
|
8348
11171
|
}
|
|
11172
|
+
else if (typeof responseFormat === 'object' && responseFormat.type === 'json_schema') {
|
|
11173
|
+
responsesOptions.text = { format: responseFormat };
|
|
11174
|
+
}
|
|
8349
11175
|
// Configure built-in tools
|
|
8350
11176
|
if (useCodeInterpreter) {
|
|
8351
11177
|
responsesOptions.tools = [{ type: 'code_interpreter', container: { type: 'auto' } }];
|