@ait-co/devtools 0.1.115 → 0.1.116

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.
Files changed (46) hide show
  1. package/dist/cli-BLBo0lkP.js +2466 -0
  2. package/dist/cli-BLBo0lkP.js.map +1 -0
  3. package/dist/debug-server-DcAKrbnq.js +921 -0
  4. package/dist/debug-server-DcAKrbnq.js.map +1 -0
  5. package/dist/debug-server-DlXJARIC.js +8171 -0
  6. package/dist/debug-server-DlXJARIC.js.map +1 -0
  7. package/dist/mcp/cli.js +3 -7925
  8. package/dist/mcp/cli.js.map +1 -1
  9. package/dist/mcp/server.js +11 -2
  10. package/dist/mcp/server.js.map +1 -1
  11. package/dist/panel/index.js +1 -1
  12. package/dist/{pool-D23t4ibd.d.ts → pool-htlVnEFl.d.ts} +2 -2
  13. package/dist/{pool-D23t4ibd.d.ts.map → pool-htlVnEFl.d.ts.map} +1 -1
  14. package/dist/relay-secret-store-BHcOmaNK.js +3 -0
  15. package/dist/relay-secret-store-CkA7KNUb.js +154 -0
  16. package/dist/{relay-secret-store-DhzAnnj-.js.map → relay-secret-store-CkA7KNUb.js.map} +1 -1
  17. package/dist/{relay-secret-store-DhzAnnj-.js → relay-secret-store-CmqchhR5.js} +3 -3
  18. package/dist/relay-secret-store-CmqchhR5.js.map +1 -0
  19. package/dist/{relay-url-store-CwKT7i04.js → relay-url-store-C0qukm3R.js} +2 -2
  20. package/dist/{relay-url-store-CwKT7i04.js.map → relay-url-store-C0qukm3R.js.map} +1 -1
  21. package/dist/relay-url-store-NDtEcOE-.js +123 -0
  22. package/dist/relay-url-store-NDtEcOE-.js.map +1 -0
  23. package/dist/{relay-worker-DERQUao2.d.ts → relay-worker-DWW4vZxU.d.ts} +2 -2
  24. package/dist/{relay-worker-DERQUao2.d.ts.map → relay-worker-DWW4vZxU.d.ts.map} +1 -1
  25. package/dist/{runtime-BKMMoeMj.d.ts → runtime-BU-iMHz6.d.ts} +43 -4
  26. package/dist/runtime-BU-iMHz6.d.ts.map +1 -0
  27. package/dist/test-runner/cli.d.ts +19 -7
  28. package/dist/test-runner/cli.d.ts.map +1 -1
  29. package/dist/test-runner/cli.js +1 -620
  30. package/dist/test-runner/config.d.ts +1 -1
  31. package/dist/test-runner/pool.d.ts +1 -1
  32. package/dist/test-runner/relay-worker.d.ts +1 -1
  33. package/dist/test-runner/rpc.d.ts +1 -1
  34. package/dist/test-runner/runtime.d.ts +1 -1
  35. package/dist/test-runner/runtime.js +111 -3
  36. package/dist/test-runner/runtime.js.map +1 -1
  37. package/dist/test-runner/task-graph.d.ts +1 -1
  38. package/dist/totp-D104cJQN.js +3 -0
  39. package/dist/{totp-WY6l0ysP.js → totp-D70zD5tJ.js} +1 -1
  40. package/dist/{totp-WY6l0ysP.js.map → totp-D70zD5tJ.js.map} +1 -1
  41. package/dist/totp-DvOYkYim.js +212 -0
  42. package/dist/totp-DvOYkYim.js.map +1 -0
  43. package/package.json +1 -1
  44. package/dist/runtime-BKMMoeMj.d.ts.map +0 -1
  45. package/dist/test-runner/cli.js.map +0 -1
  46. package/dist/totp-D1pulXLa.js +0 -3
