Compare commits

..
Author SHA1 Message Date
Antigravity AI ab0743df14 docs(rules): codify decentralized plugin auth contracts and security rules 2026-05-14 18:53:56 +12:00
Antigravity AI d21a7d3f55 fix(wwv-plugin-sdk): address PR comments on auth contracts 2026-05-14 18:50:38 +12:00
Antigravity AI 63524c5969 fix(wwv-plugin-sdk): implement PR review feedback for auth contracts 2026-05-14 18:40:20 +12:00
Antigravity AI 483769260d fix(wwv-plugin-sdk): wrap auth contract type tests in vitest suite 2026-05-14 18:31:05 +12:00
SilvertakanaandCopilot Autofix powered by AI 8135c58fee Potential fix for pull request finding 'CodeQL / Workflow does not contain permissions'
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-14 18:28:36 +12:00
Antigravity AI fd8a25ad99 feat(wwv-plugin-sdk): add shared auth contracts for decentralized plugin auth 2026-05-14 18:25:25 +12:00
Antigravity AI 7a6b3b9378 refactor(docker): separate self-host Docker compose structure from development
test(ci): add github action to verify self-host scripts
2026-05-14 12:15:37 +12:00
szski db1a9ad191 Merge pull request #103 from AlsoTheZv3n/perf/cesium-hot-path-wins
perf(globe): three Cesium hot-path wins
2026-05-13 16:49:02 -04:00
szski cfd8e4b7d0 Merge pull request #104 from AlsoTheZv3n/fix/ci-triggers-and-audit
ci: trigger on push to main and add dependency audit
2026-05-13 16:42:42 -04:00
Sven WeidenmannandClaude Opus 4.7 a475a5a562 perf(globe): replace viewer mutation with WeakMap<Viewer, Collections> [Patch]
Primitive collections (points, billboards, labels, polylines) were
attached directly to the Cesium Viewer instance as `_wwvX` properties
behind `(viewer as any)` casts. This created hidden coupling, blocked
multi-viewer setups, and left ~11 `as any` casts across three files.

Replace the viewer-mutation pattern with a module-level
`WeakMap<CesiumViewer, PrimitiveCollections>`:

- `initPrimitiveCollections` now writes into the WeakMap
- `getCollections` reads from the WeakMap and returns a destructurable
  shape with optional fields, preserving the existing call pattern
- `AnimationLoop` and `useEntityRendering` use `getCollections(viewer)`
  instead of direct `(viewer as any)._wwvX` reads
- Zero `(viewer as any)._wwv*` remain; collections GC cleanly when
  the viewer is dropped

Adds `src/core/globe/EntityRenderer.test.ts` with 7 tests covering:
- WeakMap roundtrip (init populates, getCollections retrieves, per-viewer
  isolation, graceful no-scene)
- Defer-clone behaviour from the previous commit (no clone on
  iconUrl/model path; clone on auto-SVG path; original untouched)

Refs #95

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-13 16:42:12 -04:00
Sven WeidenmannandClaude Opus 4.7 8f859f4559 perf(globe): defer effectiveOptions clone to auto-SVG branch [Patch]
`renderSingleEntity` was cloning `options` for every entity via
`const effectiveOptions = { ...options }`, even when the auto-SVG
fallback below didn't need to mutate it. With 10k+ entities per
render pass this adds avoidable GC pressure in the hot loop.

The clone is now deferred into the auto-SVG branch that actually
mutates, so entities that arrive with `iconUrl` set (or `type === "model"`)
pass `options` through by reference with zero allocation.

Refs #95

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-13 16:42:12 -04:00
Sven WeidenmannandClaude Opus 4.7 8a594d28ea perf(globe): type window._wwvFrameCount via Window interface extension [Patch]
Replace `(window as any)._wwvFrameCount = frame` with a typed
`declare global { interface Window { _wwvFrameCount?: number } }`
and a plain `window._wwvFrameCount = frame` assignment.

The external plugin contract (a window-published frame counter for
throttling) is preserved; only the cast is removed.

