@ait-co/devtools 0.1.108 → 0.1.110

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 (79) hide show
  1. package/README.en.md +13 -31
  2. package/README.md +13 -31
  3. package/dist/bundle-KFs4t-wc.d.ts +96 -0
  4. package/dist/bundle-KFs4t-wc.d.ts.map +1 -0
  5. package/dist/in-app/auto.d.ts.map +1 -1
  6. package/dist/in-app/auto.js +40 -3
  7. package/dist/in-app/auto.js.map +1 -1
  8. package/dist/in-app/index.d.ts.map +1 -1
  9. package/dist/in-app/index.js +39 -2
  10. package/dist/in-app/index.js.map +1 -1
  11. package/dist/mcp/cli.d.ts +4 -16
  12. package/dist/mcp/cli.d.ts.map +1 -1
  13. package/dist/mcp/cli.js +803 -712
  14. package/dist/mcp/cli.js.map +1 -1
  15. package/dist/mcp/server.d.ts.map +1 -1
  16. package/dist/mcp/server.js +47 -59
  17. package/dist/mcp/server.js.map +1 -1
  18. package/dist/mock/index.d.ts.map +1 -1
  19. package/dist/mock/index.js +21 -2
  20. package/dist/mock/index.js.map +1 -1
  21. package/dist/panel/index.js +47 -32
  22. package/dist/panel/index.js.map +1 -1
  23. package/dist/{pool-Dkp7I9Bf.d.ts → pool-Bf6rQci4.d.ts} +210 -48
  24. package/dist/pool-Bf6rQci4.d.ts.map +1 -0
  25. package/dist/{qr-http-server-D4EAA7Il.js → qr-http-server-BJJt3ush.js} +8 -17
  26. package/dist/qr-http-server-BJJt3ush.js.map +1 -0
  27. package/dist/{qr-http-server-A9vld8r7.cjs → qr-http-server-BVS-HZjU.cjs} +8 -17
  28. package/dist/qr-http-server-BVS-HZjU.cjs.map +1 -0
  29. package/dist/{qr-http-server-Dj3Z0NHi.cjs → qr-http-server-C1T4RNbq.cjs} +8 -17
  30. package/dist/qr-http-server-C1T4RNbq.cjs.map +1 -0
  31. package/dist/{qr-http-server-HzdCLU8s.js → qr-http-server-Cs93vEPH.js} +8 -17
  32. package/dist/qr-http-server-Cs93vEPH.js.map +1 -0
  33. package/dist/{relay-worker-BzFQ3fv9.d.ts → relay-worker-xxanNQGs.d.ts} +3 -3
  34. package/dist/relay-worker-xxanNQGs.d.ts.map +1 -0
  35. package/dist/{runtime-ORdrpizY.d.ts → runtime-Wi5d6Ywz.d.ts} +3 -3
  36. package/dist/{runtime-ORdrpizY.d.ts.map → runtime-Wi5d6Ywz.d.ts.map} +1 -1
  37. package/dist/test-runner/bundle.d.ts +1 -1
  38. package/dist/test-runner/bundle.js +148 -11
  39. package/dist/test-runner/bundle.js.map +1 -1
  40. package/dist/test-runner/cli.d.ts +59 -14
  41. package/dist/test-runner/cli.d.ts.map +1 -1
  42. package/dist/test-runner/cli.js +171 -32
  43. package/dist/test-runner/cli.js.map +1 -1
  44. package/dist/test-runner/config.d.ts +1 -1
  45. package/dist/test-runner/pool.d.ts +1 -1
  46. package/dist/test-runner/relay-worker.d.ts +1 -1
  47. package/dist/test-runner/relay-worker.js.map +1 -1
  48. package/dist/test-runner/rpc.d.ts +1 -1
  49. package/dist/test-runner/rpc.d.ts.map +1 -1
  50. package/dist/test-runner/rpc.js +1 -1
  51. package/dist/test-runner/rpc.js.map +1 -1
  52. package/dist/test-runner/task-graph.d.ts +1 -1
  53. package/dist/{tunnel-BjJROkcj.js → tunnel-Cpn3mA4u.js} +3 -3
  54. package/dist/tunnel-Cpn3mA4u.js.map +1 -0
  55. package/dist/{tunnel-d_G9AIFn.cjs → tunnel-Dj8Kf2QS.cjs} +3 -3
  56. package/dist/tunnel-Dj8Kf2QS.cjs.map +1 -0
  57. package/dist/unplugin/index.cjs +1 -1
  58. package/dist/unplugin/index.d.cts +196 -34
  59. package/dist/unplugin/index.d.cts.map +1 -1
  60. package/dist/unplugin/index.d.ts +196 -34
  61. package/dist/unplugin/index.d.ts.map +1 -1
  62. package/dist/unplugin/index.js +1 -1
  63. package/dist/unplugin/tunnel.cjs +2 -2
  64. package/dist/unplugin/tunnel.cjs.map +1 -1
  65. package/dist/unplugin/tunnel.d.cts +1 -1
  66. package/dist/unplugin/tunnel.d.ts +1 -1
  67. package/dist/unplugin/tunnel.js +2 -2
  68. package/dist/unplugin/tunnel.js.map +1 -1
  69. package/package.json +14 -14
  70. package/dist/bundle-BJm5jk56.d.ts +0 -49
  71. package/dist/bundle-BJm5jk56.d.ts.map +0 -1
  72. package/dist/pool-Dkp7I9Bf.d.ts.map +0 -1
  73. package/dist/qr-http-server-A9vld8r7.cjs.map +0 -1
  74. package/dist/qr-http-server-D4EAA7Il.js.map +0 -1
  75. package/dist/qr-http-server-Dj3Z0NHi.cjs.map +0 -1
  76. package/dist/qr-http-server-HzdCLU8s.js.map +0 -1
  77. package/dist/relay-worker-BzFQ3fv9.d.ts.map +0 -1
  78. package/dist/tunnel-BjJROkcj.js.map +0 -1
  79. package/dist/tunnel-d_G9AIFn.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","names":[],"sources":["../../src/test-runner/bundle.ts"],"sourcesContent":["/**\n * esbuild-based bundler for user test files.\n *\n * Bundles a single test file into a self-contained IIFE string that can be\n * injected into a WebView via `Runtime.evaluate`. The user's SDK imports\n * (`@apps-in-toss/web-framework` and sub-paths) are intercepted via an\n * esbuild plugin that redirects them to `window.__sdk`, which the in-app\n * debug gate (`src/in-app/auto.ts`) installs as a namespace mirror of the\n * SDK exports (works for both 2.x and 3.x SDK).\n *\n * SECRET-HANDLING: the returned bundle code is caller-managed; never log it.\n */\n\nimport * as path from 'node:path';\n// esbuild is imported for TYPES only at module scope; the runtime module is\n// loaded lazily inside `bundleTestFile` via dynamic import. esbuild runs a\n// startup invariant check (`TextEncoder().encode('') instanceof Uint8Array`)\n// that fails in a jsdom realm — a static import would break every MCP/test\n// module that merely *imports* this file's transitive graph (e.g. debug-server →\n// run_tests). Lazy load keeps esbuild off the import graph until a bundle is\n// actually built, and mirrors the cloudflared/chii dynamic-import precedent.\nimport type * as esbuild from 'esbuild';\n\n/** Options accepted by `bundleTestFile`. */\nexport interface BundleOptions {\n /**\n * Additional esbuild `external` patterns. The SDK package\n * (`@apps-in-toss/web-framework` and `@apps-in-toss/web-framework/*`) is\n * always handled by the SDK redirect plugin — callers may add more patterns\n * to be left as globals.\n */\n extraExternals?: string[];\n /**\n * Global name for the IIFE output object. Defaults to `__testBundle`.\n * The runtime entry uses this to call `__testBundle.runTestModule()`.\n */\n globalName?: string;\n}\n\n/**\n * The result of bundling a test file.\n * `code` is a self-contained IIFE string ready for `Runtime.evaluate`.\n */\nexport interface BundleResult {\n code: string;\n warnings: string[];\n}\n\n/** The SDK package name that mini-app test code imports from. */\nconst SDK_PACKAGE = '@apps-in-toss/web-framework';\n\n/**\n * Matches the bare SDK package and any sub-path import\n * (`@apps-in-toss/web-framework`, `@apps-in-toss/web-framework/foo`).\n * Built from {@link SDK_PACKAGE} so the package name has a single source.\n */\nconst SDK_IMPORT_FILTER = new RegExp(`^${SDK_PACKAGE.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}`);\n\n/**\n * esbuild plugin that intercepts SDK imports and redirects them to the\n * `window.__sdk` proxy that `src/in-app/auto.ts` installs at runtime.\n *\n * Strategy: for every import of `@apps-in-toss/web-framework` (or sub-paths),\n * esbuild resolves it to a virtual module that re-exports all named exports\n * via `window.__sdk[name]`. This avoids bundling the real SDK (which may not\n * be available in the test environment) while still making named imports work.\n *\n * If `window.__sdk` is absent (non-dog-food build), every access throws a\n * descriptive error rather than returning `undefined` silently.\n */\nfunction sdkRedirectPlugin(): esbuild.Plugin {\n return {\n name: 'sdk-redirect',\n setup(build) {\n // Match the bare package and any sub-path imports\n build.onResolve({ filter: SDK_IMPORT_FILTER }, (args) => ({\n path: args.path,\n namespace: 'sdk-redirect',\n }));\n\n build.onLoad({ filter: /.*/, namespace: 'sdk-redirect' }, () => ({\n // Generate a virtual CommonJS-style module so that esbuild does NOT perform\n // strict named-export matching. When `format:'iife'` bundles a CJS module,\n // it wraps it with its own __toCommonJS helper and satisfies named imports\n // via property access on the module.exports object — which is our Proxy.\n // This means `import { getPlatformOS } from '...'` becomes\n // `__proxy.getPlatformOS` at runtime, which correctly reads from window.__sdk.\n contents: `\nvar __proxy = (typeof window !== 'undefined' && window.__sdk)\n ? window.__sdk\n : new Proxy({}, {\n get: function(_t, p) {\n throw new Error('window.__sdk is not installed — run in a dog-food build. Missing: ' + String(p));\n }\n });\nmodule.exports = __proxy;\n`,\n loader: 'js',\n }));\n },\n };\n}\n\n/**\n * Bundles `absPath` into a single IIFE string suitable for `Runtime.evaluate`.\n *\n * The IIFE installs `window.__testBundle` (or the custom `globalName`) with\n * `runTestModule` as the callable entry point.\n *\n * @param absPath - Absolute path to the user test file.\n * @param opts - Optional bundling overrides.\n */\nexport async function bundleTestFile(absPath: string, opts?: BundleOptions): Promise<BundleResult> {\n const globalName = opts?.globalName ?? '__testBundle';\n const extraExternals = opts?.extraExternals ?? [];\n\n // Lazy load esbuild at call time (see the module-scope import note).\n const esbuild = await import('esbuild');\n\n const result = await esbuild.build({\n entryPoints: [absPath],\n bundle: true,\n format: 'iife',\n globalName,\n platform: 'browser',\n target: 'es2022',\n write: false,\n plugins: [sdkRedirectPlugin()],\n // Extra externals are left as global references (caller's responsibility\n // to ensure they exist in the WebView context).\n external: extraExternals,\n // Keep bundle self-contained; no dynamic require/import at runtime.\n treeShaking: true,\n });\n\n const warnings = result.warnings.map(\n (w) =>\n `${path.relative(process.cwd(), w.location?.file ?? '')}:${w.location?.line ?? '?'}: ${w.text}`,\n );\n\n const outputFile = result.outputFiles?.[0];\n if (!outputFile) {\n throw new Error('bundleTestFile: esbuild produced no output — check entryPoints');\n }\n\n return { code: outputFile.text, warnings };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwDA,MAAM,oBAAoB,IAAI,OAAO,IAPjB,8BAOiC,QAAQ,uBAAuB,OAAO,GAAG;;;;;;;;;;;;;AAc9F,SAAS,oBAAoC;AAC3C,QAAO;EACL,MAAM;EACN,MAAM,OAAO;AAEX,SAAM,UAAU,EAAE,QAAQ,mBAAmB,GAAG,UAAU;IACxD,MAAM,KAAK;IACX,WAAW;IACZ,EAAE;AAEH,SAAM,OAAO;IAAE,QAAQ;IAAM,WAAW;IAAgB,SAAS;IAO/D,UAAU;;;;;;;;;;IAUV,QAAQ;IACT,EAAE;;EAEN;;;;;;;;;;;AAYH,eAAsB,eAAe,SAAiB,MAA6C;CACjG,MAAM,aAAa,MAAM,cAAc;CACvC,MAAM,iBAAiB,MAAM,kBAAkB,EAAE;CAKjD,MAAM,SAAS,OAFC,MAAM,OAAO,YAEA,MAAM;EACjC,aAAa,CAAC,QAAQ;EACtB,QAAQ;EACR,QAAQ;EACR;EACA,UAAU;EACV,QAAQ;EACR,OAAO;EACP,SAAS,CAAC,mBAAmB,CAAC;EAG9B,UAAU;EAEV,aAAa;EACd,CAAC;CAEF,MAAM,WAAW,OAAO,SAAS,KAC9B,MACC,GAAG,KAAK,SAAS,QAAQ,KAAK,EAAE,EAAE,UAAU,QAAQ,GAAG,CAAC,GAAG,EAAE,UAAU,QAAQ,IAAI,IAAI,EAAE,OAC5F;CAED,MAAM,aAAa,OAAO,cAAc;AACxC,KAAI,CAAC,WACH,OAAM,IAAI,MAAM,iEAAiE;AAGnF,QAAO;EAAE,MAAM,WAAW;EAAM;EAAU"}
