Debian Codegraph @

lib/mock/snapshot-recorder.js

raw symbols SCIP
1 'use strict'
2
3 const { writeFile, readFile, mkdir } = require('node:fs/promises')
4 const { dirname, resolve } = require('node:path')
5 const { setTimeout, clearTimeout } = require('node:timers')
6 const { InvalidArgumentError, UndiciError } = require('../core/errors')
7 const { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require('./snapshot-utils')
8
9 /**
10 * @typedef {Object} SnapshotRequestOptions
11 * @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.)
12 * @property {string} path - Request path
13 * @property {string} origin - Request origin (base URL)
14 * @property {import('./snapshot-utils').Headers|import('./snapshot-utils').UndiciHeaders} headers - Request headers
15 * @property {import('./snapshot-utils').NormalizedHeaders} _normalizedHeaders - Request headers as a lowercase object
16 * @property {string|Buffer} [body] - Request body (optional)
17 */
18
19 /**
20 * @typedef {Object} SnapshotEntryRequest
21 * @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.)
22 * @property {string} url - Full URL of the request
23 * @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized headers as a lowercase object
24 * @property {string|Buffer} [body] - Request body (optional)
25 */
26
27 /**
28 * @typedef {Object} SnapshotEntryResponse
29 * @property {number} statusCode - HTTP status code of the response
30 * @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized response headers as a lowercase object
31 * @property {string} body - Response body as a base64url encoded string
32 * @property {Object} [trailers] - Optional response trailers
33 */
34
35 /**
36 * @typedef {Object} SnapshotEntry
37 * @property {SnapshotEntryRequest} request - The request object
38 * @property {Array<SnapshotEntryResponse>} responses - Array of response objects
39 * @property {number} callCount - Number of times this snapshot has been called
40 * @property {string} timestamp - ISO timestamp of when the snapshot was created
41 */
42
43 /**
44 * @typedef {Object} SnapshotRecorderMatchOptions
45 * @property {Array<string>} [matchHeaders=[]] - Headers to match (empty array means match all headers)
46 * @property {Array<string>} [ignoreHeaders=[]] - Headers to ignore for matching
47 * @property {Array<string>} [excludeHeaders=[]] - Headers to exclude from matching
48 * @property {boolean} [matchBody=true] - Whether to match request body
49 * @property {(body: string|Buffer|null|undefined) => string} [normalizeBody] - Function to normalize the body before matching (e.g. strip timestamps)
50 * @property {boolean} [matchQuery=true] - Whether to match query parameters
51 * @property {(query: URLSearchParams) => string} [normalizeQuery] - Function to normalize query parameters before matching (e.g. strip volatile params)
52 * @property {boolean} [caseSensitive=false] - Whether header matching is case-sensitive
53 */
54
55 /**
56 * @typedef {Object} SnapshotRecorderOptions
57 * @property {string} [snapshotPath] - Path to save/load snapshots
58 * @property {import('./snapshot-utils').SnapshotMode} [mode='record'] - Mode: 'record' or 'playback'
59 * @property {number} [maxSnapshots=Infinity] - Maximum number of snapshots to keep
60 * @property {boolean} [autoFlush=false] - Whether to automatically flush snapshots to disk
61 * @property {number} [flushInterval=30000] - Auto-flush interval in milliseconds (default: 30 seconds)
62 * @property {Array<string|RegExp>} [excludeUrls=[]] - URLs to exclude from recording
63 * @property {function} [shouldRecord=null] - Function to filter requests for recording
64 * @property {function} [shouldPlayback=null] - Function to filter requests
65 */
66
67 /**
68 * @typedef {Object} SnapshotFormattedRequest
69 * @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.)
70 * @property {string} url - Full URL of the request (with query parameters if matchQuery is true)
71 * @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized headers as a lowercase object
72 * @property {string} body - Request body (optional, only if matchBody is true)
73 */
74
75 /**
76 * @typedef {Object} SnapshotInfo
77 * @property {string} hash - Hash key for the snapshot
78 * @property {SnapshotEntryRequest} request - The request object
79 * @property {number} responseCount - Number of responses recorded for this request
80 * @property {number} callCount - Number of times this snapshot has been called
81 * @property {string} timestamp - ISO timestamp of when the snapshot was created
82 */
83
84 /**
85 * Normalizes the URL string used for request matching.
86 *
87 * @param {URL} url - Parsed request URL
88 * @param {boolean} matchQuery - Whether to include query parameters in matching
89 * @param {((query: URLSearchParams) => string)|undefined} normalizeQuery - Optional normalization function
90 * @returns {string} - URL string for hashing
91 */
92 function normalizeUrlForMatching (url, matchQuery, normalizeQuery) {
93 if (matchQuery === false) return `${url.origin}${url.pathname}`
94 if (normalizeQuery) {
95 const normalized = String(normalizeQuery(url.searchParams) ?? '')
96 return normalized ? `${url.origin}${url.pathname}?${normalized}` : `${url.origin}${url.pathname}`
97 }
98 return url.toString()
99 }
100
101 /**
102 * Normalizes the body value used for request matching.
103 *
104 * @param {string|Buffer|null|undefined} body - Raw request body
105 * @param {boolean} matchBody - Whether to include the body in matching
106 * @param {((body: string|Buffer|null|undefined) => string)|undefined} normalizeBody - Optional normalization function
107 * @returns {string} - Body string for hashing
108 */
109 function normalizeBodyForMatching (body, matchBody, normalizeBody) {
110 if (matchBody === false) return ''
111 if (normalizeBody) return String(normalizeBody(body) ?? '')
112 return body ? String(body) : ''
113 }
114
115 /**
116 * Formats a request for consistent snapshot storage
117 * Caches normalized headers to avoid repeated processing
118 *
119 * @param {SnapshotRequestOptions} opts - Request options
120 * @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached header sets for performance
121 * @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers and body
122 * @returns {SnapshotFormattedRequest} - Formatted request object
123 */
124 function formatRequestKey (opts, headerFilters, matchOptions = {}) {
125 const url = new URL(opts.path, opts.origin)
126
127 // Cache normalized headers if not already done
128 const normalized = opts._normalizedHeaders || normalizeHeaders(opts.headers)
129 if (!opts._normalizedHeaders) {
130 opts._normalizedHeaders = normalized
131 }
132
133 return {
134 method: opts.method || 'GET',
135 url: normalizeUrlForMatching(url, matchOptions.matchQuery, matchOptions.normalizeQuery),
136 headers: filterHeadersForMatching(normalized, headerFilters, matchOptions),
137 body: normalizeBodyForMatching(opts.body, matchOptions.matchBody, matchOptions.normalizeBody)
138 }
139 }
140
141 /**
142 * Filters headers based on matching configuration
143 *
144 * @param {import('./snapshot-utils').Headers} headers - Headers to filter
145 * @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached sets for ignore, exclude, and match headers
146 * @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers
147 */
148 function filterHeadersForMatching (headers, headerFilters, matchOptions = {}) {
149 if (!headers || typeof headers !== 'object') return {}
150
151 const {
152 caseSensitive = false
153 } = matchOptions
154
155 const filtered = {}
156 const { ignore, exclude, match } = headerFilters
157
158 for (const [key, value] of Object.entries(headers)) {
159 const headerKey = caseSensitive ? key : key.toLowerCase()
160
161 // Skip if in exclude list (for security)
162 if (exclude.has(headerKey)) continue
163
164 // Skip if in ignore list (for matching)
165 if (ignore.has(headerKey)) continue
166
167 // If matchHeaders is specified, only include those headers
168 if (match.size !== 0) {
169 if (!match.has(headerKey)) continue
170 }
171
172 filtered[headerKey] = value
173 }
174
175 return filtered
176 }
177
178 /**
179 * Filters headers for storage (only excludes sensitive headers)
180 *
181 * @param {import('./snapshot-utils').Headers} headers - Headers to filter
182 * @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached sets for ignore, exclude, and match headers
183 * @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers
184 */
185 function filterHeadersForStorage (headers, headerFilters, matchOptions = {}) {
186 if (!headers || typeof headers !== 'object') return {}
187
188 const {
189 caseSensitive = false
190 } = matchOptions
191
192 const filtered = {}
193 const { exclude: excludeSet } = headerFilters
194
195 for (const [key, value] of Object.entries(headers)) {
196 const headerKey = caseSensitive ? key : key.toLowerCase()
197
198 // Skip if in exclude list (for security)
199 if (excludeSet.has(headerKey)) continue
200
201 filtered[headerKey] = value
202 }
203
204 return filtered
205 }
206
207 /**
208 * Creates a hash key for request matching
209 * Properly orders headers to avoid conflicts and uses crypto hashing when available
210 *
211 * @param {SnapshotFormattedRequest} formattedRequest - Request object
212 * @returns {string} - Base64url encoded hash of the request
213 */
214 function createRequestHash (formattedRequest) {
215 const parts = [
216 formattedRequest.method,
217 formattedRequest.url
218 ]
219
220 // Process headers in a deterministic way to avoid conflicts
221 if (formattedRequest.headers && typeof formattedRequest.headers === 'object') {
222 const headerKeys = Object.keys(formattedRequest.headers).sort()
223 for (const key of headerKeys) {
224 const values = Array.isArray(formattedRequest.headers[key])
225 ? formattedRequest.headers[key]
226 : [formattedRequest.headers[key]]
227
228 // Add header name
229 parts.push(key)
230
231 // Add all values for this header, sorted for consistency
232 for (const value of values.sort()) {
233 parts.push(String(value))
234 }
235 }
236 }
237
238 // Add body
239 parts.push(formattedRequest.body)
240
241 const content = parts.join('|')
242
243 return hashId(content)
244 }
245
246 class SnapshotRecorder {
247 /** @type {NodeJS.Timeout | null} */
248 #flushTimeout
249
250 /** @type {import('./snapshot-utils').IsUrlExcluded} */
251 #isUrlExcluded
252
253 /** @type {Map<string, SnapshotEntry>} */
254 #snapshots = new Map()
255
256 /** @type {string|undefined} */
257 #snapshotPath
258
259 /** @type {number} */
260 #maxSnapshots = Infinity
261
262 /** @type {boolean} */
263 #autoFlush = false
264
265 /** @type {import('./snapshot-utils').HeaderFilters} */
266 #headerFilters
267
268 /**
269 * Creates a new SnapshotRecorder instance
270 * @param {SnapshotRecorderOptions&SnapshotRecorderMatchOptions} [options={}] - Configuration options for the recorder
271 */
272 constructor (options = {}) {
273 this.#snapshotPath = options.snapshotPath
274 this.#maxSnapshots = options.maxSnapshots || Infinity
275 this.#autoFlush = options.autoFlush || false
276 this.flushInterval = options.flushInterval || 30000 // 30 seconds default
277 this._flushTimer = null
278
279 // Matching configuration
280 /** @type {Required<SnapshotRecorderMatchOptions>} */
281 this.matchOptions = {
282 matchHeaders: options.matchHeaders || [], // empty means match all headers
283 ignoreHeaders: options.ignoreHeaders || [],
284 excludeHeaders: options.excludeHeaders || [],
285 matchBody: options.matchBody !== false, // default: true
286 normalizeBody: options.normalizeBody || undefined,
287 matchQuery: options.matchQuery !== false, // default: true
288 normalizeQuery: options.normalizeQuery || undefined,
289 caseSensitive: options.caseSensitive || false
290 }
291
292 // Cache processed header sets to avoid recreating them on every request
293 this.#headerFilters = createHeaderFilters(this.matchOptions)
294
295 // Request filtering callbacks
296 this.shouldRecord = options.shouldRecord || (() => true) // function(requestOpts) -> boolean
297 this.shouldPlayback = options.shouldPlayback || (() => true) // function(requestOpts) -> boolean
298
299 // URL pattern filtering
300 this.#isUrlExcluded = isUrlExcludedFactory(options.excludeUrls) // Array of regex patterns or strings
301
302 // Start auto-flush timer if enabled
303 if (this.#autoFlush && this.#snapshotPath) {
304 this.#startAutoFlush()
305 }
306 }
307
308 /**
309 * Records a request-response interaction
310 * @param {SnapshotRequestOptions} requestOpts - Request options
311 * @param {SnapshotEntryResponse} response - Response data to record
312 * @return {Promise<void>} - Resolves when the recording is complete
313 */
314 async record (requestOpts, response) {
315 // Check if recording should be filtered out
316 if (!this.shouldRecord(requestOpts)) {
317 return // Skip recording
318 }
319
320 // Check URL exclusion patterns
321 if (this.isUrlExcluded(requestOpts)) {
322 return // Skip recording
323 }
324
325 const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions)
326 const hash = createRequestHash(request)
327
328 // Extract response data - always store body as base64
329 const normalizedHeaders = normalizeHeaders(response.headers)
330
331 /** @type {SnapshotEntryResponse} */
332 const responseData = {
333 statusCode: response.statusCode,
334 headers: filterHeadersForStorage(normalizedHeaders, this.#headerFilters, this.matchOptions),
335 body: Buffer.isBuffer(response.body)
336 ? response.body.toString('base64')
337 : Buffer.from(String(response.body || '')).toString('base64'),
338 trailers: response.trailers
339 }
340
341 // Remove oldest snapshot if we exceed maxSnapshots limit
342 if (this.#snapshots.size >= this.#maxSnapshots && !this.#snapshots.has(hash)) {
343 const oldestKey = this.#snapshots.keys().next().value
344 this.#snapshots.delete(oldestKey)
345 }
346
347 // Support sequential responses - if snapshot exists, add to responses array
348 const existingSnapshot = this.#snapshots.get(hash)
349 if (existingSnapshot && existingSnapshot.responses) {
350 existingSnapshot.responses.push(responseData)
351 existingSnapshot.timestamp = new Date().toISOString()
352 } else {
353 this.#snapshots.set(hash, {
354 request,
355 responses: [responseData], // Always store as array for consistency
356 callCount: 0,
357 timestamp: new Date().toISOString()
358 })
359 }
360
361 // Auto-flush if enabled
362 if (this.#autoFlush && this.#snapshotPath) {
363 this.#scheduleFlush()
364 }
365 }
366
367 /**
368 * Checks if a URL should be excluded from recording/playback
369 * @param {SnapshotRequestOptions} requestOpts - Request options to check
370 * @returns {boolean} - True if URL is excluded
371 */
372 isUrlExcluded (requestOpts) {
373 const url = new URL(requestOpts.path, requestOpts.origin).toString()
374 return this.#isUrlExcluded(url)
375 }
376
377 /**
378 * Finds a matching snapshot for the given request
379 * Returns the appropriate response based on call count for sequential responses
380 *
381 * @param {SnapshotRequestOptions} requestOpts - Request options to match
382 * @returns {SnapshotEntry&Record<'response', SnapshotEntryResponse>|undefined} - Matching snapshot response or undefined if not found
383 */
384 findSnapshot (requestOpts) {
385 // Check if playback should be filtered out
386 if (!this.shouldPlayback(requestOpts)) {
387 return undefined // Skip playback
388 }
389
390 // Check URL exclusion patterns
391 if (this.isUrlExcluded(requestOpts)) {
392 return undefined // Skip playback
393 }
394
395 const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions)
396 const hash = createRequestHash(request)
397 const snapshot = this.#snapshots.get(hash)
398
399 if (!snapshot) return undefined
400
401 // Handle sequential responses
402 const currentCallCount = snapshot.callCount || 0
403 const responseIndex = Math.min(currentCallCount, snapshot.responses.length - 1)
404 snapshot.callCount = currentCallCount + 1
405
406 return {
407 ...snapshot,
408 response: snapshot.responses[responseIndex]
409 }
410 }
411
412 /**
413 * Loads snapshots from file
414 * @param {string} [filePath] - Optional file path to load snapshots from
415 * @return {Promise<void>} - Resolves when snapshots are loaded
416 */
417 async loadSnapshots (filePath) {
418 const path = filePath || this.#snapshotPath
419 if (!path) {
420 throw new InvalidArgumentError('Snapshot path is required')
421 }
422
423 try {
424 const data = await readFile(resolve(path), 'utf8')
425 const parsed = JSON.parse(data)
426
427 // Convert array format back to Map
428 if (Array.isArray(parsed)) {
429 this.#snapshots.clear()
430 for (const { hash, snapshot } of parsed) {
431 this.#snapshots.set(hash, snapshot)
432 }
433 } else {
434 // Legacy object format
435 this.#snapshots = new Map(Object.entries(parsed))
436 }
437 } catch (error) {
438 if (error.code === 'ENOENT') {
439 // File doesn't exist yet - that's ok for recording mode
440 this.#snapshots.clear()
441 } else {
442 throw new UndiciError(`Failed to load snapshots from ${path}`, { cause: error })
443 }
444 }
445 }
446
447 /**
448 * Saves snapshots to file
449 *
450 * @param {string} [filePath] - Optional file path to save snapshots
451 * @returns {Promise<void>} - Resolves when snapshots are saved
452 */
453 async saveSnapshots (filePath) {
454 const path = filePath || this.#snapshotPath
455 if (!path) {
456 throw new InvalidArgumentError('Snapshot path is required')
457 }
458
459 const resolvedPath = resolve(path)
460
461 // Ensure directory exists
462 await mkdir(dirname(resolvedPath), { recursive: true })
463
464 // Convert Map to serializable format
465 const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
466 hash,
467 snapshot
468 }))
469
470 await writeFile(resolvedPath, JSON.stringify(data, null, 2), { flush: true })
471 }
472
473 /**
474 * Clears all recorded snapshots
475 * @returns {void}
476 */
477 clear () {
478 this.#snapshots.clear()
479 }
480
481 /**
482 * Gets all recorded snapshots
483 * @return {Array<SnapshotEntry>} - Array of all recorded snapshots
484 */
485 getSnapshots () {
486 return Array.from(this.#snapshots.values())
487 }
488
489 /**
490 * Gets snapshot count
491 * @return {number} - Number of recorded snapshots
492 */
493 size () {
494 return this.#snapshots.size
495 }
496
497 /**
498 * Resets call counts for all snapshots (useful for test cleanup)
499 * @returns {void}
500 */
501 resetCallCounts () {
502 for (const snapshot of this.#snapshots.values()) {
503 snapshot.callCount = 0
504 }
505 }
506
507 /**
508 * Deletes a specific snapshot by request options
509 * @param {SnapshotRequestOptions} requestOpts - Request options to match
510 * @returns {boolean} - True if snapshot was deleted, false if not found
511 */
512 deleteSnapshot (requestOpts) {
513 const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions)
514 const hash = createRequestHash(request)
515 return this.#snapshots.delete(hash)
516 }
517
518 /**
519 * Gets information about a specific snapshot
520 * @param {SnapshotRequestOptions} requestOpts - Request options to match
521 * @returns {SnapshotInfo|null} - Snapshot information or null if not found
522 */
523 getSnapshotInfo (requestOpts) {
524 const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions)
525 const hash = createRequestHash(request)
526 const snapshot = this.#snapshots.get(hash)
527
528 if (!snapshot) return null
529
530 return {
531 hash,
532 request: snapshot.request,
533 responseCount: snapshot.responses ? snapshot.responses.length : (snapshot.response ? 1 : 0), // .response for legacy snapshots
534 callCount: snapshot.callCount || 0,
535 timestamp: snapshot.timestamp
536 }
537 }
538
539 /**
540 * Replaces all snapshots with new data (full replacement)
541 * @param {Array<{hash: string; snapshot: SnapshotEntry}>|Record<string, SnapshotEntry>} snapshotData - New snapshot data to replace existing ones
542 * @returns {void}
543 */
544 replaceSnapshots (snapshotData) {
545 this.#snapshots.clear()
546
547 if (Array.isArray(snapshotData)) {
548 for (const { hash, snapshot } of snapshotData) {
549 this.#snapshots.set(hash, snapshot)
550 }
551 } else if (snapshotData && typeof snapshotData === 'object') {
552 // Legacy object format
553 this.#snapshots = new Map(Object.entries(snapshotData))
554 }
555 }
556
557 /**
558 * Starts the auto-flush timer
559 * @returns {void}
560 */
561 #startAutoFlush () {
562 return this.#scheduleFlush()
563 }
564
565 /**
566 * Stops the auto-flush timer
567 * @returns {void}
568 */
569 #stopAutoFlush () {
570 if (this.#flushTimeout) {
571 clearTimeout(this.#flushTimeout)
572 // Ensure any pending flush is completed
573 this.saveSnapshots().catch(() => {
574 // Ignore flush errors
575 })
576 this.#flushTimeout = null
577 }
578 }
579
580 /**
581 * Schedules a flush (debounced to avoid excessive writes)
582 */
583 #scheduleFlush () {
584 this.#flushTimeout = setTimeout(() => {
585 this.saveSnapshots().catch(() => {
586 // Ignore flush errors
587 })
588 if (this.#autoFlush) {
589 this.#flushTimeout?.refresh()
590 } else {
591 this.#flushTimeout = null
592 }
593 }, 1000) // 1 second debounce
594 }
595
596 /**
597 * Cleanup method to stop timers
598 * @returns {void}
599 */
600 destroy () {
601 this.#stopAutoFlush()
602 if (this.#flushTimeout) {
603 clearTimeout(this.#flushTimeout)
604 this.#flushTimeout = null
605 }
606 }
607
608 /**
609 * Async close method that saves all recordings and performs cleanup
610 * @returns {Promise<void>}
611 */
612 async close () {
613 // Save any pending recordings if we have a snapshot path
614 if (this.#snapshotPath && this.#snapshots.size !== 0) {
615 await this.saveSnapshots()
616 }
617
618 // Perform cleanup
619 this.destroy()
620 }
621 }
622
623 module.exports = { SnapshotRecorder, formatRequestKey, createRequestHash, filterHeadersForMatching, filterHeadersForStorage, createHeaderFilters }