Refs #95

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-13 16:42:12 -04:00
Sven WeidenmannandClaude Opus 4.7 382ceed2f1 ci: trigger on push to main and add non-blocking dependency audit (fixes #97) [Patch]
Previously the workflow only ran on `pull_request: branches: [main]`,
so any direct push to `main` (or any other branch) bypassed CI entirely.

Changes:
- Add `push: branches: [main]` to the trigger list so main-branch pushes
  also run typecheck / test / build / audit.
- Add a new `audit` job that runs `pnpm audit --audit-level high` and
  surfaces high/critical advisories in the CI output.

The audit job is intentionally non-blocking (`continue-on-error: true`)
on first introduction: the lockfile currently has 2 high + 1 critical
transitive advisories (sentry-webpack-plugin → webpack → schema-utils →
ajv → fast-uri chain) that need to be addressed before audit can become
a hard gate. A comment in the workflow notes that the flag should be
flipped to `false` once those are resolved.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-13 16:36:02 -04:00
szski df072feea7 Merge pull request #123 from szski/chore/pin-vulnerable-transitive-deps
chore(deps): pin form-data + fast-uri overrides to patched versions
2026-05-13 16:35:27 -04:00
SapphireandClaude Opus 4.7 943ab91564 chore(deps): pin form-data + fast-uri overrides to patched versions
Resolves three high+critical advisories surfaced by the dependency
audit added in PR #104:

  CRITICAL  form-data <2.5.4   GHSA-fjxv-7rqg-78g4  unsafe random boundary
  HIGH      fast-uri  <=3.1.0  GHSA-q3j6-qgpj-74h6  path traversal
  HIGH      fast-uri  <=3.1.1  GHSA-v39h-62p7-jpjc  host confusion

form-data was 2.3.3 transitively via insecam-api -> [email protected].2.
fast-uri was 3.1.0 via @sentry/webpack-plugin -> webpack -> schema-utils
-> ajv (15 paths total).

Uses scoped pnpm overrides keyed on the vulnerable version ranges so
each major release line is patched in place: form-data stays in 2.x
(2.3.3 -> 2.5.5) rather than jumping to 4.x and risking compatibility
with the long-abandoned `request` package. Overrides for form-data 3.x
and 4.x are pre-emptive -- no current matches in the tree, but they
future-proof against new deps pulling vulnerable form-data versions.

After install, `pnpm audit --audit-level high` returns exit 0.
Five moderate findings remain (request SSRF, tough-cookie, qs,
@hono/node-server, postcss) -- all below the CI threshold and
addressable in a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-13 16:28:19 -04:00
szski 7a262c617c Merge pull request #79 from szski/feat/agent-bus
feat(agent): SSE-based AgentBus for external-tool UI control
2026-05-13 16:07:41 -04:00
SapphireandClaude Opus 4.7 a69b1d9aac docs(agent): how-to for wiring an MCP server to the agent bus
Adds docs/agent-bus.md covering enable-via-build-arg, a curl smoke test,
Node + Docker MCP client config snippets (Claude Code / Desktop / Cursor /
Cline), and per-user security notes. Links szski/wwv-mcp as the reference
MCP server with a note that it may relocate under the project org.

Cross-links the new doc from README Key Features, Repository Ecosystem,
and Documentation Index.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-13 16:01:02 -04:00
szski a1b3a71e6e Merge pull request #64 from szski/feat/osm-surveillance-camera-adapter
feat(api/camera): OSM surveillance-points adapter (depends on #62)
2026-05-13 15:51:06 -04:00
SapphireandClaude Opus 4.7 338cde0813 feat(api/camera): OSM surveillance-points adapter
Adds an adapter that pulls `man_made=surveillance` nodes from the
OpenStreetMap Overpass API as location-only camera markers. The geometry
alone is useful as a "where do public / government cameras exist" overlay
alongside the live DOT feeds — most OSM surveillance nodes don't have
stream URLs, but their tags (operator, camera:type, surveillance:type)
are surfaced via `properties.extra` for filtering.

The query is bounded to a list of major metros (~30km radius around SF,
LA, NYC, London, Paris, Tokyo, Raleigh) to keep the response size sane;
operators who want fuller coverage can extend the query in-source. Output
is capped at 3000 nodes per fetch.

Cache TTL is 7 days (overrides the default 24h) since OSM data changes
slowly and Overpass is shared infrastructure that politely asks consumers
not to poll aggressively.

Built on top of the CameraAdapter pattern from the camera adapter
refactor PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-13 15:43:26 -04:00
szski b7311268f8 Merge pull request #63 from szski/feat/ncdot-camera-adapter
feat(api/camera): NCDOT adapter (depends on #62)
2026-05-13 15:41:23 -04:00
szski 54078f351c Merge pull request #105 from AlsoTheZv3n/docs/architecture-migration
docs: migrate architecture deep-dive from AGENTS.md to docs/ARCHITECTURE.md
2026-05-13 15:36:23 -04:00
SapphireandClaude Opus 4.7 a149be8560 feat(api/camera): NCDOT adapter
Adds North Carolina DOT as a sixth source for `/api/camera/traffic`.
~770 cameras statewide, no API key required, direct JPEG snapshots.

NCDOT exposes a two-step API: a bulk endpoint that returns only
`{ id, latitude, longitude }` per camera, and a per-camera detail
endpoint with the rest (locationName, mileMarker, roadId, countyId,
imageURL, status). The adapter fans out the detail fetches with a
bounded concurrency of 20, lands the initial population in ~15 seconds,
and the registry's per-adapter cache holds it for 24h after that.

Cameras with `status !== "OK"` are filtered out. The adapter is built
on top of the CameraAdapter pattern introduced in the camera adapter
refactor PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-13 15:32:14 -04:00
szski 10fdafbdb6 Merge pull request #99 from szski/fix/camera-adapter-timeout
fix(api/camera): per-adapter timeout so one slow source can't stall the rest
2026-05-13 15:31:25 -04:00
szski 2280fc4d19 Merge pull request #108 from devangpratap/fix/imagery-fallback-blank-globe
fix(globe): fall back to OSM when imagery providers fail without API keys
2026-05-13 15:27:56 -04:00
szski 118106ff8f Merge pull request #121 from szski/fix/setup-page-white-on-white
fix(setup): logo + Sign In button rendering white-on-white
2026-05-13 15:18:11 -04:00
szski 6a915cca62 Merge pull request #122 from szski/fix/engine-manifest-port
fix(engineManifest): correct local engine port (5001) + honor data-engine env var
2026-05-13 15:15:15 -04:00
szski 42dadd0b40 Merge pull request #120 from szski/feat/test-bedrock-round-3
test: round 3 — consolidated test bedrock + stryker setup (supersedes #113, #114, #117, #118)
2026-05-13 15:03:34 -04:00
Sapphire 583c0e57a6 fix(engineManifest): correct local engine port + honor data-engine env var
Two related bugs in the local-engine detection path:

1. Hardcoded port 5000 — should be 5001
   wwv-data-engine's docker-compose.yaml binds the engine to port 5001
   (and has since the v2 refactor), but engineManifest.ts polls
   `localhost:5000/manifest` to detect it. The detection always
   reported "no local engine" even when one was running, falling back
   to the cloud engine on every plugin toggle.

   Bonus pain: macOS hijacks port 5000 for the AirPlay Receiver, which
   returns 403 to any GET request. On any macOS dev machine, this
   produced a misleading 403 in the browser console even when no
   engine was running at all. Famous local-dev gotcha that ate dev
   time.

2. NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL is ignored
   Every other code path in the app honors this env var as the
   override for the engine URL — `resolveEngineUrl`, plugin context
   injection, the radio-garden plugin, etc. But `engineManifest` ran
   its own detection independently against hardcoded localhost. So
   even when the operator pointed plugins at a custom engine URL,
   manifest detection failed silently.

Fix: read `NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL` first (normalizing
ws[s]:// → http[s]:// and stripping a trailing /stream), then fall
back to localhost:5001 if not set. Same approach used elsewhere in
the codebase.

Side effects:
- Symptoms in the browser console downstream of this bug (notably
  the spurious 403 on `localhost:5000/manifest` and the cascade of
  "seeder not running" 404s when plugins fall back to the cloud
  engine that doesn't have that seeder) clear up.
- Existing engineManifest unit tests still pass — they mock fetch
  and don't care about the URL shape.

Worth adding a test for the env-var precedence in a follow-up; left
out of this PR to keep the diff to the one-file behaviour fix.
2026-05-13 14:38:46 -04:00
Sapphire ae14a30168 fix(setup): use explicit brand color instead of unset theme accent
The setup page's `.logo` and `.button` rules use
`rgb(var(--accent-rgb, 200, 30, 30))`. Because CSS `var()` only treats
the value after the first comma as the *fallback*, the syntax
intends "use --accent-rgb if defined, otherwise fall back to
`200, 30, 30`."

The fallback never triggers in practice: `theme-tokens.css` defines
`--accent-rgb: 255, 255, 255` at the `:root` level, so the variable
is always set when the setup page renders. `rgb(255, 255, 255)`
combined with the rules' `color: #fff` gives white-on-white — the
"Sign In" button text and the "W" logo are invisible on the page.

The setup flow is pre-auth and pre-theme; it shouldn't be inheriting
the accent. Replace the var() lookups with an explicit brand red
(`rgb(200, 30, 30)`) so the page is readable regardless of which
theme is active in the rest of the app.

Affected rules: `.logo` background, `.button` background, `.input:focus`
border. Three identical edits.
2026-05-13 14:34:48 -04:00
Sapphireandsilvertakana 019b427442 test: round 3 — consolidated test bedrock + stryker setup
Consolidates four overlapping test-infra PRs (#113, #114, #117, #118)
into a single coherent batch. Each contributing PR has redundancies
with one or more of the others; together they ship a real ~134-test
expansion of the unit suite plus mutation-testing infrastructure.

Same shape as #110 / #111: small, focused, behavior-pinning tests
against load-bearing systems. Each test answers one question — *what
specific regression does it catch that I'd otherwise find from a user
bug report?* Tests pin observable contracts (events emitted, cache
entries written, public-API state) rather than internal mechanics, so
they survive refactors during the longer-term migration toward the
six-interface architecture.

## What's in this PR

### Stryker mutation testing (new in this batch)

- `stryker.config.json` — hybrid config: `coverageAnalysis: "perTest"`
  for the 5–10× speedup on a real codebase, `ignoreStatic: true` to
  drop false-positive mutants in module-load code, and a `mutate`
  scope of `src/core/**` + `src/lib/**` covering the logic-heavy
  layers without dragging the React component surface into noise.
- `.github/workflows/mutation-testing.yml` — runs Stryker on a weekly
  schedule (Sundays 22:00 US Eastern / 03:00 UTC Monday) plus
  `workflow_dispatch` for on-demand validation. Per-PR triggering
  would be too expensive (10–30 min per run even with `perTest`).
- `package.json` — adds `@stryker-mutator/core`, `@stryker-mutator/vitest-runner`,
  and `fast-check` as devDependencies. New `test:mutate` script.

### New test files (22 added)

Plugin lifecycle and loaders:
- `src/core/plugins/PluginManager.test.ts` — orchestrator lifecycle:
  register, enable, disable, data-flow contract, getAllEntities
  filters by enabled, updateTimeRange, destroy, togglePlugin,
  loadFromManifest. 11 tests.
- `src/core/plugins/loadPluginFromManifest.test.ts`
- `src/core/plugins/validateManifest.test.ts`
- `src/core/plugins/loaders/mapGeoJsonToEntities.test.ts`
- `src/core/plugins/loaders/mapJsonToEntities.test.ts`

Data layer:
- `src/core/data/DataUtils.test.ts`
- `src/core/data/WsClient.test.ts`

State (9 Zustand slices + the integration tests):
- `src/core/state/StateSlices.test.ts`
- `src/core/state/configSlice.test.ts`
- `src/core/state/dataSlice.test.ts`
- `src/core/state/favoritesSlice.test.ts`
- `src/core/state/filterSlice.test.ts`
- `src/core/state/geojsonSlice.test.ts`
- `src/core/state/globeSlice.test.ts`
- `src/core/state/layersSlice.test.ts`
- `src/core/state/timelineSlice.test.ts`
- `src/core/state/uiSlice.test.ts`

Filters:
- `src/core/filters/filterEngine.test.ts`

Library:
- `src/lib/AuthConfig.test.ts`
- `src/lib/analytics.test.ts`
- `src/lib/origin.test.ts`

### Test files extended (9 modified)

Property-based and edge-case additions to existing tests, drawn from
the upstream PRs:

- `src/core/plugins/loaders/getNestedValue.test.ts` (+46 lines)
- `src/lib/geojson/converter.test.ts` (+31)
- `src/lib/geojson/normalizer.test.ts` (+52)
- `src/lib/rateLimit.test.ts` (+44)
- `src/core/plugins/loaders/DeclarativePlugin.test.ts` (+147 — type
  fixes for `DataSourceConfig.method`/`pollInterval`/`format`)
- `src/lib/marketplace/cors.test.ts` (+5)
- `src/lib/marketplace/marketplaceToken.test.ts` (+21)
- `src/core/filters/filterEngine.test.ts` (type-corrected — uses
  `latitude`/`longitude` not `position.lat`/`lon`, nested
  `range: { min, max, step }` config, etc.)

## What's *not* in this PR (intentionally)

- **Duplicate tests for code already on main.** #113 originally
  included `.spec.ts` versions of `CacheLayer`, `DataBus`,
  `PollingManager`, `cors`, `marketplaceToken`, `repository`,
  `rateLimit`, `edition`, and `seedDefaultPlugins` — all of which are
  already tested via `.test.ts` files on main from #110 + prior. Vitest
  picks up both `.test.ts` and `.spec.ts`, so keeping both would double
  the maintenance burden without adding signal. Dropped.
- **Tautological tests.** A few accessors-only tests from #113
  (`getEntities` returning the cached array, `getAllPlugins().length`
  equals N) were dropped per the test-writing bar set on #110/#111:
  each test must catch a specific bug class that two different broken
  implementations would fail differently on.
- **`version` bump in `package.json`.** Three of the contributing PRs
  bumped the version line independently (2.9.5, 2.9.10, 2.9.10), each
  conflicting with the others. Reserve version bumps for explicit
  release commits — feature/test PRs should leave the version field
  alone to avoid this conflict hairball.
- **A duplicate `stryker.conf.json`.** #114 used that filename; #117
  used `stryker.config.json`. Stryker accepts both but only loads one
  (alphabetical resolution). Picked `stryker.config.json` as the
  canonical name.

## Verification

```
Test Files  38 passed (38)
Tests       271 passed (271)
```

137 tests on main before this PR; +134 from this consolidation, no
regressions. Type check clean (`pnpm exec tsc --noEmit`).

## Replaces

- PR #113 (test/improve-coverage) — most of its 18 truly-new files
  are included here; the 9 duplicate-of-main entries are not.
- PR #114 (chore/stryker-setup) — its CI workflow shape is here with
  the trigger changed to weekly+manual instead of per-PR.
- PR #117 (chore/stryker-and-fast-check) — its full deps and test
  additions are here.
- PR #118 (test/improve-project-coverage) — the type-corrected
  versions of its 6 test files are here, including the typefix commit
  pushed to that branch earlier.

Each of those PRs should be closed once this lands, with a comment
referencing this PR for credit.

Co-Authored-By: silvertakana <[email protected]>
2026-05-13 13:37:22 -04:00
Silvertakana 04beadc0e2 chore: enforce vitest coverage thresholds (#115) 2026-05-13 23:14:56 +12:00
Silvertakana cf67c5d96f docs(panels,core): complete TSDoc standardization for panels and core slices (#112)
This commit includes the work done by the Flash subagent to add comprehensive TSDoc comments to src/components/panels, src/core/state, and src/core/plugins, improving IDE intellisense and codebase maintainability.
2026-05-13 22:45:08 +12:00
devangpratap bf7e9c4bee merge: resolve package.json version conflict, take main (2.9.1) 2026-05-13 01:53:51 -04:00
devangpratap a1c4fed23b fix(globe): tiered imagery fallback — Google tiles → Ion/Bing → OSM
Replace direct Ion fallback with a 3-tier chain per maintainer feedback:
1. Google XYZ tiles (free, no API key)
2. Bing via Cesium Ion (free shared token)
3. OSM as last resort

useImageryManager catch block still falls to OSM if createImageryProvider
throws at runtime (e.g. direct Bing key failure, ArcGIS down).
2026-05-13 01:49:50 -04:00
szskiandSapphire e6c7dcf295 test: bedrock tests for the load-bearing data layer + camera registry (#110)
WorldWideView's Vitest setup is already wired and CI already runs
\`pnpm test\` on every PR. What's missing is tests for the systems
that actually break: the plugin lifecycle plumbing (data bus, cache,
polling) and the camera adapter aggregator that the UI hits on every
layer toggle.

This PR adds a focused first batch — 12 tests across 4 files — covering
the most common failure modes we've actually seen in practice. The
intent is to land the patterns alongside the tests so the next
contributor (human or agent) can copy the shape rather than improvise.

## What's tested

| File | Coverage | Tests |
| ---- | -------- | ----- |
| src/core/data/DataBus.test.ts | emit/subscribe round-trip, unsubscribe correctness, handler-failure isolation | 3 |
| src/core/data/CacheLayer.test.ts | memory-tier get/set, TTL expiry + eviction | 2 |
| src/core/data/PollingManager.test.ts | immediate-run on start(), interval scheduling, stop() cancels | 3 |
| src/app/api/camera/adapters/registry.test.ts | resolveSources for "all" / null / "none" / mixed-with-unknowns | 4 |

Each test answers one question: what regression does it catch that
we'd otherwise find by user bug report?

## Config change

vitest.config.ts now includes \`src/app/**/*.{test,spec}.*\` so API-route
tests under \`src/app/api\` are picked up by \`pnpm test\`. Previously only
\`src/lib\`, \`src/core\`, \`src/plugins\`, and \`packages\` were scanned —
api-route handlers had no test home.

## Docs

\`docs/testing.md\` gets four new sections:

- **Patterns** — plain-function, stateful-singleton, mock-with-vi.mock,
  fake-timers — with a callout for the \`runOnlyPendingTimersAsync\`
  double-counting gotcha we hit while writing PollingManager tests.
- **What NOT to Test (Yet)** — Cesium-heavy components, live DB
  round-trips, dynamic plugin imports.
- **Philosophy** — small focused suite > large expensive one, test
  pure logic, add a test when you fix a bug.

Original overview/test-types/run-commands sections are unchanged.

## Verification

Locally (Node 22 + pnpm 9.15.4):

\`\`\`
Test Files  17 passed (17)
Tests       127 passed (127)
\`\`\`

Existing 115 tests still pass; new 12 land cleanly.

## What's next (not in this PR)

The list of load-bearing systems still without coverage:

- PluginManager (the central plugin lifecycle orchestrator)
- The new plugin-backend supervisor + proxy (PR #100)
- The agent bus (PR #79)
- Plugin marketplace install/uninstall round-trip
- React component tests for LayerPanel and DataBusSubscriber

Worth a follow-up batch once the patterns from this PR are familiar.

Co-authored-by: Sapphire <sapphire@tiktokcoach>
2026-05-13 17:23:09 +12:00
Antigravity AI 9e44e91d81 chore: update docker-compose ports and document coding principles in AGENTS.md 2026-05-13 17:04:51 +12:00
Antigravity AI c6cd515588 Merge branch 'main' of https://github.com/silvertakana/worldwideview 2026-05-13 16:58:50 +12:00
Antigravity AI 0f871729c0 fix(docker): use compose profiles to prevent data engine collision on production deployments 2026-05-13 16:55:49 +12:00
e73f81d6fe chore: add ESLint baseline + CI lint job (fixes #96) [Patch] (#106)
Introduces a baseline ESLint configuration and wires it into CI.

Config:
- `eslint.config.mjs` (flat config, ESLint 9). Extends
  `eslint-config-next/core-web-vitals` and `eslint-config-next/typescript`
  directly — both ship as native flat-config arrays in `eslint-config-next` 16+.
- Ignores cover `.next`, `out`, `src/generated`, `public/cesium`,
  `packages/*/dist`, plus the gitignored sandboxes (`local-scripts`,
  `local-plugins`, `local-seeders`, `.agents`, `.claude`, `.worktrees`).

Rule policy:
- All rules that the Next.js preset surfaces as errors are demoted to
  `warn` on first introduction, so the lint job is runnable against
  the current codebase without blocking on pre-existing debt. The
  demoted set (react-hooks/* in React 19's stricter purity suite,
  no-unescaped-entities, ban-ts-comment, no-assign-module-variable,
  prefer-const) plus the originally-flagged `no-explicit-any` and
  `no-console` are all documented in the config with a recommended
  promotion order.
- Current state: 0 errors, 564 warnings.

Scripts:
- `pnpm lint` runs `eslint .`.

CI:
- New `lint` job in `.github/workflows/ci.yml`, parallel to typecheck /
  test / audit. Blocking on errors only — warnings are visible in the
  job log but don't fail the build.

Same incremental-introduction pattern as the audit job (#97): land the
infrastructure now, tighten policy via follow-up PRs as the backlog is
worked down.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Silvertakana <[email protected]>
2026-05-13 16:49:43 +12:00
Antigravity AI f5235bf219 fix(docker): remove hardcoded host port bindings from base docker-compose to fix Coolify deployment conflicts 2026-05-13 16:30:35 +12:00
19f10d25df Fix/UI styling and buttons (#107)
* modified:   .gitignore
	modified:   AGENTS.md
	modified:   package.json
	modified:   public/cesium/ThirdParty/zip-module.wasm
	new file:   src/components/layout/ApiKeysTab.tsx
	modified:   src/components/layout/Header.tsx
	modified:   src/components/panels/DataConfig/OverlayTab.tsx
	modified:   src/components/panels/DataConfig/index.tsx
	modified:   src/components/panels/LayerPanel.tsx
	modified:   src/components/panels/PluginsTab.css
	modified:   src/components/panels/PluginsTab.tsx

* modified:   src/components/layout/Header.tsx
	new file:   src/components/layout/timeSelect.css

* UI-Testing

* UI-testing

* modified:   src/components/layout/timeSelect.css

* Fixed Duplicate Time Button

Caused by a merge conflict

* addeb back a </div>

* Fix Sync failing

* deleted:    local-plugins/wwv-plugin-iss/index.ts
	deleted:    local-plugins/wwv-plugin-iss/package.json

* fix: dark glass timeline button, sidebar expands when timeline closed, light mode button adaptation

* temp-fix

* fix blur being disabled

---------

Co-authored-by: nullptr <[email protected]>
Co-authored-by: Silvertakana <[email protected]>
2026-05-13 16:20:59 +12:00
Antigravity AI 3ddd6ec150 feat(core): plugin toggle functionality and CLI publishing enhancements
This release groups multiple feature additions and structural stability fixes:
- feat(marketplace): API routes to enable/disable local plugins via UI (Minor)
- feat(cli): interactive publishing and global org configuration persistence (Minor)
- fix(css): resolve parsing errors in PluginsTab stylesheet (Patch)
- fix(engine): fix wwv-data-engine dependency resolution and host mounts (Patch)
- fix(db): resolve P1001 database connection issues in docker loopback (Patch)
- chore(ci): revert dynamic edition runtime injection to static build args
2026-05-13 16:18:53 +12:00
devangpratap e26aee6dd2 fix(globe): fall back to OSM when imagery providers fail without API keys
Fixes #49 [Patch]
2026-05-12 21:58:21 -04:00
Antigravity AI 42f4701fda chore(cli): bump version to 1.1.2 2026-05-13 11:37:27 +12:00
Antigravity AI 4c6978ea90 feat(cli): add interactive org prompt to publish and config command 2026-05-13 11:36:25 +12:00
Antigravity AI 3c03b4e7a4 fix(cli): publish missing dist changes for default create directory 2026-05-13 11:34:17 +12:00
Antigravity AI d2bdb0cee8 feat(cli): enhance publish command and update default create directory
- feat(cli): Add --org flag to publish to allow publishing under custom NPM scopes (Minor).
- feat(cli): Allow publish command to run from project root via path resolution (Minor).
- feat(cli): Change create default scaffolding to local-plugins/ instead of packages/ (Minor).
- feat(cli): Add --core flag to create to override default and scaffold into packages/ (Minor).
- docs: Update tutorial, CLI readmes, and agent architecture workflows with new commands (Fix).
2026-05-13 10:57:33 +12:00
Sven WeidenmannandClaude Opus 4.7 335b74a486 docs: migrate architecture deep-dive from AGENTS.md to docs/ARCHITECTURE.md (fixes #98)
`docs/ARCHITECTURE.md` was a 33-line stub, despite the README pitching
a "Deep dive into the Cesium rendering pipeline, event data bus, and
performance optimizations". The substantive content was duplicated /
buried in `AGENTS.md` §4.

Migrate it to a proper human-facing doc:

- `docs/ARCHITECTURE.md` (33 → 200 lines) now contains the full
  architecture deep-dive: system overview with mermaid diagram, plugin
  system & All-Bundle Model, Zustand state management (with slice
  table), data pipeline, data engine & seeders (agnostic-renderer
  contract), rendering pipeline (primitive collections, chunked
  processing, horizon culling, LOD, stack/spiderifier), edition
  system, key source files table, and cross-refs into `.agents/rules/`.
- `AGENTS.md` §4 collapses from ~80 lines of duplicated prose to a
  short stub that points contributors to `docs/ARCHITECTURE.md` and
  lists the key invariants agents must respect (plugin SDK as source
  of truth, agnostic frontend, nine slices, primitive rendering, three
  editions). Same hub-and-spoke pattern as the maintainer already
  applied to §3, §6, §7.
- README link description updated from "DataBus event stream and
  Zustand state management" to reflect the expanded scope.

No code changes; no version bump (consistent with prior `docs:` commits
in the history that did not touch root `package.json`).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-12 21:29:11 +02:00
Sapphire 014a360d5d fix(api/camera): per-adapter timeout so one slow source can't stall the rest
The aggregator uses `Promise.allSettled`, so the request takes as long
as the slowest adapter. Today ny511 (without a real API key) returns
empty after ~5s — fast adapters (cached) come back in <50ms but the
client waits 5s+ for the aggregate response.

With a 4s per-adapter cap, the stuck source rejects fast and either
its stale cache or an empty list is served; healthy adapters return on
their own cadence.

Concrete latency before this commit, all 7 adapters in parallel:
  caltrans:        0.04s  gdot:    0.02s  tfl:        0.01s
  ny511:           5.03s  wsdot:   0.02s  ncdot:      0.02s
  osm-surveillance:0.03s
  total:           ~10s
2026-05-12 13:20:17 -04:00
Antigravity AI 21adb9f2e8 docs: add plugin development quickstart and advanced guides, and include CLI and SDK scaffolding artifacts 2026-05-13 02:42:24 +12:00
Antigravity AI b792dc0373 chore(cli): use latest sdk for public npm template 2026-05-13 02:18:14 +12:00
Antigravity AI cbbc38ecc9 feat(plugin-iss): implement ISS tracker plugin and seeder 2026-05-13 02:06:58 +12:00
Antigravity AI bbb231541b feat: implement interactive plugin generation via prompts in cli 2026-05-13 01:54:26 +12:00
Antigravity AI 70fd3e1818 build: add prompts dependency to wwv-cli 2026-05-13 01:52:47 +12:00
dependabot[bot] 0ee8ae700c build(deps-dev): bump vite from 6.4.2 to 8.0.12 (#91)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 6.4.2 to 8.0.12.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.0.12/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 8.0.12
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-13 01:35:00 +12:00
Antigravity AI 2c17b1e701 chore: remove wwv-data-engine service from docker-compose override 2026-05-13 01:27:27 +12:00
Antigravity AI 2ed8da0e1c feat(ui): implement responsive timeline toggle and auto-hide on mobile 2026-05-13 01:21:43 +12:00
Antigravity AI 9006064240 fix: direct users to public submit URL instead of admin UI in CLI publish command 2026-05-13 01:18:28 +12:00
Antigravity AI fe2cfa9dac feat: implement publish command and complete WWV CLI reconstruction 2026-05-13 01:14:06 +12:00
Antigravity AI 84f3691c22 feat(wwv-cli): initialize commander entrypoint and stubs 2026-05-13 01:05:56 +12:00
Antigravity AI f9384b8244 build(wwv-cli): initialize typescript build pipeline and dependencies 2026-05-13 01:03:53 +12:00
Antigravity AI d0ae85049f refactor: move wwv-data-engine and wwv-redis service definitions from override to base docker-compose file 2026-05-13 00:23:13 +12:00
Antigravity AI 64815c114c feat: implement LayerPanel with tabbed navigation, plugin management, and search functionality alongside supporting styling and utility scripts. 2026-05-13 00:14:17 +12:00
Antigravity AI e86fdf56d0 chore: update dependency versions in pnpm-lock.yaml 2026-05-13 00:11:29 +12:00
Antigravity AI c25a1e6d58 refactor: consolidate docker compose setups using override pattern 2026-05-13 00:04:52 +12:00
dependabot[bot] f9c8bcff17 build(deps): bump vite from 5.4.21 to 6.4.2 (#88)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 5.4.21 to 6.4.2.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v6.4.2/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v6.4.2/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 6.4.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-12 22:18:29 +12:00
Antigravity AI 008e8cd01d chore(repo): hygiene improvements and onboarding fixes (Refs #86)
- chore: remove tracked .env and skills-lock.json
- chore: move military_bases.geojson to public/
- fix: correct README architecture doc hyperlink
- chore: add .nvmrc and enforce Node v20 via engines
- fix: implement safe-db-push.mjs wrapper to guard DATABASE_URL
- refactor: remove duplicate ApiKeysTab.tsx and fix imports
- docs: relax file size limit and remove TS aliases in AGENTS.md
2026-05-12 22:02:47 +12:00
Antigravity AI 1d1c7b270b chore: remove tracked dev artifacts, scratch files, and broken symlink (fixes #86) 2026-05-12 21:30:26 +12:00
Antigravity AI 63a5e5d8a1 docs: enforce explicit authorization and clarifying questions in AGENTS.md 2026-05-12 21:18:02 +12:00
Antigravity AI 39c1172b0b docs: enforce explicit authorization and clarifying questions in AGENTS.md 2026-05-12 21:18:02 +12:00
Antigravity AI 09ac165420 fix(license): restore full Elastic License 2.0 and update README (fixes #87) 2026-05-12 21:18:02 +12:00
dependabot[bot] 1daa8a6979 build(deps): bump lucide-react from 0.576.0 to 1.14.0 (#90)
Bumps [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) from 0.576.0 to 1.14.0.
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.14.0/packages/lucide-react)

---
updated-dependencies:
- dependency-name: lucide-react
  dependency-version: 1.14.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-12 20:59:40 +12:00
dependabot[bot] 2c97f8e1e3 build(deps-dev): bump the dependencies group across 1 directory with 2 updates (#94)
Bumps the dependencies group with 2 updates in the / directory: [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) and [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest).


Updates `@vitest/coverage-v8` from 4.1.5 to 4.1.6
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.6/packages/coverage-v8)

Updates `vitest` from 4.1.5 to 4.1.6
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.6/packages/vitest)

---
updated-dependencies:
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 4.1.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: vitest
  dependency-version: 4.1.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-12 20:59:28 +12:00
dependabot[bot] 1fb830e962 build(deps-dev): bump @types/node from 20.19.37 to 25.7.0 (#92)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 20.19.37 to 25.7.0.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.7.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-12 20:44:49 +12:00
Antigravity AI 5e542c3ca6 fix(docker): Remove obsolete copy command for deleted script 2026-05-12 19:24:40 +12:00
Antigravity AI 7e25fdfba2 Merge branch 'fix/engine-seeders-coolify' into main 2026-05-12 19:11:39 +12:00
SapphireandClaude Opus 4.7 1845a1ced9 feat(agent): SSE-based AgentBus for external-tool UI control
Adds an opt-in agent integration surface that lets a trusted external
tool (running as the same logged-in user) drive the running WWV browser
session — fly the globe, toggle layers, focus entities — by POSTing
JSON actions to the server, which fans them out over SSE to every
connected browser tab belonging to that user.

The motivating use case is an MCP server (a Model Context Protocol
adapter): an LLM agent calls a tool like `globe_fly_to({lat, lon})`,
the MCP server posts to `/api/agent/publish`, the browser subscriber
re-emits the action onto the existing client-side `dataBus`, and the
React + Cesium app handles it the same way it would handle any UI
button click. Read-only camera / engine queries already work via the
existing REST surface — this PR adds the missing write path.

What's added:

- `src/lib/agent/bus.ts` — process-local AgentBus singleton, scoped
  per user. Subscriptions live in a `Map<userId, Map<connId, sub>>`
  so user A's publish never reaches user B's stream, even though
  both run on the same Node process.

- `src/app/api/agent/stream/route.ts` — SSE channel. Auth-gated. Sends
  initial `:connected` + `retry:3000` directives and a `:hb` heartbeat
  every 25s so intermediary proxies (Caddy, Nginx, CDNs) don't tear
  down a "stalled" connection.

- `src/app/api/agent/publish/route.ts` — POST endpoint. Accepts JSON
  AgentAction shapes (`fly_to`, `face_towards`, `layer_toggle`,
  `highlight_layer`, `select_entity`, `ping`), broadcasts only to the
  publishing user's bus bucket. Returns `{delivered, subscribers}` so
  the caller knows how many tabs received the command.

- `src/components/layout/AgentBusSubscriber.tsx` — browser EventSource
  client. Re-emits received actions onto `dataBus` (`cameraGoTo`,
  `cameraFaceTowards`, `layerToggled`, `entitySelected`) — every plugin
  is already listening on those channels, so no plugin changes needed.

- `AppShell.tsx` — mounts `AgentBusSubscriber` next to the existing
  `DataBusSubscriber`. Two lines.

- `src/app/api/build/route.ts` — `/api/build` returns build id +
  timestamp + public flag state. Pairs with a one-line console.log
  the subscriber prints on mount so a stale-bundle / config-mismatch
  is visible at a glance instead of looking like a feature regression.

Default off via `NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED=true`. An unintended
deployment doesn't open a remote-control channel for users who didn't
opt in.

What's changed in the Dockerfile:

- Adds ARG declarations for the new vars (`NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED`,
  `NEXT_PUBLIC_WWV_BUILD_ID`, `NEXT_PUBLIC_WWV_BUILD_AT`).
- Stamps the build with millisecond-precision id + ISO timestamp
  (`/app/.build-id`, `/app/.build-at`); both copied into the runner
  stage for `/api/build` to read.
- Writes `/app/.env.production.local` from declared ARGs *before*
  `next build` runs. Docker doesn't reliably promote ARGs into the
  Node child-process environment for the build command, so
  `process.env.NEXT_PUBLIC_*` references that previously inlined
  through Webpack's DefinePlugin sometimes fell back to runtime
  polyfill access (`tV.env.NEXT_PUBLIC_X`) that resolves to `undefined`
  in the browser. Writing the env file is the documented Next.js path
  and behaves the same on every host.

Default-off, no schema changes, no plugin changes, fully backwards-compatible
on operators who don't opt in.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-12 00:40:12 -04:00
Silvertakana e6305ca92f fix: resolve data engine deployment, optimize logs, update agent rules (#93)
* fix(docker): revert engine port mapping back to 5000:5000

* refactor(plugins): batch 2 legacy plugin migrations

- Migrated borders, camera, civil-unrest, and conflict-events to local-plugins/

- Refactored frontend routing to use this.context.getEngineUrl()

- Updated civil-unrest and conflict-events backend seeders to use strict container paths and ESM

- Renamed mismatched seeder directories (civilUnrest -> civil-unrest, conflictEvents -> conflict-events)

- Enhanced scripts/migrate-plugin.mjs to automatically fix mismatched seeder directory names

- Bumped workspace version to 2.7.4 (Patch)

* fix(plugins): restore civil-unrest and conflict-events

- Refactored fetch() to use this.context.getEngineUrl()

- Restored file structures damaged during initial replacement

- Bumped version to 2.7.5

* feat: batch 3 plugin migrations (cyber-attacks, maritime, wildfire)

* checkout: temporary commit for worktree checkout

* fix: resolve data engine deployment, optimize logs, update agent rules

* fix: resolve typescript compilation errors for Next.js build
2026-05-12 16:29:33 +12:00
a254784c3a Feat(UI/UX) Change buttons and fix Light mode buttons (#85)
* modified:   .gitignore
	modified:   AGENTS.md
	modified:   package.json
	modified:   public/cesium/ThirdParty/zip-module.wasm
	new file:   src/components/layout/ApiKeysTab.tsx
	modified:   src/components/layout/Header.tsx
	modified:   src/components/panels/DataConfig/OverlayTab.tsx
	modified:   src/components/panels/DataConfig/index.tsx
	modified:   src/components/panels/LayerPanel.tsx
	modified:   src/components/panels/PluginsTab.css
	modified:   src/components/panels/PluginsTab.tsx

* modified:   src/components/layout/Header.tsx
	new file:   src/components/layout/timeSelect.css

* UI-Testing

* UI-testing

* modified:   src/components/layout/timeSelect.css

* Fixed Duplicate Time Button

Caused by a merge conflict

* addeb back a </div>

---------

Co-authored-by: nullptr <[email protected]>
Co-authored-by: Silvertakana <[email protected]>
2026-05-12 01:49:21 +12:00
203 changed files with 348277 additions and 2724 deletions

No files matched your search

+9
View File
@@ -36,6 +36,15 @@ Application code is **identical** across editions — always calls `auth()`, `si
---
## Decentralized Plugin Authentication (Token Exchange)
For cross-domain plugin communication (Local App connecting to Marketplace or Data Engines), WWV uses an **Asymmetric JWT Token Exchange (PKCE)** model.
- **PKCE Flow**: The Local App uses standard OAuth 2.0 PKCE to exchange a `code` for a long-lived API key from the Marketplace.
- **Token Exchange**: The Local App exchanges its long-lived API key for a short-lived, audience-bound JWT before connecting to a decentralized Data Engine.
- **WebSocket First-Message Auth**: Data Engines enforce a "First-Message Auth" pattern over WebSockets. The client MUST immediately send a `{ type: "auth", v: 1, token: "..." }` message upon opening the connection to prevent SSRF vulnerabilities and credential leakage.
---
## Registration & Auto-Provisioning
Registration: `app.worldwideview.dev/register`
+2
View File
@@ -36,6 +36,7 @@ Frontend runs at `http://localhost:3000`.
- **Framework**: Vitest with jsdom environment
- **Coverage**: `src/lib/**`, `src/core/**`, `src/plugins/**`
- **Run**: `pnpm test` (or `vitest run`)
- **Type-Level Contract Testing**: When defining shared TypeScript interfaces/contracts (e.g., in `wwv-plugin-sdk`), you MUST use `expectTypeOf` from `vitest` to assert the actual contract shapes at compile-time instead of writing literal-value identity runtime assertions. You must also enforce `@ts-expect-error` negative type tests to ensure missing or invalid fields trigger compilation errors.
- **Key test files**: `rateLimit.test.ts`, `edition.test.ts`, `demoAdmin.test.ts`, `DeclarativePlugin.test.ts`, `cors.test.ts`, `repository.test.ts`, `marketplaceToken.test.ts`
## Security Headers
@@ -253,6 +254,7 @@ The production Coolify instance runs on a local server at `192.168.68.64`. Direc
- **The "Rollback DDOS" Risk:** If you update environmental variables (like a new Upstash Redis URL) inside Coolify and deploy *without* pushing your local optimized code to GitHub, Coolify will pull the *older, unoptimized* repository code and aim it at your new endpoints. This will immediately exhaust the 500,000 requests/month Upstash free limit.
- **Redis Connection Errors:** If the data engine crashes on startup with `MaxRetriesPerRequestError: Reached the max retries per request limit (which is 3)` and `ECONNRESET`, the `REDIS_URL` in your Coolify environment variables is incorrectly using `redis://` instead of the TLS-required `rediss://`.
- **Immediate Rollback on Failure:** Whenever a Coolify deployment fails or introduces a critical bug (such as rate-limit exhaustion), **immediately select the last known working deployment in the Coolify dashboard and redeploy it.** Do not leave a broken deployment hanging while trying to debug directly in production. Roll back to stability first, debug locally, commit the verified fix, and then deploy forward.
- **Public Port Binding:** Both the `wwv` (Next.js frontend) and `wwv-data-engine` containers are meant to be directly exposed to the internet, rather than relying on Traefik internal network routing. They MUST use `ports: - "3000:3000"` and `ports: - "5000:5000"` respectively in `docker-compose.yml`. Using `expose` hides them behind internal Docker routing. Only backend infrastructure like `db` and `wwv-redis` should use `expose`.
**Local verification:**
Before pushing infrastructure changes, run `docker build -t wwv-test .` to verify that the Next.js `standalone` isolated multi-stage build works correctly.
+2 -2
View File
@@ -14,7 +14,7 @@ If you are asked to implement a feature or fix a bug, you **MUST** determine the
| Repository Folder | Purpose & When to Edit |
|---|---|
| **`worldwideview`** | The main application, Next.js frontend, Cesium globe, UI components, and the core plugin SDK. **Edit here** for anything related to the UI, state, map rendering, or built-in plugin frontend configurations. |
| **`wwv-data-engine-public`** | The V2 Data Engine (Host Environment) that runs the seeders. **Edit here** if you need to modify how the engine parses WebSocket streams, implements REST APIs, downloads seeder bundles, or handles Redis caching. |
| **`wwv-data-engine`** | The V2 Data Engine (Host Environment) that runs the seeders. **Edit here** if you need to modify how the engine parses WebSocket streams, implements REST APIs, downloads seeder bundles, or handles Redis caching. |
| **`wwv-seeders`** | The community (public) data seeders. **Edit here** to create or modify background polling scripts (e.g. `aviation.ts`, `wildfire.ts`) that fetch data from public APIs and normalize it into `GeoEntity` arrays. |
| **`wwv-seeders-private`** | The proprietary (private) data seeders. **Edit here** for closed-source, premium, or high-security data ingestion scripts. |
| **`worldwideview-marketplace`** | The Plugin Marketplace web application. **Edit here** if you are modifying the platform where users browse, purchase, or manage plugin installations. |
@@ -29,6 +29,6 @@ If you are asked to implement a feature or fix a bug, you **MUST** determine the
- Write the frontend plugin interface inside `C:\dev\worldwideview` (or dynamically loaded via `worldwideview-plugins`).
2. **Fixing Real-Time Streaming Issues:**
- Investigate `C:\dev\worldwideview` (for frontend `WsClient` or `DataBus`).
- Investigate `C:\dev\wwv-data-engine-public` (for backend Fastify websocket broadcasting).
- Investigate `C:\dev\wwv-data-engine` (for backend Fastify websocket broadcasting).
3. **Pnpm Workspaces:**
- The Data Engine V2 automatically combines `community` and `private` seeders at runtime using pnpm workspaces. When testing seeders locally, refer to `C:\dev\worldwideview\local-seeders`.
+10 -4
View File
@@ -84,7 +84,7 @@ To rapidly iterate on plugins without polluting the core monorepo `packages/` di
1. **Create**: Run `node packages/wwv-cli/dist/index.js create <name> --local` to scaffold a full plugin structure inside the `local-plugins/` directory.
2. **Develop**: Running `pnpm dev` or `pnpm dev:all` automatically spawns the `dev:plugins` watcher. Any changes made to plugins in `local-plugins/` will be instantly rebuilt using Vite (externalizing large globals) and synced to `public/plugins-local/` for hot-reloading.
3. **Promote**: Once the plugin is stable and ready to be committed or published, run `node packages/wwv-cli/dist/index.js link <name>` to automatically move it to `packages/` and clean up the sandbox.
3. **Publish**: The `dev:plugins` script natively supports hot-reloading local plugins within the workspace. Once the plugin is ready, you can simply use `node packages/wwv-cli/dist/index.js publish <name> [--org <your-org>]` from the project root to publish it.
## When to Apply
When writing `fetch` implementations for plugins, or tracing why an entity dropped off the map. Ensure missing data correctly triggers the cache fallback via the DataBus. Ensure all new external plugins use the `bundle` format and exist in the marketplace registry to avoid CDN 404 hydrating crashes.
@@ -191,6 +191,12 @@ Plugins declare auth type in the manifest:
**Recommended for scale:** `token-exchange` — your server is never in the hot path for data requests.
### Shared Auth Contracts & Security Branding
When implementing the `token-exchange` flow or communicating across domains, all plugins and endpoints MUST use the strictly defined shared auth contracts from `@worldwideview/wwv-plugin-sdk/src/auth-contracts.ts` (e.g., `TokenExchangeRequest`, `WebSocketAuthMessage`).
**Sensitive Credentials**: All long-lived secrets (like API keys and tokens) MUST use the `SensitiveString` branded type and be instantiated via the `sensitive(str)` factory function. This prevents accidental logging/serialization and creates a single grep target for security audits.
---
## Plugin Development Workflows
@@ -382,9 +388,9 @@ While avoiding monolithic coupling, WWV plans to implement the following high-UX
## Local Plugins & Seeders
### 1. Local Sandbox Workflow
- **Scaffold**: `node packages/wwv-cli/dist/index.js create <name> --local` (creates inside `local-plugins/wwv-plugin-<name>`).
- **Develop**: `pnpm dev` triggers hot-reloading.
- **Promote**: `node packages/wwv-cli/dist/index.js link <name>` moves it to `packages/`.
- **Scaffold**: `node packages/wwv-cli/dist/index.js create` (creates inside `local-plugins/wwv-plugin-<name>` by default, or `packages/` if `--core` is used).
- **Develop**: `pnpm dev` triggers hot-reloading via `dev:plugins` watch script.
- **Publish**: `node packages/wwv-cli/dist/index.js publish <name> [--org <your-org>]` publishes the plugin from the project root. (No linking is needed; the sandbox natively functions in the workspace).
### 2. Data Engine Seeders
Seeders in `wwv-data-engine/src/seeders/` provide the backend data.
@@ -0,0 +1,21 @@
---
name: architectural-decision-records
description: Use when making significant architectural decisions, adding new patterns, or altering core workflows. This skill ensures that all major technical choices are documented via ADRs.
---
# Architectural Decision Records (ADRs)
## When to use this skill
Trigger this skill whenever you are about to introduce a new architectural pattern, make a load-bearing contract change, or bypass an established standard for a necessary reason.
## Guidelines
1. **Never make a major architectural change without an ADR**.
2. Store ADRs in `docs/architecture/decisions/` (create this directory if it doesn't exist).
3. An ADR must follow this exact structure:
- **Title**: Short, descriptive noun phrase.
- **Context**: What is the problem we are solving? What forces are at play? (Be objective).
- **Decision**: What is the specific change or pattern we are adopting?
- **Consequences**: What becomes easier because of this change? What becomes harder? (There are always trade-offs).
## Actionable Steps
When tasked with a major architecture change, pause and explicitly state: *"This requires an Architectural Decision Record."* Draft the ADR and ask the user to approve the reasoning *before* writing the implementation code.
+32
View File
@@ -0,0 +1,32 @@
---
name: typescript-docs
description: Use when writing new TypeScript code or refactoring existing code to ensure strict TSDoc/JSDoc hygiene is applied to all methods and interfaces.
---
# Strict TypeScript Documentation
## When to use this skill
Trigger this skill automatically whenever you are creating a new function, class, or interface, OR when you are modifying an existing undocumented function. This is the "Nutrition Label" rule.
## Guidelines
1. **JSDoc/TSDoc format is mandatory**. Always use `/** ... */` above the definition.
2. The block MUST include a short, plain-English description of *what* the function does and *why* it exists.
3. MUST explicitly list all parameters using `@param name - Description`.
4. MUST explicitly define the return value using `@returns Description`.
5. If the function intentionally throws an error, use `@throws {ErrorType} Description`.
## Example
```ts
/**
* Resolves the appropriate WebSocket engine URL for a given plugin.
* Prioritizes the local engine during development before falling back to cloud.
*
* @param pluginId - The unique string identifier of the plugin.
* @returns The fully qualified WebSocket URL for the stream.
* @throws {Error} If the plugin ID is undefined or missing.
*/
export function resolveEngineUrl(pluginId: string): string { ... }
```
## Actionable Steps
Never consider a PR or code edit "done" unless the new or modified functions have these strict labels attached. If you spot an undocumented function nearby while working, clean it up!
+17
View File
@@ -0,0 +1,17 @@
# TSDoc Review Log
This document tracks the progress of the codebase-wide TSDoc update.
## Ambiguous Functions Requiring 3.1 Pro Review
If a function's purpose cannot be deduced from its signature or body, it is listed here along with its file path and the specific confusion.
| File Path | Function/Interface Name | Reason for Ambiguity |
| :--- | :--- | :--- |
<!-- Flash: Append rows here as you work -->
## Completed Directories
- [/] `src/core/plugins` (In Progress: PluginRegistry.ts documented)
- [ ] `src/core/state`
- [x] `src/components` (Completed: Layout, Panels, Marketplace, Timeline, UI)
- [x] `packages/wwv-plugin-sdk`
- [x] `scripts`
@@ -7,7 +7,7 @@ description: Use when creating a new plugin, adding a new data source, or debugg
## Overview
A WorldWideView plugin is a self-contained data source that renders geospatial entities on a 3D Cesium globe. Every plugin implements the `WorldPlugin` interface from the SDK and connects to a **data engine** (Fastify + Redis) that streams live data over WebSocket.
A WorldWideView plugin is a self-contained data source that renders geospatial entities on a 3D Cesium globe. Every plugin implements the `WorldPlugin` interface from the SDK and connects to the **V2 Data Engine** (Fastify + Redis) that streams live data over WebSocket.
**Core principle:** Plugins are code bundles. The engine pushes data. The frontend renders it. There is no REST polling between frontend and engine — only WebSocket streaming.
@@ -54,7 +54,7 @@ digraph plugin_type {
| Sandbox plugin | `local-plugins/wwv-plugin-<name>/` | Local development workspace for new plugins |
| Plugin class | `packages/wwv-plugin-<name>/src/index.ts` | Implements `WorldPlugin` interface |
| Package metadata | `packages/wwv-plugin-<name>/package.json` | `worldwideview` block with id, type, format, category |
| Engine seeder | `wwv-data-engine/src/seeders/<name>.ts` | Fetches external data → Redis → WS broadcast |
| Engine seeder | `wwv-seeders/src/seeders/<name>.ts` | Fetches external data → Redis → WS broadcast |
| Build config | `next.config.ts` → `transpilePackages` | Required for monorepo packages |
| TS alias | `tsconfig.json` → `paths` | Required for monorepo packages |
| Registration | `src/core/plugins/PluginRegistry.ts` | Register plugin at boot |
@@ -72,9 +72,8 @@ digraph plugin_type {
The standard way to develop a new plugin is using the **Local Sandbox** (`local-plugins/` directory). This keeps experimental code out of the main monorepo packages until it is ready for production.
1. **Scaffold**: Run `node packages/wwv-cli/dist/index.js create <name> --local` from the project root. This generates a boilerplate plugin in `local-plugins/wwv-plugin-<name>`.
2. **Develop**: Run `pnpm dev`. The built-in file watcher (`pnpm dev:plugins`) automatically rebuilds and syncs your local plugin to `public/plugins-local/` whenever you save a file.
3. **Promote**: When stable, run `node packages/wwv-cli/dist/index.js link <name>`. This promotes the plugin to the `packages/` directory and cleans up the sandbox artifacts.
4. **Install**: Run `pnpm install` from the root to update workspace symlinks.
2. **Develop**: Run `pnpm dev`. The built-in file watcher (`pnpm dev:plugins`) automatically rebuilds and syncs your local plugin to `public/plugins-local/` whenever you save a file for instant hot-reloading.
3. **Publish (Optional)**: When stable, you can use `node packages/wwv-cli/dist/index.js publish <name>` from the project root to publish the plugin to NPM (use the `--org <your-org>` flag to publish under your own NPM organization instead of `@worldwideview`). There is no need to 'link' plugins to the core monorepo manually, as the local sandbox runs natively inside the workspace.
### 1.1 Implement the Interface
@@ -230,9 +229,9 @@ await pluginManager.registerPlugin(plugin);
**C. Dynamic import (runtime):**
For user-imported GeoJSON layers, call `pluginManager.loadFromManifest(manifest)` directly.
### 1.6 Build Configuration (Promoted Monorepo Packages Only)
### 1.6 Build Configuration (Core Monorepo Packages Only)
Once a plugin is promoted from the local sandbox via the `link` command, it becomes a formal monorepo package. You must manually add it to the build pipeline:
If you decide to manually move a plugin from the local sandbox into the core `packages/` directory, you must manually add it to the build pipeline:
Add to `next.config.ts`:
@@ -257,7 +256,7 @@ Run `pnpm install` from project root after creating the package.
## Part 2: Data Engine Seeder
The data engine is a **content-agnostic runner** (`wwv-data-engine` public, deployed via Docker). It runs Fastify on port 5000 with Redis caching and WebSocket streaming. Seeders are volume-mounted from `local-seeders/` (dev) or downloaded from GitHub Releases (production).
The data engine is a **content-agnostic Host Environment runner** (`wwv-data-engine`, deployed via Docker). It runs Fastify on port 5000 with Redis caching and WebSocket streaming. Seeders are volume-mounted from `local-seeders/` (dev) or dynamically downloaded and linked via pnpm workspaces from GitHub Releases (`wwv-seeders` and `wwv-seeders-private`) in production.
> [!IMPORTANT]
> If you are **migrating** an existing plugin from `packages/` to `local-plugins/`, use the `migrate-legacy-plugin` skill instead. It covers both frontend routing fixes AND backend seeder build fixes as two independent concerns.
@@ -373,9 +372,12 @@ interface SeederDefinition {
}
```
### 2.4 Auto-Discovery
### 2.4 Auto-Discovery & Dependencies
`src/seeders/index.ts` dynamically `require()`s every `.ts`/`.js` file in the seeders directory (except `index.ts` and test files). **You do not need to manually import your seeder** — just create the file and call `registerSeeder()` at module scope.
The V2 engine dynamically `import()`s every compiled `.mjs` file in the extracted seeder workspaces. **You do not need to manually import your seeder** — just create the file and call `registerSeeder()` at module scope.
> [!IMPORTANT]
> **V2 Engine Dependencies:** Seeders run in the unified V2 host environment which provides common packages (`zod`, `ws`, `undici`, etc.). **You MUST NOT bundle these dependencies** in your seeder's `dist` folder. Leave them externalized in your build config.
### 2.5 SQLite History (Optional)
@@ -416,7 +418,7 @@ db.exec(`
**Engine → Client:**
```json
{ "type": "welcome", "engine": "wwv-data-engine", "plugins": ["earthquakes", "wildfires", ...] }
{ "type": "welcome", "engine": "wwv-data-engine-v2", "plugins": ["earthquakes", "wildfires", ...] }
{ "type": "data", "pluginId": "earthquakes", "payload": { "items": [...], "totalCount": 42 } }
```
@@ -490,10 +492,110 @@ Place GeoJSON in `data/data.json`. The compiler auto-generates a `WorldPlugin` c
---
## Part 5: Example - Simple ISS Tracker Plugin
Here is a minimal, complete example of a live ISS Tracker plugin utilizing both the frontend SDK and the V2 Engine.
### 1. Frontend Plugin (`local-plugins/wwv-plugin-iss/src/index.ts`)
```typescript
import type {
WorldPlugin, PluginContext, GeoEntity,
CesiumEntityOptions, TimeRange, LayerConfig, PluginCategory
} from "@worldwideview/wwv-plugin-sdk";
import { Satellite } from "lucide-react";
import pkg from "../package.json";
export default class IssPlugin implements WorldPlugin {
id = "iss";
name = "ISS Tracker";
description = "Real-time International Space Station tracking";
icon = Satellite;
category: PluginCategory = "space";
version = pkg.version;
async initialize(ctx: PluginContext): Promise<void> {}
destroy(): void {}
async fetch(timeRange: TimeRange): Promise<GeoEntity[]> {
return []; // WS-only plugin
}
getPollingInterval(): number {
return 0; // WS-only
}
getLayerConfig(): LayerConfig {
return {
color: "#ffffff",
clusterEnabled: false,
maxEntities: 1,
};
}
renderEntity(entity: GeoEntity): CesiumEntityOptions {
return {
type: "point",
color: "#ffffff",
size: 10,
outlineColor: "#3b82f6",
outlineWidth: 2,
};
}
}
```
### 2. Backend Init Seeder (`wwv-seeders/src/seeders/iss.ts`)
```typescript
import { setLiveSnapshot } from "../redis";
import { registerSeeder } from "../scheduler";
function startIssSeeder() {
console.log("[ISS] Starting live tracker...");
async function poll() {
try {
const res = await fetch("https://api.wheretheiss.at/v1/satellites/25544");
const data = await res.json();
const item = {
id: "iss",
lat: data.latitude,
lon: data.longitude,
alt: data.altitude * 1000, // Convert km to meters
name: "International Space Station",
speed: data.velocity,
};
await setLiveSnapshot("iss", {
source: "iss",
fetchedAt: new Date().toISOString(),
items: [item],
totalCount: 1,
}, 10);
} catch (err) {
console.error("[ISS] Fetch failed", err);
}
}
poll(); // Initial fetch
setInterval(poll, 5000); // Poll every 5 seconds
}
registerSeeder({
name: "iss",
init: startIssSeeder,
});
```
---
## Common Mistakes
### "Sandbox Plugin Breaking Next.js Build"
1. **Premature Configuration** — Modifying `next.config.ts` (`transpilePackages`) or `tsconfig.json` (`paths`) while a plugin is still in `local-plugins/`. The `local-plugins` sandbox relies on dynamic hot-loading in the browser via `pnpm dev:plugins`. Do **not** touch monorepo configs until the plugin is formally promoted using `wwv link <name>`.
1. **Premature Configuration** — Modifying `next.config.ts` (`transpilePackages`) or `tsconfig.json` (`paths`) while a plugin is still in `local-plugins/`. The `local-plugins` sandbox relies on dynamic hot-loading in the browser via `pnpm dev:plugins`. Do **not** touch monorepo configs for local plugins.
2. **Manual Registration** — Manually adding a sandbox plugin to `AppShell.tsx`. Let the local hot-loading manifest handle sandbox plugins dynamically.
### "Missing Boilerplate / Errors in package.json"
@@ -530,8 +632,8 @@ Categories are **lowercase**: `"aviation"` not `"Aviation"`, `"natural-disaster"
## End-to-End Checklist
- [ ] **Development:** Scaffolded via `wwv create <name> --local` and developed in `local-plugins/`
- [ ] **Promotion:** Promoted to monorepo via `wwv link <name>` when stable
- [ ] **Development:** Scaffolded via `node packages/wwv-cli/dist/index.js create` and developed in `local-plugins/`
- [ ] **Publishing:** Published to NPM via `node packages/wwv-cli/dist/index.js publish <name> [--org <your-org>]` (if making public)
- [ ] **Frontend:** Plugin class implements `WorldPlugin` with correct `id`
- [ ] **Frontend:** `package.json` has `worldwideview` block with matching `id`
- [ ] **Frontend:** Version imported from `package.json` (never hardcoded)
@@ -539,7 +641,7 @@ Categories are **lowercase**: `"aviation"` not `"Aviation"`, `"natural-disaster"
- [ ] **Frontend:** Added path alias in `tsconfig.json`
- [ ] **Frontend:** Registered via `pluginRegistry` + `pluginManager` in `AppShell.tsx`
- [ ] **Frontend:** `renderEntity()` doesn't mix point/billboard properties
- [ ] **Engine:** Seeder file in `src/seeders/<name>.ts`
- [ ] **Engine:** Seeder file in `wwv-seeders/src/seeders/<name>.ts` (or private repo)
- [ ] **Engine:** `registerSeeder({ name })` matches frontend plugin `id`
- [ ] **Engine:** Calls `setLiveSnapshot()` with correct plugin ID key
- [ ] **Engine:** Data shape is an object with `items` array (or plugin implements `mapWebsocketPayload`)
+2
View File
@@ -23,3 +23,5 @@ artifacts/
performance/
tmp/
*.geojson
**/.pnpm-store
local-seeders*
-24
View File
@@ -1,24 +0,0 @@
# PostgreSQL connection string.
# For local dev: The platform will automatically spin up PostgreSQL via Docker Compose.
# Set DATABASE_URL to: postgresql://postgres:postgres@localhost:5432/worldwideview?schema=public
#
# For cloud/production: Provide your external Postgres connection string (e.g. Supabase)
# and set WWV_SKIP_LOCAL_DB=true to prevent Docker from spinning up a local database instance.
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/worldwideview?schema=public
# Set this to true in production to prevent docker-compose or pnpm run dev from starting the local database.
# WWV_SKIP_LOCAL_DB=false
# Default plugins enabled on boot for demo edition
# Comma-separated list of plugin IDs
NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS=iranwarlive,satellite,gps-jamming
# Edition: "local" | "cloud" | "demo"
NEXT_PUBLIC_WWV_EDITION=demo
# Auth Secret (REQUIRED for Docker — generate with: openssl rand -hex 32)
# Must be stable across container restarts to preserve sessions.
# [WARNING] NEVER commit real secrets here. Real secrets must ONLY go into .env.local!
AUTH_SECRET=changeme_d64c1f35b447da89cf6ed5a0988da1379b21904edb91a87c3f5a63942e3d23a4_changeme
+32
View File
@@ -1,10 +1,29 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
# Non-blocking dependency audit. Surfaces high / critical vulnerabilities
# in the CI output without failing the build. Flip `continue-on-error` to
# `false` once the current transitive vulns (see #97) are resolved.
audit:
name: Dependency Audit
runs-on: ubuntu-latest
continue-on-error: true
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm audit --audit-level high
typecheck:
name: Type Check
runs-on: ubuntu-latest
@@ -19,6 +38,19 @@ jobs:
- run: npx prisma generate
- run: pnpm exec tsc --noEmit
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm lint
test:
name: Unit Tests
runs-on: ubuntu-latest
+1 -1
View File
@@ -54,7 +54,7 @@ jobs:
NEXT_PUBLIC_CESIUM_ION_TOKEN=${{ secrets.NEXT_PUBLIC_CESIUM_ION_TOKEN }}
NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=${{ secrets.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY }}
NEXT_PUBLIC_BING_MAPS_KEY=${{ secrets.NEXT_PUBLIC_BING_MAPS_KEY }}
NEXT_PUBLIC_WWV_EDITION=${{ vars.NEXT_PUBLIC_WWV_EDITION || 'demo' }}
NEXT_PUBLIC_WWV_EDITION=${{ vars.NEXT_PUBLIC_WWV_EDITION || 'local' }}
NEXT_PUBLIC_WS_ENGINE_URL=${{ vars.NEXT_PUBLIC_WS_ENGINE_URL }}
NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=${{ vars.NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL }}
NEXT_PUBLIC_ADSENSE_CLIENT_ID=${{ secrets.NEXT_PUBLIC_ADSENSE_CLIENT_ID }}
+53
View File
@@ -0,0 +1,53 @@
name: Mutation Testing
# Mutation testing is expensive (10–30 min per full run, even with
# `coverageAnalysis: "perTest"`), so we don't gate every PR on it.
# Instead it runs weekly so we catch drift in test quality, and on
# demand via workflow_dispatch when someone wants to validate a
# specific change.
on:
schedule:
# 03:00 UTC Monday = 10 PM US Eastern Sunday night.
- cron: '0 3 * * 1'
workflow_dispatch:
permissions:
contents: read
jobs:
stryker:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Required for Stryker's incremental mode.
- name: Setup pnpm
uses: pnpm/action-setup@v3
with:
version: 9
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Generate Prisma client
run: pnpm exec prisma generate
- name: Run Stryker
run: pnpm exec stryker run
- name: Upload mutation report
if: always()
uses: actions/upload-artifact@v4
with:
name: stryker-report
path: reports/mutation/
retention-days: 30
+121
View File
@@ -0,0 +1,121 @@
name: Test Setup Scripts
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
permissions:
contents: read
jobs:
test-bash:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Start local HTTP server
run: |
python3 -m http.server 8080 &
sleep 2 # Wait for server to start
- name: Patch setup.sh to use local server
run: |
sed -i 's|https://raw.githubusercontent.com/silvertakana/worldwideview/main|http://localhost:8080|g' self-host/setup.sh
- name: Run setup.sh
run: |
cd self-host
bash setup.sh
- name: Verify .env generation
run: |
cd self-host
if [ ! -f .env ]; then
echo ".env file was not created"
exit 1
fi
if ! grep -q "^AUTH_SECRET=[a-f0-9]\{64\}$" .env; then
echo "AUTH_SECRET was not generated correctly or is missing"
exit 1
fi
- name: Verify docker-compose.yml download
run: |
cd self-host
if [ ! -f docker-compose.yml ]; then
echo "docker-compose.yml was not downloaded"
exit 1
fi
- name: Verify Docker containers are running
run: |
cd self-host
docker compose ps
if ! docker compose ps | grep -q "Up"; then
echo "Docker containers failed to start"
exit 1
fi
test-powershell:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Start local HTTP server
run: |
python3 -m http.server 8080 &
sleep 2 # Wait for server to start
- name: Patch setup.ps1 to use local server
run: |
sed -i 's|https://raw.githubusercontent.com/silvertakana/worldwideview/main|http://localhost:8080|g' self-host/setup.ps1
- name: Run setup.ps1
run: |
cd self-host
pwsh ./setup.ps1
- name: Verify .env generation
run: |
cd self-host
if [ ! -f .env ]; then
echo ".env file was not created"
exit 1
fi
if ! grep -q "^AUTH_SECRET=[a-f0-9]\{64\}$" .env; then
echo "AUTH_SECRET was not generated correctly or is missing"
exit 1
fi
- name: Verify docker-compose.yml download
run: |
cd self-host
if [ ! -f docker-compose.yml ]; then
echo "docker-compose.yml was not downloaded"
exit 1
fi
- name: Verify Docker containers are running
run: |
cd self-host
docker compose ps
if ! docker compose ps | grep -q "Up"; then
echo "Docker containers failed to start"
exit 1
fi
+11 -1
View File
@@ -65,7 +65,6 @@ yarn-error.log*
# env files (can opt-in for committing if needed)
.env*
!.env
# vercel
.vercel
@@ -102,6 +101,17 @@ packages/wwv-data-engine/
/public/cesium/
build_output*.log
build_output*.txt
/build*.log
# Root-level scratch scripts and agent artifacts
tmp_*.js
dump-*.js
dump_*.py
test*.js
test*.mjs
delete-dups.js
commit.json
skills-lock.json
# Seeder repositories
/local-seeders/
+1
View File
@@ -0,0 +1 @@
v20
+294 -71
View File
@@ -37,76 +37,17 @@ Our primary design, feature-set, and operational layout goal is to mimic the str
## 4. Architecture Patterns
### 4.1 Plugin System (Core Abstraction)
> [!NOTE]
> See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the human-facing architecture deep-dive — plugin system, state management, data pipeline, data engine & seeders, rendering pipeline, and edition system.
Every data source is a **plugin** implementing the `WorldPlugin` interface from `@worldwideview/wwv-plugin-sdk`. The lifecycle utilizes a real-time WebSocket Firehose pipeline:
Key invariants agents MUST respect:
```text
PluginRegistry.register() → PluginManager.registerPlugin()
→ plugin.initialize(context)
Visibility Toggle → DataBusSubscriber subscribes to layer via WsClient
→ Engine responds with instantaneous websocket snapshots over /stream
→ WsClient pipes to DataBus.emit("dataUpdated", WsStreamPayload)
→ Store → EntityRenderer → Globe
```
Four plugin architectures exist (All-Bundle Model):
1. **Data Engine Seeder** — Lightweight `seeder.mjs` script executed by the dynamic `wwv-data-engine` runner (previously standalone microservices).
2. **Dynamic CDN Loaded (Bundle)** — Externally developed plugins dynamically imported at runtime via ES module CDNs (e.g., `unpkg.com` version-pinned URLs).
3. **Static Compiled (Bundle)** — Static GeoJSON data wrapped into JS bundles via `wwvStaticCompiler` during build/sync (previously `StaticDataPlugin`).
4. **Active Proxied (Bundle)** — Next.js API routes bundled to provide frontend interactions (previously `DeclarativePlugin`).
All plugins are now dynamically imported at runtime as ES module bundles via `loadPluginFromManifest` utilizing `import(/* webpackIgnore: true */ entry)`. The legacy `StaticDataPlugin` and `DeclarativePlugin` runtimes are fully deprecated.
Plugin types are re-exported from SDK through `src/core/plugins/PluginTypes.ts` and `PluginManifest.ts` — **source of truth is always `@worldwideview/wwv-plugin-sdk`**.
### 4.2 State Management
Zustand store with **nine slices**: `globe`, `layers`, `timeline`, `ui`, `filter`, `data`, `config`, `favorites`, `geojson`. Each slice is in its own file under `src/core/state/`.
- Access via `useStore` hook or `useStore.getState()` outside React
- Plugin settings stored in `configSlice.dataConfig.pluginSettings`
- Polling intervals stored in `configSlice.dataConfig.pollingIntervals`
### 4.3 Data Pipeline
```text
Engine push /stream → DataBusSubscriber WsClient router
→ WsClient.handleMessage() → DataBus.emit("websocketData")
→ DataBusSubscriber → _hydrateSnapshot() → Store.entitiesByPlugin
→ GlobeView (memoized visible entities)
→ EntityRenderer (billboard/point primitives)
→ AnimationLoop (horizon culling, hover/selection)
→ StackManager (co-located entity grouping)
```
### 4.3.1 Engine & Seeders Architecture
The data engine is a **content-agnostic runner** (`wwv-data-engine`, public) that discovers and executes seeder scripts from a configurable directory.
- **Local Dev**: Engine runs via Docker Compose on port 5000, reading seeders dynamically from `local-seeders/` (split into `community` and `private` tiers).
- **Production**: Engine container on Coolify, downloads release bundles from `wwv-seeders-community` and `wwv-seeders-private` on startup and unzips them into `/app/seeders`.
- **Split-routing**: `resolveEngineUrl` prioritizes the **Local Dev Engine (localhost:5001)** for local testing (following 12-Factor App methodology), falling back to cloud-hosted endpoints.
- **Agnostic Frontend Architecture**: WorldWideView is a completely agnostic renderer. It has absolutely no concept of a "unified" Data Engine. If 30 plugins require 30 different WebSocket servers, the application will blindly open 30 connections.
- **Self-Contained Plugins**: Each plugin is a self-contained package and **MUST explicitly declare its own `streamUrl` in its manifest or config**. Do NOT assume the frontend acts as a unified pipe. It just so happens that our default plugins share the `wwv-data-engine` backend, but the platform is 100% decentralized.
### 4.4 Rendering Pipeline
- **Primitive-based**: Uses `PointPrimitiveCollection`, `BillboardCollection`, `LabelCollection` — NOT Cesium Entity API
- **Chunked processing**: Large datasets (10k+) rendered via `ChunkedProcessor`
- **LOD system**: Model-type entities promoted to 3D models at close range (`useModelRendering`)
- **Horizon culling**: Manual dot-product calculation against Earth radius (NOT depth testing)
- **Stack/Spiderifier**: `StackManager` groups co-located entities; `stackAnimation` handles expansion
### 4.5 Edition System
Three editions controlled by `NEXT_PUBLIC_WWV_EDITION`:
- **`local`** — Self-hosted, full features, auth enabled
- **`cloud`** — Managed cloud instance, full features
- **`demo`** — Public demo, auth disabled, optional admin via `WWV_DEMO_ADMIN_SECRET`
Feature flags derived from edition in `src/core/edition.ts`.
- **Plugin source of truth**: `@worldwideview/wwv-plugin-sdk` — never define plugin types locally.
- **All-Bundle Model**: every plugin (seeder, CDN-loaded, static-compiled, active-proxied) is dynamically imported via `loadPluginFromManifest` using `import(/* webpackIgnore: true */ entry)`. Legacy `StaticDataPlugin` / `DeclarativePlugin` runtimes are deprecated.
- **Agnostic frontend**: the renderer has no concept of a "unified" data engine. Each plugin **MUST declare its own `streamUrl`** in its manifest or config; do not assume one shared pipe.
- **Nine Zustand slices** under `src/core/state/`: `globe`, `layers`, `timeline`, `ui`, `filter`, `data`, `config`, `favorites`, `geojson`. Access via `useStore` in React, `useStore.getState()` elsewhere.
- **Primitive-based rendering** (not Cesium Entity API). Point/Billboard/Label/Polyline collections only. Never mix `size`/`outlineWidth`/`outlineColor` onto billboard entities — GPU silently clips.
- **Three editions** controlled by `NEXT_PUBLIC_WWV_EDITION` (`local` / `cloud` / `demo`); feature flags derived in `src/core/edition.ts`.
---
@@ -114,13 +55,13 @@ Feature flags derived from edition in `src/core/edition.ts`.
### 5.1 File Size
**Max 150 lines per file.** If a file grows beyond this, modularize it. Extract helpers, split components, use hooks.
**Guideline: ~300 lines per file.** If a file grows excessively large, consider modularizing it. Extract helpers, split components, or use hooks.
### 5.2 Import Aliases
- `@/*` → `./src/*`
- `@worldwideview/wwv-plugin-sdk` → `./packages/wwv-plugin-sdk/src`
- Each plugin has its own alias in `tsconfig.json`
- Plugin modules are dynamically imported and do not require individual `tsconfig.json` aliases
### 5.3 CSS Rules
@@ -162,7 +103,8 @@ Built-in plugins are instantiated in `AppShell.tsx` and registered via `PluginRe
> - **MUST Detail Commit Levels & Bumps**: On description changes or release notes, you must detail the level of commit (Major/Minor/Fix) for *each* individual change. If there are multiple accumulated changes, you MUST EITHER commit them individually and bump the version each time, OR commit them all at once and bump the version multiple times.
> - **MUST Explain Complex Concepts Simply**: Whenever providing a complicated technical explanation to the user, you MUST include a simple explanation below it. Use an analogy with reference to the correct terminology, comparing the concept to something from everyday life to ensure the user easily understands it.
> - **MUST Be Transparent & Narrate Actions (Gemini 3.1 Agents)**: If you are a Gemini 3.1 agent, you MUST always be fully transparent. **Whenever you do anything, you must explicitly say what you are going to do in a visible chat message to the user, and ONLY THEN do it.** This ensures the user can actually see and verify what you are doing in real time. Do not jump to destructive actions without stating your intent first. Keep this narration conversational and natural. Avoid stiff, robotic templates. Just explicitly drop a brief, casual note about what you are checking, fixing, or deleting *before* you run the tool.
> - **MUST Wait for Explicit Authorization**: Do not take action unless explicitly told to do so. If the user highlights a piece of code, brings up a bug, or asks a question, your ONLY job is to analyze it, investigate the root cause, and explain what is wrong or answer the question. **Do not write the fix, delete files, or execute changes unless the user explicitly gives you the order to do so.** Wait for clear authorization before taking action. **Crucially, if you realize you have violated this rule by taking an unauthorized action, DO NOT automatically revert it. Reverting is itself an action that requires authorization. Just answer the question.**
> - **MUST Require Explicit Authorization**: Do NOT execute any state-changing tools (e.g., modifying files, writing code, running scripts, executing git commands) without first obtaining clear, explicit permission from the user to proceed with that specific action, **UNLESS** the action is a simple, straightforward, and safe operation (e.g., no deletion or dangerous operations). For safe operations, you may proceed without explicit permission. Otherwise, inform the user of your proposed plan and WAIT for their approval before acting. **Crucially, if you realize you have violated this rule by taking an unauthorized action, DO NOT automatically revert it. Reverting is itself an action that requires authorization. Just answer the question.**
> - **MUST Ask Clarifying Questions**: Never assume anything. If requirements are unclear, if you encounter an unexpected roadblock, or if the user's intent could be interpreted in multiple ways, you MUST pause and ask clarifying questions. Do NOT proceed until the developer has explicitly answered your question or requested you to proceed anyway.
### 5.8 Workspace Hygiene
Whenever agents generate temporary debugging scripts, test REST endpoints via `.mjs`, or dump traces/JSON outputs, they **MUST** save these exclusively inside `/local-scripts/`. The root directory is strictly for production configuration files.
@@ -275,3 +217,284 @@ Refer to these skill documents for specialized tasks:
- **Cesium Entity Clipping**: If `billboard` entities are clipping or failing to render correctly, verify that you are not mixing `point` primitive properties (like `size` or `outlineWidth`) into the `billboard` options.
- **Build Exhaustion (Docker)**: Multi-stage pnpm builds generate massive cache layers. If a Coolify deployment fails silently or PostgreSQL crashes abruptly, check host disk space and run `docker builder prune -a -f`.
- **Next.js Typechecking Failures**: If backend-only `scripts/` fail during Next.js build, verify that the scripts directory is properly listed in the `exclude` array of `tsconfig.json`.
## 17. Coding Principles
You are about to write or modify code. **Read this file first.** It exists to prevent the failure mode where every fix makes the next harder — the kind of accumulated coupling and band-aid-on-band-aid that turns a clean codebase into a fragile one over months. This file is the constitution that keeps that from happening.
### The hard rule
> **Always interface-based, extensible, composable, modular. Never band-aids on band-aids.**
If you find yourself adding a flag, an `if`-check, or a special case to make a problem go away, you are probably band-aiding. Stop and find the seam where the abstraction broke. Fix it there.
### Core principles
#### 1. Interfaces before implementations
Define the contract first. The contract is what other components depend on; the implementation is replaceable. Public functions accept the interface, not the concrete type.
```ts
// Yes
function attachSource(source: DataSource) { ... }
// No
function attachPostgresSource(pg: PostgresInstance) { ... }
```
When a pattern repeats across two modules, refactor it into an interface immediately. Don't wait for the third copy to "earn" the abstraction — by then the costs have compounded.
#### 2. Loose coupling through explicit contracts
Components communicate through well-defined contracts: typed function signatures, events on a bus, message queues, or capability registries. Pick the form that fits, but pick *one* and make it the only path.
Components do **not** communicate through:
- Direct imports of each other's internal modules
- Shared mutable state outside the contract
- Synchronous request/response when async fits the actual data flow
- "Just this once" backdoors that bypass the contract
If you're tempted to write `import { internalThing } from '../other-module/internal'`, you are doing it wrong. If the symbol you need isn't part of the other module's public contract, either it should be — propose adding it — or you're solving the problem in the wrong place.
#### 3. Domain boundaries are sacred
Each domain (module, service, bounded context, plugin) owns its own state and its own surface. Cross-domain access is **explicit, gated, and audited** — never a shortcut.
Forbidden:
- Reading another domain's storage directly
- Calling another domain's private functions
- Hardcoded `if (tenant === 'X')` or `if (mode === 'special')` branches in shared code
Allowed:
- A documented capability or API on the other domain that you call
- A configuration field on the relevant record that drives the strategy
- Cross-domain access gated by explicit policy (default **deny**, opt-in per case), with the access itself logged
The rule of thumb: if removing a domain would require code archaeology in three other domains to figure out what depends on its internals, the boundary has already been violated. Treat that as a bug.
#### 4. Don't bend your architecture to fit a dependency
When you bring in a library or framework, use it where it fits cleanly; build natively where it doesn't.
Let the dependency handle (don't reinvent):
- The thing it's specifically good at, in the shape it expects
Your code owns (the dependency can't represent):
- Anything that's specifically your domain
- Anything that requires identity, lifecycle, or invariants the dependency doesn't model
- The integration seams between the dependency and your domain
If you find yourself bending your design to fit a library convenience, stop. Either the library has a hook for what you need, or you build it natively. Don't compromise architecture for the convenience of pulling in someone else's defaults.
#### 5. Data lifetimes are deliberate, not incidental
Different data has different lifetimes. Get this wrong and you'll either retain garbage forever or delete things users care about. Common categories:
- **Operational telemetry** (logs, metrics, internal events) — short rolling window. Useful for crash recovery and immediate investigation; not useful enough to keep forever.
- **User content** (messages, documents, records the user created or that represent their lived experience with the system) — **permanent unless the user explicitly deletes it.** Never pruned by a sweep, never deleted by a retention policy authored for telemetry.
- **Resumable session state** — bounded window appropriate to the use case; archived (state flag flipped) rather than deleted.
Name each category in your codebase. Write the retention policy for each one separately. Never propose a sweep that crosses categories — "delete events older than 30 days" is fine if events are telemetry; the same policy applied to user content is data loss masquerading as housekeeping. If storage pressure ever becomes real for content, introduce cold-tiered storage, not deletion.
#### 6. Optional features must be truly removable
Every optional feature (plugin, extension, integration, side module) declares its surface explicitly and communicates through the same contracts as everything else. No optional feature reaches into another's internals.
Test for whether something is core vs. optional: **if removing this feature should break the system, it's core. Otherwise it's optional, and it should be removable without leaving residue.**
If you can't delete an "optional" module's directory and have the system keep running, it isn't optional. Either fix the coupling or move it into core honestly.
#### 7. Put code where it belongs
When a feature spans layers (a trigger lives here, the action lives there, the data model lives somewhere else), resist the urge to fold it all into one place "for convenience." The feature lives in three places because each piece belongs to a different domain. Routing across them is the job — not collapsing them.
The general rule: if a feature needs to read/write durable state, it's a tool/extension on top of the layer that owns that state; if it's "the system should know about this concept," it's a configuration or contract change. Often it's both, with a thin handler that wires them together. That thin handler is fine — it's load-bearing — but it doesn't justify smashing the layers together.
### Antipatterns to refuse
These are common failure modes that, repeated over time, calcify a codebase. Refuse them when you catch yourself reaching for them.
| Antipattern | Better answer |
|---|---|
| Adding a new flag to an existing function instead of extracting a strategy | Extract the strategy interface; existing call sites pass the default strategy |
| Patching around a bug at the call site | Find the seam where the abstraction broke; fix it there |
| Direct database access from a feature module | Go through the layer that owns the data; if no surface exists, propose one |
| Hardcoded paths, model names, IDs, environment specifics in business logic | Configuration; or look up via registry |
| `if (tenant === 'X') { ... }` in shared code | Strategy on the record, or a per-tenant config field |
| Inheriting one layer's concerns into another (or vice versa) | Cross the boundary through the documented contract |
| "It works for now" — inline coupling between layers | If the layers are real, draw the contract; if they're not, merge them honestly |
| Adding a defensive `try/catch` to swallow an error | Find why the error happens; gate cleanly at the right boundary |
| Writing a comment to explain what code does | Rename and refactor so the code reads itself |
| Copying a snippet from one module into another "to avoid the dependency" | Either it belongs in a shared module, or the duplicate will drift — pick |
### Debugging discipline
When something breaks:
1. **Reproduce it.** Don't trust intuition about what's failing.
2. **Find the seam.** Where did the abstraction break? Which contract is being violated, and by whom?
3. **Fix at the seam.** Not at the call site. Not at the consumer. At the boundary that's wrong.
4. **If you can't find the seam, surface it.** Tell the user explicitly: "this is a design gap; the right fix needs an architectural decision, not a patch." Do not paper over.
If a fix doesn't work, **don't add another guard on top.** Find the real seam and gate cleanly. Stacked defensive layers are how clean codebases become unmaintainable.
### Lifecycle invariants and state-changing operations
Most recurring bugs cluster around the same shape: an operation crosses lifecycle state without checking, and the result is silent corruption, lost data, or orphan rows. The recipe that prevents recurrences:
1. **Name the invariant.** "Closed sessions don't accept work." "Scoped grants need a scope id." "Subscriptions past retention can't deliver swept events." Write it down before reaching for code.
2. **Throw a typed error at the seam.** The single function that crosses the invariant refuses the bad case with a typed, named error — not a boolean return, not a silent skip, not a generic `Error`.
3. **Pre-check at every call site that mutates *before* reaching the seam.** If the seam check fires after `store.append()`, you've left an orphan row. The pre-check is hygiene; the seam check is correctness — both are required. When the same pre-check appears at a second call site, extract a helper.
4. **Validate, then mutate — never the reverse.** Within a single function, resolve all inputs that could fail (key derivation, lookups, permission checks) before touching durable state. A validation throw should leave nothing half-applied. If you can't separate validation from mutation, the function is doing two jobs.
5. **A documented unsafe API is still unsafe.** A docstring that says "don't use this when X" is a foot-gun, not a warranty disclaimer. Either make the API safe in case X (drain, throw, refuse) or remove it.
If you're tempted to skip step 3 because "the seam check covers it," check whether the call site writes anything before reaching the seam. If yes, you need the pre-check.
### Definition of done — checklist for adding or updating a function
Every code change must satisfy the relevant checklist before merge. Refusal triggers below mean **stop and surface to the user** — do not ship a half-met checklist.
#### Adding a new function
All must be true:
- [ ] Belongs in this module (not somewhere else)
- [ ] Fulfills an existing interface, OR a new interface is added with it (and reasons documented in a spec doc / ADR)
- [ ] Has a doc-comment header (purpose + params + returns + thrown errors if relevant)
- [ ] Has at least one test that targets the contract (not implementation details)
- [ ] Test passes locally and in CI
- [ ] Doesn't introduce direct cross-module imports of internals — communication through public contracts only
- [ ] Doesn't touch storage owned by another component — route through that component's surface
- [ ] Matches the spec doc's contract for this component (if no spec covers it, update the spec first)
- [ ] Name is clear enough that the header comment is a summary, not an explanation
#### Updating an existing function
All must be true:
- [ ] Reason for change is clear (bug fix / new requirement / refactor / spec change)
- [ ] Doc-comment still accurate after change (update if not)
- [ ] Existing tests cover the new behavior (add new tests if not)
- [ ] Build is green (all tests passing)
- [ ] If this changes the contract: spec doc updated AND an ADR added if the change is load-bearing
- [ ] Fix is at the seam, not at the symptom (no band-aid patches)
- [ ] No new flags or special cases added in lieu of strategy extraction
#### Refusal triggers (any one means stop)
- Adding `if (tenant === 'X')` to shared code → use per-tenant config instead
- Adding a flag to make a problem go away → extract the abstraction the flag implies
- Direct DB or filesystem access from a feature module → route through the owning component
- `try`/`catch` swallowing an error → find why the error happens, gate cleanly
- Test omitted because "it's trivial" → no
- Function-header skipped because "it's obvious" → no
- "Just add another guard here" when a guard didn't work → find the real seam
- Patch shipped to "unblock the build" without root-cause fix → no, surface the design gap
If any criterion isn't met, stop. Surface to the user as a design question. Don't paper over.
### Code-style minimums
#### Comments
**Every function gets a doc-comment header** in your language's idiomatic format (TSDoc, JSDoc, Python docstrings, Rust `///`, Javadoc, etc.). Not optional. Long-running codebases get re-read after gaps; function-header docs are how re-onboarding stays cheap.
Required content:
- One-line summary at a contract level (what the function guarantees, not what the code does line-by-line)
- Each parameter and what it represents
- Return value
- Thrown errors / failure conditions if relevant
- Example usage when the call shape is non-obvious
Apply this to public, internal, exported, and private functions. Apply to methods on classes too.
**Inline comments inside function bodies** still follow the standard rule: only for non-obvious WHY (hidden constraints, workarounds, surprising behavior, references to bug reports). Don't comment WHAT the code does — well-named identifiers and the function-header doc cover that.
#### Tests
**Every function ships with at least one test. Tests passing is a build requirement.**
- Tests target the contract (function signature + documented behavior + invariants), not implementation details. Refactoring should not break tests; behavior changes should.
- A new implementation of an interface must pass the same contract test suite (write tests against the interface, not against a specific implementation).
- Test names describe the case being verified, not the function: `it('refuses resume after archival window expires')` not `it('resumeSession')`.
- For storage code: tests use a real (temporary) instance of the storage layer, created and torn down per test or per suite. Don't mock the storage engine — you're testing the wrong thing if you do.
- For integration code that depends on an external library's hooks: contract tests against that library's surface so a dependency bump catches behavior changes.
- Build pipeline (CI or local) runs all tests; non-zero exit = build fails. There is no "build succeeded but tests failed" state.
#### Logging
**Every new feature with a non-happy-path ships with a log line at each rare branch.** Use a structured logger with module-scoped child loggers. The log file is where "something's not working" turns into "what actually happened."
Level guidance:
- **info** — expected-but-noteworthy edges: a UI race that hits a closed resource, a permission bypass for a privileged principal. Correct behavior an operator might want to confirm fired.
- **warn** — should be rare and worth investigating: race past a pre-check, lost events past retention, programmer/operator errors (calling a method after stop, a key that should have resolved didn't).
- **error** — actual failures the operator must respond to: handler crashes, dispatch loop crashes, integration failures.
- **debug** — high-volume internal state changes; always pair with a `module` field so it can be filtered.
Pass structured fields, not interpolated strings — fields are what makes a log queryable:
```ts
// Yes
logger.warn({ session_id, state }, "rejected append against non-live session");
// No
logger.warn(`session ${session_id} (${state}) rejected append`);
```
If you add a new typed error or a new event topic, also log it. The typed error tells the immediate caller; the event tells subscribers; the log tells the operator. The three are independent surfaces for the same fact, and all three are needed — events don't show up in the log, logs don't show up on the bus, errors don't survive the catch.
#### Structure
- Keep modules small. If a file is over ~500 lines, ask whether it has more than one responsibility.
- Prefer explicit composition (caller wires things together) over implicit dependency-injection magic.
- One public concept per module. If a file exports both `Foo` and `unrelatedHelperUsedNowhereElse`, the helper has the wrong home.
#### Dependencies
**Always check the registry for the current version before adding or updating a dependency.** Don't pick versions from memory.
The simple test: did you actually run `<package-manager> view <pkg> version` (or its equivalent) before pinning? If not, you're guessing — and the guess is almost always behind, sometimes by a major version with active deprecation.
Why this matters:
- **Long-running codebases.** Stale dependency anchors compound. A v3 you picked because that's what was on your mind will still be v3 a year later, and the v4 migration gets harder every month it waits.
- **Active deprecations are real.** Common libraries are mid-deprecation cycles for older majors. Pinning to a soon-deprecated version on day one means the eventual upgrade is forced rather than chosen.
- **"Latest" doesn't mean "use without thinking."** Read the changelog for breaking changes; decide whether to take them now or pin behind explicitly. But the *default* posture should be: pick latest, and justify in writing if pinning behind.
If you must pin behind latest, leave a comment in the manifest (or a CHANGELOG note) explaining why — a known incompatibility with another dep, an in-progress migration, a tested-and-rejected major bump. *"I haven't checked"* is not an acceptable reason.
Apply to: adding a new dep, updating an existing one, scaffolding a new package. *Not* required for routine no-op installs that don't touch versions.
#### Doc-vs-spec discipline
Specification documents (the deeper ones that describe how a component must behave) are **functional specifications**, not narrative essays. The discipline:
- **Concrete data structures** — type definitions, schemas, DDL, JSON examples
- **Concrete function signatures** — input/output types, error types
- **Concrete event/message payloads** — name + schema + example
- **Concrete API signatures** — input/output schemas, side effects, permission requirements
- **Flow pseudocode** — when orchestration is non-obvious
- **Invariants** — explicitly listed: "after X happens, Y is always true"
- **Failure modes** — enumerated: "if X fails, the system does Y"
- **Acceptance tests** — statements another engineer can implement: "given input X, output Y"
Avoid in spec docs:
- Long prose explaining motivation (that goes in ADRs / decision records)
- Discussion of alternatives considered (also ADRs)
- Background context (README handles this)
- Marketing/aspirational tone
Spec docs are for implementation. Read one and you should know what to build.
### When in doubt
Ask the human user. Specifically:
- "I don't see a clean seam for this; the options I see are A or B. Which fits the architecture you have in mind?"
- "This requires a new contract / capability / interface. Should I draft it before implementing?"
- "I'm about to add a special case here; that smells like a missing abstraction. Do you want me to extract the abstraction or note the smell and defer?"
Don't ship band-aids and ask forgiveness later. The user has explicitly said: prevent that pattern.
+42 -1
View File
@@ -30,6 +30,9 @@ ARG NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL
ARG NEXT_PUBLIC_ADSENSE_CLIENT_ID
ARG NEXT_PUBLIC_SUPABASE_URL
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
ARG NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED
ARG NEXT_PUBLIC_WWV_BUILD_ID
ARG NEXT_PUBLIC_WWV_BUILD_AT
# Run our pregenerate schema swap script and then generate Prisma client
RUN NEXT_PUBLIC_WWV_EDITION=$NEXT_PUBLIC_WWV_EDITION pnpm run generate
@@ -37,6 +40,41 @@ RUN NEXT_PUBLIC_WWV_EDITION=$NEXT_PUBLIC_WWV_EDITION pnpm run generate
# Database migrations run at container startup via docker-entrypoint.sh
# DATABASE_URL must be set to a PostgreSQL connection string
# Stamp the build with a millisecond-precision id + iso timestamp. If the
# operator hasn't passed NEXT_PUBLIC_WWV_BUILD_ID via build args, generate
# one here so /api/build and the client console.log both carry a unique
# value per `docker build`.
RUN if [ -z "$NEXT_PUBLIC_WWV_BUILD_ID" ]; then \
NEXT_PUBLIC_WWV_BUILD_ID="$(date +%s%3N 2>/dev/null || node -e 'process.stdout.write(String(Date.now()))')" ; \
fi && \
if [ -z "$NEXT_PUBLIC_WWV_BUILD_AT" ]; then \
NEXT_PUBLIC_WWV_BUILD_AT="$(node -e 'process.stdout.write(new Date().toISOString())')" ; \
fi && \
echo "$NEXT_PUBLIC_WWV_BUILD_ID" > /app/.build-id && \
echo "$NEXT_PUBLIC_WWV_BUILD_AT" > /app/.build-at
# Write .env.production.local so Next.js sees every NEXT_PUBLIC_* var
# whose ARG was passed in. Docker doesn't reliably promote ARGs into the
# build process's environment for `next build` to inline references with
# Webpack's DefinePlugin — `process.env.NEXT_PUBLIC_X` either gets the
# inlined literal value (when set) or stays as a runtime polyfill access
# that resolves to undefined in the browser. Writing the file is the
# documented Next.js path and behaves the same on every host.
RUN set +e ; { \
echo "NEXT_PUBLIC_WWV_BUILD_ID=$(cat /app/.build-id)" ; \
echo "NEXT_PUBLIC_WWV_BUILD_AT=$(cat /app/.build-at)" ; \
if [ -n "$NEXT_PUBLIC_WWV_EDITION" ]; then echo "NEXT_PUBLIC_WWV_EDITION=$NEXT_PUBLIC_WWV_EDITION" ; fi ; \
if [ -n "$NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED" ]; then echo "NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED=$NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED" ; fi ; \
if [ -n "$NEXT_PUBLIC_CESIUM_ION_TOKEN" ]; then echo "NEXT_PUBLIC_CESIUM_ION_TOKEN=$NEXT_PUBLIC_CESIUM_ION_TOKEN" ; fi ; \
if [ -n "$NEXT_PUBLIC_GOOGLE_MAPS_API_KEY" ]; then echo "NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=$NEXT_PUBLIC_GOOGLE_MAPS_API_KEY" ; fi ; \
if [ -n "$NEXT_PUBLIC_BING_MAPS_KEY" ]; then echo "NEXT_PUBLIC_BING_MAPS_KEY=$NEXT_PUBLIC_BING_MAPS_KEY" ; fi ; \
if [ -n "$NEXT_PUBLIC_WS_ENGINE_URL" ]; then echo "NEXT_PUBLIC_WS_ENGINE_URL=$NEXT_PUBLIC_WS_ENGINE_URL" ; fi ; \
if [ -n "$NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL" ]; then echo "NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=$NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL" ; fi ; \
if [ -n "$NEXT_PUBLIC_ADSENSE_CLIENT_ID" ]; then echo "NEXT_PUBLIC_ADSENSE_CLIENT_ID=$NEXT_PUBLIC_ADSENSE_CLIENT_ID" ; fi ; \
if [ -n "$NEXT_PUBLIC_SUPABASE_URL" ]; then echo "NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL" ; fi ; \
if [ -n "$NEXT_PUBLIC_SUPABASE_ANON_KEY" ]; then echo "NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY" ; fi ; \
} > /app/.env.production.local
# Run Next.js build with Webpack cache mounted
RUN --mount=type=cache,target=/app/.next/cache NODE_OPTIONS="--max_old_space_size=3072" pnpm run build
RUN node scripts/copy-cesium.mjs
@@ -78,7 +116,10 @@ COPY --from=builder /app/prod/node_modules ./node_modules
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
COPY --from=builder /app/scripts/https-proxy.mjs ./scripts/https-proxy.mjs
COPY --from=builder /app/scripts/migrate-legacy.mjs ./scripts/migrate-legacy.mjs
# Build stamp — read by /api/build at runtime.
COPY --from=builder /app/.build-id ./.build-id
COPY --from=builder /app/.build-at ./.build-at
# Entrypoint: migrate DB on first run, then start server
COPY docker-entrypoint.sh ./docker-entrypoint.sh
+75 -15
View File
@@ -1,33 +1,93 @@
Elastic License 2.0
Acceptance
URL: https://www.elastic.co/licensing/elastic-license
## Acceptance
By using the software, you agree to all of the terms and conditions below.
Copyright License
## Copyright License
The licensor grants you a non-exclusive, royalty-free, worldwide, non-transferable, non-sublicensable license to use, copy, distribute, make available, and prepare derivative works of the software.
The licensor grants you a non-exclusive, royalty-free, worldwide,
non-sublicensable, non-transferable license to use, copy, distribute, make
available, and prepare derivative works of the software, in each case subject to
the limitations and conditions below.
Limitations
## Limitations
You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
You may not provide the software to third parties as a hosted or managed
service, where the service provides users with access to any substantial set of
the features or functionality of the software.
You may not move, alter, disable, or circumvent any of the licensing features contained in the software, or remove or obscure any functionality in the software that is protected by the licensing features.
You may not move, change, disable, or circumvent the license key functionality
in the software, and you may not remove or obscure any functionality in the
software that is protected by the license key.
You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor's trademarks is subject to applicable law.
You may not alter, remove, or obscure any licensing, copyright, or other notices
of the licensor in the software. Any use of the licensor’s trademarks is subject
to applicable law.
Patents
## Patents
The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import, and have imported, the software. This license is subject to the conditions of this license, and does not cover patent claims infringed by your modifications or your additions to the software. If you or your company make any written claim that the software infringes or contributes to an infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
The licensor grants you a license, under any patent claims the licensor can
license, or becomes able to license, to make, have made, use, sell, offer for
sale, import and have imported the software, in each case subject to the
limitations and conditions in this license. This license does not cover any
patent claims that you cause to be infringed by modifications or additions to
the software. If you or your company make any written claim that the software
infringes or contributes to infringement of any patent, your patent license for
the software granted under these terms ends immediately. If your company makes
such a claim, your patent license ends immediately for work on behalf of your
company.
Notices
## Notices
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms. If you modify the software, you must include prominent notices in modified copies stating that you have modified it.
You must ensure that anyone who gets a copy of any part of the software from you
also gets a copy of these terms.
No Other Rights
If you modify the software, you must include in any modified copies of the
software prominent notices stating that you have modified the software.
The terms do not imply any licenses other than those expressly granted under these terms.
## No Other Rights
Termination
These terms do not imply any licenses other than those expressly granted in
these terms.
If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violations of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
## Termination
If you use the software in violation of these terms, such use is not licensed,
and your licenses will automatically terminate. If the licensor provides you
with a notice of your violation, and you cease all violation of this license no
later than 30 days after you receive that notice, your licenses will be
reinstated retroactively. However, if you violate these terms after such
reinstatement, any additional violation of these terms will cause your licenses
to terminate automatically and permanently.
## No Liability
*As far as the law allows, the software comes as is, without any warranty or
condition, and the licensor will not be liable to you for any damages arising
out of these terms or the use or nature of the software, under any kind of
legal claim.*
## Definitions
The **licensor** is the entity offering these terms, and the **software** is the
software the licensor makes available under these terms, including any portion
of it.
**you** refers to the individual or entity agreeing to these terms.
**your company** is any legal entity, sole proprietorship, or other kind of
organization that you work for, plus all organizations that have control over,
are under the control of, or are under common control with that
organization. **control** means ownership of substantially all the assets of an
entity, or the power to direct its management and policies by vote, contract, or
otherwise. Control can be direct or indirect.
**your licenses** are all the licenses granted to you for the software under
these terms.
**use** means anything you do with the software requiring one of your licenses.
**trademark** means trademarks, service marks, and similar rights.
+8 -5
View File
@@ -17,7 +17,7 @@
[![CesiumJS](https://img.shields.io/badge/Cesium-JS-4272D0)](https://cesium.com/)
[![TypeScript Strict](https://img.shields.io/badge/TypeScript-Strict-3178C6?logo=typescript)](https://www.typescriptlang.org/)
[![Docker](https://img.shields.io/badge/Docker-Multi--Stage-2496ED?logo=docker)](https://www.docker.com/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![License: Elastic 2.0](https://img.shields.io/badge/License-Elastic_2.0-blue.svg)](LICENSE)
[![Discord](https://img.shields.io/discord/1481088998750294139?color=7289da&label=discord&logo=discord)](#)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://makeapullrequest.com)
@@ -36,6 +36,7 @@ WorldWideView is a real-time geospatial engine visualizing live global data on a
- **Real-Time Data Pipeline**: High-frequency WebSocket updates managed by a custom `DataBus`.
- **Advanced Entity Management**: Automatic horizon culling, chunked primitive rendering, and 3D stacking/spiderification.
- **Marketplace Integration**: Download and sync new plugins directly from the UI.
- **Agent Bus (opt-in)**: HTTP+SSE control surface that lets an external tool — typically an MCP server fronting an LLM — fly the globe, toggle layers, and select entities in the running browser session. Default off; see [Agent Bus docs](docs/agent-bus.md).
## Core Technologies
@@ -86,13 +87,13 @@ WorldWideView uses a multi-stage Dockerfile designed for standalone output. To d
**Mac/Linux:**
```bash
mkdir worldwideview && cd worldwideview
curl -fsSL https://raw.githubusercontent.com/silvertakana/worldwideview/main/setup.sh | bash
curl -fsSL https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/setup.sh | bash
```
**Windows (PowerShell):**
```powershell
mkdir worldwideview; cd worldwideview
Invoke-WebRequest -Uri https://raw.githubusercontent.com/silvertakana/worldwideview/main/setup.ps1 -UseBasicParsing | Invoke-Expression
Invoke-WebRequest -Uri https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/setup.ps1 -UseBasicParsing | Invoke-Expression
```
> [!NOTE]
@@ -145,6 +146,7 @@ WorldWideView is distributed across several specialized repositories:
3. **`worldwideview-plugins`**: First-party maintained plugins.
4. **`worldwideview-marketplace`**: The web application driving the plugin directory.
5. **`worldwideview-web`**: Marketing and landing site.
6. **[`szski/wwv-mcp`](https://github.com/szski/wwv-mcp)**: Reference MCP server for driving the globe from an LLM agent (Claude Code, Claude Desktop, Cursor, Cline, …) via the [Agent Bus](docs/agent-bus.md). Contributor-hosted today; may move under the project org.
## Development & Workflow
@@ -160,18 +162,19 @@ We welcome community contributions! Please review our coding standards and PR pr
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
This project is licensed under the Elastic License 2.0 - see the [LICENSE](LICENSE) file for details.
## Documentation Index
Explore our comprehensive documentation suite for detailed engineering insights:
- **[Project Overview](docs/project-overview.md)**: High-level value proposition and technology stack.
- **[Architecture](docs/architecture.md)**: DataBus event stream and Zustand state management.
- **[Architecture](docs/ARCHITECTURE.md)**: Plugin system, state management, data pipeline, and Cesium rendering deep-dive.
- **[Build System](docs/build-system.md)**: Monorepo structure, Next.js standalone output, and Docker builds.
- **[Development](docs/development.md)**: Coding conventions and common implementation patterns.
- **[Testing](docs/testing.md)**: Vitest setup and coverage targets.
- **[Deployment](docs/deployment.md)**: Coolify integration and persistent volumes.
- **[Agent Bus](docs/agent-bus.md)**: Wiring an MCP server (or any external tool) to drive the running globe.
- **[Files Catalog](docs/files.md)**: Comprehensive mapping of core source files.
> [!IMPORTANT]
-7
View File
@@ -1,7 +0,0 @@
# This file lists tools managed by Aftman, a cross-platform toolchain manager.
# For more information, see https://github.com/LPGhatguy/aftman
# To add a new tool, add an entry to this table.
[tools]
rojo = "rojo-rbx/[email protected]"
# rojo = "rojo-rbx/[email protected]"
-1
View File
@@ -1 +0,0 @@
C:/dev/worldwideview/agents.md
+34 -17
View File
@@ -1,10 +1,21 @@
services:
wwv:
build: .
build:
context: .
args:
- NEXT_PUBLIC_WWV_EDITION=${NEXT_PUBLIC_WWV_EDITION:-local}
- NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=${NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL:-}
- NEXT_PUBLIC_SUPABASE_URL=${NEXT_PUBLIC_SUPABASE_URL:-}
- NEXT_PUBLIC_SUPABASE_ANON_KEY=${NEXT_PUBLIC_SUPABASE_ANON_KEY:-}
- NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=${NEXT_PUBLIC_GOOGLE_MAPS_API_KEY:-}
- NEXT_PUBLIC_BING_MAPS_KEY=${NEXT_PUBLIC_BING_MAPS_KEY:-}
- NEXT_PUBLIC_CESIUM_ION_TOKEN=${NEXT_PUBLIC_CESIUM_ION_TOKEN:-}
- NEXT_PUBLIC_ADSENSE_CLIENT_ID=${NEXT_PUBLIC_ADSENSE_CLIENT_ID:-}
ports:
- "3000:3000"
volumes:
- wwv-data:/app/data
- ./public/plugins-local:/app/public/plugins-local:ro
env_file:
- path: .env
required: false
@@ -12,7 +23,7 @@ services:
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
- "DATABASE_URL=postgresql://postgres:postgres@db:5432/worldwideview?schema=public"
depends_on:
db:
condition: service_healthy
@@ -22,16 +33,17 @@ services:
timeout: 10s
retries: 3
start_period: 30s
restart: unless-stopped
db:
image: postgres:15-alpine
restart: always
restart: unless-stopped
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: worldwideview
ports:
- "5432:5432"
expose:
- "5432"
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
@@ -40,25 +52,28 @@ services:
timeout: 5s
retries: 5
start_period: 60s
profiles:
- "${WWV_SKIP_LOCAL_DB:-}"
wwv-data-engine:
build: ../wwv-data-engine-public
image: ghcr.io/silvertakana/wwv-data-engine:latest
command: >
sh -c "
echo 'Syncing workspace dependencies...' &&
cd $$SEEDERS_DIR/community && CI=true pnpm install --ignore-scripts && pnpm -r rebuild better-sqlite3 esbuild &&
if [ -d \"$$SEEDERS_DIR/private\" ]; then cd $$SEEDERS_DIR/private && CI=true pnpm install --ignore-scripts && pnpm -r rebuild better-sqlite3 esbuild; fi &&
cd /app && node dist/server.js"
ports:
- '5000:5000'
- "5000:5000"
environment:
- PORT=5000
- REDIS_URL=redis://wwv-redis:6379
- SEEDERS_DIR=/mnt/host/c/dev/worldwideview/local-seeders
- SKIP_SEEDER_DOWNLOAD=true
- SEEDERS_DIR=/app/seeders
- DB_PATH=/app/data/engine.db
depends_on:
wwv-redis:
condition: service_healthy
volumes:
- ./local-seeders:/mnt/host/c/dev/worldwideview/local-seeders
restart: unless-stopped
profiles:
- engine
wwv-redis:
image: redis:7-alpine
@@ -67,11 +82,13 @@ services:
interval: 5s
timeout: 3s
retries: 5
volumes:
wwv-data:
postgres-data:
profiles:
- engine
networks:
coolify:
external: true
volumes:
wwv-data:
postgres-data:
+193 -26
View File
@@ -1,33 +1,200 @@
<!-- Generated: 2026-04-23 06:11:00 UTC -->
# Architecture
## Overview
WorldWideView operates on a decoupled, plugin-based architecture designed for real-time visualization of geospatial data. The system is split between a Next.js 16 frontend that handles UI and CesiumJS 3D rendering, and a network of plugin data seeders that stream live updates via WebSockets.
WorldWideView is a **real-time geospatial intelligence engine**: a Next.js 16 frontend that renders live global data on a CesiumJS 3D globe, fed by a network of independent data seeders streaming over WebSockets. The whole platform is built on an "All-Bundle" plugin architecture, so data sources are decoupled from the core viewer and can be added, removed, or hot-swapped without touching rendering code.
The core design philosophy is the "All-Bundle Model," where plugins are dynamically imported at runtime as ES module bundles (`Dynamic CDN Loaded`). The frontend maintains a modular state architecture using Zustand, routing high-frequency data updates through a custom `DataBus` singleton to avoid React render cycle bottlenecks.
This document is the deep-dive companion to the [README](../README.md). It is intended for human contributors who want to understand how the pieces fit before opening their first PR. For agent-facing rules and conventions, see [`AGENTS.md`](../AGENTS.md) at the repo root and the documents under [`.agents/rules/`](../.agents/rules/).
## Component Map
- **Frontend App Shell:** Next.js App Router providing layout and base API routes (in `src/app/`).
- **Globe Rendering Engine:** CesiumJS wrapped in Resium, responsible for 3D primitive and model rendering (in `src/core/globe/`).
- **State Management:** Zustand slice-based architecture (in `src/core/state/`).
- **Data Pipeline:** Custom event bus (`DataBus`) and WebSocket clients (`DataBusSubscriber`) routing live data to state (in `src/core/data/`).
- **Plugin System:** Registration, lifecycle management, and ES module loaders (in `src/core/plugins/`).
- **Database Layer:** Prisma ORM connecting to PostgreSQL (in `prisma/`).
## System Overview
## Key Files
- `src/core/plugins/PluginManager.ts` - The PluginManager class. Core registry that instantiates plugins, calls `initialize()`, and handles lifecycle events.
- `src/core/plugins/loaders/InstalledPluginsLoader.ts` - Dynamically fetches and imports `import(/* webpackIgnore: true */ ...)` marketplace plugins into the environment.
- `src/core/data/DataBus.ts` - Custom typed event bus singleton that routes high-frequency data around the application.
- `src/core/globe/GlobeView.tsx` - The main Cesium viewer container, handling imagery layers, cameras, and primitive collections.
- `src/core/state/store.ts` - The main Zustand store registry linking the nine state slices (globe, layers, timeline, ui, filter, data, config, favorites, geojson).
```mermaid
flowchart TD
subgraph "Data Sources"
A[Public APIs] -->|Poll| B[Data Engine Seeders]
C[Custom Microservices] -->|Stream| B
end
## Data Flow
Real-time data follows a strict unidirectional stream optimized for sub-second updates:
subgraph "Engine Tier"
B -->|WebSocket /stream| D[WsClient]
end
1. **Engine Push:** A remote data engine pushes state over WebSocket (`/stream`) from either local seeders (`ws://localhost:5000/stream`) or the cloud fallback (`wss://dataengine.worldwideview.dev/stream`).
2. **WebSocket Client Router:** `WsClient.handleMessage()` receives the payload and pipes it to the event bus.
3. **DataBus Emission:** The bus fires `DataBus.emit("websocketData", WsStreamPayload)`.
4. **State Hydration:** The `DataBusSubscriber` component listens to the bus and calls `_hydrateSnapshot()` to update the Zustand store's `entitiesByPlugin` cache.
5. **Memoized Selection:** `GlobeView` selects the visible entities from the store.
6. **Primitive Rendering:** The `EntityRenderer` translates store entities into Cesium `PointPrimitiveCollection` and `BillboardCollection` arrays for GPU rendering.
7. **Animation & LOD:** `AnimationLoop` handles horizon culling and hover effects, while `useModelRendering` promotes close-range entities to 3D glTF models.
subgraph "Frontend Pipeline"
D --> E[DataBus<br/>typed pub/sub]
E -->|"_hydrateSnapshot()"| F[Zustand Store<br/>9 slices]
F -->|Memoized visible entities| G[EntityRenderer]
G -->|Primitive collections| H[CesiumJS Globe]
H --> I[AnimationLoop<br/>horizon culling + LOD]
end
subgraph "Plugin Layer"
J[PluginRegistry] -->|"loadPluginFromManifest"| K[Dynamic ES module imports]
J -.->|register| E
end
```
The strict unidirectional flow — engine → bus → store → renderer — is what lets the system push sub-second updates for thousands of entities without React render-cycle bottlenecks.
## Plugin System (Core Abstraction)
Every data source in WorldWideView is a **plugin** implementing the `WorldPlugin` interface from [`@worldwideview/wwv-plugin-sdk`](../packages/wwv-plugin-sdk/). The plugin's lifecycle plugs into a real-time WebSocket firehose:
```text
PluginRegistry.register() → PluginManager.registerPlugin()
→ plugin.initialize(context)
Visibility Toggle → DataBusSubscriber subscribes to layer via WsClient
→ Engine responds with instantaneous WebSocket snapshots over /stream
→ WsClient pipes to DataBus.emit("dataUpdated", WsStreamPayload)
→ Store → EntityRenderer → Globe
```
Four plugin architectures coexist under the "All-Bundle Model":
1. **Data Engine Seeder** — A lightweight `seeder.mjs` script run by the dynamic `wwv-data-engine` runner. (Previously a standalone microservice container; the runner replaces that.)
2. **Dynamic CDN Loaded (Bundle)** — Externally developed plugins, dynamically imported at runtime via ES module CDNs (e.g. version-pinned `unpkg.com` URLs).
3. **Static Compiled (Bundle)** — Static GeoJSON data wrapped into JS bundles via `wwvStaticCompiler` during build/sync. (Previously `StaticDataPlugin`.)
4. **Active Proxied (Bundle)** — Next.js API routes bundled to mediate frontend interactions. (Previously `DeclarativePlugin`.)
All four are now dynamically imported at runtime as ES module bundles via `loadPluginFromManifest`, which uses `import(/* webpackIgnore: true */ entry)`. The legacy `StaticDataPlugin` and `DeclarativePlugin` runtimes are fully deprecated.
> [!IMPORTANT]
> Plugin types are re-exported from the SDK through `src/core/plugins/PluginTypes.ts` and `src/core/plugins/PluginManifest.ts`. The **source of truth is always `@worldwideview/wwv-plugin-sdk`** — never define plugin types locally.
For the contributor checklist when authoring a plugin, see [`.agents/skills/worldwideview-plugin-creation/`](../.agents/skills/) and the [Plugin Quickstart](plugin-quickstart.md).
## State Management
WorldWideView uses a Zustand store split into **nine slices**, each in its own file under [`src/core/state/`](../src/core/state/):
| Slice | Responsibility |
|---|---|
| `globe` | Camera position, imagery layers, scene settings |
| `layers` | Per-plugin visibility toggles |
| `timeline` | Playback range, current time, play/pause |
| `ui` | Panel open/closed states, selected entity |
| `filter` | Plugin filter expressions, applied via `filterEngine` |
| `data` | Entity cache (`entitiesByPlugin`), websocket connection state |
| `config` | Plugin settings, polling intervals, API keys |
| `favorites` | User-bookmarked entities |
| `geojson` | Custom GeoJSON overlays |
Access patterns:
- React components: `const camera = useStore((s) => s.camera);`
- Outside React (animation loop, hooks setup): `const state = useStore.getState();`
- Plugin settings: `configSlice.dataConfig.pluginSettings[pluginId]`
- Polling intervals: `configSlice.dataConfig.pollingIntervals[pluginId]`
The animation loop deliberately snapshots state once per frame via `getState()` rather than subscribing — `requestAnimationFrame` is the loop driver, so adding a Zustand subscription would just duplicate ticks.
## Data Pipeline
Real-time data follows a strict unidirectional path optimised for sub-second updates:
```text
Engine push /stream → DataBusSubscriber WsClient router
→ WsClient.handleMessage() → DataBus.emit("websocketData", WsStreamPayload)
→ DataBusSubscriber → _hydrateSnapshot() → Store.entitiesByPlugin
→ GlobeView (memoised visible entities)
→ EntityRenderer (billboard/point primitives)
→ AnimationLoop (horizon culling, hover/selection)
→ StackManager (co-located entity grouping)
```
The `DataBus` is a custom typed pub/sub singleton (see [`src/core/data/DataBus.ts`](../src/core/data/DataBus.ts)). It exists specifically to bypass React's render cycle for high-frequency events — store updates are batched into the Zustand store, but raw stream events ride the bus directly.
## Data Engine & Seeders
The data engine ([`wwv-data-engine`](https://github.com/silvertakana/wwv-data-engine), public) is a **content-agnostic runner**. It discovers and executes seeder scripts from a configurable directory; the engine itself knows nothing about specific data sources.
- **Local development**: The engine runs via Docker Compose on port 5001, reading seeders dynamically from `local-seeders/` (split into `community` and `private` tiers).
- **Production**: The engine container on Coolify downloads release bundles from `wwv-seeders-community` and `wwv-seeders-private` on startup, unzipping them into `/app/seeders`.
- **Split-routing**: `resolveEngineUrl` prioritises the local dev engine (`ws://localhost:5001/stream`) for local testing — 12-Factor App methodology — and falls back to cloud-hosted endpoints (e.g. `wss://dataenginev2.worldwideview.dev/stream`) when nothing local is available.
### Agnostic Frontend
WorldWideView's frontend is a **completely agnostic renderer**. It has no concept of a "unified" data engine. If 30 plugins each declare a different `streamUrl`, the application opens 30 WebSocket connections; it just so happens that the default plugin set shares `wwv-data-engine`, but the platform is 100% decentralised.
> [!IMPORTANT]
> Each plugin is a self-contained package and **MUST explicitly declare its own `streamUrl` in its manifest or config.** Do not assume the frontend acts as a unified pipe.
### Dual-Output Engine
Each seeder automatically exposes both a WebSocket stream (`/stream`) and a REST API endpoint (`/api/[plugin-id]`). Plugins can consume either depending on their data shape — bursty / live → stream, slow-moving / on-demand → REST.
### Scope Boundary (the 99 / 1 Rule)
The engine handles standard caching and broadcasting — the 99% case. Plugins that require complex on-demand compute (the 1%) must host their own custom backend; the engine intentionally does not grow features for them.
## Rendering Pipeline
The renderer is where most of WorldWideView's engineering depth lives. Three design choices drive the performance envelope:
### Primitive-based rendering
We use [`PointPrimitiveCollection`](https://cesium.com/learn/cesiumjs/ref-doc/PointPrimitiveCollection.html), `BillboardCollection`, `LabelCollection`, and `PolylineCollection` directly — **not** the Cesium Entity API. The Entity API is convenient but allocates per-entity ECS-style state that gets expensive past a few thousand entities. Primitive collections batch their state into typed GPU buffers, so 10k+ live entities still hold 60 fps on a moderate laptop.
Collections are tracked per-viewer via a module-level `WeakMap<CesiumViewer, PrimitiveCollections>` in [`src/core/globe/EntityRenderer.ts`](../src/core/globe/EntityRenderer.ts), keeping the renderer multi-viewer-capable and ensuring collections GC cleanly when a viewer is torn down.
### Chunked processing
Large datasets (10k+ entities) are rendered via [`ChunkedProcessor`](../src/core/globe/ChunkedProcessor.ts) in 500-entity chunks across multiple microtasks, so adding a new plugin layer never blocks the main thread long enough to drop a frame.
### Horizon culling and LOD
The animation loop performs **manual horizon culling** in [`AnimationLoop.ts`](../src/core/globe/AnimationLoop.ts) using a single dot-product against the Earth radius — much cheaper than depth-testing thousands of primitives every frame, and tunable for "entities just below the horizon should still be visible" semantics that depth-testing can't express.
Entities of `type: "model"` are promoted to full 3D glTF models at close range via the LOD system in [`useModelRendering.ts`](../src/core/globe/hooks/useModelRendering.ts) — so an aircraft at 50 nm range is a tinted billboard, but at 5 nm it's a textured plane model with the right wing geometry.
### Stack / Spiderifier
When multiple entities share a screen-space cluster (busy ports, busy airspaces), [`StackManager`](../src/core/globe/StackManager.ts) groups them and [`stackAnimation`](../src/core/globe/stackAnimation.ts) handles the spiderification expansion when a stack is clicked.
### Entity-type rules
> [!WARNING]
> When returning `CesiumEntityOptions` from a plugin's `renderEntity()`:
>
> - **Points**: Use `type: "point"` with `color`, `size`, `outlineColor`, `outlineWidth`.
> - **Billboards**: Use `type: "billboard"` with `iconUrl`, `color`, `iconScale`.
> - **NEVER mix**: Do not set `size` / `outlineWidth` / `outlineColor` on a billboard — Cesium silently clips the GPU upload and the icon disappears.
## Edition System
WorldWideView ships in three editions, controlled by the `NEXT_PUBLIC_WWV_EDITION` environment variable. Feature flags are derived from this in [`src/core/edition.ts`](../src/core/edition.ts).
| Edition | Auth | Use case |
|---|---|---|
| `local` | Enabled (NextAuth credentials) | Self-hosted single-user / small-team deployments |
| `cloud` | Enabled | Managed cloud instance with multi-tenancy |
| `demo` | Disabled (optional admin via `WWV_DEMO_ADMIN_SECRET`) | Public demo deployments |
Edition isn't just an auth toggle — it also gates which marketplace endpoints are queried, which default plugins boot, and whether destructive admin actions are reachable.
## Key Source Files
Quick map of the load-bearing modules:
| Path | Role |
|---|---|
| [`src/core/plugins/PluginManager.ts`](../src/core/plugins/PluginManager.ts) | Core plugin registry. Instantiates plugins, calls `initialize()`, manages lifecycle. |
| [`src/core/plugins/loaders/InstalledPluginsLoader.ts`](../src/core/plugins/loaders/InstalledPluginsLoader.ts) | Dynamic ES module loader for marketplace plugins (`import(/* webpackIgnore: true */ entry)`). |
| [`src/core/data/DataBus.ts`](../src/core/data/DataBus.ts) | Typed pub/sub singleton — the high-frequency event channel. |
| [`src/core/data/WsClient.ts`](../src/core/data/WsClient.ts) | WebSocket router. Pipes engine `/stream` messages onto the DataBus. |
| [`src/core/globe/GlobeView.tsx`](../src/core/globe/GlobeView.tsx) | The Cesium viewer container. Imagery layers, camera setup, primitive collection wiring. |
| [`src/core/globe/EntityRenderer.ts`](../src/core/globe/EntityRenderer.ts) | Translates store entities into Cesium primitives. Hot path for 10k+ entities. |
| [`src/core/globe/AnimationLoop.ts`](../src/core/globe/AnimationLoop.ts) | Per-frame update: horizon culling, hover/selection, model LOD promotion. |
| [`src/core/state/store.ts`](../src/core/state/store.ts) | Zustand store registry linking the nine slices. |
## Further Reading
For deeper coverage of specific subsystems, see the rule files under [`.agents/rules/`](../.agents/rules/):
- [`platform-architecture.md`](../.agents/rules/platform-architecture.md) — high-level platform goals, product vision, Edition System
- [`application-architecture.md`](../.agents/rules/application-architecture.md) — Next.js frontend, Zustand, CesiumJS integration
- [`plugin-architecture.md`](../.agents/rules/plugin-architecture.md) — plugin lifecycle, capability declarations, seeders
- [`marketplace-architecture.md`](../.agents/rules/marketplace-architecture.md) — dynamic plugin installation, DB sync, CDN loading
- [`cesium-rendering.md`](../.agents/rules/cesium-rendering.md) — globe rendering, entity types, primitives, LOD, culling
- [`state-management.md`](../.agents/rules/state-management.md) — slice access patterns, plugin settings
- [`data-engine-architecture.md`](../.agents/rules/data-engine-architecture.md) — engine internals, seeder loading, workspace dependencies
For getting started as a contributor, see [Development](development.md), [Plugin Quickstart](plugin-quickstart.md), and [Plugin Advanced](plugin-advanced.md).
+166
View File
@@ -0,0 +1,166 @@
# Agent Bus — driving WWV from external tools
## Overview
The Agent Bus is an opt-in HTTP+SSE surface that lets a trusted external process — most commonly a [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server fronting an LLM agent — drive the running WWV browser session. The agent can fly the globe, toggle layers, focus entities, and select things by posting JSON actions to a server endpoint, which fans them out over SSE to every browser tab belonging to the same logged-in user.
Read-only camera and engine queries already work via the existing REST API. The Agent Bus is the missing **write path**.
```
LLM client ──MCP──▶ szski/wwv-mcp ──HTTP──▶ /api/agent/publish ──SSE──▶ browser
(Claude, Cursor, …) (separate repo) (this PR adds these) (Cesium flies)
```
## Enabling the bus
The bus is **off by default**. The subscriber early-returns and no SSE connection is opened. You explicitly opt in via a build-time environment variable.
### In Docker
Pass the ARG at build time:
```sh
docker build \
--build-arg NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED=true \
-t worldwideview .
```
### In a Coolify / hosted build
Set `NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED=true` in the build environment. Because it's a `NEXT_PUBLIC_*` variable, it is inlined into the JavaScript bundle at `next build` time — runtime-only env changes will not enable it.
### Verifying it's on
On a fresh page load, open the browser DevTools console. You should see a one-line build banner:
```
[wwv build] id=1714572934123 built_at=2026-05-13T18:35:34Z agent_bus=on
```
If `agent_bus=off` after enabling the env var, the build did not pick up the variable — re-check that it was passed as `--build-arg` (Docker) or set before `next build` ran (other hosts).
You can also hit `/api/build` to confirm the served bundle's build id and flag state.
## Using it — quick smoke test with curl
To verify the bus end-to-end without an MCP server, log into WWV in your browser, grab your `__Secure-authjs.session-token` cookie value from DevTools, and POST an action:
```sh
curl -X POST https://your-wwv-host/api/agent/publish \
-H "Content-Type: application/json" \
-H "Cookie: __Secure-authjs.session-token=PASTE_TOKEN_HERE" \
-d '{"action":"fly_to","lat":35.7796,"lon":-78.6382,"distance":50000}'
```
If the bus is enabled and the cookie is valid, the open tab will fly to Raleigh and the response will be:
```json
{ "ok": true, "delivered": 1, "subscribers": 1 }
```
`subscribers: 0` means the bus is off in the build, the cookie's user has no open tabs, or the env var wasn't applied — see *Verifying* above.
## Using it — wiring an MCP server
The reference MCP server for WWV is published at **[szski/wwv-mcp](https://github.com/szski/wwv-mcp)**. It exposes 15 tools (`globe_fly_to`, `layer_toggle`, `engine_query`, `geocode`, `system_status`, etc.) and works with any MCP-aware client (Claude Code, Claude Desktop, Cursor, Continue, Cline).
> [!NOTE]
> `szski/wwv-mcp` lives in a contributor's namespace today and may move under the project's own organization later. Update the install URL accordingly when that happens.
### Install (Node)
```sh
git clone https://github.com/szski/wwv-mcp
cd wwv-mcp
npm install
npm run build
```
Then store credentials so the MCP server can auto-login at startup:
```sh
mkdir -p ~/.config/wwv-mcp
cat > ~/.config/wwv-mcp/credentials <<'EOF'
[email protected]
WWV_PASSWORD=your-password
EOF
chmod 600 ~/.config/wwv-mcp/credentials
```
### Install (Docker)
If a published image exists at `szski/wwv-mcp` (or wherever the maintainer mirrors it), no install step is needed — the MCP client config below uses `docker run` to launch the server on demand.
### Client config — Claude Code
Edit `~/.claude/settings.json`:
```json
{
"mcpServers": {
"wwv": {
"command": "node",
"args": ["/absolute/path/to/wwv-mcp/dist/index.js"],
"env": {
"WWV_BASE_URL": "https://your-wwv-host.example",
"WWV_ENGINE_URL": "http://localhost:5001"
}
}
}
}
```
Or, with Docker:
```json
{
"mcpServers": {
"wwv": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-e", "WWV_BASE_URL=http://host.docker.internal:3000",
"-e", "WWV_ENGINE_URL=http://host.docker.internal:5001",
"szski/wwv-mcp:latest"
]
}
}
}
```
Then `/mcp` in Claude Code should list `wwv` with all 15 tools.
### Client config — Claude Desktop
Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows). The `mcpServers.wwv` block is identical to Claude Code above.
### Client config — Cursor, Continue, Cline
Each of these reads an MCP server list in its own settings UI but the shape of the entry — `command` + `args` + `env` — is the same as Claude Code's. See your client's MCP docs for the exact location of its config file.
### Verifying the wiring
Once configured, ask the agent something like *"What's the status of the WWV system?"* — it should call `system_status` and report back. If you see `agent_bus_enabled: false`, the bus is off in the WWV build; fix that before trying write tools like `globe_fly_to`.
## Security and multi-tenancy
- **Default off.** Without the env var, the subscriber doesn't open a connection, the publish endpoint exists but has no subscribers, and the bundle's dead-code elimination removes the `EventSource` constructor entirely.
- **Auth gated.** Both `/api/agent/publish` and `/api/agent/stream` use the same `auth()` helper as the rest of the marketplace API. No tokens — just the existing Auth.js session cookie.
- **Per-user scoping.** Subscriptions live in `Map<userId, …>`, so a publish from user A's session never reaches user B's stream, even though both sit on the same Node process. Multi-tenant deployments are safe.
- **Same trust model as a browser tab.** An MCP server "acts as the user" by holding the user's session cookie. If you wouldn't trust a browser tab on the same machine, don't give an MCP server the cookie.
- **Single-process only.** The `AgentBus` is in-memory and process-local. Multi-instance deployments behind a load balancer would need a Redis pub/sub adapter — about 30 lines of additional code, not included here.
## Endpoint reference
| Method | Path | Purpose |
|---|---|---|
| `GET` | `/api/agent/stream` | SSE channel. Auth-gated. Streams `AgentAction` JSON events for the connected user. Heartbeat every 25s. |
| `POST` | `/api/agent/publish` | Accept an `AgentAction` JSON body, broadcast to the publishing user's subscribers, return `{ok, delivered, subscribers}`. |
| `GET` | `/api/build` | Build id + ISO timestamp + `NEXT_PUBLIC_*` flag state. Used by `AgentBusSubscriber` to print the build banner. |
`AgentAction` is currently a six-verb union: `fly_to`, `face_towards`, `layer_toggle`, `highlight_layer`, `select_entity`, `ping`. The shape is `{action: string, …payload}` JSON, so additive changes are backwards-compatible.
## Companion repos
- **[szski/wwv-mcp](https://github.com/szski/wwv-mcp)** — reference MCP server. 15 tools. Required for any LLM-driven use of the bus.
- **[silvertakana/wwv-data-engine](https://github.com/silvertakana/wwv-data-engine)** — separate repo, supplies the read-only `engine_query` data that the MCP server's read tools wrap.
+2 -2
View File
@@ -11,7 +11,7 @@ The core build configuration resides in `package.json` and `next.config.ts`. A c
### Standard Development
- **Install Dependencies:** `pnpm install` (Installs all workspace packages defined in `pnpm-workspace.yaml`).
- **Initial Setup:** `pnpm run setup` (Executes `scripts/setup.mjs` to generate a `.env.local` with a fresh `AUTH_SECRET`).
- **Run Development Server (All):** `pnpm dev:all` (Concurrently starts the Next.js frontend and the local `wwv-data-engine` + Redis containers via Docker Compose).
- **Run Development Server (All):** `pnpm dev:all` (Concurrently starts the Next.js frontend and the local `wwv-data-engine-v2` + Redis containers via Docker Compose).
### Production Build
- **Build Command:** `pnpm build` (Executes `next build --webpack`).
@@ -21,7 +21,7 @@ The core build configuration resides in `package.json` and `next.config.ts`. A c
## Platform Setup
- **Database Migrations:** Prisma schema is located at `prisma/schema.prisma`. During development, `pnpm dev` triggers a `predev` hook running `npx prisma migrate deploy` to ensure PostgreSQL tables are initialized.
- **Data Engine:** The generic data engine runner and Redis cache are started via `docker compose up wwv-data-engine wwv-redis`. Custom data seeders are placed in the `local-seeders/` sandbox and dynamically loaded by the engine.
- **Data Engine:** The generic data engine runner and Redis cache are started via `docker compose up wwv-data-engine-v2 wwv-redis`. Custom data seeders are placed in the `local-seeders/community/` or `local-seeders/private/` sandboxes and dynamically loaded by the engine.
- **Plugin Packages:** Internal plugin packages must be properly listed in `tsconfig.json` paths and `next.config.ts`'s `transpilePackages` array.
## Reference
+2 -2
View File
@@ -11,7 +11,7 @@ WorldWideView utilizes a containerized deployment strategy based on Docker's mul
- **Static Assets:** Cesium static workers are injected at build time via `scripts/copy-cesium.mjs`.
### Data Engine Runner
- The generic `wwv-data-engine` runner is deployed as a single Coolify service, orchestrating telemetry data by executing lightweight scripts from volume-mounted seeder directories.
- The generic `wwv-data-engine-v2` runner is deployed as a single Coolify service, orchestrating telemetry data by executing lightweight scripts from volume-mounted seeder directories. It features a dual-output architecture, exposing both WebSocket streams and REST APIs natively.
## Platform Deployment
@@ -19,7 +19,7 @@ WorldWideView utilizes a containerized deployment strategy based on Docker's mul
WorldWideView deploys optimally to Coolify using a Dockerfile builder.
- **Environment Variables:** Must be explicitly mapped in the Coolify UI (e.g., `DATABASE_URL`, `AUTH_SECRET`).
- **Persistent Storage:** PostgreSQL databases must be hosted externally or mounted via persistent volumes to ensure the frontend registry (installed plugins, user configs) survives container rebuilds.
- **Seeder Deployment:** The generic `wwv-data-engine` runner is deployed as a Coolify service, reading plugin seeders dynamically from a volume-mounted directory. Seeders are pulled from private/community repositories via GitHub releases.
- **Seeder Deployment:** The generic `wwv-data-engine-v2` runner is deployed as a Coolify service, reading plugin seeders dynamically from a volume-mounted directory. Seeders are pulled from private/community repositories via GitHub releases, maintaining strict namespace separation between community and private plugins.
### Docker Structure
- **Dockerfile:** Found at the project root (`Dockerfile`). Uses an Extractor Pattern (`deps` → `builder` → `runner`). The `.git` and `node_modules` folders must be explicitly untracked to prevent cache overlap.
+1 -1
View File
@@ -65,7 +65,7 @@ Whenever generating temporary debugging scripts, testing REST endpoints via `.mj
- *Reference:* The root directory is strictly for production configuration files.
### Local Plugin & Seeder Testing
When developing a custom seeder for a plugin, place the seeder directory inside `local-seeders/`. The local `wwv-data-engine` Docker container automatically mounts this folder and discovers scripts on startup, providing a seamless sandbox.
When developing a custom seeder for a plugin, place the seeder directory inside `local-seeders/community/` or `local-seeders/private/`. The local `wwv-data-engine-v2` Docker container automatically mounts this folder and discovers scripts on startup, providing a seamless sandbox.
### Scaffold a New Component
1. Create a new directory under `src/components/{category}/MyComponent`.
+1 -1
View File
@@ -21,7 +21,7 @@ The system is highly modularized to separate React UI rendering from heavy Cesiu
## Build System
- `package.json` - Root monorepo configuration with `pnpm` workspace bindings.
- `next.config.ts` - Next.js compiler settings, security headers, and standalone output configuration.
- `docker-compose.yml` - Defines the orchestration of the frontend, Redis cache, and the generic data engine runner (`wwv-data-engine`) loaded with local seeders.
- `docker-compose.yml` - Defines the orchestration of the frontend, Redis cache, and the DataEngineV2 runner (`wwv-data-engine-v2`) loaded with local seeders.
## Configuration
- `prisma/schema.prisma` - PostgreSQL database schema for storing user settings and installed plugin manifests.
+48 -35
View File
@@ -53,21 +53,44 @@ Your workspace is now ready!
---
## Step 2: Creating the Data Engine Seeder (Backend)
## Step 2: Scaffold the Plugin and Backend Seeder
The ISS moves incredibly fast. If our frontend tries to ask for its location every second, it will lag. Instead, we use the **Bring Your Own Backend (BYOB)** pattern. We will write a "Seeder" script in the Data Engine that fetches the ISS location and instantly broadcasts it to the frontend via WebSockets.
### 2.1 Create the Seeder Directory and File
We will use the workspace CLI tool to generate a blank plugin template and its associated backend seeder in one go. In your terminal, navigate to your main `worldwideview` folder and run:
Navigate to your `worldwideview` repository. Inside the `local-seeders` folder, create a new folder named `community/iss`. Inside that folder, create a file named `seeder.mjs`:
`c:\dev\worldwideview\local-seeders\community\iss\seeder.mjs`
```bash
node packages/wwv-cli/dist/index.js create
```
The CLI will launch an interactive survey. Answer as follows:
1. **Unique ID**: `iss`
2. **Display Name**: `ISS Live Tracker`
3. **Description**: `Real-time International Space Station tracking.`
4. **Category**: `Space`
5. **Data Architecture**: `Real-Time WebSockets (Generates backend seeder)`
6. **Globe Rendering**: `2D Billboard`
7. **Community Sharing**: `Yes, public community seeder`
This automatically creates:
- Your frontend plugin at `local-plugins/wwv-plugin-iss`
- Your backend seeder at `local-seeders/community/iss`
Now install the dependencies to finalize the setup:
```bash
pnpm install
```
> [!NOTE]
> **Dependency Management:** You do *not* need to create a `package.json` or manually install standard dependencies (like `axios`) for your seeder. The `wwv-data-engine` runner dynamically resolves these via the pnpm workspace, keeping your seeder lightweight.
> **Dependency Management:** You do *not* need to create a `package.json` or manually install standard dependencies (like `axios`) for your backend seeder. The `wwv-data-engine-v2` runner dynamically resolves these via the pnpm workspace, keeping your seeder lightweight.
### 2.2 Write the Polling Logic
---
Open `seeder.mjs` in your text editor and paste the following code. The Data Engine Runner will dynamically discover this script and execute its `fetch(ctx)` function based on the interval you define.
## Step 3: Write the Polling Logic (Backend Seeder)
Open the newly generated seeder file in your text editor: `local-seeders/community/iss/seeder.mjs`.
The Data Engine Runner will dynamically discover this script and execute its `fetch(ctx)` function based on the interval you define. Replace its contents with this code:
```javascript
// seeder.mjs
@@ -116,11 +139,11 @@ export default {
---
## Step 3: Testing the Data Engine
## Step 4: Testing the Data Engine
Before we build the frontend, let's prove that our backend is actually fetching the ISS data.
Before we modify the frontend, let's prove that our backend is actually fetching the ISS data.
### 3.1 Start the Engine
### 4.1 Start the Engine
In your terminal, navigate to the `worldwideview` folder and start the entire stack using Docker Compose:
```bash
@@ -130,24 +153,13 @@ Wait for the Data Engine Docker container to start. You should see `[ISS] Poll O
---
## Step 4: Creating the WorldWideView Plugin (Frontend)
## Step 5: Write the Plugin Logic (Frontend)
Now we will build the visual part of the plugin that connects to our backend stream and draws the ISS on the 3D globe.
Now we will finalize the visual part of the plugin that connects to our backend stream and draws the ISS on the 3D globe.
### 4.1 Scaffold the Plugin
### 5.1 Update the Plugin Code
In your terminal, navigate to your main `worldwideview` folder. We will use the workspace CLI tool to generate a blank plugin template in the local sandboxes folder. Run:
```bash
node packages/wwv-cli/dist/index.js create wwv-plugin-iss --local
pnpm install
```
This creates your plugin at `local-plugins/wwv-plugin-iss` and automatically registers it with the workspace.
### 4.2 Write the Plugin Logic
Open `c:\dev\worldwideview\local-plugins\wwv-plugin-iss\src\index.ts` in your text editor. Replace everything in the file with this code:
Open `local-plugins/wwv-plugin-iss/src/index.ts` in your text editor. The CLI generated a boilerplate for you, but we want to customize the rendering with a 3D model. Replace everything in the file with this code:
```typescript
import type { WorldPlugin, GeoEntity, PluginContext, LayerConfig, CesiumEntityOptions } from "@worldwideview/wwv-plugin-sdk";
@@ -201,18 +213,18 @@ export class IssPlugin implements WorldPlugin {
---
## Step 5: Connecting and Testing Everything
## Step 6: Connecting and Testing Everything
Now we will link your new plugin to your local WorldWideView application to see it in action.
### 5.1 Develop Your Plugin
### 6.1 Develop Your Plugin
Because your plugin is located in `local-plugins/wwv-plugin-iss`, it is automatically detected by the workspace.
You do not need to link it manually.
Since you already started the whole stack (`pnpm dev:all`) in Step 3, the `dev:plugins` watcher is already running in the background. It will automatically build your frontend plugin code whenever you save changes.
Since you already started the whole stack (`pnpm dev:all`) in Step 4, the `dev:plugins` watcher is already running in the background. It will automatically build your frontend plugin code whenever you save changes.
### 5.2 View the ISS
### 6.2 View the ISS
1. Open your web browser and go to `http://localhost:3000`.
2. Click the **Layers** icon on the left sidebar.
@@ -227,11 +239,11 @@ Since you already started the whole stack (`pnpm dev:all`) in Step 3, the `dev:p
---
## Step 6: Publishing Your Plugin
## Step 7: Publishing Your Plugin
You've built it, now share it with the world!
### 6.1 Update package.json
### 7.1 Update package.json
Open `c:\dev\worldwideview\local-plugins\wwv-plugin-iss\package.json`. You must add a `"worldwideview"` metadata block so the marketplace knows how to read your plugin. Ensure your file looks like this:
@@ -251,15 +263,16 @@ Open `c:\dev\worldwideview\local-plugins\wwv-plugin-iss\package.json`. You must
}
```
### 6.2 Publish to NPM
### 7.2 Publish to NPM
In your plugin terminal, log in to NPM and publish your package:
Log in to NPM and publish your package using the WWV CLI from the project root (you can also use the `--org` flag to publish under your own NPM organization):
```bash
npm login
npm publish --access public
node packages/wwv-cli/dist/index.js publish iss [--org <your-org>]
```
*(Or `npx wwv publish iss [--org <your-org>]` if installed globally)*
### 6.3 Submit to the Marketplace
### 7.3 Submit to the Marketplace
1. Go to the official marketplace at `https://marketplace.worldwideview.dev/submit`.
2. Type in your package name (`wwv-plugin-iss`) and click submit.
+16 -9
View File
@@ -20,24 +20,28 @@ WorldWideView operates on a strict **Dynamic CDN Loaded (Bundle)** architecture.
Relying on the frontend `fetch()` method is insufficient for high-frequency real-time tracking (like aviation or maritime). For continuous telemetry, you must build a **Data Engine Seeder** — a lightweight Javascript data polling script.
### Data Engine Seeder Architecture
Instead of the frontend fetching data, you write a lightweight seeder script that connects to an upstream source, normalizes the data, and is executed by the central `wwv-data-engine` runner.
WorldWideView is a completely agnostic renderer. It has absolutely no concept of a "unified" Data Engine. If 30 plugins require 30 different WebSocket servers, the application will blindly open 30 connections. Each plugin is a self-contained package and **MUST explicitly declare its own `streamUrl` in its manifest or config**. Do NOT assume the frontend acts as a unified pipe.
1. **Create a Seeder Directory:** Inside your WorldWideView project, create a folder under `local-seeders/` (e.g., `local-seeders/my-plugin/`).
While you can host your own backend, we provide the `DataEngineV2` runner as a standardized environment for seeders.
### Data Engine V2 Seeder Architecture
Instead of the frontend fetching data, you write a lightweight seeder script that connects to an upstream source, normalizes the data, and is executed by the central `wwv-data-engine-v2` host runner.
1. **Create a Seeder Directory:** Inside your WorldWideView project, create a folder under `local-seeders/` (e.g., `local-seeders/community/my-plugin/`). Note that seeders are split into `community` and `private` tiers to prevent namespace collisions.
2. **Write the Seeder Script:** Create a `seeder.mjs` file that exports a `fetch(ctx)` function.
3. **Engine Auto-Discovery:** The local Docker-based `wwv-data-engine` automatically mounts this directory, discovers your script, and runs it on the defined interval.
4. **WebSocket Delivery:** The central `wwv-data-engine` immediately broadcasts your returned updates over WebSockets to all connected clients.
3. **Engine Auto-Discovery:** The local Docker-based `wwv-data-engine-v2` automatically mounts this directory, discovers your script, and runs it on the defined interval.
4. **WebSocket & REST Delivery:** Seeders in V2 expose both a WebSocket stream (`/stream`) for real-time instantaneous updates, and a REST API endpoint (`/api/:id`) for fetching live data snapshots directly from Redis.
### Dependency Management & Monorepo Hoisting
Seeders within `local-seeders/` are strictly orchestrated within the pnpm workspace. They are executed by the central runner, not as standalone applications.
- **Keep `package.json` clean**: Do not include bulky `dependencies` in your seeder's local `package.json` (unless it's an exceptional, bespoke library).
- **Workspace Resolution**: Standard packages (e.g., `axios`, `ioredis`, `@worldwideview/wwv-plugin-sdk`) are provided by the engine. At runtime, the `wwv-data-engine` leverages native Node.js module resolution to fetch the required dependencies directly from the root workspace or its own containerized runtime.
- **Workspace Resolution**: Standard packages (e.g., `zod`, `ws`, `node-cron`, `undici`) are provided by the engine. At runtime, `wwv-data-engine-v2` leverages native Node.js module resolution to fetch the required dependencies directly from the root workspace or its own containerized runtime. Seeders MUST NOT bundle these dependencies.
- **Lightweight by Design**: This dependency orchestration guarantees that seeders remain extremely lightweight, hot-reloading takes milliseconds, and Docker container size stays optimized.
> [!TIP]
> **Debugging WebSockets:** If your frontend isn't receiving data from your backend seeder:
> 1. Check the `wwv-data-engine` logs to ensure your seeder is publishing to Redis successfully.
> 2. Verify the frontend is connected to the correct WebSocket endpoint. Local instances default to `ws://localhost:5000/stream`, while unrecognized seeders fall back to the cloud at `wss://dataengine.worldwideview.dev/stream`.
> 1. Check the `wwv-data-engine-v2` logs to ensure your seeder is publishing to Redis successfully.
> 2. Verify the frontend is connected to the correct WebSocket endpoint. Local instances default to `ws://localhost:5001/stream`, while unrecognized plugins should explicitly define their own `streamUrl`, or fallback to the cloud at `wss://dataenginev2.worldwideview.dev/stream`.
## Advanced Cesium Rendering
@@ -71,9 +75,12 @@ renderEntity(entity: GeoEntity): CesiumEntityOptions {
To distribute your plugin globally:
1. **Publish to NPM:**
Log in to NPM and publish your package using the WWV CLI from the project root (you can also use the `--org` flag to publish under your own NPM organization):
```bash
npm publish --access public
npm login
node packages/wwv-cli/dist/index.js publish <plugin-name> [--org <your-org>]
```
*(Or `npx wwv publish <plugin-name> [--org <your-org>]` if installed globally)*
2. **Submit:** Navigate to `https://marketplace.worldwideview.dev/submit`.
3. **Register:** Enter your NPM package name. The marketplace automatically scrapes your `package.json` for the required `"worldwideview"` object block (containing your `id`, `icon`, and `category`).
4. **Review:** Once approved, your plugin's ES Module bundle will be served via CDN to all WorldWideView instances worldwide.
+16 -4
View File
@@ -14,14 +14,26 @@ Before you start, ensure you have:
## 2. Scaffold Your Plugin
WorldWideView plugins are built as standard packages within the monorepo workspace. To generate a new plugin sandbox, use the official CLI from the root of your `worldwideview` repository:
WorldWideView plugins are built as standard packages within the monorepo workspace. To generate a new plugin sandbox, use the official interactive CLI from the root of your `worldwideview` repository:
```bash
node packages/wwv-cli/dist/index.js create my-first-plugin --local
pnpm install
node packages/wwv-cli/dist/index.js create --local
```
This creates a lightweight Vite-based project pre-configured with the `@worldwideview/wwv-plugin-sdk` inside the `local-plugins/wwv-plugin-my-first-plugin/` directory.
The CLI will launch an interactive survey to configure your plugin:
1. **Unique ID**: `my-first-plugin`
2. **Display Name**: `My First Data Layer`
3. **Description**: `A simple example plugin.`
4. **Category**: `Custom`
5. **Data Architecture**: `REST Polling / Static Data (Frontend only)`
6. **Globe Rendering**: `Map Point`
This automatically creates a lightweight Vite-based project pre-configured with the `@worldwideview/wwv-plugin-sdk` inside the `local-plugins/wwv-plugin-my-first-plugin/` directory.
Once the scaffolding completes, install the dependencies:
```bash
pnpm install
```
## 3. Develop Your Plugin
+1 -1
View File
@@ -3,7 +3,7 @@
WorldWideView is a real-time geospatial intelligence engine that visualizes live global data on an interactive 3D globe. It leverages a modern frontend stack to render high-density datasets synchronously, including aircraft, maritime vessels, conflict events, satellites, and environmental data.
The core value proposition of WorldWideView is mapping diverse, decoupled intelligence streams onto a central geographic interface using a dynamically loaded plugin architecture. Data sources operate completely decoupled from the display platform, streaming observations via WebSockets for sub-second visual updates. The ecosystem consists of multiple repositories, including the main app (`worldwideview`), the plugin marketplace (`worldwideview-marketplace`), and the WebSocket push server (`wwv-data-engine`).
The core value proposition of WorldWideView is mapping diverse, decoupled intelligence streams onto a central geographic interface using a dynamically loaded plugin architecture. Data sources operate completely decoupled from the display platform, streaming observations via WebSockets for sub-second visual updates. The ecosystem consists of multiple repositories, including the main app (`worldwideview`), the plugin marketplace (`worldwideview-marketplace`), and our default data provider runners like the `DataEngineV2` (`wwv-data-engine-v2`). Note that WorldWideView itself acts as an agnostic client, and any plugin can seamlessly point to its own independent backend WebSocket stream.
## Key Files
- `package.json` (Lines 1-76) - Core dependencies and project metadata for the monorepo workspace.
+41 -1
View File
@@ -38,5 +38,45 @@ Execute the following commands from the root `worldwideview` directory:
```
## Reference
- **Coverage Scope:** The Vitest configuration primarily targets tests located inside `src/lib/**`, `src/core/**`, and `src/plugins/**`.
- **Coverage Scope:** The Vitest configuration targets tests located inside `src/lib/**`, `src/core/**`, `src/plugins/**`, `src/app/**`, and `packages/**`.
- **Environment:** The test environment is configured as `jsdom` via `vite.config.ts` or `vitest.config.ts`, ensuring that DOM-specific API calls function outside of a real browser.
## Patterns
### Plain function — no mocks needed
Pull in the function, call it with representative inputs, assert the output. See `src/lib/marketplace/cors.test.ts` or `src/app/api/camera/adapters/registry.test.ts` for examples.
### Stateful singleton — reset in `afterEach`
Most of the data layer (`dataBus`, `cacheLayer`, `pollingManager`) is exported as a singleton instance. Tests pass when run alone but fail when run together if state leaks. `DataBus.test.ts` shows the canonical cleanup:
```typescript
import { dataBus } from "./DataBus";
afterEach(() => {
dataBus.removeAllListeners();
});
```
### Module-level dependency — mock with `vi.mock`
When the module under test pulls in something heavy (the store, the database, Cesium), mock that module before the import. `vi.mock` calls are hoisted, so they take effect even when written below the import in source order. See `src/lib/marketplace/repository.test.ts` (Prisma client) or `src/core/data/PollingManager.test.ts` (Zustand store).
### Timers — fake them per test
`vi.useFakeTimers()` in `beforeEach`, `vi.useRealTimers()` in `afterEach`. Advance time explicitly with `vi.advanceTimersByTimeAsync(ms)`.
> [!CAUTION]
> `vi.runOnlyPendingTimersAsync()` ticks `setInterval`s scheduled on the same tick as the call. For tests where a function runs once synchronously and then schedules a recurring interval, this double-counts the first call. To drain microtasks without advancing the clock, use `await Promise.resolve()` a few times — see `PollingManager.test.ts` for the `flushMicrotasks()` helper.
## What NOT to Test (Yet)
- **Cesium-heavy components.** Anything that mounts a `<Viewer>` or renders entities to the globe needs WebGL, which jsdom doesn't provide. These belong in Playwright-style E2E tests rather than unit tests.
- **Live database round-trips.** Mock the Prisma client at the module boundary — `repository.test.ts` is the reference pattern. Spinning up a real Postgres in CI is expensive and unreliable.
- **Dynamic-import plugin bundles.** The loader uses `import(/* webpackIgnore: true */ entry)` at runtime against a real URL. Test the loader's pre-import logic with a fake module object, not a real dynamic import.
## Philosophy
A small focused suite is more valuable than a large one that's expensive to maintain. Each test should answer: *what specific regression does this catch that I'd otherwise discover from a user bug report?*
Two practical rules:
1. **Prefer testing pure logic over orchestration.** If a function takes inputs and returns outputs, test it directly. If it coordinates a half-dozen other things (the globe, the store, Cesium primitives), either refactor the pure parts out or use an integration test.
2. **Add a test when you fix a bug.** A one-line test that fails today and passes after the fix is enough to prevent the bug from coming back. Land the test in the same PR as the fix.
+52
View File
@@ -0,0 +1,52 @@
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
import nextTypeScript from "eslint-config-next/typescript";
export default [
{
ignores: [
"node_modules/**",
".next/**",
"out/**",
"src/generated/**",
"public/cesium/**",
"packages/*/dist/**",
".worktrees/**",
"local-scripts/**",
"local-plugins/**",
"local-seeders/**",
".agents/**",
".claude/**",
],
},
...nextCoreWebVitals,
...nextTypeScript,
{
rules: {
// ─── Demoted on first introduction ─────────────────────────────
// The existing codebase has hundreds of violations across these
// rules. To make the lint job runnable in CI without blocking on
// pre-existing debt, every rule that currently fires errors is
// demoted to `warn`. Promote back to `error` once the backlog
// is addressed (recommended in this order: prefer-const,
// no-unescaped-entities, ban-ts-comment, then the react-hooks
// family once the team agrees on the React 19 hook-purity rules).
// Pre-existing — flagged in the original code review (#96):
"@typescript-eslint/no-explicit-any": "warn",
"no-console": "warn",
// React 19 hook-purity rules from eslint-plugin-react-hooks 7+:
"react-hooks/purity": "warn",
"react-hooks/refs": "warn",
"react-hooks/set-state-in-effect": "warn",
"react-hooks/immutability": "warn",
"react-hooks/static-components": "warn",
// Misc one-offs across the codebase:
"react/no-unescaped-entities": "warn",
"@typescript-eslint/ban-ts-comment": "warn",
"@next/next/no-assign-module-variable": "warn",
"prefer-const": "warn",
},
},
];
+4 -6
View File
@@ -6,7 +6,7 @@ This directory is a **pnpm workspace** for developing plugins locally without co
```bash
# Scaffold a new plugin
pnpm wwv create my-plugin --local
node packages/wwv-cli/dist/index.js create
# Start dev server (auto-discovers local plugins)
pnpm dev
@@ -20,12 +20,10 @@ pnpm dev
4. The marketplace load API auto-discovers them in dev mode
5. Everything in this directory is gitignored
## Promoting to a Package
## Publishing to NPM
When your plugin is ready to share:
When your plugin is ready to share, you can publish it directly to NPM from the root directory:
```bash
pnpm wwv link my-plugin
node packages/wwv-cli/dist/index.js publish <plugin-name> [--org <your-org>]
```
This moves it to `packages/` and adds it to version control.
View File
Whitespace-only changes.
+26 -10
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.7.8",
"version": "2.9.3",
"private": true,
"type": "module",
"packageManager": "[email protected]",
@@ -10,14 +10,16 @@
"clean": "node -e \"const fs=require('fs');fs.rmSync('.next',{recursive:true,force:true})\"",
"dev": "concurrently \"pnpm run dev:plugins\" \"next dev\"",
"dev:all": "concurrently -n \"dev,backends\" -c \"magenta,blue\" \"pnpm dev\" \"pnpm dev:backends\"",
"dev:backends": "docker compose up wwv-data-engine wwv-redis",
"dev:backends": "docker compose --profile engine up wwv-data-engine wwv-redis",
"dev:plugins": "node scripts/watch-local-plugins.mjs",
"predev": "node scripts/boot-db.mjs && npx dotenv-cli -e .env.local -c -- npx prisma db push --accept-data-loss && npx prisma generate && node scripts/copy-cesium.mjs && node scripts/sync-local-plugins.mjs",
"predev": "node scripts/boot-db.mjs && npx dotenv-cli -c -- node scripts/safe-db-push.mjs && npx prisma generate && node scripts/copy-cesium.mjs && node scripts/sync-local-plugins.mjs",
"copy-cesium": "node scripts/copy-cesium.mjs",
"prebuild": "node scripts/check-build-env.mjs",
"build": "next build --webpack",
"start": "next start",
"test": "vitest run",
"test:mutate": "stryker run",
"lint": "eslint .",
"db:reset": "npx prisma migrate reset --force",
"generate": "prisma generate"
},
@@ -38,7 +40,7 @@
"hls.js": "^1.6.16",
"insecam-api": "^0.0.3",
"jose": "^6.2.3",
"lucide-react": "^0.576.0",
"lucide-react": "^1.14.0",
"next": "16.2.6",
"next-auth": "^5.0.0-beta.30",
"pg": "^8.20.0",
@@ -54,28 +56,37 @@
"zustand": "^5.0.13"
},
"devDependencies": {
"@stryker-mutator/core": "^9.6.1",
"@stryker-mutator/vitest-runner": "^9.6.1",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.2",
"@types/bcryptjs": "^3.0.0",
"@types/cesium": "^1.70.4",
"@types/node": "^20",
"@types/node": "^25",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/ws": "^8.18.1",
"@vitejs/plugin-react": "^5.1.4",
"@vitest/coverage-v8": "4.1.5",
"@vitest/coverage-v8": "4.1.6",
"concurrently": "^9.2.1",
"copy-webpack-plugin": "^14.0.0",
"eslint": "^9",
"eslint-config-next": "^16.2.6",
"fast-check": "^4.8.0",
"jsdom": "^28.1.0",
"rollup-plugin-external-globals": "^0.13.0",
"tsx": "^4.21.0",
"typescript": "^5",
"vite": "^8.0.11",
"vitest": "^4.1.5"
"vite": "^8.0.12",
"vitest": "^4.1.6"
},
"pnpm": {
"overrides": {
"@spz-loader/core": "0.3.0"
"@spz-loader/core": "0.3.0",
"form-data@<2.5.4": "^2.5.5",
"form-data@>=3.0.0 <3.0.4": "^3.0.4",
"form-data@>=4.0.0 <4.0.4": "^4.0.5",
"fast-uri@<3.1.2": "^3.1.2"
},
"onlyBuiltDependencies": [
"@prisma/engines",
@@ -83,7 +94,12 @@
"prisma",
"protobufjs",
"sharp",
"esbuild"
"esbuild",
"better-sqlite3"
]
},
"engines": {
"node": ">=20.0.0",
"pnpm": ">=9.0.0"
}
}
+47
View File
@@ -0,0 +1,47 @@
# @worldwideview/wwv-cli
The official Command Line Interface for scaffolding and publishing WorldWideView plugins.
## Usage
This CLI is designed to be run from within the `worldwideview` monorepo.
### 1. Scaffold a new plugin
```bash
node packages/wwv-cli/dist/index.js create
```
This command generates a new plugin directory with a boilerplate `index.ts` and `package.json` configured for the WorldWideView plugin architecture inside the `local-plugins/` directory.
*(Note: To create a built-in plugin inside `packages/` instead, use the `--core` flag).*
### 2. Publish a plugin
Once your plugin is ready for release, you can publish it to NPM. You can do this from within the plugin directory or directly from the project root.
**From the plugin directory:**
```bash
cd local-plugins/<plugin-name>
npm login
node ../../packages/wwv-cli/dist/index.js publish
```
**From the project root:**
You can also run the CLI from the root by providing the plugin name:
```bash
node packages/wwv-cli/dist/index.js publish <plugin-name>
```
**Custom NPM Organizations:**
By default, plugins are scaffolded under the `@worldwideview` NPM scope. To publish to your own organization, use the `--org` flag:
```bash
node packages/wwv-cli/dist/index.js publish <plugin-name> --org my-username
```
This will permanently update your `package.json` to use `@my-username` and publish the package.
The publish command verifies that your `package.json` contains the required `"worldwideview"` manifest block and invokes `npm publish --access public`.
## Development
To re-compile the CLI during development:
```bash
pnpm --filter @worldwideview/wwv-cli run build
```
+17 -8
View File
@@ -1,15 +1,24 @@
{
"name": "@worldwideview/wwv-cli",
"version": "1.0.0",
"type": "commonjs",
"version": "1.2.0",
"type": "module",
"description": "WorldWideView CLI",
"main": "dist/index.js",
"bin": {
"wwv": "./dist/index.js"
"wwv": "dist/index.js"
},
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"clean": "rm -rf dist"
},
"dependencies": {
"commander": "^11.1.0",
"chalk": "^4.1.2",
"vite": "^5.0.0",
"archiver": "^7.0.1",
"ws": "^8.16.0"
"commander": "^12.1.0",
"prompts": "^2.4.2"
},
"devDependencies": {
"@types/node": "^20.0.0",
"@types/prompts": "^2.4.9",
"typescript": "^5.0.0"
}
}
+22
View File
@@ -0,0 +1,22 @@
import { Command } from 'commander';
import { saveConfig } from '../utils/config.js';
export const configCommand = new Command('config')
.description('Manage WWV CLI configuration')
.argument('<action>', 'Action to perform (e.g., set)')
.argument('<key>', 'Config key (e.g., org)')
.argument('<value>', 'Config value (e.g., your-username)')
.action((action, key, value) => {
if (action !== 'set') {
console.error(`[wwv-cli] Unknown config action: ${action}`);
process.exit(1);
}
if (key === 'org') {
saveConfig({ org: value });
console.log(`[wwv-cli] Successfully set default organization to @${value}`);
} else {
console.error(`[wwv-cli] Unknown config key: ${key}. Valid keys: org`);
process.exit(1);
}
});
+234
View File
@@ -0,0 +1,234 @@
import { Command } from 'commander';
import fs from 'fs';
import path from 'path';
import prompts from 'prompts';
export const createCommand = new Command('create')
.description('Interactively scaffold a new WorldWideView plugin')
.option('-c, --core', 'Create inside packages instead of local-plugins (for core contributors)')
.action(async (options) => {
const response = await prompts([
{
type: 'text',
name: 'pluginId',
message: 'What is the unique ID for your plugin? (e.g. my-tracker)',
validate: value => value.length > 0 ? true : 'Plugin ID is required'
},
{
type: 'text',
name: 'displayName',
message: 'What is the display name? (e.g. My Live Tracker)',
initial: (prev: string) => prev.replace(/-/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase())
},
{
type: 'text',
name: 'description',
message: 'Enter a short description:'
},
{
type: 'select',
name: 'category',
message: 'Which category does this plugin belong to?',
choices: [
{ title: 'Aviation (Plane icon)', value: 'aviation' },
{ title: 'Maritime (Ship icon)', value: 'maritime' },
{ title: 'Space (Satellite icon)', value: 'space' },
{ title: 'Weather (Cloud icon)', value: 'weather' },
{ title: 'Custom (Box icon)', value: 'custom' }
]
},
{
type: 'select',
name: 'architecture',
message: 'How will your plugin receive data?',
choices: [
{ title: 'REST Polling / Static Data (Frontend only)', value: 'polling' },
{ title: 'Real-Time WebSockets (Generates backend seeder)', value: 'websocket' }
]
},
{
type: (prev: string) => prev === 'websocket' ? 'select' : null,
name: 'seederTier',
message: 'Which tier should your backend seeder belong to?',
choices: [
{ title: 'Community (Open data, shared)', value: 'community' },
{ title: 'Private (Requires API keys, restricted)', value: 'private' }
]
},
{
type: 'select',
name: 'renderStyle',
message: 'How should entities be rendered on the 3D globe?',
choices: [
{ title: '2D Billboard (Great for static icons)', value: 'billboard' },
{ title: '3D Model with LOD (Transitions 2D to 3D)', value: 'model' },
{ title: 'Simple Point (High performance dots)', value: 'point' }
]
}
]);
if (!response.pluginId) {
console.log('Plugin creation cancelled.');
return;
}
const { pluginId, displayName, description, category, architecture, seederTier, renderStyle } = response;
const targetBaseDir = options.core ? 'packages' : 'local-plugins';
const pluginDir = path.join(process.cwd(), targetBaseDir, `wwv-plugin-${pluginId}`);
if (fs.existsSync(pluginDir)) {
console.error(`Error: Directory ${pluginDir} already exists.`);
process.exit(1);
}
fs.mkdirSync(pluginDir, { recursive: true });
// Determine category icon
const iconMap: Record<string, string> = {
aviation: 'Plane',
maritime: 'Ship',
space: 'Satellite',
weather: 'Cloud',
custom: 'Box'
};
const defaultIcon = iconMap[category] || 'Box';
// Package.json boilerplate
const streamUrlField = architecture === 'websocket'
? `\n "streamUrl": "wss://dataenginev2.worldwideview.dev/stream",`
: '';
const packageJsonContent = `{
"name": "@worldwideview/wwv-plugin-${pluginId}",
"version": "1.0.0",
"description": "${description}",
"main": "dist/frontend.mjs",
"module": "dist/frontend.mjs",
"exports": {
".": {
"import": "./dist/frontend.mjs",
"require": "./dist/frontend.mjs"
}
},
"scripts": {
"build": "tsc"
},
"dependencies": {
"@worldwideview/wwv-plugin-sdk": "latest"
},
"worldwideview": {
"pluginId": "${pluginId}",
"name": "${displayName}",
"description": "${description}",
"icon": "${defaultIcon}",
"category": "${category}",${streamUrlField}
"author": "Your Name",
"dev_entry": "src/index.ts",
"format": "bundle"
}
}
`;
// index.ts boilerplate
const renderBoilerplate = {
billboard: `return {
type: 'billboard',
iconUrl: '/icons/default.png',
iconScale: 1.0,
color: '#ffffff'
};`,
model: `return {
type: 'billboard', // Placeholder for LOD logic, update to 3D model path when zoomed
iconUrl: '/icons/default.png',
iconScale: 1.0,
modelUrl: '/models/default.glb', // Advanced LOD
color: '#ffffff'
};`,
point: `return {
type: 'point',
color: '#ff0000',
size: 8,
outlineColor: '#ffffff',
outlineWidth: 2
};`
}[renderStyle as string] || `return {};`;
const fetchBoilerplate = architecture === 'polling'
? `\n async fetch(): Promise<GeoEntity[]> {
// Implement REST polling logic here
return [];
}\n`
: '';
const indexTsContent = `import { WorldPlugin, GeoEntity, CesiumEntityOptions } from '@worldwideview/wwv-plugin-sdk';
export default class ${pluginId.replace(/-/g, '')}Plugin implements WorldPlugin {
id = '${pluginId}';
name = '${displayName}';
async initialize(context: any): Promise<void> {
console.log('${displayName} initialized.');
}
getPollingInterval(): number {
return ${architecture === 'polling' ? '10000' : '0'}; // ${architecture === 'polling' ? '10 seconds' : '0 for WebSockets'}
}
${fetchBoilerplate}
renderEntity(entity: GeoEntity): CesiumEntityOptions {
${renderBoilerplate}
}
renderHUD(entity: GeoEntity): string {
return \`<div>
<h3>\${entity.id}</h3>
<p>Data provided by ${displayName}</p>
</div>\`;
}
}
`;
fs.writeFileSync(path.join(pluginDir, 'package.json'), packageJsonContent);
fs.mkdirSync(path.join(pluginDir, 'src'), { recursive: true });
fs.writeFileSync(path.join(pluginDir, 'src', 'index.ts'), indexTsContent);
console.log(`\n✅ Successfully created plugin frontend at ${pluginDir}`);
// Generate seeder backend if requested
if (architecture === 'websocket' && seederTier) {
const seederDir = path.join(process.cwd(), 'local-seeders', seederTier, pluginId);
if (!fs.existsSync(seederDir)) {
fs.mkdirSync(seederDir, { recursive: true });
const seederContent = `// WWV Data Engine Seeder for ${pluginId}
export default async function run(context) {
console.log('Starting ${displayName} seeder...');
// Example: Emit a mock entity to the engine
setInterval(() => {
context.emit({
id: '${pluginId}-mock-1',
lat: 0,
lng: 0,
alt: 10000,
heading: 0,
velocity: 250,
properties: {
status: 'active'
}
});
}, 1000);
}
`;
fs.writeFileSync(path.join(seederDir, 'seeder.mjs'), seederContent);
console.log(`✅ Successfully created plugin seeder at ${seederDir}`);
}
}
console.log(`\nNext steps:
1. Run \`pnpm install\` from the project root.
2. Edit \`index.ts\` in your plugin directory.
${architecture === 'websocket' ? '3. Edit `seeder.mjs` in your local-seeders directory.' : ''}
`);
});
+120
View File
@@ -0,0 +1,120 @@
import { Command } from 'commander';
import { execSync } from 'child_process';
import path from 'path';
import fs from 'fs';
import prompts from 'prompts';
import { getConfig, saveConfig } from '../utils/config.js';
export const publishCommand = new Command('publish')
.description('Publish the plugin to NPM and notify the WWV Marketplace')
.argument('[pluginName]', 'Name of the plugin to publish (if running from root)')
.option('--org <orgName>', 'NPM organization to publish to (e.g., your-username)')
.action(async (pluginName, options) => {
console.log('[wwv-cli] Preparing to publish plugin...');
let cwd = process.cwd();
// If pluginName is provided, try to find the plugin directory
if (pluginName) {
const rootLocalPath = path.join(cwd, 'local-plugins', pluginName);
const rootWwvLocalPath = path.join(cwd, 'local-plugins', `wwv-plugin-${pluginName}`);
const packagesPath = path.join(cwd, 'packages', pluginName);
const packagesWwvPath = path.join(cwd, 'packages', `wwv-plugin-${pluginName}`);
if (fs.existsSync(rootWwvLocalPath)) {
cwd = rootWwvLocalPath;
} else if (fs.existsSync(rootLocalPath)) {
cwd = rootLocalPath;
} else if (fs.existsSync(packagesWwvPath)) {
cwd = packagesWwvPath;
} else if (fs.existsSync(packagesPath)) {
cwd = packagesPath;
} else {
console.error(`[wwv-cli] Error: Could not find plugin '${pluginName}' in local-plugins or packages.`);
process.exit(1);
}
console.log(`[wwv-cli] Found plugin at: ${cwd}`);
}
const pkgPath = path.join(cwd, 'package.json');
if (!fs.existsSync(pkgPath)) {
console.error('[wwv-cli] Error: No package.json found in directory: ' + cwd);
process.exit(1);
}
try {
const pkgContent = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
if (!pkgContent.worldwideview) {
console.error('[wwv-cli] Error: package.json is missing the "worldwideview" manifest block. Is this a WWV plugin?');
process.exit(1);
}
let originalName = pkgContent.name;
let publishedName = originalName;
// Determine organization
let targetOrg = options.org;
const config = getConfig();
if (!targetOrg) {
if (config.org) {
targetOrg = config.org;
console.log(`[wwv-cli] Using default organization from config: @${targetOrg}`);
} else {
// Fallback to NPM whoami if possible
try {
const whoami = execSync('npm whoami', { stdio: 'pipe' }).toString().trim();
targetOrg = whoami;
} catch (e) {
// Not logged in or errored, ignore
}
const response = await prompts({
type: 'text',
name: 'org',
message: 'What NPM organization/username do you want to publish under?',
initial: targetOrg || '',
validate: value => value.length > 0 ? true : 'Organization is required'
});
if (!response.org) {
console.log('Publish cancelled.');
return;
}
targetOrg = response.org;
saveConfig({ org: targetOrg });
console.log(`[wwv-cli] Saved @${targetOrg} as your default organization.`);
}
} else {
// Save the explicitly passed org as the new default
saveConfig({ org: targetOrg });
}
if (targetOrg) {
const orgPrefix = targetOrg.startsWith('@') ? targetOrg : `@${targetOrg}`;
const baseName = originalName.startsWith('@') ? originalName.split('/')[1] : originalName;
publishedName = `${orgPrefix}/${baseName}`;
if (originalName !== publishedName) {
pkgContent.name = publishedName;
fs.writeFileSync(pkgPath, JSON.stringify(pkgContent, null, 2) + '\n');
console.log(`[wwv-cli] Updated package name to ${publishedName}`);
}
}
console.log(`[wwv-cli] Publishing ${publishedName}@${pkgContent.version} to NPM...`);
// Execute npm publish
execSync('npm publish --access public', { stdio: 'inherit', cwd });
console.log('[wwv-cli] Successfully published to NPM!');
console.log('[wwv-cli] To submit this plugin to the WorldWideView Marketplace, please visit: https://marketplace.worldwideview.dev/submit');
console.log(`[wwv-cli] Package Name: ${publishedName}`);
} catch (err: any) {
console.error('[wwv-cli] Error during publish:', err.message);
process.exit(1);
}
});
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env node
import { Command } from 'commander';
import { createCommand } from './commands/create.js';
import { publishCommand } from './commands/publish.js';
import { configCommand } from './commands/config.js';
const program = new Command();
program
.name('wwv')
.description('WorldWideView Plugin CLI')
.version('1.1.2');
program.addCommand(createCommand);
program.addCommand(publishCommand);
program.addCommand(configCommand);
program.parse(process.argv);
+27
View File
@@ -0,0 +1,27 @@
import fs from 'fs';
import path from 'path';
import os from 'os';
const CONFIG_PATH = path.join(os.homedir(), '.wwvrc');
export interface WwvConfig {
org?: string;
}
export function getConfig(): WwvConfig {
if (!fs.existsSync(CONFIG_PATH)) {
return {};
}
try {
const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
return JSON.parse(raw);
} catch (e) {
return {};
}
}
export function saveConfig(config: WwvConfig): void {
const current = getConfig();
const next = { ...current, ...config };
fs.writeFileSync(CONFIG_PATH, JSON.stringify(next, null, 2), 'utf8');
}
+16
View File
@@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": false
},
"include": ["src/**/*"]
}
+8
View File
@@ -104,7 +104,15 @@ export interface ServerPluginConfig {
streamUrl?: string;
}
export interface PluginContext {
/**
* @deprecated Use `getEngineUrl()` instead. This property is statically resolved at registration time.
*/
apiBaseUrl: string;
/**
* Dynamically resolves the HTTP base URL for the data engine.
* Evaluates local overrides, manifests, and fallbacks at the moment it is called.
*/
getEngineUrl: () => string;
/**
* Key-value map of generic environment variables.
* The engine surfaces any variable starting with NEXT_PUBLIC_WWV_PLUGIN_
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,2BAA2B;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC5B,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EACxB,IAAI,GAAE,cAAmB,GAC1B,MAAM,CA4BR;AAGD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGzJ,MAAM,MAAM,cAAc,GACpB,UAAU,GACV,UAAU,GACV,UAAU,GACV,UAAU,GACV,kBAAkB,GAClB,gBAAgB,GAChB,OAAO,GACP,OAAO,GACP,UAAU,GACV,cAAc,GACd,QAAQ,CAAC;AAGf,MAAM,WAAW,SAAS;IACtB,KAAK,EAAE,IAAI,CAAC;IACZ,GAAG,EAAE,IAAI,CAAC;CACb;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AAG5D,MAAM,WAAW,SAAS;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,IAAI,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAGD,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yJAAyJ;IACzJ,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAGD,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IACzE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wBAAwB,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IACzD,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,8FAA8F;IAC9F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mHAAmH;IACnH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,CAAC,EAAE;QACX,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;QACjC,WAAW,CAAC,EAAE,OAAO,CAAC;KACzB,CAAC;IACF,2FAA2F;IAC3F,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,sEAAsE;IACtE,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAGD,MAAM,WAAW,iBAAiB;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,2FAA2F;IAC3F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAKD,MAAM,WAAW,aAAa;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,4CAA4C;IAC5C,OAAO,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;IACpC,SAAS,EAAE,SAAS,CAAC;IACrB,YAAY,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC9C,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAChC,6DAA6D;IAC7D,iBAAiB,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC;IACpE,2DAA2D;IAC3D,cAAc,EAAE,MAAM,OAAO,CAAC;IAC9B,oEAAoE;IACpE,cAAc,EAAE,MAAM,IAAI,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAAG,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;CAAE;AACrE,MAAM,WAAW,iBAAiB;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;CAAE;AAC9E,MAAM,WAAW,gBAAgB;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC7B;AAED,MAAM,MAAM,WAAW,GACjB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAG1C,MAAM,WAAW,WAAW;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,GAAG,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChE,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,mBAAmB,CAAC;IAGrD,oBAAoB,CAAC,CAAC,MAAM,EAAE,SAAS,GAAG,iBAAiB,GAAG,IAAI,CAAC;IACnE,eAAe,CAAC,IAAI,kBAAkB,CAAC;IACvC,oBAAoB,CAAC,IAAI,gBAAgB,EAAE,CAAC;IAC5C,SAAS,CAAC,IAAI;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAALine truncated
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,2BAA2B;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC5B,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EACxB,IAAI,GAAE,cAAmB,GAC1B,MAAM,CA4BR;AAGD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGzJ,MAAM,MAAM,cAAc,GACpB,UAAU,GACV,UAAU,GACV,UAAU,GACV,UAAU,GACV,kBAAkB,GAClB,gBAAgB,GAChB,OAAO,GACP,OAAO,GACP,UAAU,GACV,cAAc,GACd,QAAQ,CAAC;AAGf,MAAM,WAAW,SAAS;IACtB,KAAK,EAAE,IAAI,CAAC;IACZ,GAAG,EAAE,IAAI,CAAC;CACb;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AAG5D,MAAM,WAAW,SAAS;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,IAAI,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAGD,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yJAAyJ;IACzJ,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAGD,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IACzE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wBAAwB,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IACzD,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,8FAA8F;IAC9F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mHAAmH;IACnH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,CAAC,EAAE;QACX,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;QACjC,WAAW,CAAC,EAAE,OAAO,CAAC;KACzB,CAAC;IACF,2FAA2F;IAC3F,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,sEAAsE;IACtE,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAGD,MAAM,WAAW,iBAAiB;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,2FAA2F;IAC3F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAKD,MAAM,WAAW,aAAa;IAC1B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,YAAY,EAAE,MAAM,MAAM,CAAC;IAC3B;;;;;;OAMG;IACH,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,4CAA4C;IAC5C,OAAO,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;IACpC,SAAS,EAAE,SAAS,CAAC;IACrB,YAAY,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC9C,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAChC,6DAA6D;IAC7D,iBAAiB,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC;IACpE,2DAA2D;IAC3D,cAAc,EAAE,MAAM,OAAO,CAAC;IAC9B,oEAAoE;IACpE,cAAc,EAAE,MAAM,IAAI,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAAG,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;CAAE;AACrE,MAAM,WAAW,iBAAiB;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;CAAE;AAC9E,MAAM,WAAW,gBAAgB;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC7B;AAED,MAAM,MAAM,WAAW,GACjB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAG1C,MAAM,WAAW,WAAW;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,GAAG,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChE,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,mBAAmB,CAAC;IAGrD,oBAAoB,CAAC,CAAC,MAAM,EAAE,SAAS,GAAG,iBAAiB,GAAG,IAAI,CAAC;IACnE,eAAe,CAAC,IAAI,kBAAkB,CAAC;IACvC,oBAAoB,CAAC,IAAI,gBAAgB,EAAE,CAAC;IAC5C,SAAS,CAAC,IAAI;QAAE,KAAK,EAAELine truncated
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-plugin-sdk",
"version": "1.5.0",
"version": "1.6.0",
"description": "Plugin SDK — types, interfaces, and utilities for building WorldWideView globe plugins",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@@ -0,0 +1,92 @@
import { describe, it, expectTypeOf } from "vitest";
import type {
TokenExchangeRequest,
TokenExchangeResponse,
WebSocketAuthMessage,
SensitiveString,
Tier,
PKCEConnectRequest,
PKCETokenExchange,
PKCETokenExchangeResponse,
PluginJwtClaims,
AuthErrorResponse,
JWK,
JWKSResponse,
WebSocketMessage
} from "./auth-contracts";
describe("Auth Contracts", () => {
it("TokenExchangeRequest has exact required properties", () => {
expectTypeOf<TokenExchangeRequest>().toHaveProperty("apiKey").toEqualTypeOf<SensitiveString>();
expectTypeOf<TokenExchangeRequest>().toHaveProperty("audience").toEqualTypeOf<string>();
// @ts-expect-error - missing required apiKey
const badReq: TokenExchangeRequest = { audience: "engine-123" };
});
it("TokenExchangeResponse has exact required properties", () => {
expectTypeOf<TokenExchangeResponse>().toHaveProperty("token").toEqualTypeOf<SensitiveString>();
expectTypeOf<TokenExchangeResponse>().toHaveProperty("expiresAt").toEqualTypeOf<number>();
expectTypeOf<TokenExchangeResponse>().toHaveProperty("kid").toEqualTypeOf<string>();
expectTypeOf<TokenExchangeResponse>().toHaveProperty("tier").toEqualTypeOf<Tier | undefined>();
// @ts-expect-error - missing required token
const badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
});
it("WebSocketAuthMessage has exact required properties including protocol version", () => {
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("type").toEqualTypeOf<"auth">();
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("v").toEqualTypeOf<1>();
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("token").toEqualTypeOf<SensitiveString>();
// @ts-expect-error - missing version
const badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
// @ts-expect-error - wrong version
const badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
});
it("WebSocketMessage is a discriminated union correctly containing WebSocketAuthMessage", () => {
expectTypeOf<WebSocketMessage>().extract<{ type: "auth" }>().toEqualTypeOf<WebSocketAuthMessage>();
});
it("PKCEConnectRequest has correct snake_case shape", () => {
expectTypeOf<PKCEConnectRequest>().toHaveProperty("state").toEqualTypeOf<string>();
expectTypeOf<PKCEConnectRequest>().toHaveProperty("code_challenge").toEqualTypeOf<string>();
expectTypeOf<PKCEConnectRequest>().toHaveProperty("code_challenge_method").toEqualTypeOf<"S256">();
});
it("PKCETokenExchange implements RFC 7636 fields", () => {
expectTypeOf<PKCETokenExchange>().toHaveProperty("grant_type").toEqualTypeOf<"authorization_code">();
expectTypeOf<PKCETokenExchange>().toHaveProperty("redirect_uri").toEqualTypeOf<string>();
expectTypeOf<PKCETokenExchange>().toHaveProperty("client_id").toEqualTypeOf<string>();
expectTypeOf<PKCETokenExchange>().toHaveProperty("code").toEqualTypeOf<string>();
expectTypeOf<PKCETokenExchange>().toHaveProperty("code_verifier").toEqualTypeOf<string>();
});
it("PKCETokenExchangeResponse has exact required properties", () => {
expectTypeOf<PKCETokenExchangeResponse>().toHaveProperty("apiKey").toEqualTypeOf<SensitiveString>();
expectTypeOf<PKCETokenExchangeResponse>().toHaveProperty("tier").toEqualTypeOf<Tier | undefined>();
expectTypeOf<PKCETokenExchangeResponse>().toHaveProperty("issuedAt").toEqualTypeOf<number | undefined>();
});
it("PluginJwtClaims structure matches requirements", () => {
expectTypeOf<PluginJwtClaims>().toHaveProperty("iss").toEqualTypeOf<string>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("aud").toEqualTypeOf<string>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("exp").toEqualTypeOf<number>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("jti").toEqualTypeOf<string>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("tier").toEqualTypeOf<Tier>();
expectTypeOf<PluginJwtClaims>().toHaveProperty("plugins").toEqualTypeOf<string[] | undefined>();
});
it("JWKSResponse conforms to RFC 7517", () => {
expectTypeOf<JWKSResponse>().toHaveProperty("keys").toEqualTypeOf<JWK[]>();
expectTypeOf<JWK>().toHaveProperty("kty").toEqualTypeOf<string>();
expectTypeOf<JWK>().toHaveProperty("kid").toEqualTypeOf<string>();
});
it("AuthErrorResponse has basic OAuth error fields", () => {
expectTypeOf<AuthErrorResponse>().toHaveProperty("error").toEqualTypeOf<string>();
expectTypeOf<AuthErrorResponse>().toHaveProperty("error_description").toEqualTypeOf<string>();
});
});
@@ -0,0 +1,168 @@
/**
* @file auth-contracts.ts
* @description Shared contracts for Decentralized Plugin Authentication.
*/
/**
* A branded string type for sensitive credentials to prevent accidental logging or serialization.
*/
export type SensitiveString = string & { readonly __brand: "SensitiveString" };
/**
* Factory function to safely cast a string to a SensitiveString.
* This provides a single grep target for every place a secret enters the system.
*/
export const sensitive = (s: string): SensitiveString => s as SensitiveString;
/**
* The authorization tier of the plugin client.
*/
export type Tier = "basic" | "pro";
/**
* Payload sent by the Local App to the Marketplace to exchange a long-lived
* API key for a short-lived, audience-bound JWT.
*
* @see ADR-001 §2 "Asymmetric JWT Token Exchange"
*/
export interface TokenExchangeRequest {
/**
* The long-lived API key securely stored by the Local App
* @security Sensitive credential — must not be logged.
*/
apiKey: SensitiveString;
/** The specific Data Engine (audience) the Local App wants to connect to */
audience: string;
}
/**
* Payload returned by the Marketplace after a successful token exchange.
*
* @see ADR-001 §2 "Asymmetric JWT Token Exchange"
*/
export interface TokenExchangeResponse {
/** The JWT to attach to the WebSocket auth message */
token: SensitiveString;
/** Unix timestamp (ms) indicating when the token expires — so the Local App can refresh pre-emptively */
expiresAt: number;
/** Key id used to sign — useful when JWKS has multiple keys during rotation */
kid: string;
/** The entitlement tier of the client */
tier?: Tier;
}
/**
* Scaffold for a discriminated union of all possible WebSocket messages.
*/
export type WebSocketMessage = WebSocketAuthMessage; // | WebSocketSubscribeMessage | ...
/**
* First message sent by the Local App over the WebSocket to authenticate with the Data Engine.
*
* @see ADR-001 §4 "WebSocket Authentication Gating"
*/
export interface WebSocketAuthMessage {
type: "auth";
/** Protocol version to allow future wire shape evolution */
v: 1;
/** The short-lived JWT obtained from the Token Exchange */
token: SensitiveString;
}
/**
* Standard PKCE request shape during the initial connect flow.
* Note: snake_case fields below match RFC 7636 / RFC 6749 wire format.
*/
export interface PKCEConnectRequest {
/** Randomly generated state to prevent CSRF */
state: string;
/** The S256 hash of the code verifier */
code_challenge: string;
/** The challenge method (always "S256" for our implementation) */
code_challenge_method: "S256";
}
/**
* Standard PKCE exchange payload.
* Implements strict PKCE-protected Authorization Code Grant per RFC 7636.
* Note: snake_case fields below match RFC 7636 / RFC 6749 wire format.
*/
export interface PKCETokenExchange {
grant_type: "authorization_code";
redirect_uri: string;
client_id: string;
/** The authorization code received from the callback */
code: string;
/** The original unhashed verifier to prove possession */
code_verifier: string;
}
/**
* Payload returned by the Marketplace after a successful PKCE token exchange.
*/
export interface PKCETokenExchangeResponse {
/** The long-lived API key issued to the Local App */
apiKey: SensitiveString;
/** Tier surfaced so the Local App can show "Connected to X tier" in the UI */
tier?: Tier;
/** Optional issuance timestamp for future rotation/expiration logic */
issuedAt?: number;
}
/**
* The expected structure of the JWT claims after signature verification.
*/
export interface PluginJwtClaims {
/** Issuer (Marketplace URL) */
iss: string;
/** Subject (The plugin identifier or tenant ID) */
sub: string;
/** Audience (The specific Data Engine URL or ID) */
aud: string;
/** Expiration Time (Unix seconds) */
exp: number;
/** Not Before (Unix seconds) */
nbf: number;
/** Issued At (Unix seconds) */
iat: number;
/** JWT ID (Unique identifier for the token to prevent replay) */
jti: string;
/** The entitlement tier */
tier: Tier;
/**
* Optional array of allowed plugin namespace prefixes.
* @example ["wwv-plugin-aviation", "wwv-plugin-maritime-*"]
*/
plugins?: string[];
}
/**
* Standard error response shape for the auth API.
*/
export interface AuthErrorResponse {
/** Short error code (e.g., "invalid_grant", "rate_limit_exceeded") */
error: string;
/** Human-readable error description */
error_description: string;
}
/**
* JSON Web Key representing a single public key used to verify signatures.
* Mirrors the RFC 7517 shape.
*/
export interface JWK {
kty: string;
kid: string;
use?: string;
alg?: string;
n?: string;
e?: string;
[key: string]: unknown;
}
/**
* Expected shape of the /.well-known/jwks.json endpoint.
*/
export interface JWKSResponse {
keys: JWK[];
}
+29 -5
View File
@@ -1,6 +1,10 @@
// ─── WorldWideView Plugin SDK ─────────────────────────────────
// The public API for building WorldWideView plugins.
// Import from "@worldwideview/wwv-plugin-sdk" in your plugin.
/**
* @file index.ts
* @description Core SDK for WorldWideView plugin development.
* Defines the foundational types, interfaces, and utilities required
* to build data seeders, visualizers, and UI extensions.
* @module @worldwideview/wwv-plugin-sdk
*/
import type { ComponentType } from "react";
import { createElement } from "react";
@@ -86,17 +90,30 @@ export interface TimeRange {
export type TimeWindow = "1h" | "6h" | "24h" | "48h" | "7d";
// ─── Geo Entities ────────────────────────────────────────────
/**
* @interface GeoEntity
* @description The primary data primitive representing a geospatial object.
*/
export interface GeoEntity {
/** Globally unique identifier for this specific entity instance. */
id: string;
/** The ID of the plugin that owns this entity. */
pluginId: string;
/** WGS84 Latitude. */
latitude: number;
/** WGS84 Longitude. */
longitude: number;
/** Altitude in meters above ellipsoid (optional). */
altitude?: number;
/** Heading/Rotation in degrees (optional). */
heading?: number;
/** Speed in knots or meters/sec depending on domain (optional). */
speed?: number;
/** The moment this data was captured. */
timestamp: Date;
/** Short display string for labels. */
label?: string;
/** Arbitrary metadata associated with the entity. */
properties: Record<string, unknown>;
}
@@ -225,7 +242,11 @@ export type FilterValue =
| { type: "range"; min: number; max: number }
| { type: "boolean"; value: boolean };
// ─── World Plugin Interface ──────────────────────────────────
/**
* @interface WorldPlugin
* @description The core lifecycle interface for all WorldWideView extensions.
* Every plugin (built-in or marketplace) must implement this interface.
*/
export interface WorldPlugin {
id: string;
name: string;
@@ -278,3 +299,6 @@ export type DataBusEvents = {
};
export * from "./viteGlobals";
// ─── Auth Contracts ──────────────────────────────────────────
export * from "./auth-contracts";
+11 -3
View File
@@ -1,6 +1,10 @@
// ─── Plugin Manifest Types ───────────────────────────────────
// Schema for plugin.json manifest files.
// Three formats: declarative (JSON-only), static (GeoJSON), bundle (JS code).
/**
* @file manifest.ts
* @description Schema and types for the WorldWideView plugin manifest (plugin.json).
* Defines the contract between the platform and external modules,
* covering capabilities, security tiers, and data source configurations.
* @module @worldwideview/wwv-plugin-sdk
*/
import type { PluginCategory } from "./index";
@@ -59,6 +63,10 @@ export interface RenderingConfig {
maxEntities?: number;
}
/**
* @interface PluginManifest
* @description The structural definition of a plugin.json file.
*/
export interface PluginManifest {
id: string;
name: string;
+16 -5
View File
@@ -1,15 +1,26 @@
/**
* @file viteGlobals.ts
* @description Build-time utility for externalizing shared dependencies.
* Provides a Vite plugin that maps core libraries (React, Cesium, Zustand)
* to the host application's global context, ensuring singleton stability
* for dynamic plugin bundles.
* @module @worldwideview/wwv-plugin-sdk
*/
interface GlobalsMap {
[moduleId: string]: string;
}
/**
* A Vite/Rollup plugin that resolves shared dependencies to the
* `globalThis.__WWV_HOST__` object injected by the core WWV engine.
* @function wwvPluginGlobals
* @description Creates a Vite/Rollup plugin that resolves shared dependencies to
* the `globalThis.__WWV_HOST__` object.
*
* This ensures that dynamically loaded CDN plugins inherit the exact
* React, Zustand, and Cesium instances of the host application,
* eliminating "Invalid Hook Call" and "useCallback" context mismatches.
* This ensures that dynamically loaded plugins inherit the exact library
* instances of the host application, preventing version mismatches and
* context errors.
*
* @returns {any} A Vite plugin object.
*/
export function wwvPluginGlobals(): any {
const HOST_MAPPINGS: GlobalsMap = {
+3458 -1570
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -5,7 +5,7 @@ let dbUrl = process.env.DATABASE_URL;
if (!dbUrl) {
try {
const envLocalPath = path.resolve(process.cwd(), ".env.local");
const envLocalPath = path.resolve(process.cwd(), ".env");
if (fs.existsSync(envLocalPath)) {
const envContent = fs.readFileSync(envLocalPath, "utf8");
const match = envContent.match(/^DATABASE_URL=["']?(.*?)["']?$/m);
+13 -40
View File
@@ -1,24 +1,20 @@
// Prisma schema — PostgreSQL for all environments.
// Local dev: use `npx prisma dev` for a zero-install local PGLite instance.
// Cloud/Production: set DATABASE_URL to your Supabase/Postgres connection string.
datasource db {
provider = "postgresql"
}
generator client {
provider = "prisma-client-js"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
}
model User {
id String @id @default(uuid())
id String @id @default(uuid())
tenantId String?
email String
name String
hashedPassword String
role String @default("user")
createdAt DateTime @default(now())
role String @default("user")
createdAt DateTime @default(now())
favorites Favorite[]
memberships WorkspaceMember[]
@@ -34,7 +30,6 @@ model Favorite {
label String
pluginName String
lastSeen DateTime @default(now())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -42,25 +37,6 @@ model Favorite {
@@map("favorites")
}
// DISABLED — aviation history feature is currently turned off.
// Uncomment to re-enable.
//
// model AviationHistory {
// id Int @id @default(autoincrement())
// icao24 String
// callsign String?
// timestamp DateTime
// latitude Float
// longitude Float
// altitude Float?
// speed Float?
// heading Float?
//
// @@unique([timestamp, icao24])
// @@index([timestamp])
// @@map("aviation_history")
// }
model InstalledPlugin {
id String @id @default(uuid())
tenantId String?
@@ -85,30 +61,27 @@ model Setting {
@@map("settings")
}
// NEW — Global workspace registry
model Workspace {
id String @id @default(uuid())
id String @id @default(uuid())
name String
subdomain String @unique
status String @default("trialing")
plan String @default("basic")
subdomain String @unique
status String @default("trialing")
plan String @default("basic")
stripeCustomerId String?
stripeSubscriptionId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
members WorkspaceMember[]
@@map("workspaces")
}
// NEW — Links global users to workspaces with roles
model WorkspaceMember {
id String @id @default(uuid())
userId String
workspaceId String
role String @default("member")
joinedAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
File diff suppressed because it is too large. Load diff
+18 -11
View File
@@ -1,8 +1,21 @@
/**
* @file boot-db.mjs
* @description Database bootstrapping utility.
* Automates the startup of the local PostgreSQL container via Docker Compose
* and ensures the environment is ready for Prisma migrations.
* @module scripts
*/
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
// Load environment variables manually since dotenv might not be installed globally
/**
* @function loadEnv
* @description Manually parses a .env file into process.env to avoid
* external dependencies like 'dotenv' during early boot.
*/
const loadEnv = (file) => {
try {
if (fs.existsSync(file)) {
@@ -25,7 +38,6 @@ const loadEnv = (file) => {
};
loadEnv('.env');
loadEnv('.env.local');
const skipLocalDb = process.env.WWV_SKIP_LOCAL_DB === 'true' || process.env.WWV_SKIP_LOCAL_DB === '1';
@@ -46,19 +58,14 @@ try {
process.exit(0);
}
// Start the db service using docker compose
// Start the db service and wait for it to be healthy
console.log('📦 Starting PostgreSQL via Docker Compose...');
execSync('docker compose up -d db', { stdio: 'inherit' });
// Wait a few seconds for postgres to be ready
console.log('⏳ Waiting for PostgreSQL to be ready...');
// Simple sleep since we can't easily rely on pg_isready without pg client
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3000);
execSync('docker compose up -d --wait db', { stdio: 'inherit' });
console.log('✅ Local PostgreSQL database is ready!');
} catch (error) {
console.error('❌ Failed to start local database:', error.message);
console.log('💡 Ensure that docker is running and try again');
console.log('💡 You may need to start it manually or set WWV_SKIP_LOCAL_DB=true to use an external database.');
}
+14
View File
@@ -0,0 +1,14 @@
import { execSync } from 'child_process';
const dbUrl = process.env.DATABASE_URL || '';
const isLocal = dbUrl.includes('localhost') || dbUrl.includes('127.0.0.1') || dbUrl.includes('host.docker.internal') || dbUrl.includes('postgres:postgres@db:5432');
if (!isLocal) {
console.error("❌ ERROR: DATABASE_URL points to a remote database.");
console.error(" Running 'prisma db push --accept-data-loss' on production/staging data is forbidden.");
console.error(" If you truly need to migrate a remote db, run prisma db push manually.");
process.exit(1);
}
console.log("🔒 Local database detected. Safely running prisma db push...");
execSync('npx prisma db push --accept-data-loss', { stdio: 'inherit' });
+8 -9
View File
@@ -1,11 +1,10 @@
#!/usr/bin/env node
/**
* setup.mjs — One-command local setup
*
* Generates a .env.local file from .env.example
* and auto-fills AUTH_SECRET with a secure random value.
*
* Usage: npm run setup
* @file setup.mjs
* @description One-command local setup utility.
* Generates a .env file from .env.example and auto-fills sensitive
* secrets (like AUTH_SECRET) with secure random values.
* @module scripts
*/
import { existsSync, readFileSync, writeFileSync } from "fs";
@@ -14,10 +13,10 @@ import { resolve } from "path";
const ROOT = resolve(import.meta.dirname, "..");
const EXAMPLE = resolve(ROOT, ".env.example");
const TARGET = resolve(ROOT, ".env.local");
const TARGET = resolve(ROOT, ".env");
if (existsSync(TARGET)) {
console.log("✅ .env.local already exists — skipping setup.");
console.log("✅ .env already exists — skipping setup.");
console.log(" Delete it and re-run if you want to regenerate.");
process.exit(0);
}
@@ -49,6 +48,6 @@ content = content
writeFileSync(TARGET, content, "utf8");
console.log("✅ .env.local created with a generated AUTH_SECRET.");
console.log("✅ .env created with a generated AUTH_SECRET.");
console.log(" Fill in any optional API keys (Cesium, Bing, OpenSky, etc.)");
console.log(" then run: npm run dev");
+29 -3
View File
@@ -1,6 +1,11 @@
// scripts/sync-local-plugins.mjs
// Scans local-plugins/ for valid wwv-manifest.json files,
// builds each with Vite, and copies output to public/plugins-local/.
/**
* @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";
@@ -21,6 +26,12 @@ const EXTERNAL_GLOBALS = {
"resium": "globalThis.__WWV_HOST__.Resium",
};
/**
* @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 [];
@@ -43,6 +54,11 @@ export function discoverLocalPlugins() {
});
}
/**
* @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, pluginDir }) {
const devEntry = manifest.dev_entry || "src/index.ts";
let entryFile = path.join(pluginDir, devEntry);
@@ -74,8 +90,18 @@ export async function buildPlugin({ dir, manifest, pluginDir }) {
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,
+35 -3
View File
@@ -1,11 +1,11 @@
services:
wwv:
image: ghcr.io/silvertakana/worldwideview:latest
pull_policy: always
ports:
- "3000:3000"
volumes:
- wwv-data:/app/data
- ./public/plugins-local:/app/public/plugins-local:ro
env_file:
- path: .env
required: false
@@ -13,11 +13,17 @@ services:
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
restart: unless-stopped
- "DATABASE_URL=postgresql://postgres:postgres@db:5432/worldwideview?schema=public"
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
restart: unless-stopped
db:
image: postgres:15-alpine
@@ -37,6 +43,32 @@ services:
retries: 5
start_period: 60s
wwv-data-engine:
image: ghcr.io/silvertakana/wwv-data-engine:latest
ports:
- "5000:5000"
environment:
- PORT=5000
- REDIS_URL=redis://wwv-redis:6379
- SEEDERS_DIR=/app/seeders
- DB_PATH=/app/data/engine.db
depends_on:
wwv-redis:
condition: service_healthy
restart: unless-stopped
profiles:
- engine
wwv-redis:
image: redis:7-alpine
healthcheck:
test: ['CMD', 'redis-cli', 'ping']
interval: 5s
timeout: 3s
retries: 5
profiles:
- engine
volumes:
wwv-data:
postgres-data:
-49
View File
@@ -1,49 +0,0 @@
Write-Host "[*] Setting up WorldWideView for local self-hosting..."
# Check Docker
try {
$null = docker info 2>&1
if ($LASTEXITCODE -ne 0) { throw }
} catch {
Write-Host "[Error] Docker is not running or not accessible."
Write-Host "Please install or start Docker Desktop: https://docs.docker.com/get-docker/"
exit 1
}
# Check Docker Compose
try {
$null = docker compose version 2>&1
if ($LASTEXITCODE -ne 0) { throw }
} catch {
Write-Host "[Error] Docker Compose is not installed or accessible."
exit 1
}
# Generate docker-compose.yml
Write-Host "[*] Downloading docker-compose.yml..."
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/docker-compose.yml" -OutFile docker-compose.yml
# Generate .env
if (-Not (Test-Path .env)) {
Write-Host "[*] Generating new .env file with AUTH_SECRET..."
$bytes = New-Object Byte[] 32
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
$secret = -join ($bytes | ForEach-Object { $_.ToString("x2") })
Write-Host "[*] Downloading .env template..."
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/silvertakana/worldwideview/main/.env.example" -OutFile .env
$envContent = Get-Content .env -Raw
$envContent = $envContent -replace "(?m)^AUTH_SECRET=.*", "AUTH_SECRET=$secret"
$envContent | Out-File -FilePath .env -Encoding utf8
} else {
Write-Host "[Success] .env already exists, skipping generation."
}
Write-Host "[*] Starting Docker container..."
docker compose up -d
Write-Host "`n[Success] WorldWideView is running at http://localhost:3000"
Write-Host " Data is persisted in Docker volume 'wwv-data'"
Write-Host " Auth secret is saved in .env (don't delete this file)`n"
Write-Host "To stop the server: docker compose down"
Write-Host "To view logs: docker compose logs -f wwv"
-53
View File
@@ -1,53 +0,0 @@
#!/bin/bash
set -e
echo "🌍 Setting up WorldWideView for local self-hosting..."
# Check if docker is actually available and running
if ! docker info > /dev/null 2>&1; then
echo "❌ Error: Docker is not running or not accessible."
echo "If you are on Windows using WSL, ensure Docker Desktop is running and WSL integration is enabled for your default distro."
echo "Please install or start Docker Desktop: https://docs.docker.com/get-docker/"
exit 1
fi
# Check for docker compose plugin
if ! docker compose version > /dev/null 2>&1; then
echo "❌ Error: Docker Compose is not installed or accessible."
exit 1
fi
# 1. Download docker-compose.yml
echo "📦 Downloading docker-compose.yml..."
curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/docker-compose.yml
# 2. Generate .env with a persistent secret
if [ ! -f .env ]; then
echo "🔐 Generating new .env file with AUTH_SECRET..."
# Use openssl if available, otherwise use urandom
if command -v openssl &> /dev/null; then
SECRET=$(openssl rand -hex 32)
else
SECRET=$(head -c 32 /dev/urandom | xxd -p)
fi
echo "📥 Downloading .env template..."
curl -fsSL -o .env https://raw.githubusercontent.com/silvertakana/worldwideview/main/.env.example
# Replace AUTH_SECRET= with the generated secret
# (macOS sed requires an empty string backup extension, Linux does not. Perl is safer across platforms)
perl -pi -e "s/^AUTH_SECRET=.*$/AUTH_SECRET=$SECRET/" .env
else
echo "✅ .env already exists, skipping generation."
fi
# 3. Start it
echo "🚀 Starting Docker container..."
docker compose up -d
echo ""
echo "✅ WorldWideView is running at http://localhost:3000"
echo " Data is persisted in Docker volume 'wwv-data'"
echo " Auth secret is saved in .env (don't delete this file)"
echo ""
echo "To stop the server: docker compose down"
echo "To view logs: docker compose logs -f wwv"
View File
File renamed without changes.
Executable → Regular
View File
File renamed without changes.
-88
View File
@@ -1,88 +0,0 @@
{
"version": 1,
"skills": {
"cesium-context7": {
"source": "cesiumgs/cesium-ai-integrations",
"sourceType": "github",
"computedHash": "e4869dcd18a9b764c276f6378d3a075199d3a34b5b18b7449eb20660335b2ba4"
},
"context7": {
"source": "intellectronica/agent-skills",
"sourceType": "github",
"computedHash": "4e1e101b21c5be62420caffed99a5c11281ff48bfd208411b8714a14f8c82eab"
},
"context7-cli": {
"source": "upstash/context7",
"sourceType": "github",
"computedHash": "fc0c682dac344a4c78787072ae9b5b8708d4d5a14b2101c9b45de557bf9b7755"
},
"context7-mcp": {
"source": "upstash/context7",
"sourceType": "github",
"computedHash": "bce41b8f466edc10be7d47ebdb4ea8b9bb281adee288b12f40a4c36890c48825"
},
"find-docs": {
"source": "upstash/context7",
"sourceType": "github",
"computedHash": "d0321f889edc54a338b22615d6b00ace35f73f5879558e7183d0a70ceb819aa7"
},
"prisma-cli": {
"source": "prisma/skills",
"sourceType": "github",
"computedHash": "f91df0be8d0ac0f12c5402b5c53da12a31b284e5501dba027086bb12db879903"
},
"prisma-database-setup": {
"source": "prisma/skills",
"sourceType": "github",
"skillPath": "prisma-database-setup/SKILL.md",
"computedHash": "0d6f44ac34b1ed3f8ed2970ecf90483d0f658fd1d204458f62bfefa28f31b095"
},
"prisma-postgres": {
"source": "prisma/skills",
"sourceType": "github",
"skillPath": "prisma-postgres/SKILL.md",
"computedHash": "fd8f16f26e2cce1dd3e8e7916dcddbffddf295003eba86141f53e9d2d9d2bc0c"
},
"prisma-upgrade-v7": {
"source": "prisma/skills",
"sourceType": "github",
"skillPath": "prisma-upgrade-v7/SKILL.md",
"computedHash": "075d1fc3156d5593c3e9a559ebb07f82a2991db07125ff9df16ad90270f5c584"
},
"redis-best-practices": {
"source": "mindrally/skills",
"sourceType": "github",
"computedHash": "7d5b0f93221b2b0f1f1c35352d06990a9d18226aa95f546b161b10a4fdaabf6b"
},
"redis-development": {
"source": "redis/agent-skills",
"sourceType": "github",
"computedHash": "993ad240385d830a9717796a4b76e835ed737bfc9d3e10a4528e00bacd58cbf8"
},
"roblox-game-development": {
"source": "greedychipmunk/agent-skills",
"sourceType": "github",
"computedHash": "b16788a78d99027cf822da31d4e71e380d511a50dc3835d8481849075d5ec04a"
},
"roblox-gui": {
"source": "sentinelcore/roblox-skills",
"sourceType": "github",
"computedHash": "e50a649d3f6b1d60b393031118e2739ab697756e44d4a5442a26e53e996584c9"
},
"roblox-security": {
"source": "sentinelcore/roblox-skills",
"sourceType": "github",
"computedHash": "2581018cf2a0b71f3382065c5d353ef80ae6c81c44dd5bb63a848bd5990f5c6a"
},
"supabase": {
"source": "supabase/agent-skills",
"sourceType": "github",
"computedHash": "3bc4f56943a13f4fe355742a4b3b30c56008e6d265ae71f19c592410b5f5a01f"
},
"supabase-postgres-best-practices": {
"source": "supabase/agent-skills",
"sourceType": "github",
"computedHash": "abf015aafed757edaf2a329299fc106abebdc53bc7f089e92e1f762ed3d8f117"
}
}
}
+60
View File
@@ -0,0 +1,60 @@
import { NextResponse, type NextRequest } from "next/server";
import { auth } from "@/lib/auth";
import { agentBus, type AgentAction } from "@/lib/agent/bus";
/**
* POST /api/agent/publish
*
* Accept an AgentAction from a trusted caller (an external tool acting as
* the logged-in user) and broadcast it to every subscriber currently
* listening on /api/agent/stream *for the same user*. The browser subscriber
* routes the action onto the client-side dataBus, which the React + Cesium
* app already drives off of.
*
* Returns the number of clients the action reached.
*
* Auth: same session-cookie gate as /stream — only the same user's
* sessions can publish or subscribe, and per-user routing is enforced
* inside the bus.
*/
export async function POST(req: NextRequest) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const userId = session.user.id;
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
if (!isAgentAction(body)) {
return NextResponse.json(
{ error: "Body must be an AgentAction with a recognized `action` field" },
{ status: 400 },
);
}
const result = agentBus.publish(userId, body);
return NextResponse.json({
ok: true,
delivered: result.delivered,
subscribers: agentBus.subscribersFor(userId),
});
}
function isAgentAction(v: unknown): v is AgentAction {
if (!v || typeof v !== "object") return false;
const a = (v as { action?: unknown }).action;
return (
a === "fly_to" ||
a === "face_towards" ||
a === "layer_toggle" ||
a === "highlight_layer" ||
a === "select_entity" ||
a === "ping"
);
}
+69
View File
@@ -0,0 +1,69 @@
import { auth } from "@/lib/auth";
import { agentBus } from "@/lib/agent/bus";
/**
* GET /api/agent/stream
*
* Server-Sent Events channel that the browser subscribes to. Each connected
* client receives every action `/api/agent/publish` broadcasts *for the
* same authenticated user*. Multi-tenant safe: user A's stream never sees
* user B's publishes.
*
* Auth-gated via Auth.js session.
*/
export async function GET() {
const session = await auth();
if (!session?.user?.id) {
return new Response("Unauthorized", { status: 401 });
}
const userId = session.user.id;
let unsubscribe = () => {};
const id = `${userId}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
// Initial comment + retry hint so EventSource has something to ack
// immediately and reconnects fast if the connection drops.
controller.enqueue(encoder.encode(":connected\nretry: 3000\n\n"));
unsubscribe = agentBus.subscribe(userId, {
id,
write: (chunk) => controller.enqueue(encoder.encode(chunk)),
close: () => {
try { controller.close(); } catch { /* already closed */ }
},
});
// Heartbeat every 25s so intermediaries (Caddy, nginx, CDNs) don't
// tear down a "stalled" connection. SSE-aware proxies typically
// need a comment line every <30s to keep the channel alive.
const heartbeat = setInterval(() => {
try {
controller.enqueue(encoder.encode(`:hb ${Date.now()}\n\n`));
} catch {
clearInterval(heartbeat);
}
}, 25_000);
(controller as any)._cleanup = () => {
clearInterval(heartbeat);
unsubscribe();
};
},
cancel() {
unsubscribe();
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
});
}
+44
View File
@@ -0,0 +1,44 @@
import { NextResponse } from "next/server";
import fs from "node:fs";
import path from "node:path";
/**
* GET /api/build
*
* Lightweight build identification — lets you confirm exactly which build
* the running browser tab is talking to. Pair with the `[wwv build] ...`
* client-side console log so a refresh mismatch (browser holding stale
* chunks) becomes obvious instead of looking like a feature regression.
*
* Public — no secrets here, just a build stamp + a few public flags useful
* for diagnostics.
*/
function readMaybe(p: string): string | null {
try {
return fs.readFileSync(p, "utf-8").trim();
} catch {
return null;
}
}
const BUILD_ID =
process.env.NEXT_PUBLIC_WWV_BUILD_ID ??
readMaybe(path.join(process.cwd(), ".build-id")) ??
"dev";
const BUILD_AT =
process.env.NEXT_PUBLIC_WWV_BUILD_AT ??
readMaybe(path.join(process.cwd(), ".build-at")) ??
null;
export async function GET() {
return NextResponse.json({
build_id: BUILD_ID,
built_at: BUILD_AT,
public_flags: {
agent_bus_enabled:
process.env.NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true",
edition: process.env.NEXT_PUBLIC_WWV_EDITION ?? null,
},
});
}
+128
View File
@@ -0,0 +1,128 @@
/**
* NCDOT (North Carolina DOT) adapter.
*
* NCDOT exposes its public traffic-cam API in two parts: a bulk endpoint
* that returns ~770 cameras with only `{ id, latitude, longitude }`, and a
* detail endpoint that returns one camera's full record (locationName,
* roadId, countyId, imageURL, status). To get usable data we fan out an
* N+1 fetch from the bulk list with bounded concurrency. First call lands
* in ~15s; the registry's per-adapter cache holds it for 24h after that.
*
* No key required. Image URLs are direct ~45KB JPEGs at 640x360.
*/
import type { CameraAdapter, CameraFeature } from "./types";
const BULK_URL = "https://eapps.ncdot.gov/services/traffic-prod/v1/cameras";
const DETAIL_URL = (id: number) =>
`https://eapps.ncdot.gov/services/traffic-prod/v1/cameras/${id}`;
const CONCURRENCY = 20;
interface BulkRecord {
id: number;
latitude: number;
longitude: number;
}
interface DetailRecord {
id: number;
locationName: string | null;
displayName: string | null;
mileMarker: number | null;
roadId: number;
countyId: number;
latitude: number;
longitude: number;
imageURL: string;
isDOTCamera: boolean;
status: string;
}
async function fetchDetail(id: number): Promise<DetailRecord | null> {
try {
const res = await fetch(DETAIL_URL(id), {
headers: { "User-Agent": "WorldWideView/1.0" },
});
if (!res.ok) return null;
if (res.status === 204) return null; // camera deleted/unavailable
const text = await res.text();
if (!text) return null;
return JSON.parse(text) as DetailRecord;
} catch {
return null;
}
}
/** Bounded-concurrency Promise.all. */
async function mapWithConcurrency<T, R>(
items: T[],
limit: number,
worker: (item: T) => Promise<R>,
): Promise<R[]> {
const results: R[] = new Array(items.length);
let next = 0;
async function run() {
while (next < items.length) {
const i = next++;
results[i] = await worker(items[i]);
}
}
await Promise.all(Array.from({ length: limit }, run));
return results;
}
function toFeature(d: DetailRecord): CameraFeature | null {
if (d.status && d.status !== "OK") return null;
if (!d.imageURL) return null;
if (typeof d.latitude !== "number" || typeof d.longitude !== "number") return null;
return {
type: "Feature",
geometry: { type: "Point", coordinates: [d.longitude, d.latitude] },
properties: {
id: `ncdot-${d.id}`,
source: "ncdot",
stream: d.imageURL,
streamType: "image",
hls: null,
name: d.displayName || d.locationName || `NCDOT camera ${d.id}`,
country: "United States",
region: "North Carolina",
city: "North Carolina",
location_description: d.locationName ?? "",
categories: ["traffic"],
extra: {
mileMarker: d.mileMarker,
roadId: d.roadId,
countyId: d.countyId,
ncdotStatus: d.status,
},
},
};
}
export const ncdotAdapter: CameraAdapter = {
id: "ncdot",
displayName: "NCDOT (North Carolina)",
region: "United States — North Carolina",
fetch: async () => {
const bulkRes = await fetch(BULK_URL, {
headers: { "User-Agent": "WorldWideView/1.0" },
});
if (!bulkRes.ok) throw new Error(`NCDOT bulk ${bulkRes.status}`);
const bulk = (await bulkRes.json()) as BulkRecord[];
if (!Array.isArray(bulk)) return [];
const details = await mapWithConcurrency(bulk, CONCURRENCY, (b) =>
fetchDetail(b.id),
);
const features: CameraFeature[] = [];
for (const d of details) {
if (!d) continue;
const f = toFeature(d);
if (f) features.push(f);
}
return features;
},
};
@@ -0,0 +1,88 @@
/**
* OpenStreetMap surveillance points (`man_made=surveillance`).
*
* Location-only — most OSM surveillance nodes don't have public stream URLs,
* but the geometry alone is useful as a "where do public/government cameras
* exist" overlay alongside the live DOT feeds.
*
* The query is bounded to a list of major metros (~30km radius each) so a
* single Overpass call doesn't return hundreds of thousands of points.
* Operators who want fuller coverage can extend `OVERPASS_QUERY` and bump
* the per-query cap. Output is capped at 3000 nodes total.
*
* Cache TTL is 7 days — OSM data changes slowly and Overpass is shared
* infrastructure that politely asks consumers not to re-poll aggressively.
*/
import type { CameraAdapter, CameraFeature } from "./types";
const OVERPASS_URL = "https://overpass-api.de/api/interpreter";
const OVERPASS_QUERY = `[out:json][timeout:25];
(
node["man_made"="surveillance"](around:30000,37.7749,-122.4194);
node["man_made"="surveillance"](around:30000,34.0522,-118.2437);
node["man_made"="surveillance"](around:30000,40.7128,-74.0060);
node["man_made"="surveillance"](around:30000,51.5074,-0.1278);
node["man_made"="surveillance"](around:30000,48.8566,2.3522);
node["man_made"="surveillance"](around:30000,35.6762,139.6503);
node["man_made"="surveillance"](around:30000,35.7796,-78.6382);
);
out body 3000;`;
interface OverpassNode {
type: "node";
id: number;
lat: number;
lon: number;
tags?: Record<string, string>;
}
export const osmSurveillanceAdapter: CameraAdapter = {
id: "osm-surveillance",
displayName: "OSM Surveillance Points",
region: "Global (sampled major metros)",
cacheTtlMs: 7 * 24 * 60 * 60 * 1000,
fetch: async () => {
const res = await fetch(OVERPASS_URL, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "WorldWideView/1.0",
},
body: `data=${encodeURIComponent(OVERPASS_QUERY)}`,
});
if (!res.ok) throw new Error(`overpass ${res.status}`);
const data = (await res.json()) as { elements?: OverpassNode[] };
const nodes = (data.elements ?? []).filter(
(e): e is OverpassNode =>
e.type === "node" && typeof e.lat === "number",
);
return nodes.map<CameraFeature>((n) => {
const t = n.tags ?? {};
return {
type: "Feature",
geometry: { type: "Point", coordinates: [n.lon, n.lat] },
properties: {
id: `osm-${n.id}`,
source: "osm-surveillance",
stream: null,
streamType: null,
hls: null,
name: t.name ?? "Surveillance",
country: t["addr:country"],
location_description: t.description ?? "",
categories: ["surveillance"],
extra: {
operator: t.operator,
surveillanceType: t["surveillance:type"],
cameraType: t["camera:type"],
cameraDirection: t.camera_direction,
osmId: n.id,
},
},
};
});
},
};
@@ -0,0 +1,36 @@
import { describe, it, expect } from "vitest";
import { resolveSources, ALL_ADAPTERS } from "./registry";
/**
* `resolveSources` is the input-sanitizer at the top of every
* /api/camera/traffic and /api/camera/list call. Wrong behaviour here
* either denies legitimate clients or lets the aggregator hit adapters
* that aren't registered. Easy to test, high blast radius.
*/
describe("camera adapter registry — resolveSources", () => {
it("returns every registered adapter id when raw is 'all'", () => {
const result = resolveSources("all");
const expected = ALL_ADAPTERS.map((a) => a.id);
expect(result.sort()).toEqual(expected.sort());
});
it("returns every registered adapter id when raw is null (default behaviour)", () => {
const result = resolveSources(null);
const expected = ALL_ADAPTERS.map((a) => a.id);
expect(result.sort()).toEqual(expected.sort());
});
it("returns an empty list when raw is 'none' — clients use this to short-circuit", () => {
expect(resolveSources("none")).toEqual([]);
});
it("drops unknown ids from a comma-separated list without erroring", () => {
const knownId = ALL_ADAPTERS[0]?.id;
if (!knownId) throw new Error("registry has zero adapters — test precondition broken");
const result = resolveSources(`${knownId},completely-fake-adapter,${knownId}`);
expect(result).toContain(knownId);
expect(result).not.toContain("completely-fake-adapter");
});
});
+27 -2
View File
@@ -4,6 +4,8 @@ import { gdotAdapter } from "./gdot";
import { tflAdapter } from "./tfl";
import { ny511Adapter } from "./ny511";
import { wsdotAdapter } from "./wsdot";
import { ncdotAdapter } from "./ncdot";
import { osmSurveillanceAdapter } from "./osm-surveillance";
/**
* All registered adapters. To add a new source, add an import + push the
@@ -17,6 +19,8 @@ export const ALL_ADAPTERS: CameraAdapter[] = [
tflAdapter,
ny511Adapter,
wsdotAdapter,
ncdotAdapter,
osmSurveillanceAdapter,
];
const ADAPTERS_BY_ID: Map<string, CameraAdapter> = new Map(
@@ -83,6 +87,15 @@ export function getAdapterMetadata(): CameraAdapterMeta[] {
* way, the cache entry's `error` field is set so `/api/camera/list` can
* report unhealthy adapters.
*/
/**
* Per-adapter cold-fetch timeout. If an upstream API hangs, the aggregator
* `Promise.allSettled` waits for the slowest one — so a single dead source
* holds up every other adapter's data from reaching the client. With this
* cap a stuck source becomes a fast error, and the cache fallback path
* keeps serving stale data without blocking the response.
*/
const ADAPTER_FETCH_TIMEOUT_MS = 4_000;
export async function fetchAdapter(adapter: CameraAdapter): Promise<CameraFeature[]> {
if (!isKeyAvailable(adapter)) {
return [];
@@ -90,11 +103,23 @@ export async function fetchAdapter(adapter: CameraAdapter): Promise<CameraFeatur
const now = Date.now();
const ttl = adapter.cacheTtlMs ?? DEFAULT_TTL_MS;
const c = cache.get(adapter.id);
if (c && now < c.expiry && !c.error) {
// Serve from cache for the retry window even if the last attempt errored —
// otherwise every aggregated request re-fires a doomed upstream call and
// pays the timeout penalty each time. The error stays on the cache entry
// so /api/camera/list can still report the adapter as unhealthy.
if (c && now < c.expiry) {
return c.data;
}
try {
const data = await adapter.fetch();
const data = await Promise.race([
adapter.fetch(),
new Promise<CameraFeature[]>((_resolve, reject) =>
setTimeout(
() => reject(new Error(`Adapter ${adapter.id} timed out after ${ADAPTER_FETCH_TIMEOUT_MS}ms`)),
ADAPTER_FETCH_TIMEOUT_MS,
),
),
]);
cache.set(adapter.id, {
data,
expiry: now + ttl,
+47
View File
@@ -0,0 +1,47 @@
import { NextResponse } from "next/server";
import { validateMarketplaceAuth } from "@/lib/marketplace/auth";
import { disablePlugin } from "@/lib/marketplace/repository";
import { handlePreflight, withCors } from "@/lib/marketplace/cors";
import { marketplaceApiLimiter } from "@/lib/rateLimiters";
import { getClientIp } from "@/lib/rateLimit";
import { isPluginInstallEnabled } from "@/core/edition";
export async function OPTIONS(request: Request) {
return handlePreflight(request);
}
export async function POST(request: Request) {
if (!isPluginInstallEnabled) {
return withCors(
NextResponse.json({ error: "Plugin management is disabled on this instance" }, { status: 403 }),
request,
);
}
const rateLimited = marketplaceApiLimiter.check(getClientIp(request));
if (rateLimited) return withCors(rateLimited, request);
const authError = await validateMarketplaceAuth(request);
if (authError) return withCors(authError, request);
try {
const body = await request.json();
const { pluginId } = body;
if (!pluginId || typeof pluginId !== "string") {
return withCors(
NextResponse.json({ error: "Missing required field: pluginId" }, { status: 400 }),
request,
);
}
await disablePlugin(pluginId);
return withCors(NextResponse.json({ status: "disabled", pluginId }), request);
} catch (err) {
console.error("[marketplace/disable] Error:", err);
return withCors(
NextResponse.json({ error: "Disable failed" }, { status: 500 }),
request,
);
}
}
+47
View File
@@ -0,0 +1,47 @@
import { NextResponse } from "next/server";
import { validateMarketplaceAuth } from "@/lib/marketplace/auth";
import { enablePlugin } from "@/lib/marketplace/repository";
import { handlePreflight, withCors } from "@/lib/marketplace/cors";
import { marketplaceApiLimiter } from "@/lib/rateLimiters";
import { getClientIp } from "@/lib/rateLimit";
import { isPluginInstallEnabled } from "@/core/edition";
export async function OPTIONS(request: Request) {
return handlePreflight(request);
}
export async function POST(request: Request) {
if (!isPluginInstallEnabled) {
return withCors(
NextResponse.json({ error: "Plugin management is disabled on this instance" }, { status: 403 }),
request,
);
}
const rateLimited = marketplaceApiLimiter.check(getClientIp(request));
if (rateLimited) return withCors(rateLimited, request);
const authError = await validateMarketplaceAuth(request);
if (authError) return withCors(authError, request);
try {
const body = await request.json();
const { pluginId } = body;
if (!pluginId || typeof pluginId !== "string") {
return withCors(
NextResponse.json({ error: "Missing required field: pluginId" }, { status: 400 }),
request,
);
}
await enablePlugin(pluginId);
return withCors(NextResponse.json({ status: "enabled", pluginId }), request);
} catch (err) {
console.error("[marketplace/enable] Error:", err);
return withCors(
NextResponse.json({ error: "Enable failed" }, { status: 500 }),
request,
);
}
}
+2 -4
View File
@@ -27,10 +27,8 @@ export async function GET(request: Request) {
const dbPlugins = await getInstalledPlugins();
const dbMap = new Map(dbPlugins.map((p: any) => [p.pluginId, p]));
// Collect active DB plugins (exclude disabled ones)
const activeDbPlugins = dbPlugins.filter((p: any) => p.enabled !== false);
const plugins = activeDbPlugins;
// Collect all DB plugins (enabled and disabled)
const plugins = dbPlugins;
let canManagePlugins = !isDemo;
if (isDemo) {
+75 -60
View File
@@ -46,12 +46,11 @@ html, body {
/* ─── Glass Panel ─────────────────────────────────────────── */
.glass-panel {
background: var(--bg-glass);
backdrop-filter: blur(var(--glass-blur));
-webkit-backdrop-filter: blur(var(--glass-blur));
border: var(--glass-border);
box-shadow: var(--glass-border-inner), var(--glass-shadow);
border-radius: var(--radius-lg);
transition: all var(--duration-fast) var(--ease-smooth);
backdrop-filter: blur(24px) !important;
}
/* ─── Page Root (flex row: app + optional ad strip) ───────── */
@@ -70,7 +69,7 @@ html, body {
min-width: 0;
height: 100vh;
overflow: hidden;
isolation: isolate; /* contain fixed children so ad strip renders on top */
/* isolation: isolate; removed because it breaks backdrop-filter in chromium under some stacking contexts */
}
.app-shell__globe {
@@ -214,60 +213,6 @@ html, body {
min-height: 0;
}
/* ─── Discord Sidebar Link ────────────────────────────────── */
.discord-sidebar-link {
display: flex;
align-items: center;
gap: var(--space-sm);
padding: var(--space-md) var(--space-lg);
margin-top: var(--space-md);
background: linear-gradient(135deg, rgba(88, 101, 242, 0.15), rgba(88, 101, 242, 0.05));
border: 1px solid rgba(88, 101, 242, 0.25);
border-radius: var(--radius-md);
color: #b8bfff;
text-decoration: none;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all var(--duration-fast) var(--ease-smooth);
flex-shrink: 0;
}
.discord-sidebar-link:hover {
background: linear-gradient(135deg, rgba(88, 101, 242, 0.3), rgba(88, 101, 242, 0.12));
border-color: rgba(88, 101, 242, 0.5);
color: #dee1ff;
box-shadow: 0 0 20px rgba(88, 101, 242, 0.25);
transform: translateY(-1px);
}
/* ─── Feedback Sidebar Link ────────────────────────────────── */
.feedback-sidebar-link {
display: flex;
align-items: center;
gap: var(--space-sm);
padding: var(--space-md) var(--space-lg);
margin-top: var(--space-md);
background: linear-gradient(135deg, rgba(34, 211, 238, 0.15), rgba(34, 211, 238, 0.05));
border: 1px solid rgba(34, 211, 238, 0.25);
border-radius: var(--radius-md);
color: var(--accent-cyan);
text-decoration: none;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all var(--duration-fast) var(--ease-smooth);
flex-shrink: 0;
justify-content: center;
}
.feedback-sidebar-link:hover {
background: linear-gradient(135deg, rgba(34, 211, 238, 0.3), rgba(34, 211, 238, 0.12));
border-color: rgba(34, 211, 238, 0.5);
color: #e2e8f0;
box-shadow: var(--glow-cyan);
transform: translateY(-1px);
}
/* ─── Sidebar ─────────────────────────────────────────────── */
.sidebar {
@@ -281,7 +226,12 @@ html, body {
flex-direction: column;
overflow: hidden;
transition: transform var(--duration-slow) var(--ease-smooth),
opacity var(--duration-slow) var(--ease-smooth);
opacity var(--duration-slow) var(--ease-smooth),
bottom var(--duration-slow) var(--ease-smooth);
}
.timeline-closed .sidebar {
bottom: var(--space-lg);
}
.sidebar--left {
@@ -1018,7 +968,7 @@ html, body {
left: var(--space-sm);
right: var(--space-sm);
bottom: var(--space-sm);
padding: var(--space-sm) var(--space-md);
padding: var(--space-sm) 48px var(--space-sm) var(--space-md);
border-radius: var(--radius-md);
}
@@ -1067,7 +1017,7 @@ html, body {
left: var(--space-xs);
right: var(--space-xs);
bottom: var(--space-xs);
padding: var(--space-xs) var(--space-sm);
padding: var(--space-xs) 40px var(--space-xs) var(--space-sm);
}
}
@@ -1897,3 +1847,68 @@ body.is-resizing-sidebar .sidebar {
height: 16px;
background: var(--border-subtle);
}
/* ─── Timeline Toggle & Close ──────────────────────────────────── */
.timeline-toggle-wrapper {
position: fixed;
bottom: var(--space-lg);
left: 50%;
transform: translateX(-50%);
z-index: 100;
}
.timeline-toggle-btn {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 50%;
background: rgba(10, 10, 10, 0.5);
border: 1px solid var(--border-subtle);
color: var(--text-secondary);
cursor: pointer;
transition: all var(--duration-fast) var(--ease-smooth);
backdrop-filter: blur(12px);
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
[data-theme='light'] .timeline-toggle-btn {
background: rgba(255, 255, 255, 0.5);
}
[data-theme='light'] .timeline-toggle-btn:hover {
background: rgba(255, 255, 255, 0.65);
}
.timeline-toggle-btn:hover {
color: var(--text-primary);
background: rgba(20, 20, 20, 0.65);
transform: scale(1.05);
box-shadow: 0 6px 16px rgba(0,0,0,0.3);
}
.timeline-close-btn {
position: absolute;
top: 4px;
right: 4px;
background: transparent;
border: none;
color: var(--text-muted);
cursor: pointer;
width: 44px;
height: 44px;
border-radius: var(--radius-sm);
display: flex;
align-items: center;
justify-content: center;
transition: color var(--duration-fast), background var(--duration-fast);
z-index: 2;
}
.timeline-close-btn:hover {
color: var(--text-primary);
background: rgba(255, 255, 255, 0.1);
}
+10 -3
View File
@@ -22,7 +22,14 @@
height: 48px;
margin: 0 auto 1rem;
border-radius: 0px;
background: rgb(var(--accent-rgb, 200, 30, 30));
/*
* Setup page is pre-auth and pre-theme — `--accent-rgb` defaults
* to `255, 255, 255` (white) in theme-tokens.css, which makes
* `rgb(255, 255, 255)` + `color: #fff` render invisible. Use an
* explicit brand color so the logo is visible before any theme
* applies.
*/
background: rgb(200, 30, 30);
color: #fff;
font-weight: 700;
font-size: 1.25rem;
@@ -71,7 +78,7 @@
}
.input:focus {
border-color: rgb(var(--accent-rgb, 200, 30, 30));
border-color: rgb(200, 30, 30);
}
.error {
@@ -83,7 +90,7 @@
.button {
margin-top: 0.75rem;
padding: 0.7rem;
background: rgb(var(--accent-rgb, 200, 30, 30));
background: rgb(200, 30, 30);
color: #fff;
border: none;
border-radius: 0px;
+17
View File
@@ -1,5 +1,12 @@
"use client";
/**
* @file AdUnit.tsx
* @description Standardized Google AdSense wrapper component.
* Handles client-side script pushing and provides a development-mode mock UI.
* @module src/components/ads
*/
import { useEffect, useRef } from "react";
interface AdUnitProps {
@@ -9,6 +16,16 @@ interface AdUnitProps {
className?: string;
}
/**
* @component AdUnit
* @description Renders a Google AdSense advertisement unit.
*
* @param {AdUnitProps} props - Component properties.
* @param {string} props.adSlot - The AdSense slot ID.
* @param {string} [props.adFormat="auto"] - The AdSense format (auto, rectangle, etc).
* @param {React.CSSProperties} [props.style] - Optional inline styles for the container.
* @param {string} [props.className] - Optional CSS class for the container.
*/
export function AdUnit({ adSlot, adFormat = "auto", style, className }: AdUnitProps) {
const insRef = useRef<HTMLModElement>(null);
const pushed = useRef(false);
+2 -2
View File
@@ -13,8 +13,8 @@
justify-content: center;
gap: var(--space-lg);
background: var(--bg-glass);
backdrop-filter: var(--glass-blur);
-webkit-backdrop-filter: var(--glass-blur);
backdrop-filter: blur(var(--glass-blur));
-webkit-backdrop-filter: blur(var(--glass-blur));
border-left: 1px solid var(--glass-border);
padding: var(--space-md);
overflow-y: auto;
+12
View File
@@ -1,5 +1,12 @@
"use client";
/**
* @file DemoAdStrip.tsx
* @description specialized sidebar for the demo edition that hosts AdSense
* units and a small banner explaining the monetization model.
* @module src/components/ads
*/
import React, { useState, useEffect } from "react";
import { isDemo } from "@/core/edition";
import { dataBus } from "@/core/data/DataBus";
@@ -17,6 +24,11 @@ const AD_STRIP_WIDTH = 160;
/** Toggle to temporarily disable ads in the demo edition. */
const ENABLE_ADS = false;
/**
* @component DemoAdStrip
* @description Renders a vertical ad column on the right side of the screen.
* Automatically injects layout offsets into the page root to prevent HUD overlap.
*/
export function DemoAdStrip() {
const [showMessage, setShowMessage] = useState(false);
const [bannerDismissed, setBannerDismissed] = useState(false);
+17
View File
@@ -1,11 +1,28 @@
/**
* @file BootOverlay.tsx
* @description A high-fidelity loading overlay displayed during application initialization.
* Features animated orbital rings and brand identity.
* @module src/components/common
*/
"use client";
import "./BootOverlay.css";
/**
* Props for the BootOverlay component.
*/
interface BootOverlayProps {
/** Whether the overlay is currently visible on top of the application. */
visible: boolean;
}
/**
* @component BootOverlay
* @description Animated splash screen for initial system boot.
*
* @param {BootOverlayProps} props - Component properties.
*/
export function BootOverlay({ visible }: BootOverlayProps) {
return (
<div className={`boot-overlay ${visible ? "" : "boot-overlay--hidden"}`}>
+13 -2
View File
@@ -1,13 +1,24 @@
/**
* Discord brand icon as a React SVG component.
* Matches the lucide-react icon API (size, className props).
* @file DiscordIcon.tsx
* @description SVG component for the Discord brand identity.
*/
/**
* Props for the DiscordIcon component.
*/
interface DiscordIconProps {
/** Dimension (width and height) in pixels. Defaults to 18. */
size?: number;
/** Optional CSS class names for styling. */
className?: string;
}
/**
* Renders the Discord logo as an SVG.
*
* @param props - Component properties.
* @returns React component rendering the Discord icon.
*/
export function DiscordIcon({ size = 18, className }: DiscordIconProps) {
return (
<svg
+14
View File
@@ -1,3 +1,10 @@
/**
* @file FeedbackDialog.tsx
* @description A comprehensive feedback and bug reporting interface.
* Supports categorization, screenshot capture via getDisplayMedia,
* file uploads, and automatic diagnostic log attachment.
*/
"use client";
import React, { useState, useEffect, useRef } from "react";
@@ -7,6 +14,13 @@ import { getCapturedLogs } from "@/lib/logCatcher";
import styles from "./FeedbackDialog.module.css";
import { trackEvent } from "@/lib/analytics";
/**
* A modal dialog that allows users to submit bug reports, feature requests,
* and general feedback. The component captures application state, diagnostic
* logs, and user-provided visuals to facilitate debugging.
*
* @returns React component for the feedback portal.
*/
export function FeedbackDialog() {
const feedbackDialogOpen = useStore((s) => s.feedbackDialogOpen);
const setFeedbackDialogOpen = useStore((s) => s.setFeedbackDialogOpen);
+26
View File
@@ -1,20 +1,46 @@
/**
* @file FloatingWindow.tsx
* @description A draggable and resizable modal window container.
* Supports mouse and touch interactions, boundary constraints, and persistence callbacks.
* @module src/components/common
*/
"use client";
import React, { useState, useEffect, useRef, useCallback } from "react";
import { X } from "lucide-react";
/**
* Props for the FloatingWindow component.
*/
interface FloatingWindowProps {
/** Unique identifier for the window instance. */
id: string;
/** Title text displayed in the header bar. */
title: string;
/** Inner content to be rendered within the window body. */
children: React.ReactNode;
/** Initial screen coordinates for the window. */
initialPosition?: { x: number; y: number };
/** Initial dimensions for the window. */
initialSize?: { width: number; height: number };
/** Callback triggered when the close button is clicked. */
onClose: () => void;
/** Callback triggered when the window is moved or resized. */
onUpdate?: (updates: { position?: { x: number; y: number }; size?: { width: number; height: number } }) => void;
/** Minimum allowed width during resize. Defaults to 300. */
minWidth?: number;
/** Minimum allowed height during resize. Defaults to 200. */
minHeight?: number;
}
/**
* @component FloatingWindow
* @description A floating, interactive container used for data streams and secondary tools.
* Implements a custom drag-and-resize engine compatible with both desktop and mobile.
*
* @param {FloatingWindowProps} props - Component properties.
*/
export const FloatingWindow: React.FC<FloatingWindowProps> = ({
id,
title,
+18
View File
@@ -1,9 +1,20 @@
/**
* @file PannableView.tsx
* @description A high-performance 2D navigation container providing panning and
* pinch-zoom capabilities for inner content.
* @module src/components/common
*/
"use client";
import React, { useState, useRef, useCallback } from "react";
import { RotateCcw } from "lucide-react";
/**
* Props for the PannableView component.
*/
interface PannableViewProps {
/** The content to be rendered within the pannable and zoomable area. */
children: React.ReactNode;
}
@@ -11,6 +22,13 @@ const MIN_ZOOM = 1;
const MAX_ZOOM = 8;
const ZOOM_STEP = 0.15;
/**
* @component PannableView
* @description Wraps content in a 2D viewport that supports infinite panning and multi-touch zoom.
* Ideal for secondary maps, floor plans, or large interactive diagrams.
*
* @param {PannableViewProps} props - Component properties.
*/
export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
const [zoom, setZoom] = useState(1);
const [pan, setPan] = useState({ x: 0, y: 0 });
@@ -1,16 +1,38 @@
/**
* @file PluginErrorBoundary.tsx
* @description Fault-isolation container for dynamic plugin components.
* Ensures a single plugin crash does not bring down the entire application.
* @module src/components/common
*/
"use client";
import React, { Component, ErrorInfo, ReactNode } from "react";
/**
* Props for the PluginErrorBoundary component.
*/
interface Props {
/** The unique identifier of the plugin being wrapped. */
pluginId: string;
/** The child components to monitor for render errors. */
children: ReactNode;
}
/**
* State for the PluginErrorBoundary.
*/
interface State {
/** Whether an error has been caught in the current lifecycle. */
hasError: boolean;
}
/**
* @component PluginErrorBoundary
* @description A standard React error boundary used to isolate failures in third-party
* or dynamic plugin components. When a crash occurs, the boundary renders
* nothing (null), allowing the rest of the UI (sidebar, globe) to remain functional.
*/
export class PluginErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false
+21 -4
View File
@@ -1,3 +1,9 @@
/**
* @file PluginIcon.tsx
* @description Central icon resolver for plugins. Supports Lucide string names,
* emoji fallbacks, and custom React component icons.
*/
"use client";
import type { ComponentType } from "react";
@@ -5,17 +11,28 @@ import { icons, type LucideIcon } from "lucide-react";
const FallbackIcon = icons.Package;
/**
* Props for the PluginIcon component.
*/
interface PluginIconProps {
/**
* The icon to render. Can be a Lucide icon name (e.g., "Airplay"),
* a raw emoji string, or a React component.
*/
icon: string | ComponentType<{ size?: number; color?: string }>;
/** The size in pixels for the icon. Defaults to 18. */
size?: number;
/** The CSS color for the icon stroke/fill. */
color?: string;
}
/**
* Renders a plugin icon consistently across the app.
* Resolves any valid lucide-react icon name string dynamically,
* so new plugins can use any icon without updating this component.
* Also supports emoji strings and React component icons.
* Renders a consistent icon representation for plugins.
* Dynamically resolves Lucide icons by name to allow plugins to declare
* icons in their manifests without bundling dependencies.
*
* @param props - Component properties.
* @returns React component for the plugin icon.
*/
export function PluginIcon({ icon, size = 18, color }: PluginIconProps) {
if (typeof icon === "string") {
@@ -0,0 +1,136 @@
"use client";
/**
* Subscribes to the server's agent SSE channel and re-emits actions onto
* the client-side `dataBus`, so an external tool posting to
* /api/agent/publish lands on the same event surface the rest of the app
* already drives off of. Renders nothing — purely a side-effect component,
* paired with `DataBusSubscriber`.
*
* Disabled unless `NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true"` so an
* unintended deployment doesn't open a remote-control channel for users
* who didn't opt in.
*/
import { useEffect } from "react";
import { dataBus } from "@/core/data/DataBus";
import { pluginManager } from "@/core/plugins/PluginManager";
interface FlyToMessage {
action: "fly_to";
lat: number;
lon: number;
alt?: number;
heading?: number;
distance?: number;
}
interface FaceTowardsMessage {
action: "face_towards";
lat: number;
lon: number;
alt?: number;
}
interface LayerToggleMessage {
action: "layer_toggle";
pluginId: string;
enabled: boolean;
}
interface HighlightMessage {
action: "highlight_layer";
pluginId: string;
}
interface SelectEntityMessage {
action: "select_entity";
pluginId: string;
entityId: string;
}
interface PingMessage {
action: "ping";
ts: number;
}
type AgentMessage =
| FlyToMessage
| FaceTowardsMessage
| LayerToggleMessage
| HighlightMessage
| SelectEntityMessage
| PingMessage;
function applyAction(msg: AgentMessage): void {
switch (msg.action) {
case "fly_to":
dataBus.emit("cameraGoTo", {
lat: msg.lat,
lon: msg.lon,
alt: msg.alt ?? 0,
distance: msg.distance,
heading: msg.heading,
});
return;
case "face_towards":
dataBus.emit("cameraFaceTowards", {
lat: msg.lat,
lon: msg.lon,
alt: msg.alt ?? 0,
});
return;
case "layer_toggle": {
const managed = pluginManager.getPlugin(msg.pluginId);
if (!managed) return;
if (managed.enabled === msg.enabled) return;
pluginManager.togglePlugin(msg.pluginId);
return;
}
case "highlight_layer":
dataBus.emit("layerToggled", { pluginId: msg.pluginId, enabled: true });
return;
case "select_entity": {
const entities = pluginManager.getEntities(msg.pluginId);
const entity = entities.find((e) => e.id === msg.entityId);
if (entity) dataBus.emit("entitySelected", { entity });
return;
}
case "ping":
// No-op — useful for an external tool to verify the channel is alive.
return;
}
}
export function AgentBusSubscriber() {
useEffect(() => {
// Log build-id + agent-bus state once on mount. A stale-bundle / config
// mismatch becomes visible at a glance in the browser console instead
// of looking like a feature regression.
const buildId = process.env.NEXT_PUBLIC_WWV_BUILD_ID ?? "dev";
const builtAt = process.env.NEXT_PUBLIC_WWV_BUILD_AT ?? "";
const agentBusEnabled =
process.env.NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true";
console.log(
`[wwv build] id=${buildId} built_at=${builtAt} agent_bus=${agentBusEnabled ? "on" : "off"}`,
);
if (!agentBusEnabled) return;
if (typeof EventSource === "undefined") return;
const es = new EventSource("/api/agent/stream", { withCredentials: true });
es.onmessage = (event) => {
try {
const msg = JSON.parse(event.data) as AgentMessage;
applyAction(msg);
} catch (err) {
console.warn("[AgentBus] malformed message", err);
}
};
es.onerror = (err) => {
// EventSource auto-reconnects on its own with the `retry:` value
// we send from the server. Just log; don't tear down.
console.debug("[AgentBus] stream error (auto-reconnecting)", err);
};
return () => {
es.close();
};
}, []);
return null;
}
+20
View File
@@ -1,3 +1,11 @@
/**
* @file ApiKeysTab.tsx
* @description Manages user-provided API keys and license verification.
* Allows users to override default keys for services like Google Maps or
* proprietary data sources.
* @module src/components/layout
*/
import { useState, useCallback, useEffect, useRef } from "react";
import { Eye, EyeOff, Trash2, Key, CheckCircle, XCircle, Loader, ShieldCheck } from "lucide-react";
import {
@@ -37,6 +45,13 @@ const toggleBtnStyle: React.CSSProperties = {
const DEBOUNCE_MS = 800;
const MIN_KEY_LENGTH = 20;
/**
* @function StatusIcon
* @description Renders a status icon (loading, valid, invalid) for key verification.
* @param {Object} props - Component properties.
* @param {VerifyStatus} props.status - The current verification state.
* @returns {JSX.Element | null}
*/
function StatusIcon({ status }: { status: VerifyStatus }) {
if (status === "verifying")
return (
@@ -51,6 +66,11 @@ function StatusIcon({ status }: { status: VerifyStatus }) {
return null;
}
/**
* @component ApiKeysTab
* @description A configuration interface for managing license keys and service API keys.
* Handles persistence to local storage and asynchronous verification of keys.
*/
export function ApiKeysTab() {
const [keys, setKeys] = useState<Record<string, string>>(() => {
const initial: Record<string, string> = {};
+30 -1
View File
@@ -1,3 +1,11 @@
/**
* @file AppShell.tsx
* @description The root layout and orchestration component for WorldWideView.
* Responsible for platform initialization, plugin registration, global state hydration,
* and managing the transition from boot sequence to interactive state.
* @module src/components/layout
*/
"use client";
import { useEffect, useRef, useState } from "react";
@@ -20,6 +28,7 @@ import { useBootSequence } from "@/core/hooks/useBootSequence";
import { useIsMobile } from "@/core/hooks/useIsMobile";
import { useMarketplaceSync } from "@/core/hooks/useMarketplaceSync";
import { DataBusSubscriber } from "./DataBusSubscriber";
import { AgentBusSubscriber } from "./AgentBusSubscriber";
import { MobileHudBar } from "./MobileHudBar";
import { MobileCameraStats } from "./MobileCameraStats";
import dynamic from "next/dynamic";
@@ -37,6 +46,17 @@ const GlobeView = dynamic(() => import("@/core/globe/GlobeView"), {
ssr: false,
});
/**
* @component AppShell
* @description The primary application wrapper.
*
* Orchestrates the following:
* 1. Theme hydration from localStorage.
* 2. Injection of host globals for dynamic ES module plugins.
* 3. Loading of marketplace and built-in plugins.
* 4. Synchronization with the Cesium globe lifecycle.
* 5. Managing the "Boot" animation sequence and HUD entry.
*/
export function AppShell() {
const initLayer = useStore((s) => s.initLayer);
const boot = useBootSequence();
@@ -93,7 +113,12 @@ export function AppShell() {
for (const plugin of pluginRegistry.getAll()) {
await pluginManager.registerPlugin(plugin);
const shouldEnable = demoDefaultPlugins.has(plugin.id);
let shouldEnable = false;
if (isDemo) {
shouldEnable = demoDefaultPlugins.has(plugin.id);
} else {
shouldEnable = !disabledIds.has(plugin.id);
}
initLayer(plugin.id, shouldEnable);
if (shouldEnable) {
await pluginManager.enablePlugin(plugin.id);
@@ -131,6 +156,8 @@ export function AppShell() {
trackEvent("platform-boot", { duration });
}
}, [boot.phase]);
const timelineOpen = useStore((s) => s.timelineOpen);
const rootClasses = [
"app-shell",
isBooting && boot.headerReady ? "boot-header" : "",
@@ -138,6 +165,7 @@ export function AppShell() {
isBooting && boot.timelineReady ? "boot-timeline" : "",
isBooting && boot.controlsReady ? "boot-controls" : "",
!isBooting ? "boot-done" : "",
!timelineOpen ? "timeline-closed" : "",
].filter(Boolean).join(" ");
return (
@@ -150,6 +178,7 @@ export function AppShell() {
<TimelineSync />
<DataBusSubscriber />
<AgentBusSubscriber />
<Header />
{isMobile && <MobileHudBar />}
+10 -2
View File
@@ -1,3 +1,10 @@
/**
* @file DataBusSubscriber.tsx
* @description Headless component that bridges the DataBus event system with the Zustand store.
* Handles automatic WebSocket subscription/unsubscription when layers are toggled.
* @module src/components/layout
*/
"use client";
import { useEffect } from "react";
@@ -9,8 +16,9 @@ import { resolveEngineUrl } from "@/core/data/resolveEngineUrl";
import { fetchLocalEngineManifest } from "@/core/data/engineManifest";
/**
* Subscribes to DataBus events and syncs state.
* Renders nothing — purely a side-effect component.
* @component DataBusSubscriber
* @description Orchestrates side-effects between the event-driven DataBus and the React state store.
* This component renders no UI; it strictly manages the data pipeline lifecycle.
*/
export function DataBusSubscriber() {
const setPollingInterval = useStore((s) => s.setPollingInterval);
@@ -1,9 +1,22 @@
/**
* @file DevModeSubscriber.tsx
* @description Development-only component that connects to the `wwv-cli` dev server.
* Enables hot-reloading of local plugins during development.
*/
"use client";
import { useEffect, useState } from "react";
import { pluginManager } from "@/core/plugins/PluginManager";
import { useStore } from "@/core/state/store";
/**
* Headless component that listens for plugin updates over a local WebSocket.
* Only active in `development` environments. Allows for real-time plugin
* addition and reloading without full page refreshes.
*
* @returns null
*/
export function DevModeSubscriber() {
const [connected, setConnected] = useState(false);
const initLayer = useStore((s) => s.initLayer);
+19 -1
View File
@@ -1,5 +1,12 @@
"use client";
/**
* @file Header.tsx
* @description Primary application header providing branding, search, region presets,
* theme selection, and system-wide controls.
* @module src/components/layout
*/
import { useEffect, useRef, useState } from "react";
import { useStore } from "@/core/state/store";
import { dataBus } from "@/core/data/DataBus";
@@ -33,6 +40,17 @@ const THEMES = [
const TIME_WINDOWS = ["1h", "6h", "24h", "48h", "7d"] as const;
/**
* @component Header
* @description The main navigation and control bar of the application.
* Handles responsive layout between mobile and desktop, including time windows,
* theme selection, and region-based camera presets.
*
* @example
* ```tsx
* <Header />
* ```
*/
export function Header() {
const isMobile = useIsMobile();
const timeWindow = useStore((s) => s.timeWindow);
@@ -275,9 +293,9 @@ export function Header() {
<path d="M1 3 L5 7 L9 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</button>
</div>
</div>
<div style={{ width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0 }} />
</div>
<div className="header__actions">
<div className="status-badge">
<span className="status-badge__dot" />
+20
View File
@@ -1,11 +1,26 @@
"use client";
/**
* @file SearchBar.tsx
* @description Integrated search component providing geocoding, entity lookup,
* and history functionality with a high-performance dropdown interface.
* @module src/components/layout
*/
import { useState, useEffect, useRef } from "react";
import { Search, MapPin } from "lucide-react";
import { useSearch } from "./useSearch";
import type { SearchResult, SearchSection } from "./useSearch";
import { useIsMobile } from "@/core/hooks/useIsMobile";
/**
* @function HighlightMatch
* @description Helper component that highlights matching query text within a string.
* @param {Object} props - Component properties.
* @param {string} props.text - The full text to display.
* @param {string} props.query - The search string to highlight.
* @returns {JSX.Element} The text with highlighted spans.
*/
function HighlightMatch({ text, query }: { text: string; query: string }) {
if (!query) return <>{text}</>;
// Trim query to handle trailing spaces safely
@@ -22,6 +37,11 @@ function HighlightMatch({ text, query }: { text: string; query: string }) {
);
}
/**
* @component SearchBar
* @description Primary search input field that manages focus, keyboard navigation,
* and result dropdown visibility.
*/
export function SearchBar() {
const isMobile = useIsMobile();
const {
+50 -50
View File
@@ -1,50 +1,50 @@
.time-select {
display: inline-flex;
align-items: center;
}
.dropdown-menu {
position: fixed;
top: calc(100% + 8px);
right: 0;
min-width: 80px;
padding: 6px;
border-radius: 12px;
backdrop-filter: var(--glass-blur);
-webkit-backdrop-filter: var(--glass-blur);
background: var(--bg-glass);
border: 1px solid var(--glass-border);
box-shadow: var(--glass-shadow);
z-index: 9999;
display: flex;
flex-direction: column;
gap: 2px;
}
.dropdown-option {
padding: 8px 12px;
border-radius: 8px;
cursor: pointer;
font-size: 13px;
font-weight: 500;
color: var(--text-muted, #94a3b8);
background: transparent;
border: 1px solid transparent;
transition: all var(--duration-normal) var(--ease-spring);
text-align: center;
}
.dropdown-option:hover {
color: var(--text-primary);
background: var(--bg-glass-hover);
box-shadow: var(--glass-shadow-inner);
transform: scale(0.98);
}
.dropdown-option.active {
color: var(--accent-cyan, #63b3ed);
background: var(--bg-glass-active);
border: 1px solid rgba(var(--accent-rgb), 0.3);
box-shadow: inset 2px 0 0 0 var(--accent-cyan), var(--glass-shadow-inner);
}
␍
.time-select {
display: inline-flex;
align-items: center;
}
.dropdown-menu {
position: fixed;
top: calc(100% + 8px);
right: 0;
min-width: 80px;
padding: 6px;
border-radius: 12px;
backdrop-filter: blur(var(--glass-blur));
-webkit-backdrop-filter: blur(var(--glass-blur));
background: var(--bg-glass);
border: 1px solid var(--glass-border);
box-shadow: var(--glass-shadow);
z-index: 9999;
display: flex;
flex-direction: column;
gap: 2px;
}
.dropdown-option {
padding: 8px 12px;
border-radius: 8px;
cursor: pointer;
font-size: 13px;
font-weight: 500;
color: var(--text-muted, #94a3b8);
background: transparent;
border: 1px solid transparent;
transition: all var(--duration-normal) var(--ease-spring);
text-align: center;
}
.dropdown-option:hover {
color: var(--text-primary);
background: var(--bg-glass-hover);
box-shadow: var(--glass-shadow-inner);
transform: scale(0.98);
}
.dropdown-option.active {
color: var(--accent-cyan, #63b3ed);
background: var(--bg-glass-active);
border: 1px solid rgba(var(--accent-rgb), 0.3);
box-shadow: inset 2px 0 0 0 var(--accent-cyan), var(--glass-shadow-inner);
}
@@ -3,7 +3,7 @@
inset: 0;
z-index: 10000;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: var(--glass-blur);
backdrop-filter: blur(var(--glass-blur));
display: flex;
align-items: center;
justify-content: center;
@@ -11,7 +11,7 @@
.dialog {
background: var(--bg-glass);
backdrop-filter: var(--glass-blur);
backdrop-filter: blur(var(--glass-blur));
border: 1px solid rgba(245, 158, 11, 0.3);
border-radius: var(--radius-lg);
padding: 28px 32px;
+11 -1
View File
@@ -1,8 +1,18 @@
"use client";
/**
* @file CameraStatsPanel.tsx
* @description Head-up display (HUD) overlay providing real-time camera position,
* orientation, and performance metrics (FPS).
* @module src/components/panels
*/
import React, { useState } from "react";
import { useStore } from "@/core/state/store";
/**
* @component CameraStatsPanel
* @description A minimal HUD component that displays latitude, longitude,
* altitude, heading, pitch, roll, and FPS. Can be collapsed by the user.
*/
export default function CameraStatsPanel() {
const [collapsed, setCollapsed] = useState(false);
Loaded 100 of 203 files, more files were not shown because too many files have changed in this diff. Show more