langwatch 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/dist/{add-4WXEWG5H.js → add-CGTO6GC2.js} +28 -32
- package/dist/add-CGTO6GC2.js.map +1 -0
- package/dist/{add-D2WVVKIP.mjs → add-XCI65PVN.mjs} +14 -18
- package/dist/add-XCI65PVN.mjs.map +1 -0
- package/dist/{chunk-P4SQTYGN.js → chunk-2GYC6KEA.js} +32 -32
- package/dist/{chunk-P4SQTYGN.js.map → chunk-2GYC6KEA.js.map} +1 -1
- package/dist/{chunk-CAZONSXV.js → chunk-36XAYVMC.js} +186 -76
- package/dist/chunk-36XAYVMC.js.map +1 -0
- package/dist/{chunk-ZIULPOMQ.mjs → chunk-3P4ROGZJ.mjs} +4 -4
- package/dist/{chunk-DLJO7AK5.mjs → chunk-AD7QRYIJ.mjs} +2 -2
- package/dist/{chunk-DISMHYXC.js → chunk-CKIZDPIJ.js} +24 -22
- package/dist/chunk-CKIZDPIJ.js.map +1 -0
- package/dist/{chunk-7OZKH5K2.js → chunk-DZH6SY3Z.js} +10 -10
- package/dist/{chunk-7OZKH5K2.js.map → chunk-DZH6SY3Z.js.map} +1 -1
- package/dist/{chunk-N2V6J3U2.mjs → chunk-FEL5FLHA.mjs} +2 -2
- package/dist/{chunk-H5PON53W.mjs → chunk-GAFUPYJ3.mjs} +334 -143
- package/dist/chunk-GAFUPYJ3.mjs.map +1 -0
- package/dist/{chunk-SVXNUWZI.js → chunk-HVW45GST.js} +345 -154
- package/dist/chunk-HVW45GST.js.map +1 -0
- package/dist/{chunk-YNQ44U6D.mjs → chunk-I2SOBPAF.mjs} +23 -21
- package/dist/chunk-I2SOBPAF.mjs.map +1 -0
- package/dist/{chunk-ECOC36EA.js → chunk-J7B7BNDN.js} +11 -11
- package/dist/{chunk-ECOC36EA.js.map → chunk-J7B7BNDN.js.map} +1 -1
- package/dist/{chunk-QZGTM76F.mjs → chunk-JPWKINZP.mjs} +2 -2
- package/dist/{chunk-OXBO24RB.js → chunk-OHM7JUMR.js} +15 -2
- package/dist/chunk-OHM7JUMR.js.map +1 -0
- package/dist/chunk-PYVDTUA6.mjs +352 -0
- package/dist/chunk-PYVDTUA6.mjs.map +1 -0
- package/dist/{chunk-YH5TIVK2.js → chunk-SNDTNU3T.js} +2 -2
- package/dist/{chunk-YH5TIVK2.js.map → chunk-SNDTNU3T.js.map} +1 -1
- package/dist/{chunk-CU3443HD.mjs → chunk-URTD2WOC.mjs} +14 -1
- package/dist/{chunk-YKFTFYKK.mjs → chunk-WOBPYIKO.mjs} +2 -2
- package/dist/chunk-WOBPYIKO.mjs.map +1 -0
- package/dist/{chunk-QCYYSMCU.js → chunk-Z3NTWVVA.js} +2 -2
- package/dist/chunk-Z3NTWVVA.js.map +1 -0
- package/dist/cli/index.js +8 -8
- package/dist/cli/index.mjs +8 -8
- package/dist/{create-OQEMO4MU.mjs → create-LXQB4EFB.mjs} +4 -5
- package/dist/{create-OQEMO4MU.mjs.map → create-LXQB4EFB.mjs.map} +1 -1
- package/dist/{create-4LG4N2A4.js → create-S5RDGF3H.js} +9 -10
- package/dist/create-S5RDGF3H.js.map +1 -0
- package/dist/{implementation-BIlL6-SW.d.ts → implementation-DsHp9FYU.d.ts} +1 -1
- package/dist/{implementation-fAgqv8OM.d.mts → implementation-nE9dgTwc.d.mts} +1 -1
- package/dist/{index-DTEZr0Jn.d.mts → index-D7rKIGrO.d.mts} +12 -12
- package/dist/{index-DTEZr0Jn.d.ts → index-D7rKIGrO.d.ts} +12 -12
- package/dist/index.d.mts +256 -11
- package/dist/index.d.ts +256 -11
- package/dist/index.js +135 -12
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +133 -10
- package/dist/index.mjs.map +1 -1
- package/dist/{init-MQXXHCNT.mjs → init-T4YDPHBA.mjs} +4 -5
- package/dist/{init-MQXXHCNT.mjs.map → init-T4YDPHBA.mjs.map} +1 -1
- package/dist/init-UADBKUJU.js +15 -0
- package/dist/init-UADBKUJU.js.map +1 -0
- package/dist/{list-GIAXAAH5.js → list-GRKVAGJS.js} +14 -15
- package/dist/list-GRKVAGJS.js.map +1 -0
- package/dist/{list-PFWV7IU6.mjs → list-XHXVFN24.mjs} +13 -14
- package/dist/list-XHXVFN24.mjs.map +1 -0
- package/dist/{login-3STX2FAO.js → login-4GWM5I6F.js} +4 -4
- package/dist/{login-3STX2FAO.js.map → login-4GWM5I6F.js.map} +1 -1
- package/dist/{login-BYLXS23I.mjs → login-EKE7SFN3.mjs} +3 -3
- package/dist/observability-sdk/index.d.mts +4 -3
- package/dist/observability-sdk/index.d.ts +4 -3
- package/dist/observability-sdk/index.js +7 -7
- package/dist/observability-sdk/index.mjs +6 -6
- package/dist/observability-sdk/instrumentation/langchain/index.d.mts +2 -1
- package/dist/observability-sdk/instrumentation/langchain/index.d.ts +2 -1
- package/dist/observability-sdk/instrumentation/langchain/index.js +19 -19
- package/dist/observability-sdk/instrumentation/langchain/index.mjs +3 -3
- package/dist/observability-sdk/setup/node/index.d.mts +1 -1
- package/dist/observability-sdk/setup/node/index.d.ts +1 -1
- package/dist/observability-sdk/setup/node/index.js +15 -15
- package/dist/observability-sdk/setup/node/index.mjs +4 -4
- package/dist/{remove-U3PILQDV.js → remove-7EXB2Z6R.js} +17 -18
- package/dist/remove-7EXB2Z6R.js.map +1 -0
- package/dist/{remove-FTF3EBYV.mjs → remove-W44FQ5MF.mjs} +9 -10
- package/dist/{remove-FTF3EBYV.mjs.map → remove-W44FQ5MF.mjs.map} +1 -1
- package/dist/{sync-T3T22GVZ.js → sync-V7WRMNJV.js} +31 -35
- package/dist/sync-V7WRMNJV.js.map +1 -0
- package/dist/{sync-FOW7DHAH.mjs → sync-XGFABFAW.mjs} +16 -20
- package/dist/sync-XGFABFAW.mjs.map +1 -0
- package/dist/{types-DyUmlaDx.d.ts → types-B9772cUR.d.ts} +98 -29
- package/dist/{types-jrEEZt9d.d.mts → types-DbPAi4US.d.mts} +98 -29
- package/package.json +4 -3
- package/dist/add-4WXEWG5H.js.map +0 -1
- package/dist/add-D2WVVKIP.mjs.map +0 -1
- package/dist/chunk-CAZONSXV.js.map +0 -1
- package/dist/chunk-CKVDNVFL.mjs +0 -242
- package/dist/chunk-CKVDNVFL.mjs.map +0 -1
- package/dist/chunk-DISMHYXC.js.map +0 -1
- package/dist/chunk-DSIQSULK.js +0 -152
- package/dist/chunk-DSIQSULK.js.map +0 -1
- package/dist/chunk-H5PON53W.mjs.map +0 -1
- package/dist/chunk-OXBO24RB.js.map +0 -1
- package/dist/chunk-QCYYSMCU.js.map +0 -1
- package/dist/chunk-R6FBJN7K.js +0 -115
- package/dist/chunk-R6FBJN7K.js.map +0 -1
- package/dist/chunk-SVXNUWZI.js.map +0 -1
- package/dist/chunk-V5M3HUBV.mjs +0 -115
- package/dist/chunk-V5M3HUBV.mjs.map +0 -1
- package/dist/chunk-YEGQXDTE.mjs +0 -152
- package/dist/chunk-YEGQXDTE.mjs.map +0 -1
- package/dist/chunk-YKFTFYKK.mjs.map +0 -1
- package/dist/chunk-YNQ44U6D.mjs.map +0 -1
- package/dist/create-4LG4N2A4.js.map +0 -1
- package/dist/init-EKNL2SQE.js +0 -16
- package/dist/init-EKNL2SQE.js.map +0 -1
- package/dist/list-GIAXAAH5.js.map +0 -1
- package/dist/list-PFWV7IU6.mjs.map +0 -1
- package/dist/remove-U3PILQDV.js.map +0 -1
- package/dist/sync-FOW7DHAH.mjs.map +0 -1
- package/dist/sync-T3T22GVZ.js.map +0 -1
- /package/dist/{chunk-ZIULPOMQ.mjs.map → chunk-3P4ROGZJ.mjs.map} +0 -0
- /package/dist/{chunk-DLJO7AK5.mjs.map → chunk-AD7QRYIJ.mjs.map} +0 -0
- /package/dist/{chunk-N2V6J3U2.mjs.map → chunk-FEL5FLHA.mjs.map} +0 -0
- /package/dist/{chunk-QZGTM76F.mjs.map → chunk-JPWKINZP.mjs.map} +0 -0
- /package/dist/{chunk-CU3443HD.mjs.map → chunk-URTD2WOC.mjs.map} +0 -0
- /package/dist/{login-BYLXS23I.mjs.map → login-EKE7SFN3.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/commands/sync.ts"],"sourcesContent":["import * as fs from \"fs\";\nimport * as path from \"path\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport * as yaml from \"js-yaml\";\nimport { PromptConverter } from \"@/cli/utils/promptConverter\";\nimport {\n type ConfigData,\n Prompt,\n PromptsApiService,\n PromptsError,\n type SyncAction,\n} from \"@/client-sdk/services/prompts\";\nimport type { SyncResult } from \"../types\";\nimport { FileManager } from \"../utils/fileManager\";\nimport { ensureProjectInitialized } from \"../utils/init\";\nimport { checkApiKey } from \"../utils/apiKey\";\nimport readline from \"node:readline\";\n\n// Handle conflict resolution - show diff and ask user to choose\nconst handleConflict = async (\n promptName: string,\n conflictInfo: {\n localVersion: number;\n remoteVersion: number;\n differences: string[];\n remoteConfigData: any;\n }\n): Promise<\"local\" | \"remote\" | \"abort\"> => {\n console.log(\n chalk.yellow(`\\n⚠ Conflict detected for prompt: ${chalk.cyan(promptName)}`)\n );\n console.log(\n chalk.gray(\n `Local version: ${conflictInfo.localVersion}, Remote version: ${conflictInfo.remoteVersion}`\n )\n );\n\n if (conflictInfo.differences.length > 0) {\n console.log(chalk.yellow(\"\\nDifferences:\"));\n conflictInfo.differences.forEach((diff) => {\n console.log(chalk.gray(` • ${diff}`));\n });\n }\n\n console.log(chalk.yellow(\"\\nOptions:\"));\n console.log(\" [l] Use local version (overwrite remote)\");\n console.log(\" [r] Use remote version (overwrite local)\");\n console.log(\" [a] Abort sync for this prompt\");\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\"Choose resolution (l/r/a): \", (answer: string) => {\n rl.close();\n const choice = answer.toLowerCase();\n if (choice === \"l\" || choice === \"local\") {\n resolve(\"local\");\n } else if (choice === \"r\" || choice === \"remote\") {\n resolve(\"remote\");\n } else {\n resolve(\"abort\");\n }\n });\n });\n};\n\nexport const syncCommand = async (): Promise<void> => {\n console.log(\"🔄 Starting sync...\");\n\n const startTime = Date.now();\n\n try {\n // Check API key before doing anything else\n checkApiKey();\n\n // Get prompts API service\n const promptsApiService = new PromptsApiService();\n\n // Ensure project is initialized (prompts.json, lock file, directories)\n await ensureProjectInitialized(false); // Don't prompt for .gitignore in sync\n\n // Load prompts config and lock\n const config = FileManager.loadPromptsConfig();\n const lock = FileManager.loadPromptsLock();\n\n const result: SyncResult = {\n fetched: [],\n pushed: [],\n unchanged: [],\n cleaned: [],\n errors: [],\n };\n\n // Process remote prompts (fetch and materialize)\n const remoteDeps = Object.entries(config.prompts).filter(\n ([, dependency]) => {\n // Skip local file dependencies (both object format and string format)\n if (typeof dependency === \"object\" && dependency.file) {\n return false;\n }\n if (typeof dependency === \"string\" && dependency.startsWith(\"file:\")) {\n return false;\n }\n return true;\n }\n );\n\n if (remoteDeps.length > 0) {\n const fetchSpinner = ora(\n `Checking ${remoteDeps.length} remote prompts...`\n ).start();\n\n for (const [name, dependency] of remoteDeps) {\n try {\n const versionSpec =\n typeof dependency === \"string\"\n ? dependency\n : dependency.version ?? \"latest\";\n\n // Check if we already have this prompt with the same version\n const lockEntry = lock.prompts[name];\n\n // Fetch the prompt from the API to check current version\n const prompt = await promptsApiService.get(name);\n\n if (prompt) {\n // Check if we need to update (new version or not materialized)\n const needsUpdate =\n !lockEntry ||\n lockEntry.version !== prompt.version ||\n !lockEntry.materialized ||\n !fs.existsSync(path.resolve(lockEntry.materialized));\n\n if (needsUpdate) {\n // Convert to MaterializedPrompt format using the converter\n const materializedPrompt =\n PromptConverter.fromApiToMaterialized(prompt);\n\n const savedPath = FileManager.saveMaterializedPrompt(\n name,\n materializedPrompt\n );\n const relativePath = path.relative(process.cwd(), savedPath);\n result.fetched.push({\n name,\n version: prompt.version,\n versionSpec,\n });\n\n // Update lock file entry\n FileManager.updateLockEntry(\n lock,\n name,\n materializedPrompt,\n savedPath\n );\n\n fetchSpinner.text = `Fetched ${chalk.cyan(\n `${name}@${versionSpec}`\n )} ${chalk.gray(`(version ${prompt.version})`)} → ${chalk.gray(\n relativePath\n )}`;\n } else {\n // No change needed, track as unchanged\n result.unchanged.push(name);\n }\n } else {\n result.errors.push({ name, error: \"Prompt not found\" });\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n result.errors.push({ name, error: errorMessage });\n }\n }\n\n fetchSpinner.stop();\n }\n\n // Process local prompts (push to API) - only those explicitly declared in prompts.json\n const localFileRefs = Object.entries(config.prompts).filter(\n ([, dependency]) => {\n return typeof dependency === \"string\" && dependency.startsWith(\"file:\");\n }\n );\n\n if (localFileRefs.length > 0) {\n const pushSpinner = ora(\n `Pushing ${localFileRefs.length} local prompts...`\n ).start();\n\n // Use the existing lock file instead of reloading it\n // const lock = FileManager.loadPromptsLock(); // Don't reload - use existing lock\n\n for (const [promptName, dependency] of localFileRefs) {\n try {\n const filePath = (dependency as string).slice(5); // Remove \"file:\" prefix\n\n // Load local prompt config\n const localConfig = FileManager.loadLocalPrompt(filePath);\n\n // Get current version from lock file\n const currentVersion = lock.prompts[promptName]?.version;\n\n // Convert local config to API configData format\n const configData: ConfigData = {\n model: localConfig.model,\n prompt: PromptConverter.extractSystemPrompt(localConfig.messages),\n messages: PromptConverter.filterNonSystemMessages(\n localConfig.messages\n ) as Array<{\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }>,\n temperature: localConfig.modelParameters?.temperature,\n max_tokens: localConfig.modelParameters?.max_tokens,\n inputs: [{ identifier: \"input\", type: \"str\" }],\n outputs: [{ identifier: \"output\", type: \"str\" }],\n };\n\n // Use new sync API with conflict detection\n const syncResult = await promptsApiService.sync({\n name: promptName,\n configData,\n localVersion: currentVersion,\n commitMessage: `Synced from local file: ${path.basename(filePath)}`,\n });\n\n const relativePath = path.relative(process.cwd(), filePath);\n\n let conflictResolution: \"local\" | \"remote\" | \"abort\" | null = null;\n if (syncResult.action === \"conflict\") {\n // Handle conflict - prompt user for resolution\n pushSpinner.stop();\n conflictResolution = await handleConflict(\n promptName,\n syncResult.conflictInfo!\n );\n if (conflictResolution === \"abort\") {\n result.errors.push({\n name: promptName,\n error: \"Sync aborted due to conflict\",\n });\n continue;\n }\n\n // If user chose remote, we should pull the remote version to local file\n if (conflictResolution === \"remote\" && syncResult.conflictInfo) {\n // Update local file with remote content\n const remoteConfig = {\n model: syncResult.conflictInfo.remoteConfigData.model,\n modelParameters: {\n temperature:\n syncResult.conflictInfo.remoteConfigData.temperature,\n max_tokens:\n syncResult.conflictInfo.remoteConfigData.max_tokens,\n },\n messages: [\n {\n role: \"system\" as const,\n content: syncResult.conflictInfo.remoteConfigData.prompt,\n },\n ...(syncResult.conflictInfo.remoteConfigData.messages ?? []),\n ],\n };\n\n const yamlContent = yaml.dump(remoteConfig, {\n lineWidth: -1,\n noRefs: true,\n sortKeys: false,\n });\n\n fs.writeFileSync(filePath, yamlContent);\n }\n\n // If user chose to proceed, we continue with the sync\n pushSpinner.start();\n }\n\n // Update lock file with new version info\n if (syncResult.prompt) {\n lock.prompts[promptName] = {\n version: syncResult.prompt.version,\n versionId: syncResult.prompt.versionId,\n materialized: filePath,\n };\n } else if (syncResult.action === \"conflict\") {\n const remoteVersion = syncResult.conflictInfo?.remoteVersion ?? 0;\n if (conflictResolution === \"remote\") {\n // User chose remote - use remote version\n lock.prompts[promptName] = {\n version: remoteVersion,\n versionId: \"remote_version\", // We don't have the actual versionId from conflict info\n materialized: filePath,\n };\n } else {\n // User chose local - force push\n const syncResult = await promptsApiService.update(promptName, {\n ...localConfig,\n commitMessage: `Synced from local file: ${path.basename(\n filePath\n )}`,\n });\n lock.prompts[promptName] = {\n version: syncResult.version,\n versionId: syncResult.versionId,\n materialized: filePath,\n };\n }\n }\n\n // Determine the action text based on sync result and conflict resolution\n let actionText: string;\n if (syncResult.action === \"conflict\") {\n if (conflictResolution === \"remote\") {\n actionText = \"Pulled\"; // User chose to use remote version\n result.fetched.push({\n name: promptName,\n version: syncResult.conflictInfo?.remoteVersion ?? 0,\n versionSpec: \"latest\", // Default for conflict resolution\n });\n } else {\n actionText = \"Pushed\"; // User chose to use local version (or forced push)\n result.pushed.push({\n name: promptName,\n version: (syncResult.conflictInfo?.remoteVersion ?? 0) + 1, // New version after push\n });\n }\n } else if (syncResult.action === \"up_to_date\") {\n // For up-to-date prompts, add to unchanged instead of pushed\n actionText = \"Up-to-date\";\n result.unchanged.push(promptName);\n } else {\n const actionMap: Record<SyncAction, string> = {\n created: \"Created\",\n updated: \"Updated\",\n conflict: \"Conflict resolved\",\n up_to_date: \"Up to date\",\n };\n actionText = actionMap[syncResult.action as SyncAction] || \"Pushed\";\n result.pushed.push({\n name: promptName,\n version: syncResult.prompt?.version ?? 0,\n });\n }\n\n pushSpinner.text = `${actionText} ${chalk.cyan(\n promptName\n )} ${chalk.gray(\n `(version ${\n syncResult.prompt?.version ??\n syncResult.conflictInfo?.remoteVersion ??\n \"unknown\"\n })`\n )} ${conflictResolution === \"remote\" ? \"to\" : \"from\"} ${chalk.gray(\n relativePath\n )}`;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n result.errors.push({ name: promptName, error: errorMessage });\n }\n }\n\n // Save lock file with all updates\n FileManager.savePromptsLock(lock);\n\n pushSpinner.stop();\n }\n\n // Check for orphan local prompt files and show helpful warnings\n const discoveredLocalFiles = FileManager.getLocalPromptFiles();\n const orphanFiles = discoveredLocalFiles.filter((filePath) => {\n const promptName = FileManager.promptNameFromPath(filePath);\n return !config.prompts[promptName]; // Not declared in prompts.json\n });\n\n if (orphanFiles.length > 0) {\n console.log(\n chalk.yellow(\n `\\n⚠ Found ${orphanFiles.length} orphan prompt file${\n orphanFiles.length > 1 ? \"s\" : \"\"\n }:`\n )\n );\n\n for (const filePath of orphanFiles) {\n const promptName = FileManager.promptNameFromPath(filePath);\n const relativePath = path.relative(process.cwd(), filePath);\n\n console.log(chalk.yellow(` ${relativePath}`));\n console.log(\n chalk.gray(\n ` Add to prompts.json: \"${promptName}\": \"file:${relativePath}\"`\n )\n );\n }\n\n console.log(\n chalk.gray(\n `\\nTip: Add these to prompts.json to include them in sync operations.`\n )\n );\n }\n\n // Cleanup orphaned materialized files\n const currentDependencies = new Set(\n Object.keys(config.prompts).filter((name) => {\n const dependency = config.prompts[name];\n // Only include remote dependencies (not local file: dependencies)\n if (typeof dependency === \"object\" && dependency.file) {\n return false;\n }\n if (typeof dependency === \"string\" && dependency.startsWith(\"file:\")) {\n return false;\n }\n return true;\n })\n );\n\n const cleanedFiles =\n FileManager.cleanupOrphanedMaterializedFiles(currentDependencies);\n if (cleanedFiles.length > 0) {\n result.cleaned = cleanedFiles;\n FileManager.removeFromLock(lock, cleanedFiles);\n }\n\n // Save the updated lock file\n FileManager.savePromptsLock(lock);\n\n // Print individual results if there were actions\n if (result.fetched.length > 0) {\n for (const { name, version, versionSpec } of result.fetched) {\n // Get the actual saved path from lock file for display consistency\n const lockEntry = lock.prompts[name];\n const displayPath = lockEntry?.materialized\n ? `./${lockEntry.materialized}`\n : `./prompts/.materialized/${name}.prompt.yaml`;\n\n console.log(\n chalk.green(\n `✓ Pulled ${chalk.cyan(`${name}@${versionSpec}`)} ${chalk.gray(\n `(version ${version})`\n )} → ${chalk.gray(displayPath)}`\n )\n );\n }\n }\n\n if (result.pushed.length > 0) {\n for (const { name, version } of result.pushed) {\n const localPath = `./prompts/${name}.prompt.yaml`;\n console.log(\n chalk.green(\n `✓ Pushed ${chalk.cyan(name)} ${chalk.gray(\n `(version ${version})`\n )} from ${chalk.gray(localPath)}`\n )\n );\n }\n }\n\n // Print cleaned up files\n if (result.cleaned.length > 0) {\n for (const name of result.cleaned) {\n console.log(\n chalk.yellow(\n `✓ Cleaned ${chalk.cyan(name)} (no longer in dependencies)`\n )\n );\n }\n }\n\n // Print errors\n if (result.errors.length > 0) {\n for (const { name, error } of result.errors) {\n console.log(chalk.red(`✗ Failed ${chalk.cyan(name)}: ${error}`));\n }\n }\n\n // Print summary\n const duration = ((Date.now() - startTime) / 1000).toFixed(1);\n const totalActions =\n result.fetched.length + result.pushed.length + result.cleaned.length;\n\n if (totalActions === 0 && result.errors.length === 0) {\n console.log(chalk.gray(`Synced in ${duration}s, no changes`));\n } else {\n const summary = [];\n if (result.fetched.length > 0)\n summary.push(`${result.fetched.length} fetched`);\n if (result.pushed.length > 0)\n summary.push(`${result.pushed.length} pushed`);\n if (result.cleaned.length > 0)\n summary.push(`${result.cleaned.length} cleaned`);\n if (result.errors.length > 0)\n summary.push(`${result.errors.length} errors`);\n\n console.log(chalk.gray(`Synced ${summary.join(\", \")} in ${duration}s`));\n }\n\n if (result.errors.length > 0) {\n process.exit(1);\n }\n } catch (error) {\n if (error instanceof PromptsError) {\n console.error(chalk.red(`Error: ${error.message}`));\n } else {\n console.error(\n chalk.red(\n `Unexpected error: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`\n )\n );\n }\n process.exit(1);\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,OAAO,WAAW;AAClB,OAAO,SAAS;AAChB,YAAY,UAAU;AAatB,OAAO,cAAc;AAGrB,IAAM,iBAAiB,OACrB,YACA,iBAM0C;AAC1C,UAAQ;AAAA,IACN,MAAM,OAAO;AAAA,uCAAqC,MAAM,KAAK,UAAU,CAAC,EAAE;AAAA,EAC5E;AACA,UAAQ;AAAA,IACN,MAAM;AAAA,MACJ,kBAAkB,aAAa,YAAY,qBAAqB,aAAa,aAAa;AAAA,IAC5F;AAAA,EACF;AAEA,MAAI,aAAa,YAAY,SAAS,GAAG;AACvC,YAAQ,IAAI,MAAM,OAAO,gBAAgB,CAAC;AAC1C,iBAAa,YAAY,QAAQ,CAAC,SAAS;AACzC,cAAQ,IAAI,MAAM,KAAK,YAAO,IAAI,EAAE,CAAC;AAAA,IACvC,CAAC;AAAA,EACH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vAttributes } from './types-DRiQaKFG.js';
|
|
3
4
|
|
|
4
5
|
type ChatRole = "system" | "user" | "assistant" | "function" | "tool" | "unknown";
|
|
@@ -2700,37 +2701,102 @@ interface operations {
|
|
|
2700
2701
|
};
|
|
2701
2702
|
}
|
|
2702
2703
|
|
|
2703
|
-
|
|
2704
|
+
/**
|
|
2705
|
+
* Zod schema for core prompt data - the essential fields needed for functionality
|
|
2706
|
+
*/
|
|
2707
|
+
declare const corePromptDataSchema: z.ZodObject<{
|
|
2708
|
+
model: z.ZodString;
|
|
2709
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
2710
|
+
role: z.ZodEnum<{
|
|
2711
|
+
system: "system";
|
|
2712
|
+
user: "user";
|
|
2713
|
+
assistant: "assistant";
|
|
2714
|
+
}>;
|
|
2715
|
+
content: z.ZodString;
|
|
2716
|
+
}, z.core.$strip>>;
|
|
2717
|
+
prompt: z.ZodOptional<z.ZodString>;
|
|
2718
|
+
temperature: z.ZodOptional<z.ZodNumber>;
|
|
2719
|
+
maxTokens: z.ZodOptional<z.ZodNumber>;
|
|
2720
|
+
responseFormat: z.ZodOptional<z.ZodObject<{
|
|
2721
|
+
type: z.ZodLiteral<"json_schema">;
|
|
2722
|
+
json_schema: z.ZodNullable<z.ZodObject<{
|
|
2723
|
+
name: z.ZodString;
|
|
2724
|
+
schema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
2725
|
+
}, z.core.$strip>>;
|
|
2726
|
+
}, z.core.$strip>>;
|
|
2727
|
+
}, z.core.$strip>;
|
|
2728
|
+
/**
|
|
2729
|
+
* Combined schema for complete prompt data
|
|
2730
|
+
*/
|
|
2731
|
+
declare const promptDataSchema: z.ZodObject<{
|
|
2732
|
+
id: z.ZodOptional<z.ZodString>;
|
|
2733
|
+
handle: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
2734
|
+
version: z.ZodOptional<z.ZodNumber>;
|
|
2735
|
+
versionId: z.ZodOptional<z.ZodString>;
|
|
2736
|
+
scope: z.ZodOptional<z.ZodEnum<{
|
|
2737
|
+
ORGANIZATION: "ORGANIZATION";
|
|
2738
|
+
PROJECT: "PROJECT";
|
|
2739
|
+
}>>;
|
|
2740
|
+
model: z.ZodString;
|
|
2741
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
2742
|
+
role: z.ZodEnum<{
|
|
2743
|
+
system: "system";
|
|
2744
|
+
user: "user";
|
|
2745
|
+
assistant: "assistant";
|
|
2746
|
+
}>;
|
|
2747
|
+
content: z.ZodString;
|
|
2748
|
+
}, z.core.$strip>>;
|
|
2749
|
+
prompt: z.ZodOptional<z.ZodString>;
|
|
2750
|
+
temperature: z.ZodOptional<z.ZodNumber>;
|
|
2751
|
+
maxTokens: z.ZodOptional<z.ZodNumber>;
|
|
2752
|
+
responseFormat: z.ZodOptional<z.ZodObject<{
|
|
2753
|
+
type: z.ZodLiteral<"json_schema">;
|
|
2754
|
+
json_schema: z.ZodNullable<z.ZodObject<{
|
|
2755
|
+
name: z.ZodString;
|
|
2756
|
+
schema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
2757
|
+
}, z.core.$strip>>;
|
|
2758
|
+
}, z.core.$strip>>;
|
|
2759
|
+
}, z.core.$strip>;
|
|
2760
|
+
|
|
2761
|
+
/**
|
|
2762
|
+
* Type for template variables - supporting common data types
|
|
2763
|
+
*/
|
|
2704
2764
|
type TemplateVariables = Record<string, string | number | boolean | object | null>;
|
|
2765
|
+
/**
|
|
2766
|
+
* Core data needed for prompt functionality
|
|
2767
|
+
*/
|
|
2768
|
+
type CorePromptData = z.infer<typeof corePromptDataSchema>;
|
|
2769
|
+
/**
|
|
2770
|
+
* Combined type for creating prompts
|
|
2771
|
+
*/
|
|
2772
|
+
type PromptData = z.infer<typeof promptDataSchema>;
|
|
2773
|
+
type CreatePromptBody = NonNullable<paths["/api/prompts"]["post"]["requestBody"]>["content"]["application/json"];
|
|
2774
|
+
type UpdatePromptBody = NonNullable<paths["/api/prompts/{id}"]["put"]["requestBody"]>["content"]["application/json"];
|
|
2775
|
+
type PromptResponse = NonNullable<paths["/api/prompts/{id}"]["get"]["responses"]["200"]["content"]["application/json"]>;
|
|
2776
|
+
type PromptScope = paths["/api/prompts"]["post"]["responses"]["200"]["content"]["application/json"]["scope"];
|
|
2777
|
+
|
|
2705
2778
|
/**
|
|
2706
2779
|
* The Prompt class provides a standardized interface for working with prompt objects
|
|
2707
|
-
* within the SDK,
|
|
2708
|
-
*
|
|
2709
|
-
* handling, enforce type safety, and facilitate future enhancements without exposing
|
|
2710
|
-
* internal details or requiring changes from client code.
|
|
2780
|
+
* within the SDK, focusing on core functionality needed for template compilation and execution.
|
|
2781
|
+
* Keeps only essential fields while maintaining compatibility with tracing and observability.
|
|
2711
2782
|
*/
|
|
2712
|
-
declare class Prompt
|
|
2713
|
-
readonly
|
|
2714
|
-
readonly
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
readonly
|
|
2719
|
-
readonly
|
|
2720
|
-
readonly
|
|
2721
|
-
readonly
|
|
2722
|
-
readonly
|
|
2723
|
-
readonly
|
|
2724
|
-
readonly
|
|
2725
|
-
readonly
|
|
2726
|
-
readonly
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
readonly prompt: PromptResponse["prompt"];
|
|
2730
|
-
readonly messages: PromptResponse["messages"];
|
|
2731
|
-
readonly inputs: PromptResponse["inputs"];
|
|
2732
|
-
readonly outputs: PromptResponse["outputs"];
|
|
2733
|
-
constructor(raw: PromptResponse);
|
|
2783
|
+
declare class Prompt {
|
|
2784
|
+
readonly model: string;
|
|
2785
|
+
readonly messages: Array<{
|
|
2786
|
+
role: "user" | "assistant" | "system";
|
|
2787
|
+
content: string;
|
|
2788
|
+
}>;
|
|
2789
|
+
readonly prompt?: string;
|
|
2790
|
+
readonly temperature?: number;
|
|
2791
|
+
readonly maxTokens?: number;
|
|
2792
|
+
readonly responseFormat?: CorePromptData["responseFormat"];
|
|
2793
|
+
readonly id?: string;
|
|
2794
|
+
readonly handle?: string | null;
|
|
2795
|
+
readonly version?: number;
|
|
2796
|
+
readonly versionId?: string;
|
|
2797
|
+
readonly scope?: PromptScope;
|
|
2798
|
+
constructor(data: PromptData);
|
|
2799
|
+
private extractSystemPrompt;
|
|
2734
2800
|
/**
|
|
2735
2801
|
* Compile the prompt template with provided variables (lenient - missing variables become empty)
|
|
2736
2802
|
* @param variables - Object containing variable values for template compilation
|
|
@@ -2745,9 +2811,12 @@ declare class Prompt implements PromptResponse {
|
|
|
2745
2811
|
*/
|
|
2746
2812
|
compileStrict(variables: TemplateVariables): CompiledPrompt;
|
|
2747
2813
|
}
|
|
2814
|
+
/**
|
|
2815
|
+
* Represents a compiled prompt that extends Prompt with reference to the original template
|
|
2816
|
+
*/
|
|
2748
2817
|
declare class CompiledPrompt extends Prompt {
|
|
2749
2818
|
readonly original: Prompt;
|
|
2750
|
-
constructor(compiledData:
|
|
2819
|
+
constructor(compiledData: PromptData, original: Prompt);
|
|
2751
2820
|
}
|
|
2752
2821
|
|
|
2753
2822
|
/**
|
|
@@ -3263,4 +3332,4 @@ interface LangWatchTracer extends Tracer {
|
|
|
3263
3332
|
withActiveSpan<F extends (span: LangWatchSpan) => unknown>(name: string, options: LangWatchSpanOptions, context: Context, fn: F): ReturnType<F>;
|
|
3264
3333
|
}
|
|
3265
3334
|
|
|
3266
|
-
export { type ChatMessage as C, type InputOutputType as I, type JsonSerializable as J, type LangWatchSpan as L, type PromptResponse as P, type SpanType as S, type LangWatchTracer as a, type LangWatchSpanMetrics as b, type LangWatchSpanRAGContext as c, type LangWatchSpanOptions as d, type SimpleChatMessage as e, INPUT_OUTPUT_TYPES as f,
|
|
3335
|
+
export { type ChatMessage as C, type InputOutputType as I, type JsonSerializable as J, type LangWatchSpan as L, type PromptResponse as P, type SpanType as S, type UpdatePromptBody as U, type LangWatchTracer as a, type LangWatchSpanMetrics as b, type LangWatchSpanRAGContext as c, type LangWatchSpanOptions as d, type SimpleChatMessage as e, INPUT_OUTPUT_TYPES as f, type CreatePromptBody as g, type PromptData as h, Prompt as i, type paths as p, spanTypes as s };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SpanOptions, Span, AttributeValue, Tracer, Context } from '@opentelemetry/api';
|
|
2
|
+
import { z } from 'zod';
|
|
2
3
|
import { S as SemConvAttributes } from './types-DRiQaKFG.mjs';
|
|
3
4
|
|
|
4
5
|
type ChatRole = "system" | "user" | "assistant" | "function" | "tool" | "unknown";
|
|
@@ -2700,37 +2701,102 @@ interface operations {
|
|
|
2700
2701
|
};
|
|
2701
2702
|
}
|
|
2702
2703
|
|
|
2703
|
-
|
|
2704
|
+
/**
|
|
2705
|
+
* Zod schema for core prompt data - the essential fields needed for functionality
|
|
2706
|
+
*/
|
|
2707
|
+
declare const corePromptDataSchema: z.ZodObject<{
|
|
2708
|
+
model: z.ZodString;
|
|
2709
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
2710
|
+
role: z.ZodEnum<{
|
|
2711
|
+
system: "system";
|
|
2712
|
+
user: "user";
|
|
2713
|
+
assistant: "assistant";
|
|
2714
|
+
}>;
|
|
2715
|
+
content: z.ZodString;
|
|
2716
|
+
}, z.core.$strip>>;
|
|
2717
|
+
prompt: z.ZodOptional<z.ZodString>;
|
|
2718
|
+
temperature: z.ZodOptional<z.ZodNumber>;
|
|
2719
|
+
maxTokens: z.ZodOptional<z.ZodNumber>;
|
|
2720
|
+
responseFormat: z.ZodOptional<z.ZodObject<{
|
|
2721
|
+
type: z.ZodLiteral<"json_schema">;
|
|
2722
|
+
json_schema: z.ZodNullable<z.ZodObject<{
|
|
2723
|
+
name: z.ZodString;
|
|
2724
|
+
schema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
2725
|
+
}, z.core.$strip>>;
|
|
2726
|
+
}, z.core.$strip>>;
|
|
2727
|
+
}, z.core.$strip>;
|
|
2728
|
+
/**
|
|
2729
|
+
* Combined schema for complete prompt data
|
|
2730
|
+
*/
|
|
2731
|
+
declare const promptDataSchema: z.ZodObject<{
|
|
2732
|
+
id: z.ZodOptional<z.ZodString>;
|
|
2733
|
+
handle: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
2734
|
+
version: z.ZodOptional<z.ZodNumber>;
|
|
2735
|
+
versionId: z.ZodOptional<z.ZodString>;
|
|
2736
|
+
scope: z.ZodOptional<z.ZodEnum<{
|
|
2737
|
+
ORGANIZATION: "ORGANIZATION";
|
|
2738
|
+
PROJECT: "PROJECT";
|
|
2739
|
+
}>>;
|
|
2740
|
+
model: z.ZodString;
|
|
2741
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
2742
|
+
role: z.ZodEnum<{
|
|
2743
|
+
system: "system";
|
|
2744
|
+
user: "user";
|
|
2745
|
+
assistant: "assistant";
|
|
2746
|
+
}>;
|
|
2747
|
+
content: z.ZodString;
|
|
2748
|
+
}, z.core.$strip>>;
|
|
2749
|
+
prompt: z.ZodOptional<z.ZodString>;
|
|
2750
|
+
temperature: z.ZodOptional<z.ZodNumber>;
|
|
2751
|
+
maxTokens: z.ZodOptional<z.ZodNumber>;
|
|
2752
|
+
responseFormat: z.ZodOptional<z.ZodObject<{
|
|
2753
|
+
type: z.ZodLiteral<"json_schema">;
|
|
2754
|
+
json_schema: z.ZodNullable<z.ZodObject<{
|
|
2755
|
+
name: z.ZodString;
|
|
2756
|
+
schema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
2757
|
+
}, z.core.$strip>>;
|
|
2758
|
+
}, z.core.$strip>>;
|
|
2759
|
+
}, z.core.$strip>;
|
|
2760
|
+
|
|
2761
|
+
/**
|
|
2762
|
+
* Type for template variables - supporting common data types
|
|
2763
|
+
*/
|
|
2704
2764
|
type TemplateVariables = Record<string, string | number | boolean | object | null>;
|
|
2765
|
+
/**
|
|
2766
|
+
* Core data needed for prompt functionality
|
|
2767
|
+
*/
|
|
2768
|
+
type CorePromptData = z.infer<typeof corePromptDataSchema>;
|
|
2769
|
+
/**
|
|
2770
|
+
* Combined type for creating prompts
|
|
2771
|
+
*/
|
|
2772
|
+
type PromptData = z.infer<typeof promptDataSchema>;
|
|
2773
|
+
type CreatePromptBody = NonNullable<paths["/api/prompts"]["post"]["requestBody"]>["content"]["application/json"];
|
|
2774
|
+
type UpdatePromptBody = NonNullable<paths["/api/prompts/{id}"]["put"]["requestBody"]>["content"]["application/json"];
|
|
2775
|
+
type PromptResponse = NonNullable<paths["/api/prompts/{id}"]["get"]["responses"]["200"]["content"]["application/json"]>;
|
|
2776
|
+
type PromptScope = paths["/api/prompts"]["post"]["responses"]["200"]["content"]["application/json"]["scope"];
|
|
2777
|
+
|
|
2705
2778
|
/**
|
|
2706
2779
|
* The Prompt class provides a standardized interface for working with prompt objects
|
|
2707
|
-
* within the SDK,
|
|
2708
|
-
*
|
|
2709
|
-
* handling, enforce type safety, and facilitate future enhancements without exposing
|
|
2710
|
-
* internal details or requiring changes from client code.
|
|
2780
|
+
* within the SDK, focusing on core functionality needed for template compilation and execution.
|
|
2781
|
+
* Keeps only essential fields while maintaining compatibility with tracing and observability.
|
|
2711
2782
|
*/
|
|
2712
|
-
declare class Prompt
|
|
2713
|
-
readonly
|
|
2714
|
-
readonly
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
readonly
|
|
2719
|
-
readonly
|
|
2720
|
-
readonly
|
|
2721
|
-
readonly
|
|
2722
|
-
readonly
|
|
2723
|
-
readonly
|
|
2724
|
-
readonly
|
|
2725
|
-
readonly
|
|
2726
|
-
readonly
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
readonly prompt: PromptResponse["prompt"];
|
|
2730
|
-
readonly messages: PromptResponse["messages"];
|
|
2731
|
-
readonly inputs: PromptResponse["inputs"];
|
|
2732
|
-
readonly outputs: PromptResponse["outputs"];
|
|
2733
|
-
constructor(raw: PromptResponse);
|
|
2783
|
+
declare class Prompt {
|
|
2784
|
+
readonly model: string;
|
|
2785
|
+
readonly messages: Array<{
|
|
2786
|
+
role: "user" | "assistant" | "system";
|
|
2787
|
+
content: string;
|
|
2788
|
+
}>;
|
|
2789
|
+
readonly prompt?: string;
|
|
2790
|
+
readonly temperature?: number;
|
|
2791
|
+
readonly maxTokens?: number;
|
|
2792
|
+
readonly responseFormat?: CorePromptData["responseFormat"];
|
|
2793
|
+
readonly id?: string;
|
|
2794
|
+
readonly handle?: string | null;
|
|
2795
|
+
readonly version?: number;
|
|
2796
|
+
readonly versionId?: string;
|
|
2797
|
+
readonly scope?: PromptScope;
|
|
2798
|
+
constructor(data: PromptData);
|
|
2799
|
+
private extractSystemPrompt;
|
|
2734
2800
|
/**
|
|
2735
2801
|
* Compile the prompt template with provided variables (lenient - missing variables become empty)
|
|
2736
2802
|
* @param variables - Object containing variable values for template compilation
|
|
@@ -2745,9 +2811,12 @@ declare class Prompt implements PromptResponse {
|
|
|
2745
2811
|
*/
|
|
2746
2812
|
compileStrict(variables: TemplateVariables): CompiledPrompt;
|
|
2747
2813
|
}
|
|
2814
|
+
/**
|
|
2815
|
+
* Represents a compiled prompt that extends Prompt with reference to the original template
|
|
2816
|
+
*/
|
|
2748
2817
|
declare class CompiledPrompt extends Prompt {
|
|
2749
2818
|
readonly original: Prompt;
|
|
2750
|
-
constructor(compiledData:
|
|
2819
|
+
constructor(compiledData: PromptData, original: Prompt);
|
|
2751
2820
|
}
|
|
2752
2821
|
|
|
2753
2822
|
/**
|
|
@@ -3263,4 +3332,4 @@ interface LangWatchTracer extends Tracer {
|
|
|
3263
3332
|
withActiveSpan<F extends (span: LangWatchSpan) => unknown>(name: string, options: LangWatchSpanOptions, context: Context, fn: F): ReturnType<F>;
|
|
3264
3333
|
}
|
|
3265
3334
|
|
|
3266
|
-
export { type ChatMessage as C, type InputOutputType as I, type JsonSerializable as J, type LangWatchSpan as L, type PromptResponse as P, type SpanType as S, type LangWatchTracer as a, type LangWatchSpanMetrics as b, type LangWatchSpanRAGContext as c, type LangWatchSpanOptions as d, type SimpleChatMessage as e, INPUT_OUTPUT_TYPES as f,
|
|
3335
|
+
export { type ChatMessage as C, type InputOutputType as I, type JsonSerializable as J, type LangWatchSpan as L, type PromptResponse as P, type SpanType as S, type UpdatePromptBody as U, type LangWatchTracer as a, type LangWatchSpanMetrics as b, type LangWatchSpanRAGContext as c, type LangWatchSpanOptions as d, type SimpleChatMessage as e, INPUT_OUTPUT_TYPES as f, type CreatePromptBody as g, type PromptData as h, Prompt as i, type paths as p, spanTypes as s };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "langwatch",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "LangWatch TypeScript/JavaScript SDK. Interact with the full LangWatch API and use the LangWatch OpenTelemetry SDK to instrument your application. For more information, see https://docs.langwatch.ai/integration/typescript/guide",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -69,6 +69,7 @@
|
|
|
69
69
|
"typescript": "^5.9.2",
|
|
70
70
|
"typescript-eslint": "^8.38.0",
|
|
71
71
|
"vitest": "^3.2.4",
|
|
72
|
+
"vitest-mock-extended": "^3.1.0",
|
|
72
73
|
"yaml": "^2.8.1"
|
|
73
74
|
},
|
|
74
75
|
"dependencies": {
|
|
@@ -113,8 +114,8 @@
|
|
|
113
114
|
"test": "vitest",
|
|
114
115
|
"test:e2e": "vitest run -c ./vitest.e2e.config.mts",
|
|
115
116
|
"prebuild": "pnpm i && pnpm run prepare",
|
|
116
|
-
"build": "
|
|
117
|
-
"typecheck": "
|
|
117
|
+
"build": "tsc --noEmit && tsup",
|
|
118
|
+
"typecheck": "tsc --noEmit",
|
|
118
119
|
"prepublish": "pnpm run build",
|
|
119
120
|
"generate:openapi-types": "npx openapi-typescript ../langwatch/src/app/api/openapiLangWatch.json -o ./src/internal/generated/openapi/api-client.ts",
|
|
120
121
|
"generate:server-types": "./copy-types.sh"
|
package/dist/add-4WXEWG5H.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/langwatch/langwatch/typescript-sdk/dist/add-4WXEWG5H.js","../src/cli/commands/add.ts"],"names":[],"mappings":"AAAA;AACE;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B;AACA;AC1BA,+DAAoB;AACpB,uEAAsB;AACtB,4EAAkB;AAClB,oEAAgB;AAahB,IAAM,aAAA,EAAe,MAAA,CACnB,IAAA,EACA,aAAA,EAAA,GACkB;AAElB,EAAA,GAAA,CAAI,CAAI,EAAA,CAAA,UAAA,CAAW,aAAa,CAAA,EAAG;AACjC,IAAA,OAAA,CAAQ,KAAA,CAAM,eAAA,CAAM,GAAA,CAAI,CAAA,6BAAA,EAAgC,aAAa,CAAA,CAAA;AACvD,IAAA;AAChB,EAAA;AAE6C,EAAA;AACnC,IAAA;AACwD,MAAA;AAChE,IAAA;AACc,IAAA;AAChB,EAAA;AAGI,EAAA;AACuC,IAAA;AAGV,IAAA;AAGqB,IAAA;AACD,IAAA;AACR,IAAA;AAGF,IAAA;AACpB,IAAA;AACV,MAAA;AAAA;AACE,MAAA;AACG,MAAA;AAAA;AAChB,IAAA;AACgC,IAAA;AAExB,IAAA;AACA,MAAA;AACiD,QAAA;AACnD,UAAA;AACD,QAAA;AACH,MAAA;AACF,IAAA;AACc,EAAA;AAC6C,IAAA;AACnD,IAAA;AAC0D,MAAA;AAClE,IAAA;AACc,IAAA;AAChB,EAAA;AACF;AAKoB;AAzEpB,EAAA;AA0EM,EAAA;AAE+B,IAAA;AAC8B,MAAA;AAC/C,MAAA;AAChB,IAAA;AAGuB,IAAA;AACqB,MAAA;AAC1C,MAAA;AACF,IAAA;AAGY,IAAA;AAEoB,IAAA;AACG,IAAA;AAGnB,IAAA;AAC4B,MAAA;AACpC,IAAA;AAEJ,IAAA;AAE6C,MAAA;AAElC,MAAA;AACE,QAAA;AAC+C,QAAA;AAC9C,QAAA;AAChB,MAAA;AAGa,MAAA;AAGkB,MAAA;AAG8B,MAAA;AAGI,MAAA;AACnC,MAAA;AAC5B,QAAA;AACA,QAAA;AACF,MAAA;AAC2D,MAAA;AAGd,MAAA;AACJ,MAAA;AAElB,MAAA;AACqC,MAAA;AAGxB,MAAA;AACJ,MAAA;AAEhB,MAAA;AAKZ,MAAA;AACI,MAAA;AACA,QAAA;AACkD,UAAA;AAC1B,YAAA;AACE,UAAA;AAChC,QAAA;AACF,MAAA;AACc,IAAA;AACD,MAAA;AACsB,MAAA;AACiB,QAAA;AAC7C,MAAA;AACG,QAAA;AACA,UAAA;AAE6B,YAAA;AAEnC,UAAA;AACF,QAAA;AACF,MAAA;AACc,MAAA;AAChB,IAAA;AACc,EAAA;AACqB,IAAA;AACiB,MAAA;AAC7C,IAAA;AACG,MAAA;AACA,QAAA;AAEuC,UAAA;AAE7C,QAAA;AACF,MAAA;AACF,IAAA;AACc,IAAA;AAChB,EAAA;AACF;ADhC0E;AACA;AACA","file":"/home/runner/work/langwatch/langwatch/typescript-sdk/dist/add-4WXEWG5H.js","sourcesContent":[null,"import * as fs from \"fs\";\nimport * as path from \"path\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { FileManager } from \"../utils/fileManager\";\nimport { PromptsError } from \"@/client-sdk/services/prompts\";\nimport { PromptConverter } from \"../utils/promptConverter\";\nimport { ensureProjectInitialized } from \"../utils/init\";\nimport { checkApiKey } from \"../utils/apiKey\";\nimport { LangWatch } from \"@/client-sdk\";\n\ninterface AddOptions {\n version?: string;\n localFile?: string;\n}\n\nconst addLocalFile = async (\n name: string,\n localFilePath: string,\n): Promise<void> => {\n // Validate that the file exists and has the right extension\n if (!fs.existsSync(localFilePath)) {\n console.error(chalk.red(`Error: Local file not found: ${localFilePath}`));\n process.exit(1);\n }\n\n if (!localFilePath.endsWith(\".prompt.yaml\")) {\n console.error(\n chalk.red(`Error: Local file must have .prompt.yaml extension`),\n );\n process.exit(1);\n }\n\n // Load and validate the YAML file\n try {\n FileManager.loadLocalPrompt(localFilePath);\n\n // Ensure project is initialized\n await ensureProjectInitialized();\n\n // Add to prompts.json as a file: dependency\n const promptsConfig = FileManager.loadPromptsConfig();\n promptsConfig.prompts[name] = `file:${localFilePath}`;\n FileManager.savePromptsConfig(promptsConfig);\n\n // Update lock file\n const lock = FileManager.loadPromptsLock();\n lock.prompts[name] = {\n version: 0, // Local files start at version 0\n versionId: \"local\",\n materialized: localFilePath, // Store the original file path\n };\n FileManager.savePromptsLock(lock);\n\n console.log(\n chalk.green(\n `✓ Added local prompt: ${chalk.cyan(name)} → ${chalk.gray(\n localFilePath,\n )}`,\n ),\n );\n } catch (error) {\n console.error(chalk.red(\"Error loading local prompt file:\"));\n console.error(\n chalk.red(error instanceof Error ? error.message : String(error)),\n );\n process.exit(1);\n }\n};\n\nexport const addCommand = async (\n name: string,\n options: AddOptions,\n): Promise<void> => {\n try {\n // Validate prompt name\n if (!name || name.trim() === \"\") {\n console.error(chalk.red(\"Error: Prompt name cannot be empty\"));\n process.exit(1);\n }\n\n // Handle local file addition\n if (options.localFile) {\n await addLocalFile(name, options.localFile);\n return;\n }\n\n // Check API key before doing anything else\n checkApiKey();\n\n const langwatch = new LangWatch();\n const version = options.version ?? \"latest\";\n\n // Fetch and materialize the prompt (like sync does for individual prompts)\n const spinner = ora(\n `Adding ${chalk.cyan(`${name}@${version}`)}...`,\n ).start();\n\n try {\n // Fetch the prompt from the API\n const prompt = await langwatch.prompts.get(name);\n\n if (!prompt) {\n spinner.fail();\n console.error(chalk.red(`Error: Prompt \"${name}\" not found`));\n process.exit(1);\n }\n\n // Stop spinner before any user input prompts\n spinner.stop();\n\n // Ensure project is initialized (prompts.json, lock file, directories)\n await ensureProjectInitialized();\n\n // Restart spinner for the actual work\n spinner.start(`Adding ${chalk.cyan(`${name}@${version}`)}...`);\n\n // Convert to MaterializedPrompt format and save\n const materializedPrompt = PromptConverter.fromApiToMaterialized(prompt);\n const savedPath = FileManager.saveMaterializedPrompt(\n name,\n materializedPrompt,\n );\n const relativePath = path.relative(process.cwd(), savedPath);\n\n // Load existing config and lock, add the new dependency\n const config = FileManager.loadPromptsConfig();\n const lock = FileManager.loadPromptsLock();\n\n config.prompts[name] = version;\n FileManager.updateLockEntry(lock, name, materializedPrompt, savedPath);\n\n // Save the updated config and lock\n FileManager.savePromptsConfig(config);\n FileManager.savePromptsLock(lock);\n\n spinner.succeed();\n\n // Show what was done (add ./ prefix for consistency)\n const displayPath = relativePath.startsWith(\"./\")\n ? relativePath\n : `./${relativePath}`;\n console.log(\n chalk.green(\n `✓ Pulled ${chalk.cyan(`${name}@${version}`)} ${chalk.gray(\n `(version ${prompt.version})`,\n )} → ${chalk.gray(displayPath)}`,\n ),\n );\n } catch (error) {\n spinner.fail();\n if (error instanceof PromptsError) {\n console.error(chalk.red(`Error: ${error.message}`));\n } else {\n console.error(\n chalk.red(\n `Error adding prompt: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n ),\n );\n }\n process.exit(1);\n }\n } catch (error) {\n if (error instanceof PromptsError) {\n console.error(chalk.red(`Error: ${error.message}`));\n } else {\n console.error(\n chalk.red(\n `Unexpected error: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n ),\n );\n }\n process.exit(1);\n }\n};\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/commands/add.ts"],"sourcesContent":["import * as fs from \"fs\";\nimport * as path from \"path\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { FileManager } from \"../utils/fileManager\";\nimport { PromptsError } from \"@/client-sdk/services/prompts\";\nimport { PromptConverter } from \"../utils/promptConverter\";\nimport { ensureProjectInitialized } from \"../utils/init\";\nimport { checkApiKey } from \"../utils/apiKey\";\nimport { LangWatch } from \"@/client-sdk\";\n\ninterface AddOptions {\n version?: string;\n localFile?: string;\n}\n\nconst addLocalFile = async (\n name: string,\n localFilePath: string,\n): Promise<void> => {\n // Validate that the file exists and has the right extension\n if (!fs.existsSync(localFilePath)) {\n console.error(chalk.red(`Error: Local file not found: ${localFilePath}`));\n process.exit(1);\n }\n\n if (!localFilePath.endsWith(\".prompt.yaml\")) {\n console.error(\n chalk.red(`Error: Local file must have .prompt.yaml extension`),\n );\n process.exit(1);\n }\n\n // Load and validate the YAML file\n try {\n FileManager.loadLocalPrompt(localFilePath);\n\n // Ensure project is initialized\n await ensureProjectInitialized();\n\n // Add to prompts.json as a file: dependency\n const promptsConfig = FileManager.loadPromptsConfig();\n promptsConfig.prompts[name] = `file:${localFilePath}`;\n FileManager.savePromptsConfig(promptsConfig);\n\n // Update lock file\n const lock = FileManager.loadPromptsLock();\n lock.prompts[name] = {\n version: 0, // Local files start at version 0\n versionId: \"local\",\n materialized: localFilePath, // Store the original file path\n };\n FileManager.savePromptsLock(lock);\n\n console.log(\n chalk.green(\n `✓ Added local prompt: ${chalk.cyan(name)} → ${chalk.gray(\n localFilePath,\n )}`,\n ),\n );\n } catch (error) {\n console.error(chalk.red(\"Error loading local prompt file:\"));\n console.error(\n chalk.red(error instanceof Error ? error.message : String(error)),\n );\n process.exit(1);\n }\n};\n\nexport const addCommand = async (\n name: string,\n options: AddOptions,\n): Promise<void> => {\n try {\n // Validate prompt name\n if (!name || name.trim() === \"\") {\n console.error(chalk.red(\"Error: Prompt name cannot be empty\"));\n process.exit(1);\n }\n\n // Handle local file addition\n if (options.localFile) {\n await addLocalFile(name, options.localFile);\n return;\n }\n\n // Check API key before doing anything else\n checkApiKey();\n\n const langwatch = new LangWatch();\n const version = options.version ?? \"latest\";\n\n // Fetch and materialize the prompt (like sync does for individual prompts)\n const spinner = ora(\n `Adding ${chalk.cyan(`${name}@${version}`)}...`,\n ).start();\n\n try {\n // Fetch the prompt from the API\n const prompt = await langwatch.prompts.get(name);\n\n if (!prompt) {\n spinner.fail();\n console.error(chalk.red(`Error: Prompt \"${name}\" not found`));\n process.exit(1);\n }\n\n // Stop spinner before any user input prompts\n spinner.stop();\n\n // Ensure project is initialized (prompts.json, lock file, directories)\n await ensureProjectInitialized();\n\n // Restart spinner for the actual work\n spinner.start(`Adding ${chalk.cyan(`${name}@${version}`)}...`);\n\n // Convert to MaterializedPrompt format and save\n const materializedPrompt = PromptConverter.fromApiToMaterialized(prompt);\n const savedPath = FileManager.saveMaterializedPrompt(\n name,\n materializedPrompt,\n );\n const relativePath = path.relative(process.cwd(), savedPath);\n\n // Load existing config and lock, add the new dependency\n const config = FileManager.loadPromptsConfig();\n const lock = FileManager.loadPromptsLock();\n\n config.prompts[name] = version;\n FileManager.updateLockEntry(lock, name, materializedPrompt, savedPath);\n\n // Save the updated config and lock\n FileManager.savePromptsConfig(config);\n FileManager.savePromptsLock(lock);\n\n spinner.succeed();\n\n // Show what was done (add ./ prefix for consistency)\n const displayPath = relativePath.startsWith(\"./\")\n ? relativePath\n : `./${relativePath}`;\n console.log(\n chalk.green(\n `✓ Pulled ${chalk.cyan(`${name}@${version}`)} ${chalk.gray(\n `(version ${prompt.version})`,\n )} → ${chalk.gray(displayPath)}`,\n ),\n );\n } catch (error) {\n spinner.fail();\n if (error instanceof PromptsError) {\n console.error(chalk.red(`Error: ${error.message}`));\n } else {\n console.error(\n chalk.red(\n `Error adding prompt: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n ),\n );\n }\n process.exit(1);\n }\n } catch (error) {\n if (error instanceof PromptsError) {\n console.error(chalk.red(`Error: ${error.message}`));\n } else {\n console.error(\n chalk.red(\n `Unexpected error: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n ),\n );\n }\n process.exit(1);\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,OAAO,WAAW;AAClB,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AQ,KAAK;AACb,UAAI,iBAAiB,cAAc;AACjC,gBAAQ,MAAM,MAAM,IAAI,UAAU,MAAM,OAAO,EAAE,CAAC;AAAA,MACpD,OAAO;AACL,gBAAQ;AAAA,UACN,MAAM;AAAA,YACJ,wBACE,iBAAiB,QAAQ,MAAM,UAAU,eAC3C;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,SAAS,OAAO;AACd,QAAI,iBAAiB,cAAc;AACjC,cAAQ,MAAM,MAAM,IAAI,UAAU,MAAM,OAAO,EAAE,CAAC;AAAA,IACpD,OAAO;AACL,cAAQ;AAAA,QACN,MAAM;AAAA,UACJ,qBACE,iBAAiB,QAAQ,MAAM,UAAU,eAC3C;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/langwatch/langwatch/typescript-sdk/dist/chunk-CAZONSXV.js","../src/cli/utils/fileManager.ts"],"names":[],"mappings":"AAAA;AACE;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACA;ACPA,+DAAoB;AACpB,uEAAsB;AACtB,8EAAsB;AACtB,4EAAkB;AAKX,IAAM,YAAA,EAAN,MAAkB;AAAA,EAMvB,OAAO,oBAAA,CAAA,EAA+B;AACpC,IAAA,OAAY,IAAA,CAAA,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,mBAAmB,CAAA;AAAA,EAC1D;AAAA,EAEA,OAAO,kBAAA,CAAA,EAA6B;AAClC,IAAA,OAAY,IAAA,CAAA,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,iBAAiB,CAAA;AAAA,EACxD;AAAA,EAEA,OAAO,aAAA,CAAA,EAAwB;AAC7B,IAAA,OAAY,IAAA,CAAA,IA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,IAAA;AAEhB,IAAA;AACtB,MAAA;AACV,IAAA;AAEyB,IAAA;AAEiC,IAAA;AACG,MAAA;AAE9B,MAAA;AACe,QAAA;AACiB,QAAA;AAElC,QAAA;AAEW,UAAA;AAChC,YAAA;AACF,UAAA;AACkC,UAAA;AAC8B,QAAA;AACd,UAAA;AACpD,QAAA;AACF,MAAA;AACF,IAAA;AAEkB,IAAA;AACX,IAAA;AACT,EAAA;AAEoD,EAAA;AACZ,IAAA;AACiB,IAAA;AACN,IAAA;AACnD,EAAA;AAEoF,EAAA;AAClC,IAAA;AAEX,IAAA;AAC3B,MAAA;AACV,IAAA;AAE2B,IAAA;AAEkC,IAAA;AACA,MAAA;AAE9B,MAAA;AACe,QAAA;AACiB,QAAA;AAElC,QAAA;AACc,UAAA;AAGjC,UAAA;AACwC,YAAA;AACb,YAAA;AACN,cAAA;AACvB,YAAA;AACM,UAAA;AAER,UAAA;AACgE,QAAA;AAEC,UAAA;AAEvB,UAAA;AAClB,YAAA;AACC,YAAA;AACzB,UAAA;AACF,QAAA;AACF,MAAA;AACF,IAAA;AAE0B,IAAA;AACnB,IAAA;AACT,EAAA;AAEoH,EAAA;AAChD,IAAA;AAE7C,IAAA;AACH,MAAA;AACE,MAAA;AACJ,MAAA;AAChB,IAAA;AACF,EAAA;AAEgE,EAAA;AACpC,IAAA;AACA,MAAA;AAC1B,IAAA;AACF,EAAA;AAE2E,EAAA;AACd,IAAA;AAGxB,IAAA;AAEO,MAAA;AAAI;AACP,MAAA;AACvC,IAAA;AAGsD,IAAA;AACG,IAAA;AAG9B,IAAA;AACY,MAAA;AACvC,IAAA;AAG8D,IAAA;AAAiB;AAAU;AAAA;AAC/C,IAAA;AAEL,IAAA;AACvC,EAAA;AACF;AApSgD;AACF;AACN;AACK;ADiOmE;AACA;AACA;AACA","file":"/home/runner/work/langwatch/langwatch/typescript-sdk/dist/chunk-CAZONSXV.js","sourcesContent":[null,"import * as fs from \"fs\";\nimport * as path from \"path\";\nimport * as yaml from \"js-yaml\";\nimport chalk from \"chalk\";\nimport type { PromptsConfig, LocalPromptConfig, MaterializedPrompt, PromptsLock } from \"../types\";\nimport { localPromptConfigSchema } from \"../types\";\nimport { PromptConverter } from \"@/cli/utils/promptConverter\";\n\nexport class FileManager {\n private static readonly PROMPTS_CONFIG_FILE = \"prompts.json\";\n private static readonly PROMPTS_LOCK_FILE = \"prompts-lock.json\";\n private static readonly PROMPTS_DIR = \"prompts\";\n private static readonly MATERIALIZED_DIR = \".materialized\";\n\n static getPromptsConfigPath(): string {\n return path.join(process.cwd(), this.PROMPTS_CONFIG_FILE);\n }\n\n static getPromptsLockPath(): string {\n return path.join(process.cwd(), this.PROMPTS_LOCK_FILE);\n }\n\n static getPromptsDir(): string {\n return path.join(process.cwd(), this.PROMPTS_DIR);\n }\n\n static getMaterializedDir(): string {\n return path.join(this.getPromptsDir(), this.MATERIALIZED_DIR);\n }\n\n static ensureDirectories(): void {\n const promptsDir = this.getPromptsDir();\n const materializedDir = this.getMaterializedDir();\n\n if (!fs.existsSync(promptsDir)) {\n fs.mkdirSync(promptsDir, { recursive: true });\n }\n\n if (!fs.existsSync(materializedDir)) {\n fs.mkdirSync(materializedDir, { recursive: true });\n }\n }\n\n static loadPromptsConfig(): PromptsConfig {\n const configPath = this.getPromptsConfigPath();\n\n if (!fs.existsSync(configPath)) {\n return { prompts: {} };\n }\n\n try {\n const content = fs.readFileSync(configPath, \"utf-8\");\n return JSON.parse(content) as PromptsConfig;\n } catch (error) {\n throw new Error(`Failed to parse prompts.json: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n }\n }\n\n static savePromptsConfig(config: PromptsConfig): void {\n const configPath = this.getPromptsConfigPath();\n fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + \"\\n\");\n }\n\n static initializePromptsConfig(): { created: boolean; path: string } {\n const configPath = this.getPromptsConfigPath();\n const existed = fs.existsSync(configPath);\n\n if (!existed) {\n const emptyConfig: PromptsConfig = { prompts: {} };\n this.savePromptsConfig(emptyConfig);\n return { created: true, path: configPath };\n }\n\n return { created: false, path: configPath };\n }\n\n static loadPromptsLock(): PromptsLock {\n const lockPath = this.getPromptsLockPath();\n\n if (!fs.existsSync(lockPath)) {\n return {\n lockfileVersion: 1,\n prompts: {}\n };\n }\n\n try {\n const content = fs.readFileSync(lockPath, \"utf-8\");\n return JSON.parse(content) as PromptsLock;\n } catch (error) {\n throw new Error(`Failed to parse prompts-lock.json: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n }\n }\n\n static savePromptsLock(lock: PromptsLock): void {\n const lockPath = this.getPromptsLockPath();\n fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + \"\\n\");\n }\n\n static initializePromptsLock(): { created: boolean; path: string } {\n const lockPath = this.getPromptsLockPath();\n const existed = fs.existsSync(lockPath);\n\n if (!existed) {\n const emptyLock: PromptsLock = {\n lockfileVersion: 1,\n prompts: {}\n };\n this.savePromptsLock(emptyLock);\n return { created: true, path: lockPath };\n }\n\n return { created: false, path: lockPath };\n }\n\n static loadLocalPrompt(filePath: string): LocalPromptConfig {\n const fullPath = path.resolve(filePath);\n\n if (!fs.existsSync(fullPath)) {\n throw new Error(`Local prompt file not found: ${filePath}`);\n }\n\n try {\n const content = fs.readFileSync(fullPath, \"utf-8\");\n const rawData = yaml.load(content);\n\n // Validate with zod and provide nice error messages\n const result = localPromptConfigSchema.safeParse(rawData);\n\n if (!result.success) {\n // Format zod errors nicely (manually since z.prettifyError might not be available)\n const prettyError = result.error.issues\n .map(issue => `✖ ${issue.message}${issue.path.length > 0 ? `\\n → at ${issue.path.join('.')}` : ''}`)\n .join('\\n');\n\n throw new Error(\n `Invalid prompt configuration in ${chalk.yellow(filePath)}:\\n${prettyError}`\n );\n }\n\n return result.data;\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Invalid prompt configuration\")) {\n throw error; // Re-throw zod validation errors as-is\n }\n throw new Error(`Failed to parse local prompt file ${filePath}: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n }\n }\n\n static saveMaterializedPrompt(name: string, prompt: MaterializedPrompt): string {\n const materializedDir = this.getMaterializedDir();\n const parts = name.split(\"/\");\n const fileName = `${parts[parts.length - 1]}.prompt.yaml`;\n\n // Create nested directories if needed\n if (parts.length > 1) {\n const subDir = path.join(materializedDir, ...parts.slice(0, -1));\n if (!fs.existsSync(subDir)) {\n fs.mkdirSync(subDir, { recursive: true });\n }\n }\n\n const filePath = path.join(materializedDir, ...parts.slice(0, -1), fileName);\n\n // Convert to YAML format using the converter\n const yamlContent = PromptConverter.fromMaterializedToYaml(prompt);\n\n const yamlString = yaml.dump(yamlContent, {\n lineWidth: -1,\n noRefs: true,\n sortKeys: false\n });\n\n fs.writeFileSync(filePath, yamlString);\n return filePath;\n }\n\n static getLocalPromptFiles(): string[] {\n const promptsDir = this.getPromptsDir();\n const materializedDir = this.getMaterializedDir();\n\n if (!fs.existsSync(promptsDir)) {\n return [];\n }\n\n const files: string[] = [];\n\n const walkDir = (dir: string, relativePath = \"\"): void => {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativeFilePath = path.join(relativePath, entry.name);\n\n if (entry.isDirectory()) {\n // Skip the .materialized directory\n if (fullPath === materializedDir) {\n continue;\n }\n walkDir(fullPath, relativeFilePath);\n } else if (entry.isFile() && entry.name.endsWith(\".prompt.yaml\")) {\n files.push(path.join(promptsDir, relativeFilePath));\n }\n }\n };\n\n walkDir(promptsDir);\n return files;\n }\n\n static promptNameFromPath(filePath: string): string {\n const promptsDir = this.getPromptsDir();\n const relativePath = path.relative(promptsDir, filePath);\n return relativePath.replace(/\\.prompt\\.yaml$/, \"\");\n }\n\n static cleanupOrphanedMaterializedFiles(currentDependencies: Set<string>): string[] {\n const materializedDir = this.getMaterializedDir();\n\n if (!fs.existsSync(materializedDir)) {\n return [];\n }\n\n const cleaned: string[] = [];\n\n const cleanupDir = (dir: string, relativePath = \"\"): void => {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativeFilePath = path.join(relativePath, entry.name);\n\n if (entry.isDirectory()) {\n cleanupDir(fullPath, relativeFilePath);\n\n // Remove empty directories\n try {\n const dirEntries = fs.readdirSync(fullPath);\n if (dirEntries.length === 0) {\n fs.rmdirSync(fullPath);\n }\n } catch {\n // Directory not empty or other error, ignore\n }\n } else if (entry.isFile() && entry.name.endsWith(\".prompt.yaml\")) {\n // Extract prompt name from materialized file path\n const promptName = relativeFilePath.replace(/\\.prompt\\.yaml$/, \"\");\n\n if (!currentDependencies.has(promptName)) {\n fs.unlinkSync(fullPath);\n cleaned.push(promptName);\n }\n }\n }\n };\n\n cleanupDir(materializedDir);\n return cleaned;\n }\n\n static updateLockEntry(lock: PromptsLock, name: string, prompt: MaterializedPrompt, materializedPath: string): void {\n const relativePath = path.relative(process.cwd(), materializedPath);\n\n lock.prompts[name] = {\n version: prompt.version,\n versionId: prompt.versionId,\n materialized: relativePath,\n };\n }\n\n static removeFromLock(lock: PromptsLock, names: string[]): void {\n for (const name of names) {\n delete lock.prompts[name];\n }\n }\n\n static addToGitignore(entry: string): { added: boolean; existed: boolean } {\n const gitignorePath = path.join(process.cwd(), \".gitignore\");\n\n // Check if .gitignore exists\n if (!fs.existsSync(gitignorePath)) {\n // Create new .gitignore with the entry\n fs.writeFileSync(gitignorePath, `${entry}\\n`);\n return { added: true, existed: false };\n }\n\n // Read existing .gitignore\n const content = fs.readFileSync(gitignorePath, \"utf-8\");\n const lines = content.split(\"\\n\").map(line => line.trim());\n\n // Check if entry already exists\n if (lines.includes(entry)) {\n return { added: false, existed: true };\n }\n\n // Add entry to .gitignore\n const newContent = content.endsWith(\"\\n\") ? `${content}${entry}\\n` : `${content}\\n${entry}\\n`;\n fs.writeFileSync(gitignorePath, newContent);\n\n return { added: true, existed: false };\n }\n}\n"]}
|