From 5a7f804694c522525fdab60a2e2e88385fbe5aff Mon Sep 17 00:00:00 2001 From: Max Patiiuk Date: Wed, 18 Nov 2026 22:10:49 -0800 Subject: [PATCH] feat(playground): add previewHtmlTransform method --- src/playground-project.ts | 17 ++++++++++++++++- src/test/playground-ide_test.ts | 22 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/playground-project.ts b/src/playground-project.ts index 906c86f3..6bfba8ad 100644 --- a/src/playground-project.ts +++ b/src/playground-project.ts @@ -567,6 +567,13 @@ export class PlaygroundProject extends LitElement { iframeWindow.postMessage(message, '*', transfer); } + /** + * Transforms HTML on each preview request without modifying the project + * source files. Use this to insert monitoring or debug scripts into the + * preview HTML. + */ + previewHtmlTransform?: (html: string) => string; + private async _getFile(name: string): Promise { if (this._build === undefined) { return { @@ -574,7 +581,15 @@ export class PlaygroundProject extends LitElement { body: 'Playground build not started', }; } - return this._build.getFile(name); + const file = await this._build.getFile(name); + if ( + this.previewHtmlTransform && + 'content' in file && + file.contentType?.split(';')[0] === 'text/html' + ) { + return {...file, content: this.previewHtmlTransform(file.content)}; + } + return file; } /** diff --git a/src/test/playground-ide_test.ts b/src/test/playground-ide_test.ts index e7f56a5e..e3ad08ff 100644 --- a/src/test/playground-ide_test.ts +++ b/src/test/playground-ide_test.ts @@ -5,6 +5,7 @@ */ import {assert} from '@esm-bundle/chai'; +import {waitUntil} from '@open-wc/testing'; import {html, render} from 'lit'; import {PlaygroundIde} from '../playground-ide.js'; import '../playground-ide.js'; @@ -152,6 +153,27 @@ suite('playground-ide', () => { await assertPreviewContains('Hello HTML'); }); + test('transforms served HTML without changing source files', async () => { + const project = document.createElement('playground-project'); + project.sandboxBaseUrl = '/'; + project.previewHtmlTransform = (source) => `${source}`; + const compiled = new Promise((resolve) => { + project.addEventListener('compileDone', () => resolve(), {once: true}); + }); + project.config = {files: {'index.html': {content: '

Original

'}}}; + container.appendChild(project); + await compiled; + await waitUntil(() => project.baseUrl !== undefined); + const iframe = document.createElement('iframe'); + iframe.src = new URL('index.html', project.baseUrl).href; + container.appendChild(iframe); + await waitUntil(() => Boolean( + iframe.contentDocument?.querySelector('meta[name="instrumented"]') + )); + assert.equal(project.files![0].content, '

Original

'); + assert.isFalse(project.modified); + }); + test('handles multiple script tags', async () => { render( html`