Skip to content
Open
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
149 changes: 147 additions & 2 deletions packages/playground/website/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,15 @@ import {
// eslint-disable-next-line @nx/enforce-module-boundaries
import { oAuthMiddleware } from './vite.oauth';
import { fileURLToPath } from 'node:url';
import { copyFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import {
copyFileSync,
existsSync,
readFileSync,
readdirSync,
statSync,
} from 'node:fs';
import { join, resolve, relative, isAbsolute } from 'node:path';
import { exec } from 'node:child_process';
// eslint-disable-next-line @nx/enforce-module-boundaries
import { buildVersionPlugin } from '../../vite-extensions/vite-build-version';
// eslint-disable-next-line @nx/enforce-module-boundaries
Expand Down Expand Up @@ -123,6 +130,144 @@ export default defineConfig(({ command, mode }) => {
server.middlewares.use(oAuthMiddleware);
},
},
// Serve the built @wp-playground/client library at /client/
// to match production where playground.wordpress.net/client/index.js
// is available. Auto-builds if missing, warns if stale.
{
name: 'serve-client-library',
configureServer(server: ViteDevServer) {
const repoRoot = join(__dirname, '../../../');
const clientDistDir = join(
repoRoot,
'dist/packages/playground/client'
);
const clientSrcDir = join(__dirname, '../client/src');
let buildInProgress = false;
let stalenessWarned = false;

function newestMtimeIn(dir: string): number {
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function name newestMtimeIn uses abbreviation 'mtime' which may not be immediately clear to all developers. Consider renaming to getNewestModificationTimeIn or getLatestFileModificationTime for better clarity.

Copilot uses AI. Check for mistakes.
let newest = 0;
try {
for (const entry of readdirSync(dir, {
withFileTypes: true,
})) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
newest = Math.max(
newest,
newestMtimeIn(full)
);
} else if (entry.isFile()) {
newest = Math.max(
newest,
statSync(full).mtimeMs
);
}
}
} catch {
// Directory may not exist yet
}
return newest;
}

function triggerClientBuild() {
if (buildInProgress) {
return;
}
buildInProgress = true;
server.config.logger.warn(
'\n Building @wp-playground/client… Refresh when done.\n'
);
exec(
'npx nx build playground-client',
{ cwd: repoRoot },
(error, stdout, stderr) => {
buildInProgress = false;
stalenessWarned = false;
if (error) {
server.config.logger.error(
' @wp-playground/client build failed. ' +
'Run manually: npx nx build playground-client\n'
);
if (stderr) {
server.config.logger.error(stderr);
}
} else {
server.config.logger.info(
' @wp-playground/client built. Refresh to load.\n'
);
}
}
);
}

server.middlewares.use((req, res, next) => {
if (!req.url?.startsWith('/client/')) {
return next();
}

const distIndexPath = join(clientDistDir, 'index.js');

if (!existsSync(distIndexPath)) {
triggerClientBuild();
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Content-Type',
'application/javascript'
);
res.statusCode = 503;
res.end(
'throw new Error(' +
'"@wp-playground/client is not built yet. ' +
'A build was triggered automatically — refresh in a few seconds.\\n' +
'Or build manually: npx nx build playground-client"' +
');'
);
return;
}

if (!stalenessWarned && !buildInProgress) {
const distMtime = statSync(distIndexPath).mtimeMs;
const srcMtime = newestMtimeIn(clientSrcDir);
if (srcMtime > distMtime) {
stalenessWarned = true;
triggerClientBuild();
}
}

const urlPath = new URL(req.url, 'http://localhost')
.pathname;
Comment on lines +238 to +239
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The req.url is used directly in URL construction without validation. Malformed URLs could cause the URL constructor to throw an exception. Consider wrapping this in a try-catch block to handle potential URL parsing errors gracefully.

Suggested change
const urlPath = new URL(req.url, 'http://localhost')
.pathname;
let urlPath: string;
try {
urlPath = new URL(req.url, 'http://localhost')
.pathname;
} catch {
res.statusCode = 400;
res.end('Invalid request URL');
return;
}

Copilot uses AI. Check for mistakes.
const filePath = resolve(
clientDistDir,
urlPath.slice('/client/'.length)
);
const rel = relative(clientDistDir, filePath);
if (rel.startsWith('..') || isAbsolute(rel)) {
res.statusCode = 403;
res.end();
return;
}
if (!existsSync(filePath)) {
return next();
}
const contentTypes: Record<string, string> = {
'.js': 'application/javascript',
'.cjs': 'application/javascript',
'.json': 'application/json',
'.map': 'application/json',
};
const ext = Object.keys(contentTypes).find((e) =>
filePath.endsWith(e)
);
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Content-Type',
ext ? contentTypes[ext] : 'application/octet-stream'
);
res.end(readFileSync(filePath));
});
},
},
/**
* Copy the `.htaccess` file to the `dist` directory.
*/
Expand Down