@scoutqa/playwright 1.58.0-fork.1

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 (172) hide show
  1. package/ThirdPartyNotices.txt +3919 -0
  2. package/cli.js +19 -0
  3. package/index.d.ts +17 -0
  4. package/index.js +17 -0
  5. package/index.mjs +18 -0
  6. package/jsx-runtime.js +42 -0
  7. package/jsx-runtime.mjs +21 -0
  8. package/lib/agents/agentParser.js +89 -0
  9. package/lib/agents/copilot-setup-steps.yml +34 -0
  10. package/lib/agents/generateAgents.js +348 -0
  11. package/lib/agents/playwright-test-coverage.prompt.md +31 -0
  12. package/lib/agents/playwright-test-generate.prompt.md +8 -0
  13. package/lib/agents/playwright-test-generator.agent.md +88 -0
  14. package/lib/agents/playwright-test-heal.prompt.md +6 -0
  15. package/lib/agents/playwright-test-healer.agent.md +55 -0
  16. package/lib/agents/playwright-test-plan.prompt.md +9 -0
  17. package/lib/agents/playwright-test-planner.agent.md +73 -0
  18. package/lib/common/config.js +281 -0
  19. package/lib/common/configLoader.js +344 -0
  20. package/lib/common/esmLoaderHost.js +104 -0
  21. package/lib/common/expectBundle.js +43 -0
  22. package/lib/common/expectBundleImpl.js +407 -0
  23. package/lib/common/fixtures.js +302 -0
  24. package/lib/common/globals.js +58 -0
  25. package/lib/common/ipc.js +60 -0
  26. package/lib/common/poolBuilder.js +85 -0
  27. package/lib/common/process.js +132 -0
  28. package/lib/common/suiteUtils.js +140 -0
  29. package/lib/common/test.js +322 -0
  30. package/lib/common/testLoader.js +101 -0
  31. package/lib/common/testType.js +298 -0
  32. package/lib/common/validators.js +68 -0
  33. package/lib/fsWatcher.js +67 -0
  34. package/lib/index.js +721 -0
  35. package/lib/internalsForTest.js +42 -0
  36. package/lib/isomorphic/events.js +77 -0
  37. package/lib/isomorphic/folders.js +30 -0
  38. package/lib/isomorphic/stringInternPool.js +69 -0
  39. package/lib/isomorphic/teleReceiver.js +523 -0
  40. package/lib/isomorphic/teleSuiteUpdater.js +157 -0
  41. package/lib/isomorphic/testServerConnection.js +225 -0
  42. package/lib/isomorphic/testServerInterface.js +16 -0
  43. package/lib/isomorphic/testTree.js +329 -0
  44. package/lib/isomorphic/types.d.js +16 -0
  45. package/lib/loader/loaderMain.js +59 -0
  46. package/lib/matchers/expect.js +324 -0
  47. package/lib/matchers/matcherHint.js +87 -0
  48. package/lib/matchers/matchers.js +382 -0
  49. package/lib/matchers/toBeTruthy.js +73 -0
  50. package/lib/matchers/toEqual.js +99 -0
  51. package/lib/matchers/toHaveURL.js +102 -0
  52. package/lib/matchers/toMatchAriaSnapshot.js +159 -0
  53. package/lib/matchers/toMatchSnapshot.js +341 -0
  54. package/lib/matchers/toMatchText.js +99 -0
  55. package/lib/mcp/browser/actions.d.js +16 -0
  56. package/lib/mcp/browser/browserContextFactory.js +321 -0
  57. package/lib/mcp/browser/browserServerBackend.js +77 -0
  58. package/lib/mcp/browser/config.js +418 -0
  59. package/lib/mcp/browser/context.js +285 -0
  60. package/lib/mcp/browser/response.js +352 -0
  61. package/lib/mcp/browser/sessionLog.js +160 -0
  62. package/lib/mcp/browser/tab.js +328 -0
  63. package/lib/mcp/browser/tools/common.js +63 -0
  64. package/lib/mcp/browser/tools/console.js +44 -0
  65. package/lib/mcp/browser/tools/dialogs.js +60 -0
  66. package/lib/mcp/browser/tools/evaluate.js +59 -0
  67. package/lib/mcp/browser/tools/files.js +58 -0
  68. package/lib/mcp/browser/tools/form.js +63 -0
  69. package/lib/mcp/browser/tools/install.js +69 -0
  70. package/lib/mcp/browser/tools/keyboard.js +84 -0
  71. package/lib/mcp/browser/tools/mouse.js +107 -0
  72. package/lib/mcp/browser/tools/navigate.js +62 -0
  73. package/lib/mcp/browser/tools/network.js +60 -0
  74. package/lib/mcp/browser/tools/pdf.js +48 -0
  75. package/lib/mcp/browser/tools/runCode.js +77 -0
  76. package/lib/mcp/browser/tools/screenshot.js +105 -0
  77. package/lib/mcp/browser/tools/snapshot.js +191 -0
  78. package/lib/mcp/browser/tools/tabs.js +67 -0
  79. package/lib/mcp/browser/tools/tool.js +50 -0
  80. package/lib/mcp/browser/tools/tracing.js +74 -0
  81. package/lib/mcp/browser/tools/utils.js +94 -0
  82. package/lib/mcp/browser/tools/verify.js +143 -0
  83. package/lib/mcp/browser/tools/wait.js +63 -0
  84. package/lib/mcp/browser/tools.js +82 -0
  85. package/lib/mcp/browser/watchdog.js +44 -0
  86. package/lib/mcp/config.d.js +16 -0
  87. package/lib/mcp/extension/cdpRelay.js +351 -0
  88. package/lib/mcp/extension/extensionContextFactory.js +76 -0
  89. package/lib/mcp/extension/protocol.js +28 -0
  90. package/lib/mcp/index.js +61 -0
  91. package/lib/mcp/log.js +35 -0
  92. package/lib/mcp/program.js +93 -0
  93. package/lib/mcp/sdk/exports.js +28 -0
  94. package/lib/mcp/sdk/http.js +152 -0
  95. package/lib/mcp/sdk/inProcessTransport.js +71 -0
  96. package/lib/mcp/sdk/server.js +207 -0
  97. package/lib/mcp/sdk/tool.js +47 -0
  98. package/lib/mcp/test/browserBackend.js +98 -0
  99. package/lib/mcp/test/generatorTools.js +122 -0
  100. package/lib/mcp/test/plannerTools.js +144 -0
  101. package/lib/mcp/test/seed.js +82 -0
  102. package/lib/mcp/test/streams.js +44 -0
  103. package/lib/mcp/test/testBackend.js +99 -0
  104. package/lib/mcp/test/testContext.js +279 -0
  105. package/lib/mcp/test/testTool.js +30 -0
  106. package/lib/mcp/test/testTools.js +108 -0
  107. package/lib/plugins/gitCommitInfoPlugin.js +198 -0
  108. package/lib/plugins/index.js +28 -0
  109. package/lib/plugins/webServerPlugin.js +237 -0
  110. package/lib/program.js +417 -0
  111. package/lib/reporters/base.js +609 -0
  112. package/lib/reporters/blob.js +139 -0
  113. package/lib/reporters/dot.js +82 -0
  114. package/lib/reporters/empty.js +32 -0
  115. package/lib/reporters/github.js +128 -0
  116. package/lib/reporters/html.js +623 -0
  117. package/lib/reporters/internalReporter.js +140 -0
  118. package/lib/reporters/json.js +255 -0
  119. package/lib/reporters/junit.js +232 -0
  120. package/lib/reporters/line.js +113 -0
  121. package/lib/reporters/list.js +231 -0
  122. package/lib/reporters/listModeReporter.js +69 -0
  123. package/lib/reporters/markdown.js +144 -0
  124. package/lib/reporters/merge.js +546 -0
  125. package/lib/reporters/multiplexer.js +112 -0
  126. package/lib/reporters/reporterV2.js +102 -0
  127. package/lib/reporters/teleEmitter.js +319 -0
  128. package/lib/reporters/versions/blobV1.js +16 -0
  129. package/lib/runner/dispatcher.js +533 -0
  130. package/lib/runner/failureTracker.js +72 -0
  131. package/lib/runner/lastRun.js +77 -0
  132. package/lib/runner/loadUtils.js +334 -0
  133. package/lib/runner/loaderHost.js +89 -0
  134. package/lib/runner/processHost.js +180 -0
  135. package/lib/runner/projectUtils.js +241 -0
  136. package/lib/runner/rebase.js +189 -0
  137. package/lib/runner/reporters.js +138 -0
  138. package/lib/runner/sigIntWatcher.js +96 -0
  139. package/lib/runner/storage.js +91 -0
  140. package/lib/runner/taskRunner.js +127 -0
  141. package/lib/runner/tasks.js +410 -0
  142. package/lib/runner/testGroups.js +125 -0
  143. package/lib/runner/testRunner.js +398 -0
  144. package/lib/runner/testServer.js +269 -0
  145. package/lib/runner/uiModeReporter.js +30 -0
  146. package/lib/runner/vcs.js +72 -0
  147. package/lib/runner/watchMode.js +396 -0
  148. package/lib/runner/workerHost.js +104 -0
  149. package/lib/third_party/pirates.js +62 -0
  150. package/lib/third_party/tsconfig-loader.js +103 -0
  151. package/lib/transform/babelBundle.js +43 -0
  152. package/lib/transform/babelBundleImpl.js +461 -0
  153. package/lib/transform/babelHighlightUtils.js +63 -0
  154. package/lib/transform/compilationCache.js +272 -0
  155. package/lib/transform/esmLoader.js +103 -0
  156. package/lib/transform/portTransport.js +67 -0
  157. package/lib/transform/transform.js +296 -0
  158. package/lib/util.js +403 -0
  159. package/lib/utilsBundle.js +43 -0
  160. package/lib/utilsBundleImpl.js +100 -0
  161. package/lib/worker/fixtureRunner.js +258 -0
  162. package/lib/worker/testInfo.js +557 -0
  163. package/lib/worker/testTracing.js +345 -0
  164. package/lib/worker/timeoutManager.js +174 -0
  165. package/lib/worker/util.js +31 -0
  166. package/lib/worker/workerMain.js +529 -0
  167. package/package.json +72 -0
  168. package/test.d.ts +18 -0
  169. package/test.js +24 -0
  170. package/test.mjs +34 -0
  171. package/types/test.d.ts +10277 -0
  172. package/types/testReporter.d.ts +827 -0
package/lib/mcp/log.js ADDED
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var log_exports = {};
20
+ __export(log_exports, {
21
+ logUnhandledError: () => logUnhandledError,
22
+ testDebug: () => testDebug
23
+ });
24
+ module.exports = __toCommonJS(log_exports);
25
+ var import_utilsBundle = require("playwright-core/lib/utilsBundle");
26
+ const errorDebug = (0, import_utilsBundle.debug)("pw:mcp:error");
27
+ function logUnhandledError(error) {
28
+ errorDebug(error);
29
+ }
30
+ const testDebug = (0, import_utilsBundle.debug)("pw:mcp:test");
31
+ // Annotate the CommonJS export names for ESM import in node:
32
+ 0 && (module.exports = {
33
+ logUnhandledError,
34
+ testDebug
35
+ });
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var program_exports = {};
30
+ __export(program_exports, {
31
+ decorateCommand: () => decorateCommand
32
+ });
33
+ module.exports = __toCommonJS(program_exports);
34
+ var import_fs = __toESM(require("fs"));
35
+ var import_utilsBundle = require("playwright-core/lib/utilsBundle");
36
+ var import_server = require("playwright-core/lib/server");
37
+ var mcpServer = __toESM(require("./sdk/server"));
38
+ var import_config = require("./browser/config");
39
+ var import_watchdog = require("./browser/watchdog");
40
+ var import_browserContextFactory = require("./browser/browserContextFactory");
41
+ var import_browserServerBackend = require("./browser/browserServerBackend");
42
+ var import_extensionContextFactory = require("./extension/extensionContextFactory");
43
+ function decorateCommand(command, version) {
44
+ command.option("--allowed-hosts <hosts...>", "comma-separated list of hosts this server is allowed to serve from. Defaults to the host the server is bound to. Pass '*' to disable the host check.", import_config.commaSeparatedList).option("--allowed-origins <origins>", "semicolon-separated list of TRUSTED origins to allow the browser to request. Default is to allow all.\nImportant: *does not* serve as a security boundary and *does not* affect redirects. ", import_config.semicolonSeparatedList).option("--blocked-origins <origins>", "semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.\nImportant: *does not* serve as a security boundary and *does not* affect redirects.", import_config.semicolonSeparatedList).option("--block-service-workers", "block service workers").option("--browser <browser>", "browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.").option("--caps <caps>", "comma-separated list of additional capabilities to enable, possible values: vision, pdf.", import_config.commaSeparatedList).option("--cdp-endpoint <endpoint>", "CDP endpoint to connect to.").option("--cdp-header <headers...>", "CDP headers to send with the connect request, multiple can be specified.", import_config.headerParser).option("--config <path>", "path to the configuration file.").option("--console-level <level>", 'level of console messages to return: "error", "warning", "info", "debug". Each level includes the messages of more severe levels.', import_config.enumParser.bind(null, "--console-level", ["error", "warning", "info", "debug"])).option("--device <device>", 'device to emulate, for example: "iPhone 15"').option("--executable-path <path>", "path to the browser executable.").option("--extension", 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.').option("--grant-permissions <permissions...>", 'List of permissions to grant to the browser context, for example "geolocation", "clipboard-read", "clipboard-write".', import_config.commaSeparatedList).option("--headless", "run browser in headless mode, headed by default").option("--host <host>", "host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.").option("--ignore-https-errors", "ignore https errors").option("--init-page <path...>", "path to TypeScript file to evaluate on Playwright page object").option("--init-script <path...>", "path to JavaScript file to add as an initialization script. The script will be evaluated in every page before any of the page's scripts. Can be specified multiple times.").option("--isolated", "keep the browser profile in memory, do not save it to disk.").option("--image-responses <mode>", 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".', import_config.enumParser.bind(null, "--image-responses", ["allow", "omit"])).option("--no-sandbox", "disable the sandbox for all process types that are normally sandboxed.").option("--output-dir <path>", "path to the directory for output files.").option("--port <port>", "port to listen on for SSE transport.").option("--proxy-bypass <bypass>", 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"').option("--proxy-server <proxy>", 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"').option("--save-session", "Whether to save the Playwright MCP session into the output directory.").option("--save-trace", "Whether to save the Playwright Trace of the session into the output directory.").option("--save-video <size>", 'Whether to save the video of the session into the output directory. For example "--save-video=800x600"', import_config.resolutionParser.bind(null, "--save-video")).option("--secrets <path>", "path to a file containing secrets in the dotenv format", import_config.dotenvFileLoader).option("--shared-browser-context", "reuse the same browser context between all connected HTTP clients.").option("--snapshot-mode <mode>", 'when taking snapshots for responses, specifies the mode to use. Can be "incremental", "full", or "none". Default is incremental.').option("--storage-state <path>", "path to the storage state file for isolated sessions.").option("--test-id-attribute <attribute>", 'specify the attribute to use for test ids, defaults to "data-testid"').option("--timeout-action <timeout>", "specify action timeout in milliseconds, defaults to 5000ms", import_config.numberParser).option("--timeout-navigation <timeout>", "specify navigation timeout in milliseconds, defaults to 60000ms", import_config.numberParser).option("--user-agent <ua string>", "specify user agent string").option("--user-data-dir <path>", "path to the user data directory. If not specified, a temporary directory will be created.").option("--viewport-size <size>", 'specify browser viewport size in pixels, for example "1280x720"', import_config.resolutionParser.bind(null, "--viewport-size")).addOption(new import_utilsBundle.ProgramOption("--vision", "Legacy option, use --caps=vision instead").hideHelp()).action(async (options) => {
45
+ (0, import_watchdog.setupExitWatchdog)();
46
+ if (options.vision) {
47
+ console.error("The --vision option is deprecated, use --caps=vision instead");
48
+ options.caps = "vision";
49
+ }
50
+ const config = await (0, import_config.resolveCLIConfig)(options);
51
+ if (config.saveVideo && !checkFfmpeg()) {
52
+ console.error(import_utilsBundle.colors.red(`
53
+ Error: ffmpeg required to save the video is not installed.`));
54
+ console.error(`
55
+ Please run the command below. It will install a local copy of ffmpeg and will not change any system-wide settings.`);
56
+ console.error(`
57
+ npx playwright install ffmpeg
58
+ `);
59
+ process.exit(1);
60
+ }
61
+ const browserContextFactory = (0, import_browserContextFactory.contextFactory)(config);
62
+ const extensionContextFactory = new import_extensionContextFactory.ExtensionContextFactory(config.browser.launchOptions.channel || "chrome", config.browser.userDataDir, config.browser.launchOptions.executablePath);
63
+ if (options.extension) {
64
+ const serverBackendFactory = {
65
+ name: "Playwright w/ extension",
66
+ nameInConfig: "playwright-extension",
67
+ version,
68
+ create: () => new import_browserServerBackend.BrowserServerBackend(config, extensionContextFactory)
69
+ };
70
+ await mcpServer.start(serverBackendFactory, config.server);
71
+ return;
72
+ }
73
+ const factory = {
74
+ name: "Playwright",
75
+ nameInConfig: "playwright",
76
+ version,
77
+ create: () => new import_browserServerBackend.BrowserServerBackend(config, browserContextFactory)
78
+ };
79
+ await mcpServer.start(factory, config.server);
80
+ });
81
+ }
82
+ function checkFfmpeg() {
83
+ try {
84
+ const executable = import_server.registry.findExecutable("ffmpeg");
85
+ return import_fs.default.existsSync(executable.executablePath("javascript"));
86
+ } catch (error) {
87
+ return false;
88
+ }
89
+ }
90
+ // Annotate the CommonJS export names for ESM import in node:
91
+ 0 && (module.exports = {
92
+ decorateCommand
93
+ });
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var exports_exports = {};
17
+ module.exports = __toCommonJS(exports_exports);
18
+ __reExport(exports_exports, require("./inProcessTransport"), module.exports);
19
+ __reExport(exports_exports, require("./server"), module.exports);
20
+ __reExport(exports_exports, require("./tool"), module.exports);
21
+ __reExport(exports_exports, require("./http"), module.exports);
22
+ // Annotate the CommonJS export names for ESM import in node:
23
+ 0 && (module.exports = {
24
+ ...require("./inProcessTransport"),
25
+ ...require("./server"),
26
+ ...require("./tool"),
27
+ ...require("./http")
28
+ });
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var http_exports = {};
30
+ __export(http_exports, {
31
+ addressToString: () => addressToString,
32
+ startMcpHttpServer: () => startMcpHttpServer
33
+ });
34
+ module.exports = __toCommonJS(http_exports);
35
+ var import_assert = __toESM(require("assert"));
36
+ var import_crypto = __toESM(require("crypto"));
37
+ var import_utilsBundle = require("playwright-core/lib/utilsBundle");
38
+ var mcpBundle = __toESM(require("playwright-core/lib/mcpBundle"));
39
+ var import_utils = require("playwright-core/lib/utils");
40
+ var mcpServer = __toESM(require("./server"));
41
+ const testDebug = (0, import_utilsBundle.debug)("pw:mcp:test");
42
+ async function startMcpHttpServer(config, serverBackendFactory, allowedHosts) {
43
+ const httpServer = (0, import_utils.createHttpServer)();
44
+ await (0, import_utils.startHttpServer)(httpServer, config);
45
+ return await installHttpTransport(httpServer, serverBackendFactory, allowedHosts);
46
+ }
47
+ function addressToString(address, options) {
48
+ (0, import_assert.default)(address, "Could not bind server socket");
49
+ if (typeof address === "string")
50
+ throw new Error("Unexpected address type: " + address);
51
+ let host = address.family === "IPv4" ? address.address : `[${address.address}]`;
52
+ if (options.normalizeLoopback && (host === "0.0.0.0" || host === "[::]" || host === "[::1]" || host === "127.0.0.1"))
53
+ host = "localhost";
54
+ return `${options.protocol}://${host}:${address.port}`;
55
+ }
56
+ async function installHttpTransport(httpServer, serverBackendFactory, allowedHosts) {
57
+ const url = addressToString(httpServer.address(), { protocol: "http", normalizeLoopback: true });
58
+ const host = new URL(url).host;
59
+ allowedHosts = (allowedHosts || [host]).map((h) => h.toLowerCase());
60
+ const allowAnyHost = allowedHosts.includes("*");
61
+ const sseSessions = /* @__PURE__ */ new Map();
62
+ const streamableSessions = /* @__PURE__ */ new Map();
63
+ httpServer.on("request", async (req, res) => {
64
+ if (!allowAnyHost) {
65
+ const host2 = req.headers.host?.toLowerCase();
66
+ if (!host2) {
67
+ res.statusCode = 400;
68
+ return res.end("Missing host");
69
+ }
70
+ if (!allowedHosts.includes(host2)) {
71
+ res.statusCode = 403;
72
+ return res.end("Access is only allowed at " + allowedHosts.join(", "));
73
+ }
74
+ }
75
+ const url2 = new URL(`http://localhost${req.url}`);
76
+ if (url2.pathname === "/killkillkill" && req.method === "GET") {
77
+ res.statusCode = 200;
78
+ res.end("Killing process");
79
+ process.emit("SIGINT");
80
+ return;
81
+ }
82
+ if (url2.pathname.startsWith("/sse"))
83
+ await handleSSE(serverBackendFactory, req, res, url2, sseSessions);
84
+ else
85
+ await handleStreamable(serverBackendFactory, req, res, streamableSessions);
86
+ });
87
+ return url;
88
+ }
89
+ async function handleSSE(serverBackendFactory, req, res, url, sessions) {
90
+ if (req.method === "POST") {
91
+ const sessionId = url.searchParams.get("sessionId");
92
+ if (!sessionId) {
93
+ res.statusCode = 400;
94
+ return res.end("Missing sessionId");
95
+ }
96
+ const transport = sessions.get(sessionId);
97
+ if (!transport) {
98
+ res.statusCode = 404;
99
+ return res.end("Session not found");
100
+ }
101
+ return await transport.handlePostMessage(req, res);
102
+ } else if (req.method === "GET") {
103
+ const transport = new mcpBundle.SSEServerTransport("/sse", res);
104
+ sessions.set(transport.sessionId, transport);
105
+ testDebug(`create SSE session: ${transport.sessionId}`);
106
+ await mcpServer.connect(serverBackendFactory, transport, false);
107
+ res.on("close", () => {
108
+ testDebug(`delete SSE session: ${transport.sessionId}`);
109
+ sessions.delete(transport.sessionId);
110
+ });
111
+ return;
112
+ }
113
+ res.statusCode = 405;
114
+ res.end("Method not allowed");
115
+ }
116
+ async function handleStreamable(serverBackendFactory, req, res, sessions) {
117
+ const sessionId = req.headers["mcp-session-id"];
118
+ if (sessionId) {
119
+ const transport = sessions.get(sessionId);
120
+ if (!transport) {
121
+ res.statusCode = 404;
122
+ res.end("Session not found");
123
+ return;
124
+ }
125
+ return await transport.handleRequest(req, res);
126
+ }
127
+ if (req.method === "POST") {
128
+ const transport = new mcpBundle.StreamableHTTPServerTransport({
129
+ sessionIdGenerator: () => import_crypto.default.randomUUID(),
130
+ onsessioninitialized: async (sessionId2) => {
131
+ testDebug(`create http session: ${transport.sessionId}`);
132
+ await mcpServer.connect(serverBackendFactory, transport, true);
133
+ sessions.set(sessionId2, transport);
134
+ }
135
+ });
136
+ transport.onclose = () => {
137
+ if (!transport.sessionId)
138
+ return;
139
+ sessions.delete(transport.sessionId);
140
+ testDebug(`delete http session: ${transport.sessionId}`);
141
+ };
142
+ await transport.handleRequest(req, res);
143
+ return;
144
+ }
145
+ res.statusCode = 400;
146
+ res.end("Invalid request");
147
+ }
148
+ // Annotate the CommonJS export names for ESM import in node:
149
+ 0 && (module.exports = {
150
+ addressToString,
151
+ startMcpHttpServer
152
+ });
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var inProcessTransport_exports = {};
20
+ __export(inProcessTransport_exports, {
21
+ InProcessTransport: () => InProcessTransport
22
+ });
23
+ module.exports = __toCommonJS(inProcessTransport_exports);
24
+ class InProcessTransport {
25
+ constructor(server) {
26
+ this._connected = false;
27
+ this._server = server;
28
+ this._serverTransport = new InProcessServerTransport(this);
29
+ }
30
+ async start() {
31
+ if (this._connected)
32
+ throw new Error("InprocessTransport already started!");
33
+ await this._server.connect(this._serverTransport);
34
+ this._connected = true;
35
+ }
36
+ async send(message, options) {
37
+ if (!this._connected)
38
+ throw new Error("Transport not connected");
39
+ this._serverTransport._receiveFromClient(message);
40
+ }
41
+ async close() {
42
+ if (this._connected) {
43
+ this._connected = false;
44
+ this.onclose?.();
45
+ this._serverTransport.onclose?.();
46
+ }
47
+ }
48
+ _receiveFromServer(message, extra) {
49
+ this.onmessage?.(message, extra);
50
+ }
51
+ }
52
+ class InProcessServerTransport {
53
+ constructor(clientTransport) {
54
+ this._clientTransport = clientTransport;
55
+ }
56
+ async start() {
57
+ }
58
+ async send(message, options) {
59
+ this._clientTransport._receiveFromServer(message);
60
+ }
61
+ async close() {
62
+ this.onclose?.();
63
+ }
64
+ _receiveFromClient(message) {
65
+ this.onmessage?.(message);
66
+ }
67
+ }
68
+ // Annotate the CommonJS export names for ESM import in node:
69
+ 0 && (module.exports = {
70
+ InProcessTransport
71
+ });
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var server_exports = {};
30
+ __export(server_exports, {
31
+ connect: () => connect,
32
+ createServer: () => createServer,
33
+ firstRootPath: () => firstRootPath,
34
+ start: () => start,
35
+ wrapInClient: () => wrapInClient,
36
+ wrapInProcess: () => wrapInProcess
37
+ });
38
+ module.exports = __toCommonJS(server_exports);
39
+ var import_url = require("url");
40
+ var import_utilsBundle = require("playwright-core/lib/utilsBundle");
41
+ var mcpBundle = __toESM(require("playwright-core/lib/mcpBundle"));
42
+ var import_http = require("./http");
43
+ var import_inProcessTransport = require("./inProcessTransport");
44
+ const serverDebug = (0, import_utilsBundle.debug)("pw:mcp:server");
45
+ const serverDebugResponse = (0, import_utilsBundle.debug)("pw:mcp:server:response");
46
+ async function connect(factory, transport, runHeartbeat) {
47
+ const server = createServer(factory.name, factory.version, factory.create(), runHeartbeat);
48
+ await server.connect(transport);
49
+ }
50
+ function wrapInProcess(backend) {
51
+ const server = createServer("Internal", "0.0.0", backend, false);
52
+ return new import_inProcessTransport.InProcessTransport(server);
53
+ }
54
+ async function wrapInClient(backend, options) {
55
+ const server = createServer("Internal", "0.0.0", backend, false);
56
+ const transport = new import_inProcessTransport.InProcessTransport(server);
57
+ const client = new mcpBundle.Client({ name: options.name, version: options.version });
58
+ await client.connect(transport);
59
+ await client.ping();
60
+ return client;
61
+ }
62
+ function createServer(name, version, backend, runHeartbeat) {
63
+ const server = new mcpBundle.Server({ name, version }, {
64
+ capabilities: {
65
+ tools: {}
66
+ }
67
+ });
68
+ server.setRequestHandler(mcpBundle.ListToolsRequestSchema, async () => {
69
+ serverDebug("listTools");
70
+ const tools = await backend.listTools();
71
+ return { tools };
72
+ });
73
+ let initializePromise;
74
+ server.setRequestHandler(mcpBundle.CallToolRequestSchema, async (request, extra) => {
75
+ serverDebug("callTool", request);
76
+ const progressToken = request.params._meta?.progressToken;
77
+ let progressCounter = 0;
78
+ const progress = progressToken ? (params) => {
79
+ extra.sendNotification({
80
+ method: "notifications/progress",
81
+ params: {
82
+ progressToken,
83
+ progress: params.progress ?? ++progressCounter,
84
+ total: params.total,
85
+ message: params.message
86
+ }
87
+ }).catch(serverDebug);
88
+ } : () => {
89
+ };
90
+ try {
91
+ if (!initializePromise)
92
+ initializePromise = initializeServer(server, backend, runHeartbeat);
93
+ await initializePromise;
94
+ const toolResult = await backend.callTool(request.params.name, request.params.arguments || {}, progress);
95
+ const mergedResult = mergeTextParts(toolResult);
96
+ serverDebugResponse("callResult", mergedResult);
97
+ return mergedResult;
98
+ } catch (error) {
99
+ return {
100
+ content: [{ type: "text", text: "### Result\n" + String(error) }],
101
+ isError: true
102
+ };
103
+ }
104
+ });
105
+ addServerListener(server, "close", () => backend.serverClosed?.(server));
106
+ return server;
107
+ }
108
+ const initializeServer = async (server, backend, runHeartbeat) => {
109
+ const capabilities = server.getClientCapabilities();
110
+ let clientRoots = [];
111
+ if (capabilities?.roots) {
112
+ const { roots } = await server.listRoots().catch((e) => {
113
+ serverDebug(e);
114
+ return { roots: [] };
115
+ });
116
+ clientRoots = roots;
117
+ }
118
+ const clientInfo = {
119
+ name: server.getClientVersion()?.name ?? "unknown",
120
+ version: server.getClientVersion()?.version ?? "unknown",
121
+ roots: clientRoots,
122
+ timestamp: Date.now()
123
+ };
124
+ await backend.initialize?.(clientInfo);
125
+ if (runHeartbeat)
126
+ startHeartbeat(server);
127
+ };
128
+ const startHeartbeat = (server) => {
129
+ const beat = () => {
130
+ Promise.race([
131
+ server.ping(),
132
+ new Promise((_, reject) => setTimeout(() => reject(new Error("ping timeout")), 5e3))
133
+ ]).then(() => {
134
+ setTimeout(beat, 3e3);
135
+ }).catch(() => {
136
+ void server.close();
137
+ });
138
+ };
139
+ beat();
140
+ };
141
+ function addServerListener(server, event, listener) {
142
+ const oldListener = server[`on${event}`];
143
+ server[`on${event}`] = () => {
144
+ oldListener?.();
145
+ listener();
146
+ };
147
+ }
148
+ async function start(serverBackendFactory, options) {
149
+ if (options.port === void 0) {
150
+ await connect(serverBackendFactory, new mcpBundle.StdioServerTransport(), false);
151
+ return;
152
+ }
153
+ const url = await (0, import_http.startMcpHttpServer)(options, serverBackendFactory, options.allowedHosts);
154
+ const mcpConfig = { mcpServers: {} };
155
+ mcpConfig.mcpServers[serverBackendFactory.nameInConfig] = {
156
+ url: `${url}/mcp`
157
+ };
158
+ const message = [
159
+ `Listening on ${url}`,
160
+ "Put this in your client config:",
161
+ JSON.stringify(mcpConfig, void 0, 2),
162
+ "For legacy SSE transport support, you can use the /sse endpoint instead."
163
+ ].join("\n");
164
+ console.error(message);
165
+ }
166
+ function firstRootPath(clientInfo) {
167
+ if (clientInfo.roots.length === 0)
168
+ return void 0;
169
+ const firstRootUri = clientInfo.roots[0]?.uri;
170
+ const url = firstRootUri ? new URL(firstRootUri) : void 0;
171
+ try {
172
+ return url ? (0, import_url.fileURLToPath)(url) : void 0;
173
+ } catch (error) {
174
+ serverDebug(error);
175
+ return void 0;
176
+ }
177
+ }
178
+ function mergeTextParts(result) {
179
+ const content = [];
180
+ const testParts = [];
181
+ for (const part of result.content) {
182
+ if (part.type === "text") {
183
+ testParts.push(part.text);
184
+ continue;
185
+ }
186
+ if (testParts.length > 0) {
187
+ content.push({ type: "text", text: testParts.join("\n") });
188
+ testParts.length = 0;
189
+ }
190
+ content.push(part);
191
+ }
192
+ if (testParts.length > 0)
193
+ content.push({ type: "text", text: testParts.join("\n") });
194
+ return {
195
+ ...result,
196
+ content
197
+ };
198
+ }
199
+ // Annotate the CommonJS export names for ESM import in node:
200
+ 0 && (module.exports = {
201
+ connect,
202
+ createServer,
203
+ firstRootPath,
204
+ start,
205
+ wrapInClient,
206
+ wrapInProcess
207
+ });
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var tool_exports = {};
20
+ __export(tool_exports, {
21
+ defineToolSchema: () => defineToolSchema,
22
+ toMcpTool: () => toMcpTool
23
+ });
24
+ module.exports = __toCommonJS(tool_exports);
25
+ var import_mcpBundle = require("playwright-core/lib/mcpBundle");
26
+ function toMcpTool(tool) {
27
+ const readOnly = tool.type === "readOnly" || tool.type === "assertion";
28
+ return {
29
+ name: tool.name,
30
+ description: tool.description,
31
+ inputSchema: (0, import_mcpBundle.zodToJsonSchema)(tool.inputSchema, { strictUnions: true }),
32
+ annotations: {
33
+ title: tool.title,
34
+ readOnlyHint: readOnly,
35
+ destructiveHint: !readOnly,
36
+ openWorldHint: true
37
+ }
38
+ };
39
+ }
40
+ function defineToolSchema(tool) {
41
+ return tool;
42
+ }
43
+ // Annotate the CommonJS export names for ESM import in node:
44
+ 0 && (module.exports = {
45
+ defineToolSchema,
46
+ toMcpTool
47
+ });