Files
Module-Rust/client/vite.config.js
wtclaude 862c328176 feat: the module skeleton and every bundle seam
module-rust, id 'rust', built from the Integration Kit's template. Phase 1's job
is the kit's own argument: get every seam working at once with almost nothing in
them, so that afterwards you break exactly one at a time.

What is here:

* /rust on all three tiers, because the loader holds module.json's mounts against
  what is registered in BOTH directions -- so the declaration and the
  registration land together or not at all. The player tier is honestly thin: it
  answers the server list on the authenticated tier, delegating to the same model
  the public tier uses so the two cannot drift while they are meant to be the
  same. It is the address the app will call, registered now rather than moved
  later.
* Two tables. rust_servers is configuration an operator writes; rust_server_state
  is what a sidecar reported. Separate tables because they have different
  writers, lifetimes and audiences -- and because purging observed state while
  keeping the configuration is a thing an operator will want.
* Per-server sidecar tokens through ctx.secretBox, write-only in the API. The
  admin list reports hasToken and never the credential, and an empty token on a
  save leaves the stored one alone -- a form that posts its own blank field would
  otherwise erase a credential every time somebody renamed a server.
* A real sidecar client. It never throws: every call answers {ok, status, data},
  and the status is what tells a wrong URL from a wrong token from a mismatched
  protocol -- all three present as 'the site says my server is offline' and each
  has a different fix.
* The five guards, green: check:imports, check:swagger, check:externals, and both
  suites.

What is deliberately NOT registered: the Team provider, triggers, audiences,
engagement seeds, notification streams, the four event catalogues, and the two
extension slots. Each arrives with the phase that has something real to put in
it, and a test asserts their absence so that removing it is deliberate. A
declared trigger nothing emits and a declared slot nothing fills are both
surfaces an operator can configure and then wait on, which is worse than an
absent one because the absence is visible.

Two corrections to the kit's template, both feedback for a later phase:

* registration.test.js read one page BY NAME to check declared slots are
  rendered, so a module declaring none dies on ENOENT before reaching the loop
  that would have been empty. It now scans every file under src/routes.
* test/_fakes.js supplied validator: {}. An admin router that builds validation
  chains at file scope cannot be required with that, so the fake holds the real
  express-validator -- for the same reason it holds a real express Router.

The kit was right about noGameConnection.test.js: its header predicts that a
module adding a sidecar client will see the check go red, names sidecarClient.js
as the file to allow, and says narrow it rather than delete it. That is exactly
what happened on the first run, and the fix was the one line the header names.

Installed into a real core and verified: the module reaches 'started', publishes
its capability, serves its chunk, and renders a server whose server.hello
originated in a live Rust server.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016wDDVXWMDz82WqE1i969r4
2026-09-15 19:54:08 -05:00

138 lines
6.9 KiB
JavaScript

