Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support work with webpack worker #1195

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
22 changes: 21 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ To upgrade this node using the module version of the code, we can directly impor
```html
<script type="module">
import {upgradeElement} from './dist/main.mjs';
upgradeElement(document.getElementById('upgrade-me'), './dist/worker/worker.mjs');
upgradeElement(document.getElementById('upgrade-me'), './dist/worker/worker.js');
</script>
```

Expand All @@ -51,6 +51,26 @@ The nomodule format exposes the global `MainThread`, and could upgrade the `div`
</script>
```

### With Webpack

In main.js :
```js
import { upgradeElementByWorker } from '@ampproject/worker-dom/dist/main.mjs';

const worker = new Worker(new URL('./worker.js', import.meta.url));
upgradeElementByWorker(document.getElementById('upgrade-me'), worker);
```
In worker.js :

```js
import { initWorkerDom } from '@ampproject/worker-dom/dist/worker/worker.mjs'

initWorkerDom().then(() => {
const div = document.createElement('div');
document.body.appendChild(div);
})
```

### AMP Distribution for `amp-script`

WorkerDOM has a special output variant that supplies additional hooks for safety features e.g. HTML sanitization. This variant is distributed under the amp folder for main and worker thread binaries:
Expand Down
4 changes: 2 additions & 2 deletions config/rollup.worker-thread.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const ESModules = [
input: 'output/worker-thread/index.js',
output: {
file: 'dist/worker/worker.mjs',
format: 'iife',
format: 'es',
name: 'WorkerThread',
sourcemap: true,
},
Expand All @@ -51,7 +51,7 @@ const ESModules = [
input: 'output/worker-thread/index.js',
output: {
file: 'dist/debug/worker/worker.mjs',
format: 'iife',
format: 'es',
name: 'WorkerThread',
sourcemap: true,
},
Expand Down
14 changes: 8 additions & 6 deletions src/main-thread/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ export type LongTaskFunction = (promise: Promise<any>) => void;
export type HydrationFilterPredicate = (node: RenderableElement) => boolean;

export interface InboundWorkerDOMConfiguration {
// ---- Required Values.
authorURL: string;
domURL: string;
authorURL?: string;
domURL?: string;

// ---- Optional Overrides
// worker
worker?: Worker;
// Schedules mutation phase.
mutationPump?: MutationPumpFunction;
// Schedules long task.
Expand All @@ -43,9 +44,8 @@ export interface InboundWorkerDOMConfiguration {
}

export interface WorkerDOMConfiguration {
// ---- Required Values.
authorURL: string;
domURL: string;
authorURL?: string;
domURL?: string;

// ---- Optional, with defaults
// Schedules mutation phase.
Expand All @@ -54,6 +54,8 @@ export interface WorkerDOMConfiguration {
executorsAllowed: Array<number>;

// ---- Optional Overrides
// worker
worker?: Worker;
// Schedules long task.
longTask?: LongTaskFunction;
// Sanitizer for DOM Mutations
Expand Down
6 changes: 5 additions & 1 deletion src/main-thread/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchAndInstall } from './install';
import { fetchAndInstall, install } from './install';
import { ExportedWorker } from './exported-worker';

export function upgradeElement(baseElement: Element, domURL: string): Promise<ExportedWorker | null> {
Expand All @@ -11,3 +11,7 @@ export function upgradeElement(baseElement: Element, domURL: string): Promise<Ex
}
return Promise.resolve(null);
}

export function upgradeElementByWorker(baseElement: Element, worker: Worker) {
return install(Promise.resolve(['', '']), baseElement as HTMLElement, { worker });
}
4 changes: 3 additions & 1 deletion src/main-thread/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ const ALLOWABLE_MESSAGE_TYPES = [MessageType.MUTATE, MessageType.HYDRATE];
* @param debug
*/
export function fetchAndInstall(baseElement: HTMLElement, config: InboundWorkerDOMConfiguration): Promise<ExportedWorker | null> {
if (!config.domURL || !config.authorURL) throw new Error('miss domURL or authorURL');

const fetchPromise = Promise.all([
// TODO(KB): Fetch Polyfill for IE11.
fetch(config.domURL).then((response) => response.text()),
Expand Down Expand Up @@ -49,7 +51,7 @@ export function install(
const nodeContext = new NodeContext(stringContext, baseElement);
const normalizedConfig = normalizeConfiguration(config);
return fetchPromise.then(([domScriptContent, authorScriptContent]) => {
if (domScriptContent && authorScriptContent && config.authorURL) {
if ((domScriptContent && authorScriptContent && config.authorURL) || config.worker) {
const workerContext = new WorkerContext(baseElement, nodeContext, domScriptContent, authorScriptContent, normalizedConfig);
const mutatorContext = new MutatorProcessor(stringContext, nodeContext, workerContext, normalizedConfig, objectContext);
workerContext.worker.onmessage = (message: MessageFromWorker) => {
Expand Down
21 changes: 19 additions & 2 deletions src/main-thread/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { NodeContext } from './nodes';
import { TransferrableKeys } from '../transfer/TransferrableKeys';
import { StorageLocation } from '../transfer/TransferrableStorage';
import { IframeWorker } from './iframe-worker';
import { waitForMsg } from '../utils';

// TODO: Sanitizer storage init is likely broken, since the code currently
// attempts to stringify a Promise.
Expand Down Expand Up @@ -64,9 +65,25 @@ export class WorkerContext {
Object.assign(self, workerDOM);
}).call(self);
${authorScript}
//# sourceURL=${encodeURI(config.authorURL)}`;
//# sourceURL=${encodeURI(config.authorURL ?? '')}`;
if (!config.sandbox) {
this[TransferrableKeys.worker] = new Worker(URL.createObjectURL(new Blob([code])));
if (config.worker) {
this[TransferrableKeys.worker] = config.worker;
waitForMsg<any>(config.worker, 'initHydrateArgs').then(() => {
const hydrateArgs = [
strings,
skeleton,
cssKeys,
globalEventHandlerKeys,
[window.innerWidth, window.innerHeight],
localStorageInit,
sessionStorageInit,
];
config.worker?.postMessage({ data: JSON.stringify(hydrateArgs), type: 'initHydrateArgs' });
});
} else {
this[TransferrableKeys.worker] = new Worker(URL.createObjectURL(new Blob([code])));
}
} else if (IS_AMP) {
this[TransferrableKeys.worker] = new IframeWorker(URL.createObjectURL(new Blob([code])), config.sandbox.iframeUrl);
}
Expand Down
25 changes: 25 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,28 @@ export const enum NumericBoolean {
FALSE = 0,
TRUE = 1,
}

