@use-lattice/litmus 0.121.3

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 (199) hide show
  1. package/LICENSE +19 -0
  2. package/dist/src/accounts-Bt1oJb1Z.cjs +219 -0
  3. package/dist/src/accounts-DjOU8Rm3.js +178 -0
  4. package/dist/src/agentic-utils-D03IiXQc.js +153 -0
  5. package/dist/src/agentic-utils-Dh7xaMQM.cjs +180 -0
  6. package/dist/src/agents-C6BIMlZa.js +231 -0
  7. package/dist/src/agents-DvIpNX1L.cjs +666 -0
  8. package/dist/src/agents-ZP0RP9vV.cjs +231 -0
  9. package/dist/src/agents-maJXdjbR.js +665 -0
  10. package/dist/src/aimlapi-BTbQjG2E.cjs +30 -0
  11. package/dist/src/aimlapi-CwMxqfXP.js +30 -0
  12. package/dist/src/audio-BBUdvsde.cjs +97 -0
  13. package/dist/src/audio-D5DPZ7I-.js +97 -0
  14. package/dist/src/base-BEysXrkq.cjs +222 -0
  15. package/dist/src/base-C451JQfq.js +193 -0
  16. package/dist/src/blobs-BY8MDmpo.js +230 -0
  17. package/dist/src/blobs-BgcNn97m.cjs +256 -0
  18. package/dist/src/cache-BBE_lsTA.cjs +4 -0
  19. package/dist/src/cache-BkrqU5Ba.js +237 -0
  20. package/dist/src/cache-DsCxFlsZ.cjs +297 -0
  21. package/dist/src/chat-CPJWDP6a.cjs +289 -0
  22. package/dist/src/chat-CXX3xzkk.cjs +811 -0
  23. package/dist/src/chat-CcDgZFJ4.js +787 -0
  24. package/dist/src/chat-Dz5ZeGO2.js +289 -0
  25. package/dist/src/chatkit-Dw0mKkML.cjs +1158 -0
  26. package/dist/src/chatkit-swAIVuea.js +1157 -0
  27. package/dist/src/chunk-DEq-mXcV.js +15 -0
  28. package/dist/src/claude-agent-sdk-BXZJtOg6.js +379 -0
  29. package/dist/src/claude-agent-sdk-CkfyjDoG.cjs +383 -0
  30. package/dist/src/cloudflare-ai-BzpJcqUH.js +161 -0
  31. package/dist/src/cloudflare-ai-Cmy_R1y2.cjs +161 -0
  32. package/dist/src/cloudflare-gateway-B9tVQKok.cjs +272 -0
  33. package/dist/src/cloudflare-gateway-DrD3ew3H.js +272 -0
  34. package/dist/src/codex-sdk-Dezj9Nwm.js +1056 -0
  35. package/dist/src/codex-sdk-Dl9D4k5B.cjs +1060 -0
  36. package/dist/src/cometapi-C-9YvCHC.js +54 -0
  37. package/dist/src/cometapi-DHgDKoO2.cjs +54 -0
  38. package/dist/src/completion-B8Ctyxpr.js +120 -0
  39. package/dist/src/completion-Cxrt08sj.cjs +131 -0
  40. package/dist/src/createHash-BwgE13yv.cjs +27 -0
  41. package/dist/src/createHash-DmPQkvBh.js +15 -0
  42. package/dist/src/docker-BiqcTwLv.js +80 -0
  43. package/dist/src/docker-C7tEJnP-.cjs +80 -0
  44. package/dist/src/esm-C62Zofr1.cjs +409 -0
  45. package/dist/src/esm-DMVc93eh.js +379 -0
  46. package/dist/src/evalResult-C3NJPQOo.cjs +301 -0
  47. package/dist/src/evalResult-C7JJAPBb.js +295 -0
  48. package/dist/src/evalResult-DoVTZZWI.cjs +2 -0
  49. package/dist/src/extractor-DnMD3fwt.cjs +391 -0
  50. package/dist/src/extractor-DtlL28vL.js +374 -0
  51. package/dist/src/fetch-BTxakTSg.cjs +1133 -0
  52. package/dist/src/fetch-DQckpUFz.js +928 -0
  53. package/dist/src/fileExtensions-DnqA1y9x.js +85 -0
  54. package/dist/src/fileExtensions-bYh77CN8.cjs +114 -0
  55. package/dist/src/genaiTracer-CyZrmaK0.cjs +268 -0
  56. package/dist/src/genaiTracer-D3fD9dNV.js +256 -0
  57. package/dist/src/graders-BNscxFrU.js +13644 -0
  58. package/dist/src/graders-D2oE9Msq.js +2 -0
  59. package/dist/src/graders-c0Ez_w-9.cjs +2 -0
  60. package/dist/src/graders-d0F2M3e9.cjs +14056 -0
  61. package/dist/src/image-0ZhE0VlR.cjs +280 -0
  62. package/dist/src/image-CWE1pdNv.js +257 -0
  63. package/dist/src/image-D9ZK6hwL.js +163 -0
  64. package/dist/src/image-DKZgZITg.cjs +163 -0
  65. package/dist/src/index.cjs +11366 -0
  66. package/dist/src/index.d.cts +19640 -0
  67. package/dist/src/index.d.ts +19641 -0
  68. package/dist/src/index.js +11306 -0
  69. package/dist/src/invariant-Ddh24eXh.js +25 -0
  70. package/dist/src/invariant-kfQ8Bu82.cjs +30 -0
  71. package/dist/src/knowledgeBase-BgPyGFUd.cjs +122 -0
  72. package/dist/src/knowledgeBase-DyHilYaP.js +122 -0
  73. package/dist/src/litellm-CyMeneHS.js +135 -0
  74. package/dist/src/litellm-DWDF73yF.cjs +135 -0
  75. package/dist/src/logger-C40ZGil9.js +717 -0
  76. package/dist/src/logger-DyfK9PBt.cjs +917 -0
  77. package/dist/src/luma-ray-BAU9X_ep.cjs +315 -0
  78. package/dist/src/luma-ray-nwVseBbv.js +313 -0
  79. package/dist/src/messages-B5ADWTTv.js +245 -0
  80. package/dist/src/messages-BCnZfqrS.cjs +257 -0
  81. package/dist/src/meteor-DLZZ3osF.cjs +134 -0
  82. package/dist/src/meteor-DUiCJRC-.js +134 -0
  83. package/dist/src/modelslab-00cveB8L.cjs +163 -0
  84. package/dist/src/modelslab-D9sCU_L7.js +163 -0
  85. package/dist/src/nova-reel-CTapvqYH.js +276 -0
  86. package/dist/src/nova-reel-DlWuuroF.cjs +278 -0
  87. package/dist/src/nova-sonic-5UPWfeMv.cjs +363 -0
  88. package/dist/src/nova-sonic-BhSwQNym.js +363 -0
  89. package/dist/src/openai-BWrJK9d8.cjs +52 -0
  90. package/dist/src/openai-DumO8WQn.js +47 -0
  91. package/dist/src/openclaw-B8brrjC_.cjs +577 -0
  92. package/dist/src/openclaw-Bkayww9q.js +571 -0
  93. package/dist/src/opencode-sdk-7xjoDNiM.cjs +562 -0
  94. package/dist/src/opencode-sdk-SGwAPxht.js +558 -0
  95. package/dist/src/otlpReceiver-CoAHfAN9.cjs +15 -0
  96. package/dist/src/otlpReceiver-oO3EQwI9.js +14 -0
  97. package/dist/src/providerRegistry-4yjhaEM8.js +45 -0
  98. package/dist/src/providerRegistry-DhV4rJIc.cjs +50 -0
  99. package/dist/src/providers-B5RJVG-7.cjs +33609 -0
  100. package/dist/src/providers-BdmZCLzV.js +33262 -0
  101. package/dist/src/providers-CxtRxn8e.js +2 -0
  102. package/dist/src/providers-DnQLNbx1.cjs +3 -0
  103. package/dist/src/pythonUtils-BD0druiM.cjs +275 -0
  104. package/dist/src/pythonUtils-IBhn5YGR.js +249 -0
  105. package/dist/src/quiverai-BDOwZBsM.cjs +213 -0
  106. package/dist/src/quiverai-D3JTF5lD.js +213 -0
  107. package/dist/src/responses-B2LCDCXZ.js +667 -0
  108. package/dist/src/responses-BvNm4Xv9.cjs +685 -0
  109. package/dist/src/rubyUtils-B0NwnfpY.cjs +245 -0
  110. package/dist/src/rubyUtils-BroxzZ7c.cjs +2 -0
  111. package/dist/src/rubyUtils-hqVw5UvJ.js +222 -0
  112. package/dist/src/sagemaker-Cno2V-Sx.js +689 -0
  113. package/dist/src/sagemaker-fV_KUgs5.cjs +691 -0
  114. package/dist/src/server-BOuAXb06.cjs +238 -0
  115. package/dist/src/server-CtI-EWzm.cjs +2 -0
  116. package/dist/src/server-Cy3DZymt.js +189 -0
  117. package/dist/src/slack-CP8xBePa.js +135 -0
  118. package/dist/src/slack-DSQ1yXVb.cjs +135 -0
  119. package/dist/src/store-BwDDaBjb.cjs +246 -0
  120. package/dist/src/store-DcbLC593.cjs +2 -0
  121. package/dist/src/store-IGpqMIkv.js +240 -0
  122. package/dist/src/tables-3Q2cL7So.cjs +373 -0
  123. package/dist/src/tables-Bi2fjr4W.js +288 -0
  124. package/dist/src/telemetry-Bg2WqF79.js +161 -0
  125. package/dist/src/telemetry-D0x6u5kX.cjs +166 -0
  126. package/dist/src/telemetry-DXNimrI0.cjs +2 -0
  127. package/dist/src/text-B_UCRPp2.js +22 -0
  128. package/dist/src/text-CW1cyrwj.cjs +33 -0
  129. package/dist/src/tokenUsageUtils-NYT-WKS6.js +138 -0
  130. package/dist/src/tokenUsageUtils-bVa1ga6f.cjs +173 -0
  131. package/dist/src/transcription-Cl_W16Pr.js +122 -0
  132. package/dist/src/transcription-yt1EecY8.cjs +124 -0
  133. package/dist/src/transform-BCtGrl_W.cjs +228 -0
  134. package/dist/src/transform-Bv6gG2MJ.cjs +1688 -0
  135. package/dist/src/transform-CY1wbpRy.js +1507 -0
  136. package/dist/src/transform-DU8rUL9P.cjs +2 -0
  137. package/dist/src/transform-yWaShiKr.js +216 -0
  138. package/dist/src/transformersAvailability-BGkzavwb.js +35 -0
  139. package/dist/src/transformersAvailability-DKoRtQLy.cjs +35 -0
  140. package/dist/src/types-5aqHpBwE.cjs +3769 -0
  141. package/dist/src/types-Bn6D9c4U.js +3300 -0
  142. package/dist/src/util-BkKlTkI2.js +293 -0
  143. package/dist/src/util-CTh0bfOm.cjs +1119 -0
  144. package/dist/src/util-D17oBwo7.cjs +328 -0
  145. package/dist/src/util-DsS_-v4p.js +613 -0
  146. package/dist/src/util-DuntT1Ga.js +951 -0
  147. package/dist/src/util-aWjdCYMI.cjs +667 -0
  148. package/dist/src/utils-CisQwpjA.js +94 -0
  149. package/dist/src/utils-yWamDvmz.cjs +123 -0
  150. package/dist/tsconfig.tsbuildinfo +1 -0
  151. package/drizzle/0000_lush_hellion.sql +36 -0
  152. package/drizzle/0001_wide_calypso.sql +3 -0
  153. package/drizzle/0002_tidy_juggernaut.sql +1 -0
  154. package/drizzle/0003_lively_naoko.sql +8 -0
  155. package/drizzle/0004_minor_peter_quill.sql +19 -0
  156. package/drizzle/0005_silky_millenium_guard.sql +2 -0
  157. package/drizzle/0006_harsh_caretaker.sql +42 -0
  158. package/drizzle/0007_cloudy_wong.sql +1 -0
  159. package/drizzle/0008_broad_boomer.sql +2 -0
  160. package/drizzle/0009_strong_marten_broadcloak.sql +19 -0
  161. package/drizzle/0010_needy_bishop.sql +11 -0
  162. package/drizzle/0011_moaning_millenium_guard.sql +1 -0
  163. package/drizzle/0012_late_marten_broadcloak.sql +2 -0
  164. package/drizzle/0013_previous_dormammu.sql +9 -0
  165. package/drizzle/0014_lazy_captain_universe.sql +2 -0
  166. package/drizzle/0015_zippy_wallop.sql +29 -0
  167. package/drizzle/0016_jazzy_zemo.sql +2 -0
  168. package/drizzle/0017_reflective_praxagora.sql +4 -0
  169. package/drizzle/0018_fat_vanisher.sql +22 -0
  170. package/drizzle/0019_new_clint_barton.sql +8 -0
  171. package/drizzle/0020_skinny_maverick.sql +1 -0
  172. package/drizzle/0021_mysterious_madelyne_pryor.sql +13 -0
  173. package/drizzle/0022_sleepy_ultimo.sql +25 -0
  174. package/drizzle/0023_wooden_mandrill.sql +2 -0
  175. package/drizzle/AGENTS.md +68 -0
  176. package/drizzle/CLAUDE.md +1 -0
  177. package/drizzle/meta/0000_snapshot.json +221 -0
  178. package/drizzle/meta/0001_snapshot.json +214 -0
  179. package/drizzle/meta/0002_snapshot.json +221 -0
  180. package/drizzle/meta/0005_snapshot.json +369 -0
  181. package/drizzle/meta/0006_snapshot.json +638 -0
  182. package/drizzle/meta/0007_snapshot.json +640 -0
  183. package/drizzle/meta/0008_snapshot.json +649 -0
  184. package/drizzle/meta/0009_snapshot.json +554 -0
  185. package/drizzle/meta/0010_snapshot.json +619 -0
  186. package/drizzle/meta/0011_snapshot.json +627 -0
  187. package/drizzle/meta/0012_snapshot.json +639 -0
  188. package/drizzle/meta/0013_snapshot.json +717 -0
  189. package/drizzle/meta/0014_snapshot.json +717 -0
  190. package/drizzle/meta/0015_snapshot.json +897 -0
  191. package/drizzle/meta/0016_snapshot.json +1031 -0
  192. package/drizzle/meta/0018_snapshot.json +1210 -0
  193. package/drizzle/meta/0019_snapshot.json +1165 -0
  194. package/drizzle/meta/0020_snapshot.json +1232 -0
  195. package/drizzle/meta/0021_snapshot.json +1311 -0
  196. package/drizzle/meta/0022_snapshot.json +1481 -0
  197. package/drizzle/meta/0023_snapshot.json +1496 -0
  198. package/drizzle/meta/_journal.json +174 -0
  199. package/package.json +240 -0