@@ -1,622 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { parseArgs } from "node:util";
3
- import * as fs from "node:fs/promises";
4
- import { glob } from "node:fs/promises";
5
- import * as path from "node:path";
6
- import { isAbsolute, resolve } from "node:path";
7
- import { accessSync } from "node:fs";
8
- import { fileURLToPath } from "node:url";
9
- //#region src/test-runner/discover.ts
10
- /**
11
- * Test-file discovery shared by the `devtools-test` CLI and the `run_tests`
12
- * MCP tool, so both expand glob patterns with identical semantics.
13
- *
14
- * Uses Node's built-in `fs/promises` `glob` (Node 22+) — no extra dependency,
15
- * which keeps the MCP daemon install graph lean (a plain glob lib would land in
16
- * the `npx … devtools-mcp` path for no benefit).
17
- *
18
- * Pure Node IO only (`node:fs/promises` + `node:path`) — react-free, so it is
19
- * safe to import from the MCP daemon graph.
20
- */
21
- /**
22
- * Expands `patterns` (globs or plain paths) into a sorted, de-duplicated list of
23
- * ABSOLUTE test file paths, resolved relative to `cwd`.
24
- *
25
- * A plain (non-glob) path passes through when it matches a real file; a glob
26
- * expands against `cwd`. Absolute matches are kept as-is; relative matches are
27
- * resolved against `cwd`. `bundleTestFile` requires an absolute path, so the
28
- * absolute output feeds it directly.
29
- *
30
- * @param patterns Glob patterns or file paths (e.g. `['src/**\/*.ait.test.ts']`).
31
- * @param cwd Base directory for relative patterns/results.
32
- * @returns Sorted, de-duplicated absolute file paths. Empty when nothing matches.
33
- */
34
- async function discoverTestFiles(patterns, cwd) {
35
- const out = /* @__PURE__ */ new Set();
36
- for await (const match of glob(patterns, { cwd })) out.add(isAbsolute(match) ? match : resolve(cwd, match));
37
- return [...out].sort();
38
- }
39
- //#endregion
40
- //#region src/test-runner/bundle.ts
41
- /**
42
- * esbuild-based bundler for user test files.
43
- *
44
- * Bundles a single test file into a self-contained IIFE string that can be
45
- * injected into a WebView via `Runtime.evaluate`. The bundle includes the
46
- * test runtime (`runtime.ts`), which provides `describe/it/test/expect` and
47
- * the `runTestModule(factory)` entry point.
48
- *
49
- * ## How the wiring works
50
- *
51
- * The bundle exposes two exports on `globalThis.__testBundle`:
52
- * - `runTestModule` — the runtime's entry function.
53
- * - `__userFactory` — an async function whose body is the user's top-level
54
- * test registration code (describe/it/test calls).
55
- *
56
- * The Node-side RPC (`rpc.ts`) calls:
57
- * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
58
- *
59
- * `runTestModule` then installs `describe/it/test/expect` as globals, invokes
60
- * the factory (which registers all tests), runs them, and returns a `RunReport`.
61
- *
62
- * ## Why a factory wrapper is needed
63
- *
64
- * Naively adding the runtime to `entryPoints` and bundling the user file would
65
- * fail for two reasons:
66
- * 1. `describe/it/test/expect` from the runtime are module-local in the IIFE
67
- * scope. The user's top-level `describe(...)` calls expect them as globals —
68
- * they are not globals until `runTestModule` installs them.
69
- * 2. Even with globals pre-installed, the user file runs at IIFE-evaluation
70
- * time, before the RPC layer calls `runTestModule` to reset state and start
71
- * the test clock.
72
- *
73
- * The factory approach solves both: the user's registration code is deferred
74
- * into a function that `runTestModule` calls AFTER installing the globals.
75
- *
76
- * ## Factory extraction algorithm
77
- *
78
- * The `userFactoryPlugin` reads the user file and splits lines into:
79
- * - **top-level**: `import …` and re-export lines — kept at module scope
80
- * (the only valid position for static `import` in ESM).
81
- * - **body**: all other statements — moved into the body of the exported
82
- * `__userFactory` async function.
83
- *
84
- * esbuild processes the re-generated module, following each static import
85
- * through the normal dependency graph (including the SDK-redirect plugin).
86
- *
87
- * ## SDK redirect
88
- *
89
- * Imports of `@apps-in-toss/web-framework` (and sub-paths) are intercepted via
90
- * the `sdkRedirectPlugin` and replaced with a virtual `window.__sdk` proxy that
91
- * `src/in-app/auto.ts` installs at runtime. This works for both 2.x and 3.x SDK.
92
- *
93
- * SECRET-HANDLING: the returned bundle code is caller-managed; never log it.
94
- */
95
- /** The SDK package name that mini-app test code imports from. */
96
- const SDK_PACKAGE = "@apps-in-toss/web-framework";
97
- /**
98
- * Names the runtime installs as globals before invoking the user factory.
99
- * The `vitest` virtual module re-exports each as a lazy getter that reads from
100
- * `globalThis` at access time. Keep in sync with the globals installed in
101
- * `runtime.ts#runTestModule`.
102
- */
103
- const VITEST_GLOBAL_NAMES = [
104
- "describe",
105
- "it",
106
- "test",
107
- "expect",
108
- "beforeAll",
109
- "afterAll",
110
- "beforeEach",
111
- "afterEach",
112
- "vi"
113
- ];
114
- /**
115
- * Matches the bare SDK package and any sub-path import
116
- * (`@apps-in-toss/web-framework`, `@apps-in-toss/web-framework/foo`).
117
- * Built from {@link SDK_PACKAGE} so the package name has a single source.
118
- */
119
- const SDK_IMPORT_FILTER = new RegExp(`^${SDK_PACKAGE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
120
- /**
121
- * esbuild plugin that intercepts SDK imports and redirects them to the
122
- * `window.__sdk` proxy that `src/in-app/auto.ts` installs at runtime.
123
- *
124
- * Strategy: for every import of `@apps-in-toss/web-framework` (or sub-paths),
125
- * esbuild resolves it to a virtual module that re-exports all named exports
126
- * via `window.__sdk[name]`. This avoids bundling the real SDK (which may not
127
- * be available in the test environment) while still making named imports work.
128
- *
129
- * If `window.__sdk` is absent (non-dog-food build), every access throws a
130
- * descriptive error rather than returning `undefined` silently.
131
- */
132
- function sdkRedirectPlugin() {
133
- return {
134
- name: "sdk-redirect",
135
- setup(build) {
136
- build.onResolve({ filter: SDK_IMPORT_FILTER }, (args) => ({
137
- path: args.path,
138
- namespace: "sdk-redirect"
139
- }));
140
- build.onLoad({
141
- filter: /.*/,
142
- namespace: "sdk-redirect"
143
- }, () => ({
144
- contents: `
145
- var __proxy = (typeof window !== 'undefined' && window.__sdk)
146
- ? window.__sdk
147
- : new Proxy({}, {
148
- get: function(_t, p) {
149
- throw new Error('window.__sdk is not installed — run in a dog-food build. Missing: ' + String(p));
150
- }
151
- });
152
- module.exports = __proxy;
153
- `,
154
- loader: "js"
155
- }));
156
- }
157
- };
158
- }
159
- /**
160
- * esbuild plugin that intercepts `import … from 'vitest'` and replaces it with
161
- * a virtual module that delegates every named import to `globalThis` at ACCESS
162
- * time (not at bundle-evaluation time).
163
- *
164
- * The runtime installs `describe/it/test/expect/beforeAll/afterAll/beforeEach/
165
- * afterEach/vi` as globals inside `runTestModule`, which runs AFTER the bundle
166
- * IIFE is evaluated. A value-copy redirect (`export var describe =
167
- * globalThis.describe`) would therefore capture `undefined` at evaluation time
168
- * and the user's `describe(...)` calls would be no-ops — registering zero tests.
169
- *
170
- * The fix defers the lookup to call time using per-name **getter** exports.
171
- * We emit a CommonJS module that:
172
- * 1. sets `__esModule = true` so esbuild's `__toESM` interop maps each named
173
- * import directly to a property access on the module (NOT wrapped under a
174
- * `default` shim — which is what happens for a bare Proxy whose own-keys
175
- * are empty, leaving every named import `undefined`);
176
- * 2. defines each global name as a getter that reads `globalThis[name]` on
177
- * every access. So `import { describe } from 'vitest'` compiles to
178
- * `import_vitest.describe`, whose getter returns the real `describe` only
179
- * when the factory calls it — after `runTestModule` installs the globals.
180
- *
181
- * A plain `module.exports = new Proxy(...)` does NOT work here: esbuild routes
182
- * the virtual module through `__toESM`, which enumerates own-keys (none on an
183
- * empty Proxy target) and therefore exposes zero named exports. Explicit getter
184
- * properties give `__toESM` real keys to map while keeping access lazy.
185
- */
186
- function vitestRedirectPlugin() {
187
- return {
188
- name: "vitest-redirect",
189
- setup(build) {
190
- build.onResolve({ filter: /^vitest$/ }, () => ({
191
- path: "vitest",
192
- namespace: "vitest-redirect"
193
- }));
194
- build.onLoad({
195
- filter: /^vitest$/,
196
- namespace: "vitest-redirect"
197
- }, () => {
198
- return {
199
- contents: `Object.defineProperty(exports, '__esModule', { value: true });\n${VITEST_GLOBAL_NAMES.map((name) => `Object.defineProperty(exports, ${JSON.stringify(name)}, { enumerable: true, get: function() { return globalThis[${JSON.stringify(name)}]; } });`).join("\n")}\n`,
200
- loader: "js"
201
- };
202
- });
203
- }
204
- };
205
- }
206
- /**
207
- * esbuild plugin that transforms the user test file into a module that exports
208
- * an async `__userFactory` function. The factory defers the user's top-level
209
- * test registration code (describe/it/test calls) so it only runs when
210
- * `runTestModule(__userFactory)` explicitly invokes it — AFTER the runtime has
211
- * installed describe/it/test/expect as globals.
212
- *
213
- * Algorithm:
214
- * - Import declarations and re-export statements are kept at module top-level
215
- * (the only valid ESM position for static `import`). A statement that spans
216
- * multiple lines — e.g. a named import with one member per line:
217
- * import {
218
- * appLogin,
219
- * getAnonymousKey,
220
- * } from '@apps-in-toss/web-framework';
221
- * is tracked as a single block: every line from the opening `import {` /
222
- * `export {` through the closing `from '…'` (or side-effect `'…'`) line is
223
- * kept together at top-level. This prevents the member lines and the
224
- * closing `} from '…'` line from leaking into the factory body, which would
225
- * leave an unterminated `import {` at module scope (the #678 env3 failure:
226
- * esbuild threw `Expected "as" but found "{"` on multi-line SDK imports).
227
- * - All other lines (describe/it/test calls, local declarations, etc.) are
228
- * moved into the body of the exported async factory function.
229
- *
230
- * This preserves SDK import resolution (the sdk-redirect plugin processes
231
- * top-level imports normally) while deferring test registration to the factory.
232
- */
233
- function userFactoryPlugin(absPath) {
234
- const NAMESPACE = "user-test-factory";
235
- return {
236
- name: "user-test-factory",
237
- setup(build) {
238
- build.onResolve({ filter: /^user-test-factory$/ }, () => ({
239
- path: absPath,
240
- namespace: NAMESPACE
241
- }));
242
- build.onLoad({
243
- filter: /.*/,
244
- namespace: NAMESPACE
245
- }, async (args) => {
246
- const lines = (await fs.readFile(args.path, "utf8")).split("\n");
247
- const topLevelLines = [];
248
- const bodyLines = [];
249
- const EXPORT_DECLARATION_RE = /^(export\s+)(default\s+|async\s+function\s+|function\s+|class\s+|const\s+|let\s+|var\s+)/;
250
- const isImportStart = (trimmed) => trimmed.startsWith("import ") || trimmed.startsWith("import{") || trimmed.startsWith("import'") || trimmed.startsWith("import\"");
251
- const endsStatement = (trimmed) => /['"]\s*;?\s*$/.test(trimmed.replace(/\/\/.*$/, "").trimEnd());
252
- let inImportBlock = false;
253
- for (const line of lines) {
254
- const trimmed = line.trimStart();
255
- const indent = line.slice(0, line.length - trimmed.length);
256
- if (inImportBlock) {
257
- topLevelLines.push(line);
258
- if (endsStatement(trimmed)) inImportBlock = false;
259
- continue;
260
- }
261
- if (isImportStart(trimmed)) {
262
- topLevelLines.push(line);
263
- if (!endsStatement(trimmed)) inImportBlock = true;
264
- } else if (trimmed.startsWith("export ")) if (trimmed.match(EXPORT_DECLARATION_RE)) bodyLines.push(indent + trimmed.slice(7));
265
- else {
266
- topLevelLines.push(line);
267
- if (/\bfrom\b/.test(trimmed) ? !endsStatement(trimmed) : trimmed.endsWith("{")) inImportBlock = true;
268
- }
269
- else bodyLines.push(line);
270
- }
271
- return {
272
- contents: [
273
- ...topLevelLines,
274
- "",
275
- "// biome-ignore lint: generated factory wrapper",
276
- "export default async function __userFactory(): Promise<void> {",
277
- ...bodyLines.map((l) => ` ${l}`),
278
- "}"
279
- ].join("\n"),
280
- loader: "ts",
281
- resolveDir: path.dirname(absPath)
282
- };
283
- });
284
- }
285
- };
286
- }
287
- /**
288
- * Returns the absolute path to the test-runner runtime module.
289
- *
290
- * Searches candidates in priority order:
291
- * 1. Co-located `runtime.ts` / `runtime.js` — covers the source tree
292
- * (tsx / ts-node) and the `dist/test-runner/` entry.
293
- * 2. `../test-runner/runtime.js` — covers the `dist/mcp/cli.js` entry,
294
- * where `import.meta.url` resolves to `dist/mcp/` (a sibling directory
295
- * of `dist/test-runner/`). Without this second candidate the MCP entry
296
- * point would look for `dist/mcp/runtime.js`, which does not exist, and
297
- * every `run_tests` call would fail with an esbuild "Could not resolve"
298
- * error (#678).
299
- *
300
- * Returns the first candidate that exists on disk. Falls back to the
301
- * co-located `runtime.js` path so esbuild produces a clear "file not found"
302
- * error rather than a cryptic failure.
303
- */
304
- function getRuntimePath() {
305
- const dir = path.dirname(fileURLToPath(import.meta.url));
306
- const candidates = [
307
- path.join(dir, "runtime.ts"),
308
- path.join(dir, "runtime.js"),
309
- path.join(dir, "..", "test-runner", "runtime.js")
310
- ];
311
- for (const candidate of candidates) try {
312
- accessSync(candidate);
313
- return candidate;
314
- } catch {}
315
- return path.join(dir, "runtime.js");
316
- }
317
- /**
318
- * Bundles `absPath` into a single IIFE string suitable for `Runtime.evaluate`.
319
- *
320
- * The IIFE installs `window.__testBundle` (or the custom `globalName`) with:
321
- * - `runTestModule` — the runtime entry (from `runtime.ts`).
322
- * - `__userFactory` — an async function wrapping the user's test registration
323
- * code so it runs AFTER `runTestModule` installs the globals.
324
- *
325
- * Callers (rpc.ts) invoke:
326
- * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
327
- *
328
- * @param absPath - Absolute path to the user test file.
329
- * @param opts - Optional bundling overrides.
330
- */
331
- async function bundleTestFile(absPath, opts) {
332
- const globalName = opts?.globalName ?? "__testBundle";
333
- const extraExternals = opts?.extraExternals ?? [];
334
- const esbuild = await import("esbuild");
335
- const runtimePath = getRuntimePath();
336
- const wrapperContent = [
337
- `import { runTestModule } from ${JSON.stringify(runtimePath)};`,
338
- `import __userFactory from "user-test-factory";`,
339
- `export { runTestModule, __userFactory };`
340
- ].join("\n");
341
- const result = await esbuild.build({
342
- stdin: {
343
- contents: wrapperContent,
344
- loader: "ts",
345
- resolveDir: path.dirname(absPath)
346
- },
347
- bundle: true,
348
- format: "iife",
349
- globalName,
350
- platform: "browser",
351
- target: "es2022",
352
- write: false,
353
- plugins: [
354
- userFactoryPlugin(absPath),
355
- vitestRedirectPlugin(),
356
- sdkRedirectPlugin()
357
- ],
358
- external: extraExternals,
359
- treeShaking: true,
360
- footer: { js: `globalThis[${JSON.stringify(globalName)}] = ${globalName};` }
361
- });
362
- const warnings = result.warnings.map((w) => `${path.relative(process.cwd(), w.location?.file ?? "")}:${w.location?.line ?? "?"}: ${w.text}`);
363
- const outputFile = result.outputFiles?.[0];
364
- if (!outputFile) throw new Error("bundleTestFile: esbuild produced no output — check entryPoints");
365
- return {
366
- code: outputFile.text,
367
- warnings
368
- };
369
- }
370
- //#endregion
371
- //#region src/test-runner/rpc.ts
372
- /** Maximum milliseconds to wait for a single evaluate round-trip. */
373
- const DEFAULT_TIMEOUT_MS = 3e4;
374
- /**
375
- * Wraps bundle code in a self-executing IIFE that:
376
- * 1. Evaluates the bundle (registering describe/it/test).
377
- * 2. Calls `__testBundle.runTestModule(...)` — the entry the runtime exports.
378
- * 3. Returns a JSON-serialised `RunReport` string.
379
- *
380
- * The double-serialisation (RunReport → JSON string → returnByValue string)
381
- * is intentional: CDP `returnByValue` reliably transports strings; deeply
382
- * nested objects can lose fidelity across the Chii relay.
383
- *
384
- * SECRET-HANDLING: `bundleCode` MUST NOT be logged by callers.
385
- */
386
- function buildRunTestsExpression(bundleCode) {
387
- return `(async () => { try { ${bundleCode} } catch(e) { return JSON.stringify({ok:false,error:'bundle-eval: ' + String(e && e.message || e)}); } if (typeof globalThis.__testBundle !== 'object' || typeof globalThis.__testBundle.runTestModule !== 'function' || typeof globalThis.__testBundle.__userFactory !== 'function') { return JSON.stringify({ok:false,error:'bundle-missing-export: __testBundle.runTestModule or __userFactory is not a function'}); } try { const report = await globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory); return JSON.stringify({ok:true,value:report}); } catch(e) { return JSON.stringify({ok:false,error:'test-run: ' + String(e && e.message || e)}); }})()`;
388
- }
389
- /**
390
- * Parses the raw CDP `returnByValue` result from a `buildRunTestsExpression`
391
- * evaluate call into a typed `RpcRunResult`.
392
- *
393
- * Throws only on parse failure — an `ok:false` envelope is a normal result.
394
- *
395
- * SECRET-HANDLING: `rawValue` is not included in error messages.
396
- */
397
- function parseRunTestsResult(rawValue) {
398
- if (typeof rawValue !== "string") throw new Error(`rpc.parseRunTestsResult: unexpected return type "${typeof rawValue}" — expected JSON string`);
399
- let parsed;
400
- try {
401
- parsed = JSON.parse(rawValue);
402
- } catch {
403
- throw new Error("rpc.parseRunTestsResult: bridge returned non-JSON string");
404
- }
405
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("rpc.parseRunTestsResult: parsed result is not an object");
406
- const obj = parsed;
407
- if (obj.ok === true) return {
408
- ok: true,
409
- report: obj.value
410
- };
411
- if (obj.ok === false) return {
412
- ok: false,
413
- error: typeof obj.error === "string" ? obj.error : String(obj.error)
414
- };
415
- throw new Error("rpc.parseRunTestsResult: result missing \"ok\" field");
416
- }
417
- /**
418
- * Injects `bundleCode` into the attached page and awaits test execution.
419
- *
420
- * Uses `Runtime.evaluate` with `awaitPromise: true` to wait for the
421
- * async IIFE to settle. The 30-second CDP command timeout covers even
422
- * long-running test suites; split into smaller files if you hit it.
423
- *
424
- * @param connection - Active CDP connection (relay or local).
425
- * @param bundleCode - IIFE bundle string from `bundleTestFile`.
426
- * @param timeoutMs - Override the default 30 s timeout.
427
- *
428
- * SECRET-HANDLING: `bundleCode` and the raw CDP result value are never logged.
429
- */
430
- async function injectAndRunBundle(connection, bundleCode, timeoutMs = DEFAULT_TIMEOUT_MS) {
431
- const expression = buildRunTestsExpression(bundleCode);
432
- const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error(`rpc: evaluate timed out after ${timeoutMs}ms`)), timeoutMs));
433
- const evalPromise = connection.send("Runtime.evaluate", {
434
- expression,
435
- returnByValue: true,
436
- awaitPromise: true
437
- });
438
- const cdpResult = await Promise.race([evalPromise, timeoutPromise]);
439
- if (cdpResult.exceptionDetails) {
440
- const msg = cdpResult.exceptionDetails.exception?.description ?? cdpResult.exceptionDetails.text ?? "Runtime.evaluate threw an exception";
441
- throw new Error(`rpc.injectAndRunBundle: ${msg}`);
442
- }
443
- return parseRunTestsResult(cdpResult.result.value);
444
- }
445
- //#endregion
446
- //#region src/test-runner/relay-worker.ts
447
- /**
448
- * Runs all `files` sequentially over the given CDP `connection`.
449
- *
450
- * For each file:
451
- * 1. Bundle with esbuild (includes SDK shim + runtime).
452
- * 2. Inject into the attached page via `Runtime.evaluate`.
453
- * 3. Await the `RunReport` JSON response.
454
- * 4. Accumulate results.
455
- *
456
- * Returns a `RelayRunReport` with per-file results and flattened totals.
457
- *
458
- * This function does NOT open or manage the relay connection — the caller
459
- * is responsible for attaching and closing it.
460
- *
461
- * TODO (#645): implement the Vitest `PoolRunnerInitializer` interface here
462
- * so that `runTestFilesOverRelay` can be used as a Vitest pool entry.
463
- *
464
- * @param connection - Active CDP connection (relay or local kind).
465
- * @param files - Absolute paths to test files, run in order.
466
- * @param opts - Optional per-run overrides.
467
- */
468
- async function runTestFilesOverRelay(connection, files, opts) {
469
- const wallStart = Date.now();
470
- const startedAt = new Date(wallStart).toISOString();
471
- const fileResults = [];
472
- for (const file of files) {
473
- let fileEntry;
474
- try {
475
- const { code } = await bundleTestFile(file, opts?.bundleOptions);
476
- const rpcResult = await injectAndRunBundle(connection, code, opts?.timeoutMs);
477
- if (rpcResult.ok) fileEntry = {
478
- file,
479
- result: rpcResult.report
480
- };
481
- else fileEntry = {
482
- file,
483
- result: { error: rpcResult.error }
484
- };
485
- } catch (e) {
486
- fileEntry = {
487
- file,
488
- result: { error: e instanceof Error ? e.message : String(e) }
489
- };
490
- }
491
- fileResults.push(fileEntry);
492
- }
493
- const totals = fileResults.reduce((acc, { result }) => {
494
- if ("error" in result) {
495
- acc.failed += 1;
496
- acc.total += 1;
497
- } else {
498
- acc.passed += result.passed;
499
- acc.failed += result.failed;
500
- acc.skipped += result.skipped;
501
- acc.total += result.passed + result.failed + result.skipped;
502
- }
503
- return acc;
504
- }, {
505
- passed: 0,
506
- failed: 0,
507
- skipped: 0,
508
- total: 0
509
- });
510
- return {
511
- startedAt,
512
- duration: Date.now() - wallStart,
513
- files: fileResults,
514
- totals
515
- };
516
- }
517
- //#endregion
518
- //#region src/test-runner/cli.ts
519
- /**
520
- * `devtools-test` CLI.
521
- *
522
- * Shares test-file discovery with the `run_tests` MCP tool (`discoverTestFiles`)
523
- * and exposes `runWithConnection` — the pure run core that bundles, injects, and
524
- * collects each file over a CDP connection. Today the run path that has a live
525
- * connection is the `run_tests` MCP tool (it runs these files against the
526
- * daemon's attached page); the CLI's own standalone relay attach (resolve CDP
527
- * URL → attach → run → close) is not wired yet, so `main()` resolves the matched
528
- * files and points the operator at the MCP tool.
529
- *
530
- * NOTE: no shebang in this source file — the tsdown entry's `banner` option
531
- * injects `#!/usr/bin/env node` into the compiled output (same pattern as
532
- * `src/mcp/cli.ts`).
533
- */
534
- const USAGE = `
535
- devtools-test — run mini-app tests on a real device WebView over the CDP relay
536
-
537
- USAGE
538
- devtools-test <glob> [<glob> ...] [options]
539
-
540
- OPTIONS
541
- --timeout <ms> Per-file evaluate timeout in ms (default: 30000)
542
- --help, -h Show this help message
543
-
544
- DESCRIPTION
545
- Bundles each matched test file with esbuild (SDK imports redirected to
546
- window.__sdk), injects the bundle into the attached WebView via
547
- Runtime.evaluate, and returns a RunReport.
548
-
549
- A live CDP relay connection must be active before running tests. Use the
550
- \`run_tests\` MCP tool (via \`devtools-mcp\` / \`/ait debug\`) to run these files
551
- against an attached page — the CLI's own standalone relay attach is not wired
552
- yet (it currently resolves the matched files and defers to that tool).
553
-
554
- EXAMPLE
555
- devtools-test 'src/**/*.ait.test.ts' --timeout 60000
556
-
557
- `.trimStart();
558
- /**
559
- * Runs `files` over `connection` and returns the aggregate report.
560
- * This pure function is the testable core of the CLI (and is what the
561
- * `run_tests` MCP tool calls against the daemon's attached connection); it is
562
- * separate from `main()` so tests can call it without spawning a subprocess.
563
- *
564
- * A standalone CLI relay attach/detach lifecycle (connect via Chii relay URL,
565
- * `enableDomains`, run, then close) is not wired into `main()` yet.
566
- */
567
- async function runWithConnection(connection, files, opts) {
568
- const report = await runTestFilesOverRelay(connection, files, opts);
569
- if (opts?.printSummary) {
570
- const { totals } = report;
571
- process.stdout.write(`\ndevtools-test: ${totals.passed} passed, ${totals.failed} failed, ${totals.skipped} skipped (${report.duration}ms)\n`);
572
- }
573
- return report;
574
- }
575
- /**
576
- * CLI entry point.
577
- *
578
- * Resolves the matched test files and prints a "relay attach required" notice:
579
- * the CLI's own standalone relay attach (resolve CDP URL, attach, run, close) is
580
- * not wired yet, so today these files run via the `run_tests` MCP tool against
581
- * the daemon's attached page.
582
- */
583
- async function main(argv = process.argv.slice(2)) {
584
- let parsed;
585
- try {
586
- parsed = parseArgs({
587
- args: argv,
588
- options: {
589
- help: {
590
- type: "boolean",
591
- short: "h"
592
- },
593
- timeout: { type: "string" }
594
- },
595
- allowPositionals: true
596
- });
597
- } catch (e) {
598
- process.stderr.write(`devtools-test: ${e instanceof Error ? e.message : String(e)}\n`);
599
- process.exitCode = 1;
600
- return;
601
- }
602
- if (parsed.values.help || argv.length === 0) {
603
- process.stdout.write(USAGE);
604
- return;
605
- }
606
- const files = await discoverTestFiles(parsed.positionals, process.cwd());
607
- if (files.length === 0) {
608
- process.stderr.write(`devtools-test: no test files matched ${parsed.positionals.join(", ")}\n`);
609
- process.exitCode = 1;
610
- return;
611
- }
612
- process.stderr.write(`devtools-test: matched ${files.length} test file(s), but direct CLI relay attach is not yet wired.\n Use the devtools-mcp server (\`devtools-mcp\`) to start a debug session,\n then the \`run_tests\` MCP tool to run these files against the attached page.\n`);
613
- process.exitCode = 1;
614
- }
615
- if (import.meta.url === new URL(process.argv[1], "file://").href) main().catch((e) => {
616
- process.stderr.write(`devtools-test: unexpected error: ${e instanceof Error ? e.message : String(e)}\n`);
617
- process.exitCode = 1;
618
- });
619
- //#endregion
2
+ import { n as runWithConnection, t as main } from "../cli-BLBo0lkP.js";
620
3
  export { main, runWithConnection };
621
-
622
- //# sourceMappingURL=cli.js.map
@@ -1,4 +1,4 @@
1
- import { i as createRelayPool, n as RelayConnectionFactory, t as RELAY_POOL_NAME } from "../pool-D23t4ibd.js";
1
+ import { i as createRelayPool, n as RelayConnectionFactory, t as RELAY_POOL_NAME } from "../pool-htlVnEFl.js";
2
2
 
3
3
  //#region src/test-runner/config.d.ts
4
4
  /**
@@ -1,2 +1,2 @@
1
- import { i as createRelayPool, n as RelayConnectionFactory, r as RelayPoolOptions, t as RELAY_POOL_NAME } from "../pool-D23t4ibd.js";
1
+ import { i as createRelayPool, n as RelayConnectionFactory, r as RelayPoolOptions, t as RELAY_POOL_NAME } from "../pool-htlVnEFl.js";
2
2
  export { RELAY_POOL_NAME, RelayConnectionFactory, RelayPoolOptions, createRelayPool };
@@ -1,2 +1,2 @@
1
- import { a as runTestFilesOverRelay, i as flattenResults, n as RelayRunOptions, r as RelayRunReport, t as FileResult } from "../relay-worker-DERQUao2.js";
1
+ import { a as runTestFilesOverRelay, i as flattenResults, n as RelayRunOptions, r as RelayRunReport, t as FileResult } from "../relay-worker-DWW4vZxU.js";
2
2
  export { FileResult, RelayRunOptions, RelayRunReport, flattenResults, runTestFilesOverRelay };
@@ -1,5 +1,5 @@
1
1
  import { t as CdpConnection } from "../cdp-connection-C0AP0tH2.js";
2
- import { t as RunReport } from "../runtime-BKMMoeMj.js";
2
+ import { t as RunReport } from "../runtime-BU-iMHz6.js";
3
3
 
4
4
  //#region src/test-runner/rpc.d.ts
5
5
  /**
@@ -1,2 +1,2 @@
1
- import { i as runtimeGlobals, n as TestResult, r as runTestModule, t as RunReport } from "../runtime-BKMMoeMj.js";
1
+ import { i as runtimeGlobals, n as TestResult, r as runTestModule, t as RunReport } from "../runtime-BU-iMHz6.js";
2
2
  export { RunReport, TestResult, runTestModule, runtimeGlobals };