First Commit
This commit is contained in:
BIN
node_modules/playwright-core/lib/server/chromium/appIcon.png
generated
vendored
Normal file
BIN
node_modules/playwright-core/lib/server/chromium/appIcon.png
generated
vendored
Normal file
Binary file not shown.
After Width: | Height: | Size: 16 KiB |
391
node_modules/playwright-core/lib/server/chromium/chromium.js
generated
vendored
Normal file
391
node_modules/playwright-core/lib/server/chromium/chromium.js
generated
vendored
Normal file
@@ -0,0 +1,391 @@
|
||||
"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 chromium_exports = {};
|
||||
__export(chromium_exports, {
|
||||
Chromium: () => Chromium,
|
||||
waitForReadyState: () => waitForReadyState
|
||||
});
|
||||
module.exports = __toCommonJS(chromium_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_os = __toESM(require("os"));
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_chromiumSwitches = require("./chromiumSwitches");
|
||||
var import_crBrowser = require("./crBrowser");
|
||||
var import_crConnection = require("./crConnection");
|
||||
var import_utils = require("../../utils");
|
||||
var import_ascii = require("../utils/ascii");
|
||||
var import_debugLogger = require("../utils/debugLogger");
|
||||
var import_manualPromise = require("../../utils/isomorphic/manualPromise");
|
||||
var import_network = require("../utils/network");
|
||||
var import_userAgent = require("../utils/userAgent");
|
||||
var import_browserContext = require("../browserContext");
|
||||
var import_browserType = require("../browserType");
|
||||
var import_helper = require("../helper");
|
||||
var import_registry = require("../registry");
|
||||
var import_transport = require("../transport");
|
||||
var import_crDevTools = require("./crDevTools");
|
||||
var import_browser = require("../browser");
|
||||
var import_fileUtils = require("../utils/fileUtils");
|
||||
var import_processLauncher = require("../utils/processLauncher");
|
||||
const ARTIFACTS_FOLDER = import_path.default.join(import_os.default.tmpdir(), "playwright-artifacts-");
|
||||
class Chromium extends import_browserType.BrowserType {
|
||||
constructor(parent) {
|
||||
super(parent, "chromium");
|
||||
if ((0, import_utils.debugMode)() === "inspector")
|
||||
this._devtools = this._createDevTools();
|
||||
}
|
||||
async connectOverCDP(progress, endpointURL, options) {
|
||||
return await this._connectOverCDPInternal(progress, endpointURL, options);
|
||||
}
|
||||
async _connectOverCDPInternal(progress, endpointURL, options, onClose) {
|
||||
let headersMap;
|
||||
if (options.headers)
|
||||
headersMap = (0, import_utils.headersArrayToObject)(options.headers, false);
|
||||
if (!headersMap)
|
||||
headersMap = { "User-Agent": (0, import_userAgent.getUserAgent)() };
|
||||
else if (headersMap && !Object.keys(headersMap).some((key) => key.toLowerCase() === "user-agent"))
|
||||
headersMap["User-Agent"] = (0, import_userAgent.getUserAgent)();
|
||||
const artifactsDir = await progress.race(import_fs.default.promises.mkdtemp(ARTIFACTS_FOLDER));
|
||||
const doCleanup = async () => {
|
||||
await (0, import_fileUtils.removeFolders)([artifactsDir]);
|
||||
const cb = onClose;
|
||||
onClose = void 0;
|
||||
await cb?.();
|
||||
};
|
||||
let chromeTransport;
|
||||
const doClose = async () => {
|
||||
await chromeTransport?.closeAndWait();
|
||||
await doCleanup();
|
||||
};
|
||||
try {
|
||||
const wsEndpoint = await urlToWSEndpoint(progress, endpointURL, headersMap);
|
||||
chromeTransport = await import_transport.WebSocketTransport.connect(progress, wsEndpoint, { headers: headersMap });
|
||||
const browserProcess = { close: doClose, kill: doClose };
|
||||
const persistent = { noDefaultViewport: true };
|
||||
const browserOptions = {
|
||||
slowMo: options.slowMo,
|
||||
name: "chromium",
|
||||
isChromium: true,
|
||||
persistent,
|
||||
browserProcess,
|
||||
protocolLogger: import_helper.helper.debugProtocolLogger(),
|
||||
browserLogsCollector: new import_debugLogger.RecentLogsCollector(),
|
||||
artifactsDir,
|
||||
downloadsPath: options.downloadsPath || artifactsDir,
|
||||
tracesDir: options.tracesDir || artifactsDir,
|
||||
originalLaunchOptions: {}
|
||||
};
|
||||
(0, import_browserContext.validateBrowserContextOptions)(persistent, browserOptions);
|
||||
const browser = await progress.race(import_crBrowser.CRBrowser.connect(this.attribution.playwright, chromeTransport, browserOptions));
|
||||
browser._isCollocatedWithServer = false;
|
||||
browser.on(import_browser.Browser.Events.Disconnected, doCleanup);
|
||||
return browser;
|
||||
} catch (error) {
|
||||
await doClose().catch(() => {
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
_createDevTools() {
|
||||
const directory = import_registry.registry.findExecutable("chromium").directory;
|
||||
return directory ? new import_crDevTools.CRDevTools(import_path.default.join(directory, "devtools-preferences.json")) : void 0;
|
||||
}
|
||||
async connectToTransport(transport, options, browserLogsCollector) {
|
||||
let devtools = this._devtools;
|
||||
if (options.__testHookForDevTools) {
|
||||
devtools = this._createDevTools();
|
||||
await options.__testHookForDevTools(devtools);
|
||||
}
|
||||
try {
|
||||
return await import_crBrowser.CRBrowser.connect(this.attribution.playwright, transport, options, devtools);
|
||||
} catch (e) {
|
||||
if (browserLogsCollector.recentLogs().some((log) => log.includes("Failed to create a ProcessSingleton for your profile directory."))) {
|
||||
throw new Error(
|
||||
"Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium."
|
||||
);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
doRewriteStartupLog(error) {
|
||||
if (!error.logs)
|
||||
return error;
|
||||
if (error.logs.includes("Missing X server"))
|
||||
error.logs = "\n" + (0, import_ascii.wrapInASCIIBox)(import_browserType.kNoXServerRunningError, 1);
|
||||
if (!error.logs.includes("crbug.com/357670") && !error.logs.includes("No usable sandbox!") && !error.logs.includes("crbug.com/638180"))
|
||||
return error;
|
||||
error.logs = [
|
||||
`Chromium sandboxing failed!`,
|
||||
`================================`,
|
||||
`To avoid the sandboxing issue, do either of the following:`,
|
||||
` - (preferred): Configure your environment to support sandboxing`,
|
||||
` - (alternative): Launch Chromium without sandbox using 'chromiumSandbox: false' option`,
|
||||
`================================`,
|
||||
``
|
||||
].join("\n");
|
||||
return error;
|
||||
}
|
||||
amendEnvironment(env) {
|
||||
return env;
|
||||
}
|
||||
attemptToGracefullyCloseBrowser(transport) {
|
||||
const message = { method: "Browser.close", id: import_crConnection.kBrowserCloseMessageId, params: {} };
|
||||
transport.send(message);
|
||||
}
|
||||
async _launchWithSeleniumHub(progress, hubUrl, options) {
|
||||
await progress.race(this._createArtifactDirs(options));
|
||||
if (!hubUrl.endsWith("/"))
|
||||
hubUrl = hubUrl + "/";
|
||||
const args = this._innerDefaultArgs(options);
|
||||
args.push("--remote-debugging-port=0");
|
||||
const isEdge = options.channel && options.channel.startsWith("msedge");
|
||||
let desiredCapabilities = {
|
||||
"browserName": isEdge ? "MicrosoftEdge" : "chrome",
|
||||
[isEdge ? "ms:edgeOptions" : "goog:chromeOptions"]: { args }
|
||||
};
|
||||
if (process.env.SELENIUM_REMOTE_CAPABILITIES) {
|
||||
const remoteCapabilities = parseSeleniumRemoteParams({ name: "capabilities", value: process.env.SELENIUM_REMOTE_CAPABILITIES }, progress);
|
||||
if (remoteCapabilities)
|
||||
desiredCapabilities = { ...desiredCapabilities, ...remoteCapabilities };
|
||||
}
|
||||
let headers = {};
|
||||
if (process.env.SELENIUM_REMOTE_HEADERS) {
|
||||
const remoteHeaders = parseSeleniumRemoteParams({ name: "headers", value: process.env.SELENIUM_REMOTE_HEADERS }, progress);
|
||||
if (remoteHeaders)
|
||||
headers = remoteHeaders;
|
||||
}
|
||||
progress.log(`<selenium> connecting to ${hubUrl}`);
|
||||
const response = await (0, import_network.fetchData)(progress, {
|
||||
url: hubUrl + "session",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
...headers
|
||||
},
|
||||
data: JSON.stringify({
|
||||
capabilities: { alwaysMatch: desiredCapabilities }
|
||||
})
|
||||
}, seleniumErrorHandler);
|
||||
const value = JSON.parse(response).value;
|
||||
const sessionId = value.sessionId;
|
||||
progress.log(`<selenium> connected to sessionId=${sessionId}`);
|
||||
const disconnectFromSelenium = async () => {
|
||||
progress.log(`<selenium> disconnecting from sessionId=${sessionId}`);
|
||||
await (0, import_network.fetchData)(void 0, {
|
||||
url: hubUrl + "session/" + sessionId,
|
||||
method: "DELETE",
|
||||
headers
|
||||
}).catch((error) => progress.log(`<error disconnecting from selenium>: ${error}`));
|
||||
progress.log(`<selenium> disconnected from sessionId=${sessionId}`);
|
||||
import_processLauncher.gracefullyCloseSet.delete(disconnectFromSelenium);
|
||||
};
|
||||
import_processLauncher.gracefullyCloseSet.add(disconnectFromSelenium);
|
||||
try {
|
||||
const capabilities = value.capabilities;
|
||||
let endpointURL;
|
||||
if (capabilities["se:cdp"]) {
|
||||
progress.log(`<selenium> using selenium v4`);
|
||||
const endpointURLString = addProtocol(capabilities["se:cdp"]);
|
||||
endpointURL = new URL(endpointURLString);
|
||||
if (endpointURL.hostname === "localhost" || endpointURL.hostname === "127.0.0.1")
|
||||
endpointURL.hostname = new URL(hubUrl).hostname;
|
||||
progress.log(`<selenium> retrieved endpoint ${endpointURL.toString()} for sessionId=${sessionId}`);
|
||||
} else {
|
||||
progress.log(`<selenium> using selenium v3`);
|
||||
const maybeChromeOptions = capabilities["goog:chromeOptions"];
|
||||
const chromeOptions = maybeChromeOptions && typeof maybeChromeOptions === "object" ? maybeChromeOptions : void 0;
|
||||
const debuggerAddress = chromeOptions && typeof chromeOptions.debuggerAddress === "string" ? chromeOptions.debuggerAddress : void 0;
|
||||
const chromeOptionsURL = typeof maybeChromeOptions === "string" ? maybeChromeOptions : void 0;
|
||||
const endpointURLString = addProtocol(debuggerAddress || chromeOptionsURL).replace("localhost", "127.0.0.1");
|
||||
progress.log(`<selenium> retrieved endpoint ${endpointURLString} for sessionId=${sessionId}`);
|
||||
endpointURL = new URL(endpointURLString);
|
||||
if (endpointURL.hostname === "localhost" || endpointURL.hostname === "127.0.0.1") {
|
||||
const sessionInfoUrl = new URL(hubUrl).origin + "/grid/api/testsession?session=" + sessionId;
|
||||
try {
|
||||
const sessionResponse = await (0, import_network.fetchData)(progress, {
|
||||
url: sessionInfoUrl,
|
||||
method: "GET",
|
||||
headers
|
||||
}, seleniumErrorHandler);
|
||||
const proxyId = JSON.parse(sessionResponse).proxyId;
|
||||
endpointURL.hostname = new URL(proxyId).hostname;
|
||||
progress.log(`<selenium> resolved endpoint ip ${endpointURL.toString()} for sessionId=${sessionId}`);
|
||||
} catch (e) {
|
||||
progress.log(`<selenium> unable to resolve endpoint ip for sessionId=${sessionId}, running in standalone?`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return await this._connectOverCDPInternal(progress, endpointURL.toString(), {
|
||||
...options,
|
||||
headers: (0, import_utils.headersObjectToArray)(headers)
|
||||
}, disconnectFromSelenium);
|
||||
} catch (e) {
|
||||
await disconnectFromSelenium();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
defaultArgs(options, isPersistent, userDataDir) {
|
||||
const chromeArguments = this._innerDefaultArgs(options);
|
||||
chromeArguments.push(`--user-data-dir=${userDataDir}`);
|
||||
if (options.cdpPort !== void 0)
|
||||
chromeArguments.push(`--remote-debugging-port=${options.cdpPort}`);
|
||||
else
|
||||
chromeArguments.push("--remote-debugging-pipe");
|
||||
if (isPersistent)
|
||||
chromeArguments.push("about:blank");
|
||||
else
|
||||
chromeArguments.push("--no-startup-window");
|
||||
return chromeArguments;
|
||||
}
|
||||
_innerDefaultArgs(options) {
|
||||
const { args = [] } = options;
|
||||
const userDataDirArg = args.find((arg) => arg.startsWith("--user-data-dir"));
|
||||
if (userDataDirArg)
|
||||
throw this._createUserDataDirArgMisuseError("--user-data-dir");
|
||||
if (args.find((arg) => arg.startsWith("--remote-debugging-pipe")))
|
||||
throw new Error("Playwright manages remote debugging connection itself.");
|
||||
if (args.find((arg) => !arg.startsWith("-")))
|
||||
throw new Error("Arguments can not specify page to be opened");
|
||||
const chromeArguments = [...(0, import_chromiumSwitches.chromiumSwitches)(options.assistantMode, options.channel)];
|
||||
if (import_os.default.platform() === "darwin") {
|
||||
chromeArguments.push("--enable-unsafe-swiftshader");
|
||||
}
|
||||
if (options.devtools)
|
||||
chromeArguments.push("--auto-open-devtools-for-tabs");
|
||||
if (options.headless) {
|
||||
chromeArguments.push("--headless");
|
||||
chromeArguments.push(
|
||||
"--hide-scrollbars",
|
||||
"--mute-audio",
|
||||
"--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4"
|
||||
);
|
||||
}
|
||||
if (options.chromiumSandbox !== true)
|
||||
chromeArguments.push("--no-sandbox");
|
||||
const proxy = options.proxyOverride || options.proxy;
|
||||
if (proxy) {
|
||||
const proxyURL = new URL(proxy.server);
|
||||
const isSocks = proxyURL.protocol === "socks5:";
|
||||
if (isSocks && !options.socksProxyPort) {
|
||||
chromeArguments.push(`--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE ${proxyURL.hostname}"`);
|
||||
}
|
||||
chromeArguments.push(`--proxy-server=${proxy.server}`);
|
||||
const proxyBypassRules = [];
|
||||
if (options.socksProxyPort)
|
||||
proxyBypassRules.push("<-loopback>");
|
||||
if (proxy.bypass)
|
||||
proxyBypassRules.push(...proxy.bypass.split(",").map((t) => t.trim()).map((t) => t.startsWith(".") ? "*" + t : t));
|
||||
if (!process.env.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK && !proxyBypassRules.includes("<-loopback>"))
|
||||
proxyBypassRules.push("<-loopback>");
|
||||
if (proxyBypassRules.length > 0)
|
||||
chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`);
|
||||
}
|
||||
chromeArguments.push(...args);
|
||||
return chromeArguments;
|
||||
}
|
||||
async waitForReadyState(options, browserLogsCollector) {
|
||||
return waitForReadyState(options, browserLogsCollector);
|
||||
}
|
||||
getExecutableName(options) {
|
||||
if (options.channel)
|
||||
return options.channel;
|
||||
return options.headless ? "chromium-headless-shell" : "chromium";
|
||||
}
|
||||
}
|
||||
async function waitForReadyState(options, browserLogsCollector) {
|
||||
if (options.cdpPort === void 0 && !options.args?.some((a) => a.startsWith("--remote-debugging-port")))
|
||||
return {};
|
||||
const result = new import_manualPromise.ManualPromise();
|
||||
browserLogsCollector.onMessage((message) => {
|
||||
if (message.includes("Failed to create a ProcessSingleton for your profile directory.")) {
|
||||
result.reject(new Error("Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium."));
|
||||
}
|
||||
const match = message.match(/DevTools listening on (.*)/);
|
||||
if (match)
|
||||
result.resolve({ wsEndpoint: match[1] });
|
||||
});
|
||||
return result;
|
||||
}
|
||||
async function urlToWSEndpoint(progress, endpointURL, headers) {
|
||||
if (endpointURL.startsWith("ws"))
|
||||
return endpointURL;
|
||||
progress.log(`<ws preparing> retrieving websocket url from ${endpointURL}`);
|
||||
const url = new URL(endpointURL);
|
||||
if (!url.pathname.endsWith("/"))
|
||||
url.pathname += "/";
|
||||
url.pathname += "json/version/";
|
||||
const httpURL = url.toString();
|
||||
const json = await (0, import_network.fetchData)(
|
||||
progress,
|
||||
{
|
||||
url: httpURL,
|
||||
headers
|
||||
},
|
||||
async (_, resp) => new Error(`Unexpected status ${resp.statusCode} when connecting to ${httpURL}.
|
||||
This does not look like a DevTools server, try connecting via ws://.`)
|
||||
);
|
||||
return JSON.parse(json).webSocketDebuggerUrl;
|
||||
}
|
||||
async function seleniumErrorHandler(params, response) {
|
||||
const body = await streamToString(response);
|
||||
let message = body;
|
||||
try {
|
||||
const json = JSON.parse(body);
|
||||
message = json.value.localizedMessage || json.value.message;
|
||||
} catch (e) {
|
||||
}
|
||||
return new Error(`Error connecting to Selenium at ${params.url}: ${message}`);
|
||||
}
|
||||
function addProtocol(url) {
|
||||
if (!["ws://", "wss://", "http://", "https://"].some((protocol) => url.startsWith(protocol)))
|
||||
return "http://" + url;
|
||||
return url;
|
||||
}
|
||||
function streamToString(stream) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
|
||||
stream.on("error", reject);
|
||||
stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
||||
});
|
||||
}
|
||||
function parseSeleniumRemoteParams(env, progress) {
|
||||
try {
|
||||
const parsed = JSON.parse(env.value);
|
||||
progress.log(`<selenium> using additional ${env.name} "${env.value}"`);
|
||||
return parsed;
|
||||
} catch (e) {
|
||||
progress.log(`<selenium> ignoring additional ${env.name} "${env.value}": ${e}`);
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
Chromium,
|
||||
waitForReadyState
|
||||
});
|
93
node_modules/playwright-core/lib/server/chromium/chromiumSwitches.js
generated
vendored
Normal file
93
node_modules/playwright-core/lib/server/chromium/chromiumSwitches.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 chromiumSwitches_exports = {};
|
||||
__export(chromiumSwitches_exports, {
|
||||
chromiumSwitches: () => chromiumSwitches
|
||||
});
|
||||
module.exports = __toCommonJS(chromiumSwitches_exports);
|
||||
const disabledFeatures = (assistantMode) => [
|
||||
// See https://github.com/microsoft/playwright/pull/10380
|
||||
"AcceptCHFrame",
|
||||
// See https://github.com/microsoft/playwright/issues/14047
|
||||
"AvoidUnnecessaryBeforeUnloadCheckSync",
|
||||
"DestroyProfileOnBrowserClose",
|
||||
// See https://github.com/microsoft/playwright/pull/13854
|
||||
"DialMediaRouteProvider",
|
||||
"GlobalMediaControls",
|
||||
// See https://github.com/microsoft/playwright/pull/27605
|
||||
"HttpsUpgrades",
|
||||
// Hides the Lens feature in the URL address bar. Its not working in unofficial builds.
|
||||
"LensOverlay",
|
||||
// See https://github.com/microsoft/playwright/pull/8162
|
||||
"MediaRouter",
|
||||
// See https://github.com/microsoft/playwright/issues/28023
|
||||
"PaintHolding",
|
||||
// See https://github.com/microsoft/playwright/issues/32230
|
||||
"ThirdPartyStoragePartitioning",
|
||||
// See https://github.com/microsoft/playwright/issues/16126
|
||||
"Translate",
|
||||
// See https://issues.chromium.org/u/1/issues/435410220
|
||||
"AutoDeElevate",
|
||||
assistantMode ? "AutomationControlled" : ""
|
||||
].filter(Boolean);
|
||||
const chromiumSwitches = (assistantMode, channel) => [
|
||||
"--disable-field-trial-config",
|
||||
// https://source.chromium.org/chromium/chromium/src/+/main:testing/variations/README.md
|
||||
"--disable-background-networking",
|
||||
"--disable-background-timer-throttling",
|
||||
"--disable-backgrounding-occluded-windows",
|
||||
"--disable-back-forward-cache",
|
||||
// Avoids surprises like main request not being intercepted during page.goBack().
|
||||
"--disable-breakpad",
|
||||
"--disable-client-side-phishing-detection",
|
||||
"--disable-component-extensions-with-background-pages",
|
||||
"--disable-component-update",
|
||||
// Avoids unneeded network activity after startup.
|
||||
"--no-default-browser-check",
|
||||
"--disable-default-apps",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-extensions",
|
||||
"--disable-features=" + disabledFeatures(assistantMode).join(","),
|
||||
channel === "chromium-tip-of-tree" ? "--enable-features=CDPScreenshotNewSurface" : "",
|
||||
"--allow-pre-commit-input",
|
||||
"--disable-hang-monitor",
|
||||
"--disable-ipc-flooding-protection",
|
||||
"--disable-popup-blocking",
|
||||
"--disable-prompt-on-repost",
|
||||
"--disable-renderer-backgrounding",
|
||||
"--force-color-profile=srgb",
|
||||
"--metrics-recording-only",
|
||||
"--no-first-run",
|
||||
"--password-store=basic",
|
||||
"--use-mock-keychain",
|
||||
// See https://chromium-review.googlesource.com/c/chromium/src/+/2436773
|
||||
"--no-service-autorun",
|
||||
"--export-tagged-pdf",
|
||||
// https://chromium-review.googlesource.com/c/chromium/src/+/4853540
|
||||
"--disable-search-engine-choice-screen",
|
||||
// https://issues.chromium.org/41491762
|
||||
"--unsafely-disable-devtools-self-xss-warnings",
|
||||
// Edge can potentially restart on Windows (msRelaunchNoCompatLayer) which looses its file descriptors (stdout/stderr) and CDP (3/4). Disable until fixed upstream.
|
||||
"--edge-skip-compat-layer-relaunch",
|
||||
assistantMode ? "" : "--enable-automation"
|
||||
].filter(Boolean);
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
chromiumSwitches
|
||||
});
|
263
node_modules/playwright-core/lib/server/chromium/crAccessibility.js
generated
vendored
Normal file
263
node_modules/playwright-core/lib/server/chromium/crAccessibility.js
generated
vendored
Normal file
@@ -0,0 +1,263 @@
|
||||
"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 crAccessibility_exports = {};
|
||||
__export(crAccessibility_exports, {
|
||||
getAccessibilityTree: () => getAccessibilityTree
|
||||
});
|
||||
module.exports = __toCommonJS(crAccessibility_exports);
|
||||
async function getAccessibilityTree(client, needle) {
|
||||
const { nodes } = await client.send("Accessibility.getFullAXTree");
|
||||
const tree = CRAXNode.createTree(client, nodes);
|
||||
return {
|
||||
tree,
|
||||
needle: needle ? await tree._findElement(needle) : null
|
||||
};
|
||||
}
|
||||
class CRAXNode {
|
||||
constructor(client, payload) {
|
||||
this._children = [];
|
||||
this._richlyEditable = false;
|
||||
this._editable = false;
|
||||
this._focusable = false;
|
||||
this._expanded = false;
|
||||
this._hidden = false;
|
||||
this._client = client;
|
||||
this._payload = payload;
|
||||
this._name = this._payload.name ? this._payload.name.value : "";
|
||||
this._role = this._payload.role ? this._payload.role.value : "Unknown";
|
||||
for (const property of this._payload.properties || []) {
|
||||
if (property.name === "editable") {
|
||||
this._richlyEditable = property.value.value === "richtext";
|
||||
this._editable = true;
|
||||
}
|
||||
if (property.name === "focusable")
|
||||
this._focusable = property.value.value;
|
||||
if (property.name === "expanded")
|
||||
this._expanded = property.value.value;
|
||||
if (property.name === "hidden")
|
||||
this._hidden = property.value.value;
|
||||
}
|
||||
}
|
||||
_isPlainTextField() {
|
||||
if (this._richlyEditable)
|
||||
return false;
|
||||
if (this._editable)
|
||||
return true;
|
||||
return this._role === "textbox" || this._role === "ComboBox" || this._role === "searchbox";
|
||||
}
|
||||
_isTextOnlyObject() {
|
||||
const role = this._role;
|
||||
return role === "LineBreak" || role === "text" || role === "InlineTextBox" || role === "StaticText";
|
||||
}
|
||||
_hasFocusableChild() {
|
||||
if (this._cachedHasFocusableChild === void 0) {
|
||||
this._cachedHasFocusableChild = false;
|
||||
for (const child of this._children) {
|
||||
if (child._focusable || child._hasFocusableChild()) {
|
||||
this._cachedHasFocusableChild = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return this._cachedHasFocusableChild;
|
||||
}
|
||||
children() {
|
||||
return this._children;
|
||||
}
|
||||
async _findElement(element) {
|
||||
const objectId = element._objectId;
|
||||
const { node: { backendNodeId } } = await this._client.send("DOM.describeNode", { objectId });
|
||||
const needle = this.find((node) => node._payload.backendDOMNodeId === backendNodeId);
|
||||
return needle || null;
|
||||
}
|
||||
find(predicate) {
|
||||
if (predicate(this))
|
||||
return this;
|
||||
for (const child of this._children) {
|
||||
const result = child.find(predicate);
|
||||
if (result)
|
||||
return result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
isLeafNode() {
|
||||
if (!this._children.length)
|
||||
return true;
|
||||
if (this._isPlainTextField() || this._isTextOnlyObject())
|
||||
return true;
|
||||
switch (this._role) {
|
||||
case "doc-cover":
|
||||
case "graphics-symbol":
|
||||
case "img":
|
||||
case "Meter":
|
||||
case "scrollbar":
|
||||
case "slider":
|
||||
case "separator":
|
||||
case "progressbar":
|
||||
return true;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (this._hasFocusableChild())
|
||||
return false;
|
||||
if (this._focusable && this._role !== "WebArea" && this._role !== "RootWebArea" && this._name)
|
||||
return true;
|
||||
if (this._role === "heading" && this._name)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
isControl() {
|
||||
switch (this._role) {
|
||||
case "button":
|
||||
case "checkbox":
|
||||
case "ColorWell":
|
||||
case "combobox":
|
||||
case "DisclosureTriangle":
|
||||
case "listbox":
|
||||
case "menu":
|
||||
case "menubar":
|
||||
case "menuitem":
|
||||
case "menuitemcheckbox":
|
||||
case "menuitemradio":
|
||||
case "radio":
|
||||
case "scrollbar":
|
||||
case "searchbox":
|
||||
case "slider":
|
||||
case "spinbutton":
|
||||
case "switch":
|
||||
case "tab":
|
||||
case "textbox":
|
||||
case "tree":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
isInteresting(insideControl) {
|
||||
const role = this._role;
|
||||
if (role === "Ignored" || this._hidden)
|
||||
return false;
|
||||
if (this._focusable || this._richlyEditable)
|
||||
return true;
|
||||
if (this.isControl())
|
||||
return true;
|
||||
if (insideControl)
|
||||
return false;
|
||||
return this.isLeafNode() && !!this._name;
|
||||
}
|
||||
normalizedRole() {
|
||||
switch (this._role) {
|
||||
case "RootWebArea":
|
||||
return "WebArea";
|
||||
case "StaticText":
|
||||
return "text";
|
||||
default:
|
||||
return this._role;
|
||||
}
|
||||
}
|
||||
serialize() {
|
||||
const properties = /* @__PURE__ */ new Map();
|
||||
for (const property of this._payload.properties || [])
|
||||
properties.set(property.name.toLowerCase(), property.value.value);
|
||||
if (this._payload.description)
|
||||
properties.set("description", this._payload.description.value);
|
||||
const node = {
|
||||
role: this.normalizedRole(),
|
||||
name: this._payload.name ? this._payload.name.value || "" : ""
|
||||
};
|
||||
const userStringProperties = [
|
||||
"description",
|
||||
"keyshortcuts",
|
||||
"roledescription",
|
||||
"valuetext"
|
||||
];
|
||||
for (const userStringProperty of userStringProperties) {
|
||||
if (!properties.has(userStringProperty))
|
||||
continue;
|
||||
node[userStringProperty] = properties.get(userStringProperty);
|
||||
}
|
||||
const booleanProperties = [
|
||||
"disabled",
|
||||
"expanded",
|
||||
"focused",
|
||||
"modal",
|
||||
"multiline",
|
||||
"multiselectable",
|
||||
"readonly",
|
||||
"required",
|
||||
"selected"
|
||||
];
|
||||
for (const booleanProperty of booleanProperties) {
|
||||
if (booleanProperty === "focused" && (this._role === "WebArea" || this._role === "RootWebArea"))
|
||||
continue;
|
||||
const value = properties.get(booleanProperty);
|
||||
if (!value)
|
||||
continue;
|
||||
node[booleanProperty] = value;
|
||||
}
|
||||
const numericalProperties = [
|
||||
"level",
|
||||
"valuemax",
|
||||
"valuemin"
|
||||
];
|
||||
for (const numericalProperty of numericalProperties) {
|
||||
if (!properties.has(numericalProperty))
|
||||
continue;
|
||||
node[numericalProperty] = properties.get(numericalProperty);
|
||||
}
|
||||
const tokenProperties = [
|
||||
"autocomplete",
|
||||
"haspopup",
|
||||
"invalid",
|
||||
"orientation"
|
||||
];
|
||||
for (const tokenProperty of tokenProperties) {
|
||||
const value = properties.get(tokenProperty);
|
||||
if (!value || value === "false")
|
||||
continue;
|
||||
node[tokenProperty] = value;
|
||||
}
|
||||
const axNode = node;
|
||||
if (this._payload.value) {
|
||||
if (typeof this._payload.value.value === "string")
|
||||
axNode.valueString = this._payload.value.value;
|
||||
if (typeof this._payload.value.value === "number")
|
||||
axNode.valueNumber = this._payload.value.value;
|
||||
}
|
||||
if (properties.has("checked"))
|
||||
axNode.checked = properties.get("checked") === "true" ? "checked" : properties.get("checked") === "false" ? "unchecked" : "mixed";
|
||||
if (properties.has("pressed"))
|
||||
axNode.pressed = properties.get("pressed") === "true" ? "pressed" : properties.get("pressed") === "false" ? "released" : "mixed";
|
||||
return axNode;
|
||||
}
|
||||
static createTree(client, payloads) {
|
||||
const nodeById = /* @__PURE__ */ new Map();
|
||||
for (const payload of payloads)
|
||||
nodeById.set(payload.nodeId, new CRAXNode(client, payload));
|
||||
for (const node of nodeById.values()) {
|
||||
for (const childId of node._payload.childIds || [])
|
||||
node._children.push(nodeById.get(childId));
|
||||
}
|
||||
return nodeById.values().next().value;
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
getAccessibilityTree
|
||||
});
|
532
node_modules/playwright-core/lib/server/chromium/crBrowser.js
generated
vendored
Normal file
532
node_modules/playwright-core/lib/server/chromium/crBrowser.js
generated
vendored
Normal file
@@ -0,0 +1,532 @@
|
||||
"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 crBrowser_exports = {};
|
||||
__export(crBrowser_exports, {
|
||||
CRBrowser: () => CRBrowser,
|
||||
CRBrowserContext: () => CRBrowserContext
|
||||
});
|
||||
module.exports = __toCommonJS(crBrowser_exports);
|
||||
var import_path = __toESM(require("path"));
|
||||
var import_assert = require("../../utils/isomorphic/assert");
|
||||
var import_crypto = require("../utils/crypto");
|
||||
var import_artifact = require("../artifact");
|
||||
var import_browser = require("../browser");
|
||||
var import_browserContext = require("../browserContext");
|
||||
var import_frames = require("../frames");
|
||||
var network = __toESM(require("../network"));
|
||||
var import_page = require("../page");
|
||||
var import_crConnection = require("./crConnection");
|
||||
var import_crPage = require("./crPage");
|
||||
var import_crProtocolHelper = require("./crProtocolHelper");
|
||||
var import_crServiceWorker = require("./crServiceWorker");
|
||||
class CRBrowser extends import_browser.Browser {
|
||||
constructor(parent, connection, options) {
|
||||
super(parent, options);
|
||||
this._clientRootSessionPromise = null;
|
||||
this._contexts = /* @__PURE__ */ new Map();
|
||||
this._crPages = /* @__PURE__ */ new Map();
|
||||
this._backgroundPages = /* @__PURE__ */ new Map();
|
||||
this._serviceWorkers = /* @__PURE__ */ new Map();
|
||||
this._version = "";
|
||||
this._tracingRecording = false;
|
||||
this._userAgent = "";
|
||||
this._connection = connection;
|
||||
this._session = this._connection.rootSession;
|
||||
this._connection.on(import_crConnection.ConnectionEvents.Disconnected, () => this._didDisconnect());
|
||||
this._session.on("Target.attachedToTarget", this._onAttachedToTarget.bind(this));
|
||||
this._session.on("Target.detachedFromTarget", this._onDetachedFromTarget.bind(this));
|
||||
this._session.on("Browser.downloadWillBegin", this._onDownloadWillBegin.bind(this));
|
||||
this._session.on("Browser.downloadProgress", this._onDownloadProgress.bind(this));
|
||||
}
|
||||
static async connect(parent, transport, options, devtools) {
|
||||
options = { ...options };
|
||||
const connection = new import_crConnection.CRConnection(parent, transport, options.protocolLogger, options.browserLogsCollector);
|
||||
const browser = new CRBrowser(parent, connection, options);
|
||||
browser._devtools = devtools;
|
||||
if (browser.isClank())
|
||||
browser._isCollocatedWithServer = false;
|
||||
const session = connection.rootSession;
|
||||
if (options.__testHookOnConnectToBrowser)
|
||||
await options.__testHookOnConnectToBrowser();
|
||||
const version = await session.send("Browser.getVersion");
|
||||
browser._version = version.product.substring(version.product.indexOf("/") + 1);
|
||||
browser._userAgent = version.userAgent;
|
||||
browser.options.headful = !version.userAgent.includes("Headless");
|
||||
if (!options.persistent) {
|
||||
await session.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
|
||||
return browser;
|
||||
}
|
||||
browser._defaultContext = new CRBrowserContext(browser, void 0, options.persistent);
|
||||
await Promise.all([
|
||||
session.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }).then(async () => {
|
||||
await session.send("Target.getTargetInfo");
|
||||
}),
|
||||
browser._defaultContext._initialize()
|
||||
]);
|
||||
await browser._waitForAllPagesToBeInitialized();
|
||||
return browser;
|
||||
}
|
||||
async doCreateNewContext(options) {
|
||||
const proxy = options.proxyOverride || options.proxy;
|
||||
let proxyBypassList = void 0;
|
||||
if (proxy) {
|
||||
if (process.env.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK)
|
||||
proxyBypassList = proxy.bypass;
|
||||
else
|
||||
proxyBypassList = "<-loopback>" + (proxy.bypass ? `,${proxy.bypass}` : "");
|
||||
}
|
||||
const { browserContextId } = await this._session.send("Target.createBrowserContext", {
|
||||
disposeOnDetach: true,
|
||||
proxyServer: proxy ? proxy.server : void 0,
|
||||
proxyBypassList
|
||||
});
|
||||
const context = new CRBrowserContext(this, browserContextId, options);
|
||||
await context._initialize();
|
||||
this._contexts.set(browserContextId, context);
|
||||
return context;
|
||||
}
|
||||
contexts() {
|
||||
return Array.from(this._contexts.values());
|
||||
}
|
||||
version() {
|
||||
return this._version;
|
||||
}
|
||||
userAgent() {
|
||||
return this._userAgent;
|
||||
}
|
||||
_platform() {
|
||||
if (this._userAgent.includes("Windows"))
|
||||
return "win";
|
||||
if (this._userAgent.includes("Macintosh"))
|
||||
return "mac";
|
||||
return "linux";
|
||||
}
|
||||
isClank() {
|
||||
return this.options.name === "clank";
|
||||
}
|
||||
async _waitForAllPagesToBeInitialized() {
|
||||
await Promise.all([...this._crPages.values()].map((crPage) => crPage._page.waitForInitializedOrError()));
|
||||
}
|
||||
_onAttachedToTarget({ targetInfo, sessionId }) {
|
||||
if (targetInfo.type === "browser")
|
||||
return;
|
||||
const session = this._session.createChildSession(sessionId);
|
||||
(0, import_assert.assert)(targetInfo.browserContextId, "targetInfo: " + JSON.stringify(targetInfo, null, 2));
|
||||
let context = this._contexts.get(targetInfo.browserContextId) || null;
|
||||
if (!context) {
|
||||
context = this._defaultContext;
|
||||
}
|
||||
if (targetInfo.type === "other" && targetInfo.url.startsWith("devtools://devtools") && this._devtools) {
|
||||
this._devtools.install(session);
|
||||
return;
|
||||
}
|
||||
const treatOtherAsPage = targetInfo.type === "other" && process.env.PW_CHROMIUM_ATTACH_TO_OTHER;
|
||||
if (!context || targetInfo.type === "other" && !treatOtherAsPage) {
|
||||
session.detach().catch(() => {
|
||||
});
|
||||
return;
|
||||
}
|
||||
(0, import_assert.assert)(!this._crPages.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId);
|
||||
(0, import_assert.assert)(!this._backgroundPages.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId);
|
||||
(0, import_assert.assert)(!this._serviceWorkers.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId);
|
||||
if (targetInfo.type === "background_page") {
|
||||
const backgroundPage = new import_crPage.CRPage(session, targetInfo.targetId, context, null, { hasUIWindow: false, isBackgroundPage: true });
|
||||
this._backgroundPages.set(targetInfo.targetId, backgroundPage);
|
||||
return;
|
||||
}
|
||||
if (targetInfo.type === "page" || treatOtherAsPage) {
|
||||
const opener = targetInfo.openerId ? this._crPages.get(targetInfo.openerId) || null : null;
|
||||
const crPage = new import_crPage.CRPage(session, targetInfo.targetId, context, opener, { hasUIWindow: targetInfo.type === "page", isBackgroundPage: false });
|
||||
this._crPages.set(targetInfo.targetId, crPage);
|
||||
return;
|
||||
}
|
||||
if (targetInfo.type === "service_worker") {
|
||||
const serviceWorker = new import_crServiceWorker.CRServiceWorker(context, session, targetInfo.url);
|
||||
this._serviceWorkers.set(targetInfo.targetId, serviceWorker);
|
||||
context.emit(CRBrowserContext.CREvents.ServiceWorker, serviceWorker);
|
||||
return;
|
||||
}
|
||||
session.detach().catch(() => {
|
||||
});
|
||||
}
|
||||
_onDetachedFromTarget(payload) {
|
||||
const targetId = payload.targetId;
|
||||
const crPage = this._crPages.get(targetId);
|
||||
if (crPage) {
|
||||
this._crPages.delete(targetId);
|
||||
crPage.didClose();
|
||||
return;
|
||||
}
|
||||
const backgroundPage = this._backgroundPages.get(targetId);
|
||||
if (backgroundPage) {
|
||||
this._backgroundPages.delete(targetId);
|
||||
backgroundPage.didClose();
|
||||
return;
|
||||
}
|
||||
const serviceWorker = this._serviceWorkers.get(targetId);
|
||||
if (serviceWorker) {
|
||||
this._serviceWorkers.delete(targetId);
|
||||
serviceWorker.didClose();
|
||||
return;
|
||||
}
|
||||
}
|
||||
_didDisconnect() {
|
||||
for (const crPage of this._crPages.values())
|
||||
crPage.didClose();
|
||||
this._crPages.clear();
|
||||
for (const backgroundPage of this._backgroundPages.values())
|
||||
backgroundPage.didClose();
|
||||
this._backgroundPages.clear();
|
||||
for (const serviceWorker of this._serviceWorkers.values())
|
||||
serviceWorker.didClose();
|
||||
this._serviceWorkers.clear();
|
||||
this._didClose();
|
||||
}
|
||||
_findOwningPage(frameId) {
|
||||
for (const crPage of this._crPages.values()) {
|
||||
const frame = crPage._page.frameManager.frame(frameId);
|
||||
if (frame)
|
||||
return crPage;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
_onDownloadWillBegin(payload) {
|
||||
const page = this._findOwningPage(payload.frameId);
|
||||
if (!page) {
|
||||
return;
|
||||
}
|
||||
page.willBeginDownload();
|
||||
let originPage = page._page.initializedOrUndefined();
|
||||
if (!originPage && page._opener)
|
||||
originPage = page._opener._page.initializedOrUndefined();
|
||||
if (!originPage)
|
||||
return;
|
||||
this._downloadCreated(originPage, payload.guid, payload.url, payload.suggestedFilename);
|
||||
}
|
||||
_onDownloadProgress(payload) {
|
||||
if (payload.state === "completed")
|
||||
this._downloadFinished(payload.guid, "");
|
||||
if (payload.state === "canceled")
|
||||
this._downloadFinished(payload.guid, this._closeReason || "canceled");
|
||||
}
|
||||
async _closePage(crPage) {
|
||||
await this._session.send("Target.closeTarget", { targetId: crPage._targetId });
|
||||
}
|
||||
async newBrowserCDPSession() {
|
||||
return await this._connection.createBrowserSession();
|
||||
}
|
||||
async startTracing(page, options = {}) {
|
||||
(0, import_assert.assert)(!this._tracingRecording, "Cannot start recording trace while already recording trace.");
|
||||
this._tracingClient = page ? page.delegate._mainFrameSession._client : this._session;
|
||||
const defaultCategories = [
|
||||
"-*",
|
||||
"devtools.timeline",
|
||||
"v8.execute",
|
||||
"disabled-by-default-devtools.timeline",
|
||||
"disabled-by-default-devtools.timeline.frame",
|
||||
"toplevel",
|
||||
"blink.console",
|
||||
"blink.user_timing",
|
||||
"latencyInfo",
|
||||
"disabled-by-default-devtools.timeline.stack",
|
||||
"disabled-by-default-v8.cpu_profiler",
|
||||
"disabled-by-default-v8.cpu_profiler.hires"
|
||||
];
|
||||
const {
|
||||
screenshots = false,
|
||||
categories = defaultCategories
|
||||
} = options;
|
||||
if (screenshots)
|
||||
categories.push("disabled-by-default-devtools.screenshot");
|
||||
this._tracingRecording = true;
|
||||
await this._tracingClient.send("Tracing.start", {
|
||||
transferMode: "ReturnAsStream",
|
||||
categories: categories.join(",")
|
||||
});
|
||||
}
|
||||
async stopTracing() {
|
||||
(0, import_assert.assert)(this._tracingClient, "Tracing was not started.");
|
||||
const [event] = await Promise.all([
|
||||
new Promise((f) => this._tracingClient.once("Tracing.tracingComplete", f)),
|
||||
this._tracingClient.send("Tracing.end")
|
||||
]);
|
||||
const tracingPath = import_path.default.join(this.options.artifactsDir, (0, import_crypto.createGuid)() + ".crtrace");
|
||||
await (0, import_crProtocolHelper.saveProtocolStream)(this._tracingClient, event.stream, tracingPath);
|
||||
this._tracingRecording = false;
|
||||
const artifact = new import_artifact.Artifact(this, tracingPath);
|
||||
artifact.reportFinished();
|
||||
return artifact;
|
||||
}
|
||||
isConnected() {
|
||||
return !this._connection._closed;
|
||||
}
|
||||
async _clientRootSession() {
|
||||
if (!this._clientRootSessionPromise)
|
||||
this._clientRootSessionPromise = this._connection.createBrowserSession();
|
||||
return this._clientRootSessionPromise;
|
||||
}
|
||||
}
|
||||
class CRBrowserContext extends import_browserContext.BrowserContext {
|
||||
static {
|
||||
this.CREvents = {
|
||||
BackgroundPage: "backgroundpage",
|
||||
ServiceWorker: "serviceworker"
|
||||
};
|
||||
}
|
||||
constructor(browser, browserContextId, options) {
|
||||
super(browser, options, browserContextId);
|
||||
this._authenticateProxyViaCredentials();
|
||||
}
|
||||
async _initialize() {
|
||||
(0, import_assert.assert)(!Array.from(this._browser._crPages.values()).some((page) => page._browserContext === this));
|
||||
const promises = [super._initialize()];
|
||||
if (this._browser.options.name !== "clank" && this._options.acceptDownloads !== "internal-browser-default") {
|
||||
promises.push(this._browser._session.send("Browser.setDownloadBehavior", {
|
||||
behavior: this._options.acceptDownloads === "accept" ? "allowAndName" : "deny",
|
||||
browserContextId: this._browserContextId,
|
||||
downloadPath: this._browser.options.downloadsPath,
|
||||
eventsEnabled: true
|
||||
}));
|
||||
}
|
||||
await Promise.all(promises);
|
||||
}
|
||||
_crPages() {
|
||||
return [...this._browser._crPages.values()].filter((crPage) => crPage._browserContext === this);
|
||||
}
|
||||
possiblyUninitializedPages() {
|
||||
return this._crPages().map((crPage) => crPage._page);
|
||||
}
|
||||
async doCreateNewPage() {
|
||||
const { targetId } = await this._browser._session.send("Target.createTarget", { url: "about:blank", browserContextId: this._browserContextId });
|
||||
return this._browser._crPages.get(targetId)._page;
|
||||
}
|
||||
async doGetCookies(urls) {
|
||||
const { cookies } = await this._browser._session.send("Storage.getCookies", { browserContextId: this._browserContextId });
|
||||
return network.filterCookies(cookies.map((c) => {
|
||||
const { name, value, domain, path: path2, expires, httpOnly, secure, sameSite } = c;
|
||||
const copy = {
|
||||
name,
|
||||
value,
|
||||
domain,
|
||||
path: path2,
|
||||
expires,
|
||||
httpOnly,
|
||||
secure,
|
||||
sameSite: sameSite ?? "Lax"
|
||||
};
|
||||
if (c.partitionKey) {
|
||||
copy._crHasCrossSiteAncestor = c.partitionKey.hasCrossSiteAncestor;
|
||||
copy.partitionKey = c.partitionKey.topLevelSite;
|
||||
}
|
||||
return copy;
|
||||
}), urls);
|
||||
}
|
||||
async addCookies(cookies) {
|
||||
function toChromiumCookie(cookie) {
|
||||
const { name, value, url, domain, path: path2, expires, httpOnly, secure, sameSite, partitionKey, _crHasCrossSiteAncestor } = cookie;
|
||||
const copy = {
|
||||
name,
|
||||
value,
|
||||
url,
|
||||
domain,
|
||||
path: path2,
|
||||
expires,
|
||||
httpOnly,
|
||||
secure,
|
||||
sameSite
|
||||
};
|
||||
if (partitionKey) {
|
||||
copy.partitionKey = {
|
||||
topLevelSite: partitionKey,
|
||||
// _crHasCrossSiteAncestor is non-standard, set it true by default if the cookie is partitioned.
|
||||
hasCrossSiteAncestor: _crHasCrossSiteAncestor ?? true
|
||||
};
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
await this._browser._session.send("Storage.setCookies", {
|
||||
cookies: network.rewriteCookies(cookies).map(toChromiumCookie),
|
||||
browserContextId: this._browserContextId
|
||||
});
|
||||
}
|
||||
async doClearCookies() {
|
||||
await this._browser._session.send("Storage.clearCookies", { browserContextId: this._browserContextId });
|
||||
}
|
||||
async doGrantPermissions(origin, permissions) {
|
||||
const webPermissionToProtocol = /* @__PURE__ */ new Map([
|
||||
["geolocation", "geolocation"],
|
||||
["midi", "midi"],
|
||||
["notifications", "notifications"],
|
||||
["camera", "videoCapture"],
|
||||
["microphone", "audioCapture"],
|
||||
["background-sync", "backgroundSync"],
|
||||
["ambient-light-sensor", "sensors"],
|
||||
["accelerometer", "sensors"],
|
||||
["gyroscope", "sensors"],
|
||||
["magnetometer", "sensors"],
|
||||
["clipboard-read", "clipboardReadWrite"],
|
||||
["clipboard-write", "clipboardSanitizedWrite"],
|
||||
["payment-handler", "paymentHandler"],
|
||||
// chrome-specific permissions we have.
|
||||
["midi-sysex", "midiSysex"],
|
||||
["storage-access", "storageAccess"],
|
||||
["local-fonts", "localFonts"]
|
||||
]);
|
||||
const filtered = permissions.map((permission) => {
|
||||
const protocolPermission = webPermissionToProtocol.get(permission);
|
||||
if (!protocolPermission)
|
||||
throw new Error("Unknown permission: " + permission);
|
||||
return protocolPermission;
|
||||
});
|
||||
await this._browser._session.send("Browser.grantPermissions", { origin: origin === "*" ? void 0 : origin, browserContextId: this._browserContextId, permissions: filtered });
|
||||
}
|
||||
async doClearPermissions() {
|
||||
await this._browser._session.send("Browser.resetPermissions", { browserContextId: this._browserContextId });
|
||||
}
|
||||
async setGeolocation(geolocation) {
|
||||
(0, import_browserContext.verifyGeolocation)(geolocation);
|
||||
this._options.geolocation = geolocation;
|
||||
for (const page of this.pages())
|
||||
await page.delegate.updateGeolocation();
|
||||
}
|
||||
async doUpdateExtraHTTPHeaders() {
|
||||
for (const page of this.pages())
|
||||
await page.delegate.updateExtraHTTPHeaders();
|
||||
for (const sw of this.serviceWorkers())
|
||||
await sw.updateExtraHTTPHeaders();
|
||||
}
|
||||
async setUserAgent(userAgent) {
|
||||
this._options.userAgent = userAgent;
|
||||
for (const page of this.pages())
|
||||
await page.delegate.updateUserAgent();
|
||||
}
|
||||
async doUpdateOffline() {
|
||||
for (const page of this.pages())
|
||||
await page.delegate.updateOffline();
|
||||
for (const sw of this.serviceWorkers())
|
||||
await sw.updateOffline();
|
||||
}
|
||||
async doSetHTTPCredentials(httpCredentials) {
|
||||
this._options.httpCredentials = httpCredentials;
|
||||
for (const page of this.pages())
|
||||
await page.delegate.updateHttpCredentials();
|
||||
for (const sw of this.serviceWorkers())
|
||||
await sw.updateHttpCredentials();
|
||||
}
|
||||
async doAddInitScript(initScript) {
|
||||
for (const page of this.pages())
|
||||
await page.delegate.addInitScript(initScript);
|
||||
}
|
||||
async doRemoveInitScripts(initScripts) {
|
||||
for (const page of this.pages())
|
||||
await page.delegate.removeInitScripts(initScripts);
|
||||
}
|
||||
async doUpdateRequestInterception() {
|
||||
for (const page of this.pages())
|
||||
await page.delegate.updateRequestInterception();
|
||||
for (const sw of this.serviceWorkers())
|
||||
await sw.updateRequestInterception();
|
||||
}
|
||||
async doUpdateDefaultViewport() {
|
||||
}
|
||||
async doUpdateDefaultEmulatedMedia() {
|
||||
}
|
||||
async doExposePlaywrightBinding() {
|
||||
for (const page of this._crPages())
|
||||
await page.exposePlaywrightBinding();
|
||||
}
|
||||
async doClose(reason) {
|
||||
await this.dialogManager.closeBeforeUnloadDialogs();
|
||||
if (!this._browserContextId) {
|
||||
await this.stopVideoRecording();
|
||||
await this._browser.close({ reason });
|
||||
return;
|
||||
}
|
||||
await this._browser._session.send("Target.disposeBrowserContext", { browserContextId: this._browserContextId });
|
||||
this._browser._contexts.delete(this._browserContextId);
|
||||
for (const [targetId, serviceWorker] of this._browser._serviceWorkers) {
|
||||
if (serviceWorker.browserContext !== this)
|
||||
continue;
|
||||
serviceWorker.didClose();
|
||||
this._browser._serviceWorkers.delete(targetId);
|
||||
}
|
||||
}
|
||||
async stopVideoRecording() {
|
||||
await Promise.all(this._crPages().map((crPage) => crPage._mainFrameSession._stopVideoRecording()));
|
||||
}
|
||||
onClosePersistent() {
|
||||
for (const [targetId, backgroundPage] of this._browser._backgroundPages.entries()) {
|
||||
if (backgroundPage._browserContext === this && backgroundPage._page.initializedOrUndefined()) {
|
||||
backgroundPage.didClose();
|
||||
this._browser._backgroundPages.delete(targetId);
|
||||
}
|
||||
}
|
||||
}
|
||||
async clearCache() {
|
||||
for (const page of this._crPages())
|
||||
await page._networkManager.clearCache();
|
||||
}
|
||||
async cancelDownload(guid) {
|
||||
await this._browser._session.send("Browser.cancelDownload", {
|
||||
guid,
|
||||
browserContextId: this._browserContextId
|
||||
});
|
||||
}
|
||||
backgroundPages() {
|
||||
const result = [];
|
||||
for (const backgroundPage of this._browser._backgroundPages.values()) {
|
||||
if (backgroundPage._browserContext === this && backgroundPage._page.initializedOrUndefined())
|
||||
result.push(backgroundPage._page);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
serviceWorkers() {
|
||||
return Array.from(this._browser._serviceWorkers.values()).filter((serviceWorker) => serviceWorker.browserContext === this);
|
||||
}
|
||||
async newCDPSession(page) {
|
||||
let targetId = null;
|
||||
if (page instanceof import_page.Page) {
|
||||
targetId = page.delegate._targetId;
|
||||
} else if (page instanceof import_frames.Frame) {
|
||||
const session = page._page.delegate._sessions.get(page._id);
|
||||
if (!session)
|
||||
throw new Error(`This frame does not have a separate CDP session, it is a part of the parent frame's session`);
|
||||
targetId = session._targetId;
|
||||
} else {
|
||||
throw new Error("page: expected Page or Frame");
|
||||
}
|
||||
const rootSession = await this._browser._clientRootSession();
|
||||
return rootSession.attachToTarget(targetId);
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
CRBrowser,
|
||||
CRBrowserContext
|
||||
});
|
202
node_modules/playwright-core/lib/server/chromium/crConnection.js
generated
vendored
Normal file
202
node_modules/playwright-core/lib/server/chromium/crConnection.js
generated
vendored
Normal file
@@ -0,0 +1,202 @@
|
||||
"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 crConnection_exports = {};
|
||||
__export(crConnection_exports, {
|
||||
CDPSession: () => CDPSession,
|
||||
CRConnection: () => CRConnection,
|
||||
CRSession: () => CRSession,
|
||||
ConnectionEvents: () => ConnectionEvents,
|
||||
kBrowserCloseMessageId: () => kBrowserCloseMessageId
|
||||
});
|
||||
module.exports = __toCommonJS(crConnection_exports);
|
||||
var import_utils = require("../../utils");
|
||||
var import_debugLogger = require("../utils/debugLogger");
|
||||
var import_helper = require("../helper");
|
||||
var import_protocolError = require("../protocolError");
|
||||
var import_instrumentation = require("../instrumentation");
|
||||
const ConnectionEvents = {
|
||||
Disconnected: Symbol("ConnectionEvents.Disconnected")
|
||||
};
|
||||
const kBrowserCloseMessageId = -9999;
|
||||
class CRConnection extends import_instrumentation.SdkObject {
|
||||
constructor(parent, transport, protocolLogger, browserLogsCollector) {
|
||||
super(parent, "cr-connection");
|
||||
this._lastId = 0;
|
||||
this._sessions = /* @__PURE__ */ new Map();
|
||||
this._closed = false;
|
||||
this.setMaxListeners(0);
|
||||
this._transport = transport;
|
||||
this._protocolLogger = protocolLogger;
|
||||
this._browserLogsCollector = browserLogsCollector;
|
||||
this.rootSession = new CRSession(this, null, "");
|
||||
this._sessions.set("", this.rootSession);
|
||||
this._transport.onmessage = this._onMessage.bind(this);
|
||||
this._transport.onclose = this._onClose.bind(this);
|
||||
}
|
||||
_rawSend(sessionId, method, params) {
|
||||
const id = ++this._lastId;
|
||||
const message = { id, method, params };
|
||||
if (sessionId)
|
||||
message.sessionId = sessionId;
|
||||
this._protocolLogger("send", message);
|
||||
this._transport.send(message);
|
||||
return id;
|
||||
}
|
||||
async _onMessage(message) {
|
||||
this._protocolLogger("receive", message);
|
||||
if (message.id === kBrowserCloseMessageId)
|
||||
return;
|
||||
const session = this._sessions.get(message.sessionId || "");
|
||||
if (session)
|
||||
session._onMessage(message);
|
||||
}
|
||||
_onClose(reason) {
|
||||
this._closed = true;
|
||||
this._transport.onmessage = void 0;
|
||||
this._transport.onclose = void 0;
|
||||
this._browserDisconnectedLogs = import_helper.helper.formatBrowserLogs(this._browserLogsCollector.recentLogs(), reason);
|
||||
this.rootSession.dispose();
|
||||
Promise.resolve().then(() => this.emit(ConnectionEvents.Disconnected));
|
||||
}
|
||||
close() {
|
||||
if (!this._closed)
|
||||
this._transport.close();
|
||||
}
|
||||
async createBrowserSession() {
|
||||
const { sessionId } = await this.rootSession.send("Target.attachToBrowserTarget");
|
||||
return new CDPSession(this.rootSession, sessionId);
|
||||
}
|
||||
}
|
||||
class CRSession extends import_instrumentation.SdkObject {
|
||||
constructor(connection, parentSession, sessionId, eventListener) {
|
||||
super(connection, "cr-session");
|
||||
this._callbacks = /* @__PURE__ */ new Map();
|
||||
this._crashed = false;
|
||||
this._closed = false;
|
||||
this.setMaxListeners(0);
|
||||
this._connection = connection;
|
||||
this._parentSession = parentSession;
|
||||
this._sessionId = sessionId;
|
||||
this._eventListener = eventListener;
|
||||
this.on = super.on;
|
||||
this.addListener = super.addListener;
|
||||
this.off = super.removeListener;
|
||||
this.removeListener = super.removeListener;
|
||||
this.once = super.once;
|
||||
}
|
||||
_markAsCrashed() {
|
||||
this._crashed = true;
|
||||
}
|
||||
createChildSession(sessionId, eventListener) {
|
||||
const session = new CRSession(this._connection, this, sessionId, eventListener);
|
||||
this._connection._sessions.set(sessionId, session);
|
||||
return session;
|
||||
}
|
||||
async send(method, params) {
|
||||
if (this._crashed || this._closed || this._connection._closed || this._connection._browserDisconnectedLogs)
|
||||
throw new import_protocolError.ProtocolError(this._crashed ? "crashed" : "closed", void 0, this._connection._browserDisconnectedLogs);
|
||||
const id = this._connection._rawSend(this._sessionId, method, params);
|
||||
return new Promise((resolve, reject) => {
|
||||
this._callbacks.set(id, { resolve, reject, error: new import_protocolError.ProtocolError("error", method) });
|
||||
});
|
||||
}
|
||||
_sendMayFail(method, params) {
|
||||
return this.send(method, params).catch((error) => import_debugLogger.debugLogger.log("error", error));
|
||||
}
|
||||
_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.error.setMessage(object.error.message);
|
||||
callback.reject(callback.error);
|
||||
} else {
|
||||
callback.resolve(object.result);
|
||||
}
|
||||
} else if (object.id && object.error?.code === -32001) {
|
||||
} else {
|
||||
(0, import_utils.assert)(!object.id, object?.error?.message || void 0);
|
||||
Promise.resolve().then(() => {
|
||||
if (this._eventListener)
|
||||
this._eventListener(object.method, object.params);
|
||||
this.emit(object.method, object.params);
|
||||
});
|
||||
}
|
||||
}
|
||||
async detach() {
|
||||
if (this._closed)
|
||||
throw new Error(`Session already detached. Most likely the page has been closed.`);
|
||||
if (!this._parentSession)
|
||||
throw new Error("Root session cannot be closed");
|
||||
await this._sendMayFail("Runtime.runIfWaitingForDebugger");
|
||||
await this._parentSession.send("Target.detachFromTarget", { sessionId: this._sessionId });
|
||||
this.dispose();
|
||||
}
|
||||
dispose() {
|
||||
this._closed = true;
|
||||
this._connection._sessions.delete(this._sessionId);
|
||||
for (const callback of this._callbacks.values()) {
|
||||
callback.error.setMessage(`Internal server error, session closed.`);
|
||||
callback.error.type = this._crashed ? "crashed" : "closed";
|
||||
callback.error.logs = this._connection._browserDisconnectedLogs;
|
||||
callback.reject(callback.error);
|
||||
}
|
||||
this._callbacks.clear();
|
||||
}
|
||||
}
|
||||
class CDPSession extends import_instrumentation.SdkObject {
|
||||
constructor(parentSession, sessionId) {
|
||||
super(parentSession, "cdp-session");
|
||||
this._listeners = [];
|
||||
this._session = parentSession.createChildSession(sessionId, (method, params) => this.emit(CDPSession.Events.Event, { method, params }));
|
||||
this._listeners = [import_utils.eventsHelper.addEventListener(parentSession, "Target.detachedFromTarget", (event) => {
|
||||
if (event.sessionId === sessionId)
|
||||
this._onClose();
|
||||
})];
|
||||
}
|
||||
static {
|
||||
this.Events = {
|
||||
Event: "event",
|
||||
Closed: "close"
|
||||
};
|
||||
}
|
||||
async send(method, params) {
|
||||
return await this._session.send(method, params);
|
||||
}
|
||||
async detach() {
|
||||
return await this._session.detach();
|
||||
}
|
||||
async attachToTarget(targetId) {
|
||||
const { sessionId } = await this.send("Target.attachToTarget", { targetId, flatten: true });
|
||||
return new CDPSession(this._session, sessionId);
|
||||
}
|
||||
_onClose() {
|
||||
import_utils.eventsHelper.removeEventListeners(this._listeners);
|
||||
this._session.dispose();
|
||||
this.emit(CDPSession.Events.Closed);
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
CDPSession,
|
||||
CRConnection,
|
||||
CRSession,
|
||||
ConnectionEvents,
|
||||
kBrowserCloseMessageId
|
||||
});
|
235
node_modules/playwright-core/lib/server/chromium/crCoverage.js
generated
vendored
Normal file
235
node_modules/playwright-core/lib/server/chromium/crCoverage.js
generated
vendored
Normal file
@@ -0,0 +1,235 @@
|
||||
"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 crCoverage_exports = {};
|
||||
__export(crCoverage_exports, {
|
||||
CRCoverage: () => CRCoverage
|
||||
});
|
||||
module.exports = __toCommonJS(crCoverage_exports);
|
||||
var import_utils = require("../../utils");
|
||||
var import_eventsHelper = require("../utils/eventsHelper");
|
||||
var import_progress = require("../progress");
|
||||
class CRCoverage {
|
||||
constructor(client) {
|
||||
this._jsCoverage = new JSCoverage(client);
|
||||
this._cssCoverage = new CSSCoverage(client);
|
||||
}
|
||||
async startJSCoverage(progress, options) {
|
||||
await (0, import_progress.raceUncancellableOperationWithCleanup)(progress, () => this._jsCoverage.start(options), () => this._jsCoverage.stop());
|
||||
}
|
||||
async stopJSCoverage() {
|
||||
return await this._jsCoverage.stop();
|
||||
}
|
||||
async startCSSCoverage(progress, options) {
|
||||
await (0, import_progress.raceUncancellableOperationWithCleanup)(progress, () => this._cssCoverage.start(options), () => this._cssCoverage.stop());
|
||||
}
|
||||
async stopCSSCoverage() {
|
||||
return await this._cssCoverage.stop();
|
||||
}
|
||||
}
|
||||
class JSCoverage {
|
||||
constructor(client) {
|
||||
this._reportAnonymousScripts = false;
|
||||
this._client = client;
|
||||
this._enabled = false;
|
||||
this._scriptIds = /* @__PURE__ */ new Set();
|
||||
this._scriptSources = /* @__PURE__ */ new Map();
|
||||
this._eventListeners = [];
|
||||
this._resetOnNavigation = false;
|
||||
}
|
||||
async start(options) {
|
||||
(0, import_utils.assert)(!this._enabled, "JSCoverage is already enabled");
|
||||
const {
|
||||
resetOnNavigation = true,
|
||||
reportAnonymousScripts = false
|
||||
} = options;
|
||||
this._resetOnNavigation = resetOnNavigation;
|
||||
this._reportAnonymousScripts = reportAnonymousScripts;
|
||||
this._enabled = true;
|
||||
this._scriptIds.clear();
|
||||
this._scriptSources.clear();
|
||||
this._eventListeners = [
|
||||
import_eventsHelper.eventsHelper.addEventListener(this._client, "Debugger.scriptParsed", this._onScriptParsed.bind(this)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextsCleared", this._onExecutionContextsCleared.bind(this)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(this._client, "Debugger.paused", this._onDebuggerPaused.bind(this))
|
||||
];
|
||||
await Promise.all([
|
||||
this._client.send("Profiler.enable"),
|
||||
this._client.send("Profiler.startPreciseCoverage", { callCount: true, detailed: true }),
|
||||
this._client.send("Debugger.enable"),
|
||||
this._client.send("Debugger.setSkipAllPauses", { skip: true })
|
||||
]);
|
||||
}
|
||||
_onDebuggerPaused() {
|
||||
this._client.send("Debugger.resume");
|
||||
}
|
||||
_onExecutionContextsCleared() {
|
||||
if (!this._resetOnNavigation)
|
||||
return;
|
||||
this._scriptIds.clear();
|
||||
this._scriptSources.clear();
|
||||
}
|
||||
async _onScriptParsed(event) {
|
||||
this._scriptIds.add(event.scriptId);
|
||||
if (!event.url && !this._reportAnonymousScripts)
|
||||
return;
|
||||
const response = await this._client._sendMayFail("Debugger.getScriptSource", { scriptId: event.scriptId });
|
||||
if (response)
|
||||
this._scriptSources.set(event.scriptId, response.scriptSource);
|
||||
}
|
||||
async stop() {
|
||||
if (!this._enabled)
|
||||
return { entries: [] };
|
||||
const [profileResponse] = await Promise.all([
|
||||
this._client.send("Profiler.takePreciseCoverage"),
|
||||
this._client.send("Profiler.stopPreciseCoverage"),
|
||||
this._client.send("Profiler.disable"),
|
||||
this._client.send("Debugger.disable")
|
||||
]);
|
||||
import_eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);
|
||||
this._enabled = false;
|
||||
const coverage = { entries: [] };
|
||||
for (const entry of profileResponse.result) {
|
||||
if (!this._scriptIds.has(entry.scriptId))
|
||||
continue;
|
||||
if (!entry.url && !this._reportAnonymousScripts)
|
||||
continue;
|
||||
const source = this._scriptSources.get(entry.scriptId);
|
||||
if (source)
|
||||
coverage.entries.push({ ...entry, source });
|
||||
else
|
||||
coverage.entries.push(entry);
|
||||
}
|
||||
return coverage;
|
||||
}
|
||||
}
|
||||
class CSSCoverage {
|
||||
constructor(client) {
|
||||
this._client = client;
|
||||
this._enabled = false;
|
||||
this._stylesheetURLs = /* @__PURE__ */ new Map();
|
||||
this._stylesheetSources = /* @__PURE__ */ new Map();
|
||||
this._eventListeners = [];
|
||||
this._resetOnNavigation = false;
|
||||
}
|
||||
async start(options) {
|
||||
(0, import_utils.assert)(!this._enabled, "CSSCoverage is already enabled");
|
||||
const { resetOnNavigation = true } = options;
|
||||
this._resetOnNavigation = resetOnNavigation;
|
||||
this._enabled = true;
|
||||
this._stylesheetURLs.clear();
|
||||
this._stylesheetSources.clear();
|
||||
this._eventListeners = [
|
||||
import_eventsHelper.eventsHelper.addEventListener(this._client, "CSS.styleSheetAdded", this._onStyleSheet.bind(this)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextsCleared", this._onExecutionContextsCleared.bind(this))
|
||||
];
|
||||
await Promise.all([
|
||||
this._client.send("DOM.enable"),
|
||||
this._client.send("CSS.enable"),
|
||||
this._client.send("CSS.startRuleUsageTracking")
|
||||
]);
|
||||
}
|
||||
_onExecutionContextsCleared() {
|
||||
if (!this._resetOnNavigation)
|
||||
return;
|
||||
this._stylesheetURLs.clear();
|
||||
this._stylesheetSources.clear();
|
||||
}
|
||||
async _onStyleSheet(event) {
|
||||
const header = event.header;
|
||||
if (!header.sourceURL)
|
||||
return;
|
||||
const response = await this._client._sendMayFail("CSS.getStyleSheetText", { styleSheetId: header.styleSheetId });
|
||||
if (response) {
|
||||
this._stylesheetURLs.set(header.styleSheetId, header.sourceURL);
|
||||
this._stylesheetSources.set(header.styleSheetId, response.text);
|
||||
}
|
||||
}
|
||||
async stop() {
|
||||
if (!this._enabled)
|
||||
return { entries: [] };
|
||||
const ruleTrackingResponse = await this._client.send("CSS.stopRuleUsageTracking");
|
||||
await Promise.all([
|
||||
this._client.send("CSS.disable"),
|
||||
this._client.send("DOM.disable")
|
||||
]);
|
||||
import_eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);
|
||||
this._enabled = false;
|
||||
const styleSheetIdToCoverage = /* @__PURE__ */ new Map();
|
||||
for (const entry of ruleTrackingResponse.ruleUsage) {
|
||||
let ranges = styleSheetIdToCoverage.get(entry.styleSheetId);
|
||||
if (!ranges) {
|
||||
ranges = [];
|
||||
styleSheetIdToCoverage.set(entry.styleSheetId, ranges);
|
||||
}
|
||||
ranges.push({
|
||||
startOffset: entry.startOffset,
|
||||
endOffset: entry.endOffset,
|
||||
count: entry.used ? 1 : 0
|
||||
});
|
||||
}
|
||||
const coverage = { entries: [] };
|
||||
for (const styleSheetId of this._stylesheetURLs.keys()) {
|
||||
const url = this._stylesheetURLs.get(styleSheetId);
|
||||
const text = this._stylesheetSources.get(styleSheetId);
|
||||
const ranges = convertToDisjointRanges(styleSheetIdToCoverage.get(styleSheetId) || []);
|
||||
coverage.entries.push({ url, ranges, text });
|
||||
}
|
||||
return coverage;
|
||||
}
|
||||
}
|
||||
function convertToDisjointRanges(nestedRanges) {
|
||||
const points = [];
|
||||
for (const range of nestedRanges) {
|
||||
points.push({ offset: range.startOffset, type: 0, range });
|
||||
points.push({ offset: range.endOffset, type: 1, range });
|
||||
}
|
||||
points.sort((a, b) => {
|
||||
if (a.offset !== b.offset)
|
||||
return a.offset - b.offset;
|
||||
if (a.type !== b.type)
|
||||
return b.type - a.type;
|
||||
const aLength = a.range.endOffset - a.range.startOffset;
|
||||
const bLength = b.range.endOffset - b.range.startOffset;
|
||||
if (a.type === 0)
|
||||
return bLength - aLength;
|
||||
return aLength - bLength;
|
||||
});
|
||||
const hitCountStack = [];
|
||||
const results = [];
|
||||
let lastOffset = 0;
|
||||
for (const point of points) {
|
||||
if (hitCountStack.length && lastOffset < point.offset && hitCountStack[hitCountStack.length - 1] > 0) {
|
||||
const lastResult = results.length ? results[results.length - 1] : null;
|
||||
if (lastResult && lastResult.end === lastOffset)
|
||||
lastResult.end = point.offset;
|
||||
else
|
||||
results.push({ start: lastOffset, end: point.offset });
|
||||
}
|
||||
lastOffset = point.offset;
|
||||
if (point.type === 0)
|
||||
hitCountStack.push(point.range.count);
|
||||
else
|
||||
hitCountStack.pop();
|
||||
}
|
||||
return results.filter((range) => range.end - range.start > 1);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
CRCoverage
|
||||
});
|
113
node_modules/playwright-core/lib/server/chromium/crDevTools.js
generated
vendored
Normal file
113
node_modules/playwright-core/lib/server/chromium/crDevTools.js
generated
vendored
Normal file
@@ -0,0 +1,113 @@
|
||||
"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 crDevTools_exports = {};
|
||||
__export(crDevTools_exports, {
|
||||
CRDevTools: () => CRDevTools
|
||||
});
|
||||
module.exports = __toCommonJS(crDevTools_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
const kBindingName = "__pw_devtools__";
|
||||
class CRDevTools {
|
||||
constructor(preferencesPath) {
|
||||
this._preferencesPath = preferencesPath;
|
||||
this._savePromise = Promise.resolve();
|
||||
}
|
||||
install(session) {
|
||||
session.on("Runtime.bindingCalled", async (event) => {
|
||||
if (event.name !== kBindingName)
|
||||
return;
|
||||
const parsed = JSON.parse(event.payload);
|
||||
let result = void 0;
|
||||
if (this.__testHookOnBinding)
|
||||
this.__testHookOnBinding(parsed);
|
||||
if (parsed.method === "getPreferences") {
|
||||
if (this._prefs === void 0) {
|
||||
try {
|
||||
const json = await import_fs.default.promises.readFile(this._preferencesPath, "utf8");
|
||||
this._prefs = JSON.parse(json);
|
||||
} catch (e) {
|
||||
this._prefs = {};
|
||||
}
|
||||
}
|
||||
result = this._prefs;
|
||||
} else if (parsed.method === "setPreference") {
|
||||
this._prefs[parsed.params[0]] = parsed.params[1];
|
||||
this._save();
|
||||
} else if (parsed.method === "removePreference") {
|
||||
delete this._prefs[parsed.params[0]];
|
||||
this._save();
|
||||
} else if (parsed.method === "clearPreferences") {
|
||||
this._prefs = {};
|
||||
this._save();
|
||||
}
|
||||
session.send("Runtime.evaluate", {
|
||||
expression: `window.DevToolsAPI.embedderMessageAck(${parsed.id}, ${JSON.stringify(result)})`,
|
||||
contextId: event.executionContextId
|
||||
}).catch((e) => null);
|
||||
});
|
||||
Promise.all([
|
||||
session.send("Runtime.enable"),
|
||||
session.send("Runtime.addBinding", { name: kBindingName }),
|
||||
session.send("Page.enable"),
|
||||
session.send("Page.addScriptToEvaluateOnNewDocument", { source: `
|
||||
(() => {
|
||||
const init = () => {
|
||||
// Lazy init happens when InspectorFrontendHost is initialized.
|
||||
// At this point DevToolsHost is ready to be used.
|
||||
const host = window.DevToolsHost;
|
||||
const old = host.sendMessageToEmbedder.bind(host);
|
||||
host.sendMessageToEmbedder = message => {
|
||||
if (['getPreferences', 'setPreference', 'removePreference', 'clearPreferences'].includes(JSON.parse(message).method))
|
||||
window.${kBindingName}(message);
|
||||
else
|
||||
old(message);
|
||||
};
|
||||
};
|
||||
let value;
|
||||
Object.defineProperty(window, 'InspectorFrontendHost', {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get() { return value; },
|
||||
set(v) { value = v; init(); },
|
||||
});
|
||||
})()
|
||||
` }),
|
||||
session.send("Runtime.runIfWaitingForDebugger")
|
||||
]).catch((e) => null);
|
||||
}
|
||||
_save() {
|
||||
this._savePromise = this._savePromise.then(async () => {
|
||||
await import_fs.default.promises.writeFile(this._preferencesPath, JSON.stringify(this._prefs)).catch((e) => null);
|
||||
});
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
CRDevTools
|
||||
});
|
131
node_modules/playwright-core/lib/server/chromium/crDragDrop.js
generated
vendored
Normal file
131
node_modules/playwright-core/lib/server/chromium/crDragDrop.js
generated
vendored
Normal file
@@ -0,0 +1,131 @@
|
||||
"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 crDragDrop_exports = {};
|
||||
__export(crDragDrop_exports, {
|
||||
DragManager: () => DragManager
|
||||
});
|
||||
module.exports = __toCommonJS(crDragDrop_exports);
|
||||
var import_crProtocolHelper = require("./crProtocolHelper");
|
||||
var import_utils = require("../../utils");
|
||||
class DragManager {
|
||||
constructor(page) {
|
||||
this._dragState = null;
|
||||
this._lastPosition = { x: 0, y: 0 };
|
||||
this._crPage = page;
|
||||
}
|
||||
async cancelDrag() {
|
||||
if (!this._dragState)
|
||||
return false;
|
||||
await this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", {
|
||||
type: "dragCancel",
|
||||
x: this._lastPosition.x,
|
||||
y: this._lastPosition.y,
|
||||
data: {
|
||||
items: [],
|
||||
dragOperationsMask: 65535
|
||||
}
|
||||
});
|
||||
this._dragState = null;
|
||||
return true;
|
||||
}
|
||||
async interceptDragCausedByMove(progress, x, y, button, buttons, modifiers, moveCallback) {
|
||||
this._lastPosition = { x, y };
|
||||
if (this._dragState) {
|
||||
await progress.race(this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", {
|
||||
type: "dragOver",
|
||||
x,
|
||||
y,
|
||||
data: this._dragState,
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers)
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (button !== "left")
|
||||
return moveCallback();
|
||||
const client = this._crPage._mainFrameSession._client;
|
||||
let onDragIntercepted;
|
||||
const dragInterceptedPromise = new Promise((x2) => onDragIntercepted = x2);
|
||||
function setupDragListeners() {
|
||||
let didStartDrag = Promise.resolve(false);
|
||||
let dragEvent = null;
|
||||
const dragListener = (event) => dragEvent = event;
|
||||
const mouseListener = () => {
|
||||
didStartDrag = new Promise((callback) => {
|
||||
window.addEventListener("dragstart", dragListener, { once: true, capture: true });
|
||||
setTimeout(() => callback(dragEvent ? !dragEvent.defaultPrevented : false), 0);
|
||||
});
|
||||
};
|
||||
window.addEventListener("mousemove", mouseListener, { once: true, capture: true });
|
||||
window.__cleanupDrag = async () => {
|
||||
const val = await didStartDrag;
|
||||
window.removeEventListener("mousemove", mouseListener, { capture: true });
|
||||
window.removeEventListener("dragstart", dragListener, { capture: true });
|
||||
delete window.__cleanupDrag;
|
||||
return val;
|
||||
};
|
||||
}
|
||||
try {
|
||||
let expectingDrag = false;
|
||||
await progress.race(this._crPage._page.safeNonStallingEvaluateInAllFrames(`(${setupDragListeners.toString()})()`, "utility"));
|
||||
client.on("Input.dragIntercepted", onDragIntercepted);
|
||||
await client.send("Input.setInterceptDrags", { enabled: true });
|
||||
try {
|
||||
await progress.race(moveCallback());
|
||||
expectingDrag = (await Promise.all(this._crPage._page.frames().map(async (frame) => {
|
||||
return frame.nonStallingEvaluateInExistingContext("window.__cleanupDrag?.()", "utility").catch(() => false);
|
||||
}))).some((x2) => x2);
|
||||
} finally {
|
||||
client.off("Input.dragIntercepted", onDragIntercepted);
|
||||
await client.send("Input.setInterceptDrags", { enabled: false });
|
||||
}
|
||||
this._dragState = expectingDrag ? (await dragInterceptedPromise).data : null;
|
||||
} catch (error) {
|
||||
this._crPage._page.safeNonStallingEvaluateInAllFrames("window.__cleanupDrag?.()", "utility").catch(() => {
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
if (this._dragState) {
|
||||
await progress.race(this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", {
|
||||
type: "dragEnter",
|
||||
x,
|
||||
y,
|
||||
data: this._dragState,
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers)
|
||||
}));
|
||||
}
|
||||
}
|
||||
isDragging() {
|
||||
return !!this._dragState;
|
||||
}
|
||||
async drop(progress, x, y, modifiers) {
|
||||
(0, import_utils.assert)(this._dragState, "missing drag state");
|
||||
await progress.race(this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", {
|
||||
type: "drop",
|
||||
x,
|
||||
y,
|
||||
data: this._dragState,
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers)
|
||||
}));
|
||||
this._dragState = null;
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
DragManager
|
||||
});
|
146
node_modules/playwright-core/lib/server/chromium/crExecutionContext.js
generated
vendored
Normal file
146
node_modules/playwright-core/lib/server/chromium/crExecutionContext.js
generated
vendored
Normal file
@@ -0,0 +1,146 @@
|
||||
"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 crExecutionContext_exports = {};
|
||||
__export(crExecutionContext_exports, {
|
||||
CRExecutionContext: () => CRExecutionContext,
|
||||
createHandle: () => createHandle
|
||||
});
|
||||
module.exports = __toCommonJS(crExecutionContext_exports);
|
||||
var import_assert = require("../../utils/isomorphic/assert");
|
||||
var import_crProtocolHelper = require("./crProtocolHelper");
|
||||
var import_stackTrace = require("../../utils/isomorphic/stackTrace");
|
||||
var import_utilityScriptSerializers = require("../../utils/isomorphic/utilityScriptSerializers");
|
||||
var js = __toESM(require("../javascript"));
|
||||
var dom = __toESM(require("../dom"));
|
||||
var import_protocolError = require("../protocolError");
|
||||
class CRExecutionContext {
|
||||
constructor(client, contextPayload) {
|
||||
this._client = client;
|
||||
this._contextId = contextPayload.id;
|
||||
}
|
||||
async rawEvaluateJSON(expression) {
|
||||
const { exceptionDetails, result: remoteObject } = await this._client.send("Runtime.evaluate", {
|
||||
expression,
|
||||
contextId: this._contextId,
|
||||
returnByValue: true
|
||||
}).catch(rewriteError);
|
||||
if (exceptionDetails)
|
||||
throw new js.JavaScriptErrorInEvaluate((0, import_crProtocolHelper.getExceptionMessage)(exceptionDetails));
|
||||
return remoteObject.value;
|
||||
}
|
||||
async rawEvaluateHandle(context, expression) {
|
||||
const { exceptionDetails, result: remoteObject } = await this._client.send("Runtime.evaluate", {
|
||||
expression,
|
||||
contextId: this._contextId
|
||||
}).catch(rewriteError);
|
||||
if (exceptionDetails)
|
||||
throw new js.JavaScriptErrorInEvaluate((0, import_crProtocolHelper.getExceptionMessage)(exceptionDetails));
|
||||
return createHandle(context, remoteObject);
|
||||
}
|
||||
async evaluateWithArguments(expression, returnByValue, utilityScript, values, handles) {
|
||||
const { exceptionDetails, result: remoteObject } = await this._client.send("Runtime.callFunctionOn", {
|
||||
functionDeclaration: expression,
|
||||
objectId: utilityScript._objectId,
|
||||
arguments: [
|
||||
{ objectId: utilityScript._objectId },
|
||||
...values.map((value) => ({ value })),
|
||||
...handles.map((handle) => ({ objectId: handle._objectId }))
|
||||
],
|
||||
returnByValue,
|
||||
awaitPromise: true,
|
||||
userGesture: true
|
||||
}).catch(rewriteError);
|
||||
if (exceptionDetails)
|
||||
throw new js.JavaScriptErrorInEvaluate((0, import_crProtocolHelper.getExceptionMessage)(exceptionDetails));
|
||||
return returnByValue ? (0, import_utilityScriptSerializers.parseEvaluationResultValue)(remoteObject.value) : createHandle(utilityScript._context, remoteObject);
|
||||
}
|
||||
async getProperties(object) {
|
||||
const response = await this._client.send("Runtime.getProperties", {
|
||||
objectId: object._objectId,
|
||||
ownProperties: true
|
||||
});
|
||||
const result = /* @__PURE__ */ new Map();
|
||||
for (const property of response.result) {
|
||||
if (!property.enumerable || !property.value)
|
||||
continue;
|
||||
result.set(property.name, createHandle(object._context, property.value));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
async releaseHandle(handle) {
|
||||
if (!handle._objectId)
|
||||
return;
|
||||
await (0, import_crProtocolHelper.releaseObject)(this._client, handle._objectId);
|
||||
}
|
||||
}
|
||||
function rewriteError(error) {
|
||||
if (error.message.includes("Object reference chain is too long"))
|
||||
throw new Error("Cannot serialize result: object reference chain is too long.");
|
||||
if (error.message.includes("Object couldn't be returned by value"))
|
||||
return { result: { type: "undefined" } };
|
||||
if (error instanceof TypeError && error.message.startsWith("Converting circular structure to JSON"))
|
||||
(0, import_stackTrace.rewriteErrorMessage)(error, error.message + " Are you passing a nested JSHandle?");
|
||||
if (!js.isJavaScriptErrorInEvaluate(error) && !(0, import_protocolError.isSessionClosedError)(error))
|
||||
throw new Error("Execution context was destroyed, most likely because of a navigation.");
|
||||
throw error;
|
||||
}
|
||||
function potentiallyUnserializableValue(remoteObject) {
|
||||
const value = remoteObject.value;
|
||||
const unserializableValue = remoteObject.unserializableValue;
|
||||
return unserializableValue ? js.parseUnserializableValue(unserializableValue) : value;
|
||||
}
|
||||
function renderPreview(object) {
|
||||
if (object.type === "undefined")
|
||||
return "undefined";
|
||||
if ("value" in object)
|
||||
return String(object.value);
|
||||
if (object.unserializableValue)
|
||||
return String(object.unserializableValue);
|
||||
if (object.description === "Object" && object.preview) {
|
||||
const tokens = [];
|
||||
for (const { name, value } of object.preview.properties)
|
||||
tokens.push(`${name}: ${value}`);
|
||||
return `{${tokens.join(", ")}}`;
|
||||
}
|
||||
if (object.subtype === "array" && object.preview)
|
||||
return js.sparseArrayToString(object.preview.properties);
|
||||
return object.description;
|
||||
}
|
||||
function createHandle(context, remoteObject) {
|
||||
if (remoteObject.subtype === "node") {
|
||||
(0, import_assert.assert)(context instanceof dom.FrameExecutionContext);
|
||||
return new dom.ElementHandle(context, remoteObject.objectId);
|
||||
}
|
||||
return new js.JSHandle(context, remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
CRExecutionContext,
|
||||
createHandle
|
||||
});
|
187
node_modules/playwright-core/lib/server/chromium/crInput.js
generated
vendored
Normal file
187
node_modules/playwright-core/lib/server/chromium/crInput.js
generated
vendored
Normal file
@@ -0,0 +1,187 @@
|
||||
"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 crInput_exports = {};
|
||||
__export(crInput_exports, {
|
||||
RawKeyboardImpl: () => RawKeyboardImpl,
|
||||
RawMouseImpl: () => RawMouseImpl,
|
||||
RawTouchscreenImpl: () => RawTouchscreenImpl
|
||||
});
|
||||
module.exports = __toCommonJS(crInput_exports);
|
||||
var import_utils = require("../../utils");
|
||||
var input = __toESM(require("../input"));
|
||||
var import_macEditingCommands = require("../macEditingCommands");
|
||||
var import_crProtocolHelper = require("./crProtocolHelper");
|
||||
class RawKeyboardImpl {
|
||||
constructor(_client, _isMac, _dragManger) {
|
||||
this._client = _client;
|
||||
this._isMac = _isMac;
|
||||
this._dragManger = _dragManger;
|
||||
}
|
||||
_commandsForCode(code, modifiers) {
|
||||
if (!this._isMac)
|
||||
return [];
|
||||
const parts = [];
|
||||
for (const modifier of ["Shift", "Control", "Alt", "Meta"]) {
|
||||
if (modifiers.has(modifier))
|
||||
parts.push(modifier);
|
||||
}
|
||||
parts.push(code);
|
||||
const shortcut = parts.join("+");
|
||||
let commands = import_macEditingCommands.macEditingCommands[shortcut] || [];
|
||||
if ((0, import_utils.isString)(commands))
|
||||
commands = [commands];
|
||||
commands = commands.filter((x) => !x.startsWith("insert"));
|
||||
return commands.map((c) => c.substring(0, c.length - 1));
|
||||
}
|
||||
async keydown(progress, modifiers, keyName, description, autoRepeat) {
|
||||
const { code, key, location, text } = description;
|
||||
if (code === "Escape" && await progress.race(this._dragManger.cancelDrag()))
|
||||
return;
|
||||
const commands = this._commandsForCode(code, modifiers);
|
||||
await progress.race(this._client.send("Input.dispatchKeyEvent", {
|
||||
type: text ? "keyDown" : "rawKeyDown",
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers),
|
||||
windowsVirtualKeyCode: description.keyCodeWithoutLocation,
|
||||
code,
|
||||
commands,
|
||||
key,
|
||||
text,
|
||||
unmodifiedText: text,
|
||||
autoRepeat,
|
||||
location,
|
||||
isKeypad: location === input.keypadLocation
|
||||
}));
|
||||
}
|
||||
async keyup(progress, modifiers, keyName, description) {
|
||||
const { code, key, location } = description;
|
||||
await progress.race(this._client.send("Input.dispatchKeyEvent", {
|
||||
type: "keyUp",
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers),
|
||||
key,
|
||||
windowsVirtualKeyCode: description.keyCodeWithoutLocation,
|
||||
code,
|
||||
location
|
||||
}));
|
||||
}
|
||||
async sendText(progress, text) {
|
||||
await progress.race(this._client.send("Input.insertText", { text }));
|
||||
}
|
||||
}
|
||||
class RawMouseImpl {
|
||||
constructor(page, client, dragManager) {
|
||||
this._page = page;
|
||||
this._client = client;
|
||||
this._dragManager = dragManager;
|
||||
}
|
||||
async move(progress, x, y, button, buttons, modifiers, forClick) {
|
||||
const actualMove = async () => {
|
||||
await progress.race(this._client.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseMoved",
|
||||
button,
|
||||
buttons: (0, import_crProtocolHelper.toButtonsMask)(buttons),
|
||||
x,
|
||||
y,
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers),
|
||||
force: buttons.size > 0 ? 0.5 : 0
|
||||
}));
|
||||
};
|
||||
if (forClick) {
|
||||
await actualMove();
|
||||
return;
|
||||
}
|
||||
await this._dragManager.interceptDragCausedByMove(progress, x, y, button, buttons, modifiers, actualMove);
|
||||
}
|
||||
async down(progress, x, y, button, buttons, modifiers, clickCount) {
|
||||
if (this._dragManager.isDragging())
|
||||
return;
|
||||
await progress.race(this._client.send("Input.dispatchMouseEvent", {
|
||||
type: "mousePressed",
|
||||
button,
|
||||
buttons: (0, import_crProtocolHelper.toButtonsMask)(buttons),
|
||||
x,
|
||||
y,
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers),
|
||||
clickCount,
|
||||
force: buttons.size > 0 ? 0.5 : 0
|
||||
}));
|
||||
}
|
||||
async up(progress, x, y, button, buttons, modifiers, clickCount) {
|
||||
if (this._dragManager.isDragging()) {
|
||||
await this._dragManager.drop(progress, x, y, modifiers);
|
||||
return;
|
||||
}
|
||||
await progress.race(this._client.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseReleased",
|
||||
button,
|
||||
buttons: (0, import_crProtocolHelper.toButtonsMask)(buttons),
|
||||
x,
|
||||
y,
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers),
|
||||
clickCount
|
||||
}));
|
||||
}
|
||||
async wheel(progress, x, y, buttons, modifiers, deltaX, deltaY) {
|
||||
await progress.race(this._client.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseWheel",
|
||||
x,
|
||||
y,
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers),
|
||||
deltaX,
|
||||
deltaY
|
||||
}));
|
||||
}
|
||||
}
|
||||
class RawTouchscreenImpl {
|
||||
constructor(client) {
|
||||
this._client = client;
|
||||
}
|
||||
async tap(progress, x, y, modifiers) {
|
||||
await progress.race(Promise.all([
|
||||
this._client.send("Input.dispatchTouchEvent", {
|
||||
type: "touchStart",
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers),
|
||||
touchPoints: [{
|
||||
x,
|
||||
y
|
||||
}]
|
||||
}),
|
||||
this._client.send("Input.dispatchTouchEvent", {
|
||||
type: "touchEnd",
|
||||
modifiers: (0, import_crProtocolHelper.toModifiersMask)(modifiers),
|
||||
touchPoints: []
|
||||
})
|
||||
]));
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
RawKeyboardImpl,
|
||||
RawMouseImpl,
|
||||
RawTouchscreenImpl
|
||||
});
|
666
node_modules/playwright-core/lib/server/chromium/crNetworkManager.js
generated
vendored
Normal file
666
node_modules/playwright-core/lib/server/chromium/crNetworkManager.js
generated
vendored
Normal file
@@ -0,0 +1,666 @@
|
||||
"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 crNetworkManager_exports = {};
|
||||
__export(crNetworkManager_exports, {
|
||||
CRNetworkManager: () => CRNetworkManager
|
||||
});
|
||||
module.exports = __toCommonJS(crNetworkManager_exports);
|
||||
var import_utils = require("../../utils");
|
||||
var import_eventsHelper = require("../utils/eventsHelper");
|
||||
var import_helper = require("../helper");
|
||||
var network = __toESM(require("../network"));
|
||||
var import_protocolError = require("../protocolError");
|
||||
class CRNetworkManager {
|
||||
constructor(page, serviceWorker) {
|
||||
this._requestIdToRequest = /* @__PURE__ */ new Map();
|
||||
this._requestIdToRequestWillBeSentEvent = /* @__PURE__ */ new Map();
|
||||
this._credentials = null;
|
||||
this._attemptedAuthentications = /* @__PURE__ */ new Set();
|
||||
this._userRequestInterceptionEnabled = false;
|
||||
this._protocolRequestInterceptionEnabled = false;
|
||||
this._offline = false;
|
||||
this._extraHTTPHeaders = [];
|
||||
this._requestIdToRequestPausedEvent = /* @__PURE__ */ new Map();
|
||||
this._responseExtraInfoTracker = new ResponseExtraInfoTracker();
|
||||
this._sessions = /* @__PURE__ */ new Map();
|
||||
this._page = page;
|
||||
this._serviceWorker = serviceWorker;
|
||||
}
|
||||
async addSession(session, workerFrame, isMain) {
|
||||
const sessionInfo = { session, isMain, workerFrame, eventListeners: [] };
|
||||
sessionInfo.eventListeners = [
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Fetch.requestPaused", this._onRequestPaused.bind(this, sessionInfo)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Fetch.authRequired", this._onAuthRequired.bind(this, sessionInfo)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.requestWillBeSent", this._onRequestWillBeSent.bind(this, sessionInfo)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.requestWillBeSentExtraInfo", this._onRequestWillBeSentExtraInfo.bind(this)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.requestServedFromCache", this._onRequestServedFromCache.bind(this)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.responseReceived", this._onResponseReceived.bind(this, sessionInfo)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.responseReceivedExtraInfo", this._onResponseReceivedExtraInfo.bind(this)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.loadingFinished", this._onLoadingFinished.bind(this, sessionInfo)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.loadingFailed", this._onLoadingFailed.bind(this, sessionInfo))
|
||||
];
|
||||
if (this._page) {
|
||||
sessionInfo.eventListeners.push(...[
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.webSocketCreated", (e) => this._page.frameManager.onWebSocketCreated(e.requestId, e.url)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.webSocketWillSendHandshakeRequest", (e) => this._page.frameManager.onWebSocketRequest(e.requestId)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.webSocketHandshakeResponseReceived", (e) => this._page.frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.webSocketFrameSent", (e) => e.response.payloadData && this._page.frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.webSocketFrameReceived", (e) => e.response.payloadData && this._page.frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.webSocketClosed", (e) => this._page.frameManager.webSocketClosed(e.requestId)),
|
||||
import_eventsHelper.eventsHelper.addEventListener(session, "Network.webSocketFrameError", (e) => this._page.frameManager.webSocketError(e.requestId, e.errorMessage))
|
||||
]);
|
||||
}
|
||||
this._sessions.set(session, sessionInfo);
|
||||
await Promise.all([
|
||||
session.send("Network.enable"),
|
||||
this._updateProtocolRequestInterceptionForSession(
|
||||
sessionInfo,
|
||||
true
|
||||
/* initial */
|
||||
),
|
||||
this._setOfflineForSession(
|
||||
sessionInfo,
|
||||
true
|
||||
/* initial */
|
||||
),
|
||||
this._setExtraHTTPHeadersForSession(
|
||||
sessionInfo,
|
||||
true
|
||||
/* initial */
|
||||
)
|
||||
]);
|
||||
}
|
||||
removeSession(session) {
|
||||
const info = this._sessions.get(session);
|
||||
if (info)
|
||||
import_eventsHelper.eventsHelper.removeEventListeners(info.eventListeners);
|
||||
this._sessions.delete(session);
|
||||
}
|
||||
async _forEachSession(cb) {
|
||||
await Promise.all([...this._sessions.values()].map((info) => {
|
||||
if (info.isMain)
|
||||
return cb(info);
|
||||
return cb(info).catch((e) => {
|
||||
if ((0, import_protocolError.isSessionClosedError)(e))
|
||||
return;
|
||||
throw e;
|
||||
});
|
||||
}));
|
||||
}
|
||||
async authenticate(credentials) {
|
||||
this._credentials = credentials;
|
||||
await this._updateProtocolRequestInterception();
|
||||
}
|
||||
async setOffline(offline) {
|
||||
if (offline === this._offline)
|
||||
return;
|
||||
this._offline = offline;
|
||||
await this._forEachSession((info) => this._setOfflineForSession(info));
|
||||
}
|
||||
async _setOfflineForSession(info, initial) {
|
||||
if (initial && !this._offline)
|
||||
return;
|
||||
if (info.workerFrame)
|
||||
return;
|
||||
await info.session.send("Network.emulateNetworkConditions", {
|
||||
offline: this._offline,
|
||||
// values of 0 remove any active throttling. crbug.com/456324#c9
|
||||
latency: 0,
|
||||
downloadThroughput: -1,
|
||||
uploadThroughput: -1
|
||||
});
|
||||
}
|
||||
async setRequestInterception(value) {
|
||||
this._userRequestInterceptionEnabled = value;
|
||||
await this._updateProtocolRequestInterception();
|
||||
}
|
||||
async _updateProtocolRequestInterception() {
|
||||
const enabled = this._userRequestInterceptionEnabled || !!this._credentials;
|
||||
if (enabled === this._protocolRequestInterceptionEnabled)
|
||||
return;
|
||||
this._protocolRequestInterceptionEnabled = enabled;
|
||||
await this._forEachSession((info) => this._updateProtocolRequestInterceptionForSession(info));
|
||||
}
|
||||
async _updateProtocolRequestInterceptionForSession(info, initial) {
|
||||
const enabled = this._protocolRequestInterceptionEnabled;
|
||||
if (initial && !enabled)
|
||||
return;
|
||||
const cachePromise = info.session.send("Network.setCacheDisabled", { cacheDisabled: enabled });
|
||||
let fetchPromise = Promise.resolve(void 0);
|
||||
if (!info.workerFrame) {
|
||||
if (enabled)
|
||||
fetchPromise = info.session.send("Fetch.enable", { handleAuthRequests: true, patterns: [{ urlPattern: "*", requestStage: "Request" }] });
|
||||
else
|
||||
fetchPromise = info.session.send("Fetch.disable");
|
||||
}
|
||||
await Promise.all([cachePromise, fetchPromise]);
|
||||
}
|
||||
async setExtraHTTPHeaders(extraHTTPHeaders) {
|
||||
if (!this._extraHTTPHeaders.length && !extraHTTPHeaders.length)
|
||||
return;
|
||||
this._extraHTTPHeaders = extraHTTPHeaders;
|
||||
await this._forEachSession((info) => this._setExtraHTTPHeadersForSession(info));
|
||||
}
|
||||
async _setExtraHTTPHeadersForSession(info, initial) {
|
||||
if (initial && !this._extraHTTPHeaders.length)
|
||||
return;
|
||||
await info.session.send("Network.setExtraHTTPHeaders", { headers: (0, import_utils.headersArrayToObject)(
|
||||
this._extraHTTPHeaders,
|
||||
false
|
||||
/* lowerCase */
|
||||
) });
|
||||
}
|
||||
async clearCache() {
|
||||
await this._forEachSession(async (info) => {
|
||||
await info.session.send("Network.setCacheDisabled", { cacheDisabled: true });
|
||||
if (!this._protocolRequestInterceptionEnabled)
|
||||
await info.session.send("Network.setCacheDisabled", { cacheDisabled: false });
|
||||
if (!info.workerFrame)
|
||||
await info.session.send("Network.clearBrowserCache");
|
||||
});
|
||||
}
|
||||
_onRequestWillBeSent(sessionInfo, event) {
|
||||
if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith("data:")) {
|
||||
const requestId = event.requestId;
|
||||
const requestPausedEvent = this._requestIdToRequestPausedEvent.get(requestId);
|
||||
if (requestPausedEvent) {
|
||||
this._onRequest(sessionInfo, event, requestPausedEvent.sessionInfo, requestPausedEvent.event);
|
||||
this._requestIdToRequestPausedEvent.delete(requestId);
|
||||
} else {
|
||||
this._requestIdToRequestWillBeSentEvent.set(event.requestId, { sessionInfo, event });
|
||||
}
|
||||
} else {
|
||||
this._onRequest(sessionInfo, event, void 0, void 0);
|
||||
}
|
||||
}
|
||||
_onRequestServedFromCache(event) {
|
||||
this._responseExtraInfoTracker.requestServedFromCache(event);
|
||||
}
|
||||
_onRequestWillBeSentExtraInfo(event) {
|
||||
this._responseExtraInfoTracker.requestWillBeSentExtraInfo(event);
|
||||
}
|
||||
_onAuthRequired(sessionInfo, event) {
|
||||
let response = "Default";
|
||||
const shouldProvideCredentials = this._shouldProvideCredentials(event.request.url);
|
||||
if (this._attemptedAuthentications.has(event.requestId)) {
|
||||
response = "CancelAuth";
|
||||
} else if (shouldProvideCredentials) {
|
||||
response = "ProvideCredentials";
|
||||
this._attemptedAuthentications.add(event.requestId);
|
||||
}
|
||||
const { username, password } = shouldProvideCredentials && this._credentials ? this._credentials : { username: void 0, password: void 0 };
|
||||
sessionInfo.session._sendMayFail("Fetch.continueWithAuth", {
|
||||
requestId: event.requestId,
|
||||
authChallengeResponse: { response, username, password }
|
||||
});
|
||||
}
|
||||
_shouldProvideCredentials(url) {
|
||||
if (!this._credentials)
|
||||
return false;
|
||||
return !this._credentials.origin || new URL(url).origin.toLowerCase() === this._credentials.origin.toLowerCase();
|
||||
}
|
||||
_onRequestPaused(sessionInfo, event) {
|
||||
if (!event.networkId) {
|
||||
sessionInfo.session._sendMayFail("Fetch.continueRequest", { requestId: event.requestId });
|
||||
return;
|
||||
}
|
||||
if (event.request.url.startsWith("data:"))
|
||||
return;
|
||||
const requestId = event.networkId;
|
||||
const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId);
|
||||
if (requestWillBeSentEvent) {
|
||||
this._onRequest(requestWillBeSentEvent.sessionInfo, requestWillBeSentEvent.event, sessionInfo, event);
|
||||
this._requestIdToRequestWillBeSentEvent.delete(requestId);
|
||||
} else {
|
||||
const existingRequest = this._requestIdToRequest.get(requestId);
|
||||
const alreadyContinuedParams = existingRequest?._route?._alreadyContinuedParams;
|
||||
if (alreadyContinuedParams && !event.redirectedRequestId) {
|
||||
sessionInfo.session._sendMayFail("Fetch.continueRequest", {
|
||||
...alreadyContinuedParams,
|
||||
requestId: event.requestId
|
||||
});
|
||||
return;
|
||||
}
|
||||
this._requestIdToRequestPausedEvent.set(requestId, { sessionInfo, event });
|
||||
}
|
||||
}
|
||||
_onRequest(requestWillBeSentSessionInfo, requestWillBeSentEvent, requestPausedSessionInfo, requestPausedEvent) {
|
||||
if (requestWillBeSentEvent.request.url.startsWith("data:"))
|
||||
return;
|
||||
let redirectedFrom = null;
|
||||
if (requestWillBeSentEvent.redirectResponse) {
|
||||
const request2 = this._requestIdToRequest.get(requestWillBeSentEvent.requestId);
|
||||
if (request2) {
|
||||
this._handleRequestRedirect(request2, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp, requestWillBeSentEvent.redirectHasExtraInfo);
|
||||
redirectedFrom = request2;
|
||||
}
|
||||
}
|
||||
let frame = requestWillBeSentEvent.frameId ? this._page?.frameManager.frame(requestWillBeSentEvent.frameId) : requestWillBeSentSessionInfo.workerFrame;
|
||||
if (!frame && this._page && requestPausedEvent && requestPausedEvent.frameId)
|
||||
frame = this._page.frameManager.frame(requestPausedEvent.frameId);
|
||||
if (!frame && this._page && requestWillBeSentEvent.frameId === (this._page?.delegate)._targetId) {
|
||||
frame = this._page.frameManager.frameAttached(requestWillBeSentEvent.frameId, null);
|
||||
}
|
||||
const isInterceptedOptionsPreflight = !!requestPausedEvent && requestPausedEvent.request.method === "OPTIONS" && requestWillBeSentEvent.initiator.type === "preflight";
|
||||
if (isInterceptedOptionsPreflight && (this._page || this._serviceWorker).needsRequestInterception()) {
|
||||
const requestHeaders = requestPausedEvent.request.headers;
|
||||
const responseHeaders = [
|
||||
{ name: "Access-Control-Allow-Origin", value: requestHeaders["Origin"] || "*" },
|
||||
{ name: "Access-Control-Allow-Methods", value: requestHeaders["Access-Control-Request-Method"] || "GET, POST, OPTIONS, DELETE" },
|
||||
{ name: "Access-Control-Allow-Credentials", value: "true" }
|
||||
];
|
||||
if (requestHeaders["Access-Control-Request-Headers"])
|
||||
responseHeaders.push({ name: "Access-Control-Allow-Headers", value: requestHeaders["Access-Control-Request-Headers"] });
|
||||
requestPausedSessionInfo.session._sendMayFail("Fetch.fulfillRequest", {
|
||||
requestId: requestPausedEvent.requestId,
|
||||
responseCode: 204,
|
||||
responsePhrase: network.statusText(204),
|
||||
responseHeaders,
|
||||
body: ""
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!frame && !this._serviceWorker) {
|
||||
if (requestPausedEvent)
|
||||
requestPausedSessionInfo.session._sendMayFail("Fetch.continueRequest", { requestId: requestPausedEvent.requestId });
|
||||
return;
|
||||
}
|
||||
let route = null;
|
||||
let headersOverride;
|
||||
if (requestPausedEvent) {
|
||||
if (redirectedFrom || !this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) {
|
||||
headersOverride = redirectedFrom?._originalRequestRoute?._alreadyContinuedParams?.headers;
|
||||
requestPausedSessionInfo.session._sendMayFail("Fetch.continueRequest", { requestId: requestPausedEvent.requestId, headers: headersOverride });
|
||||
} else {
|
||||
route = new RouteImpl(requestPausedSessionInfo.session, requestPausedEvent.requestId);
|
||||
}
|
||||
}
|
||||
const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === "Document";
|
||||
const documentId = isNavigationRequest ? requestWillBeSentEvent.loaderId : void 0;
|
||||
const request = new InterceptableRequest({
|
||||
session: requestWillBeSentSessionInfo.session,
|
||||
context: (this._page || this._serviceWorker).browserContext,
|
||||
frame: frame || null,
|
||||
serviceWorker: this._serviceWorker || null,
|
||||
documentId,
|
||||
route,
|
||||
requestWillBeSentEvent,
|
||||
requestPausedEvent,
|
||||
redirectedFrom,
|
||||
headersOverride: headersOverride || null
|
||||
});
|
||||
this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request);
|
||||
if (route) {
|
||||
request.request.setRawRequestHeaders((0, import_utils.headersObjectToArray)(requestPausedEvent.request.headers, "\n"));
|
||||
}
|
||||
(this._page?.frameManager || this._serviceWorker).requestStarted(request.request, route || void 0);
|
||||
}
|
||||
_createResponse(request, responsePayload, hasExtraInfo) {
|
||||
const getResponseBody = async () => {
|
||||
const contentLengthHeader = Object.entries(responsePayload.headers).find((header) => header[0].toLowerCase() === "content-length");
|
||||
const expectedLength = contentLengthHeader ? +contentLengthHeader[1] : void 0;
|
||||
const session = request.session;
|
||||
const response2 = await session.send("Network.getResponseBody", { requestId: request._requestId });
|
||||
if (response2.body || !expectedLength)
|
||||
return Buffer.from(response2.body, response2.base64Encoded ? "base64" : "utf8");
|
||||
if (request._route?._fulfilled)
|
||||
return Buffer.from("");
|
||||
const resource = await session.send("Network.loadNetworkResource", { url: request.request.url(), frameId: this._serviceWorker ? void 0 : request.request.frame()._id, options: { disableCache: false, includeCredentials: true } });
|
||||
const chunks = [];
|
||||
while (resource.resource.stream) {
|
||||
const chunk = await session.send("IO.read", { handle: resource.resource.stream });
|
||||
chunks.push(Buffer.from(chunk.data, chunk.base64Encoded ? "base64" : "utf-8"));
|
||||
if (chunk.eof) {
|
||||
await session.send("IO.close", { handle: resource.resource.stream });
|
||||
break;
|
||||
}
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
};
|
||||
const timingPayload = responsePayload.timing;
|
||||
let timing;
|
||||
if (timingPayload && !this._responseExtraInfoTracker.servedFromCache(request._requestId)) {
|
||||
timing = {
|
||||
startTime: (timingPayload.requestTime - request._timestamp + request._wallTime) * 1e3,
|
||||
domainLookupStart: timingPayload.dnsStart,
|
||||
domainLookupEnd: timingPayload.dnsEnd,
|
||||
connectStart: timingPayload.connectStart,
|
||||
secureConnectionStart: timingPayload.sslStart,
|
||||
connectEnd: timingPayload.connectEnd,
|
||||
requestStart: timingPayload.sendStart,
|
||||
responseStart: timingPayload.receiveHeadersEnd
|
||||
};
|
||||
} else {
|
||||
timing = {
|
||||
startTime: request._wallTime * 1e3,
|
||||
domainLookupStart: -1,
|
||||
domainLookupEnd: -1,
|
||||
connectStart: -1,
|
||||
secureConnectionStart: -1,
|
||||
connectEnd: -1,
|
||||
requestStart: -1,
|
||||
responseStart: -1
|
||||
};
|
||||
}
|
||||
const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, (0, import_utils.headersObjectToArray)(responsePayload.headers), timing, getResponseBody, !!responsePayload.fromServiceWorker, responsePayload.protocol);
|
||||
if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === "number") {
|
||||
response._serverAddrFinished({
|
||||
ipAddress: responsePayload.remoteIPAddress,
|
||||
port: responsePayload.remotePort
|
||||
});
|
||||
} else {
|
||||
response._serverAddrFinished();
|
||||
}
|
||||
response._securityDetailsFinished({
|
||||
protocol: responsePayload?.securityDetails?.protocol,
|
||||
subjectName: responsePayload?.securityDetails?.subjectName,
|
||||
issuer: responsePayload?.securityDetails?.issuer,
|
||||
validFrom: responsePayload?.securityDetails?.validFrom,
|
||||
validTo: responsePayload?.securityDetails?.validTo
|
||||
});
|
||||
this._responseExtraInfoTracker.processResponse(request._requestId, response, hasExtraInfo);
|
||||
return response;
|
||||
}
|
||||
_deleteRequest(request) {
|
||||
this._requestIdToRequest.delete(request._requestId);
|
||||
if (request._interceptionId)
|
||||
this._attemptedAuthentications.delete(request._interceptionId);
|
||||
}
|
||||
_handleRequestRedirect(request, responsePayload, timestamp, hasExtraInfo) {
|
||||
const response = this._createResponse(request, responsePayload, hasExtraInfo);
|
||||
response.setTransferSize(null);
|
||||
response.setEncodedBodySize(null);
|
||||
response._requestFinished((timestamp - request._timestamp) * 1e3);
|
||||
this._deleteRequest(request);
|
||||
(this._page?.frameManager || this._serviceWorker).requestReceivedResponse(response);
|
||||
(this._page?.frameManager || this._serviceWorker).reportRequestFinished(request.request, response);
|
||||
}
|
||||
_onResponseReceivedExtraInfo(event) {
|
||||
this._responseExtraInfoTracker.responseReceivedExtraInfo(event);
|
||||
}
|
||||
_onResponseReceived(sessionInfo, event) {
|
||||
let request = this._requestIdToRequest.get(event.requestId);
|
||||
if (!request && event.response.fromServiceWorker) {
|
||||
const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId);
|
||||
if (requestWillBeSentEvent) {
|
||||
this._requestIdToRequestWillBeSentEvent.delete(event.requestId);
|
||||
this._onRequest(sessionInfo, requestWillBeSentEvent.event, void 0, void 0);
|
||||
request = this._requestIdToRequest.get(event.requestId);
|
||||
}
|
||||
}
|
||||
if (!request)
|
||||
return;
|
||||
const response = this._createResponse(request, event.response, event.hasExtraInfo);
|
||||
(this._page?.frameManager || this._serviceWorker).requestReceivedResponse(response);
|
||||
}
|
||||
_onLoadingFinished(sessionInfo, event) {
|
||||
this._responseExtraInfoTracker.loadingFinished(event);
|
||||
const request = this._requestIdToRequest.get(event.requestId);
|
||||
if (!request)
|
||||
return;
|
||||
this._maybeUpdateRequestSession(sessionInfo, request);
|
||||
const response = request.request._existingResponse();
|
||||
if (response) {
|
||||
response.setTransferSize(event.encodedDataLength);
|
||||
response.responseHeadersSize().then((size) => response.setEncodedBodySize(event.encodedDataLength - size));
|
||||
response._requestFinished(import_helper.helper.secondsToRoundishMillis(event.timestamp - request._timestamp));
|
||||
}
|
||||
this._deleteRequest(request);
|
||||
(this._page?.frameManager || this._serviceWorker).reportRequestFinished(request.request, response);
|
||||
}
|
||||
_onLoadingFailed(sessionInfo, event) {
|
||||
this._responseExtraInfoTracker.loadingFailed(event);
|
||||
let request = this._requestIdToRequest.get(event.requestId);
|
||||
if (!request) {
|
||||
const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId);
|
||||
if (requestWillBeSentEvent) {
|
||||
this._requestIdToRequestWillBeSentEvent.delete(event.requestId);
|
||||
this._onRequest(sessionInfo, requestWillBeSentEvent.event, void 0, void 0);
|
||||
request = this._requestIdToRequest.get(event.requestId);
|
||||
}
|
||||
}
|
||||
if (!request)
|
||||
return;
|
||||
this._maybeUpdateRequestSession(sessionInfo, request);
|
||||
const response = request.request._existingResponse();
|
||||
if (response) {
|
||||
response.setTransferSize(null);
|
||||
response.setEncodedBodySize(null);
|
||||
response._requestFinished(import_helper.helper.secondsToRoundishMillis(event.timestamp - request._timestamp));
|
||||
} else {
|
||||
request.request.setRawRequestHeaders(null);
|
||||
}
|
||||
this._deleteRequest(request);
|
||||
request.request._setFailureText(event.errorText || event.blockedReason || "");
|
||||
(this._page?.frameManager || this._serviceWorker).requestFailed(request.request, !!event.canceled);
|
||||
}
|
||||
_maybeUpdateRequestSession(sessionInfo, request) {
|
||||
if (request.session !== sessionInfo.session && !sessionInfo.isMain && (request._documentId === request._requestId || sessionInfo.workerFrame))
|
||||
request.session = sessionInfo.session;
|
||||
}
|
||||
}
|
||||
class InterceptableRequest {
|
||||
constructor(options) {
|
||||
const { session, context, frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom, serviceWorker, headersOverride } = options;
|
||||
this.session = session;
|
||||
this._timestamp = requestWillBeSentEvent.timestamp;
|
||||
this._wallTime = requestWillBeSentEvent.wallTime;
|
||||
this._requestId = requestWillBeSentEvent.requestId;
|
||||
this._interceptionId = requestPausedEvent && requestPausedEvent.requestId;
|
||||
this._documentId = documentId;
|
||||
this._route = route;
|
||||
this._originalRequestRoute = route ?? redirectedFrom?._originalRequestRoute;
|
||||
const {
|
||||
headers,
|
||||
method,
|
||||
url,
|
||||
postDataEntries = null
|
||||
} = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request;
|
||||
const type = (requestWillBeSentEvent.type || "").toLowerCase();
|
||||
let postDataBuffer = null;
|
||||
const entries = postDataEntries?.filter((entry) => entry.bytes);
|
||||
if (entries && entries.length)
|
||||
postDataBuffer = Buffer.concat(entries.map((entry) => Buffer.from(entry.bytes, "base64")));
|
||||
this.request = new network.Request(context, frame, serviceWorker, redirectedFrom?.request || null, documentId, url, type, method, postDataBuffer, headersOverride || (0, import_utils.headersObjectToArray)(headers));
|
||||
}
|
||||
}
|
||||
class RouteImpl {
|
||||
constructor(session, interceptionId) {
|
||||
this._fulfilled = false;
|
||||
this._session = session;
|
||||
this._interceptionId = interceptionId;
|
||||
}
|
||||
async continue(overrides) {
|
||||
this._alreadyContinuedParams = {
|
||||
requestId: this._interceptionId,
|
||||
url: overrides.url,
|
||||
headers: overrides.headers,
|
||||
method: overrides.method,
|
||||
postData: overrides.postData ? overrides.postData.toString("base64") : void 0
|
||||
};
|
||||
await catchDisallowedErrors(async () => {
|
||||
await this._session.send("Fetch.continueRequest", this._alreadyContinuedParams);
|
||||
});
|
||||
}
|
||||
async fulfill(response) {
|
||||
this._fulfilled = true;
|
||||
const body = response.isBase64 ? response.body : Buffer.from(response.body).toString("base64");
|
||||
const responseHeaders = splitSetCookieHeader(response.headers);
|
||||
await catchDisallowedErrors(async () => {
|
||||
await this._session.send("Fetch.fulfillRequest", {
|
||||
requestId: this._interceptionId,
|
||||
responseCode: response.status,
|
||||
responsePhrase: network.statusText(response.status),
|
||||
responseHeaders,
|
||||
body
|
||||
});
|
||||
});
|
||||
}
|
||||
async abort(errorCode = "failed") {
|
||||
const errorReason = errorReasons[errorCode];
|
||||
(0, import_utils.assert)(errorReason, "Unknown error code: " + errorCode);
|
||||
await catchDisallowedErrors(async () => {
|
||||
await this._session.send("Fetch.failRequest", {
|
||||
requestId: this._interceptionId,
|
||||
errorReason
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
async function catchDisallowedErrors(callback) {
|
||||
try {
|
||||
return await callback();
|
||||
} catch (e) {
|
||||
if ((0, import_protocolError.isProtocolError)(e) && e.message.includes("Invalid http status code or phrase"))
|
||||
throw e;
|
||||
if ((0, import_protocolError.isProtocolError)(e) && e.message.includes("Unsafe header"))
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
function splitSetCookieHeader(headers) {
|
||||
const index = headers.findIndex(({ name }) => name.toLowerCase() === "set-cookie");
|
||||
if (index === -1)
|
||||
return headers;
|
||||
const header = headers[index];
|
||||
const values = header.value.split("\n");
|
||||
if (values.length === 1)
|
||||
return headers;
|
||||
const result = headers.slice();
|
||||
result.splice(index, 1, ...values.map((value) => ({ name: header.name, value })));
|
||||
return result;
|
||||
}
|
||||
const errorReasons = {
|
||||
"aborted": "Aborted",
|
||||
"accessdenied": "AccessDenied",
|
||||
"addressunreachable": "AddressUnreachable",
|
||||
"blockedbyclient": "BlockedByClient",
|
||||
"blockedbyresponse": "BlockedByResponse",
|
||||
"connectionaborted": "ConnectionAborted",
|
||||
"connectionclosed": "ConnectionClosed",
|
||||
"connectionfailed": "ConnectionFailed",
|
||||
"connectionrefused": "ConnectionRefused",
|
||||
"connectionreset": "ConnectionReset",
|
||||
"internetdisconnected": "InternetDisconnected",
|
||||
"namenotresolved": "NameNotResolved",
|
||||
"timedout": "TimedOut",
|
||||
"failed": "Failed"
|
||||
};
|
||||
class ResponseExtraInfoTracker {
|
||||
constructor() {
|
||||
this._requests = /* @__PURE__ */ new Map();
|
||||
}
|
||||
requestWillBeSentExtraInfo(event) {
|
||||
const info = this._getOrCreateEntry(event.requestId);
|
||||
info.requestWillBeSentExtraInfo.push(event);
|
||||
this._patchHeaders(info, info.requestWillBeSentExtraInfo.length - 1);
|
||||
this._checkFinished(info);
|
||||
}
|
||||
requestServedFromCache(event) {
|
||||
const info = this._getOrCreateEntry(event.requestId);
|
||||
info.servedFromCache = true;
|
||||
}
|
||||
servedFromCache(requestId) {
|
||||
const info = this._requests.get(requestId);
|
||||
return !!info?.servedFromCache;
|
||||
}
|
||||
responseReceivedExtraInfo(event) {
|
||||
const info = this._getOrCreateEntry(event.requestId);
|
||||
info.responseReceivedExtraInfo.push(event);
|
||||
this._patchHeaders(info, info.responseReceivedExtraInfo.length - 1);
|
||||
this._checkFinished(info);
|
||||
}
|
||||
processResponse(requestId, response, hasExtraInfo) {
|
||||
let info = this._requests.get(requestId);
|
||||
if (!hasExtraInfo || info?.servedFromCache) {
|
||||
response.request().setRawRequestHeaders(null);
|
||||
response.setResponseHeadersSize(null);
|
||||
response.setRawResponseHeaders(null);
|
||||
return;
|
||||
}
|
||||
info = this._getOrCreateEntry(requestId);
|
||||
info.responses.push(response);
|
||||
this._patchHeaders(info, info.responses.length - 1);
|
||||
}
|
||||
loadingFinished(event) {
|
||||
const info = this._requests.get(event.requestId);
|
||||
if (!info)
|
||||
return;
|
||||
info.loadingFinished = event;
|
||||
this._checkFinished(info);
|
||||
}
|
||||
loadingFailed(event) {
|
||||
const info = this._requests.get(event.requestId);
|
||||
if (!info)
|
||||
return;
|
||||
info.loadingFailed = event;
|
||||
this._checkFinished(info);
|
||||
}
|
||||
_getOrCreateEntry(requestId) {
|
||||
let info = this._requests.get(requestId);
|
||||
if (!info) {
|
||||
info = {
|
||||
requestId,
|
||||
requestWillBeSentExtraInfo: [],
|
||||
responseReceivedExtraInfo: [],
|
||||
responses: []
|
||||
};
|
||||
this._requests.set(requestId, info);
|
||||
}
|
||||
return info;
|
||||
}
|
||||
_patchHeaders(info, index) {
|
||||
const response = info.responses[index];
|
||||
const requestExtraInfo = info.requestWillBeSentExtraInfo[index];
|
||||
if (response && requestExtraInfo) {
|
||||
response.request().setRawRequestHeaders((0, import_utils.headersObjectToArray)(requestExtraInfo.headers, "\n"));
|
||||
info.requestWillBeSentExtraInfo[index] = void 0;
|
||||
}
|
||||
const responseExtraInfo = info.responseReceivedExtraInfo[index];
|
||||
if (response && responseExtraInfo) {
|
||||
response.setResponseHeadersSize(responseExtraInfo.headersText?.length || 0);
|
||||
response.setRawResponseHeaders((0, import_utils.headersObjectToArray)(responseExtraInfo.headers, "\n"));
|
||||
info.responseReceivedExtraInfo[index] = void 0;
|
||||
}
|
||||
}
|
||||
_checkFinished(info) {
|
||||
if (!info.loadingFinished && !info.loadingFailed)
|
||||
return;
|
||||
if (info.responses.length <= info.responseReceivedExtraInfo.length) {
|
||||
this._stopTracking(info.requestId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
_stopTracking(requestId) {
|
||||
this._requests.delete(requestId);
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
CRNetworkManager
|
||||
});
|
1078
node_modules/playwright-core/lib/server/chromium/crPage.js
generated
vendored
Normal file
1078
node_modules/playwright-core/lib/server/chromium/crPage.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
121
node_modules/playwright-core/lib/server/chromium/crPdf.js
generated
vendored
Normal file
121
node_modules/playwright-core/lib/server/chromium/crPdf.js
generated
vendored
Normal file
@@ -0,0 +1,121 @@
|
||||
"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 crPdf_exports = {};
|
||||
__export(crPdf_exports, {
|
||||
CRPDF: () => CRPDF
|
||||
});
|
||||
module.exports = __toCommonJS(crPdf_exports);
|
||||
var import_crProtocolHelper = require("./crProtocolHelper");
|
||||
var import_utils = require("../../utils");
|
||||
const PagePaperFormats = {
|
||||
letter: { width: 8.5, height: 11 },
|
||||
legal: { width: 8.5, height: 14 },
|
||||
tabloid: { width: 11, height: 17 },
|
||||
ledger: { width: 17, height: 11 },
|
||||
a0: { width: 33.1, height: 46.8 },
|
||||
a1: { width: 23.4, height: 33.1 },
|
||||
a2: { width: 16.54, height: 23.4 },
|
||||
a3: { width: 11.7, height: 16.54 },
|
||||
a4: { width: 8.27, height: 11.7 },
|
||||
a5: { width: 5.83, height: 8.27 },
|
||||
a6: { width: 4.13, height: 5.83 }
|
||||
};
|
||||
const unitToPixels = {
|
||||
"px": 1,
|
||||
"in": 96,
|
||||
"cm": 37.8,
|
||||
"mm": 3.78
|
||||
};
|
||||
function convertPrintParameterToInches(text) {
|
||||
if (text === void 0)
|
||||
return void 0;
|
||||
let unit = text.substring(text.length - 2).toLowerCase();
|
||||
let valueText = "";
|
||||
if (unitToPixels.hasOwnProperty(unit)) {
|
||||
valueText = text.substring(0, text.length - 2);
|
||||
} else {
|
||||
unit = "px";
|
||||
valueText = text;
|
||||
}
|
||||
const value = Number(valueText);
|
||||
(0, import_utils.assert)(!isNaN(value), "Failed to parse parameter value: " + text);
|
||||
const pixels = value * unitToPixels[unit];
|
||||
return pixels / 96;
|
||||
}
|
||||
class CRPDF {
|
||||
constructor(client) {
|
||||
this._client = client;
|
||||
}
|
||||
async generate(options) {
|
||||
const {
|
||||
scale = 1,
|
||||
displayHeaderFooter = false,
|
||||
headerTemplate = "",
|
||||
footerTemplate = "",
|
||||
printBackground = false,
|
||||
landscape = false,
|
||||
pageRanges = "",
|
||||
preferCSSPageSize = false,
|
||||
margin = {},
|
||||
tagged = false,
|
||||
outline = false
|
||||
} = options;
|
||||
let paperWidth = 8.5;
|
||||
let paperHeight = 11;
|
||||
if (options.format) {
|
||||
const format = PagePaperFormats[options.format.toLowerCase()];
|
||||
(0, import_utils.assert)(format, "Unknown paper format: " + options.format);
|
||||
paperWidth = format.width;
|
||||
paperHeight = format.height;
|
||||
} else {
|
||||
paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
|
||||
paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
|
||||
}
|
||||
const marginTop = convertPrintParameterToInches(margin.top) || 0;
|
||||
const marginLeft = convertPrintParameterToInches(margin.left) || 0;
|
||||
const marginBottom = convertPrintParameterToInches(margin.bottom) || 0;
|
||||
const marginRight = convertPrintParameterToInches(margin.right) || 0;
|
||||
const generateDocumentOutline = outline;
|
||||
const generateTaggedPDF = tagged;
|
||||
const result = await this._client.send("Page.printToPDF", {
|
||||
transferMode: "ReturnAsStream",
|
||||
landscape,
|
||||
displayHeaderFooter,
|
||||
headerTemplate,
|
||||
footerTemplate,
|
||||
printBackground,
|
||||
scale,
|
||||
paperWidth,
|
||||
paperHeight,
|
||||
marginTop,
|
||||
marginBottom,
|
||||
marginLeft,
|
||||
marginRight,
|
||||
pageRanges,
|
||||
preferCSSPageSize,
|
||||
generateTaggedPDF,
|
||||
generateDocumentOutline
|
||||
});
|
||||
return await (0, import_crProtocolHelper.readProtocolStream)(this._client, result.stream);
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
CRPDF
|
||||
});
|
145
node_modules/playwright-core/lib/server/chromium/crProtocolHelper.js
generated
vendored
Normal file
145
node_modules/playwright-core/lib/server/chromium/crProtocolHelper.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 crProtocolHelper_exports = {};
|
||||
__export(crProtocolHelper_exports, {
|
||||
exceptionToError: () => exceptionToError,
|
||||
getExceptionMessage: () => getExceptionMessage,
|
||||
readProtocolStream: () => readProtocolStream,
|
||||
releaseObject: () => releaseObject,
|
||||
saveProtocolStream: () => saveProtocolStream,
|
||||
toButtonsMask: () => toButtonsMask,
|
||||
toConsoleMessageLocation: () => toConsoleMessageLocation,
|
||||
toModifiersMask: () => toModifiersMask
|
||||
});
|
||||
module.exports = __toCommonJS(crProtocolHelper_exports);
|
||||
var import_fs = __toESM(require("fs"));
|
||||
var import_stackTrace = require("../../utils/isomorphic/stackTrace");
|
||||
var import_fileUtils = require("../utils/fileUtils");
|
||||
function getExceptionMessage(exceptionDetails) {
|
||||
if (exceptionDetails.exception)
|
||||
return exceptionDetails.exception.description || String(exceptionDetails.exception.value);
|
||||
let message = exceptionDetails.text;
|
||||
if (exceptionDetails.stackTrace) {
|
||||
for (const callframe of exceptionDetails.stackTrace.callFrames) {
|
||||
const location = callframe.url + ":" + callframe.lineNumber + ":" + callframe.columnNumber;
|
||||
const functionName = callframe.functionName || "<anonymous>";
|
||||
message += `
|
||||
at ${functionName} (${location})`;
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
async function releaseObject(client, objectId) {
|
||||
await client.send("Runtime.releaseObject", { objectId }).catch((error) => {
|
||||
});
|
||||
}
|
||||
async function saveProtocolStream(client, handle, path) {
|
||||
let eof = false;
|
||||
await (0, import_fileUtils.mkdirIfNeeded)(path);
|
||||
const fd = await import_fs.default.promises.open(path, "w");
|
||||
while (!eof) {
|
||||
const response = await client.send("IO.read", { handle });
|
||||
eof = response.eof;
|
||||
const buf = Buffer.from(response.data, response.base64Encoded ? "base64" : void 0);
|
||||
await fd.write(buf);
|
||||
}
|
||||
await fd.close();
|
||||
await client.send("IO.close", { handle });
|
||||
}
|
||||
async function readProtocolStream(client, handle) {
|
||||
let eof = false;
|
||||
const chunks = [];
|
||||
while (!eof) {
|
||||
const response = await client.send("IO.read", { handle });
|
||||
eof = response.eof;
|
||||
const buf = Buffer.from(response.data, response.base64Encoded ? "base64" : void 0);
|
||||
chunks.push(buf);
|
||||
}
|
||||
await client.send("IO.close", { handle });
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
function toConsoleMessageLocation(stackTrace) {
|
||||
return stackTrace && stackTrace.callFrames.length ? {
|
||||
url: stackTrace.callFrames[0].url,
|
||||
lineNumber: stackTrace.callFrames[0].lineNumber,
|
||||
columnNumber: stackTrace.callFrames[0].columnNumber
|
||||
} : { url: "", lineNumber: 0, columnNumber: 0 };
|
||||
}
|
||||
function exceptionToError(exceptionDetails) {
|
||||
const messageWithStack = getExceptionMessage(exceptionDetails);
|
||||
const lines = messageWithStack.split("\n");
|
||||
const firstStackTraceLine = lines.findIndex((line) => line.startsWith(" at"));
|
||||
let messageWithName = "";
|
||||
let stack = "";
|
||||
if (firstStackTraceLine === -1) {
|
||||
messageWithName = messageWithStack;
|
||||
} else {
|
||||
messageWithName = lines.slice(0, firstStackTraceLine).join("\n");
|
||||
stack = messageWithStack;
|
||||
}
|
||||
const { name, message } = (0, import_stackTrace.splitErrorMessage)(messageWithName);
|
||||
const err = new Error(message);
|
||||
err.stack = stack;
|
||||
const nameOverride = exceptionDetails.exception?.preview?.properties.find((o) => o.name === "name");
|
||||
err.name = nameOverride ? nameOverride.value ?? "Error" : name;
|
||||
return err;
|
||||
}
|
||||
function toModifiersMask(modifiers) {
|
||||
let mask = 0;
|
||||
if (modifiers.has("Alt"))
|
||||
mask |= 1;
|
||||
if (modifiers.has("Control"))
|
||||
mask |= 2;
|
||||
if (modifiers.has("Meta"))
|
||||
mask |= 4;
|
||||
if (modifiers.has("Shift"))
|
||||
mask |= 8;
|
||||
return mask;
|
||||
}
|
||||
function toButtonsMask(buttons) {
|
||||
let mask = 0;
|
||||
if (buttons.has("left"))
|
||||
mask |= 1;
|
||||
if (buttons.has("right"))
|
||||
mask |= 2;
|
||||
if (buttons.has("middle"))
|
||||
mask |= 4;
|
||||
return mask;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
exceptionToError,
|
||||
getExceptionMessage,
|
||||
readProtocolStream,
|
||||
releaseObject,
|
||||
saveProtocolStream,
|
||||
toButtonsMask,
|
||||
toConsoleMessageLocation,
|
||||
toModifiersMask
|
||||
});
|
123
node_modules/playwright-core/lib/server/chromium/crServiceWorker.js
generated
vendored
Normal file
123
node_modules/playwright-core/lib/server/chromium/crServiceWorker.js
generated
vendored
Normal file
@@ -0,0 +1,123 @@
|
||||
"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 crServiceWorker_exports = {};
|
||||
__export(crServiceWorker_exports, {
|
||||
CRServiceWorker: () => CRServiceWorker
|
||||
});
|
||||
module.exports = __toCommonJS(crServiceWorker_exports);
|
||||
var import_page = require("../page");
|
||||
var import_crExecutionContext = require("./crExecutionContext");
|
||||
var import_crNetworkManager = require("./crNetworkManager");
|
||||
var import_browserContext = require("../browserContext");
|
||||
var network = __toESM(require("../network"));
|
||||
class CRServiceWorker extends import_page.Worker {
|
||||
constructor(browserContext, session, url) {
|
||||
super(browserContext, url);
|
||||
this._session = session;
|
||||
this.browserContext = browserContext;
|
||||
if (!!process.env.PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS)
|
||||
this._networkManager = new import_crNetworkManager.CRNetworkManager(null, this);
|
||||
session.once("Runtime.executionContextCreated", (event) => {
|
||||
this.createExecutionContext(new import_crExecutionContext.CRExecutionContext(session, event.context));
|
||||
});
|
||||
if (this._networkManager && this._isNetworkInspectionEnabled()) {
|
||||
this.updateRequestInterception();
|
||||
this.updateExtraHTTPHeaders();
|
||||
this.updateHttpCredentials();
|
||||
this.updateOffline();
|
||||
this._networkManager.addSession(
|
||||
session,
|
||||
void 0,
|
||||
true
|
||||
/* isMain */
|
||||
).catch(() => {
|
||||
});
|
||||
}
|
||||
session.send("Runtime.enable", {}).catch((e) => {
|
||||
});
|
||||
session.send("Runtime.runIfWaitingForDebugger").catch((e) => {
|
||||
});
|
||||
session.on("Inspector.targetReloadedAfterCrash", () => {
|
||||
session._sendMayFail("Runtime.runIfWaitingForDebugger", {});
|
||||
});
|
||||
}
|
||||
didClose() {
|
||||
this._networkManager?.removeSession(this._session);
|
||||
this._session.dispose();
|
||||
super.didClose();
|
||||
}
|
||||
async updateOffline() {
|
||||
if (!this._isNetworkInspectionEnabled())
|
||||
return;
|
||||
await this._networkManager?.setOffline(!!this.browserContext._options.offline).catch(() => {
|
||||
});
|
||||
}
|
||||
async updateHttpCredentials() {
|
||||
if (!this._isNetworkInspectionEnabled())
|
||||
return;
|
||||
await this._networkManager?.authenticate(this.browserContext._options.httpCredentials || null).catch(() => {
|
||||
});
|
||||
}
|
||||
async updateExtraHTTPHeaders() {
|
||||
if (!this._isNetworkInspectionEnabled())
|
||||
return;
|
||||
await this._networkManager?.setExtraHTTPHeaders(this.browserContext._options.extraHTTPHeaders || []).catch(() => {
|
||||
});
|
||||
}
|
||||
async updateRequestInterception() {
|
||||
if (!this._isNetworkInspectionEnabled())
|
||||
return;
|
||||
await this._networkManager?.setRequestInterception(this.needsRequestInterception()).catch(() => {
|
||||
});
|
||||
}
|
||||
needsRequestInterception() {
|
||||
return this._isNetworkInspectionEnabled() && this.browserContext.requestInterceptors.length > 0;
|
||||
}
|
||||
reportRequestFinished(request, response) {
|
||||
this.browserContext.emit(import_browserContext.BrowserContext.Events.RequestFinished, { request, response });
|
||||
}
|
||||
requestFailed(request, _canceled) {
|
||||
this.browserContext.emit(import_browserContext.BrowserContext.Events.RequestFailed, request);
|
||||
}
|
||||
requestReceivedResponse(response) {
|
||||
this.browserContext.emit(import_browserContext.BrowserContext.Events.Response, response);
|
||||
}
|
||||
requestStarted(request, route) {
|
||||
this.browserContext.emit(import_browserContext.BrowserContext.Events.Request, request);
|
||||
if (route)
|
||||
new network.Route(request, route).handle(this.browserContext.requestInterceptors);
|
||||
}
|
||||
_isNetworkInspectionEnabled() {
|
||||
return this.browserContext._options.serviceWorkers !== "block";
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
CRServiceWorker
|
||||
});
|
162
node_modules/playwright-core/lib/server/chromium/defaultFontFamilies.js
generated
vendored
Normal file
162
node_modules/playwright-core/lib/server/chromium/defaultFontFamilies.js
generated
vendored
Normal file
@@ -0,0 +1,162 @@
|
||||
"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 defaultFontFamilies_exports = {};
|
||||
__export(defaultFontFamilies_exports, {
|
||||
platformToFontFamilies: () => platformToFontFamilies
|
||||
});
|
||||
module.exports = __toCommonJS(defaultFontFamilies_exports);
|
||||
const platformToFontFamilies = {
|
||||
"linux": {
|
||||
"fontFamilies": {
|
||||
"standard": "Times New Roman",
|
||||
"fixed": "Monospace",
|
||||
"serif": "Times New Roman",
|
||||
"sansSerif": "Arial",
|
||||
"cursive": "Comic Sans MS",
|
||||
"fantasy": "Impact"
|
||||
}
|
||||
},
|
||||
"mac": {
|
||||
"fontFamilies": {
|
||||
"standard": "Times",
|
||||
"fixed": "Courier",
|
||||
"serif": "Times",
|
||||
"sansSerif": "Helvetica",
|
||||
"cursive": "Apple Chancery",
|
||||
"fantasy": "Papyrus"
|
||||
},
|
||||
"forScripts": [
|
||||
{
|
||||
"script": "jpan",
|
||||
"fontFamilies": {
|
||||
"standard": "Hiragino Kaku Gothic ProN",
|
||||
"fixed": "Osaka-Mono",
|
||||
"serif": "Hiragino Mincho ProN",
|
||||
"sansSerif": "Hiragino Kaku Gothic ProN"
|
||||
}
|
||||
},
|
||||
{
|
||||
"script": "hang",
|
||||
"fontFamilies": {
|
||||
"standard": "Apple SD Gothic Neo",
|
||||
"serif": "AppleMyungjo",
|
||||
"sansSerif": "Apple SD Gothic Neo"
|
||||
}
|
||||
},
|
||||
{
|
||||
"script": "hans",
|
||||
"fontFamilies": {
|
||||
"standard": ",PingFang SC,STHeiti",
|
||||
"serif": "Songti SC",
|
||||
"sansSerif": ",PingFang SC,STHeiti",
|
||||
"cursive": "Kaiti SC"
|
||||
}
|
||||
},
|
||||
{
|
||||
"script": "hant",
|
||||
"fontFamilies": {
|
||||
"standard": ",PingFang TC,Heiti TC",
|
||||
"serif": "Songti TC",
|
||||
"sansSerif": ",PingFang TC,Heiti TC",
|
||||
"cursive": "Kaiti TC"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"win": {
|
||||
"fontFamilies": {
|
||||
"standard": "Times New Roman",
|
||||
"fixed": "Consolas",
|
||||
"serif": "Times New Roman",
|
||||
"sansSerif": "Arial",
|
||||
"cursive": "Comic Sans MS",
|
||||
"fantasy": "Impact"
|
||||
},
|
||||
"forScripts": [
|
||||
{
|
||||
"script": "cyrl",
|
||||
"fontFamilies": {
|
||||
"standard": "Times New Roman",
|
||||
"fixed": "Courier New",
|
||||
"serif": "Times New Roman",
|
||||
"sansSerif": "Arial"
|
||||
}
|
||||
},
|
||||
{
|
||||
"script": "arab",
|
||||
"fontFamilies": {
|
||||
"fixed": "Courier New",
|
||||
"sansSerif": "Segoe UI"
|
||||
}
|
||||
},
|
||||
{
|
||||
"script": "grek",
|
||||
"fontFamilies": {
|
||||
"standard": "Times New Roman",
|
||||
"fixed": "Courier New",
|
||||
"serif": "Times New Roman",
|
||||
"sansSerif": "Arial"
|
||||
}
|
||||
},
|
||||
{
|
||||
"script": "jpan",
|
||||
"fontFamilies": {
|
||||
"standard": ",Meiryo,Yu Gothic",
|
||||
"fixed": "MS Gothic",
|
||||
"serif": ",Yu Mincho,MS PMincho",
|
||||
"sansSerif": ",Meiryo,Yu Gothic"
|
||||
}
|
||||
},
|
||||
{
|
||||
"script": "hang",
|
||||
"fontFamilies": {
|
||||
"standard": "Malgun Gothic",
|
||||
"fixed": "Gulimche",
|
||||
"serif": "Batang",
|
||||
"sansSerif": "Malgun Gothic",
|
||||
"cursive": "Gungsuh"
|
||||
}
|
||||
},
|
||||
{
|
||||
"script": "hans",
|
||||
"fontFamilies": {
|
||||
"standard": "Microsoft YaHei",
|
||||
"fixed": "NSimsun",
|
||||
"serif": "Simsun",
|
||||
"sansSerif": "Microsoft YaHei",
|
||||
"cursive": "KaiTi"
|
||||
}
|
||||
},
|
||||
{
|
||||
"script": "hant",
|
||||
"fontFamilies": {
|
||||
"standard": "Microsoft JhengHei",
|
||||
"fixed": "MingLiU",
|
||||
"serif": "PMingLiU",
|
||||
"sansSerif": "Microsoft JhengHei",
|
||||
"cursive": "DFKai-SB"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
platformToFontFamilies
|
||||
});
|
16
node_modules/playwright-core/lib/server/chromium/protocol.d.js
generated
vendored
Normal file
16
node_modules/playwright-core/lib/server/chromium/protocol.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 protocol_d_exports = {};
|
||||
module.exports = __toCommonJS(protocol_d_exports);
|
113
node_modules/playwright-core/lib/server/chromium/videoRecorder.js
generated
vendored
Normal file
113
node_modules/playwright-core/lib/server/chromium/videoRecorder.js
generated
vendored
Normal file
@@ -0,0 +1,113 @@
|
||||
"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 videoRecorder_exports = {};
|
||||
__export(videoRecorder_exports, {
|
||||
VideoRecorder: () => VideoRecorder
|
||||
});
|
||||
module.exports = __toCommonJS(videoRecorder_exports);
|
||||
var import_utils = require("../../utils");
|
||||
var import_page = require("../page");
|
||||
var import_processLauncher = require("../utils/processLauncher");
|
||||
const fps = 25;
|
||||
class VideoRecorder {
|
||||
constructor(page, ffmpegPath) {
|
||||
this._process = null;
|
||||
this._gracefullyClose = null;
|
||||
this._lastWritePromise = Promise.resolve();
|
||||
this._lastFrameTimestamp = 0;
|
||||
this._lastFrameBuffer = null;
|
||||
this._lastWriteTimestamp = 0;
|
||||
this._frameQueue = [];
|
||||
this._isStopped = false;
|
||||
this._ffmpegPath = ffmpegPath;
|
||||
page.on(import_page.Page.Events.ScreencastFrame, (frame) => this.writeFrame(frame.buffer, frame.frameSwapWallTime / 1e3));
|
||||
}
|
||||
static async launch(page, ffmpegPath, options) {
|
||||
if (!options.outputFile.endsWith(".webm"))
|
||||
throw new Error("File must have .webm extension");
|
||||
const recorder = new VideoRecorder(page, ffmpegPath);
|
||||
await recorder._launch(options);
|
||||
return recorder;
|
||||
}
|
||||
async _launch(options) {
|
||||
const w = options.width;
|
||||
const h = options.height;
|
||||
const args = `-loglevel error -f image2pipe -avioflags direct -fpsprobesize 0 -probesize 32 -analyzeduration 0 -c:v mjpeg -i pipe:0 -y -an -r ${fps} -c:v vp8 -qmin 0 -qmax 50 -crf 8 -deadline realtime -speed 8 -b:v 1M -threads 1 -vf pad=${w}:${h}:0:0:gray,crop=${w}:${h}:0:0`.split(" ");
|
||||
args.push(options.outputFile);
|
||||
const { launchedProcess, gracefullyClose } = await (0, import_processLauncher.launchProcess)({
|
||||
command: this._ffmpegPath,
|
||||
args,
|
||||
stdio: "stdin",
|
||||
log: (message) => import_utils.debugLogger.log("browser", message),
|
||||
tempDirectories: [],
|
||||
attemptToGracefullyClose: async () => {
|
||||
import_utils.debugLogger.log("browser", "Closing stdin...");
|
||||
launchedProcess.stdin.end();
|
||||
},
|
||||
onExit: (exitCode, signal) => {
|
||||
import_utils.debugLogger.log("browser", `ffmpeg onkill exitCode=${exitCode} signal=${signal}`);
|
||||
}
|
||||
});
|
||||
launchedProcess.stdin.on("finish", () => {
|
||||
import_utils.debugLogger.log("browser", "ffmpeg finished input.");
|
||||
});
|
||||
launchedProcess.stdin.on("error", () => {
|
||||
import_utils.debugLogger.log("browser", "ffmpeg error.");
|
||||
});
|
||||
this._process = launchedProcess;
|
||||
this._gracefullyClose = gracefullyClose;
|
||||
}
|
||||
writeFrame(frame, timestamp) {
|
||||
(0, import_utils.assert)(this._process);
|
||||
if (this._isStopped)
|
||||
return;
|
||||
if (this._lastFrameBuffer) {
|
||||
const durationSec = timestamp - this._lastFrameTimestamp;
|
||||
const repeatCount = Math.max(1, Math.round(fps * durationSec));
|
||||
for (let i = 0; i < repeatCount; ++i)
|
||||
this._frameQueue.push(this._lastFrameBuffer);
|
||||
this._lastWritePromise = this._lastWritePromise.then(() => this._sendFrames());
|
||||
}
|
||||
this._lastFrameBuffer = frame;
|
||||
this._lastFrameTimestamp = timestamp;
|
||||
this._lastWriteTimestamp = (0, import_utils.monotonicTime)();
|
||||
}
|
||||
async _sendFrames() {
|
||||
while (this._frameQueue.length)
|
||||
await this._sendFrame(this._frameQueue.shift());
|
||||
}
|
||||
async _sendFrame(frame) {
|
||||
return new Promise((f) => this._process.stdin.write(frame, f)).then((error) => {
|
||||
if (error)
|
||||
import_utils.debugLogger.log("browser", `ffmpeg failed to write: ${String(error)}`);
|
||||
});
|
||||
}
|
||||
async stop() {
|
||||
if (this._isStopped)
|
||||
return;
|
||||
this.writeFrame(Buffer.from([]), this._lastFrameTimestamp + ((0, import_utils.monotonicTime)() - this._lastWriteTimestamp) / 1e3);
|
||||
this._isStopped = true;
|
||||
await this._lastWritePromise;
|
||||
await this._gracefullyClose();
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
VideoRecorder
|
||||
});
|
Reference in New Issue
Block a user