phantomwright-driver 1.57.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.
Files changed (174) hide show
  1. package/README.md +240 -0
  2. package/ThirdPartyNotices.txt +6197 -0
  3. package/cli.js +19 -0
  4. package/index.d.ts +17 -0
  5. package/index.js +17 -0
  6. package/index.mjs +18 -0
  7. package/jsx-runtime.js +42 -0
  8. package/jsx-runtime.mjs +21 -0
  9. package/lib/agents/copilot-setup-steps.yml +34 -0
  10. package/lib/agents/generateAgents.js +395 -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 +72 -0
  18. package/lib/common/config.js +280 -0
  19. package/lib/common/configLoader.js +344 -0
  20. package/lib/common/esmLoaderHost.js +102 -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 +104 -0
  28. package/lib/common/suiteUtils.js +140 -0
  29. package/lib/common/test.js +321 -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 +682 -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 +508 -0
  40. package/lib/isomorphic/teleSuiteUpdater.js +137 -0
  41. package/lib/isomorphic/testServerConnection.js +225 -0
  42. package/lib/isomorphic/testServerInterface.js +16 -0
  43. package/lib/isomorphic/testTree.js +334 -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 +296 -0
  57. package/lib/mcp/browser/browserServerBackend.js +76 -0
  58. package/lib/mcp/browser/codegen.js +66 -0
  59. package/lib/mcp/browser/config.js +368 -0
  60. package/lib/mcp/browser/context.js +267 -0
  61. package/lib/mcp/browser/response.js +237 -0
  62. package/lib/mcp/browser/sessionLog.js +160 -0
  63. package/lib/mcp/browser/tab.js +292 -0
  64. package/lib/mcp/browser/tools/common.js +63 -0
  65. package/lib/mcp/browser/tools/console.js +44 -0
  66. package/lib/mcp/browser/tools/dialogs.js +60 -0
  67. package/lib/mcp/browser/tools/evaluate.js +69 -0
  68. package/lib/mcp/browser/tools/files.js +58 -0
  69. package/lib/mcp/browser/tools/form.js +73 -0
  70. package/lib/mcp/browser/tools/install.js +69 -0
  71. package/lib/mcp/browser/tools/keyboard.js +84 -0
  72. package/lib/mcp/browser/tools/mouse.js +107 -0
  73. package/lib/mcp/browser/tools/navigate.js +62 -0
  74. package/lib/mcp/browser/tools/network.js +54 -0
  75. package/lib/mcp/browser/tools/pdf.js +59 -0
  76. package/lib/mcp/browser/tools/runCode.js +75 -0
  77. package/lib/mcp/browser/tools/screenshot.js +106 -0
  78. package/lib/mcp/browser/tools/snapshot.js +181 -0
  79. package/lib/mcp/browser/tools/tabs.js +67 -0
  80. package/lib/mcp/browser/tools/tool.js +49 -0
  81. package/lib/mcp/browser/tools/tracing.js +74 -0
  82. package/lib/mcp/browser/tools/utils.js +89 -0
  83. package/lib/mcp/browser/tools/verify.js +153 -0
  84. package/lib/mcp/browser/tools/wait.js +63 -0
  85. package/lib/mcp/browser/tools.js +82 -0
  86. package/lib/mcp/browser/watchdog.js +44 -0
  87. package/lib/mcp/config.d.js +16 -0
  88. package/lib/mcp/extension/cdpRelay.js +351 -0
  89. package/lib/mcp/extension/extensionContextFactory.js +75 -0
  90. package/lib/mcp/extension/protocol.js +28 -0
  91. package/lib/mcp/index.js +61 -0
  92. package/lib/mcp/log.js +35 -0
  93. package/lib/mcp/program.js +116 -0
  94. package/lib/mcp/sdk/bundle.js +81 -0
  95. package/lib/mcp/sdk/exports.js +30 -0
  96. package/lib/mcp/sdk/http.js +187 -0
  97. package/lib/mcp/sdk/inProcessTransport.js +71 -0
  98. package/lib/mcp/sdk/proxyBackend.js +128 -0
  99. package/lib/mcp/sdk/server.js +198 -0
  100. package/lib/mcp/sdk/tool.js +47 -0
  101. package/lib/mcp/test/browserBackend.js +108 -0
  102. package/lib/mcp/test/generatorTools.js +122 -0
  103. package/lib/mcp/test/plannerTools.js +144 -0
  104. package/lib/mcp/test/seed.js +82 -0
  105. package/lib/mcp/test/streams.js +44 -0
  106. package/lib/mcp/test/testBackend.js +99 -0
  107. package/lib/mcp/test/testContext.js +279 -0
  108. package/lib/mcp/test/testTool.js +30 -0
  109. package/lib/mcp/test/testTools.js +106 -0
  110. package/lib/mcpBundleImpl.js +41 -0
  111. package/lib/plugins/gitCommitInfoPlugin.js +198 -0
  112. package/lib/plugins/index.js +28 -0
  113. package/lib/plugins/webServerPlugin.js +237 -0
  114. package/lib/program.js +403 -0
  115. package/lib/reporters/base.js +609 -0
  116. package/lib/reporters/blob.js +135 -0
  117. package/lib/reporters/dot.js +82 -0
  118. package/lib/reporters/empty.js +32 -0
  119. package/lib/reporters/github.js +128 -0
  120. package/lib/reporters/html.js +623 -0
  121. package/lib/reporters/internalReporter.js +132 -0
  122. package/lib/reporters/json.js +254 -0
  123. package/lib/reporters/junit.js +232 -0
  124. package/lib/reporters/line.js +113 -0
  125. package/lib/reporters/list.js +231 -0
  126. package/lib/reporters/listModeReporter.js +69 -0
  127. package/lib/reporters/markdown.js +144 -0
  128. package/lib/reporters/merge.js +541 -0
  129. package/lib/reporters/multiplexer.js +104 -0
  130. package/lib/reporters/reporterV2.js +102 -0
  131. package/lib/reporters/teleEmitter.js +299 -0
  132. package/lib/reporters/versions/blobV1.js +16 -0
  133. package/lib/runner/dispatcher.js +515 -0
  134. package/lib/runner/failureTracker.js +72 -0
  135. package/lib/runner/lastRun.js +77 -0
  136. package/lib/runner/loadUtils.js +334 -0
  137. package/lib/runner/loaderHost.js +89 -0
  138. package/lib/runner/processHost.js +161 -0
  139. package/lib/runner/projectUtils.js +241 -0
  140. package/lib/runner/rebase.js +189 -0
  141. package/lib/runner/reporters.js +138 -0
  142. package/lib/runner/sigIntWatcher.js +96 -0
  143. package/lib/runner/taskRunner.js +127 -0
  144. package/lib/runner/tasks.js +410 -0
  145. package/lib/runner/testGroups.js +117 -0
  146. package/lib/runner/testRunner.js +389 -0
  147. package/lib/runner/testServer.js +269 -0
  148. package/lib/runner/uiModeReporter.js +30 -0
  149. package/lib/runner/vcs.js +72 -0
  150. package/lib/runner/watchMode.js +395 -0
  151. package/lib/runner/workerHost.js +98 -0
  152. package/lib/third_party/pirates.js +62 -0
  153. package/lib/third_party/tsconfig-loader.js +103 -0
  154. package/lib/transform/babelBundle.js +43 -0
  155. package/lib/transform/babelBundleImpl.js +461 -0
  156. package/lib/transform/compilationCache.js +272 -0
  157. package/lib/transform/esmLoader.js +104 -0
  158. package/lib/transform/portTransport.js +67 -0
  159. package/lib/transform/transform.js +293 -0
  160. package/lib/util.js +403 -0
  161. package/lib/utilsBundle.js +43 -0
  162. package/lib/utilsBundleImpl.js +100 -0
  163. package/lib/worker/fixtureRunner.js +258 -0
  164. package/lib/worker/testInfo.js +516 -0
  165. package/lib/worker/testTracing.js +345 -0
  166. package/lib/worker/timeoutManager.js +174 -0
  167. package/lib/worker/util.js +31 -0
  168. package/lib/worker/workerMain.js +529 -0
  169. package/package.json +72 -0
  170. package/test.d.ts +18 -0
  171. package/test.js +24 -0
  172. package/test.mjs +33 -0
  173. package/types/test.d.ts +10253 -0
  174. package/types/testReporter.d.ts +821 -0
