Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions packages/injected/src/utilityScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

import { parseEvaluationResultValue, serializeAsCallArgument } from '@isomorphic/utilityScriptSerializers';

import type { SerializedValue } from '@isomorphic/utilityScriptSerializers';

// Keep in sync with eslint.config.mjs
export type Builtins = {
setTimeout: Window['setTimeout'],
Expand Down Expand Up @@ -65,9 +67,7 @@ export class UtilityScript {
(global as any).builtins = this.builtins;
}

evaluate(isFunction: boolean | undefined, returnByValue: boolean, expression: string, argCount: number, ...argsAndHandles: any[]) {
const args = argsAndHandles.slice(0, argCount);
const handles = argsAndHandles.slice(argCount);
evaluate(isFunction: boolean | undefined, returnByValue: boolean, expression: string, args: SerializedValue[], handles: any[]) {
const parameters = [];
for (let i = 0; i < args.length; i++)
parameters[i] = parseEvaluationResultValue(args[i], handles);
Expand Down Expand Up @@ -95,7 +95,7 @@ export class UtilityScript {
return returnByValue ? this._jsonValueNoThrow(result) : result;
}

jsonValue(returnByValue: true, value: any) {
jsonValue(value: any) {
// Special handling of undefined to work-around multi-step returnByValue handling in WebKit.
if (value === undefined)
return undefined;
Expand All @@ -104,7 +104,7 @@ export class UtilityScript {

private _jsonValueNoThrow(value: any) {
try {
return this.jsonValue(true, value);
return this.jsonValue(value);
} catch (e) {
return undefined;
}
Expand Down
142 changes: 82 additions & 60 deletions packages/isomorphic/utilityScriptSerializers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ export const kFunctionBindingPrefix = '__pw_fn_';

export const kBindingsControllerProperty = '__playwright__binding__controller__';

// Arrays, objects, maps and sets are arrays that start with a tag,
// so that the serialized value is as deep as the original value, and not deeper:
// - ['a', item1, item2, ...] is an array;
// - ['o', key1, value1, key2, value2, ...] is an object;
// - ['m', key1, value1, key2, value2, ...] is a map;
// - ['s', item1, item2, ...] is a set.
// Each of them gets the next number, starting with 1, in the order of serialization,
// and { ref: number } refers to the one that was serialized before.
export type SerializedValue =
undefined | boolean | number | string |
{ v: 'null' | 'undefined' | 'NaN' | 'Infinity' | '-Infinity' | '-0' } |
Expand All @@ -31,10 +39,7 @@ export type SerializedValue =
{ bi: string } |
{ e: { n: string, m: string, s: string } } |
{ r: { p: string, f: string } } |
{ a: SerializedValue[], id: number } |
{ o: { k: string, v: SerializedValue }[], id: number } |
{ m: { k: SerializedValue, v: SerializedValue }[], id: number } |
{ s: SerializedValue[], id: number } |
['a' | 'o' | 'm' | 's', ...SerializedValue[]] |
{ ref: number } |
{ h: number } |
{ fn: string } |
Expand Down Expand Up @@ -148,12 +153,53 @@ function base64ToTypedArray(base64: string, TypedArrayConstructor: any) {
return new TypedArrayConstructor(bytes.buffer);
}

export function parseEvaluationResultValue(value: SerializedValue, handles: any[] = [], refs: Map<number, object> = new Map()): any {
// |refs| has the arrays, objects, maps and sets that are parsed so far, in the order of serialization.
// Arrays are filled by index, because the page can break Array.prototype.push.
export function parseEvaluationResultValue(value: SerializedValue, handles: any[] = [], refs: object[] = []): any {
if (Object.is(value, undefined))
return undefined;
if (Array.isArray(value)) {
const tag = value[0];
if (tag === 'a') {
const result: any[] = [];
refs[refs.length] = result;
for (let i = 1; i < value.length; i++)
result[i - 1] = parseEvaluationResultValue(value[i], handles, refs);
return result;
}
if (tag === 'o') {
const result: any = {};
refs[refs.length] = result;
for (let i = 1; i < value.length; i += 2) {
const k = value[i] as string;
// Parse the value in any case, to keep the numbers in sync with the serializer.
const v = parseEvaluationResultValue(value[i + 1], handles, refs);
if (k !== '__proto__')
result[k] = v;
}
return result;
}
if (tag === 'm') {
const result = new Map();
refs[refs.length] = result;
for (let i = 1; i < value.length; i += 2) {
const k = parseEvaluationResultValue(value[i], handles, refs);
result.set(k, parseEvaluationResultValue(value[i + 1], handles, refs));
}
return result;
}
if (tag === 's') {
const result = new Set();
refs[refs.length] = result;
for (let i = 1; i < value.length; i++)
result.add(parseEvaluationResultValue(value[i], handles, refs));
return result;
}
return undefined;
}
if (typeof value === 'object' && value) {
if ('ref' in value)
return refs.get(value.ref);
return refs[value.ref - 1];
if ('v' in value) {
if (value.v === 'undefined')
return undefined;
Expand Down Expand Up @@ -185,37 +231,6 @@ export function parseEvaluationResultValue(value: SerializedValue, handles: any[
}
if ('r' in value)
return new RegExp(value.r.p, value.r.f);
if ('a' in value) {
const result: any[] = [];
refs.set(value.id, result);
for (const a of value.a)
result.push(parseEvaluationResultValue(a, handles, refs));
return result;
}
if ('o' in value) {
const result: any = {};
refs.set(value.id, result);
for (const { k, v } of value.o) {
if (k === '__proto__')
continue;
result[k] = parseEvaluationResultValue(v, handles, refs);
}
return result;
}
if ('m' in value) {
const result = new Map();
refs.set(value.id, result);
for (const { k, v } of value.m)
result.set(parseEvaluationResultValue(k, handles, refs), parseEvaluationResultValue(v, handles, refs));
return result;
}
if ('s' in value) {
const result = new Set();
refs.set(value.id, result);
for (const item of value.s)
result.add(parseEvaluationResultValue(item, handles, refs));
return result;
}
if ('h' in value)
return handles[value.h];
if ('fn' in value) {
Expand Down Expand Up @@ -310,23 +325,21 @@ function innerSerialize(value: any, handleSerializer: (value: any) => HandleOrVa

if (visitorInfo.extendedSerialization) {
if (isMap(value)) {
const m: { k: SerializedValue, v: SerializedValue }[] = [];
const id = ++visitorInfo.lastId;
visitorInfo.visited.set(value, id);
const m: SerializedValue = ['m'];
visitorInfo.visited.set(value, ++visitorInfo.lastId);
const iterator = value.entries();
const next = new Map().entries().next;
while (true) {
const entry = next.call(iterator);
if (entry.done)
break;
m.push({ k: serialize(entry.value[0], handleSerializer, visitorInfo), v: serialize(entry.value[1], handleSerializer, visitorInfo) });
m.push(serialize(entry.value[0], handleSerializer, visitorInfo), serialize(entry.value[1], handleSerializer, visitorInfo));
}
return { m, id };
return m;
}
if (isSet(value)) {
const s: SerializedValue[] = [];
const id = ++visitorInfo.lastId;
visitorInfo.visited.set(value, id);
const s: SerializedValue = ['s'];
visitorInfo.visited.set(value, ++visitorInfo.lastId);
const iterator = value.values();
const next = new Set().values().next;
while (true) {
Expand All @@ -335,49 +348,58 @@ function innerSerialize(value: any, handleSerializer: (value: any) => HandleOrVa
break;
s.push(serialize(entry.value, handleSerializer, visitorInfo));
}
return { s, id };
return s;
}
}

if (Array.isArray(value)) {
const a = [];
const id = ++visitorInfo.lastId;
visitorInfo.visited.set(value, id);
const a: SerializedValue = ['a'];
visitorInfo.visited.set(value, ++visitorInfo.lastId);
for (let i = 0; i < value.length; ++i)
a.push(serialize(value[i], handleSerializer, visitorInfo));
return { a, id };
return a;
}

if (typeof value === 'object') {
const o: { k: string, v: SerializedValue }[] = [];
const id = ++visitorInfo.lastId;
visitorInfo.visited.set(value, id);
const o: SerializedValue = ['o'];
visitorInfo.visited.set(value, ++visitorInfo.lastId);
for (const name of Object.keys(value)) {
let item;
try {
item = value[name];
} catch (e) {
continue; // native bindings will throw sometimes
}
if (name === 'toJSON' && typeof item === 'function')
o.push({ k: name, v: { o: [], id: 0 } });
else
o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });
if (name === 'toJSON' && typeof item === 'function') {
// An empty object, that takes a number like any other object.
++visitorInfo.lastId;
o.push(name, ['o']);
} else {
o.push(name, serialize(item, handleSerializer, visitorInfo));
}
}

let jsonWrapper;
try {
// If Object.keys().length === 0 we fall back to toJSON if it exists
if (o.length === 0 && value.toJSON && typeof value.toJSON === 'function')
if (o.length === 1 && value.toJSON && typeof value.toJSON === 'function')
jsonWrapper = { value: value.toJSON() };
} catch (e) {
}
if (jsonWrapper)
if (jsonWrapper) {
// This object is not in the result, so it must not take a number.
visitorInfo.visited.delete(value);
--visitorInfo.lastId;
return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);
}

return { o, id };
return o;
}

if (typeof value === 'function' && value.name.startsWith(kFunctionBindingPrefix))
return { fn: value.name };

// Other functions are not serializable. JSON turns a bare undefined inside an array into null,
// so the value is explicit.
return { v: 'undefined' };
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@
* limitations under the License.
*/

import { parseEvaluationResultValue } from '@isomorphic/utilityScriptSerializers';
import { assert } from '@isomorphic/assert';
import * as js from '../javascript';
import * as dom from '../dom';
import * as bidi from './third_party/bidiProtocol';
import { BidiSerializer } from './third_party/bidiSerializer';
import { deserializeBidiValue } from './bidiDeserializer';

import type { BidiSession } from './bidiConnection';
Expand Down Expand Up @@ -80,13 +78,12 @@ export class BidiExecutionContext implements js.ExecutionContextDelegate {
throw new js.JavaScriptErrorInEvaluate('Unexpected response type: ' + JSON.stringify(response));
}

async evaluateWithArguments(functionDeclaration: string, returnByValue: boolean, utilityScript: js.JSHandle, values: any[], handles: js.JSHandle[]): Promise<any> {
async callFunction(functionDeclaration: string, returnByValue: boolean, utilityScript: js.JSHandle, handles: js.JSHandle[]): Promise<any> {
const response = await this._session.send('script.callFunction', {
functionDeclaration,
target: this._target,
arguments: [
{ handle: utilityScript._objectId! },
...values.map(BidiSerializer.serialize),
...handles.map(handle => ({ handle: handle._objectId! })),
],
resultOwnership: returnByValue ? undefined : bidi.Script.ResultOwnership.Root, // Necessary for the handle to be returned.
Expand All @@ -98,7 +95,7 @@ export class BidiExecutionContext implements js.ExecutionContextDelegate {
throw new js.JavaScriptErrorInEvaluate(response.exceptionDetails.text);
if (response.type === 'success') {
if (returnByValue)
return parseEvaluationResultValue(deserializeBidiValue(response.result));
return deserializeBidiValue(response.result);
return createHandle(utilityScript._context, response.result);
}
throw new js.JavaScriptErrorInEvaluate('Unexpected response type: ' + JSON.stringify(response));
Expand Down
Loading
Loading