export interface Msg<T extends any = any> {
type: 'initHydrateArgs';
data: T;
}
export function listenToMsgType<T>(target: Worker | typeof globalThis, type: Msg<T>['type'], listener: (data: Msg<T>) => any) {
const _listener = (e: any) => {
if (e.data?.type === type) listener(e.data);
};
target.addEventListener('message', _listener);
return () => target.removeEventListener('message', _listener);
}

export function waitForMsg<T>(target: Worker | typeof globalThis, type: Msg<T>['type']): Promise<Msg<T>> {
return new Promise((res) => {
const removeListener = listenToMsgType<T>(target, type, (data) => {
removeListener();
res(data);
});
});
}

export function postMsg<T>(target: Worker | typeof globalThis, type: Msg<T>['type'], data?: T) {
return target.postMessage({ type, data });
}
15 changes: 15 additions & 0 deletions src/worker-thread/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ import { DocumentFragment } from './dom/DocumentFragment';
import { Element } from './dom/Element';
import { rafPolyfill, cafPolyfill } from './AnimationFrame';
import { HydrateFunction } from './hydrate';
import { TransferrableKeys } from '../transfer/TransferrableKeys';
import { waitForMsg, postMsg } from '../utils';

const globalScope: GlobalScope = {
innerWidth: 0,
Expand Down Expand Up @@ -116,3 +118,16 @@ export const workerDOM = (function (postMessage, addEventListener, removeEventLi
})(postMessage.bind(self) || noop, addEventListener.bind(self) || noop, removeEventListener.bind(self) || noop);

export const hydrate: HydrateFunction = initialize;

type SliceTuple<T extends any[]> = T extends [any, ...infer Last] ? Last : never;

export function initWorkerDom() {
postMsg(self, 'initHydrateArgs');
return waitForMsg<string>(self, 'initHydrateArgs').then((data) => {
const hydrateArgs = JSON.parse(data.data) as SliceTuple<Parameters<HydrateFunction>>;
Object.assign(self, { window: self });
hydrate(workerDOM.document, ...hydrateArgs);
workerDOM.document[TransferrableKeys.observe]();
Object.assign(self, workerDOM);
});
}