@@ -0,0 +1,81 @@
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 bundle_exports = {};
30
+ __export(bundle_exports, {
31
+ CallToolRequestSchema: () => CallToolRequestSchema,
32
+ Client: () => Client,
33
+ ListRootsRequestSchema: () => ListRootsRequestSchema,
34
+ ListToolsRequestSchema: () => ListToolsRequestSchema,
35
+ PingRequestSchema: () => PingRequestSchema,
36
+ ProgressNotificationSchema: () => ProgressNotificationSchema,
37
+ SSEClientTransport: () => SSEClientTransport,
38
+ SSEServerTransport: () => SSEServerTransport,
39
+ Server: () => Server,
40
+ StdioClientTransport: () => StdioClientTransport,
41
+ StdioServerTransport: () => StdioServerTransport,
42
+ StreamableHTTPClientTransport: () => StreamableHTTPClientTransport,
43
+ StreamableHTTPServerTransport: () => StreamableHTTPServerTransport,
44
+ z: () => z,
45
+ zodToJsonSchema: () => zodToJsonSchema
46
+ });
47
+ module.exports = __toCommonJS(bundle_exports);
48
+ var bundle = __toESM(require("../../mcpBundleImpl"));
49
+ const zodToJsonSchema = bundle.zodToJsonSchema;
50
+ const Client = bundle.Client;
51
+ const Server = bundle.Server;
52
+ const SSEClientTransport = bundle.SSEClientTransport;
53
+ const SSEServerTransport = bundle.SSEServerTransport;
54
+ const StdioClientTransport = bundle.StdioClientTransport;
55
+ const StdioServerTransport = bundle.StdioServerTransport;
56
+ const StreamableHTTPServerTransport = bundle.StreamableHTTPServerTransport;
57
+ const StreamableHTTPClientTransport = bundle.StreamableHTTPClientTransport;
58
+ const CallToolRequestSchema = bundle.CallToolRequestSchema;
59
+ const ListRootsRequestSchema = bundle.ListRootsRequestSchema;
60
+ const ProgressNotificationSchema = bundle.ProgressNotificationSchema;
61
+ const ListToolsRequestSchema = bundle.ListToolsRequestSchema;
62
+ const PingRequestSchema = bundle.PingRequestSchema;
63
+ const z = bundle.z;
64
+ // Annotate the CommonJS export names for ESM import in node:
65
+ 0 && (module.exports = {
66
+ CallToolRequestSchema,
67
+ Client,
68
+ ListRootsRequestSchema,
69
+ ListToolsRequestSchema,
70
+ PingRequestSchema,
71
+ ProgressNotificationSchema,
72
+ SSEClientTransport,
73
+ SSEServerTransport,
74
+ Server,
75
+ StdioClientTransport,
76
+ StdioServerTransport,
77
+ StreamableHTTPClientTransport,
78
+ StreamableHTTPServerTransport,
79
+ z,
80
+ zodToJsonSchema
81
+ });
@@ -0,0 +1,30 @@
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("./proxyBackend"), module.exports);
20
+ __reExport(exports_exports, require("./server"), module.exports);
21
+ __reExport(exports_exports, require("./tool"), module.exports);
22
+ __reExport(exports_exports, require("./http"), module.exports);
23
+ // Annotate the CommonJS export names for ESM import in node:
24
+ 0 && (module.exports = {
25
+ ...require("./inProcessTransport"),
26
+ ...require("./proxyBackend"),
27
+ ...require("./server"),
28
+ ...require("./tool"),
29
+ ...require("./http")
30
+ });
@@ -0,0 +1,187 @@
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
+ httpAddressToString: () => httpAddressToString,
32
+ installHttpTransport: () => installHttpTransport,
33
+ startHttpServer: () => startHttpServer
34
+ });
35
+ module.exports = __toCommonJS(http_exports);
36
+ var import_assert = __toESM(require("assert"));
37
+ var import_http = __toESM(require("http"));
38
+ var import_crypto = __toESM(require("crypto"));
39
+ var import_utilsBundle = require("phantomwright-driver-core/lib/utilsBundle");
40
+ var mcpBundle = __toESM(require("./bundle"));
41
+ var mcpServer = __toESM(require("./server"));
42
+ const testDebug = (0, import_utilsBundle.debug)("pw:mcp:test");
43
+ async function startHttpServer(config, abortSignal) {
44
+ const { host, port } = config;
45
+ const httpServer = import_http.default.createServer();
46
+ decorateServer(httpServer);
47
+ await new Promise((resolve, reject) => {
48
+ httpServer.on("error", reject);
49
+ abortSignal?.addEventListener("abort", () => {
50
+ httpServer.close();
51
+ reject(new Error("Aborted"));
52
+ });
53
+ httpServer.listen(port, host, () => {
54
+ resolve();
55
+ httpServer.removeListener("error", reject);
56
+ });
57
+ });
58
+ return httpServer;
59
+ }
60
+ function httpAddressToString(address) {
61
+ (0, import_assert.default)(address, "Could not bind server socket");
62
+ if (typeof address === "string")
63
+ return address;
64
+ const resolvedPort = address.port;
65
+ let resolvedHost = address.family === "IPv4" ? address.address : `[${address.address}]`;
66
+ if (resolvedHost === "0.0.0.0" || resolvedHost === "[::]")
67
+ resolvedHost = "localhost";
68
+ return `http://${resolvedHost}:${resolvedPort}`;
69
+ }
70
+ async function installHttpTransport(httpServer, serverBackendFactory, unguessableUrl, allowedHosts) {
71
+ const url = httpAddressToString(httpServer.address());
72
+ const host = new URL(url).host;
73
+ allowedHosts = (allowedHosts || [host]).map((h) => h.toLowerCase());
74
+ const allowAnyHost = allowedHosts.includes("*");
75
+ const pathPrefix = unguessableUrl ? `/${import_crypto.default.randomUUID()}` : "";
76
+ const sseSessions = /* @__PURE__ */ new Map();
77
+ const streamableSessions = /* @__PURE__ */ new Map();
78
+ httpServer.on("request", async (req, res) => {
79
+ if (!allowAnyHost) {
80
+ const host2 = req.headers.host?.toLowerCase();
81
+ if (!host2) {
82
+ res.statusCode = 400;
83
+ return res.end("Missing host");
84
+ }
85
+ if (!allowedHosts.includes(host2)) {
86
+ res.statusCode = 403;
87
+ return res.end("Access is only allowed at " + allowedHosts.join(", "));
88
+ }
89
+ }
90
+ if (!req.url?.startsWith(pathPrefix)) {
91
+ res.statusCode = 404;
92
+ return res.end("Not found");
93
+ }
94
+ const path = req.url?.slice(pathPrefix.length);
95
+ const url2 = new URL(`http://localhost${path}`);
96
+ if (url2.pathname === "/killkillkill" && req.method === "GET") {
97
+ res.statusCode = 200;
98
+ res.end("Killing process");
99
+ process.emit("SIGINT");
100
+ return;
101
+ }
102
+ if (url2.pathname.startsWith("/sse"))
103
+ await handleSSE(serverBackendFactory, req, res, url2, sseSessions);
104
+ else
105
+ await handleStreamable(serverBackendFactory, req, res, streamableSessions);
106
+ });
107
+ return `${url}${pathPrefix}`;
108
+ }
109
+ async function handleSSE(serverBackendFactory, req, res, url, sessions) {
110
+ if (req.method === "POST") {
111
+ const sessionId = url.searchParams.get("sessionId");
112
+ if (!sessionId) {
113
+ res.statusCode = 400;
114
+ return res.end("Missing sessionId");
115
+ }
116
+ const transport = sessions.get(sessionId);
117
+ if (!transport) {
118
+ res.statusCode = 404;
119
+ return res.end("Session not found");
120
+ }
121
+ return await transport.handlePostMessage(req, res);
122
+ } else if (req.method === "GET") {
123
+ const transport = new mcpBundle.SSEServerTransport("/sse", res);
124
+ sessions.set(transport.sessionId, transport);
125
+ testDebug(`create SSE session: ${transport.sessionId}`);
126
+ await mcpServer.connect(serverBackendFactory, transport, false);
127
+ res.on("close", () => {
128
+ testDebug(`delete SSE session: ${transport.sessionId}`);
129
+ sessions.delete(transport.sessionId);
130
+ });
131
+ return;
132
+ }
133
+ res.statusCode = 405;
134
+ res.end("Method not allowed");
135
+ }
136
+ async function handleStreamable(serverBackendFactory, req, res, sessions) {
137
+ const sessionId = req.headers["mcp-session-id"];
138
+ if (sessionId) {
139
+ const transport = sessions.get(sessionId);
140
+ if (!transport) {
141
+ res.statusCode = 404;
142
+ res.end("Session not found");
143
+ return;
144
+ }
145
+ return await transport.handleRequest(req, res);
146
+ }
147
+ if (req.method === "POST") {
148
+ const transport = new mcpBundle.StreamableHTTPServerTransport({
149
+ sessionIdGenerator: () => import_crypto.default.randomUUID(),
150
+ onsessioninitialized: async (sessionId2) => {
151
+ testDebug(`create http session: ${transport.sessionId}`);
152
+ await mcpServer.connect(serverBackendFactory, transport, true);
153
+ sessions.set(sessionId2, transport);
154
+ }
155
+ });
156
+ transport.onclose = () => {
157
+ if (!transport.sessionId)
158
+ return;
159
+ sessions.delete(transport.sessionId);
160
+ testDebug(`delete http session: ${transport.sessionId}`);
161
+ };
162
+ await transport.handleRequest(req, res);
163
+ return;
164
+ }
165
+ res.statusCode = 400;
166
+ res.end("Invalid request");
167
+ }
168
+ function decorateServer(server) {
169
+ const sockets = /* @__PURE__ */ new Set();
170
+ server.on("connection", (socket) => {
171
+ sockets.add(socket);
172
+ socket.once("close", () => sockets.delete(socket));
173
+ });
174
+ const close = server.close;
175
+ server.close = (callback) => {
176
+ for (const socket of sockets)
177
+ socket.destroy();
178
+ sockets.clear();
179
+ return close.call(server, callback);
180
+ };
181
+ }
182
+ // Annotate the CommonJS export names for ESM import in node:
183
+ 0 && (module.exports = {
184
+ httpAddressToString,
185
+ installHttpTransport,
186
+ startHttpServer
187
+ });
@@ -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,128 @@
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 proxyBackend_exports = {};
30
+ __export(proxyBackend_exports, {
31
+ ProxyBackend: () => ProxyBackend
32
+ });
33
+ module.exports = __toCommonJS(proxyBackend_exports);
34
+ var import_utilsBundle = require("phantomwright-driver-core/lib/utilsBundle");
35
+ var mcpBundle = __toESM(require("./bundle"));
36
+ const errorsDebug = (0, import_utilsBundle.debug)("pw:mcp:errors");
37
+ const { z, zodToJsonSchema } = mcpBundle;
38
+ class ProxyBackend {
39
+ constructor(mcpProviders) {
40
+ this._mcpProviders = mcpProviders;
41
+ this._contextSwitchTool = this._defineContextSwitchTool();
42
+ }
43
+ async initialize(clientInfo) {
44
+ this._clientInfo = clientInfo;
45
+ }
46
+ async listTools() {
47
+ const currentClient = await this._ensureCurrentClient();
48
+ const response = await currentClient.listTools();
49
+ if (this._mcpProviders.length === 1)
50
+ return response.tools;
51
+ return [
52
+ ...response.tools,
53
+ this._contextSwitchTool
54
+ ];
55
+ }
56
+ async callTool(name, args) {
57
+ if (name === this._contextSwitchTool.name)
58
+ return this._callContextSwitchTool(args);
59
+ const currentClient = await this._ensureCurrentClient();
60
+ return await currentClient.callTool({
61
+ name,
62
+ arguments: args
63
+ });
64
+ }
65
+ serverClosed() {
66
+ void this._currentClient?.close().catch(errorsDebug);
67
+ }
68
+ async _callContextSwitchTool(params) {
69
+ try {
70
+ const factory = this._mcpProviders.find((factory2) => factory2.name === params.name);
71
+ if (!factory)
72
+ throw new Error("Unknown connection method: " + params.name);
73
+ await this._setCurrentClient(factory);
74
+ return {
75
+ content: [{ type: "text", text: "### Result\nSuccessfully changed connection method.\n" }]
76
+ };
77
+ } catch (error) {
78
+ return {
79
+ content: [{ type: "text", text: `### Result
80
+ Error: ${error}
81
+ ` }],
82
+ isError: true
83
+ };
84
+ }
85
+ }
86
+ _defineContextSwitchTool() {
87
+ return {
88
+ name: "browser_connect",
89
+ description: [
90
+ "Connect to a browser using one of the available methods:",
91
+ ...this._mcpProviders.map((factory) => `- "${factory.name}": ${factory.description}`)
92
+ ].join("\n"),
93
+ inputSchema: zodToJsonSchema(z.object({
94
+ name: z.enum(this._mcpProviders.map((factory) => factory.name)).default(this._mcpProviders[0].name).describe("The method to use to connect to the browser")
95
+ }), { strictUnions: true }),
96
+ annotations: {
97
+ title: "Connect to a browser context",
98
+ readOnlyHint: true,
99
+ openWorldHint: false
100
+ }
101
+ };
102
+ }
103
+ async _ensureCurrentClient() {
104
+ if (this._currentClient)
105
+ return this._currentClient;
106
+ return await this._setCurrentClient(this._mcpProviders[0]);
107
+ }
108
+ async _setCurrentClient(factory) {
109
+ await this._currentClient?.close();
110
+ this._currentClient = void 0;
111
+ const client = new mcpBundle.Client({ name: "Playwright MCP Proxy", version: "0.0.0" });
112
+ client.registerCapabilities({
113
+ roots: {
114
+ listRoots: true
115
+ }
116
+ });
117
+ client.setRequestHandler(mcpBundle.ListRootsRequestSchema, () => ({ roots: this._clientInfo?.roots || [] }));
118
+ client.setRequestHandler(mcpBundle.PingRequestSchema, () => ({}));
119
+ const transport = await factory.connect();
120
+ await client.connect(transport);
121
+ this._currentClient = client;
122
+ return client;
123
+ }
124
+ }
125
+ // Annotate the CommonJS export names for ESM import in node:
126
+ 0 && (module.exports = {
127
+ ProxyBackend
128
+ });
@@ -0,0 +1,198 @@
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
+ wrapInProcess: () => wrapInProcess
36
+ });
37
+ module.exports = __toCommonJS(server_exports);
38
+ var import_url = require("url");
39
+ var import_utilsBundle = require("phantomwright-driver-core/lib/utilsBundle");
40
+ var mcpBundle = __toESM(require("./bundle"));
41
+ var import_http = require("./http");
42
+ var import_inProcessTransport = require("./inProcessTransport");
43
+ const serverDebug = (0, import_utilsBundle.debug)("pw:mcp:server");
44
+ const serverDebugResponse = (0, import_utilsBundle.debug)("pw:mcp:server:response");
45
+ async function connect(factory, transport, runHeartbeat) {
46
+ const server = createServer(factory.name, factory.version, factory.create(), runHeartbeat);
47
+ await server.connect(transport);
48
+ }
49
+ async function wrapInProcess(backend) {
50
+ const server = createServer("Internal", "0.0.0", backend, false);
51
+ return new import_inProcessTransport.InProcessTransport(server);
52
+ }
53
+ function createServer(name, version, backend, runHeartbeat) {
54
+ const server = new mcpBundle.Server({ name, version }, {
55
+ capabilities: {
56
+ tools: {}
57
+ }
58
+ });
59
+ server.setRequestHandler(mcpBundle.ListToolsRequestSchema, async () => {
60
+ serverDebug("listTools");
61
+ const tools = await backend.listTools();
62
+ return { tools };
63
+ });
64
+ let initializePromise;
65
+ server.setRequestHandler(mcpBundle.CallToolRequestSchema, async (request, extra) => {
66
+ serverDebug("callTool", request);
67
+ const progressToken = request.params._meta?.progressToken;
68
+ let progressCounter = 0;
69
+ const progress = progressToken ? (params) => {
70
+ extra.sendNotification({
71
+ method: "notifications/progress",
72
+ params: {
73
+ progressToken,
74
+ progress: params.progress ?? ++progressCounter,
75
+ total: params.total,
76
+ message: params.message
77
+ }
78
+ }).catch(serverDebug);
79
+ } : () => {
80
+ };
81
+ try {
82
+ if (!initializePromise)
83
+ initializePromise = initializeServer(server, backend, runHeartbeat);
84
+ await initializePromise;
85
+ const toolResult = await backend.callTool(request.params.name, request.params.arguments || {}, progress);
86
+ const mergedResult = mergeTextParts(toolResult);
87
+ serverDebugResponse("callResult", mergedResult);
88
+ return mergedResult;
89
+ } catch (error) {
90
+ return {
91
+ content: [{ type: "text", text: "### Result\n" + String(error) }],
92
+ isError: true
93
+ };
94
+ }
95
+ });
96
+ addServerListener(server, "close", () => backend.serverClosed?.(server));
97
+ return server;
98
+ }
99
+ const initializeServer = async (server, backend, runHeartbeat) => {
100
+ const capabilities = server.getClientCapabilities();
101
+ let clientRoots = [];
102
+ if (capabilities?.roots) {
103
+ const { roots } = await server.listRoots().catch((e) => {
104
+ serverDebug(e);
105
+ return { roots: [] };
106
+ });
107
+ clientRoots = roots;
108
+ }
109
+ const clientInfo = {
110
+ name: server.getClientVersion()?.name ?? "unknown",
111
+ version: server.getClientVersion()?.version ?? "unknown",
112
+ roots: clientRoots,
113
+ timestamp: Date.now()
114
+ };
115
+ await backend.initialize?.(clientInfo);
116
+ if (runHeartbeat)
117
+ startHeartbeat(server);
118
+ };
119
+ const startHeartbeat = (server) => {
120
+ const beat = () => {
121
+ Promise.race([
122
+ server.ping(),
123
+ new Promise((_, reject) => setTimeout(() => reject(new Error("ping timeout")), 5e3))
124
+ ]).then(() => {
125
+ setTimeout(beat, 3e3);
126
+ }).catch(() => {
127
+ void server.close();
128
+ });
129
+ };
130
+ beat();
131
+ };
132
+ function addServerListener(server, event, listener) {
133
+ const oldListener = server[`on${event}`];
134
+ server[`on${event}`] = () => {
135
+ oldListener?.();
136
+ listener();
137
+ };
138
+ }
139
+ async function start(serverBackendFactory, options) {
140
+ if (options.port === void 0) {
141
+ await connect(serverBackendFactory, new mcpBundle.StdioServerTransport(), false);
142
+ return;
143
+ }
144
+ const httpServer = await (0, import_http.startHttpServer)(options);
145
+ const url = await (0, import_http.installHttpTransport)(httpServer, serverBackendFactory, false, options.allowedHosts);
146
+ const mcpConfig = { mcpServers: {} };
147
+ mcpConfig.mcpServers[serverBackendFactory.nameInConfig] = {
148
+ url: `${url}/mcp`
149
+ };
150
+ const message = [
151
+ `Listening on ${url}`,
152
+ "Put this in your client config:",
153
+ JSON.stringify(mcpConfig, void 0, 2),
154
+ "For legacy SSE transport support, you can use the /sse endpoint instead."
155
+ ].join("\n");
156
+ console.error(message);
157
+ }
158
+ function firstRootPath(clientInfo) {
159
+ if (clientInfo.roots.length === 0)
160
+ return void 0;
161
+ const firstRootUri = clientInfo.roots[0]?.uri;
162
+ const url = firstRootUri ? new URL(firstRootUri) : void 0;
163
+ try {
164
+ return url ? (0, import_url.fileURLToPath)(url) : void 0;
165
+ } catch (error) {
166
+ serverDebug(error);
167
+ return void 0;
168
+ }
169
+ }
170
+ function mergeTextParts(result) {
171
+ const content = [];
172
+ const testParts = [];
173
+ for (const part of result.content) {
174
+ if (part.type === "text") {
175
+ testParts.push(part.text);
176
+ continue;
177
+ }
178
+ if (testParts.length > 0) {
179
+ content.push({ type: "text", text: testParts.join("\n") });
180
+ testParts.length = 0;
181
+ }
182
+ content.push(part);
183
+ }
184
+ if (testParts.length > 0)
185
+ content.push({ type: "text", text: testParts.join("\n") });
186
+ return {
187
+ ...result,
188
+ content
189
+ };
190
+ }
191
+ // Annotate the CommonJS export names for ESM import in node:
192
+ 0 && (module.exports = {
193
+ connect,
194
+ createServer,
195
+ firstRootPath,
196
+ start,
197
+ wrapInProcess
198
+ });