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

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 170 additions & 0 deletions packages/playground/client/src/blueprints-v2-handler.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ProgressTracker } from '@php-wasm/progress';
import { BlueprintsV2Handler } from './blueprints-v2-handler';

const mocks = vi.hoisted(() => {
return {
playground: {
boot: vi.fn(),
isConnected: vi.fn(),
isReady: vi.fn(),
onDownloadProgress: vi.fn(),
},
compileBlueprintForExecution: vi.fn(),
resolveRuntimeConfiguration: vi.fn(),
consumeAPI: vi.fn(),
collectPhpLogs: vi.fn(),
compiledRun: vi.fn(),
};
});

vi.mock('@php-wasm/logger', () => ({
collectPhpLogs: mocks.collectPhpLogs,
logger: {},
}));

vi.mock('@php-wasm/universal', () => ({
consumeAPI: mocks.consumeAPI,
}));

vi.mock('@wp-playground/blueprints', () => ({
compileBlueprintForExecution: mocks.compileBlueprintForExecution,
resolveRuntimeConfiguration: mocks.resolveRuntimeConfiguration,
}));

describe('BlueprintsV2Handler', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.playground.boot.mockResolvedValue(undefined);
mocks.playground.isConnected.mockResolvedValue(undefined);
mocks.playground.isReady.mockResolvedValue(undefined);
mocks.playground.onDownloadProgress.mockResolvedValue(undefined);
mocks.compiledRun.mockResolvedValue(undefined);
mocks.compileBlueprintForExecution.mockImplementation(
async (blueprint) => ({
version: 2,
declaration: blueprint,
compiled: {
runtime: {
phpVersion: '8.4',
wpVersion: 'latest',
intl: false,
networking: true,
},
},
run: mocks.compiledRun,
})
);
mocks.resolveRuntimeConfiguration.mockResolvedValue({
phpVersion: '8.4',
wpVersion: 'latest',
intl: false,
networking: true,
});
mocks.consumeAPI.mockReturnValue(mocks.playground);
});

it('boots and runs Blueprint v2 declarations through the native compiler', async () => {
mocks.compileBlueprintForExecution.mockResolvedValue({
version: 2,
declaration: {
version: 2,
},
compiled: {
runtime: {
phpVersion: '8.2',
wpVersion: '6.4',
intl: true,
networking: false,
},
},
run: mocks.compiledRun,
});
const iframe = createIframe();
const onBlueprintValidated = vi.fn();
const onBlueprintStepCompleted = vi.fn();
const onClientConnected = vi.fn();
const blueprint = {
version: 2,
siteOptions: {
blogname: 'V2 site',
},
};
const handler = new BlueprintsV2Handler({
iframe,
remoteUrl: 'http://example.com/remote.html',
blueprint,
scope: 'test-scope',
corsProxy: 'https://cors.example.test/proxy',
onBlueprintValidated,
onBlueprintStepCompleted,
onClientConnected,
});

await handler.bootPlayground(iframe, createProgressTracker());

expect(mocks.resolveRuntimeConfiguration).not.toHaveBeenCalled();
expect(mocks.playground.boot).toHaveBeenCalledWith(
expect.objectContaining({
scope: 'test-scope',
phpVersion: '8.2',
wpVersion: '6.4',
extensions: ['intl'],
withNetworking: false,
corsProxyUrl: 'https://cors.example.test/proxy',
wordpressInstallMode: 'download-and-install',
})
);
expect(mocks.compileBlueprintForExecution).toHaveBeenCalledWith(
blueprint,
expect.objectContaining({
onBlueprintValidated,
onStepCompleted: onBlueprintStepCompleted,
corsProxy: 'https://cors.example.test/proxy',
})
);
expect(mocks.compiledRun).toHaveBeenCalledWith(mocks.playground);
expect(onClientConnected).toHaveBeenCalledWith(mocks.playground);
});

it('does not pipe remote progress when progress UI is disabled', async () => {
const iframe = createIframe();
const blueprint = {
version: 2,
siteOptions: {
blogname: 'V2 site',
},
};
const progressTracker = createProgressTracker();
const handler = new BlueprintsV2Handler({
iframe,
remoteUrl: 'http://example.com/remote.html',
blueprint,
disableProgressBar: true,
});

await handler.bootPlayground(iframe, progressTracker);

expect(progressTracker.pipe).not.toHaveBeenCalled();
});
});

function createIframe() {
return {
contentWindow: {},
ownerDocument: {
defaultView: {},
},
} as HTMLIFrameElement;
}

function createProgressTracker() {
const child = {
finish: vi.fn(),
loadingListener: vi.fn(),
};
return {
pipe: vi.fn(),
stage: vi.fn(() => child),
} as unknown as ProgressTracker;
}
142 changes: 68 additions & 74 deletions packages/playground/client/src/blueprints-v2-handler.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import type { ProgressTracker } from '@php-wasm/progress';
import type { PlaygroundClient, StartPlaygroundOptions } from '.';
import { collectPhpLogs, logger } from '@php-wasm/logger';
import { consumeAPI } from '@php-wasm/universal';
import type { PHPWebExtension } from '@php-wasm/web';
import {
compileBlueprintForExecution,
resolveRuntimeConfiguration,
} from '@wp-playground/blueprints';
import type { PlaygroundClient, StartPlaygroundWebOptions } from '.';

