'use strict'; const commonjs = require('@rollup/plugin-commonjs'); const fs = require('fs-extra'); const path = require('path'); const { getConfigValue } = require('../../config-file-helpers'); const viteBrowserCompatPlugin = require('./plugins/browser-compat'); const viteServiceRewritePlugin = require('./plugins/service-rewrite'); const viteMissingModulePlugin = require('./plugins/missing-module'); const viteVue2Plugin = require('./plugins/vue2'); const viteManualChunksPlugin = require('./plugins/manual-chunks'); const viteFreeCommonjsRefsPlugin = require('./plugins/free-cjs-refs'); const { createClientEnvCollector } = require('./plugins/client-env'); const { generateViteBootstrap, VITE_BOOTSTRAP_FILE, VITE_BOOTSTRAP_NO_MOUNT_FILE, VITE_BOOTSTRAP_KEY, VITE_BOOTSTRAP_NO_MOUNT_KEY, } = require('./generate-bootstrap'); const { generateViteKilnEditEntry, KILN_EDIT_ENTRY_FILE, KILN_EDIT_ENTRY_KEY } = require('./generate-kiln-edit'); const { generateViteGlobalsInit } = require('./generate-globals-init'); const { buildStyles, SRC_GLOBS: STYLE_GLOBS } = require('./styles'); const { buildFonts, FONTS_SRC_GLOB } = require('./fonts'); const { buildTemplates, getNpmTemplateFiles, TEMPLATE_GLOB_PATTERN } = require('./templates'); const { copyVendor } = require('./vendor'); const { copyMedia } = require('./media'); // Vite 7 is ESM-only; claycli is CommonJS, so Node's require(esm) loads it. It // loads on first use so the config helpers can be required without Vite. let viteModule; const getVite = () => viteModule || (viteModule = require('vite')); const CWD = process.cwd(); const DEST = path.join(CWD, 'public', 'js'); const CLAY_DIR = path.join(CWD, '.clay'); const BUILD_STEP_NAMES = new Set(['js', 'styles', 'fonts', 'templates', 'vendor', 'media']); exports.VITE_BOOTSTRAP_KEY = VITE_BOOTSTRAP_KEY; exports.VITE_BOOTSTRAP_NO_MOUNT_KEY = VITE_BOOTSTRAP_NO_MOUNT_KEY; exports.KILN_EDIT_ENTRY_KEY = KILN_EDIT_ENTRY_KEY; /** * Normalize a `--only`/`options.only` value into a Set of build step names, * or null (meaning "no filter — run everything"). * * Throws on any unrecognized step name rather than silently dropping it. * `cli/vite.js`'s own `--only` validation already rejects this at the CLI * layer, but this function is also reachable directly (`require('claycli')` * programmatic API), which bypasses that layer entirely — dropping an * unrecognized name here used to mean a typo silently fell through to * "requested.size === 0 → build everything", the opposite of what a * narrowed `--only` invocation is for. * * @param {string|string[]} only * @returns {Set|null} */ /** * Split a --only value into a deduped, trimmed array of entries. * Accepts either repeated flags (--only js --only styles) or CSV * (--only js,styles). * * @param {string|string[]} only * @returns {string[]} */ function splitOnlyEntries(only) { const values = Array.isArray(only) ? only : [only]; return values .flatMap(v => String(v).split(',')) .map(v => v.trim()) .filter(Boolean); } /** * Partition --only entries into recognized build steps and anything * unrecognized (a typo, most likely). * * @param {string[]} entries * @returns {{ requested: Set, unrecognized: string[] }} */ function classifyOnlyEntries(entries) { const requested = new Set(); const unrecognized = []; for (const name of entries) { if (BUILD_STEP_NAMES.has(name)) { requested.add(name); } else { unrecognized.push(name); } } return { requested, unrecognized }; } function normalizeRequestedSteps(only) { if (!only || Array.isArray(only) && only.length === 0) return null; const entries = splitOnlyEntries(only); // "all" means "no filtering" so buildAll can reuse its normal path. if (entries.includes('all')) return null; const { requested, unrecognized } = classifyOnlyEntries(entries); if (unrecognized.length > 0) { throw new Error( `[clay vite] Unrecognized --only value(s): ${unrecognized.join(', ')}. ` + `Valid steps: ${['all', ...BUILD_STEP_NAMES].join(', ')}.` ); } return requested.size > 0 ? requested : null; } function buildSelectedParallelTasks(step, shouldRun, options) { // Keep the existing parallel scheduling model; this only filters which // steps participate in the Promise.all fan-out. return [ ['js', () => buildJS(options)], ['styles', () => buildStyles(options)], ['fonts', () => buildFonts()], ['templates', () => buildTemplates(options)], ['vendor', () => copyVendor()], ] .filter(([name]) => shouldRun(name)) .map(([name, runner]) => step(name, runner)); } function shouldRunMediaStep(shouldRun) { // Templates can inline SVG/media files from public/media, so media remains // a hard prerequisite even when the user requested templates only. const requestedTemplatesOnly = shouldRun('templates') && !shouldRun('media'); if (requestedTemplatesOnly) { console.log('[clay vite] --only templates also runs media (templates can inline public/media/**)'); } return shouldRun('media') || shouldRun('templates'); } // ── Config helpers ────────────────────────────────────────────────────────── /** * Read and apply the bundlerConfig() customizer from claycli.config.js. * * bundlerConfig() is the single hook for customizing the Vite build pipeline. * Plugins use the standard Rollup plugin API (resolveId, load, transform) since * Vite's production build uses Rollup internally. * * Config shape (all keys optional): * * { * minify: false, * extraEntries: [], * manualChunksMinSize: undefined, // bytes — controls chunk merging threshold. * // Not set by default: omitting it means no * // inlining/merging (equivalent to 0). * // Suggested values for CJS/mixed codebases: * // 4096 (4 KB) — conservative, fewer merges * // 8192 (8 KB) — balanced, recommended starting point * // In CJS mode (clientFilesESM:false) this feeds * // viteManualChunksPlugin which inlines small private * // deps into their owner chunk. * // In ESM mode (clientFilesESM:true) this maps to * // Rollup's native experimentalMinChunkSize which * // merges small chunks across the whole graph. * clientFilesESM: false, // set true once all client.js files and their deps * // are native ESM. Switches the view-mode pass from * // viteManualChunksPlugin to Rollup's native * // experimentalMinChunkSize (driven by manualChunksMinSize). * // Does NOT affect the kiln pass — use kilnSplit for that. * kilnSplit: false, // set true once all model.js/kiln.js are ESM — * // collapses the two-pass build into one graph. * define: {}, // identifier replacements merged on top of built-in * // defines (process.env.NODE_ENV, __dirname, etc.) * alias: {}, // module path aliases applied at resolution time. * // Equivalent to Vite's resolve.alias. Keys are * // bare specifiers or path prefixes; values are * // absolute paths or replacement specifiers: * // '@sentry/node': '@sentry/browser' * // '@utils': path.resolve(__dirname, 'src/utils') * // For complex patterns (regex, onResolve hooks), * // add a Rollup plugin via `plugins` instead. * sourcemap: true, // emit .js.map files alongside every output chunk. * // Keeps DevTools stack traces symbolicated and lets * // error monitoring (Sentry) map runtime errors to * // source lines. Disable to save build time in CI * // environments where sourcemaps are not consumed: * // config.sourcemap = false; * plugins: [], // extra Rollup/Vite plugins appended after built-ins * commonjsExclude: [], // patterns passed to @rollup/plugin-commonjs `exclude` * // for CJS packages whose internal eval() scope must * // not be rewritten (e.g. webpack dev bundles like * // pyxis-frontend that use eval() for modules) * browserStubs: {}, // site-specific Node.js module stubs for the browser * // bundle. Keys are module names; values are either * // null (empty-object stub) or a custom ESM string: * // 'ioredis': null * // 'mongodb': 'export default { connect: function() {} };' * // Site stubs override built-ins when names collide. * nodeGlobals: {}, // opt-in auto-injection for Node globals referenced as * // BARE free identifiers (`Buffer.from(...)` with no * // require('buffer')/import 'buffer') — Vite does not * // polyfill these the way Browserify's insert-module-globals * // did, and browser-compat.js's stubs only intercept an * // explicit require()/import of the built-in. Narrow and * // extensible: only `Buffer` is implemented today. * // nodeGlobals.Buffer === true — @rollup/plugin-inject * // adds an auto-import of `Buffer` from 'buffer' ONLY to * // modules that reference the free identifier; resolves * // through the existing browser-compat.js buffer stub * // (which prefers a real globalThis.Buffer when present). * // nodeGlobals.Buffer === 'polyfill' — same auto-import, but * // `alias` is extended to point the 'buffer' specifier at * // the real npm `buffer` package instead of the stub, for * // byte-capable use (e.g. createHmac). Pulls in real bytes * // — use sparingly. * // false / unset (default) — no plugin added, zero bytes, * // zero behavior change. * serverOnlyPackages: [], // opt-in stopgap: package-path prefixes (e.g. 'amphora/lib') * // that warn (not block) when pulled into a browser-reachable * // bundle — for third-party server-only packages the * // services/server -> services/client rewrite has no opinion * // on. Defaults to [], a complete no-op. See service-rewrite.js * // for the full rationale. * publicBase: undefined, // opt-out of the relative Vite `base`. Unset (the * // default) builds with base './', so chunk preloads * // resolve from wherever the bootstrap is served * // (CDN host, site path prefix, bare origin). Set an * // absolute prefix such as '/js' or * // 'https://cdn.example.com/js' only when JS is always * // served from that one location. Does not change * // _manifest.json. See resolveViteBase(). * nodeEnv: 'development', // build-time process.env.NODE_ENV literal, so * // `process.env.NODE_ENV === 'production'` guards fold. * // Defaults to process.env.NODE_ENV when set, read * // once per build (see the default below). * } * * @param {object} [cliOptions] * @returns {object} */ function getViteConfig(cliOptions = {}) { const config = { minify: cliOptions.minify || false, extraEntries: cliOptions.extraEntries || [], manualChunksMinSize: undefined, clientFilesESM: false, kilnSplit: false, define: {}, alias: {}, sourcemap: true, plugins: [], commonjsExclude: [], browserStubs: {}, // nodeGlobals: { Buffer: true | 'polyfill' | false } — see the JSDoc block // above and buildPlugins()/baseViteConfig() below for the wiring. nodeGlobals: {}, // serverOnlyPackages: [] — see the JSDoc block above and // viteServiceRewritePlugin() in plugins/service-rewrite.js. serverOnlyPackages: [], // publicBase: undefined → relative Vite base ('./'); see resolveViteBase(). publicBase: undefined, // When true, replace Vite's throwing `__vite-browser-external` proxy with // an empty ESM module so unresolved Node-only imports behave like // Browserify (silent undefined) instead of throwing at runtime on the // first property access. Intended as a migration flag while latent // server-only imports are tracked down in isomorphic code (cheerio, // postcss, @google/maps, etc.). Default off so real problems surface. lenientBrowserExternalize: false, // The build-time NODE_ENV literal, read once here. Vite's build() sets // process.env.NODE_ENV to 'production' when it is unset, and the view and // Kiln passes configure in parallel with that, so reading it per pass gave // them different values (and different library builds) depending on timing. nodeEnv: process.env.NODE_ENV || 'development', }; // Read bundlerConfig() from claycli.config.js — the single hook for // customizing the Vite build pipeline. const customizer = getConfigValue('bundlerConfig'); if (typeof customizer === 'function') { const customized = customizer(config); if (customized && typeof customized === 'object') return customized; } return config; } exports.getViteConfig = getViteConfig; /** * Build the `process.env` define that redirects client env reads to the * RUNTIME-hydrated `window.process.env`. * * This is the Vite equivalent of the legacy Browserify pipeline's transformEnv * plugin (lib/cmd/compile/scripts.js), which rewrites every `process.env` in * client code to `window.process.env` and inlines NO values ("reference window, * so browserify doesn't bundle in `process`"). * * ── Why a redirect, not an inline ─────────────────────────────────────────── * * Vite does not inline arbitrary env, and @rollup/plugin-commonjs rewrites the * bare `process.env` of a CJS module into a build-time-empty local stub * (literally `var pVt = {}`). So `const HOST = process.env.PYXIS_HOST || '…'` * compiles to `pVt.PYXIS_HOST || '…'` → always the fallback, and the read is dead * at build time. That silently breaks every Kiln plugin / universal service that * reads env (pyxis.js, glaze/agora helpers, …): they work in Browserify but not * under Vite. * * Defining `process.env` → `window.process.env` makes `process.env.PYXIS_HOST` * compile to `window.process.env.PYXIS_HOST` — a live read of the object * .clay/_env-init.js hydrates from `window.kiln.preloadData._envVars` (amphora-html * forwards the server's live env in edit mode, gated by client-env.json). It also * turns master's `window.process.env.X = process.env.X` plugin line into a harmless * self-assign instead of clobbering the hydrated value with "". * * We deliberately do NOT inline values from the build env. The Docker image build * is bare (only CLAYCLI_* args), so there is nothing to inline in prod anyway; and * inlining from the full build `process.env` would bake any referenced var — * including secrets that are NOT on the client-env.json allowlist (e.g. * CORAL_GRAPHQL_TOKEN) — into the public bundle on any env-present build (local * `make assets`, future build-args, …). The runtime object is allowlist-gated, so * a pure redirect keeps Vite's client-env exposure identical to Browserify's. * * `process.env.NODE_ENV` is kept as a build-time literal by buildDefines (a * more-specific key, so it wins over this catch-all) → `process.env.NODE_ENV === * 'production'` still tree-shakes. * * @returns {object} `{ 'process.env': 'window.process.env' }` */ function buildClientEnvDefines() { // A member-expression value (not a JSON literal) tells esbuild/Vite to REWRITE // the `process.env` token to `window.process.env` rather than substitute a // constant. `window.process.env` on the left-hand side of an assignment is left // alone (its `process` is a member of `window`, not the free `process` token). return { 'process.env': 'window.process.env' }; } /** * Build the define map injected into every module at compile time. * * Vite uses esbuild under the hood for define substitution, so these are * identifier-scoped replacements (not substring replacements like sed). * Only meaningful identifiers are replaced — string literals are never touched. * * Node globals (process, __filename, etc.) appear in isomorphic Clay services * that run on both the server and in the browser. Stubbing them here lets the * browser bundle compile without a polyfill, while the real Node values are * used at runtime on the server. * * @param {object} userDefines - extra defines from bundlerConfig() * @param {string} [NODE_ENV] - the build-time NODE_ENV literal (getViteConfig().nodeEnv) * @returns {object} */ function buildDefines(userDefines = {}, NODE_ENV = process.env.NODE_ENV || 'development') { return Object.assign( { // Guards like `if (process.env.NODE_ENV === 'production')` tree-shake // correctly in the browser bundle. 'process.env.NODE_ENV': JSON.stringify(NODE_ENV), // process.browser is a convention used by some isomorphic libraries to // branch between Node and browser paths. 'process.browser': JSON.stringify(true), // process.version and process.versions are read by clay-log to detect // the runtime environment. Stub to empty values so the browser branch // is taken rather than the Node branch. 'process.version': JSON.stringify(''), 'process.versions': JSON.stringify({}), // __filename and __dirname are used in some server-side Clay utilities. // In the browser bundle they are never accessed at runtime, but they // must resolve to something so the module compiles. __filename: JSON.stringify(''), __dirname: JSON.stringify('/'), // global → globalThis. Some older CJS packages reference global instead // of window. globalThis is universally available in ES2017+ environments. global: 'globalThis', }, // Client env (see buildClientEnvDefines): redirect `process.env` → // `window.process.env` so reads resolve to the runtime-hydrated object // (.clay/_env-init.js), matching the legacy Browserify transformEnv plugin — // no build-time values are inlined. `process.env.NODE_ENV` above is more // specific and still wins as a literal. Comes before userDefines so a site // can still override a specific var via bundlerConfig().define if needed. buildClientEnvDefines(), userDefines ); } exports.buildDefines = buildDefines; /** * Assemble the Vite plugin array for a build pass. * * Plugin order matters because each runs in sequence on every resolved module: * * 1. browser-compat — intercepts Node built-in imports (fs, path, events …) * and replaces them with browser-safe stubs BEFORE any * other plugin or Vite's resolver sees them. Runs first * because some node_modules transitively import built-ins * and must be redirected at resolution time. * * 2. service-rewrite — redirects any import of services/server/* to the * matching services/client/* file. Clay components use * isomorphic service paths; the browser bundle always gets * the client implementation. * * 3. missing-module — stubs unresolvable relative imports with an empty ESM * module instead of erroring. Browserify silently skipped * missing requires; this plugin preserves that lenient * behaviour while the codebase is still being cleaned up. * * 4. vue2 — compiles .vue Single File Components using Vue 2's * template compiler. Must run before Vite's JS pipeline * so that .vue files are converted to plain JS before * @rollup/plugin-commonjs processes any require() calls * in the