( messages: Message[], f: () => Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]>, )
| 87 | } |
| 88 | |
| 89 | export async function withVCR( |
| 90 | messages: Message[], |
| 91 | f: () => Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]>, |
| 92 | ): Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]> { |
| 93 | if (!shouldUseVCR()) { |
| 94 | return await f() |
| 95 | } |
| 96 | |
| 97 | const messagesForAPI = normalizeMessagesForAPI( |
| 98 | messages.filter(_ => { |
| 99 | if (_.type !== 'user') { |
| 100 | return true |
| 101 | } |
| 102 | if (_.isMeta) { |
| 103 | return false |
| 104 | } |
| 105 | return true |
| 106 | }), |
| 107 | ) |
| 108 | |
| 109 | const dehydratedInput = mapMessages( |
| 110 | messagesForAPI.map(_ => _.message.content), |
| 111 | dehydrateValue, |
| 112 | ) |
| 113 | const filename = join( |
| 114 | process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT ?? getCwd(), |
| 115 | `fixtures/${dehydratedInput.map(_ => createHash('sha1').update(jsonStringify(_)).digest('hex').slice(0, 6)).join('-')}.json`, |
| 116 | ) |
| 117 | |
| 118 | // Fetch cached fixture |
| 119 | try { |
| 120 | const cached = jsonParse( |
| 121 | await readFile(filename, { encoding: 'utf8' }), |
| 122 | ) as { output: (AssistantMessage | StreamEvent)[] } |
| 123 | cached.output.forEach(addCachedCostToTotalSessionCost) |
| 124 | return cached.output.map((message, index) => |
| 125 | mapMessage(message, hydrateValue, index, randomUUID()), |
| 126 | ) |
| 127 | } catch (e: unknown) { |
| 128 | const code = getErrnoCode(e) |
| 129 | if (code !== 'ENOENT') { |
| 130 | throw e |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | if (env.isCI && !isEnvTruthy(process.env.VCR_RECORD)) { |
| 135 | throw new Error( |
| 136 | `Anthropic API fixture missing: ${filename}. Re-run tests with VCR_RECORD=1, then commit the result. Input messages:\n${jsonStringify(dehydratedInput, null, 2)}`, |
| 137 | ) |
| 138 | } |
| 139 | |
| 140 | // Create & write new fixture |
| 141 | const results = await f() |
| 142 | if (env.isCI && !isEnvTruthy(process.env.VCR_RECORD)) { |
| 143 | return results |
| 144 | } |
| 145 | |
| 146 | await mkdir(dirname(filename), { recursive: true }) |
no test coverage detected