@webmcp-agents/testing 0.0.0-stage → 0.5.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.
@@ -0,0 +1,113 @@
1
+ import { a as StepUsage, c as reasoning, i as StepInput, l as text, n as StepCall, r as StepError, s as fail, t as Step, u as toolCall } from "./script-CuyU-jLV.js";
2
+ import { AgentMessage, ToolDescriptor } from "@webmcp-agents/chat";
3
+ import { MockLanguageModelV4 } from "ai/test";
4
+ /** The options of one model call, as `ai/test` records them (no direct dependency on @ai-sdk/provider's types). */
5
+ type CallOptions = MockLanguageModelV4["doStreamCalls"][number];
6
+ /** What the model was sent on one call: the tools it was offered and the prompt. */
7
+ interface MockModelCall {
8
+ /** The tools offered, as the AI SDK passes them to a provider (`{ type, name, description, inputSchema }`). */
9
+ tools: NonNullable<CallOptions["tools"]>;
10
+ /** The prompt: system, user, assistant and tool messages. */
11
+ prompt: CallOptions["prompt"];
12
+ /** Every option of the call (temperature, provider options, abort signal…). */
13
+ options: CallOptions;
14
+ }
15
+ /** A scripted AI SDK model (`MockLanguageModelV4` from `ai/test`) that remembers its calls. */
16
+ type MockModel = MockLanguageModelV4 & {
17
+ /** Every call, in order. */
18
+ readonly calls: MockModelCall[];
19
+ };
20
+ /**
21
+ * A model that plays `steps`, one per call (the last one repeats), for `createChatHandler({ model })`: the endpoint
22
+ * runs with no provider key and no network. `model.calls[n]` is what call `n` was offered and sent. `mockModel([])`
23
+ * is a model that must never be called: a call fails with a sentence saying so.
24
+ *
25
+ * @example
26
+ * const model = mockModel([toolCall("add_to_cart", { id: "mug-01" }), text("Added.")]);
27
+ * const handler = createChatHandler({ model });
28
+ * // … send a request …
29
+ * expect(model.calls[0].tools.map((t) => t.name)).toEqual(["add_to_cart"]);
30
+ */
31
+ export declare function mockModel(steps: StepInput[]): MockModel;
32
+ /** The default endpoint URL: the handler only checks that an `Origin` header, when sent, matches it. */
33
+ export declare const CHAT_URL = "http://localhost/api/chat";
34
+ /** What {@link chatRequest} puts in the body. */
35
+ interface ChatRequestBody {
36
+ /** The conversation: plain strings become user messages. */
37
+ messages: (string | AgentMessage)[];
38
+ /** The tools the page offers: names become minimal descriptors (any input). Default none. */
39
+ tools?: (string | ToolDescriptor)[];
40
+ /** The agent's id (`defineWebAgent`), when the page runs one. */
41
+ agent?: string;
42
+ /** Anything else the body carries (`page`, `model`, `trace`…). */
43
+ [key: string]: unknown;
44
+ }
45
+ /** How {@link chatRequest} sends it. */
46
+ interface ChatRequestOptions {
47
+ /** The `Origin` header. Default none (a same-site request); another site's origin gets `403`. */
48
+ origin?: string;
49
+ /** More headers (`cookie`, `cf-turnstile-response`…). */
50
+ headers?: Record<string, string>;
51
+ /** The URL. Default `http://localhost/api/chat`. */
52
+ url?: string;
53
+ }
54
+ /**
55
+ * A `POST /api/chat` request as the cloud adapter sends it.
56
+ *
57
+ * @example
58
+ * const res = await handler(chatRequest({ messages: ["Add a mug"], tools: ["add_to_cart"] }));
59
+ * const refused = await handler(chatRequest({ messages: ["hi"] }, { origin: "https://evil.example" })); // 403
60
+ */
61
+ export declare function chatRequest(body: ChatRequestBody, options?: ChatRequestOptions): Request;
62
+ /** One part of the handler's answer, read from its UI message stream. */
63
+ type ChatStreamPart = {
64
+ type: "text-delta";
65
+ delta: string;
66
+ chunk: Record<string, unknown>;
67
+ } | {
68
+ type: "reasoning";
69
+ text: string;
70
+ chunk: Record<string, unknown>;
71
+ } | {
72
+ type: "tool-call";
73
+ id: string;
74
+ name: string;
75
+ input: unknown;
76
+ chunk: Record<string, unknown>;
77
+ } | {
78
+ type: "error";
79
+ error: string;
80
+ chunk: Record<string, unknown>;
81
+ } | {
82
+ type: "finish";
83
+ reason?: string;
84
+ chunk: Record<string, unknown>;
85
+ } | {
86
+ type: "other";
87
+ chunk: Record<string, unknown>;
88
+ };
89
+ /**
90
+ * Read a chat handler's streamed answer to the end: the parts, in order (`text-delta`, `reasoning`, `tool-call`,
91
+ * `error`, `finish`; anything else as `other`). Each keeps the raw chunk. Rejects with a sentence when the response
92
+ * is not a stream (an error status: its JSON is in the message).
93
+ *
94
+ * @example
95
+ * const parts = await readChatStream(await handler(chatRequest({ messages: ["hi"], tools: ["add_to_cart"] })));
96
+ * expect(parts).toContainEqual(expect.objectContaining({ type: "tool-call", name: "add_to_cart" }));
97
+ */
98
+ export declare function readChatStream(response: Response): Promise<ChatStreamPart[]>;
99
+ /** A handler: `(req) => Response`. */
100
+ type ChatHandler = (req: Request) => Response | Promise<Response>;
101
+ /**
102
+ * Start a chat session the way the page does (a `GET` first, which sets the session cookie), and return a `send`
103
+ * that carries the cookie on every request (and keeps a renewed one). Rejects with a sentence when the GET set no
104
+ * cookie (sessions off, or chat disabled).
105
+ *
106
+ * @example
107
+ * const send = await withSession(createChatHandler({ model, session: true }));
108
+ * const res = await send(chatRequest({ messages: ["hi"] }));
109
+ */
110
+ export declare function withSession(handler: ChatHandler, options?: {
111
+ url?: string;
112
+ }): Promise<ChatHandler>;
113
+ export { type ChatHandler, type ChatRequestBody, type ChatRequestOptions, type ChatStreamPart, type MockModel, type MockModelCall, type Step, type StepCall, type StepError, type StepInput, type StepUsage, fail, reasoning, text, toolCall };
package/dist/server.js ADDED
@@ -0,0 +1,266 @@
1
+ import { t as requirePeer } from "./peer-mZEQ4Hla.js";
2
+ import { n as nextId } from "./ids-HmfSbtOs.js";
3
+ import { a as toStep, i as text, n as fail, o as toolCall, r as reasoning, t as chunksOf } from "./script-C3gmfClf.js";
4
+ // src/server/mock-model.ts
5
+ /** The Mock class from `ai/test`, handed over by the entry once the optional peer is loaded. */
6
+ let MockClass;
7
+ let convert;
8
+ /** @internal The entry calls this with `ai/test` after loading it. */
9
+ function provideAiTest(mod) {
10
+ MockClass = mod.MockLanguageModelV4;
11
+ convert = mod.convertArrayToReadableStream;
12
+ }
13
+ /** The stream parts of one step, as a provider would send them. */
14
+ function partsFor(step) {
15
+ const usage = step.usage ?? {};
16
+ const inputTokens = usage.inputTokens ?? 10;
17
+ const outputTokens = usage.outputTokens ?? 5;
18
+ const cacheRead = usage.cachedInputTokens ?? 0;
19
+ const reasoning = usage.reasoningTokens ?? 0;
20
+ const parts = [{
21
+ type: "stream-start",
22
+ warnings: []
23
+ }];
24
+ if (step.error) {
25
+ parts.push({
26
+ type: "error",
27
+ error: Object.assign(new Error(step.error.message ?? "Failed."), { code: step.error.code })
28
+ });
29
+ return parts;
30
+ }
31
+ if (step.reasoning) parts.push({
32
+ type: "reasoning-start",
33
+ id: "r1"
34
+ }, {
35
+ type: "reasoning-delta",
36
+ id: "r1",
37
+ delta: step.reasoning.text
38
+ }, {
39
+ type: "reasoning-end",
40
+ id: "r1",
41
+ providerMetadata: { anthropic: { signature: step.reasoning.signature ?? "sig" } }
42
+ });
43
+ if (step.text) {
44
+ parts.push({
45
+ type: "text-start",
46
+ id: "t1"
47
+ });
48
+ for (const delta of chunksOf(step.text, step.chunks)) parts.push({
49
+ type: "text-delta",
50
+ id: "t1",
51
+ delta
52
+ });
53
+ parts.push({
54
+ type: "text-end",
55
+ id: "t1"
56
+ });
57
+ }
58
+ for (const c of step.calls ?? []) parts.push({
59
+ type: "tool-call",
60
+ toolCallId: c.id ?? nextId("call"),
61
+ toolName: c.name,
62
+ input: JSON.stringify(c.input ?? {})
63
+ });
64
+ parts.push({
65
+ type: "finish",
66
+ usage: {
67
+ inputTokens: {
68
+ total: inputTokens,
69
+ noCache: inputTokens - cacheRead,
70
+ cacheRead,
71
+ cacheWrite: 0
72
+ },
73
+ outputTokens: {
74
+ total: outputTokens,
75
+ text: outputTokens - reasoning,
76
+ reasoning
77
+ }
78
+ },
79
+ finishReason: {
80
+ unified: step.calls?.length ? "tool-calls" : "stop",
81
+ raw: void 0
82
+ }
83
+ });
84
+ return parts;
85
+ }
86
+ /**
87
+ * A model that plays `steps`, one per call (the last one repeats), for `createChatHandler({ model })`: the endpoint
88
+ * runs with no provider key and no network. `model.calls[n]` is what call `n` was offered and sent. `mockModel([])`
89
+ * is a model that must never be called: a call fails with a sentence saying so.
90
+ *
91
+ * @example
92
+ * const model = mockModel([toolCall("add_to_cart", { id: "mug-01" }), text("Added.")]);
93
+ * const handler = createChatHandler({ model });
94
+ * // … send a request …
95
+ * expect(model.calls[0].tools.map((t) => t.name)).toEqual(["add_to_cart"]);
96
+ */
97
+ function mockModel(steps) {
98
+ if (!MockClass || !convert) throw new Error("mockModel() needs ai: import it from @webmcp-agents/testing/server.");
99
+ if (!Array.isArray(steps)) throw new TypeError("mockModel() takes a list of steps, e.g. [toolCall(\"add_to_cart\"), text(\"Added.\")].");
100
+ const toStream = convert;
101
+ let i = 0;
102
+ const model = new MockClass({ doStream: async () => {
103
+ if (!steps.length) throw new Error("mockModel([]) was called: it has no steps, so the test expected no model call.");
104
+ const step = toStep(steps[Math.min(i++, steps.length - 1)]);
105
+ return { stream: toStream(partsFor(step)) };
106
+ } });
107
+ Object.defineProperty(model, "calls", { get: () => model.doStreamCalls.map((options) => ({
108
+ tools: options.tools ?? [],
109
+ prompt: options.prompt,
110
+ options
111
+ })) });
112
+ return model;
113
+ }
114
+ // src/server/request.ts
115
+ /** The default endpoint URL: the handler only checks that an `Origin` header, when sent, matches it. */
116
+ const CHAT_URL = "http://localhost/api/chat";
117
+ const descriptor = (tool) => typeof tool === "string" ? {
118
+ name: tool,
119
+ description: `The ${tool} tool.`,
120
+ inputSchema: {
121
+ type: "object",
122
+ properties: {}
123
+ }
124
+ } : tool;
125
+ const message = (m) => typeof m === "string" ? {
126
+ id: nextId("u"),
127
+ role: "user",
128
+ parts: [{
129
+ type: "text",
130
+ text: m
131
+ }]
132
+ } : m;
133
+ /**
134
+ * A `POST /api/chat` request as the cloud adapter sends it.
135
+ *
136
+ * @example
137
+ * const res = await handler(chatRequest({ messages: ["Add a mug"], tools: ["add_to_cart"] }));
138
+ * const refused = await handler(chatRequest({ messages: ["hi"] }, { origin: "https://evil.example" })); // 403
139
+ */
140
+ function chatRequest(body, options = {}) {
141
+ if (!body || !Array.isArray(body.messages)) throw new TypeError("chatRequest() needs { messages: [...] }, e.g. chatRequest({ messages: [\"hi\"] }).");
142
+ const { messages, tools = [], ...rest } = body;
143
+ return new Request(options.url ?? "http://localhost/api/chat", {
144
+ method: "POST",
145
+ headers: {
146
+ "content-type": "application/json",
147
+ ...options.origin ? { origin: options.origin } : {},
148
+ ...options.headers
149
+ },
150
+ body: JSON.stringify({
151
+ ...rest,
152
+ messages: messages.map(message),
153
+ tools: tools.map(descriptor)
154
+ })
155
+ });
156
+ }
157
+ /** Map one AI SDK UI message chunk to a {@link ChatStreamPart}. */
158
+ function partOf(chunk) {
159
+ switch (chunk.type) {
160
+ case "text-delta": return {
161
+ type: "text-delta",
162
+ delta: String(chunk.delta ?? ""),
163
+ chunk
164
+ };
165
+ case "reasoning-delta": return {
166
+ type: "reasoning",
167
+ text: String(chunk.delta ?? ""),
168
+ chunk
169
+ };
170
+ case "tool-input-available": return {
171
+ type: "tool-call",
172
+ id: String(chunk.toolCallId),
173
+ name: String(chunk.toolName),
174
+ input: chunk.input,
175
+ chunk
176
+ };
177
+ case "error": return {
178
+ type: "error",
179
+ error: String(chunk.errorText ?? ""),
180
+ chunk
181
+ };
182
+ case "finish": return {
183
+ type: "finish",
184
+ ...typeof chunk.finishReason === "string" ? { reason: chunk.finishReason } : {},
185
+ chunk
186
+ };
187
+ default: return {
188
+ type: "other",
189
+ chunk
190
+ };
191
+ }
192
+ }
193
+ /**
194
+ * Read a chat handler's streamed answer to the end: the parts, in order (`text-delta`, `reasoning`, `tool-call`,
195
+ * `error`, `finish`; anything else as `other`). Each keeps the raw chunk. Rejects with a sentence when the response
196
+ * is not a stream (an error status: its JSON is in the message).
197
+ *
198
+ * @example
199
+ * const parts = await readChatStream(await handler(chatRequest({ messages: ["hi"], tools: ["add_to_cart"] })));
200
+ * expect(parts).toContainEqual(expect.objectContaining({ type: "tool-call", name: "add_to_cart" }));
201
+ */
202
+ async function readChatStream(response) {
203
+ if (!(response instanceof Response)) throw new TypeError("readChatStream() takes the Response the handler returned.");
204
+ if (!response.ok || !response.body) {
205
+ const text = await response.text().catch(() => "");
206
+ throw new Error(`readChatStream(): the handler answered ${response.status}, not a stream. Body: ${text.slice(0, 300)}`);
207
+ }
208
+ const text = await response.text();
209
+ const parts = [];
210
+ for (const line of text.split("\n")) {
211
+ if (!line.startsWith("data:")) continue;
212
+ const data = line.slice(5).trim();
213
+ if (!data || data === "[DONE]") continue;
214
+ try {
215
+ parts.push(partOf(JSON.parse(data)));
216
+ } catch {
217
+ parts.push({
218
+ type: "other",
219
+ chunk: { raw: data }
220
+ });
221
+ }
222
+ }
223
+ return parts;
224
+ }
225
+ /**
226
+ * Start a chat session the way the page does (a `GET` first, which sets the session cookie), and return a `send`
227
+ * that carries the cookie on every request (and keeps a renewed one). Rejects with a sentence when the GET set no
228
+ * cookie (sessions off, or chat disabled).
229
+ *
230
+ * @example
231
+ * const send = await withSession(createChatHandler({ model, session: true }));
232
+ * const res = await send(chatRequest({ messages: ["hi"] }));
233
+ */
234
+ async function withSession(handler, options = {}) {
235
+ const url = options.url ?? "http://localhost/api/chat";
236
+ const first = await handler(new Request(url));
237
+ let cookie = cookieOf(first);
238
+ if (!cookie) throw new Error(`withSession(): GET ${url} set no session cookie (status ${first.status}). Create the handler with { session: true } and a model.`);
239
+ return async (req) => {
240
+ const headers = new Headers(req.headers);
241
+ headers.set("cookie", cookie);
242
+ const res = await handler(new Request(req, { headers }));
243
+ cookie = cookieOf(res) ?? cookie;
244
+ return res;
245
+ };
246
+ }
247
+ /** `name=value` of the response's first `Set-Cookie`, or undefined. */
248
+ function cookieOf(res) {
249
+ const set = res.headers.get("set-cookie");
250
+ return set ? set.split(";")[0] : void 0;
251
+ }
252
+ // src/server/index.ts
253
+ /**
254
+ * @webmcp-agents/testing/server: test `/api/chat` (`createChatHandler`) with no provider key and no network.
255
+ *
256
+ * const handler = createChatHandler({ model: mockModel([toolCall("add_to_cart"), text("Added.")]), session: true });
257
+ * const send = await withSession(handler);
258
+ * const parts = await readChatStream(await send(chatRequest({ messages: ["Add a mug"], tools: ["add_to_cart"] })));
259
+ *
260
+ * Needs `ai` (for `ai/test`): importing this entry without it fails with a sentence naming it.
261
+ */
262
+ provideAiTest(await requirePeer(() => import("ai/test"), {
263
+ peer: "ai",
264
+ by: "@webmcp-agents/testing/server"
265
+ }));
266
+ export { CHAT_URL, chatRequest, fail, mockModel, readChatStream, reasoning, text, toolCall, withSession };
@@ -0,0 +1 @@
1
+ import "./matchers-BwXSMeTG.js";
package/dist/setup.js ADDED
@@ -0,0 +1,89 @@
1
+ import "./matchers-CcMe-gCr.js";
2
+ import { i as guardModelContext, r as endTest, s as cleanupFixtures, t as beginTest } from "./guard-9H8JcSkn.js";
3
+ import { r as resetIds, t as installIds } from "./ids-HmfSbtOs.js";
4
+ import { afterEach, beforeEach, inject } from "vitest";
5
+ import { installWebMCPPolyfill } from "@webmcp-agents/core/polyfill";
6
+ // src/setup.ts
7
+ /**
8
+ * `@webmcp-agents/testing/setup`: a `setupFiles` entry for browser-mode tests (`webAgentsProject("browser")` lists
9
+ * it). It makes runs predictable and leaves nothing behind:
10
+ *
11
+ * - registers the matchers;
12
+ * - installs the WebMCP polyfill (Playwright's Chromium has no WebMCP);
13
+ * - forces reduced motion, so the cursor snaps instead of animating (`webAgentsProject("browser", { motion: "full" })`
14
+ * keeps the motion, for tests of the motion itself);
15
+ * - makes ids deterministic (`u-1`, `a-1`, `call-1`…), reset before every test;
16
+ * - empties `sessionStorage` and `localStorage` before every test, so a conversation the chat saved (its
17
+ * `sessionStorage` key) does not carry into the next test while the ids start over;
18
+ * - after every test: unmounts what `mount` and `vitest-browser-react` rendered, removes fixtures, then fails the test
19
+ * if a tool call it started is still running or a tool it registered is still registered, naming the tool.
20
+ *
21
+ * A test of a page *without* `document.modelContext` must not use it: give that project
22
+ * `setupFiles: ["@webmcp-agents/testing/matchers"]`.
23
+ */
24
+ const browser = typeof document !== "undefined";
25
+ let context;
26
+ /** The `vitest/browser` module, when this is browser mode. */
27
+ async function browserContext() {
28
+ if (!browser) return void 0;
29
+ try {
30
+ context ??= await import("vitest/browser");
31
+ } catch {
32
+ context = void 0;
33
+ }
34
+ return context;
35
+ }
36
+ /** Make `matchMedia("(prefers-reduced-motion: reduce)")` match: through Chrome's DevTools protocol, else a stub. */
37
+ async function reduceMotion() {
38
+ const ctx = await browserContext();
39
+ try {
40
+ await (ctx?.cdp())?.send("Emulation.setEmulatedMedia", { features: [{
41
+ name: "prefers-reduced-motion",
42
+ value: "reduce"
43
+ }] });
44
+ if (matchMedia("(prefers-reduced-motion: reduce)").matches) return;
45
+ } catch {}
46
+ const original = window.matchMedia.bind(window);
47
+ window.matchMedia = (query) => {
48
+ const list = original(query);
49
+ if (!/prefers-reduced-motion:\s*reduce/.test(query)) return list;
50
+ return Object.assign(Object.create(list), {
51
+ matches: true,
52
+ media: query
53
+ });
54
+ };
55
+ }
56
+ const readMotion = () => {
57
+ try {
58
+ return inject("webAgentsMotion") === "full" ? "full" : "reduced";
59
+ } catch {
60
+ return "reduced";
61
+ }
62
+ };
63
+ installIds();
64
+ if (browser) {
65
+ const mc = installWebMCPPolyfill();
66
+ if (mc) guardModelContext(mc);
67
+ if (readMotion() === "reduced") await reduceMotion();
68
+ }
69
+ /** Empty both storages: a test starts from a page that remembers nothing. */
70
+ function clearStorage() {
71
+ for (const name of ["sessionStorage", "localStorage"]) try {
72
+ window[name].clear();
73
+ } catch {}
74
+ }
75
+ beforeEach(async () => {
76
+ resetIds();
77
+ if (!browser) return;
78
+ clearStorage();
79
+ await beginTest();
80
+ });
81
+ afterEach(async () => {
82
+ if (!browser) return;
83
+ const problems = await endTest(async () => {
84
+ const cleanup = ((await browserContext())?.page)?.[Symbol.for("vitest:component-cleanup")];
85
+ await cleanup?.();
86
+ cleanupFixtures();
87
+ });
88
+ if (problems.length) throw new Error(problems.join("\n"));
89
+ });
@@ -0,0 +1,130 @@
1
+ // src/telemetry/index.ts
2
+ /** The marker that tells a memory exporter from any other object (and from a plain array). */
3
+ const MEMORY_EXPORTER = Symbol.for("web-agents.testing.memory-exporter");
4
+ const ms = (t) => typeof t === "number" ? t : Array.isArray(t) && t.length === 2 ? t[0] * 1e3 + t[1] / 1e6 : 0;
5
+ const STATUS = [
6
+ "unset",
7
+ "ok",
8
+ "error"
9
+ ];
10
+ /** One span of either side as a {@link RecordedSpan}, or undefined for anything else. */
11
+ function recordSpan(value) {
12
+ const s = value;
13
+ if (!s || typeof s !== "object" || typeof s.name !== "string") return void 0;
14
+ const events = (Array.isArray(s.events) ? s.events : []).map((e) => ({
15
+ name: String(e?.name),
16
+ ...e?.attributes ? { attributes: { ...e.attributes } } : {}
17
+ }));
18
+ if (typeof s.spanContext === "function") {
19
+ const ctx = s.spanContext();
20
+ const parent = s.parentSpanContext?.spanId ?? s.parentSpanId;
21
+ const status = s.status;
22
+ return {
23
+ name: s.name,
24
+ traceId: ctx.traceId,
25
+ spanId: ctx.spanId,
26
+ ...parent ? { parentSpanId: parent } : {},
27
+ attributes: { ...s.attributes },
28
+ events,
29
+ status: STATUS[status?.code ?? 0] ?? "unset",
30
+ startTime: ms(s.startTime),
31
+ endTime: ms(s.endTime),
32
+ scope: s.instrumentationScope?.name
33
+ };
34
+ }
35
+ if (typeof s.traceId === "string" && typeof s.spanId === "string") {
36
+ const status = s.status;
37
+ return {
38
+ name: s.name,
39
+ traceId: s.traceId,
40
+ spanId: s.spanId,
41
+ ...typeof s.parentSpanId === "string" && s.parentSpanId ? { parentSpanId: s.parentSpanId } : {},
42
+ attributes: { ...s.attributes },
43
+ events,
44
+ status: (typeof status === "string" ? status : status?.code) ?? "unset",
45
+ startTime: ms(s.startTime),
46
+ endTime: ms(s.endTime),
47
+ scope: typeof s.scope === "string" ? s.scope : "@webmcp-agents/telemetry"
48
+ };
49
+ }
50
+ }
51
+ /**
52
+ * An exporter that keeps every span in memory, for tests.
53
+ *
54
+ * @example
55
+ * const memory = memoryExporter();
56
+ * const stop = observeAgents({ exporters: [memory], batchSize: 1 });
57
+ * await runTurn();
58
+ * await stop.flush();
59
+ * expect(memory).toBeOneTrace();
60
+ */
61
+ function memoryExporter() {
62
+ const spans = [];
63
+ return {
64
+ get spans() {
65
+ return spans;
66
+ },
67
+ reset() {
68
+ spans.length = 0;
69
+ },
70
+ export(batch, resultCallback) {
71
+ for (const s of batch) {
72
+ const recorded = recordSpan(s);
73
+ if (recorded) spans.push(recorded);
74
+ }
75
+ resultCallback?.({ code: 0 });
76
+ },
77
+ forceFlush: async () => {},
78
+ shutdown: async () => {},
79
+ [MEMORY_EXPORTER]: true
80
+ };
81
+ }
82
+ /** True for a {@link memoryExporter}. */
83
+ const isMemoryExporter = (value) => typeof value === "object" && value !== null && value[MEMORY_EXPORTER] === true;
84
+ /**
85
+ * Spans from a memory exporter, an array (span records, `ReadableSpan`s or recorded spans), an OpenTelemetry
86
+ * `InMemorySpanExporter` (`getFinishedSpans()`), or span trees. Anything else: undefined.
87
+ */
88
+ function readSpans(value) {
89
+ if (isMemoryExporter(value)) return [...value.spans];
90
+ const finished = value?.getFinishedSpans;
91
+ if (typeof finished === "function") return finished.call(value).flatMap((s) => recordSpan(s) ?? []);
92
+ if (!Array.isArray(value)) return void 0;
93
+ const flat = [];
94
+ const add = (v) => {
95
+ const node = v;
96
+ if (node && typeof node === "object" && "span" in node && Array.isArray(node.children)) {
97
+ flat.push(node.span);
98
+ for (const child of node.children) add(child);
99
+ } else flat.push(v);
100
+ };
101
+ for (const v of value) add(v);
102
+ const spans = flat.map(recordSpan);
103
+ return spans.every((s) => !!s) ? spans : void 0;
104
+ }
105
+ /**
106
+ * The spans as trees: each root (a span whose parent is not among them) with its children, both in start order.
107
+ *
108
+ * @example
109
+ * const [run] = spanTree(memory.spans);
110
+ * expect(run.children.map((c) => c.span.name)).toEqual(["chat claude-sonnet-5-5", "execute_tool add_to_cart", "chat claude-sonnet-5-5"]);
111
+ */
112
+ function spanTree(spans) {
113
+ const nodes = new Map(spans.map((span) => [span.spanId, {
114
+ span,
115
+ children: []
116
+ }]));
117
+ const roots = [];
118
+ for (const node of nodes.values()) {
119
+ const parent = node.span.parentSpanId ? nodes.get(node.span.parentSpanId) : void 0;
120
+ if (parent && parent !== node) parent.children.push(node);
121
+ else roots.push(node);
122
+ }
123
+ const order = (list) => {
124
+ list.sort((a, b) => a.span.startTime - b.span.startTime);
125
+ for (const n of list) order(n.children);
126
+ return list;
127
+ };
128
+ return order(roots);
129
+ }
130
+ export { recordSpan as a, readSpans as i, isMemoryExporter as n, spanTree as o, memoryExporter as r, MEMORY_EXPORTER as t };
@@ -0,0 +1,2 @@
1
+ import { a as isMemoryExporter, c as recordSpan, i as SpanNode, l as spanTree, n as MemoryExporter, o as memoryExporter, r as RecordedSpan, s as readSpans, t as MEMORY_EXPORTER } from "./index-BYejUroK.js";
2
+ export { MEMORY_EXPORTER, MemoryExporter, RecordedSpan, SpanNode, isMemoryExporter, memoryExporter, readSpans, recordSpan, spanTree };
@@ -0,0 +1 @@
1
+ export { t as MEMORY_EXPORTER, n as isMemoryExporter, r as memoryExporter, i as readSpans, a as recordSpan, o as spanTree } from "./telemetry-Ct63NJwU.js";
@@ -0,0 +1,56 @@
1
+ import { TestProjectInlineConfiguration } from "vitest/config";
2
+ /** How the browser setup treats motion: `"reduced"` (default) snaps the cursor; `"full"` keeps the page's own setting. */
3
+ export type MotionSetting = "reduced" | "full";
4
+ declare module "vitest" {
5
+ interface ProvidedContext {
6
+ /** Set by `webAgentsProject("browser", { motion })`, read by `./setup`. */
7
+ webAgentsMotion: MotionSetting;
8
+ }
9
+ }
10
+ /** Which project: `"unit"` runs `*.test.*` in Node, `"browser"` runs `*.browser.test.*` in Chromium. */
11
+ export type WebAgentsProjectKind = "unit" | "browser";
12
+ /** What can be changed on a project. Anything not listed goes in `test` (merged last) or at the top level. */
13
+ export interface WebAgentsProjectOptions {
14
+ /** The project's name (`--project <name>`). Default `"unit"` / `"browser"`. */
15
+ name?: string;
16
+ /** Test files. Default `**\/*.test.{ts,tsx}` (unit, minus browser tests) / `**\/*.browser.test.{ts,tsx}`. */
17
+ include?: string[];
18
+ /** Files to leave out, added to the defaults. */
19
+ exclude?: string[];
20
+ /**
21
+ * Setup files. Default `["@webmcp-agents/testing/matchers"]` (unit) / `["@webmcp-agents/testing/setup"]` (browser).
22
+ * A page that must stay without `document.modelContext` uses `["@webmcp-agents/testing/matchers"]`.
23
+ */
24
+ setupFiles?: string[];
25
+ /** Browser only: `"reduced"` (default) makes the cursor snap; `"full"` keeps the motion, for tests of the motion. */
26
+ motion?: MotionSetting;
27
+ /** Browser only: the viewport. Default 414 × 800 (keep test targets inside it). */
28
+ viewport?: {
29
+ width: number;
30
+ height: number;
31
+ };
32
+ /** Compile-time constants, e.g. `{ "process.env.NODE_ENV": JSON.stringify("production") }`. */
33
+ define?: Record<string, string>;
34
+ /** Dependencies to pre-bundle, added to React's (a dependency found mid-run reloads Vite and the test). */
35
+ optimizeDeps?: {
36
+ include?: string[];
37
+ };
38
+ /** Any other Vitest `test` option, merged over the project's. */
39
+ test?: Record<string, unknown>;
40
+ }
41
+ /**
42
+ * One Vitest project with the kit's defaults. `extends: true`, so the root config's plugins, `resolve` and `define`
43
+ * apply to it too.
44
+ *
45
+ * - `"unit"`: Node; `**\/*.test.{ts,tsx}` minus browser tests; setup `@webmcp-agents/testing/matchers`.
46
+ * - `"browser"`: Chromium through Playwright, headless, viewport 414 × 800; `**\/*.browser.test.{ts,tsx}`; setup
47
+ * `@webmcp-agents/testing/setup` (polyfill, reduced motion, deterministic ids, cleanup and leak checks); React
48
+ * pre-bundled once.
49
+ *
50
+ * @example
51
+ * export default defineConfig({ test: { projects: [webAgentsProject("unit"), webAgentsProject("browser")] } });
52
+ * @example
53
+ * // a page without WebMCP: only the matchers
54
+ * webAgentsProject("browser", { name: "no-webmcp", include: ["src/no-webmcp.browser.test.ts"], setupFiles: ["@webmcp-agents/testing/matchers"] })
55
+ */
56
+ export declare function webAgentsProject(kind: WebAgentsProjectKind, options?: WebAgentsProjectOptions): TestProjectInlineConfiguration;