@@ -0,0 +1,951 @@
1
+ import { T as state, c as sanitizeObject, r as logger, v as getEnvBool } from "./logger-C40ZGil9.js";
2
+ import { t as invariant } from "./invariant-Ddh24eXh.js";
3
+ import { o as safeResolve, r as importModule, t as getDirectory } from "./esm-DMVc93eh.js";
4
+ import { r as runPython } from "./pythonUtils-IBhn5YGR.js";
5
+ import { i as isJavascriptFile, t as JAVASCRIPT_EXTENSIONS } from "./fileExtensions-DnqA1y9x.js";
6
+ import { g as ResultFailureReason, h as OutputFileExtension } from "./types-Bn6D9c4U.js";
7
+ import { A as TERMINAL_MAX_WIDTH, M as VERSION, t as fetchWithProxy } from "./fetch-DQckpUFz.js";
8
+ import * as fs$1 from "fs";
9
+ import * as path$1 from "path";
10
+ import path from "path";
11
+ import yaml from "js-yaml";
12
+ import dotenv from "dotenv";
13
+ import * as os$1 from "os";
14
+ import dedent from "dedent";
15
+ import * as fsPromises from "fs/promises";
16
+ import { globSync, hasMagic } from "glob";
17
+ import "fast-deep-equal";
18
+ import { parse as parse$1 } from "csv-parse/sync";
19
+ import nunjucks from "nunjucks";
20
+ import { XMLBuilder } from "fast-xml-parser";
21
+ //#region src/util/provider.ts
22
+ function canonicalizeProviderId(id) {
23
+ if (id.startsWith("file://")) {
24
+ const filePath = id.slice(7);
25
+ return path$1.isAbsolute(filePath) ? id : `file://${path$1.resolve(filePath)}`;
26
+ }
27
+ for (const prefix of [
28
+ "exec:",
29
+ "python:",
30
+ "golang:"
31
+ ]) if (id.startsWith(prefix)) {
32
+ const filePath = id.slice(prefix.length);
33
+ if (filePath.includes("/") || filePath.includes("\\")) return `${prefix}${path$1.resolve(filePath)}`;
34
+ return id;
35
+ }
36
+ if ((id.endsWith(".js") || id.endsWith(".ts") || id.endsWith(".mjs")) && (id.includes("/") || id.includes("\\"))) return `file://${path$1.resolve(id)}`;
37
+ return id;
38
+ }
39
+ /**
40
+ * Gets a descriptive identifier string for a provider, showing both label and ID when both exist.
41
+ * Useful for error messages to help users debug provider reference issues.
42
+ */
43
+ function getProviderDescription(provider) {
44
+ const label = provider.label;
45
+ const id = provider.id();
46
+ if (label && label !== id) return `${label} (${id})`;
47
+ return id;
48
+ }
49
+ /**
50
+ * Checks if a provider reference matches a given provider.
51
+ * Supports exact matching and wildcard patterns.
52
+ */
53
+ function doesProviderRefMatch(ref, provider) {
54
+ const label = provider.label;
55
+ const id = provider.id();
56
+ const canonicalRef = canonicalizeProviderId(ref);
57
+ const canonicalId = canonicalizeProviderId(id);
58
+ if (label && label === ref) return true;
59
+ if (id === ref || canonicalId === canonicalRef) return true;
60
+ if (ref.endsWith("*")) {
61
+ const prefix = ref.slice(0, -1);
62
+ if (label?.startsWith(prefix) || id.startsWith(prefix) || canonicalId.startsWith(prefix)) return true;
63
+ }
64
+ if (label?.startsWith(`${ref}:`) || id.startsWith(`${ref}:`) || canonicalId.startsWith(`${ref}:`)) return true;
65
+ return false;
66
+ }
67
+ /**
68
+ * Checks if a provider is allowed based on a list of allowed references.
69
+ */
70
+ function isProviderAllowed(provider, allowedProviders) {
71
+ if (!Array.isArray(allowedProviders)) return true;
72
+ if (allowedProviders.length === 0) return false;
73
+ return allowedProviders.some((ref) => doesProviderRefMatch(ref, provider));
74
+ }
75
+ /**
76
+ * Detects if a provider uses OpenAI models.
77
+ * This includes direct OpenAI providers and Azure OpenAI.
78
+ */
79
+ function isOpenAiProvider(providerId) {
80
+ const lowerProviderId = providerId.toLowerCase();
81
+ if (lowerProviderId.startsWith("openai:")) return true;
82
+ if (lowerProviderId.startsWith("azureopenai:")) return true;
83
+ if (lowerProviderId.startsWith("azure:")) {
84
+ if ([
85
+ "gpt",
86
+ "openai",
87
+ "davinci",
88
+ "curie",
89
+ "babbage",
90
+ "ada",
91
+ "text-embedding",
92
+ "whisper",
93
+ "dall-e",
94
+ "tts"
95
+ ].some((indicator) => lowerProviderId.includes(indicator))) return true;
96
+ }
97
+ return false;
98
+ }
99
+ /**
100
+ * Detects if a provider uses Anthropic/Claude models.
101
+ * This includes direct Anthropic providers, Bedrock with Claude, and Vertex with Claude.
102
+ */
103
+ function isAnthropicProvider(providerId) {
104
+ const lowerProviderId = providerId.toLowerCase();
105
+ if (lowerProviderId.startsWith("anthropic:")) return true;
106
+ if (lowerProviderId.startsWith("bedrock:")) {
107
+ if (lowerProviderId.includes("claude") || lowerProviderId.includes("anthropic")) return true;
108
+ }
109
+ if (lowerProviderId.startsWith("vertex:")) {
110
+ if (lowerProviderId.includes("claude")) return true;
111
+ }
112
+ return false;
113
+ }
114
+ /**
115
+ * Detects if a provider uses Google models.
116
+ * This includes direct Google/Vertex providers with Gemini and other Google models.
117
+ * Note: Vertex with Claude models is NOT counted as Google (it's Anthropic).
118
+ */
119
+ function isGoogleProvider(providerId) {
120
+ const lowerProviderId = providerId.toLowerCase();
121
+ if (lowerProviderId.startsWith("google:")) return true;
122
+ if (lowerProviderId.startsWith("vertex:")) {
123
+ if (!lowerProviderId.includes("claude")) return true;
124
+ }
125
+ return false;
126
+ }
127
+ //#endregion
128
+ //#region src/util/env.ts
129
+ /**
130
+ * Load environment variables from .env file(s).
131
+ * @param envPath - Single path, array of paths, or undefined for default .env loading.
132
+ * When paths are explicitly specified, all files must exist or an error is thrown.
133
+ * When multiple files are provided, later files override values from earlier files.
134
+ */
135
+ function setupEnv(envPath) {
136
+ if (envPath) {
137
+ const paths = (Array.isArray(envPath) ? envPath : [envPath]).flatMap((p) => p.includes(",") ? p.split(",").map((s) => s.trim()) : p.trim()).filter((p) => p.length > 0);
138
+ if (paths.length === 0) {
139
+ dotenv.config({ quiet: true });
140
+ return;
141
+ }
142
+ for (const p of paths) if (!fs$1.existsSync(p)) throw new Error(`Environment file not found: ${p}`);
143
+ if (paths.length === 1) logger.info(`Loading environment variables from ${paths[0]}`);
144
+ else logger.info(`Loading environment variables from: ${paths.join(", ")}`);
145
+ const pathArg = paths.length === 1 ? paths[0] : paths;
146
+ dotenv.config({
147
+ path: pathArg,
148
+ override: true,
149
+ quiet: true
150
+ });
151
+ } else dotenv.config({ quiet: true });
152
+ }
153
+ //#endregion
154
+ //#region src/util/functions/loadFunction.ts
155
+ const functionCache = {};
156
+ /**
157
+ * Loads a function from a JavaScript or Python file
158
+ * @param options Options for loading the function
159
+ * @returns The loaded function
160
+ */
161
+ async function loadFunction({ filePath, functionName, defaultFunctionName = "func", basePath = state.basePath, useCache = true }) {
162
+ const cacheKey = `${filePath}${functionName ? `:${functionName}` : ""}`;
163
+ if (useCache && functionCache[cacheKey]) return functionCache[cacheKey];
164
+ const resolvedPath = basePath ? path.resolve(basePath, filePath) : filePath;
165
+ if (!isJavascriptFile(resolvedPath) && !resolvedPath.endsWith(".py")) throw new Error(`File must be a JavaScript (${JAVASCRIPT_EXTENSIONS.join(", ")}) or Python (.py) file`);
166
+ try {
167
+ let func;
168
+ if (isJavascriptFile(resolvedPath)) {
169
+ const module = await importModule(resolvedPath, functionName);
170
+ let moduleFunc;
171
+ if (functionName) moduleFunc = module;
172
+ else moduleFunc = typeof module === "function" ? module : module?.default?.default || module?.default || module?.[defaultFunctionName] || module;
173
+ if (typeof moduleFunc !== "function") throw new Error(functionName ? `JavaScript file must export a "${functionName}" function` : `JavaScript file must export a function (as default export or named export "${defaultFunctionName}")`);
174
+ func = moduleFunc;
175
+ } else {
176
+ const result = (...args) => runPython(resolvedPath, functionName || defaultFunctionName, args);
177
+ func = result;
178
+ }
179
+ if (useCache) functionCache[cacheKey] = func;
180
+ return func;
181
+ } catch (err) {
182
+ logger.error(`Failed to load function: ${err.message}`);
183
+ throw err;
184
+ }
185
+ }
186
+ /**
187
+ * Extracts the file path and function name from a file:// URL
188
+ * @param fileUrl The file:// URL (e.g., "file://path/to/file.js:functionName")
189
+ * @returns The file path and optional function name
190
+ */
191
+ function parseFileUrl(fileUrl) {
192
+ if (!fileUrl.startsWith("file://")) throw new Error("URL must start with file://");
193
+ const urlWithoutProtocol = fileUrl.slice(7);
194
+ const lastColonIndex = urlWithoutProtocol.lastIndexOf(":");
195
+ if (lastColonIndex > 1) return {
196
+ filePath: urlWithoutProtocol.slice(0, lastColonIndex),
197
+ functionName: urlWithoutProtocol.slice(lastColonIndex + 1)
198
+ };
199
+ return { filePath: urlWithoutProtocol };
200
+ }
201
+ //#endregion
202
+ //#region src/util/templates.ts
203
+ /**
204
+ * Get a Nunjucks engine instance with optional filters and configuration.
205
+ * @param filters - Optional map of custom Nunjucks filters.
206
+ * @param throwOnUndefined - Whether to throw an error on undefined variables.
207
+ * @param isGrader - Whether this engine is being used in a grader context.
208
+ * Nunjucks is always enabled in grader mode.
209
+ * @returns A configured Nunjucks environment.
210
+ */
211
+ function getNunjucksEngine(filters, throwOnUndefined = false, isGrader = false) {
212
+ if (!isGrader && getEnvBool("PROMPTFOO_DISABLE_TEMPLATING")) return { renderString: (template) => template };
213
+ const env = nunjucks.configure({
214
+ autoescape: false,
215
+ throwOnUndefined
216
+ });
217
+ const envGlobals = {
218
+ ...getEnvBool("PROMPTFOO_DISABLE_TEMPLATE_ENV_VARS", getEnvBool("PROMPTFOO_SELF_HOSTED", false)) ? {} : process.env,
219
+ ...state.config?.env
220
+ };
221
+ env.addGlobal("env", envGlobals);
222
+ env.addFilter("load", function(str) {
223
+ return JSON.parse(str);
224
+ });
225
+ if (filters) for (const [name, filter] of Object.entries(filters)) env.addFilter(name, filter);
226
+ return env;
227
+ }
228
+ /**
229
+ * Parse Nunjucks template to extract variables.
230
+ * @param template - The Nunjucks template string.
231
+ * @returns An array of variables used in the template.
232
+ */
233
+ function extractVariablesFromTemplate(template) {
234
+ const variableSet = /* @__PURE__ */ new Set();
235
+ const regex = /\{\{[\s]*([^{}\s|]+)[\s]*(?:\|[^}]+)?\}\}|\{%[\s]*(?:if|for)[\s]+([^{}\s]+)[\s]*.*?%\}/g;
236
+ template = template.replace(/\{#[\s\S]*?#\}/g, "");
237
+ let match;
238
+ while ((match = regex.exec(template)) !== null) {
239
+ const variable = match[1] || match[2];
240
+ if (variable) variableSet.add(variable);
241
+ }
242
+ const forLoopRegex = /\{%[\s]*for[\s]+(\w+)[\s]+in[\s]+(\w+)[\s]*%\}/g;
243
+ while ((match = forLoopRegex.exec(template)) !== null) {
244
+ variableSet.delete(match[1]);
245
+ variableSet.add(match[2]);
246
+ }
247
+ return Array.from(variableSet);
248
+ }
249
+ /**
250
+ * Extract variables from multiple Nunjucks templates.
251
+ * @param templates - An array of Nunjucks template strings.
252
+ * @returns An array of variables used in the templates.
253
+ */
254
+ function extractVariablesFromTemplates(templates) {
255
+ const variableSet = /* @__PURE__ */ new Set();
256
+ for (const template of templates) extractVariablesFromTemplate(template).forEach((variable) => variableSet.add(variable));
257
+ return Array.from(variableSet);
258
+ }
259
+ //#endregion
260
+ //#region src/util/render.ts
261
+ /**
262
+ * Renders ONLY environment variable templates in an object, leaving all other templates untouched.
263
+ * This allows env vars to be resolved at provider load time while preserving runtime var templates.
264
+ *
265
+ * Supports full Nunjucks syntax for env vars including filters and expressions:
266
+ * - {{ env.VAR_NAME }}
267
+ * - {{ env['VAR-NAME'] }}
268
+ * - {{ env["VAR-NAME"] }}
269
+ * - {{ env.VAR | default('fallback') }}
270
+ * - {{ env.VAR | upper }}
271
+ *
272
+ * Preserves non-env templates for runtime rendering:
273
+ * - {{ vars.x }} - preserved as literal
274
+ * - {{ prompt }} - preserved as literal
275
+ *
276
+ * Implementation: Uses regex to find env templates, delegates to Nunjucks for rendering.
277
+ * This ensures full Nunjucks feature support while preserving non-env templates.
278
+ *
279
+ * @param obj - The object to process
280
+ * @param envOverrides - Optional env vars to merge with (or replace) the base env
281
+ * @param replaceBase - If true, envOverrides replaces the base env entirely instead of merging
282
+ * @returns The object with only env templates rendered
283
+ */
284
+ function renderEnvOnlyInObject(obj, envOverrides, replaceBase) {
285
+ if (getEnvBool("PROMPTFOO_DISABLE_TEMPLATING")) return obj;
286
+ if (typeof obj === "string") {
287
+ const nunjucks = getNunjucksEngine();
288
+ const baseEnvGlobals = nunjucks.getGlobal("env");
289
+ const envGlobals = replaceBase ? envOverrides ?? {} : envOverrides ? {
290
+ ...baseEnvGlobals,
291
+ ...envOverrides
292
+ } : baseEnvGlobals;
293
+ return obj.replace(/\{\{(?:[^}]|\}(?!\}))*\}\}/g, (match) => {
294
+ if (!match.match(/\benv\.|env\[/)) return match;
295
+ const varMatch = match.match(/env\.(\w+)|env\[['"]([^'"]+)['"]\]/);
296
+ const varName = varMatch?.[1] || varMatch?.[2];
297
+ if (match.includes("|") || varName && varName in envGlobals && envGlobals[varName] !== void 0) try {
298
+ return nunjucks.renderString(match, { env: envGlobals });
299
+ } catch (error) {
300
+ logger.debug(`Failed to render env template "${match}": ${error instanceof Error ? error.message : String(error)}`);
301
+ return match;
302
+ }
303
+ return match;
304
+ });
305
+ }
306
+ if (Array.isArray(obj)) return obj.map((item) => renderEnvOnlyInObject(item, envOverrides, replaceBase));
307
+ if (typeof obj === "object" && obj !== null) {
308
+ const result = {};
309
+ for (const key in obj) {
310
+ if (key === "_conversation") {
311
+ result[key] = obj[key];
312
+ continue;
313
+ }
314
+ result[key] = renderEnvOnlyInObject(obj[key], envOverrides, replaceBase);
315
+ }
316
+ return result;
317
+ }
318
+ return obj;
319
+ }
320
+ function renderVarsInObject(obj, vars) {
321
+ if (!vars || getEnvBool("PROMPTFOO_DISABLE_TEMPLATING")) return obj;
322
+ if (typeof obj === "string") return getNunjucksEngine().renderString(obj, vars);
323
+ if (Array.isArray(obj)) return obj.map((item) => renderVarsInObject(item, vars));
324
+ if (typeof obj === "object" && obj !== null) {
325
+ const result = {};
326
+ for (const key in obj) result[key] = renderVarsInObject(obj[key], vars);
327
+ return result;
328
+ } else if (typeof obj === "function") return renderVarsInObject(obj({ vars }));
329
+ return obj;
330
+ }
331
+ //#endregion
332
+ //#region src/util/file.ts
333
+ /**
334
+ * Simple Nunjucks engine specifically for file paths
335
+ * This function is separate from the main getNunjucksEngine to avoid circular dependencies
336
+ */
337
+ function getNunjucksEngineForFilePath() {
338
+ const env = nunjucks.configure({ autoescape: false });
339
+ env.addGlobal("env", {
340
+ ...process.env,
341
+ ...state.config?.env
342
+ });
343
+ return env;
344
+ }
345
+ /**
346
+ * Loads content from an external file if the input is a file path, otherwise
347
+ * returns the input as-is. Supports Nunjucks templating for file paths.
348
+ *
349
+ * @param filePath - The input to process. Can be a file path string starting with "file://",
350
+ * an array of file paths, or any other type of data.
351
+ * @param context - Optional context to control file loading behavior. 'assertion' context
352
+ * preserves Python/JS file references instead of loading their content.
353
+ * @returns The loaded content if the input was a file path, otherwise the original input.
354
+ * For JSON and YAML files, the content is parsed into an object.
355
+ * For other file types, the raw file content is returned as a string.
356
+ *
357
+ * @throws {Error} If the specified file does not exist.
358
+ */
359
+ function maybeLoadFromExternalFile(filePath, context) {
360
+ if (Array.isArray(filePath)) return filePath.map((path) => {
361
+ return maybeLoadFromExternalFile(path, context);
362
+ });
363
+ if (typeof filePath !== "string") return filePath;
364
+ if (!filePath.startsWith("file://")) return filePath;
365
+ const renderedFilePath = getNunjucksEngineForFilePath().renderString(filePath, {});
366
+ const { filePath: cleanPath, functionName } = parseFileUrl(renderedFilePath);
367
+ if (context === "assertion" && (cleanPath.endsWith(".py") || isJavascriptFile(cleanPath))) {
368
+ logger.debug(`Preserving Python/JS file reference in assertion context: ${renderedFilePath}`);
369
+ return renderedFilePath;
370
+ }
371
+ if (context === "vars") {
372
+ logger.debug(`Preserving file reference in vars context: ${renderedFilePath}`);
373
+ return renderedFilePath;
374
+ }
375
+ if (functionName && (cleanPath.endsWith(".py") || isJavascriptFile(cleanPath))) return renderedFilePath;
376
+ const pathToUse = functionName && !(cleanPath.endsWith(".py") || isJavascriptFile(cleanPath)) ? renderedFilePath.slice(7) : cleanPath;
377
+ const resolvedPath = path$1.resolve(state.basePath || "", pathToUse);
378
+ if (hasMagic(pathToUse)) {
379
+ const matchedFiles = globSync(resolvedPath, { windowsPathsNoEscape: true });
380
+ if (matchedFiles.length === 0) throw new Error(`No files found matching pattern: ${resolvedPath}`);
381
+ const allContents = [];
382
+ for (const matchedFile of matchedFiles) {
383
+ let contents;
384
+ try {
385
+ contents = fs$1.readFileSync(matchedFile, "utf8");
386
+ } catch (error) {
387
+ if (error.code === "ENOENT") {
388
+ logger.debug(`File disappeared during glob expansion: ${matchedFile}`);
389
+ continue;
390
+ }
391
+ throw error;
392
+ }
393
+ if (matchedFile.endsWith(".json")) {
394
+ const parsed = JSON.parse(contents);
395
+ if (Array.isArray(parsed)) allContents.push(...parsed);
396
+ else allContents.push(parsed);
397
+ } else if (matchedFile.endsWith(".yaml") || matchedFile.endsWith(".yml")) {
398
+ const parsed = yaml.load(contents);
399
+ if (parsed === null || parsed === void 0) continue;
400
+ if (Array.isArray(parsed)) allContents.push(...parsed);
401
+ else allContents.push(parsed);
402
+ } else if (matchedFile.endsWith(".csv")) {
403
+ const records = parse$1(contents, { columns: true });
404
+ if (records.length > 0 && Object.keys(records[0]).length === 1) allContents.push(...records.map((record) => Object.values(record)[0]));
405
+ else allContents.push(...records);
406
+ } else allContents.push(contents);
407
+ }
408
+ return allContents;
409
+ }
410
+ const finalPath = resolvedPath;
411
+ let contents;
412
+ try {
413
+ contents = fs$1.readFileSync(finalPath, "utf8");
414
+ } catch (error) {
415
+ if (error.code === "ENOENT") throw new Error(`File does not exist: ${finalPath}`);
416
+ throw new Error(`Failed to read file ${finalPath}: ${error}`);
417
+ }
418
+ if (finalPath.endsWith(".json")) try {
419
+ return JSON.parse(contents);
420
+ } catch (error) {
421
+ throw new Error(`Failed to parse JSON file ${finalPath}: ${error}`);
422
+ }
423
+ if (finalPath.endsWith(".yaml") || finalPath.endsWith(".yml")) try {
424
+ return yaml.load(contents);
425
+ } catch (error) {
426
+ throw new Error(`Failed to parse YAML file ${finalPath}: ${error}`);
427
+ }
428
+ if (finalPath.endsWith(".csv")) {
429
+ const records = parse$1(contents, { columns: true });
430
+ if (records.length > 0 && Object.keys(records[0]).length === 1) return records.map((record) => Object.values(record)[0]);
431
+ return records;
432
+ }
433
+ return contents;
434
+ }
435
+ /**
436
+ * Resolves a relative file path with respect to a base path, handling cloud configuration appropriately.
437
+ * When using a cloud configuration, the current working directory is always used instead of the context's base path.
438
+ *
439
+ * @param filePath - The relative or absolute file path to resolve.
440
+ * @param isCloudConfig - Whether this is a cloud configuration.
441
+ * @returns The resolved absolute file path.
442
+ */
443
+ function getResolvedRelativePath(filePath, isCloudConfig) {
444
+ if (path$1.isAbsolute(filePath) || !isCloudConfig) return filePath;
445
+ return path$1.join(process.cwd(), filePath);
446
+ }
447
+ /**
448
+ * Recursively loads external file references from a configuration object.
449
+ *
450
+ * @param config - The configuration object to process
451
+ * @param context - Optional context to control file loading behavior
452
+ * @returns The configuration with external file references resolved
453
+ */
454
+ function maybeLoadConfigFromExternalFile(config, context) {
455
+ if (Array.isArray(config)) return config.map((item) => maybeLoadConfigFromExternalFile(item, context));
456
+ if (typeof config === "object" && config !== null) {
457
+ const result = {};
458
+ for (const key of Object.keys(config)) {
459
+ const childContext = key === "value" && "type" in config && typeof config.type === "string" && (config.type === "python" || config.type === "javascript") ? "assertion" : key === "vars" ? "vars" : context;
460
+ result[key] = maybeLoadConfigFromExternalFile(config[key], childContext);
461
+ }
462
+ return result;
463
+ }
464
+ return maybeLoadFromExternalFile(config, context);
465
+ }
466
+ /**
467
+ * Parses a file path or glob pattern to extract function names and file extensions.
468
+ * Function names can be specified in the filename like this:
469
+ * prompt.py:myFunction or prompts.js:myFunction.
470
+ * @param basePath - The base path for file resolution.
471
+ * @param promptPath - The path or glob pattern.
472
+ * @returns Parsed details including function name, file extension, and directory status.
473
+ */
474
+ function parsePathOrGlob(basePath, promptPath) {
475
+ if (promptPath.startsWith("file://")) promptPath = promptPath.slice(7);
476
+ const filePath = path$1.resolve(basePath, promptPath);
477
+ let filename = path$1.relative(basePath, filePath);
478
+ let functionName;
479
+ if (filename.includes(":")) {
480
+ const lastColonIndex = filename.lastIndexOf(":");
481
+ if (lastColonIndex > 1) {
482
+ const pathWithoutFunction = filename.slice(0, lastColonIndex);
483
+ if (isJavascriptFile(pathWithoutFunction) || pathWithoutFunction.endsWith(".py") || pathWithoutFunction.endsWith(".go") || pathWithoutFunction.endsWith(".rb")) {
484
+ functionName = filename.slice(lastColonIndex + 1);
485
+ filename = pathWithoutFunction;
486
+ }
487
+ }
488
+ }
489
+ let stats;
490
+ try {
491
+ stats = fs$1.statSync(path$1.join(basePath, filename));
492
+ } catch (err) {
493
+ if (getEnvBool("PROMPTFOO_STRICT_FILES")) throw err;
494
+ }
495
+ const normalizedFilePath = filePath.replace(/\\/g, "/");
496
+ const isPathPattern = stats?.isDirectory() || hasMagic(promptPath) || hasMagic(normalizedFilePath);
497
+ const safeFilename = path$1.relative(basePath, safeResolve(basePath, filename));
498
+ return {
499
+ extension: isPathPattern ? void 0 : path$1.parse(safeFilename).ext,
500
+ filePath: path$1.join(basePath, safeFilename),
501
+ functionName,
502
+ isPathPattern
503
+ };
504
+ }
505
+ /**
506
+ * Load custom Nunjucks filters from external files.
507
+ * Note: If a glob pattern matches multiple files, only the last file's export is used.
508
+ * Each filter name should typically resolve to a single file.
509
+ */
510
+ async function readFilters(filters, basePath = "") {
511
+ const ret = {};
512
+ for (const [name, filterPath] of Object.entries(filters)) {
513
+ const filePaths = globSync(path$1.join(basePath, filterPath), { windowsPathsNoEscape: true });
514
+ for (const filePath of filePaths) ret[name] = await importModule(path$1.resolve(filePath));
515
+ }
516
+ return ret;
517
+ }
518
+ /**
519
+ * Loads configuration from an external file with variable rendering.
520
+ * This is a convenience wrapper that combines renderVarsInObject and maybeLoadFromExternalFile.
521
+ *
522
+ * Use this for simple config fields that:
523
+ * - Need variable rendering ({{ vars.x }}, {{ env.X }})
524
+ * - May reference external files (file://path.json)
525
+ * - Don't have nested file references that need loading
526
+ *
527
+ * For fields with nested file references (like response_format.schema),
528
+ * use maybeLoadResponseFormatFromExternalFile instead.
529
+ *
530
+ * @param config - The configuration to process
531
+ * @param vars - Variables for template rendering
532
+ * @returns The processed configuration with variables rendered and files loaded
533
+ */
534
+ function maybeLoadFromExternalFileWithVars(config, vars) {
535
+ return maybeLoadFromExternalFile(renderVarsInObject(config, vars));
536
+ }
537
+ /**
538
+ * Loads response_format configuration from an external file with variable rendering.
539
+ *
540
+ * This function handles the special case where response_format may contain:
541
+ * 1. A top-level file reference (file://format.json)
542
+ * 2. A nested schema reference for json_schema type (schema: file://schema.json)
543
+ *
544
+ * Both levels need variable rendering and file loading.
545
+ *
546
+ * @param responseFormat - The response_format configuration
547
+ * @param vars - Variables for template rendering
548
+ * @returns The processed response_format with all files loaded
549
+ */
550
+ function maybeLoadResponseFormatFromExternalFile(responseFormat, vars) {
551
+ if (responseFormat === void 0 || responseFormat === null) return responseFormat;
552
+ const loaded = maybeLoadFromExternalFile(renderVarsInObject(responseFormat, vars));
553
+ if (!loaded || typeof loaded !== "object") return loaded;
554
+ if (loaded.type === "json_schema") {
555
+ const nestedSchema = loaded.schema || loaded.json_schema?.schema;
556
+ if (nestedSchema) {
557
+ const loadedSchema = maybeLoadFromExternalFile(renderVarsInObject(nestedSchema, vars));
558
+ if (loaded.schema !== void 0) return {
559
+ ...loaded,
560
+ schema: loadedSchema
561
+ };
562
+ else if (loaded.json_schema?.schema !== void 0) return {
563
+ ...loaded,
564
+ json_schema: {
565
+ ...loaded.json_schema,
566
+ schema: loadedSchema
567
+ }
568
+ };
569
+ }
570
+ }
571
+ return loaded;
572
+ }
573
+ /**
574
+ * Renders variables in a tools object and loads from external file if applicable.
575
+ * This function combines renderVarsInObject and maybeLoadFromExternalFile into a single step
576
+ * specifically for handling tools configurations.
577
+ *
578
+ * Supports loading from JSON, YAML, Python, and JavaScript files.
579
+ *
580
+ * @param tools - The tools configuration object or array to process.
581
+ * @param vars - Variables to use for rendering.
582
+ * @returns The processed tools configuration with variables rendered and content loaded from files if needed.
583
+ * @throws {Error} If the loaded tools are in an invalid format
584
+ */
585
+ async function maybeLoadToolsFromExternalFile(tools, vars) {
586
+ const rendered = renderVarsInObject(tools, vars);
587
+ if (typeof rendered === "string" && rendered.startsWith("file://")) {
588
+ const { filePath, functionName } = parseFileUrl(rendered);
589
+ if (functionName && (filePath.endsWith(".py") || isJavascriptFile(filePath))) {
590
+ const fileType = filePath.endsWith(".py") ? "Python" : "JavaScript";
591
+ logger.debug(`[maybeLoadToolsFromExternalFile] Loading tools from ${fileType} file: ${filePath}:${functionName}`);
592
+ try {
593
+ let toolDefinitions;
594
+ if (filePath.endsWith(".py")) {
595
+ const absPath = safeResolve(state.basePath || process.cwd(), filePath);
596
+ logger.debug(`[maybeLoadToolsFromExternalFile] Resolved Python path: ${absPath}`);
597
+ toolDefinitions = await runPython(absPath, functionName, []);
598
+ } else {
599
+ const absPath = safeResolve(state.basePath || process.cwd(), filePath);
600
+ logger.debug(`[maybeLoadToolsFromExternalFile] Resolved JavaScript path: ${absPath}`);
601
+ const module = await importModule(absPath);
602
+ const fn = module[functionName] || module.default?.[functionName];
603
+ if (typeof fn !== "function") {
604
+ const availableExports = Object.keys(module).filter((k) => k !== "default");
605
+ const basePath = state.basePath || process.cwd();
606
+ throw new Error(`Function "${functionName}" not found in ${filePath}. Available exports: ${availableExports.length > 0 ? availableExports.join(", ") : "(none)"}\nResolved from: ${basePath}`);
607
+ }
608
+ toolDefinitions = await Promise.resolve(fn());
609
+ }
610
+ if (!toolDefinitions || typeof toolDefinitions === "string" || typeof toolDefinitions === "number" || typeof toolDefinitions === "boolean") throw new Error(`Function "${functionName}" must return an array or object of tool definitions, but returned: ${toolDefinitions === null ? "null" : typeof toolDefinitions}`);
611
+ logger.debug(`[maybeLoadToolsFromExternalFile] Successfully loaded ${Array.isArray(toolDefinitions) ? toolDefinitions.length : "object"} tools`);
612
+ return toolDefinitions;
613
+ } catch (err) {
614
+ const errorMessage = err instanceof Error ? err.message : String(err);
615
+ const basePath = state.basePath || process.cwd();
616
+ throw new Error(`Failed to load tools from ${rendered}:\n${errorMessage}\n\nMake sure the function "${functionName}" exists and returns a valid tool definition array.\nResolved from: ${basePath}`);
617
+ }
618
+ }
619
+ if (filePath.endsWith(".py") || isJavascriptFile(filePath)) {
620
+ const ext = filePath.endsWith(".py") ? "Python" : "JavaScript";
621
+ const basePath = state.basePath || process.cwd();
622
+ throw new Error(`Cannot load tools from ${rendered}\n${ext} files require a function name. Use this format:\n tools: file://${filePath}:get_tools\n\nYour ${ext} file should export a function that returns tool definitions:\n` + (filePath.endsWith(".py") ? ` def get_tools():\n return [{"type": "function", "function": {...}}]` : ` module.exports.get_tools = () => [{ type: "function", function: {...} }];`) + `\n\nResolved from: ${basePath}`);
623
+ }
624
+ }
625
+ if (Array.isArray(rendered)) {
626
+ const results = await Promise.all(rendered.map((item) => maybeLoadToolsFromExternalFile(item, vars)));
627
+ if (results.every((r) => Array.isArray(r))) return results.flat();
628
+ return results;
629
+ }
630
+ if (typeof rendered !== "string") return rendered;
631
+ const loaded = maybeLoadFromExternalFile(rendered);
632
+ if (loaded !== void 0 && loaded !== null && typeof loaded === "string") {
633
+ if (loaded.startsWith("file://")) throw new Error(`Failed to load tools from ${loaded}\nEnsure the file exists and contains valid JSON or YAML tool definitions.`);
634
+ if (loaded.includes("def ") || loaded.includes("import ")) throw new Error("Invalid tools configuration: file appears to contain Python code.\nPython files require a function name. Use this format:\n tools: file://tools.py:get_tools");
635
+ throw new Error("Invalid tools configuration: expected an array or object, but got a string.\nIf using file://, ensure the file contains valid JSON or YAML tool definitions.");
636
+ }
637
+ return loaded;
638
+ }
639
+ //#endregion
640
+ //#region src/googleSheets.ts
641
+ async function checkGoogleSheetAccess(url) {
642
+ try {
643
+ const response = await fetchWithProxy(url);
644
+ if (response.ok) return {
645
+ public: true,
646
+ status: response.status
647
+ };
648
+ else return {
649
+ public: false,
650
+ status: response.status
651
+ };
652
+ } catch (error) {
653
+ logger.error(`Error checking sheet access: ${error}`);
654
+ return { public: false };
655
+ }
656
+ }
657
+ async function fetchCsvFromGoogleSheetUnauthenticated(url) {
658
+ const { parse: parseCsv } = await import("csv-parse/sync");
659
+ const gid = new URL(url).searchParams.get("gid");
660
+ const response = await fetchWithProxy(`${url.replace(/\/edit.*$/, "/export")}?format=csv${gid ? `&gid=${gid}` : ""}`);
661
+ if (response.status !== 200) throw new Error(`Failed to fetch CSV from Google Sheets URL: ${url}`);
662
+ return parseCsv(await response.text(), { columns: true });
663
+ }
664
+ async function fetchCsvFromGoogleSheetAuthenticated(url) {
665
+ const { sheets: googleSheets, auth: googleAuth } = await import("@googleapis/sheets");
666
+ const auth = new googleAuth.GoogleAuth({ scopes: ["https://www.googleapis.com/auth/spreadsheets.readonly"] });
667
+ const sheets = googleSheets("v4");
668
+ const match = url.match(/\/d\/([^/]+)/);
669
+ if (!match) throw new Error(`Invalid Google Sheets URL: ${url}`);
670
+ const spreadsheetId = match[1];
671
+ let range;
672
+ const gid = Number(new URL(url).searchParams.get("gid"));
673
+ if (gid) {
674
+ const sheet = (await sheets.spreadsheets.get({
675
+ spreadsheetId,
676
+ auth
677
+ })).data.sheets?.find((sheet) => sheet.properties?.sheetId === gid);
678
+ if (!sheet || !sheet.properties?.title) throw new Error(`Sheet not found for gid: ${gid}`);
679
+ range = sheet.properties.title;
680
+ } else {
681
+ const firstSheet = (await sheets.spreadsheets.get({
682
+ spreadsheetId,
683
+ auth
684
+ })).data.sheets?.[0];
685
+ if (!firstSheet || !firstSheet.properties?.title) throw new Error(`No sheets found in spreadsheet`);
686
+ range = firstSheet.properties.title;
687
+ }
688
+ const rows = (await sheets.spreadsheets.values.get({
689
+ spreadsheetId,
690
+ range,
691
+ auth
692
+ })).data.values;
693
+ if (!rows?.length) throw new Error(`No data found in Google Sheets URL: ${url}`);
694
+ const headers = rows[0];
695
+ return rows.slice(1).map((row) => {
696
+ const csvRow = {};
697
+ headers.forEach((header, index) => {
698
+ csvRow[header] = row[index] ?? "";
699
+ });
700
+ return csvRow;
701
+ });
702
+ }
703
+ async function fetchCsvFromGoogleSheet(url) {
704
+ const { public: isPublic } = await checkGoogleSheetAccess(url);
705
+ logger.debug(`Google Sheets URL: ${url}, isPublic: ${isPublic}`);
706
+ if (isPublic) return fetchCsvFromGoogleSheetUnauthenticated(url);
707
+ return fetchCsvFromGoogleSheetAuthenticated(url);
708
+ }
709
+ async function writeCsvToGoogleSheet(rows, url) {
710
+ const { sheets: googleSheets, auth: googleAuth } = await import("@googleapis/sheets");
711
+ const auth = new googleAuth.GoogleAuth({ scopes: ["https://www.googleapis.com/auth/spreadsheets"] });
712
+ const sheets = googleSheets("v4");
713
+ const match = url.match(/\/d\/([^/]+)/);
714
+ if (!match) throw new Error(`Invalid Google Sheets URL: ${url}`);
715
+ const spreadsheetId = match[1];
716
+ const headers = Object.keys(rows[0]);
717
+ const values = [headers, ...rows.map((row) => headers.map((header) => row[header]))];
718
+ const getColumnLetter = (col) => {
719
+ let letter = "";
720
+ while (col > 0) {
721
+ col--;
722
+ letter = String.fromCharCode(65 + col % 26) + letter;
723
+ col = Math.floor(col / 26);
724
+ }
725
+ return letter;
726
+ };
727
+ const numRows = values.length;
728
+ const numCols = headers.length;
729
+ const endColumn = getColumnLetter(numCols);
730
+ let range;
731
+ const gid = Number(new URL(url).searchParams.get("gid"));
732
+ if (gid) {
733
+ const sheet = (await sheets.spreadsheets.get({
734
+ spreadsheetId,
735
+ auth
736
+ })).data.sheets?.find((sheet) => sheet.properties?.sheetId === gid);
737
+ if (!sheet || !sheet.properties?.title) throw new Error(`Sheet not found for gid: ${gid}`);
738
+ range = `${sheet.properties.title}!A1:${endColumn}${numRows}`;
739
+ } else {
740
+ const newSheetTitle = `Sheet${Date.now()}`;
741
+ await sheets.spreadsheets.batchUpdate({
742
+ spreadsheetId,
743
+ auth,
744
+ requestBody: { requests: [{ addSheet: { properties: { title: newSheetTitle } } }] }
745
+ });
746
+ range = `${newSheetTitle}!A1:${endColumn}${numRows}`;
747
+ }
748
+ logger.debug(`Writing CSV to Google Sheets URL: ${url} with ${values.length} rows`);
749
+ await sheets.spreadsheets.values.update({
750
+ spreadsheetId,
751
+ range,
752
+ valueInputOption: "USER_ENTERED",
753
+ auth,
754
+ requestBody: { values }
755
+ });
756
+ }
757
+ //#endregion
758
+ //#region src/util/evalCsv.ts
759
+ async function streamEvalCsv(evalRecord, options) {
760
+ const table = await evalRecord.getTable();
761
+ if (!table) return;
762
+ const escapeCsv = (val) => {
763
+ const str = String(val ?? "");
764
+ if (str.includes(",") || str.includes("\"") || str.includes("\n")) return `"${str.replace(/"/g, "\"\"")}"`;
765
+ return str;
766
+ };
767
+ const headers = [...table.head.vars, ...table.head.prompts.map((p) => `[${p.provider}] ${p.label}`)];
768
+ await options.write(headers.map(escapeCsv).join(",") + "\n");
769
+ for (const row of table.body) {
770
+ const outputTexts = row.outputs.map((o) => {
771
+ return `[${o.pass ? "PASS" : "FAIL"}] ${o.text}`;
772
+ });
773
+ const cells = [...row.vars, ...outputTexts];
774
+ await options.write(cells.map(escapeCsv).join(",") + "\n");
775
+ }
776
+ }
777
+ //#endregion
778
+ //#region src/util/output.ts
779
+ const outputToSimpleString = (output) => {
780
+ const passFailText = output.pass ? "[PASS]" : output.failureReason === ResultFailureReason.ASSERT ? "[FAIL]" : "[ERROR]";
781
+ const namedScoresText = Object.entries(output.namedScores).map(([name, value]) => `${name}: ${value?.toFixed(2)}`).join(", ");
782
+ const scoreText = namedScoresText.length > 0 ? `(${output.score?.toFixed(2)}, ${namedScoresText})` : `(${output.score?.toFixed(2)})`;
783
+ const gradingResultText = output.gradingResult ? `${output.pass ? "Pass" : "Fail"} Reason: ${output.gradingResult.reason}` : "";
784
+ return dedent`
785
+ ${passFailText} ${scoreText}
786
+
787
+ ${output.text}
788
+
789
+ ${gradingResultText}
790
+ `.trim();
791
+ };
792
+ function sanitizeConfigForOutput(config) {
793
+ return sanitizeObject(config, {
794
+ context: "output config",
795
+ throwOnError: true,
796
+ maxDepth: Number.POSITIVE_INFINITY
797
+ });
798
+ }
799
+ function createOutputMetadata(evalRecord) {
800
+ let evaluationCreatedAt;
801
+ if (evalRecord.createdAt) try {
802
+ const date = new Date(evalRecord.createdAt);
803
+ evaluationCreatedAt = Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
804
+ } catch {
805
+ evaluationCreatedAt = void 0;
806
+ }
807
+ return {
808
+ promptfooVersion: VERSION,
809
+ nodeVersion: process.version,
810
+ platform: os$1.platform(),
811
+ arch: os$1.arch(),
812
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
813
+ evaluationCreatedAt,
814
+ author: evalRecord.author
815
+ };
816
+ }
817
+ /**
818
+ * JSON writer with improved error handling for large datasets.
819
+ * Provides helpful error messages when memory limits are exceeded.
820
+ */
821
+ async function writeJsonOutputSafely(outputPath, evalRecord, shareableUrl) {
822
+ const metadata = createOutputMetadata(evalRecord);
823
+ try {
824
+ const summary = await evalRecord.toEvaluateSummary();
825
+ const redactedConfig = sanitizeConfigForOutput(evalRecord.config);
826
+ const outputData = {
827
+ evalId: evalRecord.id,
828
+ results: summary,
829
+ config: redactedConfig,
830
+ shareableUrl,
831
+ metadata
832
+ };
833
+ const jsonString = JSON.stringify(outputData, null, 2);
834
+ await fsPromises.writeFile(outputPath, jsonString);
835
+ } catch (error) {
836
+ const msg = error?.message ?? "";
837
+ const isStringLen = error instanceof RangeError && msg.includes("Invalid string length");
838
+ const isHeapOOM = /heap out of memory|Array buffer allocation failed|ERR_STRING_TOO_LONG/i.test(msg);
839
+ if (isStringLen || isHeapOOM) {
840
+ const resultCount = await evalRecord.getResultsCount();
841
+ logger.error(`Dataset too large for JSON export (${resultCount} results).`);
842
+ throw new Error(`Dataset too large for JSON export. The evaluation has ${resultCount} results which exceeds memory limits. Consider using JSONL format instead: --output output.jsonl`);
843
+ } else throw error;
844
+ }
845
+ }
846
+ async function writeOutput(outputPath, evalRecord, shareableUrl) {
847
+ if (outputPath.match(/^https:\/\/docs\.google\.com\/spreadsheets\//)) {
848
+ const table = await evalRecord.getTable();
849
+ invariant(table, "Table is required");
850
+ const rows = table.body.map((row) => {
851
+ const csvRow = {};
852
+ table.head.vars.forEach((varName, index) => {
853
+ csvRow[varName] = row.vars[index];
854
+ });
855
+ table.head.prompts.forEach((prompt, index) => {
856
+ csvRow[`[${prompt.provider}] ${prompt.label}`] = outputToSimpleString(row.outputs[index]);
857
+ });
858
+ return csvRow;
859
+ });
860
+ logger.info(`Writing ${rows.length} rows to Google Sheets...`);
861
+ await writeCsvToGoogleSheet(rows, outputPath);
862
+ return;
863
+ }
864
+ const { data: outputExtension } = OutputFileExtension.safeParse(path$1.extname(outputPath).slice(1).toLowerCase());
865
+ invariant(outputExtension, `Unsupported output file format ${outputExtension}. Please use one of: ${OutputFileExtension.options.join(", ")}.`);
866
+ const outputDir = path$1.dirname(outputPath);
867
+ await fsPromises.mkdir(outputDir, { recursive: true });
868
+ const metadata = createOutputMetadata(evalRecord);
869
+ if (outputExtension === "csv") {
870
+ const fileHandle = await fsPromises.open(outputPath, "w");
871
+ try {
872
+ await streamEvalCsv(evalRecord, {
873
+ isRedteam: Boolean(evalRecord.config.redteam),
874
+ write: async (data) => {
875
+ await fileHandle.write(data);
876
+ }
877
+ });
878
+ } finally {
879
+ await fileHandle.close();
880
+ }
881
+ } else if (outputExtension === "json") await writeJsonOutputSafely(outputPath, evalRecord, shareableUrl);
882
+ else if (outputExtension === "yaml" || outputExtension === "yml" || outputExtension === "txt") {
883
+ const summary = await evalRecord.toEvaluateSummary();
884
+ const redactedConfig = sanitizeConfigForOutput(evalRecord.config);
885
+ await fsPromises.writeFile(outputPath, yaml.dump({
886
+ evalId: evalRecord.id,
887
+ results: summary,
888
+ config: redactedConfig,
889
+ shareableUrl,
890
+ metadata
891
+ }));
892
+ } else if (outputExtension === "html") {
893
+ const table = await evalRecord.getTable();
894
+ invariant(table, "Table is required");
895
+ const summary = await evalRecord.toEvaluateSummary();
896
+ const redactedConfig = sanitizeConfigForOutput(evalRecord.config);
897
+ const template = await fsPromises.readFile(path$1.join(getDirectory(), "tableOutput.html"), "utf-8");
898
+ const htmlTable = [[...table.head.vars, ...table.head.prompts.map((prompt) => `[${prompt.provider}] ${prompt.label}`)], ...table.body.map((row) => [...row.vars, ...row.outputs.map(outputToSimpleString)])];
899
+ const htmlOutput = getNunjucksEngine().renderString(template, {
900
+ config: redactedConfig,
901
+ table: htmlTable,
902
+ results: summary
903
+ });
904
+ await fsPromises.writeFile(outputPath, htmlOutput);
905
+ } else if (outputExtension === "jsonl") {
906
+ await fsPromises.writeFile(outputPath, "");
907
+ for await (const batchResults of evalRecord.fetchResultsBatched()) {
908
+ const text = batchResults.map((result) => JSON.stringify(result)).join(os$1.EOL) + os$1.EOL;
909
+ await fsPromises.appendFile(outputPath, text);
910
+ }
911
+ } else if (outputExtension === "xml") {
912
+ const summary = await evalRecord.toEvaluateSummary();
913
+ const redactedConfig = sanitizeConfigForOutput(evalRecord.config);
914
+ const sanitizeForXml = (obj) => {
915
+ if (obj === null || obj === void 0) return "";
916
+ if (typeof obj === "boolean" || typeof obj === "number") return String(obj);
917
+ if (typeof obj === "string") return obj;
918
+ if (Array.isArray(obj)) return obj.map(sanitizeForXml);
919
+ if (typeof obj === "object") {
920
+ const sanitized = {};
921
+ for (const [key, value] of Object.entries(obj)) sanitized[key] = sanitizeForXml(value);
922
+ return sanitized;
923
+ }
924
+ return String(obj);
925
+ };
926
+ const xmlData = new XMLBuilder({
927
+ ignoreAttributes: false,
928
+ format: true,
929
+ indentBy: " "
930
+ }).build({ promptfoo: {
931
+ evalId: evalRecord.id,
932
+ results: sanitizeForXml(summary),
933
+ config: sanitizeForXml(redactedConfig),
934
+ shareableUrl: shareableUrl || ""
935
+ } });
936
+ await fsPromises.writeFile(outputPath, xmlData);
937
+ }
938
+ }
939
+ async function writeMultipleOutputs(outputPaths, evalRecord, shareableUrl) {
940
+ await Promise.all(outputPaths.map((outputPath) => writeOutput(outputPath, evalRecord, shareableUrl)));
941
+ }
942
+ //#endregion
943
+ //#region src/util/runtime.ts
944
+ function printBorder() {
945
+ const border = "=".repeat(TERMINAL_MAX_WIDTH);
946
+ logger.info(border);
947
+ }
948
+ //#endregion
949
+ export { getProviderDescription as C, isProviderAllowed as D, isOpenAiProvider as E, doesProviderRefMatch as S, isGoogleProvider as T, extractVariablesFromTemplates as _, getNunjucksEngineForFilePath as a, parseFileUrl as b, maybeLoadFromExternalFile as c, maybeLoadToolsFromExternalFile as d, parsePathOrGlob as f, extractVariablesFromTemplate as g, renderVarsInObject as h, fetchCsvFromGoogleSheet as i, maybeLoadFromExternalFileWithVars as l, renderEnvOnlyInObject as m, writeMultipleOutputs as n, getResolvedRelativePath as o, readFilters as p, writeOutput as r, maybeLoadConfigFromExternalFile as s, printBorder as t, maybeLoadResponseFormatFromExternalFile as u, getNunjucksEngine as v, isAnthropicProvider as w, setupEnv as x, loadFunction as y };
950
+
951
+ //# sourceMappingURL=util-DuntT1Ga.js.map