Skip to content
Open
Changes from 3 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
148 changes: 146 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 } 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,143 @@ 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 {
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;
const filePath = resolve(
clientDistDir,
urlPath.slice('/client/'.length)
);
if (!filePath.startsWith(clientDistDir)) {
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