dom.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. var dom_exports = {};
  30. __export(dom_exports, {
  31. ElementHandle: () => ElementHandle,
  32. FrameExecutionContext: () => FrameExecutionContext,
  33. NonRecoverableDOMError: () => NonRecoverableDOMError,
  34. assertDone: () => assertDone,
  35. isNonRecoverableDOMError: () => isNonRecoverableDOMError,
  36. kUnableToAdoptErrorMessage: () => kUnableToAdoptErrorMessage,
  37. throwElementIsNotAttached: () => throwElementIsNotAttached,
  38. throwRetargetableDOMError: () => throwRetargetableDOMError
  39. });
  40. module.exports = __toCommonJS(dom_exports);
  41. var import_fs = __toESM(require("fs"));
  42. var js = __toESM(require("./javascript"));
  43. var import_utils = require("../utils");
  44. var import_fileUploadUtils = require("./fileUploadUtils");
  45. var rawInjectedScriptSource = __toESM(require("../generated/injectedScriptSource"));
  46. class NonRecoverableDOMError extends Error {
  47. }
  48. function isNonRecoverableDOMError(error) {
  49. return error instanceof NonRecoverableDOMError;
  50. }
  51. class FrameExecutionContext extends js.ExecutionContext {
  52. constructor(delegate, frame, world) {
  53. super(frame, delegate, world || "content-script");
  54. this.frame = frame;
  55. this.world = world;
  56. }
  57. adoptIfNeeded(handle) {
  58. if (handle instanceof ElementHandle && handle._context !== this)
  59. return this.frame._page.delegate.adoptElementHandle(handle, this);
  60. return null;
  61. }
  62. async evaluate(pageFunction, arg) {
  63. return js.evaluate(this, true, pageFunction, arg);
  64. }
  65. async evaluateHandle(pageFunction, arg) {
  66. return js.evaluate(this, false, pageFunction, arg);
  67. }
  68. async evaluateExpression(expression, options, arg) {
  69. return js.evaluateExpression(this, expression, { ...options, returnByValue: true }, arg);
  70. }
  71. async evaluateExpressionHandle(expression, options, arg) {
  72. return js.evaluateExpression(this, expression, { ...options, returnByValue: false }, arg);
  73. }
  74. injectedScript() {
  75. if (!this._injectedScriptPromise) {
  76. const customEngines = [];
  77. const selectorsRegistry = this.frame._page.browserContext.selectors();
  78. for (const [name, { source: source2 }] of selectorsRegistry._engines)
  79. customEngines.push({ name, source: `(${source2})` });
  80. const sdkLanguage = this.frame._page.browserContext._browser.sdkLanguage();
  81. const options = {
  82. isUnderTest: (0, import_utils.isUnderTest)(),
  83. sdkLanguage,
  84. testIdAttributeName: selectorsRegistry.testIdAttributeName(),
  85. stableRafCount: this.frame._page.delegate.rafCountForStablePosition(),
  86. browserName: this.frame._page.browserContext._browser.options.name,
  87. isUtilityWorld: this.world === "utility",
  88. customEngines
  89. };
  90. const source = `
  91. (() => {
  92. const module = {};
  93. ${rawInjectedScriptSource.source}
  94. return new (module.exports.InjectedScript())(globalThis, ${JSON.stringify(options)});
  95. })();
  96. `;
  97. this._injectedScriptPromise = this.rawEvaluateHandle(source).then((handle) => {
  98. handle._setPreview("InjectedScript");
  99. return handle;
  100. });
  101. }
  102. return this._injectedScriptPromise;
  103. }
  104. }
  105. class ElementHandle extends js.JSHandle {
  106. constructor(context, objectId) {
  107. super(context, "node", void 0, objectId);
  108. this.__elementhandle = true;
  109. this._page = context.frame._page;
  110. this._frame = context.frame;
  111. this._initializePreview().catch((e) => {
  112. });
  113. }
  114. async _initializePreview() {
  115. const utility = await this._context.injectedScript();
  116. this._setPreview(await utility.evaluate((injected, e) => "JSHandle@" + injected.previewNode(e), this));
  117. }
  118. asElement() {
  119. return this;
  120. }
  121. async evaluateInUtility(pageFunction, arg) {
  122. try {
  123. const utility = await this._frame._utilityContext();
  124. return await utility.evaluate(pageFunction, [await utility.injectedScript(), this, arg]);
  125. } catch (e) {
  126. if (this._frame.isNonRetriableError(e))
  127. throw e;
  128. return "error:notconnected";
  129. }
  130. }
  131. async evaluateHandleInUtility(pageFunction, arg) {
  132. try {
  133. const utility = await this._frame._utilityContext();
  134. return await utility.evaluateHandle(pageFunction, [await utility.injectedScript(), this, arg]);
  135. } catch (e) {
  136. if (this._frame.isNonRetriableError(e))
  137. throw e;
  138. return "error:notconnected";
  139. }
  140. }
  141. async ownerFrame() {
  142. const frameId = await this._page.delegate.getOwnerFrame(this);
  143. if (!frameId)
  144. return null;
  145. const frame = this._page.frameManager.frame(frameId);
  146. if (frame)
  147. return frame;
  148. for (const page of this._page.browserContext.pages()) {
  149. const frame2 = page.frameManager.frame(frameId);
  150. if (frame2)
  151. return frame2;
  152. }
  153. return null;
  154. }
  155. async isIframeElement() {
  156. return this.evaluateInUtility(([injected, node]) => node && (node.nodeName === "IFRAME" || node.nodeName === "FRAME"), {});
  157. }
  158. async contentFrame() {
  159. const isFrameElement = throwRetargetableDOMError(await this.isIframeElement());
  160. if (!isFrameElement)
  161. return null;
  162. return this._page.delegate.getContentFrame(this);
  163. }
  164. async getAttribute(progress, name) {
  165. return this._frame.getAttribute(progress, ":scope", name, {}, this);
  166. }
  167. async inputValue(progress) {
  168. return this._frame.inputValue(progress, ":scope", {}, this);
  169. }
  170. async textContent(progress) {
  171. return this._frame.textContent(progress, ":scope", {}, this);
  172. }
  173. async innerText(progress) {
  174. return this._frame.innerText(progress, ":scope", {}, this);
  175. }
  176. async innerHTML(progress) {
  177. return this._frame.innerHTML(progress, ":scope", {}, this);
  178. }
  179. async dispatchEvent(progress, type, eventInit = {}) {
  180. return this._frame.dispatchEvent(progress, ":scope", type, eventInit, {}, this);
  181. }
  182. async _scrollRectIntoViewIfNeeded(progress, rect) {
  183. return await progress.race(this._page.delegate.scrollRectIntoViewIfNeeded(this, rect));
  184. }
  185. async _waitAndScrollIntoViewIfNeeded(progress, waitForVisible) {
  186. const result = await this._retryAction(progress, "scroll into view", async () => {
  187. progress.log(` waiting for element to be stable`);
  188. const waitResult = await progress.race(this.evaluateInUtility(async ([injected, node, { waitForVisible: waitForVisible2 }]) => {
  189. return await injected.checkElementStates(node, waitForVisible2 ? ["visible", "stable"] : ["stable"]);
  190. }, { waitForVisible }));
  191. if (waitResult)
  192. return waitResult;
  193. return await this._scrollRectIntoViewIfNeeded(progress);
  194. }, {});
  195. assertDone(throwRetargetableDOMError(result));
  196. }
  197. async scrollIntoViewIfNeeded(progress) {
  198. await this._waitAndScrollIntoViewIfNeeded(
  199. progress,
  200. false
  201. /* waitForVisible */
  202. );
  203. }
  204. async _clickablePoint() {
  205. const intersectQuadWithViewport = (quad) => {
  206. return quad.map((point) => ({
  207. x: Math.min(Math.max(point.x, 0), metrics.width),
  208. y: Math.min(Math.max(point.y, 0), metrics.height)
  209. }));
  210. };
  211. const computeQuadArea = (quad) => {
  212. let area = 0;
  213. for (let i = 0; i < quad.length; ++i) {
  214. const p1 = quad[i];
  215. const p2 = quad[(i + 1) % quad.length];
  216. area += (p1.x * p2.y - p2.x * p1.y) / 2;
  217. }
  218. return Math.abs(area);
  219. };
  220. const [quads, metrics] = await Promise.all([
  221. this._page.delegate.getContentQuads(this),
  222. this._page.mainFrame()._utilityContext().then((utility) => utility.evaluate(() => ({ width: innerWidth, height: innerHeight })))
  223. ]);
  224. if (quads === "error:notconnected")
  225. return quads;
  226. if (!quads || !quads.length)
  227. return "error:notvisible";
  228. const filtered = quads.map((quad) => intersectQuadWithViewport(quad)).filter((quad) => computeQuadArea(quad) > 0.99);
  229. if (!filtered.length)
  230. return "error:notinviewport";
  231. if (this._page.browserContext._browser.options.name === "firefox") {
  232. for (const quad of filtered) {
  233. const integerPoint = findIntegerPointInsideQuad(quad);
  234. if (integerPoint)
  235. return integerPoint;
  236. }
  237. }
  238. return quadMiddlePoint(filtered[0]);
  239. }
  240. async _offsetPoint(offset) {
  241. const [box, border] = await Promise.all([
  242. this.boundingBox(),
  243. this.evaluateInUtility(([injected, node]) => injected.getElementBorderWidth(node), {}).catch((e) => {
  244. })
  245. ]);
  246. if (!box || !border)
  247. return "error:notvisible";
  248. if (border === "error:notconnected")
  249. return border;
  250. return {
  251. x: box.x + border.left + offset.x,
  252. y: box.y + border.top + offset.y
  253. };
  254. }
  255. async _retryAction(progress, actionName, action, options) {
  256. let retry = 0;
  257. const waitTime = [0, 20, 100, 100, 500];
  258. while (true) {
  259. if (retry) {
  260. progress.log(`retrying ${actionName} action${options.trial ? " (trial run)" : ""}`);
  261. const timeout = waitTime[Math.min(retry - 1, waitTime.length - 1)];
  262. if (timeout) {
  263. progress.log(` waiting ${timeout}ms`);
  264. const result2 = await progress.race(this.evaluateInUtility(([injected, node, timeout2]) => new Promise((f) => setTimeout(f, timeout2)), timeout));
  265. if (result2 === "error:notconnected")
  266. return result2;
  267. }
  268. } else {
  269. progress.log(`attempting ${actionName} action${options.trial ? " (trial run)" : ""}`);
  270. }
  271. if (!options.skipActionPreChecks && !options.force)
  272. await this._frame._page.performActionPreChecks(progress);
  273. const result = await action(retry);
  274. ++retry;
  275. if (result === "error:notvisible") {
  276. if (options.force)
  277. throw new NonRecoverableDOMError("Element is not visible");
  278. progress.log(" element is not visible");
  279. continue;
  280. }
  281. if (result === "error:notinviewport") {
  282. if (options.force)
  283. throw new NonRecoverableDOMError("Element is outside of the viewport");
  284. progress.log(" element is outside of the viewport");
  285. continue;
  286. }
  287. if (result === "error:optionsnotfound") {
  288. progress.log(" did not find some options");
  289. continue;
  290. }
  291. if (result === "error:optionnotenabled") {
  292. progress.log(" option being selected is not enabled");
  293. continue;
  294. }
  295. if (typeof result === "object" && "hitTargetDescription" in result) {
  296. progress.log(` ${result.hitTargetDescription} intercepts pointer events`);
  297. continue;
  298. }
  299. if (typeof result === "object" && "missingState" in result) {
  300. progress.log(` element is not ${result.missingState}`);
  301. continue;
  302. }
  303. return result;
  304. }
  305. }
  306. async _retryPointerAction(progress, actionName, waitForEnabled, action, options) {
  307. const skipActionPreChecks = actionName === "move and up";
  308. return await this._retryAction(progress, actionName, async (retry) => {
  309. const scrollOptions = [
  310. void 0,
  311. { block: "end", inline: "end" },
  312. { block: "center", inline: "center" },
  313. { block: "start", inline: "start" }
  314. ];
  315. const forceScrollOptions = scrollOptions[retry % scrollOptions.length];
  316. return await this._performPointerAction(progress, actionName, waitForEnabled, action, forceScrollOptions, options);
  317. }, { ...options, skipActionPreChecks });
  318. }
  319. async _performPointerAction(progress, actionName, waitForEnabled, action, forceScrollOptions, options) {
  320. const { force = false, position } = options;
  321. const doScrollIntoView = async () => {
  322. if (forceScrollOptions) {
  323. return await this.evaluateInUtility(([injected, node, options2]) => {
  324. if (node.nodeType === 1)
  325. node.scrollIntoView(options2);
  326. return "done";
  327. }, forceScrollOptions);
  328. }
  329. return await this._scrollRectIntoViewIfNeeded(progress, position ? { x: position.x, y: position.y, width: 0, height: 0 } : void 0);
  330. };
  331. if (this._frame.parentFrame()) {
  332. await progress.race(doScrollIntoView().catch(() => {
  333. }));
  334. }
  335. if (options.__testHookBeforeStable)
  336. await progress.race(options.__testHookBeforeStable());
  337. if (!force) {
  338. const elementStates = waitForEnabled ? ["visible", "enabled", "stable"] : ["visible", "stable"];
  339. progress.log(` waiting for element to be ${waitForEnabled ? "visible, enabled and stable" : "visible and stable"}`);
  340. const result = await progress.race(this.evaluateInUtility(async ([injected, node, { elementStates: elementStates2 }]) => {
  341. return await injected.checkElementStates(node, elementStates2);
  342. }, { elementStates }));
  343. if (result)
  344. return result;
  345. progress.log(` element is ${waitForEnabled ? "visible, enabled and stable" : "visible and stable"}`);
  346. }
  347. if (options.__testHookAfterStable)
  348. await progress.race(options.__testHookAfterStable());
  349. progress.log(" scrolling into view if needed");
  350. const scrolled = await progress.race(doScrollIntoView());
  351. if (scrolled !== "done")
  352. return scrolled;
  353. progress.log(" done scrolling");
  354. const maybePoint = position ? await progress.race(this._offsetPoint(position)) : await progress.race(this._clickablePoint());
  355. if (typeof maybePoint === "string")
  356. return maybePoint;
  357. const point = roundPoint(maybePoint);
  358. progress.metadata.point = point;
  359. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  360. let hitTargetInterceptionHandle;
  361. if (force) {
  362. progress.log(` forcing action`);
  363. } else {
  364. if (options.__testHookBeforeHitTarget)
  365. await progress.race(options.__testHookBeforeHitTarget());
  366. const frameCheckResult = await progress.race(this._checkFrameIsHitTarget(point));
  367. if (frameCheckResult === "error:notconnected" || "hitTargetDescription" in frameCheckResult)
  368. return frameCheckResult;
  369. const hitPoint = frameCheckResult.framePoint;
  370. const actionType = actionName === "move and up" ? "drag" : actionName === "hover" || actionName === "tap" ? actionName : "mouse";
  371. const handle = await progress.race(this.evaluateHandleInUtility(([injected, node, { actionType: actionType2, hitPoint: hitPoint2, trial }]) => injected.setupHitTargetInterceptor(node, actionType2, hitPoint2, trial), { actionType, hitPoint, trial: !!options.trial }));
  372. if (handle === "error:notconnected")
  373. return handle;
  374. if (!handle._objectId) {
  375. const error = handle.rawValue();
  376. if (error === "error:notconnected")
  377. return error;
  378. return { hitTargetDescription: error };
  379. }
  380. hitTargetInterceptionHandle = handle;
  381. }
  382. const actionResult = await this._page.frameManager.waitForSignalsCreatedBy(progress, options.waitAfter === true, async () => {
  383. if (options.__testHookBeforePointerAction)
  384. await progress.race(options.__testHookBeforePointerAction());
  385. let restoreModifiers;
  386. if (options && options.modifiers)
  387. restoreModifiers = await this._page.keyboard.ensureModifiers(progress, options.modifiers);
  388. progress.log(` performing ${actionName} action`);
  389. await action(point);
  390. if (restoreModifiers)
  391. await this._page.keyboard.ensureModifiers(progress, restoreModifiers);
  392. if (hitTargetInterceptionHandle) {
  393. const stopHitTargetInterception = this._frame.raceAgainstEvaluationStallingEvents(() => {
  394. return hitTargetInterceptionHandle.evaluate((h) => h.stop());
  395. }).catch((e) => "done").finally(() => {
  396. hitTargetInterceptionHandle?.dispose();
  397. });
  398. if (options.waitAfter !== false) {
  399. const hitTargetResult = await progress.race(stopHitTargetInterception);
  400. if (hitTargetResult !== "done")
  401. return hitTargetResult;
  402. }
  403. }
  404. progress.log(` ${options.trial ? "trial " : ""}${actionName} action done`);
  405. progress.log(" waiting for scheduled navigations to finish");
  406. if (options.__testHookAfterPointerAction)
  407. await progress.race(options.__testHookAfterPointerAction());
  408. return "done";
  409. }).finally(() => {
  410. const stopPromise = hitTargetInterceptionHandle?.evaluate((h) => h.stop()).catch(() => {
  411. });
  412. stopPromise?.then(() => hitTargetInterceptionHandle?.dispose());
  413. });
  414. if (actionResult !== "done")
  415. return actionResult;
  416. progress.log(" navigations have finished");
  417. return "done";
  418. }
  419. async _markAsTargetElement(progress) {
  420. if (!progress.metadata.id)
  421. return;
  422. await progress.race(this.evaluateInUtility(([injected, node, callId]) => {
  423. if (node.nodeType === 1)
  424. injected.markTargetElements(/* @__PURE__ */ new Set([node]), callId);
  425. }, progress.metadata.id));
  426. }
  427. async hover(progress, options) {
  428. await this._markAsTargetElement(progress);
  429. const result = await this._hover(progress, options);
  430. return assertDone(throwRetargetableDOMError(result));
  431. }
  432. _hover(progress, options) {
  433. return this._retryPointerAction(progress, "hover", false, (point) => this._page.mouse.move(progress, point.x, point.y), { ...options, waitAfter: "disabled" });
  434. }
  435. async click(progress, options) {
  436. await this._markAsTargetElement(progress);
  437. const result = await this._click(progress, { ...options, waitAfter: !options.noWaitAfter });
  438. return assertDone(throwRetargetableDOMError(result));
  439. }
  440. _click(progress, options) {
  441. return this._retryPointerAction(progress, "click", true, (point) => this._page.mouse.click(progress, point.x, point.y, options), options);
  442. }
  443. async dblclick(progress, options) {
  444. await this._markAsTargetElement(progress);
  445. const result = await this._dblclick(progress, options);
  446. return assertDone(throwRetargetableDOMError(result));
  447. }
  448. _dblclick(progress, options) {
  449. return this._retryPointerAction(progress, "dblclick", true, (point) => this._page.mouse.click(progress, point.x, point.y, { ...options, clickCount: 2 }), { ...options, waitAfter: "disabled" });
  450. }
  451. async tap(progress, options) {
  452. await this._markAsTargetElement(progress);
  453. const result = await this._tap(progress, options);
  454. return assertDone(throwRetargetableDOMError(result));
  455. }
  456. _tap(progress, options) {
  457. return this._retryPointerAction(progress, "tap", true, (point) => this._page.touchscreen.tap(progress, point.x, point.y), { ...options, waitAfter: "disabled" });
  458. }
  459. async selectOption(progress, elements, values, options) {
  460. await this._markAsTargetElement(progress);
  461. const result = await this._selectOption(progress, elements, values, options);
  462. return throwRetargetableDOMError(result);
  463. }
  464. async _selectOption(progress, elements, values, options) {
  465. let resultingOptions = [];
  466. const result = await this._retryAction(progress, "select option", async () => {
  467. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  468. if (!options.force)
  469. progress.log(` waiting for element to be visible and enabled`);
  470. const optionsToSelect = [...elements, ...values];
  471. const result2 = await progress.race(this.evaluateInUtility(async ([injected, node, { optionsToSelect: optionsToSelect2, force }]) => {
  472. if (!force) {
  473. const checkResult = await injected.checkElementStates(node, ["visible", "enabled"]);
  474. if (checkResult)
  475. return checkResult;
  476. }
  477. return injected.selectOptions(node, optionsToSelect2);
  478. }, { optionsToSelect, force: options.force }));
  479. if (Array.isArray(result2)) {
  480. progress.log(" selected specified option(s)");
  481. resultingOptions = result2;
  482. return "done";
  483. }
  484. return result2;
  485. }, options);
  486. if (result === "error:notconnected")
  487. return result;
  488. return resultingOptions;
  489. }
  490. async fill(progress, value, options) {
  491. await this._markAsTargetElement(progress);
  492. const result = await this._fill(progress, value, options);
  493. assertDone(throwRetargetableDOMError(result));
  494. }
  495. async _fill(progress, value, options) {
  496. progress.log(` fill("${value}")`);
  497. return await this._retryAction(progress, "fill", async () => {
  498. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  499. if (!options.force)
  500. progress.log(" waiting for element to be visible, enabled and editable");
  501. const result = await progress.race(this.evaluateInUtility(async ([injected, node, { value: value2, force }]) => {
  502. if (!force) {
  503. const checkResult = await injected.checkElementStates(node, ["visible", "enabled", "editable"]);
  504. if (checkResult)
  505. return checkResult;
  506. }
  507. return injected.fill(node, value2);
  508. }, { value, force: options.force }));
  509. if (result === "needsinput") {
  510. if (value)
  511. await this._page.keyboard.insertText(progress, value);
  512. else
  513. await this._page.keyboard.press(progress, "Delete");
  514. return "done";
  515. } else {
  516. return result;
  517. }
  518. }, options);
  519. }
  520. async selectText(progress, options) {
  521. const result = await this._retryAction(progress, "selectText", async () => {
  522. if (!options.force)
  523. progress.log(" waiting for element to be visible");
  524. return await progress.race(this.evaluateInUtility(async ([injected, node, { force }]) => {
  525. if (!force) {
  526. const checkResult = await injected.checkElementStates(node, ["visible"]);
  527. if (checkResult)
  528. return checkResult;
  529. }
  530. return injected.selectText(node);
  531. }, { force: options.force }));
  532. }, options);
  533. assertDone(throwRetargetableDOMError(result));
  534. }
  535. async setInputFiles(progress, params) {
  536. const inputFileItems = await progress.race((0, import_fileUploadUtils.prepareFilesForUpload)(this._frame, params));
  537. await this._markAsTargetElement(progress);
  538. const result = await this._setInputFiles(progress, inputFileItems);
  539. return assertDone(throwRetargetableDOMError(result));
  540. }
  541. async _setInputFiles(progress, items) {
  542. const { filePayloads, localPaths, localDirectory } = items;
  543. const multiple = filePayloads && filePayloads.length > 1 || localPaths && localPaths.length > 1;
  544. const result = await progress.race(this.evaluateHandleInUtility(([injected, node, { multiple: multiple2, directoryUpload }]) => {
  545. const element = injected.retarget(node, "follow-label");
  546. if (!element)
  547. return;
  548. if (element.tagName !== "INPUT")
  549. throw injected.createStacklessError("Node is not an HTMLInputElement");
  550. const inputElement = element;
  551. if (multiple2 && !inputElement.multiple && !inputElement.webkitdirectory)
  552. throw injected.createStacklessError("Non-multiple file input can only accept single file");
  553. if (directoryUpload && !inputElement.webkitdirectory)
  554. throw injected.createStacklessError("File input does not support directories, pass individual files instead");
  555. if (!directoryUpload && inputElement.webkitdirectory)
  556. throw injected.createStacklessError("[webkitdirectory] input requires passing a path to a directory");
  557. return inputElement;
  558. }, { multiple, directoryUpload: !!localDirectory }));
  559. if (result === "error:notconnected" || !result.asElement())
  560. return "error:notconnected";
  561. const retargeted = result.asElement();
  562. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  563. if (localPaths || localDirectory) {
  564. const localPathsOrDirectory = localDirectory ? [localDirectory] : localPaths;
  565. await progress.race(Promise.all(localPathsOrDirectory.map((localPath) => import_fs.default.promises.access(localPath, import_fs.default.constants.F_OK))));
  566. const waitForInputEvent = localDirectory ? this.evaluate((node) => new Promise((fulfill) => {
  567. node.addEventListener("input", fulfill, { once: true });
  568. })).catch(() => {
  569. }) : Promise.resolve();
  570. await progress.race(this._page.delegate.setInputFilePaths(retargeted, localPathsOrDirectory));
  571. await progress.race(waitForInputEvent);
  572. } else {
  573. await progress.race(retargeted.evaluateInUtility(([injected, node, files]) => injected.setInputFiles(node, files), filePayloads));
  574. }
  575. return "done";
  576. }
  577. async focus(progress) {
  578. await this._markAsTargetElement(progress);
  579. const result = await this._focus(progress);
  580. return assertDone(throwRetargetableDOMError(result));
  581. }
  582. async _focus(progress, resetSelectionIfNotFocused) {
  583. return await progress.race(this.evaluateInUtility(([injected, node, resetSelectionIfNotFocused2]) => injected.focusNode(node, resetSelectionIfNotFocused2), resetSelectionIfNotFocused));
  584. }
  585. async _blur(progress) {
  586. return await progress.race(this.evaluateInUtility(([injected, node]) => injected.blurNode(node), {}));
  587. }
  588. async type(progress, text, options) {
  589. await this._markAsTargetElement(progress);
  590. const result = await this._type(progress, text, options);
  591. return assertDone(throwRetargetableDOMError(result));
  592. }
  593. async _type(progress, text, options) {
  594. progress.log(`elementHandle.type("${text}")`);
  595. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  596. const result = await this._focus(
  597. progress,
  598. true
  599. /* resetSelectionIfNotFocused */
  600. );
  601. if (result !== "done")
  602. return result;
  603. await this._page.keyboard.type(progress, text, options);
  604. return "done";
  605. }
  606. async press(progress, key, options) {
  607. await this._markAsTargetElement(progress);
  608. const result = await this._press(progress, key, options);
  609. return assertDone(throwRetargetableDOMError(result));
  610. }
  611. async _press(progress, key, options) {
  612. progress.log(`elementHandle.press("${key}")`);
  613. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  614. return this._page.frameManager.waitForSignalsCreatedBy(progress, !options.noWaitAfter, async () => {
  615. const result = await this._focus(
  616. progress,
  617. true
  618. /* resetSelectionIfNotFocused */
  619. );
  620. if (result !== "done")
  621. return result;
  622. await this._page.keyboard.press(progress, key, options);
  623. return "done";
  624. });
  625. }
  626. async check(progress, options) {
  627. const result = await this._setChecked(progress, true, options);
  628. return assertDone(throwRetargetableDOMError(result));
  629. }
  630. async uncheck(progress, options) {
  631. const result = await this._setChecked(progress, false, options);
  632. return assertDone(throwRetargetableDOMError(result));
  633. }
  634. async _setChecked(progress, state, options) {
  635. const isChecked = async () => {
  636. const result2 = await progress.race(this.evaluateInUtility(([injected, node]) => injected.elementState(node, "checked"), {}));
  637. if (result2 === "error:notconnected" || result2.received === "error:notconnected")
  638. throwElementIsNotAttached();
  639. return { matches: result2.matches, isRadio: result2.isRadio };
  640. };
  641. await this._markAsTargetElement(progress);
  642. const checkedState = await isChecked();
  643. if (checkedState.matches === state)
  644. return "done";
  645. if (!state && checkedState.isRadio)
  646. throw new NonRecoverableDOMError("Cannot uncheck radio button. Radio buttons can only be unchecked by selecting another radio button in the same group.");
  647. const result = await this._click(progress, { ...options, waitAfter: "disabled" });
  648. if (result !== "done")
  649. return result;
  650. if (options.trial)
  651. return "done";
  652. const finalState = await isChecked();
  653. if (finalState.matches !== state)
  654. throw new NonRecoverableDOMError("Clicking the checkbox did not change its state");
  655. return "done";
  656. }
  657. async boundingBox() {
  658. return this._page.delegate.getBoundingBox(this);
  659. }
  660. async ariaSnapshot() {
  661. return await this.evaluateInUtility(([injected, element]) => injected.ariaSnapshot(element, { mode: "expect" }), {});
  662. }
  663. async screenshot(progress, options) {
  664. return await this._page.screenshotter.screenshotElement(progress, this, options);
  665. }
  666. async querySelector(selector, options) {
  667. return this._frame.selectors.query(selector, options, this);
  668. }
  669. async querySelectorAll(selector) {
  670. return this._frame.selectors.queryAll(selector, this);
  671. }
  672. async evalOnSelector(selector, strict, expression, isFunction, arg) {
  673. return this._frame.evalOnSelector(selector, strict, expression, isFunction, arg, this);
  674. }
  675. async evalOnSelectorAll(selector, expression, isFunction, arg) {
  676. return this._frame.evalOnSelectorAll(selector, expression, isFunction, arg, this);
  677. }
  678. async isVisible(progress) {
  679. return this._frame.isVisible(progress, ":scope", {}, this);
  680. }
  681. async isHidden(progress) {
  682. return this._frame.isHidden(progress, ":scope", {}, this);
  683. }
  684. async isEnabled(progress) {
  685. return this._frame.isEnabled(progress, ":scope", {}, this);
  686. }
  687. async isDisabled(progress) {
  688. return this._frame.isDisabled(progress, ":scope", {}, this);
  689. }
  690. async isEditable(progress) {
  691. return this._frame.isEditable(progress, ":scope", {}, this);
  692. }
  693. async isChecked(progress) {
  694. return this._frame.isChecked(progress, ":scope", {}, this);
  695. }
  696. async waitForElementState(progress, state) {
  697. const actionName = `wait for ${state}`;
  698. const result = await this._retryAction(progress, actionName, async () => {
  699. return await progress.race(this.evaluateInUtility(async ([injected, node, state2]) => {
  700. return await injected.checkElementStates(node, [state2]) || "done";
  701. }, state));
  702. }, {});
  703. assertDone(throwRetargetableDOMError(result));
  704. }
  705. async waitForSelector(progress, selector, options) {
  706. return await this._frame.waitForSelector(progress, selector, true, options, this);
  707. }
  708. async _adoptTo(context) {
  709. if (this._context !== context) {
  710. const adopted = await this._page.delegate.adoptElementHandle(this, context);
  711. this.dispose();
  712. return adopted;
  713. }
  714. return this;
  715. }
  716. async _checkFrameIsHitTarget(point) {
  717. let frame = this._frame;
  718. const data = [];
  719. while (frame.parentFrame()) {
  720. const frameElement = await frame.frameElement();
  721. const box = await frameElement.boundingBox();
  722. const style = await frameElement.evaluateInUtility(([injected, iframe]) => injected.describeIFrameStyle(iframe), {}).catch((e) => "error:notconnected");
  723. if (!box || style === "error:notconnected")
  724. return "error:notconnected";
  725. if (style === "transformed") {
  726. return { framePoint: void 0 };
  727. }
  728. const pointInFrame = { x: point.x - box.x - style.left, y: point.y - box.y - style.top };
  729. data.push({ frame, frameElement, pointInFrame });
  730. frame = frame.parentFrame();
  731. }
  732. data.push({ frame, frameElement: null, pointInFrame: point });
  733. for (let i = data.length - 1; i > 0; i--) {
  734. const element = data[i - 1].frameElement;
  735. const point2 = data[i].pointInFrame;
  736. const hitTargetResult = await element.evaluateInUtility(([injected, element2, hitPoint]) => {
  737. return injected.expectHitTarget(hitPoint, element2);
  738. }, point2);
  739. if (hitTargetResult !== "done")
  740. return hitTargetResult;
  741. }
  742. return { framePoint: data[0].pointInFrame };
  743. }
  744. }
  745. function throwRetargetableDOMError(result) {
  746. if (result === "error:notconnected")
  747. throwElementIsNotAttached();
  748. return result;
  749. }
  750. function throwElementIsNotAttached() {
  751. throw new Error("Element is not attached to the DOM");
  752. }
  753. function assertDone(result) {
  754. }
  755. function roundPoint(point) {
  756. return {
  757. x: (point.x * 100 | 0) / 100,
  758. y: (point.y * 100 | 0) / 100
  759. };
  760. }
  761. function quadMiddlePoint(quad) {
  762. const result = { x: 0, y: 0 };
  763. for (const point of quad) {
  764. result.x += point.x / 4;
  765. result.y += point.y / 4;
  766. }
  767. return result;
  768. }
  769. function triangleArea(p1, p2, p3) {
  770. return Math.abs(p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y)) / 2;
  771. }
  772. function isPointInsideQuad(point, quad) {
  773. const area1 = triangleArea(point, quad[0], quad[1]) + triangleArea(point, quad[1], quad[2]) + triangleArea(point, quad[2], quad[3]) + triangleArea(point, quad[3], quad[0]);
  774. const area2 = triangleArea(quad[0], quad[1], quad[2]) + triangleArea(quad[1], quad[2], quad[3]);
  775. if (Math.abs(area1 - area2) > 0.1)
  776. return false;
  777. return point.x < Math.max(quad[0].x, quad[1].x, quad[2].x, quad[3].x) && point.y < Math.max(quad[0].y, quad[1].y, quad[2].y, quad[3].y);
  778. }
  779. function findIntegerPointInsideQuad(quad) {
  780. const point = quadMiddlePoint(quad);
  781. point.x = Math.floor(point.x);
  782. point.y = Math.floor(point.y);
  783. if (isPointInsideQuad(point, quad))
  784. return point;
  785. point.x += 1;
  786. if (isPointInsideQuad(point, quad))
  787. return point;
  788. point.y += 1;
  789. if (isPointInsideQuad(point, quad))
  790. return point;
  791. point.x -= 1;
  792. if (isPointInsideQuad(point, quad))
  793. return point;
  794. }
  795. const kUnableToAdoptErrorMessage = "Unable to adopt element handle from a different document";
  796. // Annotate the CommonJS export names for ESM import in node:
  797. 0 && (module.exports = {
  798. ElementHandle,
  799. FrameExecutionContext,
  800. NonRecoverableDOMError,
  801. assertDone,
  802. isNonRecoverableDOMError,
  803. kUnableToAdoptErrorMessage,
  804. throwElementIsNotAttached,
  805. throwRetargetableDOMError
  806. });