All files / core/blong-browser/src vite.ts

81.25% Statements 13/16
70% Branches 7/10
83.33% Functions 5/6
76.92% Lines 10/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279                                                                3x               2x                                           2x       1365x 1365x                                                               2x 2x 2x                                       1x                                                                                                                                                                                                                                                                                                                     1x    
/**
 * Reusable Vite configuration factory for blong browser applications.
 *
 * Provides sensible defaults (React plugin, RPC proxy, primeicons fs allow,
 * keepNames for Storybook debugging) so suite-level `vite.config.ts` files
 * stay minimal.
 *
 * Usage:
 * ```ts
 * // vite.config.ts
 * import {defineBlongViteConfig} from '@feasibleone/blong-browser/vite';
 * export default defineBlongViteConfig({importMetaUrl: import.meta.url});
 * ```
 *
 * Override any setting via the options parameter:
 * ```ts
 * export default defineBlongViteConfig({
 *     importMetaUrl: import.meta.url,
 *     server: {proxy: {'/rpc': 'http://localhost:9090'}},
 *     resolve: {alias: {'@feasibleone/blong': new URL('../blong/types.ts', import.meta.url).pathname}},
 * });
 * ```
 */
import react from '@vitejs/plugin-react';
import {dirname} from 'node:path';
import {fileURLToPath} from 'node:url';
import gzipPlugin from 'rollup-plugin-gzip';
import {type Plugin, type UserConfig, defineConfig, mergeConfig} from 'vite';
import {brotliCompressSync} from 'zlib';
import {packageRootOf, sourceLinkDefine} from './sourceLinkDefine.ts';
import {sourceMapRegister} from './sourceMapRegister.ts';
 
