First Commit

This commit is contained in:
2025-08-28 19:35:28 -07:00
commit 264e65006a
488 changed files with 155661 additions and 0 deletions

View 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);

View File

@@ -0,0 +1,103 @@
"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 webkit_exports = {};
__export(webkit_exports, {
WebKit: () => WebKit
});
module.exports = __toCommonJS(webkit_exports);
var import_path = __toESM(require("path"));
var import_wkConnection = require("./wkConnection");
var import_ascii = require("../utils/ascii");
var import_browserType = require("../browserType");
var import_wkBrowser = require("../webkit/wkBrowser");
class WebKit extends import_browserType.BrowserType {
constructor(parent) {
super(parent, "webkit");
}
connectToTransport(transport, options) {
return import_wkBrowser.WKBrowser.connect(this.attribution.playwright, transport, options);
}
amendEnvironment(env, userDataDir, isPersistent) {
return {
...env,
CURL_COOKIE_JAR_PATH: process.platform === "win32" && isPersistent ? import_path.default.join(userDataDir, "cookiejar.db") : void 0
};
}
doRewriteStartupLog(error) {
if (!error.logs)
return error;
if (error.logs.includes("Failed to open display") || error.logs.includes("cannot open display"))
error.logs = "\n" + (0, import_ascii.wrapInASCIIBox)(import_browserType.kNoXServerRunningError, 1);
return error;
}
attemptToGracefullyCloseBrowser(transport) {
transport.send({ method: "Playwright.close", params: {}, id: import_wkConnection.kBrowserCloseMessageId });
}
defaultArgs(options, isPersistent, userDataDir) {
const { args = [], headless } = 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("-")))
throw new Error("Arguments can not specify page to be opened");
const webkitArguments = ["--inspector-pipe"];
if (process.platform === "win32")
webkitArguments.push("--disable-accelerated-compositing");
if (headless)
webkitArguments.push("--headless");
if (isPersistent)
webkitArguments.push(`--user-data-dir=${userDataDir}`);
else
webkitArguments.push(`--no-startup-window`);
const proxy = options.proxyOverride || options.proxy;
if (proxy) {
if (process.platform === "darwin") {
webkitArguments.push(`--proxy=${proxy.server}`);
if (proxy.bypass)
webkitArguments.push(`--proxy-bypass-list=${proxy.bypass}`);
} else if (process.platform === "linux") {
webkitArguments.push(`--proxy=${proxy.server}`);
if (proxy.bypass)
webkitArguments.push(...proxy.bypass.split(",").map((t) => `--ignore-host=${t}`));
} else if (process.platform === "win32") {
webkitArguments.push(`--curl-proxy=${proxy.server.replace(/^socks5:\/\//, "socks5h://")}`);
if (proxy.bypass)
webkitArguments.push(`--curl-noproxy=${proxy.bypass}`);
}
}
webkitArguments.push(...args);
if (isPersistent)
webkitArguments.push("about:blank");
return webkitArguments;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WebKit
});

View File

