@cotestdev/mcp_playwright 0.0.58 → 0.0.59

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.
@@ -0,0 +1,146 @@
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 registry_exports = {};
30
+ __export(registry_exports, {
31
+ Registry: () => Registry,
32
+ baseDaemonDir: () => baseDaemonDir,
33
+ createClientInfo: () => createClientInfo
34
+ });
35
+ module.exports = __toCommonJS(registry_exports);
36
+ var import_crypto = __toESM(require("crypto"));
37
+ var import_fs = __toESM(require("fs"));
38
+ var import_os = __toESM(require("os"));
39
+ var import_path = __toESM(require("path"));
40
+ class Registry {
41
+ constructor(entries) {
42
+ this._entries = entries;
43
+ }
44
+ entry(clientInfo, sessionName) {
45
+ const key = clientInfo.workspaceDir || clientInfo.workspaceDirHash;
46
+ const entries = this._entries.get(key) || [];
47
+ return entries.find((entry) => entry.config.name === sessionName);
48
+ }
49
+ entries(clientInfo) {
50
+ const key = clientInfo.workspaceDir || clientInfo.workspaceDirHash;
51
+ return this._entries.get(key) || [];
52
+ }
53
+ entryMap() {
54
+ return this._entries;
55
+ }
56
+ static async loadSessionEntry(file) {
57
+ try {
58
+ const data = await import_fs.default.promises.readFile(file, "utf-8");
59
+ const config = JSON.parse(data);
60
+ if (!config.name)
61
+ config.name = import_path.default.basename(file, ".session");
62
+ if (!config.timestamp)
63
+ config.timestamp = 0;
64
+ return { file, config };
65
+ } catch {
66
+ return void 0;
67
+ }
68
+ }
69
+ static async load() {
70
+ const sessions = /* @__PURE__ */ new Map();
71
+ const hashDirs = await import_fs.default.promises.readdir(baseDaemonDir).catch(() => []);
72
+ for (const workspaceDirHash of hashDirs) {
73
+ const hashDir = import_path.default.join(baseDaemonDir, workspaceDirHash);
74
+ const stat = await import_fs.default.promises.stat(hashDir);
75
+ if (!stat.isDirectory())
76
+ continue;
77
+ const files = await import_fs.default.promises.readdir(hashDir).catch(() => []);
78
+ for (const file of files) {
79
+ if (!file.endsWith(".session"))
80
+ continue;
81
+ const fileName = import_path.default.join(hashDir, file);
82
+ const entry = await Registry.loadSessionEntry(fileName);
83
+ if (!entry)
84
+ continue;
85
+ const key = entry.config.workspaceDir || workspaceDirHash;
86
+ let list = sessions.get(key);
87
+ if (!list) {
88
+ list = [];
89
+ sessions.set(key, list);
90
+ }
91
+ list.push(entry);
92
+ }
93
+ }
94
+ return new Registry(sessions);
95
+ }
96
+ }
97
+ const baseDaemonDir = (() => {
98
+ if (process.env.PLAYWRIGHT_DAEMON_SESSION_DIR)
99
+ return process.env.PLAYWRIGHT_DAEMON_SESSION_DIR;
100
+ let localCacheDir;
101
+ if (process.platform === "linux")
102
+ localCacheDir = process.env.XDG_CACHE_HOME || import_path.default.join(import_os.default.homedir(), ".cache");
103
+ if (process.platform === "darwin")
104
+ localCacheDir = import_path.default.join(import_os.default.homedir(), "Library", "Caches");
105
+ if (process.platform === "win32")
106
+ localCacheDir = process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local");
107
+ if (!localCacheDir)
108
+ throw new Error("Unsupported platform: " + process.platform);
109
+ return import_path.default.join(localCacheDir, "ms-playwright", "daemon");
110
+ })();
111
+ function createClientInfo() {
112
+ const packageLocation = require.resolve("../../../package.json");
113
+ const packageJSON = require(packageLocation);
114
+ const workspaceDir = findWorkspaceDir(process.cwd());
115
+ const version = process.env.PLAYWRIGHT_CLI_VERSION_FOR_TEST || packageJSON.version;
116
+ const hash = import_crypto.default.createHash("sha1");
117
+ hash.update(workspaceDir || packageLocation);
118
+ const workspaceDirHash = hash.digest("hex").substring(0, 16);
119
+ return {
120
+ version,
121
+ workspaceDir,
122
+ workspaceDirHash,
123
+ daemonProfilesDir: daemonProfilesDir(workspaceDirHash)
124
+ };
125
+ }
126
+ function findWorkspaceDir(startDir) {
127
+ let dir = startDir;
128
+ for (let i = 0; i < 10; i++) {
129
+ if (import_fs.default.existsSync(import_path.default.join(dir, ".playwright")))
130
+ return dir;
131
+ const parentDir = import_path.default.dirname(dir);
132
+ if (parentDir === dir)
133
+ break;
134
+ dir = parentDir;
135
+ }
136
+ return void 0;
137
+ }
138
+ const daemonProfilesDir = (workspaceDirHash) => {
139
+ return import_path.default.join(baseDaemonDir, workspaceDirHash);
140
+ };
141
+ // Annotate the CommonJS export names for ESM import in node:
142
+ 0 && (module.exports = {
143
+ Registry,
144
+ baseDaemonDir,
145
+ createClientInfo
146
+ });
@@ -0,0 +1,309 @@
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 session_exports = {};
30
+ __export(session_exports, {
31
+ Session: () => Session,
32
+ renderResolvedConfig: () => renderResolvedConfig
33
+ });
34
+ module.exports = __toCommonJS(session_exports);
35
+ var import_child_process = require("child_process");
36
+ var import_fs = __toESM(require("fs"));
37
+ var import_net = __toESM(require("net"));
38
+ var import_os = __toESM(require("os"));
39
+ var import_path = __toESM(require("path"));
40
+ var import_socketConnection = require("./socketConnection");
41
+ class Session {
42
+ constructor(clientInfo, options) {
43
+ this._nextMessageId = 1;
44
+ this._callbacks = /* @__PURE__ */ new Map();
45
+ this._clientInfo = clientInfo;
46
+ this.config = options;
47
+ this.name = options.name;
48
+ }
49
+ isCompatible() {
50
+ return this._clientInfo.version === this.config.version;
51
+ }
52
+ checkCompatible() {
53
+ if (!this.isCompatible()) {
54
+ throw new Error(`Client is v${this._clientInfo.version}, session '${this.name}' is v${this.config.version}. Run
55
+
56
+ playwright-cli${this.name !== "default" ? ` -s=${this.name}` : ""} open
57
+
58
+ to restart the browser session.`);
59
+ }
60
+ }
61
+ async open() {
62
+ await this._startDaemonIfNeeded();
63
+ this.disconnect();
64
+ }
65
+ async run(args, cwd) {
66
+ this.checkCompatible();
67
+ const result = await this._send("run", { args, cwd: cwd || process.cwd() });
68
+ this.disconnect();
69
+ return result;
70
+ }
71
+ async stop(quiet = false) {
72
+ if (!await this.canConnect()) {
73
+ if (!quiet)
74
+ console.log(`Browser '${this.name}' is not open.`);
75
+ return;
76
+ }
77
+ await this._stopDaemon();
78
+ if (!quiet)
79
+ console.log(`Browser '${this.name}' closed
80
+ `);
81
+ }
82
+ async _send(method, params = {}) {
83
+ const connection = await this._startDaemonIfNeeded();
84
+ const messageId = this._nextMessageId++;
85
+ const message = {
86
+ id: messageId,
87
+ method,
88
+ params,
89
+ version: this.config.version
90
+ };
91
+ const responsePromise = new Promise((resolve, reject) => {
92
+ this._callbacks.set(messageId, { resolve, reject, method, params });
93
+ });
94
+ const [result] = await Promise.all([responsePromise, connection.send(message)]);
95
+ return result;
96
+ }
97
+ disconnect() {
98
+ if (!this._connection)
99
+ return;
100
+ for (const callback of this._callbacks.values())
101
+ callback.reject(new Error("Session closed"));
102
+ this._callbacks.clear();
103
+ this._connection.close();
104
+ this._connection = void 0;
105
+ }
106
+ async deleteData() {
107
+ await this.stop();
108
+ const dataDirs = await import_fs.default.promises.readdir(this._clientInfo.daemonProfilesDir).catch(() => []);
109
+ const matchingEntries = dataDirs.filter((file) => file === `${this.name}.session` || file.startsWith(`ud-${this.name}-`));
110
+ if (matchingEntries.length === 0) {
111
+ console.log(`No user data found for browser '${this.name}'.`);
112
+ return;
113
+ }
114
+ for (const entry of matchingEntries) {
115
+ const userDataDir = import_path.default.resolve(this._clientInfo.daemonProfilesDir, entry);
116
+ for (let i = 0; i < 5; i++) {
117
+ try {
118
+ await import_fs.default.promises.rm(userDataDir, { recursive: true });
119
+ if (entry.startsWith("ud-"))
120
+ console.log(`Deleted user data for browser '${this.name}'.`);
121
+ break;
122
+ } catch (e) {
123
+ if (e.code === "ENOENT") {
124
+ console.log(`No user data found for browser '${this.name}'.`);
125
+ break;
126
+ }
127
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
128
+ if (i === 4)
129
+ throw e;
130
+ }
131
+ }
132
+ }
133
+ }
134
+ async _connect() {
135
+ return await new Promise((resolve) => {
136
+ const socket = import_net.default.createConnection(this.config.socketPath, () => {
137
+ resolve({ socket });
138
+ });
139
+ socket.on("error", (error) => {
140
+ if (import_os.default.platform() !== "win32")
141
+ void import_fs.default.promises.unlink(this.config.socketPath).catch(() => {
142
+ }).then(() => resolve({ error }));
143
+ else
144
+ resolve({ error });
145
+ });
146
+ });
147
+ }
148
+ async canConnect() {
149
+ const { socket } = await this._connect();
150
+ if (socket) {
151
+ socket.destroy();
152
+ return true;
153
+ }
154
+ return false;
155
+ }
156
+ async _startDaemonIfNeeded() {
157
+ if (this._connection)
158
+ return this._connection;
159
+ let { socket } = await this._connect();
160
+ if (!socket)
161
+ socket = await this._startDaemon();
162
+ this._connection = new import_socketConnection.SocketConnection(socket, this.config.version);
163
+ this._connection.onmessage = (message) => this._onMessage(message);
164
+ this._connection.onclose = () => this.disconnect();
165
+ return this._connection;
166
+ }
167
+ _onMessage(object) {
168
+ if (object.id && this._callbacks.has(object.id)) {
169
+ const callback = this._callbacks.get(object.id);
170
+ this._callbacks.delete(object.id);
171
+ if (object.error)
172
+ callback.reject(new Error(object.error));
173
+ else
174
+ callback.resolve(object.result);
175
+ } else if (object.id) {
176
+ throw new Error(`Unexpected message id: ${object.id}`);
177
+ } else {
178
+ throw new Error(`Unexpected message without id: ${JSON.stringify(object)}`);
179
+ }
180
+ }
181
+ _sessionFile(suffix) {
182
+ return import_path.default.resolve(this._clientInfo.daemonProfilesDir, `${this.name}${suffix}`);
183
+ }
184
+ async _startDaemon() {
185
+ await import_fs.default.promises.mkdir(this._clientInfo.daemonProfilesDir, { recursive: true });
186
+ const cliPath = import_path.default.join(__dirname, "../../../cli.js");
187
+ const sessionConfigFile = this._sessionFile(".session");
188
+ this.config.version = this._clientInfo.version;
189
+ this.config.timestamp = Date.now();
190
+ await import_fs.default.promises.writeFile(sessionConfigFile, JSON.stringify(this.config, null, 2));
191
+ const errLog = this._sessionFile(".err");
192
+ const err = import_fs.default.openSync(errLog, "w");
193
+ const args = [
194
+ cliPath,
195
+ "run-mcp-server",
196
+ `--daemon-session=${sessionConfigFile}`
197
+ ];
198
+ const child = (0, import_child_process.spawn)(process.execPath, args, {
199
+ detached: true,
200
+ stdio: ["ignore", "pipe", err],
201
+ cwd: process.cwd()
202
+ // Will be used as root.
203
+ });
204
+ let signalled = false;
205
+ const sigintHandler = () => {
206
+ signalled = true;
207
+ child.kill("SIGINT");
208
+ };
209
+ const sigtermHandler = () => {
210
+ signalled = true;
211
+ child.kill("SIGTERM");
212
+ };
213
+ process.on("SIGINT", sigintHandler);
214
+ process.on("SIGTERM", sigtermHandler);
215
+ let outLog = "";
216
+ await new Promise((resolve, reject) => {
217
+ child.stdout.on("data", (data) => {
218
+ outLog += data.toString();
219
+ if (!outLog.includes("<EOF>"))
220
+ return;
221
+ const errorMatch = outLog.match(/### Error\n([\s\S]*)<EOF>/);
222
+ const error = errorMatch ? errorMatch[1].trim() : void 0;
223
+ if (error) {
224
+ const errLogContent = import_fs.default.readFileSync(errLog, "utf-8");
225
+ const message = error + (errLogContent ? "\n" + errLogContent : "");
226
+ reject(new Error(message));
227
+ }
228
+ const successMatch = outLog.match(/### Success\nDaemon listening on (.*)\n<EOF>/);
229
+ if (successMatch)
230
+ resolve();
231
+ });
232
+ child.on("close", (code) => {
233
+ if (!signalled)
234
+ reject(new Error(`Daemon process exited with code ${code}`));
235
+ });
236
+ });
237
+ process.off("SIGINT", sigintHandler);
238
+ process.off("SIGTERM", sigtermHandler);
239
+ child.stdout.destroy();
240
+ child.unref();
241
+ const { socket } = await this._connect();
242
+ if (socket) {
243
+ console.log(`### Browser \`${this.name}\` opened with pid ${child.pid}.`);
244
+ const resolvedConfig = await parseResolvedConfig(outLog);
245
+ if (resolvedConfig) {
246
+ this.config.resolvedConfig = resolvedConfig;
247
+ console.log(`- ${this.name}:`);
248
+ console.log(renderResolvedConfig(resolvedConfig).join("\n"));
249
+ }
250
+ console.log(`---`);
251
+ this.config.timestamp = Date.now();
252
+ await import_fs.default.promises.writeFile(sessionConfigFile, JSON.stringify(this.config, null, 2));
253
+ return socket;
254
+ }
255
+ console.error(`Failed to connect to daemon at ${this.config.socketPath}`);
256
+ process.exit(1);
257
+ }
258
+ async _stopDaemon() {
259
+ let error;
260
+ await this._send("stop").catch((e) => {
261
+ error = e;
262
+ });
263
+ if (import_os.default.platform() !== "win32")
264
+ await import_fs.default.promises.unlink(this.config.socketPath).catch(() => {
265
+ });
266
+ this.disconnect();
267
+ if (!this.config.cli.persistent)
268
+ await this.deleteSessionConfig();
269
+ if (error && !error?.message?.includes("Session closed"))
270
+ throw error;
271
+ }
272
+ async deleteSessionConfig() {
273
+ await import_fs.default.promises.rm(this._sessionFile(".session")).catch(() => {
274
+ });
275
+ }
276
+ }
277
+ function renderResolvedConfig(resolvedConfig) {
278
+ const channel = resolvedConfig.browser.launchOptions.channel ?? resolvedConfig.browser.browserName;
279
+ const lines = [];
280
+ if (channel)
281
+ lines.push(` - browser-type: ${channel}`);
282
+ if (resolvedConfig.browser.isolated)
283
+ lines.push(` - user-data-dir: <in-memory>`);
284
+ else
285
+ lines.push(` - user-data-dir: ${resolvedConfig.browser.userDataDir}`);
286
+ lines.push(` - headed: ${!resolvedConfig.browser.launchOptions.headless}`);
287
+ return lines;
288
+ }
289
+ async function parseResolvedConfig(errLog) {
290
+ const marker = "### Config\n```json\n";
291
+ const markerIndex = errLog.indexOf(marker);
292
+ if (markerIndex === -1)
293
+ return null;
294
+ const jsonStart = markerIndex + marker.length;
295
+ const jsonEnd = errLog.indexOf("\n```", jsonStart);
296
+ if (jsonEnd === -1)
297
+ throw null;
298
+ const jsonString = errLog.substring(jsonStart, jsonEnd).trim();
299
+ try {
300
+ return JSON.parse(jsonString);
301
+ } catch {
302
+ return null;
303
+ }
304
+ }
305
+ // Annotate the CommonJS export names for ESM import in node:
306
+ 0 && (module.exports = {
307
+ Session,
308
+ renderResolvedConfig
309
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cotestdev/mcp_playwright",
3
- "version": "0.0.58",
3
+ "version": "0.0.59",
4
4
  "description": "Playwright MCP (Model Context Protocol) tools for browser automation",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
package/lib/index.d.ts DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * Copyright (c) Microsoft Corporation.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- /**
17
- * @cotestdev/mcp_playwright
18
- * Standalone MCP package for Playwright browser automation
19
- * The actual CLI entry point is at lib/mcp/cli.js
20
- */
21
- declare const _default: {};
22
- export default _default;
23
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH;;;;GAIG;;AAEH,wBAAkB"}
package/lib/index.js DELETED
@@ -1,24 +0,0 @@
1
- "use strict";
2
- /**
3
- * Copyright (c) Microsoft Corporation.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- /**
18
- * @cotestdev/mcp_playwright
19
- * Standalone MCP package for Playwright browser automation
20
- * The actual CLI entry point is at lib/mcp/cli.js
21
- */
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.default = {};
24
- //# sourceMappingURL=index.js.map
package/lib/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;AACH;;;;GAIG;;AAEH,kBAAe,EAAE,CAAC"}