MCPcopy Create free account
hub / github.com/Noumena-Network/code / withVCR

Function withVCR

src/services/vcr.ts:89–162  ·  view source on GitHub ↗
(
  messages: Message[],
  f: () => Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]>,
)

Source from the content-addressed store, hash-verified

87}
88
89export 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 })

Callers 3

withStreamingVCRFunction · 0.85
queryHaikuFunction · 0.85
queryWithModelFunction · 0.85

Calls 13

randomUUIDFunction · 0.90
isEnvTruthyFunction · 0.90
shouldUseVCRFunction · 0.85
fFunction · 0.85
normalizeMessagesForAPIFunction · 0.85
mapMessagesFunction · 0.85
getCwdFunction · 0.85
jsonStringifyFunction · 0.85
jsonParseFunction · 0.85
readFileFunction · 0.85
mapMessageFunction · 0.85
getErrnoCodeFunction · 0.85

Tested by

no test coverage detected