type WordPressInstallMode = NonNullable<
StartPlaygroundWebOptions['wordpressInstallMode']
>;

/**
* Boots Playground and runs Blueprint declarations with the native TypeScript
* Blueprint compiler.
*/
export class BlueprintsV2Handler {
private readonly options: StartPlaygroundOptions;
private readonly options: StartPlaygroundWebOptions;

constructor(options: StartPlaygroundOptions) {
constructor(options: StartPlaygroundWebOptions) {
this.options = options;
}

Expand All @@ -15,17 +28,23 @@ export class BlueprintsV2Handler {
progressTracker: ProgressTracker
) {
const {
blueprint,
onBlueprintValidated,
onBlueprintStepCompleted,
onClientConnected,
corsProxy,
gitAdditionalHeadersCallback,
mounts,
sapiName,
scope,
shouldInstallWordPress,
sqliteDriverVersion,
wordpressInstallMode,
pathAliases,
disableProgressBar,
} = this.options;
const downloadProgress = progressTracker!.stage(0.25);
const executionProgress = progressTracker!.stage(0.75);
const executionProgress = progressTracker.stage(0.5);
const downloadProgress = progressTracker.stage();
const blueprint = this.options.blueprint || { version: 2 };

// Connect the Comlink API client to the remote worker,
// boot the playground, and run the blueprint steps.
Expand All @@ -40,89 +59,64 @@ export class BlueprintsV2Handler {

// Connect the Comlink API client to the remote worker download monitor
await playground.onDownloadProgress(downloadProgress.loadingListener);
await playground.addEventListener(
'blueprint.message',
({ message }: any) => {
switch (message.type) {
case 'blueprint.target_resolved': {
// @TODO: Evaluate consistenty with the CLI worker
// if (!this.blueprintTargetResolved) {
// this.blueprintTargetResolved = true;
// for (const php of this
// .phpInstancesThatNeedMountsAfterTargetResolved) {
// // console.log('mounting resources for php', php);
// this.phpInstancesThatNeedMountsAfterTargetResolved.delete(
// php
// );
// await mountResources(php, args.mount || []);
// }
// }
break;
}
case 'blueprint.progress': {
executionProgress.set(message.progress);
executionProgress.setCaption(message.caption);
break;
}
case 'blueprint.error': {
// @TODO: Error reporting.
const red = '\x1b[31m';
const bold = '\x1b[1m';
const reset = '\x1b[0m';
if (message.details) {
logger.error(
`${red}${bold}Fatal error:${reset} Uncaught ${message.details.exception}: ${message.details.message}\n` +
` at ${message.details.file}:${message.details.line}\n` +
(message.details.trace
? message.details.trace + '\n'
: '')
);
} else {
logger.error(
`${red}${bold}Error:${reset} ${message.message}\n`
);
}

// TODO: Should we report the error like that?
throw new Error(message.message);
break;
}
}
}
);
const compiled = await compileBlueprintForExecution(blueprint, {
progress: executionProgress,
onStepCompleted: onBlueprintStepCompleted,
onBlueprintValidated,
corsProxy,
gitAdditionalHeadersCallback,
});
const runtimeConfiguration =
compiled.version === 2
? compiled.compiled.runtime
: await resolveRuntimeConfiguration(compiled.declaration);
const resolvedWordPressInstallMode = resolveWordPressInstallMode({
shouldInstallWordPress,
wordpressInstallMode,
});

const extensions: PHPWebExtension[] = runtimeConfiguration.intl
? ['intl']
: [];
extensions.push(...(this.options.extensions || []));

await playground.boot({
mounts,
sapiName,
scope: scope ?? Math.random().toFixed(16),
wordpressInstallMode: resolvedWordPressInstallMode,
phpVersion: runtimeConfiguration.phpVersion,
wpVersion: runtimeConfiguration.wpVersion,
extensions,
withNetworking: runtimeConfiguration.networking,
corsProxyUrl: corsProxy,
extensions: this.options.extensions,
experimentalBlueprintsV2Runner: true,
// Pass the declaration directly – the worker runs the V2 runner.
blueprint: blueprint as any,
sqliteDriverVersion,
pathAliases,
} as any);

});
await playground.isReady();
downloadProgress.finish();

collectPhpLogs(logger, playground);
onClientConnected?.(playground);

// @TODO: Get the landing page from the Blueprint.
playground.goTo('/');

/**
* Pre-fetch WordPress update checks to speed up the initial wp-admin load.
*
* @see https://github.com/WordPress/wordpress-playground/pull/2295
*/
// @TODO get the enabled features somehow – probably using the same
// resolveRuntimeConfiguration() logic as the redux site-slice.ts
// if (compiled.features.networking) {
// await playground.prefetchUpdateChecks();
// }
await compiled.run(playground);

return playground;
}
}

function resolveWordPressInstallMode({
shouldInstallWordPress,
wordpressInstallMode,
}: {
shouldInstallWordPress: StartPlaygroundWebOptions['shouldInstallWordPress'];
wordpressInstallMode: StartPlaygroundWebOptions['wordpressInstallMode'];
}): WordPressInstallMode {
return (
wordpressInstallMode ??
(shouldInstallWordPress === false
? 'install-from-existing-files-if-needed'
: 'download-and-install')
);
}
Loading
Loading