1
+ {"version":3,"file":"bundle.js","names":[],"sources":["../../src/test-runner/bundle.ts"],"sourcesContent":["/**\n * esbuild-based bundler for user test files.\n *\n * Bundles a single test file into a self-contained IIFE string that can be\n * injected into a WebView via `Runtime.evaluate`. The bundle includes the\n * test runtime (`runtime.ts`), which provides `describe/it/test/expect` and\n * the `runTestModule(factory)` entry point.\n *\n * ## How the wiring works\n *\n * The bundle exposes two exports on `globalThis.__testBundle`:\n * - `runTestModule` — the runtime's entry function.\n * - `__userFactory` — an async function whose body is the user's top-level\n * test registration code (describe/it/test calls).\n *\n * The Node-side RPC (`rpc.ts`) calls:\n * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`\n *\n * `runTestModule` then installs `describe/it/test/expect` as globals, invokes\n * the factory (which registers all tests), runs them, and returns a `RunReport`.\n *\n * ## Why a factory wrapper is needed\n *\n * Naively adding the runtime to `entryPoints` and bundling the user file would\n * fail for two reasons:\n * 1. `describe/it/test/expect` from the runtime are module-local in the IIFE\n * scope. The user's top-level `describe(...)` calls expect them as globals —\n * they are not globals until `runTestModule` installs them.\n * 2. Even with globals pre-installed, the user file runs at IIFE-evaluation\n * time, before the RPC layer calls `runTestModule` to reset state and start\n * the test clock.\n *\n * The factory approach solves both: the user's registration code is deferred\n * into a function that `runTestModule` calls AFTER installing the globals.\n *\n * ## Factory extraction algorithm\n *\n * The `userFactoryPlugin` reads the user file and splits lines into:\n * - **top-level**: `import …` and re-export lines — kept at module scope\n * (the only valid position for static `import` in ESM).\n * - **body**: all other statements — moved into the body of the exported\n * `__userFactory` async function.\n *\n * esbuild processes the re-generated module, following each static import\n * through the normal dependency graph (including the SDK-redirect plugin).\n *\n * ## SDK redirect\n *\n * Imports of `@apps-in-toss/web-framework` (and sub-paths) are intercepted via\n * the `sdkRedirectPlugin` and replaced with a virtual `window.__sdk` proxy that\n * `src/in-app/auto.ts` installs at runtime. This works for both 2.x and 3.x SDK.\n *\n * SECRET-HANDLING: the returned bundle code is caller-managed; never log it.\n */\n\nimport { accessSync } from 'node:fs';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n// esbuild is imported for TYPES only at module scope; the runtime module is\n// loaded lazily inside `bundleTestFile` via dynamic import. esbuild runs a\n// startup invariant check (`TextEncoder().encode('') instanceof Uint8Array`)\n// that fails in a jsdom realm — a static import would break every MCP/test\n// module that merely *imports* this file's transitive graph (e.g. debug-server →\n// run_tests). Lazy load keeps esbuild off the import graph until a bundle is\n// actually built, and mirrors the cloudflared/chii dynamic-import precedent.\nimport type * as esbuild from 'esbuild';\n\n/** Options accepted by `bundleTestFile`. */\nexport interface BundleOptions {\n /**\n * Additional esbuild `external` patterns. The SDK package\n * (`@apps-in-toss/web-framework` and `@apps-in-toss/web-framework/*`) is\n * always handled by the SDK redirect plugin — callers may add more patterns\n * to be left as globals.\n */\n extraExternals?: string[];\n /**\n * Global name for the IIFE output object. Defaults to `__testBundle`.\n * The runtime entry uses this to call `__testBundle.runTestModule(__userFactory)`.\n */\n globalName?: string;\n}\n\n/**\n * The result of bundling a test file.\n * `code` is a self-contained IIFE string ready for `Runtime.evaluate`.\n */\nexport interface BundleResult {\n code: string;\n warnings: string[];\n}\n\n/** The SDK package name that mini-app test code imports from. */\nconst SDK_PACKAGE = '@apps-in-toss/web-framework';\n\n/**\n * Matches the bare SDK package and any sub-path import\n * (`@apps-in-toss/web-framework`, `@apps-in-toss/web-framework/foo`).\n * Built from {@link SDK_PACKAGE} so the package name has a single source.\n */\nconst SDK_IMPORT_FILTER = new RegExp(`^${SDK_PACKAGE.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}`);\n\n/**\n * esbuild plugin that intercepts SDK imports and redirects them to the\n * `window.__sdk` proxy that `src/in-app/auto.ts` installs at runtime.\n *\n * Strategy: for every import of `@apps-in-toss/web-framework` (or sub-paths),\n * esbuild resolves it to a virtual module that re-exports all named exports\n * via `window.__sdk[name]`. This avoids bundling the real SDK (which may not\n * be available in the test environment) while still making named imports work.\n *\n * If `window.__sdk` is absent (non-dog-food build), every access throws a\n * descriptive error rather than returning `undefined` silently.\n */\nfunction sdkRedirectPlugin(): esbuild.Plugin {\n return {\n name: 'sdk-redirect',\n setup(build) {\n // Match the bare package and any sub-path imports\n build.onResolve({ filter: SDK_IMPORT_FILTER }, (args) => ({\n path: args.path,\n namespace: 'sdk-redirect',\n }));\n\n build.onLoad({ filter: /.*/, namespace: 'sdk-redirect' }, () => ({\n // Generate a virtual CommonJS-style module so that esbuild does NOT perform\n // strict named-export matching. When `format:'iife'` bundles a CJS module,\n // it wraps it with its own __toCommonJS helper and satisfies named imports\n // via property access on the module.exports object — which is our Proxy.\n // This means `import { getPlatformOS } from '...'` becomes\n // `__proxy.getPlatformOS` at runtime, which correctly reads from window.__sdk.\n contents: `\nvar __proxy = (typeof window !== 'undefined' && window.__sdk)\n ? window.__sdk\n : new Proxy({}, {\n get: function(_t, p) {\n throw new Error('window.__sdk is not installed — run in a dog-food build. Missing: ' + String(p));\n }\n });\nmodule.exports = __proxy;\n`,\n loader: 'js',\n }));\n },\n };\n}\n\n/**\n * esbuild plugin that transforms the user test file into a module that exports\n * an async `__userFactory` function. The factory defers the user's top-level\n * test registration code (describe/it/test calls) so it only runs when\n * `runTestModule(__userFactory)` explicitly invokes it — AFTER the runtime has\n * installed describe/it/test/expect as globals.\n *\n * Algorithm:\n * - Lines matching import declarations or re-export statements are kept at\n * module top-level (the only valid ESM position for static `import`).\n * - All other lines (describe/it/test calls, local declarations, etc.) are\n * moved into the body of the exported async factory function.\n *\n * This preserves SDK import resolution (the sdk-redirect plugin processes\n * top-level imports normally) while deferring test registration to the factory.\n */\nfunction userFactoryPlugin(absPath: string): esbuild.Plugin {\n const NAMESPACE = 'user-test-factory';\n return {\n name: 'user-test-factory',\n setup(build) {\n // Resolve the virtual \"user-test-factory\" specifier to our namespace.\n build.onResolve({ filter: /^user-test-factory$/ }, () => ({\n path: absPath,\n namespace: NAMESPACE,\n }));\n\n // Load the user file, split imports from body, wrap body in the factory.\n build.onLoad({ filter: /.*/, namespace: NAMESPACE }, async (args) => {\n const source = await fs.readFile(args.path, 'utf8');\n const lines = source.split('\\n');\n\n const topLevelLines: string[] = [];\n const bodyLines: string[] = [];\n\n // Matches `export` value declarations that cannot appear inside a\n // function body. We strip the `export` keyword so they become plain\n // declarations inside the factory.\n const EXPORT_DECLARATION_RE =\n /^(export\\s+)(default\\s+|async\\s+function\\s+|function\\s+|class\\s+|const\\s+|let\\s+|var\\s+)/;\n\n for (const line of lines) {\n const trimmed = line.trimStart();\n const indent = line.slice(0, line.length - trimmed.length);\n\n // Static import declarations must stay at module top level\n // (the ESM spec forbids `import` inside a function body).\n if (\n trimmed.startsWith('import ') ||\n trimmed.startsWith('import{') ||\n trimmed.startsWith(\"import'\") ||\n trimmed.startsWith('import\"')\n ) {\n topLevelLines.push(line);\n } else if (trimmed.startsWith('export ')) {\n // Determine whether this is a re-export (stays top-level) or a value\n // declaration (goes into the factory, export keyword stripped).\n const m = trimmed.match(EXPORT_DECLARATION_RE);\n if (m) {\n // Value declaration — strip `export ` and move into factory body.\n // e.g. `export function hello()` → `function hello()`\n // `export const x = 1` → `const x = 1`\n bodyLines.push(indent + trimmed.slice('export '.length));\n } else {\n // Re-export or `export type { … }` — stays at top level.\n topLevelLines.push(line);\n }\n } else {\n bodyLines.push(line);\n }\n }\n\n const factoryContent = [\n ...topLevelLines,\n '',\n '// biome-ignore lint: generated factory wrapper',\n 'export default async function __userFactory(): Promise<void> {',\n ...bodyLines.map((l) => ` ${l}`),\n '}',\n ].join('\\n');\n\n return {\n contents: factoryContent,\n loader: 'ts',\n resolveDir: path.dirname(absPath),\n };\n });\n },\n };\n}\n\n/**\n * Returns the absolute path to the co-located runtime module.\n *\n * In the source tree (running via tsx / ts-node) the file is `runtime.ts`.\n * After `tsdown` compiles to `dist/test-runner/`, it becomes `runtime.js`.\n * We try both extensions to support both environments.\n */\nfunction getRuntimePath(): string {\n const dir = path.dirname(fileURLToPath(import.meta.url));\n for (const ext of ['.ts', '.js']) {\n const candidate = path.join(dir, `runtime${ext}`);\n try {\n accessSync(candidate);\n return candidate;\n } catch {\n // try next extension\n }\n }\n // Let esbuild produce a \"file not found\" error with a clear path.\n return path.join(dir, 'runtime.js');\n}\n\n/**\n * Bundles `absPath` into a single IIFE string suitable for `Runtime.evaluate`.\n *\n * The IIFE installs `window.__testBundle` (or the custom `globalName`) with:\n * - `runTestModule` — the runtime entry (from `runtime.ts`).\n * - `__userFactory` — an async function wrapping the user's test registration\n * code so it runs AFTER `runTestModule` installs the globals.\n *\n * Callers (rpc.ts) invoke:\n * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`\n *\n * @param absPath - Absolute path to the user test file.\n * @param opts - Optional bundling overrides.\n */\nexport async function bundleTestFile(absPath: string, opts?: BundleOptions): Promise<BundleResult> {\n const globalName = opts?.globalName ?? '__testBundle';\n const extraExternals = opts?.extraExternals ?? [];\n\n // Lazy load esbuild at call time (see the module-scope import note).\n const esbuild = await import('esbuild');\n const runtimePath = getRuntimePath();\n\n // Stdin wrapper: import the runtime and the user factory, re-export both.\n // esbuild follows the static imports to include runtime.ts and the user file\n // (via the userFactoryPlugin) in the single IIFE output.\n const wrapperContent = [\n `import { runTestModule } from ${JSON.stringify(runtimePath)};`,\n `import __userFactory from \"user-test-factory\";`,\n `export { runTestModule, __userFactory };`,\n ].join('\\n');\n\n const result = await esbuild.build({\n stdin: {\n contents: wrapperContent,\n loader: 'ts',\n // resolveDir is used for relative imports from the wrapper. Since the\n // wrapper only imports absolute paths (runtimePath) and the virtual\n // \"user-test-factory\" specifier (resolved by plugin), the directory\n // doesn't matter — but we still provide a sensible default.\n resolveDir: path.dirname(absPath),\n },\n bundle: true,\n format: 'iife',\n globalName,\n platform: 'browser',\n target: 'es2022',\n write: false,\n plugins: [userFactoryPlugin(absPath), sdkRedirectPlugin()],\n external: extraExternals,\n treeShaking: true,\n // Ensure the IIFE result is always reachable via globalThis regardless of\n // the evaluation context. esbuild's `globalName` emits:\n // var __testBundle = (() => { ... })();\n // When `Runtime.evaluate` runs this bundle code inside an outer wrapper\n // (rpc.ts's async IIFE), `var` creates a local variable — NOT a global\n // property — so `globalThis.__testBundle` stays `undefined`. The footer\n // explicitly assigns the local variable to `globalThis` to close that gap.\n footer: {\n js: `globalThis[${JSON.stringify(globalName)}] = ${globalName};`,\n },\n });\n\n const warnings = result.warnings.map(\n (w) =>\n `${path.relative(process.cwd(), w.location?.file ?? '')}:${w.location?.line ?? '?'}: ${w.text}`,\n );\n\n const outputFile = result.outputFiles?.[0];\n if (!outputFile) {\n throw new Error('bundleTestFile: esbuild produced no output — check entryPoints');\n }\n\n return { code: outputFile.text, warnings };\n}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U,QAAQ,IAAI,IAAI,EAAE,OAC5F;CAED,MAAM,aAAa,OAAO,cAAc;AACxC,KAAI,CAAC,WACH,OAAM,IAAI,MAAM,iEAAiE;AAGnF,QAAO;EAAE,MAAM,WAAW;EAAM;EAAU"}
@@ -279,11 +279,53 @@ interface CdpConnection {
279
279
  * esbuild-based bundler for user test files.
280
280
  *
281
281
  * Bundles a single test file into a self-contained IIFE string that can be
282
- * injected into a WebView via `Runtime.evaluate`. The user's SDK imports
283
- * (`@apps-in-toss/web-framework` and sub-paths) are intercepted via an
284
- * esbuild plugin that redirects them to `window.__sdk`, which the in-app
285
- * debug gate (`src/in-app/auto.ts`) installs as a namespace mirror of the
286
- * SDK exports (works for both 2.x and 3.x SDK).
282
+ * injected into a WebView via `Runtime.evaluate`. The bundle includes the
283
+ * test runtime (`runtime.ts`), which provides `describe/it/test/expect` and
284
+ * the `runTestModule(factory)` entry point.
285
+ *
286
+ * ## How the wiring works
287
+ *
288
+ * The bundle exposes two exports on `globalThis.__testBundle`:
289
+ * - `runTestModule` — the runtime's entry function.
290
+ * - `__userFactory` — an async function whose body is the user's top-level
291
+ * test registration code (describe/it/test calls).
292
+ *
293
+ * The Node-side RPC (`rpc.ts`) calls:
294
+ * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
295
+ *
296
+ * `runTestModule` then installs `describe/it/test/expect` as globals, invokes
297
+ * the factory (which registers all tests), runs them, and returns a `RunReport`.
298
+ *
299
+ * ## Why a factory wrapper is needed
300
+ *
301
+ * Naively adding the runtime to `entryPoints` and bundling the user file would
302
+ * fail for two reasons:
303
+ * 1. `describe/it/test/expect` from the runtime are module-local in the IIFE
304
+ * scope. The user's top-level `describe(...)` calls expect them as globals —
305
+ * they are not globals until `runTestModule` installs them.
306
+ * 2. Even with globals pre-installed, the user file runs at IIFE-evaluation
307
+ * time, before the RPC layer calls `runTestModule` to reset state and start
308
+ * the test clock.
309
+ *
310
+ * The factory approach solves both: the user's registration code is deferred
311
+ * into a function that `runTestModule` calls AFTER installing the globals.
312
+ *
313
+ * ## Factory extraction algorithm
314
+ *
315
+ * The `userFactoryPlugin` reads the user file and splits lines into:
316
+ * - **top-level**: `import …` and re-export lines — kept at module scope
317
+ * (the only valid position for static `import` in ESM).
318
+ * - **body**: all other statements — moved into the body of the exported
319
+ * `__userFactory` async function.
320
+ *
321
+ * esbuild processes the re-generated module, following each static import
322
+ * through the normal dependency graph (including the SDK-redirect plugin).
323
+ *
324
+ * ## SDK redirect
325
+ *
326
+ * Imports of `@apps-in-toss/web-framework` (and sub-paths) are intercepted via
327
+ * the `sdkRedirectPlugin` and replaced with a virtual `window.__sdk` proxy that
328
+ * `src/in-app/auto.ts` installs at runtime. This works for both 2.x and 3.x SDK.
287
329
  *
288
330
  * SECRET-HANDLING: the returned bundle code is caller-managed; never log it.
289
331
  */
@@ -298,7 +340,7 @@ interface BundleOptions {
298
340
  extraExternals?: string[];
299
341
  /**
300
342
  * Global name for the IIFE output object. Defaults to `__testBundle`.
301
- * The runtime entry uses this to call `__testBundle.runTestModule()`.
343
+ * The runtime entry uses this to call `__testBundle.runTestModule(__userFactory)`.
302
344
  */
303
345
  globalName?: string;
304
346
  }
@@ -318,8 +360,8 @@ interface BundleOptions {
318
360
  *
319
361
  * @vitest/runner and @vitest/expect are listed as dependencies so that the
320
362
  * package's type contracts are available and so the browser-compatible subsets
321
- * can be referenced. Full pool integration (PoolRunnerInitializer) is tracked
322
- * in issue #645.
363
+ * can be referenced. The Vitest custom pool that drives this runtime through
364
+ * Vitest's `PoolRunnerInitializer` lives in `pool.ts`.
323
365
  *
324
366
  * NOTE: this file is imported by type from Node-side code (rpc.ts / relay-worker.ts)
325
367
  * for the RunReport / TestResult type shapes. The runtime ITSELF is not imported
@@ -398,18 +440,21 @@ interface RunWithConnectionOptions extends RelayRunOptions {
398
440
  }
399
441
  /**
400
442
  * Runs `files` over `connection` and returns the aggregate report.
401
- * This pure function is the testable core of the CLI; it is separate from
402
- * `main()` so tests can call it without spawning a subprocess.
443
+ * This pure function is the testable core of the CLI (and is what the
444
+ * `run_tests` MCP tool calls against the daemon's attached connection); it is
445
+ * separate from `main()` so tests can call it without spawning a subprocess.
403
446
  *
404
- * TODO (#645): add real relay attach/detach lifecycle here (connect via
405
- * Chii relay URL, call enableDomains, run, then close).
447
+ * A standalone CLI relay attach/detach lifecycle (connect via Chii relay URL,
448
+ * `enableDomains`, run, then close) is not wired into `main()` yet.
406
449
  */
407
450
  declare function runWithConnection(connection: CdpConnection, files: string[], opts?: RunWithConnectionOptions): Promise<RelayRunReport>;
408
451
  /**
409
452
  * CLI entry point.
410
453
  *
411
- * MVP: prints usage and a "relay attach required" notice. Real relay wiring
412
- * (resolve CDP URL, attach, run, close) is tracked in issues #645 / #646.
454
+ * Resolves the matched test files and prints a "relay attach required" notice:
455
+ * the CLI's own standalone relay attach (resolve CDP URL, attach, run, close) is
456
+ * not wired yet, so today these files run via the `run_tests` MCP tool against
457
+ * the daemon's attached page.
413
458
  */
414
459
  declare function main(argv?: string[]): Promise<void>;
415
460
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","names":[],"sources":["../../src/mcp/cdp-connection.ts","../../src/test-runner/bundle.ts","../../src/test-runner/runtime.ts","../../src/test-runner/relay-worker.ts","../../src/test-runner/cli.ts"],"mappings":";;;AAwBA;;;;;;;;;AAUA;;;;;;;;;;;AASA;;UAnBiB,SAAA;EA2BI;EAzBnB,EAAA;EAoBA;EAlBA,KAAA;EAoBA;EAlBA,GAAA;AAAA;;UAIe,eAAA;EACf,IAAA;EACA,OAAA;EACA,KAAA;EACA,WAAA;EACA,SAAA;AAAA;AAsBF;AAAA,UAlBiB,qBAAA;;EAEf,IAAA;EACA,IAAA,EAAM,eAAA;EAiBN;EAfA,SAAA;EACA,kBAAA;EACA,UAAA;IACE,UAAA,EAAY,KAAA;MACV,YAAA;MACA,GAAA;MACA,UAAA;MACA,YAAA;IAAA;EAAA;AAAA;;UAMW,6BAAA;EACf,SAAA;EACA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A;EFaC;EEXhB,SAAA;EFiBe;EEff,QAAA;EACA,MAAA;EACA,MAAA;EACA,OAAA;EACA,KAAA,EAAO,UAAA;AAAA;;;;UC5BQ,UAAA;EHiBN;EGfT,IAAA;EHmBoC;EGjBpC,MAAA,EAAQ,SAAA;IAAc,KAAA;EAAA;AAAA;;UAIP,cAAA;EHmBf;EGjBA,SAAA;EHmBE;EGjBF,QAAA;EHkBI;EGhBJ,KAAA,EAAO,UAAA;EHkBH;EGhBJ,MAAA;IACE,MAAA;IACA,MAAA;IACA,OAAA;IACA,KAAA;EAAA;AAAA;;UAKa,eAAA;EHiBb;;;EGbF,aAAA,GAAgB,aAAA;EHkBhB;;;;EGbA,SAAA;AAAA;;;;UCCe,wBAAA,SAAiC,eAAA;EJlBhD;EIoBA,YAAA;AAAA;AJhBF;;;;;;;;AAAA,iBI2BsB,iBAAA,CACpB,UAAA,EAAY,aAAA,EACZ,KAAA,YACA,IAAA,GAAO,wBAAA,GACN,OAAA,CAAQ,cAAA;;;;;;;iBAuBW,IAAA,CAAK,IAAA,cAAyC,OAAA"}
1
+ {"version":3,"file":"cli.d.ts","names":[],"sources":["../../src/mcp/cdp-connection.ts","../../src/test-runner/bundle.ts","../../src/test-runner/runtime.ts","../../src/test-runner/relay-worker.ts","../../src/test-runner/cli.ts"],"mappings":";;;AAwBA;;;;;;;;;AAUA;;;;;;;;;;;AASA;;UAnBiB,SAAA;EA2BI;EAzBnB,EAAA;EAoBA;EAlBA,KAAA;EAoBA;EAlBA,GAAA;AAAA;;UAIe,eAAA;EACf,IAAA;EACA,OAAA;EACA,KAAA;EACA,WAAA;EACA,SAAA;AAAA;AAsBF;AAAA,UAlBiB,qBAAA;;EAEf,IAAA;EACA,IAAA,EAAM,eAAA;EAiBN;EAfA,SAAA;EACA,kBAAA;EACA,UAAA;IACE,UAAA,EAAY,KAAA;MACV,YAAA;MACA,GAAA;MACA,UAAA;MACA,YAAA;IAAA;EAAA;AAAA;;UAMW,6BAAA;EACf,SAAA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EFgBA;EEdA,MAAA;EFgBA;EEdA,QAAA;EFec;EEbd,KAAA;AAAA;;UAIe,SAAA;EFaC;EEXhB,SAAA;EFiBe;EEff,QAAA;EACA,MAAA;EACA,MAAA;EACA,OAAA;EACA,KAAA,EAAO,UAAA;AAAA;;;;UC3BQ,UAAA;EHoBA;EGlBf,IAAA;;EAEA,MAAA,EAAQ,SAAA;IAAc,KAAA;EAAA;AAAA;;UAIP,cAAA;EHmBf;EGjBA,SAAA;EHkBc;EGhBd,QAAA;EHkBI;EGhBJ,KAAA,EAAO,UAAA;EHkBH;EGhBJ,MAAA;IACE,MAAA;IACA,MAAA;IACA,OAAA;IACA,KAAA;EAAA;AAAA;;UAKa,eAAA;EHiBb;;;EGbF,aAAA,GAAgB,aAAA;EHmBhB;;;;EGdA,SAAA;AAAA;;;;UCDe,wBAAA,SAAiC,eAAA;EJjBvC;EImBT,YAAA;AAAA;;;;;;;;;;iBAYoB,iBAAA,CACpB,UAAA,EAAY,aAAA,EACZ,KAAA,YACA,IAAA,GAAO,wBAAA,GACN,OAAA,CAAQ,cAAA;;;;;;;;AJbX;iBIsCsB,IAAA,CAAK,IAAA,cAAyC,OAAA"}
@@ -1,8 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from "node:util";
3
+ import * as fs from "node:fs/promises";
3
4
  import { glob } from "node:fs/promises";
4
5
  import * as path from "node:path";
5
6
  import { isAbsolute, resolve } from "node:path";
7
+ import { accessSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
6
9
  //#region src/test-runner/discover.ts
7
10
  /**
8
11
  * Test-file discovery shared by the `devtools-test` CLI and the `run_tests`
@@ -39,11 +42,53 @@ async function discoverTestFiles(patterns, cwd) {
39
42
  * esbuild-based bundler for user test files.
40
43
  *
41
44
  * Bundles a single test file into a self-contained IIFE string that can be
42
- * injected into a WebView via `Runtime.evaluate`. The user's SDK imports
43
- * (`@apps-in-toss/web-framework` and sub-paths) are intercepted via an
44
- * esbuild plugin that redirects them to `window.__sdk`, which the in-app
45
- * debug gate (`src/in-app/auto.ts`) installs as a namespace mirror of the
46
- * SDK exports (works for both 2.x and 3.x SDK).
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.
47
92
  *
48
93
  * SECRET-HANDLING: the returned bundle code is caller-managed; never log it.
49
94
  */
@@ -93,10 +138,90 @@ module.exports = __proxy;
93
138
  };
94
139
  }
95
140
  /**
141
+ * esbuild plugin that transforms the user test file into a module that exports
142
+ * an async `__userFactory` function. The factory defers the user's top-level
143
+ * test registration code (describe/it/test calls) so it only runs when
144
+ * `runTestModule(__userFactory)` explicitly invokes it — AFTER the runtime has
145
+ * installed describe/it/test/expect as globals.
146
+ *
147
+ * Algorithm:
148
+ * - Lines matching import declarations or re-export statements are kept at
149
+ * module top-level (the only valid ESM position for static `import`).
150
+ * - All other lines (describe/it/test calls, local declarations, etc.) are
151
+ * moved into the body of the exported async factory function.
152
+ *
153
+ * This preserves SDK import resolution (the sdk-redirect plugin processes
154
+ * top-level imports normally) while deferring test registration to the factory.
155
+ */
156
+ function userFactoryPlugin(absPath) {
157
+ const NAMESPACE = "user-test-factory";
158
+ return {
159
+ name: "user-test-factory",
160
+ setup(build) {
161
+ build.onResolve({ filter: /^user-test-factory$/ }, () => ({
162
+ path: absPath,
163
+ namespace: NAMESPACE
164
+ }));
165
+ build.onLoad({
166
+ filter: /.*/,
167
+ namespace: NAMESPACE
168
+ }, async (args) => {
169
+ const lines = (await fs.readFile(args.path, "utf8")).split("\n");
170
+ const topLevelLines = [];
171
+ const bodyLines = [];
172
+ const EXPORT_DECLARATION_RE = /^(export\s+)(default\s+|async\s+function\s+|function\s+|class\s+|const\s+|let\s+|var\s+)/;
173
+ for (const line of lines) {
174
+ const trimmed = line.trimStart();
175
+ const indent = line.slice(0, line.length - trimmed.length);
176
+ if (trimmed.startsWith("import ") || trimmed.startsWith("import{") || trimmed.startsWith("import'") || trimmed.startsWith("import\"")) topLevelLines.push(line);
177
+ else if (trimmed.startsWith("export ")) if (trimmed.match(EXPORT_DECLARATION_RE)) bodyLines.push(indent + trimmed.slice(7));
178
+ else topLevelLines.push(line);
179
+ else bodyLines.push(line);
180
+ }
181
+ return {
182
+ contents: [
183
+ ...topLevelLines,
184
+ "",
185
+ "// biome-ignore lint: generated factory wrapper",
186
+ "export default async function __userFactory(): Promise<void> {",
187
+ ...bodyLines.map((l) => ` ${l}`),
188
+ "}"
189
+ ].join("\n"),
190
+ loader: "ts",
191
+ resolveDir: path.dirname(absPath)
192
+ };
193
+ });
194
+ }
195
+ };
196
+ }
197
+ /**
198
+ * Returns the absolute path to the co-located runtime module.
199
+ *
200
+ * In the source tree (running via tsx / ts-node) the file is `runtime.ts`.
201
+ * After `tsdown` compiles to `dist/test-runner/`, it becomes `runtime.js`.
202
+ * We try both extensions to support both environments.
203
+ */
204
+ function getRuntimePath() {
205
+ const dir = path.dirname(fileURLToPath(import.meta.url));
206
+ for (const ext of [".ts", ".js"]) {
207
+ const candidate = path.join(dir, `runtime${ext}`);
208
+ try {
209
+ accessSync(candidate);
210
+ return candidate;
211
+ } catch {}
212
+ }
213
+ return path.join(dir, "runtime.js");
214
+ }
215
+ /**
96
216
  * Bundles `absPath` into a single IIFE string suitable for `Runtime.evaluate`.
97
217
  *
98
- * The IIFE installs `window.__testBundle` (or the custom `globalName`) with
99
- * `runTestModule` as the callable entry point.
218
+ * The IIFE installs `window.__testBundle` (or the custom `globalName`) with:
219
+ * - `runTestModule` the runtime entry (from `runtime.ts`).
220
+ * - `__userFactory` — an async function wrapping the user's test registration
221
+ * code so it runs AFTER `runTestModule` installs the globals.
222
+ *
223
+ * Callers (rpc.ts) invoke:
224
+ * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
100
225
  *
101
226
  * @param absPath - Absolute path to the user test file.
102
227
  * @param opts - Optional bundling overrides.
@@ -104,17 +229,29 @@ module.exports = __proxy;
104
229
  async function bundleTestFile(absPath, opts) {
105
230
  const globalName = opts?.globalName ?? "__testBundle";
106
231
  const extraExternals = opts?.extraExternals ?? [];
107
- const result = await (await import("esbuild")).build({
108
- entryPoints: [absPath],
232
+ const esbuild = await import("esbuild");
233
+ const runtimePath = getRuntimePath();
234
+ const wrapperContent = [
235
+ `import { runTestModule } from ${JSON.stringify(runtimePath)};`,
236
+ `import __userFactory from "user-test-factory";`,
237
+ `export { runTestModule, __userFactory };`
238
+ ].join("\n");
239
+ const result = await esbuild.build({
240
+ stdin: {
241
+ contents: wrapperContent,
242
+ loader: "ts",
243
+ resolveDir: path.dirname(absPath)
244
+ },
109
245
  bundle: true,
110
246
  format: "iife",
111
247
  globalName,
112
248
  platform: "browser",
113
249
  target: "es2022",
114
250
  write: false,
115
- plugins: [sdkRedirectPlugin()],
251
+ plugins: [userFactoryPlugin(absPath), sdkRedirectPlugin()],
116
252
  external: extraExternals,
117
- treeShaking: true
253
+ treeShaking: true,
254
+ footer: { js: `globalThis[${JSON.stringify(globalName)}] = ${globalName};` }
118
255
  });
119
256
  const warnings = result.warnings.map((w) => `${path.relative(process.cwd(), w.location?.file ?? "")}:${w.location?.line ?? "?"}: ${w.text}`);
120
257
  const outputFile = result.outputFiles?.[0];
@@ -141,7 +278,7 @@ const DEFAULT_TIMEOUT_MS = 3e4;
141
278
  * SECRET-HANDLING: `bundleCode` MUST NOT be logged by callers.
142
279
  */
143
280
  function buildRunTestsExpression(bundleCode) {
144
- 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') { return JSON.stringify({ok:false,error:'bundle-missing-export: __testBundle.runTestModule is not a function'}); } try { const report = await globalThis.__testBundle.runTestModule(); return JSON.stringify({ok:true,value:report}); } catch(e) { return JSON.stringify({ok:false,error:'test-run: ' + String(e && e.message || e)}); }})()`;
281
+ 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)}); }})()`;
145
282
  }
146
283
  /**
147
284
  * Parses the raw CDP `returnByValue` result from a `buildRunTestsExpression`
@@ -274,14 +411,15 @@ async function runTestFilesOverRelay(connection, files, opts) {
274
411
  //#endregion
275
412
  //#region src/test-runner/cli.ts
276
413
  /**
277
- * `devtools-test` CLI — MVP skeleton.
414
+ * `devtools-test` CLI.
278
415
  *
279
- * Parses argv, prints usage, and delegates to `runTestFilesOverRelay` when
280
- * a live CDP connection is provided. The relay connection wiring
281
- * (attach run detach) is tracked in issue #645 / #646.
282
- *
283
- * MVP contract: `--help` works, `runWithConnection` is a testable pure
284
- * function, and the binary entry exists in package.json.
416
+ * Shares test-file discovery with the `run_tests` MCP tool (`discoverTestFiles`)
417
+ * and exposes `runWithConnection` the pure run core that bundles, injects, and
418
+ * collects each file over a CDP connection. Today the run path that has a live
419
+ * connection is the `run_tests` MCP tool (it runs these files against the
420
+ * daemon's attached page); the CLI's own standalone relay attach (resolve CDP
421
+ * URL attach run close) is not wired yet, so `main()` resolves the matched
422
+ * files and points the operator at the MCP tool.
285
423
  *
286
424
  * NOTE: no shebang in this source file — the tsdown entry's `banner` option
287
425
  * injects `#!/usr/bin/env node` into the compiled output (same pattern as
