@codspeed/playwright-plugin 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 CodSpeed
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,138 @@
1
+ <div align="center">
2
+ <h1><code>@codspeed/playwright-plugin</code></h1>
3
+
4
+ [Playwright](https://playwright.dev) integration for [CodSpeed](https://codspeed.io), to drive an app through Playwright and report measured user flows.
5
+
6
+ [![CI](https://github.com/CodSpeedHQ/codspeed-node/actions/workflows/ci.yml/badge.svg)](https://github.com/CodSpeedHQ/codspeed-node/actions/workflows/ci.yml)
7
+ [![npm (scoped)](https://img.shields.io/npm/v/@codspeed/playwright-plugin)](https://www.npmjs.com/package/@codspeed/playwright-plugin)
8
+ [![Discord](https://img.shields.io/badge/chat%20on-discord-7289da.svg)](https://discord.com/invite/MxpaCfKSqF)
9
+ [![CodSpeed Badge](https://img.shields.io/endpoint?url=https://codspeed.io/badge.json)](https://codspeed.io/CodSpeedHQ/codspeed-node)
10
+
11
+ </div>
12
+
13
+ > [!NOTE]
14
+ > The `@codspeed/playwright-plugin` integration currently supports only the
15
+ > [walltime instrument](https://docs.codspeed.io/instruments/walltime). CPU
16
+ > Simulation is not available.
17
+
18
+ `@codspeed/playwright-plugin` is the CodSpeed integration for
19
+ [Playwright](https://playwright.dev). It runs a user-defined flow against a
20
+ target application, measures the time spent inside that flow, and reports it to
21
+ CodSpeed. The flow itself is plain Playwright code, so anything Playwright can
22
+ drive can be benchmarked.
23
+
24
+ > [!IMPORTANT]
25
+ > Today the plugin supports [Electron](https://www.electronjs.org) apps as a
26
+ > target. Browser-based targets (existing dev servers, static builds, hosted
27
+ > URLs) are on the roadmap and will be added under the same `bench` API.
28
+
29
+ ## Documentation
30
+
31
+ Check out the [documentation](https://docs.codspeed.io/benchmarks/nodejs/playwright) for complete integration instructions.
32
+
33
+ ## Installation
34
+
35
+ Install the plugin alongside `playwright`:
36
+
37
+ ```sh
38
+ npm install --save-dev @codspeed/playwright-plugin playwright
39
+ ```
40
+
41
+ or with `yarn`:
42
+
43
+ ```sh
44
+ yarn add --dev @codspeed/playwright-plugin playwright
45
+ ```
46
+
47
+ or with `pnpm`:
48
+
49
+ ```sh
50
+ pnpm add --save-dev @codspeed/playwright-plugin playwright
51
+ ```
52
+
53
+ ## Example usage with Electron
54
+
55
+ Build your Electron app first so the main entrypoint exists (e.g.,
56
+ `out/main/index.js`), then declare a benchmark with `target.kind` set to
57
+ `"electron"`:
58
+
59
+ ```ts title="bench/inbox.bench.ts"
60
+ import { bench } from "@codspeed/playwright-plugin";
61
+ import path from "node:path";
62
+
63
+ bench(
64
+ "inbox-search",
65
+ async ({ page }) => {
66
+ await page.fill("#search", "quarterly report");
67
+ await page.waitForSelector("#results");
68
+ },
69
+ {
70
+ target: {
71
+ kind: "electron",
72
+ appPath: path.resolve("out/main/index.js"),
73
+ },
74
+ beforeRound: async ({ page }) => {
75
+ await page.waitForSelector("#main:not(.loading)");
76
+ },
77
+ rounds: 5,
78
+ },
79
+ );
80
+ ```
81
+
82
+ For each round, the plugin launches Electron with the provided main entrypoint,
83
+ waits for the first window, runs `beforeRound`, measures `fn`, runs
84
+ `afterRound`, then closes the app.
85
+
86
+ ## API
87
+
88
+ The plugin exposes a single `bench` function. Its shape is target-agnostic:
89
+
90
+ ```ts
91
+ import { bench } from "@codspeed/playwright-plugin";
92
+
93
+ bench(name, fn, options);
94
+ ```
95
+
96
+ | Argument | Type | Required | Description |
97
+ | --------- | ------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
98
+ | `name` | `string` | yes | Identifier of the benchmark, used by CodSpeed to track it across runs. |
99
+ | `fn` | `({ page }) => void \| Promise<void>` | yes | The function whose execution time is measured. Receives a Playwright [`Page`](https://playwright.dev/docs/api/class-page) bound to the target. Everything inside `fn` counts toward the reported timing. |
100
+ | `options` | `BenchOptions` | yes | Target configuration and benchmark settings, detailed below. |
101
+
102
+ ### Options
103
+
104
+ | Option | Type | Default | Description |
105
+ | ------------- | ------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
106
+ | `target` | `Target` | _(required)_ | Discriminated union describing what to drive. The `kind` field selects the target; the remaining fields are specific to that kind. Current variants: [`{ kind: "electron", ... }`](#electron-target-options). |
107
+ | `rounds` | `number` | `1` | Number of measurement rounds. Can be overridden at runtime via the `CODSPEED_PLAYWRIGHT_ROUNDS` environment variable. |
108
+ | `beforeRound` | `({ page }) => void \| Promise<void>` | — | Runs before each round, after the target is ready. Use it to bring the app to a ready state. Not measured. |
109
+ | `afterRound` | `({ page }) => void \| Promise<void>` | — | Runs after each round, before the target is torn down. Not measured. |
110
+
111
+ ### Electron target options
112
+
113
+ | Option | Type | Default | Description |
114
+ | ------------------------------- | ------------ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
115
+ | `target.kind` | `"electron"` | _(required)_ | Selects the Electron target. |
116
+ | `target.appPath` | `string` | _(required)_ | Absolute path to the Electron main entrypoint, e.g., `out/main/index.js`. |
117
+ | `target.electronArgs` | `string[]` | `[]` | Extra CLI flags forwarded to the Electron process. |
118
+ | `target.cwd` | `string` | `process.cwd()` | Working directory for the Electron process. Also the directory `electron` is resolved from when `target.electronExecutablePath` is not set. |
119
+ | `target.electronExecutablePath` | `string` | resolved `electron` | Absolute path to the Electron binary. Only set this to override the default resolution. |
120
+
121
+ ## Running the benchmarks locally
122
+
123
+ With node 24+, you can run typescript files directly:
124
+
125
+ ```bash
126
+ $ node bench/inbox.bench.ts
127
+ [CodSpeed] [round 1/5] 42.13 ms
128
+ [CodSpeed] [round 2/5] 41.78 ms
129
+ [CodSpeed] [round 3/5] 42.05 ms
130
+ [CodSpeed] [round 4/5] 41.92 ms
131
+ [CodSpeed] [round 5/5] 42.21 ms
132
+ ```
133
+
134
+ Locally, `bench` runs the app and prints per-round timings to the terminal.
135
+ Results are uploaded to CodSpeed only when running in the
136
+ [CI environment](https://docs.codspeed.io/benchmarks/nodejs/playwright#running-the-benchmarks-in-your-ci)
137
+ or when using the
138
+ [CodSpeed CLI](https://docs.codspeed.io/cli#running-benchmarks).
package/dist/index.cjs ADDED
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+
3
+ var core = require('@codspeed/core');
4
+ var node_module = require('node:module');
5
+ var node_url = require('node:url');
6
+ var playwright = require('playwright');
7
+
8
+ const DEFAULT_ROUNDS = 3;
9
+ const DEFAULT_PROFILING_JS_FLAGS = "--perf-prof --perf-prof-annotate-wasm --interpreted-frames-native-stack --no-turbo-inlining --no-sandbox";
10
+ let integrationInitialized = false;
11
+ function ensureIntegrationSetup() {
12
+ if (integrationInitialized)
13
+ return;
14
+ integrationInitialized = true;
15
+ core.InstrumentHooks.setIntegration("node-custom", "5.5.0");
16
+ core.InstrumentHooks.setEnvironment("nodejs", "version", process.versions.node);
17
+ core.InstrumentHooks.setEnvironment("nodejs", "v8", process.versions.v8);
18
+ core.InstrumentHooks.writeEnvironment(process.pid);
19
+ }
20
+ function resolveRounds(optionRounds) {
21
+ const envValue = process.env.CODSPEED_PLAYWRIGHT_ROUNDS;
22
+ const raw = envValue ?? optionRounds;
23
+ if (raw === void 0)
24
+ return DEFAULT_ROUNDS;
25
+ const n = Number(raw);
26
+ if (!Number.isInteger(n) || n < 1) {
27
+ throw new Error(`Invalid rounds value: ${raw} (expected positive integer)`);
28
+ }
29
+ return n;
30
+ }
31
+ function resolveElectronExecutable(cwd) {
32
+ const require = node_module.createRequire(node_url.pathToFileURL(`${cwd}/`));
33
+ return require("electron");
34
+ }
35
+ async function launchElectronApp(target) {
36
+ const cwd = target.cwd ?? process.cwd();
37
+ return playwright._electron.launch({
38
+ args: [
39
+ target.appPath,
40
+ ...target.electronArgs ?? [],
41
+ `--js-flags=${DEFAULT_PROFILING_JS_FLAGS}`
42
+ ],
43
+ cwd,
44
+ executablePath: target.electronExecutablePath ?? resolveElectronExecutable(cwd)
45
+ });
46
+ }
47
+ async function runOneSample(fn, options) {
48
+ const app = await launchElectronApp(options.target);
49
+ const page = await app.firstWindow();
50
+ try {
51
+ if (options.beforeRound) {
52
+ await options.beforeRound({ page });
53
+ }
54
+ const startTs = core.InstrumentHooks.currentTimestamp();
55
+ await fn({ page });
56
+ const endTs = core.InstrumentHooks.currentTimestamp();
57
+ core.InstrumentHooks.addMarker(
58
+ process.pid,
59
+ core.MARKER_TYPE_BENCHMARK_START,
60
+ startTs
61
+ );
62
+ core.InstrumentHooks.addMarker(process.pid, core.MARKER_TYPE_BENCHMARK_END, endTs);
63
+ if (options.afterRound) {
64
+ await options.afterRound({ page });
65
+ }
66
+ return endTs - startTs;
67
+ } finally {
68
+ await app.close();
69
+ }
70
+ }
71
+ function buildStats(sampleTimesNs) {
72
+ const sortedTimesNs = sampleTimesNs.map((n) => Number(n)).sort((a, b) => a - b);
73
+ const sum = sortedTimesNs.reduce((acc, t) => acc + t, 0);
74
+ const meanNs = sum / sortedTimesNs.length;
75
+ const variance = sortedTimesNs.reduce((acc, t) => acc + (t - meanNs) ** 2, 0) / sortedTimesNs.length;
76
+ const stdevNs = Math.sqrt(variance);
77
+ const { q1_ns, median_ns, q3_ns, iqr_outlier_rounds, stdev_outlier_rounds } = core.calculateQuantiles({
78
+ meanNs,
79
+ stdevNs,
80
+ sortedTimesNs
81
+ });
82
+ return {
83
+ min_ns: sortedTimesNs[0],
84
+ max_ns: sortedTimesNs[sortedTimesNs.length - 1],
85
+ mean_ns: meanNs,
86
+ stdev_ns: stdevNs,
87
+ q1_ns,
88
+ median_ns,
89
+ q3_ns,
90
+ rounds: sortedTimesNs.length,
91
+ total_time: core.msToS(sum / 1e6),
92
+ iqr_outlier_rounds,
93
+ stdev_outlier_rounds,
94
+ iter_per_round: 1,
95
+ warmup_iters: 0
96
+ };
97
+ }
98
+ async function bench(name, fn, options) {
99
+ const rounds = resolveRounds(options.rounds);
100
+ const uri = `${core.getCallingFile(1)}::${name}`;
101
+ ensureIntegrationSetup();
102
+ core.InstrumentHooks.setExecutedBenchmark(process.pid, uri);
103
+ core.InstrumentHooks.startBenchmark();
104
+ const sampleTimesNs = [];
105
+ try {
106
+ for (let i = 0; i < rounds; i++) {
107
+ const elapsedNs = await runOneSample(fn, options);
108
+ sampleTimesNs.push(elapsedNs);
109
+ console.log(
110
+ `[CodSpeed] [round ${i + 1}/${rounds}] ${(Number(elapsedNs) / 1e6).toFixed(2)} ms`
111
+ );
112
+ }
113
+ } finally {
114
+ core.InstrumentHooks.stopBenchmark();
115
+ }
116
+ const benchmark = {
117
+ name,
118
+ uri,
119
+ config: {
120
+ warmup_time_ns: null,
121
+ min_round_time_ns: null,
122
+ max_rounds: rounds,
123
+ max_time_ns: null
124
+ },
125
+ stats: buildStats(sampleTimesNs)
126
+ };
127
+ core.writeWalltimeResults([benchmark]);
128
+ }
129
+
130
+ exports.bench = bench;
131
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import {\n calculateQuantiles,\n getCallingFile,\n InstrumentHooks,\n MARKER_TYPE_BENCHMARK_END,\n MARKER_TYPE_BENCHMARK_START,\n msToS,\n writeWalltimeResults,\n type Benchmark,\n type BenchmarkStats,\n} from \"@codspeed/core\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { _electron as electron } from \"playwright\";\nimport type { ElectronApplication, Page } from \"playwright-core\";\n\ndeclare const __VERSION__: string;\n\nconst DEFAULT_ROUNDS = 3;\nconst DEFAULT_PROFILING_JS_FLAGS =\n \"--perf-prof --perf-prof-annotate-wasm --interpreted-frames-native-stack --no-turbo-inlining --no-sandbox\";\n\n/**\n * The fixtures passed to a benchmark function, mirroring Playwright's `test`\n * API. Currently exposes the target's main window as `page`.\n */\nexport interface BenchFixtures {\n page: Page;\n}\n\n/**\n * The function whose execution is measured. Everything that runs inside it is\n * included in the reported timing.\n */\nexport type BenchFunction = (fixtures: BenchFixtures) => void | Promise<void>;\n\nexport type BenchHook = (fixtures: BenchFixtures) => void | Promise<void>;\n\n/**\n * Electron-specific target options.\n */\nexport interface ElectronTarget {\n kind: \"electron\";\n /**\n * Absolute path to the Electron main entrypoint (e.g. `out/main/index.js`).\n */\n appPath: string;\n /**\n * CLI flags forwarded to Electron.\n */\n electronArgs?: string[];\n /**\n * Working directory for the Electron process. Defaults to `process.cwd()`.\n */\n cwd?: string;\n /**\n * Absolute path to the Electron executable. When omitted, it is resolved from\n * the `electron` package in `cwd`. Set this only to override that default.\n */\n electronExecutablePath?: string;\n}\n\n/**\n * Determines what kind of host playwright is going to run the tests on\n */\nexport type Target = ElectronTarget;\n\n/**\n * Minimal options for a benchmark. Inspired by Vitest's `bench`, but kept\n * deliberately small.\n */\nexport interface BenchOptions {\n /**\n * Target configuration. The `kind` field selects the target; the remaining\n * fields are specific to that kind.\n */\n target: Target;\n /**\n * Number of measurement rounds to perform. Defaults to 3, or the value of CODSPEED_PLAYWRIGHT_ROUNDS.\n */\n rounds?: number;\n /**\n * Runs before each round, after the target is ready. Use it to bring the app to\n * a ready state. Not measured.\n */\n beforeRound?: BenchHook;\n /**\n * Runs after each round, before the target is torn down. Not measured.\n */\n afterRound?: BenchHook;\n}\n\nlet integrationInitialized = false;\n\n/**\n * Register the integration and environment with the instrumentation. This is\n * process-global, so it only needs to run once regardless of how many\n * benchmarks are defined.\n */\nfunction ensureIntegrationSetup(): void {\n if (integrationInitialized) return;\n integrationInitialized = true;\n\n InstrumentHooks.setIntegration(\"node-custom\", __VERSION__);\n InstrumentHooks.setEnvironment(\"nodejs\", \"version\", process.versions.node);\n InstrumentHooks.setEnvironment(\"nodejs\", \"v8\", process.versions.v8);\n InstrumentHooks.writeEnvironment(process.pid);\n}\n\nfunction resolveRounds(optionRounds: number | undefined): number {\n const envValue = process.env.CODSPEED_PLAYWRIGHT_ROUNDS;\n const raw = envValue ?? optionRounds;\n if (raw === undefined) return DEFAULT_ROUNDS;\n const n = Number(raw);\n if (!Number.isInteger(n) || n < 1) {\n throw new Error(`Invalid rounds value: ${raw} (expected positive integer)`);\n }\n return n;\n}\n\n/**\n * Resolve the path to the Electron binary.\n *\n * Playwright resolves Electron via `require(\"electron/index.js\")` from inside\n * its own package directory. Under isolated installs (e.g. pnpm), Playwright\n * cannot see the project's `electron` dependency and bails out with\n * \"Electron executablePath not found!\". We resolve it ourselves from the\n * benchmark's working directory, where `electron` is a real dependency.\n */\nfunction resolveElectronExecutable(cwd: string): string {\n const require = createRequire(pathToFileURL(`${cwd}/`));\n // `electron`'s main module exports the absolute path to its binary.\n return require(\"electron\") as string;\n}\n\nasync function launchElectronApp(\n target: ElectronTarget,\n): Promise<ElectronApplication> {\n const cwd = target.cwd ?? process.cwd();\n return electron.launch({\n args: [\n target.appPath,\n ...(target.electronArgs ?? []),\n `--js-flags=${DEFAULT_PROFILING_JS_FLAGS}`,\n ],\n cwd,\n executablePath:\n target.electronExecutablePath ?? resolveElectronExecutable(cwd),\n });\n}\n\nasync function runOneSample(\n fn: BenchFunction,\n options: BenchOptions,\n): Promise<bigint> {\n const app = await launchElectronApp(options.target);\n const page = await app.firstWindow();\n\n try {\n if (options.beforeRound) {\n await options.beforeRound({ page });\n }\n\n const startTs = InstrumentHooks.currentTimestamp();\n await fn({ page });\n const endTs = InstrumentHooks.currentTimestamp();\n\n InstrumentHooks.addMarker(\n process.pid,\n MARKER_TYPE_BENCHMARK_START,\n startTs,\n );\n InstrumentHooks.addMarker(process.pid, MARKER_TYPE_BENCHMARK_END, endTs);\n\n if (options.afterRound) {\n await options.afterRound({ page });\n }\n\n return endTs - startTs;\n } finally {\n await app.close();\n }\n}\n\nfunction buildStats(sampleTimesNs: bigint[]): BenchmarkStats {\n const sortedTimesNs = sampleTimesNs\n .map((n) => Number(n))\n .sort((a, b) => a - b);\n\n const sum = sortedTimesNs.reduce((acc, t) => acc + t, 0);\n const meanNs = sum / sortedTimesNs.length;\n const variance =\n sortedTimesNs.reduce((acc, t) => acc + (t - meanNs) ** 2, 0) /\n sortedTimesNs.length;\n const stdevNs = Math.sqrt(variance);\n\n const { q1_ns, median_ns, q3_ns, iqr_outlier_rounds, stdev_outlier_rounds } =\n calculateQuantiles({\n meanNs,\n stdevNs,\n sortedTimesNs,\n });\n\n return {\n min_ns: sortedTimesNs[0],\n max_ns: sortedTimesNs[sortedTimesNs.length - 1],\n mean_ns: meanNs,\n stdev_ns: stdevNs,\n q1_ns,\n median_ns,\n q3_ns,\n rounds: sortedTimesNs.length,\n total_time: msToS(sum / 1e6),\n iqr_outlier_rounds,\n stdev_outlier_rounds,\n iter_per_round: 1,\n warmup_iters: 0,\n };\n}\n\n/**\n * Define and run a CodSpeed-instrumented benchmark, mirroring Playwright's\n * `test` API.\n *\n * Launches the target once per round, runs the user-provided function around a\n * measured region, and writes walltime results to disk so that the CodSpeed\n * runner can pick them up.\n *\n * @example\n * ```ts\n * import { bench } from \"@codspeed/playwright-plugin\";\n *\n * bench(\n * \"renders the dashboard\",\n * async ({ page }) => {\n * await page.getByRole(\"link\", { name: \"Dashboard\" }).click();\n * await page.getByRole(\"heading\", { name: \"Overview\" }).waitFor();\n * },\n * {\n * target: { kind: \"electron\", appPath: \"out/main/index.js\" },\n * rounds: 5,\n * },\n * );\n * ```\n */\nexport async function bench(\n name: string,\n fn: BenchFunction,\n options: BenchOptions,\n): Promise<void> {\n const rounds = resolveRounds(options.rounds);\n const uri = `${getCallingFile(1)}::${name}`;\n\n ensureIntegrationSetup();\n\n InstrumentHooks.setExecutedBenchmark(process.pid, uri);\n InstrumentHooks.startBenchmark();\n\n const sampleTimesNs: bigint[] = [];\n try {\n for (let i = 0; i < rounds; i++) {\n const elapsedNs = await runOneSample(fn, options);\n sampleTimesNs.push(elapsedNs);\n console.log(\n `[CodSpeed] [round ${i + 1}/${rounds}] ${(Number(elapsedNs) / 1e6).toFixed(2)} ms`,\n );\n }\n } finally {\n InstrumentHooks.stopBenchmark();\n }\n\n const benchmark: Benchmark = {\n name,\n uri,\n config: {\n warmup_time_ns: null,\n min_round_time_ns: null,\n max_rounds: rounds,\n max_time_ns: null,\n },\n stats: buildStats(sampleTimesNs),\n };\n\n writeWalltimeResults([benchmark]);\n}\n\nexport type { Page } from \"playwright-core\";\n"],"names":["InstrumentHooks","createRequire","pathToFileURL","electron","MARKER_TYPE_BENCHMARK_START","MARKER_TYPE_BENCHMARK_END","calculateQuantiles","msToS","getCallingFile","writeWalltimeResults"],"mappings":";;;;;;;AAkBA,MAAM,cAAA,GAAiB,CAAA;AACvB,MAAM,0BAAA,GACJ,0GAAA;AAwEF,IAAI,sBAAA,GAAyB,KAAA;AAO7B,SAAS,sBAAA,GAA+B;AACtC,EAAA,IAAI,sBAAA;AAAwB,IAAA;AAC5B,EAAA,sBAAA,GAAyB,IAAA;AAEzB,EAAAA,oBAAA,CAAgB,cAAA,CAAe,eAAe,OAAW,CAAA;AACzD,EAAAA,oBAAA,CAAgB,cAAA,CAAe,QAAA,EAAU,SAAA,EAAW,OAAA,CAAQ,SAAS,IAAI,CAAA;AACzE,EAAAA,oBAAA,CAAgB,cAAA,CAAe,QAAA,EAAU,IAAA,EAAM,OAAA,CAAQ,SAAS,EAAE,CAAA;AAClE,EAAAA,oBAAA,CAAgB,gBAAA,CAAiB,QAAQ,GAAG,CAAA;AAC9C;AAEA,SAAS,cAAc,YAAA,EAA0C;AAC/D,EAAA,MAAM,QAAA,GAAW,QAAQ,GAAA,CAAI,0BAAA;AAC7B,EAAA,MAAM,MAAM,QAAA,IAAY,YAAA;AACxB,EAAA,IAAI,GAAA,KAAQ,MAAA;AAAW,IAAA,OAAO,cAAA;AAC9B,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,CAAC,CAAA,IAAK,IAAI,CAAA,EAAG;AACjC,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,sBAAA,EAAyB,GAAA,CAAA,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AA,MAAM,SAAA,GAAuB;AAAA,IAC3B,IAAA;AAAA,IACA,GAAA;AAAA,IACA,MAAA,EAAQ;AAAA,MACN,cAAA,EAAgB,IAAA;AAAA,MAChB,iBAAA,EAAmB,IAAA;AAAA,MACnB,UAAA,EAAY,MAAA;AAAA,MACZ,WAAA,EAAa;AAAA,KACf;AAAA,IACA,KAAA,EAAO,WAAW,aAAa;AAAA,GACjC;AAEA,EAAAS,yBAAA,CAAqB,CAAC,SAAS,CAAC,CAAA;AAClC;;;;"}
@@ -0,0 +1,96 @@
1
+ import { Page } from 'playwright-core';
2
+ export { Page } from 'playwright-core';
3
+
4
+ /**
5
+ * The fixtures passed to a benchmark function, mirroring Playwright's `test`
6
+ * API. Currently exposes the target's main window as `page`.
7
+ */
8
+ interface BenchFixtures {
9
+ page: Page;
10
+ }
11
+ /**
12
+ * The function whose execution is measured. Everything that runs inside it is
13
+ * included in the reported timing.
14
+ */
15
+ type BenchFunction = (fixtures: BenchFixtures) => void | Promise<void>;
16
+ type BenchHook = (fixtures: BenchFixtures) => void | Promise<void>;
17
+ /**
18
+ * Electron-specific target options.
19
+ */
20
+ interface ElectronTarget {
21
+ kind: "electron";
22
+ /**
23
+ * Absolute path to the Electron main entrypoint (e.g. `out/main/index.js`).
24
+ */
25
+ appPath: string;
26
+ /**
27
+ * CLI flags forwarded to Electron.
28
+ */
29
+ electronArgs?: string[];
30
+ /**
31
+ * Working directory for the Electron process. Defaults to `process.cwd()`.
32
+ */
33
+ cwd?: string;
34
+ /**
35
+ * Absolute path to the Electron executable. When omitted, it is resolved from
36
+ * the `electron` package in `cwd`. Set this only to override that default.
37
+ */
38
+ electronExecutablePath?: string;
39
+ }
40
+ /**
41
+ * Determines what kind of host playwright is going to run the tests on
42
+ */
43
+ type Target = ElectronTarget;
44
+ /**
45
+ * Minimal options for a benchmark. Inspired by Vitest's `bench`, but kept
46
+ * deliberately small.
47
+ */
48
+ interface BenchOptions {
49
+ /**
50
+ * Target configuration. The `kind` field selects the target; the remaining
51
+ * fields are specific to that kind.
52
+ */
53
+ target: Target;
54
+ /**
55
+ * Number of measurement rounds to perform. Defaults to 3, or the value of CODSPEED_PLAYWRIGHT_ROUNDS.
56
+ */
57
+ rounds?: number;
58
+ /**
59
+ * Runs before each round, after the target is ready. Use it to bring the app to
60
+ * a ready state. Not measured.
61
+ */
62
+ beforeRound?: BenchHook;
63
+ /**
64
+ * Runs after each round, before the target is torn down. Not measured.
65
+ */
66
+ afterRound?: BenchHook;
67
+ }
68
+ /**
69
+ * Define and run a CodSpeed-instrumented benchmark, mirroring Playwright's
70
+ * `test` API.
71
+ *
72
+ * Launches the target once per round, runs the user-provided function around a
73
+ * measured region, and writes walltime results to disk so that the CodSpeed
74
+ * runner can pick them up.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * import { bench } from "@codspeed/playwright-plugin";
79
+ *
80
+ * bench(
81
+ * "renders the dashboard",
82
+ * async ({ page }) => {
83
+ * await page.getByRole("link", { name: "Dashboard" }).click();
84
+ * await page.getByRole("heading", { name: "Overview" }).waitFor();
85
+ * },
86
+ * {
87
+ * target: { kind: "electron", appPath: "out/main/index.js" },
88
+ * rounds: 5,
89
+ * },
90
+ * );
91
+ * ```
92
+ */
93
+ declare function bench(name: string, fn: BenchFunction, options: BenchOptions): Promise<void>;
94
+
95
+ export { type BenchFixtures, type BenchFunction, type BenchHook, type BenchOptions, type ElectronTarget, type Target, bench };
96
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,129 @@
1
+ import { getCallingFile, InstrumentHooks, writeWalltimeResults, MARKER_TYPE_BENCHMARK_START, MARKER_TYPE_BENCHMARK_END, calculateQuantiles, msToS } from '@codspeed/core';
2
+ import { createRequire } from 'node:module';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { _electron } from 'playwright';
5
+
6
+ const DEFAULT_ROUNDS = 3;
7
+ const DEFAULT_PROFILING_JS_FLAGS = "--perf-prof --perf-prof-annotate-wasm --interpreted-frames-native-stack --no-turbo-inlining --no-sandbox";
8
+ let integrationInitialized = false;
9
+ function ensureIntegrationSetup() {
10
+ if (integrationInitialized)
11
+ return;
12
+ integrationInitialized = true;
13
+ InstrumentHooks.setIntegration("node-custom", "5.5.0");
14
+ InstrumentHooks.setEnvironment("nodejs", "version", process.versions.node);
15
+ InstrumentHooks.setEnvironment("nodejs", "v8", process.versions.v8);
16
+ InstrumentHooks.writeEnvironment(process.pid);
17
+ }
18
+ function resolveRounds(optionRounds) {
19
+ const envValue = process.env.CODSPEED_PLAYWRIGHT_ROUNDS;
20
+ const raw = envValue ?? optionRounds;
21
+ if (raw === void 0)
22
+ return DEFAULT_ROUNDS;
23
+ const n = Number(raw);
24
+ if (!Number.isInteger(n) || n < 1) {
25
+ throw new Error(`Invalid rounds value: ${raw} (expected positive integer)`);
26
+ }
27
+ return n;
28
+ }
29
+ function resolveElectronExecutable(cwd) {
30
+ const require = createRequire(pathToFileURL(`${cwd}/`));
31
+ return require("electron");
32
+ }
33
+ async function launchElectronApp(target) {
34
+ const cwd = target.cwd ?? process.cwd();
35
+ return _electron.launch({
36
+ args: [
37
+ target.appPath,
38
+ ...target.electronArgs ?? [],
39
+ `--js-flags=${DEFAULT_PROFILING_JS_FLAGS}`
40
+ ],
41
+ cwd,
42
+ executablePath: target.electronExecutablePath ?? resolveElectronExecutable(cwd)
43
+ });
44
+ }
45
+ async function runOneSample(fn, options) {
46
+ const app = await launchElectronApp(options.target);
47
+ const page = await app.firstWindow();
48
+ try {
49
+ if (options.beforeRound) {
50
+ await options.beforeRound({ page });
51
+ }
52
+ const startTs = InstrumentHooks.currentTimestamp();
53
+ await fn({ page });
54
+ const endTs = InstrumentHooks.currentTimestamp();
55
+ InstrumentHooks.addMarker(
56
+ process.pid,
57
+ MARKER_TYPE_BENCHMARK_START,
58
+ startTs
59
+ );
60
+ InstrumentHooks.addMarker(process.pid, MARKER_TYPE_BENCHMARK_END, endTs);
61
+ if (options.afterRound) {
62
+ await options.afterRound({ page });
63
+ }
64
+ return endTs - startTs;
65
+ } finally {
66
+ await app.close();
67
+ }
68
+ }
69
+ function buildStats(sampleTimesNs) {
70
+ const sortedTimesNs = sampleTimesNs.map((n) => Number(n)).sort((a, b) => a - b);
71
+ const sum = sortedTimesNs.reduce((acc, t) => acc + t, 0);
72
+ const meanNs = sum / sortedTimesNs.length;
73
+ const variance = sortedTimesNs.reduce((acc, t) => acc + (t - meanNs) ** 2, 0) / sortedTimesNs.length;
74
+ const stdevNs = Math.sqrt(variance);
75
+ const { q1_ns, median_ns, q3_ns, iqr_outlier_rounds, stdev_outlier_rounds } = calculateQuantiles({
76
+ meanNs,
77
+ stdevNs,
78
+ sortedTimesNs
79
+ });
80
+ return {
81
+ min_ns: sortedTimesNs[0],
82
+ max_ns: sortedTimesNs[sortedTimesNs.length - 1],
83
+ mean_ns: meanNs,
84
+ stdev_ns: stdevNs,
85
+ q1_ns,
86
+ median_ns,
87
+ q3_ns,
88
+ rounds: sortedTimesNs.length,
89
+ total_time: msToS(sum / 1e6),
90
+ iqr_outlier_rounds,
91
+ stdev_outlier_rounds,
92
+ iter_per_round: 1,
93
+ warmup_iters: 0
94
+ };
95
+ }
96
+ async function bench(name, fn, options) {
97
+ const rounds = resolveRounds(options.rounds);
98
+ const uri = `${getCallingFile(1)}::${name}`;
99
+ ensureIntegrationSetup();
100
+ InstrumentHooks.setExecutedBenchmark(process.pid, uri);
101
+ InstrumentHooks.startBenchmark();
102
+ const sampleTimesNs = [];
103
+ try {
104
+ for (let i = 0; i < rounds; i++) {
105
+ const elapsedNs = await runOneSample(fn, options);
106
+ sampleTimesNs.push(elapsedNs);
107
+ console.log(
108
+ `[CodSpeed] [round ${i + 1}/${rounds}] ${(Number(elapsedNs) / 1e6).toFixed(2)} ms`
109
+ );
110
+ }
111
+ } finally {
112
+ InstrumentHooks.stopBenchmark();
113
+ }
114
+ const benchmark = {
115
+ name,
116
+ uri,
117
+ config: {
118
+ warmup_time_ns: null,
119
+ min_round_time_ns: null,
120
+ max_rounds: rounds,
121
+ max_time_ns: null
122
+ },
123
+ stats: buildStats(sampleTimesNs)
124
+ };
125
+ writeWalltimeResults([benchmark]);
126
+ }
127
+
128
+ export { bench };
129
+ //# sourceMappingURL=index.es5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.es5.js","sources":["../src/index.ts"],"sourcesContent":["import {\n calculateQuantiles,\n getCallingFile,\n InstrumentHooks,\n MARKER_TYPE_BENCHMARK_END,\n MARKER_TYPE_BENCHMARK_START,\n msToS,\n writeWalltimeResults,\n type Benchmark,\n type BenchmarkStats,\n} from \"@codspeed/core\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { _electron as electron } from \"playwright\";\nimport type { ElectronApplication, Page } from \"playwright-core\";\n\ndeclare const __VERSION__: string;\n\nconst DEFAULT_ROUNDS = 3;\nconst DEFAULT_PROFILING_JS_FLAGS =\n \"--perf-prof --perf-prof-annotate-wasm --interpreted-frames-native-stack --no-turbo-inlining --no-sandbox\";\n\n/**\n * The fixtures passed to a benchmark function, mirroring Playwright's `test`\n * API. Currently exposes the target's main window as `page`.\n */\nexport interface BenchFixtures {\n page: Page;\n}\n\n/**\n * The function whose execution is measured. Everything that runs inside it is\n * included in the reported timing.\n */\nexport type BenchFunction = (fixtures: BenchFixtures) => void | Promise<void>;\n\nexport type BenchHook = (fixtures: BenchFixtures) => void | Promise<void>;\n\n/**\n * Electron-specific target options.\n */\nexport interface ElectronTarget {\n kind: \"electron\";\n /**\n * Absolute path to the Electron main entrypoint (e.g. `out/main/index.js`).\n */\n appPath: string;\n /**\n * CLI flags forwarded to Electron.\n */\n electronArgs?: string[];\n /**\n * Working directory for the Electron process. Defaults to `process.cwd()`.\n */\n cwd?: string;\n /**\n * Absolute path to the Electron executable. When omitted, it is resolved from\n * the `electron` package in `cwd`. Set this only to override that default.\n */\n electronExecutablePath?: string;\n}\n\n/**\n * Determines what kind of host playwright is going to run the tests on\n */\nexport type Target = ElectronTarget;\n\n/**\n * Minimal options for a benchmark. Inspired by Vitest's `bench`, but kept\n * deliberately small.\n */\nexport interface BenchOptions {\n /**\n * Target configuration. The `kind` field selects the target; the remaining\n * fields are specific to that kind.\n */\n target: Target;\n /**\n * Number of measurement rounds to perform. Defaults to 3, or the value of CODSPEED_PLAYWRIGHT_ROUNDS.\n */\n rounds?: number;\n /**\n * Runs before each round, after the target is ready. Use it to bring the app to\n * a ready state. Not measured.\n */\n beforeRound?: BenchHook;\n /**\n * Runs after each round, before the target is torn down. Not measured.\n */\n afterRound?: BenchHook;\n}\n\nlet integrationInitialized = false;\n\n/**\n * Register the integration and environment with the instrumentation. This is\n * process-global, so it only needs to run once regardless of how many\n * benchmarks are defined.\n */\nfunction ensureIntegrationSetup(): void {\n if (integrationInitialized) return;\n integrationInitialized = true;\n\n InstrumentHooks.setIntegration(\"node-custom\", __VERSION__);\n InstrumentHooks.setEnvironment(\"nodejs\", \"version\", process.versions.node);\n InstrumentHooks.setEnvironment(\"nodejs\", \"v8\", process.versions.v8);\n InstrumentHooks.writeEnvironment(process.pid);\n}\n\nfunction resolveRounds(optionRounds: number | undefined): number {\n const envValue = process.env.CODSPEED_PLAYWRIGHT_ROUNDS;\n const raw = envValue ?? optionRounds;\n if (raw === undefined) return DEFAULT_ROUNDS;\n const n = Number(raw);\n if (!Number.isInteger(n) || n < 1) {\n throw new Error(`Invalid rounds value: ${raw} (expected positive integer)`);\n }\n return n;\n}\n\n/**\n * Resolve the path to the Electron binary.\n *\n * Playwright resolves Electron via `require(\"electron/index.js\")` from inside\n * its own package directory. Under isolated installs (e.g. pnpm), Playwright\n * cannot see the project's `electron` dependency and bails out with\n * \"Electron executablePath not found!\". We resolve it ourselves from the\n * benchmark's working directory, where `electron` is a real dependency.\n */\nfunction resolveElectronExecutable(cwd: string): string {\n const require = createRequire(pathToFileURL(`${cwd}/`));\n // `electron`'s main module exports the absolute path to its binary.\n return require(\"electron\") as string;\n}\n\nasync function launchElectronApp(\n target: ElectronTarget,\n): Promise<ElectronApplication> {\n const cwd = target.cwd ?? process.cwd();\n return electron.launch({\n args: [\n target.appPath,\n ...(target.electronArgs ?? []),\n `--js-flags=${DEFAULT_PROFILING_JS_FLAGS}`,\n ],\n cwd,\n executablePath:\n target.electronExecutablePath ?? resolveElectronExecutable(cwd),\n });\n}\n\nasync function runOneSample(\n fn: BenchFunction,\n options: BenchOptions,\n): Promise<bigint> {\n const app = await launchElectronApp(options.target);\n const page = await app.firstWindow();\n\n try {\n if (options.beforeRound) {\n await options.beforeRound({ page });\n }\n\n const startTs = InstrumentHooks.currentTimestamp();\n await fn({ page });\n const endTs = InstrumentHooks.currentTimestamp();\n\n InstrumentHooks.addMarker(\n process.pid,\n MARKER_TYPE_BENCHMARK_START,\n startTs,\n );\n InstrumentHooks.addMarker(process.pid, MARKER_TYPE_BENCHMARK_END, endTs);\n\n if (options.afterRound) {\n await options.afterRound({ page });\n }\n\n return endTs - startTs;\n } finally {\n await app.close();\n }\n}\n\nfunction buildStats(sampleTimesNs: bigint[]): BenchmarkStats {\n const sortedTimesNs = sampleTimesNs\n .map((n) => Number(n))\n .sort((a, b) => a - b);\n\n const sum = sortedTimesNs.reduce((acc, t) => acc + t, 0);\n const meanNs = sum / sortedTimesNs.length;\n const variance =\n sortedTimesNs.reduce((acc, t) => acc + (t - meanNs) ** 2, 0) /\n sortedTimesNs.length;\n const stdevNs = Math.sqrt(variance);\n\n const { q1_ns, median_ns, q3_ns, iqr_outlier_rounds, stdev_outlier_rounds } =\n calculateQuantiles({\n meanNs,\n stdevNs,\n sortedTimesNs,\n });\n\n return {\n min_ns: sortedTimesNs[0],\n max_ns: sortedTimesNs[sortedTimesNs.length - 1],\n mean_ns: meanNs,\n stdev_ns: stdevNs,\n q1_ns,\n median_ns,\n q3_ns,\n rounds: sortedTimesNs.length,\n total_time: msToS(sum / 1e6),\n iqr_outlier_rounds,\n stdev_outlier_rounds,\n iter_per_round: 1,\n warmup_iters: 0,\n };\n}\n\n/**\n * Define and run a CodSpeed-instrumented benchmark, mirroring Playwright's\n * `test` API.\n *\n * Launches the target once per round, runs the user-provided function around a\n * measured region, and writes walltime results to disk so that the CodSpeed\n * runner can pick them up.\n *\n * @example\n * ```ts\n * import { bench } from \"@codspeed/playwright-plugin\";\n *\n * bench(\n * \"renders the dashboard\",\n * async ({ page }) => {\n * await page.getByRole(\"link\", { name: \"Dashboard\" }).click();\n * await page.getByRole(\"heading\", { name: \"Overview\" }).waitFor();\n * },\n * {\n * target: { kind: \"electron\", appPath: \"out/main/index.js\" },\n * rounds: 5,\n * },\n * );\n * ```\n */\nexport async function bench(\n name: string,\n fn: BenchFunction,\n options: BenchOptions,\n): Promise<void> {\n const rounds = resolveRounds(options.rounds);\n const uri = `${getCallingFile(1)}::${name}`;\n\n ensureIntegrationSetup();\n\n InstrumentHooks.setExecutedBenchmark(process.pid, uri);\n InstrumentHooks.startBenchmark();\n\n const sampleTimesNs: bigint[] = [];\n try {\n for (let i = 0; i < rounds; i++) {\n const elapsedNs = await runOneSample(fn, options);\n sampleTimesNs.push(elapsedNs);\n console.log(\n `[CodSpeed] [round ${i + 1}/${rounds}] ${(Number(elapsedNs) / 1e6).toFixed(2)} ms`,\n );\n }\n } finally {\n InstrumentHooks.stopBenchmark();\n }\n\n const benchmark: Benchmark = {\n name,\n uri,\n config: {\n warmup_time_ns: null,\n min_round_time_ns: null,\n max_rounds: rounds,\n max_time_ns: null,\n },\n stats: buildStats(sampleTimesNs),\n };\n\n writeWalltimeResults([benchmark]);\n}\n\nexport type { Page } from \"playwright-core\";\n"],"names":["electron"],"mappings":";;;;;AAkBA,MAAM,cAAA,GAAiB,CAAA;AACvB,MAAM,0BAAA,GACJ,0GAAA;AAwEF,IAAI,sBAAA,GAAyB,KAAA;AAO7B,SAAS,sBAAA,GAA+B;AACtC,EAAA,IAAI,sBAAA;AAAwB,IAAA;AAC5B,EAAA,sBAAA,GAAyB,IAAA;AAE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AEvB,EAAA,eAAA,CAAgB,oBAAA,CAAqB,OAAA,CAAQ,GAAA,EAAK,GAAG,CAAA;AACrD,EAAA,eAAA,CAAgB,cAAA,EAAe;AAE/B,EAAA,MAAM,gBAA0B,EAAC;AACjC,EAAA,IAAI;AACF,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,MAAA,EAAQ,CAAA,EAAA,EAAK;AAC/B,MAAA,MAAM,SAAA,GAAY,MAAM,YAAA,CAAa,EAAA,EAAI,OAAO,CAAA;AAChD,MAAA,aAAA,CAAc,KAAK,SAAS,CAAA;AAC5B,MAAA,OAAA,CAAQ,GAAA;AAAA,QACN,CAAA,kBAAA,EAAqB,IAAI,CAAA,CAAA,CAAA,EAAK,MAAA,CAAA,EAAA,EAAA,CAAY,OAAO,SAAS,CAAA,GAAI,GAAA,EAAK,OAAA,CAAQ,CAAC,CAAA,CAAA,GAAA;AAAA,OAC9E;AAAA,IACF;AAAA,EACF,CAAA,SAAE;AACA,IAAA,eAAA,CAAgB,aAAA,EAAc;AAAA,EAChC;AAEA,EAAA,MAAM,SAAA,GAAuB;AAAA,IAC3B,IAAA;AAAA,IACA,GAAA;AAAA,IACA,MAAA,EAAQ;AAAA,MACN,cAAA,EAAgB,IAAA;AAAA,MAChB,iBAAA,EAAmB,IAAA;AAAA,MACnB,UAAA,EAAY,MAAA;AAAA,MACZ,WAAA,EAAa;AAAA,KACf;AAAA,IACA,KAAA,EAAO,WAAW,aAAa;AAAA,GACjC;AAEA,EAAA,oBAAA,CAAqB,CAAC,SAAS,CAAC,CAAA;AAClC;;;;"}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@codspeed/playwright-plugin",
3
+ "version": "5.5.0",
4
+ "description": "Playwright benchmarking integration for CodSpeed",
5
+ "keywords": [
6
+ "codspeed",
7
+ "benchmark",
8
+ "playwright",
9
+ "electron",
10
+ "performance"
11
+ ],
12
+ "main": "dist/index.cjs",
13
+ "module": "dist/index.es5.js",
14
+ "types": "dist/index.d.ts",
15
+ "type": "module",
16
+ "exports": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.es5.js",
19
+ "require": "./dist/index.cjs"
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "author": "Guillaume Lagrange <guillaume@codspeed.io>",
25
+ "repository": "https://github.com/CodSpeedHQ/codspeed-node",
26
+ "homepage": "https://codspeed.io",
27
+ "license": "Apache-2.0",
28
+ "devDependencies": {
29
+ "playwright": "^1.48.0",
30
+ "playwright-core": "^1.48.0",
31
+ "vitest": "^3.2.4"
32
+ },
33
+ "dependencies": {
34
+ "@codspeed/core": "^5.5.0"
35
+ },
36
+ "peerDependencies": {
37
+ "playwright": ">=1.40.0"
38
+ },
39
+ "scripts": {
40
+ "build": "NODE_NO_WARNINGS=1 rollup -c rollup.config.ts --configPlugin typescript",
41
+ "test": "echo 'no tests'",
42
+ "test/integ": "echo 'no integ tests'",
43
+ "lint": "eslint .",
44
+ "typecheck": "tsc --noEmit --pretty",
45
+ "format": "prettier --config ../../.prettierrc.json --ignore-path ../../.prettierignore --check .",
46
+ "fix-format": "prettier --config ../../.prettierrc.json --ignore-path ../../.prettierignore --write .",
47
+ "clean": "rm -rf dist"
48
+ }
49
+ }