Skip to content

Commit

Permalink
cherry-pick(#28978): chore: build import registry source
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelfeldman committed Jan 18, 2024
1 parent d47ed6a commit 06518b2
Show file tree
Hide file tree
Showing 11 changed files with 203 additions and 144 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ test/assets/modernizr.js
/packages/playwright-core/src/generated/*
/packages/playwright-core/src/third_party/
/packages/playwright-core/types/*
/packages/playwright-ct-core/src/generated/*
/index.d.ts
utils/generate_types/overrides.d.ts
utils/generate_types/test/test.ts
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ node_modules/
.vscode
.idea
yarn.lock
/packages/playwright-core/src/generated/*
/packages/playwright-core/src/generated
/packages/playwright-ct-core/src/generated
packages/*/lib/
drivers/
.android-sdk/
Expand Down
8 changes: 6 additions & 2 deletions packages/playwright-ct-core/src/DEPS.list
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
[importRegistry.ts]
../types/**
[vitePlugin.ts]
generated/indexSource.ts

[mount.ts]
generated/serializers.ts
injected/**
59 changes: 0 additions & 59 deletions packages/playwright-ct-core/src/importRegistry.ts

This file was deleted.

49 changes: 49 additions & 0 deletions packages/playwright-ct-core/src/injected/importRegistry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* 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.
*/

export type ImportRef = {
__pw_type: 'importRef',
id: string,
property?: string,
};

export function isImportRef(value: any): value is ImportRef {
return typeof value === 'object' && value && value.__pw_type === 'importRef';
}

export class ImportRegistry {
private _registry = new Map<string, () => Promise<any>>();

initialize(components: Record<string, () => Promise<any>>) {
for (const [name, value] of Object.entries(components))
this._registry.set(name, value);
}

async resolveImportRef(importRef: ImportRef): Promise<any> {
const importFunction = this._registry.get(importRef.id);
if (!importFunction)
throw new Error(`Unregistered component: ${importRef.id}. Following components are registered: ${[...this._registry.keys()]}`);
let importedObject = await importFunction();
if (!importedObject)
throw new Error(`Could not resolve component: ${importRef.id}.`);
if (importRef.property) {
importedObject = importedObject[importRef.property];
if (!importedObject)
throw new Error(`Could not instantiate component: ${importRef.id}.${importRef.property}.`);
}
return importedObject;
}
}
21 changes: 21 additions & 0 deletions packages/playwright-ct-core/src/injected/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* 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.
*/

import { ImportRegistry } from './importRegistry';
import { unwrapObject } from './serializers';

window.__pwRegistry = new ImportRegistry();
window.__pwUnwrapObject = unwrapObject;
73 changes: 73 additions & 0 deletions packages/playwright-ct-core/src/injected/serializers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* 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.
*/

import { isImportRef } from './importRegistry';

type FunctionRef = {
__pw_type: 'function';
ordinal: number;
};

function isFunctionRef(value: any): value is FunctionRef {
return value && typeof value === 'object' && value.__pw_type === 'function';
}

export function wrapObject(value: any, callbacks: Function[]): any {
if (typeof value === 'function') {
const ordinal = callbacks.length;
callbacks.push(value as Function);
const result: FunctionRef = {
__pw_type: 'function',
ordinal,
};
return result;
}
if (value === null || typeof value !== 'object')
return value;
if (Array.isArray(value)) {
const result = [];
for (const item of value)
result.push(wrapObject(item, callbacks));
return result;
}
const result: any = {};
for (const [key, prop] of Object.entries(value))
result[key] = wrapObject(prop, callbacks);
return result;
}

export async function unwrapObject(value: any): Promise<any> {
if (value === null || typeof value !== 'object')
return value;
if (isFunctionRef(value)) {
return (...args: any[]) => {
window.__ctDispatchFunction(value.ordinal, args);
};
}
if (isImportRef(value))
return window.__pwRegistry.resolveImportRef(value);

if (Array.isArray(value)) {
const result = [];
for (const item of value)
result.push(await unwrapObject(item));
return result;
}
const result: any = {};
for (const [key, prop] of Object.entries(value))
result[key] = await unwrapObject(prop);
return result;
}
57 changes: 8 additions & 49 deletions packages/playwright-ct-core/src/mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
*/

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

let boundCallbacksForMount: Function[] = [];

Expand Down Expand Up @@ -46,7 +48,7 @@ export const fixtures: Fixtures<TestFixtures, WorkerFixtures, BaseTestFixtures>
if (!((info as any)._configInternal as FullConfigInternal).defineConfigWasUsed)
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');
await (page as any)._wrapApiCall(async () => {
await page.exposeFunction('__ct_dispatch', (ordinal: number, args: any[]) => {
await page.exposeFunction('__ctDispatchFunction', (ordinal: number, args: any[]) => {
boundCallbacksForMount[ordinal](...args);
});
await page.goto(process.env.PLAYWRIGHT_TEST_BASE_URL!);
Expand Down Expand Up @@ -83,59 +85,29 @@ function isJsxComponent(component: any): component is JsxComponent {
}

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

await page.evaluate(async ({ component }) => {
const unwrapFunctions = (object: any) => {
for (const [key, value] of Object.entries(object)) {
if (typeof value === 'string' && (value as string).startsWith('__pw_func_')) {
const ordinal = +value.substring('__pw_func_'.length);
object[key] = (...args: any[]) => {
(window as any)['__ct_dispatch'](ordinal, args);
};
} else if (typeof value === 'object' && value) {
unwrapFunctions(value);
}
}
};

unwrapFunctions(component);
component = await window.__pwRegistry.resolveImports(component);
component = await window.__pwUnwrapObject(component);
const rootElement = document.getElementById('root')!;
return await window.playwrightUpdate(rootElement, component);
}, { component });
}

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

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

const selector = await page.evaluate(async ({ component, hooksConfig }) => {
const unwrapFunctions = (object: any) => {
for (const [key, value] of Object.entries(object)) {
if (typeof value === 'string' && (value as string).startsWith('__pw_func_')) {
const ordinal = +value.substring('__pw_func_'.length);
object[key] = (...args: any[]) => {
(window as any)['__ct_dispatch'](ordinal, args);
};
} else if (typeof value === 'object' && value) {
unwrapFunctions(value);
}
}
};

unwrapFunctions(component);
component = await window.__pwUnwrapObject(component);
let rootElement = document.getElementById('root');
if (!rootElement) {
rootElement = document.createElement('div');
rootElement.id = 'root';
document.body.appendChild(rootElement);
}
component = await window.__pwRegistry.resolveImports(component);
await window.playwrightMount(component, rootElement, hooksConfig);

return '#root >> internal:control=component';
Expand All @@ -152,16 +124,3 @@ function createComponent(component: JsxComponent | ImportRef, options: ObjectCom
...options,
};
}

function wrapFunctions(object: any, page: Page, callbacks: Function[]) {
for (const [key, value] of Object.entries(object)) {
const type = typeof value;
if (type === 'function') {
const functionName = '__pw_func_' + callbacks.length;
callbacks.push(value as Function);
object[key] = functionName;
} else if (type === 'object' && value) {
wrapFunctions(value, page, callbacks);
}
}
}
19 changes: 2 additions & 17 deletions packages/playwright-ct-core/src/vitePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { getPlaywrightVersion } from 'playwright-core/lib/utils';
import { setExternalDependencies } from 'playwright/lib/transform/compilationCache';
import { collectComponentUsages, importInfo } from './tsxTransform';
import { version as viteVersion, build, preview, mergeConfig } from 'vite';
import { source as injectedSource } from './generated/indexSource';
import type { ImportInfo } from './tsxTransform';

const log = debug('pw:vite');
Expand Down Expand Up @@ -115,13 +116,7 @@ export function createPlugin(
let buildExists = false;
let buildInfo: BuildInfo;

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

try {
Expand Down Expand Up @@ -436,13 +431,3 @@ function hasJSComponents(components: ComponentInfo[]): boolean {
}
return false;
}


const importRegistryPrefix = `"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ImportRegistry = void 0;`;

const importRegistrySuffix = `exports.ImportRegistry = ImportRegistry;`;
Loading

0 comments on commit 06518b2

Please sign in to comment.