javascript.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 javascript_exports = {};
  30. __export(javascript_exports, {
  31. ExecutionContext: () => ExecutionContext,
  32. JSHandle: () => JSHandle,
  33. JavaScriptErrorInEvaluate: () => JavaScriptErrorInEvaluate,
  34. evaluate: () => evaluate,
  35. evaluateExpression: () => evaluateExpression,
  36. isJavaScriptErrorInEvaluate: () => isJavaScriptErrorInEvaluate,
  37. normalizeEvaluationExpression: () => normalizeEvaluationExpression,
  38. parseUnserializableValue: () => parseUnserializableValue,
  39. sparseArrayToString: () => sparseArrayToString
  40. });
  41. module.exports = __toCommonJS(javascript_exports);
  42. var import_instrumentation = require("./instrumentation");
  43. var rawUtilityScriptSource = __toESM(require("../generated/utilityScriptSource"));
  44. var import_utils = require("../utils");
  45. var import_utilityScriptSerializers = require("../utils/isomorphic/utilityScriptSerializers");
  46. var import_manualPromise = require("../utils/isomorphic/manualPromise");
  47. class ExecutionContext extends import_instrumentation.SdkObject {
  48. constructor(parent, delegate, worldNameForTest) {
  49. super(parent, "execution-context");
  50. this._contextDestroyedScope = new import_manualPromise.LongStandingScope();
  51. this.worldNameForTest = worldNameForTest;
  52. this.delegate = delegate;
  53. }
  54. contextDestroyed(reason) {
  55. this._contextDestroyedScope.close(new Error(reason));
  56. }
  57. async _raceAgainstContextDestroyed(promise) {
  58. return this._contextDestroyedScope.race(promise);
  59. }
  60. rawEvaluateJSON(expression) {
  61. return this._raceAgainstContextDestroyed(this.delegate.rawEvaluateJSON(expression));
  62. }
  63. rawEvaluateHandle(expression) {
  64. return this._raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, expression));
  65. }
  66. async evaluateWithArguments(expression, returnByValue, values, handles) {
  67. const utilityScript = await this.utilityScript();
  68. return this._raceAgainstContextDestroyed(this.delegate.evaluateWithArguments(expression, returnByValue, utilityScript, values, handles));
  69. }
  70. getProperties(object) {
  71. return this._raceAgainstContextDestroyed(this.delegate.getProperties(object));
  72. }
  73. releaseHandle(handle) {
  74. return this.delegate.releaseHandle(handle);
  75. }
  76. adoptIfNeeded(handle) {
  77. return null;
  78. }
  79. utilityScript() {
  80. if (!this._utilityScriptPromise) {
  81. const source = `
  82. (() => {
  83. const module = {};
  84. ${rawUtilityScriptSource.source}
  85. return new (module.exports.UtilityScript())(globalThis, ${(0, import_utils.isUnderTest)()});
  86. })();`;
  87. this._utilityScriptPromise = this._raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, source)).then((handle) => {
  88. handle._setPreview("UtilityScript");
  89. return handle;
  90. });
  91. }
  92. return this._utilityScriptPromise;
  93. }
  94. async doSlowMo() {
  95. }
  96. }
  97. class JSHandle extends import_instrumentation.SdkObject {
  98. constructor(context, type, preview, objectId, value) {
  99. super(context, "handle");
  100. this.__jshandle = true;
  101. this._disposed = false;
  102. this._context = context;
  103. this._objectId = objectId;
  104. this._value = value;
  105. this._objectType = type;
  106. this._preview = this._objectId ? preview || `JSHandle@${this._objectType}` : String(value);
  107. if (this._objectId && globalThis.leakedJSHandles)
  108. globalThis.leakedJSHandles.set(this, new Error("Leaked JSHandle"));
  109. }
  110. async evaluate(pageFunction, arg) {
  111. return evaluate(this._context, true, pageFunction, this, arg);
  112. }
  113. async evaluateHandle(pageFunction, arg) {
  114. return evaluate(this._context, false, pageFunction, this, arg);
  115. }
  116. async evaluateExpression(expression, options, arg) {
  117. const value = await evaluateExpression(this._context, expression, { ...options, returnByValue: true }, this, arg);
  118. await this._context.doSlowMo();
  119. return value;
  120. }
  121. async evaluateExpressionHandle(expression, options, arg) {
  122. const value = await evaluateExpression(this._context, expression, { ...options, returnByValue: false }, this, arg);
  123. await this._context.doSlowMo();
  124. return value;
  125. }
  126. async getProperty(propertyName) {
  127. const objectHandle = await this.evaluateHandle((object, propertyName2) => {
  128. const result2 = { __proto__: null };
  129. result2[propertyName2] = object[propertyName2];
  130. return result2;
  131. }, propertyName);
  132. const properties = await objectHandle.getProperties();
  133. const result = properties.get(propertyName);
  134. objectHandle.dispose();
  135. return result;
  136. }
  137. async getProperties() {
  138. if (!this._objectId)
  139. return /* @__PURE__ */ new Map();
  140. return this._context.getProperties(this);
  141. }
  142. rawValue() {
  143. return this._value;
  144. }
  145. async jsonValue() {
  146. if (!this._objectId)
  147. return this._value;
  148. const script = `(utilityScript, ...args) => utilityScript.jsonValue(...args)`;
  149. return this._context.evaluateWithArguments(script, true, [true], [this]);
  150. }
  151. asElement() {
  152. return null;
  153. }
  154. dispose() {
  155. if (this._disposed)
  156. return;
  157. this._disposed = true;
  158. if (this._objectId) {
  159. this._context.releaseHandle(this).catch((e) => {
  160. });
  161. if (globalThis.leakedJSHandles)
  162. globalThis.leakedJSHandles.delete(this);
  163. }
  164. }
  165. toString() {
  166. return this._preview;
  167. }
  168. _setPreviewCallback(callback) {
  169. this._previewCallback = callback;
  170. }
  171. preview() {
  172. return this._preview;
  173. }
  174. worldNameForTest() {
  175. return this._context.worldNameForTest;
  176. }
  177. _setPreview(preview) {
  178. this._preview = preview;
  179. if (this._previewCallback)
  180. this._previewCallback(preview);
  181. }
  182. }
  183. async function evaluate(context, returnByValue, pageFunction, ...args) {
  184. return evaluateExpression(context, String(pageFunction), { returnByValue, isFunction: typeof pageFunction === "function" }, ...args);
  185. }
  186. async function evaluateExpression(context, expression, options, ...args) {
  187. expression = normalizeEvaluationExpression(expression, options.isFunction);
  188. const handles = [];
  189. const toDispose = [];
  190. const pushHandle = (handle) => {
  191. handles.push(handle);
  192. return handles.length - 1;
  193. };
  194. args = args.map((arg) => (0, import_utilityScriptSerializers.serializeAsCallArgument)(arg, (handle) => {
  195. if (handle instanceof JSHandle) {
  196. if (!handle._objectId)
  197. return { fallThrough: handle._value };
  198. if (handle._disposed)
  199. throw new JavaScriptErrorInEvaluate("JSHandle is disposed!");
  200. const adopted = context.adoptIfNeeded(handle);
  201. if (adopted === null)
  202. return { h: pushHandle(Promise.resolve(handle)) };
  203. toDispose.push(adopted);
  204. return { h: pushHandle(adopted) };
  205. }
  206. return { fallThrough: handle };
  207. }));
  208. const utilityScriptObjects = [];
  209. for (const handle of await Promise.all(handles)) {
  210. if (handle._context !== context)
  211. throw new JavaScriptErrorInEvaluate("JSHandles can be evaluated only in the context they were created!");
  212. utilityScriptObjects.push(handle);
  213. }
  214. const utilityScriptValues = [options.isFunction, options.returnByValue, expression, args.length, ...args];
  215. const script = `(utilityScript, ...args) => utilityScript.evaluate(...args)`;
  216. try {
  217. return await context.evaluateWithArguments(script, options.returnByValue || false, utilityScriptValues, utilityScriptObjects);
  218. } finally {
  219. toDispose.map((handlePromise) => handlePromise.then((handle) => handle.dispose()));
  220. }
  221. }
  222. function parseUnserializableValue(unserializableValue) {
  223. if (unserializableValue === "NaN")
  224. return NaN;
  225. if (unserializableValue === "Infinity")
  226. return Infinity;
  227. if (unserializableValue === "-Infinity")
  228. return -Infinity;
  229. if (unserializableValue === "-0")
  230. return -0;
  231. }
  232. function normalizeEvaluationExpression(expression, isFunction) {
  233. expression = expression.trim();
  234. if (isFunction) {
  235. try {
  236. new Function("(" + expression + ")");
  237. } catch (e1) {
  238. if (expression.startsWith("async "))
  239. expression = "async function " + expression.substring("async ".length);
  240. else
  241. expression = "function " + expression;
  242. try {
  243. new Function("(" + expression + ")");
  244. } catch (e2) {
  245. throw new Error("Passed function is not well-serializable!");
  246. }
  247. }
  248. }
  249. if (/^(async)?\s*function(\s|\()/.test(expression))
  250. expression = "(" + expression + ")";
  251. return expression;
  252. }
  253. class JavaScriptErrorInEvaluate extends Error {
  254. }
  255. function isJavaScriptErrorInEvaluate(error) {
  256. return error instanceof JavaScriptErrorInEvaluate;
  257. }
  258. function sparseArrayToString(entries) {
  259. const arrayEntries = [];
  260. for (const { name, value } of entries) {
  261. const index = +name;
  262. if (isNaN(index) || index < 0)
  263. continue;
  264. arrayEntries.push({ index, value });
  265. }
  266. arrayEntries.sort((a, b) => a.index - b.index);
  267. let lastIndex = -1;
  268. const tokens = [];
  269. for (const { index, value } of arrayEntries) {
  270. const emptyItems = index - lastIndex - 1;
  271. if (emptyItems === 1)
  272. tokens.push(`empty`);
  273. else if (emptyItems > 1)
  274. tokens.push(`empty x ${emptyItems}`);
  275. tokens.push(String(value));
  276. lastIndex = index;
  277. }
  278. return "[" + tokens.join(", ") + "]";
  279. }
  280. // Annotate the CommonJS export names for ESM import in node:
  281. 0 && (module.exports = {
  282. ExecutionContext,
  283. JSHandle,
  284. JavaScriptErrorInEvaluate,
  285. evaluate,
  286. evaluateExpression,
  287. isJavaScriptErrorInEvaluate,
  288. normalizeEvaluationExpression,
  289. parseUnserializableValue,
  290. sparseArrayToString
  291. });