@@ -0,0 +1,237 @@
"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 wkAccessibility_exports = {};
__export(wkAccessibility_exports, {
getAccessibilityTree: () => getAccessibilityTree
});
module.exports = __toCommonJS(wkAccessibility_exports);
async function getAccessibilityTree(session, needle) {
const objectId = needle ? needle._objectId : void 0;
const { axNode } = await session.send("Page.accessibilitySnapshot", { objectId });
const tree = new WKAXNode(axNode);
return {
tree,
needle: needle ? tree._findNeedle() : null
};
}
const WKRoleToARIARole = new Map(Object.entries({
"TextField": "textbox"
}));
const WKUnhelpfulRoleDescriptions = new Map(Object.entries({
"WebArea": "HTML content",
"Summary": "summary",
"DescriptionList": "description list",
"ImageMap": "image map",
"ListMarker": "list marker",
"Video": "video playback",
"Mark": "highlighted",
"contentinfo": "content information",
"Details": "details",
"DescriptionListDetail": "description",
"DescriptionListTerm": "term",
"alertdialog": "web alert dialog",
"dialog": "web dialog",
"status": "application status",
"tabpanel": "tab panel",
"application": "web application"
}));
class WKAXNode {
constructor(payload) {
this._payload = payload;
this._children = [];
for (const payload2 of this._payload.children || [])
this._children.push(new WKAXNode(payload2));
}
children() {
return this._children;
}
_findNeedle() {
if (this._payload.found)
return this;
for (const child of this._children) {
const found = child._findNeedle();
if (found)
return found;
}
return null;
}
isControl() {
switch (this._payload.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 "TextField":
case "tree":
return true;
default:
return false;
}
}
_isTextControl() {
switch (this._payload.role) {
case "combobox":
case "searchfield":
case "textbox":
case "TextField":
return true;
}
return false;
}
_name() {
if (this._payload.role === "text")
return this._payload.value || "";
return this._payload.name || "";
}
isInteresting(insideControl) {
const { role, focusable } = this._payload;
const name = this._name();
if (role === "ScrollArea")
return false;
if (role === "WebArea")
return true;
if (focusable || role === "MenuListOption")
return true;
if (this.isControl())
return true;
if (insideControl)
return false;
return this.isLeafNode() && !!name;
}
_hasRedundantTextChild() {
if (this._children.length !== 1)
return false;
const child = this._children[0];
return child._payload.role === "text" && this._payload.name === child._payload.value;
}
isLeafNode() {
if (!this._children.length)
return true;
if (this._isTextControl())
return true;
if (this._hasRedundantTextChild())
return true;
return false;
}
serialize() {
const node = {
role: WKRoleToARIARole.get(this._payload.role) || this._payload.role,
name: this._name()
};
if ("description" in this._payload && this._payload.description !== node.name)
node.description = this._payload.description;
if ("roledescription" in this._payload) {
const roledescription = this._payload.roledescription;
if (roledescription !== this._payload.role && WKUnhelpfulRoleDescriptions.get(this._payload.role) !== roledescription)
node.roledescription = roledescription;
}
if ("value" in this._payload && this._payload.role !== "text") {
if (typeof this._payload.value === "string")
node.valueString = this._payload.value;
else if (typeof this._payload.value === "number")
node.valueNumber = this._payload.value;
}
if ("checked" in this._payload)
node.checked = this._payload.checked === "true" ? "checked" : this._payload.checked === "false" ? "unchecked" : "mixed";
if ("pressed" in this._payload)
node.pressed = this._payload.pressed === "true" ? "pressed" : this._payload.pressed === "false" ? "released" : "mixed";
const userStringProperties = [
"keyshortcuts",
"valuetext"
];
for (const userStringProperty of userStringProperties) {
if (!(userStringProperty in this._payload))
continue;
node[userStringProperty] = this._payload[userStringProperty];
}
const booleanProperties = [
"disabled",
"expanded",
"focused",
"modal",
"multiselectable",
"readonly",
"required",
"selected"
];
for (const booleanProperty of booleanProperties) {
if (booleanProperty === "focused" && (this._payload.role === "WebArea" || this._payload.role === "ScrollArea"))
continue;
const value = this._payload[booleanProperty];
if (!value)
continue;
node[booleanProperty] = value;
}
const numericalProperties = [
"level",
"valuemax",
"valuemin"
];
for (const numericalProperty of numericalProperties) {
if (!(numericalProperty in this._payload))
continue;
node[numericalProperty] = this._payload[numericalProperty];
}
const tokenProperties = [
"autocomplete",
"haspopup",
"invalid"
];
for (const tokenProperty of tokenProperties) {
const value = this._payload[tokenProperty];
if (!value || value === "false")
continue;
node[tokenProperty] = value;
}
const orientationIsApplicable = /* @__PURE__ */ new Set([
"ScrollArea",
"scrollbar",
"listbox",
"combobox",
"menu",
"tree",
"separator",
"slider",
"tablist",
"toolbar"
]);
if (this._payload.orientation && orientationIsApplicable.has(this._payload.role))
node.orientation = this._payload.orientation;
return node;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getAccessibilityTree
});

View File