@@ -302,12 +440,10 @@ DESCRIPTION
302
440
  window.__sdk), injects the bundle into the attached WebView via
303
441
  Runtime.evaluate, and returns a RunReport.
304
442
 
305
- A live CDP relay connection must be active before running tests.
306
- Use \`/ait debug\` (devtools-mcp) to attach and then call this CLI from
307
- the same process context.
308
-
309
- Full Vitest pool integration and the \`run_tests\` MCP tool are tracked in
310
- issues #645 and #646 respectively. This MVP provides the transport layer.
443
+ A live CDP relay connection must be active before running tests. Use the
444
+ \`run_tests\` MCP tool (via \`devtools-mcp\` / \`/ait debug\`) to run these files
445
+ against an attached page — the CLI's own standalone relay attach is not wired
446
+ yet (it currently resolves the matched files and defers to that tool).
311
447
 
312
448
  EXAMPLE
313
449
  devtools-test 'src/**/*.phone.test.ts' --timeout 60000
@@ -315,11 +451,12 @@ EXAMPLE
315
451
  `.trimStart();
316
452
  /**
317
453
  * Runs `files` over `connection` and returns the aggregate report.
318
- * This pure function is the testable core of the CLI; it is separate from
319
- * `main()` so tests can call it without spawning a subprocess.
454
+ * This pure function is the testable core of the CLI (and is what the
455
+ * `run_tests` MCP tool calls against the daemon's attached connection); it is
456
+ * separate from `main()` so tests can call it without spawning a subprocess.
320
457
  *
321
- * TODO (#645): add real relay attach/detach lifecycle here (connect via
322
- * Chii relay URL, call enableDomains, run, then close).
458
+ * A standalone CLI relay attach/detach lifecycle (connect via Chii relay URL,
459
+ * `enableDomains`, run, then close) is not wired into `main()` yet.
323
460
  */
