Files
worldwideview/scripts/sync-local-plugins.mjs
T
SilvertakanaandClaude Sonnet 4.6 58aac77a0b fix(engine): resolve plugin 404s and local engine routing (#166)
* refactor(marketplace): drive auto-seeding from signed verified registry

Retires the hard-coded DEFAULT_PLUGIN_IDS list and makes the signed
verified registry the single source of truth for what lands in a fresh
install. Publishing a plugin to the verified registry now auto-seeds
it; no code change required to add new defaults.

Also fixes the diagnosed plugins-404: fortiguard and nz-traffic-cameras
were in the static list but not published to npm, causing every fresh
boot to hit manifest 404s. Those entries are gone with the list.

- Delete src/lib/marketplace/defaultPlugins.ts (legacy static list).
- Seeder iterates getVerifiedPluginIds() from registryClient.
- Skip markSeeded when the verified set is empty so a registry outage
  doesn't lock fresh installs into zero plugins; the next request
  retries (5-min cache in registryClient bounds the request rate).
- Stamp every seeded plugin as trust=verified by definition.
- Tests rewritten against a fake verified set; new test asserts
  empty-registry deferral.
- Sync marketplace-architecture rule + migrate-legacy-plugin skill
  with the new model.
- Patch bump: 2.15.15 -> 2.15.16.

* fix(engine): resolve plugin 404s and local engine routing (#fix/diagnose-plugins-404)

- fix: engineManifest + resolveEngineUrl: port 5001→5000 to match docker-compose
  binding; removed NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL from local engine
  detection — it was poisoning local routing with the production engine URL (Patch)
- fix: WsClient: added normalizePluginId() converting underscore IDs to kebab-case
  so engine WebSocket messages route to the correct frontend plugin (Patch)
- fix: docker-compose: added ./local-seeders:/app/seeders volume mount to
  wwv-data-engine so locally-developed seeders are visible to the engine (Patch)
- feat: sync-local-plugins: added wwvHostRedirectPlugin — Vite plugin that
  intercepts @/ host-app imports in local plugin builds and redirects them to
  runtime host globals, preventing full app tree from being bundled into plugins (Minor)
- docs: plugin-architecture.md: added Plugin Data Delivery Types section (REST-only,
  WS-only, hybrid), peerDependencies rule, .tsx extension rule, mapWebsocketPayload
  signature contract (Patch)
- docs: data-engine-architecture.md: added §7 WebSocket Payload Format Contract
  documenting WsClient's three payload handling cases and the silent-drop footgun
  for plugins that send object payloads without mapWebsocketPayload (Patch)
- docs: worldwideview-plugin-creation SKILL.md: fixed ISS example which was missing
  mapWebsocketPayload and would have silently dropped all WS data; clarified
  mapWebsocketPayload requirement for non-array payloads; fixed architecture
  decision tree (Patch)
- docs: cesium-rendering.md: added Sizing Conventions table with defaults/ranges
  for point/billboard/model, cross-plugin parity rules, and silent-ignore footgun
  warning for size on billboard entities (Patch)
- docs: added ADR-0002 documenting seeder exported name as canonical plugin ID (Patch)

Version bumps: fix × 3 (Patch), feat × 1 (Minor) → 2.15.16 → 2.16.0

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* test(engine): update resolveEngineUrl test assertion from port 5001 to 5000

Follows the port correction in engineManifest.ts and resolveEngineUrl.ts.
The test was asserting the old default (5001) instead of the corrected
local engine port (5000), causing the Unit Tests CI check to fail.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
2026-05-20 22:44:47 +12:00

283 lines
10 KiB
JavaScript

/**
* @file sync-local-plugins.mjs
* @description Local plugin synchronization and build utility.
* Scans `local-plugins/`, compiles bundles using Vite, and hydrates the
* `public/plugins-local/` directory for the Next.js dev server.
* @module scripts
*/
import fs from "fs";
import path from "path";
import { build } from "vite";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, "..");
const LOCAL_PLUGINS_DIR = path.join(ROOT, "local-plugins");
const OUTPUT_DIR = path.join(ROOT, "public", "plugins-local");
// External globals — must match extract-plugins.mjs pattern
const EXTERNAL_GLOBALS = {
"react": "globalThis.__WWV_HOST__.React",
"react-dom": "globalThis.__WWV_HOST__.ReactDOM",
"react/jsx-runtime": "globalThis.__WWV_HOST__.jsxRuntime",
"@worldwideview/wwv-plugin-sdk": "globalThis.__WWV_HOST__.WWVPluginSDK",
"cesium": "globalThis.__WWV_HOST__.Cesium",
"resium": "globalThis.__WWV_HOST__.Resium",
};
/**
* Synthetic host-module exports for `@/` imports that plugins use to access
* the host application's runtime objects (store, plugin manager, components).
*
* When a plugin sub-component does `import { useStore } from "@/core/state/store"`,
* the tsconfig `@/*` alias (inherited from the main app root tsconfig) would normally
* resolve that to the actual `src/core/state/store.ts` file — pulling the entire Zustand
* store (and its transitive deps like `src/core/edition.ts`) into the bundle.
* This plugin intercepts those imports at the resolveId stage, before Vite touches
* the filesystem, and substitutes a synthetic module that reads from the host globals
* injected at runtime by `hostGlobals.ts`.
*/
const HOST_MODULE_SYNTHETICS = {
"@/core/state/store": `export const useStore = globalThis.__WWV_HOST__.useStore;`,
"@/core/plugins/PluginManager": `export const pluginManager = globalThis.__WWV_HOST__.pluginManager;`,
"@/components/video/CameraStream": `export const CameraStream = globalThis.__WWV_HOST__.CameraStream;`,
"zustand": `
const zustand = globalThis.__WWV_HOST__.zustand || {};
export default zustand;
export const { create, createStore } = zustand;
`,
};
/**
* @function wwvHostRedirectPlugin
* @description Vite plugin that intercepts host-app module imports (`@/core/...`,
* `@/components/...`) in local plugin builds and redirects them to the runtime
* host globals instead of bundling the full app source tree.
*
* @returns {import('vite').Plugin}
*/
function wwvHostRedirectPlugin() {
return {
name: "wwv-host-redirect",
enforce: "pre",
resolveId(id) {
if (id in HOST_MODULE_SYNTHETICS) return `\0${id}`;
return null;
},
load(id) {
if (!id.startsWith("\0")) return null;
const originalId = id.slice(1);
return HOST_MODULE_SYNTHETICS[originalId] ?? null;
},
};
}
/**
* @function discoverLocalPlugins
* @description Finds all directories in `local-plugins/` that contain a valid
* `package.json` with a `worldwideview` manifest block.
* @returns {Array<{dir: string, manifest: any, pluginDir: string}>}
*/
export function discoverLocalPlugins() {
if (!fs.existsSync(LOCAL_PLUGINS_DIR)) return [];
return fs.readdirSync(LOCAL_PLUGINS_DIR)
.filter(dir => {
if (dir.startsWith(".")) return false;
const pkgPath = path.join(LOCAL_PLUGINS_DIR, dir, "package.json");
if (!fs.existsSync(pkgPath)) return false;
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
return !!pkg.worldwideview;
})
.map(dir => {
const pkgPath = path.join(LOCAL_PLUGINS_DIR, dir, "package.json");
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
const manifest = pkg.worldwideview;
manifest.version = pkg.version;
manifest.name = pkg.name;
manifest.description = pkg.description;
return { dir, manifest, pkg, pluginDir: path.join(LOCAL_PLUGINS_DIR, dir) };
});
}
/**
* @function resolvePluginEntry
* @description Resolves the TypeScript source entry file for a plugin.
*
* Resolution order:
* 1. `worldwideview.dev_entry` — explicit override in the manifest block
* 2. `pkg.types` — if it points to a .ts/.tsx source file (not a .d.ts declaration)
* 3. `pkg.source` — explicit source field (less common, but valid)
* 4. Heuristic fallback: src/index.ts → src/index.tsx → index.ts → index.tsx
*
* @param {string} pluginDir - Absolute path to the plugin directory.
* @param {any} manifest - The parsed `worldwideview` manifest block.
* @param {any} pkg - The full parsed package.json object.
* @returns {string|null} Absolute path to the entry file, or null if not found.
*/
function resolvePluginEntry(pluginDir, manifest, pkg) {
const candidates = [];
if (manifest.dev_entry) {
candidates.push(path.join(pluginDir, manifest.dev_entry));
}
// pkg.types points to the TS source in all WWV plugins (e.g. "src/index.ts")
if (pkg.types && !pkg.types.endsWith(".d.ts")) {
candidates.push(path.join(pluginDir, pkg.types));
}
if (pkg.source) {
candidates.push(path.join(pluginDir, pkg.source));
}
// Heuristic fallbacks
for (const rel of ["src/index.ts", "src/index.tsx", "index.ts", "index.tsx"]) {
candidates.push(path.join(pluginDir, rel));
}
return candidates.find(f => fs.existsSync(f)) ?? null;
}
/**
* @function buildPlugin
* @description Invokes the Vite build engine to compile a plugin's source
* into a single ES module, externalizing shared host dependencies.
*/
export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
const entryFile = resolvePluginEntry(pluginDir, manifest, pkg ?? {});
if (!entryFile) {
console.warn(`[sync] ⚠ No entry file found for ${dir}, skipping`);
return false;
}
try {
await build({
root: pluginDir,
// Disable auto-loading the plugin's own vite.config.ts — the local
// plugins' node_modules may be symlinked to a different repo's SDK
// build (worktree scenario), which breaks config loading. The sync
// script provides all necessary config inline.
configFile: false,
logLevel: "warn",
plugins: [wwvHostRedirectPlugin()],
build: {
lib: {
entry: entryFile,
formats: ["es"],
fileName: () => "frontend.mjs",
},
outDir: "dist",
emptyOutDir: true,
rollupOptions: {
external: Object.keys(EXTERNAL_GLOBALS),
output: {
globals: EXTERNAL_GLOBALS,
codeSplitting: false,
banner: '"use client";',
},
plugins: [(await import("rollup-plugin-external-globals")).default(EXTERNAL_GLOBALS)],
onwarn(warning, warn) {
if (warning.code === 'MODULE_LEVEL_DIRECTIVE' && warning.message.includes('"use client"')) {
return;
}
if (warning.code === 'SOURCEMAP_ERROR') {
return;
}
warn(warning);
}
},
minify: false, // Keep readable for dev
sourcemap: true,
},
});
return true;
} catch (err) {
console.error(`[sync] ❌ Build failed for ${dir}:`, err.message);
return false;
}
}
export function syncToPublic({ dir, manifest, pluginDir }) {
const publicName = manifest.id || dir.replace("wwv-plugin-", "");
const targetDir = path.join(OUTPUT_DIR, publicName);
const distFile = path.join(pluginDir, "dist", "frontend.mjs");
const distMap = path.join(pluginDir, "dist", "frontend.mjs.map");
if (!fs.existsSync(distFile)) {
console.warn(`[sync] ⚠ No dist for ${dir}, skipping sync`);
return;
}
fs.mkdirSync(targetDir, { recursive: true });
fs.copyFileSync(distFile, path.join(targetDir, "frontend.mjs"));
if (fs.existsSync(distMap)) {
fs.copyFileSync(distMap, path.join(targetDir, "frontend.mjs.map"));
}
// Generate plugin.json manifest for the marketplace load route
const pluginJson = {
id: manifest.id || publicName,
name: manifest.name || publicName,
version: manifest.version || "0.0.0",
description: manifest.description || "",
type: manifest.type || "data-layer",
format: "bundle",
trust: "unverified",
capabilities: manifest.capabilities || ["data:own"],
category: manifest.category || "custom",
icon: manifest.icon || "Box",
entry: `/plugins-local/${publicName}/frontend.mjs`,
};
fs.writeFileSync(
path.join(targetDir, "plugin.json"),
JSON.stringify(pluginJson, null, 2)
);
console.log(`[sync] ✅ ${publicName} → public/plugins-local/${publicName}/`);
}
// Clean stale plugins from public/plugins-local/ that no longer exist in local-plugins/
function cleanStale(activeIds) {
if (!fs.existsSync(OUTPUT_DIR)) return;
const activeSet = new Set(activeIds);
for (const dir of fs.readdirSync(OUTPUT_DIR)) {
if (!activeSet.has(dir)) {
fs.rmSync(path.join(OUTPUT_DIR, dir), { recursive: true, force: true });
console.log(`[sync] 🗑 Removed stale plugin: ${dir}`);
}
}
}
export async function syncAll() {
const plugins = discoverLocalPlugins();
if (plugins.length === 0) {
console.log("[sync] No local plugins found.");
cleanStale([]);
return;
}
console.log(`[sync] Found ${plugins.length} local plugin(s): ${plugins.map(p => p.dir).join(", ")}`);
for (const plugin of plugins) {
const ok = await buildPlugin(plugin);
if (ok) syncToPublic(plugin);
}
const activeIds = plugins.map(p => p.manifest.id || p.dir.replace("wwv-plugin-", ""));
cleanStale(activeIds);
}
// Run directly: node scripts/sync-local-plugins.mjs
const isDirectRun = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
if (isDirectRun) {
syncAll().catch(err => {
console.error("[sync] Fatal:", err);
process.exit(1);
});
}