UNPKG

@iqx-limited/quick-pdf

Version:

Converting PDFs to images (📃 to 📸)

1,261 lines (1,200 loc) • 781 kB
import { g as getAugmentedNamespace, C as CDPSession, D as Deferred$1, U as UnsupportedOperation, T as TargetCloseError, E as EventEmitter$1, a as CallbackRegistry, b as assert$1, d as debug, c as debugError, e as DisposableStack, f as disposeSymbol, i as inertIfDisposed, t as throwIfDisposed, J as JSHandle, h as ElementHandle, j as environment, A as AsyncIterableUtil, k as bindIsolatedHandle, l as Dialog, s as stringifyFunction, m as interpolateFunction, S as SecurityDetails, H as HTTPResponse, n as invokeAtMostOnceForArguments, o as HTTPRequest, p as stringToBase64, q as handleError, r as STATUS_TEXTS, u as isPlainObject, v as isRegExp, w as isDate, P as ProtocolError, x as TimeoutError, y as PuppeteerURL, z as ARIAQueryHandler, R as Realm$2, B as scriptInjector, F as getSourceUrlComment, G as getSourcePuppeteerURLIfAvailable, I as isString, L as LazyArg, K as SOURCE_URL_REGEX, W as WebWorker, M as Frame, N as of, O as combineLatest, Q as fromEmitterEvent, V as map, X as first, Y as raceWith, Z as timeout, _ as Accessibility, $ as ConsoleMessage, a0 as defer, a1 as filter, a2 as isErrorLike, a3 as firstValueFrom, a4 as race, a5 as switchMap, a6 as delayWhen, a7 as fromAbortSignal, a8 as throwIfDetached, a9 as Keyboard, aa as Mouse, ab as MouseButton, ac as Touchscreen, ad as TouchError, ae as EmulationManager, af as Tracing, ag as Coverage, ah as parsePDFOptions, ai as from, aj as stringToTypedArray, ak as FileChooser, al as Page, am as bubble, an as evaluationString, ao as Target, ap as TargetType, aq as WEB_PERMISSION_TO_PROTOCOL_PERMISSION, ar as BrowserContext, as as Browser$1 } from './index-CFQXKBdX.mjs'; import require$$2 from 'node:crypto'; import 'semver'; import 'node:url'; import 'node:path'; import 'node:fs/promises'; import 'node:child_process'; import 'node:fs'; import 'node:os'; import 'node:readline'; import 'node:http'; import 'node:https'; import 'node:net'; import 'node:tls'; import 'node:events'; import 'node:assert'; import 'node:buffer'; import 'node:stream'; import 'node:dns'; import 'node:util'; import 'image-size'; import 'pdfkit'; import 'html-validate/node'; var BidiMapper = {}; var BidiServer = {}; var EventEmitter = {}; function mitt(n){return {all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e]);},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]));},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e);}),(i=n.get("*"))&&i.slice().map(function(n){n(t,e);});}}} var mitt$1 = /*#__PURE__*/Object.freeze({ __proto__: null, default: mitt }); var require$$0 = /*@__PURE__*/getAugmentedNamespace(mitt$1); var hasRequiredEventEmitter; function requireEventEmitter () { if (hasRequiredEventEmitter) return EventEmitter; hasRequiredEventEmitter = 1; var __importDefault = (EventEmitter && EventEmitter.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(EventEmitter, "__esModule", { value: true }); EventEmitter.EventEmitter = void 0; /** * Copyright 2022 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const mitt_1 = __importDefault(require$$0); let EventEmitter$1 = class EventEmitter { #emitter = (0, mitt_1.default)(); on(type, handler) { this.#emitter.on(type, handler); return this; } /** * Like `on` but the listener will only be fired once and then it will be removed. * @param event The event you'd like to listen to * @param handler The handler function to run when the event occurs * @return `this` to enable chaining method calls. */ once(event, handler) { const onceHandler = (eventData) => { handler(eventData); this.off(event, onceHandler); }; return this.on(event, onceHandler); } off(type, handler) { this.#emitter.off(type, handler); return this; } /** * Emits an event and call any associated listeners. * * @param event The event to emit. * @param eventData Any data to emit with the event. * @return `true` if there are any listeners, `false` otherwise. */ emit(event, eventData) { this.#emitter.emit(event, eventData); } /** * Removes all listeners. If given an event argument, it will remove only * listeners for that event. * @param event - the event to remove listeners for. * @returns `this` to enable you to chain method calls. */ removeAllListeners(event) { if (event) { this.#emitter.all.delete(event); } else { this.#emitter.all.clear(); } return this; } }; EventEmitter.EventEmitter = EventEmitter$1; return EventEmitter; } var log = {}; var hasRequiredLog; function requireLog () { if (hasRequiredLog) return log; hasRequiredLog = 1; /** * Copyright 2021 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(log, "__esModule", { value: true }); log.LogType = void 0; var LogType; (function (LogType) { // keep-sorted start LogType["bidi"] = "bidi"; LogType["cdp"] = "cdp"; LogType["debug"] = "debug"; LogType["debugError"] = "debug:error"; LogType["debugInfo"] = "debug:info"; LogType["debugWarn"] = "debug:warn"; // keep-sorted end })(LogType || (log.LogType = LogType = {})); return log; } var ProcessingQueue = {}; var hasRequiredProcessingQueue; function requireProcessingQueue () { if (hasRequiredProcessingQueue) return ProcessingQueue; hasRequiredProcessingQueue = 1; /** * Copyright 2022 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var _a; Object.defineProperty(ProcessingQueue, "__esModule", { value: true }); ProcessingQueue.ProcessingQueue = void 0; const log_js_1 = requireLog(); let ProcessingQueue$1 = class ProcessingQueue { static LOGGER_PREFIX = `${log_js_1.LogType.debug}:queue`; #logger; #processor; #queue = []; // Flag to keep only 1 active processor. #isProcessing = false; constructor(processor, logger) { this.#processor = processor; this.#logger = logger; } add(entry, name) { this.#queue.push([entry, name]); // No need in waiting. Just initialize processor if needed. void this.#processIfNeeded(); } async #processIfNeeded() { if (this.#isProcessing) { return; } this.#isProcessing = true; while (this.#queue.length > 0) { const arrayEntry = this.#queue.shift(); if (!arrayEntry) { continue; } const [entryPromise, name] = arrayEntry; this.#logger?.(_a.LOGGER_PREFIX, 'Processing event:', name); await entryPromise .then((entry) => { if (entry.kind === 'error') { this.#logger?.(log_js_1.LogType.debugError, 'Event threw before sending:', entry.error.message, entry.error.stack); return; } return this.#processor(entry.value); }) .catch((error) => { this.#logger?.(log_js_1.LogType.debugError, 'Event was not processed:', error?.message); }); } this.#isProcessing = false; } }; ProcessingQueue.ProcessingQueue = ProcessingQueue$1; _a = ProcessingQueue$1; return ProcessingQueue; } var CommandProcessor = {}; var protocol = {}; var cdp = {}; var hasRequiredCdp; function requireCdp () { if (hasRequiredCdp) return cdp; hasRequiredCdp = 1; Object.defineProperty(cdp, "__esModule", { value: true }); return cdp; } var chromiumBidi = {}; var hasRequiredChromiumBidi; function requireChromiumBidi () { if (hasRequiredChromiumBidi) return chromiumBidi; hasRequiredChromiumBidi = 1; /** * Copyright 2023 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(chromiumBidi, "__esModule", { value: true }); chromiumBidi.EVENT_NAMES = chromiumBidi.Bluetooth = chromiumBidi.Network = chromiumBidi.Input = chromiumBidi.BrowsingContext = chromiumBidi.Log = chromiumBidi.Script = chromiumBidi.BiDiModule = void 0; // keep-sorted end var BiDiModule; (function (BiDiModule) { // keep-sorted start BiDiModule["Bluetooth"] = "bluetooth"; BiDiModule["Browser"] = "browser"; BiDiModule["BrowsingContext"] = "browsingContext"; BiDiModule["Cdp"] = "goog:cdp"; BiDiModule["Input"] = "input"; BiDiModule["Log"] = "log"; BiDiModule["Network"] = "network"; BiDiModule["Script"] = "script"; BiDiModule["Session"] = "session"; // keep-sorted end })(BiDiModule || (chromiumBidi.BiDiModule = BiDiModule = {})); var Script; (function (Script) { (function (EventNames) { // keep-sorted start EventNames["Message"] = "script.message"; EventNames["RealmCreated"] = "script.realmCreated"; EventNames["RealmDestroyed"] = "script.realmDestroyed"; // keep-sorted end })(Script.EventNames || (Script.EventNames = {})); })(Script || (chromiumBidi.Script = Script = {})); var Log; (function (Log) { (function (EventNames) { EventNames["LogEntryAdded"] = "log.entryAdded"; })(Log.EventNames || (Log.EventNames = {})); })(Log || (chromiumBidi.Log = Log = {})); var BrowsingContext; (function (BrowsingContext) { (function (EventNames) { // keep-sorted start EventNames["ContextCreated"] = "browsingContext.contextCreated"; EventNames["ContextDestroyed"] = "browsingContext.contextDestroyed"; EventNames["DomContentLoaded"] = "browsingContext.domContentLoaded"; EventNames["DownloadWillBegin"] = "browsingContext.downloadWillBegin"; EventNames["FragmentNavigated"] = "browsingContext.fragmentNavigated"; EventNames["HistoryUpdated"] = "browsingContext.historyUpdated"; EventNames["Load"] = "browsingContext.load"; EventNames["NavigationAborted"] = "browsingContext.navigationAborted"; EventNames["NavigationCommitted"] = "browsingContext.navigationCommitted"; EventNames["NavigationFailed"] = "browsingContext.navigationFailed"; EventNames["NavigationStarted"] = "browsingContext.navigationStarted"; EventNames["UserPromptClosed"] = "browsingContext.userPromptClosed"; EventNames["UserPromptOpened"] = "browsingContext.userPromptOpened"; // keep-sorted end })(BrowsingContext.EventNames || (BrowsingContext.EventNames = {})); })(BrowsingContext || (chromiumBidi.BrowsingContext = BrowsingContext = {})); var Input; (function (Input) { (function (EventNames) { // keep-sorted start EventNames["FileDialogOpened"] = "input.fileDialogOpened"; // keep-sorted end })(Input.EventNames || (Input.EventNames = {})); })(Input || (chromiumBidi.Input = Input = {})); var Network; (function (Network) { (function (EventNames) { // keep-sorted start EventNames["AuthRequired"] = "network.authRequired"; EventNames["BeforeRequestSent"] = "network.beforeRequestSent"; EventNames["FetchError"] = "network.fetchError"; EventNames["ResponseCompleted"] = "network.responseCompleted"; EventNames["ResponseStarted"] = "network.responseStarted"; // keep-sorted end })(Network.EventNames || (Network.EventNames = {})); })(Network || (chromiumBidi.Network = Network = {})); var Bluetooth; (function (Bluetooth) { (function (EventNames) { EventNames["RequestDevicePromptUpdated"] = "bluetooth.requestDevicePromptUpdated"; EventNames["GattConnectionAttempted"] = "bluetooth.gattConnectionAttempted"; })(Bluetooth.EventNames || (Bluetooth.EventNames = {})); })(Bluetooth || (chromiumBidi.Bluetooth = Bluetooth = {})); chromiumBidi.EVENT_NAMES = new Set([ // keep-sorted start ...Object.values(BiDiModule), ...Object.values(Bluetooth.EventNames), ...Object.values(BrowsingContext.EventNames), ...Object.values(Input.EventNames), ...Object.values(Log.EventNames), ...Object.values(Network.EventNames), ...Object.values(Script.EventNames), // keep-sorted end ]); return chromiumBidi; } var webdriverBidi = {}; var hasRequiredWebdriverBidi; function requireWebdriverBidi () { if (hasRequiredWebdriverBidi) return webdriverBidi; hasRequiredWebdriverBidi = 1; /** * Copyright 2024 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(webdriverBidi, "__esModule", { value: true }); return webdriverBidi; } var ErrorResponse = {}; var hasRequiredErrorResponse; function requireErrorResponse () { if (hasRequiredErrorResponse) return ErrorResponse; hasRequiredErrorResponse = 1; Object.defineProperty(ErrorResponse, "__esModule", { value: true }); ErrorResponse.NoSuchWebExtensionException = ErrorResponse.InvalidWebExtensionException = ErrorResponse.UnderspecifiedStoragePartitionException = ErrorResponse.UnableToSetFileInputException = ErrorResponse.UnableToSetCookieException = ErrorResponse.NoSuchStoragePartitionException = ErrorResponse.UnsupportedOperationException = ErrorResponse.UnableToCloseBrowserException = ErrorResponse.UnableToCaptureScreenException = ErrorResponse.UnknownErrorException = ErrorResponse.UnknownCommandException = ErrorResponse.SessionNotCreatedException = ErrorResponse.NoSuchUserContextException = ErrorResponse.NoSuchScriptException = ErrorResponse.NoSuchRequestException = ErrorResponse.NoSuchNodeException = ErrorResponse.NoSuchInterceptException = ErrorResponse.NoSuchHistoryEntryException = ErrorResponse.NoSuchHandleException = ErrorResponse.NoSuchFrameException = ErrorResponse.NoSuchElementException = ErrorResponse.NoSuchAlertException = ErrorResponse.MoveTargetOutOfBoundsException = ErrorResponse.InvalidSessionIdException = ErrorResponse.InvalidSelectorException = ErrorResponse.InvalidArgumentException = ErrorResponse.Exception = void 0; class Exception extends Error { error; message; stacktrace; constructor(error, message, stacktrace) { super(); this.error = error; this.message = message; this.stacktrace = stacktrace; } toErrorResponse(commandId) { return { type: 'error', id: commandId, error: this.error, message: this.message, stacktrace: this.stacktrace, }; } } ErrorResponse.Exception = Exception; class InvalidArgumentException extends Exception { constructor(message, stacktrace) { super("invalid argument" /* ErrorCode.InvalidArgument */, message, stacktrace); } } ErrorResponse.InvalidArgumentException = InvalidArgumentException; class InvalidSelectorException extends Exception { constructor(message, stacktrace) { super("invalid selector" /* ErrorCode.InvalidSelector */, message, stacktrace); } } ErrorResponse.InvalidSelectorException = InvalidSelectorException; class InvalidSessionIdException extends Exception { constructor(message, stacktrace) { super("invalid session id" /* ErrorCode.InvalidSessionId */, message, stacktrace); } } ErrorResponse.InvalidSessionIdException = InvalidSessionIdException; class MoveTargetOutOfBoundsException extends Exception { constructor(message, stacktrace) { super("move target out of bounds" /* ErrorCode.MoveTargetOutOfBounds */, message, stacktrace); } } ErrorResponse.MoveTargetOutOfBoundsException = MoveTargetOutOfBoundsException; class NoSuchAlertException extends Exception { constructor(message, stacktrace) { super("no such alert" /* ErrorCode.NoSuchAlert */, message, stacktrace); } } ErrorResponse.NoSuchAlertException = NoSuchAlertException; class NoSuchElementException extends Exception { constructor(message, stacktrace) { super("no such element" /* ErrorCode.NoSuchElement */, message, stacktrace); } } ErrorResponse.NoSuchElementException = NoSuchElementException; class NoSuchFrameException extends Exception { constructor(message, stacktrace) { super("no such frame" /* ErrorCode.NoSuchFrame */, message, stacktrace); } } ErrorResponse.NoSuchFrameException = NoSuchFrameException; class NoSuchHandleException extends Exception { constructor(message, stacktrace) { super("no such handle" /* ErrorCode.NoSuchHandle */, message, stacktrace); } } ErrorResponse.NoSuchHandleException = NoSuchHandleException; class NoSuchHistoryEntryException extends Exception { constructor(message, stacktrace) { super("no such history entry" /* ErrorCode.NoSuchHistoryEntry */, message, stacktrace); } } ErrorResponse.NoSuchHistoryEntryException = NoSuchHistoryEntryException; class NoSuchInterceptException extends Exception { constructor(message, stacktrace) { super("no such intercept" /* ErrorCode.NoSuchIntercept */, message, stacktrace); } } ErrorResponse.NoSuchInterceptException = NoSuchInterceptException; class NoSuchNodeException extends Exception { constructor(message, stacktrace) { super("no such node" /* ErrorCode.NoSuchNode */, message, stacktrace); } } ErrorResponse.NoSuchNodeException = NoSuchNodeException; class NoSuchRequestException extends Exception { constructor(message, stacktrace) { super("no such request" /* ErrorCode.NoSuchRequest */, message, stacktrace); } } ErrorResponse.NoSuchRequestException = NoSuchRequestException; class NoSuchScriptException extends Exception { constructor(message, stacktrace) { super("no such script" /* ErrorCode.NoSuchScript */, message, stacktrace); } } ErrorResponse.NoSuchScriptException = NoSuchScriptException; class NoSuchUserContextException extends Exception { constructor(message, stacktrace) { super("no such user context" /* ErrorCode.NoSuchUserContext */, message, stacktrace); } } ErrorResponse.NoSuchUserContextException = NoSuchUserContextException; class SessionNotCreatedException extends Exception { constructor(message, stacktrace) { super("session not created" /* ErrorCode.SessionNotCreated */, message, stacktrace); } } ErrorResponse.SessionNotCreatedException = SessionNotCreatedException; class UnknownCommandException extends Exception { constructor(message, stacktrace) { super("unknown command" /* ErrorCode.UnknownCommand */, message, stacktrace); } } ErrorResponse.UnknownCommandException = UnknownCommandException; class UnknownErrorException extends Exception { constructor(message, stacktrace = new Error().stack) { super("unknown error" /* ErrorCode.UnknownError */, message, stacktrace); } } ErrorResponse.UnknownErrorException = UnknownErrorException; class UnableToCaptureScreenException extends Exception { constructor(message, stacktrace) { super("unable to capture screen" /* ErrorCode.UnableToCaptureScreen */, message, stacktrace); } } ErrorResponse.UnableToCaptureScreenException = UnableToCaptureScreenException; class UnableToCloseBrowserException extends Exception { constructor(message, stacktrace) { super("unable to close browser" /* ErrorCode.UnableToCloseBrowser */, message, stacktrace); } } ErrorResponse.UnableToCloseBrowserException = UnableToCloseBrowserException; class UnsupportedOperationException extends Exception { constructor(message, stacktrace) { super("unsupported operation" /* ErrorCode.UnsupportedOperation */, message, stacktrace); } } ErrorResponse.UnsupportedOperationException = UnsupportedOperationException; class NoSuchStoragePartitionException extends Exception { constructor(message, stacktrace) { super("no such storage partition" /* ErrorCode.NoSuchStoragePartition */, message, stacktrace); } } ErrorResponse.NoSuchStoragePartitionException = NoSuchStoragePartitionException; class UnableToSetCookieException extends Exception { constructor(message, stacktrace) { super("unable to set cookie" /* ErrorCode.UnableToSetCookie */, message, stacktrace); } } ErrorResponse.UnableToSetCookieException = UnableToSetCookieException; class UnableToSetFileInputException extends Exception { constructor(message, stacktrace) { super("unable to set file input" /* ErrorCode.UnableToSetFileInput */, message, stacktrace); } } ErrorResponse.UnableToSetFileInputException = UnableToSetFileInputException; class UnderspecifiedStoragePartitionException extends Exception { constructor(message, stacktrace) { super("underspecified storage partition" /* ErrorCode.UnderspecifiedStoragePartition */, message, stacktrace); } } ErrorResponse.UnderspecifiedStoragePartitionException = UnderspecifiedStoragePartitionException; class InvalidWebExtensionException extends Exception { constructor(message, stacktrace) { super("invalid web extension" /* ErrorCode.InvalidWebExtension */, message, stacktrace); } } ErrorResponse.InvalidWebExtensionException = InvalidWebExtensionException; class NoSuchWebExtensionException extends Exception { constructor(message, stacktrace) { super("no such web extension" /* ErrorCode.NoSuchWebExtension */, message, stacktrace); } } ErrorResponse.NoSuchWebExtensionException = NoSuchWebExtensionException; return ErrorResponse; } var webdriverBidiPermissions = {}; var hasRequiredWebdriverBidiPermissions; function requireWebdriverBidiPermissions () { if (hasRequiredWebdriverBidiPermissions) return webdriverBidiPermissions; hasRequiredWebdriverBidiPermissions = 1; /** * Copyright 2024 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(webdriverBidiPermissions, "__esModule", { value: true }); return webdriverBidiPermissions; } var webdriverBidiBluetooth = {}; var hasRequiredWebdriverBidiBluetooth; function requireWebdriverBidiBluetooth () { if (hasRequiredWebdriverBidiBluetooth) return webdriverBidiBluetooth; hasRequiredWebdriverBidiBluetooth = 1; /** * Copyright 2024 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(webdriverBidiBluetooth, "__esModule", { value: true }); return webdriverBidiBluetooth; } var hasRequiredProtocol; function requireProtocol () { if (hasRequiredProtocol) return protocol; hasRequiredProtocol = 1; (function (exports) { var __createBinding = (protocol && protocol.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (protocol && protocol.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (protocol && protocol.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __exportStar = (protocol && protocol.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ChromiumBidi = exports.Cdp = void 0; /** * Copyright 2023 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ exports.Cdp = __importStar(requireCdp()); exports.ChromiumBidi = __importStar(requireChromiumBidi()); __exportStar(requireWebdriverBidi(), exports); __exportStar(requireErrorResponse(), exports); __exportStar(requireWebdriverBidiPermissions(), exports); __exportStar(requireWebdriverBidiBluetooth(), exports); } (protocol)); return protocol; } var BidiNoOpParser = {}; var hasRequiredBidiNoOpParser; function requireBidiNoOpParser () { if (hasRequiredBidiNoOpParser) return BidiNoOpParser; hasRequiredBidiNoOpParser = 1; /** * Copyright 2023 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(BidiNoOpParser, "__esModule", { value: true }); BidiNoOpParser.BidiNoOpParser = void 0; let BidiNoOpParser$1 = class BidiNoOpParser { // Bluetooth module // keep-sorted start block=yes parseDisableSimulationParameters(params) { return params; } parseHandleRequestDevicePromptParams(params) { return params; } parseSimulateAdapterParameters(params) { return params; } parseSimulateAdvertisementParameters(params) { return params; } parseSimulateGattConnectionResponseParameters(params) { return params; } parseSimulatePreconnectedPeripheralParameters(params) { return params; } // keep-sorted end // Browser module // keep-sorted start block=yes parseRemoveUserContextParams(params) { return params; } // keep-sorted end // Browsing Context module // keep-sorted start block=yes parseActivateParams(params) { return params; } parseCaptureScreenshotParams(params) { return params; } parseCloseParams(params) { return params; } parseCreateParams(params) { return params; } parseGetTreeParams(params) { return params; } parseHandleUserPromptParams(params) { return params; } parseLocateNodesParams(params) { return params; } parseNavigateParams(params) { return params; } parsePrintParams(params) { return params; } parseReloadParams(params) { return params; } parseSetViewportParams(params) { return params; } parseTraverseHistoryParams(params) { return params; } // keep-sorted end // CDP module // keep-sorted start block=yes parseGetSessionParams(params) { return params; } parseResolveRealmParams(params) { return params; } parseSendCommandParams(params) { return params; } // keep-sorted end // Emulation module // keep-sorted start block=yes parseSetGeolocationOverrideParams(params) { return params; } // keep-sorted end // Script module // keep-sorted start block=yes parseAddPreloadScriptParams(params) { return params; } parseCallFunctionParams(params) { return params; } parseDisownParams(params) { return params; } parseEvaluateParams(params) { return params; } parseGetRealmsParams(params) { return params; } parseRemovePreloadScriptParams(params) { return params; } // keep-sorted end // Input module // keep-sorted start block=yes parsePerformActionsParams(params) { return params; } parseReleaseActionsParams(params) { return params; } parseSetFilesParams(params) { return params; } // keep-sorted end // Network module // keep-sorted start block=yes parseAddInterceptParams(params) { return params; } parseContinueRequestParams(params) { return params; } parseContinueResponseParams(params) { return params; } parseContinueWithAuthParams(params) { return params; } parseFailRequestParams(params) { return params; } parseProvideResponseParams(params) { return params; } parseRemoveInterceptParams(params) { return params; } parseSetCacheBehavior(params) { return params; } // keep-sorted end // Permissions module // keep-sorted start block=yes parseSetPermissionsParams(params) { return params; } // keep-sorted end // Session module // keep-sorted start block=yes parseSubscribeParams(params) { return params; } parseUnsubscribeParams(params) { return params; } // keep-sorted end // Storage module // keep-sorted start block=yes parseDeleteCookiesParams(params) { return params; } parseGetCookiesParams(params) { return params; } parseSetCookieParams(params) { return params; } // keep-sorted end // WebExtenstion module // keep-sorted start block=yes parseInstallParams(params) { return params; } parseUninstallParams(params) { return params; } }; BidiNoOpParser.BidiNoOpParser = BidiNoOpParser$1; return BidiNoOpParser; } var BrowserProcessor = {}; var hasRequiredBrowserProcessor; function requireBrowserProcessor () { if (hasRequiredBrowserProcessor) return BrowserProcessor; hasRequiredBrowserProcessor = 1; /** * Copyright 2023 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(BrowserProcessor, "__esModule", { value: true }); BrowserProcessor.BrowserProcessor = void 0; const protocol_js_1 = requireProtocol(); let BrowserProcessor$1 = class BrowserProcessor { #browserCdpClient; #browsingContextStorage; #userContextStorage; constructor(browserCdpClient, browsingContextStorage, userContextStorage) { this.#browserCdpClient = browserCdpClient; this.#browsingContextStorage = browsingContextStorage; this.#userContextStorage = userContextStorage; } close() { // Ensure that it is put at the end of the event loop. // This way we send back the response before closing the tab. setTimeout(() => this.#browserCdpClient.sendCommand('Browser.close'), 0); return {}; } async createUserContext(params) { const request = { proxyServer: params['goog:proxyServer'] ?? undefined, }; const proxyBypassList = params['goog:proxyBypassList'] ?? undefined; if (proxyBypassList) { request.proxyBypassList = proxyBypassList.join(','); } const context = await this.#browserCdpClient.sendCommand('Target.createBrowserContext', request); return { userContext: context.browserContextId, }; } async removeUserContext(params) { const userContext = params.userContext; if (userContext === 'default') { throw new protocol_js_1.InvalidArgumentException('`default` user context cannot be removed'); } try { await this.#browserCdpClient.sendCommand('Target.disposeBrowserContext', { browserContextId: userContext, }); } catch (err) { // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/devtools/protocol/target_handler.cc;l=1424;drc=c686e8f4fd379312469fe018f5c390e9c8f20d0d if (err.message.startsWith('Failed to find context with id')) { throw new protocol_js_1.NoSuchUserContextException(err.message); } throw err; } return {}; } async getUserContexts() { return { userContexts: await this.#userContextStorage.getUserContexts(), }; } async #getWindowInfo(targetId) { const windowInfo = await this.#browserCdpClient.sendCommand('Browser.getWindowForTarget', { targetId }); return { // `active` is not supported in CDP yet. active: false, clientWindow: `${windowInfo.windowId}`, state: windowInfo.bounds.windowState ?? 'normal', height: windowInfo.bounds.height ?? 0, width: windowInfo.bounds.width ?? 0, x: windowInfo.bounds.left ?? 0, y: windowInfo.bounds.top ?? 0, }; } async getClientWindows() { const topLevelTargetIds = this.#browsingContextStorage .getTopLevelContexts() .map((b) => b.cdpTarget.id); const clientWindows = await Promise.all(topLevelTargetIds.map(async (targetId) => await this.#getWindowInfo(targetId))); const uniqueClientWindowIds = new Set(); const uniqueClientWindows = new Array(); // Filter out duplicated client windows. for (const window of clientWindows) { if (!uniqueClientWindowIds.has(window.clientWindow)) { uniqueClientWindowIds.add(window.clientWindow); uniqueClientWindows.push(window); } } return { clientWindows: uniqueClientWindows }; } }; BrowserProcessor.BrowserProcessor = BrowserProcessor$1; return BrowserProcessor; } var CdpProcessor = {}; var hasRequiredCdpProcessor; function requireCdpProcessor () { if (hasRequiredCdpProcessor) return CdpProcessor; hasRequiredCdpProcessor = 1; /** * Copyright 2023 Google LLC. * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(CdpProcessor, "__esModule", { value: true }); CdpProcessor.CdpProcessor = void 0; const protocol_js_1 = requireProtocol(); let CdpProcessor$1 = class CdpProcessor { #browsingContextStorage; #realmStorage; #cdpConnection; #browserCdpClient; constructor(browsingContextStorage, realmStorage, cdpConnection, browserCdpClient) { this.#browsingContextStorage = browsingContextStorage; this.#realmStorage = realmStorage; this.#cdpConnection = cdpConnection; this.#browserCdpClient = browserCdpClient; } getSession(params) { const context = params.context; const sessionId = this.#browsingContextStorage.getContext(context).cdpTarget.cdpSessionId; if (sessionId === undefined) { return {}; } return { session: sessionId }; } resolveRealm(params) { const context = params.realm; const realm = this.#realmStorage.getRealm({ realmId: context }); if (realm === undefined) { throw new protocol_js_1.UnknownErrorException(`Could not find realm ${params.realm}`); } return { executionContextId: realm.executionContextId }; } async sendCommand(params) { const client = params.session ? this.#cdpConnection.getCdpClient(params.session) : this.#browserCdpClient; const result = await client.sendCommand(params.method, params.params); return { result, session: params.session, }; } }; CdpProcessor.CdpProcessor = CdpProcessor$1; return CdpProcessor; } var BrowsingContextProcessor = {}; var hasRequiredBrowsingContextProcessor; function requireBrowsingContextProcessor () { if (hasRequiredBrowsingContextProcessor) return BrowsingContextProcessor; hasRequiredBrowsingContextProcessor = 1; Object.defineProperty(BrowsingContextProcessor, "__esModule", { value: true }); BrowsingContextProcessor.BrowsingContextProcessor = void 0; const protocol_js_1 = requireProtocol(); let BrowsingContextProcessor$1 = class BrowsingContextProcessor { #browserCdpClient; #browsingContextStorage; #eventManager; #userContextStorage; constructor(browserCdpClient, browsingContextStorage, userContextStorage, eventManager) { this.#userContextStorage = userContextStorage; this.#browserCdpClient = browserCdpClient; this.#browsingContextStorage = browsingContextStorage; this.#eventManager = eventManager; this.#eventManager.addSubscribeHook(protocol_js_1.ChromiumBidi.BrowsingContext.EventNames.ContextCreated, this.#onContextCreatedSubscribeHook.bind(this)); } getTree(params) { const resultContexts = params.root === undefined ? this.#browsingContextStorage.getTopLevelContexts() : [this.#browsingContextStorage.getContext(params.root)]; return { contexts: resultContexts.map((c) => c.serializeToBidiValue(params.maxDepth ?? Number.MAX_VALUE)), }; } async create(params) { let referenceContext; let userContext = 'default'; if (params.referenceContext !== undefined) { referenceContext = this.#browsingContextStorage.getContext(params.referenceContext); if (!referenceContext.isTopLevelContext()) { throw new protocol_js_1.InvalidArgumentException(`referenceContext should be a top-level context`); } userContext = referenceContext.userContext; } if (params.userContext !== undefined) { userContext = params.userContext; } const existingContexts = this.#browsingContextStorage .getAllContexts() .filter((context) => context.userContext === userContext); let newWindow = false; switch (params.type) { case "tab" /* BrowsingContext.CreateType.Tab */: newWindow = false; break; case "window" /* BrowsingContext.CreateType.Window */: newWindow = true; break; } if (!existingContexts.length) { // If there are no contexts in the given user context, we need to set // newWindow to true as newWindow=false will be rejected. newWindow = true; } let result; try { result = await this.#browserCdpClient.sendCommand('Target.createTarget', { url: 'about:blank', newWindow, browserContextId: userContext === 'default' ? undefined : userContext, background: params.background === true, }); } catch (err) { if ( // See https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/devtools/protocol/target_handler.cc;l=90;drc=e80392ac11e48a691f4309964cab83a3a59e01c8 err.message.startsWith('Failed to find browser context with id') || // See https://source.chromium.org/chromium/chromium/src/+/main:headless/lib/browser/protocol/target_handler.cc;l=49;drc=e80392ac11e48a691f4309964cab83a3a59e01c8 err.message === 'browserContextId') { throw new protocol_js_1.NoSuchUserContextException(`The context ${userContext} was not found`); } throw err; } // Wait for the new target to be attached and to be added to the browsing context // storage. const context = await this.#browsingContextStorage.waitForContext(result.targetId); // Wait for the new tab to be loaded to avoid race conditions in the // `browsingContext` events, when the `browsingContext.domContentLoaded` and // `browsingContext.load` events from the initial `about:blank` navigation // are emitted after the next navigation is started. // Details: https://github.com/web-platform-tests/wpt/issues/35846 await context.lifecycleLoaded(); return { context: context.id }; } navigate(params) { const context = this.#browsingContextStorage.getContext(params.context); return context.navigate(params.url, params.wait ?? "none" /* BrowsingContext.ReadinessState.None */); } reload(params) { const context = this.#browsingContextStorage.getContext(params.context); return context.reload(params.ignoreCache ?? false, params.wait ?? "none" /* BrowsingContext.ReadinessState.None */); } async activate(params) { const context = this.#browsingContextStorage.getContext(params.context); if (!context.isTopLevelContext()) { throw new protocol_js_1.InvalidArgumentException('Activation is only supported on the top-level context'); } await context.activate(); return {}; } async captureScreenshot(params) { const context = this.#browsingContextStorage.getContext(params.context); return await context.captureScreenshot(params); } async print(params) { const context = this.#browsingContextStorage.getContext(params.context); return await context.print(params); } async setViewport(params) { const impactedTopLevelContexts = await this.#getRelatedTopLevelBrowsingContexts(params.context, params.userContexts); for (const userContextId of params.userContexts ?? []) { const userContextConfig = this.#userContextStorage.getConfig(userContextId); // `undefined` means not changes should be done to the config. if (params.devicePixelRatio !== undefined) { userContextConfig.devicePixelRatio = params.devicePixelRatio; } if (params.viewport !== undefined) { userContextConfig.viewport = params.viewport; } } await Promise.all(impactedTopLevelContexts.map((context) => context.setViewport(params.viewport, params.devicePixelRatio))); return {}; } /** * Returns a list of top-level browsing context ids. */ async #getRelatedTopLevelBrowsingContexts(browsingContextId, userContextIds) { if (browsingContextId === undefined && userContextIds === undefined) { throw new protocol_js_1.InvalidArgumentException('Either userContexts or context must be provided'); } if (browsingContextId !== undefined && userContextIds !== undefined) { throw new protocol_js_1.InvalidArgumentException('userContexts and context are mutually exclusive'); } if (browsingContextId !== undefined) { const context = this.#browsingContextStorage.getContext(browsingContextId); if (!context.isTopLevelContext()) { throw new protocol_js_1.InvalidArgumentException('Emulating viewport is only supported on the top-level context'); } return [context]; } // Verify that all user contexts exist. await this.#userContextStorage.verifyUserContextIdList(userContextIds); const result = []; for (const userContextId of userContextIds) { const topLevelBrowsingContexts = this.#browsingContextStorage .getTopLevelContexts() .filter((browsingContext) => browsingContext