refactor(bgm): use virtual: module specifiers

Rename the plugin's virtual modules to virtual:bgm/packages and
virtual:bgm/package/<id> so they read as plugin-provided modules rather
than real packages. Update the unit and build integration tests.
This commit is contained in:
2026-08-09 19:16:17 +08:00
parent ba16f17d8a
commit 845d510948
4 changed files with 52 additions and 13 deletions
+25 -6
View File
@@ -1,10 +1,19 @@
/**
* Vite plugin: resolve `bgm/<package>` imports to the package's JSON.
* Vite plugin: resolve `virtual:bgm/packages` and `virtual:bgm/package/<id>`
* imports to JSON.
*
* The loader reads a games root (markdown code blocks + real
* yaml/json/toml/csv files), collects packages, and this plugin serves each
* package as a module whose default export is the assembled JSON. Editing a
* game definition hot-reloads the app via `addWatchFile`.
* yaml/json/toml/csv files), collects packages, and this plugin serves them
* as modules:
*
* - `virtual:bgm/packages` — the default export is an array of every
* discovered package.
* - `virtual:bgm/package/<id>` — the default export is that single package's
* assembled JSON.
*
* The `virtual:` prefix marks these as plugin-provided modules, so they can't
* be mistaken for real installed packages. Editing a game definition
* hot-reloads the app via `addWatchFile`.
*/
import * as path from 'node:path';
import type { Plugin } from 'vite';
@@ -12,6 +21,10 @@ import { collectPackages, loadDefs } from './collect.js';
import type { Package } from './types.js';
const VIRTUAL_PREFIX = '\0bgm:';
/** Public specifier for the module that lists every package. */
const PACKAGES = 'virtual:bgm/packages';
/** Public specifier prefix for a single package module. */
const PACKAGE = 'virtual:bgm/package/';
export interface BgmOptions {
/** Absolute path to the games root (e.g. `<repo>/games`). */
@@ -36,11 +49,17 @@ export function bgm(options: BgmOptions): Plugin {
}
},
resolveId(id) {
if (id.startsWith('bgm/')) return VIRTUAL_PREFIX + id;
if (id === PACKAGES) return VIRTUAL_PREFIX + PACKAGES;
if (id.startsWith(PACKAGE)) return VIRTUAL_PREFIX + id;
},
load(id) {
if (!id.startsWith(VIRTUAL_PREFIX)) return;
const name = id.slice(VIRTUAL_PREFIX.length + 'bgm/'.length);
const virtual = id.slice(VIRTUAL_PREFIX.length);
if (virtual === PACKAGES) {
const packages = collect().map(toJson);
return `export default ${JSON.stringify(packages)}`;
}
const name = virtual.slice(PACKAGE.length);
const pkg = collect().find((p) => p.meta.id === name);
if (!pkg) {
throw new Error(`bgm package "${name}" not found`);