@copilotkit/aimock 1.11.0 → 1.13.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/README.md +24 -4
- package/dist/_virtual/_rolldown/runtime.cjs +2 -0
- package/dist/_virtual/_rolldown/runtime.js +29 -0
- package/dist/agui-types.d.cts.map +1 -1
- package/dist/aimock-cli.cjs +16 -0
- package/dist/aimock-cli.cjs.map +1 -1
- package/dist/aimock-cli.d.cts +2 -0
- package/dist/aimock-cli.d.cts.map +1 -1
- package/dist/aimock-cli.d.ts +2 -0
- package/dist/aimock-cli.d.ts.map +1 -1
- package/dist/aimock-cli.js +16 -0
- package/dist/aimock-cli.js.map +1 -1
- package/dist/bedrock-converse.cjs +2 -0
- 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 +2 -0
- package/dist/bedrock-converse.js.map +1 -1
- package/dist/bedrock.cjs +2 -0
- package/dist/bedrock.cjs.map +1 -1
- package/dist/bedrock.d.cts.map +1 -1
- package/dist/bedrock.d.ts.map +1 -1
- package/dist/bedrock.js +2 -0
- package/dist/bedrock.js.map +1 -1
- package/dist/cohere.cjs +1 -0
- package/dist/cohere.cjs.map +1 -1
- package/dist/cohere.js +1 -0
- package/dist/cohere.js.map +1 -1
- package/dist/config-loader.d.cts.map +1 -1
- package/dist/convert-mockllm.cjs +232 -0
- package/dist/convert-mockllm.cjs.map +1 -0
- package/dist/convert-mockllm.js +230 -0
- package/dist/convert-mockllm.js.map +1 -0
- package/dist/convert-vidaimock.cjs +110 -0
- package/dist/convert-vidaimock.cjs.map +1 -0
- package/dist/convert-vidaimock.js +108 -0
- package/dist/convert-vidaimock.js.map +1 -0
- package/dist/convert.cjs +158 -0
- package/dist/convert.cjs.map +1 -0
- package/dist/convert.d.cts +16 -0
- package/dist/convert.d.cts.map +1 -0
- package/dist/convert.d.ts +16 -0
- package/dist/convert.d.ts.map +1 -0
- package/dist/convert.js +157 -0
- package/dist/convert.js.map +1 -0
- package/dist/embeddings.cjs +2 -1
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.js +2 -1
- package/dist/embeddings.js.map +1 -1
- package/dist/gemini.cjs +1 -0
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.js +1 -0
- package/dist/gemini.js.map +1 -1
- package/dist/helpers.cjs +16 -0
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts +6 -2
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.ts +6 -2
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +13 -1
- package/dist/helpers.js.map +1 -1
- package/dist/images.cjs +166 -0
- package/dist/images.cjs.map +1 -0
- package/dist/images.d.cts +11 -0
- package/dist/images.d.cts.map +1 -0
- package/dist/images.d.ts +11 -0
- package/dist/images.d.ts.map +1 -0
- package/dist/images.js +166 -0
- package/dist/images.js.map +1 -0
- package/dist/index.cjs +13 -0
- package/dist/index.d.cts +7 -3
- package/dist/index.d.ts +7 -3
- package/dist/index.js +6 -2
- package/dist/jest.cjs +70 -0
- package/dist/jest.cjs.map +1 -0
- package/dist/jest.d.cts +33 -0
- package/dist/jest.d.cts.map +1 -0
- package/dist/jest.d.ts +33 -0
- package/dist/jest.d.ts.map +1 -0
- package/dist/jest.js +67 -0
- package/dist/jest.js.map +1 -0
- package/dist/llmock.cjs +37 -1
- package/dist/llmock.cjs.map +1 -1
- package/dist/llmock.d.cts +5 -1
- package/dist/llmock.d.cts.map +1 -1
- package/dist/llmock.d.ts +5 -1
- package/dist/llmock.d.ts.map +1 -1
- package/dist/llmock.js +37 -1
- package/dist/llmock.js.map +1 -1
- package/dist/messages.cjs +1 -0
- package/dist/messages.cjs.map +1 -1
- package/dist/messages.js +1 -0
- package/dist/messages.js.map +1 -1
- package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.cjs +934 -0
- package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.js +934 -0
- package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.cjs +1051 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.js +1042 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/index.cjs +1 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/index.js +3 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.cjs +96 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +93 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.cjs +49 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.js +43 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.cjs +456 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.js +456 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.cjs +170 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.js +169 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.js.map +1 -0
- package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.cjs +388 -0
- package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js +385 -0
- package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.cjs +12 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.js +12 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.cjs +17 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.js +17 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.cjs +12 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.js +12 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.cjs +16 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.js +16 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.cjs +14 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.js +14 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.cjs +35 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.js +35 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.cjs +13 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.js +13 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.cjs +128 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.js +123 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.cjs +41 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.js +40 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.cjs +100 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.js +100 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.cjs +26 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.js +26 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.cjs +15 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.js +15 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.cjs +22 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.js +22 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.cjs +7 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.js +6 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.cjs +13 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.js +13 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.cjs +19 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.js +19 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.cjs +26 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.js +26 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.cjs +10 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.js +9 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.cjs +31 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.js +31 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.js.map +1 -0
- package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.cjs +52 -0
- package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.js +52 -0
- package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.js.map +1 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.cjs +83 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.cjs.map +1 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.js +82 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.js.map +1 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.cjs +10 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.cjs.map +1 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.js +10 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.js.map +1 -0
- package/dist/ollama.cjs +2 -0
- 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 +2 -0
- package/dist/ollama.js.map +1 -1
- package/dist/recorder.cjs +50 -7
- package/dist/recorder.cjs.map +1 -1
- package/dist/recorder.js +50 -7
- package/dist/recorder.js.map +1 -1
- package/dist/responses.cjs +1 -0
- package/dist/responses.cjs.map +1 -1
- package/dist/responses.js +1 -0
- package/dist/responses.js.map +1 -1
- package/dist/router.cjs +8 -0
- package/dist/router.cjs.map +1 -1
- package/dist/router.d.cts.map +1 -1
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +9 -0
- package/dist/router.js.map +1 -1
- package/dist/server.cjs +80 -3
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +2 -0
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.ts +2 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +80 -3
- package/dist/server.js.map +1 -1
- package/dist/speech.cjs +144 -0
- package/dist/speech.cjs.map +1 -0
- package/dist/speech.d.cts +11 -0
- package/dist/speech.d.cts.map +1 -0
- package/dist/speech.d.ts +11 -0
- package/dist/speech.d.ts.map +1 -0
- package/dist/speech.js +144 -0
- package/dist/speech.js.map +1 -0
- package/dist/transcription.cjs +134 -0
- package/dist/transcription.cjs.map +1 -0
- package/dist/transcription.d.cts +11 -0
- package/dist/transcription.d.cts.map +1 -0
- package/dist/transcription.d.ts +11 -0
- package/dist/transcription.d.ts.map +1 -0
- package/dist/transcription.js +134 -0
- package/dist/transcription.js.map +1 -0
- package/dist/types.d.cts +44 -2
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +44 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/video.cjs +196 -0
- package/dist/video.cjs.map +1 -0
- package/dist/video.d.cts +14 -0
- package/dist/video.d.cts.map +1 -0
- package/dist/video.d.ts +14 -0
- package/dist/video.d.ts.map +1 -0
- package/dist/video.js +195 -0
- package/dist/video.js.map +1 -0
- package/dist/vitest.cjs +80 -0
- package/dist/vitest.cjs.map +1 -0
- package/dist/vitest.d.cts +30 -0
- package/dist/vitest.d.cts.map +1 -0
- package/dist/vitest.d.ts +30 -0
- package/dist/vitest.d.ts.map +1 -0
- package/dist/vitest.js +77 -0
- package/dist/vitest.js.map +1 -0
- package/fixtures/examples/a2a/a2a-config.json +42 -0
- package/fixtures/examples/agui/agui-text-response.json +35 -0
- package/fixtures/examples/chaos/chaos-config.json +10 -0
- package/fixtures/examples/full-suite.json +116 -0
- package/fixtures/examples/llm/embeddings.json +10 -0
- package/fixtures/examples/llm/error-injection.json +15 -0
- package/fixtures/examples/llm/sequential-responses.json +20 -0
- package/fixtures/examples/llm/streaming-physics.json +15 -0
- package/fixtures/examples/mcp/mcp-config.json +26 -0
- package/fixtures/examples/record-replay/record-config.json +11 -0
- package/fixtures/examples/vector/vector-config.json +34 -0
- package/package.json +60 -2
package/dist/helpers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","names":[],"sources":["../src/helpers.ts"],"sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\nimport type * as http from \"node:http\";\nimport type {\n FixtureResponse,\n TextResponse,\n ToolCallResponse,\n ContentWithToolCallsResponse,\n ErrorResponse,\n EmbeddingResponse,\n SSEChunk,\n ToolCall,\n ChatCompletion,\n} from \"./types.js\";\n\nconst REDACTED_HEADERS = new Set([\"authorization\", \"x-api-key\", \"api-key\"]);\n\nexport function flattenHeaders(headers: http.IncomingHttpHeaders): Record<string, string> {\n const flat: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n if (REDACTED_HEADERS.has(key.toLowerCase())) {\n flat[key] = \"[REDACTED]\";\n } else {\n flat[key] = Array.isArray(value) ? value.join(\", \") : value;\n }\n }\n return flat;\n}\n\nexport function generateId(prefix = \"chatcmpl\"): string {\n return `${prefix}-${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateToolCallId(): string {\n return `call_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateMessageId(): string {\n return `msg_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateToolUseId(): string {\n return `toolu_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function isTextResponse(r: FixtureResponse): r is TextResponse {\n return \"content\" in r && typeof (r as TextResponse).content === \"string\";\n}\n\nexport function isToolCallResponse(r: FixtureResponse): r is ToolCallResponse {\n return \"toolCalls\" in r && Array.isArray((r as ToolCallResponse).toolCalls);\n}\n\nexport function isContentWithToolCallsResponse(\n r: FixtureResponse,\n): r is ContentWithToolCallsResponse {\n return (\n \"content\" in r &&\n typeof (r as ContentWithToolCallsResponse).content === \"string\" &&\n \"toolCalls\" in r &&\n Array.isArray((r as ContentWithToolCallsResponse).toolCalls)\n );\n}\n\nexport function isErrorResponse(r: FixtureResponse): r is ErrorResponse {\n return (\n \"error\" in r &&\n (r as ErrorResponse).error !== null &&\n typeof (r as ErrorResponse).error === \"object\"\n );\n}\n\nexport function isEmbeddingResponse(r: FixtureResponse): r is EmbeddingResponse {\n return \"embedding\" in r && Array.isArray((r as EmbeddingResponse).embedding);\n}\n\nexport function buildTextChunks(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n): SSEChunk[] {\n const id = generateId();\n const created = Math.floor(Date.now() / 1000);\n const chunks: SSEChunk[] = [];\n\n // Reasoning chunks (emitted before content, OpenRouter format)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { reasoning_content: slice }, finish_reason: null }],\n });\n }\n }\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { role: \"assistant\", content: \"\" }, finish_reason: null }],\n });\n\n // Content chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { content: slice }, finish_reason: null }],\n });\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }],\n });\n\n return chunks;\n}\n\nexport function buildToolCallChunks(\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n): SSEChunk[] {\n const id = generateId();\n const created = Math.floor(Date.now() / 1000);\n const chunks: SSEChunk[] = [];\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { role: \"assistant\", content: null }, finish_reason: null }],\n });\n\n // Tool call chunks — one initial chunk per tool call, then argument chunks\n for (let tcIdx = 0; tcIdx < toolCalls.length; tcIdx++) {\n const tc = toolCalls[tcIdx];\n const tcId = tc.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: tc.name, arguments: \"\" },\n },\n ],\n },\n finish_reason: null,\n },\n ],\n });\n\n // Argument streaming chunks\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n finish_reason: null,\n },\n ],\n });\n }\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: {}, finish_reason: \"tool_calls\" }],\n });\n\n return chunks;\n}\n\n// Non-streaming response builders\n\nexport function buildTextCompletion(\n content: string,\n model: string,\n reasoning?: string,\n): ChatCompletion {\n return {\n id: generateId(),\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [\n {\n index: 0,\n message: {\n role: \"assistant\",\n content,\n refusal: null,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n}\n\nexport function buildToolCallCompletion(toolCalls: ToolCall[], model: string): ChatCompletion {\n return {\n id: generateId(),\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [\n {\n index: 0,\n message: {\n role: \"assistant\",\n content: null,\n refusal: null,\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id || generateToolCallId(),\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n })),\n },\n finish_reason: \"tool_calls\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n}\n\nexport function buildContentWithToolCallsChunks(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n): SSEChunk[] {\n const id = generateId();\n const created = Math.floor(Date.now() / 1000);\n const chunks: SSEChunk[] = [];\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { role: \"assistant\", content: \"\" }, finish_reason: null }],\n });\n\n // Content chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { content: slice }, finish_reason: null }],\n });\n }\n\n // Tool call chunks — one initial chunk per tool call, then argument chunks\n for (let tcIdx = 0; tcIdx < toolCalls.length; tcIdx++) {\n const tc = toolCalls[tcIdx];\n const tcId = tc.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: tc.name, arguments: \"\" },\n },\n ],\n },\n finish_reason: null,\n },\n ],\n });\n\n // Argument streaming chunks\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n finish_reason: null,\n },\n ],\n });\n }\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: {}, finish_reason: \"tool_calls\" }],\n });\n\n return chunks;\n}\n\nexport function buildContentWithToolCallsCompletion(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n): ChatCompletion {\n return {\n id: generateId(),\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [\n {\n index: 0,\n message: {\n role: \"assistant\",\n content,\n refusal: null,\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id || generateToolCallId(),\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n })),\n },\n finish_reason: \"tool_calls\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n}\n\n// ─── HTTP helpers ─────────────────────────────────────────────────────────\n\nexport function readBody(req: http.IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n\n// ─── Pattern matching ─────────────────────────────────────────────────────\n\nexport function matchesPattern(text: string, pattern: string | RegExp): boolean {\n if (typeof pattern === \"string\") {\n return text.toLowerCase().includes(pattern.toLowerCase());\n }\n return pattern.test(text);\n}\n\nexport function getTestId(req: http.IncomingMessage): string {\n const headerValue = req.headers[\"x-test-id\"];\n if (Array.isArray(headerValue)) {\n if (headerValue.length > 0 && headerValue[0]) return headerValue[0];\n } else if (typeof headerValue === \"string\" && headerValue) {\n return headerValue;\n }\n\n const url = req.url ?? \"/\";\n const qIdx = url.indexOf(\"?\");\n if (qIdx !== -1) {\n const params = new URLSearchParams(url.slice(qIdx + 1));\n const queryValue = params.get(\"testId\");\n if (queryValue) return queryValue;\n }\n\n // Duplicated from journal.ts DEFAULT_TEST_ID — importing it here would create\n // a circular dependency (journal.ts imports from helpers.ts).\n return \"__default__\";\n}\n\n// ─── Embedding helpers ─────────────────────────────────────────────────────\n\nconst DEFAULT_EMBEDDING_DIMENSIONS = 1536;\n\n/**\n * Generate a deterministic embedding vector from input text.\n * Hashes the input with SHA-256 and spreads the hash bytes across\n * the requested number of dimensions, producing values in [-1, 1].\n */\nexport function generateDeterministicEmbedding(\n input: string,\n dimensions: number = DEFAULT_EMBEDDING_DIMENSIONS,\n): number[] {\n let currentHash = createHash(\"sha256\").update(input).digest();\n const embedding: number[] = new Array(dimensions);\n for (let i = 0; i < dimensions; i++) {\n if (i > 0 && i % 32 === 0) {\n currentHash = createHash(\"sha256\").update(currentHash).digest();\n }\n // Map 0-255 → -1.0 to 1.0\n embedding[i] = currentHash[i % 32] / 127.5 - 1;\n }\n return embedding;\n}\n\nexport interface EmbeddingAPIResponse {\n object: \"list\";\n data: { object: \"embedding\"; index: number; embedding: number[] }[];\n model: string;\n usage: { prompt_tokens: number; total_tokens: number };\n}\n\n/**\n * Build an OpenAI-format embeddings API response for one or more inputs.\n */\nexport function buildEmbeddingResponse(\n embeddings: number[][],\n model: string,\n): EmbeddingAPIResponse {\n return {\n object: \"list\",\n data: embeddings.map((embedding, index) => ({\n object: \"embedding\" as const,\n index,\n embedding,\n })),\n model,\n usage: { prompt_tokens: 0, total_tokens: 0 },\n };\n}\n"],"mappings":";;;AAcA,MAAM,mBAAmB,IAAI,IAAI;CAAC;CAAiB;CAAa;CAAU,CAAC;AAE3E,SAAgB,eAAe,SAA2D;CACxF,MAAM,OAA+B,EAAE;AACvC,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,EAAE;AAClD,MAAI,UAAU,OAAW;AACzB,MAAI,iBAAiB,IAAI,IAAI,aAAa,CAAC,CACzC,MAAK,OAAO;MAEZ,MAAK,OAAO,MAAM,QAAQ,MAAM,GAAG,MAAM,KAAK,KAAK,GAAG;;AAG1D,QAAO;;AAGT,SAAgB,WAAW,SAAS,YAAoB;AACtD,QAAO,GAAG,OAAO,GAAG,YAAY,GAAG,CAAC,SAAS,YAAY;;AAG3D,SAAgB,qBAA6B;AAC3C,QAAO,QAAQ,YAAY,GAAG,CAAC,SAAS,YAAY;;AAGtD,SAAgB,oBAA4B;AAC1C,QAAO,OAAO,YAAY,GAAG,CAAC,SAAS,YAAY;;AAGrD,SAAgB,oBAA4B;AAC1C,QAAO,SAAS,YAAY,GAAG,CAAC,SAAS,YAAY;;AAGvD,SAAgB,eAAe,GAAuC;AACpE,QAAO,aAAa,KAAK,OAAQ,EAAmB,YAAY;;AAGlE,SAAgB,mBAAmB,GAA2C;AAC5E,QAAO,eAAe,KAAK,MAAM,QAAS,EAAuB,UAAU;;AAG7E,SAAgB,+BACd,GACmC;AACnC,QACE,aAAa,KACb,OAAQ,EAAmC,YAAY,YACvD,eAAe,KACf,MAAM,QAAS,EAAmC,UAAU;;AAIhE,SAAgB,gBAAgB,GAAwC;AACtE,QACE,WAAW,KACV,EAAoB,UAAU,QAC/B,OAAQ,EAAoB,UAAU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crypto\";\nimport type * as http from \"node:http\";\nimport type {\n FixtureResponse,\n TextResponse,\n ToolCallResponse,\n ContentWithToolCallsResponse,\n ErrorResponse,\n EmbeddingResponse,\n ImageResponse,\n AudioResponse,\n TranscriptionResponse,\n VideoResponse,\n SSEChunk,\n ToolCall,\n ChatCompletion,\n} from \"./types.js\";\n\nconst REDACTED_HEADERS = new Set([\"authorization\", \"x-api-key\", \"api-key\"]);\n\nexport function flattenHeaders(headers: http.IncomingHttpHeaders): Record<string, string> {\n const flat: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n if (REDACTED_HEADERS.has(key.toLowerCase())) {\n flat[key] = \"[REDACTED]\";\n } else {\n flat[key] = Array.isArray(value) ? value.join(\", \") : value;\n }\n }\n return flat;\n}\n\nexport function generateId(prefix = \"chatcmpl\"): string {\n return `${prefix}-${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateToolCallId(): string {\n return `call_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateMessageId(): string {\n return `msg_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateToolUseId(): string {\n return `toolu_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function isTextResponse(r: FixtureResponse): r is TextResponse {\n return \"content\" in r && typeof (r as TextResponse).content === \"string\";\n}\n\nexport function isToolCallResponse(r: FixtureResponse): r is ToolCallResponse {\n return \"toolCalls\" in r && Array.isArray((r as ToolCallResponse).toolCalls);\n}\n\nexport function isContentWithToolCallsResponse(\n r: FixtureResponse,\n): r is ContentWithToolCallsResponse {\n return (\n \"content\" in r &&\n typeof (r as ContentWithToolCallsResponse).content === \"string\" &&\n \"toolCalls\" in r &&\n Array.isArray((r as ContentWithToolCallsResponse).toolCalls)\n );\n}\n\nexport function isErrorResponse(r: FixtureResponse): r is ErrorResponse {\n return (\n \"error\" in r &&\n (r as ErrorResponse).error !== null &&\n typeof (r as ErrorResponse).error === \"object\"\n );\n}\n\nexport function isEmbeddingResponse(r: FixtureResponse): r is EmbeddingResponse {\n return \"embedding\" in r && Array.isArray((r as EmbeddingResponse).embedding);\n}\n\nexport function isImageResponse(r: FixtureResponse): r is ImageResponse {\n return (\n (\"image\" in r && r.image != null) ||\n (\"images\" in r && Array.isArray((r as ImageResponse).images))\n );\n}\n\nexport function isAudioResponse(r: FixtureResponse): r is AudioResponse {\n return \"audio\" in r && typeof (r as AudioResponse).audio === \"string\";\n}\n\nexport function isTranscriptionResponse(r: FixtureResponse): r is TranscriptionResponse {\n return (\n \"transcription\" in r &&\n (r as TranscriptionResponse).transcription != null &&\n typeof (r as TranscriptionResponse).transcription === \"object\"\n );\n}\n\nexport function isVideoResponse(r: FixtureResponse): r is VideoResponse {\n return (\n \"video\" in r &&\n (r as VideoResponse).video != null &&\n typeof (r as VideoResponse).video === \"object\"\n );\n}\n\nexport function buildTextChunks(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n): SSEChunk[] {\n const id = generateId();\n const created = Math.floor(Date.now() / 1000);\n const chunks: SSEChunk[] = [];\n\n // Reasoning chunks (emitted before content, OpenRouter format)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { reasoning_content: slice }, finish_reason: null }],\n });\n }\n }\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { role: \"assistant\", content: \"\" }, finish_reason: null }],\n });\n\n // Content chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { content: slice }, finish_reason: null }],\n });\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: {}, finish_reason: \"stop\" }],\n });\n\n return chunks;\n}\n\nexport function buildToolCallChunks(\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n): SSEChunk[] {\n const id = generateId();\n const created = Math.floor(Date.now() / 1000);\n const chunks: SSEChunk[] = [];\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { role: \"assistant\", content: null }, finish_reason: null }],\n });\n\n // Tool call chunks — one initial chunk per tool call, then argument chunks\n for (let tcIdx = 0; tcIdx < toolCalls.length; tcIdx++) {\n const tc = toolCalls[tcIdx];\n const tcId = tc.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: tc.name, arguments: \"\" },\n },\n ],\n },\n finish_reason: null,\n },\n ],\n });\n\n // Argument streaming chunks\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n finish_reason: null,\n },\n ],\n });\n }\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: {}, finish_reason: \"tool_calls\" }],\n });\n\n return chunks;\n}\n\n// Non-streaming response builders\n\nexport function buildTextCompletion(\n content: string,\n model: string,\n reasoning?: string,\n): ChatCompletion {\n return {\n id: generateId(),\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [\n {\n index: 0,\n message: {\n role: \"assistant\",\n content,\n refusal: null,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n },\n finish_reason: \"stop\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n}\n\nexport function buildToolCallCompletion(toolCalls: ToolCall[], model: string): ChatCompletion {\n return {\n id: generateId(),\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [\n {\n index: 0,\n message: {\n role: \"assistant\",\n content: null,\n refusal: null,\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id || generateToolCallId(),\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n })),\n },\n finish_reason: \"tool_calls\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n}\n\nexport function buildContentWithToolCallsChunks(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n): SSEChunk[] {\n const id = generateId();\n const created = Math.floor(Date.now() / 1000);\n const chunks: SSEChunk[] = [];\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { role: \"assistant\", content: \"\" }, finish_reason: null }],\n });\n\n // Content chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: { content: slice }, finish_reason: null }],\n });\n }\n\n // Tool call chunks — one initial chunk per tool call, then argument chunks\n for (let tcIdx = 0; tcIdx < toolCalls.length; tcIdx++) {\n const tc = toolCalls[tcIdx];\n const tcId = tc.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: tc.name, arguments: \"\" },\n },\n ],\n },\n finish_reason: null,\n },\n ],\n });\n\n // Argument streaming chunks\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n finish_reason: null,\n },\n ],\n });\n }\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [{ index: 0, delta: {}, finish_reason: \"tool_calls\" }],\n });\n\n return chunks;\n}\n\nexport function buildContentWithToolCallsCompletion(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n): ChatCompletion {\n return {\n id: generateId(),\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [\n {\n index: 0,\n message: {\n role: \"assistant\",\n content,\n refusal: null,\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id || generateToolCallId(),\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n })),\n },\n finish_reason: \"tool_calls\",\n },\n ],\n usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },\n };\n}\n\n// ─── HTTP helpers ─────────────────────────────────────────────────────────\n\nexport function readBody(req: http.IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n\n// ─── Pattern matching ─────────────────────────────────────────────────────\n\nexport function matchesPattern(text: string, pattern: string | RegExp): boolean {\n if (typeof pattern === \"string\") {\n return text.toLowerCase().includes(pattern.toLowerCase());\n }\n return pattern.test(text);\n}\n\nexport function getTestId(req: http.IncomingMessage): string {\n const headerValue = req.headers[\"x-test-id\"];\n if (Array.isArray(headerValue)) {\n if (headerValue.length > 0 && headerValue[0]) return headerValue[0];\n } else if (typeof headerValue === \"string\" && headerValue) {\n return headerValue;\n }\n\n const url = req.url ?? \"/\";\n const qIdx = url.indexOf(\"?\");\n if (qIdx !== -1) {\n const params = new URLSearchParams(url.slice(qIdx + 1));\n const queryValue = params.get(\"testId\");\n if (queryValue) return queryValue;\n }\n\n // Duplicated from journal.ts DEFAULT_TEST_ID — importing it here would create\n // a circular dependency (journal.ts imports from helpers.ts).\n return \"__default__\";\n}\n\n// ─── Embedding helpers ─────────────────────────────────────────────────────\n\nconst DEFAULT_EMBEDDING_DIMENSIONS = 1536;\n\n/**\n * Generate a deterministic embedding vector from input text.\n * Hashes the input with SHA-256 and spreads the hash bytes across\n * the requested number of dimensions, producing values in [-1, 1].\n */\nexport function generateDeterministicEmbedding(\n input: string,\n dimensions: number = DEFAULT_EMBEDDING_DIMENSIONS,\n): number[] {\n let currentHash = createHash(\"sha256\").update(input).digest();\n const embedding: number[] = new Array(dimensions);\n for (let i = 0; i < dimensions; i++) {\n if (i > 0 && i % 32 === 0) {\n currentHash = createHash(\"sha256\").update(currentHash).digest();\n }\n // Map 0-255 → -1.0 to 1.0\n embedding[i] = currentHash[i % 32] / 127.5 - 1;\n }\n return embedding;\n}\n\nexport interface EmbeddingAPIResponse {\n object: \"list\";\n data: { object: \"embedding\"; index: number; embedding: number[] }[];\n model: string;\n usage: { prompt_tokens: number; total_tokens: number };\n}\n\n/**\n * Build an OpenAI-format embeddings API response for one or more inputs.\n */\nexport function buildEmbeddingResponse(\n embeddings: number[][],\n model: string,\n): EmbeddingAPIResponse {\n return {\n object: \"list\",\n data: embeddings.map((embedding, index) => ({\n object: \"embedding\" as const,\n index,\n embedding,\n })),\n model,\n usage: { prompt_tokens: 0, total_tokens: 0 },\n };\n}\n"],"mappings":";;;AAkBA,MAAM,mBAAmB,IAAI,IAAI;CAAC;CAAiB;CAAa;CAAU,CAAC;AAE3E,SAAgB,eAAe,SAA2D;CACxF,MAAM,OAA+B,EAAE;AACvC,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,EAAE;AAClD,MAAI,UAAU,OAAW;AACzB,MAAI,iBAAiB,IAAI,IAAI,aAAa,CAAC,CACzC,MAAK,OAAO;MAEZ,MAAK,OAAO,MAAM,QAAQ,MAAM,GAAG,MAAM,KAAK,KAAK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,aAAa,CAAC;AAE3D,QAAO,QAAQ,KAAK,KAAK;;AAG3B,SAAgB,UAAU,KAAmC;CAC3D,MAAM,cAAc,IAAI,QAAQ;AAChC,KAAI,MAAM,QAAQ,YAAY,EAC5B;MAAI,YAAY,SAAS,KAAK,YAAY,GAAI,QAAO,YAAY;YACxD,OAAO,gBAAgB,YAAY,YAC5C,QAAO;CAGT,MAAM,MAAM,IAAI,OAAO;CACvB,MAAM,OAAO,IAAI,QAAQ,IAAI;AAC7B,KAAI,SAAS,IAAI;EAEf,MAAM,aADS,IAAI,gBAAgB,IAAI,MAAM,OAAO,EAAE,CAAC,CAC7B,IAAI,SAAS;AACvC,MAAI,WAAY,QAAO;;AAKzB,QAAO;;AAKT,MAAM,+BAA+B;;;;;;AAOrC,SAAgB,+BACd,OACA,aAAqB,8BACX;CACV,IAAI,cAAc,WAAW,SAAS,CAAC,OAAO,MAAM,CAAC,QAAQ;CAC7D,MAAM,YAAsB,IAAI,MAAM,WAAW;AACjD,MAAK,IAAI,IAAI,GAAG,IAAI,YAAY,KAAK;AACnC,MAAI,IAAI,KAAK,IAAI,OAAO,EACtB,eAAc,WAAW,SAAS,CAAC,OAAO,YAAY,CAAC,QAAQ;AAGjE,YAAU,KAAK,YAAY,IAAI,MAAM,QAAQ;;AAE/C,QAAO;;;;;AAaT,SAAgB,uBACd,YACA,OACsB;AACtB,QAAO;EACL,QAAQ;EACR,MAAM,WAAW,KAAK,WAAW,WAAW;GAC1C,QAAQ;GACR;GACA;GACD,EAAE;EACH;EACA,OAAO;GAAE,eAAe;GAAG,cAAc;GAAG;EAC7C"}
|
package/dist/images.cjs
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
const require_helpers = require('./helpers.cjs');
|
|
2
|
+
const require_router = require('./router.cjs');
|
|
3
|
+
const require_sse_writer = require('./sse-writer.cjs');
|
|
4
|
+
const require_chaos = require('./chaos.cjs');
|
|
5
|
+
const require_recorder = require('./recorder.cjs');
|
|
6
|
+
|
|
7
|
+
//#region src/images.ts
|
|
8
|
+
function buildSyntheticRequest(model, prompt) {
|
|
9
|
+
return {
|
|
10
|
+
model,
|
|
11
|
+
messages: [{
|
|
12
|
+
role: "user",
|
|
13
|
+
content: prompt
|
|
14
|
+
}],
|
|
15
|
+
_endpointType: "image"
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
async function handleImages(req, res, raw, fixtures, journal, defaults, setCorsHeaders, format = "openai", geminiModel) {
|
|
19
|
+
setCorsHeaders(res);
|
|
20
|
+
const path = req.url ?? "/v1/images/generations";
|
|
21
|
+
const method = req.method ?? "POST";
|
|
22
|
+
let model;
|
|
23
|
+
let prompt;
|
|
24
|
+
try {
|
|
25
|
+
const body = JSON.parse(raw);
|
|
26
|
+
if (format === "gemini") {
|
|
27
|
+
prompt = body.instances?.[0]?.prompt ?? "";
|
|
28
|
+
model = geminiModel ?? "imagen";
|
|
29
|
+
} else {
|
|
30
|
+
const openaiReq = body;
|
|
31
|
+
prompt = openaiReq.prompt ?? "";
|
|
32
|
+
model = openaiReq.model ?? "dall-e-3";
|
|
33
|
+
}
|
|
34
|
+
} catch {
|
|
35
|
+
journal.add({
|
|
36
|
+
method,
|
|
37
|
+
path,
|
|
38
|
+
headers: require_helpers.flattenHeaders(req.headers),
|
|
39
|
+
body: null,
|
|
40
|
+
response: {
|
|
41
|
+
status: 400,
|
|
42
|
+
fixture: null
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
|
|
46
|
+
message: "Malformed JSON",
|
|
47
|
+
type: "invalid_request_error",
|
|
48
|
+
code: "invalid_json"
|
|
49
|
+
} }));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const syntheticReq = buildSyntheticRequest(model, prompt);
|
|
53
|
+
const testId = require_helpers.getTestId(req);
|
|
54
|
+
const fixture = require_router.matchFixture(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
|
|
55
|
+
if (fixture) journal.incrementFixtureMatchCount(fixture, fixtures, testId);
|
|
56
|
+
if (require_chaos.applyChaos(res, fixture, defaults.chaos, req.headers, journal, {
|
|
57
|
+
method,
|
|
58
|
+
path,
|
|
59
|
+
headers: require_helpers.flattenHeaders(req.headers),
|
|
60
|
+
body: syntheticReq
|
|
61
|
+
}, defaults.registry, defaults.logger)) return;
|
|
62
|
+
if (!fixture) {
|
|
63
|
+
if (defaults.record) {
|
|
64
|
+
if (await require_recorder.proxyAndRecord(req, res, syntheticReq, format === "gemini" ? "gemini" : "openai", req.url ?? "/v1/images/generations", fixtures, defaults, raw)) {
|
|
65
|
+
journal.add({
|
|
66
|
+
method,
|
|
67
|
+
path,
|
|
68
|
+
headers: require_helpers.flattenHeaders(req.headers),
|
|
69
|
+
body: syntheticReq,
|
|
70
|
+
response: {
|
|
71
|
+
status: res.statusCode ?? 200,
|
|
72
|
+
fixture: null
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const strictStatus = defaults.strict ? 503 : 404;
|
|
79
|
+
const strictMessage = defaults.strict ? "Strict mode: no fixture matched" : "No fixture matched";
|
|
80
|
+
journal.add({
|
|
81
|
+
method,
|
|
82
|
+
path,
|
|
83
|
+
headers: require_helpers.flattenHeaders(req.headers),
|
|
84
|
+
body: syntheticReq,
|
|
85
|
+
response: {
|
|
86
|
+
status: strictStatus,
|
|
87
|
+
fixture: null
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
require_sse_writer.writeErrorResponse(res, strictStatus, JSON.stringify({ error: {
|
|
91
|
+
message: strictMessage,
|
|
92
|
+
type: "invalid_request_error",
|
|
93
|
+
code: "no_fixture_match"
|
|
94
|
+
} }));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const response = fixture.response;
|
|
98
|
+
if (require_helpers.isErrorResponse(response)) {
|
|
99
|
+
const status = response.status ?? 500;
|
|
100
|
+
journal.add({
|
|
101
|
+
method,
|
|
102
|
+
path,
|
|
103
|
+
headers: require_helpers.flattenHeaders(req.headers),
|
|
104
|
+
body: syntheticReq,
|
|
105
|
+
response: {
|
|
106
|
+
status,
|
|
107
|
+
fixture
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
require_sse_writer.writeErrorResponse(res, status, JSON.stringify(response));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (!require_helpers.isImageResponse(response)) {
|
|
114
|
+
journal.add({
|
|
115
|
+
method,
|
|
116
|
+
path,
|
|
117
|
+
headers: require_helpers.flattenHeaders(req.headers),
|
|
118
|
+
body: syntheticReq,
|
|
119
|
+
response: {
|
|
120
|
+
status: 500,
|
|
121
|
+
fixture
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
|
|
125
|
+
message: "Fixture response is not an image type",
|
|
126
|
+
type: "server_error"
|
|
127
|
+
} }));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
journal.add({
|
|
131
|
+
method,
|
|
132
|
+
path,
|
|
133
|
+
headers: require_helpers.flattenHeaders(req.headers),
|
|
134
|
+
body: syntheticReq,
|
|
135
|
+
response: {
|
|
136
|
+
status: 200,
|
|
137
|
+
fixture
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
const items = response.images ?? (response.image ? [response.image] : []);
|
|
141
|
+
if (format === "gemini") {
|
|
142
|
+
const predictions = items.map((item) => ({
|
|
143
|
+
bytesBase64Encoded: item.b64Json ?? "",
|
|
144
|
+
mimeType: "image/png"
|
|
145
|
+
}));
|
|
146
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
147
|
+
res.end(JSON.stringify({ predictions }));
|
|
148
|
+
} else {
|
|
149
|
+
const data = items.map((item) => {
|
|
150
|
+
const entry = {};
|
|
151
|
+
if (item.url) entry.url = item.url;
|
|
152
|
+
if (item.b64Json) entry.b64_json = item.b64Json;
|
|
153
|
+
if (item.revisedPrompt) entry.revised_prompt = item.revisedPrompt;
|
|
154
|
+
return entry;
|
|
155
|
+
});
|
|
156
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
157
|
+
res.end(JSON.stringify({
|
|
158
|
+
created: Math.floor(Date.now() / 1e3),
|
|
159
|
+
data
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
//#endregion
|
|
165
|
+
exports.handleImages = handleImages;
|
|
166
|
+
//# sourceMappingURL=images.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"images.cjs","names":["flattenHeaders","getTestId","matchFixture","applyChaos","proxyAndRecord","isErrorResponse","isImageResponse"],"sources":["../src/images.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport type { ChatCompletionRequest, Fixture, HandlerDefaults } from \"./types.js\";\nimport { isImageResponse, isErrorResponse, flattenHeaders, getTestId } from \"./helpers.js\";\nimport { matchFixture } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\ninterface OpenAIImageRequest {\n model?: string;\n prompt: string;\n n?: number;\n size?: string;\n response_format?: \"url\" | \"b64_json\";\n [key: string]: unknown;\n}\n\ninterface GeminiPredictRequest {\n instances: Array<{ prompt: string }>;\n parameters?: { sampleCount?: number };\n [key: string]: unknown;\n}\n\nfunction buildSyntheticRequest(model: string, prompt: string): ChatCompletionRequest {\n return {\n model,\n messages: [{ role: \"user\", content: prompt }],\n _endpointType: \"image\",\n };\n}\n\nexport async function handleImages(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n format: \"openai\" | \"gemini\" = \"openai\",\n geminiModel?: string,\n): Promise<void> {\n setCorsHeaders(res);\n const path = req.url ?? \"/v1/images/generations\";\n const method = req.method ?? \"POST\";\n\n let model: string;\n let prompt: string;\n\n try {\n const body = JSON.parse(raw);\n if (format === \"gemini\") {\n const geminiReq = body as GeminiPredictRequest;\n prompt = geminiReq.instances?.[0]?.prompt ?? \"\";\n model = geminiModel ?? \"imagen\";\n } else {\n const openaiReq = body as OpenAIImageRequest;\n prompt = openaiReq.prompt ?? \"\";\n model = openaiReq.model ?? \"dall-e-3\";\n }\n } catch {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: { message: \"Malformed JSON\", type: \"invalid_request_error\", code: \"invalid_json\" },\n }),\n );\n return;\n }\n\n const syntheticReq = buildSyntheticRequest(model, prompt);\n const testId = getTestId(req);\n const fixture = matchFixture(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n if (defaults.record) {\n const proxied = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n format === \"gemini\" ? \"gemini\" : \"openai\",\n req.url ?? \"/v1/images/generations\",\n fixtures,\n defaults,\n raw,\n );\n if (proxied) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null },\n });\n return;\n }\n }\n\n const strictStatus = defaults.strict ? 503 : 404;\n const strictMessage = defaults.strict\n ? \"Strict mode: no fixture matched\"\n : \"No fixture matched\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: strictStatus, fixture: null },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: { message: strictMessage, type: \"invalid_request_error\", code: \"no_fixture_match\" },\n }),\n );\n return;\n }\n\n const response = fixture.response;\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, JSON.stringify(response));\n return;\n }\n\n if (!isImageResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: { message: \"Fixture response is not an image type\", type: \"server_error\" },\n }),\n );\n return;\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n // Normalize to array of image items\n const items = response.images ?? (response.image ? [response.image] : []);\n\n if (format === \"gemini\") {\n const predictions = items.map((item) => ({\n bytesBase64Encoded: item.b64Json ?? \"\",\n mimeType: \"image/png\" as const,\n }));\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ predictions }));\n } else {\n const data = items.map((item) => {\n const entry: Record<string, string> = {};\n if (item.url) entry.url = item.url;\n if (item.b64Json) entry.b64_json = item.b64Json;\n if (item.revisedPrompt) entry.revised_prompt = item.revisedPrompt;\n return entry;\n });\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ created: Math.floor(Date.now() / 1000), data }));\n }\n}\n"],"mappings":";;;;;;;AAwBA,SAAS,sBAAsB,OAAe,QAAuC;AACnF,QAAO;EACL;EACA,UAAU,CAAC;GAAE,MAAM;GAAQ,SAAS;GAAQ,CAAC;EAC7C,eAAe;EAChB;;AAGH,eAAsB,aACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACA,SAA8B,UAC9B,aACe;AACf,gBAAe,IAAI;CACnB,MAAM,OAAO,IAAI,OAAO;CACxB,MAAM,SAAS,IAAI,UA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OAAM,MAAM,KAAK;AAC/B,OAAI,KAAK,QAAS,OAAM,WAAW,KAAK;AACxC,OAAI,KAAK,cAAe,OAAM,iBAAiB,KAAK;AACpD,UAAO;IACP;AACF,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IAAI,KAAK,UAAU;GAAE,SAAS,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;GAAE;GAAM,CAAC,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Journal } from "./journal.cjs";
|
|
2
|
+
import { Fixture, HandlerDefaults } from "./types.cjs";
|
|
3
|
+
import * as http from "node:http";
|
|
4
|
+
|
|
5
|
+
//#region src/images.d.ts
|
|
6
|
+
declare function handleImages(req: http.IncomingMessage, res: http.ServerResponse, raw: string, fixtures: Fixture[], journal: Journal, defaults: HandlerDefaults, setCorsHeaders: (res: http.ServerResponse) => void, format?: "openai" | "gemini", geminiModel?: string): Promise<void>;
|
|
7
|
+
//# sourceMappingURL=images.d.ts.map
|
|
8
|
+
|
|
9
|
+
//#endregion
|
|
10
|
+
export { handleImages };
|
|
11
|
+
//# sourceMappingURL=images.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"images.d.cts","names":[],"sources":["../src/images.ts"],"sourcesContent":[],"mappings":";;;;;iBAgCsB,YAAA,MACf,IAAA,CAAK,sBACL,IAAA,CAAK,uCAEA,oBACD,mBACC,uCACY,IAAA,CAAK,8EAG1B"}
|
package/dist/images.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Journal } from "./journal.js";
|
|
2
|
+
import { Fixture, HandlerDefaults } from "./types.js";
|
|
3
|
+
import * as http from "node:http";
|
|
4
|
+
|
|
5
|
+
//#region src/images.d.ts
|
|
6
|
+
declare function handleImages(req: http.IncomingMessage, res: http.ServerResponse, raw: string, fixtures: Fixture[], journal: Journal, defaults: HandlerDefaults, setCorsHeaders: (res: http.ServerResponse) => void, format?: "openai" | "gemini", geminiModel?: string): Promise<void>;
|
|
7
|
+
//# sourceMappingURL=images.d.ts.map
|
|
8
|
+
|
|
9
|
+
//#endregion
|
|
10
|
+
export { handleImages };
|
|
11
|
+
//# sourceMappingURL=images.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"images.d.ts","names":[],"sources":["../src/images.ts"],"sourcesContent":[],"mappings":";;;;;iBAgCsB,YAAA,MACf,IAAA,CAAK,sBACL,IAAA,CAAK,uCAEA,oBACD,mBACC,uCACY,IAAA,CAAK,8EAG1B"}
|
package/dist/images.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { flattenHeaders, getTestId, isErrorResponse, isImageResponse } from "./helpers.js";
|
|
2
|
+
import { matchFixture } from "./router.js";
|
|
3
|
+
import { writeErrorResponse } from "./sse-writer.js";
|
|
4
|
+
import { applyChaos } from "./chaos.js";
|
|
5
|
+
import { proxyAndRecord } from "./recorder.js";
|
|
6
|
+
|
|
7
|
+
//#region src/images.ts
|
|
8
|
+
function buildSyntheticRequest(model, prompt) {
|
|
9
|
+
return {
|
|
10
|
+
model,
|
|
11
|
+
messages: [{
|
|
12
|
+
role: "user",
|
|
13
|
+
content: prompt
|
|
14
|
+
}],
|
|
15
|
+
_endpointType: "image"
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
async function handleImages(req, res, raw, fixtures, journal, defaults, setCorsHeaders, format = "openai", geminiModel) {
|
|
19
|
+
setCorsHeaders(res);
|
|
20
|
+
const path = req.url ?? "/v1/images/generations";
|
|
21
|
+
const method = req.method ?? "POST";
|
|
22
|
+
let model;
|
|
23
|
+
let prompt;
|
|
24
|
+
try {
|
|
25
|
+
const body = JSON.parse(raw);
|
|
26
|
+
if (format === "gemini") {
|
|
27
|
+
prompt = body.instances?.[0]?.prompt ?? "";
|
|
28
|
+
model = geminiModel ?? "imagen";
|
|
29
|
+
} else {
|
|
30
|
+
const openaiReq = body;
|
|
31
|
+
prompt = openaiReq.prompt ?? "";
|
|
32
|
+
model = openaiReq.model ?? "dall-e-3";
|
|
33
|
+
}
|
|
34
|
+
} catch {
|
|
35
|
+
journal.add({
|
|
36
|
+
method,
|
|
37
|
+
path,
|
|
38
|
+
headers: flattenHeaders(req.headers),
|
|
39
|
+
body: null,
|
|
40
|
+
response: {
|
|
41
|
+
status: 400,
|
|
42
|
+
fixture: null
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
writeErrorResponse(res, 400, JSON.stringify({ error: {
|
|
46
|
+
message: "Malformed JSON",
|
|
47
|
+
type: "invalid_request_error",
|
|
48
|
+
code: "invalid_json"
|
|
49
|
+
} }));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const syntheticReq = buildSyntheticRequest(model, prompt);
|
|
53
|
+
const testId = getTestId(req);
|
|
54
|
+
const fixture = matchFixture(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
|
|
55
|
+
if (fixture) journal.incrementFixtureMatchCount(fixture, fixtures, testId);
|
|
56
|
+
if (applyChaos(res, fixture, defaults.chaos, req.headers, journal, {
|
|
57
|
+
method,
|
|
58
|
+
path,
|
|
59
|
+
headers: flattenHeaders(req.headers),
|
|
60
|
+
body: syntheticReq
|
|
61
|
+
}, defaults.registry, defaults.logger)) return;
|
|
62
|
+
if (!fixture) {
|
|
63
|
+
if (defaults.record) {
|
|
64
|
+
if (await proxyAndRecord(req, res, syntheticReq, format === "gemini" ? "gemini" : "openai", req.url ?? "/v1/images/generations", fixtures, defaults, raw)) {
|
|
65
|
+
journal.add({
|
|
66
|
+
method,
|
|
67
|
+
path,
|
|
68
|
+
headers: flattenHeaders(req.headers),
|
|
69
|
+
body: syntheticReq,
|
|
70
|
+
response: {
|
|
71
|
+
status: res.statusCode ?? 200,
|
|
72
|
+
fixture: null
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const strictStatus = defaults.strict ? 503 : 404;
|
|
79
|
+
const strictMessage = defaults.strict ? "Strict mode: no fixture matched" : "No fixture matched";
|
|
80
|
+
journal.add({
|
|
81
|
+
method,
|
|
82
|
+
path,
|
|
83
|
+
headers: flattenHeaders(req.headers),
|
|
84
|
+
body: syntheticReq,
|
|
85
|
+
response: {
|
|
86
|
+
status: strictStatus,
|
|
87
|
+
fixture: null
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
writeErrorResponse(res, strictStatus, JSON.stringify({ error: {
|
|
91
|
+
message: strictMessage,
|
|
92
|
+
type: "invalid_request_error",
|
|
93
|
+
code: "no_fixture_match"
|
|
94
|
+
} }));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const response = fixture.response;
|
|
98
|
+
if (isErrorResponse(response)) {
|
|
99
|
+
const status = response.status ?? 500;
|
|
100
|
+
journal.add({
|
|
101
|
+
method,
|
|
102
|
+
path,
|
|
103
|
+
headers: flattenHeaders(req.headers),
|
|
104
|
+
body: syntheticReq,
|
|
105
|
+
response: {
|
|
106
|
+
status,
|
|
107
|
+
fixture
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
writeErrorResponse(res, status, JSON.stringify(response));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (!isImageResponse(response)) {
|
|
114
|
+
journal.add({
|
|
115
|
+
method,
|
|
116
|
+
path,
|
|
117
|
+
headers: flattenHeaders(req.headers),
|
|
118
|
+
body: syntheticReq,
|
|
119
|
+
response: {
|
|
120
|
+
status: 500,
|
|
121
|
+
fixture
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
writeErrorResponse(res, 500, JSON.stringify({ error: {
|
|
125
|
+
message: "Fixture response is not an image type",
|
|
126
|
+
type: "server_error"
|
|
127
|
+
} }));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
journal.add({
|
|
131
|
+
method,
|
|
132
|
+
path,
|
|
133
|
+
headers: flattenHeaders(req.headers),
|
|
134
|
+
body: syntheticReq,
|
|
135
|
+
response: {
|
|
136
|
+
status: 200,
|
|
137
|
+
fixture
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
const items = response.images ?? (response.image ? [response.image] : []);
|
|
141
|
+
if (format === "gemini") {
|
|
142
|
+
const predictions = items.map((item) => ({
|
|
143
|
+
bytesBase64Encoded: item.b64Json ?? "",
|
|
144
|
+
mimeType: "image/png"
|
|
145
|
+
}));
|
|
146
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
147
|
+
res.end(JSON.stringify({ predictions }));
|
|
148
|
+
} else {
|
|
149
|
+
const data = items.map((item) => {
|
|
150
|
+
const entry = {};
|
|
151
|
+
if (item.url) entry.url = item.url;
|
|
152
|
+
if (item.b64Json) entry.b64_json = item.b64Json;
|
|
153
|
+
if (item.revisedPrompt) entry.revised_prompt = item.revisedPrompt;
|
|
154
|
+
return entry;
|
|
155
|
+
});
|
|
156
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
157
|
+
res.end(JSON.stringify({
|
|
158
|
+
created: Math.floor(Date.now() / 1e3),
|
|
159
|
+
data
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
//#endregion
|
|
165
|
+
export { handleImages };
|
|
166
|
+
//# sourceMappingURL=images.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"images.js","names":[],"sources":["../src/images.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport type { ChatCompletionRequest, Fixture, HandlerDefaults } from \"./types.js\";\nimport { isImageResponse, isErrorResponse, flattenHeaders, getTestId } from \"./helpers.js\";\nimport { matchFixture } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\ninterface OpenAIImageRequest {\n model?: string;\n prompt: string;\n n?: number;\n size?: string;\n response_format?: \"url\" | \"b64_json\";\n [key: string]: unknown;\n}\n\ninterface GeminiPredictRequest {\n instances: Array<{ prompt: string }>;\n parameters?: { sampleCount?: number };\n [key: string]: unknown;\n}\n\nfunction buildSyntheticRequest(model: string, prompt: string): ChatCompletionRequest {\n return {\n model,\n messages: [{ role: \"user\", content: prompt }],\n _endpointType: \"image\",\n };\n}\n\nexport async function handleImages(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n format: \"openai\" | \"gemini\" = \"openai\",\n geminiModel?: string,\n): Promise<void> {\n setCorsHeaders(res);\n const path = req.url ?? \"/v1/images/generations\";\n const method = req.method ?? \"POST\";\n\n let model: string;\n let prompt: string;\n\n try {\n const body = JSON.parse(raw);\n if (format === \"gemini\") {\n const geminiReq = body as GeminiPredictRequest;\n prompt = geminiReq.instances?.[0]?.prompt ?? \"\";\n model = geminiModel ?? \"imagen\";\n } else {\n const openaiReq = body as OpenAIImageRequest;\n prompt = openaiReq.prompt ?? \"\";\n model = openaiReq.model ?? \"dall-e-3\";\n }\n } catch {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: { message: \"Malformed JSON\", type: \"invalid_request_error\", code: \"invalid_json\" },\n }),\n );\n return;\n }\n\n const syntheticReq = buildSyntheticRequest(model, prompt);\n const testId = getTestId(req);\n const fixture = matchFixture(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n if (defaults.record) {\n const proxied = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n format === \"gemini\" ? \"gemini\" : \"openai\",\n req.url ?? \"/v1/images/generations\",\n fixtures,\n defaults,\n raw,\n );\n if (proxied) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null },\n });\n return;\n }\n }\n\n const strictStatus = defaults.strict ? 503 : 404;\n const strictMessage = defaults.strict\n ? \"Strict mode: no fixture matched\"\n : \"No fixture matched\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: strictStatus, fixture: null },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: { message: strictMessage, type: \"invalid_request_error\", code: \"no_fixture_match\" },\n }),\n );\n return;\n }\n\n const response = fixture.response;\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, JSON.stringify(response));\n return;\n }\n\n if (!isImageResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: { message: \"Fixture response is not an image type\", type: \"server_error\" },\n }),\n );\n return;\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n // Normalize to array of image items\n const items = response.images ?? (response.image ? [response.image] : []);\n\n if (format === \"gemini\") {\n const predictions = items.map((item) => ({\n bytesBase64Encoded: item.b64Json ?? \"\",\n mimeType: \"image/png\" as const,\n }));\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ predictions }));\n } else {\n const data = items.map((item) => {\n const entry: Record<string, string> = {};\n if (item.url) entry.url = item.url;\n if (item.b64Json) entry.b64_json = item.b64Json;\n if (item.revisedPrompt) entry.revised_prompt = item.revisedPrompt;\n return entry;\n });\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ created: Math.floor(Date.now() / 1000), data }));\n }\n}\n"],"mappings":";;;;;;;AAwBA,SAAS,sBAAsB,OAAe,QAAuC;AACnF,QAAO;EACL;EACA,UAAU,CAAC;GAAE,MAAM;GAAQ,SAAS;GAAQ,CAAC;EAC7C,eAAe;EAChB;;AAGH,eAAsB,aACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACA,SAA8B,UAC9B,aACe;AACf,gBAAe,IAAI;CACnB,MAAM,OAAO,IAAI,OAAO;CACxB,MAAM,SAAS,IAAI,UAAU;CAE7B,IAAI;CACJ,IAAI;AAEJ,KAAI;EACF,MAAM,OAAO,KAAK,MAAM,IAAI;AAC5B,MAAI,WAAW,UAAU;AAEvB,YADkB,KACC,YAAY,IAAI,UAAU;AAC7C,WAAQ,eAAe;SAClB;GACL,MAAM,YAAY;AAClB,YAAS,UAAU,UAAU;AAC7B,WAAQ,UAAU,SAAS;;SAEvB;AACN,UAAQ,IAAI;GACV;GACA;GACA,SAAS,eAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,qBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GAAE,SAAS;GAAkB,MAAM;GAAyB,MAAM;GAAgB,EAC1F,CAAC,CACH;AACD;;CAGF,MAAM,eAAe,sBAAsB,OAAO,OAAO;CACzD,MAAM,SAAS,UAAU,IAAI;CAC7B,MAAM,UAAU,aACd,UACA,cACA,QAAQ,6BAA6B,OAAO,EAC5C,SAAS,iBACV;AAED,KAAI,QACF,SAAQ,2BAA2B,SAAS,UAAU,OAAO;AAG/D,KACE,WACE,KACA,SACA,SAAS,OACT,IAAI,SACJ,SACA;EAAE;EAAQ;EAAM,SAAS,eAAe,IAAI,QAAQ;EAAE,MAAM;EAAc,EAC1E,SAAS,UACT,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;GAAK;GAAS;EACnC,CAAC;CAGF,MAAM,QAAQ,SAAS,WAAW,SAAS,QAAQ,CAAC,SAAS,MAAM,GAAG,EAAE;AAExE,KAAI,WAAW,UAAU;EACvB,MAAM,cAAc,MAAM,KAAK,UAAU;GACvC,oBAAoB,KAAK,WAAW;GACpC,UAAU;GACX,EAAE;AACH,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IAAI,KAAK,UAAU,EAAE,aAAa,CAAC,CAAC;QACnC;EACL,MAAM,OAAO,MAAM,KAAK,SAAS;GAC/B,MAAM,QAAgC,EAAE;AACxC,OAAI,KAAK,IAAK,OAAM,MAAM,KAAK;AAC/B,OAAI,KAAK,QAAS,OAAM,WAAW,KAAK;AACxC,OAAI,KAAK,cAAe,OAAM,iBAAiB,KAAK;AACpD,UAAO;IACP;AACF,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IAAI,KAAK,UAAU;GAAE,SAAS,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;GAAE;GAAM,CAAC,CAAC"}
|
package/dist/index.cjs
CHANGED
|
@@ -18,6 +18,10 @@ const require_aws_event_stream = require('./aws-event-stream.cjs');
|
|
|
18
18
|
const require_bedrock = require('./bedrock.cjs');
|
|
19
19
|
const require_bedrock_converse = require('./bedrock-converse.cjs');
|
|
20
20
|
const require_embeddings = require('./embeddings.cjs');
|
|
21
|
+
const require_images = require('./images.cjs');
|
|
22
|
+
const require_speech = require('./speech.cjs');
|
|
23
|
+
const require_transcription = require('./transcription.cjs');
|
|
24
|
+
const require_video = require('./video.cjs');
|
|
21
25
|
const require_ndjson_writer = require('./ndjson-writer.cjs');
|
|
22
26
|
const require_ollama = require('./ollama.cjs');
|
|
23
27
|
const require_cohere = require('./cohere.cjs');
|
|
@@ -103,6 +107,7 @@ exports.handleConverse = require_bedrock_converse.handleConverse;
|
|
|
103
107
|
exports.handleConverseStream = require_bedrock_converse.handleConverseStream;
|
|
104
108
|
exports.handleEmbeddings = require_embeddings.handleEmbeddings;
|
|
105
109
|
exports.handleGemini = require_gemini.handleGemini;
|
|
110
|
+
exports.handleImages = require_images.handleImages;
|
|
106
111
|
exports.handleMessages = require_messages.handleMessages;
|
|
107
112
|
exports.handleModeration = require_moderation.handleModeration;
|
|
108
113
|
exports.handleOllama = require_ollama.handleOllama;
|
|
@@ -110,10 +115,18 @@ exports.handleOllamaGenerate = require_ollama.handleOllamaGenerate;
|
|
|
110
115
|
exports.handleRerank = require_rerank.handleRerank;
|
|
111
116
|
exports.handleResponses = require_responses.handleResponses;
|
|
112
117
|
exports.handleSearch = require_search.handleSearch;
|
|
118
|
+
exports.handleSpeech = require_speech.handleSpeech;
|
|
119
|
+
exports.handleTranscription = require_transcription.handleTranscription;
|
|
120
|
+
exports.handleVideoCreate = require_video.handleVideoCreate;
|
|
121
|
+
exports.handleVideoStatus = require_video.handleVideoStatus;
|
|
113
122
|
exports.handleWebSocketGeminiLive = require_ws_gemini_live.handleWebSocketGeminiLive;
|
|
114
123
|
exports.handleWebSocketRealtime = require_ws_realtime.handleWebSocketRealtime;
|
|
115
124
|
exports.handleWebSocketResponses = require_ws_responses.handleWebSocketResponses;
|
|
125
|
+
exports.isAudioResponse = require_helpers.isAudioResponse;
|
|
116
126
|
exports.isEmbeddingResponse = require_helpers.isEmbeddingResponse;
|
|
127
|
+
exports.isImageResponse = require_helpers.isImageResponse;
|
|
128
|
+
exports.isTranscriptionResponse = require_helpers.isTranscriptionResponse;
|
|
129
|
+
exports.isVideoResponse = require_helpers.isVideoResponse;
|
|
117
130
|
exports.loadConfig = require_config_loader.loadConfig;
|
|
118
131
|
exports.loadFixtureFile = require_fixture_loader.loadFixtureFile;
|
|
119
132
|
exports.loadFixturesFromDir = require_fixture_loader.loadFixturesFromDir;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DEFAULT_TEST_ID, Journal } from "./journal.cjs";
|
|
2
2
|
import { LogLevel, Logger } from "./logger.cjs";
|
|
3
3
|
import { MetricsRegistry, createMetricsRegistry, normalizePathLabel } from "./metrics.cjs";
|
|
4
|
-
import { ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureFile, FixtureFileEntry, FixtureMatch, FixtureOpts, FixtureResponse, JournalEntry, MockServerOptions, Mountable, RecordConfig, RecordProviderKey, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition } from "./types.cjs";
|
|
4
|
+
import { AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureFile, FixtureFileEntry, FixtureMatch, FixtureOpts, FixtureResponse, ImageItem, ImageResponse, JournalEntry, MockServerOptions, Mountable, RecordConfig, RecordProviderKey, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse } from "./types.cjs";
|
|
5
5
|
import { A2AAgentDefinition, A2AArtifact, A2AMessage, A2AMockOptions, A2APart, A2ARole, A2AStreamEvent, A2ATask, A2ATaskResponse, A2ATaskState } from "./a2a-types.cjs";
|
|
6
6
|
import { A2AMock } from "./a2a-mock.cjs";
|
|
7
7
|
import { SearchFixture, SearchResult, handleSearch } from "./search.cjs";
|
|
@@ -12,6 +12,7 @@ import { MCPContent, MCPMockOptions, MCPPromptDefinition, MCPPromptResult, MCPRe
|
|
|
12
12
|
import { AGUIActivityDeltaEvent, AGUIActivitySnapshotEvent, AGUIEvent, AGUIEventType, AGUIFixture, AGUIFixtureMatch, AGUIMessage, AGUIMessagesSnapshotEvent, AGUIMockOptions, AGUIRecordConfig, AGUIRunAgentInput, AGUIRunErrorEvent, AGUIRunFinishedEvent, AGUIRunStartedEvent, AGUIStateDeltaEvent, AGUIStateSnapshotEvent, AGUITextMessageChunkEvent, AGUITextMessageContentEvent, AGUITextMessageEndEvent, AGUITextMessageStartEvent, AGUIToolCall, AGUIToolCallArgsEvent, AGUIToolCallEndEvent, AGUIToolCallResultEvent, AGUIToolCallStartEvent, AGUIToolDefinition } from "./agui-types.cjs";
|
|
13
13
|
import { QueryHandler, QueryResult, VectorCollection, VectorEntry, VectorMockOptions, VectorQuery } from "./vector-types.cjs";
|
|
14
14
|
import { AimockConfig, loadConfig, startFromConfig } from "./config-loader.cjs";
|
|
15
|
+
import { VideoStateMap, handleVideoCreate, handleVideoStatus } from "./video.cjs";
|
|
15
16
|
import { ServerInstance, ServiceFixtures, createServer } from "./server.cjs";
|
|
16
17
|
import { ValidationResult, loadFixtureFile, loadFixturesFromDir, validateFixtures } from "./fixture-loader.cjs";
|
|
17
18
|
import { getTextContent, matchFixture } from "./router.cjs";
|
|
@@ -29,7 +30,10 @@ import { WebSocketConnection, computeAcceptKey, upgradeToWebSocket } from "./ws-
|
|
|
29
30
|
import { handleWebSocketResponses } from "./ws-responses.cjs";
|
|
30
31
|
import { handleWebSocketRealtime } from "./ws-realtime.cjs";
|
|
31
32
|
import { handleWebSocketGeminiLive } from "./ws-gemini-live.cjs";
|
|
32
|
-
import {
|
|
33
|
+
import { handleImages } from "./images.cjs";
|
|
34
|
+
import { handleSpeech } from "./speech.cjs";
|
|
35
|
+
import { handleTranscription } from "./transcription.cjs";
|
|
36
|
+
import { EmbeddingAPIResponse, buildEmbeddingResponse, buildTextChunks, buildToolCallChunks, flattenHeaders, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, isAudioResponse, isEmbeddingResponse, isImageResponse, isTranscriptionResponse, isVideoResponse } from "./helpers.cjs";
|
|
33
37
|
import { InterruptionControl, createInterruptionSignal } from "./interruption.cjs";
|
|
34
38
|
import { StreamOptions, calculateDelay, delay, writeErrorResponse, writeSSEStream } from "./sse-writer.cjs";
|
|
35
39
|
import { applyChaos, evaluateChaos } from "./chaos.cjs";
|
|
@@ -43,4 +47,4 @@ import { proxyAndRecordAGUI } from "./agui-recorder.cjs";
|
|
|
43
47
|
import { buildActivityResponse, buildCompositeResponse, buildErrorResponse, buildMessagesSnapshot, buildReasoningResponse, buildStateDelta, buildStateUpdate, buildStepWithText, buildTextChunkResponse, buildTextResponse, buildToolCallResponse, extractLastUserMessage, findFixture, writeAGUIEventStream } from "./agui-handler.cjs";
|
|
44
48
|
import { JsonRpcDispatcherOptions, JsonRpcResponse, MethodHandler, createJsonRpcDispatcher } from "./jsonrpc.cjs";
|
|
45
49
|
import { MockSuite, MockSuiteOptions, createMockSuite } from "./suite.cjs";
|
|
46
|
-
export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIMessage, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRecordConfig, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageStartEvent, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, type AimockConfig, type ChaosAction, type ChaosConfig, type ChatCompletion, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type Fixture, type FixtureFile, type FixtureFileEntry, type FixtureMatch, type FixtureOpts, type FixtureResponse, type InterruptionControl, Journal, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LogLevel, Logger, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, type MethodHandler, type MetricsRegistry, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, type QueryHandler, type QueryResult, type RecordConfig, type RecordProviderKey, type RerankFixture, type RerankResult, type ResponsesSSEEvent, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type ValidationResult, type VectorCollection, type VectorEntry, VectorMock, type VectorMockOptions, type VectorQuery, WebSocketConnection, applyChaos, bedrockToCompletionRequest, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallResponse as buildAGUIToolCallResponse, buildEmbeddingResponse, buildTextChunks, buildTextStreamEvents, buildToolCallChunks, buildToolCallStreamEvents, calculateDelay, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, findFixture as findAGUIFixture, flattenHeaders, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getTextContent, handleBedrock, handleBedrockStream, handleCohere, handleConverse, handleConverseStream, handleEmbeddings, handleGemini, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleRerank, handleResponses, handleSearch, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isEmbeddingResponse, loadConfig, loadFixtureFile, loadFixturesFromDir, matchFixture, normalizePathLabel, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, resolveUpstreamUrl, startFromConfig, upgradeToWebSocket, validateFixtures, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
|
|
50
|
+
export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIMessage, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRecordConfig, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageStartEvent, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, type AimockConfig, type AudioResponse, type ChaosAction, type ChaosConfig, type ChatCompletion, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type Fixture, type FixtureFile, type FixtureFileEntry, type FixtureMatch, type FixtureOpts, type FixtureResponse, type ImageItem, type ImageResponse, type InterruptionControl, Journal, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LogLevel, Logger, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, type MethodHandler, type MetricsRegistry, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, type QueryHandler, type QueryResult, type RecordConfig, type RecordProviderKey, type RerankFixture, type RerankResult, type ResponsesSSEEvent, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type TranscriptionResponse, type ValidationResult, type VectorCollection, type VectorEntry, VectorMock, type VectorMockOptions, type VectorQuery, type VideoResponse, type VideoStateMap, WebSocketConnection, applyChaos, bedrockToCompletionRequest, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallResponse as buildAGUIToolCallResponse, buildEmbeddingResponse, buildTextChunks, buildTextStreamEvents, buildToolCallChunks, buildToolCallStreamEvents, calculateDelay, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, findFixture as findAGUIFixture, flattenHeaders, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getTextContent, handleBedrock, handleBedrockStream, handleCohere, handleConverse, handleConverseStream, handleEmbeddings, handleGemini, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isEmbeddingResponse, isImageResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixturesFromDir, matchFixture, normalizePathLabel, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, resolveUpstreamUrl, startFromConfig, upgradeToWebSocket, validateFixtures, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
|