@copilotkit/aimock 1.43.0 → 1.44.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +15 -0
- package/README.md +8 -2
- package/dist/agui-handler.d.ts.map +1 -1
- package/dist/agui-types.d.ts.map +1 -1
- package/dist/bedrock-converse.cjs +32 -4
- package/dist/bedrock-converse.cjs.map +1 -1
- package/dist/bedrock-converse.d.cts.map +1 -1
- package/dist/bedrock-converse.d.ts.map +1 -1
- package/dist/bedrock-converse.js +32 -4
- package/dist/bedrock-converse.js.map +1 -1
- package/dist/chaos.cjs +8 -5
- package/dist/chaos.cjs.map +1 -1
- package/dist/chaos.d.cts.map +1 -1
- package/dist/chaos.d.ts.map +1 -1
- package/dist/chaos.js +9 -6
- package/dist/chaos.js.map +1 -1
- package/dist/cli.cjs +89 -7
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +91 -9
- package/dist/cli.js.map +1 -1
- package/dist/cohere.cjs +27 -1
- package/dist/cohere.cjs.map +1 -1
- package/dist/cohere.js +27 -1
- package/dist/cohere.js.map +1 -1
- package/dist/config-loader.cjs +1 -1
- package/dist/config-loader.d.ts.map +1 -1
- package/dist/config-loader.js +1 -1
- package/dist/constants.cjs +8 -0
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +6 -2
- package/dist/constants.d.ts +6 -2
- package/dist/constants.js +8 -1
- package/dist/constants.js.map +1 -1
- package/dist/echo-text.cjs +65 -0
- package/dist/echo-text.cjs.map +1 -0
- package/dist/echo-text.d.cts +22 -0
- package/dist/echo-text.d.cts.map +1 -0
- package/dist/echo-text.d.ts +22 -0
- package/dist/echo-text.d.ts.map +1 -0
- package/dist/echo-text.js +65 -0
- package/dist/echo-text.js.map +1 -0
- package/dist/embeddings.cjs +18 -1
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.d.cts +1 -1
- package/dist/embeddings.d.cts.map +1 -1
- package/dist/embeddings.d.ts +1 -1
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/embeddings.js +18 -1
- package/dist/embeddings.js.map +1 -1
- package/dist/files.cjs +9 -11
- package/dist/files.cjs.map +1 -1
- package/dist/files.d.cts.map +1 -1
- package/dist/files.d.ts.map +1 -1
- package/dist/files.js +10 -13
- package/dist/files.js.map +1 -1
- package/dist/fine-tuning.cjs +1 -19
- package/dist/fine-tuning.cjs.map +1 -1
- package/dist/fine-tuning.d.cts.map +1 -1
- package/dist/fine-tuning.d.ts.map +1 -1
- package/dist/fine-tuning.js +2 -20
- package/dist/fine-tuning.js.map +1 -1
- package/dist/fixture-loader-services.cjs +116 -0
- package/dist/fixture-loader-services.cjs.map +1 -0
- package/dist/fixture-loader-services.d.cts +48 -0
- package/dist/fixture-loader-services.d.cts.map +1 -0
- package/dist/fixture-loader-services.d.ts +48 -0
- package/dist/fixture-loader-services.d.ts.map +1 -0
- package/dist/fixture-loader-services.js +114 -0
- package/dist/fixture-loader-services.js.map +1 -0
- package/dist/fixture-loader.cjs +172 -11
- package/dist/fixture-loader.cjs.map +1 -1
- package/dist/fixture-loader.d.cts +95 -1
- package/dist/fixture-loader.d.cts.map +1 -1
- package/dist/fixture-loader.d.ts +95 -1
- package/dist/fixture-loader.d.ts.map +1 -1
- package/dist/fixture-loader.js +168 -12
- package/dist/fixture-loader.js.map +1 -1
- package/dist/gemini-embeddings.cjs +42 -2
- package/dist/gemini-embeddings.cjs.map +1 -1
- package/dist/gemini-embeddings.js +43 -3
- package/dist/gemini-embeddings.js.map +1 -1
- package/dist/gemini-interactions.cjs +38 -0
- package/dist/gemini-interactions.cjs.map +1 -1
- package/dist/gemini-interactions.d.cts.map +1 -1
- package/dist/gemini-interactions.d.ts.map +1 -1
- package/dist/gemini-interactions.js +38 -0
- package/dist/gemini-interactions.js.map +1 -1
- package/dist/gemini.cjs +8 -1
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.d.cts.map +1 -1
- package/dist/gemini.d.ts.map +1 -1
- package/dist/gemini.js +8 -1
- package/dist/gemini.js.map +1 -1
- package/dist/helpers.cjs +276 -5
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +275 -7
- package/dist/helpers.js.map +1 -1
- package/dist/images.cjs +3 -2
- package/dist/images.cjs.map +1 -1
- package/dist/images.js +3 -2
- package/dist/images.js.map +1 -1
- package/dist/index.cjs +30 -1
- package/dist/index.d.cts +8 -3
- package/dist/index.d.ts +8 -3
- package/dist/index.js +9 -3
- package/dist/jest.cjs +15 -10
- package/dist/jest.cjs.map +1 -1
- package/dist/jest.d.cts +4 -2
- package/dist/jest.d.cts.map +1 -1
- package/dist/jest.d.ts +4 -2
- package/dist/jest.d.ts.map +1 -1
- package/dist/jest.js +16 -11
- package/dist/jest.js.map +1 -1
- package/dist/journal.cjs +20 -0
- package/dist/journal.cjs.map +1 -1
- package/dist/journal.d.cts +16 -0
- package/dist/journal.d.cts.map +1 -1
- package/dist/journal.d.ts +16 -0
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +20 -0
- package/dist/journal.js.map +1 -1
- package/dist/llmock.cjs +82 -10
- package/dist/llmock.cjs.map +1 -1
- package/dist/llmock.d.cts +35 -0
- package/dist/llmock.d.cts.map +1 -1
- package/dist/llmock.d.ts +35 -0
- package/dist/llmock.d.ts.map +1 -1
- package/dist/llmock.js +83 -11
- package/dist/llmock.js.map +1 -1
- package/dist/mcp-fakes-mount.cjs +216 -0
- package/dist/mcp-fakes-mount.cjs.map +1 -0
- package/dist/mcp-fakes-mount.js +210 -0
- package/dist/mcp-fakes-mount.js.map +1 -0
- package/dist/mcp-fakes.cjs +1619 -0
- package/dist/mcp-fakes.cjs.map +1 -0
- package/dist/mcp-fakes.d.cts +101 -0
- package/dist/mcp-fakes.d.cts.map +1 -0
- package/dist/mcp-fakes.d.ts +101 -0
- package/dist/mcp-fakes.d.ts.map +1 -0
- package/dist/mcp-fakes.js +1614 -0
- package/dist/mcp-fakes.js.map +1 -0
- package/dist/mcp-handler.cjs +331 -17
- package/dist/mcp-handler.cjs.map +1 -1
- package/dist/mcp-handler.js +330 -18
- package/dist/mcp-handler.js.map +1 -1
- package/dist/mcp-mock.cjs +217 -49
- package/dist/mcp-mock.cjs.map +1 -1
- package/dist/mcp-mock.d.cts +66 -1
- package/dist/mcp-mock.d.cts.map +1 -1
- package/dist/mcp-mock.d.ts +66 -1
- package/dist/mcp-mock.d.ts.map +1 -1
- package/dist/mcp-mock.js +218 -50
- package/dist/mcp-mock.js.map +1 -1
- package/dist/mcp-stub.cjs +5 -1
- package/dist/mcp-stub.d.cts +3 -1
- package/dist/mcp-stub.d.ts +3 -1
- package/dist/mcp-stub.js +3 -1
- package/dist/mcp-types.d.cts +6 -0
- package/dist/mcp-types.d.ts +6 -0
- package/dist/message-text.cjs +192 -0
- package/dist/message-text.cjs.map +1 -0
- package/dist/message-text.d.cts +31 -0
- package/dist/message-text.d.cts.map +1 -0
- package/dist/message-text.d.ts +31 -0
- package/dist/message-text.d.ts.map +1 -0
- package/dist/message-text.js +184 -0
- package/dist/message-text.js.map +1 -0
- package/dist/messages.cjs +38 -0
- package/dist/messages.cjs.map +1 -1
- package/dist/messages.js +38 -0
- package/dist/messages.js.map +1 -1
- package/dist/metrics.cjs +46 -66
- package/dist/metrics.cjs.map +1 -1
- package/dist/metrics.d.cts +14 -6
- package/dist/metrics.d.cts.map +1 -1
- package/dist/metrics.d.ts +14 -6
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js +32 -40
- package/dist/metrics.js.map +1 -1
- package/dist/ollama.cjs +5 -1
- package/dist/ollama.cjs.map +1 -1
- package/dist/ollama.d.cts.map +1 -1
- package/dist/ollama.d.ts.map +1 -1
- package/dist/ollama.js +5 -1
- package/dist/ollama.js.map +1 -1
- package/dist/openapi.cjs +3405 -0
- package/dist/openapi.cjs.map +1 -0
- package/dist/openapi.d.cts +30 -0
- package/dist/openapi.d.cts.map +1 -0
- package/dist/openapi.d.ts +30 -0
- package/dist/openapi.d.ts.map +1 -0
- package/dist/openapi.js +3404 -0
- package/dist/openapi.js.map +1 -0
- package/dist/openrouter-video.cjs +4 -4
- package/dist/openrouter-video.cjs.map +1 -1
- package/dist/openrouter-video.d.cts.map +1 -1
- package/dist/openrouter-video.d.ts.map +1 -1
- package/dist/openrouter-video.js +4 -4
- package/dist/openrouter-video.js.map +1 -1
- package/dist/recorder.cjs +9 -1
- package/dist/recorder.cjs.map +1 -1
- package/dist/recorder.d.cts.map +1 -1
- package/dist/recorder.d.ts.map +1 -1
- package/dist/recorder.js +9 -1
- package/dist/recorder.js.map +1 -1
- package/dist/responses.cjs +43 -4
- package/dist/responses.cjs.map +1 -1
- package/dist/responses.d.cts.map +1 -1
- package/dist/responses.d.ts.map +1 -1
- package/dist/responses.js +43 -4
- package/dist/responses.js.map +1 -1
- package/dist/route-registry.cjs +951 -0
- package/dist/route-registry.cjs.map +1 -0
- package/dist/route-registry.d.cts +33 -0
- package/dist/route-registry.d.cts.map +1 -0
- package/dist/route-registry.d.ts +33 -0
- package/dist/route-registry.d.ts.map +1 -0
- package/dist/route-registry.js +866 -0
- package/dist/route-registry.js.map +1 -0
- package/dist/router.cjs +1 -1
- package/dist/router.cjs.map +1 -1
- package/dist/router.js +1 -1
- package/dist/router.js.map +1 -1
- package/dist/server.cjs +590 -191
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +4 -1
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.ts +4 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +498 -99
- package/dist/server.js.map +1 -1
- package/dist/speech.cjs +4 -2
- package/dist/speech.cjs.map +1 -1
- package/dist/speech.js +4 -2
- package/dist/speech.js.map +1 -1
- package/dist/suite.cjs +1 -1
- package/dist/suite.js +1 -1
- package/dist/transcription.cjs +2 -2
- package/dist/transcription.cjs.map +1 -1
- package/dist/transcription.d.cts.map +1 -1
- package/dist/transcription.d.ts.map +1 -1
- package/dist/transcription.js +2 -2
- package/dist/transcription.js.map +1 -1
- package/dist/types.cjs +18 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +202 -2
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +202 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +17 -0
- package/dist/types.js.map +1 -0
- package/dist/validate-cli.cjs +89 -31
- package/dist/validate-cli.cjs.map +1 -1
- package/dist/validate-cli.js +91 -33
- package/dist/validate-cli.js.map +1 -1
- package/dist/vector-stores.cjs +1180 -0
- package/dist/vector-stores.cjs.map +1 -0
- package/dist/vector-stores.d.cts +106 -0
- package/dist/vector-stores.d.cts.map +1 -0
- package/dist/vector-stores.d.ts +106 -0
- package/dist/vector-stores.d.ts.map +1 -0
- package/dist/vector-stores.js +1164 -0
- package/dist/vector-stores.js.map +1 -0
- package/dist/vector-types.d.cts.map +1 -1
- package/dist/vector-types.d.ts.map +1 -1
- package/dist/video.cjs +19 -0
- package/dist/video.cjs.map +1 -1
- package/dist/video.d.cts.map +1 -1
- package/dist/video.d.ts.map +1 -1
- package/dist/video.js +19 -0
- package/dist/video.js.map +1 -1
- package/dist/vitest.cjs +15 -10
- package/dist/vitest.cjs.map +1 -1
- package/dist/vitest.d.cts +4 -2
- package/dist/vitest.d.cts.map +1 -1
- package/dist/vitest.d.ts +4 -2
- package/dist/vitest.d.ts.map +1 -1
- package/dist/vitest.js +16 -11
- package/dist/vitest.js.map +1 -1
- package/dist/ws-gemini-live.d.ts +2 -2
- package/dist/ws-realtime.d.ts +2 -2
- package/dist/ws-responses.cjs +14 -2
- package/dist/ws-responses.cjs.map +1 -1
- package/dist/ws-responses.js +14 -2
- package/dist/ws-responses.js.map +1 -1
- package/package.json +4 -1
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { A2AMock } from "./a2a-mock.js";
|
|
|
5
5
|
import { buildActivityDelta, buildActivityResponse, buildCompositeResponse, buildCustomEvent, buildErrorResponse, buildMessagesSnapshot, buildRawEvent, buildReasoningChunk, buildReasoningEncryptedValue, buildReasoningResponse, buildStateDelta, buildStateUpdate, buildStepWithText, buildTextChunkResponse, buildTextResponse, buildToolCallChunk, buildToolCallResponse, extractLastUserMessage, findFixture, getLastMessageIfToolResult, matchesFixture, writeAGUIEventStream } from "./agui-handler.js";
|
|
6
6
|
import { calculateDelay, delay, writeErrorResponse, writeSSEStream } from "./sse-writer.js";
|
|
7
7
|
import { applyChaosAsync, applyChaosDeprecated, evaluateChaos, resolveChaosLatencyMs } from "./chaos.js";
|
|
8
|
-
import { loadFixtureFile, loadFixturesFromDir, normalizeResponse, renderValidationRef, validateFixtures } from "./fixture-loader.js";
|
|
8
|
+
import { FixtureLoadError, loadFixtureFile, loadFixturesFromDir, normalizeResponse, renderValidationRef, validateFixtures } from "./fixture-loader.js";
|
|
9
9
|
import { getTextContent, matchFixture, matchFixtureDiagnostic } from "./router.js";
|
|
10
10
|
import { MAX_COLLAPSE_STRING_LENGTH, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, setCollapseStringLimitForTests } from "./stream-collapse.js";
|
|
11
11
|
import { resolveUpstreamUrl } from "./url.js";
|
|
@@ -42,18 +42,24 @@ import { handleSearch } from "./search.js";
|
|
|
42
42
|
import { handleRerank } from "./rerank.js";
|
|
43
43
|
import { handleModeration } from "./moderation.js";
|
|
44
44
|
import { clearFineTuningStore, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve } from "./fine-tuning.js";
|
|
45
|
+
import { clearVectorStoreStore, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch } from "./vector-stores.js";
|
|
45
46
|
import { clearFileStore, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve } from "./files.js";
|
|
46
47
|
import { clearBatchStore, handleBatchesCancel, handleBatchesCreate, handleBatchesList, handleBatchesRetrieve } from "./batches.js";
|
|
47
48
|
import { WebSocketConnection, computeAcceptKey, upgradeToWebSocket } from "./ws-framing.js";
|
|
48
49
|
import { handleWebSocketResponses } from "./ws-responses.js";
|
|
49
50
|
import { handleWebSocketRealtime } from "./ws-realtime.js";
|
|
50
51
|
import { handleWebSocketGeminiLive } from "./ws-gemini-live.js";
|
|
52
|
+
import { ROUTE_DEFINITIONS } from "./route-registry.js";
|
|
53
|
+
import { CATALOG_ROUTES, buildOpenApiDocument } from "./openapi.js";
|
|
51
54
|
import { createMetricsRegistry, normalizePathLabel } from "./metrics.js";
|
|
55
|
+
import { MCP_FAKE_ERROR_CODES } from "./types.js";
|
|
56
|
+
import { McpFakesAddError } from "./mcp-fakes.js";
|
|
57
|
+
import { MCPMock } from "./mcp-mock.js";
|
|
52
58
|
import { createServer } from "./server.js";
|
|
59
|
+
import { loadFixtureFileWithServices, loadFixturesFromDirWithServices } from "./fixture-loader-services.js";
|
|
53
60
|
import { LLMock } from "./llmock.js";
|
|
54
|
-
import { MCPMock } from "./mcp-mock.js";
|
|
55
61
|
import { VectorMock } from "./vector-mock.js";
|
|
56
62
|
import { loadConfig, startFromConfig } from "./config-loader.js";
|
|
57
63
|
import { createMockSuite } from "./suite.js";
|
|
58
64
|
|
|
59
|
-
export { A2AMock, AGUIMock, AGUI_RECORD_BUFFER_HARD_CEILING, BYTEPLUS_VIDEO_MAX_ENTRIES, BYTEPLUS_VIDEO_TASKS_PATH, BytePlusVideoJobMap, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, Journal, LLMock, Logger, MAX_COLLAPSE_STRING_LENGTH, MCPMock, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, VEO_VIDEO_MAX_ENTRIES, VectorMock, VeoVideoJobMap, VideoStateMap, WebSocketConnection, applyChaosDeprecated as applyChaos, applyChaosAsync, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildBytePlusMatchText, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, clearBatchStore, clearElevenLabsVoices, clearFileStore, clearFineTuningStore, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBatchesCancel, handleBatchesCreate, handleBatchesList, handleBatchesRetrieve, handleBedrock, handleBedrockStream, handleBytePlusVideoCreate, handleBytePlusVideoStatus, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, handleEmbeddings, handleFal, handleFalQueue, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isChatCompletionBody, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixturesFromDir, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, renderValidationRef, resolveChaosLatencyMs, resolveFixtureBlocks, resolveRequestId, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, voiceDesignToJson, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
|
|
65
|
+
export { A2AMock, AGUIMock, AGUI_RECORD_BUFFER_HARD_CEILING, BYTEPLUS_VIDEO_MAX_ENTRIES, BYTEPLUS_VIDEO_TASKS_PATH, BytePlusVideoJobMap, CATALOG_ROUTES, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, FixtureLoadError, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, Journal, LLMock, Logger, MAX_COLLAPSE_STRING_LENGTH, MCPMock, MCP_FAKE_ERROR_CODES, McpFakesAddError, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, ROUTE_DEFINITIONS, VEO_VIDEO_MAX_ENTRIES, VectorMock, VeoVideoJobMap, VideoStateMap, WebSocketConnection, applyChaosDeprecated as applyChaos, applyChaosAsync, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildBytePlusMatchText, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildOpenApiDocument, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, clearBatchStore, clearElevenLabsVoices, clearFileStore, clearFineTuningStore, clearVectorStoreStore, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBatchesCancel, handleBatchesCreate, handleBatchesList, handleBatchesRetrieve, handleBedrock, handleBedrockStream, handleBytePlusVideoCreate, handleBytePlusVideoStatus, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, handleEmbeddings, handleFal, handleFalQueue, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isChatCompletionBody, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixtureFileWithServices, loadFixturesFromDir, loadFixturesFromDirWithServices, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, renderValidationRef, resolveChaosLatencyMs, resolveFixtureBlocks, resolveRequestId, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, voiceDesignToJson, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
|
package/dist/jest.cjs
CHANGED
|
@@ -9,8 +9,10 @@ let node_path = require("node:path");
|
|
|
9
9
|
/**
|
|
10
10
|
* Start an aimock server for the duration of the test suite.
|
|
11
11
|
*
|
|
12
|
-
* - `beforeAll`: starts the server and optionally loads fixtures
|
|
13
|
-
*
|
|
12
|
+
* - `beforeAll`: starts the server and optionally loads fixtures (LLM fixtures and
|
|
13
|
+
* `mcpFakes` blocks; a bad `mcpFakes` block fails `beforeAll`)
|
|
14
|
+
* - `beforeEach`: closes Live sessions and resets fixture match counts and MCP fake
|
|
15
|
+
* consumption (not fixtures or fakes)
|
|
14
16
|
* - `afterEach`: closes Live sessions owned by this helper's server
|
|
15
17
|
* - `afterAll`: stops the server
|
|
16
18
|
*
|
|
@@ -26,10 +28,7 @@ function useAimock(options = {}) {
|
|
|
26
28
|
beforeAll(async () => {
|
|
27
29
|
const { fixtures: fixturePath, patchEnv, ...serverOpts } = options;
|
|
28
30
|
const llm = new require_llmock.LLMock(serverOpts);
|
|
29
|
-
if (fixturePath)
|
|
30
|
-
const loadedFixtures = loadFixtures((0, node_path.resolve)(fixturePath), options.live);
|
|
31
|
-
for (const f of loadedFixtures) llm.addFixture(f);
|
|
32
|
-
}
|
|
31
|
+
if (fixturePath) loadFixtures(llm, (0, node_path.resolve)(fixturePath));
|
|
33
32
|
const url = await llm.start();
|
|
34
33
|
if (patchEnv !== false) {
|
|
35
34
|
origOpenaiUrl = process.env.OPENAI_BASE_URL;
|
|
@@ -68,13 +67,19 @@ function useAimock(options = {}) {
|
|
|
68
67
|
return handle;
|
|
69
68
|
};
|
|
70
69
|
}
|
|
71
|
-
|
|
70
|
+
/**
|
|
71
|
+
* Load a fixture file or directory into `llm`: its LLM fixtures and its
|
|
72
|
+
* `mcpFakes` blocks, which the LLMock buffers and auto-mounts at start (F12).
|
|
73
|
+
* A `FixtureLoadError` (a bad `mcpFakes` block) propagates and fails
|
|
74
|
+
* `beforeAll`; any other load failure is only warned about, as before.
|
|
75
|
+
*/
|
|
76
|
+
function loadFixtures(llm, fixturePath) {
|
|
72
77
|
try {
|
|
73
|
-
if ((0, node_fs.statSync)(fixturePath).isDirectory())
|
|
74
|
-
|
|
78
|
+
if ((0, node_fs.statSync)(fixturePath).isDirectory()) llm.loadFixtureDir(fixturePath);
|
|
79
|
+
else llm.loadFixtureFile(fixturePath);
|
|
75
80
|
} catch (err) {
|
|
81
|
+
if (err instanceof require_fixture_loader.FixtureLoadError) throw err;
|
|
76
82
|
console.warn(`[aimock] Failed to load fixtures from ${fixturePath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
77
|
-
return [];
|
|
78
83
|
}
|
|
79
84
|
}
|
|
80
85
|
|
package/dist/jest.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jest.cjs","names":["LLMock","
|
|
1
|
+
{"version":3,"file":"jest.cjs","names":["LLMock","FixtureLoadError"],"sources":["../src/jest.ts"],"sourcesContent":["/**\n * Jest integration for aimock.\n *\n * Usage:\n * import { useAimock } from \"@copilotkit/aimock/jest\";\n *\n * const mock = useAimock({ fixtures: \"./fixtures\" });\n *\n * it(\"responds\", async () => {\n * const res = await fetch(`${mock().url}/v1/chat/completions`, { ... });\n * });\n */\n\n/* eslint-disable no-var */\n// Jest globals — available at runtime in jest test files\ndeclare var beforeAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var beforeEach: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterEach: (fn: () => Promise<void> | void, timeout?: number) => void;\n/* eslint-enable no-var */\n\nimport { LLMock } from \"./llmock.js\";\nimport { FixtureLoadError } from \"./fixture-loader.js\";\nimport type { MockServerOptions } from \"./types.js\";\nimport { statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nexport interface UseAimockOptions extends MockServerOptions {\n /** Path to fixture file or directory. Loaded automatically on start. */\n fixtures?: string;\n /** If true, sets process.env.OPENAI_BASE_URL to the mock URL + /v1. */\n patchEnv?: boolean;\n}\n\nexport interface AimockHandle {\n /** The LLMock instance. */\n readonly llm: LLMock;\n /** The server URL (e.g., http://127.0.0.1:4010). */\n readonly url: string;\n}\n\n/**\n * Start an aimock server for the duration of the test suite.\n *\n * - `beforeAll`: starts the server and optionally loads fixtures (LLM fixtures and\n * `mcpFakes` blocks; a bad `mcpFakes` block fails `beforeAll`)\n * - `beforeEach`: closes Live sessions and resets fixture match counts and MCP fake\n * consumption (not fixtures or fakes)\n * - `afterEach`: closes Live sessions owned by this helper's server\n * - `afterAll`: stops the server\n *\n * Returns a getter function — call it inside tests to access the handle.\n *\n * NOTE: Jest globals (beforeAll, afterAll, beforeEach, afterEach) must be available\n * in the test environment. This works with the default jest configuration.\n */\nexport function useAimock(options: UseAimockOptions = {}): () => AimockHandle {\n let handle: AimockHandle | null = null;\n let origOpenaiUrl: string | undefined;\n let origAnthropicUrl: string | undefined;\n\n beforeAll(async () => {\n const { fixtures: fixturePath, patchEnv, ...serverOpts } = options;\n const llm = new LLMock(serverOpts);\n\n if (fixturePath) {\n loadFixtures(llm, resolve(fixturePath));\n }\n\n const url = await llm.start();\n\n if (patchEnv !== false) {\n origOpenaiUrl = process.env.OPENAI_BASE_URL;\n origAnthropicUrl = process.env.ANTHROPIC_BASE_URL;\n process.env.OPENAI_BASE_URL = `${url}/v1`;\n process.env.ANTHROPIC_BASE_URL = `${url}/v1`;\n }\n\n handle = { llm, url };\n });\n\n beforeEach(() => {\n if (handle) {\n handle.llm.closeLiveSessions();\n handle.llm.resetMatchCounts();\n }\n });\n\n afterEach(() => {\n handle?.llm.closeLiveSessions();\n });\n\n afterAll(async () => {\n if (handle) {\n if (options.patchEnv !== false) {\n if (origOpenaiUrl !== undefined) process.env.OPENAI_BASE_URL = origOpenaiUrl;\n else delete process.env.OPENAI_BASE_URL;\n if (origAnthropicUrl !== undefined) process.env.ANTHROPIC_BASE_URL = origAnthropicUrl;\n else delete process.env.ANTHROPIC_BASE_URL;\n }\n await handle.llm.stop();\n handle = null;\n }\n });\n\n return () => {\n if (!handle) {\n throw new Error(\"useAimock(): server not started — are you calling this inside a test?\");\n }\n return handle;\n };\n}\n\n/**\n * Load a fixture file or directory into `llm`: its LLM fixtures and its\n * `mcpFakes` blocks, which the LLMock buffers and auto-mounts at start (F12).\n * A `FixtureLoadError` (a bad `mcpFakes` block) propagates and fails\n * `beforeAll`; any other load failure is only warned about, as before.\n */\nfunction loadFixtures(llm: LLMock, fixturePath: string): void {\n try {\n const stat = statSync(fixturePath);\n if (stat.isDirectory()) {\n llm.loadFixtureDir(fixturePath);\n } else {\n llm.loadFixtureFile(fixturePath);\n }\n } catch (err) {\n if (err instanceof FixtureLoadError) throw err;\n console.warn(\n `[aimock] Failed to load fixtures from ${fixturePath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nexport { LLMock } from \"./llmock.js\";\nexport type { MockServerOptions, Fixture } from \"./types.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,UAAU,UAA4B,EAAE,EAAsB;CAC5E,IAAI,SAA8B;CAClC,IAAI;CACJ,IAAI;AAEJ,WAAU,YAAY;EACpB,MAAM,EAAE,UAAU,aAAa,UAAU,GAAG,eAAe;EAC3D,MAAM,MAAM,IAAIA,sBAAO,WAAW;AAElC,MAAI,YACF,cAAa,4BAAa,YAAY,CAAC;EAGzC,MAAM,MAAM,MAAM,IAAI,OAAO;AAE7B,MAAI,aAAa,OAAO;AACtB,mBAAgB,QAAQ,IAAI;AAC5B,sBAAmB,QAAQ,IAAI;AAC/B,WAAQ,IAAI,kBAAkB,GAAG,IAAI;AACrC,WAAQ,IAAI,qBAAqB,GAAG,IAAI;;AAG1C,WAAS;GAAE;GAAK;GAAK;GACrB;AAEF,kBAAiB;AACf,MAAI,QAAQ;AACV,UAAO,IAAI,mBAAmB;AAC9B,UAAO,IAAI,kBAAkB;;GAE/B;AAEF,iBAAgB;AACd,UAAQ,IAAI,mBAAmB;GAC/B;AAEF,UAAS,YAAY;AACnB,MAAI,QAAQ;AACV,OAAI,QAAQ,aAAa,OAAO;AAC9B,QAAI,kBAAkB,OAAW,SAAQ,IAAI,kBAAkB;QAC1D,QAAO,QAAQ,IAAI;AACxB,QAAI,qBAAqB,OAAW,SAAQ,IAAI,qBAAqB;QAChE,QAAO,QAAQ,IAAI;;AAE1B,SAAM,OAAO,IAAI,MAAM;AACvB,YAAS;;GAEX;AAEF,cAAa;AACX,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,wEAAwE;AAE1F,SAAO;;;;;;;;;AAUX,SAAS,aAAa,KAAa,aAA2B;AAC5D,KAAI;AAEF,4BADsB,YAAY,CACzB,aAAa,CACpB,KAAI,eAAe,YAAY;MAE/B,KAAI,gBAAgB,YAAY;UAE3B,KAAK;AACZ,MAAI,eAAeC,wCAAkB,OAAM;AAC3C,UAAQ,KACN,yCAAyC,YAAY,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,GAC1G"}
|
package/dist/jest.d.cts
CHANGED
|
@@ -18,8 +18,10 @@ interface AimockHandle {
|
|
|
18
18
|
/**
|
|
19
19
|
* Start an aimock server for the duration of the test suite.
|
|
20
20
|
*
|
|
21
|
-
* - `beforeAll`: starts the server and optionally loads fixtures
|
|
22
|
-
*
|
|
21
|
+
* - `beforeAll`: starts the server and optionally loads fixtures (LLM fixtures and
|
|
22
|
+
* `mcpFakes` blocks; a bad `mcpFakes` block fails `beforeAll`)
|
|
23
|
+
* - `beforeEach`: closes Live sessions and resets fixture match counts and MCP fake
|
|
24
|
+
* consumption (not fixtures or fakes)
|
|
23
25
|
* - `afterEach`: closes Live sessions owned by this helper's server
|
|
24
26
|
* - `afterAll`: stops the server
|
|
25
27
|
*
|
package/dist/jest.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jest.d.cts","names":[],"sources":["../src/jest.ts"],"sourcesContent":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"jest.d.cts","names":[],"sources":["../src/jest.ts"],"sourcesContent":[],"mappings":";;;;;UA2BiB,gBAAA,SAAyB;;;;;;UAOzB,YAAA;;gBAED;;;;;;;;;;;;;;;;;;;iBAoBA,SAAA,WAAmB,yBAA8B"}
|
package/dist/jest.d.ts
CHANGED
|
@@ -18,8 +18,10 @@ interface AimockHandle {
|
|
|
18
18
|
/**
|
|
19
19
|
* Start an aimock server for the duration of the test suite.
|
|
20
20
|
*
|
|
21
|
-
* - `beforeAll`: starts the server and optionally loads fixtures
|
|
22
|
-
*
|
|
21
|
+
* - `beforeAll`: starts the server and optionally loads fixtures (LLM fixtures and
|
|
22
|
+
* `mcpFakes` blocks; a bad `mcpFakes` block fails `beforeAll`)
|
|
23
|
+
* - `beforeEach`: closes Live sessions and resets fixture match counts and MCP fake
|
|
24
|
+
* consumption (not fixtures or fakes)
|
|
23
25
|
* - `afterEach`: closes Live sessions owned by this helper's server
|
|
24
26
|
* - `afterAll`: stops the server
|
|
25
27
|
*
|
package/dist/jest.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jest.d.ts","names":[],"sources":["../src/jest.ts"],"sourcesContent":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"jest.d.ts","names":[],"sources":["../src/jest.ts"],"sourcesContent":[],"mappings":";;;;;UA2BiB,gBAAA,SAAyB;;;;;;UAOzB,YAAA;;gBAED;;;;;;;;;;;;;;;;;;;iBAoBA,SAAA,WAAmB,yBAA8B"}
|
package/dist/jest.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { FixtureLoadError } from "./fixture-loader.js";
|
|
2
2
|
import { LLMock } from "./llmock.js";
|
|
3
3
|
import { statSync } from "node:fs";
|
|
4
4
|
import { resolve } from "node:path";
|
|
@@ -7,8 +7,10 @@ import { resolve } from "node:path";
|
|
|
7
7
|
/**
|
|
8
8
|
* Start an aimock server for the duration of the test suite.
|
|
9
9
|
*
|
|
10
|
-
* - `beforeAll`: starts the server and optionally loads fixtures
|
|
11
|
-
*
|
|
10
|
+
* - `beforeAll`: starts the server and optionally loads fixtures (LLM fixtures and
|
|
11
|
+
* `mcpFakes` blocks; a bad `mcpFakes` block fails `beforeAll`)
|
|
12
|
+
* - `beforeEach`: closes Live sessions and resets fixture match counts and MCP fake
|
|
13
|
+
* consumption (not fixtures or fakes)
|
|
12
14
|
* - `afterEach`: closes Live sessions owned by this helper's server
|
|
13
15
|
* - `afterAll`: stops the server
|
|
14
16
|
*
|
|
@@ -24,10 +26,7 @@ function useAimock(options = {}) {
|
|
|
24
26
|
beforeAll(async () => {
|
|
25
27
|
const { fixtures: fixturePath, patchEnv, ...serverOpts } = options;
|
|
26
28
|
const llm = new LLMock(serverOpts);
|
|
27
|
-
if (fixturePath)
|
|
28
|
-
const loadedFixtures = loadFixtures(resolve(fixturePath), options.live);
|
|
29
|
-
for (const f of loadedFixtures) llm.addFixture(f);
|
|
30
|
-
}
|
|
29
|
+
if (fixturePath) loadFixtures(llm, resolve(fixturePath));
|
|
31
30
|
const url = await llm.start();
|
|
32
31
|
if (patchEnv !== false) {
|
|
33
32
|
origOpenaiUrl = process.env.OPENAI_BASE_URL;
|
|
@@ -66,13 +65,19 @@ function useAimock(options = {}) {
|
|
|
66
65
|
return handle;
|
|
67
66
|
};
|
|
68
67
|
}
|
|
69
|
-
|
|
68
|
+
/**
|
|
69
|
+
* Load a fixture file or directory into `llm`: its LLM fixtures and its
|
|
70
|
+
* `mcpFakes` blocks, which the LLMock buffers and auto-mounts at start (F12).
|
|
71
|
+
* A `FixtureLoadError` (a bad `mcpFakes` block) propagates and fails
|
|
72
|
+
* `beforeAll`; any other load failure is only warned about, as before.
|
|
73
|
+
*/
|
|
74
|
+
function loadFixtures(llm, fixturePath) {
|
|
70
75
|
try {
|
|
71
|
-
if (statSync(fixturePath).isDirectory())
|
|
72
|
-
|
|
76
|
+
if (statSync(fixturePath).isDirectory()) llm.loadFixtureDir(fixturePath);
|
|
77
|
+
else llm.loadFixtureFile(fixturePath);
|
|
73
78
|
} catch (err) {
|
|
79
|
+
if (err instanceof FixtureLoadError) throw err;
|
|
74
80
|
console.warn(`[aimock] Failed to load fixtures from ${fixturePath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
75
|
-
return [];
|
|
76
81
|
}
|
|
77
82
|
}
|
|
78
83
|
|
package/dist/jest.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jest.js","names":[],"sources":["../src/jest.ts"],"sourcesContent":["/**\n * Jest integration for aimock.\n *\n * Usage:\n * import { useAimock } from \"@copilotkit/aimock/jest\";\n *\n * const mock = useAimock({ fixtures: \"./fixtures\" });\n *\n * it(\"responds\", async () => {\n * const res = await fetch(`${mock().url}/v1/chat/completions`, { ... });\n * });\n */\n\n/* eslint-disable no-var */\n// Jest globals — available at runtime in jest test files\ndeclare var beforeAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var beforeEach: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterEach: (fn: () => Promise<void> | void, timeout?: number) => void;\n/* eslint-enable no-var */\n\nimport { LLMock } from \"./llmock.js\";\nimport {
|
|
1
|
+
{"version":3,"file":"jest.js","names":[],"sources":["../src/jest.ts"],"sourcesContent":["/**\n * Jest integration for aimock.\n *\n * Usage:\n * import { useAimock } from \"@copilotkit/aimock/jest\";\n *\n * const mock = useAimock({ fixtures: \"./fixtures\" });\n *\n * it(\"responds\", async () => {\n * const res = await fetch(`${mock().url}/v1/chat/completions`, { ... });\n * });\n */\n\n/* eslint-disable no-var */\n// Jest globals — available at runtime in jest test files\ndeclare var beforeAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var beforeEach: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterEach: (fn: () => Promise<void> | void, timeout?: number) => void;\n/* eslint-enable no-var */\n\nimport { LLMock } from \"./llmock.js\";\nimport { FixtureLoadError } from \"./fixture-loader.js\";\nimport type { MockServerOptions } from \"./types.js\";\nimport { statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nexport interface UseAimockOptions extends MockServerOptions {\n /** Path to fixture file or directory. Loaded automatically on start. */\n fixtures?: string;\n /** If true, sets process.env.OPENAI_BASE_URL to the mock URL + /v1. */\n patchEnv?: boolean;\n}\n\nexport interface AimockHandle {\n /** The LLMock instance. */\n readonly llm: LLMock;\n /** The server URL (e.g., http://127.0.0.1:4010). */\n readonly url: string;\n}\n\n/**\n * Start an aimock server for the duration of the test suite.\n *\n * - `beforeAll`: starts the server and optionally loads fixtures (LLM fixtures and\n * `mcpFakes` blocks; a bad `mcpFakes` block fails `beforeAll`)\n * - `beforeEach`: closes Live sessions and resets fixture match counts and MCP fake\n * consumption (not fixtures or fakes)\n * - `afterEach`: closes Live sessions owned by this helper's server\n * - `afterAll`: stops the server\n *\n * Returns a getter function — call it inside tests to access the handle.\n *\n * NOTE: Jest globals (beforeAll, afterAll, beforeEach, afterEach) must be available\n * in the test environment. This works with the default jest configuration.\n */\nexport function useAimock(options: UseAimockOptions = {}): () => AimockHandle {\n let handle: AimockHandle | null = null;\n let origOpenaiUrl: string | undefined;\n let origAnthropicUrl: string | undefined;\n\n beforeAll(async () => {\n const { fixtures: fixturePath, patchEnv, ...serverOpts } = options;\n const llm = new LLMock(serverOpts);\n\n if (fixturePath) {\n loadFixtures(llm, resolve(fixturePath));\n }\n\n const url = await llm.start();\n\n if (patchEnv !== false) {\n origOpenaiUrl = process.env.OPENAI_BASE_URL;\n origAnthropicUrl = process.env.ANTHROPIC_BASE_URL;\n process.env.OPENAI_BASE_URL = `${url}/v1`;\n process.env.ANTHROPIC_BASE_URL = `${url}/v1`;\n }\n\n handle = { llm, url };\n });\n\n beforeEach(() => {\n if (handle) {\n handle.llm.closeLiveSessions();\n handle.llm.resetMatchCounts();\n }\n });\n\n afterEach(() => {\n handle?.llm.closeLiveSessions();\n });\n\n afterAll(async () => {\n if (handle) {\n if (options.patchEnv !== false) {\n if (origOpenaiUrl !== undefined) process.env.OPENAI_BASE_URL = origOpenaiUrl;\n else delete process.env.OPENAI_BASE_URL;\n if (origAnthropicUrl !== undefined) process.env.ANTHROPIC_BASE_URL = origAnthropicUrl;\n else delete process.env.ANTHROPIC_BASE_URL;\n }\n await handle.llm.stop();\n handle = null;\n }\n });\n\n return () => {\n if (!handle) {\n throw new Error(\"useAimock(): server not started — are you calling this inside a test?\");\n }\n return handle;\n };\n}\n\n/**\n * Load a fixture file or directory into `llm`: its LLM fixtures and its\n * `mcpFakes` blocks, which the LLMock buffers and auto-mounts at start (F12).\n * A `FixtureLoadError` (a bad `mcpFakes` block) propagates and fails\n * `beforeAll`; any other load failure is only warned about, as before.\n */\nfunction loadFixtures(llm: LLMock, fixturePath: string): void {\n try {\n const stat = statSync(fixturePath);\n if (stat.isDirectory()) {\n llm.loadFixtureDir(fixturePath);\n } else {\n llm.loadFixtureFile(fixturePath);\n }\n } catch (err) {\n if (err instanceof FixtureLoadError) throw err;\n console.warn(\n `[aimock] Failed to load fixtures from ${fixturePath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nexport { LLMock } from \"./llmock.js\";\nexport type { MockServerOptions, Fixture } from \"./types.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,UAAU,UAA4B,EAAE,EAAsB;CAC5E,IAAI,SAA8B;CAClC,IAAI;CACJ,IAAI;AAEJ,WAAU,YAAY;EACpB,MAAM,EAAE,UAAU,aAAa,UAAU,GAAG,eAAe;EAC3D,MAAM,MAAM,IAAI,OAAO,WAAW;AAElC,MAAI,YACF,cAAa,KAAK,QAAQ,YAAY,CAAC;EAGzC,MAAM,MAAM,MAAM,IAAI,OAAO;AAE7B,MAAI,aAAa,OAAO;AACtB,mBAAgB,QAAQ,IAAI;AAC5B,sBAAmB,QAAQ,IAAI;AAC/B,WAAQ,IAAI,kBAAkB,GAAG,IAAI;AACrC,WAAQ,IAAI,qBAAqB,GAAG,IAAI;;AAG1C,WAAS;GAAE;GAAK;GAAK;GACrB;AAEF,kBAAiB;AACf,MAAI,QAAQ;AACV,UAAO,IAAI,mBAAmB;AAC9B,UAAO,IAAI,kBAAkB;;GAE/B;AAEF,iBAAgB;AACd,UAAQ,IAAI,mBAAmB;GAC/B;AAEF,UAAS,YAAY;AACnB,MAAI,QAAQ;AACV,OAAI,QAAQ,aAAa,OAAO;AAC9B,QAAI,kBAAkB,OAAW,SAAQ,IAAI,kBAAkB;QAC1D,QAAO,QAAQ,IAAI;AACxB,QAAI,qBAAqB,OAAW,SAAQ,IAAI,qBAAqB;QAChE,QAAO,QAAQ,IAAI;;AAE1B,SAAM,OAAO,IAAI,MAAM;AACvB,YAAS;;GAEX;AAEF,cAAa;AACX,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,wEAAwE;AAE1F,SAAO;;;;;;;;;AAUX,SAAS,aAAa,KAAa,aAA2B;AAC5D,KAAI;AAEF,MADa,SAAS,YAAY,CACzB,aAAa,CACpB,KAAI,eAAe,YAAY;MAE/B,KAAI,gBAAgB,YAAY;UAE3B,KAAK;AACZ,MAAI,eAAe,iBAAkB,OAAM;AAC3C,UAAQ,KACN,yCAAyC,YAAY,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,GAC1G"}
|
package/dist/journal.cjs
CHANGED
|
@@ -92,6 +92,26 @@ var Journal = class {
|
|
|
92
92
|
const testIdCap = options.fixtureCountsMaxTestIds;
|
|
93
93
|
this.fixtureCountsMaxTestIds = testIdCap !== void 0 && testIdCap > 0 ? testIdCap : 0;
|
|
94
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* The per-test-id cap on fixture match-count maps, for an MCP mount to pass
|
|
97
|
+
* to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`
|
|
98
|
+
* meaning unbounded, and never throws, whatever option was passed:
|
|
99
|
+
* omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above
|
|
100
|
+
* `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more
|
|
101
|
+
* is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values
|
|
102
|
+
* it is the number of test ids the journal keeps.
|
|
103
|
+
*
|
|
104
|
+
* An option between 0 and 1 is the exception. The journal keeps no test id
|
|
105
|
+
* (each new count map is evicted as soon as it is made, so counts never
|
|
106
|
+
* advance), and a store cap cannot say "keep none" because `0` is
|
|
107
|
+
* unbounded. The getter returns `1`, the smallest bounded cap, so a store
|
|
108
|
+
* given it keeps 1 test id where the journal keeps 0.
|
|
109
|
+
*/
|
|
110
|
+
get fixtureCountsMaxTestIdsCap() {
|
|
111
|
+
const cap = this.fixtureCountsMaxTestIds;
|
|
112
|
+
if (!(cap > 0) || cap > Number.MAX_SAFE_INTEGER) return 0;
|
|
113
|
+
return Math.max(1, Math.floor(cap));
|
|
114
|
+
}
|
|
95
115
|
/** Backwards-compatible accessor — returns the default (no testId) count map. */
|
|
96
116
|
get fixtureMatchCounts() {
|
|
97
117
|
return this.getFixtureMatchCountsForTest(require_constants.DEFAULT_TEST_ID);
|
package/dist/journal.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.cjs","names":["DEFAULT_TEST_ID","generateId"],"sources":["../src/journal.ts"],"sourcesContent":["import { generateId } from \"./helpers.js\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureMatch,\n JournalBody,\n JournalEntry,\n} from \"./types.js\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nexport { DEFAULT_TEST_ID } from \"./constants.js\";\n\n/**\n * Maximum UTF-8 byte length of a serialized request body retained in a\n * journal entry. Bodies whose JSON serialization exceeds this byte size are\n * replaced with a truncation marker.\n *\n * Only the request `body` field is capped here. `headers` and `path` are\n * retained uncapped, but they are naturally bounded by Node's default ~16 KB\n * maximum HTTP header size, so the per-entry overhead beyond the body cap\n * remains small. Combined with the journal's maxEntries limit (default 1000),\n * the total `JSON.stringify(journal.getAll())` output stays well under V8's\n * ~512 MB string limit even at maximum capacity.\n */\nconst JOURNAL_BODY_CAP_BYTES = 64 * 1024; // 64 KB\n\n/**\n * If `body` serializes to more than JOURNAL_BODY_CAP_BYTES (in UTF-8 bytes),\n * replace it with a truncation marker. Returns the original body when within\n * the cap, or null when `body` is null.\n *\n * The gate uses Buffer.byteLength (UTF-8 bytes) rather than .length (UTF-16\n * code units) to match the constant name and to correctly cap multibyte\n * content (e.g. CJK/emoji) whose code-unit count falls under the threshold\n * but whose byte size does not.\n */\nfunction capBody(body: JournalBody | null): JournalBody | null {\n if (body === null) return null;\n const serialized = JSON.stringify(body);\n if (Buffer.byteLength(serialized, \"utf8\") <= JOURNAL_BODY_CAP_BYTES) return body;\n // The marker is not a chat request, and `JournalBody` no longer claims it is\n // — downstream consumers (e.g. GET /journal) treat the body as opaque JSON.\n return {\n __aimock_truncated: true,\n originalByteSize: Buffer.byteLength(serialized, \"utf8\"),\n note: \"body truncated by aimock journal cap (64 KB limit)\",\n };\n}\n\n/**\n * Narrow a journaled body to a chat-completion request.\n *\n * `JournalEntry.body` is a union (see {@link JournalBody}): most entries hold a\n * chat request, but the fine-tuning create payload and this module's own\n * truncation marker do not. Anything reading `messages`, `model` or the rest of\n * the chat shape off a journal entry — inside aimock or in a consumer's test\n * — goes through here, so an entry that is not a chat request fails as a\n * `false` it can assert on rather than as an undefined property three accesses\n * later.\n *\n * `messages` is the discriminator because it is the one required field no\n * other journaled shape carries.\n */\nexport function isChatCompletionBody(\n body: JournalBody | null | undefined,\n): body is ChatCompletionRequest {\n return (\n body !== null &&\n body !== undefined &&\n Array.isArray((body as { messages?: unknown }).messages) &&\n typeof (body as { model?: unknown }).model === \"string\"\n );\n}\n\n/**\n * Compare two field values, handling RegExp by source+flags rather than reference.\n */\nfunction fieldEqual(a: unknown, b: unknown): boolean {\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return a === b;\n}\n\n/**\n * Compare two systemMessage values. Handles string, string[], and RegExp.\n * Both-undefined is treated as equal.\n */\nfunction systemMessageEqual(\n a: string | string[] | RegExp | undefined,\n b: string | string[] | RegExp | undefined,\n): boolean {\n if (a === undefined && b === undefined) return true;\n if (a === undefined || b === undefined) return false;\n if (typeof a === \"string\" && typeof b === \"string\") return a === b;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i]);\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return false;\n}\n\n/**\n * Check whether two fixture match objects have the same criteria\n * (ignoring sequenceIndex). Used to group sequenced fixtures.\n */\nfunction matchCriteriaEqual(a: FixtureMatch, b: FixtureMatch): boolean {\n return (\n fieldEqual(a.userMessage, b.userMessage) &&\n systemMessageEqual(a.systemMessage, b.systemMessage) &&\n fieldEqual(a.inputText, b.inputText) &&\n fieldEqual(a.toolCallId, b.toolCallId) &&\n fieldEqual(a.toolName, b.toolName) &&\n fieldEqual(a.model, b.model) &&\n fieldEqual(a.responseFormat, b.responseFormat) &&\n fieldEqual(a.predicate, b.predicate) &&\n fieldEqual(a.endpoint, b.endpoint) &&\n fieldEqual(a.turnIndex, b.turnIndex) &&\n fieldEqual(a.hasToolResult, b.hasToolResult) &&\n fieldEqual(a.toolResultContains, b.toolResultContains) &&\n fieldEqual(a.context, b.context)\n );\n}\n\nexport interface JournalOptions {\n /**\n * Maximum number of entries to retain. When exceeded, oldest entries are\n * dropped FIFO. Set to 0 (or omit) for unbounded retention (the historical\n * default — suitable for short-lived test runs only). Negative values are\n * rejected at the CLI parse layer; programmatically they are treated as 0\n * (unbounded) for back-compat.\n *\n * Long-running servers (e.g. mock proxies in CI/demo environments) should\n * always set a finite cap: every request appends an entry holding the\n * request body + headers + fixture reference, and without a cap the\n * journal grows until the process OOMs.\n */\n maxEntries?: number;\n /**\n * Maximum number of unique testIds retained in the fixture match-count\n * map (`fixtureMatchCountsByTestId`). When exceeded, the oldest testId\n * (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for\n * unbounded retention. Negative values are rejected at the CLI parse\n * layer; programmatically they are treated as 0 (unbounded) for\n * back-compat. Without a cap this map can grow over time in long-running\n * servers that see many unique testIds.\n */\n fixtureCountsMaxTestIds?: number;\n /**\n * Called with every entry {@link Journal.add} creates, right after it is\n * recorded. The hook exists so an embedder can attribute an entry to the\n * request that produced it WITHOUT touching each of the ~100 `journal.add`\n * call sites spread across the handler modules: the server binds the entry\n * to the in-flight `IncomingMessage` here, and its error arm then amends\n * that exact object rather than guessing from a caller-supplied header.\n *\n * The entry is already recorded when the hook runs, so a hook that throws\n * does not lose the write — but it does propagate out of `add` into the\n * caller's error path, so a hook must not throw.\n */\n onAdd?: (entry: JournalEntry) => void;\n}\n\nexport class Journal {\n private entries: JournalEntry[] = [];\n private readonly matchedFixtures = new WeakMap<JournalEntry, Fixture>();\n private readonly fixtureMatchCountsByTestId: Map<string, Map<Fixture, number>> = new Map();\n private readonly maxEntries: number;\n private readonly fixtureCountsMaxTestIds: number;\n private readonly onAdd?: (entry: JournalEntry) => void;\n\n constructor(options: JournalOptions = {}) {\n this.onAdd = options.onAdd;\n // Treat 0 or negative as \"unbounded\" to preserve prior behavior when\n // the option is omitted or explicitly disabled.\n const cap = options.maxEntries;\n this.maxEntries = cap !== undefined && cap > 0 ? cap : 0;\n const testIdCap = options.fixtureCountsMaxTestIds;\n this.fixtureCountsMaxTestIds = testIdCap !== undefined && testIdCap > 0 ? testIdCap : 0;\n }\n\n /** Backwards-compatible accessor — returns the default (no testId) count map. */\n get fixtureMatchCounts(): Map<Fixture, number> {\n return this.getFixtureMatchCountsForTest(DEFAULT_TEST_ID);\n }\n\n /** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */\n add(entry: Omit<JournalEntry, \"id\" | \"timestamp\">, matchedFixture?: Fixture): JournalEntry {\n const full: JournalEntry = {\n id: generateId(\"req\"),\n timestamp: Date.now(),\n ...entry,\n body: capBody(entry.body),\n };\n if (matchedFixture) this.matchedFixtures.set(full, matchedFixture);\n this.entries.push(full);\n // FIFO eviction when over capacity. Array.prototype.shift() is O(n)\n // regardless of how many we drop per add; we accept it at small caps\n // (default 1000) because the constant factor is tiny and this runs once\n // per request. For much larger caps, switch to a ring buffer for true\n // O(1) eviction.\n if (this.maxEntries > 0 && this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n this.onAdd?.(full);\n return full;\n }\n\n /**\n * Return every entry, or with `limit` the most recent `limit` entries.\n * `0` returns `[]` — exactly what `GET /__aimock/journal?limit=0` answers.\n * `slice(-0)` is `slice(0)`, so a `0` used to return the ENTIRE journal; it\n * is special-cased so the library and the HTTP route agree. This is a public\n * library API, so odd limits are tolerated rather than thrown on: a\n * non-finite limit (`NaN`, `Infinity`) means \"no limit\", a fractional limit\n * floors, and any limit at or below `0` asks for nothing.\n */\n getAll(opts?: { limit?: number }): JournalEntry[] {\n if (opts?.limit !== undefined && Number.isFinite(opts.limit)) {\n const limit = Math.floor(opts.limit);\n if (limit <= 0) return [];\n return this.entries.slice(-limit);\n }\n return this.entries.slice();\n }\n\n getLast(): JournalEntry | null {\n return this.entries.length > 0 ? this.entries[this.entries.length - 1] : null;\n }\n\n findByFixture(fixture: Fixture): JournalEntry[] {\n return this.entries.filter(\n (e) => (this.matchedFixtures.get(e) ?? e.response.fixture) === fixture,\n );\n }\n\n /**\n * READ-ONLY accessor. Returns the existing count map for `testId`, or an\n * empty transient Map if none exists. Does NOT insert into the cache and\n * does NOT trigger FIFO eviction — callers may read freely without\n * perturbing cache state. For the write path, see\n * `getOrCreateFixtureMatchCountsForTest`.\n */\n getFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n return this.fixtureMatchCountsByTestId.get(testId) ?? new Map();\n }\n\n /**\n * WRITE path: get the count map for `testId`, inserting a fresh empty Map\n * if missing and running FIFO eviction when the testId cap is exceeded.\n * Only callers that intend to mutate the map (e.g. incrementing a count)\n * should use this.\n */\n private getOrCreateFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n let counts = this.fixtureMatchCountsByTestId.get(testId);\n if (!counts) {\n counts = new Map();\n this.fixtureMatchCountsByTestId.set(testId, counts);\n // FIFO eviction when over capacity. JS Map preserves insertion order,\n // so the first key returned by keys() is the oldest. Same O(n) shift\n // caveat as `entries`: acceptable at small caps (default 500).\n if (\n this.fixtureCountsMaxTestIds > 0 &&\n this.fixtureMatchCountsByTestId.size > this.fixtureCountsMaxTestIds\n ) {\n const oldest = this.fixtureMatchCountsByTestId.keys().next().value;\n if (oldest !== undefined) {\n this.fixtureMatchCountsByTestId.delete(oldest);\n }\n }\n }\n return counts;\n }\n\n getFixtureMatchCount(fixture: Fixture, testId = DEFAULT_TEST_ID): number {\n return this.getFixtureMatchCountsForTest(testId).get(fixture) ?? 0;\n }\n\n incrementFixtureMatchCount(\n fixture: Fixture,\n allFixtures?: readonly Fixture[],\n testId = DEFAULT_TEST_ID,\n ): void {\n const counts = this.getOrCreateFixtureMatchCountsForTest(testId);\n counts.set(fixture, (counts.get(fixture) ?? 0) + 1);\n // When a sequenced fixture matches, also increment all siblings with matching criteria\n if (fixture.match.sequenceIndex !== undefined && allFixtures) {\n for (const sibling of allFixtures) {\n if (sibling === fixture) continue;\n if (sibling.match.sequenceIndex === undefined) continue;\n if (matchCriteriaEqual(fixture.match, sibling.match)) {\n counts.set(sibling, (counts.get(sibling) ?? 0) + 1);\n }\n }\n }\n }\n\n clearMatchCounts(testId?: string): void {\n if (testId !== undefined) {\n this.fixtureMatchCountsByTestId.delete(testId);\n } else {\n this.fixtureMatchCountsByTestId.clear();\n }\n }\n\n /**\n * Clear ONLY the request journal entries, preserving fixture match-counts.\n * Match-counts are fixture-matching/sequencing state, not journal data, so\n * clearing the journal must not silently rewind sequenced fixtures. Used by\n * `POST /__aimock/reset/journal`. For a full reset (entries + match-counts),\n * use `clear()` instead.\n */\n clearEntries(): void {\n this.entries = [];\n }\n\n clear(): void {\n this.entries = [];\n this.fixtureMatchCountsByTestId.clear();\n }\n\n get size(): number {\n return this.entries.length;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAM,yBAAyB,KAAK;;;;;;;;;;;AAYpC,SAAS,QAAQ,MAA8C;AAC7D,KAAI,SAAS,KAAM,QAAO;CAC1B,MAAM,aAAa,KAAK,UAAU,KAAK;AACvC,KAAI,OAAO,WAAW,YAAY,OAAO,IAAI,uBAAwB,QAAO;AAG5E,QAAO;EACL,oBAAoB;EACpB,kBAAkB,OAAO,WAAW,YAAY,OAAO;EACvD,MAAM;EACP;;;;;;;;;;;;;;;;AAiBH,SAAgB,qBACd,MAC+B;AAC/B,QACE,SAA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AAO,oBAAI,IAAI,KAAK;;;;;;;;CASjE,AAAQ,qCAAqC,QAAsC;EACjF,IAAI,SAAS,KAAK,2BAA2B,IAAI,OAAO;AACxD,MAAI,CAAC,QAAQ;AACX,4BAAS,IAAI,KAAK;AAClB,QAAK,2BAA2B,IAAI,QAAQ,OAAO;AAInD,OACE,KAAK,0BAA0B,KAC/B,KAAK,2BAA2B,OAAO,KAAK,yBAC5C;IACA,MAAM,SAAS,KAAK,2BAA2B,MAAM,CAAC,MAAM,CAAC;AAC7D,QAAI,WAAW,OACb,MAAK,2BAA2B,OAAO,OAAO;;;AAIpD,SAAO;;CAGT,qBAAqB,SAAkB,SAASD,mCAAyB;AACvE,SAAO,KAAK,6BAA6B,OAAO,CAAC,IAAI,QAAQ,IAAI;;CAGnE,2BACE,SACA,aACA,SAASA,mCACH;EACN,MAAM,SAAS,KAAK,qCAAqC,OAAO;AAChE,SAAO,IAAI,UAAU,OAAO,IAAI,QAAQ,IAAI,KAAK,EAAE;AAEnD,MAAI,QAAQ,MAAM,kBAAkB,UAAa,YAC/C,MAAK,MAAM,WAAW,aAAa;AACjC,OAAI,YAAY,QAAS;AACzB,OAAI,QAAQ,MAAM,kBAAkB,OAAW;AAC/C,OAAI,mBAAmB,QAAQ,OAAO,QAAQ,MAAM,CAClD,QAAO,IAAI,UAAU,OAAO,IAAI,QAAQ,IAAI,KAAK,EAAE;;;CAM3D,iBAAiB,QAAuB;AACtC,MAAI,WAAW,OACb,MAAK,2BAA2B,OAAO,OAAO;MAE9C,MAAK,2BAA2B,OAAO;;;;;;;;;CAW3C,eAAqB;AACnB,OAAK,UAAU,EAAE;;CAGnB,QAAc;AACZ,OAAK,UAAU,EAAE;AACjB,OAAK,2BAA2B,OAAO;;CAGzC,IAAI,OAAe;AACjB,SAAO,KAAK,QAAQ"}
|
|
1
|
+
{"version":3,"file":"journal.cjs","names":["DEFAULT_TEST_ID","generateId"],"sources":["../src/journal.ts"],"sourcesContent":["import { generateId } from \"./helpers.js\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureMatch,\n JournalBody,\n JournalEntry,\n} from \"./types.js\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nexport { DEFAULT_TEST_ID } from \"./constants.js\";\n\n/**\n * Maximum UTF-8 byte length of a serialized request body retained in a\n * journal entry. Bodies whose JSON serialization exceeds this byte size are\n * replaced with a truncation marker.\n *\n * Only the request `body` field is capped here. `headers` and `path` are\n * retained uncapped, but they are naturally bounded by Node's default ~16 KB\n * maximum HTTP header size, so the per-entry overhead beyond the body cap\n * remains small. Combined with the journal's maxEntries limit (default 1000),\n * the total `JSON.stringify(journal.getAll())` output stays well under V8's\n * ~512 MB string limit even at maximum capacity.\n */\nconst JOURNAL_BODY_CAP_BYTES = 64 * 1024; // 64 KB\n\n/**\n * If `body` serializes to more than JOURNAL_BODY_CAP_BYTES (in UTF-8 bytes),\n * replace it with a truncation marker. Returns the original body when within\n * the cap, or null when `body` is null.\n *\n * The gate uses Buffer.byteLength (UTF-8 bytes) rather than .length (UTF-16\n * code units) to match the constant name and to correctly cap multibyte\n * content (e.g. CJK/emoji) whose code-unit count falls under the threshold\n * but whose byte size does not.\n */\nfunction capBody(body: JournalBody | null): JournalBody | null {\n if (body === null) return null;\n const serialized = JSON.stringify(body);\n if (Buffer.byteLength(serialized, \"utf8\") <= JOURNAL_BODY_CAP_BYTES) return body;\n // The marker is not a chat request, and `JournalBody` no longer claims it is\n // — downstream consumers (e.g. GET /journal) treat the body as opaque JSON.\n return {\n __aimock_truncated: true,\n originalByteSize: Buffer.byteLength(serialized, \"utf8\"),\n note: \"body truncated by aimock journal cap (64 KB limit)\",\n };\n}\n\n/**\n * Narrow a journaled body to a chat-completion request.\n *\n * `JournalEntry.body` is a union (see {@link JournalBody}): most entries hold a\n * chat request, but the fine-tuning create payload and this module's own\n * truncation marker do not. Anything reading `messages`, `model` or the rest of\n * the chat shape off a journal entry — inside aimock or in a consumer's test\n * — goes through here, so an entry that is not a chat request fails as a\n * `false` it can assert on rather than as an undefined property three accesses\n * later.\n *\n * `messages` is the discriminator because it is the one required field no\n * other journaled shape carries.\n */\nexport function isChatCompletionBody(\n body: JournalBody | null | undefined,\n): body is ChatCompletionRequest {\n return (\n body !== null &&\n body !== undefined &&\n Array.isArray((body as { messages?: unknown }).messages) &&\n typeof (body as { model?: unknown }).model === \"string\"\n );\n}\n\n/**\n * Compare two field values, handling RegExp by source+flags rather than reference.\n */\nfunction fieldEqual(a: unknown, b: unknown): boolean {\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return a === b;\n}\n\n/**\n * Compare two systemMessage values. Handles string, string[], and RegExp.\n * Both-undefined is treated as equal.\n */\nfunction systemMessageEqual(\n a: string | string[] | RegExp | undefined,\n b: string | string[] | RegExp | undefined,\n): boolean {\n if (a === undefined && b === undefined) return true;\n if (a === undefined || b === undefined) return false;\n if (typeof a === \"string\" && typeof b === \"string\") return a === b;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i]);\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return false;\n}\n\n/**\n * Check whether two fixture match objects have the same criteria\n * (ignoring sequenceIndex). Used to group sequenced fixtures.\n */\nfunction matchCriteriaEqual(a: FixtureMatch, b: FixtureMatch): boolean {\n return (\n fieldEqual(a.userMessage, b.userMessage) &&\n systemMessageEqual(a.systemMessage, b.systemMessage) &&\n fieldEqual(a.inputText, b.inputText) &&\n fieldEqual(a.toolCallId, b.toolCallId) &&\n fieldEqual(a.toolName, b.toolName) &&\n fieldEqual(a.model, b.model) &&\n fieldEqual(a.responseFormat, b.responseFormat) &&\n fieldEqual(a.predicate, b.predicate) &&\n fieldEqual(a.endpoint, b.endpoint) &&\n fieldEqual(a.turnIndex, b.turnIndex) &&\n fieldEqual(a.hasToolResult, b.hasToolResult) &&\n fieldEqual(a.toolResultContains, b.toolResultContains) &&\n fieldEqual(a.context, b.context)\n );\n}\n\nexport interface JournalOptions {\n /**\n * Maximum number of entries to retain. When exceeded, oldest entries are\n * dropped FIFO. Set to 0 (or omit) for unbounded retention (the historical\n * default — suitable for short-lived test runs only). Negative values are\n * rejected at the CLI parse layer; programmatically they are treated as 0\n * (unbounded) for back-compat.\n *\n * Long-running servers (e.g. mock proxies in CI/demo environments) should\n * always set a finite cap: every request appends an entry holding the\n * request body + headers + fixture reference, and without a cap the\n * journal grows until the process OOMs.\n */\n maxEntries?: number;\n /**\n * Maximum number of unique testIds retained in the fixture match-count\n * map (`fixtureMatchCountsByTestId`). When exceeded, the oldest testId\n * (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for\n * unbounded retention. Negative values are rejected at the CLI parse\n * layer; programmatically they are treated as 0 (unbounded) for\n * back-compat. Without a cap this map can grow over time in long-running\n * servers that see many unique testIds.\n */\n fixtureCountsMaxTestIds?: number;\n /**\n * Called with every entry {@link Journal.add} creates, right after it is\n * recorded. The hook exists so an embedder can attribute an entry to the\n * request that produced it WITHOUT touching each of the ~100 `journal.add`\n * call sites spread across the handler modules: the server binds the entry\n * to the in-flight `IncomingMessage` here, and its error arm then amends\n * that exact object rather than guessing from a caller-supplied header.\n *\n * The entry is already recorded when the hook runs, so a hook that throws\n * does not lose the write — but it does propagate out of `add` into the\n * caller's error path, so a hook must not throw.\n */\n onAdd?: (entry: JournalEntry) => void;\n}\n\nexport class Journal {\n private entries: JournalEntry[] = [];\n private readonly matchedFixtures = new WeakMap<JournalEntry, Fixture>();\n private readonly fixtureMatchCountsByTestId: Map<string, Map<Fixture, number>> = new Map();\n private readonly maxEntries: number;\n private readonly fixtureCountsMaxTestIds: number;\n private readonly onAdd?: (entry: JournalEntry) => void;\n\n constructor(options: JournalOptions = {}) {\n this.onAdd = options.onAdd;\n // Treat 0 or negative as \"unbounded\" to preserve prior behavior when\n // the option is omitted or explicitly disabled.\n const cap = options.maxEntries;\n this.maxEntries = cap !== undefined && cap > 0 ? cap : 0;\n const testIdCap = options.fixtureCountsMaxTestIds;\n this.fixtureCountsMaxTestIds = testIdCap !== undefined && testIdCap > 0 ? testIdCap : 0;\n }\n\n /**\n * The per-test-id cap on fixture match-count maps, for an MCP mount to pass\n * to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`\n * meaning unbounded, and never throws, whatever option was passed:\n * omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above\n * `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more\n * is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values\n * it is the number of test ids the journal keeps.\n *\n * An option between 0 and 1 is the exception. The journal keeps no test id\n * (each new count map is evicted as soon as it is made, so counts never\n * advance), and a store cap cannot say \"keep none\" because `0` is\n * unbounded. The getter returns `1`, the smallest bounded cap, so a store\n * given it keeps 1 test id where the journal keeps 0.\n */\n get fixtureCountsMaxTestIdsCap(): number {\n const cap = this.fixtureCountsMaxTestIds;\n if (!(cap > 0) || cap > Number.MAX_SAFE_INTEGER) return 0;\n return Math.max(1, Math.floor(cap));\n }\n\n /** Backwards-compatible accessor — returns the default (no testId) count map. */\n get fixtureMatchCounts(): Map<Fixture, number> {\n return this.getFixtureMatchCountsForTest(DEFAULT_TEST_ID);\n }\n\n /** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */\n add(entry: Omit<JournalEntry, \"id\" | \"timestamp\">, matchedFixture?: Fixture): JournalEntry {\n const full: JournalEntry = {\n id: generateId(\"req\"),\n timestamp: Date.now(),\n ...entry,\n body: capBody(entry.body),\n };\n if (matchedFixture) this.matchedFixtures.set(full, matchedFixture);\n this.entries.push(full);\n // FIFO eviction when over capacity. Array.prototype.shift() is O(n)\n // regardless of how many we drop per add; we accept it at small caps\n // (default 1000) because the constant factor is tiny and this runs once\n // per request. For much larger caps, switch to a ring buffer for true\n // O(1) eviction.\n if (this.maxEntries > 0 && this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n this.onAdd?.(full);\n return full;\n }\n\n /**\n * Return every entry, or with `limit` the most recent `limit` entries.\n * `0` returns `[]` — exactly what `GET /__aimock/journal?limit=0` answers.\n * `slice(-0)` is `slice(0)`, so a `0` used to return the ENTIRE journal; it\n * is special-cased so the library and the HTTP route agree. This is a public\n * library API, so odd limits are tolerated rather than thrown on: a\n * non-finite limit (`NaN`, `Infinity`) means \"no limit\", a fractional limit\n * floors, and any limit at or below `0` asks for nothing.\n */\n getAll(opts?: { limit?: number }): JournalEntry[] {\n if (opts?.limit !== undefined && Number.isFinite(opts.limit)) {\n const limit = Math.floor(opts.limit);\n if (limit <= 0) return [];\n return this.entries.slice(-limit);\n }\n return this.entries.slice();\n }\n\n getLast(): JournalEntry | null {\n return this.entries.length > 0 ? this.entries[this.entries.length - 1] : null;\n }\n\n findByFixture(fixture: Fixture): JournalEntry[] {\n return this.entries.filter(\n (e) => (this.matchedFixtures.get(e) ?? e.response.fixture) === fixture,\n );\n }\n\n /**\n * READ-ONLY accessor. Returns the existing count map for `testId`, or an\n * empty transient Map if none exists. Does NOT insert into the cache and\n * does NOT trigger FIFO eviction — callers may read freely without\n * perturbing cache state. For the write path, see\n * `getOrCreateFixtureMatchCountsForTest`.\n */\n getFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n return this.fixtureMatchCountsByTestId.get(testId) ?? new Map();\n }\n\n /**\n * WRITE path: get the count map for `testId`, inserting a fresh empty Map\n * if missing and running FIFO eviction when the testId cap is exceeded.\n * Only callers that intend to mutate the map (e.g. incrementing a count)\n * should use this.\n */\n private getOrCreateFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n let counts = this.fixtureMatchCountsByTestId.get(testId);\n if (!counts) {\n counts = new Map();\n this.fixtureMatchCountsByTestId.set(testId, counts);\n // FIFO eviction when over capacity. JS Map preserves insertion order,\n // so the first key returned by keys() is the oldest. Same O(n) shift\n // caveat as `entries`: acceptable at small caps (createServer\n // default 500; a bare Journal is unbounded).\n if (\n this.fixtureCountsMaxTestIds > 0 &&\n this.fixtureMatchCountsByTestId.size > this.fixtureCountsMaxTestIds\n ) {\n const oldest = this.fixtureMatchCountsByTestId.keys().next().value;\n if (oldest !== undefined) {\n this.fixtureMatchCountsByTestId.delete(oldest);\n }\n }\n }\n return counts;\n }\n\n getFixtureMatchCount(fixture: Fixture, testId = DEFAULT_TEST_ID): number {\n return this.getFixtureMatchCountsForTest(testId).get(fixture) ?? 0;\n }\n\n incrementFixtureMatchCount(\n fixture: Fixture,\n allFixtures?: readonly Fixture[],\n testId = DEFAULT_TEST_ID,\n ): void {\n const counts = this.getOrCreateFixtureMatchCountsForTest(testId);\n counts.set(fixture, (counts.get(fixture) ?? 0) + 1);\n // When a sequenced fixture matches, also increment all siblings with matching criteria\n if (fixture.match.sequenceIndex !== undefined && allFixtures) {\n for (const sibling of allFixtures) {\n if (sibling === fixture) continue;\n if (sibling.match.sequenceIndex === undefined) continue;\n if (matchCriteriaEqual(fixture.match, sibling.match)) {\n counts.set(sibling, (counts.get(sibling) ?? 0) + 1);\n }\n }\n }\n }\n\n clearMatchCounts(testId?: string): void {\n if (testId !== undefined) {\n this.fixtureMatchCountsByTestId.delete(testId);\n } else {\n this.fixtureMatchCountsByTestId.clear();\n }\n }\n\n /**\n * Clear ONLY the request journal entries, preserving fixture match-counts.\n * Match-counts are fixture-matching/sequencing state, not journal data, so\n * clearing the journal must not silently rewind sequenced fixtures. Used by\n * `POST /__aimock/reset/journal`. For a full reset (entries + match-counts),\n * use `clear()` instead.\n */\n clearEntries(): void {\n this.entries = [];\n }\n\n clear(): void {\n this.entries = [];\n this.fixtureMatchCountsByTestId.clear();\n }\n\n get size(): number {\n return this.entries.length;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAM,yBAAyB,KAAK;;;;;;;;;;;AAYpC,SAAS,QAAQ,MAA8C;AAC7D,KAAI,SAAS,KAAM,QAAO;CAC1B,MAAM,aAAa,KAAK,UAAU,KAAK;AACvC,KAAI,OAAO,WAAW,YAAY,OAAO,IAAI,uBAAwB,QAAO;AAG5E,QAAO;EACL,oB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O;MAE9C,MAAK,2BAA2B,OAAO;;;;;;;;;CAW3C,eAAqB;AACnB,OAAK,UAAU,EAAE;;CAGnB,QAAc;AACZ,OAAK,UAAU,EAAE;AACjB,OAAK,2BAA2B,OAAO;;CAGzC,IAAI,OAAe;AACjB,SAAO,KAAK,QAAQ"}
|
package/dist/journal.d.cts
CHANGED
|
@@ -64,6 +64,22 @@ declare class Journal {
|
|
|
64
64
|
private readonly fixtureCountsMaxTestIds;
|
|
65
65
|
private readonly onAdd?;
|
|
66
66
|
constructor(options?: JournalOptions);
|
|
67
|
+
/**
|
|
68
|
+
* The per-test-id cap on fixture match-count maps, for an MCP mount to pass
|
|
69
|
+
* to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`
|
|
70
|
+
* meaning unbounded, and never throws, whatever option was passed:
|
|
71
|
+
* omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above
|
|
72
|
+
* `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more
|
|
73
|
+
* is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values
|
|
74
|
+
* it is the number of test ids the journal keeps.
|
|
75
|
+
*
|
|
76
|
+
* An option between 0 and 1 is the exception. The journal keeps no test id
|
|
77
|
+
* (each new count map is evicted as soon as it is made, so counts never
|
|
78
|
+
* advance), and a store cap cannot say "keep none" because `0` is
|
|
79
|
+
* unbounded. The getter returns `1`, the smallest bounded cap, so a store
|
|
80
|
+
* given it keeps 1 test id where the journal keeps 0.
|
|
81
|
+
*/
|
|
82
|
+
get fixtureCountsMaxTestIdsCap(): number;
|
|
67
83
|
/** Backwards-compatible accessor — returns the default (no testId) count map. */
|
|
68
84
|
get fixtureMatchCounts(): Map<Fixture, number>;
|
|
69
85
|
/** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */
|
package/dist/journal.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.d.cts","names":[],"sources":["../src/journal.ts"],"sourcesContent":[],"mappings":";;;;;;;AA8DA;;;;;AA4DA;AAuCA;;;;;;
|
|
1
|
+
{"version":3,"file":"journal.d.cts","names":[],"sources":["../src/journal.ts"],"sourcesContent":[],"mappings":";;;;;;;AA8DA;;;;;AA4DA;AAuCA;;;;;;AA6Ca,iBAhJG,oBAAA,CAgJH,IAAA,EA/IL,WA+IK,GAAA,IAAA,GAAA,SAAA,CAAA,EAAA,IAAA,IA9IF,qBA8IE;AAAyD,UApFrD,cAAA,CAoFqD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAhDpD;;cAGL,OAAA;;;;;;;wBAQU;;;;;;;;;;;;;;;;;;4BAgCK,IAAI;;aAKnB,KAAK,oDAAoD,UAAU;;;;;;;;;;;;MA8B3C;aASxB;yBAIY,UAAU;;;;;;;;gDAaa,IAAI;;;;;;;;gCAgCpB;sCAKnB,gCACc"}
|
package/dist/journal.d.ts
CHANGED
|
@@ -64,6 +64,22 @@ declare class Journal {
|
|
|
64
64
|
private readonly fixtureCountsMaxTestIds;
|
|
65
65
|
private readonly onAdd?;
|
|
66
66
|
constructor(options?: JournalOptions);
|
|
67
|
+
/**
|
|
68
|
+
* The per-test-id cap on fixture match-count maps, for an MCP mount to pass
|
|
69
|
+
* to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`
|
|
70
|
+
* meaning unbounded, and never throws, whatever option was passed:
|
|
71
|
+
* omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above
|
|
72
|
+
* `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more
|
|
73
|
+
* is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values
|
|
74
|
+
* it is the number of test ids the journal keeps.
|
|
75
|
+
*
|
|
76
|
+
* An option between 0 and 1 is the exception. The journal keeps no test id
|
|
77
|
+
* (each new count map is evicted as soon as it is made, so counts never
|
|
78
|
+
* advance), and a store cap cannot say "keep none" because `0` is
|
|
79
|
+
* unbounded. The getter returns `1`, the smallest bounded cap, so a store
|
|
80
|
+
* given it keeps 1 test id where the journal keeps 0.
|
|
81
|
+
*/
|
|
82
|
+
get fixtureCountsMaxTestIdsCap(): number;
|
|
67
83
|
/** Backwards-compatible accessor — returns the default (no testId) count map. */
|
|
68
84
|
get fixtureMatchCounts(): Map<Fixture, number>;
|
|
69
85
|
/** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */
|
package/dist/journal.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.d.ts","names":[],"sources":["../src/journal.ts"],"sourcesContent":[],"mappings":";;;;;;;AA8DA;;;;;AA4DA;AAuCA;;;;;;
|
|
1
|
+
{"version":3,"file":"journal.d.ts","names":[],"sources":["../src/journal.ts"],"sourcesContent":[],"mappings":";;;;;;;AA8DA;;;;;AA4DA;AAuCA;;;;;;AA6Ca,iBAhJG,oBAAA,CAgJH,IAAA,EA/IL,WA+IK,GAAA,IAAA,GAAA,SAAA,CAAA,EAAA,IAAA,IA9IF,qBA8IE;AAAyD,UApFrD,cAAA,CAoFqD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAhDpD;;cAGL,OAAA;;;;;;;wBAQU;;;;;;;;;;;;;;;;;;4BAgCK,IAAI;;aAKnB,KAAK,oDAAoD,UAAU;;;;;;;;;;;;MA8B3C;aASxB;yBAIY,UAAU;;;;;;;;gDAaa,IAAI;;;;;;;;gCAgCpB;sCAKnB,gCACc"}
|
package/dist/journal.js
CHANGED
|
@@ -92,6 +92,26 @@ var Journal = class {
|
|
|
92
92
|
const testIdCap = options.fixtureCountsMaxTestIds;
|
|
93
93
|
this.fixtureCountsMaxTestIds = testIdCap !== void 0 && testIdCap > 0 ? testIdCap : 0;
|
|
94
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* The per-test-id cap on fixture match-count maps, for an MCP mount to pass
|
|
97
|
+
* to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`
|
|
98
|
+
* meaning unbounded, and never throws, whatever option was passed:
|
|
99
|
+
* omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above
|
|
100
|
+
* `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more
|
|
101
|
+
* is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values
|
|
102
|
+
* it is the number of test ids the journal keeps.
|
|
103
|
+
*
|
|
104
|
+
* An option between 0 and 1 is the exception. The journal keeps no test id
|
|
105
|
+
* (each new count map is evicted as soon as it is made, so counts never
|
|
106
|
+
* advance), and a store cap cannot say "keep none" because `0` is
|
|
107
|
+
* unbounded. The getter returns `1`, the smallest bounded cap, so a store
|
|
108
|
+
* given it keeps 1 test id where the journal keeps 0.
|
|
109
|
+
*/
|
|
110
|
+
get fixtureCountsMaxTestIdsCap() {
|
|
111
|
+
const cap = this.fixtureCountsMaxTestIds;
|
|
112
|
+
if (!(cap > 0) || cap > Number.MAX_SAFE_INTEGER) return 0;
|
|
113
|
+
return Math.max(1, Math.floor(cap));
|
|
114
|
+
}
|
|
95
115
|
/** Backwards-compatible accessor — returns the default (no testId) count map. */
|
|
96
116
|
get fixtureMatchCounts() {
|
|
97
117
|
return this.getFixtureMatchCountsForTest(DEFAULT_TEST_ID);
|
package/dist/journal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.js","names":[],"sources":["../src/journal.ts"],"sourcesContent":["import { generateId } from \"./helpers.js\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureMatch,\n JournalBody,\n JournalEntry,\n} from \"./types.js\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nexport { DEFAULT_TEST_ID } from \"./constants.js\";\n\n/**\n * Maximum UTF-8 byte length of a serialized request body retained in a\n * journal entry. Bodies whose JSON serialization exceeds this byte size are\n * replaced with a truncation marker.\n *\n * Only the request `body` field is capped here. `headers` and `path` are\n * retained uncapped, but they are naturally bounded by Node's default ~16 KB\n * maximum HTTP header size, so the per-entry overhead beyond the body cap\n * remains small. Combined with the journal's maxEntries limit (default 1000),\n * the total `JSON.stringify(journal.getAll())` output stays well under V8's\n * ~512 MB string limit even at maximum capacity.\n */\nconst JOURNAL_BODY_CAP_BYTES = 64 * 1024; // 64 KB\n\n/**\n * If `body` serializes to more than JOURNAL_BODY_CAP_BYTES (in UTF-8 bytes),\n * replace it with a truncation marker. Returns the original body when within\n * the cap, or null when `body` is null.\n *\n * The gate uses Buffer.byteLength (UTF-8 bytes) rather than .length (UTF-16\n * code units) to match the constant name and to correctly cap multibyte\n * content (e.g. CJK/emoji) whose code-unit count falls under the threshold\n * but whose byte size does not.\n */\nfunction capBody(body: JournalBody | null): JournalBody | null {\n if (body === null) return null;\n const serialized = JSON.stringify(body);\n if (Buffer.byteLength(serialized, \"utf8\") <= JOURNAL_BODY_CAP_BYTES) return body;\n // The marker is not a chat request, and `JournalBody` no longer claims it is\n // — downstream consumers (e.g. GET /journal) treat the body as opaque JSON.\n return {\n __aimock_truncated: true,\n originalByteSize: Buffer.byteLength(serialized, \"utf8\"),\n note: \"body truncated by aimock journal cap (64 KB limit)\",\n };\n}\n\n/**\n * Narrow a journaled body to a chat-completion request.\n *\n * `JournalEntry.body` is a union (see {@link JournalBody}): most entries hold a\n * chat request, but the fine-tuning create payload and this module's own\n * truncation marker do not. Anything reading `messages`, `model` or the rest of\n * the chat shape off a journal entry — inside aimock or in a consumer's test\n * — goes through here, so an entry that is not a chat request fails as a\n * `false` it can assert on rather than as an undefined property three accesses\n * later.\n *\n * `messages` is the discriminator because it is the one required field no\n * other journaled shape carries.\n */\nexport function isChatCompletionBody(\n body: JournalBody | null | undefined,\n): body is ChatCompletionRequest {\n return (\n body !== null &&\n body !== undefined &&\n Array.isArray((body as { messages?: unknown }).messages) &&\n typeof (body as { model?: unknown }).model === \"string\"\n );\n}\n\n/**\n * Compare two field values, handling RegExp by source+flags rather than reference.\n */\nfunction fieldEqual(a: unknown, b: unknown): boolean {\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return a === b;\n}\n\n/**\n * Compare two systemMessage values. Handles string, string[], and RegExp.\n * Both-undefined is treated as equal.\n */\nfunction systemMessageEqual(\n a: string | string[] | RegExp | undefined,\n b: string | string[] | RegExp | undefined,\n): boolean {\n if (a === undefined && b === undefined) return true;\n if (a === undefined || b === undefined) return false;\n if (typeof a === \"string\" && typeof b === \"string\") return a === b;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i]);\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return false;\n}\n\n/**\n * Check whether two fixture match objects have the same criteria\n * (ignoring sequenceIndex). Used to group sequenced fixtures.\n */\nfunction matchCriteriaEqual(a: FixtureMatch, b: FixtureMatch): boolean {\n return (\n fieldEqual(a.userMessage, b.userMessage) &&\n systemMessageEqual(a.systemMessage, b.systemMessage) &&\n fieldEqual(a.inputText, b.inputText) &&\n fieldEqual(a.toolCallId, b.toolCallId) &&\n fieldEqual(a.toolName, b.toolName) &&\n fieldEqual(a.model, b.model) &&\n fieldEqual(a.responseFormat, b.responseFormat) &&\n fieldEqual(a.predicate, b.predicate) &&\n fieldEqual(a.endpoint, b.endpoint) &&\n fieldEqual(a.turnIndex, b.turnIndex) &&\n fieldEqual(a.hasToolResult, b.hasToolResult) &&\n fieldEqual(a.toolResultContains, b.toolResultContains) &&\n fieldEqual(a.context, b.context)\n );\n}\n\nexport interface JournalOptions {\n /**\n * Maximum number of entries to retain. When exceeded, oldest entries are\n * dropped FIFO. Set to 0 (or omit) for unbounded retention (the historical\n * default — suitable for short-lived test runs only). Negative values are\n * rejected at the CLI parse layer; programmatically they are treated as 0\n * (unbounded) for back-compat.\n *\n * Long-running servers (e.g. mock proxies in CI/demo environments) should\n * always set a finite cap: every request appends an entry holding the\n * request body + headers + fixture reference, and without a cap the\n * journal grows until the process OOMs.\n */\n maxEntries?: number;\n /**\n * Maximum number of unique testIds retained in the fixture match-count\n * map (`fixtureMatchCountsByTestId`). When exceeded, the oldest testId\n * (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for\n * unbounded retention. Negative values are rejected at the CLI parse\n * layer; programmatically they are treated as 0 (unbounded) for\n * back-compat. Without a cap this map can grow over time in long-running\n * servers that see many unique testIds.\n */\n fixtureCountsMaxTestIds?: number;\n /**\n * Called with every entry {@link Journal.add} creates, right after it is\n * recorded. The hook exists so an embedder can attribute an entry to the\n * request that produced it WITHOUT touching each of the ~100 `journal.add`\n * call sites spread across the handler modules: the server binds the entry\n * to the in-flight `IncomingMessage` here, and its error arm then amends\n * that exact object rather than guessing from a caller-supplied header.\n *\n * The entry is already recorded when the hook runs, so a hook that throws\n * does not lose the write — but it does propagate out of `add` into the\n * caller's error path, so a hook must not throw.\n */\n onAdd?: (entry: JournalEntry) => void;\n}\n\nexport class Journal {\n private entries: JournalEntry[] = [];\n private readonly matchedFixtures = new WeakMap<JournalEntry, Fixture>();\n private readonly fixtureMatchCountsByTestId: Map<string, Map<Fixture, number>> = new Map();\n private readonly maxEntries: number;\n private readonly fixtureCountsMaxTestIds: number;\n private readonly onAdd?: (entry: JournalEntry) => void;\n\n constructor(options: JournalOptions = {}) {\n this.onAdd = options.onAdd;\n // Treat 0 or negative as \"unbounded\" to preserve prior behavior when\n // the option is omitted or explicitly disabled.\n const cap = options.maxEntries;\n this.maxEntries = cap !== undefined && cap > 0 ? cap : 0;\n const testIdCap = options.fixtureCountsMaxTestIds;\n this.fixtureCountsMaxTestIds = testIdCap !== undefined && testIdCap > 0 ? testIdCap : 0;\n }\n\n /** Backwards-compatible accessor — returns the default (no testId) count map. */\n get fixtureMatchCounts(): Map<Fixture, number> {\n return this.getFixtureMatchCountsForTest(DEFAULT_TEST_ID);\n }\n\n /** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */\n add(entry: Omit<JournalEntry, \"id\" | \"timestamp\">, matchedFixture?: Fixture): JournalEntry {\n const full: JournalEntry = {\n id: generateId(\"req\"),\n timestamp: Date.now(),\n ...entry,\n body: capBody(entry.body),\n };\n if (matchedFixture) this.matchedFixtures.set(full, matchedFixture);\n this.entries.push(full);\n // FIFO eviction when over capacity. Array.prototype.shift() is O(n)\n // regardless of how many we drop per add; we accept it at small caps\n // (default 1000) because the constant factor is tiny and this runs once\n // per request. For much larger caps, switch to a ring buffer for true\n // O(1) eviction.\n if (this.maxEntries > 0 && this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n this.onAdd?.(full);\n return full;\n }\n\n /**\n * Return every entry, or with `limit` the most recent `limit` entries.\n * `0` returns `[]` — exactly what `GET /__aimock/journal?limit=0` answers.\n * `slice(-0)` is `slice(0)`, so a `0` used to return the ENTIRE journal; it\n * is special-cased so the library and the HTTP route agree. This is a public\n * library API, so odd limits are tolerated rather than thrown on: a\n * non-finite limit (`NaN`, `Infinity`) means \"no limit\", a fractional limit\n * floors, and any limit at or below `0` asks for nothing.\n */\n getAll(opts?: { limit?: number }): JournalEntry[] {\n if (opts?.limit !== undefined && Number.isFinite(opts.limit)) {\n const limit = Math.floor(opts.limit);\n if (limit <= 0) return [];\n return this.entries.slice(-limit);\n }\n return this.entries.slice();\n }\n\n getLast(): JournalEntry | null {\n return this.entries.length > 0 ? this.entries[this.entries.length - 1] : null;\n }\n\n findByFixture(fixture: Fixture): JournalEntry[] {\n return this.entries.filter(\n (e) => (this.matchedFixtures.get(e) ?? e.response.fixture) === fixture,\n );\n }\n\n /**\n * READ-ONLY accessor. Returns the existing count map for `testId`, or an\n * empty transient Map if none exists. Does NOT insert into the cache and\n * does NOT trigger FIFO eviction — callers may read freely without\n * perturbing cache state. For the write path, see\n * `getOrCreateFixtureMatchCountsForTest`.\n */\n getFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n return this.fixtureMatchCountsByTestId.get(testId) ?? new Map();\n }\n\n /**\n * WRITE path: get the count map for `testId`, inserting a fresh empty Map\n * if missing and running FIFO eviction when the testId cap is exceeded.\n * Only callers that intend to mutate the map (e.g. incrementing a count)\n * should use this.\n */\n private getOrCreateFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n let counts = this.fixtureMatchCountsByTestId.get(testId);\n if (!counts) {\n counts = new Map();\n this.fixtureMatchCountsByTestId.set(testId, counts);\n // FIFO eviction when over capacity. JS Map preserves insertion order,\n // so the first key returned by keys() is the oldest. Same O(n) shift\n // caveat as `entries`: acceptable at small caps (default 500).\n if (\n this.fixtureCountsMaxTestIds > 0 &&\n this.fixtureMatchCountsByTestId.size > this.fixtureCountsMaxTestIds\n ) {\n const oldest = this.fixtureMatchCountsByTestId.keys().next().value;\n if (oldest !== undefined) {\n this.fixtureMatchCountsByTestId.delete(oldest);\n }\n }\n }\n return counts;\n }\n\n getFixtureMatchCount(fixture: Fixture, testId = DEFAULT_TEST_ID): number {\n return this.getFixtureMatchCountsForTest(testId).get(fixture) ?? 0;\n }\n\n incrementFixtureMatchCount(\n fixture: Fixture,\n allFixtures?: readonly Fixture[],\n testId = DEFAULT_TEST_ID,\n ): void {\n const counts = this.getOrCreateFixtureMatchCountsForTest(testId);\n counts.set(fixture, (counts.get(fixture) ?? 0) + 1);\n // When a sequenced fixture matches, also increment all siblings with matching criteria\n if (fixture.match.sequenceIndex !== undefined && allFixtures) {\n for (const sibling of allFixtures) {\n if (sibling === fixture) continue;\n if (sibling.match.sequenceIndex === undefined) continue;\n if (matchCriteriaEqual(fixture.match, sibling.match)) {\n counts.set(sibling, (counts.get(sibling) ?? 0) + 1);\n }\n }\n }\n }\n\n clearMatchCounts(testId?: string): void {\n if (testId !== undefined) {\n this.fixtureMatchCountsByTestId.delete(testId);\n } else {\n this.fixtureMatchCountsByTestId.clear();\n }\n }\n\n /**\n * Clear ONLY the request journal entries, preserving fixture match-counts.\n * Match-counts are fixture-matching/sequencing state, not journal data, so\n * clearing the journal must not silently rewind sequenced fixtures. Used by\n * `POST /__aimock/reset/journal`. For a full reset (entries + match-counts),\n * use `clear()` instead.\n */\n clearEntries(): void {\n this.entries = [];\n }\n\n clear(): void {\n this.entries = [];\n this.fixtureMatchC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AAO,IAAI,QAAQ,IAAI,KAAK,EAAE;;;CAM3D,iBAAiB,QAAuB;AACtC,MAAI,WAAW,OACb,MAAK,2BAA2B,OAAO,OAAO;MAE9C,MAAK,2BAA2B,OAAO;;;;;;;;;CAW3C,eAAqB;AACnB,OAAK,UAAU,EAAE;;CAGnB,QAAc;AACZ,OAAK,UAAU,EAAE;AACjB,OAAK,2BAA2B,OAAO;;CAGzC,IAAI,OAAe;AACjB,SAAO,KAAK,QAAQ"}
|
|
1
|
+
{"version":3,"file":"journal.js","names":[],"sources":["../src/journal.ts"],"sourcesContent":["import { generateId } from \"./helpers.js\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureMatch,\n JournalBody,\n JournalEntry,\n} from \"./types.js\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nexport { DEFAULT_TEST_ID } from \"./constants.js\";\n\n/**\n * Maximum UTF-8 byte length of a serialized request body retained in a\n * journal entry. Bodies whose JSON serialization exceeds this byte size are\n * replaced with a truncation marker.\n *\n * Only the request `body` field is capped here. `headers` and `path` are\n * retained uncapped, but they are naturally bounded by Node's default ~16 KB\n * maximum HTTP header size, so the per-entry overhead beyond the body cap\n * remains small. Combined with the journal's maxEntries limit (default 1000),\n * the total `JSON.stringify(journal.getAll())` output stays well under V8's\n * ~512 MB string limit even at maximum capacity.\n */\nconst JOURNAL_BODY_CAP_BYTES = 64 * 1024; // 64 KB\n\n/**\n * If `body` serializes to more than JOURNAL_BODY_CAP_BYTES (in UTF-8 bytes),\n * replace it with a truncation marker. Returns the original body when within\n * the cap, or null when `body` is null.\n *\n * The gate uses Buffer.byteLength (UTF-8 bytes) rather than .length (UTF-16\n * code units) to match the constant name and to correctly cap multibyte\n * content (e.g. CJK/emoji) whose code-unit count falls under the threshold\n * but whose byte size does not.\n */\nfunction capBody(body: JournalBody | null): JournalBody | null {\n if (body === null) return null;\n const serialized = JSON.stringify(body);\n if (Buffer.byteLength(serialized, \"utf8\") <= JOURNAL_BODY_CAP_BYTES) return body;\n // The marker is not a chat request, and `JournalBody` no longer claims it is\n // — downstream consumers (e.g. GET /journal) treat the body as opaque JSON.\n return {\n __aimock_truncated: true,\n originalByteSize: Buffer.byteLength(serialized, \"utf8\"),\n note: \"body truncated by aimock journal cap (64 KB limit)\",\n };\n}\n\n/**\n * Narrow a journaled body to a chat-completion request.\n *\n * `JournalEntry.body` is a union (see {@link JournalBody}): most entries hold a\n * chat request, but the fine-tuning create payload and this module's own\n * truncation marker do not. Anything reading `messages`, `model` or the rest of\n * the chat shape off a journal entry — inside aimock or in a consumer's test\n * — goes through here, so an entry that is not a chat request fails as a\n * `false` it can assert on rather than as an undefined property three accesses\n * later.\n *\n * `messages` is the discriminator because it is the one required field no\n * other journaled shape carries.\n */\nexport function isChatCompletionBody(\n body: JournalBody | null | undefined,\n): body is ChatCompletionRequest {\n return (\n body !== null &&\n body !== undefined &&\n Array.isArray((body as { messages?: unknown }).messages) &&\n typeof (body as { model?: unknown }).model === \"string\"\n );\n}\n\n/**\n * Compare two field values, handling RegExp by source+flags rather than reference.\n */\nfunction fieldEqual(a: unknown, b: unknown): boolean {\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return a === b;\n}\n\n/**\n * Compare two systemMessage values. Handles string, string[], and RegExp.\n * Both-undefined is treated as equal.\n */\nfunction systemMessageEqual(\n a: string | string[] | RegExp | undefined,\n b: string | string[] | RegExp | undefined,\n): boolean {\n if (a === undefined && b === undefined) return true;\n if (a === undefined || b === undefined) return false;\n if (typeof a === \"string\" && typeof b === \"string\") return a === b;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i]);\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return false;\n}\n\n/**\n * Check whether two fixture match objects have the same criteria\n * (ignoring sequenceIndex). Used to group sequenced fixtures.\n */\nfunction matchCriteriaEqual(a: FixtureMatch, b: FixtureMatch): boolean {\n return (\n fieldEqual(a.userMessage, b.userMessage) &&\n systemMessageEqual(a.systemMessage, b.systemMessage) &&\n fieldEqual(a.inputText, b.inputText) &&\n fieldEqual(a.toolCallId, b.toolCallId) &&\n fieldEqual(a.toolName, b.toolName) &&\n fieldEqual(a.model, b.model) &&\n fieldEqual(a.responseFormat, b.responseFormat) &&\n fieldEqual(a.predicate, b.predicate) &&\n fieldEqual(a.endpoint, b.endpoint) &&\n fieldEqual(a.turnIndex, b.turnIndex) &&\n fieldEqual(a.hasToolResult, b.hasToolResult) &&\n fieldEqual(a.toolResultContains, b.toolResultContains) &&\n fieldEqual(a.context, b.context)\n );\n}\n\nexport interface JournalOptions {\n /**\n * Maximum number of entries to retain. When exceeded, oldest entries are\n * dropped FIFO. Set to 0 (or omit) for unbounded retention (the historical\n * default — suitable for short-lived test runs only). Negative values are\n * rejected at the CLI parse layer; programmatically they are treated as 0\n * (unbounded) for back-compat.\n *\n * Long-running servers (e.g. mock proxies in CI/demo environments) should\n * always set a finite cap: every request appends an entry holding the\n * request body + headers + fixture reference, and without a cap the\n * journal grows until the process OOMs.\n */\n maxEntries?: number;\n /**\n * Maximum number of unique testIds retained in the fixture match-count\n * map (`fixtureMatchCountsByTestId`). When exceeded, the oldest testId\n * (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for\n * unbounded retention. Negative values are rejected at the CLI parse\n * layer; programmatically they are treated as 0 (unbounded) for\n * back-compat. Without a cap this map can grow over time in long-running\n * servers that see many unique testIds.\n */\n fixtureCountsMaxTestIds?: number;\n /**\n * Called with every entry {@link Journal.add} creates, right after it is\n * recorded. The hook exists so an embedder can attribute an entry to the\n * request that produced it WITHOUT touching each of the ~100 `journal.add`\n * call sites spread across the handler modules: the server binds the entry\n * to the in-flight `IncomingMessage` here, and its error arm then amends\n * that exact object rather than guessing from a caller-supplied header.\n *\n * The entry is already recorded when the hook runs, so a hook that throws\n * does not lose the write — but it does propagate out of `add` into the\n * caller's error path, so a hook must not throw.\n */\n onAdd?: (entry: JournalEntry) => void;\n}\n\nexport class Journal {\n private entries: JournalEntry[] = [];\n private readonly matchedFixtures = new WeakMap<JournalEntry, Fixture>();\n private readonly fixtureMatchCountsByTestId: Map<string, Map<Fixture, number>> = new Map();\n private readonly maxEntries: number;\n private readonly fixtureCountsMaxTestIds: number;\n private readonly onAdd?: (entry: JournalEntry) => void;\n\n constructor(options: JournalOptions = {}) {\n this.onAdd = options.onAdd;\n // Treat 0 or negative as \"unbounded\" to preserve prior behavior when\n // the option is omitted or explicitly disabled.\n const cap = options.maxEntries;\n this.maxEntries = cap !== undefined && cap > 0 ? cap : 0;\n const testIdCap = options.fixtureCountsMaxTestIds;\n this.fixtureCountsMaxTestIds = testIdCap !== undefined && testIdCap > 0 ? testIdCap : 0;\n }\n\n /**\n * The per-test-id cap on fixture match-count maps, for an MCP mount to pass\n * to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`\n * meaning unbounded, and never throws, whatever option was passed:\n * omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above\n * `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more\n * is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values\n * it is the number of test ids the journal keeps.\n *\n * An option between 0 and 1 is the exception. The journal keeps no test id\n * (each new count map is evicted as soon as it is made, so counts never\n * advance), and a store cap cannot say \"keep none\" because `0` is\n * unbounded. The getter returns `1`, the smallest bounded cap, so a store\n * given it keeps 1 test id where the journal keeps 0.\n */\n get fixtureCountsMaxTestIdsCap(): number {\n const cap = this.fixtureCountsMaxTestIds;\n if (!(cap > 0) || cap > Number.MAX_SAFE_INTEGER) return 0;\n return Math.max(1, Math.floor(cap));\n }\n\n /** Backwards-compatible accessor — returns the default (no testId) count map. */\n get fixtureMatchCounts(): Map<Fixture, number> {\n return this.getFixtureMatchCountsForTest(DEFAULT_TEST_ID);\n }\n\n /** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */\n add(entry: Omit<JournalEntry, \"id\" | \"timestamp\">, matchedFixture?: Fixture): JournalEntry {\n const full: JournalEntry = {\n id: generateId(\"req\"),\n timestamp: Date.now(),\n ...entry,\n body: capBody(entry.body),\n };\n if (matchedFixture) this.matchedFixtures.set(full, matchedFixture);\n this.entries.push(full);\n // FIFO eviction when over capacity. Array.prototype.shift() is O(n)\n // regardless of how many we drop per add; we accept it at small caps\n // (default 1000) because the constant factor is tiny and this runs once\n // per request. For much larger caps, switch to a ring buffer for true\n // O(1) eviction.\n if (this.maxEntries > 0 && this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n this.onAdd?.(full);\n return full;\n }\n\n /**\n * Return every entry, or with `limit` the most recent `limit` entries.\n * `0` returns `[]` — exactly what `GET /__aimock/journal?limit=0` answers.\n * `slice(-0)` is `slice(0)`, so a `0` used to return the ENTIRE journal; it\n * is special-cased so the library and the HTTP route agree. This is a public\n * library API, so odd limits are tolerated rather than thrown on: a\n * non-finite limit (`NaN`, `Infinity`) means \"no limit\", a fractional limit\n * floors, and any limit at or below `0` asks for nothing.\n */\n getAll(opts?: { limit?: number }): JournalEntry[] {\n if (opts?.limit !== undefined && Number.isFinite(opts.limit)) {\n const limit = Math.floor(opts.limit);\n if (limit <= 0) return [];\n return this.entries.slice(-limit);\n }\n return this.entries.slice();\n }\n\n getLast(): JournalEntry | null {\n return this.entries.length > 0 ? this.entries[this.entries.length - 1] : null;\n }\n\n findByFixture(fixture: Fixture): JournalEntry[] {\n return this.entries.filter(\n (e) => (this.matchedFixtures.get(e) ?? e.response.fixture) === fixture,\n );\n }\n\n /**\n * READ-ONLY accessor. Returns the existing count map for `testId`, or an\n * empty transient Map if none exists. Does NOT insert into the cache and\n * does NOT trigger FIFO eviction — callers may read freely without\n * perturbing cache state. For the write path, see\n * `getOrCreateFixtureMatchCountsForTest`.\n */\n getFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n return this.fixtureMatchCountsByTestId.get(testId) ?? new Map();\n }\n\n /**\n * WRITE path: get the count map for `testId`, inserting a fresh empty Map\n * if missing and running FIFO eviction when the testId cap is exceeded.\n * Only callers that intend to mutate the map (e.g. incrementing a count)\n * should use this.\n */\n private getOrCreateFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n let counts = this.fixtureMatchCountsByTestId.get(testId);\n if (!counts) {\n counts = new Map();\n this.fixtureMatchCountsByTestId.set(testId, counts);\n // FIFO eviction when over capacity. JS Map preserves insertion order,\n // so the first key returned by keys() is the oldest. Same O(n) shift\n // caveat as `entries`: acceptable at small caps (createServer\n // default 500; a bare Journal is unbounded).\n if (\n this.fixtureCountsMaxTestIds > 0 &&\n this.fixtureMatchCountsByTestId.size > this.fixtureCountsMaxTestIds\n ) {\n const oldest = this.fixtureMatchCountsByTestId.keys().next().value;\n if (oldest !== undefined) {\n this.fixtureMatchCountsByTestId.delete(oldest);\n }\n }\n }\n return counts;\n }\n\n getFixtureMatchCount(fixture: Fixture, testId = DEFAULT_TEST_ID): number {\n return this.getFixtureMatchCountsForTest(testId).get(fixture) ?? 0;\n }\n\n incrementFixtureMatchCount(\n fixture: Fixture,\n allFixtures?: readonly Fixture[],\n testId = DEFAULT_TEST_ID,\n ): void {\n const counts = this.getOrCreateFixtureMatchCountsForTest(testId);\n counts.set(fixture, (counts.get(fixture) ?? 0) + 1);\n // When a sequenced fixture matches, also increment all siblings with matching criteria\n if (fixture.match.sequenceIndex !== undefined && allFixtures) {\n for (const sibling of allFixtures) {\n if (sibling === fixture) continue;\n if (sibling.match.sequenceIndex === undefined) continue;\n if (matchCriteriaEqual(fixture.match, sibling.match)) {\n counts.set(sibling, (counts.get(sibling) ?? 0) + 1);\n }\n }\n }\n }\n\n clearMatchCounts(testId?: string): void {\n if (testId !== undefined) {\n this.fixtureMatchCountsByTestId.delete(testId);\n } else {\n this.fixtureMatchCountsByTestId.clear();\n }\n }\n\n /**\n * Clear ONLY the request journal entries, preserving fixture match-counts.\n * Match-counts are fixture-matching/sequencing state, not journal data, so\n * clearing the journal must not silently rewind sequenced fixtures. Used by\n * `POST /__aimock/reset/journal`. For a full reset (entries + match-counts),\n * use `clear()` instead.\n */\n clearEntries(): void {\n this.entries = [];\n }\n\n clear(): void {\n this.entries = [];\n this.fixtureMatchCountsByTestId.clear();\n }\n\n get size(): number {\n return this.entries.length;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAM,yBAAyB,KAAK;;;;;;;;;;;AAYpC,SAAS,QAAQ,MAA8C;AAC7D,KAAI,SAAS,KAAM,QAAO;CAC1B,MAAM,aAAa,KAAK,UAAU,KAAK;AACvC,KAAI,OAAO,WAAW,YAAY,OAAO,IAAI,uBAAwB,QAAO;AAG5E,QAAO;EACL,oBAAoB;EACpB,kBAAkB,OAAO,WAAW,YAAY,OAAO;EACvD,MAAM;EACP;;;;;;;;;;;;;;;;AAiBH,SAAgB,qBACd,MAC+B;AAC/B,QACE,SAAS,QACT,SAAS,UACT,MAAM,QAAS,KAAgC,SAAS,IACxD,OAAQ,KAA6B,UAAU;;;;;AAOnD,SAAS,WAAW,GAAY,GAAqB;AACnD,KAAI,aAAa,UAAU,aAAa,OACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE;AAChD,QAAO,MAAM;;;;;;AAOf,SAAS,mBACP,GACA,GACS;AACT,KAAI,MAAM,UAAa,MAAM,OAAW,QAAO;AAC/C,KAAI,MAAM,UAAa,MAAM,OAAW,QAAO;AAC/C,KAAI,OAAO,MAAM,YAAY,OAAO,MAAM,SAAU,QAAO,MAAM;AACjE,KAAI,MAAM,QAAQ,EAAE,IAAI,MAAM,QAAQ,EAAE,CACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,GAAG,MAAM,MAAM,EAAE,GAAG;AAC/D,KAAI,aAAa,UAAU,aAAa,OACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE;AAChD,QAAO;;;;;;AAOT,SAAS,mBAAmB,GAAiB,GAA0B;AACrE,QACE,WAAW,EAAE,aAAa,EAAE,YAAY,IACxC,mBAAmB,EAAE,e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