324
461
  async function runWithConnection(connection, files, opts) {
325
462
  const report = await runTestFilesOverRelay(connection, files, opts);
@@ -332,8 +469,10 @@ async function runWithConnection(connection, files, opts) {
332
469
  /**
333
470
  * CLI entry point.
334
471
  *
335
- * MVP: prints usage and a "relay attach required" notice. Real relay wiring
336
- * (resolve CDP URL, attach, run, close) is tracked in issues #645 / #646.
472
+ * Resolves the matched test files and prints a "relay attach required" notice:
473
+ * the CLI's own standalone relay attach (resolve CDP URL, attach, run, close) is
474
+ * not wired yet, so today these files run via the `run_tests` MCP tool against
475
+ * the daemon's attached page.
337
476
  */
338
477
  async function main(argv = process.argv.slice(2)) {
339
478
  let parsed;
@@ -364,7 +503,7 @@ async function main(argv = process.argv.slice(2)) {
364
503
  process.exitCode = 1;
365
504
  return;
366
505
  }
367
- 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 Direct CLI relay wiring is tracked in issue #645.\n`);
506
+ 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`);
368
507
  process.exitCode = 1;
369
508
  }
370
509
  if (import.meta.url === new URL(process.argv[1], "file://").href) main().catch((e) => {