@hongymagic/q 2026.422.0 → 2026.427.0-next.3a1fca4

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.
Files changed (2) hide show
  1. package/dist/q.js +457 -1921
  2. package/package.json +3 -3
package/dist/q.js CHANGED
@@ -3949,14 +3949,14 @@ var require_cross_spawn = __commonJS((exports, module) => {
3949
3949
  // node_modules/run-jxa/node_modules/execa/node_modules/strip-final-newline/index.js
3950
3950
  var require_strip_final_newline = __commonJS((exports, module) => {
3951
3951
  module.exports = (input) => {
3952
- const LF = typeof input === "string" ? `
3952
+ const LF2 = typeof input === "string" ? `
3953
3953
  ` : `
3954
3954
  `.charCodeAt();
3955
- const CR = typeof input === "string" ? "\r" : "\r".charCodeAt();
3956
- if (input[input.length - 1] === LF) {
3955
+ const CR2 = typeof input === "string" ? "\r" : "\r".charCodeAt();
3956
+ if (input[input.length - 1] === LF2) {
3957
3957
  input = input.slice(0, input.length - 1);
3958
3958
  }
3959
- if (input[input.length - 1] === CR) {
3959
+ if (input[input.length - 1] === CR2) {
3960
3960
  input = input.slice(0, input.length - 1);
3961
3961
  }
3962
3962
  return input;
@@ -7826,11 +7826,11 @@ import { stripVTControlCharacters } from "node:util";
7826
7826
  var joinCommand = (filePath, rawArguments) => {
7827
7827
  const fileAndArguments = [filePath, ...rawArguments];
7828
7828
  const command = fileAndArguments.join(" ");
7829
- const escapedCommand = fileAndArguments.map((fileAndArgument) => quoteString(escapeControlCharacters(fileAndArgument))).join(" ");
7829
+ const escapedCommand = fileAndArguments.map((fileAndArgument) => quoteString(escapeControlCharacters2(fileAndArgument))).join(" ");
7830
7830
  return { command, escapedCommand };
7831
7831
  }, escapeLines = (lines) => stripVTControlCharacters(lines).split(`
7832
- `).map((line) => escapeControlCharacters(line)).join(`
7833
- `), escapeControlCharacters = (line) => line.replaceAll(SPECIAL_CHAR_REGEXP, (character) => escapeControlCharacter(character)), escapeControlCharacter = (character) => {
7832
+ `).map((line) => escapeControlCharacters2(line)).join(`
7833
+ `), escapeControlCharacters2 = (line) => line.replaceAll(SPECIAL_CHAR_REGEXP, (character) => escapeControlCharacter(character)), escapeControlCharacter = (character) => {
7834
7834
  const commonEscape = COMMON_ESCAPES[character];
7835
7835
  if (commonEscape !== undefined) {
7836
7836
  return commonEscape;
@@ -9827,11 +9827,11 @@ function stripFinalNewline(input) {
9827
9827
  }
9828
9828
  return stripFinalNewlineBinary(input);
9829
9829
  }
9830
- var stripFinalNewlineString = (input) => input.at(-1) === LF ? input.slice(0, input.at(-2) === CR ? -2 : -1) : input, stripFinalNewlineBinary = (input) => input.at(-1) === LF_BINARY ? input.subarray(0, input.at(-2) === CR_BINARY ? -2 : -1) : input, LF = `
9831
- `, LF_BINARY, CR = "\r", CR_BINARY;
9830
+ var stripFinalNewlineString = (input) => input.at(-1) === LF2 ? input.slice(0, input.at(-2) === CR2 ? -2 : -1) : input, stripFinalNewlineBinary = (input) => input.at(-1) === LF_BINARY ? input.subarray(0, input.at(-2) === CR_BINARY ? -2 : -1) : input, LF2 = `
9831
+ `, LF_BINARY, CR2 = "\r", CR_BINARY;
9832
9832
  var init_strip_final_newline = __esm(() => {
9833
- LF_BINARY = LF.codePointAt(0);
9834
- CR_BINARY = CR.codePointAt(0);
9833
+ LF_BINARY = LF2.codePointAt(0);
9834
+ CR_BINARY = CR2.codePointAt(0);
9835
9835
  });
9836
9836
 
9837
9837
  // node_modules/is-stream/index.js
@@ -11486,8 +11486,8 @@ var getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binar
11486
11486
  yield previousChunks;
11487
11487
  }
11488
11488
  }, getAppendNewlineGenerator = ({ binary, preserveNewlines, readableObjectMode, state }) => binary || preserveNewlines || readableObjectMode ? undefined : { transform: appendNewlineGenerator.bind(undefined, state) }, appendNewlineGenerator = function* ({ isWindowsNewline = false }, chunk) {
11489
- const { unixNewline, windowsNewline, LF: LF2, concatBytes } = typeof chunk === "string" ? linesStringInfo : linesUint8ArrayInfo;
11490
- if (chunk.at(-1) === LF2) {
11489
+ const { unixNewline, windowsNewline, LF: LF3, concatBytes } = typeof chunk === "string" ? linesStringInfo : linesUint8ArrayInfo;
11490
+ if (chunk.at(-1) === LF3) {
11491
11491
  yield chunk;
11492
11492
  return;
11493
11493
  }
@@ -12115,7 +12115,7 @@ var init_main_sync = __esm(() => {
12115
12115
 
12116
12116
  // node_modules/execa/lib/ipc/get-one.js
12117
12117
  import { once as once5, on as on2 } from "node:events";
12118
- var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = true, filter: filter3 } = {}) => {
12118
+ var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = true, filter: filter2 } = {}) => {
12119
12119
  validateIpcMethod({
12120
12120
  methodName: "getOneMessage",
12121
12121
  isSubprocess,
@@ -12126,16 +12126,16 @@ var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = t
12126
12126
  anyProcess,
12127
12127
  channel,
12128
12128
  isSubprocess,
12129
- filter: filter3,
12129
+ filter: filter2,
12130
12130
  reference
12131
12131
  });
12132
- }, getOneMessageAsync = async ({ anyProcess, channel, isSubprocess, filter: filter3, reference }) => {
12132
+ }, getOneMessageAsync = async ({ anyProcess, channel, isSubprocess, filter: filter2, reference }) => {
12133
12133
  addReference(channel, reference);
12134
12134
  const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);
12135
12135
  const controller = new AbortController;
12136
12136
  try {
12137
12137
  return await Promise.race([
12138
- getMessage(ipcEmitter, filter3, controller),
12138
+ getMessage(ipcEmitter, filter2, controller),
12139
12139
  throwOnDisconnect2(ipcEmitter, isSubprocess, controller),
12140
12140
  throwOnStrictError(ipcEmitter, isSubprocess, controller)
12141
12141
  ]);
@@ -12146,13 +12146,13 @@ var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = t
12146
12146
  controller.abort();
12147
12147
  removeReference(channel, reference);
12148
12148
  }
12149
- }, getMessage = async (ipcEmitter, filter3, { signal }) => {
12150
- if (filter3 === undefined) {
12149
+ }, getMessage = async (ipcEmitter, filter2, { signal }) => {
12150
+ if (filter2 === undefined) {
12151
12151
  const [message] = await once5(ipcEmitter, "message", { signal });
12152
12152
  return message;
12153
12153
  }
12154
12154
  for await (const [message] of on2(ipcEmitter, "message", { signal })) {
12155
- if (filter3(message)) {
12155
+ if (filter2(message)) {
12156
12156
  return message;
12157
12157
  }
12158
12158
  }
@@ -12503,7 +12503,7 @@ var getHighWaterMark = (streams, objectMode) => {
12503
12503
  if (signal.aborted || !streams.has(stream)) {
12504
12504
  return;
12505
12505
  }
12506
- if (isAbortError3(error48)) {
12506
+ if (isAbortError2(error48)) {
12507
12507
  aborted2.add(stream);
12508
12508
  } else {
12509
12509
  errorStream(passThroughStream, error48);
@@ -12522,12 +12522,12 @@ var getHighWaterMark = (streams, objectMode) => {
12522
12522
  stream.end();
12523
12523
  }
12524
12524
  }, errorOrAbortStream = (stream, error48) => {
12525
- if (isAbortError3(error48)) {
12525
+ if (isAbortError2(error48)) {
12526
12526
  abortStream(stream);
12527
12527
  } else {
12528
12528
  errorStream(stream, error48);
12529
12529
  }
12530
- }, isAbortError3 = (error48) => error48?.code === "ERR_STREAM_PREMATURE_CLOSE", abortStream = (stream) => {
12530
+ }, isAbortError2 = (error48) => error48?.code === "ERR_STREAM_PREMATURE_CLOSE", abortStream = (stream) => {
12531
12531
  if (stream.readable || stream.writable) {
12532
12532
  stream.destroy();
12533
12533
  }
@@ -14720,6 +14720,7 @@ var init_clipboardy = __esm(() => {
14720
14720
  var exports_ansi = {};
14721
14721
  __export(exports_ansi, {
14722
14722
  stripAnsi: () => stripAnsi2,
14723
+ sanitizeForTerminal: () => sanitizeForTerminal2,
14723
14724
  sanitizeForClipboard: () => sanitizeForClipboard,
14724
14725
  createAnsiStripper: () => createAnsiStripper2
14725
14726
  });
@@ -14728,14 +14729,26 @@ function stripAnsi2(str) {
14728
14729
  return str;
14729
14730
  return str.replace(ANSI_REGEX2, "");
14730
14731
  }
14732
+ function escapeControlCharacters3(str) {
14733
+ const normalised = str.replace(/\r\n/g, `
14734
+ `);
14735
+ return normalised.replace(/[\x00-\x08\x0B-\x1F\x7F-\x9F‪-‮⁦-⁩]/g, (char) => {
14736
+ const code = char.charCodeAt(0);
14737
+ if (code > 255) {
14738
+ return `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`;
14739
+ }
14740
+ return `\\x${code.toString(16).padStart(2, "0").toUpperCase()}`;
14741
+ });
14742
+ }
14731
14743
  function sanitizeForClipboard(str) {
14732
14744
  if (!str)
14733
14745
  return str;
14734
- const stripped = stripAnsi2(str);
14735
- return stripped.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, (char) => {
14736
- const hex3 = char.charCodeAt(0).toString(16).padStart(2, "0").toUpperCase();
14737
- return `\\x${hex3}`;
14738
- });
14746
+ return escapeControlCharacters3(stripAnsi2(str));
14747
+ }
14748
+ function sanitizeForTerminal2(str) {
14749
+ if (!str)
14750
+ return str;
14751
+ return escapeControlCharacters3(str);
14739
14752
  }
14740
14753
  function createAnsiStripper2() {
14741
14754
  let buffer = "";
@@ -14772,7 +14785,7 @@ import { parseArgs } from "node:util";
14772
14785
  // package.json
14773
14786
  var package_default = {
14774
14787
  name: "@hongymagic/q",
14775
- version: "2026.422.0",
14788
+ version: "2026.427.0-next.3a1fca4",
14776
14789
  description: "Quick AI answers from the command line",
14777
14790
  main: "dist/q.js",
14778
14791
  type: "module",
@@ -14838,8 +14851,8 @@ var package_default = {
14838
14851
  zod: "4.3.6"
14839
14852
  },
14840
14853
  devDependencies: {
14841
- "@biomejs/biome": "2.4.12",
14842
- "@types/bun": "1.3.12",
14854
+ "@biomejs/biome": "2.4.13",
14855
+ "@types/bun": "1.3.13",
14843
14856
  "@vitest/coverage-v8": "4.1.5",
14844
14857
  lefthook: "2.1.6",
14845
14858
  typescript: "6.0.3",
@@ -28810,8 +28823,8 @@ function isSensitiveKey(key) {
28810
28823
  // src/logging.ts
28811
28824
  var sessionEntries = [];
28812
28825
  var sessionContext = new Map;
28813
- function logDebug(message, debug) {
28814
- if (!debug) {
28826
+ function logDebug(message) {
28827
+ if (sessionContext.get("debug") !== true) {
28815
28828
  return;
28816
28829
  }
28817
28830
  recordLogEntry("debug", message);
@@ -29182,9 +29195,7 @@ function getXdgConfigDir() {
29182
29195
  function getCwdConfigPath() {
29183
29196
  return join(process.cwd(), "config.toml");
29184
29197
  }
29185
- function getConfigPath() {
29186
- return getXdgConfigPath();
29187
- }
29198
+
29188
29199
  class Config {
29189
29200
  default;
29190
29201
  providers;
@@ -29203,8 +29214,7 @@ class Config {
29203
29214
  };
29204
29215
  const mergedProviders = {
29205
29216
  ...getBuiltInProviderConfigs(),
29206
- ...xdgConfig?.providers ?? {},
29207
- ...cwdConfig?.providers ?? {}
29217
+ ...xdgConfig?.providers ?? {}
29208
29218
  };
29209
29219
  const inferredProvider = await Config.inferDefaultProvider(mergedDefault);
29210
29220
  const providerForDefaultModel = env.Q_PROVIDER ?? mergedDefault.provider ?? inferredProvider;
@@ -29314,7 +29324,12 @@ var ALLOWED_INTERPOLATION_VARS = new Set([
29314
29324
  "AZURE_API_KEY",
29315
29325
  "ANTHROPIC_BASE_URL",
29316
29326
  "OPENAI_BASE_URL",
29327
+ "OPENAI_COMPATIBLE_BASE_URL",
29317
29328
  "PORTKEY_BASE_URL",
29329
+ "GROQ_BASE_URL",
29330
+ "OLLAMA_BASE_URL",
29331
+ "GOOGLE_BASE_URL",
29332
+ "AZURE_BASE_URL",
29318
29333
  "PORTKEY_PROVIDER",
29319
29334
  "AZURE_RESOURCE_NAME",
29320
29335
  "AWS_ACCESS_KEY_ID",
@@ -29390,10 +29405,14 @@ async function runConfigDoctor() {
29390
29405
  }
29391
29406
  ];
29392
29407
  const providerIssues = [];
29393
- const configuredProviderNames = new Set([
29394
- ...Object.keys((xdgData ?? {}).providers ?? {}),
29395
- ...Object.keys((cwdData ?? {}).providers ?? {})
29396
- ]);
29408
+ const configuredProviderNames = new Set(Object.keys((xdgData ?? {}).providers ?? {}));
29409
+ const cwdProviderNames = Object.keys((cwdData ?? {}).providers ?? {});
29410
+ if (cwdProviderNames.length > 0) {
29411
+ providerIssues.push({
29412
+ provider: "(cwd config)",
29413
+ issue: `Provider definitions in '${cwdPath}' are ignored for security. Define providers only in '${xdgPath}'. Ignored: ${cwdProviderNames.join(", ")}`
29414
+ });
29415
+ }
29397
29416
  try {
29398
29417
  const config2 = await Config.load();
29399
29418
  if (!xdgExists && !cwdExists) {
@@ -29412,9 +29431,6 @@ async function runConfigDoctor() {
29412
29431
  if (config2.default.provider) {
29413
29432
  configuredProviderNames.add(config2.default.provider);
29414
29433
  }
29415
- if (configuredProviderNames.size === 0 && config2.default.provider) {
29416
- configuredProviderNames.add(config2.default.provider);
29417
- }
29418
29434
  for (const name of configuredProviderNames) {
29419
29435
  const providerConfig = config2.providers[name];
29420
29436
  if (!providerConfig) {
@@ -30065,8 +30081,8 @@ function updateLogContext(context) {
30065
30081
  sessionContext2.set(key, value);
30066
30082
  }
30067
30083
  }
30068
- function logDebug2(message, debug) {
30069
- if (!debug) {
30084
+ function logDebug2(message) {
30085
+ if (sessionContext2.get("debug") !== true) {
30070
30086
  return;
30071
30087
  }
30072
30088
  recordLogEntry2("debug", message);
@@ -30155,7 +30171,10 @@ function formatSessionContext() {
30155
30171
  if (sessionContext2.size === 0) {
30156
30172
  return "(none)";
30157
30173
  }
30158
- return [...sessionContext2.entries()].sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)).map(([key, value]) => `${key}: ${String(value)}`).join(`
30174
+ return [...sessionContext2.entries()].sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)).map(([key, value]) => {
30175
+ const display = isSensitiveKey(key) ? "[REDACTED]" : String(value);
30176
+ return `${key}: ${display}`;
30177
+ }).join(`
30159
30178
  `);
30160
30179
  }
30161
30180
  function formatSessionEntries() {
@@ -34567,43 +34586,114 @@ class ParseError extends Error {
34567
34586
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
34568
34587
  }
34569
34588
  }
34589
+ var LF = 10;
34590
+ var CR = 13;
34591
+ var SPACE = 32;
34570
34592
  function noop(_arg) {}
34571
34593
  function createParser(callbacks) {
34572
34594
  if (typeof callbacks == "function")
34573
34595
  throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
34574
- const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
34575
- let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
34576
- function feed(newChunk) {
34577
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
34578
- for (const line of complete)
34579
- parseLine(line);
34580
- incompleteLine = incomplete, isFirstChunk = false;
34581
- }
34582
- function parseLine(line) {
34583
- if (line === "") {
34596
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];
34597
+ let isFirstChunk = true, id, data = "", dataLines = 0, eventType;
34598
+ function feed(chunk) {
34599
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
34600
+ const trailing2 = processLines(chunk);
34601
+ trailing2 !== "" && pendingFragments.push(trailing2);
34602
+ return;
34603
+ }
34604
+ if (chunk.indexOf(`
34605
+ `) === -1 && chunk.indexOf("\r") === -1) {
34606
+ pendingFragments.push(chunk);
34607
+ return;
34608
+ }
34609
+ pendingFragments.push(chunk);
34610
+ const input = pendingFragments.join("");
34611
+ pendingFragments.length = 0;
34612
+ const trailing = processLines(input);
34613
+ trailing !== "" && pendingFragments.push(trailing);
34614
+ }
34615
+ function processLines(chunk) {
34616
+ let searchIndex = 0;
34617
+ if (chunk.indexOf("\r") === -1) {
34618
+ let lfIndex = chunk.indexOf(`
34619
+ `, searchIndex);
34620
+ for (;lfIndex !== -1; ) {
34621
+ if (searchIndex === lfIndex) {
34622
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = undefined, data = "", dataLines = 0, eventType = undefined, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
34623
+ `, searchIndex);
34624
+ continue;
34625
+ }
34626
+ const firstCharCode = chunk.charCodeAt(searchIndex);
34627
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
34628
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
34629
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
34630
+ onEvent({ id, event: eventType, data: value }), id = undefined, data = "", eventType = undefined, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
34631
+ `, searchIndex);
34632
+ continue;
34633
+ }
34634
+ data = dataLines === 0 ? value : `${data}
34635
+ ${value}`, dataLines++;
34636
+ } else
34637
+ isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || undefined : parseLine(chunk, searchIndex, lfIndex);
34638
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
34639
+ `, searchIndex);
34640
+ }
34641
+ return chunk.slice(searchIndex);
34642
+ }
34643
+ for (;searchIndex < chunk.length; ) {
34644
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
34645
+ `, searchIndex);
34646
+ let lineEnd = -1;
34647
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
34648
+ break;
34649
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
34650
+ }
34651
+ return chunk.slice(searchIndex);
34652
+ }
34653
+ function parseLine(chunk, start, end) {
34654
+ if (start === end) {
34584
34655
  dispatchEvent();
34585
34656
  return;
34586
34657
  }
34587
- if (line.startsWith(":")) {
34588
- onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
34658
+ const firstCharCode = chunk.charCodeAt(start);
34659
+ if (isDataPrefix(chunk, start, firstCharCode)) {
34660
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
34661
+ data = dataLines === 0 ? value2 : `${data}
34662
+ ${value2}`, dataLines++;
34663
+ return;
34664
+ }
34665
+ if (isEventPrefix(chunk, start, firstCharCode)) {
34666
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined;
34667
+ return;
34668
+ }
34669
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
34670
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
34671
+ id = value2.includes("\x00") ? undefined : value2;
34589
34672
  return;
34590
34673
  }
34591
- const fieldSeparatorIndex = line.indexOf(":");
34592
- if (fieldSeparatorIndex !== -1) {
34593
- const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
34594
- processField(field, value, line);
34674
+ if (firstCharCode === 58) {
34675
+ if (onComment) {
34676
+ const line2 = chunk.slice(start, end);
34677
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
34678
+ }
34679
+ return;
34680
+ }
34681
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
34682
+ if (fieldSeparatorIndex === -1) {
34683
+ processField(line, "", line);
34595
34684
  return;
34596
34685
  }
34597
- processField(line, "", line);
34686
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
34687
+ processField(field, value, line);
34598
34688
  }
34599
34689
  function processField(field, value, line) {
34600
34690
  switch (field) {
34601
34691
  case "event":
34602
- eventType = value;
34692
+ eventType = value || undefined;
34603
34693
  break;
34604
34694
  case "data":
34605
- data = `${data}${value}
34606
- `;
34695
+ data = dataLines === 0 ? value : `${data}
34696
+ ${value}`, dataLines++;
34607
34697
  break;
34608
34698
  case "id":
34609
34699
  id = value.includes("\x00") ? undefined : value;
@@ -34621,35 +34711,26 @@ function createParser(callbacks) {
34621
34711
  }
34622
34712
  }
34623
34713
  function dispatchEvent() {
34624
- data.length > 0 && onEvent({
34714
+ dataLines > 0 && onEvent({
34625
34715
  id,
34626
- event: eventType || undefined,
34627
- data: data.endsWith(`
34628
- `) ? data.slice(0, -1) : data
34629
- }), id = undefined, data = "", eventType = "";
34716
+ event: eventType,
34717
+ data
34718
+ }), id = undefined, data = "", dataLines = 0, eventType = undefined;
34630
34719
  }
34631
34720
  function reset(options = {}) {
34632
- incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = undefined, data = "", eventType = "", incompleteLine = "";
34721
+ if (options.consume && pendingFragments.length > 0) {
34722
+ const incompleteLine = pendingFragments.join("");
34723
+ parseLine(incompleteLine, 0, incompleteLine.length);
34724
+ }
34725
+ isFirstChunk = true, id = undefined, data = "", dataLines = 0, eventType = undefined, pendingFragments.length = 0;
34633
34726
  }
34634
34727
  return { feed, reset };
34635
34728
  }
34636
- function splitLines(chunk) {
34637
- const lines = [];
34638
- let incompleteLine = "", searchIndex = 0;
34639
- for (;searchIndex < chunk.length; ) {
34640
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
34641
- `, searchIndex);
34642
- let lineEnd = -1;
34643
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
34644
- incompleteLine = chunk.slice(searchIndex);
34645
- break;
34646
- } else {
34647
- const line = chunk.slice(searchIndex, lineEnd);
34648
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
34649
- ` && searchIndex++;
34650
- }
34651
- }
34652
- return [lines, incompleteLine];
34729
+ function isDataPrefix(chunk, i, firstCharCode) {
34730
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
34731
+ }
34732
+ function isEventPrefix(chunk, i, firstCharCode) {
34733
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
34653
34734
  }
34654
34735
 
34655
34736
  // node_modules/eventsource-parser/dist/stream.js
@@ -49160,6 +49241,19 @@ class HeaderMarshaller {
49160
49241
  return out;
49161
49242
  }
49162
49243
  }
49244
+ var HEADER_VALUE_TYPE;
49245
+ (function(HEADER_VALUE_TYPE2) {
49246
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue";
49247
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse";
49248
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte";
49249
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short";
49250
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer";
49251
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long";
49252
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray";
49253
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string";
49254
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp";
49255
+ HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid";
49256
+ })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {}));
49163
49257
  var BOOLEAN_TAG = "boolean";
49164
49258
  var BYTE_TAG = "byte";
49165
49259
  var SHORT_TAG = "short";
@@ -55077,1748 +55171,172 @@ var groq = createGroq();
55077
55171
 
55078
55172
  // src/providers/groq.ts
55079
55173
  function createGroqProvider(config2, providerName) {
55080
- return createGroq({
55081
- apiKey: resolveApiKey(config2.api_key_env, providerName),
55082
- baseURL: config2.base_url,
55083
- headers: config2.headers
55084
- });
55174
+ return createStandardProvider(createGroq, config2, providerName);
55085
55175
  }
55086
55176
 
55087
- // node_modules/ollama-ai-provider-v2/node_modules/@ai-sdk/provider-utils/dist/index.mjs
55088
- function combineHeaders2(...headers) {
55089
- return headers.reduce((combinedHeaders, currentHeaders) => ({
55090
- ...combinedHeaders,
55091
- ...currentHeaders != null ? currentHeaders : {}
55092
- }), {});
55093
- }
55094
- function extractResponseHeaders2(response) {
55095
- return Object.fromEntries([...response.headers]);
55096
- }
55097
- var name16 = "AI_DownloadError";
55098
- var marker17 = `vercel.ai.error.${name16}`;
55099
- var symbol17 = Symbol.for(marker17);
55100
- var _a17;
55101
- var _b17;
55102
- var DownloadError2 = class extends (_b17 = AISDKError, _a17 = symbol17, _b17) {
55103
- constructor({
55104
- url: url2,
55105
- statusCode,
55106
- statusText,
55107
- cause,
55108
- message = cause == null ? `Failed to download ${url2}: ${statusCode} ${statusText}` : `Failed to download ${url2}: ${cause}`
55109
- }) {
55110
- super({ name: name16, message, cause });
55111
- this[_a17] = true;
55112
- this.url = url2;
55113
- this.statusCode = statusCode;
55114
- this.statusText = statusText;
55115
- }
55116
- static isInstance(error48) {
55117
- return AISDKError.hasMarker(error48, marker17);
55118
- }
55119
- };
55120
- var DEFAULT_MAX_DOWNLOAD_SIZE2 = 2 * 1024 * 1024 * 1024;
55121
- var createIdGenerator2 = ({
55122
- prefix,
55123
- size = 16,
55124
- alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
55125
- separator = "-"
55126
- } = {}) => {
55127
- const generator = () => {
55128
- const alphabetLength = alphabet.length;
55129
- const chars = new Array(size);
55130
- for (let i = 0;i < size; i++) {
55131
- chars[i] = alphabet[Math.random() * alphabetLength | 0];
55132
- }
55133
- return chars.join("");
55134
- };
55135
- if (prefix == null) {
55136
- return generator;
55137
- }
55138
- if (alphabet.includes(separator)) {
55139
- throw new InvalidArgumentError({
55140
- argument: "separator",
55141
- message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
55142
- });
55143
- }
55144
- return () => `${prefix}${separator}${generator()}`;
55145
- };
55146
- var generateId2 = createIdGenerator2();
55147
- function isAbortError2(error48) {
55148
- return (error48 instanceof Error || error48 instanceof DOMException) && (error48.name === "AbortError" || error48.name === "ResponseAborted" || error48.name === "TimeoutError");
55149
- }
55150
- var FETCH_FAILED_ERROR_MESSAGES2 = ["fetch failed", "failed to fetch"];
55151
- var BUN_ERROR_CODES2 = [
55152
- "ConnectionRefused",
55153
- "ConnectionClosed",
55154
- "FailedToOpenSocket",
55155
- "ECONNRESET",
55156
- "ECONNREFUSED",
55157
- "ETIMEDOUT",
55158
- "EPIPE"
55159
- ];
55160
- function isBunNetworkError2(error48) {
55161
- if (!(error48 instanceof Error)) {
55162
- return false;
55163
- }
55164
- const code = error48.code;
55165
- if (typeof code === "string" && BUN_ERROR_CODES2.includes(code)) {
55166
- return true;
55167
- }
55168
- return false;
55169
- }
55170
- function handleFetchError2({
55171
- error: error48,
55172
- url: url2,
55173
- requestBodyValues
55177
+ // node_modules/ollama-ai-provider-v2/dist/index.mjs
55178
+ function convertToOllamaCompletionPrompt({
55179
+ prompt,
55180
+ user = "user",
55181
+ assistant = "assistant"
55174
55182
  }) {
55175
- if (isAbortError2(error48)) {
55176
- return error48;
55177
- }
55178
- if (error48 instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES2.includes(error48.message.toLowerCase())) {
55179
- const cause = error48.cause;
55180
- if (cause != null) {
55181
- return new APICallError({
55182
- message: `Cannot connect to API: ${cause.message}`,
55183
- cause,
55184
- url: url2,
55185
- requestBodyValues,
55186
- isRetryable: true
55187
- });
55188
- }
55189
- }
55190
- if (isBunNetworkError2(error48)) {
55191
- return new APICallError({
55192
- message: `Cannot connect to API: ${error48.message}`,
55193
- cause: error48,
55194
- url: url2,
55195
- requestBodyValues,
55196
- isRetryable: true
55197
- });
55198
- }
55199
- return error48;
55200
- }
55201
- function getRuntimeEnvironmentUserAgent2(globalThisAny = globalThis) {
55202
- var _a23, _b22, _c;
55203
- if (globalThisAny.window) {
55204
- return `runtime/browser`;
55205
- }
55206
- if ((_a23 = globalThisAny.navigator) == null ? undefined : _a23.userAgent) {
55207
- return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
55208
- }
55209
- if ((_c = (_b22 = globalThisAny.process) == null ? undefined : _b22.versions) == null ? undefined : _c.node) {
55210
- return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
55211
- }
55212
- if (globalThisAny.EdgeRuntime) {
55213
- return `runtime/vercel-edge`;
55214
- }
55215
- return "runtime/unknown";
55216
- }
55217
- function normalizeHeaders2(headers) {
55218
- if (headers == null) {
55219
- return {};
55183
+ let text = "";
55184
+ if (prompt[0].role === "system") {
55185
+ text += `${prompt[0].content}
55186
+
55187
+ `;
55188
+ prompt = prompt.slice(1);
55220
55189
  }
55221
- const normalized = {};
55222
- if (headers instanceof Headers) {
55223
- headers.forEach((value, key) => {
55224
- normalized[key.toLowerCase()] = value;
55225
- });
55226
- } else {
55227
- if (!Array.isArray(headers)) {
55228
- headers = Object.entries(headers);
55229
- }
55230
- for (const [key, value] of headers) {
55231
- if (value != null) {
55232
- normalized[key.toLowerCase()] = value;
55190
+ for (const { role, content } of prompt) {
55191
+ switch (role) {
55192
+ case "system": {
55193
+ throw new InvalidPromptError({
55194
+ message: "Unexpected system message in prompt: ${content}",
55195
+ prompt
55196
+ });
55233
55197
  }
55234
- }
55235
- }
55236
- return normalized;
55237
- }
55238
- function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
55239
- const normalizedHeaders = new Headers(normalizeHeaders2(headers));
55240
- const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
55241
- normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
55242
- return Object.fromEntries(normalizedHeaders.entries());
55243
- }
55244
- var VERSION8 = "4.0.21";
55245
- var suspectProtoRx2 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
55246
- var suspectConstructorRx2 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
55247
- function _parse3(text) {
55248
- const obj = JSON.parse(text);
55249
- if (obj === null || typeof obj !== "object") {
55250
- return obj;
55251
- }
55252
- if (suspectProtoRx2.test(text) === false && suspectConstructorRx2.test(text) === false) {
55253
- return obj;
55254
- }
55255
- return filter2(obj);
55256
- }
55257
- function filter2(obj) {
55258
- let next = [obj];
55259
- while (next.length) {
55260
- const nodes = next;
55261
- next = [];
55262
- for (const node of nodes) {
55263
- if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
55264
- throw new SyntaxError("Object contains forbidden prototype property");
55198
+ case "user": {
55199
+ const userMessage = content.map((part) => {
55200
+ switch (part.type) {
55201
+ case "text": {
55202
+ return part.text;
55203
+ }
55204
+ }
55205
+ }).filter(Boolean).join("");
55206
+ text += `${user}:
55207
+ ${userMessage}
55208
+
55209
+ `;
55210
+ break;
55265
55211
  }
55266
- if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
55267
- throw new SyntaxError("Object contains forbidden prototype property");
55212
+ case "assistant": {
55213
+ const assistantMessage = content.map((part) => {
55214
+ switch (part.type) {
55215
+ case "text": {
55216
+ return part.text;
55217
+ }
55218
+ case "tool-call": {
55219
+ throw new UnsupportedFunctionalityError({
55220
+ functionality: "tool-call messages"
55221
+ });
55222
+ }
55223
+ }
55224
+ }).join("");
55225
+ text += `${assistant}:
55226
+ ${assistantMessage}
55227
+
55228
+ `;
55229
+ break;
55268
55230
  }
55269
- for (const key in node) {
55270
- const value = node[key];
55271
- if (value && typeof value === "object") {
55272
- next.push(value);
55273
- }
55231
+ case "tool": {
55232
+ throw new UnsupportedFunctionalityError({
55233
+ functionality: "tool messages"
55234
+ });
55274
55235
  }
55275
- }
55276
- }
55277
- return obj;
55278
- }
55279
- function secureJsonParse2(text) {
55280
- const { stackTraceLimit } = Error;
55281
- try {
55282
- Error.stackTraceLimit = 0;
55283
- } catch (e) {
55284
- return _parse3(text);
55285
- }
55286
- try {
55287
- return _parse3(text);
55288
- } finally {
55289
- Error.stackTraceLimit = stackTraceLimit;
55290
- }
55291
- }
55292
- function addAdditionalPropertiesToJsonSchema2(jsonSchema2) {
55293
- if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
55294
- jsonSchema2.additionalProperties = false;
55295
- const { properties } = jsonSchema2;
55296
- if (properties != null) {
55297
- for (const key of Object.keys(properties)) {
55298
- properties[key] = visit2(properties[key]);
55236
+ default: {
55237
+ const _exhaustiveCheck = role;
55238
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
55299
55239
  }
55300
55240
  }
55301
55241
  }
55302
- if (jsonSchema2.items != null) {
55303
- jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit2) : visit2(jsonSchema2.items);
55304
- }
55305
- if (jsonSchema2.anyOf != null) {
55306
- jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit2);
55307
- }
55308
- if (jsonSchema2.allOf != null) {
55309
- jsonSchema2.allOf = jsonSchema2.allOf.map(visit2);
55310
- }
55311
- if (jsonSchema2.oneOf != null) {
55312
- jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit2);
55313
- }
55314
- const { definitions } = jsonSchema2;
55315
- if (definitions != null) {
55316
- for (const key of Object.keys(definitions)) {
55317
- definitions[key] = visit2(definitions[key]);
55318
- }
55319
- }
55320
- return jsonSchema2;
55321
- }
55322
- function visit2(def) {
55323
- if (typeof def === "boolean")
55324
- return def;
55325
- return addAdditionalPropertiesToJsonSchema2(def);
55326
- }
55327
- var ignoreOverride2 = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use");
55328
- var defaultOptions2 = {
55329
- name: undefined,
55330
- $refStrategy: "root",
55331
- basePath: ["#"],
55332
- effectStrategy: "input",
55333
- pipeStrategy: "all",
55334
- dateStrategy: "format:date-time",
55335
- mapStrategy: "entries",
55336
- removeAdditionalStrategy: "passthrough",
55337
- allowedAdditionalProperties: true,
55338
- rejectedAdditionalProperties: false,
55339
- definitionPath: "definitions",
55340
- strictUnions: false,
55341
- definitions: {},
55342
- errorMessages: false,
55343
- patternStrategy: "escape",
55344
- applyRegexFlags: false,
55345
- emailStrategy: "format:email",
55346
- base64Strategy: "contentEncoding:base64",
55347
- nameStrategy: "ref"
55348
- };
55349
- var getDefaultOptions2 = (options) => typeof options === "string" ? {
55350
- ...defaultOptions2,
55351
- name: options
55352
- } : {
55353
- ...defaultOptions2,
55354
- ...options
55355
- };
55356
- function parseAnyDef2() {
55357
- return {};
55358
- }
55359
- function parseArrayDef2(def, refs) {
55360
- var _a23, _b22, _c;
55361
- const res = {
55362
- type: "array"
55363
- };
55364
- if (((_a23 = def.type) == null ? undefined : _a23._def) && ((_c = (_b22 = def.type) == null ? undefined : _b22._def) == null ? undefined : _c.typeName) !== ZodFirstPartyTypeKind2.ZodAny) {
55365
- res.items = parseDef2(def.type._def, {
55366
- ...refs,
55367
- currentPath: [...refs.currentPath, "items"]
55368
- });
55369
- }
55370
- if (def.minLength) {
55371
- res.minItems = def.minLength.value;
55372
- }
55373
- if (def.maxLength) {
55374
- res.maxItems = def.maxLength.value;
55375
- }
55376
- if (def.exactLength) {
55377
- res.minItems = def.exactLength.value;
55378
- res.maxItems = def.exactLength.value;
55379
- }
55380
- return res;
55381
- }
55382
- function parseBigintDef2(def) {
55383
- const res = {
55384
- type: "integer",
55385
- format: "int64"
55242
+ text += `${assistant}:
55243
+ `;
55244
+ return {
55245
+ prompt: text,
55246
+ stopSequences: [`
55247
+ ${user}:`]
55386
55248
  };
55387
- if (!def.checks)
55388
- return res;
55389
- for (const check2 of def.checks) {
55390
- switch (check2.kind) {
55391
- case "min":
55392
- if (check2.inclusive) {
55393
- res.minimum = check2.value;
55394
- } else {
55395
- res.exclusiveMinimum = check2.value;
55396
- }
55397
- break;
55398
- case "max":
55399
- if (check2.inclusive) {
55400
- res.maximum = check2.value;
55401
- } else {
55402
- res.exclusiveMaximum = check2.value;
55403
- }
55404
- break;
55405
- case "multipleOf":
55406
- res.multipleOf = check2.value;
55407
- break;
55408
- }
55409
- }
55410
- return res;
55411
- }
55412
- function parseBooleanDef2() {
55413
- return { type: "boolean" };
55414
- }
55415
- function parseBrandedDef2(_def, refs) {
55416
- return parseDef2(_def.type._def, refs);
55417
55249
  }
55418
- var parseCatchDef2 = (def, refs) => {
55419
- return parseDef2(def.innerType._def, refs);
55420
- };
55421
- function parseDateDef2(def, refs, overrideDateStrategy) {
55422
- const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
55423
- if (Array.isArray(strategy)) {
55424
- return {
55425
- anyOf: strategy.map((item, i) => parseDateDef2(def, refs, item))
55426
- };
55427
- }
55428
- switch (strategy) {
55429
- case "string":
55430
- case "format:date-time":
55250
+ function mapOllamaFinishReason(finishReason) {
55251
+ switch (finishReason) {
55252
+ case "stop":
55431
55253
  return {
55432
- type: "string",
55433
- format: "date-time"
55254
+ raw: finishReason,
55255
+ unified: "stop"
55434
55256
  };
55435
- case "format:date":
55257
+ case "length":
55436
55258
  return {
55437
- type: "string",
55438
- format: "date"
55259
+ raw: finishReason,
55260
+ unified: "length"
55261
+ };
55262
+ case "content_filter":
55263
+ return {
55264
+ raw: finishReason,
55265
+ unified: "content-filter"
55266
+ };
55267
+ case "function_call":
55268
+ case "tool_calls":
55269
+ return {
55270
+ raw: finishReason,
55271
+ unified: "tool-calls"
55272
+ };
55273
+ default:
55274
+ return {
55275
+ raw: finishReason,
55276
+ unified: "other"
55439
55277
  };
55440
- case "integer":
55441
- return integerDateParser2(def);
55442
55278
  }
55443
55279
  }
55444
- var integerDateParser2 = (def) => {
55445
- const res = {
55446
- type: "integer",
55447
- format: "unix-time"
55448
- };
55449
- for (const check2 of def.checks) {
55450
- switch (check2.kind) {
55451
- case "min":
55452
- res.minimum = check2.value;
55453
- break;
55454
- case "max":
55455
- res.maximum = check2.value;
55456
- break;
55457
- }
55458
- }
55459
- return res;
55460
- };
55461
- function parseDefaultDef2(_def, refs) {
55280
+ function getResponseMetadata5({
55281
+ model,
55282
+ created_at
55283
+ }) {
55462
55284
  return {
55463
- ...parseDef2(_def.innerType._def, refs),
55464
- default: _def.defaultValue()
55285
+ id: undefined,
55286
+ modelId: model != null ? model : undefined,
55287
+ timestamp: created_at != null ? new Date(created_at) : undefined
55465
55288
  };
55466
55289
  }
55467
- function parseEffectsDef2(_def, refs) {
55468
- return refs.effectStrategy === "input" ? parseDef2(_def.schema._def, refs) : parseAnyDef2();
55469
- }
55470
- function parseEnumDef2(def) {
55471
- return {
55472
- type: "string",
55473
- enum: Array.from(def.values)
55474
- };
55475
- }
55476
- var isJsonSchema7AllOfType2 = (type) => {
55477
- if ("type" in type && type.type === "string")
55478
- return false;
55479
- return "allOf" in type;
55480
- };
55481
- function parseIntersectionDef2(def, refs) {
55482
- const allOf = [
55483
- parseDef2(def.left._def, {
55484
- ...refs,
55485
- currentPath: [...refs.currentPath, "allOf", "0"]
55486
- }),
55487
- parseDef2(def.right._def, {
55488
- ...refs,
55489
- currentPath: [...refs.currentPath, "allOf", "1"]
55490
- })
55491
- ].filter((x) => !!x);
55492
- const mergedAllOf = [];
55493
- allOf.forEach((schema) => {
55494
- if (isJsonSchema7AllOfType2(schema)) {
55495
- mergedAllOf.push(...schema.allOf);
55496
- } else {
55497
- let nestedSchema = schema;
55498
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
55499
- const { additionalProperties, ...rest } = schema;
55500
- nestedSchema = rest;
55501
- }
55502
- mergedAllOf.push(nestedSchema);
55503
- }
55504
- });
55505
- return mergedAllOf.length ? { allOf: mergedAllOf } : undefined;
55506
- }
55507
- function parseLiteralDef2(def) {
55508
- const parsedType2 = typeof def.value;
55509
- if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") {
55510
- return {
55511
- type: Array.isArray(def.value) ? "array" : "object"
55512
- };
55513
- }
55514
- return {
55515
- type: parsedType2 === "bigint" ? "integer" : parsedType2,
55516
- const: def.value
55517
- };
55518
- }
55519
- var emojiRegex3 = undefined;
55520
- var zodPatterns2 = {
55521
- cuid: /^[cC][^\s-]{8,}$/,
55522
- cuid2: /^[0-9a-z]+$/,
55523
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
55524
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
55525
- emoji: () => {
55526
- if (emojiRegex3 === undefined) {
55527
- emojiRegex3 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
55528
- }
55529
- return emojiRegex3;
55530
- },
55531
- uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
55532
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
55533
- ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
55534
- ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
55535
- ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
55536
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
55537
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
55538
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
55539
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
55540
- };
55541
- function parseStringDef2(def, refs) {
55542
- const res = {
55543
- type: "string"
55544
- };
55545
- if (def.checks) {
55546
- for (const check2 of def.checks) {
55547
- switch (check2.kind) {
55548
- case "min":
55549
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value;
55550
- break;
55551
- case "max":
55552
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value;
55553
- break;
55554
- case "email":
55555
- switch (refs.emailStrategy) {
55556
- case "format:email":
55557
- addFormat2(res, "email", check2.message, refs);
55558
- break;
55559
- case "format:idn-email":
55560
- addFormat2(res, "idn-email", check2.message, refs);
55561
- break;
55562
- case "pattern:zod":
55563
- addPattern2(res, zodPatterns2.email, check2.message, refs);
55564
- break;
55565
- }
55566
- break;
55567
- case "url":
55568
- addFormat2(res, "uri", check2.message, refs);
55569
- break;
55570
- case "uuid":
55571
- addFormat2(res, "uuid", check2.message, refs);
55572
- break;
55573
- case "regex":
55574
- addPattern2(res, check2.regex, check2.message, refs);
55575
- break;
55576
- case "cuid":
55577
- addPattern2(res, zodPatterns2.cuid, check2.message, refs);
55578
- break;
55579
- case "cuid2":
55580
- addPattern2(res, zodPatterns2.cuid2, check2.message, refs);
55581
- break;
55582
- case "startsWith":
55583
- addPattern2(res, RegExp(`^${escapeLiteralCheckValue2(check2.value, refs)}`), check2.message, refs);
55584
- break;
55585
- case "endsWith":
55586
- addPattern2(res, RegExp(`${escapeLiteralCheckValue2(check2.value, refs)}$`), check2.message, refs);
55587
- break;
55588
- case "datetime":
55589
- addFormat2(res, "date-time", check2.message, refs);
55590
- break;
55591
- case "date":
55592
- addFormat2(res, "date", check2.message, refs);
55593
- break;
55594
- case "time":
55595
- addFormat2(res, "time", check2.message, refs);
55596
- break;
55597
- case "duration":
55598
- addFormat2(res, "duration", check2.message, refs);
55599
- break;
55600
- case "length":
55601
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value;
55602
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value;
55603
- break;
55604
- case "includes": {
55605
- addPattern2(res, RegExp(escapeLiteralCheckValue2(check2.value, refs)), check2.message, refs);
55606
- break;
55607
- }
55608
- case "ip": {
55609
- if (check2.version !== "v6") {
55610
- addFormat2(res, "ipv4", check2.message, refs);
55611
- }
55612
- if (check2.version !== "v4") {
55613
- addFormat2(res, "ipv6", check2.message, refs);
55614
- }
55615
- break;
55616
- }
55617
- case "base64url":
55618
- addPattern2(res, zodPatterns2.base64url, check2.message, refs);
55619
- break;
55620
- case "jwt":
55621
- addPattern2(res, zodPatterns2.jwt, check2.message, refs);
55622
- break;
55623
- case "cidr": {
55624
- if (check2.version !== "v6") {
55625
- addPattern2(res, zodPatterns2.ipv4Cidr, check2.message, refs);
55626
- }
55627
- if (check2.version !== "v4") {
55628
- addPattern2(res, zodPatterns2.ipv6Cidr, check2.message, refs);
55629
- }
55630
- break;
55631
- }
55632
- case "emoji":
55633
- addPattern2(res, zodPatterns2.emoji(), check2.message, refs);
55634
- break;
55635
- case "ulid": {
55636
- addPattern2(res, zodPatterns2.ulid, check2.message, refs);
55637
- break;
55638
- }
55639
- case "base64": {
55640
- switch (refs.base64Strategy) {
55641
- case "format:binary": {
55642
- addFormat2(res, "binary", check2.message, refs);
55643
- break;
55644
- }
55645
- case "contentEncoding:base64": {
55646
- res.contentEncoding = "base64";
55647
- break;
55648
- }
55649
- case "pattern:zod": {
55650
- addPattern2(res, zodPatterns2.base64, check2.message, refs);
55651
- break;
55652
- }
55653
- }
55654
- break;
55655
- }
55656
- case "nanoid": {
55657
- addPattern2(res, zodPatterns2.nanoid, check2.message, refs);
55658
- }
55659
- case "toLowerCase":
55660
- case "toUpperCase":
55661
- case "trim":
55662
- break;
55663
- default:
55664
- }
55665
- }
55666
- }
55667
- return res;
55668
- }
55669
- function escapeLiteralCheckValue2(literal2, refs) {
55670
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric2(literal2) : literal2;
55671
- }
55672
- var ALPHA_NUMERIC2 = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
55673
- function escapeNonAlphaNumeric2(source) {
55674
- let result = "";
55675
- for (let i = 0;i < source.length; i++) {
55676
- if (!ALPHA_NUMERIC2.has(source[i])) {
55677
- result += "\\";
55678
- }
55679
- result += source[i];
55680
- }
55681
- return result;
55682
- }
55683
- function addFormat2(schema, value, message, refs) {
55684
- var _a23;
55685
- if (schema.format || ((_a23 = schema.anyOf) == null ? undefined : _a23.some((x) => x.format))) {
55686
- if (!schema.anyOf) {
55687
- schema.anyOf = [];
55688
- }
55689
- if (schema.format) {
55690
- schema.anyOf.push({
55691
- format: schema.format
55692
- });
55693
- delete schema.format;
55694
- }
55695
- schema.anyOf.push({
55696
- format: value,
55697
- ...message && refs.errorMessages && { errorMessage: { format: message } }
55698
- });
55699
- } else {
55700
- schema.format = value;
55701
- }
55702
- }
55703
- function addPattern2(schema, regex, message, refs) {
55704
- var _a23;
55705
- if (schema.pattern || ((_a23 = schema.allOf) == null ? undefined : _a23.some((x) => x.pattern))) {
55706
- if (!schema.allOf) {
55707
- schema.allOf = [];
55708
- }
55709
- if (schema.pattern) {
55710
- schema.allOf.push({
55711
- pattern: schema.pattern
55712
- });
55713
- delete schema.pattern;
55714
- }
55715
- schema.allOf.push({
55716
- pattern: stringifyRegExpWithFlags2(regex, refs),
55717
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
55718
- });
55719
- } else {
55720
- schema.pattern = stringifyRegExpWithFlags2(regex, refs);
55721
- }
55722
- }
55723
- function stringifyRegExpWithFlags2(regex, refs) {
55724
- var _a23;
55725
- if (!refs.applyRegexFlags || !regex.flags) {
55726
- return regex.source;
55727
- }
55728
- const flags = {
55729
- i: regex.flags.includes("i"),
55730
- m: regex.flags.includes("m"),
55731
- s: regex.flags.includes("s")
55732
- };
55733
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
55734
- let pattern = "";
55735
- let isEscaped = false;
55736
- let inCharGroup = false;
55737
- let inCharRange = false;
55738
- for (let i = 0;i < source.length; i++) {
55739
- if (isEscaped) {
55740
- pattern += source[i];
55741
- isEscaped = false;
55742
- continue;
55743
- }
55744
- if (flags.i) {
55745
- if (inCharGroup) {
55746
- if (source[i].match(/[a-z]/)) {
55747
- if (inCharRange) {
55748
- pattern += source[i];
55749
- pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
55750
- inCharRange = false;
55751
- } else if (source[i + 1] === "-" && ((_a23 = source[i + 2]) == null ? undefined : _a23.match(/[a-z]/))) {
55752
- pattern += source[i];
55753
- inCharRange = true;
55754
- } else {
55755
- pattern += `${source[i]}${source[i].toUpperCase()}`;
55756
- }
55757
- continue;
55758
- }
55759
- } else if (source[i].match(/[a-z]/)) {
55760
- pattern += `[${source[i]}${source[i].toUpperCase()}]`;
55761
- continue;
55762
- }
55763
- }
55764
- if (flags.m) {
55765
- if (source[i] === "^") {
55766
- pattern += `(^|(?<=[\r
55767
- ]))`;
55768
- continue;
55769
- } else if (source[i] === "$") {
55770
- pattern += `($|(?=[\r
55771
- ]))`;
55772
- continue;
55773
- }
55774
- }
55775
- if (flags.s && source[i] === ".") {
55776
- pattern += inCharGroup ? `${source[i]}\r
55777
- ` : `[${source[i]}\r
55778
- ]`;
55779
- continue;
55780
- }
55781
- pattern += source[i];
55782
- if (source[i] === "\\") {
55783
- isEscaped = true;
55784
- } else if (inCharGroup && source[i] === "]") {
55785
- inCharGroup = false;
55786
- } else if (!inCharGroup && source[i] === "[") {
55787
- inCharGroup = true;
55788
- }
55789
- }
55790
- try {
55791
- new RegExp(pattern);
55792
- } catch (e) {
55793
- console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
55794
- return regex.source;
55795
- }
55796
- return pattern;
55797
- }
55798
- function parseRecordDef2(def, refs) {
55799
- var _a23, _b22, _c, _d, _e, _f;
55800
- const schema = {
55801
- type: "object",
55802
- additionalProperties: (_a23 = parseDef2(def.valueType._def, {
55803
- ...refs,
55804
- currentPath: [...refs.currentPath, "additionalProperties"]
55805
- })) != null ? _a23 : refs.allowedAdditionalProperties
55806
- };
55807
- if (((_b22 = def.keyType) == null ? undefined : _b22._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? undefined : _c.length)) {
55808
- const { type, ...keyType } = parseStringDef2(def.keyType._def, refs);
55809
- return {
55810
- ...schema,
55811
- propertyNames: keyType
55812
- };
55813
- } else if (((_d = def.keyType) == null ? undefined : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
55814
- return {
55815
- ...schema,
55816
- propertyNames: {
55817
- enum: def.keyType._def.values
55818
- }
55819
- };
55820
- } else if (((_e = def.keyType) == null ? undefined : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? undefined : _f.length)) {
55821
- const { type, ...keyType } = parseBrandedDef2(def.keyType._def, refs);
55822
- return {
55823
- ...schema,
55824
- propertyNames: keyType
55825
- };
55826
- }
55827
- return schema;
55828
- }
55829
- function parseMapDef2(def, refs) {
55830
- if (refs.mapStrategy === "record") {
55831
- return parseRecordDef2(def, refs);
55832
- }
55833
- const keys = parseDef2(def.keyType._def, {
55834
- ...refs,
55835
- currentPath: [...refs.currentPath, "items", "items", "0"]
55836
- }) || parseAnyDef2();
55837
- const values = parseDef2(def.valueType._def, {
55838
- ...refs,
55839
- currentPath: [...refs.currentPath, "items", "items", "1"]
55840
- }) || parseAnyDef2();
55841
- return {
55842
- type: "array",
55843
- maxItems: 125,
55844
- items: {
55845
- type: "array",
55846
- items: [keys, values],
55847
- minItems: 2,
55848
- maxItems: 2
55849
- }
55850
- };
55851
- }
55852
- function parseNativeEnumDef2(def) {
55853
- const object2 = def.values;
55854
- const actualKeys = Object.keys(def.values).filter((key) => {
55855
- return typeof object2[object2[key]] !== "number";
55856
- });
55857
- const actualValues = actualKeys.map((key) => object2[key]);
55858
- const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
55859
- return {
55860
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
55861
- enum: actualValues
55862
- };
55863
- }
55864
- function parseNeverDef2() {
55865
- return { not: parseAnyDef2() };
55866
- }
55867
- function parseNullDef2() {
55868
- return {
55869
- type: "null"
55870
- };
55871
- }
55872
- var primitiveMappings2 = {
55873
- ZodString: "string",
55874
- ZodNumber: "number",
55875
- ZodBigInt: "integer",
55876
- ZodBoolean: "boolean",
55877
- ZodNull: "null"
55878
- };
55879
- function parseUnionDef2(def, refs) {
55880
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
55881
- if (options.every((x) => (x._def.typeName in primitiveMappings2) && (!x._def.checks || !x._def.checks.length))) {
55882
- const types = options.reduce((types2, x) => {
55883
- const type = primitiveMappings2[x._def.typeName];
55884
- return type && !types2.includes(type) ? [...types2, type] : types2;
55885
- }, []);
55886
- return {
55887
- type: types.length > 1 ? types : types[0]
55888
- };
55889
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
55890
- const types = options.reduce((acc, x) => {
55891
- const type = typeof x._def.value;
55892
- switch (type) {
55893
- case "string":
55894
- case "number":
55895
- case "boolean":
55896
- return [...acc, type];
55897
- case "bigint":
55898
- return [...acc, "integer"];
55899
- case "object":
55900
- if (x._def.value === null)
55901
- return [...acc, "null"];
55902
- case "symbol":
55903
- case "undefined":
55904
- case "function":
55905
- default:
55906
- return acc;
55907
- }
55908
- }, []);
55909
- if (types.length === options.length) {
55910
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
55911
- return {
55912
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
55913
- enum: options.reduce((acc, x) => {
55914
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
55915
- }, [])
55916
- };
55917
- }
55918
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
55919
- return {
55920
- type: "string",
55921
- enum: options.reduce((acc, x) => [
55922
- ...acc,
55923
- ...x._def.values.filter((x2) => !acc.includes(x2))
55924
- ], [])
55925
- };
55926
- }
55927
- return asAnyOf2(def, refs);
55928
- }
55929
- var asAnyOf2 = (def, refs) => {
55930
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef2(x._def, {
55931
- ...refs,
55932
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
55933
- })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
55934
- return anyOf.length ? { anyOf } : undefined;
55935
- };
55936
- function parseNullableDef2(def, refs) {
55937
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
55938
- return {
55939
- type: [
55940
- primitiveMappings2[def.innerType._def.typeName],
55941
- "null"
55942
- ]
55943
- };
55944
- }
55945
- const base = parseDef2(def.innerType._def, {
55946
- ...refs,
55947
- currentPath: [...refs.currentPath, "anyOf", "0"]
55948
- });
55949
- return base && { anyOf: [base, { type: "null" }] };
55950
- }
55951
- function parseNumberDef2(def) {
55952
- const res = {
55953
- type: "number"
55954
- };
55955
- if (!def.checks)
55956
- return res;
55957
- for (const check2 of def.checks) {
55958
- switch (check2.kind) {
55959
- case "int":
55960
- res.type = "integer";
55961
- break;
55962
- case "min":
55963
- if (check2.inclusive) {
55964
- res.minimum = check2.value;
55965
- } else {
55966
- res.exclusiveMinimum = check2.value;
55967
- }
55968
- break;
55969
- case "max":
55970
- if (check2.inclusive) {
55971
- res.maximum = check2.value;
55972
- } else {
55973
- res.exclusiveMaximum = check2.value;
55974
- }
55975
- break;
55976
- case "multipleOf":
55977
- res.multipleOf = check2.value;
55978
- break;
55979
- }
55980
- }
55981
- return res;
55982
- }
55983
- function parseObjectDef2(def, refs) {
55984
- const result = {
55985
- type: "object",
55986
- properties: {}
55987
- };
55988
- const required2 = [];
55989
- const shape = def.shape();
55990
- for (const propName in shape) {
55991
- let propDef = shape[propName];
55992
- if (propDef === undefined || propDef._def === undefined) {
55993
- continue;
55994
- }
55995
- const propOptional = safeIsOptional2(propDef);
55996
- const parsedDef = parseDef2(propDef._def, {
55997
- ...refs,
55998
- currentPath: [...refs.currentPath, "properties", propName],
55999
- propertyPath: [...refs.currentPath, "properties", propName]
56000
- });
56001
- if (parsedDef === undefined) {
56002
- continue;
56003
- }
56004
- result.properties[propName] = parsedDef;
56005
- if (!propOptional) {
56006
- required2.push(propName);
56007
- }
56008
- }
56009
- if (required2.length) {
56010
- result.required = required2;
56011
- }
56012
- const additionalProperties = decideAdditionalProperties2(def, refs);
56013
- if (additionalProperties !== undefined) {
56014
- result.additionalProperties = additionalProperties;
56015
- }
56016
- return result;
56017
- }
56018
- function decideAdditionalProperties2(def, refs) {
56019
- if (def.catchall._def.typeName !== "ZodNever") {
56020
- return parseDef2(def.catchall._def, {
56021
- ...refs,
56022
- currentPath: [...refs.currentPath, "additionalProperties"]
56023
- });
56024
- }
56025
- switch (def.unknownKeys) {
56026
- case "passthrough":
56027
- return refs.allowedAdditionalProperties;
56028
- case "strict":
56029
- return refs.rejectedAdditionalProperties;
56030
- case "strip":
56031
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
56032
- }
56033
- }
56034
- function safeIsOptional2(schema) {
56035
- try {
56036
- return schema.isOptional();
56037
- } catch (e) {
56038
- return true;
56039
- }
56040
- }
56041
- var parseOptionalDef2 = (def, refs) => {
56042
- var _a23;
56043
- if (refs.currentPath.toString() === ((_a23 = refs.propertyPath) == null ? undefined : _a23.toString())) {
56044
- return parseDef2(def.innerType._def, refs);
56045
- }
56046
- const innerSchema = parseDef2(def.innerType._def, {
56047
- ...refs,
56048
- currentPath: [...refs.currentPath, "anyOf", "1"]
56049
- });
56050
- return innerSchema ? { anyOf: [{ not: parseAnyDef2() }, innerSchema] } : parseAnyDef2();
56051
- };
56052
- var parsePipelineDef2 = (def, refs) => {
56053
- if (refs.pipeStrategy === "input") {
56054
- return parseDef2(def.in._def, refs);
56055
- } else if (refs.pipeStrategy === "output") {
56056
- return parseDef2(def.out._def, refs);
56057
- }
56058
- const a = parseDef2(def.in._def, {
56059
- ...refs,
56060
- currentPath: [...refs.currentPath, "allOf", "0"]
56061
- });
56062
- const b = parseDef2(def.out._def, {
56063
- ...refs,
56064
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
56065
- });
56066
- return {
56067
- allOf: [a, b].filter((x) => x !== undefined)
56068
- };
56069
- };
56070
- function parsePromiseDef2(def, refs) {
56071
- return parseDef2(def.type._def, refs);
56072
- }
56073
- function parseSetDef2(def, refs) {
56074
- const items = parseDef2(def.valueType._def, {
56075
- ...refs,
56076
- currentPath: [...refs.currentPath, "items"]
56077
- });
56078
- const schema = {
56079
- type: "array",
56080
- uniqueItems: true,
56081
- items
56082
- };
56083
- if (def.minSize) {
56084
- schema.minItems = def.minSize.value;
56085
- }
56086
- if (def.maxSize) {
56087
- schema.maxItems = def.maxSize.value;
56088
- }
56089
- return schema;
56090
- }
56091
- function parseTupleDef2(def, refs) {
56092
- if (def.rest) {
56093
- return {
56094
- type: "array",
56095
- minItems: def.items.length,
56096
- items: def.items.map((x, i) => parseDef2(x._def, {
56097
- ...refs,
56098
- currentPath: [...refs.currentPath, "items", `${i}`]
56099
- })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []),
56100
- additionalItems: parseDef2(def.rest._def, {
56101
- ...refs,
56102
- currentPath: [...refs.currentPath, "additionalItems"]
56103
- })
56104
- };
56105
- } else {
56106
- return {
56107
- type: "array",
56108
- minItems: def.items.length,
56109
- maxItems: def.items.length,
56110
- items: def.items.map((x, i) => parseDef2(x._def, {
56111
- ...refs,
56112
- currentPath: [...refs.currentPath, "items", `${i}`]
56113
- })).reduce((acc, x) => x === undefined ? acc : [...acc, x], [])
56114
- };
56115
- }
56116
- }
56117
- function parseUndefinedDef2() {
56118
- return {
56119
- not: parseAnyDef2()
56120
- };
56121
- }
56122
- function parseUnknownDef2() {
56123
- return parseAnyDef2();
56124
- }
56125
- var parseReadonlyDef2 = (def, refs) => {
56126
- return parseDef2(def.innerType._def, refs);
56127
- };
56128
- var selectParser2 = (def, typeName, refs) => {
56129
- switch (typeName) {
56130
- case ZodFirstPartyTypeKind2.ZodString:
56131
- return parseStringDef2(def, refs);
56132
- case ZodFirstPartyTypeKind2.ZodNumber:
56133
- return parseNumberDef2(def);
56134
- case ZodFirstPartyTypeKind2.ZodObject:
56135
- return parseObjectDef2(def, refs);
56136
- case ZodFirstPartyTypeKind2.ZodBigInt:
56137
- return parseBigintDef2(def);
56138
- case ZodFirstPartyTypeKind2.ZodBoolean:
56139
- return parseBooleanDef2();
56140
- case ZodFirstPartyTypeKind2.ZodDate:
56141
- return parseDateDef2(def, refs);
56142
- case ZodFirstPartyTypeKind2.ZodUndefined:
56143
- return parseUndefinedDef2();
56144
- case ZodFirstPartyTypeKind2.ZodNull:
56145
- return parseNullDef2();
56146
- case ZodFirstPartyTypeKind2.ZodArray:
56147
- return parseArrayDef2(def, refs);
56148
- case ZodFirstPartyTypeKind2.ZodUnion:
56149
- case ZodFirstPartyTypeKind2.ZodDiscriminatedUnion:
56150
- return parseUnionDef2(def, refs);
56151
- case ZodFirstPartyTypeKind2.ZodIntersection:
56152
- return parseIntersectionDef2(def, refs);
56153
- case ZodFirstPartyTypeKind2.ZodTuple:
56154
- return parseTupleDef2(def, refs);
56155
- case ZodFirstPartyTypeKind2.ZodRecord:
56156
- return parseRecordDef2(def, refs);
56157
- case ZodFirstPartyTypeKind2.ZodLiteral:
56158
- return parseLiteralDef2(def);
56159
- case ZodFirstPartyTypeKind2.ZodEnum:
56160
- return parseEnumDef2(def);
56161
- case ZodFirstPartyTypeKind2.ZodNativeEnum:
56162
- return parseNativeEnumDef2(def);
56163
- case ZodFirstPartyTypeKind2.ZodNullable:
56164
- return parseNullableDef2(def, refs);
56165
- case ZodFirstPartyTypeKind2.ZodOptional:
56166
- return parseOptionalDef2(def, refs);
56167
- case ZodFirstPartyTypeKind2.ZodMap:
56168
- return parseMapDef2(def, refs);
56169
- case ZodFirstPartyTypeKind2.ZodSet:
56170
- return parseSetDef2(def, refs);
56171
- case ZodFirstPartyTypeKind2.ZodLazy:
56172
- return () => def.getter()._def;
56173
- case ZodFirstPartyTypeKind2.ZodPromise:
56174
- return parsePromiseDef2(def, refs);
56175
- case ZodFirstPartyTypeKind2.ZodNaN:
56176
- case ZodFirstPartyTypeKind2.ZodNever:
56177
- return parseNeverDef2();
56178
- case ZodFirstPartyTypeKind2.ZodEffects:
56179
- return parseEffectsDef2(def, refs);
56180
- case ZodFirstPartyTypeKind2.ZodAny:
56181
- return parseAnyDef2();
56182
- case ZodFirstPartyTypeKind2.ZodUnknown:
56183
- return parseUnknownDef2();
56184
- case ZodFirstPartyTypeKind2.ZodDefault:
56185
- return parseDefaultDef2(def, refs);
56186
- case ZodFirstPartyTypeKind2.ZodBranded:
56187
- return parseBrandedDef2(def, refs);
56188
- case ZodFirstPartyTypeKind2.ZodReadonly:
56189
- return parseReadonlyDef2(def, refs);
56190
- case ZodFirstPartyTypeKind2.ZodCatch:
56191
- return parseCatchDef2(def, refs);
56192
- case ZodFirstPartyTypeKind2.ZodPipeline:
56193
- return parsePipelineDef2(def, refs);
56194
- case ZodFirstPartyTypeKind2.ZodFunction:
56195
- case ZodFirstPartyTypeKind2.ZodVoid:
56196
- case ZodFirstPartyTypeKind2.ZodSymbol:
56197
- return;
56198
- default:
56199
- return /* @__PURE__ */ ((_) => {
56200
- return;
56201
- })(typeName);
56202
- }
56203
- };
56204
- var getRelativePath2 = (pathA, pathB) => {
56205
- let i = 0;
56206
- for (;i < pathA.length && i < pathB.length; i++) {
56207
- if (pathA[i] !== pathB[i])
56208
- break;
56209
- }
56210
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
56211
- };
56212
- function parseDef2(def, refs, forceResolution = false) {
56213
- var _a23;
56214
- const seenItem = refs.seen.get(def);
56215
- if (refs.override) {
56216
- const overrideResult = (_a23 = refs.override) == null ? undefined : _a23.call(refs, def, refs, seenItem, forceResolution);
56217
- if (overrideResult !== ignoreOverride2) {
56218
- return overrideResult;
56219
- }
56220
- }
56221
- if (seenItem && !forceResolution) {
56222
- const seenSchema = get$ref2(seenItem, refs);
56223
- if (seenSchema !== undefined) {
56224
- return seenSchema;
56225
- }
56226
- }
56227
- const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
56228
- refs.seen.set(def, newItem);
56229
- const jsonSchemaOrGetter = selectParser2(def, def.typeName, refs);
56230
- const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef2(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
56231
- if (jsonSchema2) {
56232
- addMeta2(def, refs, jsonSchema2);
56233
- }
56234
- if (refs.postProcess) {
56235
- const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
56236
- newItem.jsonSchema = jsonSchema2;
56237
- return postProcessResult;
56238
- }
56239
- newItem.jsonSchema = jsonSchema2;
56240
- return jsonSchema2;
56241
- }
56242
- var get$ref2 = (item, refs) => {
56243
- switch (refs.$refStrategy) {
56244
- case "root":
56245
- return { $ref: item.path.join("/") };
56246
- case "relative":
56247
- return { $ref: getRelativePath2(refs.currentPath, item.path) };
56248
- case "none":
56249
- case "seen": {
56250
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
56251
- console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
56252
- return parseAnyDef2();
56253
- }
56254
- return refs.$refStrategy === "seen" ? parseAnyDef2() : undefined;
56255
- }
56256
- }
56257
- };
56258
- var addMeta2 = (def, refs, jsonSchema2) => {
56259
- if (def.description) {
56260
- jsonSchema2.description = def.description;
56261
- }
56262
- return jsonSchema2;
56263
- };
56264
- var getRefs2 = (options) => {
56265
- const _options = getDefaultOptions2(options);
56266
- const currentPath = _options.name !== undefined ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
56267
- return {
56268
- ..._options,
56269
- currentPath,
56270
- propertyPath: undefined,
56271
- seen: new Map(Object.entries(_options.definitions).map(([name22, def]) => [
56272
- def._def,
56273
- {
56274
- def: def._def,
56275
- path: [..._options.basePath, _options.definitionPath, name22],
56276
- jsonSchema: undefined
56277
- }
56278
- ]))
56279
- };
56280
- };
56281
- var zod3ToJsonSchema2 = (schema, options) => {
56282
- var _a23;
56283
- const refs = getRefs2(options);
56284
- let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name32, schema2]) => {
56285
- var _a32;
56286
- return {
56287
- ...acc,
56288
- [name32]: (_a32 = parseDef2(schema2._def, {
56289
- ...refs,
56290
- currentPath: [...refs.basePath, refs.definitionPath, name32]
56291
- }, true)) != null ? _a32 : parseAnyDef2()
56292
- };
56293
- }, {}) : undefined;
56294
- const name22 = typeof options === "string" ? options : (options == null ? undefined : options.nameStrategy) === "title" ? undefined : options == null ? undefined : options.name;
56295
- const main = (_a23 = parseDef2(schema._def, name22 === undefined ? refs : {
56296
- ...refs,
56297
- currentPath: [...refs.basePath, refs.definitionPath, name22]
56298
- }, false)) != null ? _a23 : parseAnyDef2();
56299
- const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined;
56300
- if (title !== undefined) {
56301
- main.title = title;
56302
- }
56303
- const combined = name22 === undefined ? definitions ? {
56304
- ...main,
56305
- [refs.definitionPath]: definitions
56306
- } : main : {
56307
- $ref: [
56308
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
56309
- refs.definitionPath,
56310
- name22
56311
- ].join("/"),
56312
- [refs.definitionPath]: {
56313
- ...definitions,
56314
- [name22]: main
56315
- }
56316
- };
56317
- combined.$schema = "http://json-schema.org/draft-07/schema#";
56318
- return combined;
56319
- };
56320
- var schemaSymbol2 = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
56321
- function jsonSchema2(jsonSchema22, {
56322
- validate
56323
- } = {}) {
56324
- return {
56325
- [schemaSymbol2]: true,
56326
- _type: undefined,
56327
- get jsonSchema() {
56328
- if (typeof jsonSchema22 === "function") {
56329
- jsonSchema22 = jsonSchema22();
56330
- }
56331
- return jsonSchema22;
56332
- },
56333
- validate
56334
- };
56335
- }
56336
- function isSchema2(value) {
56337
- return typeof value === "object" && value !== null && schemaSymbol2 in value && value[schemaSymbol2] === true && "jsonSchema" in value && "validate" in value;
56338
- }
56339
- function asSchema2(schema) {
56340
- return schema == null ? jsonSchema2({ properties: {}, additionalProperties: false }) : isSchema2(schema) ? schema : ("~standard" in schema) ? schema["~standard"].vendor === "zod" ? zodSchema2(schema) : standardSchema2(schema) : schema();
56341
- }
56342
- function standardSchema2(standardSchema22) {
56343
- return jsonSchema2(() => addAdditionalPropertiesToJsonSchema2(standardSchema22["~standard"].jsonSchema.input({
56344
- target: "draft-07"
56345
- })), {
56346
- validate: async (value) => {
56347
- const result = await standardSchema22["~standard"].validate(value);
56348
- return "value" in result ? { success: true, value: result.value } : {
56349
- success: false,
56350
- error: new TypeValidationError({
56351
- value,
56352
- cause: result.issues
56353
- })
56354
- };
56355
- }
56356
- });
56357
- }
56358
- function zod3Schema2(zodSchema2, options) {
56359
- var _a23;
56360
- const useReferences = (_a23 = options == null ? undefined : options.useReferences) != null ? _a23 : false;
56361
- return jsonSchema2(() => zod3ToJsonSchema2(zodSchema2, {
56362
- $refStrategy: useReferences ? "root" : "none"
56363
- }), {
56364
- validate: async (value) => {
56365
- const result = await zodSchema2.safeParseAsync(value);
56366
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
56367
- }
56368
- });
56369
- }
56370
- function zod4Schema2(zodSchema2, options) {
56371
- var _a23;
56372
- const useReferences = (_a23 = options == null ? undefined : options.useReferences) != null ? _a23 : false;
56373
- return jsonSchema2(() => addAdditionalPropertiesToJsonSchema2(toJSONSchema(zodSchema2, {
56374
- target: "draft-7",
56375
- io: "input",
56376
- reused: useReferences ? "ref" : "inline"
56377
- })), {
56378
- validate: async (value) => {
56379
- const result = await safeParseAsync2(zodSchema2, value);
56380
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
56381
- }
56382
- });
56383
- }
56384
- function isZod4Schema2(zodSchema2) {
56385
- return "_zod" in zodSchema2;
56386
- }
56387
- function zodSchema2(zodSchema22, options) {
56388
- if (isZod4Schema2(zodSchema22)) {
56389
- return zod4Schema2(zodSchema22, options);
56390
- } else {
56391
- return zod3Schema2(zodSchema22, options);
56392
- }
56393
- }
56394
- async function validateTypes2({
56395
- value,
56396
- schema,
56397
- context
56398
- }) {
56399
- const result = await safeValidateTypes2({ value, schema, context });
56400
- if (!result.success) {
56401
- throw TypeValidationError.wrap({ value, cause: result.error, context });
56402
- }
56403
- return result.value;
56404
- }
56405
- async function safeValidateTypes2({
56406
- value,
56407
- schema,
56408
- context
56409
- }) {
56410
- const actualSchema = asSchema2(schema);
56411
- try {
56412
- if (actualSchema.validate == null) {
56413
- return { success: true, value, rawValue: value };
56414
- }
56415
- const result = await actualSchema.validate(value);
56416
- if (result.success) {
56417
- return { success: true, value: result.value, rawValue: value };
56418
- }
56419
- return {
56420
- success: false,
56421
- error: TypeValidationError.wrap({ value, cause: result.error, context }),
56422
- rawValue: value
56423
- };
56424
- } catch (error48) {
56425
- return {
56426
- success: false,
56427
- error: TypeValidationError.wrap({ value, cause: error48, context }),
56428
- rawValue: value
56429
- };
56430
- }
56431
- }
56432
- async function parseJSON2({
56433
- text,
56434
- schema
56435
- }) {
56436
- try {
56437
- const value = secureJsonParse2(text);
56438
- if (schema == null) {
56439
- return value;
56440
- }
56441
- return validateTypes2({ value, schema });
56442
- } catch (error48) {
56443
- if (JSONParseError.isInstance(error48) || TypeValidationError.isInstance(error48)) {
56444
- throw error48;
56445
- }
56446
- throw new JSONParseError({ text, cause: error48 });
56447
- }
56448
- }
56449
- async function safeParseJSON2({
56450
- text,
56451
- schema
56452
- }) {
56453
- try {
56454
- const value = secureJsonParse2(text);
56455
- if (schema == null) {
56456
- return { success: true, value, rawValue: value };
56457
- }
56458
- return await safeValidateTypes2({ value, schema });
56459
- } catch (error48) {
56460
- return {
56461
- success: false,
56462
- error: JSONParseError.isInstance(error48) ? error48 : new JSONParseError({ text, cause: error48 }),
56463
- rawValue: undefined
56464
- };
56465
- }
56466
- }
56467
- async function parseProviderOptions2({
56468
- provider,
56469
- providerOptions,
56470
- schema
56471
- }) {
56472
- if ((providerOptions == null ? undefined : providerOptions[provider]) == null) {
56473
- return;
56474
- }
56475
- const parsedProviderOptions = await safeValidateTypes2({
56476
- value: providerOptions[provider],
56477
- schema
56478
- });
56479
- if (!parsedProviderOptions.success) {
56480
- throw new InvalidArgumentError({
56481
- argument: "providerOptions",
56482
- message: `invalid ${provider} provider options`,
56483
- cause: parsedProviderOptions.error
56484
- });
56485
- }
56486
- return parsedProviderOptions.value;
56487
- }
56488
- var getOriginalFetch22 = () => globalThis.fetch;
56489
- var postJsonToApi2 = async ({
56490
- url: url2,
56491
- headers,
56492
- body,
56493
- failedResponseHandler,
56494
- successfulResponseHandler,
56495
- abortSignal,
56496
- fetch: fetch2
56497
- }) => postToApi2({
56498
- url: url2,
56499
- headers: {
56500
- "Content-Type": "application/json",
56501
- ...headers
56502
- },
56503
- body: {
56504
- content: JSON.stringify(body),
56505
- values: body
56506
- },
56507
- failedResponseHandler,
56508
- successfulResponseHandler,
56509
- abortSignal,
56510
- fetch: fetch2
56511
- });
56512
- var postToApi2 = async ({
56513
- url: url2,
56514
- headers = {},
56515
- body,
56516
- successfulResponseHandler,
56517
- failedResponseHandler,
56518
- abortSignal,
56519
- fetch: fetch2 = getOriginalFetch22()
56520
- }) => {
56521
- try {
56522
- const response = await fetch2(url2, {
56523
- method: "POST",
56524
- headers: withUserAgentSuffix2(headers, `ai-sdk/provider-utils/${VERSION8}`, getRuntimeEnvironmentUserAgent2()),
56525
- body: body.content,
56526
- signal: abortSignal
56527
- });
56528
- const responseHeaders = extractResponseHeaders2(response);
56529
- if (!response.ok) {
56530
- let errorInformation;
56531
- try {
56532
- errorInformation = await failedResponseHandler({
56533
- response,
56534
- url: url2,
56535
- requestBodyValues: body.values
56536
- });
56537
- } catch (error48) {
56538
- if (isAbortError2(error48) || APICallError.isInstance(error48)) {
56539
- throw error48;
56540
- }
56541
- throw new APICallError({
56542
- message: "Failed to process error response",
56543
- cause: error48,
56544
- statusCode: response.status,
56545
- url: url2,
56546
- responseHeaders,
56547
- requestBodyValues: body.values
56548
- });
56549
- }
56550
- throw errorInformation.value;
56551
- }
56552
- try {
56553
- return await successfulResponseHandler({
56554
- response,
56555
- url: url2,
56556
- requestBodyValues: body.values
56557
- });
56558
- } catch (error48) {
56559
- if (error48 instanceof Error) {
56560
- if (isAbortError2(error48) || APICallError.isInstance(error48)) {
56561
- throw error48;
56562
- }
56563
- }
56564
- throw new APICallError({
56565
- message: "Failed to process successful response",
56566
- cause: error48,
56567
- statusCode: response.status,
56568
- url: url2,
56569
- responseHeaders,
56570
- requestBodyValues: body.values
56571
- });
56572
- }
56573
- } catch (error48) {
56574
- throw handleFetchError2({ error: error48, url: url2, requestBodyValues: body.values });
56575
- }
56576
- };
56577
- var createJsonErrorResponseHandler2 = ({
56578
- errorSchema,
56579
- errorToMessage,
56580
- isRetryable
56581
- }) => async ({ response, url: url2, requestBodyValues }) => {
56582
- const responseBody = await response.text();
56583
- const responseHeaders = extractResponseHeaders2(response);
56584
- if (responseBody.trim() === "") {
56585
- return {
56586
- responseHeaders,
56587
- value: new APICallError({
56588
- message: response.statusText,
56589
- url: url2,
56590
- requestBodyValues,
56591
- statusCode: response.status,
56592
- responseHeaders,
56593
- responseBody,
56594
- isRetryable: isRetryable == null ? undefined : isRetryable(response)
56595
- })
56596
- };
56597
- }
56598
- try {
56599
- const parsedError = await parseJSON2({
56600
- text: responseBody,
56601
- schema: errorSchema
56602
- });
56603
- return {
56604
- responseHeaders,
56605
- value: new APICallError({
56606
- message: errorToMessage(parsedError),
56607
- url: url2,
56608
- requestBodyValues,
56609
- statusCode: response.status,
56610
- responseHeaders,
56611
- responseBody,
56612
- data: parsedError,
56613
- isRetryable: isRetryable == null ? undefined : isRetryable(response, parsedError)
56614
- })
56615
- };
56616
- } catch (parseError) {
56617
- return {
56618
- responseHeaders,
56619
- value: new APICallError({
56620
- message: response.statusText,
56621
- url: url2,
56622
- requestBodyValues,
56623
- statusCode: response.status,
56624
- responseHeaders,
56625
- responseBody,
56626
- isRetryable: isRetryable == null ? undefined : isRetryable(response)
56627
- })
56628
- };
56629
- }
56630
- };
56631
- var createJsonResponseHandler2 = (responseSchema2) => async ({ response, url: url2, requestBodyValues }) => {
56632
- const responseBody = await response.text();
56633
- const parsedResult = await safeParseJSON2({
56634
- text: responseBody,
56635
- schema: responseSchema2
56636
- });
56637
- const responseHeaders = extractResponseHeaders2(response);
56638
- if (!parsedResult.success) {
56639
- throw new APICallError({
56640
- message: "Invalid JSON response",
56641
- cause: parsedResult.error,
56642
- statusCode: response.status,
56643
- responseHeaders,
56644
- responseBody,
56645
- url: url2,
56646
- requestBodyValues
56647
- });
56648
- }
56649
- return {
56650
- responseHeaders,
56651
- value: parsedResult.value,
56652
- rawValue: parsedResult.rawValue
56653
- };
56654
- };
56655
- function withoutTrailingSlash2(url2) {
56656
- return url2 == null ? undefined : url2.replace(/\/$/, "");
56657
- }
56658
-
56659
- // node_modules/ollama-ai-provider-v2/dist/index.mjs
56660
- function convertToOllamaCompletionPrompt({
56661
- prompt,
56662
- user = "user",
56663
- assistant = "assistant"
56664
- }) {
56665
- let text = "";
56666
- if (prompt[0].role === "system") {
56667
- text += `${prompt[0].content}
56668
-
56669
- `;
56670
- prompt = prompt.slice(1);
56671
- }
56672
- for (const { role, content } of prompt) {
56673
- switch (role) {
56674
- case "system": {
56675
- throw new InvalidPromptError({
56676
- message: "Unexpected system message in prompt: ${content}",
56677
- prompt
56678
- });
56679
- }
56680
- case "user": {
56681
- const userMessage = content.map((part) => {
56682
- switch (part.type) {
56683
- case "text": {
56684
- return part.text;
56685
- }
56686
- }
56687
- }).filter(Boolean).join("");
56688
- text += `${user}:
56689
- ${userMessage}
56690
-
56691
- `;
56692
- break;
56693
- }
56694
- case "assistant": {
56695
- const assistantMessage = content.map((part) => {
56696
- switch (part.type) {
56697
- case "text": {
56698
- return part.text;
56699
- }
56700
- case "tool-call": {
56701
- throw new UnsupportedFunctionalityError({
56702
- functionality: "tool-call messages"
56703
- });
56704
- }
56705
- }
56706
- }).join("");
56707
- text += `${assistant}:
56708
- ${assistantMessage}
56709
-
56710
- `;
56711
- break;
56712
- }
56713
- case "tool": {
56714
- throw new UnsupportedFunctionalityError({
56715
- functionality: "tool messages"
56716
- });
56717
- }
56718
- default: {
56719
- const _exhaustiveCheck = role;
56720
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
56721
- }
56722
- }
56723
- }
56724
- text += `${assistant}:
56725
- `;
56726
- return {
56727
- prompt: text,
56728
- stopSequences: [`
56729
- ${user}:`]
56730
- };
56731
- }
56732
- function mapOllamaFinishReason(finishReason) {
56733
- switch (finishReason) {
56734
- case "stop":
56735
- return {
56736
- raw: finishReason,
56737
- unified: "stop"
56738
- };
56739
- case "length":
56740
- return {
56741
- raw: finishReason,
56742
- unified: "length"
56743
- };
56744
- case "content_filter":
56745
- return {
56746
- raw: finishReason,
56747
- unified: "content-filter"
56748
- };
56749
- case "function_call":
56750
- case "tool_calls":
56751
- return {
56752
- raw: finishReason,
56753
- unified: "tool-calls"
56754
- };
56755
- default:
56756
- return {
56757
- raw: finishReason,
56758
- unified: "other"
56759
- };
56760
- }
56761
- }
56762
- function getResponseMetadata5({
56763
- model,
56764
- created_at
56765
- }) {
56766
- return {
56767
- id: undefined,
56768
- modelId: model != null ? model : undefined,
56769
- timestamp: created_at != null ? new Date(created_at) : undefined
56770
- };
56771
- }
56772
- function createNdjsonStreamResponseHandler(schema) {
56773
- return async ({ response }) => {
56774
- const responseHeaders = extractResponseHeaders2(response);
56775
- if (response.body == null) {
56776
- throw new Error("Response body is null");
56777
- }
56778
- const reader = response.body.getReader();
56779
- const decoder = new TextDecoder;
56780
- let buffer = "";
56781
- const stream = new ReadableStream({
56782
- async pull(controller) {
56783
- while (true) {
56784
- const { done, value } = await reader.read();
56785
- if (done) {
56786
- if (buffer.trim()) {
56787
- try {
56788
- const parsed = JSON.parse(buffer.trim());
56789
- const validated = schema.parse(parsed);
56790
- controller.enqueue({ success: true, value: validated, rawValue: validated });
56791
- } catch (e) {}
56792
- }
56793
- controller.close();
56794
- return;
56795
- }
56796
- buffer += decoder.decode(value, { stream: true });
56797
- const lines = buffer.split(`
56798
- `);
56799
- buffer = lines.pop() || "";
56800
- for (const line of lines) {
56801
- const trimmedLine = line.trim();
56802
- if (trimmedLine) {
56803
- try {
56804
- const parsed = JSON.parse(trimmedLine);
56805
- const validated = schema.parse(parsed);
56806
- controller.enqueue({ success: true, value: validated, rawValue: validated });
56807
- } catch (error48) {
56808
- console.warn("Failed to parse NDJSON line:", error48);
56809
- }
56810
- }
56811
- }
56812
- }
56813
- },
56814
- cancel() {
56815
- reader.cancel();
56816
- }
56817
- });
56818
- return {
56819
- responseHeaders,
56820
- value: stream
56821
- };
55290
+ function createNdjsonStreamResponseHandler(schema) {
55291
+ return async ({ response }) => {
55292
+ const responseHeaders = extractResponseHeaders(response);
55293
+ if (response.body == null) {
55294
+ throw new Error("Response body is null");
55295
+ }
55296
+ const reader = response.body.getReader();
55297
+ const decoder = new TextDecoder;
55298
+ let buffer = "";
55299
+ const stream = new ReadableStream({
55300
+ async pull(controller) {
55301
+ while (true) {
55302
+ const { done, value } = await reader.read();
55303
+ if (done) {
55304
+ if (buffer.trim()) {
55305
+ try {
55306
+ const parsed = JSON.parse(buffer.trim());
55307
+ const validated = schema.parse(parsed);
55308
+ controller.enqueue({ success: true, value: validated, rawValue: validated });
55309
+ } catch (e) {}
55310
+ }
55311
+ controller.close();
55312
+ return;
55313
+ }
55314
+ buffer += decoder.decode(value, { stream: true });
55315
+ const lines = buffer.split(`
55316
+ `);
55317
+ buffer = lines.pop() || "";
55318
+ for (const line of lines) {
55319
+ const trimmedLine = line.trim();
55320
+ if (trimmedLine) {
55321
+ try {
55322
+ const parsed = JSON.parse(trimmedLine);
55323
+ const validated = schema.parse(parsed);
55324
+ controller.enqueue({ success: true, value: validated, rawValue: validated });
55325
+ } catch (error48) {
55326
+ console.warn("Failed to parse NDJSON line:", error48);
55327
+ }
55328
+ }
55329
+ }
55330
+ }
55331
+ },
55332
+ cancel() {
55333
+ reader.cancel();
55334
+ }
55335
+ });
55336
+ return {
55337
+ responseHeaders,
55338
+ value: stream
55339
+ };
56822
55340
  };
56823
55341
  }
56824
55342
  var ollamaErrorDataSchema = exports_external.object({
@@ -56829,7 +55347,7 @@ var ollamaErrorDataSchema = exports_external.object({
56829
55347
  code: exports_external.union([exports_external.string(), exports_external.number()]).nullish()
56830
55348
  })
56831
55349
  });
56832
- var ollamaFailedResponseHandler = createJsonErrorResponseHandler2({
55350
+ var ollamaFailedResponseHandler = createJsonErrorResponseHandler({
56833
55351
  errorSchema: ollamaErrorDataSchema,
56834
55352
  errorToMessage: (data) => data.error.message
56835
55353
  });
@@ -56911,15 +55429,15 @@ var OllamaCompletionLanguageModel = class {
56911
55429
  responseHeaders,
56912
55430
  value: response,
56913
55431
  rawValue: rawResponse
56914
- } = await postJsonToApi2({
55432
+ } = await postJsonToApi({
56915
55433
  url: this.config.url({
56916
55434
  path: "/generate",
56917
55435
  modelId: this.modelId
56918
55436
  }),
56919
- headers: combineHeaders2(this.config.headers(), options.headers),
55437
+ headers: combineHeaders(this.config.headers(), options.headers),
56920
55438
  body: { ...body, stream: false },
56921
55439
  failedResponseHandler: ollamaFailedResponseHandler,
56922
- successfulResponseHandler: createJsonResponseHandler2(baseOllamaResponseSchema),
55440
+ successfulResponseHandler: createJsonResponseHandler(baseOllamaResponseSchema),
56923
55441
  abortSignal: options.abortSignal,
56924
55442
  fetch: this.config.fetch
56925
55443
  });
@@ -56961,12 +55479,12 @@ var OllamaCompletionLanguageModel = class {
56961
55479
  ...args,
56962
55480
  stream: true
56963
55481
  };
56964
- const { responseHeaders, value: response } = await postJsonToApi2({
55482
+ const { responseHeaders, value: response } = await postJsonToApi({
56965
55483
  url: this.config.url({
56966
55484
  path: "/generate",
56967
55485
  modelId: this.modelId
56968
55486
  }),
56969
- headers: combineHeaders2(this.config.headers(), options.headers),
55487
+ headers: combineHeaders(this.config.headers(), options.headers),
56970
55488
  body,
56971
55489
  failedResponseHandler: ollamaFailedResponseHandler,
56972
55490
  successfulResponseHandler: createNdjsonStreamResponseHandler(baseOllamaResponseSchema),
@@ -56990,7 +55508,7 @@ var OllamaCompletionLanguageModel = class {
56990
55508
  };
56991
55509
  let isFirstChunk = true;
56992
55510
  let textStarted = false;
56993
- const textId = generateId2();
55511
+ const textId = generateId();
56994
55512
  return {
56995
55513
  stream: response.pipeThrough(new TransformStream({
56996
55514
  transform(chunk, controller) {
@@ -57104,7 +55622,7 @@ var OllamaEmbeddingModel = class {
57104
55622
  values
57105
55623
  });
57106
55624
  }
57107
- const ollamaOptions = await parseProviderOptions2({
55625
+ const ollamaOptions = await parseProviderOptions({
57108
55626
  provider: "ollama",
57109
55627
  providerOptions,
57110
55628
  schema: ollamaEmbeddingProviderOptions
@@ -57126,15 +55644,15 @@ var OllamaEmbeddingModel = class {
57126
55644
  responseHeaders,
57127
55645
  value: response,
57128
55646
  rawValue
57129
- } = await postJsonToApi2({
55647
+ } = await postJsonToApi({
57130
55648
  url: this.config.url({
57131
55649
  path: "/embed",
57132
55650
  modelId: this.modelId
57133
55651
  }),
57134
- headers: combineHeaders2(this.config.headers(), headers),
55652
+ headers: combineHeaders(this.config.headers(), headers),
57135
55653
  body: { ...body },
57136
55654
  failedResponseHandler: ollamaFailedResponseHandler,
57137
- successfulResponseHandler: createJsonResponseHandler2(ollamaTextEmbeddingResponseSchema),
55655
+ successfulResponseHandler: createJsonResponseHandler(ollamaTextEmbeddingResponseSchema),
57138
55656
  abortSignal,
57139
55657
  fetch: this.config.fetch
57140
55658
  });
@@ -57216,7 +55734,7 @@ var OllamaResponseProcessor = class {
57216
55734
  for (const toolCall of (_a16 = response.message.tool_calls) != null ? _a16 : []) {
57217
55735
  content.push({
57218
55736
  type: "tool-call",
57219
- toolCallId: (_e = toolCall.id) != null ? _e : (_d = (_c = (_b16 = this.config).generateId) == null ? undefined : _c.call(_b16)) != null ? _d : generateId2(),
55737
+ toolCallId: (_e = toolCall.id) != null ? _e : (_d = (_c = (_b16 = this.config).generateId) == null ? undefined : _c.call(_b16)) != null ? _d : generateId(),
57220
55738
  toolName: toolCall.function.name,
57221
55739
  input: JSON.stringify(toolCall.function.arguments)
57222
55740
  });
@@ -57665,7 +56183,7 @@ var OllamaRequestBuilder = class {
57665
56183
  return warnings;
57666
56184
  }
57667
56185
  async parseProviderOptions(providerOptions) {
57668
- const result = await parseProviderOptions2({
56186
+ const result = await parseProviderOptions({
57669
56187
  provider: "ollama",
57670
56188
  providerOptions,
57671
56189
  schema: ollamaProviderOptions
@@ -57741,8 +56259,8 @@ var OllamaStreamProcessor = class {
57741
56259
  hasReasoningStarted: false,
57742
56260
  textEnded: false,
57743
56261
  reasoningEnded: false,
57744
- textId: generateId2(),
57745
- reasoningId: generateId2()
56262
+ textId: generateId(),
56263
+ reasoningId: generateId()
57746
56264
  };
57747
56265
  }
57748
56266
  processChunk(chunk, controller, options) {
@@ -57853,7 +56371,7 @@ var OllamaStreamProcessor = class {
57853
56371
  }
57854
56372
  emitToolCall(toolCall, controller) {
57855
56373
  var _a16, _b16, _c, _d;
57856
- const id = (_d = toolCall.id) != null ? _d : (_c = (_b16 = (_a16 = this.config).generateId) == null ? undefined : _b16.call(_a16)) != null ? _c : generateId2();
56374
+ const id = (_d = toolCall.id) != null ? _d : (_c = (_b16 = (_a16 = this.config).generateId) == null ? undefined : _b16.call(_a16)) != null ? _c : generateId();
57857
56375
  controller.enqueue({
57858
56376
  type: "tool-input-start",
57859
56377
  id,
@@ -57918,15 +56436,15 @@ var OllamaResponsesLanguageModel = class {
57918
56436
  responseHeaders,
57919
56437
  value: response,
57920
56438
  rawValue: rawResponse
57921
- } = await postJsonToApi2({
56439
+ } = await postJsonToApi({
57922
56440
  url: this.config.url({
57923
56441
  path: "/chat",
57924
56442
  modelId: this.modelId
57925
56443
  }),
57926
- headers: combineHeaders2(this.config.headers(), options.headers),
56444
+ headers: combineHeaders(this.config.headers(), options.headers),
57927
56445
  body: { ...body, stream: false },
57928
56446
  failedResponseHandler: ollamaFailedResponseHandler,
57929
- successfulResponseHandler: createJsonResponseHandler2(baseOllamaResponseSchema2),
56447
+ successfulResponseHandler: createJsonResponseHandler(baseOllamaResponseSchema2),
57930
56448
  abortSignal: options.abortSignal,
57931
56449
  fetch: this.config.fetch
57932
56450
  });
@@ -57945,12 +56463,12 @@ var OllamaResponsesLanguageModel = class {
57945
56463
  }
57946
56464
  async doStream(options) {
57947
56465
  const { args: body, warnings } = await this.prepareRequest(options);
57948
- const { responseHeaders, value: response } = await postJsonToApi2({
56466
+ const { responseHeaders, value: response } = await postJsonToApi({
57949
56467
  url: this.config.url({
57950
56468
  path: "/chat",
57951
56469
  modelId: this.modelId
57952
56470
  }),
57953
- headers: combineHeaders2(this.config.headers(), options.headers),
56471
+ headers: combineHeaders(this.config.headers(), options.headers),
57954
56472
  body: { ...body, stream: true },
57955
56473
  failedResponseHandler: ollamaFailedResponseHandler,
57956
56474
  successfulResponseHandler: createNdjsonStreamResponseHandler(baseOllamaResponseSchema2),
@@ -57974,7 +56492,7 @@ var OllamaResponsesLanguageModel = class {
57974
56492
  };
57975
56493
  function createOllama(options = {}) {
57976
56494
  var _a16, _b16;
57977
- const baseURL = (_a16 = withoutTrailingSlash2(options.baseURL)) != null ? _a16 : "http://127.0.0.1:11434/api";
56495
+ const baseURL = (_a16 = withoutTrailingSlash(options.baseURL)) != null ? _a16 : "http://127.0.0.1:11434/api";
57978
56496
  const providerName = (_b16 = options.name) != null ? _b16 : "ollama";
57979
56497
  const getHeaders = () => ({
57980
56498
  "Ollama-Organization": options.organization,
@@ -61679,8 +60197,8 @@ async function prepareResponsesTools3({
61679
60197
  value: tool2.args,
61680
60198
  schema: mcpArgsSchema2
61681
60199
  });
61682
- const mapApprovalFilter = (filter3) => ({
61683
- tool_names: filter3.toolNames
60200
+ const mapApprovalFilter = (filter2) => ({
60201
+ tool_names: filter2.toolNames
61684
60202
  });
61685
60203
  const requireApproval = args.requireApproval;
61686
60204
  const requireApprovalParam = requireApproval == null ? undefined : typeof requireApproval === "string" ? requireApproval : requireApproval.never != null ? { never: mapApprovalFilter(requireApproval.never) } : undefined;
@@ -63741,7 +62259,7 @@ var OpenAITranscriptionModel2 = class {
63741
62259
  };
63742
62260
  }
63743
62261
  };
63744
- var VERSION9 = "3.0.53";
62262
+ var VERSION8 = "3.0.53";
63745
62263
  function createOpenAI(options = {}) {
63746
62264
  var _a16, _b16;
63747
62265
  const baseURL = (_a16 = withoutTrailingSlash(loadOptionalSetting({
@@ -63758,7 +62276,7 @@ function createOpenAI(options = {}) {
63758
62276
  "OpenAI-Organization": options.organization,
63759
62277
  "OpenAI-Project": options.project,
63760
62278
  ...options.headers
63761
- }, `ai-sdk/openai/${VERSION9}`);
62279
+ }, `ai-sdk/openai/${VERSION8}`);
63762
62280
  const createChatModel = (modelId) => new OpenAIChatLanguageModel2(modelId, {
63763
62281
  provider: `${providerName}.chat`,
63764
62282
  url: ({ path: path2 }) => `${baseURL}${path2}`,
@@ -63835,11 +62353,7 @@ var openai = createOpenAI();
63835
62353
 
63836
62354
  // src/providers/openai.ts
63837
62355
  function createOpenAIProvider(config2, providerName) {
63838
- return createOpenAI({
63839
- apiKey: resolveApiKey(config2.api_key_env, providerName),
63840
- baseURL: config2.base_url,
63841
- headers: config2.headers
63842
- });
62356
+ return createStandardProvider(createOpenAI, config2, providerName);
63843
62357
  }
63844
62358
 
63845
62359
  // node_modules/@ai-sdk/openai-compatible/dist/index.mjs
@@ -65310,7 +63824,7 @@ async function fileToBlob3(file2) {
65310
63824
  const data = file2.data instanceof Uint8Array ? file2.data : convertBase64ToUint8Array(file2.data);
65311
63825
  return new Blob([data], { type: file2.mediaType });
65312
63826
  }
65313
- var VERSION10 = "2.0.41";
63827
+ var VERSION9 = "2.0.41";
65314
63828
  function createOpenAICompatible(options) {
65315
63829
  const baseURL = withoutTrailingSlash(options.baseURL);
65316
63830
  const providerName = options.name;
@@ -65318,7 +63832,7 @@ function createOpenAICompatible(options) {
65318
63832
  ...options.apiKey && { Authorization: `Bearer ${options.apiKey}` },
65319
63833
  ...options.headers
65320
63834
  };
65321
- const getHeaders = () => withUserAgentSuffix(headers, `ai-sdk/openai-compatible/${VERSION10}`);
63835
+ const getHeaders = () => withUserAgentSuffix(headers, `ai-sdk/openai-compatible/${VERSION9}`);
65322
63836
  const getCommonModelConfig = (modelType) => ({
65323
63837
  provider: `${providerName}.${modelType}`,
65324
63838
  url: ({ path: path2 }) => {
@@ -65372,7 +63886,7 @@ function createOpenAICompatibleProvider(config2, providerName) {
65372
63886
  }
65373
63887
 
65374
63888
  // src/providers/portkey.ts
65375
- function createPortkeyProvider(config2, providerName, debug = false) {
63889
+ function createPortkeyProvider(config2, providerName) {
65376
63890
  if (!config2.base_url) {
65377
63891
  throw new ConfigValidationError(`Provider '${providerName}' (type: portkey) requires 'base_url' to be set.
65378
63892
  ` + `Example: base_url = "https://api.portkey.ai/v1"`);
@@ -65395,18 +63909,18 @@ function createPortkeyProvider(config2, providerName, debug = false) {
65395
63909
  if (config2.headers) {
65396
63910
  Object.assign(headers, config2.headers);
65397
63911
  }
65398
- logDebug(`Portkey base URL: ${config2.base_url}`, debug);
65399
- logDebug(`Portkey headers:`, debug);
63912
+ logDebug(`Portkey base URL: ${config2.base_url}`);
63913
+ logDebug(`Portkey headers:`);
65400
63914
  for (const [key, value] of Object.entries(headers)) {
65401
63915
  const maskedValue = isSensitiveKey(key) ? "[REDACTED]" : value;
65402
- logDebug(` ${key}: ${maskedValue}`, debug);
63916
+ logDebug(` ${key}: ${maskedValue}`);
65403
63917
  }
65404
63918
  const provider = createOpenAI({
65405
63919
  apiKey: "portkey",
65406
63920
  baseURL: config2.base_url,
65407
63921
  headers
65408
63922
  });
65409
- logDebug("Using Chat Completions API (not Responses API)", debug);
63923
+ logDebug("Using Chat Completions API (not Responses API)");
65410
63924
  return provider.chat;
65411
63925
  }
65412
63926
 
@@ -65430,16 +63944,19 @@ function resolveApiKeyCandidates(envVarNames, providerName) {
65430
63944
  }
65431
63945
  throw new MissingApiKeyError(envVarNames.join(" or "), providerName);
65432
63946
  }
65433
-
65434
- // src/providers/anthropic.ts
65435
- function createAnthropicProvider(config2, providerName) {
65436
- return createAnthropic({
63947
+ function createStandardProvider(factory12, config2, providerName) {
63948
+ return factory12({
65437
63949
  apiKey: resolveApiKey(config2.api_key_env, providerName),
65438
63950
  baseURL: config2.base_url,
65439
63951
  headers: config2.headers
65440
63952
  });
65441
63953
  }
65442
63954
 
63955
+ // src/providers/anthropic.ts
63956
+ function createAnthropicProvider(config2, providerName) {
63957
+ return createStandardProvider(createAnthropic, config2, providerName);
63958
+ }
63959
+
65443
63960
  // src/providers/index.ts
65444
63961
  function filterSensitiveFields(config2) {
65445
63962
  try {
@@ -65453,7 +63970,7 @@ function filterSensitiveFields(config2) {
65453
63970
  return {};
65454
63971
  }
65455
63972
  }
65456
- function resolveProvider(config2, providerOverride, modelOverride, debug = false) {
63973
+ function resolveProvider(config2, providerOverride, modelOverride) {
65457
63974
  const providerName = providerOverride ?? env.Q_PROVIDER ?? config2.default.provider;
65458
63975
  if (!providerName) {
65459
63976
  throw new SetupRequiredError;
@@ -65466,15 +63983,15 @@ function resolveProvider(config2, providerOverride, modelOverride, debug = false
65466
63983
  if (!modelId) {
65467
63984
  throw new ModelNotConfiguredError(providerName);
65468
63985
  }
65469
- logDebug(`Provider config: ${JSON.stringify(filterSensitiveFields(providerConfig), null, 2)}`, debug);
65470
- const model = createModel(providerConfig, providerName, modelId, debug);
63986
+ logDebug(`Provider config: ${JSON.stringify(filterSensitiveFields(providerConfig), null, 2)}`);
63987
+ const model = createModel(providerConfig, providerName, modelId);
65471
63988
  return {
65472
63989
  model,
65473
63990
  providerName,
65474
63991
  modelId
65475
63992
  };
65476
63993
  }
65477
- function createModel(config2, providerName, modelId, debug = false) {
63994
+ function createModel(config2, providerName, modelId) {
65478
63995
  switch (config2.type) {
65479
63996
  case "openai": {
65480
63997
  const provider = createOpenAIProvider(config2, providerName);
@@ -65493,7 +64010,7 @@ function createModel(config2, providerName, modelId, debug = false) {
65493
64010
  return provider(modelId);
65494
64011
  }
65495
64012
  case "portkey": {
65496
- const provider = createPortkeyProvider(config2, providerName, debug);
64013
+ const provider = createPortkeyProvider(config2, providerName);
65497
64014
  return provider(modelId);
65498
64015
  }
65499
64016
  case "google": {
@@ -65546,11 +64063,11 @@ function listProviders(config2) {
65546
64063
  // node_modules/@ai-sdk/gateway/dist/index.mjs
65547
64064
  var import_oidc = __toESM(require_dist(), 1);
65548
64065
  var import_oidc2 = __toESM(require_dist(), 1);
65549
- var marker18 = "vercel.ai.gateway.error";
65550
- var symbol18 = Symbol.for(marker18);
65551
- var _a18;
65552
- var _b18;
65553
- var GatewayError = class _GatewayError extends (_b18 = Error, _a18 = symbol18, _b18) {
64066
+ var marker17 = "vercel.ai.gateway.error";
64067
+ var symbol17 = Symbol.for(marker17);
64068
+ var _a17;
64069
+ var _b17;
64070
+ var GatewayError = class _GatewayError extends (_b17 = Error, _a17 = symbol17, _b17) {
65554
64071
  constructor({
65555
64072
  message,
65556
64073
  statusCode = 500,
@@ -65558,7 +64075,7 @@ var GatewayError = class _GatewayError extends (_b18 = Error, _a18 = symbol18, _
65558
64075
  generationId
65559
64076
  }) {
65560
64077
  super(generationId ? `${message} [${generationId}]` : message);
65561
- this[_a18] = true;
64078
+ this[_a17] = true;
65562
64079
  this.statusCode = statusCode;
65563
64080
  this.cause = cause;
65564
64081
  this.generationId = generationId;
@@ -65567,11 +64084,11 @@ var GatewayError = class _GatewayError extends (_b18 = Error, _a18 = symbol18, _
65567
64084
  return _GatewayError.hasMarker(error48);
65568
64085
  }
65569
64086
  static hasMarker(error48) {
65570
- return typeof error48 === "object" && error48 !== null && symbol18 in error48 && error48[symbol18] === true;
64087
+ return typeof error48 === "object" && error48 !== null && symbol17 in error48 && error48[symbol17] === true;
65571
64088
  }
65572
64089
  };
65573
- var name17 = "GatewayAuthenticationError";
65574
- var marker22 = `vercel.ai.gateway.error.${name17}`;
64090
+ var name16 = "GatewayAuthenticationError";
64091
+ var marker22 = `vercel.ai.gateway.error.${name16}`;
65575
64092
  var symbol23 = Symbol.for(marker22);
65576
64093
  var _a23;
65577
64094
  var _b22;
@@ -65584,7 +64101,7 @@ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b22
65584
64101
  } = {}) {
65585
64102
  super({ message, statusCode, cause, generationId });
65586
64103
  this[_a23] = true;
65587
- this.name = name17;
64104
+ this.name = name16;
65588
64105
  this.type = "authentication_error";
65589
64106
  }
65590
64107
  static isInstance(error48) {
@@ -66846,7 +65363,7 @@ async function getVercelRequestId() {
66846
65363
  var _a92;
66847
65364
  return (_a92 = import_oidc.getContext().headers) == null ? undefined : _a92["x-vercel-id"];
66848
65365
  }
66849
- var VERSION11 = "3.0.104";
65366
+ var VERSION10 = "3.0.104";
66850
65367
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
66851
65368
  function createGatewayProvider(options = {}) {
66852
65369
  var _a92, _b92;
@@ -66863,7 +65380,7 @@ function createGatewayProvider(options = {}) {
66863
65380
  "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
66864
65381
  [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
66865
65382
  ...options.headers
66866
- }, `ai-sdk/gateway/${VERSION11}`);
65383
+ }, `ai-sdk/gateway/${VERSION10}`);
66867
65384
  } catch (error48) {
66868
65385
  throw GatewayAuthenticationError.createContextualError({
66869
65386
  apiKeyProvided: false,
@@ -67041,10 +65558,10 @@ var __export2 = (target, all) => {
67041
65558
  for (var name21 in all)
67042
65559
  __defProp2(target, name21, { get: all[name21], enumerable: true });
67043
65560
  };
67044
- var name18 = "AI_InvalidArgumentError";
67045
- var marker19 = `vercel.ai.error.${name18}`;
67046
- var symbol19 = Symbol.for(marker19);
67047
- var _a19;
65561
+ var name17 = "AI_InvalidArgumentError";
65562
+ var marker18 = `vercel.ai.error.${name17}`;
65563
+ var symbol18 = Symbol.for(marker18);
65564
+ var _a18;
67048
65565
  var InvalidArgumentError2 = class extends AISDKError {
67049
65566
  constructor({
67050
65567
  parameter,
@@ -67052,18 +65569,18 @@ var InvalidArgumentError2 = class extends AISDKError {
67052
65569
  message
67053
65570
  }) {
67054
65571
  super({
67055
- name: name18,
65572
+ name: name17,
67056
65573
  message: `Invalid argument for parameter ${parameter}: ${message}`
67057
65574
  });
67058
- this[_a19] = true;
65575
+ this[_a18] = true;
67059
65576
  this.parameter = parameter;
67060
65577
  this.value = value;
67061
65578
  }
67062
65579
  static isInstance(error48) {
67063
- return AISDKError.hasMarker(error48, marker19);
65580
+ return AISDKError.hasMarker(error48, marker18);
67064
65581
  }
67065
65582
  };
67066
- _a19 = symbol19;
65583
+ _a18 = symbol18;
67067
65584
  var name23 = "AI_InvalidStreamPartError";
67068
65585
  var marker23 = `vercel.ai.error.${name23}`;
67069
65586
  var symbol24 = Symbol.for(marker23);
@@ -67303,15 +65820,15 @@ var InvalidMessageRoleError = class extends AISDKError {
67303
65820
  }
67304
65821
  };
67305
65822
  _a172 = symbol172;
67306
- var name182 = "AI_MessageConversionError";
67307
- var marker182 = `vercel.ai.error.${name182}`;
65823
+ var name18 = "AI_MessageConversionError";
65824
+ var marker182 = `vercel.ai.error.${name18}`;
67308
65825
  var symbol182 = Symbol.for(marker182);
67309
65826
  var _a182;
67310
65827
  _a182 = symbol182;
67311
65828
  var name19 = "AI_RetryError";
67312
- var marker192 = `vercel.ai.error.${name19}`;
67313
- var symbol192 = Symbol.for(marker192);
67314
- var _a192;
65829
+ var marker19 = `vercel.ai.error.${name19}`;
65830
+ var symbol19 = Symbol.for(marker19);
65831
+ var _a19;
67315
65832
  var RetryError = class extends AISDKError {
67316
65833
  constructor({
67317
65834
  message,
@@ -67319,16 +65836,16 @@ var RetryError = class extends AISDKError {
67319
65836
  errors: errors3
67320
65837
  }) {
67321
65838
  super({ name: name19, message });
67322
- this[_a192] = true;
65839
+ this[_a19] = true;
67323
65840
  this.reason = reason;
67324
65841
  this.errors = errors3;
67325
65842
  this.lastError = errors3[errors3.length - 1];
67326
65843
  }
67327
65844
  static isInstance(error48) {
67328
- return AISDKError.hasMarker(error48, marker192);
65845
+ return AISDKError.hasMarker(error48, marker19);
67329
65846
  }
67330
65847
  };
67331
- _a192 = symbol192;
65848
+ _a19 = symbol19;
67332
65849
  function asArray(value) {
67333
65850
  return value === undefined ? [] : Array.isArray(value) ? value : [value];
67334
65851
  }
@@ -67625,7 +66142,7 @@ function detectMediaType({
67625
66142
  }
67626
66143
  return;
67627
66144
  }
67628
- var VERSION12 = "6.0.168";
66145
+ var VERSION11 = "6.0.168";
67629
66146
  var download = async ({
67630
66147
  url: url2,
67631
66148
  maxBytes,
@@ -67636,7 +66153,7 @@ var download = async ({
67636
66153
  validateDownloadUrl(urlText);
67637
66154
  try {
67638
66155
  const response = await fetch(urlText, {
67639
- headers: withUserAgentSuffix({}, `ai-sdk/${VERSION12}`, getRuntimeEnvironmentUserAgent()),
66156
+ headers: withUserAgentSuffix({}, `ai-sdk/${VERSION11}`, getRuntimeEnvironmentUserAgent()),
67640
66157
  signal: abortSignal
67641
66158
  });
67642
66159
  if (response.redirected) {
@@ -69490,9 +68007,9 @@ var object2 = ({
69490
68007
  const schema = asSchema(inputSchema);
69491
68008
  return {
69492
68009
  name: "object",
69493
- responseFormat: resolve(schema.jsonSchema).then((jsonSchema22) => ({
68010
+ responseFormat: resolve(schema.jsonSchema).then((jsonSchema2) => ({
69494
68011
  type: "json",
69495
- schema: jsonSchema22,
68012
+ schema: jsonSchema2,
69496
68013
  ...name21 != null && { name: name21 },
69497
68014
  ...description != null && { description }
69498
68015
  })),
@@ -69552,8 +68069,8 @@ var array2 = ({
69552
68069
  const elementSchema = asSchema(inputElementSchema);
69553
68070
  return {
69554
68071
  name: "array",
69555
- responseFormat: resolve(elementSchema.jsonSchema).then((jsonSchema22) => {
69556
- const { $schema, ...itemSchema } = jsonSchema22;
68072
+ responseFormat: resolve(elementSchema.jsonSchema).then((jsonSchema2) => {
68073
+ const { $schema, ...itemSchema } = jsonSchema2;
69557
68074
  return {
69558
68075
  type: "json",
69559
68076
  schema: {
@@ -71219,7 +69736,7 @@ function runToolsTransformation({
71219
69736
  abortSignal,
71220
69737
  repairToolCall,
71221
69738
  experimental_context,
71222
- generateId: generateId22,
69739
+ generateId: generateId2,
71223
69740
  stepNumber,
71224
69741
  model,
71225
69742
  onToolCallStart,
@@ -71349,14 +69866,14 @@ function runToolsTransformation({
71349
69866
  })) {
71350
69867
  toolResultsStreamController.enqueue({
71351
69868
  type: "tool-approval-request",
71352
- approvalId: generateId22(),
69869
+ approvalId: generateId2(),
71353
69870
  toolCall
71354
69871
  });
71355
69872
  break;
71356
69873
  }
71357
69874
  toolInputs.set(toolCall.toolCallId, toolCall.input);
71358
69875
  if (tool2.execute != null && toolCall.providerExecuted !== true) {
71359
- const toolExecutionId = generateId22();
69876
+ const toolExecutionId = generateId2();
71360
69877
  outstandingToolResults.add(toolExecutionId);
71361
69878
  executeToolCall({
71362
69879
  toolCall,
@@ -71489,7 +70006,7 @@ function streamText({
71489
70006
  experimental_onToolCallFinish: onToolCallFinish,
71490
70007
  experimental_context,
71491
70008
  experimental_include: include,
71492
- _internal: { now: now2 = now, generateId: generateId22 = originalGenerateId2 } = {},
70009
+ _internal: { now: now2 = now, generateId: generateId2 = originalGenerateId2 } = {},
71493
70010
  ...settings
71494
70011
  }) {
71495
70012
  const totalTimeoutMs = getTotalTimeoutMs(timeout);
@@ -71534,7 +70051,7 @@ function streamText({
71534
70051
  onToolCallStart,
71535
70052
  onToolCallFinish,
71536
70053
  now: now2,
71537
- generateId: generateId22,
70054
+ generateId: generateId2,
71538
70055
  experimental_context,
71539
70056
  download: download2,
71540
70057
  include
@@ -71628,7 +70145,7 @@ var DefaultStreamTextResult = class {
71628
70145
  prepareStep,
71629
70146
  includeRawChunks,
71630
70147
  now: now2,
71631
- generateId: generateId22,
70148
+ generateId: generateId2,
71632
70149
  timeout,
71633
70150
  stopWhen,
71634
70151
  originalAbortSignal,
@@ -72274,7 +70791,7 @@ var DefaultStreamTextResult = class {
72274
70791
  repairToolCall,
72275
70792
  abortSignal,
72276
70793
  experimental_context,
72277
- generateId: generateId22,
70794
+ generateId: generateId2,
72278
70795
  stepNumber: recordedSteps.length,
72279
70796
  model: stepModelInfo,
72280
70797
  onToolCallStart: [
@@ -72297,7 +70814,7 @@ var DefaultStreamTextResult = class {
72297
70814
  let stepProviderMetadata;
72298
70815
  let stepFirstChunk = true;
72299
70816
  let stepResponse = {
72300
- id: generateId22(),
70817
+ id: generateId2(),
72301
70818
  timestamp: /* @__PURE__ */ new Date,
72302
70819
  modelId: modelInfo.modelId
72303
70820
  };
@@ -73345,6 +71862,22 @@ function stripAnsi(str) {
73345
71862
  return str;
73346
71863
  return str.replace(ANSI_REGEX, "");
73347
71864
  }
71865
+ function escapeControlCharacters(str) {
71866
+ const normalised = str.replace(/\r\n/g, `
71867
+ `);
71868
+ return normalised.replace(/[\x00-\x08\x0B-\x1F\x7F-\x9F‪-‮⁦-⁩]/g, (char) => {
71869
+ const code = char.charCodeAt(0);
71870
+ if (code > 255) {
71871
+ return `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`;
71872
+ }
71873
+ return `\\x${code.toString(16).padStart(2, "0").toUpperCase()}`;
71874
+ });
71875
+ }
71876
+ function sanitizeForTerminal(str) {
71877
+ if (!str)
71878
+ return str;
71879
+ return escapeControlCharacters(str);
71880
+ }
73348
71881
  function createAnsiStripper() {
73349
71882
  let buffer = "";
73350
71883
  return (chunk) => {
@@ -73373,7 +71906,7 @@ function buildUserPrompt(query, context2) {
73373
71906
  if (!context2) {
73374
71907
  return query;
73375
71908
  }
73376
- const safeContext = context2.replace(/<\/\s*context\b[^>]*>/gi, "<\\/context>");
71909
+ const safeContext = context2.replace(/<\s*context\b[^>]*>/gi, "<\\context>").replace(/<\/\s*context\b[^>]*>/gi, "<\\/context>");
73377
71910
  return `<context>
73378
71911
  ${safeContext}
73379
71912
  </context>
@@ -73397,26 +71930,29 @@ async function runQuery(options) {
73397
71930
  });
73398
71931
  let fullText = "";
73399
71932
  let sawTextChunk = false;
71933
+ let lastWriteEndsWithNewline = false;
73400
71934
  const stripper = createAnsiStripper();
73401
71935
  for await (const textPart of result.textStream) {
73402
71936
  if (!sawTextChunk) {
73403
71937
  sawTextChunk = true;
73404
71938
  onFirstChunk?.();
73405
71939
  }
73406
- const safeText = stripper(textPart);
73407
- process.stdout.write(safeText);
71940
+ const safeText = sanitizeForTerminal(stripper(textPart));
71941
+ if (safeText.length > 0) {
71942
+ process.stdout.write(safeText);
71943
+ lastWriteEndsWithNewline = safeText.endsWith(`
71944
+ `);
71945
+ }
73408
71946
  fullText += textPart;
73409
71947
  }
73410
71948
  if (streamError !== undefined) {
73411
- if (fullText !== "" && !fullText.endsWith(`
73412
- `)) {
71949
+ if (sawTextChunk && !lastWriteEndsWithNewline) {
73413
71950
  process.stdout.write(`
73414
71951
  `);
73415
71952
  }
73416
71953
  throw streamError;
73417
71954
  }
73418
- if (!fullText.endsWith(`
73419
- `)) {
71955
+ if (sawTextChunk && !lastWriteEndsWithNewline) {
73420
71956
  process.stdout.write(`
73421
71957
  `);
73422
71958
  }
@@ -73489,7 +72025,7 @@ async function main() {
73489
72025
  const args = parseCliArgs();
73490
72026
  debug = args.options.debug;
73491
72027
  configureLogging({ debug });
73492
- updateLogContext({ command: args.command, configPath: getConfigPath() });
72028
+ updateLogContext({ command: args.command, configPath: getXdgConfigPath() });
73493
72029
  if (args.options.version) {
73494
72030
  console.log(getVersion());
73495
72031
  process.exit(0);
@@ -73497,7 +72033,7 @@ async function main() {
73497
72033
  if (args.command === "config") {
73498
72034
  switch (args.subcommand) {
73499
72035
  case "path":
73500
- console.log(getConfigPath());
72036
+ console.log(getXdgConfigPath());
73501
72037
  process.exit(0);
73502
72038
  break;
73503
72039
  case "init": {
@@ -73536,10 +72072,10 @@ async function main() {
73536
72072
  updateLogContext({
73537
72073
  attempt,
73538
72074
  command: args.command,
73539
- configPath: getConfigPath()
72075
+ configPath: getXdgConfigPath()
73540
72076
  });
73541
72077
  try {
73542
- await runQueryAttempt(args, stdinInput, debug);
72078
+ await runQueryAttempt(args, stdinInput);
73543
72079
  process.exit(0);
73544
72080
  } catch (err) {
73545
72081
  const action = await handleFailure(err, debug, stdinInput);
@@ -73554,7 +72090,7 @@ async function main() {
73554
72090
  }
73555
72091
  } catch (err) {
73556
72092
  configureLogging({ debug });
73557
- updateLogContext({ configPath: getConfigPath() });
72093
+ updateLogContext({ configPath: getXdgConfigPath() });
73558
72094
  await handleFailure(err, debug, null);
73559
72095
  if (err instanceof QError2) {
73560
72096
  process.exit(err.exitCode);
@@ -73562,29 +72098,29 @@ async function main() {
73562
72098
  process.exit(1);
73563
72099
  }
73564
72100
  }
73565
- async function runQueryAttempt(args, stdinInput, debug) {
72101
+ async function runQueryAttempt(args, stdinInput) {
73566
72102
  const { source, query, context: context2 } = resolveInput(stdinInput, args.query);
73567
72103
  updateLogContext({
73568
72104
  source,
73569
72105
  queryLength: query.length,
73570
72106
  contextLength: context2?.length ?? 0
73571
72107
  });
73572
- logDebug2(`Source: ${source}`, debug);
72108
+ logDebug2(`Source: ${source}`);
73573
72109
  if (query.length > MAX_QUERY_LENGTH) {
73574
72110
  throw new UsageError2(`Query too long (${query.length} characters). Maximum is ${MAX_QUERY_LENGTH}.`);
73575
72111
  }
73576
72112
  if (context2 && context2.length > MAX_CONTEXT_LENGTH) {
73577
72113
  throw new UsageError2(`Context too long (${context2.length} characters). Maximum is ${MAX_CONTEXT_LENGTH}.`);
73578
72114
  }
73579
- logDebug2("Loading config...", debug);
72115
+ logDebug2("Loading config...");
73580
72116
  const config2 = await loadConfig();
73581
- logDebug2(`Resolving provider: ${args.options.provider ?? config2.default.provider}`, debug);
73582
- const { model, providerName, modelId } = resolveProvider(config2, args.options.provider, args.options.model, debug);
72117
+ logDebug2(`Resolving provider: ${args.options.provider ?? config2.default.provider}`);
72118
+ const { model, providerName, modelId } = resolveProvider(config2, args.options.provider, args.options.model);
73583
72119
  updateLogContext({ provider: providerName, model: modelId });
73584
72120
  const envInfo = getEnvironmentInfo();
73585
- logDebug2(`Query: ${query}`, debug);
73586
- logDebug2(`Provider: ${providerName}, Model: ${modelId}`, debug);
73587
- logDebug2(formatEnvForDebug(envInfo), debug);
72121
+ logDebug2(`Query: ${query}`);
72122
+ logDebug2(`Provider: ${providerName}, Model: ${modelId}`);
72123
+ logDebug2(formatEnvForDebug(envInfo));
73588
72124
  const loadingIndicator = startLoadingIndicator({
73589
72125
  enabled: process.stderr.isTTY === true
73590
72126
  });
@@ -73603,7 +72139,7 @@ async function runQueryAttempt(args, stdinInput, debug) {
73603
72139
  const { sanitizeForClipboard: sanitizeForClipboard2 } = await Promise.resolve().then(() => (init_ansi(), exports_ansi));
73604
72140
  const safeClipboardText = sanitizeForClipboard2(result.text);
73605
72141
  await clipboard8.write(safeClipboardText);
73606
- logDebug2("Copied to clipboard", debug);
72142
+ logDebug2("Copied to clipboard");
73607
72143
  } catch {
73608
72144
  printStderr2("Warning: could not copy to clipboard.");
73609
72145
  }