Skip to content

Commit 06518b2

Browse files
committed
cherry-pick(#28978): chore: build import registry source
1 parent d47ed6a commit 06518b2

File tree

11 files changed

+203
-144
lines changed

11 files changed

+203
-144
lines changed

.eslintignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ test/assets/modernizr.js
44
/packages/playwright-core/src/generated/*
55
/packages/playwright-core/src/third_party/
66
/packages/playwright-core/types/*
7+
/packages/playwright-ct-core/src/generated/*
78
/index.d.ts
89
utils/generate_types/overrides.d.ts
910
utils/generate_types/test/test.ts

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ node_modules/
99
.vscode
1010
.idea
1111
yarn.lock
12-
/packages/playwright-core/src/generated/*
12+
/packages/playwright-core/src/generated
13+
/packages/playwright-ct-core/src/generated
1314
packages/*/lib/
1415
drivers/
1516
.android-sdk/
Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
1-
[importRegistry.ts]
2-
../types/**
1+
[vitePlugin.ts]
2+
generated/indexSource.ts
3+
4+
[mount.ts]
5+
generated/serializers.ts
6+
injected/**

packages/playwright-ct-core/src/importRegistry.ts

Lines changed: 0 additions & 59 deletions
This file was deleted.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Copyright (c) Microsoft Corporation.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
export type ImportRef = {
18+
__pw_type: 'importRef',
19+
id: string,
20+
property?: string,
21+
};
22+
23+
export function isImportRef(value: any): value is ImportRef {
24+
return typeof value === 'object' && value && value.__pw_type === 'importRef';
25+
}
26+
27+
export class ImportRegistry {
28+
private _registry = new Map<string, () => Promise<any>>();
29+
30+
initialize(components: Record<string, () => Promise<any>>) {
31+
for (const [name, value] of Object.entries(components))
32+
this._registry.set(name, value);
33+
}
34+
35+
async resolveImportRef(importRef: ImportRef): Promise<any> {
36+
const importFunction = this._registry.get(importRef.id);
37+
if (!importFunction)
38+
throw new Error(`Unregistered component: ${importRef.id}. Following components are registered: ${[...this._registry.keys()]}`);
39+
let importedObject = await importFunction();
40+
if (!importedObject)
41+
throw new Error(`Could not resolve component: ${importRef.id}.`);
42+
if (importRef.property) {
43+
importedObject = importedObject[importRef.property];
44+
if (!importedObject)
45+
throw new Error(`Could not instantiate component: ${importRef.id}.${importRef.property}.`);
46+
}
47+
return importedObject;
48+
}
49+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Copyright (c) Microsoft Corporation.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import { ImportRegistry } from './importRegistry';
18+
import { unwrapObject } from './serializers';
19+
20+
window.__pwRegistry = new ImportRegistry();
21+
window.__pwUnwrapObject = unwrapObject;
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* Copyright (c) Microsoft Corporation.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import { isImportRef } from './importRegistry';
18+
19+
type FunctionRef = {
20+
__pw_type: 'function';
21+
ordinal: number;
22+
};
23+
24+
function isFunctionRef(value: any): value is FunctionRef {
25+
return value && typeof value === 'object' && value.__pw_type === 'function';
26+
}
27+
28+
export function wrapObject(value: any, callbacks: Function[]): any {
29+
if (typeof value === 'function') {
30+
const ordinal = callbacks.length;
31+
callbacks.push(value as Function);
32+
const result: FunctionRef = {
33+
__pw_type: 'function',
34+
ordinal,
35+
};
36+
return result;
37+
}
38+
if (value === null || typeof value !== 'object')
39+
return value;
40+
if (Array.isArray(value)) {
41+
const result = [];
42+
for (const item of value)
43+
result.push(wrapObject(item, callbacks));
44+
return result;
45+
}
46+
const result: any = {};
47+
for (const [key, prop] of Object.entries(value))
48+
result[key] = wrapObject(prop, callbacks);
49+
return result;
50+
}
51+
52+
export async function unwrapObject(value: any): Promise<any> {
53+
if (value === null || typeof value !== 'object')
54+
return value;
55+
if (isFunctionRef(value)) {
56+
return (...args: any[]) => {
57+
window.__ctDispatchFunction(value.ordinal, args);
58+
};
59+
}
60+
if (isImportRef(value))
61+
return window.__pwRegistry.resolveImportRef(value);
62+
63+
if (Array.isArray(value)) {
64+
const result = [];
65+
for (const item of value)
66+
result.push(await unwrapObject(item));
67+
return result;
68+
}
69+
const result: any = {};
70+
for (const [key, prop] of Object.entries(value))
71+
result[key] = await unwrapObject(prop);
72+
return result;
73+
}

packages/playwright-ct-core/src/mount.ts

Lines changed: 8 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@
1515
*/
1616

1717
import type { Fixtures, Locator, Page, BrowserContextOptions, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, BrowserContext } from 'playwright/test';
18-
import type { Component, ImportRef, JsxComponent, MountOptions, ObjectComponentOptions } from '../types/component';
18+
import type { Component, JsxComponent, MountOptions, ObjectComponentOptions } from '../types/component';
1919
import type { ContextReuseMode, FullConfigInternal } from '../../playwright/src/common/config';
20+
import type { ImportRef } from './injected/importRegistry';
21+
import { wrapObject } from './injected/serializers';
2022

2123
let boundCallbacksForMount: Function[] = [];
2224

@@ -46,7 +48,7 @@ export const fixtures: Fixtures<TestFixtures, WorkerFixtures, BaseTestFixtures>
4648
if (!((info as any)._configInternal as FullConfigInternal).defineConfigWasUsed)
4749
throw new Error('Component testing requires the use of the defineConfig() in your playwright-ct.config.{ts,js}: https://aka.ms/playwright/ct-define-config');
4850
await (page as any)._wrapApiCall(async () => {
49-
await page.exposeFunction('__ct_dispatch', (ordinal: number, args: any[]) => {
51+
await page.exposeFunction('__ctDispatchFunction', (ordinal: number, args: any[]) => {
5052
boundCallbacksForMount[ordinal](...args);
5153
});
5254
await page.goto(process.env.PLAYWRIGHT_TEST_BASE_URL!);
@@ -83,59 +85,29 @@ function isJsxComponent(component: any): component is JsxComponent {
8385
}
8486

8587
async function innerUpdate(page: Page, componentRef: JsxComponent | ImportRef, options: ObjectComponentOptions = {}): Promise<void> {
86-
const component = createComponent(componentRef, options);
87-
wrapFunctions(component, page, boundCallbacksForMount);
88+
const component = wrapObject(createComponent(componentRef, options), boundCallbacksForMount);
8889

8990
await page.evaluate(async ({ component }) => {
90-
const unwrapFunctions = (object: any) => {
91-
for (const [key, value] of Object.entries(object)) {
92-
if (typeof value === 'string' && (value as string).startsWith('__pw_func_')) {
93-
const ordinal = +value.substring('__pw_func_'.length);
94-
object[key] = (...args: any[]) => {
95-
(window as any)['__ct_dispatch'](ordinal, args);
96-
};
97-
} else if (typeof value === 'object' && value) {
98-
unwrapFunctions(value);
99-
}
100-
}
101-
};
102-
103-
unwrapFunctions(component);
104-
component = await window.__pwRegistry.resolveImports(component);
91+
component = await window.__pwUnwrapObject(component);
10592
const rootElement = document.getElementById('root')!;
10693
return await window.playwrightUpdate(rootElement, component);
10794
}, { component });
10895
}
10996

11097
async function innerMount(page: Page, componentRef: JsxComponent | ImportRef, options: ObjectComponentOptions & MountOptions = {}): Promise<string> {
111-
const component = createComponent(componentRef, options);
112-
wrapFunctions(component, page, boundCallbacksForMount);
98+
const component = wrapObject(createComponent(componentRef, options), boundCallbacksForMount);
11399

114100
// WebKit does not wait for deferred scripts.
115101
await page.waitForFunction(() => !!window.playwrightMount);
116102

117103
const selector = await page.evaluate(async ({ component, hooksConfig }) => {
118-
const unwrapFunctions = (object: any) => {
119-
for (const [key, value] of Object.entries(object)) {
120-
if (typeof value === 'string' && (value as string).startsWith('__pw_func_')) {
121-
const ordinal = +value.substring('__pw_func_'.length);
122-
object[key] = (...args: any[]) => {
123-
(window as any)['__ct_dispatch'](ordinal, args);
124-
};
125-
} else if (typeof value === 'object' && value) {
126-
unwrapFunctions(value);
127-
}
128-
}
129-
};
130-
131-
unwrapFunctions(component);
104+
component = await window.__pwUnwrapObject(component);
132105
let rootElement = document.getElementById('root');
133106
if (!rootElement) {
134107
rootElement = document.createElement('div');
135108
rootElement.id = 'root';
136109
document.body.appendChild(rootElement);
137110
}
138-
component = await window.__pwRegistry.resolveImports(component);
139111
await window.playwrightMount(component, rootElement, hooksConfig);
140112

141113
return '#root >> internal:control=component';
@@ -152,16 +124,3 @@ function createComponent(component: JsxComponent | ImportRef, options: ObjectCom
152124
...options,
153125
};
154126
}
155-
156-
function wrapFunctions(object: any, page: Page, callbacks: Function[]) {
157-
for (const [key, value] of Object.entries(object)) {
158-
const type = typeof value;
159-
if (type === 'function') {
160-
const functionName = '__pw_func_' + callbacks.length;
161-
callbacks.push(value as Function);
162-
object[key] = functionName;
163-
} else if (type === 'object' && value) {
164-
wrapFunctions(value, page, callbacks);
165-
}
166-
}
167-
}

packages/playwright-ct-core/src/vitePlugin.ts

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { getPlaywrightVersion } from 'playwright-core/lib/utils';
3232
import { setExternalDependencies } from 'playwright/lib/transform/compilationCache';
3333
import { collectComponentUsages, importInfo } from './tsxTransform';
3434
import { version as viteVersion, build, preview, mergeConfig } from 'vite';
35+
import { source as injectedSource } from './generated/indexSource';
3536
import type { ImportInfo } from './tsxTransform';
3637

3738
const log = debug('pw:vite');
@@ -115,13 +116,7 @@ export function createPlugin(
115116
let buildExists = false;
116117
let buildInfo: BuildInfo;
117118

118-
const importRegistryFile = await fs.promises.readFile(path.resolve(__dirname, 'importRegistry.js'), 'utf-8');
119-
assert(importRegistryFile.includes(importRegistryPrefix));
120-
assert(importRegistryFile.includes(importRegistrySuffix));
121-
const importRegistrySource = importRegistryFile.replace(importRegistryPrefix, '').replace(importRegistrySuffix, '') + `
122-
window.__pwRegistry = new ImportRegistry();
123-
`;
124-
const registerSource = importRegistrySource + await fs.promises.readFile(registerSourceFile, 'utf-8');
119+
const registerSource = injectedSource + '\n' + await fs.promises.readFile(registerSourceFile, 'utf-8');
125120
const registerSourceHash = calculateSha1(registerSource);
126121

127122
try {
@@ -436,13 +431,3 @@ function hasJSComponents(components: ComponentInfo[]): boolean {
436431
}
437432
return false;
438433
}
439-
440-
441-
const importRegistryPrefix = `"use strict";
442-
443-
Object.defineProperty(exports, "__esModule", {
444-
value: true
445-
});
446-
exports.ImportRegistry = void 0;`;
447-
448-
const importRegistrySuffix = `exports.ImportRegistry = ImportRegistry;`;

0 commit comments

Comments
 (0)