@@ -0,0 +1,335 @@
"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 wkBrowser_exports = {};
__export(wkBrowser_exports, {
WKBrowser: () => WKBrowser,
WKBrowserContext: () => WKBrowserContext
});
module.exports = __toCommonJS(wkBrowser_exports);
var import_utils = require("../../utils");
var import_browser = require("../browser");
var import_browserContext = require("../browserContext");
var network = __toESM(require("../network"));
var import_wkConnection = require("./wkConnection");
var import_wkPage = require("./wkPage");
var import_errors = require("../errors");
const BROWSER_VERSION = "26.0";
const DEFAULT_USER_AGENT = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/${BROWSER_VERSION} Safari/605.1.15`;
class WKBrowser extends import_browser.Browser {
constructor(parent, transport, options) {
super(parent, options);
this._contexts = /* @__PURE__ */ new Map();
this._wkPages = /* @__PURE__ */ new Map();
this._connection = new import_wkConnection.WKConnection(transport, this._onDisconnect.bind(this), options.protocolLogger, options.browserLogsCollector);
this._browserSession = this._connection.browserSession;
this._browserSession.on("Playwright.pageProxyCreated", this._onPageProxyCreated.bind(this));
this._browserSession.on("Playwright.pageProxyDestroyed", this._onPageProxyDestroyed.bind(this));
this._browserSession.on("Playwright.provisionalLoadFailed", (event) => this._onProvisionalLoadFailed(event));
this._browserSession.on("Playwright.windowOpen", (event) => this._onWindowOpen(event));
this._browserSession.on("Playwright.downloadCreated", this._onDownloadCreated.bind(this));
this._browserSession.on("Playwright.downloadFilenameSuggested", this._onDownloadFilenameSuggested.bind(this));
this._browserSession.on("Playwright.downloadFinished", this._onDownloadFinished.bind(this));
this._browserSession.on("Playwright.screencastFinished", this._onScreencastFinished.bind(this));
this._browserSession.on(import_wkConnection.kPageProxyMessageReceived, this._onPageProxyMessageReceived.bind(this));
}
static async connect(parent, transport, options) {
const browser = new WKBrowser(parent, transport, options);
if (options.__testHookOnConnectToBrowser)
await options.__testHookOnConnectToBrowser();
const promises = [
browser._browserSession.send("Playwright.enable")
];
if (options.persistent) {
options.persistent.userAgent ||= DEFAULT_USER_AGENT;
browser._defaultContext = new WKBrowserContext(browser, void 0, options.persistent);
promises.push(browser._defaultContext._initialize());
}
await Promise.all(promises);
return browser;
}
_onDisconnect() {
for (const wkPage of this._wkPages.values())
wkPage.didClose();
this._wkPages.clear();
for (const video of this._idToVideo.values())
video.artifact.reportFinished(new import_errors.TargetClosedError());
this._idToVideo.clear();
this._didClose();
}
async doCreateNewContext(options) {
const proxy = options.proxyOverride || options.proxy;
const createOptions = proxy ? {
// Enable socks5 hostname resolution on Windows.
// See https://github.com/microsoft/playwright/issues/20451
proxyServer: process.platform === "win32" ? proxy.server.replace(/^socks5:\/\//, "socks5h://") : proxy.server,
proxyBypassList: proxy.bypass
} : void 0;
const { browserContextId } = await this._browserSession.send("Playwright.createContext", createOptions);
options.userAgent = options.userAgent || DEFAULT_USER_AGENT;
const context = new WKBrowserContext(this, browserContextId, options);
await context._initialize();
this._contexts.set(browserContextId, context);
return context;
}
contexts() {
return Array.from(this._contexts.values());
}
version() {
return BROWSER_VERSION;
}
userAgent() {
return DEFAULT_USER_AGENT;
}
_onDownloadCreated(payload) {
const page = this._wkPages.get(payload.pageProxyId);
if (!page)
return;
page._page.frameManager.frameAbortedNavigation(payload.frameId, "Download is starting");
let originPage = page._page.initializedOrUndefined();
if (!originPage) {
page._firstNonInitialNavigationCommittedReject(new Error("Starting new page download"));
if (page._opener)
originPage = page._opener._page.initializedOrUndefined();
}
if (!originPage)
return;
this._downloadCreated(originPage, payload.uuid, payload.url);
}
_onDownloadFilenameSuggested(payload) {
this._downloadFilenameSuggested(payload.uuid, payload.suggestedFilename);
}
_onDownloadFinished(payload) {
this._downloadFinished(payload.uuid, payload.error);
}
_onScreencastFinished(payload) {
this._takeVideo(payload.screencastId)?.reportFinished();
}
_onPageProxyCreated(event) {
const pageProxyId = event.pageProxyId;
let context = null;
if (event.browserContextId) {
context = this._contexts.get(event.browserContextId) || null;
}
if (!context)
context = this._defaultContext;
if (!context)
return;
const pageProxySession = new import_wkConnection.WKSession(this._connection, pageProxyId, (message) => {
this._connection.rawSend({ ...message, pageProxyId });
});
const opener = event.openerId ? this._wkPages.get(event.openerId) : void 0;
const wkPage = new import_wkPage.WKPage(context, pageProxySession, opener || null);
this._wkPages.set(pageProxyId, wkPage);
}
_onPageProxyDestroyed(event) {
const pageProxyId = event.pageProxyId;
const wkPage = this._wkPages.get(pageProxyId);
if (!wkPage)
return;
this._wkPages.delete(pageProxyId);
wkPage.didClose();
}
_onPageProxyMessageReceived(event) {
const wkPage = this._wkPages.get(event.pageProxyId);
if (!wkPage)
return;
wkPage.dispatchMessageToSession(event.message);
}
_onProvisionalLoadFailed(event) {
const wkPage = this._wkPages.get(event.pageProxyId);
if (!wkPage)
return;
wkPage.handleProvisionalLoadFailed(event);
}
_onWindowOpen(event) {
const wkPage = this._wkPages.get(event.pageProxyId);
if (!wkPage)
return;
wkPage.handleWindowOpen(event);
}
isConnected() {
return !this._connection.isClosed();
}
}
class WKBrowserContext extends import_browserContext.BrowserContext {
constructor(browser, browserContextId, options) {
super(browser, options, browserContextId);
this._validateEmulatedViewport(options.viewport);
this._authenticateProxyViaHeader();
}
async _initialize() {
(0, import_utils.assert)(!this._wkPages().length);
const browserContextId = this._browserContextId;
const promises = [super._initialize()];
promises.push(this._browser._browserSession.send("Playwright.setDownloadBehavior", {
behavior: this._options.acceptDownloads === "accept" ? "allow" : "deny",
downloadPath: this._browser.options.downloadsPath,
browserContextId
}));
if (this._options.ignoreHTTPSErrors || this._options.internalIgnoreHTTPSErrors)
promises.push(this._browser._browserSession.send("Playwright.setIgnoreCertificateErrors", { browserContextId, ignore: true }));
if (this._options.locale)
promises.push(this._browser._browserSession.send("Playwright.setLanguages", { browserContextId, languages: [this._options.locale] }));
if (this._options.geolocation)
promises.push(this.setGeolocation(this._options.geolocation));
if (this._options.offline)
promises.push(this.doUpdateOffline());
if (this._options.httpCredentials)
promises.push(this.setHTTPCredentials(this._options.httpCredentials));
await Promise.all(promises);
}
_wkPages() {
return Array.from(this._browser._wkPages.values()).filter((wkPage) => wkPage._browserContext === this);
}
possiblyUninitializedPages() {
return this._wkPages().map((wkPage) => wkPage._page);
}
async doCreateNewPage() {
const { pageProxyId } = await this._browser._browserSession.send("Playwright.createPage", { browserContextId: this._browserContextId });
return this._browser._wkPages.get(pageProxyId)._page;
}
async doGetCookies(urls) {
const { cookies } = await this._browser._browserSession.send("Playwright.getAllCookies", { browserContextId: this._browserContextId });
return network.filterCookies(cookies.map((c) => {
const { name, value, domain, path, expires, httpOnly, secure, sameSite } = c;
const copy = {
name,
value,
domain,
path,
expires: expires === -1 ? -1 : expires / 1e3,
httpOnly,
secure,
sameSite
};
return copy;
}), urls);
}
async addCookies(cookies) {
const cc = network.rewriteCookies(cookies).map((c) => {
const { name, value, domain, path, expires, httpOnly, secure, sameSite } = c;
const copy = {
name,
value,
domain,
path,
expires: expires && expires !== -1 ? expires * 1e3 : expires,
httpOnly,
secure,
sameSite,
session: expires === -1 || expires === void 0
};
return copy;
});
await this._browser._browserSession.send("Playwright.setCookies", { cookies: cc, browserContextId: this._browserContextId });
}
async doClearCookies() {
await this._browser._browserSession.send("Playwright.deleteAllCookies", { browserContextId: this._browserContextId });
}
async doGrantPermissions(origin, permissions) {
await Promise.all(this.pages().map((page) => page.delegate._grantPermissions(origin, permissions)));
}
async doClearPermissions() {
await Promise.all(this.pages().map((page) => page.delegate._clearPermissions()));
}
async setGeolocation(geolocation) {
(0, import_browserContext.verifyGeolocation)(geolocation);
this._options.geolocation = geolocation;
const payload = geolocation ? { ...geolocation, timestamp: Date.now() } : void 0;
await this._browser._browserSession.send("Playwright.setGeolocationOverride", { browserContextId: this._browserContextId, geolocation: payload });
}
async doUpdateExtraHTTPHeaders() {
for (const page of this.pages())
await page.delegate.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();
}
async doSetHTTPCredentials(httpCredentials) {
this._options.httpCredentials = httpCredentials;
for (const page of this.pages())
await page.delegate.updateHttpCredentials();
}
async doAddInitScript(initScript) {
for (const page of this.pages())
await page.delegate._updateBootstrapScript();
}
async doRemoveInitScripts(initScripts) {
for (const page of this.pages())
await page.delegate._updateBootstrapScript();
}
async doUpdateRequestInterception() {
for (const page of this.pages())
await page.delegate.updateRequestInterception();
}
async doUpdateDefaultViewport() {
}
async doUpdateDefaultEmulatedMedia() {
}
async doExposePlaywrightBinding() {
for (const page of this.pages())
await page.delegate.exposePlaywrightBinding();
}
onClosePersistent() {
}
async clearCache() {
await this._browser._browserSession.send("Playwright.clearMemoryCache", {
browserContextId: this._browserContextId
});
}
async doClose(reason) {
if (!this._browserContextId) {
await Promise.all(this._wkPages().map((wkPage) => wkPage._stopVideo()));
await this._browser.close({ reason });
} else {
await this._browser._browserSession.send("Playwright.deleteContext", { browserContextId: this._browserContextId });
this._browser._contexts.delete(this._browserContextId);
}
}
async cancelDownload(uuid) {
await this._browser._browserSession.send("Playwright.cancelDownload", { uuid });
}
_validateEmulatedViewport(viewportSize) {
if (!viewportSize)
return;
if (process.platform === "win32" && this._browser.options.headful && (viewportSize.width < 250 || viewportSize.height < 240))
throw new Error(`WebKit on Windows has a minimal viewport of 250x240.`);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WKBrowser,
WKBrowserContext
});

View File

@@ -0,0 +1,149 @@
"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 wkConnection_exports = {};
__export(wkConnection_exports, {
WKConnection: () => WKConnection,
WKSession: () => WKSession,
kBrowserCloseMessageId: () => kBrowserCloseMessageId,
kPageProxyMessageReceived: () => kPageProxyMessageReceived
});
module.exports = __toCommonJS(wkConnection_exports);
var import_events = require("events");
var import_utils = require("../../utils");
var import_debugLogger = require("../utils/debugLogger");
var import_helper = require("../helper");
var import_protocolError = require("../protocolError");
const kBrowserCloseMessageId = -9999;
const kPageProxyMessageReceived = Symbol("kPageProxyMessageReceived");
class WKConnection {
constructor(transport, onDisconnect, protocolLogger, browserLogsCollector) {
this._lastId = 0;
this._closed = false;
this._transport = transport;
this._onDisconnect = onDisconnect;
this._protocolLogger = protocolLogger;
this._browserLogsCollector = browserLogsCollector;
this.browserSession = new WKSession(this, "", (message) => {
this.rawSend(message);
});
this._transport.onmessage = this._dispatchMessage.bind(this);
this._transport.onclose = this._onClose.bind(this);
}
nextMessageId() {
return ++this._lastId;
}
rawSend(message) {
this._protocolLogger("send", message);
this._transport.send(message);
}
_dispatchMessage(message) {
this._protocolLogger("receive", message);
if (message.id === kBrowserCloseMessageId)
return;
if (message.pageProxyId) {
const payload = { message, pageProxyId: message.pageProxyId };
this.browserSession.dispatchMessage({ method: kPageProxyMessageReceived, params: payload });
return;
}
this.browserSession.dispatchMessage(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.browserSession.dispose();
this._onDisconnect();
}
isClosed() {
return this._closed;
}
close() {
if (!this._closed)
this._transport.close();
}
}
class WKSession extends import_events.EventEmitter {
constructor(connection, sessionId, rawSend) {
super();
this._disposed = false;
this._callbacks = /* @__PURE__ */ new Map();
this._crashed = false;
this.setMaxListeners(0);
this.connection = connection;
this.sessionId = sessionId;
this._rawSend = rawSend;
this.on = super.on;
this.off = super.removeListener;
this.addListener = super.addListener;
this.removeListener = super.removeListener;
this.once = super.once;
}
async send(method, params) {
if (this._crashed || this._disposed || this.connection._browserDisconnectedLogs)
throw new import_protocolError.ProtocolError(this._crashed ? "crashed" : "closed", void 0, this.connection._browserDisconnectedLogs);
const id = this.connection.nextMessageId();
const messageObj = { id, method, params };
this._rawSend(messageObj);
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));
}
markAsCrashed() {
this._crashed = true;
}
isDisposed() {
return this._disposed;
}
dispose() {
for (const callback of this._callbacks.values()) {
callback.error.type = this._crashed ? "crashed" : "closed";
callback.error.logs = this.connection._browserDisconnectedLogs;
callback.reject(callback.error);
}
this._callbacks.clear();
this._disposed = true;
}
dispatchMessage(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) {
(0, import_utils.assert)(this.isDisposed());
} else {
Promise.resolve().then(() => this.emit(object.method, object.params));
}
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WKConnection,
WKSession,
kBrowserCloseMessageId,
kPageProxyMessageReceived
});

View File

@@ -0,0 +1,154 @@
"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 wkExecutionContext_exports = {};
__export(wkExecutionContext_exports, {
WKExecutionContext: () => WKExecutionContext,
createHandle: () => createHandle
});
module.exports = __toCommonJS(wkExecutionContext_exports);
var js = __toESM(require("../javascript"));
var dom = __toESM(require("../dom"));
var import_protocolError = require("../protocolError");
var import_assert = require("../../utils/isomorphic/assert");
var import_utilityScriptSerializers = require("../../utils/isomorphic/utilityScriptSerializers");
class WKExecutionContext {
constructor(session, contextId) {
this._session = session;
this._contextId = contextId;
}
async rawEvaluateJSON(expression) {
try {
const response = await this._session.send("Runtime.evaluate", {
expression,
contextId: this._contextId,
returnByValue: true
});
if (response.wasThrown)
throw new js.JavaScriptErrorInEvaluate(response.result.description);
return response.result.value;
} catch (error) {
throw rewriteError(error);
}
}
async rawEvaluateHandle(context, expression) {
try {
const response = await this._session.send("Runtime.evaluate", {
expression,
contextId: this._contextId,
returnByValue: false
});
if (response.wasThrown)
throw new js.JavaScriptErrorInEvaluate(response.result.description);
return createHandle(context, response.result);
} catch (error) {
throw rewriteError(error);
}
}
async evaluateWithArguments(expression, returnByValue, utilityScript, values, handles) {
try {
const response = await this._session.send("Runtime.callFunctionOn", {
functionDeclaration: expression,
objectId: utilityScript._objectId,
arguments: [
{ objectId: utilityScript._objectId },
...values.map((value) => ({ value })),
...handles.map((handle) => ({ objectId: handle._objectId }))
],
returnByValue,
emulateUserGesture: true,
awaitPromise: true
});
if (response.wasThrown)
throw new js.JavaScriptErrorInEvaluate(response.result.description);
if (returnByValue)
return (0, import_utilityScriptSerializers.parseEvaluationResultValue)(response.result.value);
return createHandle(utilityScript._context, response.result);
} catch (error) {
throw rewriteError(error);
}
}
async getProperties(object) {
const response = await this._session.send("Runtime.getProperties", {
objectId: object._objectId,
ownProperties: true
});
const result = /* @__PURE__ */ new Map();
for (const property of response.properties) {
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 this._session.send("Runtime.releaseObject", { objectId: handle._objectId });
}
}
function potentiallyUnserializableValue(remoteObject) {
const value = remoteObject.value;
const isUnserializable = remoteObject.type === "number" && ["NaN", "-Infinity", "Infinity", "-0"].includes(remoteObject.description);
return isUnserializable ? js.parseUnserializableValue(remoteObject.description) : value;
}
function rewriteError(error) {
if (error.message.includes("Object has too long reference chain"))
throw new Error("Cannot serialize result: object reference chain is too long.");
if (!js.isJavaScriptErrorInEvaluate(error) && !(0, import_protocolError.isSessionClosedError)(error))
return new Error("Execution context was destroyed, most likely because of a navigation.");
return error;
}
function renderPreview(object) {
if (object.type === "undefined")
return "undefined";
if ("value" in object)
return String(object.value);
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);
}
const isPromise = remoteObject.className === "Promise";
return new js.JSHandle(context, isPromise ? "promise" : remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WKExecutionContext,
createHandle
});

View File

@@ -0,0 +1,181 @@
"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 wkInput_exports = {};
__export(wkInput_exports, {
RawKeyboardImpl: () => RawKeyboardImpl,
RawMouseImpl: () => RawMouseImpl,
RawTouchscreenImpl: () => RawTouchscreenImpl
});
module.exports = __toCommonJS(wkInput_exports);
var import_utils = require("../../utils");
var input = __toESM(require("../input"));
var import_macEditingCommands = require("../macEditingCommands");
function toModifiersMask(modifiers) {
let mask = 0;
if (modifiers.has("Shift"))
mask |= 1;
if (modifiers.has("Control"))
mask |= 2;
if (modifiers.has("Alt"))
mask |= 4;
if (modifiers.has("Meta"))
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;
}
class RawKeyboardImpl {
constructor(session) {
this._pageProxySession = session;
}
setSession(session) {
this._session = session;
}
async keydown(progress, modifiers, keyName, description, autoRepeat) {
const parts = [];
for (const modifier of ["Shift", "Control", "Alt", "Meta"]) {
if (modifiers.has(modifier))
parts.push(modifier);
}
const { code, keyCode, key, text } = description;
parts.push(code);
const shortcut = parts.join("+");
let commands = import_macEditingCommands.macEditingCommands[shortcut];
if ((0, import_utils.isString)(commands))
commands = [commands];
await progress.race(this._pageProxySession.send("Input.dispatchKeyEvent", {
type: "keyDown",
modifiers: toModifiersMask(modifiers),
windowsVirtualKeyCode: keyCode,
code,
key,
text,
unmodifiedText: text,
autoRepeat,
macCommands: commands,
isKeypad: description.location === input.keypadLocation
}));
}
async keyup(progress, modifiers, keyName, description) {
const { code, key } = description;
await progress.race(this._pageProxySession.send("Input.dispatchKeyEvent", {
type: "keyUp",
modifiers: toModifiersMask(modifiers),
key,
windowsVirtualKeyCode: description.keyCode,
code,
isKeypad: description.location === input.keypadLocation
}));
}
async sendText(progress, text) {
await progress.race(this._session.send("Page.insertText", { text }));
}
}
class RawMouseImpl {
constructor(session) {
this._pageProxySession = session;
}
setSession(session) {
this._session = session;
}
async move(progress, x, y, button, buttons, modifiers, forClick) {
await progress.race(this._pageProxySession.send("Input.dispatchMouseEvent", {
type: "move",
button,
buttons: toButtonsMask(buttons),
x,
y,
modifiers: toModifiersMask(modifiers)
}));
}
async down(progress, x, y, button, buttons, modifiers, clickCount) {
await progress.race(this._pageProxySession.send("Input.dispatchMouseEvent", {
type: "down",
button,
buttons: toButtonsMask(buttons),
x,
y,
modifiers: toModifiersMask(modifiers),
clickCount
}));
}
async up(progress, x, y, button, buttons, modifiers, clickCount) {
await progress.race(this._pageProxySession.send("Input.dispatchMouseEvent", {
type: "up",
button,
buttons: toButtonsMask(buttons),
x,
y,
modifiers: toModifiersMask(modifiers),
clickCount
}));
}
async wheel(progress, x, y, buttons, modifiers, deltaX, deltaY) {
if (this._page?.browserContext._options.isMobile)
throw new Error("Mouse wheel is not supported in mobile WebKit");
await this._session.send("Page.updateScrollingState");
await progress.race(this._page.mainFrame().evaluateExpression(`new Promise(requestAnimationFrame)`, { world: "utility" }));
await progress.race(this._pageProxySession.send("Input.dispatchWheelEvent", {
x,
y,
deltaX,
deltaY,
modifiers: toModifiersMask(modifiers)
}));
}
setPage(page) {
this._page = page;
}
}
class RawTouchscreenImpl {
constructor(session) {
this._pageProxySession = session;
}
async tap(progress, x, y, modifiers) {
await progress.race(this._pageProxySession.send("Input.dispatchTapEvent", {
x,
y,
modifiers: toModifiersMask(modifiers)
}));
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
RawKeyboardImpl,
RawMouseImpl,
RawTouchscreenImpl
});

View File

@@ -0,0 +1,169 @@
"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 wkInterceptableRequest_exports = {};
__export(wkInterceptableRequest_exports, {
WKInterceptableRequest: () => WKInterceptableRequest,
WKRouteImpl: () => WKRouteImpl
});
module.exports = __toCommonJS(wkInterceptableRequest_exports);
var import_utils = require("../../utils");
var network = __toESM(require("../network"));
const errorReasons = {
"aborted": "Cancellation",
"accessdenied": "AccessControl",
"addressunreachable": "General",
"blockedbyclient": "Cancellation",
"blockedbyresponse": "General",
"connectionaborted": "General",
"connectionclosed": "General",
"connectionfailed": "General",
"connectionrefused": "General",
"connectionreset": "General",
"internetdisconnected": "General",
"namenotresolved": "General",
"timedout": "Timeout",
"failed": "General"
};
class WKInterceptableRequest {
constructor(session, frame, event, redirectedFrom, documentId) {
this._session = session;
this._requestId = event.requestId;
const resourceType = event.type ? event.type.toLowerCase() : redirectedFrom ? redirectedFrom.request.resourceType() : "other";
let postDataBuffer = null;
this._timestamp = event.timestamp;
this._wallTime = event.walltime * 1e3;
if (event.request.postData)
postDataBuffer = Buffer.from(event.request.postData, "base64");
this.request = new network.Request(
frame._page.browserContext,
frame,
null,
redirectedFrom?.request || null,
documentId,
event.request.url,
resourceType,
event.request.method,
postDataBuffer,
(0, import_utils.headersObjectToArray)(event.request.headers)
);
}
adoptRequestFromNewProcess(newSession, requestId) {
this._session = newSession;
this._requestId = requestId;
}
createResponse(responsePayload) {
const getResponseBody = async () => {
const response2 = await this._session.send("Network.getResponseBody", { requestId: this._requestId });
return Buffer.from(response2.body, response2.base64Encoded ? "base64" : "utf8");
};
const timingPayload = responsePayload.timing;
const timing = {
startTime: this._wallTime,
domainLookupStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.domainLookupStart) : -1,
domainLookupEnd: timingPayload ? wkMillisToRoundishMillis(timingPayload.domainLookupEnd) : -1,
connectStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.connectStart) : -1,
secureConnectionStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.secureConnectionStart) : -1,
connectEnd: timingPayload ? wkMillisToRoundishMillis(timingPayload.connectEnd) : -1,
requestStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.requestStart) : -1,
responseStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.responseStart) : -1
};
const setCookieSeparator = process.platform === "darwin" ? "," : "playwright-set-cookie-separator";
const response = new network.Response(this.request, responsePayload.status, responsePayload.statusText, (0, import_utils.headersObjectToArray)(responsePayload.headers, ",", setCookieSeparator), timing, getResponseBody, responsePayload.source === "service-worker");
response.setRawResponseHeaders(null);
response.setTransferSize(null);
if (responsePayload.requestHeaders && Object.keys(responsePayload.requestHeaders).length) {
const headers = { ...responsePayload.requestHeaders };
if (!headers["host"])
headers["Host"] = new URL(this.request.url()).host;
this.request.setRawRequestHeaders((0, import_utils.headersObjectToArray)(headers));
} else {
this.request.setRawRequestHeaders(null);
}
return response;
}
}
class WKRouteImpl {
constructor(session, requestId) {
this._session = session;
this._requestId = requestId;
}
async abort(errorCode) {
const errorType = errorReasons[errorCode];
(0, import_utils.assert)(errorType, "Unknown error code: " + errorCode);
await this._session.sendMayFail("Network.interceptRequestWithError", { requestId: this._requestId, errorType });
}
async fulfill(response) {
if (300 <= response.status && response.status < 400)
throw new Error("Cannot fulfill with redirect status: " + response.status);
let mimeType = response.isBase64 ? "application/octet-stream" : "text/plain";
const headers = (0, import_utils.headersArrayToObject)(
response.headers,
true
/* lowerCase */
);
const contentType = headers["content-type"];
if (contentType)
mimeType = contentType.split(";")[0].trim();
await this._session.sendMayFail("Network.interceptRequestWithResponse", {
requestId: this._requestId,
status: response.status,
statusText: network.statusText(response.status),
mimeType,
headers,
base64Encoded: response.isBase64,
content: response.body
});
}
async continue(overrides) {
await this._session.sendMayFail("Network.interceptWithRequest", {
requestId: this._requestId,
url: overrides.url,
method: overrides.method,
headers: overrides.headers ? (0, import_utils.headersArrayToObject)(
overrides.headers,
false
/* lowerCase */
) : void 0,
postData: overrides.postData ? Buffer.from(overrides.postData).toString("base64") : void 0
});
}
}
function wkMillisToRoundishMillis(value) {
if (value === -1e3)
return -1;
if (value <= 0) {
return -1;
}
return (value * 1e3 | 0) / 1e3;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WKInterceptableRequest,
WKRouteImpl
});

1135
node_modules/playwright-core/lib/server/webkit/wkPage.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
"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 wkProvisionalPage_exports = {};
__export(wkProvisionalPage_exports, {
WKProvisionalPage: () => WKProvisionalPage
});
module.exports = __toCommonJS(wkProvisionalPage_exports);
var import_utils = require("../../utils");
var import_eventsHelper = require("../utils/eventsHelper");
class WKProvisionalPage {
constructor(session, page) {
this._sessionListeners = [];
this._mainFrameId = null;
this._session = session;
this._wkPage = page;
this._coopNavigationRequest = page._page.mainFrame().pendingDocument()?.request;
const overrideFrameId = (handler) => {
return (payload) => {
if (payload.frameId)
payload.frameId = this._wkPage._page.frameManager.mainFrame()._id;
handler(payload);
};
};
const wkPage = this._wkPage;
this._sessionListeners = [
import_eventsHelper.eventsHelper.addEventListener(session, "Network.requestWillBeSent", overrideFrameId((e) => this._onRequestWillBeSent(e))),
import_eventsHelper.eventsHelper.addEventListener(session, "Network.requestIntercepted", overrideFrameId((e) => wkPage._onRequestIntercepted(session, e))),
import_eventsHelper.eventsHelper.addEventListener(session, "Network.responseReceived", overrideFrameId((e) => wkPage._onResponseReceived(session, e))),
import_eventsHelper.eventsHelper.addEventListener(session, "Network.loadingFinished", overrideFrameId((e) => this._onLoadingFinished(e))),
import_eventsHelper.eventsHelper.addEventListener(session, "Network.loadingFailed", overrideFrameId((e) => this._onLoadingFailed(e)))
];
this.initializationPromise = this._wkPage._initializeSession(session, true, ({ frameTree }) => this._handleFrameTree(frameTree));
}
coopNavigationRequest() {
return this._coopNavigationRequest;
}
dispose() {
import_eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);
}
commit() {
(0, import_utils.assert)(this._mainFrameId);
this._wkPage._onFrameAttached(this._mainFrameId, null);
}
_onRequestWillBeSent(event) {
if (this._coopNavigationRequest && this._coopNavigationRequest.url() === event.request.url) {
this._wkPage._adoptRequestFromNewProcess(this._coopNavigationRequest, this._session, event.requestId);
return;
}
this._wkPage._onRequestWillBeSent(this._session, event);
}
_onLoadingFinished(event) {
this._coopNavigationRequest = void 0;
this._wkPage._onLoadingFinished(event);
}
_onLoadingFailed(event) {
this._coopNavigationRequest = void 0;
this._wkPage._onLoadingFailed(this._session, event);
}
_handleFrameTree(frameTree) {
(0, import_utils.assert)(!frameTree.frame.parentId);
this._mainFrameId = frameTree.frame.id;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WKProvisionalPage
});

View File

@@ -0,0 +1,104 @@
"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 wkWorkers_exports = {};
__export(wkWorkers_exports, {
WKWorkers: () => WKWorkers
});
module.exports = __toCommonJS(wkWorkers_exports);
var import_eventsHelper = require("../utils/eventsHelper");
var import_page = require("../page");
var import_wkConnection = require("./wkConnection");
var import_wkExecutionContext = require("./wkExecutionContext");
class WKWorkers {
constructor(page) {
this._sessionListeners = [];
this._workerSessions = /* @__PURE__ */ new Map();
this._page = page;
}
setSession(session) {
import_eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);
this.clear();
this._sessionListeners = [
import_eventsHelper.eventsHelper.addEventListener(session, "Worker.workerCreated", (event) => {
const worker = new import_page.Worker(this._page, event.url);
const workerSession = new import_wkConnection.WKSession(session.connection, event.workerId, (message) => {
session.send("Worker.sendMessageToWorker", {
workerId: event.workerId,
message: JSON.stringify(message)
}).catch((e) => {
workerSession.dispatchMessage({ id: message.id, error: { message: e.message } });
});
});
this._workerSessions.set(event.workerId, workerSession);
worker.createExecutionContext(new import_wkExecutionContext.WKExecutionContext(workerSession, void 0));
this._page.addWorker(event.workerId, worker);
workerSession.on("Console.messageAdded", (event2) => this._onConsoleMessage(worker, event2));
Promise.all([
workerSession.send("Runtime.enable"),
workerSession.send("Console.enable"),
session.send("Worker.initialized", { workerId: event.workerId })
]).catch((e) => {
this._page.removeWorker(event.workerId);
});
}),
import_eventsHelper.eventsHelper.addEventListener(session, "Worker.dispatchMessageFromWorker", (event) => {
const workerSession = this._workerSessions.get(event.workerId);
if (!workerSession)
return;
workerSession.dispatchMessage(JSON.parse(event.message));
}),
import_eventsHelper.eventsHelper.addEventListener(session, "Worker.workerTerminated", (event) => {
const workerSession = this._workerSessions.get(event.workerId);
if (!workerSession)
return;
workerSession.dispose();
this._workerSessions.delete(event.workerId);
this._page.removeWorker(event.workerId);
})
];
}
clear() {
this._page.clearWorkers();
this._workerSessions.clear();
}
async initializeSession(session) {
await session.send("Worker.enable");
}
async _onConsoleMessage(worker, event) {
const { type, level, text, parameters, url, line: lineNumber, column: columnNumber } = event.message;
let derivedType = type || "";
if (type === "log")
derivedType = level;
else if (type === "timing")
derivedType = "timeEnd";
const handles = (parameters || []).map((p) => {
return (0, import_wkExecutionContext.createHandle)(worker.existingExecutionContext, p);
});
const location = {
url: url || "",
lineNumber: (lineNumber || 1) - 1,
columnNumber: (columnNumber || 1) - 1
};
this._page.addConsoleMessage(derivedType, handles, location, handles.length ? void 0 : text);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WKWorkers
});