feat(auth): implement user authentication system
This commit is contained in:
parent
4847ab793a
commit
25cea4fbe8
12051 changed files with 1462377 additions and 0 deletions
329
backend/node_modules/playwright/lib/mcp/browser/browserContextFactory.js
generated
vendored
Normal file
329
backend/node_modules/playwright/lib/mcp/browser/browserContextFactory.js
generated
vendored
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var browserContextFactory_exports = {};
|
||||
__export(browserContextFactory_exports, {
|
||||
SharedContextFactory: () => SharedContextFactory,
|
||||
contextFactory: () => contextFactory,
|
||||
identityBrowserContextFactory: () => identityBrowserContextFactory
|
||||
});
|
||||
module.exports = __toCommonJS(browserContextFactory_exports);
|
||||
var import_crypto = __toESM(require("crypto"));
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_net = __toESM(require("net"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var playwright = __toESM(require("playwright-core"));
|
||||
var import_registry = require("playwright-core/lib/server/registry/index");
|
||||
var import_server = require("playwright-core/lib/server");
|
||||
var import_log = require("../log");
|
||||
var import_config = require("./config");
|
||||
var import_server2 = require("../sdk/server");
|
||||
function contextFactory(config) {
|
||||
if (config.sharedBrowserContext)
|
||||
return SharedContextFactory.create(config);
|
||||
if (config.browser.remoteEndpoint)
|
||||
return new RemoteContextFactory(config);
|
||||
if (config.browser.cdpEndpoint)
|
||||
return new CdpContextFactory(config);
|
||||
if (config.browser.isolated)
|
||||
return new IsolatedContextFactory(config);
|
||||
return new PersistentContextFactory(config);
|
||||
}
|
||||
function identityBrowserContextFactory(browserContext) {
|
||||
return {
|
||||
createContext: async (clientInfo, abortSignal, options) => {
|
||||
return {
|
||||
browserContext,
|
||||
close: async () => {
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
class BaseContextFactory {
|
||||
constructor(name, config) {
|
||||
this._logName = name;
|
||||
this.config = config;
|
||||
}
|
||||
async _obtainBrowser(clientInfo, options) {
|
||||
if (this._browserPromise)
|
||||
return this._browserPromise;
|
||||
(0, import_log.testDebug)(`obtain browser (${this._logName})`);
|
||||
this._browserPromise = this._doObtainBrowser(clientInfo, options);
|
||||
void this._browserPromise.then((browser) => {
|
||||
browser.on("disconnected", () => {
|
||||
this._browserPromise = void 0;
|
||||
});
|
||||
}).catch(() => {
|
||||
this._browserPromise = void 0;
|
||||
});
|
||||
return this._browserPromise;
|
||||
}
|
||||
async _doObtainBrowser(clientInfo, options) {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
async createContext(clientInfo, _, options) {
|
||||
(0, import_log.testDebug)(`create browser context (${this._logName})`);
|
||||
const browser = await this._obtainBrowser(clientInfo, options);
|
||||
const browserContext = await this._doCreateContext(browser, clientInfo);
|
||||
await addInitScript(browserContext, this.config.browser.initScript);
|
||||
return {
|
||||
browserContext,
|
||||
close: () => this._closeBrowserContext(browserContext, browser)
|
||||
};
|
||||
}
|
||||
async _doCreateContext(browser, clientInfo) {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
async _closeBrowserContext(browserContext, browser) {
|
||||
(0, import_log.testDebug)(`close browser context (${this._logName})`);
|
||||
if (browser.contexts().length === 1)
|
||||
this._browserPromise = void 0;
|
||||
await browserContext.close().catch(import_log.logUnhandledError);
|
||||
if (browser.contexts().length === 0) {
|
||||
(0, import_log.testDebug)(`close browser (${this._logName})`);
|
||||
await browser.close().catch(import_log.logUnhandledError);
|
||||
}
|
||||
}
|
||||
}
|
||||
class IsolatedContextFactory extends BaseContextFactory {
|
||||
constructor(config) {
|
||||
super("isolated", config);
|
||||
}
|
||||
async _doObtainBrowser(clientInfo, options) {
|
||||
await injectCdpPort(this.config.browser);
|
||||
const browserType = playwright[this.config.browser.browserName];
|
||||
const tracesDir = await computeTracesDir(this.config, clientInfo);
|
||||
if (tracesDir && this.config.saveTrace)
|
||||
await startTraceServer(this.config, tracesDir);
|
||||
return browserType.launch({
|
||||
tracesDir,
|
||||
...this.config.browser.launchOptions,
|
||||
handleSIGINT: false,
|
||||
handleSIGTERM: false,
|
||||
...options.forceHeadless !== void 0 ? { headless: options.forceHeadless === "headless" } : {}
|
||||
}).catch((error) => {
|
||||
if (error.message.includes("Executable doesn't exist"))
|
||||
throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
async _doCreateContext(browser, clientInfo) {
|
||||
return browser.newContext(await browserContextOptionsFromConfig(this.config, clientInfo));
|
||||
}
|
||||
}
|
||||
class CdpContextFactory extends BaseContextFactory {
|
||||
constructor(config) {
|
||||
super("cdp", config);
|
||||
}
|
||||
async _doObtainBrowser() {
|
||||
return playwright.chromium.connectOverCDP(this.config.browser.cdpEndpoint, {
|
||||
headers: this.config.browser.cdpHeaders,
|
||||
timeout: this.config.browser.cdpTimeout
|
||||
});
|
||||
}
|
||||
async _doCreateContext(browser) {
|
||||
return this.config.browser.isolated ? await browser.newContext() : browser.contexts()[0];
|
||||
}
|
||||
}
|
||||
class RemoteContextFactory extends BaseContextFactory {
|
||||
constructor(config) {
|
||||
super("remote", config);
|
||||
}
|
||||
async _doObtainBrowser() {
|
||||
const url = new URL(this.config.browser.remoteEndpoint);
|
||||
url.searchParams.set("browser", this.config.browser.browserName);
|
||||
if (this.config.browser.launchOptions)
|
||||
url.searchParams.set("launch-options", JSON.stringify(this.config.browser.launchOptions));
|
||||
return playwright[this.config.browser.browserName].connect(String(url));
|
||||
}
|
||||
async _doCreateContext(browser) {
|
||||
return browser.newContext();
|
||||
}
|
||||
}
|
||||
class PersistentContextFactory {
|
||||
constructor(config) {
|
||||
this.name = "persistent";
|
||||
this.description = "Create a new persistent browser context";
|
||||
this._userDataDirs = /* @__PURE__ */ new Set();
|
||||
this.config = config;
|
||||
}
|
||||
async createContext(clientInfo, abortSignal, options) {
|
||||
await injectCdpPort(this.config.browser);
|
||||
(0, import_log.testDebug)("create browser context (persistent)");
|
||||
const userDataDir = this.config.browser.userDataDir ?? await this._createUserDataDir(clientInfo);
|
||||
const tracesDir = await computeTracesDir(this.config, clientInfo);
|
||||
if (tracesDir && this.config.saveTrace)
|
||||
await startTraceServer(this.config, tracesDir);
|
||||
this._userDataDirs.add(userDataDir);
|
||||
(0, import_log.testDebug)("lock user data dir", userDataDir);
|
||||
const browserType = playwright[this.config.browser.browserName];
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const launchOptions = {
|
||||
tracesDir,
|
||||
...this.config.browser.launchOptions,
|
||||
...await browserContextOptionsFromConfig(this.config, clientInfo),
|
||||
handleSIGINT: false,
|
||||
handleSIGTERM: false,
|
||||
ignoreDefaultArgs: [
|
||||
"--disable-extensions"
|
||||
],
|
||||
assistantMode: true,
|
||||
...options.forceHeadless !== void 0 ? { headless: options.forceHeadless === "headless" } : {}
|
||||
};
|
||||
try {
|
||||
const browserContext = await browserType.launchPersistentContext(userDataDir, launchOptions);
|
||||
await addInitScript(browserContext, this.config.browser.initScript);
|
||||
const close = () => this._closeBrowserContext(browserContext, userDataDir);
|
||||
return { browserContext, close };
|
||||
} catch (error) {
|
||||
if (error.message.includes("Executable doesn't exist"))
|
||||
throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
|
||||
if (error.message.includes("cannot open shared object file: No such file or directory")) {
|
||||
const browserName = launchOptions.channel ?? this.config.browser.browserName;
|
||||
throw new Error(`Missing system dependencies required to run browser ${browserName}. Install them with: sudo npx playwright install-deps ${browserName}`);
|
||||
}
|
||||
if (error.message.includes("ProcessSingleton") || // On Windows the process exits silently with code 21 when the profile is in use.
|
||||
error.message.includes("exitCode=21")) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
|
||||
}
|
||||
async _closeBrowserContext(browserContext, userDataDir) {
|
||||
(0, import_log.testDebug)("close browser context (persistent)");
|
||||
(0, import_log.testDebug)("release user data dir", userDataDir);
|
||||
await browserContext.close().catch(() => {
|
||||
});
|
||||
this._userDataDirs.delete(userDataDir);
|
||||
if (process.env.PWMCP_PROFILES_DIR_FOR_TEST && userDataDir.startsWith(process.env.PWMCP_PROFILES_DIR_FOR_TEST))
|
||||
await import_fs.default.promises.rm(userDataDir, { recursive: true }).catch(import_log.logUnhandledError);
|
||||
(0, import_log.testDebug)("close browser context complete (persistent)");
|
||||
}
|
||||
async _createUserDataDir(clientInfo) {
|
||||
const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? import_registry.registryDirectory;
|
||||
const browserToken = this.config.browser.launchOptions?.channel ?? this.config.browser?.browserName;
|
||||
const rootPath = (0, import_server2.firstRootPath)(clientInfo);
|
||||
const rootPathToken = rootPath ? `-${createHash(rootPath)}` : "";
|
||||
const result = import_path.default.join(dir, `mcp-${browserToken}${rootPathToken}`);
|
||||
await import_fs.default.promises.mkdir(result, { recursive: true });
|
||||
return result;
|
||||
}
|
||||
}
|
||||
async function injectCdpPort(browserConfig) {
|
||||
if (browserConfig.browserName === "chromium")
|
||||
browserConfig.launchOptions.cdpPort = await findFreePort();
|
||||
}
|
||||
async function findFreePort() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = import_net.default.createServer();
|
||||
server.listen(0, () => {
|
||||
const { port } = server.address();
|
||||
server.close(() => resolve(port));
|
||||
});
|
||||
server.on("error", reject);
|
||||
});
|
||||
}
|
||||
async function startTraceServer(config, tracesDir) {
|
||||
if (!config.saveTrace)
|
||||
return;
|
||||
const server = await (0, import_server.startTraceViewerServer)();
|
||||
const urlPrefix = server.urlPrefix("human-readable");
|
||||
const url = urlPrefix + "/trace/index.html?trace=" + tracesDir + "/trace.json";
|
||||
console.error("\nTrace viewer listening on " + url);
|
||||
}
|
||||
function createHash(data) {
|
||||
return import_crypto.default.createHash("sha256").update(data).digest("hex").slice(0, 7);
|
||||
}
|
||||
async function addInitScript(browserContext, initScript) {
|
||||
for (const scriptPath of initScript ?? [])
|
||||
await browserContext.addInitScript({ path: import_path.default.resolve(scriptPath) });
|
||||
}
|
||||
class SharedContextFactory {
|
||||
static create(config) {
|
||||
if (SharedContextFactory._instance)
|
||||
throw new Error("SharedContextFactory already exists");
|
||||
const baseConfig = { ...config, sharedBrowserContext: false };
|
||||
const baseFactory = contextFactory(baseConfig);
|
||||
SharedContextFactory._instance = new SharedContextFactory(baseFactory);
|
||||
return SharedContextFactory._instance;
|
||||
}
|
||||
constructor(baseFactory) {
|
||||
this._baseFactory = baseFactory;
|
||||
}
|
||||
async createContext(clientInfo, abortSignal, options) {
|
||||
if (!this._contextPromise) {
|
||||
(0, import_log.testDebug)("create shared browser context");
|
||||
this._contextPromise = this._baseFactory.createContext(clientInfo, abortSignal, options);
|
||||
}
|
||||
const { browserContext } = await this._contextPromise;
|
||||
(0, import_log.testDebug)(`shared context client connected`);
|
||||
return {
|
||||
browserContext,
|
||||
close: async () => {
|
||||
(0, import_log.testDebug)(`shared context client disconnected`);
|
||||
}
|
||||
};
|
||||
}
|
||||
static async dispose() {
|
||||
await SharedContextFactory._instance?._dispose();
|
||||
}
|
||||
async _dispose() {
|
||||
const contextPromise = this._contextPromise;
|
||||
this._contextPromise = void 0;
|
||||
if (!contextPromise)
|
||||
return;
|
||||
const { close } = await contextPromise;
|
||||
await close();
|
||||
}
|
||||
}
|
||||
async function computeTracesDir(config, clientInfo) {
|
||||
if (!config.saveTrace && !config.capabilities?.includes("tracing"))
|
||||
return;
|
||||
return await (0, import_config.outputFile)(config, clientInfo, `traces`, { origin: "code", title: "Collecting trace" });
|
||||
}
|
||||
async function browserContextOptionsFromConfig(config, clientInfo) {
|
||||
const result = { ...config.browser.contextOptions };
|
||||
if (config.saveVideo) {
|
||||
const dir = await (0, import_config.outputFile)(config, clientInfo, `videos`, { origin: "code", title: "Saving video" });
|
||||
result.recordVideo = {
|
||||
dir,
|
||||
size: config.saveVideo
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
SharedContextFactory,
|
||||
contextFactory,
|
||||
identityBrowserContextFactory
|
||||
});
|
||||
84
backend/node_modules/playwright/lib/mcp/browser/browserServerBackend.js
generated
vendored
Normal file
84
backend/node_modules/playwright/lib/mcp/browser/browserServerBackend.js
generated
vendored
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var browserServerBackend_exports = {};
|
||||
__export(browserServerBackend_exports, {
|
||||
BrowserServerBackend: () => BrowserServerBackend
|
||||
});
|
||||
module.exports = __toCommonJS(browserServerBackend_exports);
|
||||
var import_context = require("./context");
|
||||
var import_log = require("../log");
|
||||
var import_response = require("./response");
|
||||
var import_sessionLog = require("./sessionLog");
|
||||
var import_tools = require("./tools");
|
||||
var import_tool = require("../sdk/tool");
|
||||
class BrowserServerBackend {
|
||||
constructor(config, factory) {
|
||||
this._config = config;
|
||||
this._browserContextFactory = factory;
|
||||
this._tools = (0, import_tools.filteredTools)(config);
|
||||
}
|
||||
async initialize(clientInfo) {
|
||||
this._sessionLog = this._config.saveSession ? await import_sessionLog.SessionLog.create(this._config, clientInfo) : void 0;
|
||||
this._context = new import_context.Context({
|
||||
config: this._config,
|
||||
browserContextFactory: this._browserContextFactory,
|
||||
sessionLog: this._sessionLog,
|
||||
clientInfo
|
||||
});
|
||||
}
|
||||
async listTools() {
|
||||
return this._tools.map((tool) => (0, import_tool.toMcpTool)(tool.schema));
|
||||
}
|
||||
async callTool(name, rawArguments) {
|
||||
const tool = this._tools.find((tool2) => tool2.schema.name === name);
|
||||
if (!tool) {
|
||||
return {
|
||||
content: [{ type: "text", text: `### Error
|
||||
Tool "${name}" not found` }],
|
||||
isError: true
|
||||
};
|
||||
}
|
||||
const parsedArguments = tool.schema.inputSchema.parse(rawArguments || {});
|
||||
const context = this._context;
|
||||
const response = import_response.Response.create(context, name, parsedArguments);
|
||||
context.setRunningTool(name);
|
||||
let responseObject;
|
||||
try {
|
||||
await tool.handle(context, parsedArguments, response);
|
||||
responseObject = await response.build();
|
||||
this._sessionLog?.logResponse(name, parsedArguments, responseObject);
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{ type: "text", text: `### Error
|
||||
${String(error)}` }],
|
||||
isError: true
|
||||
};
|
||||
} finally {
|
||||
context.setRunningTool(void 0);
|
||||
}
|
||||
return responseObject;
|
||||
}
|
||||
serverClosed() {
|
||||
void this._context?.dispose().catch(import_log.logUnhandledError);
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
BrowserServerBackend
|
||||
});
|
||||
421
backend/node_modules/playwright/lib/mcp/browser/config.js
generated
vendored
Normal file
421
backend/node_modules/playwright/lib/mcp/browser/config.js
generated
vendored
Normal file
|
|
@ -0,0 +1,421 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var config_exports = {};
|
||||
__export(config_exports, {
|
||||
commaSeparatedList: () => commaSeparatedList,
|
||||
configFromCLIOptions: () => configFromCLIOptions,
|
||||
defaultConfig: () => defaultConfig,
|
||||
dotenvFileLoader: () => dotenvFileLoader,
|
||||
enumParser: () => enumParser,
|
||||
headerParser: () => headerParser,
|
||||
numberParser: () => numberParser,
|
||||
outputDir: () => outputDir,
|
||||
outputFile: () => outputFile,
|
||||
resolutionParser: () => resolutionParser,
|
||||
resolveCLIConfig: () => resolveCLIConfig,
|
||||
resolveConfig: () => resolveConfig,
|
||||
semicolonSeparatedList: () => semicolonSeparatedList
|
||||
});
|
||||
module.exports = __toCommonJS(config_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_os = __toESM(require("os"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_playwright_core = require("playwright-core");
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_util = require("../../util");
|
||||
var import_server = require("../sdk/server");
|
||||
const defaultConfig = {
|
||||
browser: {
|
||||
browserName: "chromium",
|
||||
launchOptions: {
|
||||
channel: "chrome",
|
||||
headless: import_os.default.platform() === "linux" && !process.env.DISPLAY,
|
||||
chromiumSandbox: true
|
||||
},
|
||||
contextOptions: {
|
||||
viewport: null
|
||||
}
|
||||
},
|
||||
console: {
|
||||
level: "info"
|
||||
},
|
||||
network: {
|
||||
allowedOrigins: void 0,
|
||||
blockedOrigins: void 0
|
||||
},
|
||||
server: {},
|
||||
saveTrace: false,
|
||||
snapshot: {
|
||||
mode: "incremental",
|
||||
output: "stdout"
|
||||
},
|
||||
timeouts: {
|
||||
action: 5e3,
|
||||
navigation: 6e4
|
||||
}
|
||||
};
|
||||
async function resolveConfig(config) {
|
||||
return mergeConfig(defaultConfig, config);
|
||||
}
|
||||
async function resolveCLIConfig(cliOptions) {
|
||||
const configInFile = await loadConfig(cliOptions.config);
|
||||
const envOverrides = configFromEnv();
|
||||
const cliOverrides = configFromCLIOptions(cliOptions);
|
||||
let result = defaultConfig;
|
||||
result = mergeConfig(result, configInFile);
|
||||
result = mergeConfig(result, envOverrides);
|
||||
result = mergeConfig(result, cliOverrides);
|
||||
await validateConfig(result);
|
||||
return result;
|
||||
}
|
||||
async function validateConfig(config) {
|
||||
if (config.browser.initScript) {
|
||||
for (const script of config.browser.initScript) {
|
||||
if (!await (0, import_util.fileExistsAsync)(script))
|
||||
throw new Error(`Init script file does not exist: ${script}`);
|
||||
}
|
||||
}
|
||||
if (config.browser.initPage) {
|
||||
for (const page of config.browser.initPage) {
|
||||
if (!await (0, import_util.fileExistsAsync)(page))
|
||||
throw new Error(`Init page file does not exist: ${page}`);
|
||||
}
|
||||
}
|
||||
if (config.sharedBrowserContext && config.saveVideo)
|
||||
throw new Error("saveVideo is not supported when sharedBrowserContext is true");
|
||||
}
|
||||
function configFromCLIOptions(cliOptions) {
|
||||
let browserName;
|
||||
let channel;
|
||||
switch (cliOptions.browser) {
|
||||
case "chrome":
|
||||
case "chrome-beta":
|
||||
case "chrome-canary":
|
||||
case "chrome-dev":
|
||||
case "chromium":
|
||||
case "msedge":
|
||||
case "msedge-beta":
|
||||
case "msedge-canary":
|
||||
case "msedge-dev":
|
||||
browserName = "chromium";
|
||||
channel = cliOptions.browser;
|
||||
break;
|
||||
case "firefox":
|
||||
browserName = "firefox";
|
||||
break;
|
||||
case "webkit":
|
||||
browserName = "webkit";
|
||||
break;
|
||||
}
|
||||
const launchOptions = {
|
||||
channel,
|
||||
executablePath: cliOptions.executablePath,
|
||||
headless: cliOptions.headless
|
||||
};
|
||||
if (cliOptions.sandbox === false)
|
||||
launchOptions.chromiumSandbox = false;
|
||||
if (cliOptions.proxyServer) {
|
||||
launchOptions.proxy = {
|
||||
server: cliOptions.proxyServer
|
||||
};
|
||||
if (cliOptions.proxyBypass)
|
||||
launchOptions.proxy.bypass = cliOptions.proxyBypass;
|
||||
}
|
||||
if (cliOptions.device && cliOptions.cdpEndpoint)
|
||||
throw new Error("Device emulation is not supported with cdpEndpoint.");
|
||||
const contextOptions = cliOptions.device ? import_playwright_core.devices[cliOptions.device] : {};
|
||||
if (cliOptions.storageState)
|
||||
contextOptions.storageState = cliOptions.storageState;
|
||||
if (cliOptions.userAgent)
|
||||
contextOptions.userAgent = cliOptions.userAgent;
|
||||
if (cliOptions.viewportSize)
|
||||
contextOptions.viewport = cliOptions.viewportSize;
|
||||
if (cliOptions.ignoreHttpsErrors)
|
||||
contextOptions.ignoreHTTPSErrors = true;
|
||||
if (cliOptions.blockServiceWorkers)
|
||||
contextOptions.serviceWorkers = "block";
|
||||
if (cliOptions.grantPermissions)
|
||||
contextOptions.permissions = cliOptions.grantPermissions;
|
||||
const result = {
|
||||
browser: {
|
||||
browserName,
|
||||
isolated: cliOptions.isolated,
|
||||
userDataDir: cliOptions.userDataDir,
|
||||
launchOptions,
|
||||
contextOptions,
|
||||
cdpEndpoint: cliOptions.cdpEndpoint,
|
||||
cdpHeaders: cliOptions.cdpHeader,
|
||||
initPage: cliOptions.initPage,
|
||||
initScript: cliOptions.initScript
|
||||
},
|
||||
server: {
|
||||
port: cliOptions.port,
|
||||
host: cliOptions.host,
|
||||
allowedHosts: cliOptions.allowedHosts
|
||||
},
|
||||
capabilities: cliOptions.caps,
|
||||
console: {
|
||||
level: cliOptions.consoleLevel
|
||||
},
|
||||
network: {
|
||||
allowedOrigins: cliOptions.allowedOrigins,
|
||||
blockedOrigins: cliOptions.blockedOrigins
|
||||
},
|
||||
allowUnrestrictedFileAccess: cliOptions.allowUnrestrictedFileAccess,
|
||||
codegen: cliOptions.codegen,
|
||||
saveSession: cliOptions.saveSession,
|
||||
saveTrace: cliOptions.saveTrace,
|
||||
saveVideo: cliOptions.saveVideo,
|
||||
secrets: cliOptions.secrets,
|
||||
sharedBrowserContext: cliOptions.sharedBrowserContext,
|
||||
snapshot: cliOptions.snapshotMode ? { mode: cliOptions.snapshotMode } : void 0,
|
||||
outputMode: cliOptions.outputMode,
|
||||
outputDir: cliOptions.outputDir,
|
||||
imageResponses: cliOptions.imageResponses,
|
||||
testIdAttribute: cliOptions.testIdAttribute,
|
||||
timeouts: {
|
||||
action: cliOptions.timeoutAction,
|
||||
navigation: cliOptions.timeoutNavigation
|
||||
}
|
||||
};
|
||||
return result;
|
||||
}
|
||||
function configFromEnv() {
|
||||
const options = {};
|
||||
options.allowedHosts = commaSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_HOSTNAMES);
|
||||
options.allowedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS);
|
||||
options.allowUnrestrictedFileAccess = envToBoolean(process.env.PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS);
|
||||
options.blockedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_BLOCKED_ORIGINS);
|
||||
options.blockServiceWorkers = envToBoolean(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS);
|
||||
options.browser = envToString(process.env.PLAYWRIGHT_MCP_BROWSER);
|
||||
options.caps = commaSeparatedList(process.env.PLAYWRIGHT_MCP_CAPS);
|
||||
options.cdpEndpoint = envToString(process.env.PLAYWRIGHT_MCP_CDP_ENDPOINT);
|
||||
options.cdpHeader = headerParser(process.env.PLAYWRIGHT_MCP_CDP_HEADERS, {});
|
||||
options.config = envToString(process.env.PLAYWRIGHT_MCP_CONFIG);
|
||||
if (process.env.PLAYWRIGHT_MCP_CONSOLE_LEVEL)
|
||||
options.consoleLevel = enumParser("--console-level", ["error", "warning", "info", "debug"], process.env.PLAYWRIGHT_MCP_CONSOLE_LEVEL);
|
||||
options.device = envToString(process.env.PLAYWRIGHT_MCP_DEVICE);
|
||||
options.executablePath = envToString(process.env.PLAYWRIGHT_MCP_EXECUTABLE_PATH);
|
||||
options.grantPermissions = commaSeparatedList(process.env.PLAYWRIGHT_MCP_GRANT_PERMISSIONS);
|
||||
options.headless = envToBoolean(process.env.PLAYWRIGHT_MCP_HEADLESS);
|
||||
options.host = envToString(process.env.PLAYWRIGHT_MCP_HOST);
|
||||
options.ignoreHttpsErrors = envToBoolean(process.env.PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS);
|
||||
const initPage = envToString(process.env.PLAYWRIGHT_MCP_INIT_PAGE);
|
||||
if (initPage)
|
||||
options.initPage = [initPage];
|
||||
const initScript = envToString(process.env.PLAYWRIGHT_MCP_INIT_SCRIPT);
|
||||
if (initScript)
|
||||
options.initScript = [initScript];
|
||||
options.isolated = envToBoolean(process.env.PLAYWRIGHT_MCP_ISOLATED);
|
||||
if (process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES)
|
||||
options.imageResponses = enumParser("--image-responses", ["allow", "omit"], process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES);
|
||||
options.sandbox = envToBoolean(process.env.PLAYWRIGHT_MCP_SANDBOX);
|
||||
options.outputDir = envToString(process.env.PLAYWRIGHT_MCP_OUTPUT_DIR);
|
||||
options.port = numberParser(process.env.PLAYWRIGHT_MCP_PORT);
|
||||
options.proxyBypass = envToString(process.env.PLAYWRIGHT_MCP_PROXY_BYPASS);
|
||||
options.proxyServer = envToString(process.env.PLAYWRIGHT_MCP_PROXY_SERVER);
|
||||
options.saveTrace = envToBoolean(process.env.PLAYWRIGHT_MCP_SAVE_TRACE);
|
||||
options.saveVideo = resolutionParser("--save-video", process.env.PLAYWRIGHT_MCP_SAVE_VIDEO);
|
||||
options.secrets = dotenvFileLoader(process.env.PLAYWRIGHT_MCP_SECRETS_FILE);
|
||||
options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);
|
||||
options.testIdAttribute = envToString(process.env.PLAYWRIGHT_MCP_TEST_ID_ATTRIBUTE);
|
||||
options.timeoutAction = numberParser(process.env.PLAYWRIGHT_MCP_TIMEOUT_ACTION);
|
||||
options.timeoutNavigation = numberParser(process.env.PLAYWRIGHT_MCP_TIMEOUT_NAVIGATION);
|
||||
options.userAgent = envToString(process.env.PLAYWRIGHT_MCP_USER_AGENT);
|
||||
options.userDataDir = envToString(process.env.PLAYWRIGHT_MCP_USER_DATA_DIR);
|
||||
options.viewportSize = resolutionParser("--viewport-size", process.env.PLAYWRIGHT_MCP_VIEWPORT_SIZE);
|
||||
return configFromCLIOptions(options);
|
||||
}
|
||||
async function loadConfig(configFile) {
|
||||
if (!configFile)
|
||||
return {};
|
||||
try {
|
||||
return JSON.parse(await import_fs.default.promises.readFile(configFile, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to load config file: ${configFile}, ${error}`);
|
||||
}
|
||||
}
|
||||
function tmpDir() {
|
||||
return import_path.default.join(process.env.PW_TMPDIR_FOR_TEST ?? import_os.default.tmpdir(), "playwright-mcp-output");
|
||||
}
|
||||
function outputDir(config, clientInfo) {
|
||||
const rootPath = (0, import_server.firstRootPath)(clientInfo);
|
||||
return config.outputDir ?? (rootPath ? import_path.default.join(rootPath, ".playwright-mcp") : void 0) ?? import_path.default.join(tmpDir(), String(clientInfo.timestamp));
|
||||
}
|
||||
async function outputFile(config, clientInfo, fileName, options) {
|
||||
const file = await resolveFile(config, clientInfo, fileName, options);
|
||||
await import_fs.default.promises.mkdir(import_path.default.dirname(file), { recursive: true });
|
||||
(0, import_utilsBundle.debug)("pw:mcp:file")(options.title, file);
|
||||
return file;
|
||||
}
|
||||
async function resolveFile(config, clientInfo, fileName, options) {
|
||||
const dir = outputDir(config, clientInfo);
|
||||
if (options.origin === "code")
|
||||
return import_path.default.resolve(dir, fileName);
|
||||
if (options.origin === "llm") {
|
||||
fileName = fileName.split("\\").join("/");
|
||||
const resolvedFile = import_path.default.resolve(dir, fileName);
|
||||
if (!resolvedFile.startsWith(import_path.default.resolve(dir) + import_path.default.sep))
|
||||
throw new Error(`Resolved file path ${resolvedFile} is outside of the output directory ${dir}. Use relative file names to stay within the output directory.`);
|
||||
return resolvedFile;
|
||||
}
|
||||
return import_path.default.join(dir, sanitizeForFilePath(fileName));
|
||||
}
|
||||
function pickDefined(obj) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj ?? {}).filter(([_, v]) => v !== void 0)
|
||||
);
|
||||
}
|
||||
function mergeConfig(base, overrides) {
|
||||
const browser = {
|
||||
...pickDefined(base.browser),
|
||||
...pickDefined(overrides.browser),
|
||||
browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? "chromium",
|
||||
isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
|
||||
launchOptions: {
|
||||
...pickDefined(base.browser?.launchOptions),
|
||||
...pickDefined(overrides.browser?.launchOptions),
|
||||
...{ assistantMode: true }
|
||||
},
|
||||
contextOptions: {
|
||||
...pickDefined(base.browser?.contextOptions),
|
||||
...pickDefined(overrides.browser?.contextOptions)
|
||||
}
|
||||
};
|
||||
if (browser.browserName !== "chromium" && browser.launchOptions)
|
||||
delete browser.launchOptions.channel;
|
||||
return {
|
||||
...pickDefined(base),
|
||||
...pickDefined(overrides),
|
||||
browser,
|
||||
console: {
|
||||
...pickDefined(base.console),
|
||||
...pickDefined(overrides.console)
|
||||
},
|
||||
network: {
|
||||
...pickDefined(base.network),
|
||||
...pickDefined(overrides.network)
|
||||
},
|
||||
server: {
|
||||
...pickDefined(base.server),
|
||||
...pickDefined(overrides.server)
|
||||
},
|
||||
snapshot: {
|
||||
...pickDefined(base.snapshot),
|
||||
...pickDefined(overrides.snapshot)
|
||||
},
|
||||
timeouts: {
|
||||
...pickDefined(base.timeouts),
|
||||
...pickDefined(overrides.timeouts)
|
||||
}
|
||||
};
|
||||
}
|
||||
function semicolonSeparatedList(value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
return value.split(";").map((v) => v.trim());
|
||||
}
|
||||
function commaSeparatedList(value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
return value.split(",").map((v) => v.trim());
|
||||
}
|
||||
function dotenvFileLoader(value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
return import_utilsBundle.dotenv.parse(import_fs.default.readFileSync(value, "utf8"));
|
||||
}
|
||||
function numberParser(value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
return +value;
|
||||
}
|
||||
function resolutionParser(name, value) {
|
||||
if (!value)
|
||||
return void 0;
|
||||
if (value.includes("x")) {
|
||||
const [width, height] = value.split("x").map((v) => +v);
|
||||
if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0)
|
||||
throw new Error(`Invalid resolution format: use ${name}="800x600"`);
|
||||
return { width, height };
|
||||
}
|
||||
if (value.includes(",")) {
|
||||
const [width, height] = value.split(",").map((v) => +v);
|
||||
if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0)
|
||||
throw new Error(`Invalid resolution format: use ${name}="800x600"`);
|
||||
return { width, height };
|
||||
}
|
||||
throw new Error(`Invalid resolution format: use ${name}="800x600"`);
|
||||
}
|
||||
function headerParser(arg, previous) {
|
||||
if (!arg)
|
||||
return previous || {};
|
||||
const result = previous || {};
|
||||
const [name, value] = arg.split(":").map((v) => v.trim());
|
||||
result[name] = value;
|
||||
return result;
|
||||
}
|
||||
function enumParser(name, options, value) {
|
||||
if (!options.includes(value))
|
||||
throw new Error(`Invalid ${name}: ${value}. Valid values are: ${options.join(", ")}`);
|
||||
return value;
|
||||
}
|
||||
function envToBoolean(value) {
|
||||
if (value === "true" || value === "1")
|
||||
return true;
|
||||
if (value === "false" || value === "0")
|
||||
return false;
|
||||
return void 0;
|
||||
}
|
||||
function envToString(value) {
|
||||
return value ? value.trim() : void 0;
|
||||
}
|
||||
function sanitizeForFilePath(s) {
|
||||
const sanitize = (s2) => s2.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, "-");
|
||||
const separator = s.lastIndexOf(".");
|
||||
if (separator === -1)
|
||||
return sanitize(s);
|
||||
return sanitize(s.substring(0, separator)) + "." + sanitize(s.substring(separator + 1));
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
commaSeparatedList,
|
||||
configFromCLIOptions,
|
||||
defaultConfig,
|
||||
dotenvFileLoader,
|
||||
enumParser,
|
||||
headerParser,
|
||||
numberParser,
|
||||
outputDir,
|
||||
outputFile,
|
||||
resolutionParser,
|
||||
resolveCLIConfig,
|
||||
resolveConfig,
|
||||
semicolonSeparatedList
|
||||
});
|
||||
244
backend/node_modules/playwright/lib/mcp/browser/context.js
generated
vendored
Normal file
244
backend/node_modules/playwright/lib/mcp/browser/context.js
generated
vendored
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var context_exports = {};
|
||||
__export(context_exports, {
|
||||
Context: () => Context
|
||||
});
|
||||
module.exports = __toCommonJS(context_exports);
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_playwright_core = require("playwright-core");
|
||||
var import_url = require("url");
|
||||
var import_os = __toESM(require("os"));
|
||||
var import_log = require("../log");
|
||||
var import_tab = require("./tab");
|
||||
var import_config = require("./config");
|
||||
const testDebug = (0, import_utilsBundle.debug)("pw:mcp:test");
|
||||
class Context {
|
||||
constructor(options) {
|
||||
this._tabs = [];
|
||||
this._abortController = new AbortController();
|
||||
this.config = options.config;
|
||||
this.sessionLog = options.sessionLog;
|
||||
this.options = options;
|
||||
this._browserContextFactory = options.browserContextFactory;
|
||||
this._clientInfo = options.clientInfo;
|
||||
testDebug("create context");
|
||||
Context._allContexts.add(this);
|
||||
}
|
||||
static {
|
||||
this._allContexts = /* @__PURE__ */ new Set();
|
||||
}
|
||||
static async disposeAll() {
|
||||
await Promise.all([...Context._allContexts].map((context) => context.dispose()));
|
||||
}
|
||||
tabs() {
|
||||
return this._tabs;
|
||||
}
|
||||
currentTab() {
|
||||
return this._currentTab;
|
||||
}
|
||||
currentTabOrDie() {
|
||||
if (!this._currentTab)
|
||||
throw new Error("No open pages available.");
|
||||
return this._currentTab;
|
||||
}
|
||||
async newTab() {
|
||||
const { browserContext } = await this._ensureBrowserContext({});
|
||||
const page = await browserContext.newPage();
|
||||
this._currentTab = this._tabs.find((t) => t.page === page);
|
||||
return this._currentTab;
|
||||
}
|
||||
async selectTab(index) {
|
||||
const tab = this._tabs[index];
|
||||
if (!tab)
|
||||
throw new Error(`Tab ${index} not found`);
|
||||
await tab.page.bringToFront();
|
||||
this._currentTab = tab;
|
||||
return tab;
|
||||
}
|
||||
async ensureTab(options = {}) {
|
||||
const { browserContext } = await this._ensureBrowserContext(options);
|
||||
if (!this._currentTab)
|
||||
await browserContext.newPage();
|
||||
return this._currentTab;
|
||||
}
|
||||
async closeTab(index) {
|
||||
const tab = index === void 0 ? this._currentTab : this._tabs[index];
|
||||
if (!tab)
|
||||
throw new Error(`Tab ${index} not found`);
|
||||
const url = tab.page.url();
|
||||
await tab.page.close();
|
||||
return url;
|
||||
}
|
||||
async outputFile(fileName, options) {
|
||||
return (0, import_config.outputFile)(this.config, this._clientInfo, fileName, options);
|
||||
}
|
||||
_onPageCreated(page) {
|
||||
const tab = new import_tab.Tab(this, page, (tab2) => this._onPageClosed(tab2));
|
||||
this._tabs.push(tab);
|
||||
if (!this._currentTab)
|
||||
this._currentTab = tab;
|
||||
}
|
||||
_onPageClosed(tab) {
|
||||
const index = this._tabs.indexOf(tab);
|
||||
if (index === -1)
|
||||
return;
|
||||
this._tabs.splice(index, 1);
|
||||
if (this._currentTab === tab)
|
||||
this._currentTab = this._tabs[Math.min(index, this._tabs.length - 1)];
|
||||
if (!this._tabs.length)
|
||||
void this.closeBrowserContext();
|
||||
}
|
||||
async closeBrowserContext() {
|
||||
if (!this._closeBrowserContextPromise)
|
||||
this._closeBrowserContextPromise = this._closeBrowserContextImpl().catch(import_log.logUnhandledError);
|
||||
await this._closeBrowserContextPromise;
|
||||
this._closeBrowserContextPromise = void 0;
|
||||
}
|
||||
isRunningTool() {
|
||||
return this._runningToolName !== void 0;
|
||||
}
|
||||
setRunningTool(name) {
|
||||
this._runningToolName = name;
|
||||
}
|
||||
async _closeBrowserContextImpl() {
|
||||
if (!this._browserContextPromise)
|
||||
return;
|
||||
testDebug("close context");
|
||||
const promise = this._browserContextPromise;
|
||||
this._browserContextPromise = void 0;
|
||||
this._browserContextOption = void 0;
|
||||
await promise.then(async ({ browserContext, close }) => {
|
||||
if (this.config.saveTrace)
|
||||
await browserContext.tracing.stop();
|
||||
await close();
|
||||
});
|
||||
}
|
||||
async dispose() {
|
||||
this._abortController.abort("MCP context disposed");
|
||||
await this.closeBrowserContext();
|
||||
Context._allContexts.delete(this);
|
||||
}
|
||||
async _setupRequestInterception(context) {
|
||||
if (this.config.network?.allowedOrigins?.length) {
|
||||
await context.route("**", (route) => route.abort("blockedbyclient"));
|
||||
for (const origin of this.config.network.allowedOrigins)
|
||||
await context.route(originOrHostGlob(origin), (route) => route.continue());
|
||||
}
|
||||
if (this.config.network?.blockedOrigins?.length) {
|
||||
for (const origin of this.config.network.blockedOrigins)
|
||||
await context.route(originOrHostGlob(origin), (route) => route.abort("blockedbyclient"));
|
||||
}
|
||||
}
|
||||
async ensureBrowserContext(options = {}) {
|
||||
const { browserContext } = await this._ensureBrowserContext(options);
|
||||
return browserContext;
|
||||
}
|
||||
_ensureBrowserContext(options) {
|
||||
if (this._browserContextPromise && (options.forceHeadless === void 0 || this._browserContextOption?.forceHeadless === options.forceHeadless))
|
||||
return this._browserContextPromise;
|
||||
const closePrework = this._browserContextPromise ? this.closeBrowserContext() : Promise.resolve();
|
||||
this._browserContextPromise = closePrework.then(() => this._setupBrowserContext(options));
|
||||
this._browserContextPromise.catch(() => {
|
||||
this._browserContextPromise = void 0;
|
||||
this._browserContextOption = void 0;
|
||||
});
|
||||
this._browserContextOption = options;
|
||||
return this._browserContextPromise;
|
||||
}
|
||||
async _setupBrowserContext(options) {
|
||||
if (this._closeBrowserContextPromise)
|
||||
throw new Error("Another browser context is being closed.");
|
||||
if (this.config.testIdAttribute)
|
||||
import_playwright_core.selectors.setTestIdAttribute(this.config.testIdAttribute);
|
||||
const result = await this._browserContextFactory.createContext(this._clientInfo, this._abortController.signal, { toolName: this._runningToolName, ...options });
|
||||
const { browserContext } = result;
|
||||
if (!this.config.allowUnrestrictedFileAccess) {
|
||||
browserContext._setAllowedProtocols(["http:", "https:", "about:", "data:"]);
|
||||
browserContext._setAllowedDirectories(allRootPaths(this._clientInfo));
|
||||
}
|
||||
await this._setupRequestInterception(browserContext);
|
||||
for (const page of browserContext.pages())
|
||||
this._onPageCreated(page);
|
||||
browserContext.on("page", (page) => this._onPageCreated(page));
|
||||
if (this.config.saveTrace) {
|
||||
await browserContext.tracing.start({
|
||||
name: "trace-" + Date.now(),
|
||||
screenshots: true,
|
||||
snapshots: true,
|
||||
_live: true
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
lookupSecret(secretName) {
|
||||
if (!this.config.secrets?.[secretName])
|
||||
return { value: secretName, code: (0, import_utils.escapeWithQuotes)(secretName, "'") };
|
||||
return {
|
||||
value: this.config.secrets[secretName],
|
||||
code: `process.env['${secretName}']`
|
||||
};
|
||||
}
|
||||
firstRootPath() {
|
||||
return allRootPaths(this._clientInfo)[0];
|
||||
}
|
||||
}
|
||||
function allRootPaths(clientInfo) {
|
||||
const paths = [];
|
||||
for (const root of clientInfo.roots) {
|
||||
const url = new URL(root.uri);
|
||||
let rootPath;
|
||||
try {
|
||||
rootPath = (0, import_url.fileURLToPath)(url);
|
||||
} catch (e) {
|
||||
if (e.code === "ERR_INVALID_FILE_URL_PATH" && import_os.default.platform() === "win32")
|
||||
rootPath = decodeURIComponent(url.pathname);
|
||||
}
|
||||
if (!rootPath)
|
||||
continue;
|
||||
paths.push(rootPath);
|
||||
}
|
||||
if (paths.length === 0)
|
||||
paths.push(process.cwd());
|
||||
return paths;
|
||||
}
|
||||
function originOrHostGlob(originOrHost) {
|
||||
try {
|
||||
const url = new URL(originOrHost);
|
||||
if (url.origin !== "null")
|
||||
return `${url.origin}/**`;
|
||||
} catch {
|
||||
}
|
||||
return `*://${originOrHost}/**`;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
Context
|
||||
});
|
||||
278
backend/node_modules/playwright/lib/mcp/browser/response.js
generated
vendored
Normal file
278
backend/node_modules/playwright/lib/mcp/browser/response.js
generated
vendored
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var response_exports = {};
|
||||
__export(response_exports, {
|
||||
Response: () => Response,
|
||||
parseResponse: () => parseResponse,
|
||||
renderTabMarkdown: () => renderTabMarkdown,
|
||||
renderTabsMarkdown: () => renderTabsMarkdown,
|
||||
requestDebug: () => requestDebug
|
||||
});
|
||||
module.exports = __toCommonJS(response_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_tab = require("./tab");
|
||||
var import_utils = require("./tools/utils");
|
||||
const requestDebug = (0, import_utilsBundle.debug)("pw:mcp:request");
|
||||
class Response {
|
||||
constructor(ordinal, context, toolName, toolArgs) {
|
||||
this._results = [];
|
||||
this._errors = [];
|
||||
this._code = [];
|
||||
this._images = [];
|
||||
this._includeSnapshot = "none";
|
||||
this._ordinal = ordinal;
|
||||
this._context = context;
|
||||
this.toolName = toolName;
|
||||
this.toolArgs = toolArgs;
|
||||
}
|
||||
static {
|
||||
this._ordinal = 0;
|
||||
}
|
||||
static create(context, toolName, toolArgs) {
|
||||
return new Response(++Response._ordinal, context, toolName, toolArgs);
|
||||
}
|
||||
addTextResult(result) {
|
||||
this._results.push({ text: result });
|
||||
}
|
||||
async addResult(result) {
|
||||
if (result.data && !result.suggestedFilename)
|
||||
result.suggestedFilename = (0, import_utils.dateAsFileName)(result.ext ?? "bin");
|
||||
if (this._context.config.outputMode === "file") {
|
||||
if (!result.suggestedFilename)
|
||||
result.suggestedFilename = (0, import_utils.dateAsFileName)(result.ext ?? (result.text ? "txt" : "bin"));
|
||||
}
|
||||
const entry = { text: result.text, data: result.data, title: result.title };
|
||||
if (result.suggestedFilename)
|
||||
entry.filename = await this._context.outputFile(result.suggestedFilename, { origin: "llm", title: result.title ?? "Saved result" });
|
||||
this._results.push(entry);
|
||||
return { fileName: entry.filename };
|
||||
}
|
||||
addError(error) {
|
||||
this._errors.push(error);
|
||||
}
|
||||
addCode(code) {
|
||||
this._code.push(code);
|
||||
}
|
||||
addImage(image) {
|
||||
this._images.push(image);
|
||||
}
|
||||
setIncludeSnapshot() {
|
||||
this._includeSnapshot = this._context.config.snapshot.mode;
|
||||
}
|
||||
setIncludeFullSnapshot(includeSnapshotFileName) {
|
||||
this._includeSnapshot = "full";
|
||||
this._includeSnapshotFileName = includeSnapshotFileName;
|
||||
}
|
||||
async build() {
|
||||
const rootPath = this._context.firstRootPath();
|
||||
const sections = [];
|
||||
const addSection = (title) => {
|
||||
const section = { title, content: [] };
|
||||
sections.push(section);
|
||||
return section.content;
|
||||
};
|
||||
if (this._errors.length) {
|
||||
const text = addSection("Error");
|
||||
text.push("### Error");
|
||||
text.push(this._errors.join("\n"));
|
||||
}
|
||||
if (this._results.length) {
|
||||
const text = addSection("Result");
|
||||
for (const result of this._results) {
|
||||
if (result.filename) {
|
||||
text.push(`- [${result.title}](${rootPath ? import_path.default.relative(rootPath, result.filename) : result.filename})`);
|
||||
if (result.data)
|
||||
await import_fs.default.promises.writeFile(result.filename, result.data);
|
||||
else if (result.text)
|
||||
await import_fs.default.promises.writeFile(result.filename, this._redactText(result.text));
|
||||
} else if (result.text) {
|
||||
text.push(result.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this._context.config.codegen !== "none" && this._code.length) {
|
||||
const text = addSection("Ran Playwright code");
|
||||
text.push(...this._code);
|
||||
}
|
||||
const tabSnapshot = this._context.currentTab() ? await this._context.currentTabOrDie().captureSnapshot() : void 0;
|
||||
const tabHeaders = await Promise.all(this._context.tabs().map((tab) => tab.headerSnapshot()));
|
||||
if (tabHeaders.some((header) => header.changed)) {
|
||||
if (tabHeaders.length !== 1) {
|
||||
const text2 = addSection("Open tabs");
|
||||
text2.push(...renderTabsMarkdown(tabHeaders));
|
||||
}
|
||||
const text = addSection("Page");
|
||||
text.push(...renderTabMarkdown(tabHeaders[0]));
|
||||
}
|
||||
if (tabSnapshot?.modalStates.length) {
|
||||
const text = addSection("Modal state");
|
||||
text.push(...(0, import_tab.renderModalStates)(tabSnapshot.modalStates));
|
||||
}
|
||||
if (tabSnapshot && this._includeSnapshot === "full") {
|
||||
let fileName;
|
||||
if (this._includeSnapshotFileName)
|
||||
fileName = await this._context.outputFile(this._includeSnapshotFileName, { origin: "llm", title: "Saved snapshot" });
|
||||
else if (this._context.config.outputMode === "file")
|
||||
fileName = await this._context.outputFile(`snapshot-${this._ordinal}.yml`, { origin: "code", title: "Saved snapshot" });
|
||||
if (fileName) {
|
||||
await import_fs.default.promises.writeFile(fileName, tabSnapshot.ariaSnapshot);
|
||||
const text = addSection("Snapshot");
|
||||
text.push(`- File: ${rootPath ? import_path.default.relative(rootPath, fileName) : fileName}`);
|
||||
} else {
|
||||
const text = addSection("Snapshot");
|
||||
text.push("```yaml");
|
||||
text.push(tabSnapshot.ariaSnapshot);
|
||||
text.push("```");
|
||||
}
|
||||
}
|
||||
if (tabSnapshot && this._includeSnapshot === "incremental") {
|
||||
const text = addSection("Snapshot");
|
||||
text.push("```yaml");
|
||||
if (tabSnapshot.ariaSnapshotDiff !== void 0)
|
||||
text.push(tabSnapshot.ariaSnapshotDiff);
|
||||
else
|
||||
text.push(tabSnapshot.ariaSnapshot);
|
||||
text.push("```");
|
||||
}
|
||||
if (tabSnapshot?.events.filter((event) => event.type !== "request").length) {
|
||||
const text = addSection("Events");
|
||||
for (const event of tabSnapshot.events) {
|
||||
if (event.type === "console") {
|
||||
if ((0, import_tab.shouldIncludeMessage)(this._context.config.console.level, event.message.type))
|
||||
text.push(`- ${trimMiddle(event.message.toString(), 100)}`);
|
||||
} else if (event.type === "download-start") {
|
||||
text.push(`- Downloading file ${event.download.download.suggestedFilename()} ...`);
|
||||
} else if (event.type === "download-finish") {
|
||||
text.push(`- Downloaded file ${event.download.download.suggestedFilename()} to "${rootPath ? import_path.default.relative(rootPath, event.download.outputFile) : event.download.outputFile}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const allText = sections.flatMap((section) => {
|
||||
const content2 = [];
|
||||
content2.push(`### ${section.title}`);
|
||||
content2.push(...section.content);
|
||||
content2.push("");
|
||||
return content2;
|
||||
}).join("\n");
|
||||
const content = [
|
||||
{
|
||||
type: "text",
|
||||
text: this._redactText(allText)
|
||||
}
|
||||
];
|
||||
if (this._context.config.imageResponses !== "omit") {
|
||||
for (const image of this._images)
|
||||
content.push({ type: "image", data: image.data.toString("base64"), mimeType: image.contentType });
|
||||
}
|
||||
return {
|
||||
content,
|
||||
...this._errors.length > 0 ? { isError: true } : {}
|
||||
};
|
||||
}
|
||||
_redactText(text) {
|
||||
for (const [secretName, secretValue] of Object.entries(this._context.config.secrets ?? {}))
|
||||
text = text.replaceAll(secretValue, `<secret>${secretName}</secret>`);
|
||||
return text;
|
||||
}
|
||||
}
|
||||
function renderTabMarkdown(tab) {
|
||||
const lines = [`- Page URL: ${tab.url}`];
|
||||
if (tab.title)
|
||||
lines.push(`- Page Title: ${tab.title}`);
|
||||
return lines;
|
||||
}
|
||||
function renderTabsMarkdown(tabs) {
|
||||
if (!tabs.length)
|
||||
return ['No open tabs. Use the "browser_navigate" tool to navigate to a page first.'];
|
||||
const lines = [];
|
||||
for (let i = 0; i < tabs.length; i++) {
|
||||
const tab = tabs[i];
|
||||
const current = tab.current ? " (current)" : "";
|
||||
lines.push(`- ${i}:${current} [${tab.title}](${tab.url})`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
function trimMiddle(text, maxLength) {
|
||||
if (text.length <= maxLength)
|
||||
return text;
|
||||
return text.slice(0, Math.floor(maxLength / 2)) + "..." + text.slice(-3 - Math.floor(maxLength / 2));
|
||||
}
|
||||
function parseSections(text) {
|
||||
const sections = /* @__PURE__ */ new Map();
|
||||
const sectionHeaders = text.split(/^### /m).slice(1);
|
||||
for (const section of sectionHeaders) {
|
||||
const firstNewlineIndex = section.indexOf("\n");
|
||||
if (firstNewlineIndex === -1)
|
||||
continue;
|
||||
const sectionName = section.substring(0, firstNewlineIndex);
|
||||
const sectionContent = section.substring(firstNewlineIndex + 1).trim();
|
||||
sections.set(sectionName, sectionContent);
|
||||
}
|
||||
return sections;
|
||||
}
|
||||
function parseResponse(response) {
|
||||
if (response.content?.[0].type !== "text")
|
||||
return void 0;
|
||||
const text = response.content[0].text;
|
||||
const sections = parseSections(text);
|
||||
const error = sections.get("Error");
|
||||
const result = sections.get("Result");
|
||||
const code = sections.get("Ran Playwright code");
|
||||
const tabs = sections.get("Open tabs");
|
||||
const page = sections.get("Page");
|
||||
const snapshot = sections.get("Snapshot");
|
||||
const events = sections.get("Events");
|
||||
const modalState = sections.get("Modal state");
|
||||
const codeNoFrame = code?.replace(/^```js\n/, "").replace(/\n```$/, "");
|
||||
const isError = response.isError;
|
||||
const attachments = response.content.length > 1 ? response.content.slice(1) : void 0;
|
||||
return {
|
||||
result,
|
||||
error,
|
||||
code: codeNoFrame,
|
||||
tabs,
|
||||
page,
|
||||
snapshot,
|
||||
events,
|
||||
modalState,
|
||||
isError,
|
||||
attachments,
|
||||
text
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
Response,
|
||||
parseResponse,
|
||||
renderTabMarkdown,
|
||||
renderTabsMarkdown,
|
||||
requestDebug
|
||||
});
|
||||
75
backend/node_modules/playwright/lib/mcp/browser/sessionLog.js
generated
vendored
Normal file
75
backend/node_modules/playwright/lib/mcp/browser/sessionLog.js
generated
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var sessionLog_exports = {};
|
||||
__export(sessionLog_exports, {
|
||||
SessionLog: () => SessionLog
|
||||
});
|
||||
module.exports = __toCommonJS(sessionLog_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_config = require("./config");
|
||||
var import_response = require("./response");
|
||||
class SessionLog {
|
||||
constructor(sessionFolder) {
|
||||
this._sessionFileQueue = Promise.resolve();
|
||||
this._folder = sessionFolder;
|
||||
this._file = import_path.default.join(this._folder, "session.md");
|
||||
}
|
||||
static async create(config, clientInfo) {
|
||||
const sessionFolder = await (0, import_config.outputFile)(config, clientInfo, `session-${Date.now()}`, { origin: "code", title: "Saving session" });
|
||||
await import_fs.default.promises.mkdir(sessionFolder, { recursive: true });
|
||||
console.error(`Session: ${sessionFolder}`);
|
||||
return new SessionLog(sessionFolder);
|
||||
}
|
||||
logResponse(toolName, toolArgs, responseObject) {
|
||||
const parsed = (0, import_response.parseResponse)(responseObject);
|
||||
if (parsed)
|
||||
delete parsed.text;
|
||||
const lines = [""];
|
||||
lines.push(
|
||||
`### Tool call: ${toolName}`,
|
||||
`- Args`,
|
||||
"```json",
|
||||
JSON.stringify(toolArgs, null, 2),
|
||||
"```"
|
||||
);
|
||||
if (parsed) {
|
||||
lines.push(`- Result`);
|
||||
lines.push("```json");
|
||||
lines.push(JSON.stringify(parsed, null, 2));
|
||||
lines.push("```");
|
||||
}
|
||||
lines.push("");
|
||||
this._sessionFileQueue = this._sessionFileQueue.then(() => import_fs.default.promises.appendFile(this._file, lines.join("\n")));
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
SessionLog
|
||||
});
|
||||
343
backend/node_modules/playwright/lib/mcp/browser/tab.js
generated
vendored
Normal file
343
backend/node_modules/playwright/lib/mcp/browser/tab.js
generated
vendored
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var tab_exports = {};
|
||||
__export(tab_exports, {
|
||||
Tab: () => Tab,
|
||||
TabEvents: () => TabEvents,
|
||||
renderModalStates: () => renderModalStates,
|
||||
shouldIncludeMessage: () => shouldIncludeMessage
|
||||
});
|
||||
module.exports = __toCommonJS(tab_exports);
|
||||
var import_events = require("events");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_utils2 = require("./tools/utils");
|
||||
var import_log = require("../log");
|
||||
var import_dialogs = require("./tools/dialogs");
|
||||
var import_files = require("./tools/files");
|
||||
var import_transform = require("../../transform/transform");
|
||||
const TabEvents = {
|
||||
modalState: "modalState"
|
||||
};
|
||||
class Tab extends import_events.EventEmitter {
|
||||
constructor(context, page, onPageClose) {
|
||||
super();
|
||||
this._lastHeader = { title: "about:blank", url: "about:blank", current: false };
|
||||
this._consoleMessages = [];
|
||||
this._downloads = [];
|
||||
this._requests = /* @__PURE__ */ new Set();
|
||||
this._modalStates = [];
|
||||
this._needsFullSnapshot = false;
|
||||
this._eventEntries = [];
|
||||
this._recentEventEntries = [];
|
||||
this.context = context;
|
||||
this.page = page;
|
||||
this._onPageClose = onPageClose;
|
||||
page.on("console", (event) => this._handleConsoleMessage(messageToConsoleMessage(event)));
|
||||
page.on("pageerror", (error) => this._handleConsoleMessage(pageErrorToConsoleMessage(error)));
|
||||
page.on("request", (request) => this._handleRequest(request));
|
||||
page.on("close", () => this._onClose());
|
||||
page.on("filechooser", (chooser) => {
|
||||
this.setModalState({
|
||||
type: "fileChooser",
|
||||
description: "File chooser",
|
||||
fileChooser: chooser,
|
||||
clearedBy: import_files.uploadFile.schema.name
|
||||
});
|
||||
});
|
||||
page.on("dialog", (dialog) => this._dialogShown(dialog));
|
||||
page.on("download", (download) => {
|
||||
void this._downloadStarted(download);
|
||||
});
|
||||
page.setDefaultNavigationTimeout(this.context.config.timeouts.navigation);
|
||||
page.setDefaultTimeout(this.context.config.timeouts.action);
|
||||
page[tabSymbol] = this;
|
||||
this._initializedPromise = this._initialize();
|
||||
}
|
||||
static forPage(page) {
|
||||
return page[tabSymbol];
|
||||
}
|
||||
static async collectConsoleMessages(page) {
|
||||
const result = [];
|
||||
const messages = await page.consoleMessages().catch(() => []);
|
||||
for (const message of messages)
|
||||
result.push(messageToConsoleMessage(message));
|
||||
const errors = await page.pageErrors().catch(() => []);
|
||||
for (const error of errors)
|
||||
result.push(pageErrorToConsoleMessage(error));
|
||||
return result;
|
||||
}
|
||||
async _initialize() {
|
||||
for (const message of await Tab.collectConsoleMessages(this.page))
|
||||
this._handleConsoleMessage(message);
|
||||
const requests = await this.page.requests().catch(() => []);
|
||||
for (const request of requests)
|
||||
this._requests.add(request);
|
||||
for (const initPage of this.context.config.browser.initPage || []) {
|
||||
try {
|
||||
const { default: func } = await (0, import_transform.requireOrImport)(initPage);
|
||||
await func({ page: this.page });
|
||||
} catch (e) {
|
||||
(0, import_log.logUnhandledError)(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
modalStates() {
|
||||
return this._modalStates;
|
||||
}
|
||||
setModalState(modalState) {
|
||||
this._modalStates.push(modalState);
|
||||
this.emit(TabEvents.modalState, modalState);
|
||||
}
|
||||
clearModalState(modalState) {
|
||||
this._modalStates = this._modalStates.filter((state) => state !== modalState);
|
||||
}
|
||||
_dialogShown(dialog) {
|
||||
this.setModalState({
|
||||
type: "dialog",
|
||||
description: `"${dialog.type()}" dialog with message "${dialog.message()}"`,
|
||||
dialog,
|
||||
clearedBy: import_dialogs.handleDialog.schema.name
|
||||
});
|
||||
}
|
||||
async _downloadStarted(download) {
|
||||
const entry = {
|
||||
download,
|
||||
finished: false,
|
||||
outputFile: await this.context.outputFile(download.suggestedFilename(), { origin: "web", title: "Saving download" })
|
||||
};
|
||||
this._downloads.push(entry);
|
||||
this._addLogEntry({ type: "download-start", wallTime: Date.now(), download: entry });
|
||||
await download.saveAs(entry.outputFile);
|
||||
entry.finished = true;
|
||||
this._addLogEntry({ type: "download-finish", wallTime: Date.now(), download: entry });
|
||||
}
|
||||
_clearCollectedArtifacts() {
|
||||
this._consoleMessages.length = 0;
|
||||
this._downloads.length = 0;
|
||||
this._requests.clear();
|
||||
this._eventEntries.length = 0;
|
||||
this._recentEventEntries.length = 0;
|
||||
}
|
||||
_handleRequest(request) {
|
||||
this._requests.add(request);
|
||||
this._addLogEntry({ type: "request", wallTime: Date.now(), request });
|
||||
}
|
||||
_handleConsoleMessage(message) {
|
||||
this._consoleMessages.push(message);
|
||||
this._addLogEntry({ type: "console", wallTime: Date.now(), message });
|
||||
}
|
||||
_addLogEntry(entry) {
|
||||
this._eventEntries.push(entry);
|
||||
this._recentEventEntries.push(entry);
|
||||
}
|
||||
_onClose() {
|
||||
this._clearCollectedArtifacts();
|
||||
this._onPageClose(this);
|
||||
}
|
||||
async headerSnapshot() {
|
||||
let title;
|
||||
await this._raceAgainstModalStates(async () => {
|
||||
title = await (0, import_utils2.callOnPageNoTrace)(this.page, (page) => page.title());
|
||||
});
|
||||
if (this._lastHeader.title !== title || this._lastHeader.url !== this.page.url() || this._lastHeader.current !== this.isCurrentTab()) {
|
||||
this._lastHeader = { title: title ?? "", url: this.page.url(), current: this.isCurrentTab() };
|
||||
return { ...this._lastHeader, changed: true };
|
||||
}
|
||||
return { ...this._lastHeader, changed: false };
|
||||
}
|
||||
isCurrentTab() {
|
||||
return this === this.context.currentTab();
|
||||
}
|
||||
async waitForLoadState(state, options) {
|
||||
await this._initializedPromise;
|
||||
await (0, import_utils2.callOnPageNoTrace)(this.page, (page) => page.waitForLoadState(state, options).catch(import_log.logUnhandledError));
|
||||
}
|
||||
async navigate(url) {
|
||||
await this._initializedPromise;
|
||||
this._clearCollectedArtifacts();
|
||||
const { promise: downloadEvent, abort: abortDownloadEvent } = (0, import_utils2.eventWaiter)(this.page, "download", 3e3);
|
||||
try {
|
||||
await this.page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
abortDownloadEvent();
|
||||
} catch (_e) {
|
||||
const e = _e;
|
||||
const mightBeDownload = e.message.includes("net::ERR_ABORTED") || e.message.includes("Download is starting");
|
||||
if (!mightBeDownload)
|
||||
throw e;
|
||||
const download = await downloadEvent;
|
||||
if (!download)
|
||||
throw e;
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
return;
|
||||
}
|
||||
await this.waitForLoadState("load", { timeout: 5e3 });
|
||||
}
|
||||
async consoleMessages(level) {
|
||||
await this._initializedPromise;
|
||||
return this._consoleMessages.filter((message) => shouldIncludeMessage(level, message.type));
|
||||
}
|
||||
async requests() {
|
||||
await this._initializedPromise;
|
||||
return this._requests;
|
||||
}
|
||||
async captureSnapshot() {
|
||||
await this._initializedPromise;
|
||||
let tabSnapshot;
|
||||
const modalStates = await this._raceAgainstModalStates(async () => {
|
||||
const snapshot = await this.page._snapshotForAI({ track: "response" });
|
||||
tabSnapshot = {
|
||||
ariaSnapshot: snapshot.full,
|
||||
ariaSnapshotDiff: this._needsFullSnapshot ? void 0 : snapshot.incremental,
|
||||
modalStates: [],
|
||||
events: []
|
||||
};
|
||||
});
|
||||
if (tabSnapshot) {
|
||||
tabSnapshot.events = this._recentEventEntries;
|
||||
this._recentEventEntries = [];
|
||||
}
|
||||
this._needsFullSnapshot = !tabSnapshot;
|
||||
return tabSnapshot ?? {
|
||||
ariaSnapshot: "",
|
||||
ariaSnapshotDiff: "",
|
||||
modalStates,
|
||||
events: []
|
||||
};
|
||||
}
|
||||
_javaScriptBlocked() {
|
||||
return this._modalStates.some((state) => state.type === "dialog");
|
||||
}
|
||||
async _raceAgainstModalStates(action) {
|
||||
if (this.modalStates().length)
|
||||
return this.modalStates();
|
||||
const promise = new import_utils.ManualPromise();
|
||||
const listener = (modalState) => promise.resolve([modalState]);
|
||||
this.once(TabEvents.modalState, listener);
|
||||
return await Promise.race([
|
||||
action().then(() => {
|
||||
this.off(TabEvents.modalState, listener);
|
||||
return [];
|
||||
}),
|
||||
promise
|
||||
]);
|
||||
}
|
||||
async waitForCompletion(callback) {
|
||||
await this._initializedPromise;
|
||||
await this._raceAgainstModalStates(() => (0, import_utils2.waitForCompletion)(this, callback));
|
||||
}
|
||||
async refLocator(params) {
|
||||
await this._initializedPromise;
|
||||
return (await this.refLocators([params]))[0];
|
||||
}
|
||||
async refLocators(params) {
|
||||
await this._initializedPromise;
|
||||
return Promise.all(params.map(async (param) => {
|
||||
try {
|
||||
let locator = this.page.locator(`aria-ref=${param.ref}`);
|
||||
if (param.element)
|
||||
locator = locator.describe(param.element);
|
||||
const { resolvedSelector } = await locator._resolveSelector();
|
||||
return { locator, resolved: (0, import_utils.asLocator)("javascript", resolvedSelector) };
|
||||
} catch (e) {
|
||||
throw new Error(`Ref ${param.ref} not found in the current page snapshot. Try capturing new snapshot.`);
|
||||
}
|
||||
}));
|
||||
}
|
||||
async waitForTimeout(time) {
|
||||
if (this._javaScriptBlocked()) {
|
||||
await new Promise((f) => setTimeout(f, time));
|
||||
return;
|
||||
}
|
||||
await (0, import_utils2.callOnPageNoTrace)(this.page, (page) => {
|
||||
return page.evaluate(() => new Promise((f) => setTimeout(f, 1e3))).catch(() => {
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
function messageToConsoleMessage(message) {
|
||||
return {
|
||||
type: message.type(),
|
||||
text: message.text(),
|
||||
toString: () => `[${message.type().toUpperCase()}] ${message.text()} @ ${message.location().url}:${message.location().lineNumber}`
|
||||
};
|
||||
}
|
||||
function pageErrorToConsoleMessage(errorOrValue) {
|
||||
if (errorOrValue instanceof Error) {
|
||||
return {
|
||||
type: "error",
|
||||
text: errorOrValue.message,
|
||||
toString: () => errorOrValue.stack || errorOrValue.message
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "error",
|
||||
text: String(errorOrValue),
|
||||
toString: () => String(errorOrValue)
|
||||
};
|
||||
}
|
||||
function renderModalStates(modalStates) {
|
||||
const result = [];
|
||||
if (modalStates.length === 0)
|
||||
result.push("- There is no modal state present");
|
||||
for (const state of modalStates)
|
||||
result.push(`- [${state.description}]: can be handled by the "${state.clearedBy}" tool`);
|
||||
return result;
|
||||
}
|
||||
const consoleMessageLevels = ["error", "warning", "info", "debug"];
|
||||
function shouldIncludeMessage(thresholdLevel, type) {
|
||||
const messageLevel = consoleLevelForMessageType(type);
|
||||
return consoleMessageLevels.indexOf(messageLevel) <= consoleMessageLevels.indexOf(thresholdLevel);
|
||||
}
|
||||
function consoleLevelForMessageType(type) {
|
||||
switch (type) {
|
||||
case "assert":
|
||||
case "error":
|
||||
return "error";
|
||||
case "warning":
|
||||
return "warning";
|
||||
case "count":
|
||||
case "dir":
|
||||
case "dirxml":
|
||||
case "info":
|
||||
case "log":
|
||||
case "table":
|
||||
case "time":
|
||||
case "timeEnd":
|
||||
return "info";
|
||||
case "clear":
|
||||
case "debug":
|
||||
case "endGroup":
|
||||
case "profile":
|
||||
case "profileEnd":
|
||||
case "startGroup":
|
||||
case "startGroupCollapsed":
|
||||
case "trace":
|
||||
return "debug";
|
||||
default:
|
||||
return "info";
|
||||
}
|
||||
}
|
||||
const tabSymbol = Symbol("tabSymbol");
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
Tab,
|
||||
TabEvents,
|
||||
renderModalStates,
|
||||
shouldIncludeMessage
|
||||
});
|
||||
84
backend/node_modules/playwright/lib/mcp/browser/tools.js
generated
vendored
Normal file
84
backend/node_modules/playwright/lib/mcp/browser/tools.js
generated
vendored
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var tools_exports = {};
|
||||
__export(tools_exports, {
|
||||
browserTools: () => browserTools,
|
||||
filteredTools: () => filteredTools
|
||||
});
|
||||
module.exports = __toCommonJS(tools_exports);
|
||||
var import_common = __toESM(require("./tools/common"));
|
||||
var import_console = __toESM(require("./tools/console"));
|
||||
var import_dialogs = __toESM(require("./tools/dialogs"));
|
||||
var import_evaluate = __toESM(require("./tools/evaluate"));
|
||||
var import_files = __toESM(require("./tools/files"));
|
||||
var import_form = __toESM(require("./tools/form"));
|
||||
var import_install = __toESM(require("./tools/install"));
|
||||
var import_keyboard = __toESM(require("./tools/keyboard"));
|
||||
var import_mouse = __toESM(require("./tools/mouse"));
|
||||
var import_navigate = __toESM(require("./tools/navigate"));
|
||||
var import_network = __toESM(require("./tools/network"));
|
||||
var import_open = __toESM(require("./tools/open"));
|
||||
var import_pdf = __toESM(require("./tools/pdf"));
|
||||
var import_runCode = __toESM(require("./tools/runCode"));
|
||||
var import_snapshot = __toESM(require("./tools/snapshot"));
|
||||
var import_screenshot = __toESM(require("./tools/screenshot"));
|
||||
var import_tabs = __toESM(require("./tools/tabs"));
|
||||
var import_tracing = __toESM(require("./tools/tracing"));
|
||||
var import_wait = __toESM(require("./tools/wait"));
|
||||
var import_verify = __toESM(require("./tools/verify"));
|
||||
const browserTools = [
|
||||
...import_common.default,
|
||||
...import_console.default,
|
||||
...import_dialogs.default,
|
||||
...import_evaluate.default,
|
||||
...import_files.default,
|
||||
...import_form.default,
|
||||
...import_install.default,
|
||||
...import_keyboard.default,
|
||||
...import_mouse.default,
|
||||
...import_navigate.default,
|
||||
...import_network.default,
|
||||
...import_open.default,
|
||||
...import_pdf.default,
|
||||
...import_runCode.default,
|
||||
...import_screenshot.default,
|
||||
...import_snapshot.default,
|
||||
...import_tabs.default,
|
||||
...import_tracing.default,
|
||||
...import_wait.default,
|
||||
...import_verify.default
|
||||
];
|
||||
function filteredTools(config) {
|
||||
return browserTools.filter((tool) => tool.capability.startsWith("core") || config.capabilities?.includes(tool.capability));
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
browserTools,
|
||||
filteredTools
|
||||
});
|
||||
65
backend/node_modules/playwright/lib/mcp/browser/tools/common.js
generated
vendored
Normal file
65
backend/node_modules/playwright/lib/mcp/browser/tools/common.js
generated
vendored
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var common_exports = {};
|
||||
__export(common_exports, {
|
||||
default: () => common_default
|
||||
});
|
||||
module.exports = __toCommonJS(common_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_response = require("../response");
|
||||
const close = (0, import_tool.defineTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_close",
|
||||
title: "Close browser",
|
||||
description: "Close the page",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
await context.closeBrowserContext();
|
||||
const result = (0, import_response.renderTabsMarkdown)([]);
|
||||
response.addTextResult(result.join("\n"));
|
||||
response.addCode(`await page.close()`);
|
||||
}
|
||||
});
|
||||
const resize = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_resize",
|
||||
title: "Resize browser window",
|
||||
description: "Resize the browser window",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
width: import_mcpBundle.z.number().describe("Width of the browser window"),
|
||||
height: import_mcpBundle.z.number().describe("Height of the browser window")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.addCode(`await page.setViewportSize({ width: ${params.width}, height: ${params.height} });`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.setViewportSize({ width: params.width, height: params.height });
|
||||
});
|
||||
}
|
||||
});
|
||||
var common_default = [
|
||||
close,
|
||||
resize
|
||||
];
|
||||
46
backend/node_modules/playwright/lib/mcp/browser/tools/console.js
generated
vendored
Normal file
46
backend/node_modules/playwright/lib/mcp/browser/tools/console.js
generated
vendored
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var console_exports = {};
|
||||
__export(console_exports, {
|
||||
default: () => console_default
|
||||
});
|
||||
module.exports = __toCommonJS(console_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const console = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_console_messages",
|
||||
title: "Get console messages",
|
||||
description: "Returns all console messages",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
level: import_mcpBundle.z.enum(["error", "warning", "info", "debug"]).default("info").describe('Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".'),
|
||||
filename: import_mcpBundle.z.string().optional().describe("Filename to save the console messages to. If not provided, messages are returned as text.")
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const messages = await tab.consoleMessages(params.level);
|
||||
const text = messages.map((message) => message.toString()).join("\n");
|
||||
await response.addResult({ text, suggestedFilename: params.filename });
|
||||
}
|
||||
});
|
||||
var console_default = [
|
||||
console
|
||||
];
|
||||
60
backend/node_modules/playwright/lib/mcp/browser/tools/dialogs.js
generated
vendored
Normal file
60
backend/node_modules/playwright/lib/mcp/browser/tools/dialogs.js
generated
vendored
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var dialogs_exports = {};
|
||||
__export(dialogs_exports, {
|
||||
default: () => dialogs_default,
|
||||
handleDialog: () => handleDialog
|
||||
});
|
||||
module.exports = __toCommonJS(dialogs_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const handleDialog = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_handle_dialog",
|
||||
title: "Handle a dialog",
|
||||
description: "Handle a dialog",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
accept: import_mcpBundle.z.boolean().describe("Whether to accept the dialog."),
|
||||
promptText: import_mcpBundle.z.string().optional().describe("The text of the prompt in case of a prompt dialog.")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const dialogState = tab.modalStates().find((state) => state.type === "dialog");
|
||||
if (!dialogState)
|
||||
throw new Error("No dialog visible");
|
||||
tab.clearModalState(dialogState);
|
||||
await tab.waitForCompletion(async () => {
|
||||
if (params.accept)
|
||||
await dialogState.dialog.accept(params.promptText);
|
||||
else
|
||||
await dialogState.dialog.dismiss();
|
||||
});
|
||||
},
|
||||
clearsModalState: "dialog"
|
||||
});
|
||||
var dialogs_default = [
|
||||
handleDialog
|
||||
];
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
handleDialog
|
||||
});
|
||||
61
backend/node_modules/playwright/lib/mcp/browser/tools/evaluate.js
generated
vendored
Normal file
61
backend/node_modules/playwright/lib/mcp/browser/tools/evaluate.js
generated
vendored
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var evaluate_exports = {};
|
||||
__export(evaluate_exports, {
|
||||
default: () => evaluate_default
|
||||
});
|
||||
module.exports = __toCommonJS(evaluate_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
const evaluateSchema = import_mcpBundle.z.object({
|
||||
function: import_mcpBundle.z.string().describe("() => { /* code */ } or (element) => { /* code */ } when element is provided"),
|
||||
element: import_mcpBundle.z.string().optional().describe("Human-readable element description used to obtain permission to interact with the element"),
|
||||
ref: import_mcpBundle.z.string().optional().describe("Exact target element reference from the page snapshot"),
|
||||
filename: import_mcpBundle.z.string().optional().describe("Filename to save the result to. If not provided, result is returned as JSON string.")
|
||||
});
|
||||
const evaluate = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_evaluate",
|
||||
title: "Evaluate JavaScript",
|
||||
description: "Evaluate JavaScript expression on page or element",
|
||||
inputSchema: evaluateSchema,
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
let locator;
|
||||
if (params.ref && params.element) {
|
||||
locator = await tab.refLocator({ ref: params.ref, element: params.element });
|
||||
response.addCode(`await page.${locator.resolved}.evaluate(${(0, import_utils.escapeWithQuotes)(params.function)});`);
|
||||
} else {
|
||||
response.addCode(`await page.evaluate(${(0, import_utils.escapeWithQuotes)(params.function)});`);
|
||||
}
|
||||
await tab.waitForCompletion(async () => {
|
||||
const receiver = locator?.locator ?? tab.page;
|
||||
const result = await receiver._evaluateFunction(params.function);
|
||||
const text = JSON.stringify(result, null, 2) || "undefined";
|
||||
await response.addResult({ text, suggestedFilename: params.filename });
|
||||
});
|
||||
}
|
||||
});
|
||||
var evaluate_default = [
|
||||
evaluate
|
||||
];
|
||||
58
backend/node_modules/playwright/lib/mcp/browser/tools/files.js
generated
vendored
Normal file
58
backend/node_modules/playwright/lib/mcp/browser/tools/files.js
generated
vendored
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var files_exports = {};
|
||||
__export(files_exports, {
|
||||
default: () => files_default,
|
||||
uploadFile: () => uploadFile
|
||||
});
|
||||
module.exports = __toCommonJS(files_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const uploadFile = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_file_upload",
|
||||
title: "Upload files",
|
||||
description: "Upload one or multiple files",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
paths: import_mcpBundle.z.array(import_mcpBundle.z.string()).optional().describe("The absolute paths to the files to upload. Can be single file or multiple files. If omitted, file chooser is cancelled.")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const modalState = tab.modalStates().find((state) => state.type === "fileChooser");
|
||||
if (!modalState)
|
||||
throw new Error("No file chooser visible");
|
||||
response.addCode(`await fileChooser.setFiles(${JSON.stringify(params.paths)})`);
|
||||
tab.clearModalState(modalState);
|
||||
await tab.waitForCompletion(async () => {
|
||||
if (params.paths)
|
||||
await modalState.fileChooser.setFiles(params.paths);
|
||||
});
|
||||
},
|
||||
clearsModalState: "fileChooser"
|
||||
});
|
||||
var files_default = [
|
||||
uploadFile
|
||||
];
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
uploadFile
|
||||
});
|
||||
63
backend/node_modules/playwright/lib/mcp/browser/tools/form.js
generated
vendored
Normal file
63
backend/node_modules/playwright/lib/mcp/browser/tools/form.js
generated
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var form_exports = {};
|
||||
__export(form_exports, {
|
||||
default: () => form_default
|
||||
});
|
||||
module.exports = __toCommonJS(form_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
const fillForm = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_fill_form",
|
||||
title: "Fill form",
|
||||
description: "Fill multiple form fields",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
fields: import_mcpBundle.z.array(import_mcpBundle.z.object({
|
||||
name: import_mcpBundle.z.string().describe("Human-readable field name"),
|
||||
type: import_mcpBundle.z.enum(["textbox", "checkbox", "radio", "combobox", "slider"]).describe("Type of the field"),
|
||||
ref: import_mcpBundle.z.string().describe("Exact target field reference from the page snapshot"),
|
||||
value: import_mcpBundle.z.string().describe("Value to fill in the field. If the field is a checkbox, the value should be `true` or `false`. If the field is a combobox, the value should be the text of the option.")
|
||||
})).describe("Fields to fill in")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
for (const field of params.fields) {
|
||||
const { locator, resolved } = await tab.refLocator({ element: field.name, ref: field.ref });
|
||||
const locatorSource = `await page.${resolved}`;
|
||||
if (field.type === "textbox" || field.type === "slider") {
|
||||
const secret = tab.context.lookupSecret(field.value);
|
||||
await locator.fill(secret.value);
|
||||
response.addCode(`${locatorSource}.fill(${secret.code});`);
|
||||
} else if (field.type === "checkbox" || field.type === "radio") {
|
||||
await locator.setChecked(field.value === "true");
|
||||
response.addCode(`${locatorSource}.setChecked(${field.value});`);
|
||||
} else if (field.type === "combobox") {
|
||||
await locator.selectOption({ label: field.value });
|
||||
response.addCode(`${locatorSource}.selectOption(${(0, import_utils.escapeWithQuotes)(field.value)});`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
var form_default = [
|
||||
fillForm
|
||||
];
|
||||
72
backend/node_modules/playwright/lib/mcp/browser/tools/install.js
generated
vendored
Normal file
72
backend/node_modules/playwright/lib/mcp/browser/tools/install.js
generated
vendored
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var install_exports = {};
|
||||
__export(install_exports, {
|
||||
default: () => install_default
|
||||
});
|
||||
module.exports = __toCommonJS(install_exports);
|
||||
var import_child_process = require("child_process");
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_response = require("../response");
|
||||
const install = (0, import_tool.defineTool)({
|
||||
capability: "core-install",
|
||||
schema: {
|
||||
name: "browser_install",
|
||||
title: "Install the browser specified in the config",
|
||||
description: "Install the browser specified in the config. Call this if you get an error about the browser not being installed.",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const channel = context.config.browser?.launchOptions?.channel ?? context.config.browser?.browserName ?? "chrome";
|
||||
const cliPath = import_path.default.join(require.resolve("playwright/package.json"), "../cli.js");
|
||||
const child = (0, import_child_process.fork)(cliPath, ["install", channel], {
|
||||
stdio: "pipe"
|
||||
});
|
||||
const output = [];
|
||||
child.stdout?.on("data", (data) => output.push(data.toString()));
|
||||
child.stderr?.on("data", (data) => output.push(data.toString()));
|
||||
await new Promise((resolve, reject) => {
|
||||
child.on("close", (code) => {
|
||||
if (code === 0)
|
||||
resolve();
|
||||
else
|
||||
reject(new Error(`Failed to install browser: ${output.join("")}`));
|
||||
});
|
||||
});
|
||||
const tabHeaders = await Promise.all(context.tabs().map((tab) => tab.headerSnapshot()));
|
||||
const result = (0, import_response.renderTabsMarkdown)(tabHeaders);
|
||||
response.addTextResult(result.join("\n"));
|
||||
}
|
||||
});
|
||||
var install_default = [
|
||||
install
|
||||
];
|
||||
107
backend/node_modules/playwright/lib/mcp/browser/tools/keyboard.js
generated
vendored
Normal file
107
backend/node_modules/playwright/lib/mcp/browser/tools/keyboard.js
generated
vendored
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var keyboard_exports = {};
|
||||
__export(keyboard_exports, {
|
||||
default: () => keyboard_default
|
||||
});
|
||||
module.exports = __toCommonJS(keyboard_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_snapshot = require("./snapshot");
|
||||
const pressKey = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_press_key",
|
||||
title: "Press a key",
|
||||
description: "Press a key on the keyboard",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
key: import_mcpBundle.z.string().describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.addCode(`// Press ${params.key}`);
|
||||
response.addCode(`await page.keyboard.press('${params.key}');`);
|
||||
await tab.page.keyboard.press(params.key);
|
||||
}
|
||||
});
|
||||
const pressSequentially = (0, import_tool.defineTabTool)({
|
||||
capability: "internal",
|
||||
schema: {
|
||||
name: "browser_press_sequentially",
|
||||
title: "Press sequentially",
|
||||
description: "Press text sequentially on the keyboard",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
text: import_mcpBundle.z.string().describe("Text to press sequentially"),
|
||||
submit: import_mcpBundle.z.boolean().optional().describe("Whether to submit entered text (press Enter after)")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.addCode(`// Press ${params.text}`);
|
||||
response.addCode(`await page.keyboard.type('${params.text}');`);
|
||||
await tab.page.keyboard.type(params.text);
|
||||
if (params.submit) {
|
||||
response.addCode(`await page.keyboard.press('Enter');`);
|
||||
response.setIncludeSnapshot();
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.keyboard.press("Enter");
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
const typeSchema = import_snapshot.elementSchema.extend({
|
||||
text: import_mcpBundle.z.string().describe("Text to type into the element"),
|
||||
submit: import_mcpBundle.z.boolean().optional().describe("Whether to submit entered text (press Enter after)"),
|
||||
slowly: import_mcpBundle.z.boolean().optional().describe("Whether to type one character at a time. Useful for triggering key handlers in the page. By default entire text is filled in at once.")
|
||||
});
|
||||
const type = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_type",
|
||||
title: "Type text",
|
||||
description: "Type text into editable element",
|
||||
inputSchema: typeSchema,
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const { locator, resolved } = await tab.refLocator(params);
|
||||
const secret = tab.context.lookupSecret(params.text);
|
||||
await tab.waitForCompletion(async () => {
|
||||
if (params.slowly) {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.${resolved}.pressSequentially(${secret.code});`);
|
||||
await locator.pressSequentially(secret.value);
|
||||
} else {
|
||||
response.addCode(`await page.${resolved}.fill(${secret.code});`);
|
||||
await locator.fill(secret.value);
|
||||
}
|
||||
if (params.submit) {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.${resolved}.press('Enter');`);
|
||||
await locator.press("Enter");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
var keyboard_default = [
|
||||
pressKey,
|
||||
type,
|
||||
pressSequentially
|
||||
];
|
||||
107
backend/node_modules/playwright/lib/mcp/browser/tools/mouse.js
generated
vendored
Normal file
107
backend/node_modules/playwright/lib/mcp/browser/tools/mouse.js
generated
vendored
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var mouse_exports = {};
|
||||
__export(mouse_exports, {
|
||||
default: () => mouse_default
|
||||
});
|
||||
module.exports = __toCommonJS(mouse_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const elementSchema = import_mcpBundle.z.object({
|
||||
element: import_mcpBundle.z.string().describe("Human-readable element description used to obtain permission to interact with the element")
|
||||
});
|
||||
const mouseMove = (0, import_tool.defineTabTool)({
|
||||
capability: "vision",
|
||||
schema: {
|
||||
name: "browser_mouse_move_xy",
|
||||
title: "Move mouse",
|
||||
description: "Move mouse to a given position",
|
||||
inputSchema: elementSchema.extend({
|
||||
x: import_mcpBundle.z.number().describe("X coordinate"),
|
||||
y: import_mcpBundle.z.number().describe("Y coordinate")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.addCode(`// Move mouse to (${params.x}, ${params.y})`);
|
||||
response.addCode(`await page.mouse.move(${params.x}, ${params.y});`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.mouse.move(params.x, params.y);
|
||||
});
|
||||
}
|
||||
});
|
||||
const mouseClick = (0, import_tool.defineTabTool)({
|
||||
capability: "vision",
|
||||
schema: {
|
||||
name: "browser_mouse_click_xy",
|
||||
title: "Click",
|
||||
description: "Click left mouse button at a given position",
|
||||
inputSchema: elementSchema.extend({
|
||||
x: import_mcpBundle.z.number().describe("X coordinate"),
|
||||
y: import_mcpBundle.z.number().describe("Y coordinate")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`// Click mouse at coordinates (${params.x}, ${params.y})`);
|
||||
response.addCode(`await page.mouse.move(${params.x}, ${params.y});`);
|
||||
response.addCode(`await page.mouse.down();`);
|
||||
response.addCode(`await page.mouse.up();`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.mouse.move(params.x, params.y);
|
||||
await tab.page.mouse.down();
|
||||
await tab.page.mouse.up();
|
||||
});
|
||||
}
|
||||
});
|
||||
const mouseDrag = (0, import_tool.defineTabTool)({
|
||||
capability: "vision",
|
||||
schema: {
|
||||
name: "browser_mouse_drag_xy",
|
||||
title: "Drag mouse",
|
||||
description: "Drag left mouse button to a given position",
|
||||
inputSchema: elementSchema.extend({
|
||||
startX: import_mcpBundle.z.number().describe("Start X coordinate"),
|
||||
startY: import_mcpBundle.z.number().describe("Start Y coordinate"),
|
||||
endX: import_mcpBundle.z.number().describe("End X coordinate"),
|
||||
endY: import_mcpBundle.z.number().describe("End Y coordinate")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`// Drag mouse from (${params.startX}, ${params.startY}) to (${params.endX}, ${params.endY})`);
|
||||
response.addCode(`await page.mouse.move(${params.startX}, ${params.startY});`);
|
||||
response.addCode(`await page.mouse.down();`);
|
||||
response.addCode(`await page.mouse.move(${params.endX}, ${params.endY});`);
|
||||
response.addCode(`await page.mouse.up();`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await tab.page.mouse.move(params.startX, params.startY);
|
||||
await tab.page.mouse.down();
|
||||
await tab.page.mouse.move(params.endX, params.endY);
|
||||
await tab.page.mouse.up();
|
||||
});
|
||||
}
|
||||
});
|
||||
var mouse_default = [
|
||||
mouseMove,
|
||||
mouseClick,
|
||||
mouseDrag
|
||||
];
|
||||
71
backend/node_modules/playwright/lib/mcp/browser/tools/navigate.js
generated
vendored
Normal file
71
backend/node_modules/playwright/lib/mcp/browser/tools/navigate.js
generated
vendored
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var navigate_exports = {};
|
||||
__export(navigate_exports, {
|
||||
default: () => navigate_default
|
||||
});
|
||||
module.exports = __toCommonJS(navigate_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const navigate = (0, import_tool.defineTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_navigate",
|
||||
title: "Navigate to a URL",
|
||||
description: "Navigate to a URL",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
url: import_mcpBundle.z.string().describe("The URL to navigate to")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const tab = await context.ensureTab();
|
||||
let url = params.url;
|
||||
try {
|
||||
new URL(url);
|
||||
} catch (e) {
|
||||
if (url.startsWith("localhost"))
|
||||
url = "http://" + url;
|
||||
else
|
||||
url = "https://" + url;
|
||||
}
|
||||
await tab.navigate(url);
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.goto('${params.url}');`);
|
||||
}
|
||||
});
|
||||
const goBack = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_navigate_back",
|
||||
title: "Go back",
|
||||
description: "Go back to the previous page",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
await tab.page.goBack();
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.goBack();`);
|
||||
}
|
||||
});
|
||||
var navigate_default = [
|
||||
navigate,
|
||||
goBack
|
||||
];
|
||||
63
backend/node_modules/playwright/lib/mcp/browser/tools/network.js
generated
vendored
Normal file
63
backend/node_modules/playwright/lib/mcp/browser/tools/network.js
generated
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var network_exports = {};
|
||||
__export(network_exports, {
|
||||
default: () => network_default
|
||||
});
|
||||
module.exports = __toCommonJS(network_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const requests = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_network_requests",
|
||||
title: "List network requests",
|
||||
description: "Returns all network requests since loading the page",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
includeStatic: import_mcpBundle.z.boolean().default(false).describe("Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false."),
|
||||
filename: import_mcpBundle.z.string().optional().describe("Filename to save the network requests to. If not provided, requests are returned as text.")
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const requests2 = await tab.requests();
|
||||
const text = [];
|
||||
for (const request of requests2) {
|
||||
const rendered = await renderRequest(request, params.includeStatic);
|
||||
if (rendered)
|
||||
text.push(rendered);
|
||||
}
|
||||
await response.addResult({ text: text.join("\n"), suggestedFilename: params.filename });
|
||||
}
|
||||
});
|
||||
async function renderRequest(request, includeStatic) {
|
||||
const response = request._hasResponse ? await request.response() : void 0;
|
||||
const isStaticRequest = ["document", "stylesheet", "image", "media", "font", "script", "manifest"].includes(request.resourceType());
|
||||
const isSuccessfulRequest = !response || response.status() < 400;
|
||||
if (isStaticRequest && isSuccessfulRequest && !includeStatic)
|
||||
return void 0;
|
||||
const result = [];
|
||||
result.push(`[${request.method().toUpperCase()}] ${request.url()}`);
|
||||
if (response)
|
||||
result.push(`=> [${response.status()}] ${response.statusText()}`);
|
||||
return result.join(" ");
|
||||
}
|
||||
var network_default = [
|
||||
requests
|
||||
];
|
||||
57
backend/node_modules/playwright/lib/mcp/browser/tools/open.js
generated
vendored
Normal file
57
backend/node_modules/playwright/lib/mcp/browser/tools/open.js
generated
vendored
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var open_exports = {};
|
||||
__export(open_exports, {
|
||||
default: () => open_default
|
||||
});
|
||||
module.exports = __toCommonJS(open_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const open = (0, import_tool.defineTool)({
|
||||
capability: "internal",
|
||||
schema: {
|
||||
name: "browser_open",
|
||||
title: "Open URL",
|
||||
description: "Open a URL in the browser",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
url: import_mcpBundle.z.string().describe("The URL to open"),
|
||||
headed: import_mcpBundle.z.boolean().optional().describe("Run browser in headed mode")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const forceHeadless = params.headed ? "headed" : "headless";
|
||||
const tab = await context.ensureTab({ forceHeadless });
|
||||
let url = params.url;
|
||||
try {
|
||||
new URL(url);
|
||||
} catch (e) {
|
||||
if (url.startsWith("localhost"))
|
||||
url = "http://" + url;
|
||||
else
|
||||
url = "https://" + url;
|
||||
}
|
||||
await tab.navigate(url);
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await page.goto('${params.url}');`);
|
||||
}
|
||||
});
|
||||
var open_default = [
|
||||
open
|
||||
];
|
||||
49
backend/node_modules/playwright/lib/mcp/browser/tools/pdf.js
generated
vendored
Normal file
49
backend/node_modules/playwright/lib/mcp/browser/tools/pdf.js
generated
vendored
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var pdf_exports = {};
|
||||
__export(pdf_exports, {
|
||||
default: () => pdf_default
|
||||
});
|
||||
module.exports = __toCommonJS(pdf_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
var import_utils2 = require("./utils");
|
||||
const pdfSchema = import_mcpBundle.z.object({
|
||||
filename: import_mcpBundle.z.string().optional().describe("File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified. Prefer relative file names to stay within the output directory.")
|
||||
});
|
||||
const pdf = (0, import_tool.defineTabTool)({
|
||||
capability: "pdf",
|
||||
schema: {
|
||||
name: "browser_pdf_save",
|
||||
title: "Save as PDF",
|
||||
description: "Save page as PDF",
|
||||
inputSchema: pdfSchema,
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const data = await tab.page.pdf();
|
||||
const suggestedFilename = params.filename ?? (0, import_utils2.dateAsFileName)("pdf");
|
||||
await response.addResult({ data, title: "Page as pdf", suggestedFilename });
|
||||
response.addCode(`await page.pdf(${(0, import_utils.formatObject)({ path: suggestedFilename })});`);
|
||||
}
|
||||
});
|
||||
var pdf_default = [
|
||||
pdf
|
||||
];
|
||||
78
backend/node_modules/playwright/lib/mcp/browser/tools/runCode.js
generated
vendored
Normal file
78
backend/node_modules/playwright/lib/mcp/browser/tools/runCode.js
generated
vendored
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var runCode_exports = {};
|
||||
__export(runCode_exports, {
|
||||
default: () => runCode_default
|
||||
});
|
||||
module.exports = __toCommonJS(runCode_exports);
|
||||
var import_vm = __toESM(require("vm"));
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const codeSchema = import_mcpBundle.z.object({
|
||||
code: import_mcpBundle.z.string().describe(`A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction. For example: \`async (page) => { await page.getByRole('button', { name: 'Submit' }).click(); return await page.title(); }\``),
|
||||
filename: import_mcpBundle.z.string().optional().describe("Filename to save the result to. If not provided, result is returned as JSON string.")
|
||||
});
|
||||
const runCode = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_run_code",
|
||||
title: "Run Playwright code",
|
||||
description: "Run Playwright code snippet",
|
||||
inputSchema: codeSchema,
|
||||
type: "action"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
response.addCode(`await (${params.code})(page);`);
|
||||
const __end__ = new import_utils.ManualPromise();
|
||||
const context = {
|
||||
page: tab.page,
|
||||
__end__
|
||||
};
|
||||
import_vm.default.createContext(context);
|
||||
await tab.waitForCompletion(async () => {
|
||||
const snippet = `(async () => {
|
||||
try {
|
||||
const result = await (${params.code})(page);
|
||||
__end__.resolve(JSON.stringify(result));
|
||||
} catch (e) {
|
||||
__end__.reject(e);
|
||||
}
|
||||
})()`;
|
||||
await import_vm.default.runInContext(snippet, context);
|
||||
const result = await __end__;
|
||||
if (typeof result === "string")
|
||||
await response.addResult({ text: result, suggestedFilename: params.filename });
|
||||
});
|
||||
}
|
||||
});
|
||||
var runCode_default = [
|
||||
runCode
|
||||
];
|
||||
93
backend/node_modules/playwright/lib/mcp/browser/tools/screenshot.js
generated
vendored
Normal file
93
backend/node_modules/playwright/lib/mcp/browser/tools/screenshot.js
generated
vendored
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var screenshot_exports = {};
|
||||
__export(screenshot_exports, {
|
||||
default: () => screenshot_default,
|
||||
scaleImageToFitMessage: () => scaleImageToFitMessage
|
||||
});
|
||||
module.exports = __toCommonJS(screenshot_exports);
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_utils2 = require("playwright-core/lib/utils");
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_utils3 = require("./utils");
|
||||
const screenshotSchema = import_mcpBundle.z.object({
|
||||
type: import_mcpBundle.z.enum(["png", "jpeg"]).default("png").describe("Image format for the screenshot. Default is png."),
|
||||
filename: import_mcpBundle.z.string().optional().describe("File name to save the screenshot to. Defaults to `page-{timestamp}.{png|jpeg}` if not specified. Prefer relative file names to stay within the output directory."),
|
||||
element: import_mcpBundle.z.string().optional().describe("Human-readable element description used to obtain permission to screenshot the element. If not provided, the screenshot will be taken of viewport. If element is provided, ref must be provided too."),
|
||||
ref: import_mcpBundle.z.string().optional().describe("Exact target element reference from the page snapshot. If not provided, the screenshot will be taken of viewport. If ref is provided, element must be provided too."),
|
||||
fullPage: import_mcpBundle.z.boolean().optional().describe("When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Cannot be used with element screenshots.")
|
||||
});
|
||||
const screenshot = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_take_screenshot",
|
||||
title: "Take a screenshot",
|
||||
description: `Take a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.`,
|
||||
inputSchema: screenshotSchema,
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
if (!!params.element !== !!params.ref)
|
||||
throw new Error("Both element and ref must be provided or neither.");
|
||||
if (params.fullPage && params.ref)
|
||||
throw new Error("fullPage cannot be used with element screenshots.");
|
||||
const fileType = params.type || "png";
|
||||
const options = {
|
||||
type: fileType,
|
||||
quality: fileType === "png" ? void 0 : 90,
|
||||
scale: "css",
|
||||
...params.fullPage !== void 0 && { fullPage: params.fullPage }
|
||||
};
|
||||
const isElementScreenshot = params.element && params.ref;
|
||||
const screenshotTarget = isElementScreenshot ? params.element : params.fullPage ? "full page" : "viewport";
|
||||
const ref = params.ref ? await tab.refLocator({ element: params.element || "", ref: params.ref }) : null;
|
||||
const data = ref ? await ref.locator.screenshot(options) : await tab.page.screenshot(options);
|
||||
const fileName = params.filename || (0, import_utils3.dateAsFileName)(fileType);
|
||||
response.addCode(`// Screenshot ${screenshotTarget} and save it as ${fileName}`);
|
||||
if (ref)
|
||||
response.addCode(`await page.${ref.resolved}.screenshot(${(0, import_utils2.formatObject)({ ...options, path: fileName })});`);
|
||||
else
|
||||
response.addCode(`await page.screenshot(${(0, import_utils2.formatObject)({ ...options, path: fileName })});`);
|
||||
await response.addResult({ data, title: `Screenshot of ${screenshotTarget}`, suggestedFilename: fileName });
|
||||
response.addImage({
|
||||
contentType: fileType === "png" ? "image/png" : "image/jpeg",
|
||||
data: scaleImageToFitMessage(data, fileType)
|
||||
});
|
||||
}
|
||||
});
|
||||
function scaleImageToFitMessage(buffer, imageType) {
|
||||
const image = imageType === "png" ? import_utilsBundle.PNG.sync.read(buffer) : import_utilsBundle.jpegjs.decode(buffer, { maxMemoryUsageInMB: 512 });
|
||||
const pixels = image.width * image.height;
|
||||
const shrink = Math.min(1568 / image.width, 1568 / image.height, Math.sqrt(1.15 * 1024 * 1024 / pixels));
|
||||
if (shrink > 1)
|
||||
return buffer;
|
||||
const width = image.width * shrink | 0;
|
||||
const height = image.height * shrink | 0;
|
||||
const scaledImage = (0, import_utils.scaleImageToSize)(image, { width, height });
|
||||
return imageType === "png" ? import_utilsBundle.PNG.sync.write(scaledImage) : import_utilsBundle.jpegjs.encode(scaledImage, 80).data;
|
||||
}
|
||||
var screenshot_default = [
|
||||
screenshot
|
||||
];
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
scaleImageToFitMessage
|
||||
});
|
||||
173
backend/node_modules/playwright/lib/mcp/browser/tools/snapshot.js
generated
vendored
Normal file
173
backend/node_modules/playwright/lib/mcp/browser/tools/snapshot.js
generated
vendored
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var snapshot_exports = {};
|
||||
__export(snapshot_exports, {
|
||||
default: () => snapshot_default,
|
||||
elementSchema: () => elementSchema
|
||||
});
|
||||
module.exports = __toCommonJS(snapshot_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
const snapshot = (0, import_tool.defineTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_snapshot",
|
||||
title: "Page snapshot",
|
||||
description: "Capture accessibility snapshot of the current page, this is better than screenshot",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
filename: import_mcpBundle.z.string().optional().describe("Save snapshot to markdown file instead of returning it in the response.")
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
await context.ensureTab();
|
||||
response.setIncludeFullSnapshot(params.filename);
|
||||
}
|
||||
});
|
||||
const elementSchema = import_mcpBundle.z.object({
|
||||
element: import_mcpBundle.z.string().optional().describe("Human-readable element description used to obtain permission to interact with the element"),
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference from the page snapshot")
|
||||
});
|
||||
const clickSchema = elementSchema.extend({
|
||||
doubleClick: import_mcpBundle.z.boolean().optional().describe("Whether to perform a double click instead of a single click"),
|
||||
button: import_mcpBundle.z.enum(["left", "right", "middle"]).optional().describe("Button to click, defaults to left"),
|
||||
modifiers: import_mcpBundle.z.array(import_mcpBundle.z.enum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"])).optional().describe("Modifier keys to press")
|
||||
});
|
||||
const click = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_click",
|
||||
title: "Click",
|
||||
description: "Perform click on a web page",
|
||||
inputSchema: clickSchema,
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const { locator, resolved } = await tab.refLocator(params);
|
||||
const options = {
|
||||
button: params.button,
|
||||
modifiers: params.modifiers
|
||||
};
|
||||
const formatted = (0, import_utils.formatObject)(options, " ", "oneline");
|
||||
const optionsAttr = formatted !== "{}" ? formatted : "";
|
||||
if (params.doubleClick)
|
||||
response.addCode(`await page.${resolved}.dblclick(${optionsAttr});`);
|
||||
else
|
||||
response.addCode(`await page.${resolved}.click(${optionsAttr});`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
if (params.doubleClick)
|
||||
await locator.dblclick(options);
|
||||
else
|
||||
await locator.click(options);
|
||||
});
|
||||
}
|
||||
});
|
||||
const drag = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_drag",
|
||||
title: "Drag mouse",
|
||||
description: "Perform drag and drop between two elements",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
startElement: import_mcpBundle.z.string().describe("Human-readable source element description used to obtain the permission to interact with the element"),
|
||||
startRef: import_mcpBundle.z.string().describe("Exact source element reference from the page snapshot"),
|
||||
endElement: import_mcpBundle.z.string().describe("Human-readable target element description used to obtain the permission to interact with the element"),
|
||||
endRef: import_mcpBundle.z.string().describe("Exact target element reference from the page snapshot")
|
||||
}),
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const [start, end] = await tab.refLocators([
|
||||
{ ref: params.startRef, element: params.startElement },
|
||||
{ ref: params.endRef, element: params.endElement }
|
||||
]);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await start.locator.dragTo(end.locator);
|
||||
});
|
||||
response.addCode(`await page.${start.resolved}.dragTo(page.${end.resolved});`);
|
||||
}
|
||||
});
|
||||
const hover = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_hover",
|
||||
title: "Hover mouse",
|
||||
description: "Hover over element on page",
|
||||
inputSchema: elementSchema,
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const { locator, resolved } = await tab.refLocator(params);
|
||||
response.addCode(`await page.${resolved}.hover();`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await locator.hover();
|
||||
});
|
||||
}
|
||||
});
|
||||
const selectOptionSchema = elementSchema.extend({
|
||||
values: import_mcpBundle.z.array(import_mcpBundle.z.string()).describe("Array of values to select in the dropdown. This can be a single value or multiple values.")
|
||||
});
|
||||
const selectOption = (0, import_tool.defineTabTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_select_option",
|
||||
title: "Select option",
|
||||
description: "Select an option in a dropdown",
|
||||
inputSchema: selectOptionSchema,
|
||||
type: "input"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
response.setIncludeSnapshot();
|
||||
const { locator, resolved } = await tab.refLocator(params);
|
||||
response.addCode(`await page.${resolved}.selectOption(${(0, import_utils.formatObject)(params.values)});`);
|
||||
await tab.waitForCompletion(async () => {
|
||||
await locator.selectOption(params.values);
|
||||
});
|
||||
}
|
||||
});
|
||||
const pickLocator = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_generate_locator",
|
||||
title: "Create locator for element",
|
||||
description: "Generate locator for the given element to use in tests",
|
||||
inputSchema: elementSchema,
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const { resolved } = await tab.refLocator(params);
|
||||
response.addTextResult(resolved);
|
||||
}
|
||||
});
|
||||
var snapshot_default = [
|
||||
snapshot,
|
||||
click,
|
||||
drag,
|
||||
hover,
|
||||
selectOption,
|
||||
pickLocator
|
||||
];
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
elementSchema
|
||||
});
|
||||
67
backend/node_modules/playwright/lib/mcp/browser/tools/tabs.js
generated
vendored
Normal file
67
backend/node_modules/playwright/lib/mcp/browser/tools/tabs.js
generated
vendored
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var tabs_exports = {};
|
||||
__export(tabs_exports, {
|
||||
default: () => tabs_default
|
||||
});
|
||||
module.exports = __toCommonJS(tabs_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
var import_response = require("../response");
|
||||
const browserTabs = (0, import_tool.defineTool)({
|
||||
capability: "core-tabs",
|
||||
schema: {
|
||||
name: "browser_tabs",
|
||||
title: "Manage tabs",
|
||||
description: "List, create, close, or select a browser tab.",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
action: import_mcpBundle.z.enum(["list", "new", "close", "select"]).describe("Operation to perform"),
|
||||
index: import_mcpBundle.z.number().optional().describe("Tab index, used for close/select. If omitted for close, current tab is closed.")
|
||||
}),
|
||||
type: "action"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
switch (params.action) {
|
||||
case "list": {
|
||||
await context.ensureTab();
|
||||
break;
|
||||
}
|
||||
case "new": {
|
||||
await context.newTab();
|
||||
break;
|
||||
}
|
||||
case "close": {
|
||||
await context.closeTab(params.index);
|
||||
break;
|
||||
}
|
||||
case "select": {
|
||||
if (params.index === void 0)
|
||||
throw new Error("Tab index is required");
|
||||
await context.selectTab(params.index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
const tabHeaders = await Promise.all(context.tabs().map((tab) => tab.headerSnapshot()));
|
||||
const result = (0, import_response.renderTabsMarkdown)(tabHeaders);
|
||||
response.addTextResult(result.join("\n"));
|
||||
}
|
||||
});
|
||||
var tabs_default = [
|
||||
browserTabs
|
||||
];
|
||||
47
backend/node_modules/playwright/lib/mcp/browser/tools/tool.js
generated
vendored
Normal file
47
backend/node_modules/playwright/lib/mcp/browser/tools/tool.js
generated
vendored
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var tool_exports = {};
|
||||
__export(tool_exports, {
|
||||
defineTabTool: () => defineTabTool,
|
||||
defineTool: () => defineTool
|
||||
});
|
||||
module.exports = __toCommonJS(tool_exports);
|
||||
function defineTool(tool) {
|
||||
return tool;
|
||||
}
|
||||
function defineTabTool(tool) {
|
||||
return {
|
||||
...tool,
|
||||
handle: async (context, params, response) => {
|
||||
const tab = await context.ensureTab();
|
||||
const modalStates = tab.modalStates().map((state) => state.type);
|
||||
if (tool.clearsModalState && !modalStates.includes(tool.clearsModalState))
|
||||
response.addError(`Error: The tool "${tool.schema.name}" can only be used when there is related modal state present.`);
|
||||
else if (!tool.clearsModalState && modalStates.length)
|
||||
response.addError(`Error: Tool "${tool.schema.name}" does not handle the modal state.`);
|
||||
else
|
||||
return tool.handle(tab, params, response);
|
||||
}
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
defineTabTool,
|
||||
defineTool
|
||||
});
|
||||
74
backend/node_modules/playwright/lib/mcp/browser/tools/tracing.js
generated
vendored
Normal file
74
backend/node_modules/playwright/lib/mcp/browser/tools/tracing.js
generated
vendored
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var tracing_exports = {};
|
||||
__export(tracing_exports, {
|
||||
default: () => tracing_default
|
||||
});
|
||||
module.exports = __toCommonJS(tracing_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const tracingStart = (0, import_tool.defineTool)({
|
||||
capability: "tracing",
|
||||
schema: {
|
||||
name: "browser_start_tracing",
|
||||
title: "Start tracing",
|
||||
description: "Start trace recording",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const browserContext = await context.ensureBrowserContext();
|
||||
const tracesDir = await context.outputFile(`traces`, { origin: "code", title: "Collecting trace" });
|
||||
const name = "trace-" + Date.now();
|
||||
await browserContext.tracing.start({
|
||||
name,
|
||||
screenshots: true,
|
||||
snapshots: true,
|
||||
_live: true
|
||||
});
|
||||
const traceLegend = `- Action log: ${tracesDir}/${name}.trace
|
||||
- Network log: ${tracesDir}/${name}.network
|
||||
- Resources with content by sha1: ${tracesDir}/resources`;
|
||||
response.addTextResult(`Tracing started, saving to ${tracesDir}.
|
||||
${traceLegend}`);
|
||||
browserContext.tracing[traceLegendSymbol] = traceLegend;
|
||||
}
|
||||
});
|
||||
const tracingStop = (0, import_tool.defineTool)({
|
||||
capability: "tracing",
|
||||
schema: {
|
||||
name: "browser_stop_tracing",
|
||||
title: "Stop tracing",
|
||||
description: "Stop trace recording",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
const browserContext = await context.ensureBrowserContext();
|
||||
await browserContext.tracing.stop();
|
||||
const traceLegend = browserContext.tracing[traceLegendSymbol];
|
||||
response.addTextResult(`Tracing stopped.
|
||||
${traceLegend}`);
|
||||
}
|
||||
});
|
||||
var tracing_default = [
|
||||
tracingStart,
|
||||
tracingStop
|
||||
];
|
||||
const traceLegendSymbol = Symbol("tracesDir");
|
||||
94
backend/node_modules/playwright/lib/mcp/browser/tools/utils.js
generated
vendored
Normal file
94
backend/node_modules/playwright/lib/mcp/browser/tools/utils.js
generated
vendored
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var utils_exports = {};
|
||||
__export(utils_exports, {
|
||||
callOnPageNoTrace: () => callOnPageNoTrace,
|
||||
dateAsFileName: () => dateAsFileName,
|
||||
eventWaiter: () => eventWaiter,
|
||||
waitForCompletion: () => waitForCompletion
|
||||
});
|
||||
module.exports = __toCommonJS(utils_exports);
|
||||
async function waitForCompletion(tab, callback) {
|
||||
const requests = [];
|
||||
const requestListener = (request) => requests.push(request);
|
||||
const disposeListeners = () => {
|
||||
tab.page.off("request", requestListener);
|
||||
};
|
||||
tab.page.on("request", requestListener);
|
||||
let result;
|
||||
try {
|
||||
result = await callback();
|
||||
await tab.waitForTimeout(500);
|
||||
} finally {
|
||||
disposeListeners();
|
||||
}
|
||||
const requestedNavigation = requests.some((request) => request.isNavigationRequest());
|
||||
if (requestedNavigation) {
|
||||
await tab.page.mainFrame().waitForLoadState("load", { timeout: 1e4 }).catch(() => {
|
||||
});
|
||||
return result;
|
||||
}
|
||||
const promises = [];
|
||||
for (const request of requests) {
|
||||
if (["document", "stylesheet", "script", "xhr", "fetch"].includes(request.resourceType()))
|
||||
promises.push(request.response().then((r) => r?.finished()).catch(() => {
|
||||
}));
|
||||
else
|
||||
promises.push(request.response().catch(() => {
|
||||
}));
|
||||
}
|
||||
const timeout = new Promise((resolve) => setTimeout(resolve, 5e3));
|
||||
await Promise.race([Promise.all(promises), timeout]);
|
||||
if (requests.length)
|
||||
await tab.waitForTimeout(500);
|
||||
return result;
|
||||
}
|
||||
async function callOnPageNoTrace(page, callback) {
|
||||
return await page._wrapApiCall(() => callback(page), { internal: true });
|
||||
}
|
||||
function dateAsFileName(extension) {
|
||||
const date = /* @__PURE__ */ new Date();
|
||||
return `page-${date.toISOString().replace(/[:.]/g, "-")}.${extension}`;
|
||||
}
|
||||
function eventWaiter(page, event, timeout) {
|
||||
const disposables = [];
|
||||
const eventPromise = new Promise((resolve, reject) => {
|
||||
page.on(event, resolve);
|
||||
disposables.push(() => page.off(event, resolve));
|
||||
});
|
||||
let abort;
|
||||
const abortPromise = new Promise((resolve, reject) => {
|
||||
abort = () => resolve(void 0);
|
||||
});
|
||||
const timeoutPromise = new Promise((f) => {
|
||||
const timeoutId = setTimeout(() => f(void 0), timeout);
|
||||
disposables.push(() => clearTimeout(timeoutId));
|
||||
});
|
||||
return {
|
||||
promise: Promise.race([eventPromise, abortPromise, timeoutPromise]).finally(() => disposables.forEach((dispose) => dispose())),
|
||||
abort
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
callOnPageNoTrace,
|
||||
dateAsFileName,
|
||||
eventWaiter,
|
||||
waitForCompletion
|
||||
});
|
||||
143
backend/node_modules/playwright/lib/mcp/browser/tools/verify.js
generated
vendored
Normal file
143
backend/node_modules/playwright/lib/mcp/browser/tools/verify.js
generated
vendored
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var verify_exports = {};
|
||||
__export(verify_exports, {
|
||||
default: () => verify_default
|
||||
});
|
||||
module.exports = __toCommonJS(verify_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_tool = require("./tool");
|
||||
const verifyElement = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_verify_element_visible",
|
||||
title: "Verify element visible",
|
||||
description: "Verify element is visible on the page",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
role: import_mcpBundle.z.string().describe('ROLE of the element. Can be found in the snapshot like this: `- {ROLE} "Accessible Name":`'),
|
||||
accessibleName: import_mcpBundle.z.string().describe('ACCESSIBLE_NAME of the element. Can be found in the snapshot like this: `- role "{ACCESSIBLE_NAME}"`')
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const locator = tab.page.getByRole(params.role, { name: params.accessibleName });
|
||||
if (await locator.count() === 0) {
|
||||
response.addError(`Element with role "${params.role}" and accessible name "${params.accessibleName}" not found`);
|
||||
return;
|
||||
}
|
||||
response.addCode(`await expect(page.getByRole(${(0, import_utils.escapeWithQuotes)(params.role)}, { name: ${(0, import_utils.escapeWithQuotes)(params.accessibleName)} })).toBeVisible();`);
|
||||
response.addTextResult("Done");
|
||||
}
|
||||
});
|
||||
const verifyText = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_verify_text_visible",
|
||||
title: "Verify text visible",
|
||||
description: `Verify text is visible on the page. Prefer ${verifyElement.schema.name} if possible.`,
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
text: import_mcpBundle.z.string().describe('TEXT to verify. Can be found in the snapshot like this: `- role "Accessible Name": {TEXT}` or like this: `- text: {TEXT}`')
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const locator = tab.page.getByText(params.text).filter({ visible: true });
|
||||
if (await locator.count() === 0) {
|
||||
response.addError("Text not found");
|
||||
return;
|
||||
}
|
||||
response.addCode(`await expect(page.getByText(${(0, import_utils.escapeWithQuotes)(params.text)})).toBeVisible();`);
|
||||
response.addTextResult("Done");
|
||||
}
|
||||
});
|
||||
const verifyList = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_verify_list_visible",
|
||||
title: "Verify list visible",
|
||||
description: "Verify list is visible on the page",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
element: import_mcpBundle.z.string().describe("Human-readable list description"),
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference that points to the list"),
|
||||
items: import_mcpBundle.z.array(import_mcpBundle.z.string()).describe("Items to verify")
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const { locator } = await tab.refLocator({ ref: params.ref, element: params.element });
|
||||
const itemTexts = [];
|
||||
for (const item of params.items) {
|
||||
const itemLocator = locator.getByText(item);
|
||||
if (await itemLocator.count() === 0) {
|
||||
response.addError(`Item "${item}" not found`);
|
||||
return;
|
||||
}
|
||||
itemTexts.push(await itemLocator.textContent());
|
||||
}
|
||||
const ariaSnapshot = `\`
|
||||
- list:
|
||||
${itemTexts.map((t) => ` - listitem: ${(0, import_utils.escapeWithQuotes)(t, '"')}`).join("\n")}
|
||||
\``;
|
||||
response.addCode(`await expect(page.locator('body')).toMatchAriaSnapshot(${ariaSnapshot});`);
|
||||
response.addTextResult("Done");
|
||||
}
|
||||
});
|
||||
const verifyValue = (0, import_tool.defineTabTool)({
|
||||
capability: "testing",
|
||||
schema: {
|
||||
name: "browser_verify_value",
|
||||
title: "Verify value",
|
||||
description: "Verify element value",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
type: import_mcpBundle.z.enum(["textbox", "checkbox", "radio", "combobox", "slider"]).describe("Type of the element"),
|
||||
element: import_mcpBundle.z.string().describe("Human-readable element description"),
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference that points to the element"),
|
||||
value: import_mcpBundle.z.string().describe('Value to verify. For checkbox, use "true" or "false".')
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (tab, params, response) => {
|
||||
const { locator, resolved } = await tab.refLocator({ ref: params.ref, element: params.element });
|
||||
const locatorSource = `page.${resolved}`;
|
||||
if (params.type === "textbox" || params.type === "slider" || params.type === "combobox") {
|
||||
const value = await locator.inputValue();
|
||||
if (value !== params.value) {
|
||||
response.addError(`Expected value "${params.value}", but got "${value}"`);
|
||||
return;
|
||||
}
|
||||
response.addCode(`await expect(${locatorSource}).toHaveValue(${(0, import_utils.escapeWithQuotes)(params.value)});`);
|
||||
} else if (params.type === "checkbox" || params.type === "radio") {
|
||||
const value = await locator.isChecked();
|
||||
if (value !== (params.value === "true")) {
|
||||
response.addError(`Expected value "${params.value}", but got "${value}"`);
|
||||
return;
|
||||
}
|
||||
const matcher = value ? "toBeChecked" : "not.toBeChecked";
|
||||
response.addCode(`await expect(${locatorSource}).${matcher}();`);
|
||||
}
|
||||
response.addTextResult("Done");
|
||||
}
|
||||
});
|
||||
var verify_default = [
|
||||
verifyElement,
|
||||
verifyText,
|
||||
verifyList,
|
||||
verifyValue
|
||||
];
|
||||
63
backend/node_modules/playwright/lib/mcp/browser/tools/wait.js
generated
vendored
Normal file
63
backend/node_modules/playwright/lib/mcp/browser/tools/wait.js
generated
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var wait_exports = {};
|
||||
__export(wait_exports, {
|
||||
default: () => wait_default
|
||||
});
|
||||
module.exports = __toCommonJS(wait_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_tool = require("./tool");
|
||||
const wait = (0, import_tool.defineTool)({
|
||||
capability: "core",
|
||||
schema: {
|
||||
name: "browser_wait_for",
|
||||
title: "Wait for",
|
||||
description: "Wait for text to appear or disappear or a specified time to pass",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
time: import_mcpBundle.z.number().optional().describe("The time to wait in seconds"),
|
||||
text: import_mcpBundle.z.string().optional().describe("The text to wait for"),
|
||||
textGone: import_mcpBundle.z.string().optional().describe("The text to wait for to disappear")
|
||||
}),
|
||||
type: "assertion"
|
||||
},
|
||||
handle: async (context, params, response) => {
|
||||
if (!params.text && !params.textGone && !params.time)
|
||||
throw new Error("Either time, text or textGone must be provided");
|
||||
if (params.time) {
|
||||
response.addCode(`await new Promise(f => setTimeout(f, ${params.time} * 1000));`);
|
||||
await new Promise((f) => setTimeout(f, Math.min(3e4, params.time * 1e3)));
|
||||
}
|
||||
const tab = context.currentTabOrDie();
|
||||
const locator = params.text ? tab.page.getByText(params.text).first() : void 0;
|
||||
const goneLocator = params.textGone ? tab.page.getByText(params.textGone).first() : void 0;
|
||||
if (goneLocator) {
|
||||
response.addCode(`await page.getByText(${JSON.stringify(params.textGone)}).first().waitFor({ state: 'hidden' });`);
|
||||
await goneLocator.waitFor({ state: "hidden" });
|
||||
}
|
||||
if (locator) {
|
||||
response.addCode(`await page.getByText(${JSON.stringify(params.text)}).first().waitFor({ state: 'visible' });`);
|
||||
await locator.waitFor({ state: "visible" });
|
||||
}
|
||||
response.addTextResult(`Waited for ${params.text || params.textGone || params.time}`);
|
||||
response.setIncludeSnapshot();
|
||||
}
|
||||
});
|
||||
var wait_default = [
|
||||
wait
|
||||
];
|
||||
44
backend/node_modules/playwright/lib/mcp/browser/watchdog.js
generated
vendored
Normal file
44
backend/node_modules/playwright/lib/mcp/browser/watchdog.js
generated
vendored
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var watchdog_exports = {};
|
||||
__export(watchdog_exports, {
|
||||
setupExitWatchdog: () => setupExitWatchdog
|
||||
});
|
||||
module.exports = __toCommonJS(watchdog_exports);
|
||||
var import_browserContextFactory = require("./browserContextFactory");
|
||||
var import_context = require("./context");
|
||||
function setupExitWatchdog() {
|
||||
let isExiting = false;
|
||||
const handleExit = async () => {
|
||||
if (isExiting)
|
||||
return;
|
||||
isExiting = true;
|
||||
setTimeout(() => process.exit(0), 15e3);
|
||||
await import_context.Context.disposeAll();
|
||||
await import_browserContextFactory.SharedContextFactory.dispose();
|
||||
process.exit(0);
|
||||
};
|
||||
process.stdin.on("close", handleExit);
|
||||
process.on("SIGINT", handleExit);
|
||||
process.on("SIGTERM", handleExit);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
setupExitWatchdog
|
||||
});
|
||||
16
backend/node_modules/playwright/lib/mcp/config.d.js
generated
vendored
Normal file
16
backend/node_modules/playwright/lib/mcp/config.d.js
generated
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var config_d_exports = {};
|
||||
module.exports = __toCommonJS(config_d_exports);
|
||||
351
backend/node_modules/playwright/lib/mcp/extension/cdpRelay.js
generated
vendored
Normal file
351
backend/node_modules/playwright/lib/mcp/extension/cdpRelay.js
generated
vendored
Normal file
|
|
@ -0,0 +1,351 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var cdpRelay_exports = {};
|
||||
__export(cdpRelay_exports, {
|
||||
CDPRelayServer: () => CDPRelayServer
|
||||
});
|
||||
module.exports = __toCommonJS(cdpRelay_exports);
|
||||
var import_child_process = require("child_process");
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_registry = require("playwright-core/lib/server/registry/index");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_http2 = require("../sdk/http");
|
||||
var import_log = require("../log");
|
||||
var protocol = __toESM(require("./protocol"));
|
||||
const debugLogger = (0, import_utilsBundle.debug)("pw:mcp:relay");
|
||||
class CDPRelayServer {
|
||||
constructor(server, browserChannel, userDataDir, executablePath) {
|
||||
this._playwrightConnection = null;
|
||||
this._extensionConnection = null;
|
||||
this._nextSessionId = 1;
|
||||
this._wsHost = (0, import_http2.addressToString)(server.address(), { protocol: "ws" });
|
||||
this._browserChannel = browserChannel;
|
||||
this._userDataDir = userDataDir;
|
||||
this._executablePath = executablePath;
|
||||
const uuid = crypto.randomUUID();
|
||||
this._cdpPath = `/cdp/${uuid}`;
|
||||
this._extensionPath = `/extension/${uuid}`;
|
||||
this._resetExtensionConnection();
|
||||
this._wss = new import_utilsBundle.wsServer({ server });
|
||||
this._wss.on("connection", this._onConnection.bind(this));
|
||||
}
|
||||
cdpEndpoint() {
|
||||
return `${this._wsHost}${this._cdpPath}`;
|
||||
}
|
||||
extensionEndpoint() {
|
||||
return `${this._wsHost}${this._extensionPath}`;
|
||||
}
|
||||
async ensureExtensionConnectionForMCPContext(clientInfo, abortSignal, toolName) {
|
||||
debugLogger("Ensuring extension connection for MCP context");
|
||||
if (this._extensionConnection)
|
||||
return;
|
||||
this._connectBrowser(clientInfo, toolName);
|
||||
debugLogger("Waiting for incoming extension connection");
|
||||
await Promise.race([
|
||||
this._extensionConnectionPromise,
|
||||
new Promise((_, reject) => setTimeout(() => {
|
||||
reject(new Error(`Extension connection timeout. Make sure the "Playwright MCP Bridge" extension is installed. See https://github.com/microsoft/playwright-mcp/blob/main/extension/README.md for installation instructions.`));
|
||||
}, process.env.PWMCP_TEST_CONNECTION_TIMEOUT ? parseInt(process.env.PWMCP_TEST_CONNECTION_TIMEOUT, 10) : 5e3)),
|
||||
new Promise((_, reject) => abortSignal.addEventListener("abort", reject))
|
||||
]);
|
||||
debugLogger("Extension connection established");
|
||||
}
|
||||
_connectBrowser(clientInfo, toolName) {
|
||||
const mcpRelayEndpoint = `${this._wsHost}${this._extensionPath}`;
|
||||
const url = new URL("chrome-extension://jakfalbnbhgkpmoaakfflhflbfpkailf/connect.html");
|
||||
url.searchParams.set("mcpRelayUrl", mcpRelayEndpoint);
|
||||
const client = {
|
||||
name: clientInfo.name,
|
||||
version: clientInfo.version
|
||||
};
|
||||
url.searchParams.set("client", JSON.stringify(client));
|
||||
url.searchParams.set("protocolVersion", process.env.PWMCP_TEST_PROTOCOL_VERSION ?? protocol.VERSION.toString());
|
||||
if (toolName)
|
||||
url.searchParams.set("newTab", String(toolName === "browser_navigate"));
|
||||
const token = process.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN;
|
||||
if (token)
|
||||
url.searchParams.set("token", token);
|
||||
const href = url.toString();
|
||||
let executablePath = this._executablePath;
|
||||
if (!executablePath) {
|
||||
const executableInfo = import_registry.registry.findExecutable(this._browserChannel);
|
||||
if (!executableInfo)
|
||||
throw new Error(`Unsupported channel: "${this._browserChannel}"`);
|
||||
executablePath = executableInfo.executablePath("javascript");
|
||||
if (!executablePath)
|
||||
throw new Error(`"${this._browserChannel}" executable not found. Make sure it is installed at a standard location.`);
|
||||
}
|
||||
const args = [];
|
||||
if (this._userDataDir)
|
||||
args.push(`--user-data-dir=${this._userDataDir}`);
|
||||
args.push(href);
|
||||
(0, import_child_process.spawn)(executablePath, args, {
|
||||
windowsHide: true,
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdio: "ignore"
|
||||
});
|
||||
}
|
||||
stop() {
|
||||
this.closeConnections("Server stopped");
|
||||
this._wss.close();
|
||||
}
|
||||
closeConnections(reason) {
|
||||
this._closePlaywrightConnection(reason);
|
||||
this._closeExtensionConnection(reason);
|
||||
}
|
||||
_onConnection(ws2, request) {
|
||||
const url = new URL(`http://localhost${request.url}`);
|
||||
debugLogger(`New connection to ${url.pathname}`);
|
||||
if (url.pathname === this._cdpPath) {
|
||||
this._handlePlaywrightConnection(ws2);
|
||||
} else if (url.pathname === this._extensionPath) {
|
||||
this._handleExtensionConnection(ws2);
|
||||
} else {
|
||||
debugLogger(`Invalid path: ${url.pathname}`);
|
||||
ws2.close(4004, "Invalid path");
|
||||
}
|
||||
}
|
||||
_handlePlaywrightConnection(ws2) {
|
||||
if (this._playwrightConnection) {
|
||||
debugLogger("Rejecting second Playwright connection");
|
||||
ws2.close(1e3, "Another CDP client already connected");
|
||||
return;
|
||||
}
|
||||
this._playwrightConnection = ws2;
|
||||
ws2.on("message", async (data) => {
|
||||
try {
|
||||
const message = JSON.parse(data.toString());
|
||||
await this._handlePlaywrightMessage(message);
|
||||
} catch (error) {
|
||||
debugLogger(`Error while handling Playwright message
|
||||
${data.toString()}
|
||||
`, error);
|
||||
}
|
||||
});
|
||||
ws2.on("close", () => {
|
||||
if (this._playwrightConnection !== ws2)
|
||||
return;
|
||||
this._playwrightConnection = null;
|
||||
this._closeExtensionConnection("Playwright client disconnected");
|
||||
debugLogger("Playwright WebSocket closed");
|
||||
});
|
||||
ws2.on("error", (error) => {
|
||||
debugLogger("Playwright WebSocket error:", error);
|
||||
});
|
||||
debugLogger("Playwright MCP connected");
|
||||
}
|
||||
_closeExtensionConnection(reason) {
|
||||
this._extensionConnection?.close(reason);
|
||||
this._extensionConnectionPromise.reject(new Error(reason));
|
||||
this._resetExtensionConnection();
|
||||
}
|
||||
_resetExtensionConnection() {
|
||||
this._connectedTabInfo = void 0;
|
||||
this._extensionConnection = null;
|
||||
this._extensionConnectionPromise = new import_utils.ManualPromise();
|
||||
void this._extensionConnectionPromise.catch(import_log.logUnhandledError);
|
||||
}
|
||||
_closePlaywrightConnection(reason) {
|
||||
if (this._playwrightConnection?.readyState === import_utilsBundle.ws.OPEN)
|
||||
this._playwrightConnection.close(1e3, reason);
|
||||
this._playwrightConnection = null;
|
||||
}
|
||||
_handleExtensionConnection(ws2) {
|
||||
if (this._extensionConnection) {
|
||||
ws2.close(1e3, "Another extension connection already established");
|
||||
return;
|
||||
}
|
||||
this._extensionConnection = new ExtensionConnection(ws2);
|
||||
this._extensionConnection.onclose = (c, reason) => {
|
||||
debugLogger("Extension WebSocket closed:", reason, c === this._extensionConnection);
|
||||
if (this._extensionConnection !== c)
|
||||
return;
|
||||
this._resetExtensionConnection();
|
||||
this._closePlaywrightConnection(`Extension disconnected: ${reason}`);
|
||||
};
|
||||
this._extensionConnection.onmessage = this._handleExtensionMessage.bind(this);
|
||||
this._extensionConnectionPromise.resolve();
|
||||
}
|
||||
_handleExtensionMessage(method, params) {
|
||||
switch (method) {
|
||||
case "forwardCDPEvent":
|
||||
const sessionId = params.sessionId || this._connectedTabInfo?.sessionId;
|
||||
this._sendToPlaywright({
|
||||
sessionId,
|
||||
method: params.method,
|
||||
params: params.params
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
async _handlePlaywrightMessage(message) {
|
||||
debugLogger("\u2190 Playwright:", `${message.method} (id=${message.id})`);
|
||||
const { id, sessionId, method, params } = message;
|
||||
try {
|
||||
const result = await this._handleCDPCommand(method, params, sessionId);
|
||||
this._sendToPlaywright({ id, sessionId, result });
|
||||
} catch (e) {
|
||||
debugLogger("Error in the extension:", e);
|
||||
this._sendToPlaywright({
|
||||
id,
|
||||
sessionId,
|
||||
error: { message: e.message }
|
||||
});
|
||||
}
|
||||
}
|
||||
async _handleCDPCommand(method, params, sessionId) {
|
||||
switch (method) {
|
||||
case "Browser.getVersion": {
|
||||
return {
|
||||
protocolVersion: "1.3",
|
||||
product: "Chrome/Extension-Bridge",
|
||||
userAgent: "CDP-Bridge-Server/1.0.0"
|
||||
};
|
||||
}
|
||||
case "Browser.setDownloadBehavior": {
|
||||
return {};
|
||||
}
|
||||
case "Target.setAutoAttach": {
|
||||
if (sessionId)
|
||||
break;
|
||||
const { targetInfo } = await this._extensionConnection.send("attachToTab", {});
|
||||
this._connectedTabInfo = {
|
||||
targetInfo,
|
||||
sessionId: `pw-tab-${this._nextSessionId++}`
|
||||
};
|
||||
debugLogger("Simulating auto-attach");
|
||||
this._sendToPlaywright({
|
||||
method: "Target.attachedToTarget",
|
||||
params: {
|
||||
sessionId: this._connectedTabInfo.sessionId,
|
||||
targetInfo: {
|
||||
...this._connectedTabInfo.targetInfo,
|
||||
attached: true
|
||||
},
|
||||
waitingForDebugger: false
|
||||
}
|
||||
});
|
||||
return {};
|
||||
}
|
||||
case "Target.getTargetInfo": {
|
||||
return this._connectedTabInfo?.targetInfo;
|
||||
}
|
||||
}
|
||||
return await this._forwardToExtension(method, params, sessionId);
|
||||
}
|
||||
async _forwardToExtension(method, params, sessionId) {
|
||||
if (!this._extensionConnection)
|
||||
throw new Error("Extension not connected");
|
||||
if (this._connectedTabInfo?.sessionId === sessionId)
|
||||
sessionId = void 0;
|
||||
return await this._extensionConnection.send("forwardCDPCommand", { sessionId, method, params });
|
||||
}
|
||||
_sendToPlaywright(message) {
|
||||
debugLogger("\u2192 Playwright:", `${message.method ?? `response(id=${message.id})`}`);
|
||||
this._playwrightConnection?.send(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
class ExtensionConnection {
|
||||
constructor(ws2) {
|
||||
this._callbacks = /* @__PURE__ */ new Map();
|
||||
this._lastId = 0;
|
||||
this._ws = ws2;
|
||||
this._ws.on("message", this._onMessage.bind(this));
|
||||
this._ws.on("close", this._onClose.bind(this));
|
||||
this._ws.on("error", this._onError.bind(this));
|
||||
}
|
||||
async send(method, params) {
|
||||
if (this._ws.readyState !== import_utilsBundle.ws.OPEN)
|
||||
throw new Error(`Unexpected WebSocket state: ${this._ws.readyState}`);
|
||||
const id = ++this._lastId;
|
||||
this._ws.send(JSON.stringify({ id, method, params }));
|
||||
const error = new Error(`Protocol error: ${method}`);
|
||||
return new Promise((resolve, reject) => {
|
||||
this._callbacks.set(id, { resolve, reject, error });
|
||||
});
|
||||
}
|
||||
close(message) {
|
||||
debugLogger("closing extension connection:", message);
|
||||
if (this._ws.readyState === import_utilsBundle.ws.OPEN)
|
||||
this._ws.close(1e3, message);
|
||||
}
|
||||
_onMessage(event) {
|
||||
const eventData = event.toString();
|
||||
let parsedJson;
|
||||
try {
|
||||
parsedJson = JSON.parse(eventData);
|
||||
} catch (e) {
|
||||
debugLogger(`<closing ws> Closing websocket due to malformed JSON. eventData=${eventData} e=${e?.message}`);
|
||||
this._ws.close();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this._handleParsedMessage(parsedJson);
|
||||
} catch (e) {
|
||||
debugLogger(`<closing ws> Closing websocket due to failed onmessage callback. eventData=${eventData} e=${e?.message}`);
|
||||
this._ws.close();
|
||||
}
|
||||
}
|
||||
_handleParsedMessage(object) {
|
||||
if (object.id && this._callbacks.has(object.id)) {
|
||||
const callback = this._callbacks.get(object.id);
|
||||
this._callbacks.delete(object.id);
|
||||
if (object.error) {
|
||||
const error = callback.error;
|
||||
error.message = object.error;
|
||||
callback.reject(error);
|
||||
} else {
|
||||
callback.resolve(object.result);
|
||||
}
|
||||
} else if (object.id) {
|
||||
debugLogger("\u2190 Extension: unexpected response", object);
|
||||
} else {
|
||||
this.onmessage?.(object.method, object.params);
|
||||
}
|
||||
}
|
||||
_onClose(event) {
|
||||
debugLogger(`<ws closed> code=${event.code} reason=${event.reason}`);
|
||||
this._dispose();
|
||||
this.onclose?.(this, event.reason);
|
||||
}
|
||||
_onError(event) {
|
||||
debugLogger(`<ws error> message=${event.message} type=${event.type} target=${event.target}`);
|
||||
this._dispose();
|
||||
}
|
||||
_dispose() {
|
||||
for (const callback of this._callbacks.values())
|
||||
callback.reject(new Error("WebSocket closed"));
|
||||
this._callbacks.clear();
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
CDPRelayServer
|
||||
});
|
||||
76
backend/node_modules/playwright/lib/mcp/extension/extensionContextFactory.js
generated
vendored
Normal file
76
backend/node_modules/playwright/lib/mcp/extension/extensionContextFactory.js
generated
vendored
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var extensionContextFactory_exports = {};
|
||||
__export(extensionContextFactory_exports, {
|
||||
ExtensionContextFactory: () => ExtensionContextFactory
|
||||
});
|
||||
module.exports = __toCommonJS(extensionContextFactory_exports);
|
||||
var playwright = __toESM(require("playwright-core"));
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_cdpRelay = require("./cdpRelay");
|
||||
const debugLogger = (0, import_utilsBundle.debug)("pw:mcp:relay");
|
||||
class ExtensionContextFactory {
|
||||
constructor(browserChannel, userDataDir, executablePath) {
|
||||
this._browserChannel = browserChannel;
|
||||
this._userDataDir = userDataDir;
|
||||
this._executablePath = executablePath;
|
||||
}
|
||||
async createContext(clientInfo, abortSignal, options) {
|
||||
const browser = await this._obtainBrowser(clientInfo, abortSignal, options?.toolName);
|
||||
return {
|
||||
browserContext: browser.contexts()[0],
|
||||
close: async () => {
|
||||
debugLogger("close() called for browser context");
|
||||
await browser.close();
|
||||
}
|
||||
};
|
||||
}
|
||||
async _obtainBrowser(clientInfo, abortSignal, toolName) {
|
||||
const relay = await this._startRelay(abortSignal);
|
||||
await relay.ensureExtensionConnectionForMCPContext(clientInfo, abortSignal, toolName);
|
||||
return await playwright.chromium.connectOverCDP(relay.cdpEndpoint(), { isLocal: true });
|
||||
}
|
||||
async _startRelay(abortSignal) {
|
||||
const httpServer = (0, import_utils.createHttpServer)();
|
||||
await (0, import_utils.startHttpServer)(httpServer, {});
|
||||
if (abortSignal.aborted) {
|
||||
httpServer.close();
|
||||
throw new Error(abortSignal.reason);
|
||||
}
|
||||
const cdpRelayServer = new import_cdpRelay.CDPRelayServer(httpServer, this._browserChannel, this._userDataDir, this._executablePath);
|
||||
abortSignal.addEventListener("abort", () => cdpRelayServer.stop());
|
||||
debugLogger(`CDP relay server started, extension endpoint: ${cdpRelayServer.extensionEndpoint()}.`);
|
||||
return cdpRelayServer;
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
ExtensionContextFactory
|
||||
});
|
||||
28
backend/node_modules/playwright/lib/mcp/extension/protocol.js
generated
vendored
Normal file
28
backend/node_modules/playwright/lib/mcp/extension/protocol.js
generated
vendored
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var protocol_exports = {};
|
||||
__export(protocol_exports, {
|
||||
VERSION: () => VERSION
|
||||
});
|
||||
module.exports = __toCommonJS(protocol_exports);
|
||||
const VERSION = 1;
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
VERSION
|
||||
});
|
||||
61
backend/node_modules/playwright/lib/mcp/index.js
generated
vendored
Normal file
61
backend/node_modules/playwright/lib/mcp/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var mcp_exports = {};
|
||||
__export(mcp_exports, {
|
||||
createConnection: () => createConnection
|
||||
});
|
||||
module.exports = __toCommonJS(mcp_exports);
|
||||
var import_browserServerBackend = require("./browser/browserServerBackend");
|
||||
var import_config = require("./browser/config");
|
||||
var import_browserContextFactory = require("./browser/browserContextFactory");
|
||||
var mcpServer = __toESM(require("./sdk/server"));
|
||||
const packageJSON = require("../../package.json");
|
||||
async function createConnection(userConfig = {}, contextGetter) {
|
||||
const config = await (0, import_config.resolveConfig)(userConfig);
|
||||
const factory = contextGetter ? new SimpleBrowserContextFactory(contextGetter) : (0, import_browserContextFactory.contextFactory)(config);
|
||||
return mcpServer.createServer("Playwright", packageJSON.version, new import_browserServerBackend.BrowserServerBackend(config, factory), false);
|
||||
}
|
||||
class SimpleBrowserContextFactory {
|
||||
constructor(contextGetter) {
|
||||
this.name = "custom";
|
||||
this.description = "Connect to a browser using a custom context getter";
|
||||
this._contextGetter = contextGetter;
|
||||
}
|
||||
async createContext() {
|
||||
const browserContext = await this._contextGetter();
|
||||
return {
|
||||
browserContext,
|
||||
close: () => browserContext.close()
|
||||
};
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
createConnection
|
||||
});
|
||||
35
backend/node_modules/playwright/lib/mcp/log.js
generated
vendored
Normal file
35
backend/node_modules/playwright/lib/mcp/log.js
generated
vendored
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var log_exports = {};
|
||||
__export(log_exports, {
|
||||
logUnhandledError: () => logUnhandledError,
|
||||
testDebug: () => testDebug
|
||||
});
|
||||
module.exports = __toCommonJS(log_exports);
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
const errorDebug = (0, import_utilsBundle.debug)("pw:mcp:error");
|
||||
function logUnhandledError(error) {
|
||||
errorDebug(error);
|
||||
}
|
||||
const testDebug = (0, import_utilsBundle.debug)("pw:mcp:test");
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
logUnhandledError,
|
||||
testDebug
|
||||
});
|
||||
111
backend/node_modules/playwright/lib/mcp/program.js
generated
vendored
Normal file
111
backend/node_modules/playwright/lib/mcp/program.js
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
28
backend/node_modules/playwright/lib/mcp/sdk/exports.js
generated
vendored
Normal file
28
backend/node_modules/playwright/lib/mcp/sdk/exports.js
generated
vendored
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var exports_exports = {};
|
||||
module.exports = __toCommonJS(exports_exports);
|
||||
__reExport(exports_exports, require("./inProcessTransport"), module.exports);
|
||||
__reExport(exports_exports, require("./server"), module.exports);
|
||||
__reExport(exports_exports, require("./tool"), module.exports);
|
||||
__reExport(exports_exports, require("./http"), module.exports);
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
...require("./inProcessTransport"),
|
||||
...require("./server"),
|
||||
...require("./tool"),
|
||||
...require("./http")
|
||||
});
|
||||
152
backend/node_modules/playwright/lib/mcp/sdk/http.js
generated
vendored
Normal file
152
backend/node_modules/playwright/lib/mcp/sdk/http.js
generated
vendored
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var http_exports = {};
|
||||
__export(http_exports, {
|
||||
addressToString: () => addressToString,
|
||||
startMcpHttpServer: () => startMcpHttpServer
|
||||
});
|
||||
module.exports = __toCommonJS(http_exports);
|
||||
var import_assert = __toESM(require("assert"));
|
||||
var import_crypto = __toESM(require("crypto"));
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var mcpBundle = __toESM(require("playwright-core/lib/mcpBundle"));
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var mcpServer = __toESM(require("./server"));
|
||||
const testDebug = (0, import_utilsBundle.debug)("pw:mcp:test");
|
||||
async function startMcpHttpServer(config, serverBackendFactory, allowedHosts) {
|
||||
const httpServer = (0, import_utils.createHttpServer)();
|
||||
await (0, import_utils.startHttpServer)(httpServer, config);
|
||||
return await installHttpTransport(httpServer, serverBackendFactory, allowedHosts);
|
||||
}
|
||||
function addressToString(address, options) {
|
||||
(0, import_assert.default)(address, "Could not bind server socket");
|
||||
if (typeof address === "string")
|
||||
throw new Error("Unexpected address type: " + address);
|
||||
let host = address.family === "IPv4" ? address.address : `[${address.address}]`;
|
||||
if (options.normalizeLoopback && (host === "0.0.0.0" || host === "[::]" || host === "[::1]" || host === "127.0.0.1"))
|
||||
host = "localhost";
|
||||
return `${options.protocol}://${host}:${address.port}`;
|
||||
}
|
||||
async function installHttpTransport(httpServer, serverBackendFactory, allowedHosts) {
|
||||
const url = addressToString(httpServer.address(), { protocol: "http", normalizeLoopback: true });
|
||||
const host = new URL(url).host;
|
||||
allowedHosts = (allowedHosts || [host]).map((h) => h.toLowerCase());
|
||||
const allowAnyHost = allowedHosts.includes("*");
|
||||
const sseSessions = /* @__PURE__ */ new Map();
|
||||
const streamableSessions = /* @__PURE__ */ new Map();
|
||||
httpServer.on("request", async (req, res) => {
|
||||
if (!allowAnyHost) {
|
||||
const host2 = req.headers.host?.toLowerCase();
|
||||
if (!host2) {
|
||||
res.statusCode = 400;
|
||||
return res.end("Missing host");
|
||||
}
|
||||
if (!allowedHosts.includes(host2)) {
|
||||
res.statusCode = 403;
|
||||
return res.end("Access is only allowed at " + allowedHosts.join(", "));
|
||||
}
|
||||
}
|
||||
const url2 = new URL(`http://localhost${req.url}`);
|
||||
if (url2.pathname === "/killkillkill" && req.method === "GET") {
|
||||
res.statusCode = 200;
|
||||
res.end("Killing process");
|
||||
process.emit("SIGINT");
|
||||
return;
|
||||
}
|
||||
if (url2.pathname.startsWith("/sse"))
|
||||
await handleSSE(serverBackendFactory, req, res, url2, sseSessions);
|
||||
else
|
||||
await handleStreamable(serverBackendFactory, req, res, streamableSessions);
|
||||
});
|
||||
return url;
|
||||
}
|
||||
async function handleSSE(serverBackendFactory, req, res, url, sessions) {
|
||||
if (req.method === "POST") {
|
||||
const sessionId = url.searchParams.get("sessionId");
|
||||
if (!sessionId) {
|
||||
res.statusCode = 400;
|
||||
return res.end("Missing sessionId");
|
||||
}
|
||||
const transport = sessions.get(sessionId);
|
||||
if (!transport) {
|
||||
res.statusCode = 404;
|
||||
return res.end("Session not found");
|
||||
}
|
||||
return await transport.handlePostMessage(req, res);
|
||||
} else if (req.method === "GET") {
|
||||
const transport = new mcpBundle.SSEServerTransport("/sse", res);
|
||||
sessions.set(transport.sessionId, transport);
|
||||
testDebug(`create SSE session: ${transport.sessionId}`);
|
||||
await mcpServer.connect(serverBackendFactory, transport, false);
|
||||
res.on("close", () => {
|
||||
testDebug(`delete SSE session: ${transport.sessionId}`);
|
||||
sessions.delete(transport.sessionId);
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.statusCode = 405;
|
||||
res.end("Method not allowed");
|
||||
}
|
||||
async function handleStreamable(serverBackendFactory, req, res, sessions) {
|
||||
const sessionId = req.headers["mcp-session-id"];
|
||||
if (sessionId) {
|
||||
const transport = sessions.get(sessionId);
|
||||
if (!transport) {
|
||||
res.statusCode = 404;
|
||||
res.end("Session not found");
|
||||
return;
|
||||
}
|
||||
return await transport.handleRequest(req, res);
|
||||
}
|
||||
if (req.method === "POST") {
|
||||
const transport = new mcpBundle.StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: () => import_crypto.default.randomUUID(),
|
||||
onsessioninitialized: async (sessionId2) => {
|
||||
testDebug(`create http session: ${transport.sessionId}`);
|
||||
await mcpServer.connect(serverBackendFactory, transport, true);
|
||||
sessions.set(sessionId2, transport);
|
||||
}
|
||||
});
|
||||
transport.onclose = () => {
|
||||
if (!transport.sessionId)
|
||||
return;
|
||||
sessions.delete(transport.sessionId);
|
||||
testDebug(`delete http session: ${transport.sessionId}`);
|
||||
};
|
||||
await transport.handleRequest(req, res);
|
||||
return;
|
||||
}
|
||||
res.statusCode = 400;
|
||||
res.end("Invalid request");
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
addressToString,
|
||||
startMcpHttpServer
|
||||
});
|
||||
71
backend/node_modules/playwright/lib/mcp/sdk/inProcessTransport.js
generated
vendored
Normal file
71
backend/node_modules/playwright/lib/mcp/sdk/inProcessTransport.js
generated
vendored
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var inProcessTransport_exports = {};
|
||||
__export(inProcessTransport_exports, {
|
||||
InProcessTransport: () => InProcessTransport
|
||||
});
|
||||
module.exports = __toCommonJS(inProcessTransport_exports);
|
||||
class InProcessTransport {
|
||||
constructor(server) {
|
||||
this._connected = false;
|
||||
this._server = server;
|
||||
this._serverTransport = new InProcessServerTransport(this);
|
||||
}
|
||||
async start() {
|
||||
if (this._connected)
|
||||
throw new Error("InprocessTransport already started!");
|
||||
await this._server.connect(this._serverTransport);
|
||||
this._connected = true;
|
||||
}
|
||||
async send(message, options) {
|
||||
if (!this._connected)
|
||||
throw new Error("Transport not connected");
|
||||
this._serverTransport._receiveFromClient(message);
|
||||
}
|
||||
async close() {
|
||||
if (this._connected) {
|
||||
this._connected = false;
|
||||
this.onclose?.();
|
||||
this._serverTransport.onclose?.();
|
||||
}
|
||||
}
|
||||
_receiveFromServer(message, extra) {
|
||||
this.onmessage?.(message, extra);
|
||||
}
|
||||
}
|
||||
class InProcessServerTransport {
|
||||
constructor(clientTransport) {
|
||||
this._clientTransport = clientTransport;
|
||||
}
|
||||
async start() {
|
||||
}
|
||||
async send(message, options) {
|
||||
this._clientTransport._receiveFromServer(message);
|
||||
}
|
||||
async close() {
|
||||
this.onclose?.();
|
||||
}
|
||||
_receiveFromClient(message) {
|
||||
this.onmessage?.(message);
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
InProcessTransport
|
||||
});
|
||||
223
backend/node_modules/playwright/lib/mcp/sdk/server.js
generated
vendored
Normal file
223
backend/node_modules/playwright/lib/mcp/sdk/server.js
generated
vendored
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var server_exports = {};
|
||||
__export(server_exports, {
|
||||
allRootPaths: () => allRootPaths,
|
||||
connect: () => connect,
|
||||
createServer: () => createServer,
|
||||
firstRootPath: () => firstRootPath,
|
||||
start: () => start,
|
||||
wrapInClient: () => wrapInClient,
|
||||
wrapInProcess: () => wrapInProcess
|
||||
});
|
||||
module.exports = __toCommonJS(server_exports);
|
||||
var import_url = require("url");
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var mcpBundle = __toESM(require("playwright-core/lib/mcpBundle"));
|
||||
var import_http = require("./http");
|
||||
var import_inProcessTransport = require("./inProcessTransport");
|
||||
const serverDebug = (0, import_utilsBundle.debug)("pw:mcp:server");
|
||||
const serverDebugResponse = (0, import_utilsBundle.debug)("pw:mcp:server:response");
|
||||
async function connect(factory, transport, runHeartbeat) {
|
||||
const server = createServer(factory.name, factory.version, factory.create(), runHeartbeat);
|
||||
await server.connect(transport);
|
||||
}
|
||||
function wrapInProcess(backend) {
|
||||
const server = createServer("Internal", "0.0.0", backend, false);
|
||||
return new import_inProcessTransport.InProcessTransport(server);
|
||||
}
|
||||
async function wrapInClient(backend, options) {
|
||||
const server = createServer("Internal", "0.0.0", backend, false);
|
||||
const transport = new import_inProcessTransport.InProcessTransport(server);
|
||||
const client = new mcpBundle.Client({ name: options.name, version: options.version });
|
||||
await client.connect(transport);
|
||||
await client.ping();
|
||||
return client;
|
||||
}
|
||||
function createServer(name, version, backend, runHeartbeat) {
|
||||
const server = new mcpBundle.Server({ name, version }, {
|
||||
capabilities: {
|
||||
tools: {}
|
||||
}
|
||||
});
|
||||
server.setRequestHandler(mcpBundle.ListToolsRequestSchema, async () => {
|
||||
serverDebug("listTools");
|
||||
const tools = await backend.listTools();
|
||||
return { tools };
|
||||
});
|
||||
let initializePromise;
|
||||
server.setRequestHandler(mcpBundle.CallToolRequestSchema, async (request, extra) => {
|
||||
serverDebug("callTool", request);
|
||||
const progressToken = request.params._meta?.progressToken;
|
||||
let progressCounter = 0;
|
||||
const progress = progressToken ? (params) => {
|
||||
extra.sendNotification({
|
||||
method: "notifications/progress",
|
||||
params: {
|
||||
progressToken,
|
||||
progress: params.progress ?? ++progressCounter,
|
||||
total: params.total,
|
||||
message: params.message
|
||||
}
|
||||
}).catch(serverDebug);
|
||||
} : () => {
|
||||
};
|
||||
try {
|
||||
if (!initializePromise)
|
||||
initializePromise = initializeServer(server, backend, runHeartbeat);
|
||||
await initializePromise;
|
||||
const toolResult = await backend.callTool(request.params.name, request.params.arguments || {}, progress);
|
||||
const mergedResult = mergeTextParts(toolResult);
|
||||
serverDebugResponse("callResult", mergedResult);
|
||||
return mergedResult;
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{ type: "text", text: "### Result\n" + String(error) }],
|
||||
isError: true
|
||||
};
|
||||
}
|
||||
});
|
||||
addServerListener(server, "close", () => backend.serverClosed?.(server));
|
||||
return server;
|
||||
}
|
||||
const initializeServer = async (server, backend, runHeartbeat) => {
|
||||
const capabilities = server.getClientCapabilities();
|
||||
let clientRoots = [];
|
||||
if (capabilities?.roots) {
|
||||
const { roots } = await server.listRoots().catch((e) => {
|
||||
serverDebug(e);
|
||||
return { roots: [] };
|
||||
});
|
||||
clientRoots = roots;
|
||||
}
|
||||
const clientInfo = {
|
||||
name: server.getClientVersion()?.name ?? "unknown",
|
||||
version: server.getClientVersion()?.version ?? "unknown",
|
||||
roots: clientRoots,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
await backend.initialize?.(clientInfo);
|
||||
if (runHeartbeat)
|
||||
startHeartbeat(server);
|
||||
};
|
||||
const startHeartbeat = (server) => {
|
||||
const beat = () => {
|
||||
Promise.race([
|
||||
server.ping(),
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error("ping timeout")), 5e3))
|
||||
]).then(() => {
|
||||
setTimeout(beat, 3e3);
|
||||
}).catch(() => {
|
||||
void server.close();
|
||||
});
|
||||
};
|
||||
beat();
|
||||
};
|
||||
function addServerListener(server, event, listener) {
|
||||
const oldListener = server[`on${event}`];
|
||||
server[`on${event}`] = () => {
|
||||
oldListener?.();
|
||||
listener();
|
||||
};
|
||||
}
|
||||
async function start(serverBackendFactory, options) {
|
||||
if (options.port === void 0) {
|
||||
await connect(serverBackendFactory, new mcpBundle.StdioServerTransport(), false);
|
||||
return;
|
||||
}
|
||||
const url = await (0, import_http.startMcpHttpServer)(options, serverBackendFactory, options.allowedHosts);
|
||||
const mcpConfig = { mcpServers: {} };
|
||||
mcpConfig.mcpServers[serverBackendFactory.nameInConfig] = {
|
||||
url: `${url}/mcp`
|
||||
};
|
||||
const message = [
|
||||
`Listening on ${url}`,
|
||||
"Put this in your client config:",
|
||||
JSON.stringify(mcpConfig, void 0, 2),
|
||||
"For legacy SSE transport support, you can use the /sse endpoint instead."
|
||||
].join("\n");
|
||||
console.error(message);
|
||||
}
|
||||
function firstRootPath(clientInfo) {
|
||||
if (clientInfo.roots.length === 0)
|
||||
return void 0;
|
||||
const firstRootUri = clientInfo.roots[0]?.uri;
|
||||
const url = firstRootUri ? new URL(firstRootUri) : void 0;
|
||||
try {
|
||||
return url ? (0, import_url.fileURLToPath)(url) : void 0;
|
||||
} catch (error) {
|
||||
serverDebug(error);
|
||||
return void 0;
|
||||
}
|
||||
}
|
||||
function allRootPaths(clientInfo) {
|
||||
const paths = [];
|
||||
for (const root of clientInfo.roots) {
|
||||
try {
|
||||
const url = new URL(root.uri);
|
||||
const path = (0, import_url.fileURLToPath)(url);
|
||||
if (path)
|
||||
paths.push(path);
|
||||
} catch (error) {
|
||||
serverDebug(error);
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
function mergeTextParts(result) {
|
||||
const content = [];
|
||||
const testParts = [];
|
||||
for (const part of result.content) {
|
||||
if (part.type === "text") {
|
||||
testParts.push(part.text);
|
||||
continue;
|
||||
}
|
||||
if (testParts.length > 0) {
|
||||
content.push({ type: "text", text: testParts.join("\n") });
|
||||
testParts.length = 0;
|
||||
}
|
||||
content.push(part);
|
||||
}
|
||||
if (testParts.length > 0)
|
||||
content.push({ type: "text", text: testParts.join("\n") });
|
||||
return {
|
||||
...result,
|
||||
content
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
allRootPaths,
|
||||
connect,
|
||||
createServer,
|
||||
firstRootPath,
|
||||
start,
|
||||
wrapInClient,
|
||||
wrapInProcess
|
||||
});
|
||||
47
backend/node_modules/playwright/lib/mcp/sdk/tool.js
generated
vendored
Normal file
47
backend/node_modules/playwright/lib/mcp/sdk/tool.js
generated
vendored
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var tool_exports = {};
|
||||
__export(tool_exports, {
|
||||
defineToolSchema: () => defineToolSchema,
|
||||
toMcpTool: () => toMcpTool
|
||||
});
|
||||
module.exports = __toCommonJS(tool_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
function toMcpTool(tool) {
|
||||
const readOnly = tool.type === "readOnly" || tool.type === "assertion";
|
||||
return {
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
inputSchema: import_mcpBundle.z.toJSONSchema(tool.inputSchema),
|
||||
annotations: {
|
||||
title: tool.title,
|
||||
readOnlyHint: readOnly,
|
||||
destructiveHint: !readOnly,
|
||||
openWorldHint: true
|
||||
}
|
||||
};
|
||||
}
|
||||
function defineToolSchema(tool) {
|
||||
return tool;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
defineToolSchema,
|
||||
toMcpTool
|
||||
});
|
||||
296
backend/node_modules/playwright/lib/mcp/terminal/cli.js
generated
vendored
Normal file
296
backend/node_modules/playwright/lib/mcp/terminal/cli.js
generated
vendored
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var import_child_process = require("child_process");
|
||||
var import_crypto = __toESM(require("crypto"));
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_net = __toESM(require("net"));
|
||||
var import_os = __toESM(require("os"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_socketConnection = require("./socketConnection");
|
||||
const debugCli = (0, import_utilsBundle.debug)("pw:cli");
|
||||
const packageJSON = require("../../../package.json");
|
||||
async function runCliCommand(sessionName, args) {
|
||||
const session = await connectToDaemon(sessionName);
|
||||
const result = await session.runCliCommand(args);
|
||||
console.log(result);
|
||||
session.dispose();
|
||||
}
|
||||
async function socketExists(socketPath) {
|
||||
try {
|
||||
const stat = await import_fs.default.promises.stat(socketPath);
|
||||
if (stat?.isSocket())
|
||||
return true;
|
||||
} catch (e) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
class SocketSession {
|
||||
constructor(connection) {
|
||||
this._nextMessageId = 1;
|
||||
this._callbacks = /* @__PURE__ */ new Map();
|
||||
this._connection = connection;
|
||||
this._connection.onmessage = (message) => this._onMessage(message);
|
||||
this._connection.onclose = () => this.dispose();
|
||||
}
|
||||
async callTool(name, args) {
|
||||
return this._send(name, args);
|
||||
}
|
||||
async runCliCommand(args) {
|
||||
return await this._send("runCliCommand", { args });
|
||||
}
|
||||
async _send(method, params = {}) {
|
||||
const messageId = this._nextMessageId++;
|
||||
const message = {
|
||||
id: messageId,
|
||||
method,
|
||||
params
|
||||
};
|
||||
await this._connection.send(message);
|
||||
return new Promise((resolve, reject) => {
|
||||
this._callbacks.set(messageId, { resolve, reject });
|
||||
});
|
||||
}
|
||||
dispose() {
|
||||
for (const callback of this._callbacks.values())
|
||||
callback.reject(new Error("Disposed"));
|
||||
this._callbacks.clear();
|
||||
this._connection.close();
|
||||
}
|
||||
_onMessage(object) {
|
||||
if (object.id && this._callbacks.has(object.id)) {
|
||||
const callback = this._callbacks.get(object.id);
|
||||
this._callbacks.delete(object.id);
|
||||
if (object.error)
|
||||
callback.reject(new Error(object.error));
|
||||
else
|
||||
callback.resolve(object.result);
|
||||
} else if (object.id) {
|
||||
throw new Error(`Unexpected message id: ${object.id}`);
|
||||
} else {
|
||||
throw new Error(`Unexpected message without id: ${JSON.stringify(object)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
function localCacheDir() {
|
||||
if (process.platform === "linux")
|
||||
return process.env.XDG_CACHE_HOME || import_path.default.join(import_os.default.homedir(), ".cache");
|
||||
if (process.platform === "darwin")
|
||||
return import_path.default.join(import_os.default.homedir(), "Library", "Caches");
|
||||
if (process.platform === "win32")
|
||||
return process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local");
|
||||
throw new Error("Unsupported platform: " + process.platform);
|
||||
}
|
||||
function playwrightCacheDir() {
|
||||
return import_path.default.join(localCacheDir(), "ms-playwright");
|
||||
}
|
||||
function calculateSha1(buffer) {
|
||||
const hash = import_crypto.default.createHash("sha1");
|
||||
hash.update(buffer);
|
||||
return hash.digest("hex");
|
||||
}
|
||||
function socketDirHash() {
|
||||
return calculateSha1(__dirname);
|
||||
}
|
||||
function daemonSocketDir() {
|
||||
return import_path.default.resolve(playwrightCacheDir(), "daemon", socketDirHash());
|
||||
}
|
||||
function daemonSocketPath(sessionName) {
|
||||
const socketName = `${sessionName}.sock`;
|
||||
if (import_os.default.platform() === "win32")
|
||||
return `\\\\.\\pipe\\${socketDirHash()}-${socketName}`;
|
||||
return import_path.default.resolve(daemonSocketDir(), socketName);
|
||||
}
|
||||
async function connectToDaemon(sessionName) {
|
||||
const socketPath = daemonSocketPath(sessionName);
|
||||
debugCli(`Connecting to daemon at ${socketPath}`);
|
||||
if (await socketExists(socketPath)) {
|
||||
debugCli(`Socket file exists, attempting to connect...`);
|
||||
try {
|
||||
return await connectToSocket(socketPath);
|
||||
} catch (e) {
|
||||
if (import_os.default.platform() !== "win32")
|
||||
await import_fs.default.promises.unlink(socketPath).catch(() => {
|
||||
});
|
||||
}
|
||||
}
|
||||
const cliPath = import_path.default.join(__dirname, "../../../cli.js");
|
||||
debugCli(`Will launch daemon process: ${cliPath}`);
|
||||
const userDataDir = import_path.default.resolve(daemonSocketDir(), `${sessionName}-user-data`);
|
||||
const child = (0, import_child_process.spawn)(process.execPath, [cliPath, "run-mcp-server", `--daemon=${socketPath}`, `--user-data-dir=${userDataDir}`], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
cwd: process.cwd()
|
||||
// Will be used as root.
|
||||
});
|
||||
child.unref();
|
||||
const maxRetries = 50;
|
||||
const retryDelay = 100;
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
try {
|
||||
return await connectToSocket(socketPath);
|
||||
} catch (e) {
|
||||
if (e.code !== "ENOENT")
|
||||
throw e;
|
||||
debugCli(`Retrying to connect to daemon at ${socketPath} (${i + 1}/${maxRetries})`);
|
||||
}
|
||||
}
|
||||
throw new Error(`Failed to connect to daemon at ${socketPath} after ${maxRetries * retryDelay}ms`);
|
||||
}
|
||||
async function connectToSocket(socketPath) {
|
||||
const socket = await new Promise((resolve, reject) => {
|
||||
const socket2 = import_net.default.createConnection(socketPath, () => {
|
||||
debugCli(`Connected to daemon at ${socketPath}`);
|
||||
resolve(socket2);
|
||||
});
|
||||
socket2.on("error", reject);
|
||||
});
|
||||
return new SocketSession(new import_socketConnection.SocketConnection(socket));
|
||||
}
|
||||
function currentSessionPath() {
|
||||
return import_path.default.resolve(daemonSocketDir(), "current-session");
|
||||
}
|
||||
async function getCurrentSession() {
|
||||
try {
|
||||
const session = await import_fs.default.promises.readFile(currentSessionPath(), "utf-8");
|
||||
return session.trim() || "default";
|
||||
} catch {
|
||||
return "default";
|
||||
}
|
||||
}
|
||||
async function setCurrentSession(sessionName) {
|
||||
await import_fs.default.promises.mkdir(daemonSocketDir(), { recursive: true });
|
||||
await import_fs.default.promises.writeFile(currentSessionPath(), sessionName);
|
||||
}
|
||||
async function canConnectToSocket(socketPath) {
|
||||
return new Promise((resolve) => {
|
||||
const socket = import_net.default.createConnection(socketPath, () => {
|
||||
socket.destroy();
|
||||
resolve(true);
|
||||
});
|
||||
socket.on("error", () => {
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
async function listSessions() {
|
||||
const dir = daemonSocketDir();
|
||||
try {
|
||||
const files = await import_fs.default.promises.readdir(dir);
|
||||
const sessions = [];
|
||||
for (const file of files) {
|
||||
if (file.endsWith("-user-data")) {
|
||||
const sessionName = file.slice(0, -"-user-data".length);
|
||||
const socketPath = daemonSocketPath(sessionName);
|
||||
const live = await canConnectToSocket(socketPath);
|
||||
sessions.push({ name: sessionName, live });
|
||||
}
|
||||
}
|
||||
return sessions;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
function resolveSessionName(args) {
|
||||
if (args.session)
|
||||
return args.session;
|
||||
if (process.env.PLAYWRIGHT_CLI_SESSION)
|
||||
return process.env.PLAYWRIGHT_CLI_SESSION;
|
||||
return "default";
|
||||
}
|
||||
async function handleSessionCommand(args) {
|
||||
const subcommand = args._[1];
|
||||
if (!subcommand) {
|
||||
const current = await getCurrentSession();
|
||||
console.log(current);
|
||||
return;
|
||||
}
|
||||
if (subcommand === "list") {
|
||||
const sessions = await listSessions();
|
||||
const current = await getCurrentSession();
|
||||
console.log("Sessions:");
|
||||
for (const session of sessions) {
|
||||
const marker = session.name === current ? "->" : " ";
|
||||
const liveMarker = session.live ? " (live)" : "";
|
||||
console.log(`${marker} ${session.name}${liveMarker}`);
|
||||
}
|
||||
if (sessions.length === 0)
|
||||
console.log(" (no sessions)");
|
||||
return;
|
||||
}
|
||||
if (subcommand === "set") {
|
||||
const sessionName = args._[2];
|
||||
if (!sessionName) {
|
||||
console.error("Usage: playwright-cli session set <session-name>");
|
||||
process.exit(1);
|
||||
}
|
||||
await setCurrentSession(sessionName);
|
||||
console.log(`Current session set to: ${sessionName}`);
|
||||
return;
|
||||
}
|
||||
console.error(`Unknown session subcommand: ${subcommand}`);
|
||||
process.exit(1);
|
||||
}
|
||||
async function main() {
|
||||
const argv = process.argv.slice(2);
|
||||
const args = require("minimist")(argv);
|
||||
const help = require("./help.json");
|
||||
const commandName = args._[0];
|
||||
if (args.version || args.v) {
|
||||
console.log(packageJSON.version);
|
||||
process.exit(0);
|
||||
}
|
||||
if (commandName === "session") {
|
||||
await handleSessionCommand(args);
|
||||
return;
|
||||
}
|
||||
const command = help.commands[commandName];
|
||||
if (args.help || args.h) {
|
||||
if (command) {
|
||||
console.log(command);
|
||||
} else {
|
||||
console.log("playwright-cli - run playwright mcp commands from terminal\n");
|
||||
console.log(help.global);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
if (!command) {
|
||||
console.error(`Unknown command: ${commandName}
|
||||
`);
|
||||
console.log(help.global);
|
||||
process.exit(1);
|
||||
}
|
||||
let sessionName = resolveSessionName(args);
|
||||
if (sessionName === "default" && !args.session && !process.env.PLAYWRIGHT_CLI_SESSION)
|
||||
sessionName = await getCurrentSession();
|
||||
runCliCommand(sessionName, args).catch((e) => {
|
||||
console.error(e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
main().catch((e) => {
|
||||
console.error(e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
56
backend/node_modules/playwright/lib/mcp/terminal/command.js
generated
vendored
Normal file
56
backend/node_modules/playwright/lib/mcp/terminal/command.js
generated
vendored
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var command_exports = {};
|
||||
__export(command_exports, {
|
||||
declareCommand: () => declareCommand,
|
||||
parseCommand: () => parseCommand
|
||||
});
|
||||
module.exports = __toCommonJS(command_exports);
|
||||
function declareCommand(command) {
|
||||
return command;
|
||||
}
|
||||
function parseCommand(command, args) {
|
||||
const shape = command.args ? command.args.shape : {};
|
||||
const argv = args["_"];
|
||||
const options = command.options?.parse({ ...args, _: void 0 }) ?? {};
|
||||
const argsObject = {};
|
||||
let i = 0;
|
||||
for (const name of Object.keys(shape))
|
||||
argsObject[name] = argv[++i];
|
||||
let parsedArgsObject = {};
|
||||
try {
|
||||
parsedArgsObject = command.args?.parse(argsObject) ?? {};
|
||||
} catch (e) {
|
||||
throw new Error(formatZodError(e));
|
||||
}
|
||||
const toolName = typeof command.toolName === "function" ? command.toolName(parsedArgsObject, options) : command.toolName;
|
||||
const toolParams = command.toolParams(parsedArgsObject, options);
|
||||
return { toolName, toolParams };
|
||||
}
|
||||
function formatZodError(error) {
|
||||
const issue = error.issues[0];
|
||||
if (issue.code === "invalid_type")
|
||||
return `${issue.message} in <${issue.path.join(".")}>`;
|
||||
return error.issues.map((i) => i.message).join("\n");
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
declareCommand,
|
||||
parseCommand
|
||||
});
|
||||
333
backend/node_modules/playwright/lib/mcp/terminal/commands.js
generated
vendored
Normal file
333
backend/node_modules/playwright/lib/mcp/terminal/commands.js
generated
vendored
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var commands_exports = {};
|
||||
__export(commands_exports, {
|
||||
commands: () => commands
|
||||
});
|
||||
module.exports = __toCommonJS(commands_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_command = require("./command");
|
||||
const click = (0, import_command.declareCommand)({
|
||||
name: "click",
|
||||
description: "Perform click on a web page",
|
||||
args: import_mcpBundle.z.object({
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference from the page snapshot")
|
||||
}),
|
||||
options: import_mcpBundle.z.object({
|
||||
button: import_mcpBundle.z.string().optional().describe("Button to click, defaults to left"),
|
||||
modifiers: import_mcpBundle.z.array(import_mcpBundle.z.string()).optional().describe("Modifier keys to press")
|
||||
}),
|
||||
toolName: "browser_click",
|
||||
toolParams: ({ ref }, { button, modifiers }) => ({ ref, button, modifiers })
|
||||
});
|
||||
const doubleClick = (0, import_command.declareCommand)({
|
||||
name: "dblclick",
|
||||
description: "Perform double click on a web page",
|
||||
args: import_mcpBundle.z.object({
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference from the page snapshot")
|
||||
}),
|
||||
options: import_mcpBundle.z.object({
|
||||
button: import_mcpBundle.z.string().optional().describe("Button to click, defaults to left"),
|
||||
modifiers: import_mcpBundle.z.array(import_mcpBundle.z.string()).optional().describe("Modifier keys to press")
|
||||
}),
|
||||
toolName: "browser_click",
|
||||
toolParams: ({ ref }, { button, modifiers }) => ({ ref, button, modifiers, doubleClick: true })
|
||||
});
|
||||
const close = (0, import_command.declareCommand)({
|
||||
name: "close",
|
||||
description: "Close the page",
|
||||
args: import_mcpBundle.z.object({}),
|
||||
toolName: "browser_close",
|
||||
toolParams: () => ({})
|
||||
});
|
||||
const consoleMessages = (0, import_command.declareCommand)({
|
||||
name: "console",
|
||||
description: "Returns all console messages",
|
||||
args: import_mcpBundle.z.object({
|
||||
level: import_mcpBundle.z.string().optional().describe('Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".')
|
||||
}),
|
||||
toolName: "browser_console_messages",
|
||||
toolParams: ({ level }) => ({ level })
|
||||
});
|
||||
const drag = (0, import_command.declareCommand)({
|
||||
name: "drag",
|
||||
description: "Perform drag and drop between two elements",
|
||||
args: import_mcpBundle.z.object({
|
||||
startRef: import_mcpBundle.z.string().describe("Exact source element reference from the page snapshot"),
|
||||
endRef: import_mcpBundle.z.string().describe("Exact target element reference from the page snapshot")
|
||||
}),
|
||||
options: import_mcpBundle.z.object({
|
||||
headed: import_mcpBundle.z.boolean().default(false).describe("Run browser in headed mode")
|
||||
}),
|
||||
toolName: "browser_drag",
|
||||
toolParams: ({ startRef, endRef }) => ({ startRef, endRef })
|
||||
});
|
||||
const evaluate = (0, import_command.declareCommand)({
|
||||
name: "evaluate",
|
||||
description: "Evaluate JavaScript expression on page or element",
|
||||
args: import_mcpBundle.z.object({
|
||||
function: import_mcpBundle.z.string().describe("() => { /* code */ } or (element) => { /* code */ } when element is provided"),
|
||||
ref: import_mcpBundle.z.string().optional().describe("Exact target element reference from the page snapshot")
|
||||
}),
|
||||
toolName: "browser_evaluate",
|
||||
toolParams: ({ function: fn, ref }) => ({ function: fn, ref })
|
||||
});
|
||||
const fileUpload = (0, import_command.declareCommand)({
|
||||
name: "upload-file",
|
||||
description: "Upload one or multiple files",
|
||||
args: import_mcpBundle.z.object({}),
|
||||
options: import_mcpBundle.z.object({
|
||||
paths: import_mcpBundle.z.array(import_mcpBundle.z.string()).optional().describe("The absolute paths to the files to upload. Can be single file or multiple files. If omitted, file chooser is cancelled.")
|
||||
}),
|
||||
toolName: "browser_file_upload",
|
||||
toolParams: (_, { paths }) => ({ paths })
|
||||
});
|
||||
const handleDialog = (0, import_command.declareCommand)({
|
||||
name: "handle-dialog",
|
||||
description: "Handle a dialog",
|
||||
args: import_mcpBundle.z.object({
|
||||
accept: import_mcpBundle.z.boolean().describe("Whether to accept the dialog."),
|
||||
promptText: import_mcpBundle.z.string().optional().describe("The text of the prompt in case of a prompt dialog.")
|
||||
}),
|
||||
toolName: "browser_handle_dialog",
|
||||
toolParams: ({ accept, promptText }) => ({ accept, promptText })
|
||||
});
|
||||
const hover = (0, import_command.declareCommand)({
|
||||
name: "hover",
|
||||
description: "Hover over element on page",
|
||||
args: import_mcpBundle.z.object({
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference from the page snapshot")
|
||||
}),
|
||||
toolName: "browser_hover",
|
||||
toolParams: ({ ref }) => ({ ref })
|
||||
});
|
||||
const open = (0, import_command.declareCommand)({
|
||||
name: "open",
|
||||
description: "Open URL",
|
||||
args: import_mcpBundle.z.object({
|
||||
url: import_mcpBundle.z.string().describe("The URL to navigate to")
|
||||
}),
|
||||
options: import_mcpBundle.z.object({
|
||||
headed: import_mcpBundle.z.boolean().default(false).describe("Run browser in headed mode")
|
||||
}),
|
||||
toolName: "browser_open",
|
||||
toolParams: ({ url }, { headed }) => ({ url, headed })
|
||||
});
|
||||
const navigateBack = (0, import_command.declareCommand)({
|
||||
name: "go-back",
|
||||
description: "Go back to the previous page",
|
||||
args: import_mcpBundle.z.object({}),
|
||||
toolName: "browser_navigate_back",
|
||||
toolParams: () => ({})
|
||||
});
|
||||
const networkRequests = (0, import_command.declareCommand)({
|
||||
name: "network-requests",
|
||||
description: "Returns all network requests since loading the page",
|
||||
args: import_mcpBundle.z.object({}),
|
||||
options: import_mcpBundle.z.object({
|
||||
includeStatic: import_mcpBundle.z.boolean().optional().describe("Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.")
|
||||
}),
|
||||
toolName: "browser_network_requests",
|
||||
toolParams: (_, { includeStatic }) => ({ includeStatic })
|
||||
});
|
||||
const pressKey = (0, import_command.declareCommand)({
|
||||
name: "press",
|
||||
description: "Press a key on the keyboard",
|
||||
args: import_mcpBundle.z.object({
|
||||
key: import_mcpBundle.z.string().describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`")
|
||||
}),
|
||||
toolName: "browser_press_key",
|
||||
toolParams: ({ key }) => ({ key })
|
||||
});
|
||||
const resize = (0, import_command.declareCommand)({
|
||||
name: "resize",
|
||||
description: "Resize the browser window",
|
||||
args: import_mcpBundle.z.object({
|
||||
width: import_mcpBundle.z.number().describe("Width of the browser window"),
|
||||
height: import_mcpBundle.z.number().describe("Height of the browser window")
|
||||
}),
|
||||
toolName: "browser_resize",
|
||||
toolParams: ({ width, height }) => ({ width, height })
|
||||
});
|
||||
const runCode = (0, import_command.declareCommand)({
|
||||
name: "run-code",
|
||||
description: "Run Playwright code snippet",
|
||||
args: import_mcpBundle.z.object({
|
||||
code: import_mcpBundle.z.string().describe("A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction.")
|
||||
}),
|
||||
toolName: "browser_run_code",
|
||||
toolParams: ({ code }) => ({ code })
|
||||
});
|
||||
const selectOption = (0, import_command.declareCommand)({
|
||||
name: "select-option",
|
||||
description: "Select an option in a dropdown",
|
||||
args: import_mcpBundle.z.object({
|
||||
ref: import_mcpBundle.z.string().describe("Exact target element reference from the page snapshot"),
|
||||
values: import_mcpBundle.z.array(import_mcpBundle.z.string()).describe("Array of values to select in the dropdown. This can be a single value or multiple values.")
|
||||
}),
|
||||
toolName: "browser_select_option",
|
||||
toolParams: ({ ref, values }) => ({ ref, values })
|
||||
});
|
||||
const snapshot = (0, import_command.declareCommand)({
|
||||
name: "snapshot",
|
||||
description: "Capture accessibility snapshot of the current page, this is better than screenshot",
|
||||
args: import_mcpBundle.z.object({}),
|
||||
options: import_mcpBundle.z.object({
|
||||
filename: import_mcpBundle.z.string().optional().describe("Save snapshot to markdown file instead of returning it in the response.")
|
||||
}),
|
||||
toolName: "browser_snapshot",
|
||||
toolParams: (_, { filename }) => ({ filename })
|
||||
});
|
||||
const screenshot = (0, import_command.declareCommand)({
|
||||
name: "screenshot",
|
||||
description: "Take a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.",
|
||||
args: import_mcpBundle.z.object({
|
||||
ref: import_mcpBundle.z.string().optional().describe("Exact target element reference from the page snapshot.")
|
||||
}),
|
||||
options: import_mcpBundle.z.object({
|
||||
filename: import_mcpBundle.z.string().optional().describe("File name to save the screenshot to. Defaults to `page-{timestamp}.{png|jpeg}` if not specified."),
|
||||
fullPage: import_mcpBundle.z.boolean().optional().describe("When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport.")
|
||||
}),
|
||||
toolName: "browser_take_screenshot",
|
||||
toolParams: ({ ref }, { filename, fullPage }) => ({ filename, ref, fullPage })
|
||||
});
|
||||
const type = (0, import_command.declareCommand)({
|
||||
name: "type",
|
||||
description: "Type text into editable element",
|
||||
args: import_mcpBundle.z.object({
|
||||
text: import_mcpBundle.z.string().describe("Text to type into the element")
|
||||
}),
|
||||
options: import_mcpBundle.z.object({
|
||||
submit: import_mcpBundle.z.boolean().optional().describe("Whether to submit entered text (press Enter after)")
|
||||
}),
|
||||
toolName: "browser_press_sequentially",
|
||||
toolParams: ({ text }, { submit }) => ({ text, submit })
|
||||
});
|
||||
const waitFor = (0, import_command.declareCommand)({
|
||||
name: "wait-for",
|
||||
description: "Wait for text to appear or disappear or a specified time to pass",
|
||||
args: import_mcpBundle.z.object({}),
|
||||
options: import_mcpBundle.z.object({
|
||||
time: import_mcpBundle.z.number().optional().describe("The time to wait in seconds"),
|
||||
text: import_mcpBundle.z.string().optional().describe("The text to wait for"),
|
||||
textGone: import_mcpBundle.z.string().optional().describe("The text to wait for to disappear")
|
||||
}),
|
||||
toolName: "browser_wait_for",
|
||||
toolParams: (_, { time, text, textGone }) => ({ time, text, textGone })
|
||||
});
|
||||
const tab = (0, import_command.declareCommand)({
|
||||
name: "tab",
|
||||
description: "Close a browser tab",
|
||||
args: import_mcpBundle.z.object({
|
||||
action: import_mcpBundle.z.string().describe(`Action to perform on tabs, 'list' | 'new' | 'close' | 'select'`),
|
||||
index: import_mcpBundle.z.number().optional().describe("Tab index. If omitted, current tab is closed.")
|
||||
}),
|
||||
toolName: "browser_tabs",
|
||||
toolParams: ({ action, index }) => ({ action, index })
|
||||
});
|
||||
const mouseClickXy = (0, import_command.declareCommand)({
|
||||
name: "mouse-click-xy",
|
||||
description: "Click left mouse button at a given position",
|
||||
args: import_mcpBundle.z.object({
|
||||
x: import_mcpBundle.z.number().describe("X coordinate"),
|
||||
y: import_mcpBundle.z.number().describe("Y coordinate")
|
||||
}),
|
||||
toolName: "browser_mouse_click_xy",
|
||||
toolParams: ({ x, y }) => ({ x, y })
|
||||
});
|
||||
const mouseDragXy = (0, import_command.declareCommand)({
|
||||
name: "mouse-drag-xy",
|
||||
description: "Drag left mouse button to a given position",
|
||||
args: import_mcpBundle.z.object({
|
||||
startX: import_mcpBundle.z.number().describe("Start X coordinate"),
|
||||
startY: import_mcpBundle.z.number().describe("Start Y coordinate"),
|
||||
endX: import_mcpBundle.z.number().describe("End X coordinate"),
|
||||
endY: import_mcpBundle.z.number().describe("End Y coordinate")
|
||||
}),
|
||||
toolName: "browser_mouse_drag_xy",
|
||||
toolParams: ({ startX, startY, endX, endY }) => ({ startX, startY, endX, endY })
|
||||
});
|
||||
const mouseMoveXy = (0, import_command.declareCommand)({
|
||||
name: "mouse-move-xy",
|
||||
description: "Move mouse to a given position",
|
||||
args: import_mcpBundle.z.object({
|
||||
x: import_mcpBundle.z.number().describe("X coordinate"),
|
||||
y: import_mcpBundle.z.number().describe("Y coordinate")
|
||||
}),
|
||||
toolName: "browser_mouse_move_xy",
|
||||
toolParams: ({ x, y }) => ({ x, y })
|
||||
});
|
||||
const pdfSave = (0, import_command.declareCommand)({
|
||||
name: "pdf-save",
|
||||
description: "Save page as PDF",
|
||||
args: import_mcpBundle.z.object({}),
|
||||
options: import_mcpBundle.z.object({
|
||||
filename: import_mcpBundle.z.string().optional().describe("File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified.")
|
||||
}),
|
||||
toolName: "browser_pdf_save",
|
||||
toolParams: (_, { filename }) => ({ filename })
|
||||
});
|
||||
const startTracing = (0, import_command.declareCommand)({
|
||||
name: "start-tracing",
|
||||
description: "Start trace recording",
|
||||
args: import_mcpBundle.z.object({}),
|
||||
toolName: "browser_start_tracing",
|
||||
toolParams: () => ({})
|
||||
});
|
||||
const stopTracing = (0, import_command.declareCommand)({
|
||||
name: "stop-tracing",
|
||||
description: "Stop trace recording",
|
||||
args: import_mcpBundle.z.object({}),
|
||||
toolName: "browser_stop_tracing",
|
||||
toolParams: () => ({})
|
||||
});
|
||||
const commandsArray = [
|
||||
click,
|
||||
close,
|
||||
doubleClick,
|
||||
consoleMessages,
|
||||
drag,
|
||||
evaluate,
|
||||
fileUpload,
|
||||
handleDialog,
|
||||
hover,
|
||||
open,
|
||||
navigateBack,
|
||||
networkRequests,
|
||||
pressKey,
|
||||
resize,
|
||||
runCode,
|
||||
selectOption,
|
||||
snapshot,
|
||||
screenshot,
|
||||
type,
|
||||
waitFor,
|
||||
tab,
|
||||
mouseClickXy,
|
||||
mouseDragXy,
|
||||
mouseMoveXy,
|
||||
pdfSave,
|
||||
startTracing,
|
||||
stopTracing
|
||||
];
|
||||
const commands = Object.fromEntries(commandsArray.map((cmd) => [cmd.name, cmd]));
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
commands
|
||||
});
|
||||
129
backend/node_modules/playwright/lib/mcp/terminal/daemon.js
generated
vendored
Normal file
129
backend/node_modules/playwright/lib/mcp/terminal/daemon.js
generated
vendored
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var daemon_exports = {};
|
||||
__export(daemon_exports, {
|
||||
startMcpDaemonServer: () => startMcpDaemonServer
|
||||
});
|
||||
module.exports = __toCommonJS(daemon_exports);
|
||||
var import_promises = __toESM(require("fs/promises"));
|
||||
var import_net = __toESM(require("net"));
|
||||
var import_os = __toESM(require("os"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_url = __toESM(require("url"));
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
var import_socketConnection = require("./socketConnection");
|
||||
var import_commands = require("./commands");
|
||||
var import_command = require("./command");
|
||||
const daemonDebug = (0, import_utilsBundle.debug)("pw:daemon");
|
||||
async function socketExists(socketPath) {
|
||||
try {
|
||||
const stat = await import_promises.default.stat(socketPath);
|
||||
if (stat?.isSocket())
|
||||
return true;
|
||||
} catch (e) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
async function startMcpDaemonServer(socketPath, serverBackendFactory) {
|
||||
if (import_os.default.platform() !== "win32" && await socketExists(socketPath)) {
|
||||
daemonDebug(`Socket already exists, removing: ${socketPath}`);
|
||||
try {
|
||||
await import_promises.default.unlink(socketPath);
|
||||
} catch (error) {
|
||||
daemonDebug(`Failed to remove existing socket: ${error}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const backend = serverBackendFactory.create();
|
||||
const cwd = import_url.default.pathToFileURL(process.cwd()).href;
|
||||
await backend.initialize?.({
|
||||
name: "playwright-cli",
|
||||
version: "1.0.0",
|
||||
roots: [{
|
||||
uri: cwd,
|
||||
name: "cwd"
|
||||
}],
|
||||
timestamp: Date.now()
|
||||
});
|
||||
await import_promises.default.mkdir(import_path.default.dirname(socketPath), { recursive: true });
|
||||
const server = import_net.default.createServer((socket) => {
|
||||
daemonDebug("new client connection");
|
||||
const connection = new import_socketConnection.SocketConnection(socket);
|
||||
connection.onclose = () => {
|
||||
daemonDebug("client disconnected");
|
||||
};
|
||||
connection.onmessage = async (message) => {
|
||||
const { id, method, params } = message;
|
||||
try {
|
||||
daemonDebug("received command", method);
|
||||
if (method === "runCliCommand") {
|
||||
const { toolName, toolParams } = parseCliCommand(params.args);
|
||||
const response = await backend.callTool(toolName, toolParams, () => {
|
||||
});
|
||||
await connection.send({ id, result: formatResult(response) });
|
||||
} else {
|
||||
throw new Error(`Unknown method: ${method}`);
|
||||
}
|
||||
} catch (e) {
|
||||
daemonDebug("command failed", e);
|
||||
await connection.send({ id, error: e.message });
|
||||
}
|
||||
};
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
server.on("error", (error) => {
|
||||
daemonDebug(`server error: ${error.message}`);
|
||||
reject(error);
|
||||
});
|
||||
server.listen(socketPath, () => {
|
||||
daemonDebug(`daemon server listening on ${socketPath}`);
|
||||
resolve(socketPath);
|
||||
});
|
||||
});
|
||||
}
|
||||
function formatResult(result) {
|
||||
const lines = [];
|
||||
for (const content of result.content) {
|
||||
if (content.type === "text")
|
||||
lines.push(content.text);
|
||||
else
|
||||
lines.push(`<${content.type} content>`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
function parseCliCommand(args) {
|
||||
const command = import_commands.commands[args._[0]];
|
||||
if (!command)
|
||||
throw new Error("Command is required");
|
||||
return (0, import_command.parseCommand)(command, args);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
startMcpDaemonServer
|
||||
});
|
||||
32
backend/node_modules/playwright/lib/mcp/terminal/help.json
generated
vendored
Normal file
32
backend/node_modules/playwright/lib/mcp/terminal/help.json
generated
vendored
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"global": "Usage: playwright-cli <command> [options]\nCommands:\n click <ref> perform click on a web page\n close close the page\n dblclick <ref> perform double click on a web page\n console <level> returns all console messages\n drag <startRef> <endRef> perform drag and drop between two elements\n evaluate <function> <ref> evaluate javascript expression on page or element\n upload-file upload one or multiple files\n handle-dialog <accept> <promptText> handle a dialog\n hover <ref> hover over element on page\n open <url> open url\n go-back go back to the previous page\n network-requests returns all network requests since loading the page\n press <key> press a key on the keyboard\n resize <width> <height> resize the browser window\n run-code <code> run playwright code snippet\n select-option <ref> <values> select an option in a dropdown\n snapshot capture accessibility snapshot of the current page, this is better than screenshot\n screenshot <ref> take a screenshot of the current page. you can't perform actions based on the screenshot, use browser_snapshot for actions.\n type <text> type text into editable element\n wait-for wait for text to appear or disappear or a specified time to pass\n tab <action> <index> close a browser tab\n mouse-click-xy <x> <y> click left mouse button at a given position\n mouse-drag-xy <startX> <startY> <endX> <endY> drag left mouse button to a given position\n mouse-move-xy <x> <y> move mouse to a given position\n pdf-save save page as pdf\n start-tracing start trace recording\n stop-tracing stop trace recording",
|
||||
"commands": {
|
||||
"click": "playwright-cli click <ref>\n\nPerform click on a web page\n\nArguments:\n <ref>\tExact target element reference from the page snapshot\nOptions:\n --button\tbutton to click, defaults to left\n --modifiers\tmodifier keys to press",
|
||||
"close": "playwright-cli close \n\nClose the page\n",
|
||||
"dblclick": "playwright-cli dblclick <ref>\n\nPerform double click on a web page\n\nArguments:\n <ref>\tExact target element reference from the page snapshot\nOptions:\n --button\tbutton to click, defaults to left\n --modifiers\tmodifier keys to press",
|
||||
"console": "playwright-cli console <level>\n\nReturns all console messages\n\nArguments:\n <level>\tLevel of the console messages to return. Each level includes the messages of more severe levels. Defaults to \"info\".",
|
||||
"drag": "playwright-cli drag <startRef> <endRef>\n\nPerform drag and drop between two elements\n\nArguments:\n <startRef>\tExact source element reference from the page snapshot\n <endRef>\tExact target element reference from the page snapshot\nOptions:\n --headed\trun browser in headed mode",
|
||||
"evaluate": "playwright-cli evaluate <function> <ref>\n\nEvaluate JavaScript expression on page or element\n\nArguments:\n <function>\t() => { /* code */ } or (element) => { /* code */ } when element is provided\n <ref>\tExact target element reference from the page snapshot",
|
||||
"upload-file": "playwright-cli upload-file \n\nUpload one or multiple files\n\nOptions:\n --paths\tthe absolute paths to the files to upload. can be single file or multiple files. if omitted, file chooser is cancelled.",
|
||||
"handle-dialog": "playwright-cli handle-dialog <accept> <promptText>\n\nHandle a dialog\n\nArguments:\n <accept>\tWhether to accept the dialog.\n <promptText>\tThe text of the prompt in case of a prompt dialog.",
|
||||
"hover": "playwright-cli hover <ref>\n\nHover over element on page\n\nArguments:\n <ref>\tExact target element reference from the page snapshot",
|
||||
"open": "playwright-cli open <url>\n\nOpen URL\n\nArguments:\n <url>\tThe URL to navigate to\nOptions:\n --headed\trun browser in headed mode",
|
||||
"go-back": "playwright-cli go-back \n\nGo back to the previous page\n",
|
||||
"network-requests": "playwright-cli network-requests \n\nReturns all network requests since loading the page\n\nOptions:\n --includeStatic\twhether to include successful static resources like images, fonts, scripts, etc. defaults to false.",
|
||||
"press": "playwright-cli press <key>\n\nPress a key on the keyboard\n\nArguments:\n <key>\tName of the key to press or a character to generate, such as `ArrowLeft` or `a`",
|
||||
"resize": "playwright-cli resize <width> <height>\n\nResize the browser window\n\nArguments:\n <width>\tWidth of the browser window\n <height>\tHeight of the browser window",
|
||||
"run-code": "playwright-cli run-code <code>\n\nRun Playwright code snippet\n\nArguments:\n <code>\tA JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction.",
|
||||
"select-option": "playwright-cli select-option <ref> <values>\n\nSelect an option in a dropdown\n\nArguments:\n <ref>\tExact target element reference from the page snapshot\n <values>\tArray of values to select in the dropdown. This can be a single value or multiple values.",
|
||||
"snapshot": "playwright-cli snapshot \n\nCapture accessibility snapshot of the current page, this is better than screenshot\n\nOptions:\n --filename\tsave snapshot to markdown file instead of returning it in the response.",
|
||||
"screenshot": "playwright-cli screenshot <ref>\n\nTake a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.\n\nArguments:\n <ref>\tExact target element reference from the page snapshot.\nOptions:\n --filename\tfile name to save the screenshot to. defaults to `page-{timestamp}.{png|jpeg}` if not specified.\n --fullPage\twhen true, takes a screenshot of the full scrollable page, instead of the currently visible viewport.",
|
||||
"type": "playwright-cli type <text>\n\nType text into editable element\n\nArguments:\n <text>\tText to type into the element\nOptions:\n --submit\twhether to submit entered text (press enter after)",
|
||||
"wait-for": "playwright-cli wait-for \n\nWait for text to appear or disappear or a specified time to pass\n\nOptions:\n --time\tthe time to wait in seconds\n --text\tthe text to wait for\n --textGone\tthe text to wait for to disappear",
|
||||
"tab": "playwright-cli tab <action> <index>\n\nClose a browser tab\n\nArguments:\n <action>\tAction to perform on tabs, 'list' | 'new' | 'close' | 'select'\n <index>\tTab index. If omitted, current tab is closed.",
|
||||
"mouse-click-xy": "playwright-cli mouse-click-xy <x> <y>\n\nClick left mouse button at a given position\n\nArguments:\n <x>\tX coordinate\n <y>\tY coordinate",
|
||||
"mouse-drag-xy": "playwright-cli mouse-drag-xy <startX> <startY> <endX> <endY>\n\nDrag left mouse button to a given position\n\nArguments:\n <startX>\tStart X coordinate\n <startY>\tStart Y coordinate\n <endX>\tEnd X coordinate\n <endY>\tEnd Y coordinate",
|
||||
"mouse-move-xy": "playwright-cli mouse-move-xy <x> <y>\n\nMove mouse to a given position\n\nArguments:\n <x>\tX coordinate\n <y>\tY coordinate",
|
||||
"pdf-save": "playwright-cli pdf-save \n\nSave page as PDF\n\nOptions:\n --filename\tfile name to save the pdf to. defaults to `page-{timestamp}.pdf` if not specified.",
|
||||
"start-tracing": "playwright-cli start-tracing \n\nStart trace recording\n",
|
||||
"stop-tracing": "playwright-cli stop-tracing \n\nStop trace recording\n"
|
||||
}
|
||||
}
|
||||
88
backend/node_modules/playwright/lib/mcp/terminal/helpGenerator.js
generated
vendored
Normal file
88
backend/node_modules/playwright/lib/mcp/terminal/helpGenerator.js
generated
vendored
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_commands = require("./commands");
|
||||
function generateCommandHelp(command) {
|
||||
const args = [];
|
||||
const shape = command.args ? command.args.shape : {};
|
||||
for (const [name, schema] of Object.entries(shape)) {
|
||||
const zodSchema = schema;
|
||||
const description = zodSchema.description ?? "";
|
||||
args.push({ name, description });
|
||||
}
|
||||
const lines = [
|
||||
`playwright-cli ${command.name} ${Object.keys(shape).map((k) => `<${k}>`).join(" ")}`,
|
||||
"",
|
||||
command.description,
|
||||
""
|
||||
];
|
||||
if (args.length) {
|
||||
lines.push("Arguments:");
|
||||
lines.push(...args.map(({ name, description }) => ` <${name}> ${description}`));
|
||||
}
|
||||
if (command.options) {
|
||||
lines.push("Options:");
|
||||
const optionsShape = command.options.shape;
|
||||
for (const [name, schema] of Object.entries(optionsShape)) {
|
||||
const zodSchema = schema;
|
||||
const description = (zodSchema.description ?? "").toLowerCase();
|
||||
lines.push(` --${name} ${description}`);
|
||||
}
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
function generateHelp() {
|
||||
const lines = [];
|
||||
lines.push("Usage: playwright-cli <command> [options]");
|
||||
lines.push("Commands:");
|
||||
for (const command of Object.values(import_commands.commands))
|
||||
lines.push(" " + generateHelpEntry(command));
|
||||
return lines.join("\n");
|
||||
}
|
||||
function generateHelpEntry(command) {
|
||||
const args = [];
|
||||
const shape = command.args.shape;
|
||||
for (const [name, schema] of Object.entries(shape)) {
|
||||
const zodSchema = schema;
|
||||
const description = zodSchema.description ?? "";
|
||||
args.push({ name, description });
|
||||
}
|
||||
const prefix = `${command.name} ${Object.keys(shape).map((k) => `<${k}>`).join(" ")}`;
|
||||
const suffix = command.description.toLowerCase();
|
||||
const padding = " ".repeat(Math.max(1, 40 - prefix.length));
|
||||
return prefix + padding + suffix;
|
||||
}
|
||||
async function main() {
|
||||
const help = {
|
||||
global: generateHelp(),
|
||||
commands: Object.fromEntries(
|
||||
Object.entries(import_commands.commands).map(([name, command]) => [name, generateCommandHelp(command)])
|
||||
)
|
||||
};
|
||||
const fileName = import_path.default.resolve(__dirname, "help.json").replace("lib", "src");
|
||||
console.log("Writing ", import_path.default.relative(process.cwd(), fileName));
|
||||
await import_fs.default.promises.writeFile(fileName, JSON.stringify(help, null, 2));
|
||||
}
|
||||
void main();
|
||||
80
backend/node_modules/playwright/lib/mcp/terminal/socketConnection.js
generated
vendored
Normal file
80
backend/node_modules/playwright/lib/mcp/terminal/socketConnection.js
generated
vendored
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var socketConnection_exports = {};
|
||||
__export(socketConnection_exports, {
|
||||
SocketConnection: () => SocketConnection
|
||||
});
|
||||
module.exports = __toCommonJS(socketConnection_exports);
|
||||
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
|
||||
const daemonDebug = (0, import_utilsBundle.debug)("pw:daemon");
|
||||
class SocketConnection {
|
||||
constructor(socket) {
|
||||
this._pendingBuffers = [];
|
||||
this._socket = socket;
|
||||
socket.on("data", (buffer) => this._onData(buffer));
|
||||
socket.on("close", () => {
|
||||
this.onclose?.();
|
||||
});
|
||||
socket.on("error", (e) => daemonDebug(`error: ${e.message}`));
|
||||
}
|
||||
async send(message) {
|
||||
await new Promise((resolve, reject) => {
|
||||
this._socket.write(`${JSON.stringify(message)}
|
||||
`, (error) => {
|
||||
if (error)
|
||||
reject(error);
|
||||
else
|
||||
resolve(void 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
close() {
|
||||
this._socket.destroy();
|
||||
}
|
||||
_onData(buffer) {
|
||||
let end = buffer.indexOf("\n");
|
||||
if (end === -1) {
|
||||
this._pendingBuffers.push(buffer);
|
||||
return;
|
||||
}
|
||||
this._pendingBuffers.push(buffer.slice(0, end));
|
||||
const message = Buffer.concat(this._pendingBuffers).toString();
|
||||
this._dispatchMessage(message);
|
||||
let start = end + 1;
|
||||
end = buffer.indexOf("\n", start);
|
||||
while (end !== -1) {
|
||||
const message2 = buffer.toString(void 0, start, end);
|
||||
this._dispatchMessage(message2);
|
||||
start = end + 1;
|
||||
end = buffer.indexOf("\n", start);
|
||||
}
|
||||
this._pendingBuffers = [buffer.slice(start)];
|
||||
}
|
||||
_dispatchMessage(message) {
|
||||
try {
|
||||
this.onmessage?.(JSON.parse(message));
|
||||
} catch (e) {
|
||||
daemonDebug("failed to dispatch message", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
SocketConnection
|
||||
});
|
||||
98
backend/node_modules/playwright/lib/mcp/test/browserBackend.js
generated
vendored
Normal file
98
backend/node_modules/playwright/lib/mcp/test/browserBackend.js
generated
vendored
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var browserBackend_exports = {};
|
||||
__export(browserBackend_exports, {
|
||||
createCustomMessageHandler: () => createCustomMessageHandler
|
||||
});
|
||||
module.exports = __toCommonJS(browserBackend_exports);
|
||||
var import_config = require("../browser/config");
|
||||
var import_browserServerBackend = require("../browser/browserServerBackend");
|
||||
var import_tab = require("../browser/tab");
|
||||
var import_util = require("../../util");
|
||||
var import_browserContextFactory = require("../browser/browserContextFactory");
|
||||
function createCustomMessageHandler(testInfo, context) {
|
||||
let backend;
|
||||
return async (data) => {
|
||||
if (data.initialize) {
|
||||
if (backend)
|
||||
throw new Error("MCP backend is already initialized");
|
||||
backend = new import_browserServerBackend.BrowserServerBackend({ ...import_config.defaultConfig, capabilities: ["testing"] }, (0, import_browserContextFactory.identityBrowserContextFactory)(context));
|
||||
await backend.initialize(data.initialize.clientInfo);
|
||||
const pausedMessage = await generatePausedMessage(testInfo, context);
|
||||
return { initialize: { pausedMessage } };
|
||||
}
|
||||
if (data.listTools) {
|
||||
if (!backend)
|
||||
throw new Error("MCP backend is not initialized");
|
||||
return { listTools: await backend.listTools() };
|
||||
}
|
||||
if (data.callTool) {
|
||||
if (!backend)
|
||||
throw new Error("MCP backend is not initialized");
|
||||
return { callTool: await backend.callTool(data.callTool.name, data.callTool.arguments) };
|
||||
}
|
||||
if (data.close) {
|
||||
backend?.serverClosed();
|
||||
backend = void 0;
|
||||
return { close: {} };
|
||||
}
|
||||
throw new Error("Unknown MCP request");
|
||||
};
|
||||
}
|
||||
async function generatePausedMessage(testInfo, context) {
|
||||
const lines = [];
|
||||
if (testInfo.errors.length) {
|
||||
lines.push(`### Paused on error:`);
|
||||
for (const error of testInfo.errors)
|
||||
lines.push((0, import_util.stripAnsiEscapes)(error.message || ""));
|
||||
} else {
|
||||
lines.push(`### Paused at end of test. ready for interaction`);
|
||||
}
|
||||
for (let i = 0; i < context.pages().length; i++) {
|
||||
const page = context.pages()[i];
|
||||
const stateSuffix = context.pages().length > 1 ? i + 1 + " of " + context.pages().length : "state";
|
||||
lines.push(
|
||||
"",
|
||||
`### Page ${stateSuffix}`,
|
||||
`- Page URL: ${page.url()}`,
|
||||
`- Page Title: ${await page.title()}`.trim()
|
||||
);
|
||||
let console = testInfo.errors.length ? await import_tab.Tab.collectConsoleMessages(page) : [];
|
||||
console = console.filter((msg) => msg.type === "error");
|
||||
if (console.length) {
|
||||
lines.push("- Console Messages:");
|
||||
for (const message of console)
|
||||
lines.push(` - ${message.toString()}`);
|
||||
}
|
||||
lines.push(
|
||||
`- Page Snapshot:`,
|
||||
"```yaml",
|
||||
(await page._snapshotForAI()).full,
|
||||
"```"
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
if (testInfo.errors.length)
|
||||
lines.push(`### Task`, `Try recovering from the error prior to continuing`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
createCustomMessageHandler
|
||||
});
|
||||
122
backend/node_modules/playwright/lib/mcp/test/generatorTools.js
generated
vendored
Normal file
122
backend/node_modules/playwright/lib/mcp/test/generatorTools.js
generated
vendored
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var generatorTools_exports = {};
|
||||
__export(generatorTools_exports, {
|
||||
generatorReadLog: () => generatorReadLog,
|
||||
generatorWriteTest: () => generatorWriteTest,
|
||||
setupPage: () => setupPage
|
||||
});
|
||||
module.exports = __toCommonJS(generatorTools_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_testTool = require("./testTool");
|
||||
var import_testContext = require("./testContext");
|
||||
const setupPage = (0, import_testTool.defineTestTool)({
|
||||
schema: {
|
||||
name: "generator_setup_page",
|
||||
title: "Setup generator page",
|
||||
description: "Setup the page for test.",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
plan: import_mcpBundle.z.string().describe("The plan for the test. This should be the actual test plan with all the steps."),
|
||||
project: import_mcpBundle.z.string().optional().describe('Project to use for setup. For example: "chromium", if no project is provided uses the first project in the config.'),
|
||||
seedFile: import_mcpBundle.z.string().optional().describe('A seed file contains a single test that is used to setup the page for testing, for example: "tests/seed.spec.ts". If no seed file is provided, a default seed file is created.')
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params) => {
|
||||
const seed = await context.getOrCreateSeedFile(params.seedFile, params.project);
|
||||
context.generatorJournal = new import_testContext.GeneratorJournal(context.rootPath, params.plan, seed);
|
||||
const { output, status } = await context.runSeedTest(seed.file, seed.projectName);
|
||||
return { content: [{ type: "text", text: output }], isError: status !== "paused" };
|
||||
}
|
||||
});
|
||||
const generatorReadLog = (0, import_testTool.defineTestTool)({
|
||||
schema: {
|
||||
name: "generator_read_log",
|
||||
title: "Retrieve test log",
|
||||
description: "Retrieve the performed test log",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context) => {
|
||||
if (!context.generatorJournal)
|
||||
throw new Error(`Please setup page using "${setupPage.schema.name}" first.`);
|
||||
const result = context.generatorJournal.journal();
|
||||
return { content: [{
|
||||
type: "text",
|
||||
text: result
|
||||
}] };
|
||||
}
|
||||
});
|
||||
const generatorWriteTest = (0, import_testTool.defineTestTool)({
|
||||
schema: {
|
||||
name: "generator_write_test",
|
||||
title: "Write test",
|
||||
description: "Write the generated test to the test file",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
fileName: import_mcpBundle.z.string().describe("The file to write the test to"),
|
||||
code: import_mcpBundle.z.string().describe("The generated test code")
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params) => {
|
||||
if (!context.generatorJournal)
|
||||
throw new Error(`Please setup page using "${setupPage.schema.name}" first.`);
|
||||
const testRunner = context.existingTestRunner();
|
||||
if (!testRunner)
|
||||
throw new Error("No test runner found, please setup page and perform actions first.");
|
||||
const config = await testRunner.loadConfig();
|
||||
const dirs = [];
|
||||
for (const project of config.projects) {
|
||||
const testDir = import_path.default.relative(context.rootPath, project.project.testDir).replace(/\\/g, "/");
|
||||
const fileName = params.fileName.replace(/\\/g, "/");
|
||||
if (fileName.startsWith(testDir)) {
|
||||
const resolvedFile = import_path.default.resolve(context.rootPath, fileName);
|
||||
await import_fs.default.promises.mkdir(import_path.default.dirname(resolvedFile), { recursive: true });
|
||||
await import_fs.default.promises.writeFile(resolvedFile, params.code);
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `### Result
|
||||
Test written to ${params.fileName}`
|
||||
}]
|
||||
};
|
||||
}
|
||||
dirs.push(testDir);
|
||||
}
|
||||
throw new Error(`Test file did not match any of the test dirs: ${dirs.join(", ")}`);
|
||||
}
|
||||
});
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
generatorReadLog,
|
||||
generatorWriteTest,
|
||||
setupPage
|
||||
});
|
||||
145
backend/node_modules/playwright/lib/mcp/test/plannerTools.js
generated
vendored
Normal file
145
backend/node_modules/playwright/lib/mcp/test/plannerTools.js
generated
vendored
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var plannerTools_exports = {};
|
||||
__export(plannerTools_exports, {
|
||||
saveTestPlan: () => saveTestPlan,
|
||||
setupPage: () => setupPage,
|
||||
submitTestPlan: () => submitTestPlan
|
||||
});
|
||||
module.exports = __toCommonJS(plannerTools_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_testTool = require("./testTool");
|
||||
const setupPage = (0, import_testTool.defineTestTool)({
|
||||
schema: {
|
||||
name: "planner_setup_page",
|
||||
title: "Setup planner page",
|
||||
description: "Setup the page for test planning",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
project: import_mcpBundle.z.string().optional().describe('Project to use for setup. For example: "chromium", if no project is provided uses the first project in the config.'),
|
||||
seedFile: import_mcpBundle.z.string().optional().describe('A seed file contains a single test that is used to setup the page for testing, for example: "tests/seed.spec.ts". If no seed file is provided, a default seed file is created.')
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params) => {
|
||||
const seed = await context.getOrCreateSeedFile(params.seedFile, params.project);
|
||||
const { output, status } = await context.runSeedTest(seed.file, seed.projectName);
|
||||
return { content: [{ type: "text", text: output }], isError: status !== "paused" };
|
||||
}
|
||||
});
|
||||
const planSchema = import_mcpBundle.z.object({
|
||||
overview: import_mcpBundle.z.string().describe("A brief overview of the application to be tested"),
|
||||
suites: import_mcpBundle.z.array(import_mcpBundle.z.object({
|
||||
name: import_mcpBundle.z.string().describe("The name of the suite"),
|
||||
seedFile: import_mcpBundle.z.string().describe("A seed file that was used to setup the page for testing."),
|
||||
tests: import_mcpBundle.z.array(import_mcpBundle.z.object({
|
||||
name: import_mcpBundle.z.string().describe("The name of the test"),
|
||||
file: import_mcpBundle.z.string().describe('The file the test should be saved to, for example: "tests/<suite-name>/<test-name>.spec.ts".'),
|
||||
steps: import_mcpBundle.z.array(import_mcpBundle.z.object({
|
||||
perform: import_mcpBundle.z.string().optional().describe(`Action to perform. For example: 'Click on the "Submit" button'.`),
|
||||
expect: import_mcpBundle.z.string().array().describe(`Expected result of the action where appropriate. For example: 'The page should show the "Thank you for your submission" message'`)
|
||||
}))
|
||||
}))
|
||||
}))
|
||||
});
|
||||
const submitTestPlan = (0, import_testTool.defineTestTool)({
|
||||
schema: {
|
||||
name: "planner_submit_plan",
|
||||
title: "Submit test plan",
|
||||
description: "Submit the test plan to the test planner",
|
||||
inputSchema: planSchema,
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params) => {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: JSON.stringify(params, null, 2)
|
||||
}]
|
||||
};
|
||||
}
|
||||
});
|
||||
const saveTestPlan = (0, import_testTool.defineTestTool)({
|
||||
schema: {
|
||||
name: "planner_save_plan",
|
||||
title: "Save test plan as markdown file",
|
||||
description: "Save the test plan as a markdown file",
|
||||
inputSchema: planSchema.extend({
|
||||
name: import_mcpBundle.z.string().describe('The name of the test plan, for example: "Test Plan".'),
|
||||
fileName: import_mcpBundle.z.string().describe('The file to save the test plan to, for example: "spec/test.plan.md". Relative to the workspace root.')
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params) => {
|
||||
const lines = [];
|
||||
lines.push(`# ${params.name}`);
|
||||
lines.push(``);
|
||||
lines.push(`## Application Overview`);
|
||||
lines.push(``);
|
||||
lines.push(params.overview);
|
||||
lines.push(``);
|
||||
lines.push(`## Test Scenarios`);
|
||||
for (let i = 0; i < params.suites.length; i++) {
|
||||
lines.push(``);
|
||||
const suite = params.suites[i];
|
||||
lines.push(`### ${i + 1}. ${suite.name}`);
|
||||
lines.push(``);
|
||||
lines.push(`**Seed:** \`${suite.seedFile}\``);
|
||||
for (let j = 0; j < suite.tests.length; j++) {
|
||||
lines.push(``);
|
||||
const test = suite.tests[j];
|
||||
lines.push(`#### ${i + 1}.${j + 1}. ${test.name}`);
|
||||
lines.push(``);
|
||||
lines.push(`**File:** \`${test.file}\``);
|
||||
lines.push(``);
|
||||
lines.push(`**Steps:**`);
|
||||
for (let k = 0; k < test.steps.length; k++) {
|
||||
lines.push(` ${k + 1}. ${test.steps[k].perform ?? "-"}`);
|
||||
for (const expect of test.steps[k].expect)
|
||||
lines.push(` - expect: ${expect}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.push(``);
|
||||
await import_fs.default.promises.writeFile(import_path.default.resolve(context.rootPath, params.fileName), lines.join("\n"));
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `Test plan saved to ${params.fileName}`
|
||||
}]
|
||||
};
|
||||
}
|
||||
});
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
saveTestPlan,
|
||||
setupPage,
|
||||
submitTestPlan
|
||||
});
|
||||
82
backend/node_modules/playwright/lib/mcp/test/seed.js
generated
vendored
Normal file
82
backend/node_modules/playwright/lib/mcp/test/seed.js
generated
vendored
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var seed_exports = {};
|
||||
__export(seed_exports, {
|
||||
defaultSeedFile: () => defaultSeedFile,
|
||||
ensureSeedFile: () => ensureSeedFile,
|
||||
findSeedFile: () => findSeedFile,
|
||||
seedFileContent: () => seedFileContent,
|
||||
seedProject: () => seedProject
|
||||
});
|
||||
module.exports = __toCommonJS(seed_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_projectUtils = require("../../runner/projectUtils");
|
||||
function seedProject(config, projectName) {
|
||||
if (!projectName)
|
||||
return (0, import_projectUtils.findTopLevelProjects)(config)[0];
|
||||
const project = config.projects.find((p) => p.project.name === projectName);
|
||||
if (!project)
|
||||
throw new Error(`Project ${projectName} not found`);
|
||||
return project;
|
||||
}
|
||||
async function findSeedFile(project) {
|
||||
const files = await (0, import_projectUtils.collectFilesForProject)(project);
|
||||
return files.find((file) => import_path.default.basename(file).includes("seed"));
|
||||
}
|
||||
function defaultSeedFile(project) {
|
||||
const testDir = project.project.testDir;
|
||||
return import_path.default.resolve(testDir, "seed.spec.ts");
|
||||
}
|
||||
async function ensureSeedFile(project) {
|
||||
const seedFile = await findSeedFile(project);
|
||||
if (seedFile)
|
||||
return seedFile;
|
||||
const seedFilePath = defaultSeedFile(project);
|
||||
await (0, import_utils.mkdirIfNeeded)(seedFilePath);
|
||||
await import_fs.default.promises.writeFile(seedFilePath, seedFileContent);
|
||||
return seedFilePath;
|
||||
}
|
||||
const seedFileContent = `import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('Test group', () => {
|
||||
test('seed', async ({ page }) => {
|
||||
// generate code here.
|
||||
});
|
||||
});
|
||||
`;
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
defaultSeedFile,
|
||||
ensureSeedFile,
|
||||
findSeedFile,
|
||||
seedFileContent,
|
||||
seedProject
|
||||
});
|
||||
44
backend/node_modules/playwright/lib/mcp/test/streams.js
generated
vendored
Normal file
44
backend/node_modules/playwright/lib/mcp/test/streams.js
generated
vendored
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var streams_exports = {};
|
||||
__export(streams_exports, {
|
||||
StringWriteStream: () => StringWriteStream
|
||||
});
|
||||
module.exports = __toCommonJS(streams_exports);
|
||||
var import_stream = require("stream");
|
||||
var import_util = require("../../util");
|
||||
class StringWriteStream extends import_stream.Writable {
|
||||
constructor(output, stdio) {
|
||||
super();
|
||||
this._output = output;
|
||||
this._prefix = stdio === "stdout" ? "" : "[err] ";
|
||||
}
|
||||
_write(chunk, encoding, callback) {
|
||||
let text = (0, import_util.stripAnsiEscapes)(chunk.toString());
|
||||
if (text.endsWith("\n"))
|
||||
text = text.slice(0, -1);
|
||||
if (text)
|
||||
this._output.push(this._prefix + text);
|
||||
callback();
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
StringWriteStream
|
||||
});
|
||||
99
backend/node_modules/playwright/lib/mcp/test/testBackend.js
generated
vendored
Normal file
99
backend/node_modules/playwright/lib/mcp/test/testBackend.js
generated
vendored
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var testBackend_exports = {};
|
||||
__export(testBackend_exports, {
|
||||
TestServerBackend: () => TestServerBackend
|
||||
});
|
||||
module.exports = __toCommonJS(testBackend_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var mcp = __toESM(require("../sdk/exports"));
|
||||
var import_testContext = require("./testContext");
|
||||
var testTools = __toESM(require("./testTools.js"));
|
||||
var generatorTools = __toESM(require("./generatorTools.js"));
|
||||
var plannerTools = __toESM(require("./plannerTools.js"));
|
||||
var import_tools = require("../browser/tools");
|
||||
class TestServerBackend {
|
||||
constructor(configPath, options) {
|
||||
this.name = "Playwright";
|
||||
this.version = "0.0.1";
|
||||
this._tools = [
|
||||
plannerTools.saveTestPlan,
|
||||
plannerTools.setupPage,
|
||||
plannerTools.submitTestPlan,
|
||||
generatorTools.setupPage,
|
||||
generatorTools.generatorReadLog,
|
||||
generatorTools.generatorWriteTest,
|
||||
testTools.listTests,
|
||||
testTools.runTests,
|
||||
testTools.debugTest,
|
||||
...import_tools.browserTools.map((tool) => wrapBrowserTool(tool))
|
||||
];
|
||||
this._options = options || {};
|
||||
this._configPath = configPath;
|
||||
}
|
||||
async initialize(clientInfo) {
|
||||
this._context = new import_testContext.TestContext(clientInfo, this._configPath, this._options);
|
||||
}
|
||||
async listTools() {
|
||||
return this._tools.map((tool) => mcp.toMcpTool(tool.schema));
|
||||
}
|
||||
async callTool(name, args) {
|
||||
const tool = this._tools.find((tool2) => tool2.schema.name === name);
|
||||
if (!tool)
|
||||
throw new Error(`Tool not found: ${name}. Available tools: ${this._tools.map((tool2) => tool2.schema.name).join(", ")}`);
|
||||
try {
|
||||
return await tool.handle(this._context, tool.schema.inputSchema.parse(args || {}));
|
||||
} catch (e) {
|
||||
return { content: [{ type: "text", text: String(e) }], isError: true };
|
||||
}
|
||||
}
|
||||
serverClosed() {
|
||||
void this._context?.close();
|
||||
}
|
||||
}
|
||||
const typesWithIntent = ["action", "assertion", "input"];
|
||||
function wrapBrowserTool(tool) {
|
||||
const inputSchema = typesWithIntent.includes(tool.schema.type) ? tool.schema.inputSchema.extend({
|
||||
intent: import_mcpBundle.z.string().describe("The intent of the call, for example the test step description plan idea")
|
||||
}) : tool.schema.inputSchema;
|
||||
return {
|
||||
schema: {
|
||||
...tool.schema,
|
||||
inputSchema
|
||||
},
|
||||
handle: async (context, params) => {
|
||||
const response = await context.sendMessageToPausedTest({ callTool: { name: tool.schema.name, arguments: params } });
|
||||
return response.callTool;
|
||||
}
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
TestServerBackend
|
||||
});
|
||||
285
backend/node_modules/playwright/lib/mcp/test/testContext.js
generated
vendored
Normal file
285
backend/node_modules/playwright/lib/mcp/test/testContext.js
generated
vendored
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var testContext_exports = {};
|
||||
__export(testContext_exports, {
|
||||
GeneratorJournal: () => GeneratorJournal,
|
||||
TestContext: () => TestContext,
|
||||
createScreen: () => createScreen
|
||||
});
|
||||
module.exports = __toCommonJS(testContext_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_os = __toESM(require("os"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_utils = require("playwright-core/lib/utils");
|
||||
var import_base = require("../../reporters/base");
|
||||
var import_list = __toESM(require("../../reporters/list"));
|
||||
var import_streams = require("./streams");
|
||||
var import_util = require("../../util");
|
||||
var import_testRunner = require("../../runner/testRunner");
|
||||
var import_seed = require("./seed");
|
||||
var import_exports = require("../sdk/exports");
|
||||
var import_configLoader = require("../../common/configLoader");
|
||||
var import_response = require("../browser/response");
|
||||
var import_log = require("../log");
|
||||
class GeneratorJournal {
|
||||
constructor(rootPath, plan, seed) {
|
||||
this._rootPath = rootPath;
|
||||
this._plan = plan;
|
||||
this._seed = seed;
|
||||
this._steps = [];
|
||||
}
|
||||
logStep(title, code) {
|
||||
if (title)
|
||||
this._steps.push({ title, code });
|
||||
}
|
||||
journal() {
|
||||
const result = [];
|
||||
result.push(`# Plan`);
|
||||
result.push(this._plan);
|
||||
result.push(`# Seed file: ${(0, import_utils.toPosixPath)(import_path.default.relative(this._rootPath, this._seed.file))}`);
|
||||
result.push("```ts");
|
||||
result.push(this._seed.content);
|
||||
result.push("```");
|
||||
result.push(`# Steps`);
|
||||
result.push(this._steps.map((step) => `### ${step.title}
|
||||
\`\`\`ts
|
||||
${step.code}
|
||||
\`\`\``).join("\n\n"));
|
||||
result.push(bestPracticesMarkdown);
|
||||
return result.join("\n\n");
|
||||
}
|
||||
}
|
||||
class TestContext {
|
||||
constructor(clientInfo, configPath, options) {
|
||||
this._clientInfo = clientInfo;
|
||||
const rootPath = (0, import_exports.firstRootPath)(clientInfo);
|
||||
this._configLocation = (0, import_configLoader.resolveConfigLocation)(configPath || rootPath);
|
||||
this.rootPath = rootPath || this._configLocation.configDir;
|
||||
if (options?.headless !== void 0)
|
||||
this.computedHeaded = !options.headless;
|
||||
else
|
||||
this.computedHeaded = !process.env.CI && !(import_os.default.platform() === "linux" && !process.env.DISPLAY);
|
||||
}
|
||||
existingTestRunner() {
|
||||
return this._testRunnerAndScreen?.testRunner;
|
||||
}
|
||||
async _cleanupTestRunner() {
|
||||
if (!this._testRunnerAndScreen)
|
||||
return;
|
||||
await this._testRunnerAndScreen.testRunner.stopTests();
|
||||
this._testRunnerAndScreen.claimStdio();
|
||||
try {
|
||||
await this._testRunnerAndScreen.testRunner.runGlobalTeardown();
|
||||
} finally {
|
||||
this._testRunnerAndScreen.releaseStdio();
|
||||
this._testRunnerAndScreen = void 0;
|
||||
}
|
||||
}
|
||||
async createTestRunner() {
|
||||
await this._cleanupTestRunner();
|
||||
const testRunner = new import_testRunner.TestRunner(this._configLocation, {});
|
||||
await testRunner.initialize({});
|
||||
const testPaused = new import_utils.ManualPromise();
|
||||
const testRunnerAndScreen = {
|
||||
...createScreen(),
|
||||
testRunner,
|
||||
waitForTestPaused: () => testPaused
|
||||
};
|
||||
this._testRunnerAndScreen = testRunnerAndScreen;
|
||||
testRunner.on(import_testRunner.TestRunnerEvent.TestPaused, (params) => {
|
||||
testRunnerAndScreen.sendMessageToPausedTest = params.sendMessage;
|
||||
testPaused.resolve();
|
||||
});
|
||||
return testRunnerAndScreen;
|
||||
}
|
||||
async getOrCreateSeedFile(seedFile, projectName) {
|
||||
const configDir = this._configLocation.configDir;
|
||||
const { testRunner } = await this.createTestRunner();
|
||||
const config = await testRunner.loadConfig();
|
||||
const project = (0, import_seed.seedProject)(config, projectName);
|
||||
if (!seedFile) {
|
||||
seedFile = await (0, import_seed.ensureSeedFile)(project);
|
||||
} else {
|
||||
const candidateFiles = [];
|
||||
const testDir = project.project.testDir;
|
||||
candidateFiles.push(import_path.default.resolve(testDir, seedFile));
|
||||
candidateFiles.push(import_path.default.resolve(configDir, seedFile));
|
||||
candidateFiles.push(import_path.default.resolve(this.rootPath, seedFile));
|
||||
let resolvedSeedFile;
|
||||
for (const candidateFile of candidateFiles) {
|
||||
if (await (0, import_util.fileExistsAsync)(candidateFile)) {
|
||||
resolvedSeedFile = candidateFile;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!resolvedSeedFile)
|
||||
throw new Error("seed test not found.");
|
||||
seedFile = resolvedSeedFile;
|
||||
}
|
||||
const seedFileContent = await import_fs.default.promises.readFile(seedFile, "utf8");
|
||||
return {
|
||||
file: seedFile,
|
||||
content: seedFileContent,
|
||||
projectName: project.project.name
|
||||
};
|
||||
}
|
||||
async runSeedTest(seedFile, projectName) {
|
||||
const result = await this.runTestsWithGlobalSetupAndPossiblePause({
|
||||
headed: this.computedHeaded,
|
||||
locations: ["/" + (0, import_utils.escapeRegExp)(seedFile) + "/"],
|
||||
projects: [projectName],
|
||||
timeout: 0,
|
||||
workers: 1,
|
||||
pauseAtEnd: true,
|
||||
disableConfigReporters: true,
|
||||
failOnLoadErrors: true
|
||||
});
|
||||
if (result.status === "passed")
|
||||
result.output += "\nError: seed test not found.";
|
||||
else if (result.status !== "paused")
|
||||
result.output += "\nError while running the seed test.";
|
||||
return result;
|
||||
}
|
||||
async runTestsWithGlobalSetupAndPossiblePause(params) {
|
||||
const configDir = this._configLocation.configDir;
|
||||
const testRunnerAndScreen = await this.createTestRunner();
|
||||
const { testRunner, screen, claimStdio, releaseStdio } = testRunnerAndScreen;
|
||||
claimStdio();
|
||||
try {
|
||||
const setupReporter = new MCPListReporter({ configDir, screen, includeTestId: true });
|
||||
const { status: status2 } = await testRunner.runGlobalSetup([setupReporter]);
|
||||
if (status2 !== "passed")
|
||||
return { output: testRunnerAndScreen.output.join("\n"), status: status2 };
|
||||
} finally {
|
||||
releaseStdio();
|
||||
}
|
||||
let status = "passed";
|
||||
const cleanup = async () => {
|
||||
claimStdio();
|
||||
try {
|
||||
const result = await testRunner.runGlobalTeardown();
|
||||
if (status === "passed")
|
||||
status = result.status;
|
||||
} finally {
|
||||
releaseStdio();
|
||||
}
|
||||
};
|
||||
try {
|
||||
const reporter = new MCPListReporter({ configDir, screen, includeTestId: true });
|
||||
status = await Promise.race([
|
||||
testRunner.runTests(reporter, params).then((result) => result.status),
|
||||
testRunnerAndScreen.waitForTestPaused().then(() => "paused")
|
||||
]);
|
||||
if (status === "paused") {
|
||||
const response = await testRunnerAndScreen.sendMessageToPausedTest({ request: { initialize: { clientInfo: this._clientInfo } } });
|
||||
if (response.error)
|
||||
throw new Error(response.error.message);
|
||||
testRunnerAndScreen.output.push(response.response.initialize.pausedMessage);
|
||||
return { output: testRunnerAndScreen.output.join("\n"), status };
|
||||
}
|
||||
} catch (e) {
|
||||
status = "failed";
|
||||
testRunnerAndScreen.output.push(String(e));
|
||||
await cleanup();
|
||||
return { output: testRunnerAndScreen.output.join("\n"), status };
|
||||
}
|
||||
await cleanup();
|
||||
return { output: testRunnerAndScreen.output.join("\n"), status };
|
||||
}
|
||||
async close() {
|
||||
await this._cleanupTestRunner().catch(import_log.logUnhandledError);
|
||||
}
|
||||
async sendMessageToPausedTest(request) {
|
||||
const sendMessage = this._testRunnerAndScreen?.sendMessageToPausedTest;
|
||||
if (!sendMessage)
|
||||
throw new Error("Must setup test before interacting with the page");
|
||||
const result = await sendMessage({ request });
|
||||
if (result.error)
|
||||
throw new Error(result.error.message);
|
||||
if (typeof request?.callTool?.arguments?.["intent"] === "string") {
|
||||
const response = (0, import_response.parseResponse)(result.response.callTool);
|
||||
if (response && !response.isError && response.code)
|
||||
this.generatorJournal?.logStep(request.callTool.arguments["intent"], response.code);
|
||||
}
|
||||
return result.response;
|
||||
}
|
||||
}
|
||||
function createScreen() {
|
||||
const output = [];
|
||||
const stdout = new import_streams.StringWriteStream(output, "stdout");
|
||||
const stderr = new import_streams.StringWriteStream(output, "stderr");
|
||||
const screen = {
|
||||
...import_base.terminalScreen,
|
||||
isTTY: false,
|
||||
colors: import_utils.noColors,
|
||||
stdout,
|
||||
stderr
|
||||
};
|
||||
const originalStdoutWrite = process.stdout.write;
|
||||
const originalStderrWrite = process.stderr.write;
|
||||
const claimStdio = () => {
|
||||
process.stdout.write = (chunk) => {
|
||||
stdout.write(chunk);
|
||||
return true;
|
||||
};
|
||||
process.stderr.write = (chunk) => {
|
||||
stderr.write(chunk);
|
||||
return true;
|
||||
};
|
||||
};
|
||||
const releaseStdio = () => {
|
||||
process.stdout.write = originalStdoutWrite;
|
||||
process.stderr.write = originalStderrWrite;
|
||||
};
|
||||
return { screen, claimStdio, releaseStdio, output };
|
||||
}
|
||||
const bestPracticesMarkdown = `
|
||||
# Best practices
|
||||
- Do not improvise, do not add directives that were not asked for
|
||||
- Use clear, descriptive assertions to validate the expected behavior
|
||||
- Use reliable locators from this log
|
||||
- Use local variables for locators that are used multiple times
|
||||
- Use Playwright waiting assertions and best practices from this log
|
||||
- NEVER! use page.waitForLoadState()
|
||||
- NEVER! use page.waitForNavigation()
|
||||
- NEVER! use page.waitForTimeout()
|
||||
- NEVER! use page.evaluate()
|
||||
`;
|
||||
class MCPListReporter extends import_list.default {
|
||||
async onTestPaused() {
|
||||
await new Promise(() => {
|
||||
});
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
GeneratorJournal,
|
||||
TestContext,
|
||||
createScreen
|
||||
});
|
||||
30
backend/node_modules/playwright/lib/mcp/test/testTool.js
generated
vendored
Normal file
30
backend/node_modules/playwright/lib/mcp/test/testTool.js
generated
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var testTool_exports = {};
|
||||
__export(testTool_exports, {
|
||||
defineTestTool: () => defineTestTool
|
||||
});
|
||||
module.exports = __toCommonJS(testTool_exports);
|
||||
function defineTestTool(tool) {
|
||||
return tool;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
defineTestTool
|
||||
});
|
||||
108
backend/node_modules/playwright/lib/mcp/test/testTools.js
generated
vendored
Normal file
108
backend/node_modules/playwright/lib/mcp/test/testTools.js
generated
vendored
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
var testTools_exports = {};
|
||||
__export(testTools_exports, {
|
||||
debugTest: () => debugTest,
|
||||
listTests: () => listTests,
|
||||
runTests: () => runTests
|
||||
});
|
||||
module.exports = __toCommonJS(testTools_exports);
|
||||
var import_mcpBundle = require("playwright-core/lib/mcpBundle");
|
||||
var import_listModeReporter = __toESM(require("../../reporters/listModeReporter"));
|
||||
var import_testTool = require("./testTool");
|
||||
const listTests = (0, import_testTool.defineTestTool)({
|
||||
schema: {
|
||||
name: "test_list",
|
||||
title: "List tests",
|
||||
description: "List tests",
|
||||
inputSchema: import_mcpBundle.z.object({}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context) => {
|
||||
const { testRunner, screen, output } = await context.createTestRunner();
|
||||
const reporter = new import_listModeReporter.default({ screen, includeTestId: true });
|
||||
await testRunner.listTests(reporter, {});
|
||||
return { content: output.map((text) => ({ type: "text", text })) };
|
||||
}
|
||||
});
|
||||
const runTests = (0, import_testTool.defineTestTool)({
|
||||
schema: {
|
||||
name: "test_run",
|
||||
title: "Run tests",
|
||||
description: "Run tests",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
locations: import_mcpBundle.z.array(import_mcpBundle.z.string()).optional().describe('Folder, file or location to run: "test/e2e" or "test/e2e/file.spec.ts" or "test/e2e/file.spec.ts:20"'),
|
||||
projects: import_mcpBundle.z.array(import_mcpBundle.z.string()).optional().describe('Projects to run, projects from playwright.config.ts, by default runs all projects. Running with "chromium" is a good start')
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params) => {
|
||||
const { output } = await context.runTestsWithGlobalSetupAndPossiblePause({
|
||||
locations: params.locations ?? [],
|
||||
projects: params.projects,
|
||||
disableConfigReporters: true
|
||||
});
|
||||
return { content: [{ type: "text", text: output }] };
|
||||
}
|
||||
});
|
||||
const debugTest = (0, import_testTool.defineTestTool)({
|
||||
schema: {
|
||||
name: "test_debug",
|
||||
title: "Debug single test",
|
||||
description: "Debug single test",
|
||||
inputSchema: import_mcpBundle.z.object({
|
||||
test: import_mcpBundle.z.object({
|
||||
id: import_mcpBundle.z.string().describe("Test ID to debug."),
|
||||
title: import_mcpBundle.z.string().describe("Human readable test title for granting permission to debug the test.")
|
||||
})
|
||||
}),
|
||||
type: "readOnly"
|
||||
},
|
||||
handle: async (context, params) => {
|
||||
const { output, status } = await context.runTestsWithGlobalSetupAndPossiblePause({
|
||||
headed: context.computedHeaded,
|
||||
locations: [],
|
||||
// we can make this faster by passing the test's location, so we don't need to scan all tests to find the ID
|
||||
testIds: [params.test.id],
|
||||
// For automatic recovery
|
||||
timeout: 0,
|
||||
workers: 1,
|
||||
pauseOnError: true,
|
||||
disableConfigReporters: true,
|
||||
actionTimeout: 5e3
|
||||
});
|
||||
return { content: [{ type: "text", text: output }], isError: status !== "paused" && status !== "passed" };
|
||||
}
|
||||
});
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
debugTest,
|
||||
listTests,
|
||||
runTests
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue