Compare commits

..
Author SHA1 Message Date
Antigravity AI a0646a5ab1 fix: merge origin/main, resolve version conflict (bump to 2.48.24)
Merged latest main (2.48.23) into fix/hardcoded-engine-urls. Resolved the
single conflict in package.json by taking main's changes and bumping the
version to 2.48.24 per the patch-level commit rule.
2026-06-05 00:28:16 +12:00
Silvertakana 9a5adb832e docs(rules): seeder authoring contract + close-context-gaps meta-directive (#240)
* docs(rules): add seeder authoring contract to data-engine-architecture rule

Adds section 8 documenting how to write a seeder: the auto-discovery model,
the three module shapes (interval+fetch, cron+fn, init), the { redis }-only
ctx, and publishing via @worldwideview/seeder-sdk. Includes good/bad examples
contrasting the ctx.setLiveSnapshot trap (which caused a silent CI failure)
against the two correct shapes. This rule auto-loads on local-seeders/** edits.

* docs(rules): add close-context-gaps AI meta-directive to AGENTS.md

When missing/wrong/undocumented context causes an error, a long struggle, or
slow understanding, agents must fix the doc/context (or add a guardrail) at its
source, or ask the user to; in autonomous mode, log the gap to revisit. Codifies
the lesson from the seeder ctx.setLiveSnapshot incident for all contributors.
2026-06-05 00:25:44 +12:00
Antigravity AI 3200d38194 refactor(env): rename NEXT_PUBLIC_WWV_DATA_ENGINE_URL to NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL
Rename the env var to make its scope unambiguous: it is a local dev
override only and must never be set in production. Split the old single
var into two with clearly documented purposes:

- NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL (local dev, .env.local, browser+server)
  Used by resolveEngineUrl.ts and engineManifest.ts to redirect WS
  connections to a locally-running engine during plugin development.
  Each worktree should use a different port to avoid collisions.

- WWV_DATA_ENGINE_URL (production, docker-compose/Coolify, server-side only)
  Used by service.ts for MCP REST calls to the engine. NOT read by
  the browser. Set in docker-compose, not in .env.local.

service.ts shim reads WWV_DATA_ENGINE_URL first so existing production
docker-compose deployments are not broken by this rename.

Also fixes stale dataengine.worldwideview.dev subdomain references in
hostGlobals.ts (cloud fallback URLs now correctly point to dataenginev2).
2026-06-05 00:24:27 +12:00
Silvertakana f447bd7e72 fix(ci): stub seeder interval+fetch + drop redundant compose mount (#239)
Companion to wwv-data-engine fix/ci-stub-interval-fetch. The source-of-truth
stub (docker/ci/stub-seeder) used cron+fn and called ctx.setLiveSnapshot,
which the seeder ctx ({ redis }) does not expose — the snapshot never landed.
Switch to interval+fetch (return the array; scheduler auto-wraps + stores it).

Also remove the plugin-CI compose's ./stub-seeder volume mount and the stale
'Known foundation gap (deferred)' comment: the stub is now baked into the :ci
image at /app/seeders/stub, so the compose needs no host path and a consumer
repo can run it with only this YAML.
2026-06-04 23:58:20 +12:00
Silvertakana a833cf4790 fix(ci-probe): subscribe to pluginId on /stream + safe stub + plugin-CI auth bypass (#238) 2026-06-04 23:40:08 +12:00
SilvertakanaandClaude Sonnet 4.6 352fbce768 feat: CI smoke-test foundation (probe + mock-upstream + isolated docker CI) (#236)
* feat: CI smoke-test foundation (probe + docker compose + rule updates)

Phase 1 of multi-repo CI initiative for catching plugin/seeder integration
failures (ADR-0002 id drift, missing mapWebsocketPayload, namespace
collisions, BOM in package.json) that current CI misses.

- packages/wwv-ci-probe: shared CLI with `seeder`, `ws`, `id-contract`
  subcommands. README documents why no `plugin` subcommand (Playwright belongs
  in wwv-plugins, not coupled to this probe). `files` + `prepublishOnly`
  configured for clean npm publish.
- docker/ci/: reusable docker-compose stacks for plugin-CI and seeder-CI,
  plus mock-upstream HTTP fixture server and CI-only stub-seeder. Compose
  comments document scope boundary (consumer workflow owns user/plugin-row
  injection via Playwright globalSetup pattern) and the deferred stub-seeder
  bake-in for wwv-data-engine.
- .github/workflows/docker-publish.yml: adds `:ci` tag alias for downstream
  consumers (one-line edit).
- .agents/rules/*: rename worldwideview-plugins → wwv-plugins (4 files) to
  reflect repo rename + clarify it lives at local-plugins/ as its own git
  working tree.

Bump 2.15.16 → 2.16.0 (Minor — new ci-probe package + new docker/ci
infrastructure are net-new features for the CI ecosystem).

Foundation has NOT been booted end-to-end yet — ghcr.io/silvertakana/
worldwideview:ci doesn't exist until this lands on main and the workflow
publishes. Next session: validate via real compose-up, then mirror the :ci
tag in wwv-data-engine repo and wire consumer workflows in wwv-plugins.

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

* refactor(ci-probe): extract shared payload-shape validator with contract tests

* fix(ci): add /__health route to mock-upstream and gate engine on service_healthy

* chore: bump version to 2.48.18 for CI foundation landing

* chore: bump to 2.48.19 and reconcile lockfile after merging main (validateManifest fix)

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
2026-06-04 23:00:02 +12:00
Antigravity AI 1831e7e5d8 docs(rules): document data engine agnosticism separation of concern
Add an explicit rule section clarifying that plugins own their streamUrl,
WWV never overrides it globally, and the NEXT_PUBLIC_WWV_DATA_ENGINE_URL var
is for server-side REST calls only -- not plugin streaming.
2026-06-04 22:35:45 +12:00
Antigravity AI 0f43baacf0 fix(engine): replace stale dataengine subdomain with dataenginev2
hostGlobals.ts and resolveEngineUrl.ts comment both referenced the old
dataengine.worldwideview.dev subdomain; updated to dataenginev2.worldwideview.dev.
2026-06-04 22:35:17 +12:00
Antigravity AI 138f26c8e8 refactor(data-engine): consolidate engine URL to single NEXT_PUBLIC_WWV_DATA_ENGINE_URL
Replaces two separate env vars (NEXT_PUBLIC_WWV_LOCAL_ENGINE_PORT and
WWV_DATA_ENGINE_URL) with one: NEXT_PUBLIC_WWV_DATA_ENGINE_URL (full
HTTP base URL, default http://localhost:5000). Available both client-side
and server-side so it only needs to be defined once.

- engineManifest.ts: getLocalEngineBase() reads the new var directly
- resolveEngineUrl.ts: getLocalWsUrl() converts http->ws from the new var
- service.ts: getEngineUrl() reads the new var (fixes 5001->5000 default)
- Tests updated to set the full URL instead of a port number
- .env.example documents the new var with local and Docker examples
2026-06-04 22:24:08 +12:00
Antigravity AI cdad4dc776 fix(data-engine): replace hardcoded engine URLs with env var
Deduplicates the WWV_DATA_ENGINE_URL fallback: discoveryHelpers.ts now
calls getEngineUrl() from data-query/service instead of inlining the
same logic. Comments and test mocks that referenced literal localhost:5001
or localhost:5000 now reference NEXT_PUBLIC_WWV_LOCAL_ENGINE_PORT or use
a generic test host. Closes #182.
2026-06-04 21:10:21 +12:00
18 changed files with 269 additions and 52 deletions

No files matched your search

+57
View File
@@ -89,3 +89,60 @@ This means:
> [!CAUTION]
> The most common silent bug: seeder sends `{ items: [...] }` (an object), frontend plugin omits `mapWebsocketPayload`. Data arrives but WsClient drops it with a console warning. The globe stays empty. Always implement `mapWebsocketPayload` for any plugin whose seeder sends an object payload.
## 8. Seeder Authoring Contract — the module shape
§7 covers what a seeder **sends**. This covers how you **write** one. The engine
auto-discovers a seeder by scanning `SEEDERS_DIR` for any folder with
`dist/index.mjs` and importing its **default export**. The seeder's `id` is the
**folder name**, not the `name` field. You never call a register function — the
authoritative reference is `wwv-data-engine/README.md` → "Authoring a Seeder".
The default export is `{ name }` plus **one** of these shapes:
| Shape | You provide | How data is published |
|---|---|---|
| `interval` + `fetch(ctx)` | `fetch` **returns** the array | scheduler wraps + stores + broadcasts it for you |
| `cron` + `fn(ctx)` | `fn` publishes itself | `import { setLiveSnapshot } from '@worldwideview/seeder-sdk'` and call it |
| `init(ctx)` | a persistent listener | publish via the SDK as push data arrives |
**The trap (this caused a real, silent CI failure):** `ctx` is **only `{ redis }`**.
There is no `ctx.setLiveSnapshot`. Reaching for it throws at runtime and the
snapshot never lands. Publish helpers come from `@worldwideview/seeder-sdk`, not
from `ctx`. The engine now types `ctx` as `SeederContext { redis }`, so this is a
compile error for any typed seeder — but `.mjs` seeders without type-checking get
no such safety net, so know the contract.
<bad-example>
```ts
// cron + fn reaching for a method that does not exist on ctx
export default {
name: "earthquakes",
cron: "0 * * * *",
fn: async (ctx) => {
await ctx.setLiveSnapshot("earthquakes", items, 3600); // ❌ not a function — dies silently
},
};
```
</bad-example>
<good-example>
```ts
// Option A — cron + fn: publish via the SDK (dominant idiom)
import { setLiveSnapshot } from "@worldwideview/seeder-sdk";
export default {
name: "earthquakes",
cron: "0 * * * *",
fn: async () => {
await setLiveSnapshot("earthquakes", { source: "earthquakes", fetchedAt: new Date().toISOString(), items, totalCount: items.length }, 3600);
},
};
// Option B — interval + fetch: just return the array, scheduler does the rest
export default {
name: "earthquakes",
interval: 60_000,
fetch: async () => items, // ✅ no publishing call needed
};
```
</good-example>
+16
View File
@@ -12,6 +12,22 @@ paths:
## Purpose
The standard operating procedure for instantiating, modifying, and registering a new data source plugin within the engine.
## Data Engine Agnosticism (Separation of Concern)
> [!IMPORTANT]
> **WWV is agnostic to which data engine a plugin uses.** Each plugin MUST declare its own `streamUrl` in `getServerConfig()`. The WWV application never controls or overrides plugin stream URLs.
This is intentional architectural separation: a user can have 30 plugins pointing to 30 different custom backend servers, and WWV opens 30 separate WebSocket connections without caring. The WWV app does not have a "the data engine" — each plugin has its own.
**Practical rules:**
- Plugins hardcode their cloud engine URL (e.g. `wss://dataenginev2.worldwideview.dev/stream`) — this is correct and by design.
- Do not add env vars to let WWV override a plugin's `streamUrl` globally — that breaks the separation.
- When editing a plugin's fallback fetch URL, use `https://dataenginev2.worldwideview.dev` (note the `v2`).
- `NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL` is a local dev only var (`.env.local` only, never production) that routes locally-developed plugin seeders to a local engine instance. It is NOT injected into plugin stream URLs.
- `WWV_DATA_ENGINE_URL` is the production server-side var (docker-compose / Coolify) for the WWV app's own REST calls (MCP tools, entity search). Never set `NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL` in production.
---
## The WorldPlugin Contract
All data ingest flows through `WorldPlugin` (defined entirely within `@worldwideview/wwv-plugin-sdk`).
+13
View File
@@ -96,6 +96,19 @@ PROXY_HOST_ALLOWLIST=*
# Comma-separated list of plugin IDs
NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS=
# Local Engine URL (local dev only — set in .env.local, NEVER in production)
# Points at your local data engine instance for per-plugin WS stream routing.
# Each worktree should use a different port so their engines don't collide.
# Local dev (engine on host): http://localhost:5000
NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL=
# Data Engine REST URL (production / Docker Compose — server-side only)
# Used by MCP data tools and server-side entity queries to reach the engine REST API.
# NOT read by the browser. Set this in docker-compose or Coolify, not in .env.local.
# Docker Compose (same network): http://wwv-data-engine:5000
# External engine: http://<engine-host-ip>:5002
# WWV_DATA_ENGINE_URL=
# Edition: "local" | "cloud" | "demo"
NEXT_PUBLIC_WWV_EDITION=local
+1
View File
@@ -60,6 +60,7 @@ Agents MUST respect these at all times:
> - **MUST** require explicit user authorization before any state-changing action that isn't simple/safe.
> - **MUST** ask clarifying questions rather than assume when requirements are unclear.
> - **MUST** update `.agents/rules/` files immediately whenever an architectural shift invalidates them.
> - **MUST** close context gaps: when missing/wrong/undocumented context made you err, struggle, or go slow, fix the relevant doc/context (or add a type/guardrail) at its source — or ask the user to update it when it depends on their knowledge. In autonomous mode, log the gap to revisit later. Never fix only the symptom and leave the trap armed for the next contributor.
---
+10 -14
View File
@@ -18,18 +18,12 @@
# Reuse the pattern from worldwideview/tests/global.setup.ts. DB migrations
# are handled automatically by the wwv-app entrypoint at container start.
#
# ─── Known foundation gap (deferred) ───
# ─── Stub seeder source ───
#
# The stub-seeder is mounted via `./stub-seeder:/app/seeders/community/stub-seeder`
# below — a path RELATIVE to this compose file. When a consumer repo downloads
# only this YAML, that path resolves to nothing. The clean fix is to bake the
# stub-seeder into the `wwv-data-engine:ci` image at /app/seeders/community/__ci-stub__/
# so the compose only needs to set STUB_PLUGIN_ID. That requires a coordinated
# Dockerfile change in the wwv-data-engine repo — tracked as the next session's
# first task.
#
# Until then, this compose only works when the worldwideview source tree
# (with docker/ci/stub-seeder/) is the working directory.
# The stub seeder is baked into the `wwv-data-engine:ci` image at
# /app/seeders/stub (see wwv-data-engine/Dockerfile.ci). The compose only needs
# to set STUB_PLUGIN_ID — no volume mount, so a consumer repo can download just
# this YAML and run it without the worldwideview source tree present.
#
# Expected env vars from consuming workflow:
# PLUGIN_ID — kebab-case id of the plugin under test (e.g. "aviation")
@@ -69,9 +63,11 @@ services:
DB_PATH: /tmp/engine.db
# Stub seeder reads the target plugin id from this env var
STUB_PLUGIN_ID: ${PLUGIN_ID}
volumes:
# Mount only the stub seeder — no other seeders to avoid contamination
- ./stub-seeder:/app/seeders/community/stub-seeder:ro
WWV_SKIP_WS_AUTH: "true"
NODE_ENV: ci
# No volume mount: the stub seeder is baked into the :ci image at
# /app/seeders/stub, so the engine discovers it as id "stub" with no host
# path dependency.
depends_on:
wwv-redis:
condition: service_healthy
+19 -14
View File
@@ -7,10 +7,14 @@
// fine in CI. Do NOT copy this pattern into real seeders.
const pluginId = process.env.STUB_PLUGIN_ID;
if (!pluginId) {
console.error("[stub-seeder] STUB_PLUGIN_ID env var is required");
process.exit(1);
}
// When unconfigured (e.g. seeder-CI, where this stub is baked into the shared
// :ci image but unused), export a nameless module so the seeder-loader skips
// it instead of crashing the engine.
//
// Uses the interval+fetch seeder contract: fetch() RETURNS the array and the
// scheduler auto-wraps it into a snapshot stored under the seeder id. The
// cron+fn contract would require the engine-internal setLiveSnapshot, which is
// NOT exposed on the seeder ctx (ctx is only { redis }).
function makeEntities() {
const now = new Date().toISOString();
@@ -38,13 +42,14 @@ function makeEntities() {
];
}
export default {
name: pluginId,
// Run immediately and every 10s — CI doesn't wait for cron schedules
cron: "*/10 * * * * *",
fn: async (ctx) => {
const entities = makeEntities();
await ctx.setLiveSnapshot(pluginId, entities, 300);
console.log(`[stub-seeder] emitted ${entities.length} entities for ${pluginId}`);
},
};
export default pluginId
? {
name: pluginId,
interval: 10000,
fetch: async () => {
const entities = makeEntities();
console.log(`[stub-seeder] emitting ${entities.length} entities for ${pluginId}`);
return entities;
},
}
: {};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.48.19",
"version": "2.48.24",
"private": true,
"type": "module",
"packageManager": "[email protected]",
+36
View File
@@ -0,0 +1,36 @@
import { describe, it, expect, afterEach } from "vitest";
import { WebSocketServer } from "ws";
import { probeWs } from "./ws.js";
let server: WebSocketServer | undefined;
afterEach(() => { server?.close(); server = undefined; });
function startEngine(opts: { pluginId: string; requireSubscribe: boolean }) {
server = new WebSocketServer({ port: 0 });
server.on("connection", (sock) => {
sock.send(JSON.stringify({ type: "welcome", engine: "test", plugins: [opts.pluginId] }));
const send = () =>
sock.send(JSON.stringify({ type: "data", pluginId: opts.pluginId, payload: [{ id: "x" }] }));
if (!opts.requireSubscribe) { setInterval(send, 20); return; }
sock.on("message", (raw) => {
const msg = JSON.parse(raw.toString());
if (msg.action === "subscribe" && msg.pluginId === opts.pluginId) send();
});
});
const addr = server.address();
const port = typeof addr === "object" && addr ? addr.port : 0;
return `ws://127.0.0.1:${port}/stream`;
}
describe("probeWs", () => {
it("receives data from a subscribe-required engine (sends subscribe frame)", async () => {
const url = startEngine({ pluginId: "stub", requireSubscribe: true });
const ok = await probeWs({ name: "stub", wsUrl: url, timeoutMs: 3000 });
expect(ok).toBe(true);
});
it("times out (false) when the plugin never produces data", async () => {
const url = startEngine({ pluginId: "other", requireSubscribe: true });
const ok = await probeWs({ name: "stub", wsUrl: url, timeoutMs: 800 });
expect(ok).toBe(false);
});
});
+5 -1
View File
@@ -31,7 +31,11 @@ export async function probeWs(opts: {
}, opts.timeoutMs);
ws.on("open", () => {
console.log(`[ws] connected to ${opts.wsUrl}, waiting for pluginId="${opts.name}"`);
// The engine is subscribe-required: it only broadcasts a plugin's data to
// connections that have subscribed to it (websocket.ts broadcastPluginData).
// Auth is bypassed in CI via WWV_SKIP_WS_AUTH=true, so no auth frame is sent.
ws.send(JSON.stringify({ action: "subscribe", pluginId: opts.name }));
console.log(`[ws] connected to ${opts.wsUrl}, subscribed to pluginId="${opts.name}"`);
});
ws.on("message", (raw) => {
+2 -2
View File
@@ -15,7 +15,7 @@
import type { PluginDataSnapshot } from "@/lib/data-query/types";
import type { RegionOptions } from "@/lib/data-query/types";
import type { FilterDefinition } from "@/core/plugins/PluginTypes";
import { getAllPluginSnapshots } from "@/lib/data-query/service";
import { getAllPluginSnapshots, getEngineUrl } from "@/lib/data-query/service";
import { getLocalSourceIds } from "@/lib/data-query/localSources";
import { readActiveSessions, readGlobeState } from "@/lib/globeStateStore";
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
@@ -112,7 +112,7 @@ export interface ListStreamingPluginsResult {
* are not blocked waiting for a slow engine.
*/
async function probeEngineReachable(): Promise<boolean> {
const engineUrl = (process.env.WWV_DATA_ENGINE_URL ?? "http://localhost:5001") + "/manifest";
const engineUrl = getEngineUrl() + "/manifest";
try {
const res = await fetch(engineUrl, { signal: AbortSignal.timeout(2000) });
return res.ok;
+1 -1
View File
@@ -64,7 +64,7 @@ describe("resolveEngineUrl", () => {
await fetchLocalEngineManifest();
const url = resolveEngineUrl("plugin-local");
expect(url).toContain("localhost:5000/stream");
expect(url).toMatch(/ws:\/\/localhost:\d+\/stream/);
});
it("should fall back to plugin's custom streamUrl if not local", () => {
@@ -0,0 +1,46 @@
// src/core/data/__tests__/engineManifest.test.ts
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { fetchLocalEngineManifest, resetManifestCache } from '../engineManifest';
const mockFetch = vi.fn();
describe('fetchLocalEngineManifest', () => {
beforeEach(() => {
resetManifestCache();
mockFetch.mockReset();
vi.stubGlobal('fetch', mockFetch);
});
afterEach(() => {
vi.unstubAllGlobals();
delete process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL;
});
it('probes port 5000 when NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL is not set', async () => {
mockFetch.mockResolvedValue({ ok: false } as Response);
await fetchLocalEngineManifest();
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining(':5000/manifest'),
expect.any(Object)
);
});
it('probes the env-configured URL when NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL is set', async () => {
process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL = 'http://localhost:5003';
mockFetch.mockResolvedValue({ ok: false } as Response);
await fetchLocalEngineManifest();
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining(':5003/manifest'),
expect.any(Object)
);
});
it('returns plugin list when engine responds successfully', async () => {
mockFetch.mockResolvedValue({
ok: true,
json: async () => ({ plugins: ['flight-tracker', 'ais-tracker'] }),
} as Response);
const result = await fetchLocalEngineManifest();
expect(result).toEqual(['flight-tracker', 'ais-tracker']);
});
});
@@ -0,0 +1,42 @@
// src/core/data/__tests__/resolveEngineUrl.test.ts
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('../engineManifest', () => ({
localEngineHasPlugin: vi.fn(),
}));
vi.mock('@/core/plugins/PluginManager', () => ({
pluginManager: {
getPlugin: vi.fn().mockReturnValue(null),
getManifest: vi.fn().mockReturnValue(null),
},
}));
import { resolveEngineUrl } from '../resolveEngineUrl';
import { localEngineHasPlugin } from '../engineManifest';
describe('resolveEngineUrl', () => {
beforeEach(() => {
vi.mocked(localEngineHasPlugin).mockReset();
});
afterEach(() => {
delete process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL;
});
it('uses port 5000 by default when no env var is set', () => {
vi.mocked(localEngineHasPlugin).mockReturnValue(true);
expect(resolveEngineUrl('test-plugin')).toContain(':5000/stream');
});
it('uses the configured URL when NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL is set', () => {
process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL = 'http://localhost:5003';
vi.mocked(localEngineHasPlugin).mockReturnValue(true);
expect(resolveEngineUrl('test-plugin')).toContain(':5003/stream');
});
it('falls back to cloud URL when local engine does not have the plugin', () => {
vi.mocked(localEngineHasPlugin).mockReturnValue(false);
expect(resolveEngineUrl('test-plugin')).toContain('worldwideview.dev');
});
});
+5 -8
View File
@@ -8,16 +8,13 @@ let manifestFetched = false;
/**
* Resolve the base URL of the local data engine.
*
* Always checks localhost:5000 — the port docker-compose.yml binds for
* wwv-data-engine. NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL is intentionally
* NOT used here: that variable belongs to each plugin's own declared engine
* URL (production, third-party, etc.) and must not poison local detection.
* Mixing the two caused the production engine to be reported as "local".
* Reads NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL (default http://localhost:5000).
* Only set this in .env.local for local development — never in production.
* Each plugin owns its own streamUrl; this variable is only for routing
* locally-developed plugin seeders to a local engine instance.
*/
function getLocalEngineBase() {
const port = process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_PORT || '5000';
if (typeof window === "undefined") return `http://localhost:${port}`;
return `${window.location.protocol}//${window.location.hostname}:${port}`;
return process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL ?? 'http://localhost:5000';
}
/**
+5 -5
View File
@@ -20,19 +20,19 @@ function toWsStreamUrl(url: string): string {
const DEFAULT_ENGINE_URL = toWsStreamUrl(RAW_ENGINE_URL);
function getLocalWsUrl() {
const port = process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_PORT || '5000';
if (typeof window === "undefined") return `ws://localhost:${port}/stream`;
return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.hostname}:${port}/stream`;
const base = process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL ?? 'http://localhost:5000';
const ws = base.replace(/^https:\/\//, 'wss://').replace(/^http:\/\//, 'ws://');
return ws.replace(/\/+$/, '') + '/stream';
}
/**
* Resolves the WebSocket engine URL for a given plugin.
*
* Resolution order:
* 1. Local engine (if running at localhost:5000 and has this plugin's seeder)
* 1. Local engine (if running at NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL and has this plugin's seeder)
* 2. Plugin's ServerPluginConfig.streamUrl (code-based plugins)
* 3. Plugin's PluginManifest.dataSource.streamUrl (manifest-based plugins)
* 4. NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL env var
* 5. Fallback: wss://dataengine.worldwideview.dev/stream (cloud)
* 5. Fallback: wss://dataenginev2.worldwideview.dev/stream (cloud)
*/
export function resolveEngineUrl(pluginId: string): string {
// 1. Local engine (split-routing) - PRIORITY #1
+4 -4
View File
@@ -70,18 +70,18 @@ export async function injectHostGlobals(): Promise<void> {
};
// REST Engine URL (Fallback)
// Note: Local Docker-based engine interception (localhost:5000) happens dynamically inside
// resolveEngineUrl.ts during plugin routing. These variables act as global fallbacks.
// Note: Local engine interception (via NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL) happens dynamically
// inside resolveEngineUrl.ts during plugin routing. These variables act as global fallbacks.
const envDataEngine = process.env.NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL;
if (envDataEngine) {
(globalThis as Record<string, unknown>).__WWV_ENGINE_URL__ = envDataEngine;
} else {
// ALWAYS default to the cloud engine unless explicitly told otherwise via env var
(globalThis as Record<string, unknown>).__WWV_ENGINE_URL__ = 'https://dataengine.worldwideview.dev';
(globalThis as Record<string, unknown>).__WWV_ENGINE_URL__ = 'https://dataenginev2.worldwideview.dev';
}
// WebSocket Engine URL
const fallbackWs = envDataEngine ? `${envDataEngine.replace(/^http/, "ws")}/stream` : 'wss://dataengine.worldwideview.dev/stream';
const fallbackWs = envDataEngine ? `${envDataEngine.replace(/^http/, "ws")}/stream` : 'wss://dataenginev2.worldwideview.dev/stream';
(globalThis as Record<string, unknown>).__WWV_WS_ENGINE_URL__ = fallbackWs;
console.log("[HostGlobals] React and SDK injected for dynamic plugins");
@@ -123,7 +123,7 @@ describe("DeclarativePlugin", () => {
getCurrentTime: () => new Date(),
env: {},
edition: "local",
getEngineUrl: () => "http://localhost:5001",
getEngineUrl: () => "http://test-engine/",
});
const entities = await plugin.fetch({ start: new Date(), end: new Date() });
+5 -1
View File
@@ -12,7 +12,11 @@ import type { FilterValue } from "@/core/plugins/PluginTypes";
import { hasLocalSource, resolveLocalSnapshot, getLocalSourceIds } from "./localSources";
export function getEngineUrl(): string {
return process.env.WWV_DATA_ENGINE_URL ?? "http://localhost:5001";
// WWV_DATA_ENGINE_URL = production (docker-compose, server-side only)
// NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL = local dev override
return process.env.WWV_DATA_ENGINE_URL
?? process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_URL
?? "http://localhost:5000";
}
function normalizeEntity(raw: unknown): GeoEntity | null {