@ait-co/devtools 0.1.107 → 0.1.109
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle-KFs4t-wc.d.ts +96 -0
- package/dist/bundle-KFs4t-wc.d.ts.map +1 -0
- package/dist/cdp-connection-C0AP0tH2.d.ts +277 -0
- package/dist/cdp-connection-C0AP0tH2.d.ts.map +1 -0
- package/dist/in-app/auto.d.ts +17 -0
- package/dist/in-app/auto.d.ts.map +1 -1
- package/dist/in-app/auto.js +76 -0
- package/dist/in-app/auto.js.map +1 -1
- package/dist/in-app/index.d.ts +48 -1
- package/dist/in-app/index.d.ts.map +1 -1
- package/dist/in-app/index.js +60 -1
- package/dist/in-app/index.js.map +1 -1
- package/dist/mcp/cli.js +651 -9
- package/dist/mcp/cli.js.map +1 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +59 -2
- package/dist/mcp/server.js.map +1 -1
- package/dist/panel/index.js +1 -1
- package/dist/pool-CuVMzWGB.d.ts +14577 -0
- package/dist/pool-CuVMzWGB.d.ts.map +1 -0
- package/dist/relay-worker-xxanNQGs.d.ts +74 -0
- package/dist/relay-worker-xxanNQGs.d.ts.map +1 -0
- package/dist/runtime-Wi5d6Ywz.d.ts +50 -0
- package/dist/runtime-Wi5d6Ywz.d.ts.map +1 -0
- package/dist/test-runner/bundle.d.ts +2 -0
- package/dist/test-runner/bundle.js +232 -0
- package/dist/test-runner/bundle.js.map +1 -0
- package/dist/test-runner/cli.d.ts +462 -0
- package/dist/test-runner/cli.d.ts.map +1 -0
- package/dist/test-runner/cli.js +516 -0
- package/dist/test-runner/cli.js.map +1 -0
- package/dist/test-runner/config.d.ts +80 -0
- package/dist/test-runner/config.d.ts.map +1 -0
- package/dist/test-runner/config.js +54 -0
- package/dist/test-runner/config.js.map +1 -0
- package/dist/test-runner/pool.d.ts +2 -0
- package/dist/test-runner/pool.js +136 -0
- package/dist/test-runner/pool.js.map +1 -0
- package/dist/test-runner/relay-worker.d.ts +2 -0
- package/dist/test-runner/relay-worker.js +96 -0
- package/dist/test-runner/relay-worker.js.map +1 -0
- package/dist/test-runner/rpc.d.ts +53 -0
- package/dist/test-runner/rpc.d.ts.map +1 -0
- package/dist/test-runner/rpc.js +78 -0
- package/dist/test-runner/rpc.js.map +1 -0
- package/dist/test-runner/task-graph.d.ts +38 -0
- package/dist/test-runner/task-graph.d.ts.map +1 -0
- package/dist/test-runner/task-graph.js +182 -0
- package/dist/test-runner/task-graph.js.map +1 -0
- package/dist/unplugin/index.d.cts +13 -32
- package/dist/unplugin/index.d.cts.map +1 -1
- package/dist/unplugin/index.d.ts +13 -32
- package/dist/unplugin/index.d.ts.map +1 -1
- package/package.json +13 -3
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { t as BundleOptions } from "./bundle-KFs4t-wc.js";
|
|
2
|
+
import { t as CdpConnection } from "./cdp-connection-C0AP0tH2.js";
|
|
3
|
+
import { n as TestResult, t as RunReport } from "./runtime-Wi5d6Ywz.js";
|
|
4
|
+
|
|
5
|
+
//#region src/test-runner/relay-worker.d.ts
|
|
6
|
+
/** Per-file result in the aggregate `RunReport`. */
|
|
7
|
+
interface FileResult {
|
|
8
|
+
/** Absolute or relative path to the test file. */
|
|
9
|
+
file: string;
|
|
10
|
+
/** Full run report for this file, or an error if bundling/injection failed. */
|
|
11
|
+
result: RunReport | {
|
|
12
|
+
error: string;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** Aggregate report returned by `runTestFilesOverRelay`. */
|
|
16
|
+
interface RelayRunReport {
|
|
17
|
+
/** ISO timestamp of when the run started. */
|
|
18
|
+
startedAt: string;
|
|
19
|
+
/** Total elapsed wall-clock milliseconds. */
|
|
20
|
+
duration: number;
|
|
21
|
+
/** Per-file results in execution order. */
|
|
22
|
+
files: FileResult[];
|
|
23
|
+
/** Flattened totals across all files. */
|
|
24
|
+
totals: {
|
|
25
|
+
passed: number;
|
|
26
|
+
failed: number;
|
|
27
|
+
skipped: number;
|
|
28
|
+
total: number;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** Options for `runTestFilesOverRelay`. */
|
|
32
|
+
interface RelayRunOptions {
|
|
33
|
+
/**
|
|
34
|
+
* Options forwarded to `bundleTestFile` for each file.
|
|
35
|
+
*/
|
|
36
|
+
bundleOptions?: BundleOptions;
|
|
37
|
+
/**
|
|
38
|
+
* Per-file evaluate timeout in milliseconds. Defaults to 30 000.
|
|
39
|
+
* Increase for long-running suites or split the file.
|
|
40
|
+
*/
|
|
41
|
+
timeoutMs?: number;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Runs all `files` sequentially over the given CDP `connection`.
|
|
45
|
+
*
|
|
46
|
+
* For each file:
|
|
47
|
+
* 1. Bundle with esbuild (includes SDK shim + runtime).
|
|
48
|
+
* 2. Inject into the attached page via `Runtime.evaluate`.
|
|
49
|
+
* 3. Await the `RunReport` JSON response.
|
|
50
|
+
* 4. Accumulate results.
|
|
51
|
+
*
|
|
52
|
+
* Returns a `RelayRunReport` with per-file results and flattened totals.
|
|
53
|
+
*
|
|
54
|
+
* This function does NOT open or manage the relay connection — the caller
|
|
55
|
+
* is responsible for attaching and closing it.
|
|
56
|
+
*
|
|
57
|
+
* TODO (#645): implement the Vitest `PoolRunnerInitializer` interface here
|
|
58
|
+
* so that `runTestFilesOverRelay` can be used as a Vitest pool entry.
|
|
59
|
+
*
|
|
60
|
+
* @param connection - Active CDP connection (relay or local kind).
|
|
61
|
+
* @param files - Absolute paths to test files, run in order.
|
|
62
|
+
* @param opts - Optional per-run overrides.
|
|
63
|
+
*/
|
|
64
|
+
declare function runTestFilesOverRelay(connection: CdpConnection, files: string[], opts?: RelayRunOptions): Promise<RelayRunReport>;
|
|
65
|
+
/**
|
|
66
|
+
* Flattens all test results from a `RelayRunReport` into a single array.
|
|
67
|
+
* Files that errored during bundle/inject produce a synthetic failed entry.
|
|
68
|
+
*/
|
|
69
|
+
declare function flattenResults(report: RelayRunReport): Array<TestResult & {
|
|
70
|
+
file: string;
|
|
71
|
+
}>;
|
|
72
|
+
//#endregion
|
|
73
|
+
export { runTestFilesOverRelay as a, flattenResults as i, RelayRunOptions as n, RelayRunReport as r, FileResult as t };
|
|
74
|
+
//# sourceMappingURL=relay-worker-xxanNQGs.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relay-worker-xxanNQGs.d.ts","names":[],"sources":["../src/test-runner/relay-worker.ts"],"mappings":";;;;;;UAuBiB,UAAA;EAcf;EAZA,IAAA;EAcA;EAZA,MAAA,EAAQ,SAAA;IAAc,KAAA;EAAA;AAAA;;UAIP,cAAA;EAiBA;EAff,SAAA;;EAEA,QAAA;EAiBA;EAfA,KAAA,EAAO,UAAA;EAoBP;EAlBA,MAAA;IACE,MAAA;IACA,MAAA;IACA,OAAA;IACA,KAAA;EAAA;AAAA;;UAKa,eAAA;EAqCP;;;EAjCR,aAAA,GAAgB,aAAA;EA+BhB;;;;EA1BA,SAAA;AAAA;;AAoFF;;;;;;;;;;;;;;;;;;;;iBA5DsB,qBAAA,CACpB,UAAA,EAAY,aAAA,EACZ,KAAA,YACA,IAAA,GAAO,eAAA,GACN,OAAA,CAAQ,cAAA;;;;;iBAwDK,cAAA,CAAe,MAAA,EAAQ,cAAA,GAAiB,KAAA,CAAM,UAAA;EAAe,IAAA;AAAA"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
//#region src/test-runner/runtime.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Thin test runtime for WebView execution.
|
|
4
|
+
*
|
|
5
|
+
* This file is bundled by `bundle.ts` together with the user's test file
|
|
6
|
+
* into a single IIFE injected into the WebView via `Runtime.evaluate`.
|
|
7
|
+
* It MUST stay browser-compatible — no Node.js APIs allowed.
|
|
8
|
+
*
|
|
9
|
+
* Design: rather than shipping @vitest/runner verbatim into a WebView (where
|
|
10
|
+
* its Node-side internals cause issues), this runtime provides a minimal
|
|
11
|
+
* compatible API surface — describe/it/test/expect globals — collects results
|
|
12
|
+
* into a plain JSON-safe object, and exports `runTestModule` as the entry point.
|
|
13
|
+
*
|
|
14
|
+
* @vitest/runner and @vitest/expect are listed as dependencies so that the
|
|
15
|
+
* package's type contracts are available and so the browser-compatible subsets
|
|
16
|
+
* can be referenced. The Vitest custom pool that drives this runtime through
|
|
17
|
+
* Vitest's `PoolRunnerInitializer` lives in `pool.ts`.
|
|
18
|
+
*
|
|
19
|
+
* NOTE: this file is imported by type from Node-side code (rpc.ts / relay-worker.ts)
|
|
20
|
+
* for the RunReport / TestResult type shapes. The runtime ITSELF is not imported
|
|
21
|
+
* at runtime on the Node side — only the types are used.
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Result of a single test case.
|
|
25
|
+
* All fields are JSON-serialisable.
|
|
26
|
+
*/
|
|
27
|
+
interface TestResult {
|
|
28
|
+
/** Full dot-joined test name including nested suite names. */
|
|
29
|
+
name: string;
|
|
30
|
+
/** `'pass'` or `'fail'`. `'skip'` for skipped tests. */
|
|
31
|
+
status: 'pass' | 'fail' | 'skip';
|
|
32
|
+
/** Duration in milliseconds. */
|
|
33
|
+
duration: number;
|
|
34
|
+
/** Error message (fail only). Does NOT include the expression/secret. */
|
|
35
|
+
error?: string;
|
|
36
|
+
}
|
|
37
|
+
/** Aggregate report returned by `runTestModule`. */
|
|
38
|
+
interface RunReport {
|
|
39
|
+
/** ISO timestamp of when `runTestModule` was called. */
|
|
40
|
+
startedAt: string;
|
|
41
|
+
/** Total elapsed milliseconds (wall-clock). */
|
|
42
|
+
duration: number;
|
|
43
|
+
passed: number;
|
|
44
|
+
failed: number;
|
|
45
|
+
skipped: number;
|
|
46
|
+
tests: TestResult[];
|
|
47
|
+
}
|
|
48
|
+
//#endregion
|
|
49
|
+
export { TestResult as n, RunReport as t };
|
|
50
|
+
//# sourceMappingURL=runtime-Wi5d6Ywz.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-Wi5d6Ywz.d.ts","names":[],"sources":["../src/test-runner/runtime.ts"],"mappings":";;AA8BA;;;;;;;;;;AAYA;;;;;;;;;;;;;;UAZiB,UAAA;;EAEf,IAAA;;EAEA,MAAA;;EAEA,QAAA;;EAEA,KAAA;AAAA;;UAIe,SAAA;;EAEf,SAAA;;EAEA,QAAA;EACA,MAAA;EACA,MAAA;EACA,OAAA;EACA,KAAA,EAAO,UAAA;AAAA"}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { accessSync } from "node:fs";
|
|
2
|
+
import * as fs from "node:fs/promises";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
//#region src/test-runner/bundle.ts
|
|
6
|
+
/**
|
|
7
|
+
* esbuild-based bundler for user test files.
|
|
8
|
+
*
|
|
9
|
+
* Bundles a single test file into a self-contained IIFE string that can be
|
|
10
|
+
* injected into a WebView via `Runtime.evaluate`. The bundle includes the
|
|
11
|
+
* test runtime (`runtime.ts`), which provides `describe/it/test/expect` and
|
|
12
|
+
* the `runTestModule(factory)` entry point.
|
|
13
|
+
*
|
|
14
|
+
* ## How the wiring works
|
|
15
|
+
*
|
|
16
|
+
* The bundle exposes two exports on `globalThis.__testBundle`:
|
|
17
|
+
* - `runTestModule` — the runtime's entry function.
|
|
18
|
+
* - `__userFactory` — an async function whose body is the user's top-level
|
|
19
|
+
* test registration code (describe/it/test calls).
|
|
20
|
+
*
|
|
21
|
+
* The Node-side RPC (`rpc.ts`) calls:
|
|
22
|
+
* `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
|
|
23
|
+
*
|
|
24
|
+
* `runTestModule` then installs `describe/it/test/expect` as globals, invokes
|
|
25
|
+
* the factory (which registers all tests), runs them, and returns a `RunReport`.
|
|
26
|
+
*
|
|
27
|
+
* ## Why a factory wrapper is needed
|
|
28
|
+
*
|
|
29
|
+
* Naively adding the runtime to `entryPoints` and bundling the user file would
|
|
30
|
+
* fail for two reasons:
|
|
31
|
+
* 1. `describe/it/test/expect` from the runtime are module-local in the IIFE
|
|
32
|
+
* scope. The user's top-level `describe(...)` calls expect them as globals —
|
|
33
|
+
* they are not globals until `runTestModule` installs them.
|
|
34
|
+
* 2. Even with globals pre-installed, the user file runs at IIFE-evaluation
|
|
35
|
+
* time, before the RPC layer calls `runTestModule` to reset state and start
|
|
36
|
+
* the test clock.
|
|
37
|
+
*
|
|
38
|
+
* The factory approach solves both: the user's registration code is deferred
|
|
39
|
+
* into a function that `runTestModule` calls AFTER installing the globals.
|
|
40
|
+
*
|
|
41
|
+
* ## Factory extraction algorithm
|
|
42
|
+
*
|
|
43
|
+
* The `userFactoryPlugin` reads the user file and splits lines into:
|
|
44
|
+
* - **top-level**: `import …` and re-export lines — kept at module scope
|
|
45
|
+
* (the only valid position for static `import` in ESM).
|
|
46
|
+
* - **body**: all other statements — moved into the body of the exported
|
|
47
|
+
* `__userFactory` async function.
|
|
48
|
+
*
|
|
49
|
+
* esbuild processes the re-generated module, following each static import
|
|
50
|
+
* through the normal dependency graph (including the SDK-redirect plugin).
|
|
51
|
+
*
|
|
52
|
+
* ## SDK redirect
|
|
53
|
+
*
|
|
54
|
+
* Imports of `@apps-in-toss/web-framework` (and sub-paths) are intercepted via
|
|
55
|
+
* the `sdkRedirectPlugin` and replaced with a virtual `window.__sdk` proxy that
|
|
56
|
+
* `src/in-app/auto.ts` installs at runtime. This works for both 2.x and 3.x SDK.
|
|
57
|
+
*
|
|
58
|
+
* SECRET-HANDLING: the returned bundle code is caller-managed; never log it.
|
|
59
|
+
*/
|
|
60
|
+
/**
|
|
61
|
+
* Matches the bare SDK package and any sub-path import
|
|
62
|
+
* (`@apps-in-toss/web-framework`, `@apps-in-toss/web-framework/foo`).
|
|
63
|
+
* Built from {@link SDK_PACKAGE} so the package name has a single source.
|
|
64
|
+
*/
|
|
65
|
+
const SDK_IMPORT_FILTER = new RegExp(`^${"@apps-in-toss/web-framework".replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
|
|
66
|
+
/**
|
|
67
|
+
* esbuild plugin that intercepts SDK imports and redirects them to the
|
|
68
|
+
* `window.__sdk` proxy that `src/in-app/auto.ts` installs at runtime.
|
|
69
|
+
*
|
|
70
|
+
* Strategy: for every import of `@apps-in-toss/web-framework` (or sub-paths),
|
|
71
|
+
* esbuild resolves it to a virtual module that re-exports all named exports
|
|
72
|
+
* via `window.__sdk[name]`. This avoids bundling the real SDK (which may not
|
|
73
|
+
* be available in the test environment) while still making named imports work.
|
|
74
|
+
*
|
|
75
|
+
* If `window.__sdk` is absent (non-dog-food build), every access throws a
|
|
76
|
+
* descriptive error rather than returning `undefined` silently.
|
|
77
|
+
*/
|
|
78
|
+
function sdkRedirectPlugin() {
|
|
79
|
+
return {
|
|
80
|
+
name: "sdk-redirect",
|
|
81
|
+
setup(build) {
|
|
82
|
+
build.onResolve({ filter: SDK_IMPORT_FILTER }, (args) => ({
|
|
83
|
+
path: args.path,
|
|
84
|
+
namespace: "sdk-redirect"
|
|
85
|
+
}));
|
|
86
|
+
build.onLoad({
|
|
87
|
+
filter: /.*/,
|
|
88
|
+
namespace: "sdk-redirect"
|
|
89
|
+
}, () => ({
|
|
90
|
+
contents: `
|
|
91
|
+
var __proxy = (typeof window !== 'undefined' && window.__sdk)
|
|
92
|
+
? window.__sdk
|
|
93
|
+
: new Proxy({}, {
|
|
94
|
+
get: function(_t, p) {
|
|
95
|
+
throw new Error('window.__sdk is not installed — run in a dog-food build. Missing: ' + String(p));
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
module.exports = __proxy;
|
|
99
|
+
`,
|
|
100
|
+
loader: "js"
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* esbuild plugin that transforms the user test file into a module that exports
|
|
107
|
+
* an async `__userFactory` function. The factory defers the user's top-level
|
|
108
|
+
* test registration code (describe/it/test calls) so it only runs when
|
|
109
|
+
* `runTestModule(__userFactory)` explicitly invokes it — AFTER the runtime has
|
|
110
|
+
* installed describe/it/test/expect as globals.
|
|
111
|
+
*
|
|
112
|
+
* Algorithm:
|
|
113
|
+
* - Lines matching import declarations or re-export statements are kept at
|
|
114
|
+
* module top-level (the only valid ESM position for static `import`).
|
|
115
|
+
* - All other lines (describe/it/test calls, local declarations, etc.) are
|
|
116
|
+
* moved into the body of the exported async factory function.
|
|
117
|
+
*
|
|
118
|
+
* This preserves SDK import resolution (the sdk-redirect plugin processes
|
|
119
|
+
* top-level imports normally) while deferring test registration to the factory.
|
|
120
|
+
*/
|
|
121
|
+
function userFactoryPlugin(absPath) {
|
|
122
|
+
const NAMESPACE = "user-test-factory";
|
|
123
|
+
return {
|
|
124
|
+
name: "user-test-factory",
|
|
125
|
+
setup(build) {
|
|
126
|
+
build.onResolve({ filter: /^user-test-factory$/ }, () => ({
|
|
127
|
+
path: absPath,
|
|
128
|
+
namespace: NAMESPACE
|
|
129
|
+
}));
|
|
130
|
+
build.onLoad({
|
|
131
|
+
filter: /.*/,
|
|
132
|
+
namespace: NAMESPACE
|
|
133
|
+
}, async (args) => {
|
|
134
|
+
const lines = (await fs.readFile(args.path, "utf8")).split("\n");
|
|
135
|
+
const topLevelLines = [];
|
|
136
|
+
const bodyLines = [];
|
|
137
|
+
const EXPORT_DECLARATION_RE = /^(export\s+)(default\s+|async\s+function\s+|function\s+|class\s+|const\s+|let\s+|var\s+)/;
|
|
138
|
+
for (const line of lines) {
|
|
139
|
+
const trimmed = line.trimStart();
|
|
140
|
+
const indent = line.slice(0, line.length - trimmed.length);
|
|
141
|
+
if (trimmed.startsWith("import ") || trimmed.startsWith("import{") || trimmed.startsWith("import'") || trimmed.startsWith("import\"")) topLevelLines.push(line);
|
|
142
|
+
else if (trimmed.startsWith("export ")) if (trimmed.match(EXPORT_DECLARATION_RE)) bodyLines.push(indent + trimmed.slice(7));
|
|
143
|
+
else topLevelLines.push(line);
|
|
144
|
+
else bodyLines.push(line);
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
contents: [
|
|
148
|
+
...topLevelLines,
|
|
149
|
+
"",
|
|
150
|
+
"// biome-ignore lint: generated factory wrapper",
|
|
151
|
+
"export default async function __userFactory(): Promise<void> {",
|
|
152
|
+
...bodyLines.map((l) => ` ${l}`),
|
|
153
|
+
"}"
|
|
154
|
+
].join("\n"),
|
|
155
|
+
loader: "ts",
|
|
156
|
+
resolveDir: path.dirname(absPath)
|
|
157
|
+
};
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Returns the absolute path to the co-located runtime module.
|
|
164
|
+
*
|
|
165
|
+
* In the source tree (running via tsx / ts-node) the file is `runtime.ts`.
|
|
166
|
+
* After `tsdown` compiles to `dist/test-runner/`, it becomes `runtime.js`.
|
|
167
|
+
* We try both extensions to support both environments.
|
|
168
|
+
*/
|
|
169
|
+
function getRuntimePath() {
|
|
170
|
+
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
171
|
+
for (const ext of [".ts", ".js"]) {
|
|
172
|
+
const candidate = path.join(dir, `runtime${ext}`);
|
|
173
|
+
try {
|
|
174
|
+
accessSync(candidate);
|
|
175
|
+
return candidate;
|
|
176
|
+
} catch {}
|
|
177
|
+
}
|
|
178
|
+
return path.join(dir, "runtime.js");
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Bundles `absPath` into a single IIFE string suitable for `Runtime.evaluate`.
|
|
182
|
+
*
|
|
183
|
+
* The IIFE installs `window.__testBundle` (or the custom `globalName`) with:
|
|
184
|
+
* - `runTestModule` — the runtime entry (from `runtime.ts`).
|
|
185
|
+
* - `__userFactory` — an async function wrapping the user's test registration
|
|
186
|
+
* code so it runs AFTER `runTestModule` installs the globals.
|
|
187
|
+
*
|
|
188
|
+
* Callers (rpc.ts) invoke:
|
|
189
|
+
* `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
|
|
190
|
+
*
|
|
191
|
+
* @param absPath - Absolute path to the user test file.
|
|
192
|
+
* @param opts - Optional bundling overrides.
|
|
193
|
+
*/
|
|
194
|
+
async function bundleTestFile(absPath, opts) {
|
|
195
|
+
const globalName = opts?.globalName ?? "__testBundle";
|
|
196
|
+
const extraExternals = opts?.extraExternals ?? [];
|
|
197
|
+
const esbuild = await import("esbuild");
|
|
198
|
+
const runtimePath = getRuntimePath();
|
|
199
|
+
const wrapperContent = [
|
|
200
|
+
`import { runTestModule } from ${JSON.stringify(runtimePath)};`,
|
|
201
|
+
`import __userFactory from "user-test-factory";`,
|
|
202
|
+
`export { runTestModule, __userFactory };`
|
|
203
|
+
].join("\n");
|
|
204
|
+
const result = await esbuild.build({
|
|
205
|
+
stdin: {
|
|
206
|
+
contents: wrapperContent,
|
|
207
|
+
loader: "ts",
|
|
208
|
+
resolveDir: path.dirname(absPath)
|
|
209
|
+
},
|
|
210
|
+
bundle: true,
|
|
211
|
+
format: "iife",
|
|
212
|
+
globalName,
|
|
213
|
+
platform: "browser",
|
|
214
|
+
target: "es2022",
|
|
215
|
+
write: false,
|
|
216
|
+
plugins: [userFactoryPlugin(absPath), sdkRedirectPlugin()],
|
|
217
|
+
external: extraExternals,
|
|
218
|
+
treeShaking: true,
|
|
219
|
+
footer: { js: `globalThis[${JSON.stringify(globalName)}] = ${globalName};` }
|
|
220
|
+
});
|
|
221
|
+
const warnings = result.warnings.map((w) => `${path.relative(process.cwd(), w.location?.file ?? "")}:${w.location?.line ?? "?"}: ${w.text}`);
|
|
222
|
+
const outputFile = result.outputFiles?.[0];
|
|
223
|
+
if (!outputFile) throw new Error("bundleTestFile: esbuild produced no output — check entryPoints");
|
|
224
|
+
return {
|
|
225
|
+
code: outputFile.text,
|
|
226
|
+
warnings
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
230
|
+
export { bundleTestFile };
|
|
231
|
+
|
|
232
|
+
//# sourceMappingURL=bundle.js.map
|
|
@@ -0,0 +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 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}\n"],"mappings":"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"}
|