// ── The client half's library build ────────────────────────────────────────
//
// Produces `dist/entry.js`: one prebuilt ES module that core injects as a
// same-origin `<script type="module" src>` before `</body>`. The operator never
// builds anything (MODULE_SYSTEM.md §1.14), so this config is not a developer
// convenience — it is how the artifact that ships is made, and CI runs it.
//
// The normative contract is MODULE_API.md §3.6. Three mechanical details in here
// were each found the hard way and are worth reading before changing anything.
//
// **1. `resolve.alias` uses the ARRAY form with anchored regexes.** Vite's object
// form does PREFIX matching, so a `react` key also rewrites `react/jsx-runtime`
// — silently, to the wrong shim, and the chunk then fails at its first element
// with a message about `jsx` not being a function. `^react$` and
// `^react/jsx-runtime$` cannot collide.
//
// **2. The aliases replace `external`; they do not accompany it.** §3.6 shows
// both, and they do not compose: Rollup asks `external` BEFORE Vite's alias
// resolver runs, so a specifier listed there is marked external and never
// aliased. The chunk then ships bare `import 'react'` specifiers, which the
// browser cannot resolve without an import map — and core's `script-src 'self'`
// forbids the inline script an import map has to be. (`output.globals` would
// have covered iife/umd and does nothing for an ES module.) The first real module
// shipped with both, built cleanly, and emitted exactly that chunk;
// `scripts/checkExternals.js` is what caught it. So: alias only, and nothing in
// `external`.
//
// **3. What `external` was there to guard is guarded by `assertSharedNotBundled`
// below.** The risk it was covering is real — an alias that misses means a
// second React welded into the chunk, which loads fine and then throws about an
// invalid hook call somewhere unrelated. A resolution-time assertion catches
// that precisely, at build time, instead of by looking for fingerprints in
// minified output afterwards.
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { fileURLToPath } from 'node:url'
const shim = (name) => fileURLToPath(new URL(`./src/shim/${name}.js`, import.meta.url))
// The shared dependencies, in one place: what a module must never bundle, and
// the shim it is aliased to instead. Adding to this list means adding to
// `window.__rg` in core, which is a MODULE_API minor bump — not a decision this
// file can make on its own.
export const SHARED = [
{ specifier: 'react', shim: 'react' },
{ specifier: 'react/jsx-runtime', shim: 'jsx-runtime' },
// A production `vite build` emits the non-dev runtime, but the plugin picks
// per mode and a `--mode development` build would reach for this one. Aliased
// rather than left to chance: the shim re-exports `jsxDEV` too.
{ specifier: 'react/jsx-dev-runtime', shim: 'jsx-runtime' },
{ specifier: 'react-dom', shim: 'react-dom' },
{ specifier: 'react-dom/client', shim: 'react-dom' },
{ specifier: 'react-router-dom', shim: 'react-router-dom' },
]
// The packages whose real source must never end up in the chunk.
//
// Stated independently of SHARED, and that is the whole point — an earlier
// version derived this from the alias list "so the two cannot disagree", which
// meant deleting an alias also deleted the guard against the thing that alias
// prevented. The guard then reported nothing on a chunk with react-router welded
// into it. What may not be bundled is a fact about core's `window.__rg`, not a
// function of what this config happens to alias; `test/build.test.js` asserts
// every SHARED specifier is covered here, which is the direction the dependency
// belongs in.
//
// `react-router` and `@remix-run/router` are react-router-dom's own internals.
// They cannot appear while the alias holds — nothing resolves through to them —
// so naming them costs nothing and closes the case where a module imports one
// directly and gets a second navigation context in a page that otherwise works.
export const SHARED_PACKAGES = ['react', 'react-dom', 'react-router-dom', 'react-router', '@remix-run/router']
/**
* Fail the build if a shared dependency's real source is about to be bundled.
*
* This is the safety net, and it is a resolution-time one on purpose. The
* alternative — grepping the built chunk for a fingerprint — has to guess at
* strings that survive minification, and guesses at that are how a check ends up
* passing on a chunk that carries a second React. Here there is nothing to
* guess: if a module id resolved into `node_modules/react`, an alias missed, and
* the alias that missed is named in the error.
*
* It hooks `transform` rather than `load`, and that is not interchangeable:
* `load` is FIRST-WINS, so an earlier plugin returning the module's contents
* means this hook is never called for it. Written against `load` this guard sat
* in the build doing nothing, and a deliberately-broken alias produced a 24 kB
* chunk with react-router welded into it and a green build — which is the exact
* failure it exists to prevent. `transform` runs for every module, every time.
*/
function assertSharedNotBundled() {
return {
name: 'rust:assert-shared-not-bundled',
enforce: 'post',
transform(code, id) {
const normalised = id.split('\\').join('/')
const hit = SHARED_PACKAGES.find((pkg) => normalised.includes(`/node_modules/${pkg}/`))
if (hit) {
this.error(
`"${hit}" resolved into node_modules (${normalised}). It must be aliased to a shim that ` +
're-exports from window.__rg — there is exactly one React in the page and core owns it ' +
'(MODULE_API.md §3.2, §3.6). Check resolve.alias in vite.config.js.',
)
}
return null
},
}
}
export default defineConfig({
plugins: [react(), assertSharedNotBundled()],
resolve: {
alias: SHARED.map(({ specifier, shim: name }) => ({
find: new RegExp(`^${specifier.replace(/[/\\^$*+?.()|[\]{}]/g, '\\$&')}$`),
replacement: shim(name),
})),
},
build: {
lib: {
entry: fileURLToPath(new URL('./src/entry.jsx', import.meta.url)),
formats: ['es'],
// Unhashed, deliberately: `module.json` names this file, and a hashed name
// would have to be discovered at runtime. Core answers the cache question
// instead, serving it `no-cache` so a revalidation catches a new build
// (MODULE_API.md §3.1).
fileName: () => 'entry.js',
},
outDir: 'dist',
emptyOutDir: true,
// No inline bootstrap, for the same reason core disables it: an inline
// script is refused under `script-src 'self'`, and the failure is a chunk
// that never evaluates with a CSP report as the only clue.
modulePreload: { polyfill: false },
// `rollupOptions.external` is deliberately EMPTY — see note 2 at the top.
rollupOptions: { external: [] },
},
})