const dir = (url: string) => dirname(url.replace(/file:\//g, ''));
 
/**
 * Name of the plugin that keeps fixtures out of an app build.
 *
 * Exported so `defineBlongStorybookMain` removes the very same plugin instead of
 * repeating the string: Storybook is the one build that wants the real rows.
 */
export const DROP_FIXTURES = 'blong-drop-fixtures';
 
/**
 * Replace every `meta/fixture` module with an empty handler of the same name.
 *
 * A realm globs `meta/fixture` in its `browser.ts` so the Storybook mock adapter
 * can register the sample rows it reads through `handler['{subject}Fixture']`.
 * That glob cannot be made conditional: `import.meta.glob` is expanded at build
 * time, so the matched modules are in the app's module graph — and in its
 * output — even behind a branch that is never taken.
 *
 * Fixtures are Storybook's data, so an app build drops them here instead: each
 * `meta/fixture` module resolves to a handler that returns no rows, and
 * Storybook's own config removes this plugin (see `storybookMain.ts`) so its
 * build keeps the real file.
 *
 * The stub is a *handler* rather than an empty module on purpose: the loader logs
 * an error for a handler file whose default export is missing, and a stub that
 * threw would turn an unused fixture into a boot failure. The server platform is
 * unaffected either way — it scans layer folders instead of globbing them, so a
 * realm's `config.mock` still serves its models from the real fixture file.
 */
const dropFixtures = (): Plugin => ({
    name: DROP_FIXTURES,
    enforce: 'pre',
    load(id) {
        const [file] = id.split('?');
        Eif (!/[\\/]meta[\\/]fixture[\\/]/.test(file as string)) return null;
        const name = (file as string)
            .split(/[\\/]/)
            .pop()!
            .replace(/\.\w+$/, '');
        return [
            `import {handler} from '@feasibleone/blong';`,
            `export default handler(() => async function ${name}() {`,
            `    return {};`,
            `});`,
            '',
        ].join('\n');
    },
});
 
/**
 * This package, as source — what a suite bundles instead of the published bundle.
 *
 * `exports` of `@feasibleone/blong-browser` sends a production build to
 * `dist/blong-browser.es.js`, and the package's own `build` script emits declarations
 * only: the bundle is a *publish* artifact, produced by the manual `build_` script,
 * which no rush build and no workflow in this repository runs. A suite's `vite build`
 * therefore resolved a file that either does not exist or is whatever a previous
 * manual run left behind — which is how `@feasibleone/blong-suite` came to fail with
 * `"DiagramViewer" is not exported by …/dist/blong-browser.es.js` after the viewer was
 * added, and would have failed the same way on a clean checkout. Bundling the source
 * is what the dev server already does (the `development` export condition), so the two
 * now agree; the published package is unchanged for consumers outside the monorepo.
 *
 * Kept lazy and scheme-agnostic because this module is also loaded outside a build:
 * `browserBundle.test.ts` imports it, and there `import.meta.url` is not a file url.
 */
const browserEntry = (() => {
    const entry = new URL('./index.ts', import.meta.url);
    return entry.protocol === 'file:' ? fileURLToPath(entry) : entry.href;
})();
 
export interface IBlongViteOptions {
    /**
     * `import.meta.url` from the caller's vite.config.ts.
     * Used to derive the correct `server.fs.allow` path for primeicons assets.
     */
    importMetaUrl: string;
    /** Any Vite UserConfig overrides merged on top of the defaults. */
    overrides?: UserConfig;
    /** Override the RPC proxy target (defaults to 'http://localhost:8080'). */
    rpcTarget?: string;
}
 
export function defineBlongViteConfig({
    importMetaUrl,
    overrides = {},
    rpcTarget = `http://localhost:${process.env['PLAYWRIGHT_BACKEND_PORT'] || 8080}`,
}: IBlongViteOptions): ReturnType<typeof defineConfig> {
    const base: UserConfig = {
        base: '/s/',
        plugins: [react(), dropFixtures(), sourceMapRegister()],
        define: sourceLinkDefine(packageRootOf(importMetaUrl)),
        optimizeDeps: {
            /**
             * What the dependency scan crawls, and why it is named.
             *
             * Left to itself the scanner walks every `.html` under the root, which
             * includes any static Storybook build a checkout carries
             * (`storybook-static/`). That bundle references Storybook-only packages
             * (`@sinclair/typebox-codegen` among them) which the app does not install,
             * so the scan aborts with *"Skipping dependency pre-bundling"* — and the
             * browser then discovers dependencies one import at a time, each discovery
             * rewriting the optimized bundle and **reloading the page**. A cold
             * Playwright run paid four document loads (~2.3 s) for the login screen
             * instead of one (~0.9 s), and CI is cold on every checkout: this is the
             * 4-5 s the specs spend before the login form exists, @@D-746.
             */
            entries: ['index.html'],
        },
        build: {
            minify: false,
            assetsInlineLimit: 0,
            cssCodeSplit: true,
            rollupOptions: {
                output: {
                    // Keep function names for better debugging in Storybook
                    keepNames: true,
                },
                plugins: [
                    // Compression is a publish step: the `.gz`/`.br` siblings are for
                    // whatever serves the build, and no browser reads them locally. It is
                    // also 92% of a build's time (27.7 s of 30.1 s measured), which is why
                    // a build made to *time* the app sets `BLONG_SKIP_COMPRESSION`.
                    ...(process.env['BLONG_SKIP_COMPRESSION']
                        ? []
                        : [
                              gzipPlugin(), // Generates .gz files
                              gzipPlugin({
                                  customCompression: content =>
                                      brotliCompressSync(Buffer.from(content)),
                                  fileName: '.br', // Generates .br files
                              }),
                          ]),
                ],
            },
        },
        server: {
            proxy: {
                '/rpc': rpcTarget,
                // A stored file is served from its own path, not from `/rpc` — one place per blob,
                // under the read cookie (`@@D-836`). Without this line every image on every page is a
                // 404 in dev while the same app works behind the gateway's own port, which is what a
                // Playwright run found and no server test could (`@@F-740`).
                '/a': rpcTarget,
            },
            /**
             * What the watcher must not look at: the artifacts the run itself
             * writes.
             *
             * Playwright's output directory is `.playwright/` here — the default
             * `test-results/` is in Vite's own ignore list, which is why this was
             * never a problem before the tooling moved it. Every trace resource it
             * writes is an `.html` file inside the served root, so the watcher sees
             * it, the HTML handling treats it as a page, and the browser is told to
             * **reload** — mid-test. One failing test therefore reloads every test
             * that follows it, which is how a single flake becomes a run of
             * failures. The rest of the list is the same class of file: anything a
             * run writes into its own package.
             *
             * `dist/` is on that list for the same reason and cost a debugging
             * cycle: `vite build` leaves the app bundle (HTML included) in the
             * served root, and a Playwright run started while that write is fresh
             * reloads mid-test — six tests went flaky with one-minute timeouts,
             * then the suite was green twice in a row once `dist/` was removed.
             */
            watch: {
                ignored: [
                    '**/.git/**',
                    '**/node_modules/**',
                    '**/dist/**',
                    '**/.playwright/**',
                    '**/allure-results/**',
                    '**/allure-report/**',
                    '**/.ci-report/**',
                    '**/.tap/**',
                    '**/coverage/**',
                    '**/storybook-static/**',
                ],
            },
            fs: {
                // Allow Vite to serve files from the Rush pnpm virtual store.
                //
                // Needed for:
                //  - fonts/assets in packages like primeicons;
                //  - `primereact` theme CSS, loaded at runtime as `?inline`
                //    dynamic imports by the theme switcher (`themeRegistry.ts`).
                //    Vite's dev-server fs guard runs the allow-list check on
                //    query-bearing requests (`?inline`/`?url`/`?raw`), so a
                //    package that is only reachable through the module graph is
                //    served as raw CSS instead of being transformed to a JS
                //    module — the browser then rejects it with a
                //    `text/css` MIME type error and no theme is applied.
                allow: [
                    dir(importMetaUrl),
                    dir(new URL(import.meta.resolve('primeicons/package.json')).pathname),
                    dir(new URL(import.meta.resolve('primereact/package.json')).pathname),
                ],
            },
        },
        /**
         * The same proxy for a *built* app.
         *
         * `server.proxy` is a dev-server option and `vite preview` ignores it, so a build
         * served from disk answered every `/rpc/*` call from its own origin and the login
         * form could not authenticate — the app looked broken in exactly the way a missing
         * gateway looks. Preview is how a build is sanity-checked locally and how the boot
         * comparison measures it (`@@T-605`), so the proxy is declared for it too.
         */
        preview: {
            proxy: {
                '/rpc': rpcTarget,
                /** The served blob path, for the reason the dev proxy carries it (`@@D-836`). */
                '/a': rpcTarget,
            },
        },
        resolve: {
            alias: [
                // Exact match, so the package's own subpath exports (`/vite`,
                // `/playwright`, `/browser.js`) keep resolving through `exports`.
                {find: /^@feasibleone\/blong-browser$/, replacement: browserEntry},
                // In the monorepo, point @feasibleone/blong directly at source
                // so Vite picks up TypeScript changes without a build step.
                {
                    find: '@feasibleone/blong/types',
                    replacement: new URL(import.meta.resolve('@feasibleone/blong/types')).href,
                },
                {
                    // The blob contract a realm stores references with (@@D-842): `blob://` and its
                    // parser live in one file both sides import, so a reference is never spelled twice.
                    find: '@feasibleone/blong/blob',
                    replacement: new URL(
                        './blob.ts',
                        import.meta.resolve('@feasibleone/blong/types'),
                    ).href,
                },
                {
                    find: '@feasibleone/blong',
                    replacement: new URL(import.meta.resolve('@feasibleone/blong')).pathname,
                },
            ],
        },
    };
 
    return defineConfig(mergeConfig(base, overrides));
}