Files
IdeaSDK/examples/cline-ai-plugin/tests/helpers/fake-provider.mjs
2026-11-19 16:30:49 +01:00

47 lines
2.7 KiB
JavaScript

import assert from "node:assert/strict";
export const endpoint = "https://fixture.invalid/v1";
export function fakeProvider({ text = "hello from fixture", holdFirst = false, toolCall = false, advertisedToolNames = false, forbiddenCredential } = {}) {
const calls = [];
const attempts = [];
const failures = [];
let holding = false;
let entered;
const held = new Promise((resolve) => { entered = resolve; });
const fetch = async (input, init = {}) => {
const url = typeof input === "string" || input instanceof URL ? String(input) : input.url;
attempts.push({ url, bodyType: typeof init.body });
try {
assert.equal(url, `${endpoint}/chat/completions`, "unexpected provider/metadata network request");
const body = JSON.parse(init.body ?? await input.clone().text());
const headers = new Headers(init.headers ?? input.headers);
assert.ok(!forbiddenCredential || ![...headers.values()].some((value) => value.includes(forbiddenCredential)), "inherited credential reached provider headers");
calls.push({ url, body });
if (holdFirst && calls.length === 1) {
holding = true;
const signal = init.signal ?? input.signal;
entered();
return await new Promise((_, reject) => {
const aborted = () => reject(new DOMException("fixture abort", "AbortError"));
if (signal?.aborted) aborted(); else signal?.addEventListener("abort", aborted, { once: true });
});
}
const toolNames = advertisedToolNames ? body.tools.map((tool) => tool.function.name) : ["host_echo", "host_echo"];
const choices = toolCall && calls.length === 1 ? [
{ delta: { role: "assistant", tool_calls: [
{ index: 0, id: "fixture-tool-1", type: "function", function: { name: toolNames[0], arguments: '{"value":"fixture argument"}' } },
{ index: 1, id: "fixture-tool-2", type: "function", function: { name: toolNames[1] ?? toolNames[0], arguments: '{"value":"second argument"}' } },
] }, finish_reason: null },
{ delta: {}, finish_reason: "tool_calls" },
] : [
{ delta: { role: "assistant", content: text.slice(0, 6) }, finish_reason: null },
{ delta: { content: text.slice(6) }, finish_reason: null },
{ delta: {}, finish_reason: "stop" },
];
const chunks = choices.map((choice) => `data: ${JSON.stringify({ id: "chatcmpl-fixture", object: "chat.completion.chunk", created: 0, model: body.model, choices: [{ index: 0, ...choice }] })}\n\n`).join("") + "data: [DONE]\n\n";
return new Response(chunks, { status: 200, headers: { "content-type": "text/event-stream" } });
} catch (error) { failures.push({ name: error.name, message: error.message }); throw error; }
};
return { calls, fetch, held, attempts, failures, get holding() { return holding; } };
}